refactor: port Scala trait registration to Java

This commit is contained in:
Algent committed 2026-09-03 14:48:44 +02:00
1 parent d2276c45f3
commit 21535e50eb
4 files changed
+215 -65

No files matched your search

+28
View File
@@ -1522,3 +1522,31 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec
versions match both packaged jar versions. External Scala-trait tests remain green; existing manual client checks
and Java-source model-bridge limitations remain outstanding. Next: Scala-trait registration metadata,
`getAndRegisterParentTraits` and `registerScalaTrait`, characterized first with no registration algorithm changes.
- Added twelve Forge characterization tests for Scala-trait registration, passing against untouched Scala and
committed separately as `d2276c4`. Real compiled Scala traits exercise parent/field/method/super metadata and side
selection; synthetic signatures pin cached identity/nulls, lookup-before-registration ordering, duplicate parents,
partial caches after failure, owner value equality, filtering precedence, first exact method identity, preceding
accessor selection and mutation of the publication key by a metadata callback. Baseline: 333 JVM / 159 Forge.
- Extracted `getAndRegisterParentTraits` and `registerScalaTrait` into Java `ScalaTraitRegistration`, retaining their
exact Scala entry points and four small callbacks for nested metadata type tests/casts and accessors. A javac probe
confirms it expects `ASMMixinCompiler$ClassInfo$$ScalaClassInfo` for the existing nested model, whose binary name has
only one `$` between `ClassInfo` and `ScalaClassInfo`. The model stays in Scala. The class-symbol callback uses
`Object` at the joint-compilation boundary and the retained `ClassSymbolRef` inside Java. No named model or bridge
is removed; collection dispatch/builders, cache publication and registration algorithms are unchanged.
- The compiled fixtures exposed the existing Scala `String` alias limitation: its parameter descriptor becomes
`Lscala/Predef/String;`, which cannot match the classfile method. A dedicated test freezes the exact registration
failure, while the successful fixture spells the type `java.lang.String`. Missing accessors/methods and partial
parent registration on failure remain unchanged. These are reference behaviors, not new divergences or fixes.
- Saved pre-port source/jar, reports and 40 generated dumps in ignored `run/migration-scala-trait-reference/`. All 16
named compiler APIs match by member names/descriptors/modifiers/generic signatures and private fields; 14 named
classfiles are byte-identical. All 217 other named compiler methods, 28 other algorithm closures, 19 existing
metadata-helper methods and 147 other ASM/generator disassemblies match. All 40 dump names/hashes match exactly.
The Java helper/callbacks and retained Scala type bridges change the packaged inventory from 450 to 455 classes;
private artifacts are covered by the shared compiler entry, so no new ledger entry is needed. Sources total 210
Java files and 9 Scala files / 1,629 nonblank Scala lines.
- Formatting/checkstyle/build and Forge pass, including clean verification after stopping Gradle: 333 JVM / 159 Forge,
zero failures/errors/skips. The twelve characterization tests are unchanged after extraction. The clean jar repeats
the API/disassembly/dump comparisons; the local dev config and forced Scala-compilation guard are unchanged. All
five `@Mod` versions match both packaged jar versions. External Scala-trait tests remain green; existing manual
client checks and Java-source model-bridge limitations remain. Next: `getBytes`, `classNode` and `internalDefine`
class-byte loading/cache helpers, characterized first and without loader/cache algorithm changes.
+41 -9
View File
@@ -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`. 183 commits including the API-cleanup plan, divergence-log cleanup, ports
through side-only annotation filtering, and the ASM characterization backfill and review fixes.
Branch: `algent/java`. Base: `master`. 185 commits including the API-cleanup plan, divergence-log cleanup, ports
through Scala-trait registration metadata, and the ASM characterization backfill and review fixes.
The multipart review corrections (`5af333c`) are on `algent/java`; subsequent migration work continues in that branch.
@@ -76,7 +76,7 @@ awk -F'"' '/<testsuite /{t+=$4;f+=$8;e+=$10} END{print "tests="t" failures="f" e
grep -o 'tests="[0-9]*" skipped="[0-9]*" failures="[0-9]*" errors="[0-9]*"' run/server/junit-out/TEST-*.xml
```
Current baseline: **333 plain-JVM tests and 147 Java 8 Forge dedicated-server tests passing.** The ignored local server
Current baseline: **333 plain-JVM tests and 159 Java 8 Forge dedicated-server tests passing.** The ignored local server
EULA is accepted in this checkout. GitHub Actions runs the same self-validating Forge suite in a dependent job after
the shared GTNH build; keep both jobs required.
@@ -282,7 +282,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.
209 Java files, 9 Scala files, 1,664 Scala lines left (non-blank; that is the metric this figure has always used).
210 Java files, 9 Scala files, 1,629 Scala lines left (non-blank; that is the metric this figure has always used).
## What is left, and in what order
@@ -773,11 +773,43 @@ repeat the matches above; the dev config and forced Scala-compilation guard are
match both packaged jar versions. External Scala-trait tests remain green; manual client checks and Java-source
model-bridge limitations remain outstanding.
**Next: Scala-trait registration metadata in `ASMMixinCompiler`: `getAndRegisterParentTraits` and
`registerScalaTrait`.** Characterize parent traversal/registration order, cached registration, side filtering,
field/method/super metadata and failures before extraction. Preserve the existing registration algorithm, Scala
collection behavior, external Scala-trait support and retained model/`ScalaSignature` bridges. Keep Java-trait
rewriting and composition separate. Save a fresh reference and compare generated dumps before expanding scope.
`ASMMixinCompiler.getAndRegisterParentTraits` and `registerScalaTrait` now delegate to Java `ScalaTraitRegistration`.
Twelve Forge characterization tests passed against untouched Scala and were committed separately as `d2276c4`.
Compiled Scala traits freeze real parent/field/method/super metadata and side selection. Synthetic signatures cover
cached identity/nulls, parent lookup before registration, duplicate/order preservation, partial parent-cache state on
failure, owner value equality, filter precedence, exact first-method identity, accessor ordering and callback-driven
publication-key changes. The original singleton requires Forge initialization, so the existing harness is used.
Four small Scala callbacks retain nested metadata type tests/casts and accessors. A javac probe confirms that
`ClassInfo$.ScalaClassInfo` is looked up as `ASMMixinCompiler$ClassInfo$$ScalaClassInfo`, while its retained binary name
contains only one `$` between `ClassInfo` and `ScalaClassInfo`. Renaming that model would break compatibility; its
Scala bridge remains. Joint compilation also needs the class-symbol callback to return `Object`, with the existing
`ScalaSignature.ClassSymbolRef` cast inside Java. The named model classes, primitive/erased ScalaSignature bridges,
Scala collection dispatch/builders and registration algorithm remain unchanged.
The compiled fixtures exposed a pre-existing decoder limitation: an unqualified Scala `String` parameter is decoded
as `Lscala/Predef/String;` and registration fails to find its classfile method. A dedicated regression test preserves
that exact failure; the successful fixture uses `java.lang.String`. Missing accessors/methods still fail rather than
being silently repaired, and failed child registration keeps already-completed parent registrations.
Reference source/jar, reports, dumps, logs and comparisons are under ignored `run/migration-scala-trait-reference/`.
All 16 named compiler APIs retain names/descriptors/modifiers/generic signatures and private fields; 14 named
classfiles are byte-identical. All 217 other named compiler methods, 28 other algorithm closures, 19 existing
metadata-helper methods and 147 other ASM/generator disassemblies match. All 40 generated dump names/hashes match
exactly. The new Java helper/callbacks and retained Scala type bridges bring the inventory from 450 to 455 classes;
the shared compiler entry covers the private artifacts, with no new effective divergence. Sources total 210 Java
files and 9 Scala files / 1,629 nonblank Scala lines.
Formatting/checkstyle/build and Forge pass, including a clean build after stopping Gradle: 333 JVM / 159 Forge,
zero failures/errors/skips. All twelve characterization tests remain unchanged after the port. Clean APIs and dumps
repeat the matches above; the dev config and forced Scala-compilation guard are unchanged. All five `@Mod` versions
match both packaged jar versions. External Scala-trait tests remain green; manual client checks and Java-source
model-bridge limitations remain outstanding.
**Next: `ASMMixinCompiler` class-byte loading/cache helpers: `getBytes`, `classNode` and `internalDefine`.**
Characterize name normalization, cache identity/invalidation, transformer exclusions/remapping, nulls and failure
ordering before extraction. Preserve the existing loader and cache algorithm. Keep reflective class definition,
Java-trait rewriting and composition separate, and retain external Scala-trait support and the model bridges.
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.
@@ -436,11 +436,17 @@ object ASMMixinCompiler {
stack: StackAnalyser
): Option[MethodInfo] = ClassInfoLookup.getSuper(minsn, stack)
// javac expects an extra '$' in the retained ClassInfo$ nested binary names.
def getAndRegisterParentTraits(cnode: ClassNode) =
cnode.interfaces.map(getClassInfo).collect {
case i: ClassInfo.ScalaClassInfo if i.isTrait && !i.csym.isInterface =>
registerScalaTrait(i.cnode)
}
ScalaTraitRegistration.getAndRegisterParentTraits(
cnode,
info =>
info match {
case i: ClassInfo.ScalaClassInfo => i.isTrait && !i.csym.isInterface
case _ => false
},
info => info.asInstanceOf[ClassInfo.ScalaClassInfo].cnode
)
def registerJavaTrait(cnode: ClassNode) {
if ((cnode.access & ACC_INTERFACE) != 0)
@@ -714,56 +720,11 @@ object ASMMixinCompiler {
def listSideOnly(sig: ScalaSignature) = ClassInfoLookup.listSideOnly(sig)
def registerScalaTrait(cnode: ClassNode): MixinInfo = {
getMixinInfo(cnode.name) match {
case Some(info) => return info
case None =>
}
val info = getClassInfo(cnode).asInstanceOf[ClassInfo.ScalaClassInfo]
val sig = info.sig
val sideOnly = listSideOnly(sig)
val parentTraits = getAndRegisterParentTraits(cnode)
val fieldAccessors = MMap[String, sig.MethodSymbol]()
val fields = MList[FieldMixin]()
val methods = MList[MethodNode]()
val supers = MList[String]()
val csym = info.csym
for (sym <- sig.collect[sig.MethodSymbol](8)) {
if (sym.isParam || sym.owner != csym) {} else if (
sideOnly(sym.full)
) {} else if (sym.isAccessor) {
fieldAccessors.put(sym.name, sym)
} else if (sym.isMethod) {
val desc = sym.jDesc
if (sym.name.startsWith("super$"))
supers += sym.name.substring(6) + desc
else if (!sym.isPrivate && !sym.isDeferred && sym.name != "$init$")
methods += (cnode.methods.find(m =>
m.name == sym.name && m.desc == desc
) match {
case Some(m) => m
case None =>
throw new IllegalArgumentException(
"Unable to add mixin trait " + cnode.name + ": " +
sym.name + desc + " found in scala signature but not in class file. Most likely an obfuscation issue."
)
})
} else {
fields += FieldMixin(
sym.name.trim,
sym.jDesc,
if (fieldAccessors(sym.name.trim).isPrivate) ACC_PRIVATE
else ACC_PUBLIC
)
}
}
val mixin =
MixinInfo(cnode.name, csym.jParent, parentTraits, fields, methods, supers)
mixinMap.put(cnode.name, mixin)
mixin
}
def registerScalaTrait(cnode: ClassNode): MixinInfo =
ScalaTraitRegistration.registerScalaTrait(
cnode,
mixinMap,
info => info.asInstanceOf[ClassInfo.ScalaClassInfo].sig,
info => info.asInstanceOf[ClassInfo.ScalaClassInfo].csym
)
}
@@ -0,0 +1,129 @@
package codechicken.multipart.asm;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import java.util.Objects;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.multipart.asm.ASMMixinCompiler.ClassInfo;
import codechicken.multipart.asm.ASMMixinCompiler.FieldMixin;
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
import codechicken.multipart.asm.ScalaSignature.MethodSymbol;
import scala.Function1;
import scala.MatchError;
import scala.None$;
import scala.Option;
import scala.Some;
import scala.collection.JavaConversions;
import scala.collection.TraversableLike;
import scala.collection.immutable.Set;
import scala.collection.mutable.Buffer;
import scala.collection.mutable.Buffer$;
import scala.collection.mutable.ListBuffer;
import scala.collection.mutable.Map;
import scala.collection.mutable.Map$;
import scala.runtime.AbstractFunction1;
import scala.runtime.AbstractPartialFunction;
import scala.runtime.BoxedUnit;
import scala.runtime.BoxesRunTime;
/** Registration behind the Scala bridges for the retained ClassInfo$ nested types. */
@SuppressWarnings({ "unchecked", "rawtypes" })
final class ScalaTraitRegistration {
private ScalaTraitRegistration() {}
static Buffer<MixinInfo> getAndRegisterParentTraits(ClassNode node, final Function1<ClassInfo, Boolean> isTrait,
final Function1<ClassInfo, ClassNode> traitNode) {
TraversableLike parents = (TraversableLike) ((TraversableLike) JavaConversions.asScalaBuffer(node.interfaces))
.map(new AbstractFunction1<String, ClassInfo>() {
@Override
public ClassInfo apply(String name) {
return ASMMixinCompiler$.MODULE$.getClassInfo(name);
}
}, Buffer$.MODULE$.canBuildFrom());
return (Buffer<MixinInfo>) parents.collect(new AbstractPartialFunction<ClassInfo, MixinInfo>() {
@Override
public boolean isDefinedAt(ClassInfo info) {
return BoxesRunTime.unboxToBoolean(isTrait.apply(info));
}
@Override
public <A1 extends ClassInfo, B1> B1 applyOrElse(A1 info, Function1<A1, B1> fallback) {
if (isDefinedAt(info)) return (B1) ASMMixinCompiler$.MODULE$.registerScalaTrait(traitNode.apply(info));
return fallback.apply(info);
}
}, Buffer$.MODULE$.canBuildFrom());
}
static MixinInfo registerScalaTrait(final ClassNode node, Map<String, MixinInfo> mixins,
Function1<ClassInfo, ScalaSignature> signature, Function1<ClassInfo, Object> classSymbol) {
Option<MixinInfo> cached = ASMMixinCompiler$.MODULE$.getMixinInfo(node.name);
if (cached instanceof Some) return cached.get();
if (cached != (Object) None$.MODULE$) throw new MatchError(cached);
ClassInfo info = ASMMixinCompiler$.MODULE$.getClassInfo(node);
ScalaSignature sig = signature.apply(info);
final Set<String> sideOnly = ASMMixinCompiler$.MODULE$.listSideOnly(sig);
Buffer<MixinInfo> parents = ASMMixinCompiler$.MODULE$.getAndRegisterParentTraits(node);
final Map<String, MethodSymbol> accessors = Map$.MODULE$.empty();
final ListBuffer<FieldMixin> fields = new ListBuffer<>();
final ListBuffer<MethodNode> methods = new ListBuffer<>();
final ListBuffer<String> supers = new ListBuffer<>();
final ScalaSignature.ClassSymbolRef symbol = (ScalaSignature.ClassSymbolRef) classSymbol.apply(info);
sig.<MethodSymbol>collect(8).foreach(new AbstractFunction1<MethodSymbol, BoxedUnit>() {
@Override
public BoxedUnit apply(final MethodSymbol method) {
if (method.isParam() || !BoxesRunTime.equals(method.owner(), symbol)) return BoxedUnit.UNIT;
if (sideOnly.apply(method.full())) return BoxedUnit.UNIT;
if (method.isAccessor()) {
accessors.put(method.name(), method);
} else if (method.isMethod()) {
final String desc = method.jDesc();
if (method.name().startsWith("super$")) {
supers.$plus$eq(method.name().substring(6) + desc);
} else
if (!method.isPrivate() && !method.isDeferred() && !Objects.equals(method.name(), "$init$")) {
Option<MethodNode> found = JavaConversions.asScalaBuffer(node.methods)
.find(new AbstractFunction1<MethodNode, Object>() {
@Override
public Object apply(MethodNode candidate) {
return Objects.equals(candidate.name, method.name())
&& Objects.equals(candidate.desc, desc);
}
});
if (found instanceof Some) {
methods.$plus$eq(found.get());
} else if (found == (Object) None$.MODULE$) {
throw new IllegalArgumentException(
"Unable to add mixin trait " + node.name
+ ": "
+ method.name()
+ desc
+ " found in scala signature but not in class file. Most likely an obfuscation issue.");
} else {
throw new MatchError(found);
}
}
} else {
fields.$plus$eq(
new FieldMixin(
method.name().trim(),
method.jDesc(),
accessors.apply(method.name().trim()).isPrivate() ? ACC_PRIVATE : ACC_PUBLIC));
}
return BoxedUnit.UNIT;
}
});
MixinInfo mixin = new MixinInfo(node.name, symbol.jParent(), parents, fields, methods, supers);
mixins.put(node.name, mixin);
return mixin;
}
}