From 13ec2f5547470b658c88e95936ac2b3c35e770a3 Mon Sep 17 00:00:00 2001 From: Algent Date: Wed, 2 Sep 2026 21:01:15 +0200 Subject: [PATCH] refactor: port ASM mixin factory to Java Preserve Scala collection descriptors and public JVM hooks. Recompiled Scala callers need explicit Seq arguments. --- JAVA_MIGRATION.md | 17 ++ JAVA_MIGRATION_DIVERGENCES.md | 4 + JAVA_MIGRATION_HANDOFF.md | 29 ++-- .../multipart/asm/ASMMixinFactory.java | 149 ++++++++++++++++++ .../multipart/asm/ASMMixinFactory.scala | 104 ------------ .../multipart/asm/MultipartMixinFactory.scala | 10 +- 6 files changed, 196 insertions(+), 117 deletions(-) create mode 100644 src/main/scala/codechicken/multipart/asm/ASMMixinFactory.java delete mode 100644 src/main/scala/codechicken/multipart/asm/ASMMixinFactory.scala diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 7728d99..a23a045 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -1299,3 +1299,20 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec JVM tests; Java 8 Forge passes all 116 tests, including external Scala-trait generation. All 39 generated dump names and SHA-256 hashes match the reference. No new ledger entry is needed. `multipart/asm/ASMMixinFactory.scala` is next as a single factory port before the larger nested signature model and compiler. + +### 2026-09-02 + +- Ported `ASMMixinFactory` directly to Java, retaining the Scala `Seq` constructor/argument descriptors, all six + fields, synchronized construction, live parameter conversion, copied cache keys, generated-name sequence and both + Scala- and Java-trait registration paths. Parent validation and callback/registration order remain unchanged; + reflection failures escape as the same exceptions without adding checked exceptions to the public methods. +- Kept the reference's public JVM callbacks and both public mangled parent helpers. The retained Scala subclass + needs only an explicit empty parameter sequence and public override syntax. Its companion and five closure types + have identical disassembly; Scala adds four static facade forwarders without changing any existing entry. The + ledger records that additive surface and the Scala-source syntax changes. +- No tests were added, per the current user instruction. Clean formatting/checkstyle/build passes all 276 existing + JVM tests; Java 8 Forge passes all 116 tests, including the external Scala-trait and generated-tile fixtures. All + 39 generated dump names and SHA-256 hashes match the saved `f7be2b1` reference. Both generator companions and all + 137 signature/compiler types have identical disassembly. Removing two private parent-traversal closures reduces + the packaged inventory from 462 to 460 classes. `multipart/asm/MultipartMixinFactory.scala` is next, with the + signature model and compiler algorithms still reserved for later targets. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index ffb9eef..c77db2c 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -75,6 +75,7 @@ Other retained `$class` bridges and `MODULE$` companions are not covered by this | `MicroMaterialRegistry` | Static `setupIDMap`, `calcMaxCuttingStrength` and `loadIcons` forwarders | | `PacketScheduler` / `TScheduledPacketPart` | Static `sendScheduled()` on the facade and `readMask(part, packet)` on the interface | | `TileMultipart` | No-op `renderStatic`, `renderDynamic` and `randomDisplayTick` hooks for dispatching generated overrides through a stable superclass | +| `MultipartMixinFactory` | Four additional Scala-generated static forwarders: `onCompiled`, `autoCompleteJavaTrait` and the two mangled `ASMMixinFactory` parent helpers. Java must expose the base members at their original public JVM access, so Scala now forwards them too; existing facade entries are unchanged. | Previously abstract JVM interface methods now have Java defaults, allowing inheritance without Scala forwarders: @@ -133,6 +134,9 @@ Previously compiled calls to **retained** `$class` bridges still link. This does `angelicaCompat` and microblock `shape`. - `ByteCodeReader.advance(length)(value)` becomes `advance(length, value)` when recompiling Scala. Argument evaluation remains eager, and previously compiled calls retain the same binary descriptor. +- `ASMMixinFactory` constructor parameters and `construct` arguments need an explicit Scala `Seq`, not Scala + varargs syntax. Overrides of `onCompiled` and `autoCompleteJavaTrait` must be public: Java preserves their original + public JVM access without Scala's protected-source metadata. - `tile.partList(i)` becomes `tile.partList.apply(i)`. Static bounds getters on Face, Corner, Edge and Post factories need `aBounds()(index)` instead of `aBounds(index)`; Java no-argument methods may need explicit parentheses. - `TileMultipart.getOrConvertTile2` exposes `Tuple2` instead of a Scala-typed Boolean second diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 7130384..efc0360 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -12,8 +12,8 @@ what breaks, and what is left. The other documents hold the reasoning. | `JAVA_MIGRATION_MANUAL_CHECKS.md` | What no automated test can cover, and must be checked by hand in a client | | `JAVA_MIGRATION_PROFILE.md` | The focused baseline, first measured result, findings, and exact rerun command | -Branch: `algent/java`. Base: `master`. 161 commits including the API-cleanup plan, divergence-log cleanup and ports -through `ScalaSigReader`. +Branch: `algent/java`. Base: `master`. 162 commits including the API-cleanup plan, divergence-log cleanup and ports +through `ASMMixinFactory`. ## The one rule that matters @@ -278,7 +278,7 @@ across the port. It is also where the two shim constraints in the gotchas list w `rayTraceAll`'s index production is now characterized, closing the gap the read-path cleanup left: the index written into `ExtendedMOP.data` is what `reduceMOP` hands back to every click, activate, harvest and pick block. -202 Java files, 11 Scala files, 2,254 Scala lines left (non-blank; that is the metric this figure has always used). +203 Java files, 10 Scala files, 2,170 Scala lines left (non-blank; that is the metric this figure has always used). ## What is left, and in what order @@ -532,8 +532,8 @@ transparency decisions, render masks, traversal ranges and the complete trait de trait/helper disassembly is bytecode-identical; only the private shrink traversal closure disappears. WR-CBE's load-bearing static `MicroOcclusion.recalcBounds(JMicroShrinkRender, Cuboid6)` call remains exact. -The microblock generator is now a Java facade, companion and real nested material interface over the unchanged Scala -`ASMMixinFactory` and the now-Java `ScratchBitSet`. Three plain-JVM cases freeze all three runtime surfaces, scratch replacement +The microblock generator is now a Java facade, companion and real nested material interface over the now-Java +`ASMMixinFactory` and `ScratchBitSet`. Three plain-JVM cases freeze all three runtime surfaces, scratch replacement and clearing, and the load-bearing call opcodes. One Forge case covers the previously missing full path from an `IGeneratedMaterial` callback through registered external Scala-trait initialization and dispatch. The runtime class list and all callable public descriptors remain exact for ProjectRed and GuideNH. @@ -583,11 +583,20 @@ identical disassembly, and all 39 Forge-suite dump names and contents match. Onl closure disappears, reducing the packaged inventory from 463 to 462 classes. Existing suites remain at 276 JVM and 116 Forge tests; no tests were added. -**Next: `multipart/asm/ASMMixinFactory.scala`.** Port this single factory before the larger nested signature model. -Preserve its Scala `Seq` constructor/argument boundaries, protected callbacks, synchronized construction, copied -BitSet cache keys, generated-name sequence and registration/parent-validation order. Keep both Scala- and Java-trait -registration paths and the existing maps. Leave `MultipartMixinFactory`, the signature model and compiler algorithms -unchanged apart from necessary source-call adjustments. +`ASMMixinFactory` is now Java. Its Scala `Seq` boundaries, synchronized construction, copied BitSet cache keys, +generated-name sequence, registration order and both trait-registration paths remain. The callbacks declared +`protected` in Scala are public in the reference bytecode and remain public, as do both mangled parent helpers. +All existing callable surfaces match the reference; the retained Scala `MultipartMixinFactory` emits four additional +static forwarders, recorded in the ledger. Its companion and five closures, both generator companions and all 137 +signature/compiler types have identical disassembly. All 39 generated dump names and contents match, and the existing +276 JVM / 116 Forge tests pass unchanged. Removing two private parent-traversal closures reduces the packaged +inventory from 462 to 460 classes. No tests were added. + +**Next: `multipart/asm/MultipartMixinFactory.scala`.** Port this facade/companion pair before the larger nested +signature model. Preserve the current public surface (including the four new static forwarders), constructor, +side-safe `onCompiled` callback, non-transient-field `copyFrom` generation and pass-through bytecode. Keep method +collection/override order, generated names, missing-interface logging and registration order; compare generated dumps +against a saved reference. Leave the signature model and compiler algorithms unchanged. The remaining generated microblock traits still need the Phase 7 abstract-Java-mixin and side-only-member support before their Java mixin inputs are safe; do not bypass those prerequisites by flattening their inheritance. diff --git a/src/main/scala/codechicken/multipart/asm/ASMMixinFactory.java b/src/main/scala/codechicken/multipart/asm/ASMMixinFactory.java new file mode 100644 index 0000000..a1a7103 --- /dev/null +++ b/src/main/scala/codechicken/multipart/asm/ASMMixinFactory.java @@ -0,0 +1,149 @@ +package codechicken.multipart.asm; + +import java.lang.reflect.Constructor; +import java.util.BitSet; +import java.util.Objects; + +import org.objectweb.asm.tree.ClassNode; + +import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo; +import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo; +import scala.Option; +import scala.collection.Seq; +import scala.collection.Seq$; +import scala.collection.mutable.ArrayBuffer; +import scala.collection.mutable.Builder; +import scala.collection.mutable.HashMap; +import scala.collection.mutable.Map; +import scala.reflect.ClassTag$; +import scala.runtime.BoxesRunTime; + +public class ASMMixinFactory { + + private final Class baseType; + private final Seq> paramTypes; + private final Map traitMap; + private final ArrayBuffer traits; + private final Map> classMap; + private int ugenid; + + public ASMMixinFactory(Class baseType, Seq> paramTypes) { + this.baseType = baseType; + this.paramTypes = paramTypes; + traitMap = new HashMap<>(); + traits = new ArrayBuffer<>(); + classMap = new HashMap<>(); + } + + public Class baseType() { + return baseType; + } + + private String nextName() { + String name = baseType().getSimpleName() + "_cmp$$" + ugenid; + ugenid++; + return name; + } + + @SuppressWarnings("unchecked") + private Constructor compile(BitSet traitSet) throws NoSuchMethodException { + Builder> seq = Seq$.MODULE$.newBuilder(); + for (int i = traitSet.nextSetBit(0); i >= 0; i = traitSet.nextSetBit(i + 1)) { + seq.$plus$eq(traits.apply(i)); + } + + Class clazz = (Class) ASMMixinCompiler$.MODULE$ + .mixinClasses(nextName(), ASMImplicits.nodeName(baseType().getName()), seq.result()); + onCompiled(clazz, traitSet); + return clazz.getDeclaredConstructor((Class[]) paramTypes.toArray(ClassTag$.MODULE$.apply(Class.class))); + } + + // Scala's protected hooks are public in the reference bytecode. + public void onCompiled(Class clazz, BitSet traitSet) {} + + public void autoCompleteJavaTrait(ClassNode cnode) {} + + public synchronized T construct(BitSet traitSet, Seq args) { + try { + Option> cached = classMap.get(traitSet); + Constructor constructor; + if (cached.isDefined()) { + constructor = cached.get(); + } else { + constructor = compile(traitSet); + classMap.put(ASMImplicits.ExtBitSet$.MODULE$.copy$extension(traitSet), constructor); + } + return constructor.newInstance((Object[]) args.toArray(ClassTag$.MODULE$.Object())); + } catch (ReflectiveOperationException e) { + return ASMMixinFactory.throwUnchecked(e); + } + } + + public int getId(String s_trait) { + return BoxesRunTime.unboxToInt(traitMap.apply(s_trait)); + } + + public int registerTrait(Class traitClass) { + return registerTrait(ASMImplicits.nodeName(traitClass.getName())); + } + + public int registerTrait(String s_trait) { + ClassNode cnode = ASMMixinCompiler$.MODULE$.classNode(s_trait); + if (cnode == null) { + return ASMMixinFactory.throwUnchecked(new ClassNotFoundException(s_trait)); + } + + Option registered = traitMap.get(cnode.name); + if (registered.isDefined()) { + return BoxesRunTime.unboxToInt(registered.get()); + } + + ClassInfo info = ASMMixinCompiler$.MODULE$.getClassInfo(cnode); + String parentName = codechicken$multipart$asm$ASMMixinFactory$$concreteParent$1(info).name(); + if (!codechicken$multipart$asm$ASMMixinFactory$$checkParent$1( + ASMMixinCompiler$.MODULE$.getClassInfo(baseType()), + parentName)) { + throw new IllegalArgumentException( + ASMImplicits.nodeName(baseType().getName()) + " does not extend parent " + + parentName + + " of mixin trait " + + s_trait); + } + + if (info.isTrait()) { + ASMMixinCompiler$.MODULE$.registerScalaTrait(cnode); + } else { + autoCompleteJavaTrait(cnode); + ASMMixinCompiler$.MODULE$.registerJavaTrait(cnode); + } + + int id = traits.size(); + traits.$plus$eq(cnode.name); + traitMap.put(cnode.name, id); + return id; + } + + // Retain the public helpers emitted for Scala's local recursive functions. + public final ClassInfo codechicken$multipart$asm$ASMMixinFactory$$concreteParent$1(ClassInfo info) { + Option mixin = ASMMixinCompiler$.MODULE$.getMixinInfo(info.name()); + if (mixin.isDefined()) { + return ASMMixinCompiler$.MODULE$.getClassInfo(mixin.get().parent()); + } + ClassInfo parent = info.superClass().get(); + if (parent.isTrait() || ASMMixinCompiler$.MODULE$.getMixinInfo(parent.name()).isDefined()) { + return codechicken$multipart$asm$ASMMixinFactory$$concreteParent$1(parent); + } + return parent; + } + + public final boolean codechicken$multipart$asm$ASMMixinFactory$$checkParent$1(ClassInfo info, String parentName) { + if (Objects.equals(info.name(), parentName)) return true; + Option parent = info.superClass(); + return parent.isDefined() && codechicken$multipart$asm$ASMMixinFactory$$checkParent$1(parent.get(), parentName); + } + + @SuppressWarnings("unchecked") + private static R throwUnchecked(Throwable throwable) throws E { + throw (E) throwable; + } +} diff --git a/src/main/scala/codechicken/multipart/asm/ASMMixinFactory.scala b/src/main/scala/codechicken/multipart/asm/ASMMixinFactory.scala deleted file mode 100644 index eb7a055..0000000 --- a/src/main/scala/codechicken/multipart/asm/ASMMixinFactory.scala +++ /dev/null @@ -1,104 +0,0 @@ -package codechicken.multipart.asm - -import java.lang.reflect.Constructor -import scala.collection.mutable -import org.objectweb.asm.tree.ClassNode -import java.util.BitSet -import scala.collection.mutable.ArrayBuffer -import ASMMixinCompiler._ -import ASMImplicits._ - -class ASMMixinFactory[T]( - val baseType: Class[T], - private val paramTypes: Class[_]* -) { - private val traitMap = mutable.Map[String, Int]() - private val traits = ArrayBuffer[String]() - private val classMap = mutable.Map[BitSet, Constructor[_ <: T]]() - - private var ugenid = 0 - - private def nextName() = { - val ret = baseType.getSimpleName + "_cmp$$" + ugenid - ugenid += 1 - ret - } - - private def compile(traitSet: BitSet) = { - val seq = Seq.newBuilder[String] - var i = -1 - while ({ i = traitSet.nextSetBit(i + 1); i >= 0 }) - seq += traits(i) - - val c = ASMMixinCompiler - .mixinClasses(nextName(), nodeName(baseType.getName), seq.result()) - .asInstanceOf[Class[_ <: T]] - onCompiled(c, traitSet) - c.getDeclaredConstructor(paramTypes: _*) - } - - protected def onCompiled(clazz: Class[_ <: T], traitSet: BitSet) {} - protected def autoCompleteJavaTrait(cnode: ClassNode) {} - - def construct(traitSet: BitSet, args: Object*) = synchronized { - (classMap.get(traitSet) match { - case Some(c) => c - case None => - val c = compile(traitSet) - classMap.put(ExtBitSet$.MODULE$.copy$extension(traitSet), c) - c - }).newInstance(args: _*) - } - - def getId(s_trait: String) = traitMap(s_trait) - - def registerTrait(traitClass: Class[_]): Int = registerTrait( - nodeName(traitClass.getName) - ) - - def registerTrait(s_trait: String): Int = { - val cnode = classNode(s_trait) - if (cnode == null) - throw new ClassNotFoundException(s_trait) - - traitMap.get(cnode.name) match { - case Some(id) => return id - case None => - } - - val info = getClassInfo(cnode) - def concreteParent(info: ClassInfo): ClassInfo = getMixinInfo( - info.name - ) match { - case Some(mixin) => getClassInfo(mixin.parent) - case None => - info.superClass.map { - case i if i.isTrait || getMixinInfo(i.name).isDefined => - concreteParent(i) - case i => i - }.get - } - - val parentName = concreteParent(info).name - def checkParent(info: ClassInfo): Boolean = - info.name == parentName || info.superClass.exists(checkParent) - if (!checkParent(getClassInfo(baseType))) - throw new IllegalArgumentException( - nodeName( - baseType.getName - ) + " does not extend parent " + parentName + " of mixin trait " + s_trait - ) - - if (info.isTrait) { - registerScalaTrait(cnode) - } else { - autoCompleteJavaTrait(cnode) - registerJavaTrait(cnode) - } - - val id = traits.size - traits += cnode.name - traitMap.put(cnode.name, id) - id - } -} diff --git a/src/main/scala/codechicken/multipart/asm/MultipartMixinFactory.scala b/src/main/scala/codechicken/multipart/asm/MultipartMixinFactory.scala index 82cbc52..35c5f64 100644 --- a/src/main/scala/codechicken/multipart/asm/MultipartMixinFactory.scala +++ b/src/main/scala/codechicken/multipart/asm/MultipartMixinFactory.scala @@ -12,8 +12,12 @@ import ASMImplicits._ import scala.collection.JavaConversions._ -object MultipartMixinFactory extends ASMMixinFactory(classOf[TileMultipart]) { - override protected def autoCompleteJavaTrait(cnode: ClassNode) { +object MultipartMixinFactory + extends ASMMixinFactory[TileMultipart]( + classOf[TileMultipart], + scala.Predef.wrapRefArray(new Array[Class[_]](0)) + ) { + override def autoCompleteJavaTrait(cnode: ClassNode) { val copyFields = cnode.fields.filter(f => (f.access & ACC_TRANSIENT) == 0) if ( !copyFields.isEmpty && findMethod( @@ -241,7 +245,7 @@ object MultipartMixinFactory extends ASMMixinFactory(classOf[TileMultipart]) { return tname } - override protected def onCompiled( + override def onCompiled( clazz: Class[_ <: TileMultipart], traitSet: BitSet ) =