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
Original file line number Diff line number Diff line change
Expand Up @@ -316,14 +316,8 @@ public static Result flatten(ImReturn s, ImTranslator t, ImFunction f) {


public static Result flatten(ImSet s, ImTranslator t, ImFunction f) {
Result l = s.getLeft().flatten(t, f);
Result r = s.getRight().flatten(t, f);
List<ImStmt> stmts = new ArrayList<>(l.stmts.size() + r.stmts.size() + 1);
stmts.addAll(l.stmts);
stmts.addAll(r.stmts);
ImSet replacement = JassIm.ImSet(s.getTrace(), (ImLExpr) l.expr, r.expr);
// Flatten moves the operands out of s. Initializer metadata must follow the replacement,
// rather than retaining the abandoned assignment with children now owned by another node.
// Keep a complete lazy initializer before lowering moves its operands. Sharing the replacement
// lets later inlining replace its arguments with locals, which do not exist during a lazy read.
ImVar variable = s.getLeft() instanceof ImVarAccess access ? access.getVar()
: s.getLeft() instanceof ImVarArrayAccess access ? access.getVar() : null;
List<ImSet> initializers = variable == null ? null : t.imProg().getGlobalInits().get(variable);
Expand All @@ -334,9 +328,15 @@ public static Result flatten(ImSet s, ImTranslator t, ImFunction f) {
initializers = new ArrayList<>(initializers);
t.imProg().getGlobalInits().put(variable, initializers);
}
initializers.set(i, replacement);
initializers.set(i, s.copy());
}
}
Result l = s.getLeft().flatten(t, f);
Result r = s.getRight().flatten(t, f);
List<ImStmt> stmts = new ArrayList<>(l.stmts.size() + r.stmts.size() + 1);
stmts.addAll(l.stmts);
stmts.addAll(r.stmts);
ImSet replacement = JassIm.ImSet(s.getTrace(), (ImLExpr) l.expr, r.expr);
stmts.add(replacement);
return new Result(stmts);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ public void visit(ImFunctionCall call) {
}
return stub;
});
} else if (hasGuardedParam(f)) {
} else if (f.isNative() && hasGuardedParam(f)) {
// Decided per call: an argument which is never nil needs no test.
List<ImVar> params = f.getParameters();
boolean[] guarded = new boolean[params.size()];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class ImMetadataAdapterTests {
assertNotEquals(function.sourceModificationCount(), source);
}

@Test public void flattenKeepsInitializerMetadataPointingAtTheOwnedReplacement() {
@Test public void flattenKeepsAnIndependentCompleteLazyInitializer() {
var trace = de.peeeq.wurstscript.ast.Ast.NoExpr();
var translator = new de.peeeq.wurstscript.translation.imtranslation.ImTranslator(
de.peeeq.wurstscript.ast.Ast.WurstModel(), false, new de.peeeq.wurstscript.RunArgs("-lua"));
Expand All @@ -38,10 +38,35 @@ public class ImMetadataAdapterTests {
translator.imProg().getGlobalInits().put(variable, List.of(initializer));
function.flatten(translator);
var current = translator.imProg().getGlobalInits().get(variable).getFirst();
assertSame(current, function.getBody().getFirst());
assertNotSame(current, function.getBody().getFirst());
((de.peeeq.wurstscript.jassIm.ImSet) function.getBody().getFirst()).setRight(JassIm.ImIntVal(9));
assertEquals(((de.peeeq.wurstscript.jassIm.ImIntVal) current.getRight()).getValI(), 7);
NodeGraphs.validate(current);
}

@Test public void flattenKeepsStatementsNeededByALazyInitializer() {
var trace = de.peeeq.wurstscript.ast.Ast.NoExpr();
var translator = new de.peeeq.wurstscript.translation.imtranslation.ImTranslator(
de.peeeq.wurstscript.ast.Ast.WurstModel(), false, new de.peeeq.wurstscript.RunArgs());
var variable = JassIm.ImVar(trace, JassIm.ImSimpleType("int"), "global", false);
var temporary = JassIm.ImVar(trace, JassIm.ImSimpleType("int"), "temporary", false);
var initializer = JassIm.ImSet(trace, JassIm.ImVarAccess(variable), JassIm.ImStatementExpr(
JassIm.ImStmts(JassIm.ImSet(trace, JassIm.ImVarAccess(temporary), JassIm.ImIntVal(7))),
JassIm.ImVarAccess(temporary)));
var function = JassIm.ImFunction(trace, "initialize", JassIm.ImTypeVars(), JassIm.ImVars(),
JassIm.ImVoid(), JassIm.ImVars(temporary), JassIm.ImStmts(initializer), new ArrayList<>());
translator.imProg().getGlobals().add(variable);
translator.imProg().getFunctions().add(function);
translator.imProg().getGlobalInits().put(variable, List.of(initializer));
function.flatten(translator);
var state = new de.peeeq.wurstscript.intermediatelang.interpreter.ProgramState(
new de.peeeq.wurstscript.gui.WurstGuiCliImpl(), translator.imProg(), true);
var value = JassIm.ImVarAccess(variable).evaluate(state,
new de.peeeq.wurstscript.intermediatelang.interpreter.LocalState());
assertEquals(value, de.peeeq.wurstscript.intermediatelang.ILconstInt.create(7));
NodeGraphs.validate(translator.imProg().getGlobalInits().get(variable).getFirst());
}

@Test public void insertionOrderedFastutilMapsKeepNonComparableImKeysAndRepairTheirReferences() {
var first=JassIm.ImSimpleType("first");var second=JassIm.ImSimpleType("second");
var firstCopy=JassIm.ImSimpleType("first");var secondCopy=JassIm.ImSimpleType("second");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1183,9 +1183,19 @@ public void aNullEnumHandleIsTheHandleOfIdZeroOnLua() throws IOException {
assertTrue("a null unit type is UNIT_TYPE_HERO:\n" + type, type.contains("ConvertUnitType(0)"));
}

@Test
public void aBlizzardHelperEvaluatesNullUsingItsOwnBody() {
test().testLua(true).withStdLib().executeProg().lines(
"package Test",
"init",
" if not IsUnitDeadBJ(null)",
" testFail(\"IsUnitDeadBJ(null) must read the null unit's zero life\")",
" testSuccess()");
}

/**
* Only a native reads a null enum handle as id 0. A blizzard.j helper sees the null, which Jass keeps, so its
* guard answers the default as for any other null handle rather than handing the helper the id-0 handle:
* call passes null through rather than handing the helper the id-0 handle:
* RemovePlayerPreserveUnitsBJ compares its game result with PLAYER_GAME_RESULT_VICTORY before any native.
*/
@Test
Expand All @@ -1197,8 +1207,11 @@ public void aBlizzardHelperIsNotHandedTheHandleOfIdZero() throws IOException {
"init",
" remove(null, null)");
String compiled = compiledLua("aBlizzardHelperIsNotHandedTheHandleOfIdZero");
String wrapper = topLevelFunctionBodyWithPrefix(compiled, "__wurst_safe_RemovePlayerPreserveUnitsBJ");
assertFalse("a helper sees the null:\n" + wrapper, wrapper.contains("ConvertPlayerGameResult"));
String caller = topLevelFunctionBodyWithPrefix(compiled, "remove");
assertTrue("call the Blizzard helper directly:\n" + caller, caller.contains("RemovePlayerPreserveUnitsBJ("));
assertFalse("a helper needs no native nil guard:\n" + compiled,
compiled.contains("__wurst_safe_RemovePlayerPreserveUnitsBJ"));
assertFalse("a helper sees the null:\n" + caller, caller.contains("ConvertPlayerGameResult"));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,8 @@ function DestroyForce(f) end
function ForceAddPlayer(f, p) f.members[p.id] = p end
function ForceRemovePlayer(f, p) f.members[p.id] = nil end
function ForceClear(f) f.members = {} end
function IsPlayerInForce(p, f) return f.members[p.id] ~= nil end
-- A null player or force is not a member, matching the native null-handle default.
function IsPlayerInForce(p, f) return p ~= nil and f ~= nil and f.members[p.id] ~= nil end
local enumPlayers = {}
function GetEnumPlayer() return enumPlayers[#enumPlayers] end
function ForForce(f, callback)
Expand Down Expand Up @@ -417,6 +418,11 @@ end
-- A killed unit stays in its groups (measured on the 3.0.0 client).
function KillUnit(u) u.dead = true end
function GetUnitTypeId(u) return u.typeId end
-- Null-handle defaults let Blizzard helpers evaluate their own conditions. Live unit state is not modeled.
function GetUnitState(u, state)
if u == nil then return 0 end
error("GetUnitState: live unit state is not modeled by the test runtime")
end
function CreateDestructable(objectId, x, y, face, scale, variation)
return { typeId = objectId, x = x, y = y, face = face, scale = scale, variation = variation }
end
Expand Down
2 changes: 1 addition & 1 deletion docs/WC3_RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ A test that passes in the first two columns says nothing about the third where t
* **code** The natives of the standard library's `Reflection` read this bookkeeping. A type id numbers a class from 1 (`TypeId`: by package, name and source position, each class followed by its subclasses); when compile-time code read a type id, the classes keep the ids they had then and Jass numbers the classes the generics add after them (`TypeId.keeping`), so an id stored at compile time stays its class's; `maxTypeId` is the largest and `typeIdToTypeName` the class's qualified name. `instanceCount` is the number of live objects of the class's allocator group, not of the class alone, and `maxInstanceCount` the most the group had alive at once, which on Jass is the group's highest id (`EliminateClasses`). Lua has no group allocator, so it keeps a live count and a peak per group, updated by the allocations and destroys of the group's classes, only in a program which calls these natives and only for the groups it can ask about (`LuaReflection`). Lua numbers the classes the emitted program keeps, except the copies a targeted specialisation makes, which have the type id and the group of the class they copy (`LuaTranslator.getTypeId`); a program which can see the numbering (`maxTypeId`, or a type id which is not `C.typeId` or `o.typeId`) keeps every class, so its numbers are Jass's. A number which is no type id answers `"unknown"` and 0 on both targets and in the interpreter. Two differences remain, both pinned in `LuaTranslationTests`: the Jass replay of compile-time objects sets the group's highest id to the highest one used at compile time, so the ids of the objects destroyed or dropped then count as live there, while Lua counts only the objects it makes again (compile-time code numbers a new-generic class's objects as the erased class's, so each instantiation's group continues after the highest id of them all: `CompiletimeFunctionRunner.emitJassObjectAllocs`); and a new-generic class is a class per instantiation on Jass but one erased class on Lua (AGENTS.md §9), so with `Box<T:>` and `Sub<T:> extends Box<T>`, `Box<int>`, `Sub<int>` and `Box<string>` are type ids 1, 2 and 3 in two groups on Jass, while Lua has the type ids 1 and 2 in one group which counts all three objects. Matching that would take a class per instantiation on Lua, or the type arguments at every allocation, which erased generic code does not have. The interpreter counts each allocator group's live objects and their peak as the targets do.

* **measured, 3.0.0** Hashtables: a handle load is typed (a saved unit loads as itself through `LoadUnitHandle` and `LoadWidgetHandle`, as null through `LoadItemHandle` or `LoadTimerHandle`); saving a null handle stores nothing and keeps what was there; `FlushParentHashtable` destroys the hashtable, so nothing saved to it afterwards stays and every load answers its default; a null hashtable answers every load with its default and ignores every write. The Lua emulation (`LuaHashtable`) and the interpreter (`HashtableProvider`) answer the same. A handle saved through a supertype (`SaveAgentHandle`, `SaveWidgetHandle`) and loaded as a subtype is answered on Lua, which cannot tell its type.
* **measured, 3.0.0** A null enum handle (a type which a common.j `ConvertX(integer)` native makes, such as `unitstate`, `unittype`, `playerstate`, `attacktype`, `damagetype`) is the handle of id 0 to the engine: `GetUnitState(u, null)` is the life, `IsUnitType(hero, null)` is true (`UNIT_TYPE_HERO`), `GetPlayerState(p, null)` is the game result, `SetPlayerState(p, null, v)` writes it, and `UnitDamageTarget` with a null attack, damage and weapon type deals the damage. The Lua backend's nil guard of a handle native therefore passes `ConvertX(0)` for a nil enum argument and answers the native's default only for any other nil handle; a blizzard.j helper keeps the null, as Jass does until a native reads it, so its guard answers the default (`LuaNativeLowering.createNilSafeWrapper`, `ImTranslator.enumConverter`). The interpreter's mocks of `IsUnitType`, `GetUnitState`, `GetPlayerState` and `SetPlayerState` read a null enum as id 0 too, and the game result is 3 (`PLAYER_GAME_RESULT_NEUTRAL`) while the game runs.
* **measured, 3.0.0** A null enum handle (a type which a common.j `ConvertX(integer)` native makes, such as `unitstate`, `unittype`, `playerstate`, `attacktype`, `damagetype`) is the handle of id 0 to the engine: `GetUnitState(u, null)` is the life, `IsUnitType(hero, null)` is true (`UNIT_TYPE_HERO`), `GetPlayerState(p, null)` is the game result, `SetPlayerState(p, null, v)` writes it, and `UnitDamageTarget` with a null attack, damage and weapon type deals the damage. The Lua backend's nil guard of a handle native therefore passes `ConvertX(0)` for a nil enum argument and answers the native's default only for any other nil handle; a blizzard.j helper is called directly and its body decides how to handle the null, as Jass does until a native reads it (`LuaNativeLowering.createNilSafeWrapper`, `ImTranslator.enumConverter`). The interpreter's mocks of `IsUnitType`, `GetUnitState`, `GetPlayerState` and `SetPlayerState` read a null enum as id 0 too, and the game result is 3 (`PLAYER_GAME_RESULT_NEUTRAL`) while the game runs.
* **measured, 3.0.0** Null strings: Jass keeps null and `""` apart (`null == ""` is false; an unset string array element, field or global is null; `SubString` past the end, any `SubString` of `""` and `StringCase("")` answer null; `StringLength`, `S2I`, `S2R` and `StringHash` of null answer 0, as of `""`). The game's Lua natives answer `""` in each of those places, and every string native probed raises on a nil argument ("string expected, got nil": `StringLength`, `SubString`, `StringCase`, `S2I`, `S2R`, `StringHash`, `GetLocalizedString`, `BlzSetUnitName`, `SetTextTagText`, `BlzFrameSetText`, `DisplayTextToPlayer`). So on Lua the null string is `""`, as the game's natives treat it (`EliminateLocalTypes`), and nothing the compiler emits answers nil for a string: the emulated `LoadStr` answers `""` when nothing is stored. `null == ""` is therefore true on Lua and false on Jass; matching Jass would mean wrapping every native which returns a string. In Jass, `BlzSetUnitName(u, null)` crashes the client.

## Jass function parameters
Expand Down
Loading