mirror of
https://github.com/GTNewHorizons/ForgeMultipart.git
synced 2026-11-26 15:03:18 +00:00
refactor: port Java trait rewriting to Java
This commit is contained in:
1 parent
85ad2e45cd
commit
c91bdb33c4
5 files changed
+309
-287
No files matched your search
+3
-3
@@ -25,9 +25,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 now delegates to
|
||||
Java `MixinClassGenerator`; the next bounded target is `ASMMixinCompiler.registerJavaTrait`, characterized before
|
||||
its mechanical extraction and kept separate from planned compiler algorithm changes.
|
||||
files and the compiler/signature/analyser compatibility shells remain Scala. Composite generation and Java-trait
|
||||
rewriting now delegate to Java helpers. The next bounded target is an assessment of the remaining compiler
|
||||
startup/model shell; retain ScalaSignature path-dependent bridges and keep compiler behavior changes separate.
|
||||
|
||||
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
|
||||
|
||||
+10
-10
@@ -16,18 +16,18 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes
|
||||
|
||||
## Current state and next target
|
||||
|
||||
**333 plain-JVM tests and 191 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **212 Java
|
||||
files and 9 Scala files / 1,444 nonblank Scala lines**. The packaged inventory has 442 classes.
|
||||
**333 plain-JVM tests and 200 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **213 Java
|
||||
files and 9 Scala files / 1,196 nonblank Scala lines**. The packaged inventory has 436 classes.
|
||||
|
||||
Latest bounded port: `ASMMixinCompiler.mixinClasses` delegates to Java `MixinClassGenerator`, after eight
|
||||
characterization tests passed against untouched Scala (`1c9cd65`). Clean verification after stopping Gradle matched
|
||||
426 non-closure APIs, all 13 non-target compiler closures, 3,628 non-target method bodies and all 79 generated dump
|
||||
names/hashes. The five `@Mod` annotations match both packaged versions. Local reference jars, reports and scripts are
|
||||
in `run/migration-composition-reference/`; `clean` preserves this ignored directory.
|
||||
Latest bounded port: `ASMMixinCompiler.registerJavaTrait` delegates to Java `JavaTraitRegistration`, after nine
|
||||
characterization tests passed against untouched Scala (`85ad2e4`). Clean verification after stopping Gradle matched
|
||||
428 non-target class APIs, all five non-target compiler closures, 3,635 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-java-trait-reference/`; `clean` preserves this ignored directory.
|
||||
|
||||
**Next: `ASMMixinCompiler.registerJavaTrait` rewriting.** Characterize rejected shapes, cloning, initialization,
|
||||
field/method/super rewriting, publication and failure ordering before extraction. Preserve the existing algorithm;
|
||||
keep abstract-mixin support, side-only member filtering and other compiler changes separate.
|
||||
**Next: assess the remaining `ASMMixinCompiler` startup/model shell and select the next isolated extraction.** The
|
||||
ScalaSignature path-dependent model bridges must remain Scala-facing. Keep abstract-Java-mixin support, Java-path
|
||||
side-only filtering and other compiler changes as separate behavior targets with fresh characterization.
|
||||
|
||||
Remaining Scala units:
|
||||
|
||||
|
||||
@@ -949,3 +949,23 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m
|
||||
the forced Scala-compilation guard and dev config remain correct. Sources total 212 Java files and 9 Scala files /
|
||||
1,444 nonblank Scala lines. Next: `ASMMixinCompiler.registerJavaTrait`, characterized before extraction; abstract
|
||||
mixins, side-only filtering and the wide-field defect remain separate compiler changes.
|
||||
|
||||
### 2026-09-03 — Java trait rewriting
|
||||
|
||||
- Added nine Forge characterization tests for `ASMMixinCompiler.registerJavaTrait`, passing against untouched Scala
|
||||
and committed first as `85ad2e4`. They freeze rejected shapes, exact input cloning, constructors, initialization,
|
||||
field accessors, private/public methods, virtual self calls, super dispatch, parent traits, source metadata,
|
||||
implemented-interface deduplication, side-only annotation retention and partial publication after definition errors.
|
||||
They also preserve the existing primitive-`NEWARRAY`, foreign-field and inherited-call failures.
|
||||
- Moved only rewriting into Java `JavaTraitRegistration`; registration dispatch and the Scala `MixinInfo` shell remain
|
||||
in the singleton. Abstract mixins and Java-path side filtering remain planned behavior changes. Nine unreferenced
|
||||
target closures and local compiler helpers become the Java helper, its context and callback, taking the packaged
|
||||
inventory from 442 to 436 classes. The shared classfile ledger covers these artifacts; no effective divergence was
|
||||
added.
|
||||
- Saved the pre-port source/jar, reports, 102 generated outputs and checks in ignored
|
||||
`run/migration-java-trait-reference/`. Clean verification after stopping Gradle matches 428 non-target class APIs,
|
||||
3,635 non-target method bodies, all five other compiler closures and every output name/hash. Formatting, checkstyle,
|
||||
build and Forge pass: 333 JVM / 200 Forge, zero failures/errors/skips. All five packaged `@Mod` versions, the forced
|
||||
Scala-compilation guard and dev config remain correct. Sources total 213 Java files and 9 Scala files / 1,196
|
||||
nonblank Scala lines. Next: assess the remaining compiler startup/model shell before selecting another extraction;
|
||||
retained ScalaSignature model bridges remain the Java-source limit.
|
||||
@@ -1,14 +1,12 @@
|
||||
package codechicken.multipart.asm
|
||||
|
||||
import scala.collection.mutable.{Map => MMap, ListBuffer => MList, Set => MSet}
|
||||
import scala.collection.mutable.{Map => MMap}
|
||||
import scala.collection.JavaConversions._
|
||||
import org.objectweb.asm.tree._
|
||||
import org.objectweb.asm.Opcodes._
|
||||
import org.objectweb.asm.Type
|
||||
import org.objectweb.asm.MethodVisitor
|
||||
import Type._
|
||||
import org.objectweb.asm.Type._
|
||||
import codechicken.lib.asm.ASMHelper._
|
||||
import codechicken.lib.asm.{InsnListSection, InsnComparator}
|
||||
import java.lang.reflect.Method
|
||||
import java.lang.reflect.Modifier
|
||||
import net.minecraft.launchwrapper.LaunchClassLoader
|
||||
@@ -240,276 +238,8 @@ object ASMMixinCompiler {
|
||||
info => info.asInstanceOf[ClassInfo.ScalaClassInfo].cnode
|
||||
)
|
||||
|
||||
def registerJavaTrait(cnode: ClassNode) {
|
||||
if ((cnode.access & ACC_INTERFACE) != 0)
|
||||
throw new IllegalArgumentException(
|
||||
"Cannot register java interface " + cnode.name + " as a mixin trait. Try register passThroughInterface"
|
||||
)
|
||||
if (!cnode.innerClasses.isEmpty)
|
||||
throw new IllegalArgumentException(
|
||||
"Inner classes are not permitted for " + cnode.name + " as a java mixin trait. Use scala"
|
||||
)
|
||||
if ((cnode.access & ACC_ABSTRACT) != 0)
|
||||
throw new IllegalArgumentException(
|
||||
"Cannot register abstract class " + cnode.name + " as a java mixin trait. Use scala"
|
||||
)
|
||||
|
||||
val parentTrait = getMixinInfo(cnode.superName)
|
||||
val fields = cnode.fields
|
||||
.map(f => (f.name, FieldMixin(f.name, f.desc, f.access)))
|
||||
.toMap
|
||||
val supers = MList[String]() // nameDesc to super owner
|
||||
val methods = MList[MethodNode]()
|
||||
val methodSigs = cnode.methods.map(m => m.name + m.desc).toSet
|
||||
|
||||
/*if ((cnode.access & ACC_ABSTRACT) != 0) {//verify all methods are implemented
|
||||
def getInterfaces(cnode:ClassNode):Seq[ClassNode] = cnode.interfaces.map(classNode).flatMap(i => getInterfaces(i) :+ i)
|
||||
val interfaces = getInterfaces(cnode).distinct
|
||||
val implementedSigs = (cnode.methods.filter(m => (m.access & ACC_ABSTRACT) == 0)++parentTraits.flatMap(_.methods)).map(m => m.name + m.desc).toSet
|
||||
val missing = interfaces.flatMap(_.methods).map(m => m.name + m.desc).filterNot(implementedSigs)
|
||||
if(!missing.isEmpty)
|
||||
throw new IllegalArgumentException("Abstract java trait "+cnode.name+" needs to implement "+missing.mkString(", "))
|
||||
}*/
|
||||
|
||||
val inode = new ClassNode() // impl node
|
||||
inode.visit(
|
||||
V1_6,
|
||||
ACC_ABSTRACT | ACC_PUBLIC,
|
||||
cnode.name + "$class",
|
||||
null,
|
||||
"java/lang/Object",
|
||||
null
|
||||
)
|
||||
inode.sourceFile = cnode.sourceFile
|
||||
|
||||
val tnode = new ClassNode() // trait node (interface)
|
||||
tnode.visit(
|
||||
V1_6,
|
||||
ACC_INTERFACE | ACC_ABSTRACT | ACC_PUBLIC,
|
||||
cnode.name,
|
||||
null,
|
||||
"java/lang/Object",
|
||||
(cnode.interfaces ++ parentTrait.map(_.name)).distinct.toArray
|
||||
)
|
||||
|
||||
def fname(name: String) = fields(name).accessName(cnode.name)
|
||||
|
||||
fields.values.foreach { fnode =>
|
||||
tnode.visitMethod(
|
||||
ACC_PUBLIC | ACC_ABSTRACT,
|
||||
fname(fnode.name),
|
||||
"()" + fnode.desc,
|
||||
null,
|
||||
null
|
||||
)
|
||||
tnode.visitMethod(
|
||||
ACC_PUBLIC | ACC_ABSTRACT,
|
||||
fname(fnode.name) + "_$eq",
|
||||
"(" + fnode.desc + ")V",
|
||||
null,
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
def superInsn(minsn: MethodInsnNode) = {
|
||||
val bridgeName = cnode.name.replace('/', '$') + "$$super$" + minsn.name
|
||||
if (!supers.contains(minsn.name + minsn.desc)) {
|
||||
tnode.visitMethod(
|
||||
ACC_PUBLIC | ACC_ABSTRACT,
|
||||
bridgeName,
|
||||
minsn.desc,
|
||||
null,
|
||||
null
|
||||
)
|
||||
supers += minsn.name + minsn.desc
|
||||
}
|
||||
new MethodInsnNode(
|
||||
INVOKEINTERFACE,
|
||||
cnode.name,
|
||||
bridgeName,
|
||||
minsn.desc,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
def staticClone(mnode: MethodNode, name: String, access: Int) = {
|
||||
val mv = inode
|
||||
.visitMethod(
|
||||
access | ACC_STATIC,
|
||||
name,
|
||||
staticDesc(cnode.name, mnode.desc),
|
||||
null,
|
||||
Array(mnode.exceptions: _*)
|
||||
)
|
||||
.asInstanceOf[MethodNode]
|
||||
copy(mnode, mv)
|
||||
mv
|
||||
}
|
||||
|
||||
def staticTransform(mnode: MethodNode, base: MethodNode) {
|
||||
val stack = new StackAnalyser(
|
||||
getType(Type.getObjectType(cnode.name).getDescriptor),
|
||||
base
|
||||
)
|
||||
val insnList = mnode.instructions
|
||||
var insn = insnList.getFirst
|
||||
|
||||
def replace(newinsn: AbstractInsnNode) {
|
||||
insnList.insert(insn, newinsn)
|
||||
insnList.remove(insn)
|
||||
insn = newinsn
|
||||
}
|
||||
|
||||
// transform
|
||||
while (insn != null) {
|
||||
insn match {
|
||||
case finsn: FieldInsnNode =>
|
||||
insn.getOpcode match {
|
||||
case GETFIELD =>
|
||||
replace(
|
||||
new MethodInsnNode(
|
||||
INVOKEINTERFACE,
|
||||
cnode.name,
|
||||
fname(finsn.name),
|
||||
"()" + finsn.desc,
|
||||
true
|
||||
)
|
||||
)
|
||||
case PUTFIELD =>
|
||||
replace(
|
||||
new MethodInsnNode(
|
||||
INVOKEINTERFACE,
|
||||
cnode.name,
|
||||
fname(finsn.name) + "_$eq",
|
||||
"(" + finsn.desc + ")V",
|
||||
true
|
||||
)
|
||||
)
|
||||
case _ =>
|
||||
}
|
||||
case minsn: MethodInsnNode =>
|
||||
insn.getOpcode match {
|
||||
case INVOKESPECIAL =>
|
||||
if (getSuper(minsn, stack).isDefined)
|
||||
replace(superInsn(minsn))
|
||||
case INVOKEVIRTUAL =>
|
||||
if (minsn.owner == cnode.name) {
|
||||
if (methodSigs.contains(minsn.name + minsn.desc)) { // call the interface method
|
||||
replace(
|
||||
new MethodInsnNode(
|
||||
INVOKEINTERFACE,
|
||||
minsn.owner,
|
||||
minsn.name,
|
||||
minsn.desc,
|
||||
true
|
||||
)
|
||||
)
|
||||
} else {
|
||||
// cast to parent class and call
|
||||
val mType = Type.getMethodType(minsn.desc)
|
||||
val instanceEntry =
|
||||
stack.peek(width(mType.getArgumentTypes))
|
||||
insnList.insert(
|
||||
instanceEntry.insn,
|
||||
new TypeInsnNode(
|
||||
CHECKCAST,
|
||||
Type.getObjectType(cnode.superName).getDescriptor
|
||||
)
|
||||
)
|
||||
minsn.owner = cnode.superName
|
||||
}
|
||||
}
|
||||
case _ =>
|
||||
}
|
||||
case _ =>
|
||||
}
|
||||
stack.visitInsn(insn)
|
||||
insn = insn.getNext
|
||||
}
|
||||
}
|
||||
|
||||
def convertMethod(mnode: MethodNode) {
|
||||
if (mnode.name == "<clinit>")
|
||||
throw new IllegalArgumentException(
|
||||
"Static initialisers are not permitted " + cnode.name + " as a mixin trait"
|
||||
)
|
||||
|
||||
if (mnode.name == "<init>") {
|
||||
if (mnode.desc != "()V")
|
||||
throw new IllegalArgumentException(
|
||||
"Constructor arguments are not permitted " + cnode.name + " as a mixin trait"
|
||||
)
|
||||
|
||||
val mv = staticClone(mnode, "$init$", ACC_PUBLIC)
|
||||
def removeSuperConstructor() {
|
||||
val insns = new InsnListSection
|
||||
insns.add(new VarInsnNode(ALOAD, 0))
|
||||
insns.add(
|
||||
new MethodInsnNode(
|
||||
INVOKESPECIAL,
|
||||
cnode.superName,
|
||||
"<init>",
|
||||
"()V",
|
||||
false
|
||||
)
|
||||
)
|
||||
|
||||
val minsns = new InsnListSection(mv.instructions)
|
||||
val found = InsnComparator.matches(minsns, insns, Set[LabelNode]())
|
||||
if (found == null)
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid constructor insn sequence " + cnode.name + "\n" + minsns
|
||||
)
|
||||
found.trim(Set[LabelNode]()).remove()
|
||||
}
|
||||
removeSuperConstructor()
|
||||
staticTransform(mv, mnode)
|
||||
return
|
||||
}
|
||||
|
||||
if ((mnode.access & ACC_PRIVATE) == 0) {
|
||||
val mv = tnode.visitMethod(
|
||||
ACC_PUBLIC | ACC_ABSTRACT,
|
||||
mnode.name,
|
||||
mnode.desc,
|
||||
null,
|
||||
Array(mnode.exceptions: _*)
|
||||
)
|
||||
methods += mv.asInstanceOf[MethodNode]
|
||||
}
|
||||
|
||||
// convert that method!
|
||||
val access =
|
||||
if ((mnode.access & ACC_PRIVATE) == 0) ACC_PUBLIC else ACC_PRIVATE
|
||||
val mv = staticClone(mnode, mnode.name, access)
|
||||
staticTransform(mv, mnode)
|
||||
}
|
||||
|
||||
def isGeneratedFieldAccessor(mnode: MethodNode) = fields.values.exists {
|
||||
field =>
|
||||
val name = field.accessName(cnode.name)
|
||||
mnode.name == name && mnode.desc == "()" + field.desc ||
|
||||
mnode.name == name + "_$eq" && mnode.desc == "(" + field.desc + ")V"
|
||||
}
|
||||
|
||||
cnode.methods.filterNot(isGeneratedFieldAccessor).foreach(convertMethod)
|
||||
|
||||
define(inode.name, createBytes(inode, 0))
|
||||
define(tnode.name, createBytes(tnode, 0))
|
||||
|
||||
mixinMap.put(
|
||||
tnode.name,
|
||||
MixinInfo(
|
||||
tnode.name,
|
||||
parentTrait.map(_.parent).getOrElse(cnode.superName),
|
||||
parentTrait.toSeq,
|
||||
fields.values.toSeq,
|
||||
methods,
|
||||
supers
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
def registerJavaTrait(cnode: ClassNode) =
|
||||
JavaTraitRegistration.register(cnode, mixinMap)
|
||||
def listSideOnly(sig: ScalaSignature) = ClassInfoLookup.listSideOnly(sig)
|
||||
|
||||
def registerScalaTrait(cnode: ClassNode): MixinInfo =
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
package codechicken.multipart.asm;
|
||||
|
||||
import static org.objectweb.asm.Opcodes.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.objectweb.asm.Type;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.FieldInsnNode;
|
||||
import org.objectweb.asm.tree.FieldNode;
|
||||
import org.objectweb.asm.tree.InsnList;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
import org.objectweb.asm.tree.TypeInsnNode;
|
||||
import org.objectweb.asm.tree.VarInsnNode;
|
||||
|
||||
import codechicken.lib.asm.ASMHelper;
|
||||
import codechicken.lib.asm.InsnComparator;
|
||||
import codechicken.lib.asm.InsnListSection;
|
||||
import codechicken.multipart.asm.ASMMixinCompiler.FieldMixin;
|
||||
import codechicken.multipart.asm.ASMMixinCompiler.MixinInfo;
|
||||
import scala.Function1;
|
||||
import scala.Option;
|
||||
import scala.Tuple2;
|
||||
import scala.collection.JavaConversions;
|
||||
import scala.collection.TraversableLike;
|
||||
import scala.collection.immutable.Map;
|
||||
import scala.collection.mutable.Buffer;
|
||||
import scala.collection.mutable.ListBuffer;
|
||||
import scala.runtime.AbstractFunction1;
|
||||
|
||||
/** Java mixin rewriting behind the retained compiler singleton and Scala metadata models. */
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
final class JavaTraitRegistration {
|
||||
|
||||
private JavaTraitRegistration() {}
|
||||
|
||||
static void register(ClassNode input, scala.collection.mutable.Map<String, MixinInfo> mixins) {
|
||||
if ((input.access & ACC_INTERFACE) != 0) throw new IllegalArgumentException(
|
||||
"Cannot register java interface " + input.name
|
||||
+ " 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<MixinInfo> parentTrait = compiler.getMixinInfo(input.superName);
|
||||
Buffer<FieldNode> sourceFields = JavaConversions.asScalaBuffer(input.fields);
|
||||
Map<String, FieldMixin> 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)));
|
||||
ListBuffer<String> supers = new ListBuffer<>();
|
||||
ListBuffer<MethodNode> methods = new ListBuffer<>();
|
||||
java.util.Set<String> methodSignatures = new LinkedHashSet<>();
|
||||
for (MethodNode method : input.methods) 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);
|
||||
implementation.sourceFile = input.sourceFile;
|
||||
ClassNode contract = new ClassNode();
|
||||
List<String> interfaces = new ArrayList<>(input.interfaces);
|
||||
if (parentTrait.isDefined()) interfaces.add(parentTrait.get().name());
|
||||
contract.visit(
|
||||
V1_6,
|
||||
ACC_INTERFACE | ACC_ABSTRACT | ACC_PUBLIC,
|
||||
input.name,
|
||||
null,
|
||||
"java/lang/Object",
|
||||
new LinkedHashSet<>(interfaces).toArray(new String[0]));
|
||||
|
||||
for (FieldMixin field : iterable(fields.values())) {
|
||||
String name = field.accessName(input.name);
|
||||
contract.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, name, "()" + field.desc(), null, null);
|
||||
contract.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, name + "_$eq", "(" + field.desc() + ")V", null, null);
|
||||
}
|
||||
|
||||
Context context = new Context(input, implementation, contract, fields, methodSignatures, supers, methods);
|
||||
Buffer<MethodNode> sourceMethods = JavaConversions.asScalaBuffer(input.methods);
|
||||
Buffer<MethodNode> selected = (Buffer<MethodNode>) ((TraversableLike) sourceMethods)
|
||||
.filterNot(fn(context::isGeneratedFieldAccessor));
|
||||
selected.foreach(fn(method -> {
|
||||
context.convertMethod(method);
|
||||
return scala.runtime.BoxedUnit.UNIT;
|
||||
}));
|
||||
|
||||
compiler.define(implementation.name, ASMHelper.createBytes(implementation, 0));
|
||||
compiler.define(contract.name, ASMHelper.createBytes(contract, 0));
|
||||
mixins.put(
|
||||
contract.name,
|
||||
new MixinInfo(
|
||||
contract.name,
|
||||
parentTrait.isDefined() ? parentTrait.get().parent() : input.superName,
|
||||
JavaConversions.asScalaBuffer(
|
||||
parentTrait.isDefined() ? java.util.Collections.singletonList(parentTrait.get())
|
||||
: java.util.Collections.<MixinInfo>emptyList())
|
||||
.toList(),
|
||||
fields.values().toSeq(),
|
||||
methods,
|
||||
supers));
|
||||
}
|
||||
|
||||
private static final class Context {
|
||||
|
||||
final ClassNode input;
|
||||
final ClassNode implementation;
|
||||
final ClassNode contract;
|
||||
final Map<String, FieldMixin> fields;
|
||||
final java.util.Set<String> methodSignatures;
|
||||
final ListBuffer<String> supers;
|
||||
final ListBuffer<MethodNode> methods;
|
||||
|
||||
Context(ClassNode input, ClassNode implementation, ClassNode contract, Map<String, FieldMixin> fields,
|
||||
java.util.Set<String> methodSignatures, ListBuffer<String> supers, ListBuffer<MethodNode> methods) {
|
||||
this.input = input;
|
||||
this.implementation = implementation;
|
||||
this.contract = contract;
|
||||
this.fields = fields;
|
||||
this.methodSignatures = methodSignatures;
|
||||
this.supers = supers;
|
||||
this.methods = methods;
|
||||
}
|
||||
|
||||
String fieldName(String name) {
|
||||
return fields.apply(name).accessName(input.name);
|
||||
}
|
||||
|
||||
MethodInsnNode superInstruction(MethodInsnNode instruction) {
|
||||
String bridge = input.name.replace('/', '$') + "$$super$" + instruction.name;
|
||||
if (!supers.contains(instruction.name + instruction.desc)) {
|
||||
contract.visitMethod(ACC_PUBLIC | ACC_ABSTRACT, bridge, instruction.desc, null, null);
|
||||
supers.$plus$eq(instruction.name + instruction.desc);
|
||||
}
|
||||
return new MethodInsnNode(INVOKEINTERFACE, input.name, bridge, instruction.desc, true);
|
||||
}
|
||||
|
||||
MethodNode staticClone(MethodNode source, String name, int access) {
|
||||
MethodNode result = (MethodNode) implementation.visitMethod(
|
||||
access | ACC_STATIC,
|
||||
name,
|
||||
ASMMixinCompiler$.MODULE$.staticDesc(input.name, source.desc),
|
||||
null,
|
||||
(String[]) source.exceptions.toArray(new String[0]));
|
||||
ASMHelper.copy(source, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
void staticTransform(MethodNode method, MethodNode base) {
|
||||
StackAnalyser stack = new StackAnalyser(Type.getType(Type.getObjectType(input.name).getDescriptor()), base);
|
||||
InsnList instructions = method.instructions;
|
||||
AbstractInsnNode instruction = instructions.getFirst();
|
||||
while (instruction != null) {
|
||||
if (instruction instanceof FieldInsnNode) {
|
||||
FieldInsnNode field = (FieldInsnNode) instruction;
|
||||
if (instruction.getOpcode() == GETFIELD) instruction = replace(
|
||||
instructions,
|
||||
instruction,
|
||||
new MethodInsnNode(
|
||||
INVOKEINTERFACE,
|
||||
input.name,
|
||||
fieldName(field.name),
|
||||
"()" + field.desc,
|
||||
true));
|
||||
else if (instruction.getOpcode() == PUTFIELD) instruction = replace(
|
||||
instructions,
|
||||
instruction,
|
||||
new MethodInsnNode(
|
||||
INVOKEINTERFACE,
|
||||
input.name,
|
||||
fieldName(field.name) + "_$eq",
|
||||
"(" + field.desc + ")V",
|
||||
true));
|
||||
} else if (instruction instanceof MethodInsnNode) {
|
||||
MethodInsnNode call = (MethodInsnNode) instruction;
|
||||
if (instruction.getOpcode() == INVOKESPECIAL) {
|
||||
if (ASMMixinCompiler$.MODULE$.getSuper(call, stack).isDefined())
|
||||
instruction = replace(instructions, instruction, superInstruction(call));
|
||||
} else if (instruction.getOpcode() == INVOKEVIRTUAL && Objects.equals(call.owner, input.name)) {
|
||||
if (methodSignatures.contains(call.name + call.desc)) instruction = replace(
|
||||
instructions,
|
||||
instruction,
|
||||
new MethodInsnNode(INVOKEINTERFACE, call.owner, call.name, call.desc, true));
|
||||
else {
|
||||
Type methodType = Type.getMethodType(call.desc);
|
||||
StackAnalyser.StackEntry receiver = stack.peek(
|
||||
StackAnalyser.width(
|
||||
JavaConversions.asScalaBuffer(
|
||||
java.util.Arrays.asList(methodType.getArgumentTypes()))));
|
||||
instructions.insert(
|
||||
receiver.insn(),
|
||||
new TypeInsnNode(CHECKCAST, Type.getObjectType(input.superName).getDescriptor()));
|
||||
call.owner = input.superName;
|
||||
}
|
||||
}
|
||||
}
|
||||
stack.visitInsn(instruction);
|
||||
instruction = instruction.getNext();
|
||||
}
|
||||
}
|
||||
|
||||
void convertMethod(MethodNode source) {
|
||||
if (Objects.equals(source.name, "<clinit>")) throw new IllegalArgumentException(
|
||||
"Static initialisers are not permitted " + input.name + " as a mixin trait");
|
||||
if (Objects.equals(source.name, "<init>")) {
|
||||
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);
|
||||
staticTransform(result, source);
|
||||
return;
|
||||
}
|
||||
if ((source.access & ACC_PRIVATE) == 0) {
|
||||
MethodNode exposed = (MethodNode) contract.visitMethod(
|
||||
ACC_PUBLIC | ACC_ABSTRACT,
|
||||
source.name,
|
||||
source.desc,
|
||||
null,
|
||||
(String[]) source.exceptions.toArray(new String[0]));
|
||||
methods.$plus$eq(exposed);
|
||||
}
|
||||
int access = (source.access & ACC_PRIVATE) == 0 ? ACC_PUBLIC : ACC_PRIVATE;
|
||||
staticTransform(staticClone(source, source.name, access), source);
|
||||
}
|
||||
|
||||
void removeSuperConstructor(MethodNode constructor) {
|
||||
InsnListSection expected = new InsnListSection();
|
||||
expected.add(new VarInsnNode(ALOAD, 0));
|
||||
expected.add(new MethodInsnNode(INVOKESPECIAL, input.superName, "<init>", "()V", false));
|
||||
InsnListSection actual = new InsnListSection(constructor.instructions);
|
||||
InsnListSection found = InsnComparator.matches(actual, expected, java.util.Collections.emptySet());
|
||||
if (found == null)
|
||||
throw new IllegalArgumentException("Invalid constructor insn sequence " + input.name + "\n" + actual);
|
||||
found.trim(java.util.Collections.emptySet()).remove();
|
||||
}
|
||||
|
||||
boolean isGeneratedFieldAccessor(MethodNode method) {
|
||||
for (FieldMixin field : iterable(fields.values())) {
|
||||
String name = field.accessName(input.name);
|
||||
if (Objects.equals(method.name, name) && Objects.equals(method.desc, "()" + field.desc())
|
||||
|| Objects.equals(method.name, name + "_$eq")
|
||||
&& Objects.equals(method.desc, "(" + field.desc() + ")V"))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static AbstractInsnNode replace(InsnList instructions, AbstractInsnNode old, AbstractInsnNode replacement) {
|
||||
instructions.insert(old, replacement);
|
||||
instructions.remove(old);
|
||||
return replacement;
|
||||
}
|
||||
|
||||
private static <A> java.lang.Iterable<A> iterable(scala.collection.Iterable<A> values) {
|
||||
return JavaConversions.asJavaIterable(values);
|
||||
}
|
||||
|
||||
private static <A, B> Function1<A, B> fn(Function<A, B> function) {
|
||||
return new AbstractFunction1<A, B>() {
|
||||
|
||||
@Override
|
||||
public B apply(A value) {
|
||||
return function.apply(value);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user