Skip to content
Closed
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
38 changes: 11 additions & 27 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,6 @@ Notes; finished-work narrative does not.
Each repro is a whole program after `package Test` and `native testSuccess()`. The full product
(`WURST_GENERIC_MATRIX=full`) adds no other class of failure.

- **Jass: `this.field instanceof Box<T>` in a generic class fails translation** ("Could not find field
array for this.G_held<integer>"), also for a local captured by a closure, which becomes a field. A
local copy (`let h = held`) compiles, so the matrix reads one:

```wurst
interface Marker
class Box<T:> implements Marker
T item
class G<T:>
Marker held = null
function r() returns boolean
return held instanceof Box<T>
init
let g = new G<int>()
g.held = new Box<int>()
if g.r()
testSuccess()
```

- **Executing tests left off Lua.** Master CI runs every executing test on Lua too (`-PallBackends`) on
its Linux and Windows jobs, whose Lua is 5.3; macOS, with Homebrew's unpinned Lua, does not. The 13
`MISSING_TEST_NATIVE` exemptions wait for natives in `wc3shim.lua`, and `executeTests()` (Wurst `@Test`
Expand All @@ -67,14 +48,17 @@ Notes; finished-work narrative does not.
Bound the Jass search and make the interpreter answer as the backends do (docs/WC3_RUNTIME.md
"Objects and memory").

- **`GetHandleId` of a unit or another agent is the compiler's own counter on Lua.** `LuaNativeLowering`
replaces `GetHandleId` of the `OPAQUE_RUNTIME_HANDLE_TYPES` (unit, item, timer, trigger, ...) with
`__wurst_GetHandleId`, which numbers handles from 1 in `__wurst_objectIndexMap` and keeps every handle it
numbered. The game's ids start at 0x100000 (measured on the 3.0.0 client), as the interpreter's do, so
`InterpreterTests.conversionNativesAsMeasured` is exempt from Lua, and a program which subtracts 0x100000
to index an array reads a negative index there. The tests check the remap's shape
(`LuaTranslationTests.getHandleIdIsRemappedToWurstPolyfillInLua`), not this difference. Call the game's
`GetHandleId`, or record why the remap is needed and document the difference (AGENTS.md §7).
- **`GetHandleId` of an agent on Lua is the compiler's own counter, for a desync nobody measured.**
`LuaNativeLowering` replaces `GetHandleId` of the `OPAQUE_RUNTIME_HANDLE_TYPES` (unit, item, timer, trigger,
...) with `__wurst_GetHandleId`, which numbers handles from 1 in `__wurst_objectIndexMap` and keeps every
handle it numbered reachable. The code gives no reason now; #1181 added it with the note that the game's ids
"can desync in Lua mode", and nothing in the repository measures that. The game's ids are no contract a
program can use either: #1323 saw agent ids from 1048676 up on the 3.0.0 client, the game recycles them, and
they run past a Jass array's bounds even less 0x100000. The interpreter numbers agents from 0x100000 as that
client did, so `InterpreterTests.conversionNativesAsMeasured` is exempt from Lua.
Measure in game whether one agent's `GetHandleId` differs between clients on Lua. If it does not, call the
native and drop the remap with the handles it keeps alive; if it does, record the measurement and document
the difference (AGENTS.md §7).

- **Represent raw Lua helper bindings structurally.** Lua name compression now runs after backend
lowering so it includes descriptors, field storage and resolved dispatch slots. `LuaLiteral` still
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ public void run() {

execute(toExecute);
long tExecuted = System.nanoTime();
if (globalState.typeIdsRead()) {
translator.rememberTypeIdsBeforeGenerics(globalState.genericTypeIdReads());
}

if (functionFlag == FunctionFlagToRun.CompiletimeFunctions) {
emitCompiletimeState();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public WurstflectionProvider(AbstractInterpreter interpreter) {


public ILconstString typeIdToTypeName(ILconstInt typeId) {
interpreter.noteTypeIdsRead();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject generic IDs discovered through reflection

When compile-time code discovers an ID by iterating through maxTypeId() and calling typeIdToTypeName(i), this records only the blanket read flag and never adds the resolved ImClass to genericTypeIdReads. For a new-generic Box<T:>, Jass therefore misses the intended diagnostic: TypeId.keeping leaves the pre-specialization Box ID as an unused gap and assigns Box<int> a later ID, so a discovered and stored constant silently refers to no runtime class. Record the resolved class via noteTypeIdRead (or otherwise reject this indirect read).

AGENTS.md reference: AGENTS.md:L67-L70

Useful? React with 👍 / 👎.

ImProg prog = interpreter.getImProg();
int typeIdInt = typeId.getVal();
for (Map.Entry<ImClass, Integer> e : prog.attrTypeId().entrySet()) {
Expand All @@ -40,14 +41,17 @@ public ILconstString typeIdToTypeName(ILconstInt typeId) {
}

public ILconstInt maxTypeId() {
interpreter.noteTypeIdsRead();
return new ILconstInt(calculateMaxTypeId(interpreter.getImProg()));
}

public ILconstInt instanceCount(ILconstInt typeId) {
interpreter.noteTypeIdsRead();
return new ILconstInt(interpreter.getInstanceCount(typeId.getVal()));
}

public ILconstInt maxInstanceCount(ILconstInt typeId) {
interpreter.noteTypeIdsRead();
return new ILconstInt(interpreter.getMaxInstanceCount(typeId.getVal()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,8 @@ public interface AbstractInterpreter {
int getInstanceCount(int val);

int getMaxInstanceCount(int val);

/** Records that the program read a type id; see {@code ProgramState.noteTypeIdsRead}. */
default void noteTypeIdsRead() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ public static ILconst eval(ImInstanceof e, ProgramState globalState,

public static ILconst eval(ImTypeIdOfClass e,
ProgramState globalState, LocalState localState) {
globalState.noteTypeIdRead(e.getClazz().getClassDef(), e.attrTrace());
return new ILconstInt(e.getClazz().getClassDef().attrTypeId());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,11 @@ public ImProg getImProg() {
return prog;
}

@Override
public void noteTypeIdsRead() {
globalState.noteTypeIdsRead();
}

@Override
public int getInstanceCount(int val) {
long count = 0L;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ public class ProgramState extends State implements AutoCloseable {
/** The key of the one id space all classes share; see {@link #useOneObjectIdSpace}. */
private static final Object SHARED_ID_SPACE = new Object();
private boolean oneObjectIdSpace;
/** Whether the program read a type id; see {@link #noteTypeIdsRead}. */
private boolean typeIdsRead;
/** Where the program first read the type id of each new-generic class; see {@link #noteTypeIdRead}. */
private final Map<ImClass, Element> genericTypeIdReads = new LinkedHashMap<>();
/** See {@link #isGenericHierarchy}; only looked up, never iterated. */
private final Map<ImClass, Boolean> genericHierarchy = new IdentityHashMap<>();
/** See {@link #dispatch}; only looked up, never iterated. */
Expand Down Expand Up @@ -405,9 +409,38 @@ public boolean isGenericHierarchy(ImClass c) {

public int getTypeId(ILconstObject obj, Element trace) {
assertAllocated(obj, trace);
noteTypeIdRead(obj.getImClass(), trace);
return obj.getImClass().attrTypeId();
}

/**
* Records the read of the type id of {@code clazz} at {@code trace}. The interpreter has one class for all the
* instantiations of a new-generic class, as Lua does; Jass makes a class of each after compile time.
*/
public void noteTypeIdRead(ImClass clazz, Element trace) {
noteTypeIdsRead();
if (!clazz.getTypeVariables().isEmpty()) {
genericTypeIdReads.putIfAbsent(clazz, trace);
}
}

public Map<ImClass, Element> genericTypeIdReads() {
return genericTypeIdReads;
}

/**
* Records that the program read a type id, or a number which stands for one: compile-time code may keep it in
* the generated script, so the classes keep their type ids when the generics add classes
* ({@code ImTranslator.rememberTypeIdsBeforeGenerics}).
*/
public void noteTypeIdsRead() {
typeIdsRead = true;
}

public boolean typeIdsRead() {
return typeIdsRead;
}

/** {@code entry} is where the frame is entered: the call, or the function when nothing called it. */
public void pushStackframeWithTypes(ImFunction f, @Nullable ILconstObject receiver,
ILconst[] args, de.peeeq.wurstscript.jassIm.Element entry,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public EliminateClasses(ImTranslator tr, ImProg prog, boolean checkedDispatch) {
translator = tr;
this.prog = prog;
this.checkedDispatch = checkedDispatch;
this.classIds = TypeId.calculate(prog);
this.classIds = tr.typeIds();
}

public void eliminateClasses() {
Expand Down Expand Up @@ -241,7 +241,7 @@ private void eliminateClass(ImClass c) {
}

// create management functions
recycleCodeGen.createAllocFunc(translator, prog, c);
recycleCodeGen.createAllocFunc(translator, prog, c, typeIdOf(c));
recycleCodeGen.createDeallocFunc(translator, prog, c);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,18 @@ public void transform() {
dbg(checkDanglingMethodRefs("end"));

// TODO fix or remove this check
forgetCachedClassStructure();
}

/**
* Specialisation adds classes and rewrites superclass lists, so the type ids and subclass lists cached before
* it (compile-time code reads them through the interpreter) no longer describe the program's classes.
*/
private void forgetCachedClassStructure() {
prog.clearAttributesLocal();
for (ImClass c : prog.getClasses()) {
c.clearAttributesLocal();
}
}

/**
Expand Down Expand Up @@ -171,6 +183,7 @@ public void transformGenericNewOnly(boolean specializeTupleValueTypes, boolean o
if (!specializeTupleValueTypes && !runtimeTypeSpecializations.isEmpty()) {
keepErasedChecksWhereAnAllocationStaysErased();
}
forgetCachedClassStructure();
}

/**
Expand Down Expand Up @@ -3023,20 +3036,23 @@ public void visit(ImAlloc f) {

@Override
public void visit(ImDealloc f) {
super.visit(f);
if (isGenericType(f.getClazz())) {
genericsUses.add(new GenericClazzUse(f));
}
}

@Override
public void visit(ImInstanceof f) {
super.visit(f);
if (isGenericType(f.getClazz())) {
genericsUses.add(new GenericClazzUse(f));
}
}

@Override
public void visit(ImTypeIdOfObj f) {
super.visit(f);
if (isGenericType(f.getClazz())) {
genericsUses.add(new GenericClazzUse(f));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3410,6 +3410,45 @@ public Map<ImClass, ClassManagementVars> getClassManagementVars() {
return classManagementVars;
}

/** The type ids handed out before the generics added classes; see {@link #typeIds()}. */
private @Nullable Map<ImClass, Integer> typeIdsBeforeGenerics;
/** Where compile-time code read the type id of a new-generic class; see {@link #typeIds()}. */
private Map<ImClass, de.peeeq.wurstscript.ast.Element> genericTypeIdReads = Collections.emptyMap();

/**
* Keeps the type ids the classes have now, before the generics are eliminated, as the ids of the program:
* compile-time code read them and may have put them into the script. Only then, since the classes the
* generics add are numbered after them and the ids of the classes they replace stay unused.
*/
public void rememberTypeIdsBeforeGenerics(Map<ImClass, de.peeeq.wurstscript.ast.Element> genericTypeIdReads) {
typeIdsBeforeGenerics = new LinkedHashMap<>(imProg.attrTypeId());
this.genericTypeIdReads = new LinkedHashMap<>(genericTypeIdReads);
}

/** The type ids handed out before the generics, when compile-time code read them; else null. */
public @Nullable Map<ImClass, Integer> typeIdsBeforeGenerics() {
return typeIdsBeforeGenerics;
}

/**
* The type ids of the program's classes on Jass, keeping those handed out before the generics were eliminated.
* Jass makes a class of each instantiation of a new-generic class, so a type id compile-time code read of the
* class it replaced is the id of none of them: that is an error.
*/
public Map<ImClass, Integer> typeIds() {
if (typeIdsBeforeGenerics == null) {
return TypeId.calculate(imProg);
}
for (Map.Entry<ImClass, de.peeeq.wurstscript.ast.Element> read : genericTypeIdReads.entrySet()) {
if (!imProg.getClasses().contains(read.getKey())) {
throw new CompileError(read.getValue().attrSource(), "compile-time code read the type id of "
+ read.getKey().getName() + ", a new-generic class which Jass makes a class of each instantiation"
+ " after compile time, so the id is the id of none of them. Read the type id at run time.");
}
}
return TypeId.keeping(typeIdsBeforeGenerics, imProg.getClasses());
}

public void clearStaleClassManagementVars() {
if (classManagementVars == null) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

public interface RecycleCodeGenerator {

void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c);
void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c, int typeId);

void createDeallocFunc(ImTranslator translator, ImProg prog, ImClass c);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class RecycleCodeGeneratorQueue implements RecycleCodeGenerator {
private @Nullable Supplier<ImExpr> maxSizeElementFn = null;

@Override
public void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c) {
public void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c, int typeId) {
ImFunction f = translator.allocFunc.getFor(c);
prog.getFunctions().add(f);
ImVars locals = f.getLocals();
Expand Down Expand Up @@ -64,7 +64,7 @@ public void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c) {
// this = maxIndex
ifEnoughMemory.add(JassIm.ImSet(tr, JassIm.ImVarAccess(thisVar), JassIm.ImVarAccess(mVars.maxIndex)));
// typeId[this] = ...
ifEnoughMemory.add(JassIm.ImSet(tr, JassIm.ImVarArrayAccess(tr, mVars.typeId, JassIm.ImExprs(JassIm.ImVarAccess(thisVar))), JassIm.ImIntVal(c.attrTypeId())));
ifEnoughMemory.add(JassIm.ImSet(tr, JassIm.ImVarArrayAccess(tr, mVars.typeId, JassIm.ImExprs(JassIm.ImVarAccess(thisVar))), JassIm.ImIntVal(typeId)));
// else:
// error("out of memory")
ifNotEnoughMemory.add(translator.imError(c.getTrace(), JassIm.ImStringVal("Out of memory: Could not create " + c.getName() + ".")));
Expand All @@ -77,7 +77,7 @@ public void createAllocFunc(ImTranslator translator, ImProg prog, ImClass c) {
// this = free[freeCount]
elseBlock.add(JassIm.ImSet(tr, JassIm.ImVarAccess(thisVar), JassIm.ImVarArrayAccess(tr, mVars.free, JassIm.ImExprs(JassIm.ImVarAccess(mVars.freeCount)))));
// typeId[this] = ...
elseBlock.add(JassIm.ImSet(tr, JassIm.ImVarArrayAccess(tr, mVars.typeId, JassIm.ImExprs(JassIm.ImVarAccess(thisVar))), JassIm.ImIntVal(c.attrTypeId())));
elseBlock.add(JassIm.ImSet(tr, JassIm.ImVarArrayAccess(tr, mVars.typeId, JassIm.ImExprs(JassIm.ImVarAccess(thisVar))), JassIm.ImIntVal(typeId)));
// endif


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,36 @@ public static Map<ImClass, Integer> calculate(Collection<ImClass> classesToNumbe
return result;
}

/**
* Type ids for {@code classes} which keep the ids in {@code before} and number the classes not in it after the
* largest of them: compile-time code may have stored an id, so a class which had one keeps it. The checks and
* dispatch built from type ids take a list of ids, so the ids need not be contiguous.
*/
public static Map<ImClass, Integer> keeping(Map<ImClass, Integer> before, Collection<ImClass> classes) {
return keeping(before, classes, TypeId::superClassDefs);
}

/** {@link #keeping(Map, Collection)} along the superclass edges {@code superClasses} gives. */
public static Map<ImClass, Integer> keeping(Map<ImClass, Integer> before, Collection<ImClass> classes,
Function<ImClass, List<ImClass>> superClasses) {
Map<ImClass, Integer> result = Maps.newLinkedHashMap();
List<ImClass> added = new java.util.ArrayList<>();
for (ImClass c : classes) {
Integer id = before.get(c);
if (id != null) {
result.put(c, id);
} else {
added.add(c);
}
}
int offset = before.values().stream().mapToInt(Integer::intValue).max().orElse(0);
java.util.Set<ImClass> addedSet = new java.util.HashSet<>(added);
Map<ImClass, Integer> addedIds = calculate(added, c -> superClasses.apply(c).stream()
.filter(addedSet::contains).collect(Collectors.toList()));
addedIds.forEach((c, id) -> result.put(c, offset + id));
return result;
}

private static List<ImClass> superClassDefs(ImClass c) {
return c.getSuperClasses().stream().map(ImClassType::getClassDef).collect(Collectors.toList());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2988,7 +2988,8 @@ public LuaExprlist translateExprList(ImExprs exprs) {

/**
* The type ids of the Lua program. A targeted specialisation keeps the nominal identity of the class it was
* copied from, so only those classes are numbered, and a copy has the type id of its class.
* copied from, so only those classes are numbered, and a copy has the type id of its class. When compile-time
* code read type ids, the classes keep the ids they had then ({@link ImTranslator#typeIdsBeforeGenerics}).
*/
private @Nullable Map<ImClass, Integer> typeIds;

Expand All @@ -3002,7 +3003,11 @@ Map<ImClass, Integer> typeIds() {
nominal.add(c);
}
}
result = TypeId.calculate(nominal, this::nominalSuperClasses);
// Compile-time code which read a type id may have put it into the script, so those ids stay.
Map<ImClass, Integer> before = imTr.typeIdsBeforeGenerics();
result = before == null
? TypeId.calculate(nominal, this::nominalSuperClasses)
: TypeId.keeping(before, nominal, this::nominalSuperClasses);
typeIds = result;
}
return result;
Expand Down
Loading