Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,17 +251,19 @@ Notes; finished-work narrative does not.
exemption fails the run (21 of 48 `testLua(false)` were stale and now run Lua). Land the shim natives
first. `executeTests()` (Wurst `@Test` functions) has no Lua path in the harness at all.

- **A generic class's static is dropped on Lua when only a static inner class reads it.**
`GenericsWithTypeclassesTests.genericClassWithStaticInnerClass` and `genericModuleThistypeSmall` pass
on the interpreter and Jass and fail on Lua, also after #1498; neither opts into Lua. In
`class Outer<T:>` with `static T t`, the specialised constructor's `t = iVal` is not emitted and
`Inner.next()` reads the erased `Outer_t`, which stays nil. A static function of `Outer` reading `t`
instead passes on both Lua variants, so the reader in the unspecialised inner class splits the store.
The module form (`static thistype t` in a module used by `class A<T:>`) loses `t = this` the same way
with `-inline -localOptimizations`, and without it the Lua translation crashes in
`TypeSubst.resolve` ("Could not find replacement for T... when replacing [T...] with []"), from
`ExprTranslation.translateEquals` typing `a.iterator().next()`. Fix in `EliminateGenerics`, where the
store is split, and turn on `testLua(true).luaOnly(false)` for both tests.
- **A generic class constructed with a tuple loses the static its constructor writes, on Lua.** In
`class Outer<T:>` with `static T last` and `construct(T value)` / `last = value`,
`new Outer<pair>(pair(2, 3))` leaves `Outer<pair>.get().y` unset on Lua; Jass passes. The constructor's
copy keeps the class's `T` as its parameter type, so the emitted function takes one parameter more than
the call passes tuple components: `EliminateGenerics.specializeFunction` rewrites the type variables only
of a function which declares some, and a function which writes a generic static takes that branch, while
this target does not lift the class's variables onto its functions (`specializeClassFunction` does it).

- **`EliminateGenerics.fillMissingTypeArgsFromScope` matches type variables by name.** On the Jass path it
completed the owner type arguments of a static inner class's type, which the IM translation now gives
itself (`WurstTypeClassOrInterface.imTranslateType`). Made to throw whenever it fills one, it is reached by
none of the generics, closure, module, class and Lua audit test classes (October 2026). Check the whole
suite and remove it.

- **`typeIdToTypeName`, `maxTypeId`, `instanceCount` and `maxInstanceCount` answer defaults on Lua.**
Only `EliminateClasses` implements them, on the Jass path. On Lua they compile to the generic native
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -459,10 +459,29 @@ public void pushStackframeWithTypes(ImFunction f, @Nullable ILconstObject receiv
rt = imClassType;
}

ImClassType adapted = adaptToSuperclass(rt, owner);
ImClassType adapted = adaptToOwner(rt, owner);
return adapted != null ? adapted : rt;
}

/**
* {@code ct} as an instantiation of {@code owner}, through the superclass edges. A static inner class is first
* taken to the owner whose type parameters it captured, so that it reads the statics of its owner's instantiation
* and of the superclasses of that, as {@code EliminateGenerics.adaptGenericsToOwner} does.
*/
private @Nullable ImClassType adaptToOwner(ImClassType ct, ImClass owner) {
ImClassType adapted = adaptToSuperclass(ct, owner);
if (adapted != null) {
return adapted;
}
ImClassType capturedOwner = specialisations.capturedOwnerType(ct.getClassDef());
if (capturedOwner == null) {
return null;
}
ImType ownerInstantiation = resolveType(ImAttrType.substituteType(capturedOwner, ct.getTypeArguments(),
ct.getClassDef().getTypeVariables()));
return ownerInstantiation instanceof ImClassType ownerType ? adaptToOwner(ownerType, owner) : null;
}

private @Nullable ImClassType adaptToSuperclass(ImClassType ct, ImClass owner) {
if (ct.getClassDef() == owner) return ct;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1837,7 +1837,12 @@ private ImVar specializedGlobal(ImVar original) {
});
}

