Skip to content
Draft
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
14 changes: 14 additions & 0 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,20 @@ Notes; finished-work narrative does not.
were simply the easiest thing to emit. Method: read the emitted script of a real map next to what
hand-written Lua would be, list every compiler-introduced call, allocation or table write on an
ordinary path, and fix the root (AGENTS.md §3, §7).

- **Give collections a Lua-native backing store instead of carrying the Jass arena.**
Implemented as draft [stdlib #517](https://github.com/wurstscript/WurstStdlib2/pull/517)
and [compiler #1545](https://github.com/wurstscript/WurstScript/pull/1545), using
existing typed array fields rather than adding vector intrinsics. Lua avoids
arena offsets, allocation and relocation; Jass retains its arena. Array buffers
are reset and reused on recycled Wurst IDs, with explicit destruction-time
reference cleanup. [Generated-code benchmark and controls](docs/LUA_COLLECTION_STORAGE.md)
cover growth, scans, small-list churn, scratch reuse and stopped-GC heap growth.
In-game acceptance, long-session retained memory and real-map profiling remain
open; high-water buffer retention and tiny-list costs must be assessed before
release. Result ownership/reduction could then remove the spatial query's
snapshot-to-list copy without breaking yielding or nested callbacks.

## Blocked on a decision

- **Is the generated AST the right shape for the passes?** Generated nodes are single-parent mutable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,39 @@ public int optimize(ImTranslator trans) {
return totalRewrites;
}

/**
* Resolve literal branches before inlining without merging sequential stores into larger expressions.
* Such merging belongs after inlining: doing it here changes the simultaneous register demand of
* otherwise independent inline sites. Boolean rewrites can make statement expressions, so flatten here too.
*/
public int simplifyControlFlow(ImTranslator trans) {
ImProg prog = trans.getImProg();
sideEffectAnalysis = new SideEffectAnalyzer(prog);
jassTarget = !trans.isLuaTarget();
totalRewrites = 0;
simplifyControlFlow(prog);
prog.flatten(trans);
removeUnreachableCode(prog);
return totalRewrites;
}

private void simplifyControlFlow(Element elem) {
for (int i = 0; i < elem.size(); i++) {
simplifyControlFlow(elem.get(i));
}
if (elem instanceof ImOperatorCall call) {
WurstOperator op = call.getOp();
if (op == WurstOperator.NOT || op == WurstOperator.AND || op == WurstOperator.OR
|| call.getArguments().stream().allMatch(ImBoolVal.class::isInstance)) {
optimizeOpCall(call);
}
} else if (elem instanceof ImIf branch) {
optimizeIf(branch);
} else if (elem instanceof ImExitwhen exit) {
optimizeExitwhen(exit);
}
}

@Override
public String getName() {
return "Simple Rewrites";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ public int optimize(ImTranslator trans) {
// so it is important, that we do not optimize away the compiletime constant
continue;
}
if (v.getName().equals("MagicFunctions_isLua") && trans.isLuaTarget()) {
// In Lua mode, isLua must evaluate to true.
// Normal inlining would use the declared value (false); override it here.
if (v.getName().equals("MagicFunctions_isLua")) {
// A backend constant, including when compile-time serialization has left several
// initialization writes. Ordinary global analysis must not keep the other backend's code.
for (ImVarRead read : new ArrayList<>(v.attrReads())) {
read.replaceBy(JassIm.ImBoolVal(true));
read.replaceBy(JassIm.ImBoolVal(trans.isLuaTarget()));
}
for (ImVarWrite write : new ArrayList<>(v.attrWrites())) {
if (write.getParent() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ public void doInlining() {
removeGarbage();
GlobalsInliner globalsInliner = new GlobalsInliner();
globalsInliner.optimize(trans);
// Constants (including Lua's isLua) must choose their branches before the inliner rates
// the callees. Otherwise an empty Lua operation is charged for its entire Jass body and
// survives as a call even after local optimisations remove that body.
new SimpleRewrites().simplifyControlFlow(trans);
ImInliner inliner = new ImInliner(trans);
inliner.doInlining();
trans.assertProperties();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,9 @@ public ImExpr case_ImVoid(ImVoid imVoid) {

@Override
public ImExpr case_ImClassType(ImClassType imClassType) {
return JassIm.ImIntVal(0);
// Keep semantic null until class lowering chooses its representation. Tuple
// lowering uses this on Lua too, where a class null is nil rather than integer 0.
return JassIm.ImNull(imClassType.copy());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
* goes back; only the allocation function of a class nothing allocates (an abstract base), which nothing calls, is
* left without them.
* <p>
* An array field gets a table of its own per object, which IM cannot express; the backend's allocation always makes
* those ({@link #isArrayField}).
* An array field gets a buffer of its own per object, which IM cannot express; the backend initializes those,
* resetting and reusing a buffer when an object ID is recycled ({@link #isArrayField}).
*/
public final class LuaFieldDefaults {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1603,8 +1603,11 @@ private void createClassInitFunction(ImClass c, LuaVariable classVar, LuaFunctio
// The defaults the optimiser did not remove at some allocation of this class (LuaFieldDefaults), and the
// table an array field needs per object, which only the backend can make.
Set<ImVar> survivingDefaults = fieldDefaultsOnAllocation.getOrDefault(c, Collections.emptySet());
LuaVariable arrayBuffer = null;
for (ImVar field : LuaFieldDefaults.fieldsOf(c, imTr)) {
if (LuaFieldDefaults.isArrayField(field) || survivingDefaults.contains(imTr.canonical(field))) {
if (LuaFieldDefaults.isArrayField(field)) {
arrayBuffer = resetArrayField(body, field, newInst, arrayBuffer);
} else if (survivingDefaults.contains(imTr.canonical(field))) {
body.add(LuaAst.LuaAssignment(
LuaAst.LuaExprArrayAccess(LuaAst.LuaExprVarAccess(fieldStorage(field)),
LuaAst.LuaExprlist(LuaAst.LuaExprVarAccess(newInst))),
Expand All @@ -1617,6 +1620,48 @@ private void createClassInitFunction(ImClass c, LuaVariable classVar, LuaFunctio
body.add(LuaAst.LuaReturn(LuaAst.LuaExprVarAccess(newInst)));
}

private @Nullable LuaFunction arrayReset;

/**
* Array fields have no first-class identity in Wurst. Resetting the old buffer is therefore equivalent to
* replacing it, while retaining its capacity across manually recycled object IDs. No Wurst object lifetime
* depends on the Lua collector. Clearing keys invokes no user code, and its order cannot affect the result.
*/
private LuaVariable resetArrayField(LuaStatements body, ImVar field, LuaVariable instance,
@Nullable LuaVariable buffer) {
LuaExpr slot = LuaAst.LuaExprArrayAccess(LuaAst.LuaExprVarAccess(fieldStorage(field)),
LuaAst.LuaExprlist(LuaAst.LuaExprVarAccess(instance)));
if (buffer == null) {
buffer = LuaAst.LuaVariable(uniqueName("array"), slot.copy());
body.add(buffer);
} else {
body.add(LuaAst.LuaAssignment(LuaAst.LuaExprVarAccess(buffer), slot.copy()));
}
LuaVariable metatable = defaultArrayMetatable(arrayComponentType((ImArrayLikeType) field.getType()));
body.add(LuaAst.LuaIf(
LuaAst.LuaExprBinary(LuaAst.LuaExprVarAccess(buffer), LuaAst.LuaOpEquals(), LuaAst.LuaExprNull()),
LuaAst.LuaStatements(LuaAst.LuaAssignment(slot, defaultValue(field.getType()))),
LuaAst.LuaStatements(LuaAst.LuaExprFunctionCall(resetArrayFunction(),
LuaAst.LuaExprlist(LuaAst.LuaExprVarAccess(buffer),
metatable == null ? LuaAst.LuaExprNull() : LuaAst.LuaExprVarAccess(metatable))))));
return buffer;
}

private LuaFunction resetArrayFunction() {
if (arrayReset == null) {
arrayReset = LuaAst.LuaFunction(uniqueName("__wurst_resetArray"),
LuaAst.LuaParams(LuaAst.LuaVariable("t", LuaAst.LuaNoExpr()),
LuaAst.LuaVariable("mt", LuaAst.LuaNoExpr())), LuaAst.LuaStatements());
// A fixed-size helper: the generic for's hidden registers never depend on the user's local count.
arrayReset.getBody().add(LuaAst.LuaLiteral("for k in pairs(t) do t[k] = nil end"));
// Specialised fields share canonical storage. A recycled ID can change its element
// type, so it must get the current default, including removing a previous metatable.
arrayReset.getBody().add(LuaAst.LuaLiteral("setmetatable(t, mt)"));
luaModel.add(arrayReset);
}
return arrayReset;
}

/** Adds to {@code body} the local {@code new_inst}, a fresh or recycled id recorded as an object of {@code classExpr}. */
private LuaVariable addAllocation(LuaStatements body, LuaExpr classExpr) {
LuaVariable newInst = LuaAst.LuaVariable("new_inst", LuaAst.LuaNoExpr());
Expand Down Expand Up @@ -2811,15 +2856,7 @@ public LuaExpr case_ImClassType(ImClassType imClassType) {

@Override
public LuaExpr case_ImArrayTypeMulti(ImArrayTypeMulti at) {
ImType baseType;
if (at.getArraySize().size() <= 1) {
baseType = at.getEntryType();
} else {
List<Integer> arraySizes = new ArrayList<>(at.getArraySize());
arraySizes.remove(0);
baseType = JassIm.ImArrayTypeMulti(at.getEntryType(), arraySizes);
}
return newDefaultArray(baseType);
return newDefaultArray(arrayComponentType(at));
}

@Override
Expand Down Expand Up @@ -2849,6 +2886,15 @@ public LuaExpr case_ImTypeVarRef(ImTypeVarRef imTypeVarRef) {
});
}

private static ImType arrayComponentType(ImArrayLikeType array) {
if (array instanceof ImArrayTypeMulti multi && multi.getArraySize().size() > 1) {
List<Integer> sizes = new ArrayList<>(multi.getArraySize());
sizes.remove(0);
return JassIm.ImArrayTypeMulti(multi.getEntryType(), sizes);
}
return array.getEntryType();
}

/**
* Builds a fresh array table whose reads of never-written slots yield the
* default value for {@code entryType}, matching Jass's fully-initialized
Expand All @@ -2859,16 +2905,22 @@ public LuaExpr case_ImTypeVarRef(ImTypeVarRef imTypeVarRef) {
* per-class instance metatable in translateClass().
*/
private LuaExpr newDefaultArray(ImType entryType) {
LuaVariable metatable = defaultArrayMetatable(entryType);
return metatable == null ? LuaAst.LuaTableConstructor(LuaAst.LuaTableFields())
: setmetatableCall(metatable);
}

private @Nullable LuaVariable defaultArrayMetatable(ImType entryType) {
if (isAlwaysNilDefault(entryType)) {
// An untouched Lua table key already reads as nil - no metatable needed.
return LuaAst.LuaTableConstructor(LuaAst.LuaTableFields());
return null;
}
if (entryType instanceof ImSimpleType imSimpleType) {
return setmetatableCall(getOrCreatePrimitiveArrayMetatable(imSimpleType));
return getOrCreatePrimitiveArrayMetatable(imSimpleType);
}
// Table-typed default (tuple / nested array): each slot needs its own,
// separately mutable default value, materialized lazily on first read.
return setmetatableCall(getOrCreateLazyArrayMetatable(entryType));
return getOrCreateLazyArrayMetatable(entryType);
}

private LuaExpr setmetatableCall(LuaVariable metatableVar) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,26 @@
*/
public class DeterministicChecks extends WurstScriptTest {

@Test
public void recycledArrayBuffersIgnoreCompilationUnitOrder() throws IOException {
CU first = compilationUnit("ArraysA.wurst", "package ArraysA", "public class IntBuffer",
" int array[4] cells");
CU second = compilationUnit("ArraysB.wurst", "package ArraysB", "public class TextBuffer",
" string array[4] cells");
CU main = compilationUnit("Main.wurst", "package Main", "import ArraysA", "import ArraysB",
"native testSuccess()", "init", " let a = new IntBuffer()", " let b = new TextBuffer()",
" a.cells[3] = 42", " b.cells[2] = \"old\"", " destroy a", " destroy b",
" let c = new TextBuffer()", " let d = new IntBuffer()",
" if c.cells[2] == \"\" and d.cells[3] == 0", " testSuccess()");
String name = "recycledArrayBuffers";
testNamed(name).testLua(true).inline().localOptimizations().executeProg()
.compilationUnits(first, second, main);
String forward = compiledLua(name);
testNamed(name).testLua(true).inline().localOptimizations().executeProg()
.compilationUnits(second, main, first);
assertEquals(compiledLua(name), forward);
}

@Test
public void branchNullFactsIgnoreCompilationUnitOrder() throws IOException {
CU program = compilationUnit("NullFacts.wurst",
Expand Down
Loading
Loading