From e21f25c2154daec21d08352d90191e2ad9821af5 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Tue, 10 Nov 2026 15:51:59 -0500 Subject: [PATCH 01/21] Remove unnecessary checkcasts --- javatools/src/main/java/org/xvm/javajit/BuildContext.java | 6 +++--- javatools/src/main/java/org/xvm/javajit/Builder.java | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/BuildContext.java b/javatools/src/main/java/org/xvm/javajit/BuildContext.java index 34fd0ac2e8..443e5956eb 100644 --- a/javatools/src/main/java/org/xvm/javajit/BuildContext.java +++ b/javatools/src/main/java/org/xvm/javajit/BuildContext.java @@ -783,9 +783,9 @@ public void enterMethod(CodeBuilder code) { } else if (!thisType.isJitPrimitive()) { RegisterInfo regThis = new SingleSlot(Op.A_THIS, 0, Specific, thisType, CD_this, "thi$"); - // an augmented interface (e.g. Service) can declare the method while every runtime - // instance is represented by the corresponding native class (nService) - if (thisType.isInterfaceType()) { + // interface bodies may need a native-class view of this (e.g. Service -> nService); + // native Ref/Var bodies already use their concrete receiver type + if (thisType.isInterfaceType() && !thisType.isNativeRef()) { ClassDesc cdValue = builder.getCCDesc(thisType); if (!cdValue.equals(CD_this)) { regThis = new Narrowed(Op.A_THIS, regThis.slots(), thisType, Specific, cdValue, diff --git a/javatools/src/main/java/org/xvm/javajit/Builder.java b/javatools/src/main/java/org/xvm/javajit/Builder.java index 34def63b2d..0f103490f2 100644 --- a/javatools/src/main/java/org/xvm/javajit/Builder.java +++ b/javatools/src/main/java/org/xvm/javajit/Builder.java @@ -2443,6 +2443,11 @@ public void convertCallArgument(CodeBuilder code, JitMethodDesc jmd, int argInde // - Widened -> NullablePrimitive (Int?|String n narrowed to Int?; f(n) with f(Int?)) switch (srcFlavor.name() + "->" + dstFlavor.name()) { case "Specific->SpecificWithDefault": + if (!srcReg.cd().equals(pd.cd) && !srcReg.type().isJitAssignableTo(pd.type)) { + generateCheckCast(code, pd.type, ctxSlot); + } + return; + case "Widened->Specific", "Widened->SpecificWithDefault": if (!srcReg.cd().equals(pd.cd)) { From a275ed72b9881530034d500e74ae13ed2260bf29 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Tue, 10 Nov 2026 17:30:41 -0500 Subject: [PATCH 02/21] Add the actual class name to the dump (jasm) --- .../xvm/asm/constants/PropertyClassTypeConstant.java | 2 +- .../src/main/java/org/xvm/javajit/ModuleLoader.java | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java b/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java index 26b90f1411..c26155b2b9 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java @@ -483,7 +483,7 @@ protected int compareDetails(Constant obj) { @Override public String getValueString() { - return m_typeParent.getValueString() + '.' + m_idProp.getName(); + return getRefType().getValueString(); } // ----- XvmStructure methods ------------------------------------------------------------------ diff --git a/javatools/src/main/java/org/xvm/javajit/ModuleLoader.java b/javatools/src/main/java/org/xvm/javajit/ModuleLoader.java index deae918850..b28eb97cd3 100644 --- a/javatools/src/main/java/org/xvm/javajit/ModuleLoader.java +++ b/javatools/src/main/java/org/xvm/javajit/ModuleLoader.java @@ -21,6 +21,8 @@ import org.xvm.asm.Constant; import org.xvm.asm.ModuleStructure; +import static org.xvm.javajit.TypeSystem.getJitSuffix; + import static org.xvm.util.Handy.isHexit; import static org.xvm.util.Handy.require; @@ -159,8 +161,13 @@ public void dump(File dir, Predicate filter) { File file = new File(dir, fileName + ".jasm"); try (PrintStream out = new PrintStream(new FileOutputStream(file))) { - out.println("\n**** " + (isInterface ? "interface " : "class ") + - className.replace('/', '.')); + out.print("\n**** " + (isInterface ? "interface " : "class ") + fileName); + + int typeId = getJitSuffix(className); + if (typeId >= 0) { + out.print(" (" + typeSystem.pool().getConstant(typeId).getValueString() + ')'); + } + out.println(); model.superclass().ifPresent(ce -> out.println("Extends: " + ce.asInternalName().replace('/', '.'))); From 5477a94216264e76f56d7d6575973531d23dc80b Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 14:35:25 -0500 Subject: [PATCH 03/21] Fix FPNumberTests --- .../xvm/javajit/builders/NumberBuilder.java | 24 ++++++++++----- .../x/jit/jit_tests/numbers/FPNumberTests.x | 29 +++++++------------ 2 files changed, 26 insertions(+), 27 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java index 684b25ed17..dafc809cdd 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java @@ -94,14 +94,22 @@ protected void assembleProperties(ClassBuilder classBuilder) { if (prop.isFormalType()) { continue; } - PropertyInfo declaredProp = prop; - prop = typeInfo.findProperty(prop.getName()); - assert prop != null; - - String jitName = prop.ensureJitName(typeSystem); - BiConsumer generator = getPropertyCodeGenerator(jitName); - if (generator != null && generatedProperties.add(jitName)) { - assemblePrimitivePropertyAccessor(classBuilder, prop, declaredProp, generator); + PropertyInfo actualProp = typeInfo.findProperty(prop.getName()); + assert actualProp != null; + + String jitName = actualProp.ensureJitName(typeSystem); + var generator = getPropertyCodeGenerator(jitName); + + if (generator == null) { + JitMethodDesc jmd = actualProp.getGetterJitDesc(this, thisType); + if (!jmd.standardMD.equals(prop.getGetterJitDesc(this).standardMD)) { + // naturally compiled covariant getters still need the base signature; + // e.g. Dec32.emax returns Int, while FPNumber.emax returns IntNumber + generatePrimitiveGetterWrapper(classBuilder, prop, + actualProp.ensureGetterJitMethodName(typeSystem), jmd); + } + } else if (generatedProperties.add(jitName)) { + assemblePrimitivePropertyAccessor(classBuilder, actualProp, prop, generator); } } } diff --git a/manualTests/src/main/x/jit/jit_tests/numbers/FPNumberTests.x b/manualTests/src/main/x/jit/jit_tests/numbers/FPNumberTests.x index c1ef197a15..6ae1f7392b 100644 --- a/manualTests/src/main/x/jit/jit_tests/numbers/FPNumberTests.x +++ b/manualTests/src/main/x/jit/jit_tests/numbers/FPNumberTests.x @@ -200,19 +200,16 @@ class FPNumberTests { } void testEMaxFPNumber(FPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.emax.toInt() == expected; + assert n.emax.toInt() == expected; } void testEMaxBinaryFPNumber(BinaryFPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.emax.toInt() == expected; + assert n.emax.toInt() == expected; testEMaxFPNumber(n, expected); } void testEMaxDecimalFPNumber(DecimalFPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.emax.toInt() == expected; + assert n.emax.toInt() == expected; testEMaxFPNumber(n, expected); } @@ -222,7 +219,7 @@ class FPNumberTests { assert Dec64.one().emin == -383; testEMinDecimalFPNumber(Dec64.one(), -383); assert Dec128.one().emin == -6143; - testEMinDecimalFPNumber(Dec128.one(), -6144); + testEMinDecimalFPNumber(Dec128.one(), -6143); assert Float16.one().emin == -14; testEMinBinaryFPNumber(Float16.one(), -14); @@ -233,19 +230,16 @@ class FPNumberTests { } void testEMinFPNumber(FPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.emin.toInt() == expected; + assert n.emin.toInt() == expected; } void testEMinBinaryFPNumber(BinaryFPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.emin.toInt() == expected; + assert n.emin.toInt() == expected; testEMinFPNumber(n, expected); } void testEMinDecimalFPNumber(DecimalFPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.emin.toInt() == expected; + assert n.emin.toInt() == expected; testEMinFPNumber(n, expected); } @@ -266,19 +260,16 @@ class FPNumberTests { } void testBiasFPNumber(FPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.bias.toInt() == expected; + assert n.bias.toInt() == expected; } void testBiasBinaryFPNumber(BinaryFPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.bias.toInt() == expected; + assert n.bias.toInt() == expected; testBiasFPNumber(n, expected); } void testBiasDecimalFPNumber(DecimalFPNumber n, Int expected) { -// TODO Fails due to missing "capped" property accessor -// assert n.bias.toInt() == expected; + assert n.bias.toInt() == expected; testBiasFPNumber(n, expected); } From df1d107150c7b79fd137700e8346019061925950 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 14:56:15 -0500 Subject: [PATCH 04/21] Remove invalid assertion --- .../java/org/xvm/asm/constants/TypeConstant.java | 16 ++++++---------- .../src/main/x/jit/jit_tests/basic/callTests.x | 2 -- .../src/main/x/jit/jit_tests/basic/equalTests.x | 8 ++++++++ 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java b/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java index fa2a018b02..ddee7445f3 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java @@ -3621,7 +3621,7 @@ private boolean computeIncomplete(Composition composition, TypeConstant typeCont // if we're building Object or some interface that Object depends on, then we ignore // chicken-and-egg problems because the Object interface should still be able to be // successfully and correctly built; specifically, Object depends on Comparable, - // but in reality, Comparable "is a" Object, so we need to solve the chicken-and-egg + // but in reality, Comparable "isA" Object, so we need to solve the chicken-and-egg // problem by allowing the creation of Object to proceed return false; } @@ -7712,9 +7712,6 @@ public void buildCompare(BuildContext bctx, CodeBuilder code, int nOp, */ public void buildCompare(BuildContext bctx, CodeBuilder code, int nOp, RegisterInfo reg1, Loader argLoader, Label lblTrue) { - TypeConstant type1 = reg1.type(); - assert type1.isA(this.removeImmutable()) || this.containsFormalType(false); - boolean fLocalTrue = lblTrue == null; if (fLocalTrue) { lblTrue = code.newLabel(); @@ -7871,9 +7868,9 @@ public void buildCompare(BuildContext bctx, CodeBuilder code, int nOp, } } else { // type is a non-primitive - TypeSystem ts = bctx.typeSystem; - ConstantPool pool = ts.pool(); - SignatureConstant sig = switch (nOp) { + TypeSystem ts = bctx.typeSystem; + ConstantPool pool = ts.pool(); + SignatureConstant sig = switch (nOp) { case Op.OP_IS_EQ, Op.OP_JMP_EQ, Op.OP_IS_NEQ, Op.OP_JMP_NEQ -> pool.sigEquals(); case Op.OP_IS_GT, Op.OP_JMP_GT, @@ -7884,9 +7881,8 @@ public void buildCompare(BuildContext bctx, CodeBuilder code, int nOp, default -> throw new IllegalStateException(); }; - TypeConstant typeFormal = isFormalType() - ? this - : type1.isFormalType() ? type1 : null; + TypeConstant type1 = reg1.type(); + TypeConstant typeFormal = isFormalType() ? this : type1.isFormalType() ? type1 : null; boolean isFormal = typeFormal != null; ClassDesc cd; String sJitName; diff --git a/manualTests/src/main/x/jit/jit_tests/basic/callTests.x b/manualTests/src/main/x/jit/jit_tests/basic/callTests.x index c08d683a19..17201e3882 100644 --- a/manualTests/src/main/x/jit/jit_tests/basic/callTests.x +++ b/manualTests/src/main/x/jit/jit_tests/basic/callTests.x @@ -426,8 +426,6 @@ package callTests { assert !source.find(False); assert Object found := source.find(True); assert found.as(String) == "value"; - // TODO GG: equality through Object fails for the returned String under JIT - // assert found == "value"; } interface Source { diff --git a/manualTests/src/main/x/jit/jit_tests/basic/equalTests.x b/manualTests/src/main/x/jit/jit_tests/basic/equalTests.x index 514ebf3013..1d539dc391 100644 --- a/manualTests/src/main/x/jit/jit_tests/basic/equalTests.x +++ b/manualTests/src/main/x/jit/jit_tests/basic/equalTests.x @@ -2,6 +2,7 @@ package equalTests { void run() { testEqualityRouting(); + testObjectEquality(); } void testEqualityRouting() { @@ -30,4 +31,11 @@ package equalTests { class Derived(String text) extends Simple(text); } + void testObjectEquality() { + Object value = "value"; + assert value == "value"; + assert asObject(value) == asObject(value); + + Object asObject(Object o) = o; + } } From 8660a7f8a150ea48b4a34104ca3026d8e0997604 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 15:14:56 -0500 Subject: [PATCH 05/21] Fix JIT method dispatch through Enum --- javatools/src/main/java/org/xvm/javajit/Builder.java | 8 ++------ .../main/java/org/xvm/javajit/NativeTypeSystem.java | 1 - .../src/main/java/org/xtclang/ecstasy/Enum.java | 7 +++++++ .../src/main/java/org/xtclang/ecstasy/nEnum.java | 2 +- .../src/main/x/jit/jit_tests/enums/BooleanTests.x | 12 +++++------- 5 files changed, 15 insertions(+), 15 deletions(-) create mode 100644 javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Enum.java diff --git a/javatools/src/main/java/org/xvm/javajit/Builder.java b/javatools/src/main/java/org/xvm/javajit/Builder.java index 0f103490f2..ce4892a75c 100644 --- a/javatools/src/main/java/org/xvm/javajit/Builder.java +++ b/javatools/src/main/java/org/xvm/javajit/Builder.java @@ -1337,7 +1337,6 @@ public PropertyInfo loadProperty(CodeBuilder code, TypeConstant typeContainer, TypeConstant typeOwner = typeJit; JitMethodDesc jmdGet = jitInfo.getGetterJitDesc(this, typeContainer); - boolean isNative = jitInfo.isNative(); boolean invokeStatic = jmdGet.isOptimizedStatic && allowUnboxing; if (!invokeStatic) { @@ -1363,14 +1362,11 @@ public PropertyInfo loadProperty(CodeBuilder code, TypeConstant typeContainer, md = jmdGet.standardMD; } - // Note: - // 1) an optimized static getter is used only when the caller allows unboxing; - // 2) native accessors are hosted by their Java bridge class even when the Ecstasy owner - // otherwise maps to a JIT interface + // an optimized static getter is used only when the caller allows unboxing code.aload(ctxSlot); if (invokeStatic) { code.invokestatic(ownerCD, getterName, md); - } else if (!isNative && typeOwner.isJitCCInterface()) { + } else if (typeOwner.isJitCCInterface()) { code.invokeinterface(ownerCD, getterName, md); } else { code.invokevirtual(ownerCD, getterName, md); diff --git a/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java b/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java index 0f6165ec35..c2128d97d7 100644 --- a/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java +++ b/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java @@ -319,7 +319,6 @@ void registerNativeClasses() { ConstantPool pool = pool(); // only rebased types need to be registered - nativeByClass.put(pool.clzEnum(), Builder.N_nEnum); nativeByClass.put(pool.clzEnumValue(), Builder.N_nEnum); nativeByClass.put(pool.clzModule(), Builder.N_nModule); nativeByClass.put(pool.clzObject(), Builder.N_Object); diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Enum.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Enum.java new file mode 100644 index 0000000000..9bbab47529 --- /dev/null +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Enum.java @@ -0,0 +1,7 @@ +package org.xtclang.ecstasy; + +/** + * Native interface for {@code ecstasy.Enum}; its methods are added by JIT augmentation. + */ +public interface Enum extends Object { +} diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nEnum.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nEnum.java index 1b44581808..a932c50de8 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nEnum.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nEnum.java @@ -13,7 +13,7 @@ */ public abstract class nEnum extends nConst - implements Object { + implements Enum { public nEnum(Ctx ctx) { super(ctx); } diff --git a/manualTests/src/main/x/jit/jit_tests/enums/BooleanTests.x b/manualTests/src/main/x/jit/jit_tests/enums/BooleanTests.x index c71246897d..1cdc87c680 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/BooleanTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/BooleanTests.x @@ -64,19 +64,17 @@ class BooleanTests { Sequential s = nextAsSequential(False); assert s == True; -// TODO see nextAsEnum below -// Enum e = nextAsEnum(False); -// assert e == True; + Enum e = nextAsEnum(False); + assert e == True; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// conditional Enum nextAsEnum(Enum e) { -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = False.prev(); From 2444c965d01043ada206c0396f89fed7fff3a402 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 15:29:29 -0500 Subject: [PATCH 06/21] Fix equality comparisons through Enum --- .../main/java/org/xtclang/ecstasy/Const.java | 12 +++ .../main/java/org/xtclang/ecstasy/nType.java | 5 ++ .../x/jit/jit_tests/enums/MutabilityTests.x | 86 +++++++++---------- 3 files changed, 56 insertions(+), 47 deletions(-) diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java index 501bcd12e0..283cb9f44c 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java @@ -1,7 +1,19 @@ package org.xtclang.ecstasy; +import org.xvm.javajit.Ctx; + /** * Native representation of `ecstasy.Const`. */ public interface Const extends Object { + /** + * Native implementation of: "static Boolean equals(CompileType + * value1, CompileType value2)". + */ + static boolean equals$p(Ctx ctx, nType CompileType, Const value1, Const value2) { + if (CompileType.$dataType.equals(ctx.pool().typeConst())) { + throw Exception.$unsupported(ctx, "Const.equals() requires a concrete comparison type"); + } + return CompileType.equals$p(ctx, value1, value2); + } } diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nType.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nType.java index 78c39fe06f..c0562fcf57 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nType.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/nType.java @@ -188,6 +188,11 @@ public String toString(Ctx ctx) { return true; } + if ($dataType.equals(ctx.pool().typeEnum())) { + // Enum inherits Const.equals(), whose native implementation uses ordinal equality + return nEnum.equals$p(ctx, this, (nEnum) value1, (nEnum) value2); + } + nType type1 = ((nObject) value1).$type(ctx); nType type2 = ((nObject) value2).$type(ctx); if ($dataType.isJitPrimitive()) { diff --git a/manualTests/src/main/x/jit/jit_tests/enums/MutabilityTests.x b/manualTests/src/main/x/jit/jit_tests/enums/MutabilityTests.x index 8e92a7193d..950a0e94bf 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/MutabilityTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/MutabilityTests.x @@ -60,25 +60,23 @@ class MutabilityTests { hasNext = nextAsSequential(Mutability.Mutable); assert hasNext == False; -// TODO see nextAsEnum below -// assert Enum e := nextAsEnum(Mutability.Constant); -// assert e == Mutability.Persistent; -// assert e := nextAsEnum(Mutability.Persistent); -// assert e == Mutability.Fixed; -// assert e := nextAsEnum(Mutability.Fixed); -// assert e == Mutability.Mutable; -// hasNext = nextAsEnum(Mutability.Mutable); -// assert hasNext == False; + assert Enum e := nextAsEnum(Mutability.Constant); + assert e == Mutability.Persistent; + assert e := nextAsEnum(Mutability.Persistent); + assert e == Mutability.Fixed; + assert e := nextAsEnum(Mutability.Fixed); + assert e == Mutability.Mutable; + hasNext = nextAsEnum(Mutability.Mutable); + assert hasNext == False; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum nextAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = Mutability.Constant.prev(); @@ -99,25 +97,23 @@ class MutabilityTests { assert s := prevAsSequential(Mutability.Mutable); assert s == Mutability.Fixed; -// TODO see prevAsEnum below -// hasPrev = prevAsEnum(Mutability.Constant); -// assert hasPrev == False; -// assert Enum e := prevAsEnum(Mutability.Persistent); -// assert e == Mutability.Constant; -// assert e := prevAsEnum(Mutability.Fixed); -// assert e == Mutability.Persistent; -// assert e := prevAsEnum(Mutability.Mutable); -// assert e == Mutability.Fixed; + hasPrev = prevAsEnum(Mutability.Constant); + assert hasPrev == False; + assert Enum e := prevAsEnum(Mutability.Persistent); + assert e == Mutability.Constant; + assert e := prevAsEnum(Mutability.Fixed); + assert e == Mutability.Persistent; + assert e := prevAsEnum(Mutability.Mutable); + assert e == Mutability.Fixed; } conditional Sequential prevAsSequential(Sequential s) { return s.prev(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum prevAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum prevAsEnum(Enum e) { + return e.prev(); + } void testSkip() { Mutability b = Mutability.Constant.skip(0); @@ -193,26 +189,24 @@ class MutabilityTests { // expected } -// TODO see skipAsEnum below -// Enum e = skipAsEnum(Mutability.Constant, 2); -// assert e == Mutability.Fixed; -// -// try { -// skipAsEnum(Mutability.Persistent, -3); -// assert as "should have thrown OOB"; -// } catch (OutOfBounds _) { -// // expected -// } + Enum e = skipAsEnum(Mutability.Constant, 2); + assert e == Mutability.Fixed; + + try { + skipAsEnum(Mutability.Persistent, -3); + assert as "should have thrown OOB"; + } catch (OutOfBounds _) { + // expected + } } Sequential skipAsSequential(Sequential s, Int steps) { return s.skip(steps); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Enum skipAsEnum(Enum e, Int steps) { -// return e.skip(steps); -// } + Enum skipAsEnum(Enum e, Int steps) { + return e.skip(steps); + } void testStepsTo() { Mutability c = Constant; @@ -243,19 +237,17 @@ class MutabilityTests { assert stepsToAsSequential(Mutability.Constant, Mutability.Fixed) == 2; assert stepsToAsSequential(Mutability.Fixed, Mutability.Persistent) == -1; -// TODO see stepsToAsEnum below -// assert stepsToAsEnum(Mutability.Constant, Mutability.Fixed) == 2; -// assert stepsToAsEnum(Mutability.Fixed, Mutability.Persistent) == -1; + assert stepsToAsEnum(Mutability.Constant, Mutability.Fixed) == 2; + assert stepsToAsEnum(Mutability.Fixed, Mutability.Persistent) == -1; } Int stepsToAsSequential(Sequential s1, Sequential s2) { return s1.stepsTo(s2); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Int stepsToAsEnum(Enum e1, Enum e2) { -// return e1.stepsTo(e2); -// } + Int stepsToAsEnum(Enum e1, Enum e2) { + return e1.stepsTo(e2); + } void testConstant() { assert Mutability.Constant.name == "Constant"; From 9cbffccf89369acac84099eab313a6dfe88b08d8 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 15:43:14 -0500 Subject: [PATCH 07/21] Remove already fixed TODOs --- .../main/x/jit/jit_tests/enums/ColorTests.x | 78 +++++++-------- .../x/jit/jit_tests/enums/NullableTests.x | 60 +++++------- .../main/x/jit/jit_tests/enums/OrderedTests.x | 78 +++++++-------- .../x/jit/jit_tests/enums/RoundingTests.x | 94 +++++++++---------- .../main/x/jit/jit_tests/enums/SignumTests.x | 78 +++++++-------- .../main/x/jit/jit_tests/temporal/DateTests.x | 11 +-- 6 files changed, 178 insertions(+), 221 deletions(-) diff --git a/manualTests/src/main/x/jit/jit_tests/enums/ColorTests.x b/manualTests/src/main/x/jit/jit_tests/enums/ColorTests.x index 9e1cd1edfb..930d81c4a3 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/ColorTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/ColorTests.x @@ -57,23 +57,21 @@ class ColorTests { hasNext = nextAsSequential(Color.Blue); assert hasNext == False; -// TODO see nextAsEnum below -// assert Enum e := nextAsEnum(Color.Red); -// assert e == Color.Green; -// assert e := nextAsEnum(Color.Green); -// assert e == Color.Blue; -// hasNext = nextAsEnum(Color.Blue); -// assert hasNext == False; + assert Enum e := nextAsEnum(Color.Red); + assert e == Color.Green; + assert e := nextAsEnum(Color.Green); + assert e == Color.Blue; + hasNext = nextAsEnum(Color.Blue); + assert hasNext == False; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum nextAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = Color.Red.prev(); @@ -90,23 +88,21 @@ class ColorTests { assert s := prevAsSequential(Color.Blue); assert s == Color.Green; -// TODO see prevAsEnum below -// hasPrev = prevAsEnum(Color.Red); -// assert hasPrev == False; -// assert Enum e := prevAsEnum(Color.Green); -// assert e == Color.Red; -// assert e := prevAsEnum(Color.Blue); -// assert e == Color.Green; + hasPrev = prevAsEnum(Color.Red); + assert hasPrev == False; + assert Enum e := prevAsEnum(Color.Green); + assert e == Color.Red; + assert e := prevAsEnum(Color.Blue); + assert e == Color.Green; } conditional Sequential prevAsSequential(Sequential s) { return s.prev(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum prevAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum prevAsEnum(Enum e) { + return e.prev(); + } void testSkip() { Color b = Color.Red.skip(0); @@ -182,26 +178,24 @@ class ColorTests { // expected } -// TODO see skipAsEnum below -// Enum e = skipAsEnum(Color.Red, 2); -// assert e == Color.Blue; -// -// try { -// skipAsEnum(Color.Green, -3); -// assert as "should have thrown OOB"; -// } catch (OutOfBounds _) { -// // expected -// } + Enum e = skipAsEnum(Color.Red, 2); + assert e == Color.Blue; + + try { + skipAsEnum(Color.Green, -3); + assert as "should have thrown OOB"; + } catch (OutOfBounds _) { + // expected + } } Sequential skipAsSequential(Sequential s, Int steps) { return s.skip(steps); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Enum skipAsEnum(Enum e, Int steps) { -// return e.skip(steps); -// } + Enum skipAsEnum(Enum e, Int steps) { + return e.skip(steps); + } void testStepsTo() { Color r = Red; @@ -223,19 +217,17 @@ class ColorTests { assert stepsToAsSequential(Color.Red, Color.Blue) == 2; assert stepsToAsSequential(Color.Blue, Color.Green) == -1; -// TODO see stepsToAsEnum below -// assert stepsToAsEnum(Color.Red, Color.Blue) == 2; -// assert stepsToAsEnum(Color.Blue, Color.Green) == -1; + assert stepsToAsEnum(Color.Red, Color.Blue) == 2; + assert stepsToAsEnum(Color.Blue, Color.Green) == -1; } Int stepsToAsSequential(Sequential s1, Sequential s2) { return s1.stepsTo(s2); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Int stepsToAsEnum(Enum e1, Enum e2) { -// return e1.stepsTo(e2); -// } + Int stepsToAsEnum(Enum e1, Enum e2) { + return e1.stepsTo(e2); + } void testOrder() { assert Color.Red <=> Color.Red == Equal; // compile time computation diff --git a/manualTests/src/main/x/jit/jit_tests/enums/NullableTests.x b/manualTests/src/main/x/jit/jit_tests/enums/NullableTests.x index de6e8e702b..36227e4e0e 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/NullableTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/NullableTests.x @@ -36,19 +36,17 @@ class NullableTests { hasNext = nextAsSequential(Nullable.Null); assert hasNext == False; -// TODO see nextAsEnum below -// hasNext = nextAsEnum(Nullable.Null); -// assert hasNext == False; + hasNext = nextAsEnum(Nullable.Null); + assert hasNext == False; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum nextAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = Nullable.Null.prev(); @@ -57,19 +55,17 @@ class NullableTests { hasPrev = prevAsSequential(Nullable.Null); assert hasPrev == False; -// TODO see prevAsEnum below -// hasPrev = prevAsEnum(Nullable.Null); -// assert hasPrev == False; + hasPrev = prevAsEnum(Nullable.Null); + assert hasPrev == False; } conditional Sequential prevAsSequential(Sequential s) { return s.prev(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum prevAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum prevAsEnum(Enum e) { + return e.next(); + } void testSkip() { Nullable b = Nullable.Null.skip(0); @@ -99,44 +95,40 @@ class NullableTests { // expected } -// TODO see skipAsEnum below -// Enum e = skipAsEnum(Nullable.Null, 0); -// assert e == Nullable.Null; -// -// try { -// skipAsEnum(Nullable.Null, -3); -// assert as "should have thrown OOB"; -// } catch (OutOfBounds _) { -// // expected -// } + Enum e = skipAsEnum(Nullable.Null, 0); + assert e == Nullable.Null; + + try { + skipAsEnum(Nullable.Null, -3); + assert as "should have thrown OOB"; + } catch (OutOfBounds _) { + // expected + } } Sequential skipAsSequential(Sequential s, Int steps) { return s.skip(steps); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Enum skipAsEnum(Enum e, Int steps) { -// return e.skip(steps); -// } + Enum skipAsEnum(Enum e, Int steps) { + return e.skip(steps); + } void testStepsTo() { assert Nullable.Null.stepsTo(Null) == 0; assert stepsToAsSequential(Nullable.Null, Nullable.Null) == 0; assert stepsToAsSequential(Nullable.Null, Nullable.Null) == 0; -// TODO see stepsToAsEnum below -// assert stepsToAsEnum(Nullable.Null, Nullable.Null) == 0; + assert stepsToAsEnum(Nullable.Null, Nullable.Null) == 0; } Int stepsToAsSequential(Sequential s1, Sequential s2) { return s1.stepsTo(s2); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Int stepsToAsEnum(Enum e1, Enum e2) { -// return e1.stepsTo(e2); -// } + Int stepsToAsEnum(Enum e1, Enum e2) { + return e1.stepsTo(e2); + } void testNull() { assert Nullable.Null.name == "Null"; diff --git a/manualTests/src/main/x/jit/jit_tests/enums/OrderedTests.x b/manualTests/src/main/x/jit/jit_tests/enums/OrderedTests.x index 595452a09c..8a197a5df4 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/OrderedTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/OrderedTests.x @@ -51,23 +51,21 @@ class OrderedTests { hasNext = nextAsSequential(Ordered.Greater); assert hasNext == False; -// TODO see nextAsEnum below -// assert Enum e := nextAsEnum(Ordered.Lesser); -// assert e == Ordered.Equal; -// assert e := nextAsEnum(Ordered.Equal); -// assert e == Ordered.Greater; -// hasNext = nextAsEnum(Ordered.Greater); -// assert hasNext == False; + assert Enum e := nextAsEnum(Ordered.Lesser); + assert e == Ordered.Equal; + assert e := nextAsEnum(Ordered.Equal); + assert e == Ordered.Greater; + hasNext = nextAsEnum(Ordered.Greater); + assert hasNext == False; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum nextAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = Ordered.Lesser.prev(); @@ -84,23 +82,21 @@ class OrderedTests { assert s := prevAsSequential(Ordered.Greater); assert s == Ordered.Equal; -// TODO see prevAsEnum below -// hasPrev = prevAsEnum(Ordered.Lesser); -// assert hasPrev == False; -// assert Enum e := prevAsEnum(Ordered.Equal); -// assert e == Ordered.Lesser; -// assert e := prevAsEnum(Ordered.Greater); -// assert e == Ordered.Equal; + hasPrev = prevAsEnum(Ordered.Lesser); + assert hasPrev == False; + assert Enum e := prevAsEnum(Ordered.Equal); + assert e == Ordered.Lesser; + assert e := prevAsEnum(Ordered.Greater); + assert e == Ordered.Equal; } conditional Sequential prevAsSequential(Sequential s) { return s.prev(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum prevAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum prevAsEnum(Enum e) { + return e.prev(); + } void testSkip() { Ordered b = Ordered.Lesser.skip(0); @@ -176,26 +172,24 @@ class OrderedTests { // expected } -// TODO see skipAsEnum below -// Enum e = skipAsEnum(Ordered.Lesser, 2); -// assert e == Ordered.Greater; -// -// try { -// skipAsEnum(Ordered.Equal, -3); -// assert as "should have thrown OOB"; -// } catch (OutOfBounds _) { -// // expected -// } + Enum e = skipAsEnum(Ordered.Lesser, 2); + assert e == Ordered.Greater; + + try { + skipAsEnum(Ordered.Equal, -3); + assert as "should have thrown OOB"; + } catch (OutOfBounds _) { + // expected + } } Sequential skipAsSequential(Sequential s, Int steps) { return s.skip(steps); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Enum skipAsEnum(Enum e, Int steps) { -// return e.skip(steps); -// } + Enum skipAsEnum(Enum e, Int steps) { + return e.skip(steps); + } void testStepsTo() { Ordered l = Lesser; @@ -217,19 +211,17 @@ class OrderedTests { assert stepsToAsSequential(Ordered.Lesser, Ordered.Greater) == 2; assert stepsToAsSequential(Ordered.Greater, Ordered.Equal) == -1; -// TODO see stepsToAsEnum below -// assert stepsToAsEnum(Ordered.Lesser, Ordered.Greater) == 2; -// assert stepsToAsEnum(Ordered.Greater, Ordered.Equal) == -1; + assert stepsToAsEnum(Ordered.Lesser, Ordered.Greater) == 2; + assert stepsToAsEnum(Ordered.Greater, Ordered.Equal) == -1; } Int stepsToAsSequential(Sequential s1, Sequential s2) { return s1.stepsTo(s2); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Int stepsToAsEnum(Enum e1, Enum e2) { -// return e1.stepsTo(e2); -// } + Int stepsToAsEnum(Enum e1, Enum e2) { + return e1.stepsTo(e2); + } void testLesser() { assert Ordered.Lesser.name == "Lesser"; diff --git a/manualTests/src/main/x/jit/jit_tests/enums/RoundingTests.x b/manualTests/src/main/x/jit/jit_tests/enums/RoundingTests.x index dd3f77c1ee..7dbd712b81 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/RoundingTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/RoundingTests.x @@ -67,27 +67,25 @@ class RoundingTests { hasNext = nextAsSequential(Rounding.TowardNegative); assert hasNext == False; -// TODO see nextAsEnum below -// assert Enum e := nextAsEnum(Rounding.TiesToEven); -// assert e == Rounding.TiesToAway; -// assert e := nextAsEnum(Rounding.TiesToAway); -// assert e == Rounding.TowardPositive; -// assert e := nextAsEnum(Rounding.TowardPositive); -// assert e == Rounding.TowardZero; -// assert e := nextAsEnum(Rounding.TowardZero); -// assert e == Rounding.TowardNegative; -// hasNext = nextAsEnum(Rounding.TowardNegative); -// assert hasNext == False; + assert Enum e := nextAsEnum(Rounding.TiesToEven); + assert e == Rounding.TiesToAway; + assert e := nextAsEnum(Rounding.TiesToAway); + assert e == Rounding.TowardPositive; + assert e := nextAsEnum(Rounding.TowardPositive); + assert e == Rounding.TowardZero; + assert e := nextAsEnum(Rounding.TowardZero); + assert e == Rounding.TowardNegative; + hasNext = nextAsEnum(Rounding.TowardNegative); + assert hasNext == False; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum nextAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = Rounding.TiesToEven.prev(); @@ -112,27 +110,25 @@ class RoundingTests { assert s := prevAsSequential(Rounding.TowardNegative); assert s == Rounding.TowardZero; -// TODO see prevAsEnum below -// hasPrev = prevAsEnum(Rounding.TiesToEven); -// assert hasPrev == False; -// assert Enum e := prevAsEnum(Rounding.TiesToAway); -// assert e == Rounding.TiesToEven; -// assert e := prevAsEnum(Rounding.TowardPositive); -// assert e == Rounding.TiesToAway; -// assert e := prevAsEnum(Rounding.TowardZero); -// assert e == Rounding.TowardPositive; -// assert e := prevAsEnum(Rounding.TowardNegative); -// assert e == Rounding.TowardZero; + hasPrev = prevAsEnum(Rounding.TiesToEven); + assert hasPrev == False; + assert Enum e := prevAsEnum(Rounding.TiesToAway); + assert e == Rounding.TiesToEven; + assert e := prevAsEnum(Rounding.TowardPositive); + assert e == Rounding.TiesToAway; + assert e := prevAsEnum(Rounding.TowardZero); + assert e == Rounding.TowardPositive; + assert e := prevAsEnum(Rounding.TowardNegative); + assert e == Rounding.TowardZero; } conditional Sequential prevAsSequential(Sequential s) { return s.prev(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum prevAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum prevAsEnum(Enum e) { + return e.prev(); + } void testSkip() { Rounding b = Rounding.TiesToEven.skip(0); @@ -242,26 +238,24 @@ class RoundingTests { // expected } -// TODO see skipAsEnum below -// Enum e = skipAsEnum(Rounding.TiesToEven, 2); -// assert e == Rounding.TowardPositive; -// -// try { -// skipAsEnum(Rounding.TiesToAway, -3); -// assert as "should have thrown OOB"; -// } catch (OutOfBounds _) { -// // expected -// } + Enum e = skipAsEnum(Rounding.TiesToEven, 2); + assert e == Rounding.TowardPositive; + + try { + skipAsEnum(Rounding.TiesToAway, -3); + assert as "should have thrown OOB"; + } catch (OutOfBounds _) { + // expected + } } Sequential skipAsSequential(Sequential s, Int steps) { return s.skip(steps); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Enum skipAsEnum(Enum e, Int steps) { -// return e.skip(steps); -// } + Enum skipAsEnum(Enum e, Int steps) { + return e.skip(steps); + } void testStepsTo() { Rounding e = TiesToEven; @@ -303,19 +297,17 @@ class RoundingTests { assert stepsToAsSequential(Rounding.TiesToEven, Rounding.TowardPositive) == 2; assert stepsToAsSequential(Rounding.TowardPositive, Rounding.TiesToAway) == -1; -// TODO see stepsToAsEnum below -// assert stepsToAsEnum(Rounding.TiesToEven, Rounding.TowardPositive) == 2; -// assert stepsToAsEnum(Rounding.TowardPositive, Rounding.TiesToAway) == -1; + assert stepsToAsEnum(Rounding.TiesToEven, Rounding.TowardPositive) == 2; + assert stepsToAsEnum(Rounding.TowardPositive, Rounding.TiesToAway) == -1; } Int stepsToAsSequential(Sequential s1, Sequential s2) { return s1.stepsTo(s2); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Int stepsToAsEnum(Enum e1, Enum e2) { -// return e1.stepsTo(e2); -// } + Int stepsToAsEnum(Enum e1, Enum e2) { + return e1.stepsTo(e2); + } void testTiesToEven() { assert Rounding.TiesToEven.name == "TiesToEven"; diff --git a/manualTests/src/main/x/jit/jit_tests/enums/SignumTests.x b/manualTests/src/main/x/jit/jit_tests/enums/SignumTests.x index e834572016..cf7c258486 100644 --- a/manualTests/src/main/x/jit/jit_tests/enums/SignumTests.x +++ b/manualTests/src/main/x/jit/jit_tests/enums/SignumTests.x @@ -51,23 +51,21 @@ class SignumTests { hasNext = nextAsSequential(Signum.Positive); assert hasNext == False; -// TODO see nextAsEnum below -// assert Enum e := nextAsEnum(Signum.Negative); -// assert e == Signum.Zero; -// assert e := nextAsEnum(Signum.Zero); -// assert e == Signum.Positive; -// hasNext = nextAsEnum(Signum.Positive); -// assert hasNext == False; + assert Enum e := nextAsEnum(Signum.Negative); + assert e == Signum.Zero; + assert e := nextAsEnum(Signum.Zero); + assert e == Signum.Positive; + hasNext = nextAsEnum(Signum.Positive); + assert hasNext == False; } conditional Sequential nextAsSequential(Sequential s) { return s.next(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum nextAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum nextAsEnum(Enum e) { + return e.next(); + } void testPrev() { Boolean hasPrev = Signum.Negative.prev(); @@ -84,23 +82,21 @@ class SignumTests { assert s := prevAsSequential(Signum.Positive); assert s == Signum.Zero; -// TODO see prevAsEnum below -// hasPrev = prevAsEnum(Signum.Negative); -// assert hasPrev == False; -// assert Enum e := prevAsEnum(Signum.Zero); -// assert e == Signum.Negative; -// assert e := prevAsEnum(Signum.Positive); -// assert e == Signum.Zero; + hasPrev = prevAsEnum(Signum.Negative); + assert hasPrev == False; + assert Enum e := prevAsEnum(Signum.Zero); + assert e == Signum.Negative; + assert e := prevAsEnum(Signum.Positive); + assert e == Signum.Zero; } conditional Sequential prevAsSequential(Sequential s) { return s.prev(); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// conditional Enum prevAsEnum(Enum e) { -// return e.next(); -// } + conditional Enum prevAsEnum(Enum e) { + return e.prev(); + } void testSkip() { Signum b = Signum.Negative.skip(0); @@ -176,26 +172,24 @@ class SignumTests { // expected } -// TODO see skipAsEnum below -// Enum e = skipAsEnum(Signum.Negative, 2); -// assert e == Signum.Positive; -// -// try { -// skipAsEnum(Signum.Zero, -3); -// assert as "should have thrown OOB"; -// } catch (OutOfBounds _) { -// // expected -// } + Enum e = skipAsEnum(Signum.Negative, 2); + assert e == Signum.Positive; + + try { + skipAsEnum(Signum.Zero, -3); + assert as "should have thrown OOB"; + } catch (OutOfBounds _) { + // expected + } } Sequential skipAsSequential(Sequential s, Int steps) { return s.skip(steps); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Enum skipAsEnum(Enum e, Int steps) { -// return e.skip(steps); -// } + Enum skipAsEnum(Enum e, Int steps) { + return e.skip(steps); + } void testStepsTo() { Signum n = Negative; @@ -217,19 +211,17 @@ class SignumTests { assert stepsToAsSequential(Signum.Negative, Signum.Positive) == 2; assert stepsToAsSequential(Signum.Positive, Signum.Zero) == -1; -// TODO see stepsToAsEnum below -// assert stepsToAsEnum(Signum.Negative, Signum.Positive) == 2; -// assert stepsToAsEnum(Signum.Positive, Signum.Zero) == -1; + assert stepsToAsEnum(Signum.Negative, Signum.Positive) == 2; + assert stepsToAsEnum(Signum.Positive, Signum.Zero) == -1; } Int stepsToAsSequential(Sequential s1, Sequential s2) { return s1.stepsTo(s2); } -// TODO requires calls to methods on nEnum to be invokevirtual instead of invokeinterface -// Int stepsToAsEnum(Enum e1, Enum e2) { -// return e1.stepsTo(e2); -// } + Int stepsToAsEnum(Enum e1, Enum e2) { + return e1.stepsTo(e2); + } void testNegative() { assert Signum.Negative.name == "Negative"; diff --git a/manualTests/src/main/x/jit/jit_tests/temporal/DateTests.x b/manualTests/src/main/x/jit/jit_tests/temporal/DateTests.x index f7201cc352..2d050c923a 100644 --- a/manualTests/src/main/x/jit/jit_tests/temporal/DateTests.x +++ b/manualTests/src/main/x/jit/jit_tests/temporal/DateTests.x @@ -29,12 +29,10 @@ class DateTests { } void testCreateDateFromString() { -// TODO fails calling String.split$p(): missing Array.freeze$p(Ctx, boolean, boolean) -// Also review the original slash-separated input: Date(String) expects ISO-8601 -// Date d = new Date("1976/6/20"); -// assert d.year == 1976; -// assert d.month == 6; -// assert d.day == 20; + Date d = new Date("1976-6-20"); + assert d.year == 1976; + assert d.month == 6; + assert d.day == 20; } void testLeapYear() { @@ -182,5 +180,4 @@ class DateTests { assert supplied[1] == date; assert supplied[2] == date; } - } From af39144ae220a3f389bcf7849c4fe8be4362e12f Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 15:59:08 -0500 Subject: [PATCH 08/21] Fix Javadoc --- .../src/main/java/org/xtclang/ecstasy/Const.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java index 283cb9f44c..485f6f1840 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/Const.java @@ -7,8 +7,9 @@ */ public interface Const extends Object { /** - * Native implementation of: "static Boolean equals(CompileType - * value1, CompileType value2)". + * Native implementation of: + * + * {@code static Boolean equals(CompileType value1, CompileType value2)}. */ static boolean equals$p(Ctx ctx, nType CompileType, Const value1, Const value2) { if (CompileType.$dataType.equals(ctx.pool().typeConst())) { From c421b2407458f303a58abb9acb49f332ed60910b Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 16:03:05 -0500 Subject: [PATCH 09/21] Fix ClassConstant.getType() bug for inner classes --- .../org/xvm/asm/constants/ClassConstant.java | 12 +++-- .../x/jit/jit_tests/files/DirectoryTests.x | 53 +++++++++---------- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/javatools/src/main/java/org/xvm/asm/constants/ClassConstant.java b/javatools/src/main/java/org/xvm/asm/constants/ClassConstant.java index e39f6a8a56..3451b5cb37 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/ClassConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/ClassConstant.java @@ -300,13 +300,15 @@ public boolean isClass() { @Override public TypeConstant getType() { - ClassStructure clz = (ClassStructure) getComponent(); + ConstantPool pool = getConstantPool(); + ClassStructure clz = (ClassStructure) getComponent(); - return clz.isVirtualChild() ? getConstantPool().ensureVirtualChildTypeConstant( + // an inner class's outer is the containing class, not an intervening method or property + return clz.isVirtualChild() ? pool.ensureVirtualChildTypeConstant( getParentConstant().getType(), getName()) - : clz.isInnerChild() ? getConstantPool().ensureInnerChildTypeConstant( - getParentConstant().getType(), this) - : clz.isAnonInnerClass() ? getConstantPool().ensureAnonymousClassTypeConstant( + : clz.isInnerChild() ? pool.ensureInnerChildTypeConstant( + getParentConstant().getClassIdentity().getFormalType(), this) + : clz.isAnonInnerClass() ? pool.ensureAnonymousClassTypeConstant( getParentConstant().getType(), this) : super.getType(); } diff --git a/manualTests/src/main/x/jit/jit_tests/files/DirectoryTests.x b/manualTests/src/main/x/jit/jit_tests/files/DirectoryTests.x index 1a8010f942..9c2e52823e 100644 --- a/manualTests/src/main/x/jit/jit_tests/files/DirectoryTests.x +++ b/manualTests/src/main/x/jit/jit_tests/files/DirectoryTests.x @@ -173,33 +173,32 @@ class DirectoryTests { } void shouldListFilesRecursively() { -// TODO inner Iterator of Directory.filesRecursively() fails to compile -// @Inject Directory tmpDir; -// Directory dir = tmpDir.dirFor("foo"); -// assert !dir.exists; -// dir.ensure(); -// assert dir.exists; -// -// File subFile1 = dir.fileFor("file-1.txt").ensure(); -// assert subFile1.exists; -// File[] files = dir.filesRecursively().toArray(); -// assert files.size == 1; -// assert files[0].name == "file-1.txt"; -// -// Directory subDir = dir.dirFor("sub-dir-1").ensure(); -// assert subDir.exists; -// files = dir.filesRecursively().toArray(); -// assert files.size == 1; -// assert files[0].name == "file-1.txt"; -// -// File subFile2 = subDir.fileFor("file-2.txt").ensure(); -// assert subFile2.exists; -// files = dir.filesRecursively().toArray(); -// assert files.size == 2; -// assert (files[0].name == "file-1.txt" && files[1].name == "file-2.txt") -// || (files[0].name == "file-2.txt" && files[1].name == "file-1.txt"); -// -// cleanup([subFile1, subFile2, subDir, dir]); + @Inject Directory tmpDir; + Directory dir = tmpDir.dirFor("foo"); + assert !dir.exists; + dir.ensure(); + assert dir.exists; + + File subFile1 = dir.fileFor("file-1.txt").ensure(); + assert subFile1.exists; + File[] files = dir.filesRecursively().toArray(); + assert files.size == 1; + assert files[0].name == "file-1.txt"; + + Directory subDir = dir.dirFor("sub-dir-1").ensure(); + assert subDir.exists; + files = dir.filesRecursively().toArray(); + assert files.size == 1; + assert files[0].name == "file-1.txt"; + + File subFile2 = subDir.fileFor("file-2.txt").ensure(); + assert subFile2.exists; + files = dir.filesRecursively().toArray(); + assert files.size == 2; + assert (files[0].name == "file-1.txt" && files[1].name == "file-2.txt") + || (files[0].name == "file-2.txt" && files[1].name == "file-1.txt"); + + cleanup([subFile1, subFile2, subDir, dir]); } void shouldDeleteRecursively() { From 98a6b6172b7be788c1f391f09a656c466236f816 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 16:22:09 -0500 Subject: [PATCH 10/21] Change OSFileNode.$toOsPath() to return an absolute path --- .../org/xtclang/_native/fs/OSFileNode.java | 4 ++-- .../main/x/jit/jit_tests/files/FileNodeTests.x | 18 ++++++++---------- .../x/jit/jit_tests/files/FileStoreTests.x | 10 ++++++---- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java index c0acc734df..5e66ebc185 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java @@ -193,11 +193,11 @@ protected OSFileNode(Ctx ctx, OSFileStore store, java.nio.file.Path path) { } /** - * A utility method to convert a string path to a Java path. + * A utility method to convert a string path to an absolute Java path. */ public static java.nio.file.Path $toOsPath(Ctx ctx, String pathString) { try { - return xOSFileNode.toOsPath(pathString.toString()); + return xOSFileNode.toOsPath(pathString.toString()).toAbsolutePath(); } catch (InvalidPathException e) { throw $io(ctx, e.getMessage()); } diff --git a/manualTests/src/main/x/jit/jit_tests/files/FileNodeTests.x b/manualTests/src/main/x/jit/jit_tests/files/FileNodeTests.x index ce525bf518..56694f58cb 100644 --- a/manualTests/src/main/x/jit/jit_tests/files/FileNodeTests.x +++ b/manualTests/src/main/x/jit/jit_tests/files/FileNodeTests.x @@ -12,7 +12,7 @@ class FileNodeTests { void run() { shouldHaveStorage(); shouldHaveNullParentIfRoot(); - shouldHaveNullParentIfCurrentDir(); + shouldHaveParentIfCurrentDir(); shouldHaveParent(); shouldHavePath(); shouldHaveName(); @@ -36,7 +36,7 @@ class FileNodeTests { void shouldHaveStorage() { @Inject FileStore storage; assert FileNode node := storage.find(RootPath); -// assert node.store == storage; + assert node.store == storage; } void shouldHaveNullParentIfRoot() { @@ -45,14 +45,12 @@ class FileNodeTests { assert node.parent == Null; } - // TODO node.parent throws due to assertion in FileNode.x parent.get() as the - // current directory path has a Null parent path - // The same would happen for a FileNode created from the parent path ".." - void shouldHaveNullParentIfCurrentDir() { -// @Inject FileStore storage; -// assert FileNode node := storage.find(new Path(".")); -// console.print(node.parent); -// assert node.parent == Null; + void shouldHaveParentIfCurrentDir() { + @Inject FileStore storage; + assert FileNode node := storage.find(new Path(".")); + assert node.path.absolute; + assert Directory parent ?= node.parent; + assert parent.path == node.path.parent; } void shouldHaveParent() { diff --git a/manualTests/src/main/x/jit/jit_tests/files/FileStoreTests.x b/manualTests/src/main/x/jit/jit_tests/files/FileStoreTests.x index cdfbcc819f..2ef9e567bc 100644 --- a/manualTests/src/main/x/jit/jit_tests/files/FileStoreTests.x +++ b/manualTests/src/main/x/jit/jit_tests/files/FileStoreTests.x @@ -59,10 +59,12 @@ class FileStoreTests { void shouldGetRelativeDirForPath() { @Inject FileStore storage; - Path path = new Path("one/two"); - Directory dir = storage.dirFor(path); - assert dir.toString() == "one/two"; - assert dir.path == path; + @Inject Directory curDir; + Path path = new Path("one/two"); + Directory dir = storage.dirFor(path); + Path expected = new Path(curDir.path, "one/two"); + assert dir.toString() == expected.toString(); + assert dir.path == expected; } void shouldGetFileForPath() { From f6d3cc00881455449eb2ec4820492cfb1789d8ce Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 16:36:06 -0500 Subject: [PATCH 11/21] Add Int128 -> Dec conversion --- .../javajit/builders/IntNumberBuilder.java | 55 +++++++++++++++++-- .../x/jit/jit_tests/temporal/DurationTests.x | 9 ++- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/builders/IntNumberBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/IntNumberBuilder.java index 8b5f23b7b2..9a6a9d5940 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/IntNumberBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/IntNumberBuilder.java @@ -6,7 +6,9 @@ import java.lang.constant.ClassDesc; +import java.math.BigDecimal; import java.math.BigInteger; +import java.math.MathContext; import java.util.Collection; @@ -25,6 +27,8 @@ import static java.lang.constant.ConstantDescs.CD_Long; import static java.lang.constant.ConstantDescs.CD_int; import static java.lang.constant.ConstantDescs.CD_long; +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.INIT_NAME; /** * The builder for IntNumber types. @@ -56,13 +60,23 @@ protected BiConsumer getMethodCodeGenerator(String j return switch (jitName) { case "and", "or", "xor" -> (code, jmd) -> generateBinaryBitwise(code, jmd, jitName); - case "not" -> this::generateNot; + + case "not" -> + this::generateNot; + case "toByte", "toNibble", "toInt", "toInt8", "toInt16", "toInt32", "toInt64", "toInt128", "toUInt", "toUInt8", "toUInt16", "toUInt32", "toUInt64", "toUInt128" -> this::generateFixedConversion; - case "toIntN", "toUIntN" -> this::generateUnboundedConversion; - default -> super.getMethodCodeGenerator(jitName); + + case "toIntN", "toUIntN" -> + this::generateUnboundedConversion; + + case "toDec128" -> + this::generateToDec128; + + default -> + super.getMethodCodeGenerator(jitName); }; } @@ -389,6 +403,37 @@ protected void generateUnboundedConversion(CodeBuilder code, JitMethodDesc jmd) code.areturn(); } + /** + * Assemble an optimized static implementation of "toDec128$p()". + * + *

{@code return Dec128.$toLongBits(ctx, new BigDecimal(value, MathContext.DECIMAL128));} + */ + protected void generateToDec128(CodeBuilder code, JitMethodDesc jmd) { + FixedInt source = FixedInt.of(thisType); + + code.aload(code.parameterSlot(jmd.optimizedCtx())) + .new_(CD_BigDecimal) + .dup(); + + if (source.bitLength == 128 || !source.signed && source.bitLength == 64) { + if (source.bitLength == 128) { + code.lload(code.parameterSlot(0)) + .lload(code.parameterSlot(1)) + .invokestatic(art.CD(), "$toBigInteger", md(CD_BigInteger, CD_long, CD_long)); + } else { + generateUnsignedLongAsBigInteger(code); + } + code.getstatic(CD_MathContext, "DECIMAL128", CD_MathContext) + .invokespecial(CD_BigDecimal, INIT_NAME, md(CD_void, CD_BigInteger, CD_MathContext)); + } else { + loadComparableLong(code, source); + code.invokespecial(CD_BigDecimal, INIT_NAME, md(CD_void, CD_long)); + } + + code.invokestatic(CD_Dec128, "$toLongBits", md(CD_long, CD_Ctx, CD_BigDecimal)) + .lreturn(); + } + /** * Convert the unsigned long value to a positive {@link BigInteger}. */ @@ -752,5 +797,7 @@ private UnsupportedOperationException unsupportedNumber() { return new UnsupportedOperationException("Unsupported number type: " + thisType); } - private static final ClassDesc CD_BigInteger = ClassDesc.of(BigInteger.class.getName()); + private static final ClassDesc CD_BigDecimal = ClassDesc.of(BigDecimal.class.getName()); + private static final ClassDesc CD_BigInteger = ClassDesc.of(BigInteger.class.getName()); + private static final ClassDesc CD_MathContext = ClassDesc.of(MathContext.class.getName()); } diff --git a/manualTests/src/main/x/jit/jit_tests/temporal/DurationTests.x b/manualTests/src/main/x/jit/jit_tests/temporal/DurationTests.x index ba687aab20..bf69bc0e18 100644 --- a/manualTests/src/main/x/jit/jit_tests/temporal/DurationTests.x +++ b/manualTests/src/main/x/jit/jit_tests/temporal/DurationTests.x @@ -229,11 +229,10 @@ class DurationTests { } void testMultiplyDec() { -// TODO requires Int128 to Dec128 conversion support -// Int128 n1 = 97515543876234567; -// Duration d1 = Duration.ofPicos(n1); -// Dec factor = 3.5; -// assert d1 * factor == new Duration(n1 * factor.toInt128()); + Int128 n1 = 97515543876234567; + Duration d1 = Duration.ofPicos(n1); + Dec factor = 3.5; + assert d1 * factor == new Duration(n1 * 7 / 2); // 3.5 = 7/2 } void testDivInt() { From 551422712dd3373845eec116bb2167fba5924793 Mon Sep 17 00:00:00 2001 From: Jonathan Knight Date: Thu, 12 Nov 2026 18:51:06 +0300 Subject: [PATCH 12/21] Add JIT annotations to support specialized native code generation --- .../org/xvm/javajit/NativeTypeSystem.java | 4 +- .../javajit/annotations/JitFromNatural.java | 16 ++ .../xvm/javajit/annotations/JitGenerated.java | 70 ++++++ .../javajit/builders/AugmentingBuilder.java | 231 +++++++++++++++--- .../xvm/javajit/builders/NumberBuilder.java | 2 +- .../generators/OSStorageGenerator.java | 41 ++++ .../org/xtclang/_native/fs/OSDirectory.java | 173 ------------- .../java/org/xtclang/_native/fs/OSFile.java | 6 +- .../org/xtclang/_native/fs/OSFileNode.java | 32 +-- .../org/xtclang/_native/fs/OSFileStore.java | 54 ++-- .../org/xtclang/_native/fs/OSStorage.java | 33 ++- .../java/org/xtclang/ecstasy/fs/Path.java | 158 +----------- 12 files changed, 377 insertions(+), 443 deletions(-) create mode 100644 javatools/src/main/java/org/xvm/javajit/annotations/JitFromNatural.java create mode 100644 javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java create mode 100644 javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java diff --git a/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java b/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java index c2128d97d7..e1250d20ba 100644 --- a/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java +++ b/javatools/src/main/java/org/xvm/javajit/NativeTypeSystem.java @@ -231,7 +231,7 @@ private byte[] augmentNativeClass(ClassModel model, String className, TypeConsta Artifact art = new Artifact(type, struct, ClassfileShape.Impl, className); ConstantPool pool = pool(); - Builder builder; + AugmentingBuilder builder; if (type.isArray()) { builder = new ArrayBuilder(this, art, model); } else if (type.isA(pool.typeNumber())) { @@ -268,7 +268,7 @@ private byte[] augmentNativeClass(ClassModel model, String className, TypeConsta return; } - classBuilder.with(element); // copy everything else "as is" + builder.processElement(element, classBuilder); if (element instanceof Superclass) { // augment the new classfile using the Ecstasy class structure (just once!) diff --git a/javatools/src/main/java/org/xvm/javajit/annotations/JitFromNatural.java b/javatools/src/main/java/org/xvm/javajit/annotations/JitFromNatural.java new file mode 100644 index 0000000000..07c9dd9445 --- /dev/null +++ b/javatools/src/main/java/org/xvm/javajit/annotations/JitFromNatural.java @@ -0,0 +1,16 @@ +package org.xvm.javajit.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * A marker annotation to indicate that the annotated element should be generated by the JIT from + * the natural Ecstasy code. The content of an annotated method will be replaced by the + * corresponding natural code for that method. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface JitFromNatural { +} diff --git a/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java b/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java new file mode 100644 index 0000000000..b2b071e214 --- /dev/null +++ b/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java @@ -0,0 +1,70 @@ +package org.xvm.javajit.annotations; + +import java.lang.annotation.Retention; + +import java.lang.annotation.RetentionPolicy; + +import java.lang.classfile.ClassBuilder; +import java.lang.classfile.ClassElement; +import java.lang.classfile.ClassFileElement; + +import org.xvm.javajit.builders.AugmentingBuilder; + +/** + * An annotation to indicate that the annotated source element is handled as a special case by + * the {@link AugmentingBuilder}. + *

+ * A class that contains elements annotated with {@link JitGenerated} elements must itself be + * annotated with the {@link JitGenerated} annotation. Any generator class specified for the + * class level annotation is ignored. + *

+ * The default generator class {@link #value()} is the {@link NaturalCode} generator, which + * indicates that the JIT will produce code using the corresponding natural Ecstasy code for the + * annotated element. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface JitGenerated { + /** + * The {@link Class} of the {@link Generator} to use to generate custom code. + *

+ * The default value is the {@link NaturalCode} generator, which indicates that the JIT will + * produce code using the corresponding natural Ecstasy code for the annotated element. + * + * @return the {@link Class} of the {@link Generator} to use to generate custom code for the + * annotated element. + */ + Class> value() default NaturalCode.class; + + /** + * A Java code generator that handles customizations to classes processed by the + * {@link AugmentingBuilder}. + *

+ * Each instance of {@link Generator} is typically used to generate a specific piece of Java + * code, for example customize the contents of a method. + */ + interface Generator { + /** + * Generate the Java code for the specified element. + * + * @param builder the current {@link AugmentingBuilder} + * @param element the element of the {@link Class} that this annotation applied to + * @param classBuilder the {@link ClassBuilder} to use to generate code + */ + void generate(AugmentingBuilder builder, E element, ClassBuilder classBuilder); + } + + /** + * A no-op generator to indicate that the code should be produced from the natural code for + * the annotated element. + */ + class NaturalCode implements Generator { + /** + * A singleton instance of the {@link NaturalCode} generator. + */ + public static final NaturalCode INSTANCE = new NaturalCode(); + + @Override + public void generate(AugmentingBuilder builder, ClassElement element, ClassBuilder classBuilder) { + } + } +} diff --git a/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java index 96dac09b31..879988386a 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java @@ -1,27 +1,43 @@ package org.xvm.javajit.builders; +import java.lang.classfile.Annotation; +import java.lang.classfile.AnnotationElement; +import java.lang.classfile.AnnotationValue; +import java.lang.classfile.AttributedElement; +import java.lang.classfile.Attributes; import java.lang.classfile.ClassBuilder; +import java.lang.classfile.ClassElement; import java.lang.classfile.ClassFile; +import java.lang.classfile.ClassFileElement; import java.lang.classfile.ClassModel; import java.lang.classfile.CodeBuilder; import java.lang.classfile.FieldModel; import java.lang.classfile.Label; import java.lang.classfile.MethodModel; + +import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; + import java.lang.classfile.instruction.ReturnInstruction; import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDesc; import java.lang.constant.ConstantDescs; import java.lang.constant.MethodTypeDesc; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.xvm.asm.constants.MethodInfo; import org.xvm.asm.constants.PropertyInfo; import org.xvm.asm.constants.TypeConstant; import org.xvm.javajit.Builder; +import org.xvm.javajit.annotations.JitFromNatural; import org.xvm.javajit.JitCtorDesc; import org.xvm.javajit.JitFlavor; +import org.xvm.javajit.annotations.JitGenerated; +import org.xvm.javajit.annotations.JitGenerated.Generator; import org.xvm.javajit.JitMethodDesc; import org.xvm.javajit.JitTypeDesc; import org.xvm.javajit.NativeTypeSystem; @@ -42,7 +58,8 @@ public class AugmentingBuilder extends CommonBuilder { public AugmentingBuilder(TypeSystem typeSystem, Artifact art, ClassModel model) { super(typeSystem, art); - this.model = model; + this.model = model; + this.isJitAnnotated = isAnnotated(model, CD_JitGenerated); } /** @@ -50,6 +67,20 @@ public AugmentingBuilder(TypeSystem typeSystem, Artifact art, ClassModel model) */ public final ClassModel model; + /** + * A flag indicating whether the class represented by the model is annotated with the + * {@link JitGenerated} annotation. + */ + public final boolean isJitAnnotated; + + /** + * A cache of elements identified as being natively implemented. + */ + private final Map nativeElements = new HashMap<>(); + + private static final ClassDesc CD_JitGenerated = ClassDesc.of(JitGenerated.class.getName()); + private static final ClassDesc CD_JitFromNatural = ClassDesc.of(JitFromNatural.class.getName()); + protected NativeTypeSystem getTypeSystem() { return (NativeTypeSystem) typeSystem; } @@ -116,11 +147,8 @@ protected void prependCLInit(CodeBuilder code) { } @Override - protected void assembleInit( - ClassBuilder classBuilder, - List props) { - MethodModel mm = findMethod(INIT_NAME, MD_xvmVoid); - if (mm == null) { + protected void assembleInit(ClassBuilder classBuilder, List props) { + if (!isNativeMethod(INIT_NAME, MD_xvmVoid)) { super.assembleInit(classBuilder, props); } } @@ -166,16 +194,17 @@ protected void assembleField(ClassBuilder classBuilder, PropertyInfo prop) { @Override protected void assemblePropertyAccessor(ClassBuilder classBuilder, PropertyInfo prop, String jitName, JitMethodDesc jmd, boolean isGetter) { - MethodTypeDesc md = jmd.isOptimized ? jmd.optimizedMD : jmd.standardMD; - MethodModel mm = findMethod(jitName, md); - if (mm != null && ((mm.flags().flagsMask() & ClassFile.ACC_ABSTRACT) == 0 || + MethodTypeDesc md = jmd.isOptimized ? jmd.optimizedMD : jmd.standardMD; + MethodModel mm = findMethod(jitName, md); + boolean isNative = mm != null && isNativeElement(mm); + if (isNative && ((mm.flags().flagsMask() & ClassFile.ACC_ABSTRACT) == 0 || prop.isAbstract() || prop.isNative())) { // the native accessor still need its boxed entry point if (jmd.isOptimized) { String standardName = isGetter ? prop.ensureGetterJitMethodName(typeSystem) : prop.ensureSetterJitMethodName(typeSystem); - if (findMethod(standardName, jmd.standardMD) == null) { + if (!isNativeMethod(standardName, jmd.standardMD)) { assembleMethodWrapper(classBuilder, standardName, jmd); } } @@ -192,10 +221,10 @@ protected void assembleInflatedAccessors(ClassBuilder classBuilder, PropertyInfo if (jmd.isOptimized && findMethod(jitName + OPT, jmd.optimizedMD) != null) { // the native optimized getter still needs its boxed entry point - if (findMethod(jitName, jmd.standardMD) == null) { + if (!isNativeMethod(jitName, jmd.standardMD)) { assembleMethodWrapper(classBuilder, jitName, jmd); } - } else if (findMethod(jitName, jmd.standardMD) == null) { + } else if (!isNativeMethod(jitName, jmd.standardMD)) { super.assembleInflatedAccessors(classBuilder, prop); } } @@ -205,12 +234,12 @@ protected void generateTrivialGetter(ClassBuilder classBuilder, PropertyInfo pro String jitName = prop.ensureGetterJitMethodName(typeSystem); JitMethodDesc jmd = prop.getGetterJitDesc(this, thisType); - if (jmd.isOptimized && findMethod(jitName + OPT, jmd.optimizedMD) != null) { + if (jmd.isOptimized && isNativeMethod(jitName + OPT, jmd.optimizedMD)) { // the native optimized getter still needs its boxed entry point - if (findMethod(jitName, jmd.standardMD) == null) { + if (!isNativeMethod(jitName, jmd.standardMD)) { assembleMethodWrapper(classBuilder, jitName, jmd); } - } else if (findMethod(jitName, jmd.standardMD) == null) { + } else if (!isNativeMethod(jitName, jmd.standardMD)) { super.generateTrivialGetter(classBuilder, prop); } } @@ -220,19 +249,19 @@ protected void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo pro String jitName = prop.ensureSetterJitMethodName(typeSystem); JitMethodDesc jmd = prop.getSetterJitDesc(this, thisType); - if (jmd.isOptimized && findMethod(jitName + OPT, jmd.optimizedMD) != null) { + if (jmd.isOptimized && isNativeMethod(jitName + OPT, jmd.optimizedMD)) { // the native optimized setter still needs its boxed entry point - if (findMethod(jitName, jmd.standardMD) == null) { + if (!isNativeMethod(jitName, jmd.standardMD)) { assembleMethodWrapper(classBuilder, jitName, jmd); } - } else if (findMethod(jitName, jmd.standardMD) == null) { + } else if (!isNativeMethod(jitName, jmd.standardMD)) { super.generateTrivialSetter(classBuilder, prop); } } @Override protected void assembleGenericProperty(ClassBuilder classBuilder, String name) { - if (findMethod(name + "$get", null) == null) { + if (!isNativeMethod(name + "$get", null)) { super.assembleGenericProperty(classBuilder, name); } } @@ -242,12 +271,12 @@ protected void assembleMethod( ClassBuilder classBuilder, MethodInfo method, String jitName, JitMethodDesc jmd) { if (method.isConstructorOnly()) { - String newName = jitName.replace("construct", typeInfo.isSingleton() ? INIT : NEW); - JitMethodDesc newJmd = Builder.convertConstructToNew(typeInfo, art.CD(), (JitCtorDesc) jmd); - MethodModel newMM = newJmd.isOptimized - ? findMethod(newName + OPT, newJmd.optimizedMD) - : findMethod(newName, newJmd.standardMD); - if (newMM != null) { + String newName = jitName.replace("construct", typeInfo.isSingleton() ? INIT : NEW); + JitMethodDesc newJmd = Builder.convertConstructToNew(typeInfo, art.CD(), (JitCtorDesc) jmd); + boolean isNative = newJmd.isOptimized + ? isNativeMethod(newName + OPT, newJmd.optimizedMD) + : isNativeMethod(newName, newJmd.standardMD); + if (isNative) { // the "new" method has been natively implemented; we should not attempt to generate // the constructor return; @@ -258,10 +287,11 @@ protected void assembleMethod( ? findMethod(jitName + OPT, jmd.optimizedMD) : findMethod(jitName, jmd.standardMD); - if (mm != null && - ((mm.flags().flagsMask() & ClassFile.ACC_ABSTRACT) == 0 || + boolean isNative = isNativeElement(mm); + + if (mm != null && isNative && ((mm.flags().flagsMask() & ClassFile.ACC_ABSTRACT) == 0 || method.isAbstract() || method.isNative())) { - if (jmd.isOptimized && findMethod(jitName, jmd.standardMD) == null) { + if (jmd.isOptimized && !isNativeMethod(jitName, jmd.standardMD)) { // we have the optimized native method; still need to generate the standard one assembleMethodWrapper(classBuilder, jitName, jmd); } @@ -274,7 +304,7 @@ protected void assembleMethod( TypeConstant typeDeclared = method.getJitIdentity().getClassIdentity().getType(); JitMethodDesc jmdDeclared = method.getJitDesc(this, typeDeclared); if (jmdDeclared.isOptimized && !jmdDeclared.isOptimizedStatic && - findMethod(jitName + OPT, jmdDeclared.optimizedMD) == null) { + !isNativeMethod(jitName + OPT, jmdDeclared.optimizedMD)) { assembleOptimizedCap(classBuilder, jitName + OPT, jitName + OPT, jmdDeclared, jmd, method.isConditionalReturn(typeInfo)); } @@ -307,15 +337,50 @@ protected void assembleXvmType(ClassBuilder classBuilder) { @Override protected void assembleNew(ClassBuilder classBuilder, MethodInfo constructor, String jitName, JitMethodDesc jmd, List annoConstructors) { - MethodModel mm = jmd.isOptimized - ? findMethod(jitName + OPT, jmd.optimizedMD) - : findMethod(jitName, jmd.standardMD); + boolean isNative = jmd.isOptimized + ? isNativeMethod(jitName + OPT, jmd.optimizedMD) + : isNativeMethod(jitName, jmd.standardMD); - if (mm == null) { + if (!isNative) { super.assembleNew(classBuilder, constructor, jitName, jmd, annoConstructors); } } + /** + * Apply any custom processing to the {@link ClassFileElement}. + * + * @param element the {@link ClassFileElement} to customize + * @param classBuilder the {@link ClassBuilder} to use to generate code + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public void processElement(ClassElement element, ClassBuilder classBuilder) { + if (isJitAnnotated) { + if (isAnnotated(element, CD_JitFromNatural)) { + // the element is annotated with JitNatural, let the JIT compile it + return; + } + + Annotation generated = findAnnotation(element, CD_JitGenerated); + if (generated != null) { + // element has a JitGenerated annotation, so execute its generator + ClassDesc genCD = getGeneratorClass(generated); + try { + var className = genCD.packageName() + "." + genCD.displayName(); + var clz = (Class) Class.forName(className); + var constructor = clz.getDeclaredConstructor(); + var generator = constructor.newInstance(); + generator.generate(this, element, classBuilder); + } catch (Exception e) { + throw new RuntimeException(e); + } + return; + } + } + + // element has no JIT annotations, so it is native code + classBuilder.with(element); + } + // ----- helper methods ------------------------------------------------------------------------ /** @@ -385,11 +450,107 @@ private MethodModel findMethod(ClassModel declaringModel, String jitName, @Override protected boolean isNativeMethod(String jitName, MethodTypeDesc md) { - return findMethod(jitName, md) != null; + return nativeElements.computeIfAbsent(new NativeKey(jitName, md, false), k -> { + MethodModel mm = findMethod(jitName, md); + return isNativeElement(mm); + }); } @Override protected boolean isNativeField(String jitName) { - return findField(jitName) != null; + return nativeElements.computeIfAbsent(new NativeKey(jitName, true), k -> { + FieldModel fm = findField(jitName); + return isNativeElement(fm); + }); + } + + /** + * Determine whether the specified element is coded natively. + *

+ * If the element is {@code null} it is not native. + *

+ * If the element is annotated with {@link JitFromNatural} it is not native. + *

+ * If the element is annotated with {@link JitGenerated} then the annotation's generator class + * is checked. If the generator class is {@link JitGenerated.NaturalCode}, then the element + * is not native, otherwise for all other generator classes the element is native. + *

+ * Otherwise if the element is not {@code null} and has neither {@link JitFromNatural} nor + * {@link JitGenerated} annotations then it is native. + * + * @param element the {@link ClassFileElement} to test + * + * @return {@code true} if the element is coded natively + */ + public boolean isNativeElement(ClassFileElement element) { + if (element == null) { + return false; + } + if (isAnnotated(element, CD_JitFromNatural)) { + return false; + } + Annotation an = findAnnotation(element, CD_JitGenerated); + if (an != null) { + ClassDesc cd = getGeneratorClass(an); + return !CD_JitFromNatural.equals(cd); + } + return true; + } + + /** + * @return the {@link Generator} class for the specified {@link JitGenerated} + * annotation. + */ + protected ClassDesc getGeneratorClass(Annotation annotation) { + List elements = annotation.elements(); + if (elements.isEmpty()) { + return CD_JitFromNatural; + } + + for (AnnotationElement annotationElement : elements) { + if (annotationElement.name().equalsString("value")) { + return ((AnnotationValue.OfClass) annotationElement.value()).classSymbol(); + } + } + throw new IllegalStateException("generator value not found"); + } + + /** + * @return {@code true} if the specified element is annotated with the specified annotation + */ + public static boolean isAnnotated(ClassFileElement element, ClassDesc annotation) { + return findAnnotation(element, annotation) != null; + } + + /** + * @return if the element is annotated with the specified annotation, then return it, + * otherwise return {@code null} + */ + public static Annotation findAnnotation(ClassFileElement element, ClassDesc annotation) { + if (element instanceof AttributedElement attributedElement) { + List annotations = attributedElement + .findAttribute(Attributes.runtimeVisibleAnnotations()) + .map(RuntimeVisibleAnnotationsAttribute::annotations) + .orElse(null); + + if (annotations != null) { + return annotations.stream() + .filter(ann -> ann.classSymbol().equals(annotation)) + .findFirst() + .orElse(null); + } + } + return null; + } + + // ----- inner record: NativeKey --------------------------------------------------------------- + + /** + * The key used in the native element cache map {@link #nativeElements}. + */ + private record NativeKey(String jitName, ConstantDesc desc, boolean isField) { + private NativeKey(String jitName, boolean isField) { + this(jitName, null, isField); + } } } diff --git a/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java index dafc809cdd..18d21db6e3 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/NumberBuilder.java @@ -1121,7 +1121,7 @@ protected void generateCompare(ClassBuilder classBuilder) { int flags = ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC; String jitName = "compare"; - if (findMethod(jitName, mdCompare) != null) { + if (isNativeMethod(jitName, mdCompare)) { return; } diff --git a/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java b/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java new file mode 100644 index 0000000000..1ff6b5364a --- /dev/null +++ b/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java @@ -0,0 +1,41 @@ +package org.xvm.javajit.builders.generators; + +import java.lang.classfile.ClassBuilder; +import java.lang.classfile.MethodModel; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; + +import org.xvm.javajit.annotations.JitGenerated; +import org.xvm.javajit.builders.AugmentingBuilder; + +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static org.xvm.javajit.Builder.CD_Ctx; +import static org.xvm.javajit.Builder.md; + +/** + * The {@link JitGenerated.Generator} implementation for the {@code ecstasy.fs.OSStorage} type. + */ +public class OSStorageGenerator + implements JitGenerated.Generator { + + @Override + public void generate(AugmentingBuilder builder, MethodModel model, ClassBuilder classBuilder) { + assert model.methodName().equalsString("instance"); + + MethodTypeDesc methodTypeDesc = model.methodTypeSymbol(); + String name = model.methodName().stringValue(); + int flags = model.flags().flagsMask(); + ClassDesc cd = builder.art.CD(); + + classBuilder.withMethodBody(name, methodTypeDesc, flags, code -> { + // generate the following: + // return new OSStorage(ctx); + code.new_(cd) + .dup() + .aload(code.parameterSlot(0)) + .invokespecial(cd, INIT_NAME, md(CD_void, CD_Ctx)) + .areturn(); + }); + } +} diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSDirectory.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSDirectory.java index 1871d03186..aa315c5e4c 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSDirectory.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSDirectory.java @@ -1,6 +1,5 @@ package org.xtclang._native.fs; -import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; @@ -10,21 +9,8 @@ import java.nio.file.attribute.BasicFileAttributes; -import java.util.Collections; -import java.util.List; - -import java.util.stream.Stream; - -import org.xtclang.ecstasy.Iterator; -import org.xtclang.ecstasy.nObject; -import org.xtclang.ecstasy.nType; - import org.xtclang.ecstasy.fs.Directory; -import org.xvm.asm.ConstantPool; - -import org.xvm.asm.constants.TypeConstant; - import org.xvm.javajit.Ctx; import static org.xtclang.ecstasy.Exception.$io; @@ -40,39 +26,6 @@ public OSDirectory(Ctx ctx, OSFileStore store, java.nio.file.Path path) { super(ctx, store, path); } - /** - * The primitive property getter for {@code Int size.get()}. - */ - public long size$get$p(Ctx ctx) { - java.nio.file.Path path = $getJavaPath(ctx); - if (Files.exists(path)) { - try (Stream stream = Files.walk(path, 1)) { - return stream.map(java.nio.file.Path::toFile) - .filter(File::isFile) - .mapToLong(File::length) - .sum(); - } catch (IOException e) { - throw $io(ctx, e); - } - } else { - return 0L; - } - } - - /** - * The native implementation of the OSDirectory.x method {@code Iterator dirs();}. - */ - public Iterator dirs(Ctx ctx) { - return new nIterator(ctx, $getJavaPath(ctx), ctx.pool().typeDirectory(), 1); - } - - /** - * The native implementation of the OSDirectory.x method {@code Iterator files();}. - */ - public Iterator files(Ctx ctx) { - return new nIterator(ctx, $getJavaPath(ctx),ctx.pool().typeFile(), 2); - } - /** * The primitive implementation of the OSDirectory.x method {@code Boolean deleteRecursively();}. */ @@ -89,20 +42,6 @@ public Iterator files(Ctx ctx) { return false; } - /** - * The native implementation of the OSDirectory.x method {@code Iterator filesRecursively();}. - */ - public Iterator filesRecursively(Ctx ctx) { - return new nRecursiveIterator(ctx, $getJavaPath(ctx)); - } - - /** - * The native implementation of the OSDirectory.x method {@code Iterator nodes();}. - */ - public Iterator nodes(Ctx ctx) { - return new nIterator(ctx, $getJavaPath(ctx), ctx.pool().typeFileNode(), 0); - } - // ----- inner class nDeleteVisitor ------------------------------------------------------------ /** @@ -128,116 +67,4 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) return FileVisitResult.CONTINUE; } } - - // ----- inner class nIterator ----------------------------------------------------------------- - - /** - * A native implementation of Iterator.x to iterate over this directory's files and directories. - */ - private class nIterator extends nObject implements Iterator { - - private final java.util.Iterator fileIterator; - - private final TypeConstant type; - - public nIterator(Ctx ctx, java.nio.file.Path path, TypeConstant type, int filesOrDirs) { - super(ctx); - this.type = type; - if (Files.exists(path)) { - File[] files = switch (filesOrDirs) { - case 1 -> path.toFile().listFiles(File::isDirectory); - case 2 -> path.toFile().listFiles(File::isFile); - default -> path.toFile().listFiles(); - }; - fileIterator = files != null - ? List.of(files).iterator() - : Collections.emptyIterator(); - } else { - fileIterator = Collections.emptyIterator(); - } - } - - @Override - public TypeConstant $xvmType(Ctx ctx) { - ConstantPool pool = ctx.pool(); - return pool.ensureParameterizedTypeConstant( - pool.typeIterator(), type); - } - - @Override - public boolean $isImmut() { - return false; - } - - @Override - public nType Element$get(Ctx ctx) { - return nType.$ensureType(ctx, type); - } - - @Override - public boolean next$p(Ctx ctx) { - if (fileIterator.hasNext()) { - ctx.o0 = OSFileNode.$nodeFor(ctx, store, fileIterator.next().toPath()); - return true; - } - return false; - } - } - - // ----- inner class nRecursiveIterator -------------------------------------------------------- - - /** - * A native implementation of Iterator.x to recursively iterate over this directory's files and - * directories. - */ - private class nRecursiveIterator extends nObject implements Iterator { - - private final nIterator dirIterator; - - private final nIterator fileIterator; - - private final TypeConstant type; - - private nRecursiveIterator iterator = null; - - public nRecursiveIterator(Ctx ctx, java.nio.file.Path path) { - super(ctx); - this.type = ctx.pool().typeFile(); - dirIterator = new nIterator(ctx, path, ctx.pool().typeDirectory(), 1); - fileIterator = new nIterator(ctx, path, ctx.pool().typeFile(), 2); - } - - @Override - public TypeConstant $xvmType(Ctx ctx) { - ConstantPool pool = ctx.pool(); - return pool.ensureParameterizedTypeConstant( - pool.typeIterator(), type); - } - - @Override - public boolean $isImmut() { - return false; - } - - @Override - public nType Element$get(Ctx ctx) { - return nType.$ensureType(ctx, type); - } - - @Override - public boolean next$p(Ctx ctx) { - if (fileIterator.next$p(ctx)) { - return true; - } - while (iterator == null || !iterator.next$p(ctx)) { - if (dirIterator.next$p(ctx)) { - OSFileNode node = (OSFileNode) ctx.o0; - iterator = new nRecursiveIterator(ctx, node.$getJavaPath(ctx)); - } else { - return false; - } - } - return iterator != null; - } - } } diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFile.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFile.java index 01b2155d94..7c582aa4a6 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFile.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFile.java @@ -73,7 +73,7 @@ public OSFile(Ctx ctx, OSFileStore store, java.nio.file.Path path) { try { java.io.File file = path.toFile(); if (!file.exists()) { - throw $fileNotFound(ctx, $getPath(ctx)); + throw $fileNotFound(ctx, path$get(ctx)); } return ArrayᐸUInt8ᐳ.$makeArray(ctx, Handy.readFileBytes(file)); } catch (IOException e) { @@ -108,7 +108,7 @@ public OSFile(Ctx ctx, OSFileStore store, java.nio.file.Path path) { java.io.File file = path.toFile(); if (!file.exists() || !file.isFile()) { - throw $fileNotFound(ctx, $getPath(ctx)); + throw $fileNotFound(ctx, path$get(ctx)); } long start = range.effectiveLowerBound$get$p(ctx); @@ -145,7 +145,7 @@ public OSFile(Ctx ctx, OSFileStore store, java.nio.file.Path path) { java.io.File file = path.toFile(); if (!file.exists() || !file.isFile()) { - throw $fileNotFound(ctx, $getPath(ctx)); + throw $fileNotFound(ctx, path$get(ctx)); } long length = file.length(); diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java index 5e66ebc185..2e6c9f5289 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileNode.java @@ -13,11 +13,13 @@ import org.xtclang.ecstasy.fs.FileNode; import org.xtclang.ecstasy.fs.Path; -import org.xtclang.ecstasy.reflect.nRef; import org.xtclang.ecstasy.text.String; import org.xvm.javajit.Ctx; +import org.xvm.javajit.annotations.JitFromNatural; +import org.xvm.javajit.annotations.JitGenerated; + import org.xvm.runtime.template._native.fs.xOSFileNode; import static org.xtclang.ecstasy.Exception.$io; @@ -25,6 +27,7 @@ /** * Native implementation for {@code _native.fs.OSFileNode}. */ +@JitGenerated public class OSFileNode extends nConst implements FileNode { @@ -33,14 +36,8 @@ protected OSFileNode(Ctx ctx, OSFileStore store, java.nio.file.Path path) { super(ctx); this.store = store; this.$javaPath = path; - this.path = new nRef(ctx, Path.$fromJavaPath(ctx, path), ctx.pool().typePath(), false); } - /** - * The native property {@code @RO Path path;} - */ - public nRef path; - /** * The field for the native property {@code OSFileStore store;}. */ @@ -62,12 +59,11 @@ protected OSFileNode(Ctx ctx, OSFileStore store, java.nio.file.Path path) { /** * The native property getter for {@code @Lazy Path path.calc()} */ + @JitFromNatural public Path path$get(Ctx ctx) { - nRef path = this.path; - if (path == null) { - path = this.path = new nRef(ctx, Path.$fromJavaPath(ctx, $javaPath), ctx.pool().typePath(), false); - } - return (Path) path.get(ctx); + // the JIT will generate the code for this method from the natural code in + // _native.fs.OSFileNode.x + return null; } /** @@ -107,11 +103,6 @@ protected OSFileNode(Ctx ctx, OSFileStore store, java.nio.file.Path path) { return pathString$get(ctx).appendTo(ctx, appender); } -// @Override -// public String toString(Ctx ctx) { -// return path$get(ctx).toString(ctx); -// } - // ----- OSFileNode API ------------------------------------------------------------------------ /** @@ -174,13 +165,6 @@ protected OSFileNode(Ctx ctx, OSFileStore store, java.nio.file.Path path) { // ----- JIT helper methods -------------------------------------------------------------------- - /** - * @return the path from the {@link #path} ref for this node - */ - protected Path $getPath(Ctx ctx) { - return (Path) path.get(ctx); - } - /** * @return the Java {@code java.nio.file.Path} for this node */ diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileStore.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileStore.java index ed1dc59402..faa3471ded 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileStore.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSFileStore.java @@ -20,80 +20,72 @@ import org.xtclang.ecstasy.fs.Directory; import org.xtclang.ecstasy.fs.FileStore; -import org.xtclang.ecstasy.reflect.nRef; - import org.xtclang.ecstasy.text.String; import org.xvm.javajit.Ctx; -import static org.xtclang.ecstasy.Exception.$illegalState; +import org.xvm.javajit.annotations.JitFromNatural; +import org.xvm.javajit.annotations.JitGenerated; /** * The native implementation of {@code _native.fs.OSFileStore}. */ +@JitGenerated public class OSFileStore extends nObject implements FileStore { - protected OSFileStore(Ctx ctx, OSStorage storage, boolean readOnly) { - super(ctx); - this.storage = storage; - this.readOnly = readOnly; + private OSFileStore() { + super(null); } /** - * The native field for the property {@code @Lazy Directory root.calc()}. - */ - public nRef root; - - /** - * The native field for the property {@code OSStorage storage;}. - */ - public OSStorage storage; - - /** - * The native property {@code public/private Boolean readOnly;}. + * The primitive constructor + * {@code construct(OSStorage storage, Boolean readOnly)} */ - public boolean readOnly; + @JitFromNatural + public static OSFileStore $new$p(Ctx ctx, OSStorage storage, boolean readOnly) { + // this method is declared so that other native code can call the constructor + // the JIT will generate the code for this method from the natural code in + // _native.fs.OSFileStore.x + return null; + } /** * The root of the Java file system. */ - private static final java.io.File ROOT = new java.io.File("/"); + private static final java.io.File $ROOT = new java.io.File("/"); /** * The native implementation of {@code @Lazy Directory root.calc()}. */ + @JitFromNatural public Directory root$get(Ctx ctx) { - nRef ref = this.root; - if (ref == null) { - if (!storage.find$p(ctx, this, String.of(ctx, "/"))) { - throw $illegalState(ctx, "Assertion failed"); - } - ref = this.root = new nRef(ctx, (nObject) ctx.o0, ctx.pool().typeDirectory(), true); - } - return (Directory) ref.get(ctx); + // this method is declared so that other native code can access the root directory property + // the JIT will generate the code for this method from the natural code in + // _native.fs.OSFileStore.x + return null; } /** * The native implementation of {@code @RO Int capacity;}. */ public long capacity$get$p(Ctx ctx) { - return ROOT.getTotalSpace(); + return $ROOT.getTotalSpace(); } /** * The native implementation of {@code @RO Int bytesUsed;}. */ public long bytesUsed$get$p(Ctx ctx) { - return ROOT.getTotalSpace() - ROOT.getFreeSpace(); + return $ROOT.getTotalSpace() - $ROOT.getFreeSpace(); } /** * The native implementation of {@code @RO Int bytesFree;}. */ public long bytesFree$get$p(Ctx ctx) { - return ROOT.getFreeSpace(); + return $ROOT.getFreeSpace(); } /** diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSStorage.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSStorage.java index f8357128b7..c1d46c223a 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSStorage.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/fs/OSStorage.java @@ -15,24 +15,27 @@ import org.xtclang.ecstasy.text.String; import org.xvm.javajit.Ctx; -import org.xvm.javajit.ModuleLoader; + +import org.xvm.javajit.annotations.JitGenerated; + +import org.xvm.javajit.builders.generators.OSStorageGenerator; /** * The native implementation of {@code _native.fs.OSStorage}. */ +@JitGenerated public class OSStorage extends nService { private OSStorage() { - ModuleLoader loader = (ModuleLoader) OSStorage.class.getClassLoader(); - Ctx ctx = loader.getCtx(); - super(ctx); - fileStore = new OSFileStore(ctx, this, false); + super(null); } - /** - * The singleton instance of {@link OSStorage}. - */ - private static final OSStorage $INSTANCE = new OSStorage(); + // TODO this constructor should be generated by the JIT but depends on specialized HashMap + // (long arm implementation) + public OSStorage(Ctx ctx) { + super(ctx); + fileStore = OSFileStore.$new$p(ctx, this, false); + } /** * The {@link OSFileStore} property. @@ -41,13 +44,6 @@ private OSStorage() { // ----- OSStorage.x implementation ------------------------------------------------------------ - /** - * The native property getter for the property {@code OSFileStore fileStore;} - */ - public OSFileStore fileStore$get(Ctx ctx) { - return fileStore; - } - /** * The native implementation of the property {@code @Abstract @RO Directory homeDir;}. */ @@ -172,7 +168,10 @@ void unwatch(Ctx ctx, String pathStringDir) { /** * The native implementation of the method {@code static OSStorage instance()}. */ + @JitGenerated(OSStorageGenerator.class) public static OSStorage instance(Ctx ctx) { - return $INSTANCE; + // the JIT will generate the following code for this method: + // return new OSStorage(ctx); + return null; } } diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/fs/Path.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/fs/Path.java index e012646631..72033bb086 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/fs/Path.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/fs/Path.java @@ -1,169 +1,13 @@ package org.xtclang.ecstasy.fs; import org.xtclang.ecstasy.nConst; -import org.xtclang.ecstasy.nEnum; -import org.xtclang.ecstasy.Nullable; -import org.xtclang.ecstasy.Object; - -import org.xtclang.ecstasy.text.String; - -import org.xvm.javajit.Ctx; /** * The native implementation of {@code ecstasy.fs.Path}. */ public class Path extends nConst { - /** - * Dummy constructor, the JIT will generate the real constructors. - */ - protected Path() { + private Path() { super(null); } - - public Object parent; - - public String name; - - public long size; - - public boolean absolute; - - public ElementForm form; - - private java.nio.file.Path $javaPath; - - /** - * The property {@code static Path ROOT = new Path(Null, Root);}. - */ - public static Path ROOT; - - /** - * The property {@code static Path CURRENT = new Path(Null, Current);}. - */ - public static Path CURRENT; - - /** - * The property {@code static Path PARENT = new Path(Null, Parent);}. - */ - public static Path PARENT; - - /** - * The native property getter {@code Path? parent;}. - */ - public Object parent$get(Ctx ctx) { - Object parent = this.parent; - if (parent == null) { - // will only be null if created from the $fromJavaPath method - java.nio.file.Path path = $javaPath.getParent(); - if (path == null) { - parent = this.parent = Nullable.Null.$INSTANCE; - } else { - parent = this.parent = $fromJavaPath(ctx, path); - } - } - return parent; - } - - // ----- JIT support --------------------------------------------------------------------------- - - public static Path $fromJavaPath(Ctx ctx, java.nio.file.Path javaPath) { - int size = javaPath.getNameCount(); - java.lang.String name = size == 0 ? "/" : javaPath.getFileName().toString(); - - if (name.isEmpty()) { - return CURRENT; - } - - Path path = new Path(); - boolean absolute = javaPath.isAbsolute(); - - path.parent = null; - path.$javaPath = javaPath; - path.name = String.of(ctx, name); - path.size = absolute ? size + 1 : size; - path.absolute = absolute; - path.form = switch (name) { - case "/" -> ElementForm.Root.$INSTANCE; - case ".." -> ElementForm.Parent.$INSTANCE; - case "." -> ElementForm.Current.$INSTANCE; - default -> ElementForm.Name.$INSTANCE; - }; - return path; - } - - java.nio.file.Path $getJavaPath() { - java.nio.file.Path javaPath = $javaPath; - if (javaPath == null) { - if (parent instanceof Path parentPath) { - javaPath = $javaPath = parentPath.$getJavaPath().resolve(name.toString()); - } else { - javaPath = $javaPath = java.nio.file.Paths.get(name.toString()); - } - } - return javaPath; - } - - // ----- inner enum ElementForm ---------------------------------------------------------------- - - /** - * The native implementation of {@code ecstasy.fs.Path.ElementForm}. - */ - public static class ElementForm extends nEnum { - private ElementForm(long ordinal, String name, String text, long depth) { - super(null); - this.$ordinal = ordinal; - this.$name = name; - this.text = text; - this.depth = depth; - } - - public final long $ordinal; - public final String $name; - public final String text; - public final long depth; - - @Override - public String name$get(Ctx ctx) { - return $name; - } - - @Override - public long ordinal$get$p(Ctx ctx) { - return $ordinal; - } - - @Override - public java.lang.String toString() { - return "ElementForm." + $name.toString(); - } - - public static class Root extends ElementForm { - public static Root $INSTANCE = new Root(); - public Root() { - super(0, String.of(null, "Root"), String.of(null, "/"), 0L); - } - } - - public static class Parent extends ElementForm { - public static Parent $INSTANCE = new Parent(); - public Parent() { - super(1, String.of(null, "Parent"), String.of(null, ".."), -1L); - } - } - - public static class Current extends ElementForm { - public static Current $INSTANCE = new Current(); - public Current() { - super(2, String.of(null, "Current"), String.of(null, "."), 0L); - } - } - - public static class Name extends ElementForm { - public static Name $INSTANCE = new Name(); - public Name() { - super(3, String.of(null, "Name"), String.of(null, "name"), 1L); - } - } - } } From 405b45e3b4691d2d6d5dc492be9ba79aaef35ff1 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Fri, 13 Nov 2026 10:38:31 -0500 Subject: [PATCH 13/21] Post merge review --- .../xvm/javajit/annotations/JitGenerated.java | 1 - .../javajit/builders/AugmentingBuilder.java | 55 ++++++++----------- .../generators/OSStorageGenerator.java | 4 +- 3 files changed, 27 insertions(+), 33 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java b/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java index b2b071e214..cce8b8b26f 100644 --- a/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java +++ b/javatools/src/main/java/org/xvm/javajit/annotations/JitGenerated.java @@ -6,7 +6,6 @@ import java.lang.classfile.ClassBuilder; import java.lang.classfile.ClassElement; -import java.lang.classfile.ClassFileElement; import org.xvm.javajit.builders.AugmentingBuilder; diff --git a/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java index 879988386a..0a045b4311 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/AugmentingBuilder.java @@ -32,12 +32,13 @@ import org.xvm.asm.constants.PropertyInfo; import org.xvm.asm.constants.TypeConstant; -import org.xvm.javajit.Builder; import org.xvm.javajit.annotations.JitFromNatural; -import org.xvm.javajit.JitCtorDesc; -import org.xvm.javajit.JitFlavor; import org.xvm.javajit.annotations.JitGenerated; import org.xvm.javajit.annotations.JitGenerated.Generator; + +import org.xvm.javajit.Builder; +import org.xvm.javajit.JitCtorDesc; +import org.xvm.javajit.JitFlavor; import org.xvm.javajit.JitMethodDesc; import org.xvm.javajit.JitTypeDesc; import org.xvm.javajit.NativeTypeSystem; @@ -59,7 +60,7 @@ public AugmentingBuilder(TypeSystem typeSystem, Artifact art, ClassModel model) super(typeSystem, art); this.model = model; - this.isJitAnnotated = isAnnotated(model, CD_JitGenerated); + this.isJitGenerated = isAnnotated(model, CD_JitGenerated); } /** @@ -71,7 +72,7 @@ public AugmentingBuilder(TypeSystem typeSystem, Artifact art, ClassModel model) * A flag indicating whether the class represented by the model is annotated with the * {@link JitGenerated} annotation. */ - public final boolean isJitAnnotated; + public final boolean isJitGenerated; /** * A cache of elements identified as being natively implemented. @@ -352,17 +353,16 @@ protected void assembleNew(ClassBuilder classBuilder, MethodInfo constructor, St * @param element the {@link ClassFileElement} to customize * @param classBuilder the {@link ClassBuilder} to use to generate code */ - @SuppressWarnings({"unchecked", "rawtypes"}) public void processElement(ClassElement element, ClassBuilder classBuilder) { - if (isJitAnnotated) { + if (isJitGenerated) { if (isAnnotated(element, CD_JitFromNatural)) { - // the element is annotated with JitNatural, let the JIT compile it + // the element is annotated with JitFromNatural, let the JIT compile it return; } Annotation generated = findAnnotation(element, CD_JitGenerated); if (generated != null) { - // element has a JitGenerated annotation, so execute its generator + // element has a JitGenerated annotation; execute its generator ClassDesc genCD = getGeneratorClass(generated); try { var className = genCD.packageName() + "." + genCD.displayName(); @@ -370,7 +370,7 @@ public void processElement(ClassElement element, ClassBuilder classBuilder) { var constructor = clz.getDeclaredConstructor(); var generator = constructor.newInstance(); generator.generate(this, element, classBuilder); - } catch (Exception e) { + } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } return; @@ -458,7 +458,7 @@ protected boolean isNativeMethod(String jitName, MethodTypeDesc md) { @Override protected boolean isNativeField(String jitName) { - return nativeElements.computeIfAbsent(new NativeKey(jitName, true), k -> { + return nativeElements.computeIfAbsent(new NativeKey(jitName, null, true), k -> { FieldModel fm = findField(jitName); return isNativeElement(fm); }); @@ -466,17 +466,15 @@ protected boolean isNativeField(String jitName) { /** * Determine whether the specified element is coded natively. - *

- * If the element is {@code null} it is not native. - *

- * If the element is annotated with {@link JitFromNatural} it is not native. - *

- * If the element is annotated with {@link JitGenerated} then the annotation's generator class - * is checked. If the generator class is {@link JitGenerated.NaturalCode}, then the element - * is not native, otherwise for all other generator classes the element is native. - *

- * Otherwise if the element is not {@code null} and has neither {@link JitFromNatural} nor - * {@link JitGenerated} annotations then it is native. + *

    + *
  • If the element is {@code null} it is not native. + *
  • If the element is annotated with {@link JitFromNatural} it is not native. + *
  • If the element is annotated with {@link JitGenerated} then the annotation's generator + * class is checked. If the generator class is {@link JitGenerated.NaturalCode}, then the + * element is not native, otherwise for all other generator classes the element is native. + *
  • Otherwise if the element is not {@code null} and has neither {@link JitFromNatural} nor + * {@link JitGenerated} annotations then it is native. + *
* * @param element the {@link ClassFileElement} to test * @@ -498,8 +496,7 @@ public boolean isNativeElement(ClassFileElement element) { } /** - * @return the {@link Generator} class for the specified {@link JitGenerated} - * annotation. + * @return the {@link Generator} class for the specified {@link JitGenerated} annotation. */ protected ClassDesc getGeneratorClass(Annotation annotation) { List elements = annotation.elements(); @@ -523,8 +520,8 @@ public static boolean isAnnotated(ClassFileElement element, ClassDesc annotation } /** - * @return if the element is annotated with the specified annotation, then return it, - * otherwise return {@code null} + * @return if the element is annotated with the specified annotation, then return it, otherwise + * return {@code null} */ public static Annotation findAnnotation(ClassFileElement element, ClassDesc annotation) { if (element instanceof AttributedElement attributedElement) { @@ -548,9 +545,5 @@ public static Annotation findAnnotation(ClassFileElement element, ClassDesc anno /** * The key used in the native element cache map {@link #nativeElements}. */ - private record NativeKey(String jitName, ConstantDesc desc, boolean isField) { - private NativeKey(String jitName, boolean isField) { - this(jitName, null, isField); - } - } + private record NativeKey(String jitName, ConstantDesc desc, boolean isField) {} } diff --git a/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java b/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java index 1ff6b5364a..0b6f0e6b26 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/generators/OSStorageGenerator.java @@ -2,6 +2,7 @@ import java.lang.classfile.ClassBuilder; import java.lang.classfile.MethodModel; + import java.lang.constant.ClassDesc; import java.lang.constant.MethodTypeDesc; @@ -10,11 +11,12 @@ import static java.lang.constant.ConstantDescs.CD_void; import static java.lang.constant.ConstantDescs.INIT_NAME; + import static org.xvm.javajit.Builder.CD_Ctx; import static org.xvm.javajit.Builder.md; /** - * The {@link JitGenerated.Generator} implementation for the {@code ecstasy.fs.OSStorage} type. + * The {@link JitGenerated.Generator} implementation for native {@code ecstasy.fs.OSStorage} class. */ public class OSStorageGenerator implements JitGenerated.Generator { From 0696200959b5d30007052b5b4de1eaad796de723 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Fri, 13 Nov 2026 10:46:28 -0500 Subject: [PATCH 14/21] FIx TypeInfo computation for PCTC --- .../java/org/xvm/asm/constants/PropertyClassTypeConstant.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java b/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java index c26155b2b9..f733797445 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java @@ -404,7 +404,7 @@ protected TypeInfo buildTypeInfo(ErrorListener errs) { return new TypeInfoReal(this, cInvals, infoBase.getClassStructure(), idBase.getNestedDepth() + 1, false, mapTypeParams, Annotation.NO_ANNOTATIONS, infoBase.getMixinAnnotations(), typeBase, null, null, - Collections.emptyList(), ListMap.empty(), ListMap.empty(), + infoBase.getContributionList(), infoBase.getClassChain(), infoBase.getDefaultChain(), mapProps, mapMethods, mapVirtProps, mapVirtMethods, mapChildren, null, TypeInfo.Progress.Complete); } From cbad3f88a92579091dd37634e439ee0f8e6c7ee1 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Wed, 11 Nov 2026 19:55:41 -0500 Subject: [PATCH 15/21] Add support for static annotated properties --- .../main/java/org/xvm/asm/OpInvocable.java | 28 ++--- .../xvm/asm/constants/AccessTypeConstant.java | 5 + .../constants/PropertyClassTypeConstant.java | 104 +++++++++++++++--- .../org/xvm/asm/constants/PropertyInfo.java | 15 ++- .../org/xvm/asm/constants/TypeConstant.java | 16 ++- .../java/org/xvm/javajit/BuildContext.java | 12 +- .../main/java/org/xvm/javajit/Builder.java | 59 ++++++++-- .../main/java/org/xvm/javajit/TypeSystem.java | 28 +++-- .../javajit/builders/AnnotationHelper.java | 12 +- .../xvm/javajit/builders/CommonBuilder.java | 81 ++++++++++---- ...der.java => HostedPropertyRefBuilder.java} | 15 ++- .../org/xvm/javajit/builders/RefBuilder.java | 2 +- .../builders/StaticPropertyRefBuilder.java | 52 +++++++++ .../x/jit/jit_tests/basic/propertyInitTests.x | 18 ++- 14 files changed, 346 insertions(+), 101 deletions(-) rename javatools/src/main/java/org/xvm/javajit/builders/{PropertyRefBuilder.java => HostedPropertyRefBuilder.java} (96%) create mode 100644 javatools/src/main/java/org/xvm/javajit/builders/StaticPropertyRefBuilder.java diff --git a/javatools/src/main/java/org/xvm/asm/OpInvocable.java b/javatools/src/main/java/org/xvm/asm/OpInvocable.java index 01f13f0ae6..929ec820f6 100644 --- a/javatools/src/main/java/org/xvm/asm/OpInvocable.java +++ b/javatools/src/main/java/org/xvm/asm/OpInvocable.java @@ -492,15 +492,9 @@ private void buildSingleInvoke(BuildContext bctx, CodeBuilder code, ClassDesc cd call = bctx.builder.resolvePrivateDetachedCall(infoMethod, typeInvoke); } - JitMethodDesc jmd; - if (call == null) { - jmd = infoMethod.getJitDesc(bctx.builder, typeInvoke); - } else { - jmd = call.jmd(); - code.checkcast(call.receiverCD() == null ? call.owner() : call.receiverCD()); - } - - String methodName = infoMethod.ensureJitMethodName(bctx.typeSystem); + JitMethodDesc jmd = call == null + ? infoMethod.getJitDesc(bctx.builder, typeInvoke) + : call.jmd(); if (isTupleReturn()) { if (jmd.isPrimitivized() && fUnboxed) { @@ -521,11 +515,17 @@ private void buildSingleInvoke(BuildContext bctx, CodeBuilder code, ClassDesc cd Builder.unbox(code, typeInvoke); } - if (!isPropCall && (bodyHead.getIdentity().getNestedDepth() > 2 || - infoMethod.getTypeInfo() == null)) { - // nested and private mixin methods absent from TypeInfo need to be built here; - // the second check is based on the synthetic info produced by computeMethodInfo() - bctx.buildMethod(methodName, bodyHead); + String methodName = infoMethod.ensureJitMethodName(bctx.typeSystem); + TypeInfo infoOwner = infoMethod.getTypeInfo(); + if (!isPropCall) { + IdentityConstant idNamespace = bodyHead.getIdentity().getNamespace(); + if (infoOwner == null || + idNamespace.isNested() && + !idNamespace.equals(infoOwner.getType().getDefiningConstant())) { + // direct members are assembled by their type's method loop; nested methods + // and methods absent from TypeInfo are assembled on demand + bctx.buildMethod(methodName, bodyHead); + } } MethodTypeDesc md; diff --git a/javatools/src/main/java/org/xvm/asm/constants/AccessTypeConstant.java b/javatools/src/main/java/org/xvm/asm/constants/AccessTypeConstant.java index 898009de9a..d738c3a40d 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/AccessTypeConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/AccessTypeConstant.java @@ -210,6 +210,11 @@ public String getJitICName(TypeSystem ts) { return m_constType.getJitICName(ts); } + @Override + public String getJitImplName(TypeSystem ts) { + return m_constType.getJitImplName(ts); + } + // ----- Constant methods ---------------------------------------------------------------------- @Override diff --git a/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java b/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java index f733797445..e54e3eeaa9 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/PropertyClassTypeConstant.java @@ -71,6 +71,14 @@ public class PropertyClassTypeConstant * @param idProp the property id */ public PropertyClassTypeConstant(ConstantPool pool, TypeConstant typeParent, PropertyConstant idProp) { + this(pool, typeParent, idProp, false); + } + + /** + * Internal constructor. + */ + private PropertyClassTypeConstant(ConstantPool pool, TypeConstant typeParent, + PropertyConstant idProp, boolean fNativeRebase) { super(pool, typeParent); // unlike VirtualChildConstant, it's never unresolved @@ -81,7 +89,8 @@ public PropertyClassTypeConstant(ConstantPool pool, TypeConstant typeParent, Pro throw new IllegalArgumentException("property is required"); } - m_idProp = idProp; + m_idProp = idProp; + f_fNativeRebase = fNativeRebase; } /** @@ -97,7 +106,8 @@ public PropertyClassTypeConstant(ConstantPool pool, Format format, DataInput in) throws IOException { super(pool, format, in); - m_iProp = readIndex(in); + m_iProp = readIndex(in); + f_fNativeRebase = false; } @Override @@ -134,7 +144,33 @@ public PropertyInfo getPropertyInfo() { * @return the property ref type */ public TypeConstant getRefType() { - return getPropertyInfo().getBaseRefType(); + PropertyInfo info = getPropertyInfo(); + TypeConstant type = info.getBaseRefType(); + + return f_fNativeRebase + ? info.getType().asNativeRef(getConstantPool(), info.isVar()) + .adoptAnnotations(getConstantPool(), type) + : type; + } + + /** + * @return the runtime-only property type based on the native Ref/Var implementation + */ + public PropertyClassTypeConstant asNativeRebase() { + return f_fNativeRebase + ? this + : getConstantPool().register(new PropertyClassTypeConstant( + getConstantPool(), m_typeParent, m_idProp, true)); + } + + /** + * @return the property type based on the ordinary Ref/Var interface + */ + public PropertyClassTypeConstant asStandardRef() { + return f_fNativeRebase + ? getConstantPool().register(new PropertyClassTypeConstant( + getConstantPool(), m_typeParent, m_idProp, false)) + : this; } // ----- TypeConstant methods ------------------------------------------------------------------ @@ -156,7 +192,9 @@ public Constant getDefiningConstant() { @Override protected TypeConstant cloneSingle(ConstantPool pool, TypeConstant type) { - return pool.ensurePropertyClassTypeConstant(type, m_idProp); + PropertyClassTypeConstant typeClone = (PropertyClassTypeConstant) + pool.ensurePropertyClassTypeConstant(type, m_idProp); + return f_fNativeRebase ? typeClone.asNativeRebase() : typeClone; } @Override @@ -267,8 +305,10 @@ protected Usage checkProduction(String sTypeName, Access access, List listExplode = new ArrayList<>(); PropertyStructure structProp = infoProp.getHead().getStructure(); - collectChildInfo(idBase, false, structProp, mapTypeParams, mapContribProps, - mapContribMethods, mapContribChildren, listExplode, mapVirtProps, - 0, 0, errs); + + // collect the property's own members as ordinary Ref/Var declarations + IdentityConstant idRef = idBase instanceof NativeRebaseConstant idNative + ? idNative.getClassConstant() + : idBase; + collectChildInfo(idRef, false, structProp, mapTypeParams, mapContribProps, + mapContribMethods, mapContribChildren, listExplode, mapVirtProps, 0, 0, errs); for (PropertyConstant idProp : listExplode) { PropertyInfo propExplode = mapContribProps.remove(idProp); @@ -343,7 +388,7 @@ protected TypeInfo buildTypeInfo(ErrorListener errs) { if (mapContribProps.isEmpty() && mapContribMethods.isEmpty() && mapContribChildren.isEmpty()) { // nothing has been added - return infoBase; + continue; } if (!mapContribProps.isEmpty()) { @@ -401,7 +446,7 @@ protected TypeInfo buildTypeInfo(ErrorListener errs) { } } - return new TypeInfoReal(this, cInvals, infoBase.getClassStructure(), + return new TypeInfoReal(ensureAccess(Access.PRIVATE), cInvals, infoBase.getClassStructure(), idBase.getNestedDepth() + 1, false, mapTypeParams, Annotation.NO_ANNOTATIONS, infoBase.getMixinAnnotations(), typeBase, null, null, infoBase.getContributionList(), infoBase.getClassChain(), infoBase.getDefaultChain(), @@ -413,7 +458,7 @@ protected TypeInfo buildTypeInfo(ErrorListener errs) { @Override public TypeConstant getJitCCType() { - return getRefType().getJitCCType(); + return this; } @Override @@ -421,10 +466,25 @@ public TypeConstant getJitICType() { return this; } + @Override + public String getJitCCName(TypeSystem ts) { + return f_fNativeRebase ? getJitICName(ts) : getRefType().getJitCCName(ts); + } + + @Override + public boolean isJitL2Specialized() { + return getRefType().isJitL2Specialized(); + } + + @Override + public boolean isJitAnnotatedRef() { + return getRefType().isJitAnnotatedRef(); + } + @Override public String getJitICName(TypeSystem ts) { - ModuleLoader loader = ts.findOwnerLoader(getParentType()); - TypeConstant type = loader.typeSystem.pool().register(this); + ModuleLoader loader = ts.findOwnerLoader(getParentType()); + TypeConstant type = loader.typeSystem.pool().register(asStandardRef()); StringBuilder sbName = new StringBuilder(getProperty().getClassJitName(ts)); TypeSystem.appendJitSuffix(sbName, type.getPosition()); @@ -477,6 +537,9 @@ protected int compareDetails(Constant obj) { } n = this.m_idProp.compareTo(that.m_idProp); + if (n == 0) { + n = Boolean.compare(this.f_fNativeRebase, that.f_fNativeRebase); + } } return n; } @@ -498,6 +561,9 @@ protected void registerConstants(ConstantPool pool) { @Override protected void assemble(DataOutput out) throws IOException { + if (f_fNativeRebase) { + throw new IllegalStateException("Native property class types cannot be serialized"); + } super.assemble(out); writeMagnitude(out, m_idProp.getPosition()); @@ -508,7 +574,8 @@ protected void assemble(DataOutput out) @Override protected int computeHashCode() { return Hash.of(m_typeParent, - Hash.of(m_idProp)); + Hash.of(m_idProp, + Hash.of(f_fNativeRebase))); } // ----- data fields --------------------------------------------------------------------------- @@ -527,4 +594,9 @@ protected int computeHashCode() { * Cached property info. */ private transient PropertyInfo m_info; + + /** + * Indicates that the property type uses the native Ref/Var implementation at runtime. + */ + private final transient boolean f_fNativeRebase; } diff --git a/javatools/src/main/java/org/xvm/asm/constants/PropertyInfo.java b/javatools/src/main/java/org/xvm/asm/constants/PropertyInfo.java index 4c0f38fc19..b9f63b41cb 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/PropertyInfo.java +++ b/javatools/src/main/java/org/xvm/asm/constants/PropertyInfo.java @@ -30,6 +30,8 @@ import org.xvm.javajit.JitMethodDesc; import org.xvm.javajit.TypeSystem; +import org.xvm.javajit.builders.AnnotationHelper; + import org.xvm.util.Handy; import org.xvm.util.Severity; @@ -1385,11 +1387,20 @@ private ConstantPool pool() { // ----- JIT support --------------------------------------------------------------------------- /** - * @return true iff the JIT requires a field that stores a Ref object for this property + * @return true iff the JIT requires Ref storage for this property, on the containing object + * or in the container for a static property */ public boolean isJitInflated() { // TODO: handle Future in a later phase; keep its stored-Ref implementation for now - return containsRefAnnotation(pool().clzFuture()); + return isConstant() && isJitRefAnnotated() || + containsRefAnnotation(pool().clzFuture()); + } + + /** + * @return true iff the property contains any runtime reference annotations + */ + public boolean isJitRefAnnotated() { + return isRefAnnotated() && AnnotationHelper.hasRuntimeAnnotations(getRefAnnotations()); } /** diff --git a/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java b/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java index ddee7445f3..d7d0900458 100644 --- a/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java +++ b/javatools/src/main/java/org/xvm/asm/constants/TypeConstant.java @@ -2267,7 +2267,7 @@ private TypeInfo buildTypeInfoImpl(ErrorListener errs) { } if (typeUnderlying instanceof PropertyClassTypeConstant typePropClass) { - return typePropClass.buildTypeInfo(errs); + return typePropClass.buildPrivateInfo(errs); } // this implementation only deals with modifying (not including immutable) and terminal type @@ -7546,7 +7546,8 @@ public boolean isJitAssignableTo(TypeConstant that) { // likewise, for an annotation A into C: // Ecstasy: A --into--> C, so A.isA(C), but // Java: JCC(A) is not a subtype of JCC(C); A -> C requires a checkcast - boolean fIntoCast = Builder.isEmbedded(typeThisJit.getExplicitClassFormat()) && + boolean fIntoCast = typeThisJit.isExplicitClassIdentity(true) && + Builder.isEmbedded(typeThisJit.getExplicitClassFormat()) && typeThisJit.getExplicitClassInto(true).isA(typeThatJit); return typeThisJit.equals(typeThatJit) || !fIntoCast && @@ -7561,7 +7562,8 @@ public boolean isJitAssignableTo(TypeConstant that) { * @return true iff this type's JCC is a Java interface */ public boolean isJitCCInterface() { - return isJitImplInterface() || isDerivedVirtualChildClass(); + TypeConstant typeJit = getJitCCType(); + return typeJit.isJitImplInterface() || typeJit.isDerivedVirtualChildClass(); } /** @@ -7573,7 +7575,8 @@ public boolean isJitImplInterface() { TypeConstant typeJit = getJitCCType(); return (typeJit.isInterfaceType() || Builder.isEmbedded(typeJit.getExplicitClassFormat())) && !typeJit.isTuple() - && !typeJit.isTypeOfType(); + && !typeJit.isTypeOfType() + && !typeJit.isNativeRef(); } /** @@ -7616,8 +7619,9 @@ public JitTypeDesc getJitDesc(Builder builder) { * the corresponding type. It's the minimal (the widest) type that produces the same "JIT Call * Class Name' CC(T). * - *

The canonical type C(T) is always a {@link #isSingleUnderlyingClass single underlying - * class} that could parameterized by non-parameterized callable JIT types as parameters. + *

For class types, CC(T) is a {@link #isSingleUnderlyingClass single underlying class} that + * could be parameterized by non-parameterized callable JIT types as parameters. Property class + * types retain their property identity. * *

The following should hold : *

    diff --git a/javatools/src/main/java/org/xvm/javajit/BuildContext.java b/javatools/src/main/java/org/xvm/javajit/BuildContext.java index 443e5956eb..1bdcffd1b3 100644 --- a/javatools/src/main/java/org/xvm/javajit/BuildContext.java +++ b/javatools/src/main/java/org/xvm/javajit/BuildContext.java @@ -2487,14 +2487,12 @@ public TypeInfo getTypeInfo(TypeConstant type) { } TypeConstant publicType = thisType.removeAccess(); - if (type.equals(publicType) || type instanceof CastTypeConstant castType && + if (type.removeAccess().equals(publicType) || type instanceof CastTypeConstant castType && castType.getUnderlyingType2().removeAccess().isEquivalent(publicType)) { return typeInfo; } - assert publicType.isSingleUnderlyingClass(true); - - if (type.isSingleUnderlyingClass(true)) { + if (publicType.isSingleUnderlyingClass(true) && type.isSingleUnderlyingClass(true)) { IdentityConstant thisId = publicType.getSingleUnderlyingClass(true); IdentityConstant thatId = type.getSingleUnderlyingClass(true); @@ -2635,6 +2633,12 @@ public void buildPropertyRef(CodeBuilder code, int targetId, int propIdIndex, in RegisterInfo refReg = realizeRef(code, retId, referentType, isVar); if (propInfo.isConstant()) { + if (propInfo.isJitInflated()) { + builder.loadStaticRef(code, propInfo, ctxSlot(code)); + code.astore(refReg.slot()); + return; + } + assert !isVar; Constant initial = propInfo.getInitialValue(); diff --git a/javatools/src/main/java/org/xvm/javajit/Builder.java b/javatools/src/main/java/org/xvm/javajit/Builder.java index ce4892a75c..ad4251f277 100644 --- a/javatools/src/main/java/org/xvm/javajit/Builder.java +++ b/javatools/src/main/java/org/xvm/javajit/Builder.java @@ -138,8 +138,7 @@ public ClassDesc getSuperCD() { * @return true iff the property's Ref annotations are implemented on its containing class */ public boolean isHostedProperty(PropertyInfo property) { - return property.isRefAnnotated() && !property.isJitInflated() && - AnnotationHelper.hasRuntimeAnnotations(property.getRefAnnotations()); + return property.isJitRefAnnotated() && !property.isJitInflated(); } /** @@ -282,8 +281,8 @@ public boolean shouldGenerate(IdentityConstant id) { ? id.getClassIdentity() : id.getNamespace(); - return containerId.equals(getThisType().getSingleUnderlyingClass(true)) || - isEmbedded(containerId.getComponent().getFormat()); + IdentityConstant thisId = (IdentityConstant) getThisType().getDefiningConstant(); + return containerId.equals(thisId) || isEmbedded(containerId.getComponent().getFormat()); } /** @@ -585,6 +584,7 @@ public RegisterInfo loadConstant(BuildContext bctx, CodeBuilder code, Constant c if (singleton.getClassConstant() instanceof PropertyConstant propId) { TypeConstant ownerType = propId.getClassIdentity().getType(); PropertyInfo propInfo = propId.getPropertyInfo(ownerType); + if (!propInfo.isConstant()) { // an instance property on a runtime constant (e.g. singleton) RegisterInfo targetReg = loadConstant(bctx, code, @@ -592,10 +592,39 @@ public RegisterInfo loadConstant(BuildContext bctx, CodeBuilder code, Constant c return loadPropertyValue(code, targetReg, propId, bctx.ctxSlot(code)); } - TypeConstant propType = singleton.getType(); - JitTypeDesc jtd = propType.getJitDesc(this); - + TypeConstant propType = singleton.getType(); + JitTypeDesc jtd = propType.getJitDesc(this); RegisterInfo singletonReg = new SingleSlot(propType, jtd.flavor, jtd.cd, ""); + + if (propInfo.isJitInflated()) { + int ctxSlot = bctx == null ? code.parameterSlot(0) : bctx.ctxSlot(code); + + loadStaticRef(code, propInfo, ctxSlot); + code.aload(ctxSlot) + .invokevirtual(CD_nRef, "get", md(CD_Object, CD_Ctx)) + .checkcast(getCCDesc(propType)); + + if (jtd.flavor.isOptimized) { + if (propType.isNullable()) { + unboxNullable(code, propType, getCCDesc(propType.removeNullable())); + } else { + unbox(code, propType); + } + } + + return switch (jtd.flavor) { + case NullablePrimitive -> + new ExtendedSlot(Op.A_STACK, 0, 0, jtd.flavor, propType, jtd.cd, ""); + + case XvmPrimitive, NullableXvmPrimitive -> + new MultiSlot(jtd.flavor, propType, jtd.cd, + JitTypeDesc.getXvmPrimitiveClasses(propType)); + + default -> + singletonReg; + }; + } + if (isContainerScoped(propInfo)) { assert !jtd.flavor.isOptimized; @@ -985,14 +1014,28 @@ private RegisterInfo loadPropertyValue(CodeBuilder code, RegisterInfo targetReg, * a service; unless its declared type guarantees a const result, the value must be assumed to be * a service and initialized separately for each Container. * + * Static properties with declaration site Ref annotations retain their Ref instance and + * annotation state separately for each Container as well. + * * @return true iff the static field holds a computation handle instead of the property value */ protected boolean isContainerScoped(PropertyInfo prop) { return prop.isConstant() && - (prop.isInjected() || + (prop.isJitInflated() || prop.isInjected() || prop.getInitializer() != null && !prop.getType().isConst()); } + /** + * Load the container's shared Ref instance for an inflated static property. + */ + public void loadStaticRef(CodeBuilder code, PropertyInfo prop, int ctxSlot) { + TypeConstant ownerType = prop.getIdentity().getClassIdentity().getType(); + code.aload(ctxSlot) + .getstatic(getCCDesc(ownerType), prop.ensureJitName(typeSystem), CD_MethodHandle) + .invokevirtual(CD_Ctx, "getStatic", Ctx.MD_getStatic) + .checkcast(CD_nRef); + } + /** * Determine whether the instance value of the specified singleton type must be scoped to a * container. Singleton services are always container-specific. A singleton const is also diff --git a/javatools/src/main/java/org/xvm/javajit/TypeSystem.java b/javatools/src/main/java/org/xvm/javajit/TypeSystem.java index ebd737e926..2ad52cbd08 100644 --- a/javatools/src/main/java/org/xvm/javajit/TypeSystem.java +++ b/javatools/src/main/java/org/xvm/javajit/TypeSystem.java @@ -19,20 +19,23 @@ import org.xvm.asm.constants.IdentityConstant; import org.xvm.asm.constants.ModuleConstant; import org.xvm.asm.constants.PropertyClassTypeConstant; +import org.xvm.asm.constants.PropertyInfo; import org.xvm.asm.constants.SignatureConstant; import org.xvm.asm.constants.TypeConstant; +import org.xvm.javajit.builders.AnnotationHelper; import org.xvm.javajit.builders.CommonBuilder; import org.xvm.javajit.builders.EnumBuilder; import org.xvm.javajit.builders.EnumValueBuilder; import org.xvm.javajit.builders.EnumerationBuilder; import org.xvm.javajit.builders.ExceptionBuilder; +import org.xvm.javajit.builders.HostedPropertyRefBuilder; import org.xvm.javajit.builders.ModuleBuilder; import org.xvm.javajit.builders.PackageBuilder; -import org.xvm.javajit.builders.PropertyRefBuilder; import org.xvm.javajit.builders.PureBuilder; import org.xvm.javajit.builders.PureVirtualChildBuilder; import org.xvm.javajit.builders.RefBuilder; +import org.xvm.javajit.builders.StaticPropertyRefBuilder; import org.xvm.javajit.builders.VirtualChildBuilder; import static org.xvm.javajit.Builder.CD_Class; @@ -430,8 +433,10 @@ protected Builder ensureBuilder(Artifact art) { ConstantPool pool = pool(); TypeConstant type = art.type(); - if (type instanceof PropertyClassTypeConstant) { - return new PropertyRefBuilder(this, art); + if (art.type() instanceof PropertyClassTypeConstant propType) { + return propType.getPropertyInfo().isConstant() + ? new StaticPropertyRefBuilder(this, art) + : new HostedPropertyRefBuilder(this, art); } if (art.shape() == ClassfileShape.Pure) { @@ -569,10 +574,17 @@ public Artifact deduceArtifact(ModuleStructure module, String prefix, String suf // e.g. org.xtclang.ecstasy.numbers.Number$compare$Family$UIntegerꖛ7503 Constant constant = pool().getConstant(id); if (constant instanceof TypeConstant type) { - if (type instanceof PropertyClassTypeConstant property) { - ClassStructure struct = (ClassStructure) property.getParentType() - .getSingleUnderlyingClass(true).getComponent(); - return new Artifact(type, struct, shape, className); + if (type instanceof PropertyClassTypeConstant propType) { + ClassStructure struct = (ClassStructure) propType.getParentType(). + getSingleUnderlyingClass(true).getComponent(); + PropertyInfo prop = propType.getPropertyInfo(); + if (prop.isConstant()) { + // use the native Ref composition; retain the property's class name + assert AnnotationHelper.hasRuntimeAnnotations(prop.getRefAnnotations()); + + propType = propType.asNativeRebase(); + } + return new Artifact(propType, struct, shape, className); } // the type suffix identifies the class even when it is nested inside a method @@ -801,7 +813,7 @@ public static int getJitSuffix(String name) { */ public static String addJitSuffix(String name, int id) { assert id >= 0; - return name + HASH + String.valueOf(id); + return name + HASH + id; } /** diff --git a/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java b/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java index 2669fb57ea..3a3f3ca608 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java @@ -48,23 +48,25 @@ public class AnnotationHelper { /** * Create a helper for a type whose composition contains annotations. * - * @param builder the builder assembling the incorporating type - * @param annotations the nonempty TypeInfo annotation array, in invocation order + * @param builder the builder assembling the incorporating type + * @param annotations the nonempty TypeInfo annotation array, in invocation order + * @param isConstructionSite true iff the type has construction site annotations */ - public AnnotationHelper(CommonBuilder builder, Annotation[] annotations) { + public AnnotationHelper(CommonBuilder builder, Annotation[] annotations, boolean isConstructionSite) { assert annotations.length > 0; this.builder = builder; this.annotations = annotations; this.thisType = builder.thisType; - this.isConstructionSite = thisType.isAnnotated(); + this.isConstructionSite = isConstructionSite; TypeConstant baseType = isConstructionSite ? thisType.removeAnnotations() : builder.typeInfo.getExtends(); if (baseType == null) { baseType = thisType.isConst() - ? builder.pool().typeConstRB() : builder.pool().typeObject(); + ? builder.pool().typeConstRB() + : builder.pool().typeObject(); } this.baseType = baseType.ensureAccess(Access.PRIVATE); this.constructionSiteCount = isConstructionSite ? thisType.getAnnotations().length : 0; diff --git a/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java index d78046e49d..3b8c0645fe 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java @@ -104,16 +104,17 @@ public CommonBuilder(TypeSystem typeSystem, Artifact art) { super(typeSystem, art); TypeConstant type = art.type(); - assert type.isSingleUnderlyingClass(true) && !type.isAccessSpecified(); + assert !type.isAccessSpecified(); - this.classStruct = (ClassStructure) type.getSingleUnderlyingClass(true).getComponent(); + this.thisType = type.ensureAccess(Access.PRIVATE); + this.typeInfo = thisType.ensureTypeInfo(); + this.classStruct = typeInfo.getClassStructure(); // if the class is parameterizable, the type must be either formal or specialized // (some formal parameters resolved to XVM primitive types) - assert classStruct.isParameterized() == type.isParamsSpecified(); + assert !type.isSingleUnderlyingClass(true) || + classStruct.isParameterized() == type.isParamsSpecified(); - this.thisType = type.ensureAccess(Access.PRIVATE); - this.typeInfo = thisType.ensureTypeInfo(); this.structInfo = thisType.ensureAccess(Access.STRUCT).ensureTypeInfo(); this.thisId = classStruct.getIdentityConstant(); this.jitType = thisType.getJitCCType(); @@ -123,7 +124,8 @@ public CommonBuilder(TypeSystem typeSystem, Artifact art) { Annotation[] annotations = typeInfo.getMixinAnnotations(); this.annotated = annotations.length == 0 ? null - : new AnnotationHelper(this, annotations); + : new AnnotationHelper(this, annotations, thisType.isAnnotated()); + for (PropertyInfo prop : typeInfo.getProperties().values()) { if (isHostedProperty(prop)) { hostedProperties.put(prop.getIdentity(), new PropertyHosting(this, prop)); @@ -833,7 +835,7 @@ protected void assembleProperties(ClassBuilder classBuilder) { for (PropertyInfo prop : structInfo.getProperties().values()) { MethodConstant initializer = prop.getInitializer(); - if (!prop.hasField() && !prop.isInjected() && + if (!prop.hasField() && !prop.isInjected() && !prop.isJitInflated() && // initializers for static properties still need to be generated !(prop.isConstant() && initializer != null)) { @@ -932,6 +934,13 @@ protected void assembleField(ClassBuilder classBuilder, PropertyInfo prop, Strin if (isContainerScoped(prop)) { // the generated class can be shared by containers, so store the computation means classBuilder.withField(jitName, CD_MethodHandle, flags); + + if (prop.isJitInflated()) { + assert prop.isConstant(); + // generate the custom Ref class initializer; it will be linked to the MethodHandle + // by assembleCLInit() + assembleStaticRefInitializer(classBuilder, prop); + } return; } @@ -1167,12 +1176,22 @@ protected void assembleCLInit(ClassBuilder classBuilder) { if (isContainerScoped(prop)) { // store the initializer as a container-independent computation; its result can // be a service and therefore cannot be shared across containers using this class - MethodConstant initId = prop.getInitializer(); - String initName = initId.ensureJitMethodName(ts); - MethodBody body = new MethodBody((MethodStructure) initId.getComponent()); - JitMethodDesc jmd = body.getJitDesc(this, thisType); + MethodConstant initId = prop.getInitializer(); + MethodTypeDesc initMD; + String initName; + + if (prop.isJitInflated()) { + assert prop.isConstant(); - code.ldc(MethodHandleDesc.ofMethod(Kind.STATIC, CD_this, initName, jmd.standardMD)) + initMD = md(CD_nRef, CD_Ctx); + initName = jitName + "$ref"; + } else { + MethodBody body = new MethodBody((MethodStructure) initId.getComponent()); + initMD = body.getJitDesc(this, thisType).standardMD; + initName = initId.ensureJitMethodName(ts); + } + + code.ldc(MethodHandleDesc.ofMethod(Kind.STATIC, CD_this, initName, initMD)) .invokestatic(CD_Container, "createInitializerHandle", md(CD_MethodHandle, CD_MethodHandle)) .putstatic(CD_this, jitName, CD_MethodHandle); @@ -1632,6 +1651,23 @@ protected void initializeInflatedField(CodeBuilder code, PropertyInfo prop, int code.putfield(art.CD(), prop.ensureJitName(typeSystem), CD_nRef); } + /** + * Assemble the container-scoped factory for a static property's Ref implementation. + */ + protected void assembleStaticRefInitializer(ClassBuilder classBuilder, PropertyInfo prop) { + TypeConstant refType = pool().ensurePropertyClassTypeConstant( + thisType.removeAccess(), prop.getIdentity()); + ClassDesc refCD = getICDesc(refType); + + classBuilder.withMethodBody(prop.ensureJitName(typeSystem) + "$ref", md(CD_nRef, CD_Ctx), + ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, code -> { + code.aload(code.parameterSlot(0)); + loadTypeConstant(code, refType); + code.invokestatic(refCD, NEW, md(refCD, CD_Ctx, CD_TypeConstant)) + .areturn(); + }); + } + /** * @return the property's native Ref/Var type, retaining runtime Ref annotations */ @@ -2010,8 +2046,7 @@ protected void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo pro generateTrivialSetter(classBuilder, prop, prop.ensureSetterJitMethodName(typeSystem)); } - private void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo prop, - String setterName) { + private void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo prop, String setterName) { String jitFieldName = prop.ensureJitName(typeSystem); ClassDesc CD_this = art.CD(); JitMethodDesc jmd = prop.getSetterJitDesc(this, thisType); @@ -2024,15 +2059,15 @@ private void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo prop, flags |= ClassFile.ACC_STATIC; } classBuilder.withMethodBody(jitName, md, flags, code -> { - int ctxSlot = code.parameterSlot(isOpt ? jmd.optimizedCtx() : jmd.standardCtx()); - String propName = getThisType().getSingleUnderlyingClass(true).getName() + - '.' + prop.getName(); + int ctxSlot = code.parameterSlot(isOpt ? jmd.optimizedCtx() : jmd.standardCtx()); // skip the check for Unassigned annotations // TODO: Lazy's exemption needs one-time assignment and concurrency checks - // once services/fibers are implemented + // once services/fibers are implemented if (!prop.isJitPotentiallyUnassigned()) { if (getThisType().isConst() || prop.isConstant()) { + String propName = ((IdentityConstant) thisType.getDefiningConstant()).getName() + + '.' + prop.getName(); throwReadOnly(code, propName, ctxSlot); return; } @@ -2111,11 +2146,11 @@ private void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo prop, } if (prop.isConstant()) { code.iload(argSlot) - .putstatic(CD_this, jitFieldName + EXT, CD_boolean); + .putstatic(CD_this, jitFieldName + EXT, CD_boolean); } else { code.aload(0) - .iload(argSlot) - .putfield(CD_this, jitFieldName + EXT, CD_boolean); + .iload(argSlot) + .putfield(CD_this, jitFieldName + EXT, CD_boolean); } break; @@ -2126,8 +2161,8 @@ private void generateTrivialSetter(ClassBuilder classBuilder, PropertyInfo prop, JitParamDesc pdStd = jmd.standardParams[0]; if (prop.isConstant()) { - code.aload(argSlot); - code.putstatic(CD_this, jitFieldName, pdStd.cd); + code.aload(argSlot) + .putstatic(CD_this, jitFieldName, pdStd.cd); } else { code.aload(0) .aload(argSlot) diff --git a/javatools/src/main/java/org/xvm/javajit/builders/PropertyRefBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/HostedPropertyRefBuilder.java similarity index 96% rename from javatools/src/main/java/org/xvm/javajit/builders/PropertyRefBuilder.java rename to javatools/src/main/java/org/xvm/javajit/builders/HostedPropertyRefBuilder.java index 3700a49b80..cae9804d29 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/PropertyRefBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/HostedPropertyRefBuilder.java @@ -39,14 +39,11 @@ /** * Builds a reference view that routes property operations to the containing object. */ -public class PropertyRefBuilder extends Builder { - public PropertyRefBuilder(TypeSystem typeSystem, Artifact art) { +public class HostedPropertyRefBuilder extends Builder { + public HostedPropertyRefBuilder(TypeSystem typeSystem, Artifact art) { super(typeSystem, art); - propertyType = (PropertyClassTypeConstant) art.type(); } - private final PropertyClassTypeConstant propertyType; - @Override public ClassDesc getSuperCD() { return CD_nRefProp; @@ -54,8 +51,7 @@ public ClassDesc getSuperCD() { @Override public void build(ClassBuilder classBuilder) { - classBuilder.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_SUPER) - .withSuperclass(CD_nRefProp); + PropertyClassTypeConstant propertyType = (PropertyClassTypeConstant) art.type(); PropertyInfo property = propertyType.getPropertyInfo(); PropertyConstant propId = property.getIdentity(); @@ -70,7 +66,10 @@ public void build(ClassBuilder classBuilder) { AnnotationHelper.filterAnnotations(property.getBaseRefType()).getAnnotations()) { interfaces.add(getCCDesc(annotation.getAnnotationType())); } - classBuilder.withInterfaceSymbols(interfaces); + + classBuilder.withFlags(ClassFile.ACC_PUBLIC | ClassFile.ACC_SUPER) + .withSuperclass(CD_nRefProp) + .withInterfaceSymbols(interfaces); MethodTypeDesc init = md(CD_void, CD_Ctx, CD_TypeConstant, CD_boolean, CD_nObject, CD_MethodHandle, CD_MethodHandle, CD_MethodHandle); diff --git a/javatools/src/main/java/org/xvm/javajit/builders/RefBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/RefBuilder.java index 69bb709672..499f523b6d 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/RefBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/RefBuilder.java @@ -39,7 +39,7 @@ public class RefBuilder extends CommonBuilder { public RefBuilder(TypeSystem typeSystem, Artifact art) { super(typeSystem, art); - assert thisType.isJitAnnotatedRef(); + assert jitType.isJitAnnotatedRef(); } @Override diff --git a/javatools/src/main/java/org/xvm/javajit/builders/StaticPropertyRefBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/StaticPropertyRefBuilder.java new file mode 100644 index 0000000000..278b597137 --- /dev/null +++ b/javatools/src/main/java/org/xvm/javajit/builders/StaticPropertyRefBuilder.java @@ -0,0 +1,52 @@ +package org.xvm.javajit.builders; + +import java.lang.classfile.CodeBuilder; + +import org.xvm.asm.constants.PropertyClassTypeConstant; +import org.xvm.asm.constants.PropertyInfo; +import org.xvm.asm.constants.TypeConstant; + +import org.xvm.javajit.TypeSystem; +import org.xvm.javajit.TypeSystem.Artifact; + +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.INIT_NAME; + +/** + * Builds self-contained annotated static properties, with storage and methods on the Ref itself. + */ +public class StaticPropertyRefBuilder extends RefBuilder { + public StaticPropertyRefBuilder(TypeSystem typeSystem, Artifact art) { + super(typeSystem, art); + + this.propertyType = (PropertyClassTypeConstant) art.type(); + } + + private final PropertyClassTypeConstant propertyType; + + @Override + public TypeConstant getSuperType() { + // all annotation bodies belong here; the superclass supplies only native storage + return propertyType.getRefType().removeAnnotations(); + } + + @Override + protected void callSuperInitializer(CodeBuilder code) { + PropertyInfo prop = propertyType.getPropertyInfo(); + + // this Ref owns the static property's value and annotation state; its get/set methods use + // this storage, so initialize nRef with its value-backed constructor leaving the referent + // unassigned; it will be set by annotation constructors or later annotation operations + // (e.g. Lazy.get() calling set(calc()) on the first read) + + // super(ctx, null, referentType, isVar); + code.aload(0) + .aload(code.parameterSlot(0)) + .aconst_null(); + loadTypeConstant(code, prop.getType()); + loadBoolean(code, prop.isVar()); + code.invokespecial(CD_nRef, INIT_NAME, + md(CD_void, CD_Ctx, CD_nObject, CD_TypeConstant, CD_boolean)); + } +} diff --git a/manualTests/src/main/x/jit/jit_tests/basic/propertyInitTests.x b/manualTests/src/main/x/jit/jit_tests/basic/propertyInitTests.x index 0c77d36a3f..b253a02c94 100644 --- a/manualTests/src/main/x/jit/jit_tests/basic/propertyInitTests.x +++ b/manualTests/src/main/x/jit/jit_tests/basic/propertyInitTests.x @@ -231,17 +231,23 @@ package propertyInitTests { Var asNullableVar(Object value) = value.as(Var); } - @Lazy Int lazyInstance.calc() = 42; - // TODO: static annotated properties need shared annotation storage and initialization support -// static @Lazy Int lazyStatic.calc() = 42; + @Lazy Int lazyInstance { + @Override Int calc() = compute(); + Int compute() = 42; + } + + static @Lazy Int lazyStatic { + @Override Int calc() = compute(); + Int compute() = 42; + } void testLazyProperty() { assert !&lazyInstance.assigned; assert lazyInstance == 42; assert &lazyInstance.assigned; -// assert !&lazyStatic.assigned; -// assert lazyStatic == 42; -// assert &lazyStatic.assigned; + assert !&lazyStatic.assigned; + assert lazyStatic == 42; + assert &lazyStatic.assigned; const Point(Int x, Int y) { @Lazy Int hypo.calc() = x*x + y*y; From 6e3b8ea747f861bff9d5f3fcb158879010808870 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Sat, 14 Nov 2026 10:51:18 -0500 Subject: [PATCH 16/21] Add missing native method names --- .../java/org/xvm/javajit/NativeNames.java | 83 ++++++++++--------- .../xtclang/_native/mgmt/nMainInjector.java | 3 - 2 files changed, 42 insertions(+), 44 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/NativeNames.java b/javatools/src/main/java/org/xvm/javajit/NativeNames.java index 09354427a1..1076088b93 100644 --- a/javatools/src/main/java/org/xvm/javajit/NativeNames.java +++ b/javatools/src/main/java/org/xvm/javajit/NativeNames.java @@ -70,35 +70,37 @@ public class NativeNames { reservedMethodName.put("numbers.Random/float32/0", "float32"); reservedMethodName.put("numbers.Random/float64/0", "float64"); - reservedMethodName.put("collections.Array/add/1", "add"); - reservedMethodName.put("collections.Array/addAll/1", "addAll"); - reservedMethodName.put("collections.Array/delete/1", "delete"); - reservedMethodName.put("collections.Array/elementAt/1", "elementAt"); - reservedMethodName.put("collections.Array/getElement/1", "getElement"); - reservedMethodName.put("collections.Array/insert/2", "insert"); - reservedMethodName.put("collections.Array/insertAll/2", "insertAll"); - reservedMethodName.put("collections.Array/reify/1", "reify"); - reservedMethodName.put("collections.Array/removeAll/1", "removeAll"); - reservedMethodName.put("collections.Array/slice/1", "slice"); + reservedMethodName.put("collections.Array/add/1", "add"); + reservedMethodName.put("collections.Array/addAll/1", "addAll"); + reservedMethodName.put("collections.Array/delete/1", "delete"); + reservedMethodName.put("collections.Array/elementAt/1", "elementAt"); + reservedMethodName.put("collections.Array/getElement/1", "getElement"); + reservedMethodName.put("collections.Array/insert/2", "insert"); + reservedMethodName.put("collections.Array/insertAll/2", "insertAll"); + reservedMethodName.put("collections.Array/makeImmutable/0", "makeImmutable"); + reservedMethodName.put("collections.Array/reify/1", "reify"); + reservedMethodName.put("collections.Array/removeAll/1", "removeAll"); + reservedMethodName.put("collections.Array/slice/1", "slice"); reservedMethodName.put("collections.Array.FreezableArray/freeze/1", "freeze"); - reservedMethodName.put("collections.Collection/reify/0", "reify"); - reservedMethodName.put("collections.Hashable/hashCode/2", "hashCode"); - reservedMethodName.put("collections.HashCollector/compute/0", "compute"); - reservedMethodName.put("collections.HashCollector/reset/0", "reset"); - reservedMethodName.put("collections.Tuple/add/2", "add"); - reservedMethodName.put("collections.Tuple/addAll/1", "addAll"); - reservedMethodName.put("collections.Tuple/elementAt/1", "elementAt"); - reservedMethodName.put("collections.Tuple/equals/2", "equals"); - reservedMethodName.put("collections.Tuple/freeze/1", "freeze"); - reservedMethodName.put("collections.Tuple/getElement/1", "getElement"); - reservedMethodName.put("collections.Tuple/remove/1", "remove"); - reservedMethodName.put("collections.Tuple/removeAll/1", "removeAll"); - reservedMethodName.put("collections.Tuple/replace/2", "replace"); - reservedMethodName.put("collections.Tuple/slice/1", "slice"); - - reservedMethodName.put("collections.UniformIndexed/getElement/1", "getElement"); - reservedMethodName.put("Range/getElement/1", "getElement"); - reservedMethodName.put("text.String/getElement/1", "getElement"); + reservedMethodName.put("collections.Collection/reify/0", "reify"); + reservedMethodName.put("collections.Hashable/hashCode/2", "hashCode"); + reservedMethodName.put("collections.HashCollector/compute/0", "compute"); + reservedMethodName.put("collections.HashCollector/reset/0", "reset"); + reservedMethodName.put("collections.Tuple/add/2", "add"); + reservedMethodName.put("collections.Tuple/addAll/1", "addAll"); + reservedMethodName.put("collections.Tuple/elementAt/1", "elementAt"); + reservedMethodName.put("collections.Tuple/equals/2", "equals"); + reservedMethodName.put("collections.Tuple/freeze/1", "freeze"); + reservedMethodName.put("collections.Tuple/getElement/1", "getElement"); + reservedMethodName.put("collections.Tuple/remove/1", "remove"); + reservedMethodName.put("collections.Tuple/removeAll/1", "removeAll"); + reservedMethodName.put("collections.Tuple/replace/2", "replace"); + reservedMethodName.put("collections.Tuple/slice/1", "slice"); + reservedMethodName.put("collections.UniformIndexed/getElement/1", "getElement"); + + reservedMethodName.put("Range/getElement/1", "getElement"); + reservedMethodName.put("text.Destringable/construct/1", "construct"); + reservedMethodName.put("text.String/getElement/1", "getElement"); reservedMethodName.put("numbers.Number/toInt8/2", "toInt8$FP"); reservedMethodName.put("numbers.Number/toInt16/2", "toInt16$FP"); @@ -175,19 +177,18 @@ public class NativeNames { // JavaTools Bridge _native types - reservedMethodName.put("fs.OSStorage/createDir/1", "createDir"); - reservedMethodName.put("fs.OSStorage/createFile/1", "createFile"); - reservedMethodName.put("fs.OSStorage/delete/1", "delete"); - reservedMethodName.put("fs.OSStorage/find/2", "find"); - reservedMethodName.put("fs.OSFileStore/dirFor/1", "dirFor"); - reservedMethodName.put("fs.OSFileStore/fileFor/1", "fileFor"); - reservedMethodName.put("fs.OSStorage/instance/0", "instance"); - reservedMethodName.put("fs.OSStorage/names/1", "names"); - reservedMethodName.put("fs.OSStorage/unwatch/1", "unwatch"); - reservedMethodName.put("fs.OSStorage/watch/1", "watch"); - reservedMethodName.put("fs.OSFileStore/copyOrMove/5", "copyOrMove"); - reservedMethodName.put("fs.OSFileStore/linkAsFile/1", "linkAsFile"); - + reservedMethodName.put("fs.OSStorage/createDir/1", "createDir"); + reservedMethodName.put("fs.OSStorage/createFile/1", "createFile"); + reservedMethodName.put("fs.OSStorage/delete/1", "delete"); + reservedMethodName.put("fs.OSStorage/find/2", "find"); + reservedMethodName.put("fs.OSFileStore/dirFor/1", "dirFor"); + reservedMethodName.put("fs.OSFileStore/fileFor/1", "fileFor"); + reservedMethodName.put("fs.OSStorage/instance/0", "instance"); + reservedMethodName.put("fs.OSStorage/names/1", "names"); + reservedMethodName.put("fs.OSStorage/unwatch/1", "unwatch"); + reservedMethodName.put("fs.OSStorage/watch/1", "watch"); + reservedMethodName.put("fs.OSFileStore/copyOrMove/5", "copyOrMove"); + reservedMethodName.put("fs.OSFileStore/linkAsFile/1", "linkAsFile"); reservedMethodName.put("fs.OSDirectory/dirs/0", "dirs"); reservedMethodName.put("fs.OSDirectory/files/0", "files"); reservedMethodName.put("fs.OSDirectory/filesRecursively/0", "filesRecursively"); diff --git a/javatools_jitbridge/src/main/java/org/xtclang/_native/mgmt/nMainInjector.java b/javatools_jitbridge/src/main/java/org/xtclang/_native/mgmt/nMainInjector.java index 31b33ab2f1..65fbb8c378 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/_native/mgmt/nMainInjector.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/_native/mgmt/nMainInjector.java @@ -18,8 +18,6 @@ import org.xtclang.ecstasy.Exception; import org.xtclang.ecstasy.Nullable; -import org.xtclang.ecstasy.text.String; - import org.xvm.asm.ConstantPool; import org.xvm.asm.constants.TypeConstant; @@ -89,7 +87,6 @@ public void addNativeResources() { ConstantPool pool = xvm.ecstasyPool; TypeConstant consoleType = pool.ensureEcstasyTypeConstant("io.Console"); - java.lang.Class temporaryLoadStringClassToPrimeConstTypeInfo = String.class; suppliers.put(new Resource(consoleType, "console"), TerminalConsole::$create); TypeConstant randomType = pool.ensureEcstasyTypeConstant("numbers.Random"); From 3ce41f2c193b94f0ab0f1bdf646de4e8a159eb1e Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Sun, 15 Nov 2026 12:55:44 -0500 Subject: [PATCH 17/21] Add JMD.asDetached() helper --- javatools/src/main/java/org/xvm/asm/OpCallable.java | 4 ++-- .../src/main/java/org/xvm/asm/OpInvocable.java | 2 +- .../src/main/java/org/xvm/javajit/BuildContext.java | 4 ++-- .../src/main/java/org/xvm/javajit/JitCtorDesc.java | 2 +- .../java/org/xvm/javajit/JitDetachedBodyDesc.java | 6 +----- .../main/java/org/xvm/javajit/JitMethodDesc.java | 13 ++++++++++--- .../xvm/javajit/builders/VirtualChildBuilder.java | 4 ++-- 7 files changed, 19 insertions(+), 16 deletions(-) diff --git a/javatools/src/main/java/org/xvm/asm/OpCallable.java b/javatools/src/main/java/org/xvm/asm/OpCallable.java index db7b012db3..ccc1d79a44 100644 --- a/javatools/src/main/java/org/xvm/asm/OpCallable.java +++ b/javatools/src/main/java/org/xvm/asm/OpCallable.java @@ -824,7 +824,7 @@ protected int buildCall(BuildContext bctx, CodeBuilder code, int[] anArgValue) { boolean fTuple = isTupleReturn(); if (fTuple) { - jmdCall = jmdCall.standardOnly(); + jmdCall = jmdCall.asStandardOnly(); } int[] anRet = isMultiReturn() @@ -888,7 +888,7 @@ protected int buildCall(BuildContext bctx, CodeBuilder code, int[] anArgValue) { } if (isTupleReturn()) { - jmdCall = jmdCall.standardOnly(); + jmdCall = jmdCall.asStandardOnly(); } MethodTypeDesc mdCall; diff --git a/javatools/src/main/java/org/xvm/asm/OpInvocable.java b/javatools/src/main/java/org/xvm/asm/OpInvocable.java index 929ec820f6..ad873a270b 100644 --- a/javatools/src/main/java/org/xvm/asm/OpInvocable.java +++ b/javatools/src/main/java/org/xvm/asm/OpInvocable.java @@ -502,7 +502,7 @@ private void buildSingleInvoke(BuildContext bctx, CodeBuilder code, ClassDesc cd cdInvoke = bctx.builder.getCCDesc(typeInvoke); fUnboxed = false; } - jmd = jmd.standardOnly(); + jmd = jmd.asStandardOnly(); } boolean fOptimized = jmd.isOptimized; diff --git a/javatools/src/main/java/org/xvm/javajit/BuildContext.java b/javatools/src/main/java/org/xvm/javajit/BuildContext.java index 1bdcffd1b3..5165416a23 100644 --- a/javatools/src/main/java/org/xvm/javajit/BuildContext.java +++ b/javatools/src/main/java/org/xvm/javajit/BuildContext.java @@ -233,7 +233,7 @@ private BuildContext(BuildContext bctx, String jitName, int callDepth) { this.methodStruct = body.getMethodStructure(); this.callDepth = callDepth; this.methodDesc = bctx.methodDesc instanceof JitDetachedBodyDesc detached - ? new JitDetachedBodyDesc(jmd, detached.receiverCD) : jmd; + ? jmd.asDetached(detached.receiverCD) : jmd; this.methodJitName = jitName; this.isStatic = bctx.isStatic; this.isConstructor = bctx.isConstructor; @@ -3649,7 +3649,7 @@ public void buildMethod(String jitName, MethodBody body) { if (methodDesc instanceof JitDetachedBodyDesc detached && !body.getMethodStructure().isStatic()) { // nested methods must accept the same interface receiver as their enclosing body - jmd = new JitDetachedBodyDesc(jmd, detached.receiverCD); + jmd = jmd.asDetached(detached.receiverCD); jitName = DetachedBody + jitName; } deferAssembly(new BuildContext(this, jitName, body, jmd)); diff --git a/javatools/src/main/java/org/xvm/javajit/JitCtorDesc.java b/javatools/src/main/java/org/xvm/javajit/JitCtorDesc.java index 620995c827..997e35e101 100644 --- a/javatools/src/main/java/org/xvm/javajit/JitCtorDesc.java +++ b/javatools/src/main/java/org/xvm/javajit/JitCtorDesc.java @@ -86,7 +86,7 @@ protected int fillExtraClassDesc(ClassDesc[] paramCDs, int ix) { } @Override - public JitCtorDesc standardOnly() { + public JitCtorDesc asStandardOnly() { return isOptimized ? new JitCtorDesc(typeTarget, targetCD, addCtorCtx, addType, addOuter, standardReturns, standardParams, null, null) diff --git a/javatools/src/main/java/org/xvm/javajit/JitDetachedBodyDesc.java b/javatools/src/main/java/org/xvm/javajit/JitDetachedBodyDesc.java index 870cc1529c..a3461d5373 100644 --- a/javatools/src/main/java/org/xvm/javajit/JitDetachedBodyDesc.java +++ b/javatools/src/main/java/org/xvm/javajit/JitDetachedBodyDesc.java @@ -28,11 +28,7 @@ public class JitDetachedBodyDesc extends JitMethodDesc { * @param method the logical Ecstasy instance-method descriptor * @param receiverCD the leading receiver of the detached body */ - public JitDetachedBodyDesc(JitMethodDesc method, ClassDesc receiverCD) { - this(method, receiverCD, false); - } - - private JitDetachedBodyDesc(JitMethodDesc method, ClassDesc receiverCD, boolean isStatic) { + protected JitDetachedBodyDesc(JitMethodDesc method, ClassDesc receiverCD, boolean isStatic) { this.receiverCD = receiverCD; super(method.typeTarget, method.standardReturns, method.standardParams, method.optimizedReturns, method.optimizedParams, isStatic); diff --git a/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java b/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java index 36d402d212..57b8c7ac43 100644 --- a/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java +++ b/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java @@ -224,13 +224,20 @@ private static JitParamDesc[] select(JitParamDesc[] descs, int[] indexes) { /** * Obtain a descriptor that uses only the standard calling convention. */ - public JitMethodDesc standardOnly() { + public JitMethodDesc asStandardOnly() { return isOptimized ? new JitMethodDesc(typeTarget, standardReturns, standardParams, null, null, isStandardStatic) : this; } + /** + * Obtain a detached-body descriptor with the specified explicit receiver. + */ + public JitDetachedBodyDesc asDetached(ClassDesc receiverCD) { + return new JitDetachedBodyDesc(this, receiverCD, false); + } + protected MethodTypeDesc computeMethodDesc(JitParamDesc[] returns, JitParamDesc[] params) { int extraCount = getImplicitParamCount(); int paramCount = params.length; @@ -376,7 +383,7 @@ public static JitMethodDesc of( optParamList.add( new JitParamDesc(type, optFlavor, CD_boolean, iOrig, iOpt++, true)); } - } else if ((cd = JitTypeDesc.getNullableXvmPrimitiveClass(type)) != null) { + } else if ((JitTypeDesc.getNullableXvmPrimitiveClass(type)) != null) { assert type.isNullable(); if (iOrig >= 0) { @@ -463,7 +470,7 @@ public static JitMethodDesc of( for (ClassDesc cdArg : JitTypeDesc.getXvmPrimitiveClasses(type)) { optParamList.add(new JitParamDesc(type, XvmPrimitive, cdArg, iOrig, ixLong++, false)); } - } else if ((cd = JitTypeDesc.getNullableXvmPrimitiveClass(type)) != null) { + } else if ((JitTypeDesc.getNullableXvmPrimitiveClass(type)) != null) { isOptimized = true; stdParamList.add(new JitParamDesc(type, Widened, CD_nObject, iOrig, ixStdObj++, false)); diff --git a/javatools/src/main/java/org/xvm/javajit/builders/VirtualChildBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/VirtualChildBuilder.java index 9676073ae8..44c758a9d4 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/VirtualChildBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/VirtualChildBuilder.java @@ -387,7 +387,7 @@ private void assemblePropertyBody(ClassBuilder classBuilder, PropertyInfo prop, } JitCallDesc jcd = resolveChildCall(body, thisType); - JitDetachedBodyDesc jmd = new JitDetachedBodyDesc(jcd.jmd(), jcd.receiverCD()); + JitDetachedBodyDesc jmd = jcd.jmd().asDetached(jcd.receiverCD()); if (jmd.isOptimized) { assembleMethodWrapper(classBuilder, jcd.name(), jmd.staticWrapper()); @@ -733,7 +733,7 @@ private void assembleDetachedBody(ClassBuilder classBuilder, MethodInfo method, } JitCallDesc call = resolveChildMethodCall(this, body, thisType); - JitDetachedBodyDesc bodyJmd = new JitDetachedBodyDesc(call.jmd(), call.receiverCD()); + JitDetachedBodyDesc bodyJmd = call.jmd().asDetached(call.receiverCD()); String bodyName = call.name(); BuildContext bctx = new BuildContext(this, typeInfo, method, bodyJmd, depth); From b6b9fee1c9bf0ed90d90c3f610450c33c1b5d644 Mon Sep 17 00:00:00 2001 From: Jonathan Knight Date: Mon, 16 Nov 2026 13:21:13 +0300 Subject: [PATCH 18/21] Fix native code for IntN and UIntN magnitude property getter method --- .../org/xtclang/ecstasy/numbers/IntN.java | 10 +-- .../org/xtclang/ecstasy/numbers/UIntN.java | 10 +-- .../main/x/jit/jit_tests/numbers/IntNTests.x | 77 +++++++++---------- 3 files changed, 38 insertions(+), 59 deletions(-) diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/IntN.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/IntN.java index d5e3b0e479..24310c1b30 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/IntN.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/IntN.java @@ -135,14 +135,6 @@ public static Boolean range(Ctx ctx) { return bitLength == 0 ? 8 : ((bitLength + 7L) / 8L) * 8L; } - /** - * The native implementation of: - * IntNumber bitCount.get() - */ - public UIntN magnitude$get$p(Ctx ctx) { - return abs(ctx).toUIntN(ctx); - } - /** * The primitive implementation of: * Int byteLength.get() @@ -251,7 +243,7 @@ public IntN pow(Ctx ctx, IntN n) { * The native implementation of: * UIntN magnitude.get() */ - public UIntN magnitude$get(Ctx ctx) { + public Number magnitude$get(Ctx ctx) { return UIntN.$box($value.abs()); } diff --git a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/UIntN.java b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/UIntN.java index 6d751edf3c..18e5647e37 100644 --- a/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/UIntN.java +++ b/javatools_jitbridge/src/main/java/org/xtclang/ecstasy/numbers/UIntN.java @@ -240,7 +240,7 @@ public UIntN pow(Ctx ctx, UIntN n) { * The native implementation of: * UIntN magnitude.get() */ - public UIntN magnitude$get(Ctx ctx) { + public Number magnitude$get(Ctx ctx) { return this; } @@ -309,14 +309,6 @@ public UIntN pow(Ctx ctx, UIntN n) { return $value.bitCount(); } - /** - * The native implementation of: - * IntNumber bitCount.get() - */ - public UIntN magnitude$get$p(Ctx ctx) { - return this; - } - /** * The native implementation of: * IntNumber and(UIntN n); diff --git a/manualTests/src/main/x/jit/jit_tests/numbers/IntNTests.x b/manualTests/src/main/x/jit/jit_tests/numbers/IntNTests.x index 8874b77e7e..a5315d3215 100644 --- a/manualTests/src/main/x/jit/jit_tests/numbers/IntNTests.x +++ b/manualTests/src/main/x/jit/jit_tests/numbers/IntNTests.x @@ -1074,13 +1074,12 @@ class IntNTests { } void testMagnitude() { -// TODO fix IntN.magnitude -// IntN n = 0; -// assert n.magnitude == 0; -// n = 100; -// assert n.magnitude == 100; -// n = -100; -// assert n.magnitude == 100; + IntN n = 0; + assert n.magnitude == 0; + n = 100; + assert n.magnitude == 100; + n = -100; + assert n.magnitude == 100; } // ----- As Number tests ----------------------------------------------------------------------- @@ -1325,26 +1324,24 @@ class IntNTests { } void testMagnitudeAsNumber() { -// TODO fix IntN.magnitude -// IntN n1 = 0; -// Number n2 = getNumberMagnitude(n1); -// assert n2.is(UIntN); -// assert n2 == 0; -// -// n1 = 100; -// n2 = getNumberMagnitude(n1); -// assert n2.is(UIntN); -// assert n2 == 100; -// -// n1 = -100; -// n2 = getNumberMagnitude(n1); -// assert n2.is(UIntN); -// assert n2 == 100; + IntN n1 = 0; + Number n2 = getNumberMagnitude(n1); + assert n2.is(UIntN); + assert n2 == 0; + + n1 = 100; + n2 = getNumberMagnitude(n1); + assert n2.is(UIntN); + assert n2 == 100; + + n1 = -100; + n2 = getNumberMagnitude(n1); + assert n2.is(UIntN); + assert n2 == 100; } Number getNumberMagnitude(Number n) { - TODO fix IntN.magnitude -// return n.magnitude; + return n.magnitude; } // ----- As IntNumber tests -------------------------------------------------------------------- @@ -1805,26 +1802,24 @@ class IntNTests { } void testMagnitudeAsIntNumber() { -// TODO fix IntN.magnitude -// IntN n1 = 0; -// IntNumber n2 = getIntNumberMagnitude(n1); -// assert n2.is(UIntN); -// assert n2 == 0; -// -// n1 = 100; -// n2 = getIntNumberMagnitude(n1); -// assert n2.is(UIntN); -// assert n2 == 100; -// -// n1 = -100; -// n2 = getIntNumberMagnitude(n1); -// assert n2.is(UIntN); -// assert n2 == 100; + IntN n1 = 0; + IntNumber n2 = getIntNumberMagnitude(n1); + assert n2.is(UIntN); + assert n2 == 0; + + n1 = 100; + n2 = getIntNumberMagnitude(n1); + assert n2.is(UIntN); + assert n2 == 100; + + n1 = -100; + n2 = getIntNumberMagnitude(n1); + assert n2.is(UIntN); + assert n2 == 100; } IntNumber getIntNumberMagnitude(IntNumber n) { - TODO fix IntN.magnitude -// return n.magnitude; + return n.magnitude; } // ----- As Sequential tests ------------------------------------------------------------------- From 91bc9c9bc3a505580f36012bb620a5727f142282 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Mon, 16 Nov 2026 09:52:33 -0500 Subject: [PATCH 19/21] Simplify StringHelper --- .../java/org/xvm/javajit/BuildContext.java | 75 ++++--------------- .../java/org/xvm/javajit/TextSupport.java | 43 +++++++++-- 2 files changed, 51 insertions(+), 67 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/BuildContext.java b/javatools/src/main/java/org/xvm/javajit/BuildContext.java index 5165416a23..04a3cb8a4f 100644 --- a/javatools/src/main/java/org/xvm/javajit/BuildContext.java +++ b/javatools/src/main/java/org/xvm/javajit/BuildContext.java @@ -7,7 +7,6 @@ import java.lang.constant.ClassDesc; import java.lang.constant.DirectMethodHandleDesc; import java.lang.constant.DirectMethodHandleDesc.Kind; -import java.lang.constant.DynamicCallSiteDesc; import java.lang.constant.MethodHandleDesc; import java.lang.constant.MethodTypeDesc; @@ -81,12 +80,7 @@ import org.xvm.javajit.registers.Ref; import org.xvm.javajit.registers.SingleSlot; -import static java.lang.constant.ConstantDescs.CD_CallSite; import static java.lang.constant.ConstantDescs.CD_MethodHandle; -import static java.lang.constant.ConstantDescs.CD_MethodHandles_Lookup; -import static java.lang.constant.ConstantDescs.CD_MethodType; -import static java.lang.constant.ConstantDescs.CD_Object; -import static java.lang.constant.ConstantDescs.CD_String; import static java.lang.constant.ConstantDescs.CD_boolean; import static java.lang.constant.ConstantDescs.CD_void; import static java.lang.constant.ConstantDescs.INIT_NAME; @@ -446,12 +440,12 @@ public void preprocess(CodeBuilder code, Op[] ops) { Deque> jumpAddrStack = new ArrayDeque<>(); Deque> jumpDestStack = new ArrayDeque<>(); - int guardAddr = -1; // the address of the last GuardAll op - int finAddr = -1; // the address of the last FinallyEnd op - List jumpsAddr = new ArrayList<>(); // the addresses of Jump ops - List jumpsDest = new ArrayList<>(); // the addresses of jump destinations - Map refs = null; // the ids of registers that need to be boxed as Refs - boolean doReturn = false; // indicates whether FinallyEnd should generate returns + int guardAddr = -1; // the address of the last GuardAll op + int finAddr = -1; // the address of the last FinallyEnd op + List jumpsAddr = new ArrayList<>(); // the addresses of Jump ops + List jumpsDest = new ArrayList<>(); // the addresses of jump destinations + Map refs = null; // the ids of registers that need to be boxed as Refs + boolean doReturn = false; // indicates whether FinallyEnd should generate returns for (int iPC = 0, opsCount = ops.length; iPC < opsCount; iPC++) { Op op = ops[currOpAddr = iPC]; switch (op) { @@ -813,10 +807,10 @@ public void enterMethod(CodeBuilder code) { type = thisType; slot = code.parameterSlot(0); } else { - param = methodStruct.getParam(varIndex); - name = param.getName(); - type = resolveSpecialized(param.getType()); - slot = code.parameterSlot(extraArgs + i); // compensate for implicits + param = methodStruct.getParam(varIndex); + name = param.getName(); + type = resolveSpecialized(param.getType()); + slot = code.parameterSlot(extraArgs + i); // compensate for implicits } if (debugInfo) { @@ -2087,8 +2081,8 @@ public RegisterInfo introduceRef(CodeBuilder code, int regId, TypeConstant type, Constant[] params = anno.getParams(); int paramCount = params.length; - Constant nameConst = paramCount > 0 ? params[0] : null; - Constant optsConst = paramCount > 1 ? params[1] : null; + Constant nameConst = paramCount > 0 ? params[0] : null; + Constant optsConst = paramCount > 1 ? params[1] : null; String resourceName = nameConst instanceof StringConstant stringConst ? stringConst.getValue() : name; @@ -2849,7 +2843,7 @@ public void buildSetProperty(CodeBuilder code, TypeConstant targetType, Loader t MethodTypeDesc md; if (jmd.isOptimized) { - md = jmd.optimizedMD; + md = jmd.optimizedMD; setterName += Builder.OPT; } else { md = jmd.standardMD; @@ -3513,47 +3507,6 @@ public void throwUnsupported(CodeBuilder code) { .athrow(); } - /** - * Create a String and store the reference to the String on the stack. - * - *

    The String template is formatted with values from the provided slots. - * Each occurrence of {@code "\u0001"} is replaced with the value from an entry in the {@code - * argSlots} array. - * - * @param code the {@link CodeBuilder} to use - * @param text the String template to inject values into - * @param argsTypes the types of the arguments to inject into the String. The array must - */ - public void buildString(CodeBuilder code, String text, ClassDesc... argsTypes) { - DirectMethodHandleDesc bsm = MethodHandleDesc.ofMethod( - DirectMethodHandleDesc.Kind.STATIC, - ClassDesc.of("java.lang.invoke.StringConcatFactory"), - "makeConcatWithConstants", - md(CD_CallSite, CD_MethodHandles_Lookup, CD_String, - CD_MethodType, CD_String, CD_Object.arrayType()) - ); - code.invokedynamic(DynamicCallSiteDesc.of(bsm, "makeConcat", - md(CD_String, argsTypes), text)); - } - - /** - * Create a String and store the reference to the String in a new local variable slot. - * - *

    The String template is formatted with values from the provided slots. - * Each occurrence of {@code "\u0001"} is replaced with the value from an entry in the {@code - * argSlots} array. - * - * @param code the {@link CodeBuilder} to use - * @param text the String template to inject values into - * @param argsTypes the types of the arguments to inject into the String. The array must - * - * @return the identifier of the local variable slot that the String has been stored into - */ - public int buildAndStoreString(CodeBuilder code, String text, ClassDesc... argsTypes) { - buildString(code, text, argsTypes); - return storeTempValue(code, CD_String); - } - /** * Create a temporary {@link RegisterInfo} for internal "use once within a scope" scenarios. * This register can only be addressed via the synthetic register -1, at which point it will be @@ -3847,7 +3800,7 @@ public TypeConstant resolveFormalType(FormalConstant formalConst) { case TypeParameter: { // look for a match only amongst the method's formal type parameters TypeParameterConstant typeParam = (TypeParameterConstant) formalConst; - MethodConstant methodId = typeParam.getMethod(); + MethodConstant methodId = typeParam.getMethod(); if (methodId.equals(methodStruct.getIdentityConstant())) { regId = typeParam.getRegister(); diff --git a/javatools/src/main/java/org/xvm/javajit/TextSupport.java b/javatools/src/main/java/org/xvm/javajit/TextSupport.java index 4618921490..4d39498abc 100644 --- a/javatools/src/main/java/org/xvm/javajit/TextSupport.java +++ b/javatools/src/main/java/org/xvm/javajit/TextSupport.java @@ -2,8 +2,18 @@ import java.lang.classfile.CodeBuilder; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.DirectMethodHandleDesc; +import java.lang.constant.DynamicCallSiteDesc; +import java.lang.constant.MethodHandleDesc; + import org.xvm.asm.constants.TypeConstant; +import static java.lang.constant.ConstantDescs.CD_CallSite; +import static java.lang.constant.ConstantDescs.CD_MethodHandles_Lookup; +import static java.lang.constant.ConstantDescs.CD_MethodType; +import static java.lang.constant.ConstantDescs.CD_Object; import static java.lang.constant.ConstantDescs.CD_char; import static org.xvm.javajit.Builder.CD_Char; @@ -11,6 +21,7 @@ import static org.xvm.javajit.Builder.MD_Char_addInt; import static org.xvm.javajit.Builder.MD_Char_subInt; import static org.xvm.javajit.Builder.MD_StringOf; +import static org.xvm.javajit.Builder.md; /** * A "mixin" interface to generate bytecodes for operations on Ecstasy text types such as Char @@ -80,13 +91,12 @@ default TypeConstant buildAddIntToChar(BuildContext bctx, CodeBuilder code, */ default TypeConstant buildAddCharToChar(BuildContext bctx, CodeBuilder code, RegisterInfo regTarget, int nArgId) { + bctx.loadCtx(code); regTarget.load(code); code.i2c(); bctx.loadArgument(code, nArgId); code.i2c(); - int slot = bctx.buildAndStoreString(code, "\u0001\u0001", CD_char, CD_char); - bctx.loadCtx(code); - code.aload(slot); + buildString(code, "\u0001\u0001", CD_char, CD_char); code.invokestatic(CD_String, "of", MD_StringOf); return bctx.pool().typeString(); } @@ -105,16 +115,37 @@ default TypeConstant buildAddCharToChar(BuildContext bctx, CodeBuilder code, */ default TypeConstant buildAddStringToChar(BuildContext bctx, CodeBuilder code, RegisterInfo regTarget, int nArgId) { + bctx.loadCtx(code); regTarget.load(code); code.i2c(); bctx.loadArgument(code, nArgId); - int slot = bctx.buildAndStoreString(code, "\u0001\u0001", CD_char, CD_String); - bctx.loadCtx(code); - code.aload(slot); + buildString(code, "\u0001\u0001", CD_char, CD_String); code.invokestatic(CD_String, "of", MD_StringOf); return bctx.pool().typeString(); } + /** + * Create a String and store the reference to the String on the stack. + * + *

    The String template is formatted with values from the provided slots. Each occurrence of + * {@code "\u0001"} is replaced with the value from an entry in the {@code argSlots} array. + * + * @param code the {@link CodeBuilder} to use + * @param text the String template to inject values into + * @param argsTypes the types of the arguments to inject into the String. The array must + */ + default void buildString(CodeBuilder code, String text, ClassDesc... argsTypes) { + DirectMethodHandleDesc bsm = MethodHandleDesc.ofMethod( + DirectMethodHandleDesc.Kind.STATIC, + ClassDesc.of("java.lang.invoke.StringConcatFactory"), + "makeConcatWithConstants", + md(CD_CallSite, CD_MethodHandles_Lookup, ConstantDescs.CD_String, + CD_MethodType, ConstantDescs.CD_String, CD_Object.arrayType()) + ); + code.invokedynamic(DynamicCallSiteDesc.of(bsm, "makeConcat", + md(ConstantDescs.CD_String, argsTypes), text)); + } + /** * Generate the byte codes to subtract an Int or Char from a Char. * From 4b020267ddbea74b7656489f5d0378286f23e7d4 Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Sat, 14 Nov 2026 15:46:10 -0500 Subject: [PATCH 20/21] Add support for constructor finalizers --- doc/jit-plan.txt | 24 +-- .../java/org/xvm/asm/MethodStructure.java | 47 +++++ .../src/main/java/org/xvm/asm/OpCallable.java | 11 ++ .../java/org/xvm/javajit/BuildContext.java | 141 +++++++++++++-- .../src/main/java/org/xvm/javajit/Ctx.java | 40 ++++- .../java/org/xvm/javajit/JitMethodDesc.java | 4 +- .../javajit/builders/AnnotationHelper.java | 15 +- .../xvm/javajit/builders/CommonBuilder.java | 61 ++++--- .../main/x/jit/jit_tests/basic/annoTests.x | 170 +++++++++++++----- 9 files changed, 401 insertions(+), 112 deletions(-) diff --git a/doc/jit-plan.txt b/doc/jit-plan.txt index 5118e09a48..9d71cf576a 100644 --- a/doc/jit-plan.txt +++ b/doc/jit-plan.txt @@ -1,32 +1,32 @@ From Cam's email on Mar 2025 -[ ] Mixin vs Annotation — also: Exception +[X] Mixin vs Annotation — also: Exception [ ] Service API review, also const [ ] make/immutable review -[ ] Gold/types -[ ] mixin design! -[ ] AST vs byte code design +[-] Gold/types +[X] mixin design! +[X] AST vs byte code design [ ] GC & RAM usage design [ ] Fiber <-> virtual thread design [ ] Future design -[ ] String design & review — graphemes, normalization +[X] String design & review — graphemes, normalization [ ] Struct vs Object, also Public/RO references and +/- types/masking [ ] Unions -[ ] Immutable Objects -[ ] Properties -[ ] Calling convention!!! -[ ] Property/Field layout +[X] Immutable Objects +[X] Properties +[X] Calling convention!!! +[X] Property/Field layout [ ] Container design & lifecycle/masking [ ] Bin code caching/storage/JIT/optJIT [ ] Safepoints — how to include & what do they do? [ ] CPU measure -[ ] Intrinsics — how to design "the divide" +[X] Intrinsics — how to design "the divide" [ ] Service boundary design & automation [ ] Class, Type, Generics [ ] Specialization -[ ] default args +[X] default args [x] Construction — 7 steps (BaseTemplate.Construct proceed) -[ ] Enum | Enumeration type design +[X] Enum | Enumeration type design Review eg. Prev & Next [ ] obj persistence (native optimization) [ ] Container persistence (shelf) diff --git a/javatools/src/main/java/org/xvm/asm/MethodStructure.java b/javatools/src/main/java/org/xvm/asm/MethodStructure.java index 41019bf95a..bbcfc9b2bd 100644 --- a/javatools/src/main/java/org/xvm/asm/MethodStructure.java +++ b/javatools/src/main/java/org/xvm/asm/MethodStructure.java @@ -1271,6 +1271,53 @@ public void setConstructFinally(MethodStructure structFinally) { m_idFinally = structFinally.getIdentityConstant(); } + /** + * @return true iff this constructor or a constructor it invokes has a finalizer + */ + public boolean hasConstructorFinalizers() { + assert isConstructor(); + return hasConstructorFinalizers(new HashSet<>()); + } + + /** + * @return true iff this constructor or any constructor it invokes has a finalizer (recursively) + */ + private boolean hasConstructorFinalizers(Set setVisited) { + // constructor cycles are not expected; this guard is simply defensive + if (!setVisited.add(getIdentityConstant())) { + return false; + } + + if (getConstructFinally() != null) { + return true; + } + + if (hasCode()) { + Constant[] aconst = getLocalConstants(); + for (Op op : getOps()) { + op = op.ensureOp(); + + switch (op.getOpCode()) { + case Op.OP_CONSTR_0, Op.OP_CONSTR_1, Op.OP_CONSTR_N, Op.OP_CONSTR_T: + int nCtorId = ((OpCallable) op).getFunctionId(); + assert nCtorId <= Op.CONSTANT_OFFSET; + + MethodConstant idCtor = (MethodConstant) aconst[Op.CONSTANT_OFFSET - nCtorId]; + MethodStructure ctor = (MethodStructure) idCtor.getComponent(); + + if (ctor.hasConstructorFinalizers(setVisited)) { + return true; + } + break; + + default: + break; + } + } + } + return false; + } + /** * @return true iff this method has code */ diff --git a/javatools/src/main/java/org/xvm/asm/OpCallable.java b/javatools/src/main/java/org/xvm/asm/OpCallable.java index ccc1d79a44..2aaa706f89 100644 --- a/javatools/src/main/java/org/xvm/asm/OpCallable.java +++ b/javatools/src/main/java/org/xvm/asm/OpCallable.java @@ -152,12 +152,15 @@ public void registerConstants(ConstantRegistry registry) { public String toString() { return super.toString() + ' ' + getFunctionString() + '(' + getParamsString() + ") -> " + getReturnsString(); } + protected String getFunctionString() { return Argument.toIdString(m_argFunction, m_nFunctionId); } + protected String getParamsString() { return ""; } + protected static String getParamsString(int[] anArgValue, Argument[] aArgValue) { StringBuilder sb = new StringBuilder(); int cArgNums = anArgValue == null ? 0 : anArgValue.length; @@ -171,6 +174,7 @@ protected static String getParamsString(int[] anArgValue, Argument[] aArgValue) } return sb.toString(); } + protected String getReturnsString() { if (m_anRetValue != null || m_aArgReturn != null) { // multi-return @@ -194,6 +198,13 @@ protected String getReturnsString() { // ----- helper methods ------------------------------------------------------------------------ + /** + * @return the encoded function argument id + */ + public int getFunctionId() { + return m_nFunctionId; + } + /** * This Op holds a constant for the constructor of a child of the compile-time parent. * The run-time type of the parent could extend the compile-time type and that parent diff --git a/javatools/src/main/java/org/xvm/javajit/BuildContext.java b/javatools/src/main/java/org/xvm/javajit/BuildContext.java index 04a3cb8a4f..fe638c2861 100644 --- a/javatools/src/main/java/org/xvm/javajit/BuildContext.java +++ b/javatools/src/main/java/org/xvm/javajit/BuildContext.java @@ -7,9 +7,12 @@ import java.lang.constant.ClassDesc; import java.lang.constant.DirectMethodHandleDesc; import java.lang.constant.DirectMethodHandleDesc.Kind; +import java.lang.constant.DynamicCallSiteDesc; import java.lang.constant.MethodHandleDesc; import java.lang.constant.MethodTypeDesc; +import java.lang.invoke.LambdaMetafactory; + import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; @@ -80,7 +83,11 @@ import org.xvm.javajit.registers.Ref; import org.xvm.javajit.registers.SingleSlot; +import static java.lang.constant.ConstantDescs.CD_CallSite; import static java.lang.constant.ConstantDescs.CD_MethodHandle; +import static java.lang.constant.ConstantDescs.CD_MethodHandles_Lookup; +import static java.lang.constant.ConstantDescs.CD_MethodType; +import static java.lang.constant.ConstantDescs.CD_String; import static java.lang.constant.ConstantDescs.CD_boolean; import static java.lang.constant.ConstantDescs.CD_void; import static java.lang.constant.ConstantDescs.INIT_NAME; @@ -105,6 +112,7 @@ import static org.xvm.javajit.Builder.MD_EnsureType; import static org.xvm.javajit.Builder.MD_TypeIsA; import static org.xvm.javajit.Builder.MD_xvmType; +import static org.xvm.javajit.Builder.OPT; import static org.xvm.javajit.Builder.md; import static org.xvm.javajit.JitFlavor.AlwaysNull; @@ -238,18 +246,23 @@ private BuildContext(BuildContext bctx, String jitName, int callDepth) { } /** - * Construct {@link BuildContext} for a synthetic function. + * Construct {@link BuildContext} for a synthetic function or a constructor finalizer. * - * Note, a synthetic body has its own calling convention, e.g. a static lambda in a constructor. + * Note: a synthetic body has its own calling convention, e.g. a static lambda in a constructor. + * Note 2: constructors operate on STRUCT view, but finalizers operate on PRIVATE */ private BuildContext(BuildContext bctx, String jitName, MethodBody body, JitMethodDesc jmd) { + boolean isFinalizer = body.getMethodStructure().isConstructorFinalizer(); + this.builder = bctx.builder; this.typeSystem = bctx.builder.typeSystem; this.className = bctx.className; - this.typeInfo = bctx.typeInfo; + this.typeInfo = isFinalizer + ? bctx.typeInfo.getType().ensureAccess(Access.PRIVATE).ensureTypeInfo() + : bctx.typeInfo; this.thisType = bctx.thisType; this.jitType = bctx.jitType; - this.callChain = bctx.callChain; + this.callChain = isFinalizer ? new MethodBody[] {body} : bctx.callChain; this.methodStruct = body.getMethodStructure(); this.callDepth = 0; this.methodDesc = jmd; @@ -764,13 +777,15 @@ public void enterMethod(CodeBuilder code) { } } - int extraArgs = methodDesc.getImplicitParamCount(); // e.g. $ctx, $cctx, thi$, ... - ClassDesc CD_this = builder.getThisCD(this); - JitParamDesc[] params = isOptimized ? methodDesc.optimizedParams : methodDesc.standardParams; + int implicitCount = methodDesc.getImplicitParamCount(); // e.g. $ctx, $cctx, thi$ + ClassDesc CD_this = builder.getThisCD(this); + JitParamDesc[] params = isOptimized + ? methodDesc.optimizedParams : methodDesc.standardParams; if (isConstructor) { TypeConstant structType = thisType.ensureAccess(Access.STRUCT); registerInfos.put(Op.A_THIS, - new SingleSlot(Op.A_THIS, extraArgs - 1, Specific, structType, CD_this, "thi$")); + new SingleSlot(Op.A_THIS, implicitCount - 1, Specific, + structType, CD_this, "thi$")); typeMatrix.declare(-1, Op.A_THIS, structType); } else if (isStatic) { typeMatrix.ensureMutableView(0); @@ -810,7 +825,7 @@ public void enterMethod(CodeBuilder code) { param = methodStruct.getParam(varIndex); name = param.getName(); type = resolveSpecialized(param.getType()); - slot = code.parameterSlot(extraArgs + i); // compensate for implicits + slot = code.parameterSlot(implicitCount + i); // compensate for implicits } if (debugInfo) { @@ -843,7 +858,7 @@ public void enterMethod(CodeBuilder code) { Label ifNotDefault = code.newLabel(); if (flavor == PrimitiveWithDefault) { // if the "extSlot" is "true", use the value from the method structure - int extSlot = code.parameterSlot(extraArgs + i + 1); + int extSlot = code.parameterSlot(implicitCount + i + 1); i++; // we consumed the next param code.iload(extSlot) .ifeq(ifNotDefault); @@ -873,7 +888,7 @@ public void enterMethod(CodeBuilder code) { assert param != null && param.hasDefaultValue(); Label ifNotDefault = code.newLabel(); - int extSlot = code.parameterSlot(extraArgs + i + 1); + int extSlot = code.parameterSlot(implicitCount + i + 1); // if the "extSlot" is -1, use the default value from the method structure, // otherwise it's a NullablePrimitive @@ -900,7 +915,7 @@ public void enterMethod(CodeBuilder code) { } case NullablePrimitive: { - int extSlot = code.parameterSlot(extraArgs + i + 1); + int extSlot = code.parameterSlot(implicitCount + i + 1); i++; // we consumed the next param registerInfos.put(varIndex, @@ -914,7 +929,7 @@ public void enterMethod(CodeBuilder code) { ClassDesc[] cds = JitTypeDesc.getXvmPrimitiveClasses(paramDesc.type); Label ifNotDefault = code.newLabel(); - int extSlot = code.parameterSlot(extraArgs + i + cds.length); + int extSlot = code.parameterSlot(implicitCount + i + cds.length); code.iload(extSlot); if (flavor == XvmPrimitiveWithDefault) { @@ -939,7 +954,7 @@ public void enterMethod(CodeBuilder code) { // not Null - store the multi-slot primitives (in the reverse order) and "false" assert defaultReg.flavor() == XvmPrimitive; for (int j = cds.length - 1; j >= 0; j--) { - slot = code.parameterSlot(extraArgs + i + j); + slot = code.parameterSlot(implicitCount + i + j); Builder.store(code, cds[j], slot); } code.iconst_0(); @@ -956,7 +971,7 @@ public void enterMethod(CodeBuilder code) { int[] slots = new int[cds.length]; for (int j = 0; j < cds.length; j++) { - slots[j] = code.parameterSlot(isThis ? j : extraArgs + i + j); + slots[j] = code.parameterSlot(isThis ? j : implicitCount + i + j); } i += cds.length - 1; // we consumed the next params @@ -967,7 +982,7 @@ public void enterMethod(CodeBuilder code) { i++; // skip the next param } } else { - extSlot = code.parameterSlot(extraArgs + i + 1); + extSlot = code.parameterSlot(implicitCount + i + 1); i++; // we consumed the next param } @@ -982,6 +997,100 @@ public void enterMethod(CodeBuilder code) { } typeMatrix.declare(-1, varIndex, type); } + + MethodStructure finalizer = methodStruct.isConstructor() + ? methodStruct.getConstructFinally() : null; + if (finalizer != null) { + // capture this constructor's finalizer for invocation after construction succeeds + MethodBody body = new MethodBody(finalizer); + JitMethodDesc desc = body.getJitDesc(builder, getMethodTargetType()); + + if (thisType.isDerivedVirtualChildClass()) { + // a derived child's receiver may not extend the Java class holding the body + desc = desc.asDetached(CD_this); + } + + MethodConstant id = body.getIdentity(); + if (propertyHosting != null) { + // the same annotation on different properties has distinct hosted state; + // scope the finalizer identity to the property so each gets its own body + id = propertyHosting.nestedIdentity(id); + } + + // two annotations can have finalizers with the same signature + String name = "finally$" + pool().register(id).getPosition(); + deferAssembly(new BuildContext(this, name, body, desc)); + + registerFinalizer(code, name, desc, implicitCount, params); + } + } + + /** + * Capture a constructor finalizer as a Runnable and register it with the constructor context, + * preserving the captured values' JVM representations. + * + * @param name the finalizer's method name without the optimization suffix + * @param desc the descriptor of the finalizer body + * @param implicitCount the number of implicit constructor parameters, ending with the receiver + * @param params the constructor's explicit JVM parameters, including primitive + * components and default flags + */ + private void registerFinalizer(CodeBuilder code, String name, JitMethodDesc desc, + int implicitCount, JitParamDesc[] params) { + // ordinary finalizers are instance methods, but virtual-child bodies can be detached + MethodTypeDesc finalizerMD = desc.isOptimized ? desc.optimizedMD : desc.standardMD; + Kind kind = desc instanceof JitDetachedBodyDesc ? Kind.STATIC : Kind.VIRTUAL; + DirectMethodHandleDesc finalizerHandle = MethodHandleDesc.ofMethod(kind, + builder.art.CD(), name + (desc.isOptimized ? OPT : ""), finalizerMD); + + // the handle's invocation type includes the receiver for either calling convention + // factoryMD: (C, Ctx, X, Y, Z) -> Runnable; captures the supplied values + // runMD: () -> void; Runnable.run() forwards those values to the finalizer body + // primitive body parameters remain primitive factory parameters; no boxing is needed + ClassDesc CD_runnable = ClassDesc.of(Runnable.class.getName()); + MethodTypeDesc runMD = md(CD_void); + MethodTypeDesc factoryMD = finalizerHandle.invocationType().changeReturnType(CD_runnable); + + // describe the bootstrap method the JVM uses to link the factory + DirectMethodHandleDesc bootstrap = MethodHandleDesc.ofMethod(Kind.STATIC, + ClassDesc.of(LambdaMetafactory.class.getName()), "metafactory", + md(CD_CallSite, + CD_MethodHandles_Lookup, // caller access supplied by the JVM + CD_String, // invokedynamic method name: "run" + CD_MethodType, // invokedynamic factory signature + CD_MethodType, // declared interface method signature + CD_MethodHandle, // finalizer implementation to invoke + CD_MethodType)); // adapted interface method signature + + // at linkage the JVM calls metafactory with (caller Lookup, "run", factoryMD), followed + // by these three constants; executions of the linked factory create captured Runnables + // Runnable has no generic signature to adapt, so its declared and adapted runMD match + DynamicCallSiteDesc factory = DynamicCallSiteDesc.of(bootstrap, "run", factoryMD, + runMD, // Runnable's declared run() signature + finalizerHandle, // the implementation invoked by run() + runMD); // run() signature after adaptation; unchanged for Runnable + + // capture arguments before the constructor can change its parameter registers + // final X savedX = x; + // final Y savedY = y; + // final Z savedZ = z; + // cctx.push(() -> thi$.finally$17(ctx, savedX, savedY, savedZ)); + loadCtorCtx(code); + + // the receiver is the last implicit constructor parameter + code.aload(code.parameterSlot(implicitCount - 1)); + loadCtx(code); + + // copy each JVM component directly, including primitives and their auxiliary flags + for (int i = 0; i < params.length; i++) { + Builder.load(code, params[i].cd, code.parameterSlot(implicitCount + i)); + } + + // stack: cctx, thi$, ctx, args...; the factory consumes the captured values + code.invokedynamic(factory); + + // stack: cctx, Runnable; register it for invocation after construction succeeds + code.invokevirtual(CD_CtorCtx, "push", md(CD_void, CD_runnable)); } /** diff --git a/javatools/src/main/java/org/xvm/javajit/Ctx.java b/javatools/src/main/java/org/xvm/javajit/Ctx.java index b2e1f3afe8..559f47673e 100644 --- a/javatools/src/main/java/org/xvm/javajit/Ctx.java +++ b/javatools/src/main/java/org/xvm/javajit/Ctx.java @@ -4,6 +4,11 @@ import java.lang.constant.MethodTypeDesc; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; + import java.util.function.Function; import org.xvm.asm.ConstantPool; @@ -124,7 +129,40 @@ public CtorCtx ctorCtx() { * The constructor context is required if a “finally” chain exists. */ public static class CtorCtx { - // TODO CP: + private final Deque finalizers = new ArrayDeque<>(); + private final List annotations = new ArrayList<>(); + + /** + * Add a finalizer with its constructor's receiver and arguments captured. + */ + public void push(Runnable finalizer) { + finalizers.push(finalizer); + } + + /** + * @return a new annotation constructor chain, preceding this class's finalizers + * + * @see org.xvm.javajit.builders.AnnotationHelper#invokeAnnotationConstructors + */ + public CtorCtx addChain() { + CtorCtx chain = new CtorCtx(); + annotations.add(chain); + return chain; + } + + /** + * Run annotation chains in construction order, followed by the class chain. Each chain + * runs in reverse constructor invocation order. A failing finalizer prevents the remaining + * finalizers from running. + */ + public void run() { + for (CtorCtx annotation : annotations) { + annotation.run(); + } + while (!finalizers.isEmpty()) { + finalizers.pop().run(); + } + } } // ----- Container and Service support --------------------------------------------------------- diff --git a/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java b/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java index 57b8c7ac43..a6ad4dafe8 100644 --- a/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java +++ b/javatools/src/main/java/org/xvm/javajit/JitMethodDesc.java @@ -9,8 +9,8 @@ import java.util.stream.IntStream; -import org.xvm.asm.ConstantPool; import org.xvm.asm.Component.Format; +import org.xvm.asm.ConstantPool; import org.xvm.asm.MethodStructure; import org.xvm.asm.constants.TypeConstant; @@ -280,7 +280,7 @@ protected int fillExtraClassDesc(ClassDesc[] paramCDs, int ix) { public static int flagsFor(MethodStructure method) { if ((method.isConstructor() || method.isValidator()) && !method.isPropertyInitializer()) { int flags = JMD_CONSTRUCTOR; - if (method.isConstructor() && method.getConstructFinally() != null) { + if (method.isConstructor() && method.hasConstructorFinalizers()) { flags |= JMD_FINALIZER; } return flags; diff --git a/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java b/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java index 3a3f3ca608..843bef966f 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/AnnotationHelper.java @@ -37,7 +37,6 @@ import org.xvm.javajit.RegisterInfo; import static org.xvm.javajit.Builder.CD_CtorCtx; -import static org.xvm.javajit.Builder.CD_Ctx; import static org.xvm.javajit.Builder.OPT; import static org.xvm.javajit.TypeSystem.AT; @@ -453,16 +452,18 @@ public void invokeAnnotationConstructors(CodeBuilder code, continue; } - if (jmd.hasCtorCtx() && cctxSlot < 0) { - cctxSlot = code.allocateLocal(TypeKind.REFERENCE); - code.aload(ctxSlot) - .invokevirtual(CD_Ctx, "ctorCtx", Builder.md(CD_CtorCtx)) - .astore(cctxSlot); + int chainedCctxSlot = -1; + if (jmd.hasCtorCtx()) { + assert cctxSlot >= 0; + chainedCctxSlot = code.allocateLocal(TypeKind.REFERENCE); + code.aload(cctxSlot) + .invokevirtual(CD_CtorCtx, "addChain", Builder.md(CD_CtorCtx)) + .astore(chainedCctxSlot); } code.aload(ctxSlot); if (jmd.hasCtorCtx()) { - code.aload(cctxSlot); + code.aload(chainedCctxSlot); } code.aload(thisSlot); if (constructor.isConstructionSite()) { diff --git a/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java index 3b8c0645fe..139e800a18 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java @@ -4602,8 +4602,8 @@ protected List collectVariants(JitMethodDesc baseDesc) { * // step 5: annotation constructors are called * * // step 6: the constructor gets called - * // - we do NOT have to save off the arguments for the `finally()` call - * // in the constructor context because we have the arguments right here + * // - each constructor captures its finalizer's receiver and arguments in cctx + * // before executing its body or calling another constructor * // note: cctx argument is optional * construct$17(ctx, cctx, thi$, x, y, z); * @@ -4628,39 +4628,31 @@ protected List collectVariants(JitMethodDesc baseDesc) { * // step 9: post construction work e.g. const freezing * // TODO GG define * - * // step 10: any `finally {...}` methods corresponding to constructors - * // from #3 and #4 are executed, in reverse order of what the constructors - * // were called in - * // note: cctx argument is optional - * finally$17(ctx, cctx, thi$, x, y, z); + * // step 10: annotation finalizer chains run in annotation construction order, + * // followed by the class chain; each chain runs in reverse constructor invocation order + * // - cctx is absent if no constructor in these chains has a finalizer + * cctx.run(); * } * * // assuming C extends B and B has a finally that takes some (P p, Q q): - * public static construct$17(CtorCtx cctx, C thi$, X x, Y y, Z z) { - * // user logic before the `construct B(p,q);` + * public static void construct$17(Ctx ctx, CtorCtx cctx, C thi$, X x, Y y, Z z) { + * cctx.push(() -> thi$.finally$17(ctx, x, y, z)); + * + * // user logic before the `construct B(p, q);` * P p; * Q q; * // ... * - * // this is the translation of the call to `construct B(p,q);` - * cctx.push(p); - * cctx.push(q); - * B.construct$17(cctx, thi$, p, q); + * // this is the translation of the call to `construct B(p, q);` + * // B captures its own finalizer and arguments in the same context + * B.construct$17(ctx, cctx, thi$, p, q); * - * // user logic after the `construct B(p,q);` + * // user logic after the `construct B(p, q);` * // ... * } * - * public static finally$17(CtorCtx cctx, C thi$, X x, Y y, Z z) { - * // run the `finally` on B before running the `finally` on D - * // (we saved off the args in the constructor .. it's basically - * // a hand-rolled closure) - * { - * Q q = cctx.pop(); - * P p = cctx.pop(); - * B.finally$17(cctx, thi$, p, q); - * } - * + * public void finally$17(Ctx ctx, X x, Y y, Z z) { + * // CtorCtx has already run B's captured finalizer before invoking this body * // user logic from C.finally goes here * // ... * } @@ -4764,8 +4756,12 @@ protected void assembleNew(ClassBuilder classBuilder, MethodInfo constructor, St TypeConstant ownerType = hasConstructionSiteAnnotations() ? annotated.getBaseType() : thisType; JitCtorDesc ctorDesc = (JitCtorDesc) constructor.getJitDesc(this, ownerType); - boolean hasCtorCtx = ctorDesc.hasCtorCtx(); - int cctxSlot = -1; + boolean hasCtorCtx = ctorDesc.hasCtorCtx() || + annotationConstructors != null && + annotationConstructors.stream(). + anyMatch(ctor -> ctor.desc().hasCtorCtx()); + + int cctxSlot = -1; if (hasCtorCtx) { cctxSlot = code.allocateLocal(TypeKind.REFERENCE); if (debugInfo) { @@ -4851,7 +4847,13 @@ protected void assembleNew(ClassBuilder classBuilder, MethodInfo constructor, St } } - // steps 8, 9, 10: TODO + // steps 8, 9: TODO + + // step 10: run captured annotation and class finalizers on the completed object + if (cctxSlot >= 0) { + code.aload(cctxSlot) + .invokevirtual(CD_CtorCtx, "run", md(CD_void)); + } code.labelBinding(endScope) .aload(thisSlot) @@ -5068,8 +5070,11 @@ public String toString() { // TODO: conditional ListMapIndex super calls and MapFreezer Map.entry("org.xtclang.ecstasy.maps.DiscreteEntry", Set.of("construct")), // TODO: verify specialized constructor return with a conditional mixin + Map.entry("org.xtclang.ecstasy.maps.HasherMap", + Set.of("finally")), // TODO: &hasher lookup in the constructor finalizer Map.entry("org.xtclang.ecstasy.Timeout", - Set.of("construct")), // TODO: invokes nService with invokeinterface although nService is a Java class + Set.of("construct", "finally")), + // TODO: invokes nService with invokeinterface although nService is a Java class Map.entry("org.xtclang.ecstasy.io.Channel", Set.of("write")), // TODO: Future support Map.entry("org.xtclang._native.fs.OSStorage", diff --git a/manualTests/src/main/x/jit/jit_tests/basic/annoTests.x b/manualTests/src/main/x/jit/jit_tests/basic/annoTests.x index 37851d4997..ec90b6e7d3 100644 --- a/manualTests/src/main/x/jit/jit_tests/basic/annoTests.x +++ b/manualTests/src/main/x/jit/jit_tests/basic/annoTests.x @@ -7,6 +7,7 @@ package annoTests { testIntoClass(); testIntoChild(); testIntoInheritedChild(); + testChildConstructorFinalizers(); testNestedChildDispatch(); testIntoInterface(); testIntoException(); @@ -46,62 +47,55 @@ package annoTests { console.reset(); Int age = 26; - val p1 = new Named("Jane"); - val p2 = new @Aged(age + 1) Named("Joe"); - val p3 = new @Aged(age) @Skilled("Java") Named("Jon"); - val p4 = new @Skilled("Ecstasy") @Aged(21) Named("Joanne"); - -// TODO: this is the ultimate target - with finalizers -// assert console.output() == \|construct name Jane -// |assert name Jane -// |finally name Jane -// |construct aged 27 -// |construct name Joe -// |assert aged 27 -// |assert name Joe -// |finally aged 27 -// |finally name Joe -// |construct aged 26 -// |construct skill Java -// |construct name Jon -// |assert aged 26 -// |assert skill Java -// |assert name Jon -// |finally aged 26 -// |finally skill Java -// |finally name Jon -// |construct skill Ecstasy -// |construct aged 21 -// |construct name Joanne -// |assert skill Ecstasy -// |assert aged 21 -// |assert name Joanne -// |finally skill Ecstasy -// |finally aged 21 -// |finally name Joanne -// | -// ; + + // finalizers follow all validators, in annotation order and then the class + val p1 = new Named("Jane"); assert console.output() == \|construct name Jane |assert name Jane - |construct aged 27 + |finally name Jane + | + ; + + console.reset(); + val p2 = new @Aged(age + 1) Named("Joe"); + assert console.output() == \|construct aged 27 |construct name Joe |assert aged 27 |assert name Joe - |construct aged 26 + |finally aged 27 + |finally name Joe + | + ; + + console.reset(); + val p3 = new @Aged(age) @Skilled("Java") Named("Jon"); + assert console.output() == \|construct aged 26 |construct skill Java |construct name Jon |assert aged 26 |assert skill Java |assert name Jon - |construct skill Ecstasy + |finally aged 26 + |finally skill Java + |finally name Jon + | + ; + + console.reset(); + val p4 = new @Skilled("Ecstasy") @Aged(21) Named("Joanne"); + assert console.output() == \|construct skill Ecstasy |construct aged 21 |construct name Joanne |assert skill Ecstasy |assert aged 21 |assert name Joanne + |finally skill Ecstasy + |finally aged 21 + |finally name Joanne | ; + console.reset(); Boolean rejected = False; try { new @Aged(-1) Named("Joe"); @@ -109,6 +103,7 @@ package annoTests { rejected = True; } assert rejected; + assert console.output() == "construct aged -1\nconstruct name Joe\n"; assert asNamed(p4).name == "Joanne"; assert asSkilled(p4).skill == "Ecstasy"; @@ -118,25 +113,33 @@ package annoTests { Skilled asSkilled(Object value) = value.as(Skilled); Aged asAged(Object value) = value.as(Aged); + console.reset(); rejected = False; try { - new @Skilled("Ecstasy") @Aged(21) Named(""); + new @Skilled("Ecstasy") @Aged(21) Named("?"); } catch (IllegalState e) { rejected = True; } assert rejected; + assert console.output() == \|construct skill Ecstasy + |construct aged 21 + |construct name ? + |assert skill Ecstasy + |assert aged 21 + | + ; } const Named { construct(String name) { console.print($"construct name {name}"); this.name = name; -// } finally { -// console.print($"finally name {name}"); + } finally { + console.print($"finally name {name}"); } assert() { - assert name.size > 0; + assert name.size > 1; console.print($"assert name {name}"); } @@ -147,8 +150,8 @@ package annoTests { construct(Int age) { console.print($"construct aged {age}"); this.age = age; -// } finally { -// console.print($"finally aged {age}"); + } finally { + console.print($"finally aged {age}"); } assert() { @@ -163,8 +166,8 @@ package annoTests { construct(String skill) { console.print($"construct skill {skill}"); this.skill = skill; -// } finally { -// console.print($"finally skill {skill}"); + } finally { + console.print($"finally skill {skill}"); } assert() { @@ -376,6 +379,59 @@ package annoTests { } } + void testChildConstructorFinalizers() { + console.reset(); + new Base().new C1(3); + assert console.output() == \|base 3 + |child 3 + | + ; + + console.reset(); + new Derived().new C0(5); + assert console.output() == \|base 5 + |derived ready 5 + | + ; + + class Base { + class C0 { + construct(Int value) { + this.value = value; + } finally { + assert this.value == value; + console.print($"base {value}"); + } + + Int value; + } + + class C1 extends C0 { + construct(Int value) { + construct C0(value); + } finally { + assert this.value == value; + console.print($"child {value}"); + } + } + } + + class Derived extends Base { + @Override + class C0 { + construct(Int value) { + construct Base.C0(value); + tag = "ready"; + } finally { + assert this.value == value; + console.print($"derived {tag} {value}"); + } + + String tag = "unset"; + } + } + } + void testNestedChildDispatch() { // adapted from testInsane() in manualTests/src/main/x/nesting.x console.reset(); @@ -729,18 +785,34 @@ package annoTests { } void testOptimizedConstructors() { + console.reset(); + Int128 wide = 123; Int? marker = 17; val explicit = new @Count(4, marker) Counter(9, wide); + assert console.output() == \|finally Count + |finally Counter + | + ; assert explicit.seed == 9 && explicit.wide == wide; assert explicit.amount == 4 && explicit.marker == marker; + console.reset(); val defaults = new @Count Counter(); + assert console.output() == \|finally Count + |finally Counter + | + ; assert defaults.seed == 3 && defaults.wide == 0; assert defaults.amount == 5 && defaults.marker == Null; + console.reset(); val chained = new @Ignored(wide) @Count(8, Null) Counter(2, wide); + assert console.output() == \|finally Count + |finally Counter + | + ; assert chained.seed == 2 && chained.wide == wide; assert chained.amount == 8 && chained.marker == Null; @@ -748,6 +820,9 @@ package annoTests { construct(Int seed = 3, Int128 wide = 0) { this.seed = seed; this.wide = wide; + } finally { + assert seed == this.seed && wide == this.wide; + console.print("finally Counter"); } Int seed; @@ -758,6 +833,9 @@ package annoTests { construct(Int amount = 5, Int? marker = Null) { this.amount = amount; this.marker = marker; + } finally { + assert amount == this.amount && marker == this.marker; + console.print("finally Count"); } Int amount; From 5a3f720e28a11d5f0283d63cf9c5355bad13ff8c Mon Sep 17 00:00:00 2001 From: Gene Gleyzer Date: Mon, 16 Nov 2026 12:08:24 -0500 Subject: [PATCH 21/21] Remove completed TODOs --- .../main/java/org/xvm/javajit/builders/CommonBuilder.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java b/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java index 139e800a18..f5b0c0887f 100644 --- a/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java +++ b/javatools/src/main/java/org/xvm/javajit/builders/CommonBuilder.java @@ -2922,8 +2922,6 @@ protected void assembleConstMethods(ClassBuilder classBuilder) { } // the reason we need to generate "hashCode" for primitive types is to produce // non-predictable implementations - // TODO JK: consider implementing them natively via a Ctx-based facility, in which - // case we can simplify the code production assembleConstHashCode(classBuilder); } @@ -4611,8 +4609,7 @@ protected List collectVariants(JitMethodDesc baseDesc) { * // base classes, mixins, annotations -- of the composition) * // - there is no assert method if this class has no assert() defined and * // none of its supers has an assert() defined - * // - each calls its super first (TODO GG verify) - * // - TODO GG define mixin and annotation assert() order + * // - each calls its super first * // - depending on ordering requirements this could be a method (not a * // "static") * $assert();