/** Maps a concrete subclass instantiation onto the type arguments of a static's declaring class. */
/**
* Maps a concrete instantiation onto the type arguments of a static's declaring class, through the superclass
* edges. A static inner class is first taken to the owner whose type parameters it captured
* ({@code Outer<T>.Inner} is {@code Inner<T>}): in {@code Inner<int>}, a static of {@code Outer} or of a
* superclass of it is the one of {@code Outer<int>}.
*/
private @Nullable GenericTypes adaptGenericsToOwner(ImClass concreteOwner,
GenericTypes concreteGenerics,
ImClass declaringOwner) {
Expand All @@ -1850,13 +1855,28 @@ private ImVar specializedGlobal(ImVar original) {
}
ImClassType adapted = adaptToSuperclass(
JassIm.ImClassType(concreteOwner, arguments), declaringOwner);
if (adapted == null || adapted.getTypeArguments().size() != declaringOwner.getTypeVariables().size()
if (adapted == null) {
ImClassType owner = capturedOwnerInstantiation(concreteOwner, concreteGenerics);
return owner == null ? null
: adaptGenericsToOwner(owner.getClassDef(), new GenericTypes(owner.getTypeArguments()), declaringOwner);
}
if (adapted.getTypeArguments().size() != declaringOwner.getTypeVariables().size()
|| typeArgumentsContainTypeVariable(adapted.getTypeArguments())) {
return null;
}
return new GenericTypes(adapted.getTypeArguments());
}

/** The instantiation of the owner a static inner class captured type parameters from, for one of the inner class. */
private @Nullable ImClassType capturedOwnerInstantiation(ImClass innerClass, GenericTypes innerGenerics) {
ImClassType ownerType = translator.capturedOwnerType(innerClass);
int count = innerClass.getTypeVariables().size();
if (ownerType == null || innerGenerics.getTypeArguments().size() < count) {
return null;
}
return (ImClassType) transformType(ownerType, innerGenerics.take(count), innerClass.getTypeVariables());
}

/**
* creates a specialized version of this method
*/
Expand Down Expand Up @@ -2267,6 +2287,7 @@ private ImClass specializeClass(ImClass c, GenericTypes generics) {
// NEW: Create specialized global variables for this class instantiation
createSpecializedGlobals(c, generics, typeVars);
if (genericNewOnly && (classOwnsGenericGlobals(c)
|| !translator.capturedOwnerTypeParameters(c).isEmpty()
|| (specializeTupleValueTypes && genericTypesContainTuple(generics)))) {
rewriteOwnedGenericGlobals(newC, c, generics);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,8 @@ public List<ImVar> pinnedGlobals() {
private final RunArgs runArgs;

private final Map<ClassDef, Map<TypeParamDef, ImTypeVar>> capturedOwnerTypeVarsByStaticClass = new IdentityHashMap<>();
/** The class or interface whose type parameters a static inner class captured. */
private final Map<ClassDef, ClassOrInterface> capturingOwnerByStaticClass = new IdentityHashMap<>();
private final Deque<Map<TypeParamDef, ImTypeVar>> typeVarOverrideStack = new ArrayDeque<>();
private final Deque<ImVar> continueFlagStack = new ArrayDeque<>();

Expand Down Expand Up @@ -388,6 +390,51 @@ public Map<TypeParamDef, ImTypeVar> getTypeVarOverridesForClass(ClassDef cd) {
return (m == null) ? Collections.emptyMap() : m;
}

/**
* The owner's type parameters a static inner class captured ({@link #addCapturedTypeVarsFromOwningGeneric}), in
* the order of the class's type variables, which follow its own. A type naming the class supplies them after its
* own type arguments.
*/
public List<TypeParamDef> capturedOwnerTypeParameters(ImClass imClass) {
if (!(imClass.getTrace() instanceof ClassDef classDef)) {
return Collections.emptyList();
}
Map<TypeParamDef, ImTypeVar> captured = capturedOwnerTypeVarsByStaticClass.get(classDef);
if (captured == null || captured.isEmpty()) {
return Collections.emptyList();
}
List<TypeParamDef> result = new ArrayList<>();
for (ImTypeVar typeVariable : imClass.getTypeVariables()) {
TypeParamDef ownerParameter = typeVariableReverse.get(typeVariable);
if (ownerParameter != null && captured.get(ownerParameter) == typeVariable) {
result.add(ownerParameter);
}
}
return result;
}

@Override
public @Nullable ImClassType capturedOwnerType(ImClass imClass) {
if (!(imClass.getTrace() instanceof ClassDef classDef)) {
return null;
}
Map<TypeParamDef, ImTypeVar> captured = capturedOwnerTypeVarsByStaticClass.get(classDef);
ClassOrInterface owner = capturingOwnerByStaticClass.get(classDef);
ImClass ownerClass = owner == null ? null : classForStructureDef.get(owner);
if (captured == null || captured.isEmpty() || ownerClass == null) {
return null;
}
ImTypeArguments typeArguments = JassIm.ImTypeArguments();
for (ImTypeVar ownerVariable : ownerClass.getTypeVariables()) {
ImTypeVar capturedVariable = captured.get(typeVariableReverse.get(ownerVariable));
if (capturedVariable == null || !imClass.getTypeVariables().contains(capturedVariable)) {
return null;
}
typeArguments.add(JassIm.ImTypeArgument(JassIm.ImTypeVarRef(capturedVariable), Collections.emptyMap()));
}
return JassIm.ImClassType(ownerClass, typeArguments);
}

public void pushTypeVarOverrides(Map<TypeParamDef, ImTypeVar> m) {
if (m != null && !m.isEmpty()) typeVarOverrideStack.push(m);
}
Expand Down Expand Up @@ -3094,6 +3141,9 @@ private void addCapturedTypeVarsFromOwningGeneric(ImTypeVars typeVariables, Clas

if (owner == null) return;
if (owner == cd) return;
if (owner instanceof ClassOrInterface ownerScope) {
capturingOwnerByStaticClass.put(cd, ownerScope);
}

// override map for this static inner class: owner TypeParamDef -> captured ImTypeVar (fresh node)
Map<TypeParamDef, ImTypeVar> override =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import de.peeeq.wurstscript.jassIm.Element;
import de.peeeq.wurstscript.jassIm.ImClass;
import de.peeeq.wurstscript.jassIm.ImClassType;
import de.peeeq.wurstscript.jassIm.ImVar;
import org.eclipse.jdt.annotation.Nullable;

Expand All @@ -26,6 +27,16 @@ public interface SpecialisationLookup {
*/
@Nullable ImClass genericStaticOwnerOf(ImVar global);

/**
* For a static inner class which captured the type parameters of its generic owner, the owner's type as the inner
* class sees it, {@code Outer<T>} with the inner class's own copy of {@code T}; null for any other class. An inner
* class's instantiation is its owner's this way, and a static of the owner or of a superclass of it belongs to
* that.
*/
default @Nullable ImClassType capturedOwnerType(ImClass staticInnerClass) {
return null;
}

/**
* For a program which did not come from a translation that recorded anything - a hand-built
* program in a test, say. Every node is its own original, which is what a program with no
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@
import com.google.common.collect.Multimap;
import de.peeeq.wurstscript.ast.ClassOrInterface;
import de.peeeq.wurstscript.ast.Element;
import de.peeeq.wurstscript.ast.TypeParamDef;
import de.peeeq.wurstscript.attributes.CheckHelper;
import de.peeeq.wurstscript.attributes.names.DefLink;
import de.peeeq.wurstscript.attributes.names.FuncLink;
import de.peeeq.wurstscript.attributes.names.NameLink;
import de.peeeq.wurstscript.jassIm.ImClass;
import de.peeeq.wurstscript.jassIm.ImType;
import de.peeeq.wurstscript.jassIm.ImTypeArguments;
import de.peeeq.wurstscript.jassIm.JassIm;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import io.vavr.control.Option;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

import java.util.HashMap;
import java.util.List;

public abstract class WurstTypeClassOrInterface extends WurstTypeNamedScope {
Expand Down Expand Up @@ -141,7 +145,22 @@ public final ImType imTranslateType(ImTranslator tr) {
typeArgs.add(btp.imTranslateToTypeArgument(tr));
}
}
return JassIm.ImClassType(tr.getClassFor(getDef()), typeArgs);
ImClass imClass = tr.getClassFor(getDef());
// A static inner class of a generic class also has the owner's type parameters it captured. The captured
// binding says what they were instantiated with, as for `outer.inner()`; where nothing is bound, as in the
// owner or the inner class itself, a parameter stands for itself, which is what a constructor call passes
// (ExprTranslation.getFunctionCallTypeArguments).
List<TypeParamDef> ownerParameters = tr.capturedOwnerTypeParameters(imClass);
if (!ownerParameters.isEmpty()) {
VariableBinding binding = getTypeArgBinding();
for (TypeParamDef ownerParameter : ownerParameters) {
Option<WurstTypeBoundTypeParam> bound = binding.get(ownerParameter);
typeArgs.add(bound.isDefined()
? bound.get().imTranslateToTypeArgument(tr)
: JassIm.ImTypeArgument(JassIm.ImTypeVarRef(tr.getTypeVar(ownerParameter)), new HashMap<>()));
}
}
return JassIm.ImClassType(imClass, typeArgs);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,60 @@ public void bridgesOfAGenericClassAreTheSameInAnyUnitOrder() throws IOException
assertEquals(Files.toString(lua, Charsets.UTF_8), firstLua, "Lua must not depend on the unit order");
}

/**
* A static inner class of a generic class takes the owner's instantiation from the type it is handed out as, and
* Lua specialises its reader of the owner's static for that instantiation. Two such owners in packages of their
* own: what is specialised, and its names, must not depend on which is translated first.
*/
@Test
public void staticInnerClassesOfGenericOwnersAreTheSameInAnyUnitOrder() throws IOException {
List<CU> units = List.of(
compilationUnit("OuterLib.wurst",
"package OuterLib",
"public class Outer<T:>",
" static T last",
" construct(T value)",
" last = value",
" function reader() returns Reader",
" return new Reader()",
" static class Reader",
" function read() returns T",
" return last"),
compilationUnit("BoxLib.wurst",
"package BoxLib",
"public class Box<T:>",
" static T held",
" construct(T value)",
" held = value",
" function reader() returns Reader",
" return new Reader()",
" static class Reader",
" function read() returns T",
" return held"),
compilationUnit("Main.wurst",
"package Main",
"import OuterLib",
"import BoxLib",
"native testSuccess()",
"init",
" let ints = new Outer<int>(7)",
" let strings = new Outer<string>(\"ok\")",
" let box = new Box<int>(3)",
" if ints.reader().read() == 7 and strings.reader().read() == \"ok\" and box.reader().read() == 3",
" testSuccess()"));
String name = "staticInnerClassesOfGenericOwners";
File jass = new File("test-output/DeterministicChecks_" + name + "_no_opts.j");
File lua = new File("test-output/lua/DeterministicChecks_" + name + ".lua");
testNamed(name).testLua(true).luaOnly(false).executeProg()
.compilationUnits(units.get(0), units.get(1), units.get(2));
String firstJass = Files.toString(jass, Charsets.UTF_8);
String firstLua = Files.toString(lua, Charsets.UTF_8);
testNamed(name).testLua(true).luaOnly(false).executeProg()
.compilationUnits(units.get(1), units.get(0), units.get(2));
assertEquals(Files.toString(jass, Charsets.UTF_8), firstJass, "Jass must not depend on the unit order");
assertEquals(Files.toString(lua, Charsets.UTF_8), firstLua, "Lua must not depend on the unit order");
}

/** Compiles {@code units} to Lua, runs them, and returns the script, which is written under {@code name}. */
private String compileToLua(String name, List<CU> units) throws IOException {
testNamed(name).testLua(true).executeProg().compilationUnits(units.toArray(new CU[0]));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2088,7 +2088,7 @@ public void genericClassWithLLModule() {

@Test
public void genericClassWithStaticInnerClass() {
testAssertOkLines(true,
test().testLua(true).luaOnly(false).executeProg().lines(
"package test",
" native testSuccess()",
" class Outer<T:>",
Expand All @@ -2109,9 +2109,36 @@ public void genericClassWithStaticInnerClass() {
);
}

@Test
public void genericClassWithStaticInnerClassHeldInLocals() {
// A local typed by the owner's method keeps the owner's instantiation, which is all that tells
// the two readers apart.
test().testLua(true).luaOnly(false).executeProg().lines(
"package test",
" native testSuccess()",
" class Outer<T:>",
" static T t = null",
" construct(T iVal)",
" t = iVal",
" function iterator() returns Inner",
" return new Inner()",
" static class Inner",
" function next() returns T",
" return t",
" init",
" let ints = new Outer<int>(3)",
" let strings = new Outer<string>(\"ok\")",
" let intIterator = ints.iterator()",
" let stringIterator = strings.iterator()",
" if intIterator.next() == 3 and stringIterator.next() == \"ok\"",
" testSuccess()",
"endpackage"
);
}

@Test
public void genericModuleThistypeSmall() {
testAssertOkLines(true,
test().testLua(true).luaOnly(false).executeProg().lines(
"package test",
" native testSuccess()",
" module LLM",
Expand Down
Loading
Loading