From e07fa532285912c9beb91cb23072a7f38c32dd36 Mon Sep 17 00:00:00 2001 From: Algent Date: Thu, 3 Sep 2026 20:18:54 +0200 Subject: [PATCH] refactor: support abstract Java mixins --- JAVA_MIGRATION.md | 24 ++-- JAVA_MIGRATION_DIVERGENCES.md | 1 + JAVA_MIGRATION_HANDOFF.md | 30 +++-- docs/migration/HISTORY.md | 22 ++++ .../test/AbstractJavaMixinFunctionalTest.java | 124 ++++++++++++++++-- .../JavaTraitRegistrationFunctionalTest.java | 4 +- .../multipart/asm/JavaTraitRegistration.java | 51 ++++++- 7 files changed, 214 insertions(+), 42 deletions(-) diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 3f3f338..86a30b6 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -136,9 +136,12 @@ paths to effectively zero measured allocation; these remain focused measurements `ASMMixinCompiler` already supports two inputs: - `registerScalaTrait`, which reads Scala signature data and understands Scala trait output. -- `registerJavaTrait`, which transforms a concrete Java mixin class into the interface/static-helper form used by the generator. +- `registerJavaTrait`, which transforms a concrete or abstract Java mixin class into the interface/static-helper form used by the generator. -The Java path rejects Java interfaces, inner classes, abstract classes, static initializers, and constructors with arguments. Those restrictions must be accounted for when converting built-in tile traits, but the path proves that Java implementations can participate in the current composition system. +The Java path rejects Java interfaces, inner classes, static initializers, and constructors with arguments. Abstract +inputs retain their abstract methods as interface contracts while later mixins provide the implementation. Those +restrictions must be accounted for when converting built-in tile traits, but the path proves that Java implementations +can participate in the current composition system. `MultipartGenerator.registerPassThroughInterface` also explicitly supports interfaces that generated tiles must expose. This is part of the compatibility surface and must not be lost in a static subclass rewrite. @@ -378,7 +381,7 @@ Exit condition: normal runtime implementation is Java; any remaining Scala is is - [ ] Translate the existing compiler/generator into readable Java while preserving emitted class shapes and cache keys. - [ ] Evaluate GTNHLib ASM helpers where they reduce boilerplate without altering semantics. - [ ] Keep Scala-trait registration while deprecated bridges or supported external Scala traits require it. -- [ ] Allow abstract Java mixins whose base type is abstract, skipping their abstract members instead of rejecting the +- [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 signatures. Required before a client-only Java mixin method is safe on a dedicated server. See Phase 10. @@ -530,13 +533,14 @@ reflection sits inside an empty `catch (Exception)`. ProjectRed's `LightMicroblock` is the audited external constraint on retiring runtime Scala-signature decoding. Its Java rewrite removes that external dependency only after the updated consumer is released into the pack; decoder removal also requires retiring internal Scala trait inputs and resolving retained model bridges. -The rewrite still needs two Phase 7 prerequisites: -1. **Abstract Java mixins over an abstract base.** `registerJavaTrait` rejects `ACC_ABSTRACT` classes - (`ASMMixinCompiler.scala`), but `Microblock` is abstract (`Microblock.java`) with abstract `microClass`, - `itemClassID`, and `render`. A Java mixin over it must therefore be abstract as well, so the check has to admit - abstract mixins and skip their abstract members rather than reject the class. The existing Java-mixin example, - `TPartialOcclusionTile`, avoids this only because its base `TileMultipart` is concrete. -2. **`@SideOnly` stripping on the Java path.** Side stripping is implemented only for Scala traits, through +The rewrite has two Phase 7 prerequisites: +1. **Abstract Java mixins over an abstract base — complete.** `registerJavaTrait` now admits `ACC_ABSTRACT` classes, + retains declared abstract members on the generated interface, and omits them from the static helper and concrete + 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 diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index 60dc329..e8320aa 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -19,6 +19,7 @@ and `JAVA_MIGRATION_CONSUMER_AUDIT.md` before extending this list. | `MultipartRenderer` dynamic-part guard | Uses short-circuit `\|\|` instead of `\|`; the second getter is no longer evaluated when the first operand succeeds. Ordinary getters give the same render decision. | | `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. | 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 4afffe3..486de8f 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -16,18 +16,20 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes ## Current state and next target -**333 plain-JVM tests and 207 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **214 Java +**333 plain-JVM tests and 210 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 port: `ASMMixinCompiler` startup reflection, map construction and sanity warmup delegate to Java -`CompilerBootstrap`, after seven characterization tests passed against untouched Scala (`e9d81d6`). Clean verification -after stopping Gradle matched 431 non-target class APIs, all five compiler closures, 3,653 non-target method bodies and -all 102 generated dump names/hashes. The five `@Mod` annotations match both packaged versions. Local reference jars, -reports and scripts are in `run/migration-compiler-startup-reference/`; `clean` preserves this ignored directory. +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. -**Next: allow abstract Java mixins as a separate compiler behavior target.** This is the first prerequisite for -porting the remaining microblock traits. Characterize rejection, base selection and abstract-method handling first; -keep Java-path side-only filtering as its own following target. The ScalaSignature path-dependent model bridges remain. +**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. Remaining Scala units: @@ -36,7 +38,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 abstract Java mixins and Java-path side-only member handling first | +| `microblock/MicroblockTraits.scala`, `FaceMicroblockTraits.scala`, `CornerMicroblockTraits.scala`, `EdgeMicroblockTraits.scala`, `HollowMicroblockTraits.scala`, `TMicroOcclusion.scala` | Generated traits; need Java-path side-only member handling first | 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 @@ -99,7 +101,7 @@ 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 needs both abstract-base mixin support and Java-path `@SideOnly` member handling, then a released + 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. - **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 @@ -241,6 +243,12 @@ because `IRedstoneTile` is unrelated to `TileMultipart`, forcing a real `checkca attribute. An anonymous `AbstractFunction1` for an `operate` callback, a lambda, or a string switch all trip it. Put the callback in the access shim as a named class, as `TTileChangeTileAccess.NeighborTileChanged` does. +**Abstract Java mixins declare contracts without helper bodies.** Their abstract methods stay on the generated +interface so concrete mixin methods can dispatch through them, but do not enter `MixinInfo.methods` until a later +mixin implements them. Their source constructor must still be no-argument; it may directly call a superclass +constructor with arguments. Registration removes that call and its argument evaluation because the generated +composite has already invoked the real base constructor, then preserves the remaining field initialization. + ## Release gaps and cleanup - The full [manual checklist](JAVA_MIGRATION_MANUAL_CHECKS.md) is still open. The user confirmed the ProjectRed diff --git a/docs/migration/HISTORY.md b/docs/migration/HISTORY.md index 684b846..099e948 100644 --- a/docs/migration/HISTORY.md +++ b/docs/migration/HISTORY.md @@ -990,3 +990,25 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m wide state fields and the Forge registration suite remains green. Wide getter maxima, primitive-array analysis and malformed inherited-call casts are real but dormant for current consumers. Abstract Java mixins and Java-path side filtering remain required before the microblock traits can move, and will be separate behavior targets. + +### 2026-09-03 — abstract Java mixins + +- Added two Forge characterizations before changing behavior and committed them as `3556725`. They freeze the old + abstract-input rejection before parent or method inspection and prove that concrete Java mixins already preserve + virtual dispatch when their base class is abstract. +- `registerJavaTrait` now accepts abstract inputs. Declared abstract methods remain on the generated interface so + concrete methods can call them, but no static helper or `MixinInfo.methods` entry is emitted until a child mixin + supplies the implementation. The no-argument mixin constructor may directly call a superclass constructor with + arguments; registration removes that receiver/argument/call sequence while retaining subsequent state + initialization. Constructor parameters and missing direct superclass calls still fail before publication. +- The feature fixture executes a two-layer generated composite over an abstract base with an `int` constructor. It + verifies base-argument forwarding, post-super field initialization, parent metadata, abstract-contract exceptions, + interface dispatch from the base and parent mixin, and final concrete instantiation. Existing Scala-trait + registration and all current Java mixin outputs are unchanged. +- Saved the pre-change jar/source, reports, 106 generated outputs and checks in ignored + `run/migration-abstract-java-reference/`. Clean verification after stopping Gradle matches all 432 class APIs, + 3,643 non-target method bodies and all five compiler closures. The 106 existing dump names/hashes match exactly; + the abstract-layer fixture adds six outputs. Formatting, checkstyle, build and Forge pass: 333 JVM / 210 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: Java-path + `@SideOnly` member filtering, characterized first as its own compiler behavior target. diff --git a/src/functionalTest/java/codechicken/multipart/test/AbstractJavaMixinFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/AbstractJavaMixinFunctionalTest.java index ba005e9..820fe77 100644 --- a/src/functionalTest/java/codechicken/multipart/test/AbstractJavaMixinFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/AbstractJavaMixinFunctionalTest.java @@ -5,11 +5,14 @@ import static org.junit.jupiter.api.Assertions.*; import static org.objectweb.asm.Opcodes.*; import java.lang.reflect.Modifier; +import java.util.Arrays; import org.junit.jupiter.api.Test; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; +import codechicken.lib.asm.ASMHelper; import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo; class AbstractJavaMixinFunctionalTest { @@ -17,23 +20,71 @@ class AbstractJavaMixinFunctionalTest { private static final String ROOT = "codechicken/multipart/test/abstractmixin/"; @Test - void abstractInputIsRejectedBeforeItsMissingParentOrMethodsAreInspected() throws Exception { + void abstractLayerKeepsItsContractAndConcreteChildCompletesTheComposite() throws Exception { try (Scope scope = new Scope()) { - ClassNode input = node(ROOT + "Rejected", ROOT + "MissingParent", ACC_PUBLIC | ACC_ABSTRACT); - input.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "required", "()I", null, null); - MethodVisitor malformed = input.visitMethod(ACC_PUBLIC, "malformed", "()[I", null, null); - malformed.visitInsn(ICONST_1); - malformed.visitIntInsn(NEWARRAY, T_INT); - malformed.visitInsn(ARETURN); - malformed.visitMaxs(1, 1); + ClassNode base = abstractIntBase("LayerBase"); + Class baseClass = scope.define(base); + ClassNode layer = abstractInput("Layer", base.name); + byte[] before = ASMHelper.createBytes(layer, 0); + COMPILER.registerJavaTrait(layer); + assertArrayEquals(before, ASMHelper.createBytes(layer, 0)); + ClassNode contract = COMPILER.classNode(layer.name); + MethodNode required = method(contract, "required"); + assertEquals(ACC_PUBLIC | ACC_ABSTRACT, required.access); + assertEquals(Arrays.asList("java/io/IOException"), required.exceptions); + ClassNode helper = COMPILER.classNode(layer.name + "$class"); + assertFalse(helper.methods.stream().anyMatch(m -> ((MethodNode) m).name.equals("required"))); + MixinInfo layerInfo = COMPILER.getMixinInfo(layer.name).get(); + assertEquals(base.name, layerInfo.parent()); + assertEquals(1, layerInfo.methods().size()); + assertEquals("fromMixin", layerInfo.methods().apply(0).name); + + ClassNode child = concreteInput("Child", layer.name); + COMPILER.registerJavaTrait(child); + MixinInfo childInfo = COMPILER.getMixinInfo(child.name).get(); + assertEquals(base.name, childInfo.parent()); + assertEquals(1, childInfo.parentTraits().size()); + assertSame(layerInfo, childInfo.parentTraits().apply(0)); + + Class composite = COMPILER.mixinClasses(ROOT + "LayerComposite", base.name, seq(child.name)); + assertFalse(Modifier.isAbstract(composite.getModifiers())); + Object value = composite.getConstructor(int.class).newInstance(41); + assertEquals(41, composite.getField("seed").get(value)); + assertEquals(23, composite.getMethod("required").invoke(value)); + assertEquals(23, composite.getMethod("fromMixin").invoke(value)); + assertEquals(23, baseClass.getMethod("fromBase").invoke(value)); + String fieldName = layerInfo.fields().apply(0).accessName(layer.name); + assertEquals(11, composite.getMethod(fieldName).invoke(value)); + } + } + + @Test + void abstractConstructorsStillRejectParametersAndMissingDirectSuperCalls() throws Exception { + try (Scope scope = new Scope()) { + ClassNode arguments = node(ROOT + "Arguments", "java/lang/Object", ACC_PUBLIC | ACC_ABSTRACT); + arguments.visitMethod(ACC_PUBLIC, "", "(I)V", null, null); assertEquals( - "Cannot register abstract class " + input.name + " as a java mixin trait. Use scala", - assertThrows(IllegalArgumentException.class, () -> COMPILER.registerJavaTrait(input)).getMessage()); - assertFalse(scope.info.contains(input.superName)); - assertFalse(scope.bytes.contains(input.name)); - assertFalse(scope.bytes.contains(input.name + "$class")); - assertFalse(scope.mixins.contains(input.name)); + "Constructor arguments are not permitted " + arguments.name + " as a mixin trait", + assertThrows(IllegalArgumentException.class, () -> COMPILER.registerJavaTrait(arguments)) + .getMessage()); + + ClassNode invalid = node(ROOT + "Invalid", ROOT + "ExpectedBase", ACC_PUBLIC | ACC_ABSTRACT); + MethodVisitor constructor = invalid.visitMethod(ACC_PUBLIC, "", "()V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + constructor.visitInsn(RETURN); + constructor.visitMaxs(1, 1); + IllegalArgumentException failure = assertThrows( + IllegalArgumentException.class, + () -> COMPILER.registerJavaTrait(invalid)); + assertTrue(failure.getMessage().startsWith("Invalid constructor insn sequence " + invalid.name + "\n")); + + for (ClassNode input : Arrays.asList(arguments, invalid)) { + assertFalse(scope.bytes.contains(input.name)); + assertFalse(scope.bytes.contains(input.name + "$class")); + assertFalse(scope.mixins.contains(input.name)); + } } } @@ -73,6 +124,47 @@ class AbstractJavaMixinFunctionalTest { return base; } + private static ClassNode abstractIntBase(String suffix) { + ClassNode base = node(ROOT + suffix, "java/lang/Object", ACC_PUBLIC | ACC_ABSTRACT); + base.visitField(ACC_PUBLIC, "seed", "I", null, null); + MethodVisitor constructor = base.visitMethod(ACC_PUBLIC, "", "(I)V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitVarInsn(ILOAD, 1); + constructor.visitFieldInsn(PUTFIELD, base.name, "seed", "I"); + constructor.visitInsn(RETURN); + constructor.visitMaxs(2, 2); + base.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "required", "()I", null, null); + MethodVisitor fromBase = base.visitMethod(ACC_PUBLIC, "fromBase", "()I", null, null); + fromBase.visitVarInsn(ALOAD, 0); + fromBase.visitMethodInsn(INVOKEVIRTUAL, base.name, "required", "()I", false); + fromBase.visitInsn(IRETURN); + fromBase.visitMaxs(1, 1); + return base; + } + + private static ClassNode abstractInput(String suffix, String parent) { + ClassNode input = node(ROOT + suffix, parent, ACC_PUBLIC | ACC_ABSTRACT); + input.visitField(ACC_PRIVATE, "initialized", "I", null, null); + MethodVisitor constructor = input.visitMethod(ACC_PROTECTED, "", "()V", null, null); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitInsn(ICONST_0); + constructor.visitMethodInsn(INVOKESPECIAL, parent, "", "(I)V", false); + constructor.visitVarInsn(ALOAD, 0); + constructor.visitIntInsn(BIPUSH, 11); + constructor.visitFieldInsn(PUTFIELD, input.name, "initialized", "I"); + constructor.visitInsn(RETURN); + constructor.visitMaxs(2, 1); + input.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, "required", "()I", null, new String[] { "java/io/IOException" }); + MethodVisitor fromMixin = input.visitMethod(ACC_PUBLIC, "fromMixin", "()I", null, null); + fromMixin.visitVarInsn(ALOAD, 0); + fromMixin.visitMethodInsn(INVOKEVIRTUAL, input.name, "required", "()I", false); + fromMixin.visitInsn(IRETURN); + fromMixin.visitMaxs(1, 1); + return input; + } + private static ClassNode concreteInput(String suffix, String parent) { ClassNode input = node(ROOT + suffix, parent, ACC_PUBLIC); MethodVisitor constructor = input.visitMethod(ACC_PUBLIC, "", "()V", null, null); @@ -91,4 +183,8 @@ class AbstractJavaMixinFunctionalTest { fromMixin.visitMaxs(1, 1); return input; } + + private static MethodNode method(ClassNode owner, String name) { + return (MethodNode) owner.methods.stream().filter(m -> ((MethodNode) m).name.equals(name)).findFirst().get(); + } } diff --git a/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java index 4edcfd3..efada32 100644 --- a/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/JavaTraitRegistrationFunctionalTest.java @@ -27,7 +27,7 @@ class JavaTraitRegistrationFunctionalTest { private static final String ROOT = "codechicken/multipart/test/javatrait/"; @Test - void rejectsInterfacesThenInnerClassesThenAbstractClassesWithoutPublishing() throws Exception { + void rejectsInterfacesThenInnerClassesWithoutPublishing() throws Exception { try (Scope scope = new Scope()) { ClassNode input = input("Rejected", "java/lang/Object"); input.access |= ACC_INTERFACE | ACC_ABSTRACT; @@ -40,8 +40,6 @@ class JavaTraitRegistrationFunctionalTest { assertFailure( input, "Inner classes are not permitted for " + input.name + " as a java mixin trait. Use scala"); - input.innerClasses.clear(); - assertFailure(input, "Cannot register abstract class " + input.name + " as a java mixin trait. Use scala"); assertFalse(scope.bytes.contains(input.name)); assertFalse(scope.bytes.contains(input.name + "$class")); assertFalse(scope.mixins.contains(input.name)); diff --git a/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java b/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java index add684b..5d2ddc7 100644 --- a/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java +++ b/src/main/scala/codechicken/multipart/asm/JavaTraitRegistration.java @@ -46,9 +46,6 @@ final class JavaTraitRegistration { + " as a mixin trait. Try register passThroughInterface"); if (!input.innerClasses.isEmpty()) throw new IllegalArgumentException( "Inner classes are not permitted for " + input.name + " as a java mixin trait. Use scala"); - if ((input.access & ACC_ABSTRACT) != 0) throw new IllegalArgumentException( - "Cannot register abstract class " + 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); @@ -210,10 +207,20 @@ final class JavaTraitRegistration { if (!Objects.equals(source.desc, "()V")) throw new IllegalArgumentException( "Constructor arguments are not permitted " + input.name + " as a mixin trait"); MethodNode result = staticClone(source, "$init$", ACC_PUBLIC); - removeSuperConstructor(result); + if ((input.access & ACC_ABSTRACT) != 0) removeAbstractSuperConstructor(result, source); + else removeSuperConstructor(result); staticTransform(result, source); return; } + if ((source.access & ACC_ABSTRACT) != 0) { + contract.visitMethod( + ACC_PUBLIC | ACC_ABSTRACT, + source.name, + source.desc, + null, + (String[]) source.exceptions.toArray(new String[0])); + return; + } if ((source.access & ACC_PRIVATE) == 0) { MethodNode exposed = (MethodNode) contract.visitMethod( ACC_PUBLIC | ACC_ABSTRACT, @@ -238,6 +245,32 @@ final class JavaTraitRegistration { found.trim(java.util.Collections.emptySet()).remove(); } + void removeAbstractSuperConstructor(MethodNode constructor, MethodNode source) { + StackAnalyser stack = new StackAnalyser(Type.getObjectType(input.name), source); + AbstractInsnNode instruction = constructor.instructions.getFirst(); + while (instruction != null) { + if (instruction.getOpcode() == INVOKESPECIAL && instruction instanceof MethodInsnNode) { + MethodInsnNode call = (MethodInsnNode) instruction; + if (Objects.equals(call.owner, input.superName) && Objects.equals(call.name, "")) { + int argumentWidth = 0; + for (Type argument : Type.getArgumentTypes(call.desc)) argumentWidth += argument.getSize(); + StackAnalyser.StackEntry receiver = stack.peek(argumentWidth); + if (receiver instanceof StackAnalyser.Load + && ((StackAnalyser.Load) receiver).e() instanceof StackAnalyser.This) { + removeRange(constructor.instructions, receiver.insn(), instruction); + return; + } + } + } + stack.visitInsn(instruction); + instruction = instruction.getNext(); + } + throw new IllegalArgumentException( + "Invalid constructor insn sequence " + input.name + + "\n" + + new InsnListSection(constructor.instructions)); + } + boolean isGeneratedFieldAccessor(MethodNode method) { for (FieldMixin field : iterable(fields.values())) { String name = field.accessName(input.name); @@ -256,6 +289,16 @@ final class JavaTraitRegistration { return replacement; } + private static void removeRange(InsnList instructions, AbstractInsnNode first, AbstractInsnNode last) { + AbstractInsnNode after = last.getNext(); + AbstractInsnNode instruction = first; + while (instruction != after) { + AbstractInsnNode next = instruction.getNext(); + instructions.remove(instruction); + instruction = next; + } + } + private static java.lang.Iterable iterable(scala.collection.Iterable values) { return JavaConversions.asJavaIterable(values); }