From f5d449d041f2dd5f5fd22b3b2571fdeae73c5e8d Mon Sep 17 00:00:00 2001 From: Algent Date: Thu, 3 Sep 2026 20:55:54 +0200 Subject: [PATCH] refactor: filter Java mixins by side --- JAVA_MIGRATION.md | 39 +++++++------ JAVA_MIGRATION_CONSUMER_AUDIT.md | 4 +- JAVA_MIGRATION_DIVERGENCES.md | 1 + JAVA_MIGRATION_HANDOFF.md | 33 ++++++----- docs/migration/HISTORY.md | 23 ++++++++ .../JavaTraitRegistrationFunctionalTest.java | 57 ++++++++++++++++--- .../multipart/asm/JavaTraitRegistration.java | 51 ++++++++++++++--- 7 files changed, 160 insertions(+), 48 deletions(-) diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 86a30b6..f0a49f5 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -26,8 +26,9 @@ No trustworthy tool will produce a maintainable Java port automatically. A decom Work continues on `algent/java`. The low-coupling queue, core part/tile types, registries, handlers, factories, placement/render helpers, both generators and all built-in tile traits are Java. Six generated microblock trait files and the compiler/signature/analyser compatibility shells remain Scala. Composite generation, Java-trait -rewriting and compiler startup now delegate to Java helpers. The next bounded target is abstract-Java-mixin support, -separate from Java-path side-only filtering; retain the ScalaSignature path-dependent model bridges. +rewriting and compiler startup now delegate to Java helpers. Abstract Java mixins and Java-path side-only filtering +are complete; the next bounded target is `microblock/MicroblockTraits.scala`. Retain the ScalaSignature +path-dependent model bridges. Start with [JAVA_MIGRATION_HANDOFF.md](JAVA_MIGRATION_HANDOFF.md) for the exact source/test baseline, workflow and Java-source limitations. Read both the [ABI inventory](JAVA_MIGRATION_ABI_INVENTORY.md) and @@ -364,8 +365,8 @@ cache remain reference-identical; pass-through-interface coverage remains green. ### Phase 6 — Convert multipart core and microblocks Status: core code, factories and ordinary helpers are Java. The six remaining generated microblock trait files -still need the abstract-Java-mixin and side-only-member prerequisites from Phase 7. The following gates continue -to apply to those remaining units; completed per-type evidence is in the history. +can now move through the Java mixin path because both Phase 7 prerequisites are complete. The following gates +continue to apply to those remaining units; completed per-type evidence is in the history. - [ ] Add characterization coverage for each subsystem immediately before its conversion. - [ ] Convert the central tile, part, registry, placement, rendering, networking, scheduler, and microblock code in dependency order. @@ -383,9 +384,9 @@ Exit condition: normal runtime implementation is Java; any remaining Scala is is - [ ] Keep Scala-trait registration while deprecated bridges or supported external Scala traits require it. - [x] Allow abstract Java mixins whose base type is abstract, skipping their abstract members instead of rejecting the class. Required before any Java mixin over `Microblock` is possible. See Phase 10. -- [ ] Implement `@SideOnly` member stripping on the Java mixin path, matching what `listSideOnly` does for Scala +- [x] Implement `@SideOnly` member stripping on the Java mixin path, matching what `listSideOnly` does for Scala signatures. Required before a client-only Java mixin method is safe on a dedicated server. See Phase 10. -- [ ] Run ProjectRed's `LightMicroblock` external Scala-trait fixture and pass-through-interface fixtures against the +- [x] Run ProjectRed's `LightMicroblock` external Scala-trait fixture and pass-through-interface fixtures against the ported generator. - [ ] Decide separately whether a future generator design can avoid custom bytecode generation. Do not couple that experiment to the source-language port. @@ -518,7 +519,7 @@ The standard pattern is a three-step ratchet, and only the first step is on FMP' | Consumer | What FMP is currently forced to preserve | Upstream fix | Can start | | --- | --- | --- | --- | -| ProjectRed | Runtime Scala-signature decoding and external trait registration, reached through `MicroblockGenerator.registerTrait(classOf[LightMicroblock])` | Rewrite the ~60-line `LightMicroblock` trait as a Java mixin registered through the `registerJavaTrait` path | **Blocked on FMP**; see the prerequisites below | +| ProjectRed | Runtime Scala-signature decoding and external trait registration, reached through `MicroblockGenerator.registerTrait(classOf[LightMicroblock])` | Rewrite the ~60-line `LightMicroblock` trait as a Java mixin registered through the `registerJavaTrait` path | FMP compiler prerequisites complete; consumer rewrite and release remain | | Schematica | Private Scala-mangled field `codechicken$multipart$MultiPartRegistry$$typeMap`, cast to `scala.collection.mutable.Map` | FMP exposes a supported registry lookup; Schematica uses it instead of the field | After step 1 | | GuideNH | Companion-only `MultipartGenerator$.MODULE$.generateCompositeTile` and `MicroblockGenerator$.create`; `partList_$eq(scala.collection.Seq)`; mixin into private `BlockMicroMaterial.block` and `.meta` | FMP exposes supported static entry points and `setPartList(List)`; GuideNH targets those and public material accessors | After step 1 and Phase 9.1 | | Et Futurum Requiem | Mutable static `int[] ButtonPart.metaSideMap` and `sideMetaMap` must stay public and mutable | FMP exposes a supported orientation-override API; Et Futurum uses it | After step 1 | @@ -539,15 +540,16 @@ The rewrite has two Phase 7 prerequisites: method metadata until a later mixin supplies an implementation. A no-argument mixin constructor may call an argument-taking base constructor; that direct call is discarded because the generated composite invokes the real base constructor before trait initialization. -2. **`@SideOnly` stripping on the Java path — outstanding.** Side stripping is implemented only for Scala traits, - through - `listSideOnly(sig: ScalaSignature)` reading the Scala signature annotation table inside `registerScalaTrait`. - `LightMicroblock.renderDynamic` is `@SideOnly(Side.CLIENT)` and the trait is applied on both sides, because - ProjectRed's `addTraits` ignores its `client` argument. Without an equivalent annotation-driven strip in - `registerJavaTrait`, a Java rewrite would merge a client-only method into server-side generated microblocks. +2. **`@SideOnly` stripping on the Java path — complete.** `registerJavaTrait` checks both visible and invisible + annotations before collecting fields, signatures or methods. Opposite-side members are omitted; an excluded + no-argument constructor produces an empty `$init$` so generated composites remain valid without executing its + body, including when Forge stripped it before registration. Current-side members retain their generated behavior. + `LightMicroblock.renderDynamic` can therefore remain + `@SideOnly(Side.CLIENT)` when ProjectRed rewrites the trait to Java, even though its `addTraits` ignores the + `client` argument. -Both prerequisites are Phase 7 work and are worth doing regardless, since they are also what any future FMP-internal -Java microblock mixin would need. +Both compiler prerequisites are complete. The FMP microblock trait files can now move through the Java path; removing +external Scala-signature support still waits for a released ProjectRed Java rewrite. UtilitiesInExcess is the cheapest case in the table because it is not yet in the pack. Anything fixed before it ships never becomes a compatibility obligation at all. @@ -560,8 +562,9 @@ placeholder, rather than lost material data. Extra Utilities writes `mat` as wel `PartConnecting`, and `PartPipeJacket`, so correcting the key also matches the legacy tags reached through UtilitiesInExcess's `extrautils:*` aliases; there is no legacy-conversion risk in the fix. -- [ ] Land the two Phase 7 Java-mixin prerequisites, then the ProjectRed `LightMicroblock` Java rewrite, with a - fixture proving the Java-trait path produces equivalent generated microblocks on both sides. +- [x] Land the two Phase 7 Java-mixin prerequisites with generated Java-trait fixtures. +- [ ] Land the ProjectRed `LightMicroblock` Java rewrite with a fixture proving equivalent generated microblocks on + both sides. - [ ] Land the Galacticraft reflection signature check. - [ ] Fix the UtilitiesInExcess `mat`/`material` key mismatch and its `getIdMap()` use before it enters the pack. - [ ] Add the supported public equivalents needed by Schematica, GuideNH, Et Futurum, and Iguana as additive API. @@ -674,7 +677,7 @@ Still open, and only to be decided when they become necessary: Track remaining work by completed compatibility gates, not the retired pre-audit calendar estimates: 1. Extract the remaining compiler algorithms with unchanged characterization and generated output. -2. Characterize and add the Java-mixin prerequisites, then port the remaining generated microblock traits. +2. Characterize and port the remaining generated microblock traits through the completed Java-mixin path. 3. Resolve or explicitly retain the Scala model bridges; finish the applicable API and pre-merge cleanup gates. 4. Complete packaged-pack, client and performance validation with recorded results. diff --git a/JAVA_MIGRATION_CONSUMER_AUDIT.md b/JAVA_MIGRATION_CONSUMER_AUDIT.md index 9e2b5aa..5f3c0ec 100644 --- a/JAVA_MIGRATION_CONSUMER_AUDIT.md +++ b/JAVA_MIGRATION_CONSUMER_AUDIT.md @@ -507,7 +507,9 @@ name like ProjectRed's `LightMicroblock`, direct-Java-source `TPartialOcclusionT direct-Java-source `TRedstoneTile`'s exact eight-method interface and class caching, and server-only pass-through forwarding, overloading, single-implementor selection, copying/rebinding, and removal cleanup. `TRedstoneTileFunctionalTest` additionally pins the ProjectRed/Extra Utilities query surface, masks, conduction, and -world-side routing. Full downstream mixed tiles and client-side selection remain Phase 7 integration cases. +world-side routing. `JavaTraitRegistrationFunctionalTest` now pins current/opposite-side selection for visible and +invisible Java annotations, including method dispatch, field state and constructor initialization. Full downstream +mixed tiles and client-side selection remain Phase 7 integration cases. With these gates, the source audit is actionable: the port can simplify internals freely where no listed observation changes, while each externally observed behavior has a named consumer and a focused way to prove compatibility. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index e8320aa..4733360 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -20,6 +20,7 @@ and `JAVA_MIGRATION_CONSUMER_AUDIT.md` before extending this list. | `ControlKeyModifer.map()` | The exposed Java map has no Scala default-value wrapper: an absent key returns null from `get`, not false from Scala `apply`. Use `isControlDown` for the unchanged absent-means-false behavior. | | Public companion constructors, including `ASMImplicits.ExtBitSet$` / `ExtClass$` | Explicit construction creates an independent instance instead of replacing `MODULE$`. Java initializes the retained final module field in its static initializer; use `MODULE$` for singleton identity. | | `registerJavaTrait` abstract inputs | Abstract Java classes are accepted instead of throwing `IllegalArgumentException`. Declared abstract methods become generated-interface contracts without helper bodies; a later mixin must implement them before those members can be invoked. A no-argument abstract-mixin constructor may call an argument-taking superclass constructor; registration discards that direct call and its argument evaluation because the composite invokes the real base constructor first. This enables Java microblock mixins without changing existing concrete registrations. | +| `registerJavaTrait` members annotated `@SideOnly` | The old Java path ignored the annotation. It now omits opposite-side fields and methods from generated metadata and output, matching Forge and the Scala-trait path; visible and invisible annotation tables are both accepted. If the no-argument constructor is absent, including after Forge has already stripped it, an empty `$init$` preserves the generated initializer contract without running its body. Current-side members are unchanged. No audited Java registration relied on the old retention. | Concrete collection implementations also change without changing the declared `java.lang.Iterable`/`List` contracts: diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 486de8f..2e6696f 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -16,20 +16,23 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes ## Current state and next target -**333 plain-JVM tests and 210 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **214 Java +**333 plain-JVM tests and 211 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **214 Java files and 9 Scala files / 1,188 nonblank Scala lines**. The packaged inventory has 437 classes. -Latest bounded compiler change: abstract Java mixins can extend an abstract base and leave methods for a later mixin -to implement. Two Forge tests first characterized the prior rejection and the already-working concrete/base dispatch -(`3556725`). The generated interface retains abstract contracts, the helper omits their nonexistent bodies, and an -abstract input's no-argument constructor may call an argument-taking superclass constructor. Clean verification after -stopping Gradle matched 432 class APIs, all five compiler closures, 3,643 non-target method bodies and all 106 existing -generated dump names/hashes; six feature-fixture dumps are new. Local evidence is in -`run/migration-abstract-java-reference/`; `clean` preserves this ignored directory. +Latest bounded compiler change: Java mixins now filter opposite-side fields, methods and constructors before metadata +or bytecode rewriting. The Forge test first characterized the previous retention of visible/invisible annotations, +state and constructor initialization (`a481859`). Current-side members remain; when the no-argument constructor is absent, +an empty `$init$` satisfies the generated initializer contract without executing the opposite-side body. A regression +also passes input through Forge's real side transformer before registration. Clean verification after stopping Gradle +matched 432 class APIs, all five compiler closures and 3,643 non-target method bodies. All 112 reference dump names +remain; 109 hashes are exact and only the trait, helper and composite from the SideOnly fixture differ. Four outputs +are new for the already-stripped-constructor fixture. Local evidence is in +`run/migration-java-side-only-reference/`; `clean` preserves this ignored directory. -**Next: add Java-path `@SideOnly` member filtering as a separate compiler behavior target.** This is the remaining -compiler prerequisite for porting the microblock traits. Characterize visible/invisible annotations, side selection, -fields, methods and constructors first. The ScalaSignature path-dependent model bridges remain. +**Next: port `microblock/MicroblockTraits.scala` as the first generated microblock trait group.** Both Java-mixin +prerequisites are complete. Characterize its interface/helper ABI, initialization, generated common/client dispatch, +render/effect routing, slots, partial-occlusion boxes and item class ID before conversion. Keep the external ProjectRed +Scala-trait fixture green and retain the ScalaSignature path-dependent model bridges. Remaining Scala units: @@ -38,7 +41,7 @@ Remaining Scala units: | `multipart/asm/ASMMixinCompiler.scala` | Retained nested models, construction callbacks and Scala entry-point shell | | `multipart/asm/ScalaSignature.scala` | Named models, primitive/erased bridges and five generic inner-construction branches | | `multipart/asm/StackAnalyser.scala` | Class/companion/model shell over Java `StackAnalyserLogic` | -| `microblock/MicroblockTraits.scala`, `FaceMicroblockTraits.scala`, `CornerMicroblockTraits.scala`, `EdgeMicroblockTraits.scala`, `HollowMicroblockTraits.scala`, `TMicroOcclusion.scala` | Generated traits; need Java-path side-only member handling first | +| `microblock/MicroblockTraits.scala`, `FaceMicroblockTraits.scala`, `CornerMicroblockTraits.scala`, `EdgeMicroblockTraits.scala`, `HollowMicroblockTraits.scala`, `TMicroOcclusion.scala` | Generated traits; port in dependency order now that both Java-mixin prerequisites are complete | Both generators, both registries, core tile/part classes, ordinary microblock helpers/factories, handlers, networking, placement/render helpers and built-in tile traits are Java. The low-risk queue and immediate consumer gate are @@ -79,7 +82,7 @@ job must stay required. The ignored local server EULA is already accepted. Generated dumps: `run/server/asm/multipart/**/*.txt`; enumerate recursively and assert a nonzero expected count. Compare names and hashes first. Investigate differences before normalizing only proven debug/private-name changes. -The current reference includes the deterministic class-definition fixture, bringing the count to 42. +The current baseline emits 116 dumps, including the deterministic definition, compiler and feature fixtures. ### Binary and fixture checks @@ -101,8 +104,8 @@ Compilation against the migrated artifact would defeat the binary-compatibility - **External Scala traits remain supported.** ProjectRed registers `LightMicroblock` through `MicroblockGenerator.registerTrait`; keep its ScalaSignature ingestion, `$class` helper and generated dispatch. - A Java rewrite still needs Java-path `@SideOnly` member handling, then a released - consumer update. Do not flatten generated microblock inheritance to bypass those prerequisites. + The Java path now supports its `@SideOnly` requirement, but retiring this external Scala path still needs a released + ProjectRed Java rewrite. Do not flatten generated microblock inheritance to bypass that consumer transition. - **ScalaSignature models cannot be mechanically replaced.** Primitive literal `value()` methods coexist with erased `Object value()` bridges; Java source cannot declare both. Five generic inner constructors also need their retained Scala construction branches and exact outer-instance bindings. diff --git a/docs/migration/HISTORY.md b/docs/migration/HISTORY.md index 099e948..d009fb0 100644 --- a/docs/migration/HISTORY.md +++ b/docs/migration/HISTORY.md @@ -1012,3 +1012,26 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m zero failures/errors/skips. All five packaged `@Mod` versions, the forced Scala-compilation guard and dev config remain correct. Sources stay at 214 Java files and 9 Scala files / 1,188 nonblank Scala lines. Next: Java-path `@SideOnly` member filtering, characterized first as its own compiler behavior target. + +### 2026-09-03 — Java mixin side filtering + +- Expanded the Forge Java-trait fixture against the untouched implementation and committed it first as `a481859`. + It proves that the old Java path retained runtime-visible and runtime-invisible client annotations on a dedicated + server: both methods execute, both fields keep initialized state, and a client-marked constructor runs its body. +- `registerJavaTrait` now filters opposite-side fields and methods before building field metadata, method signatures + or helper bodies. It reads both annotation tables and retains current-side members. When the no-argument constructor + is absent, the helper receives an empty `$init$`; generated composites construct normally without executing + side-specific initialization. The regressions cover a method body that would otherwise fail primitive-array + analysis and input already processed by Forge's real side transformer. External Scala traits still use the + unchanged ScalaSignature path. +- This deliberately changes the previously ignored Java annotation, so the divergence ledger records it. No audited + Java trait depends on retaining an opposite-side member; the change supplies the remaining compiler prerequisite + for a Java ProjectRed `LightMicroblock`, whose `renderDynamic` is client-only while the trait is selected both ways. +- Saved the pre-change jar/source, Forge report and 112 generated outputs under ignored + `run/migration-java-side-only-reference/`. Clean verification after stopping Gradle keeps all 437 packaged classes, + matches 432 class APIs, 3,643 non-target method bodies and all five compiler closures. All 112 reference dump names + remain: 109 hashes are exact and only the SideOnly fixture's trait, helper and composite change; four outputs are + new for the already-stripped-constructor fixture. Formatting, checkstyle, build and Forge pass: 333 JVM / 211 Forge, + zero failures/errors/skips. All five packaged `@Mod` versions, the forced + Scala-compilation guard and dev config remain correct. Sources stay at 214 Java files and 9 Scala files / 1,188 + nonblank Scala lines. Next: `microblock/MicroblockTraits.scala`, characterized before conversion. diff --git a/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java index d8761e9..136bcf4 100644 --- a/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java @@ -19,6 +19,7 @@ import org.objectweb.asm.tree.TypeInsnNode; import codechicken.lib.asm.ASMHelper; import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo; +import cpw.mods.fml.common.asm.transformers.SideTransformer; import scala.MatchError; import scala.collection.JavaConversions; @@ -162,7 +163,7 @@ class JavaTraitRegistrationFunctionalTest { } @Test - void sideOnlyAnnotationsDoNotStripJavaMembersOrInitializationOnTheServer() throws Exception { + void sideOnlyAnnotationsStripOppositeJavaMembersAndInitializationOnTheServer() throws Exception { try (Scope scope = new Scope()) { ClassNode parent = base("SideJavaBase"); scope.define(parent); @@ -191,21 +192,63 @@ class JavaTraitRegistrationFunctionalTest { constant(input, "clientInvisible", "()I", 41, ACC_PUBLIC); method(input, "clientInvisible").visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", false) .visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT"); + MethodVisitor clientInvalid = input.visitMethod(ACC_PUBLIC, "clientInvalid", "()[I", null, null); + clientInvalid.visitInsn(ICONST_1); + clientInvalid.visitIntInsn(NEWARRAY, T_INT); + clientInvalid.visitInsn(ARETURN); + clientInvalid.visitMaxs(1, 1); + clientInvalid.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true) + .visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT"); constant(input, "serverVisible", "()I", 43, ACC_PUBLIC); method(input, "serverVisible").visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true) .visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "SERVER"); COMPILER.registerJavaTrait(input); MixinInfo info = COMPILER.getMixinInfo(input.name).get(); - assertEquals(Arrays.asList("clientVisible()I", "clientInvisible()I", "serverVisible()I"), signatures(info)); + assertEquals(Arrays.asList("serverVisible()I"), signatures(info)); + assertEquals(1, info.fields().size()); + assertEquals("serverField", info.fields().apply(0).name()); Object value = COMPILER.mixinClasses(ROOT + "SideComposite", parent.name, seq(input.name)) .getConstructor(int.class).newInstance(0); - assertEquals(37, value.getClass().getMethod("clientVisible").invoke(value)); - assertEquals(41, value.getClass().getMethod("clientInvisible").invoke(value)); + assertThrows(NoSuchMethodException.class, () -> value.getClass().getMethod("clientVisible")); + assertThrows(NoSuchMethodException.class, () -> value.getClass().getMethod("clientInvisible")); + assertThrows(NoSuchMethodException.class, () -> value.getClass().getMethod("clientInvalid")); assertEquals(43, value.getClass().getMethod("serverVisible").invoke(value)); String fieldPrefix = input.name.replace('/', '$') + "$$"; - assertEquals(11, value.getClass().getMethod(fieldPrefix + "clientVisibleField").invoke(value)); - assertEquals(13, value.getClass().getMethod(fieldPrefix + "clientInvisibleField").invoke(value)); - assertEquals(17, value.getClass().getMethod(fieldPrefix + "serverField").invoke(value)); + assertThrows( + NoSuchMethodException.class, + () -> value.getClass().getMethod(fieldPrefix + "clientVisibleField")); + assertThrows( + NoSuchMethodException.class, + () -> value.getClass().getMethod(fieldPrefix + "clientInvisibleField")); + assertEquals(0, value.getClass().getMethod(fieldPrefix + "serverField").invoke(value)); + } + } + + @Test + void alreadyStrippedForgeConstructorStillSuppliesAnEmptyMixinInitializer() throws Exception { + try (Scope scope = new Scope()) { + ClassNode parent = base("PrestrippedSideJavaBase"); + scope.define(parent); + ClassNode input = input("PrestrippedSide", parent.name); + input.visitField(ACC_PRIVATE, "state", "I", null, null); + MethodNode constructor = method(input, ""); + constructor.visitAnnotation("Lcpw/mods/fml/relauncher/SideOnly;", true) + .visitEnum("value", "Lcpw/mods/fml/relauncher/Side;", "CLIENT"); + constructor.instructions.remove(constructor.instructions.getLast()); + initialize(constructor, input.name, "state", 29); + constructor.visitInsn(RETURN); + constructor.visitMaxs(2, 1); + constant(input, "available", "()I", 47, ACC_PUBLIC); + ClassNode stripped = ASMHelper.createClassNode( + new SideTransformer().transform(input.name, input.name, ASMHelper.createBytes(input, 0)), + 0); + assertTrue(stripped.methods.stream().noneMatch(m -> ((MethodNode) m).name.equals(""))); + COMPILER.registerJavaTrait(stripped); + Object value = COMPILER.mixinClasses(ROOT + "PrestrippedSideComposite", parent.name, seq(input.name)) + .getConstructor(int.class).newInstance(7); + assertEquals(7, value.getClass().getMethod("score").invoke(value)); + assertEquals(47, value.getClass().getMethod("available").invoke(value)); + assertEquals(0, value.getClass().getMethod(input.name.replace('/', '$') + "$$state").invoke(value)); } } diff --git a/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java b/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java index 5d2ddc7..a9d05e8 100644 --- a/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java +++ b/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java @@ -10,6 +10,7 @@ import java.util.function.Function; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FieldNode; @@ -24,6 +25,8 @@ import codechicken.lib.asm.InsnComparator; import codechicken.lib.asm.InsnListSection; import codechicken.multipart.asm.ASMMixinCompiler.FieldMixin; import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo; +import cpw.mods.fml.relauncher.FMLLaunchHandler; +import cpw.mods.fml.relauncher.SideOnly; import scala.Function1; import scala.Option; import scala.Tuple2; @@ -48,14 +51,21 @@ final class JavaTraitRegistration { "Inner classes are not permitted for " + input.name + " as a java mixin trait. Use scala"); ASMMixinCompiler$ compiler = ASMMixinCompiler$.MODULE$; Option parentTrait = compiler.getMixinInfo(input.superName); - Buffer sourceFields = JavaConversions.asScalaBuffer(input.fields); Map fields = scala.collection.immutable.Map$.MODULE$.empty(); - for (FieldNode field : iterable(sourceFields)) - fields = fields.$plus(new Tuple2<>(field.name, new FieldMixin(field.name, field.desc, field.access))); + for (FieldNode field : input.fields) { + if (!excludedOnCurrentSide(field.visibleAnnotations, field.invisibleAnnotations)) + fields = fields.$plus(new Tuple2<>(field.name, new FieldMixin(field.name, field.desc, field.access))); + } ListBuffer supers = new ListBuffer<>(); ListBuffer methods = new ListBuffer<>(); java.util.Set methodSignatures = new LinkedHashSet<>(); - for (MethodNode method : input.methods) methodSignatures.add(method.name + method.desc); + List sourceMethods = new ArrayList<>(); + for (MethodNode method : input.methods) { + if (!excludedOnCurrentSide(method.visibleAnnotations, method.invisibleAnnotations)) { + sourceMethods.add(method); + methodSignatures.add(method.name + method.desc); + } + } ClassNode implementation = new ClassNode(); implementation.visit(V1_6, ACC_ABSTRACT | ACC_PUBLIC, input.name + "$class", null, "java/lang/Object", null); @@ -78,13 +88,19 @@ final class JavaTraitRegistration { } Context context = new Context(input, implementation, contract, fields, methodSignatures, supers, methods); - Buffer sourceMethods = JavaConversions.asScalaBuffer(input.methods); - Buffer selected = (Buffer) ((TraversableLike) sourceMethods) - .filterNot(fn(context::isGeneratedFieldAccessor)); + Buffer selected = (Buffer) ((TraversableLike) JavaConversions + .asScalaBuffer(sourceMethods)).filterNot(fn(context::isGeneratedFieldAccessor)); selected.foreach(fn(method -> { context.convertMethod(method); return scala.runtime.BoxedUnit.UNIT; })); + // Forge may have stripped the constructor before this ClassNode reaches the compiler. + if (!methodSignatures.contains("()V")) { + MethodNode initializer = (MethodNode) implementation + .visitMethod(ACC_PUBLIC | ACC_STATIC, "$init$", "(L" + input.name + ";)V", null, null); + initializer.visitInsn(RETURN); + initializer.visitMaxs(0, 1); + } compiler.define(implementation.name, ASMHelper.createBytes(implementation, 0)); compiler.define(contract.name, ASMHelper.createBytes(contract, 0)); @@ -102,6 +118,27 @@ final class JavaTraitRegistration { supers)); } + private static boolean excludedOnCurrentSide(List visible, List invisible) { + return excludedOnCurrentSide(visible) || excludedOnCurrentSide(invisible); + } + + private static boolean excludedOnCurrentSide(List annotations) { + if (annotations == null) return false; + String side = FMLLaunchHandler.side().name(); + String descriptor = Type.getDescriptor(SideOnly.class); + for (AnnotationNode annotation : annotations) { + if (!Objects.equals(annotation.desc, descriptor) || annotation.values == null) continue; + for (int i = 0; i < annotation.values.size() - 1; i += 2) { + if (!Objects.equals(annotation.values.get(i), "value")) continue; + Object value = annotation.values.get(i + 1); + if (value instanceof String[] && ((String[]) value).length > 1 + && !Objects.equals(((String[]) value)[1], side)) + return true; + } + } + return false; + } + private static final class Context { final ClassNode input;