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
19 changes: 19 additions & 0 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,25 @@ 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).
- **Lua enum nil tests on gameplay paths, given a common.j constant through a parameter.** A native's
nil-safety wrapper turns a null enum argument into the handle of id 0, and skips that test where the call
passes a common.j constant. On the optimised Lua of a large real map (Oct 2026), that removed 305 of the
471 tests given a constant: 293 in setup code (`InitCustomTeams`, `config`) and 12 elsewhere. The 166
left include every gameplay one: `IsUnitType` 46, `GetUnitState` 29, `GetPlayerState` 13,
`SetUnitState` 12. They reach the native through a standard library parameter that only forwards the
enum (`unit.getState(unitstate state)` calls `GetUnitState(this, state)`), and the constant appears only
once the inliner has removed that function, after the lowering has chosen the test. Two candidate roots;
choose one:
1. In the lowering, move the `p = ConvertX(0)` normalisation of such a parameter to the function's direct
callers, where a constant needs none. This is only sound when every call of the function is seen (not
referenced, not a method implementation, not run by ExecuteFunc, name not preserved), nothing assigns
the parameter and nothing else reads it. Parameters which only forward to each other (mutually
recursive helpers) must also reach a native, or the callers pay for a test nothing needs. A
return-default guard (a null unit) must never move. A prototype of about 100 lines took the map from
494 enum tests to 25 (2 still given a constant), for about −2,900 static Lua instructions.
2. Decide after inlining, where the code reads `t = UNIT_STATE_MAX_LIFE; if t == nil then ...`: the fact
that a common.j constant global is never nil would fold the test there. That belongs to the optimiser,
which is outside this repository's scope.

## Blocked on a decision

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.ast.GlobalVarDef;
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.types.TypesHelper;
Expand Down Expand Up @@ -32,6 +33,8 @@
* {@code boolexpr} and {@code code} typed params are intentionally skipped: these
* are optional/nullable in Jass (e.g. the filter arg of
* {@code TriggerRegisterPlayerUnitEvent}) and passing {@code nil} is valid.
* The guards are chosen per call: an argument which reads a common.j constant is never nil and is
* not tested.
* <p>KNOWN LIMITATION: natives where {@code null} in a non-boolexpr/code handle
* param is a meaningful "clear/reset" argument are silently skipped by the
* wrapper instead of being forwarded. If such a native is identified, add it
Expand Down Expand Up @@ -183,9 +186,11 @@ public static void transform(ImProg prog, ImTranslator translator) {
lowerDivMod(prog, translator);
lowerRealToInt(prog, translator);

// Maps original BJ function → replacement (IS_NATIVE stub or nil-safety wrapper).
// Maps original BJ function → replacement (IS_NATIVE hashtable stub).
// Populated lazily during the traversal.
Map<ImFunction, ImFunction> replacements = new LinkedHashMap<>();
// Nil-safety wrappers by name, one per BJ function and set of guarded parameters.
Map<String, ImFunction> nilSafeWrappers = new LinkedHashMap<>();
Map<String, ImFunction> specialNativeStubs = new LinkedHashMap<>();
// BJ functions that don't need a replacement (not GetHandleId, not hashtable/callback,
// no handle params). Cached to avoid rechecking the same function at every call site.
Expand Down Expand Up @@ -240,39 +245,43 @@ public void visit(ImFunctionCall call) {
}
if (noReplacement.contains(f)) return;

if (!replacements.containsKey(f)) {
ImFunction r = computeReplacement(f);
if (r != null) {
replacements.put(f, r);
ImFunction replacement;
if (LuaHashtable.isNative(f.getName())) {
replacement = replacements.computeIfAbsent(f, bj -> {
// Kept by the translator, so the optimizer and the backend match the stub by identity.
ImFunction stub = translator.luaHashtableStubs.computeIfAbsent(LuaHashtable.stubName(bj.getName()),
stubName -> createNativeStub(stubName, bj));
// A hashtable stub of an earlier run is already in the program, unless it was removed.
if (r.getParent() == null) {
deferredAdditions.add(r);
if (stub.getParent() == null) {
deferredAdditions.add(stub);
}
} else {
noReplacement.add(f);
return stub;
});
} else if (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()];
boolean any = false;
for (int i = 0; i < guarded.length; i++) {
guarded[i] = isGuardedParam(params.get(i)) && !isNeverNil(call.getArguments().get(i), prog);
any |= guarded[i];
}
if (!any) return;
replacement = nilSafeWrappers.computeIfAbsent(nilSafeWrapperName(f, guarded), name -> {
ImFunction wrapper = createNilSafeWrapper(f, guarded, name, translator, deferredAdditions);
deferredAdditions.add(wrapper);
return wrapper;
});
} else {
noReplacement.add(f);
return;
}
ImFunction replacement = replacements.get(f);

if (replacement != null) {
call.replaceBy(JassIm.ImFunctionCall(
call.attrTrace(), replacement,
JassIm.ImTypeArguments(),
call.getArguments().copy(),
false, CallType.NORMAL));
}
}

private ImFunction computeReplacement(ImFunction bj) {
String name = bj.getName();
if (LuaHashtable.isNative(name)) {
// Kept by the translator, so the optimizer and the backend match the stub by identity.
return translator.luaHashtableStubs.computeIfAbsent(LuaHashtable.stubName(name),
stubName -> createNativeStub(stubName, bj));
} else if (hasHandleParam(bj)) {
return createNilSafeWrapper(bj, translator, deferredAdditions);
}
return null;
call.replaceBy(JassIm.ImFunctionCall(
call.attrTrace(), replacement,
JassIm.ImTypeArguments(),
call.getArguments().copy(),
false, CallType.NORMAL));
}
});

Expand Down Expand Up @@ -903,13 +912,14 @@ private static ImType erasedForStub(ImType t) {
}

/**
* Creates a nil-safety wrapper for {@code bjNative}.
* Creates a nil-safety wrapper for {@code bjNative} named {@code name}.
*
* <p>The generated function checks each handle-typed parameter against
* {@code null} and returns the type-appropriate default value if any is
* <p>The generated function checks each parameter marked in {@code guarded}
* against {@code null} and returns the type-appropriate default value if any is
* null. Otherwise it delegates to the original BJ function.
*/
private static ImFunction createNilSafeWrapper(ImFunction bjNative, ImTranslator translator, List<ImFunction> deferredAdditions) {
private static ImFunction createNilSafeWrapper(ImFunction bjNative, boolean[] guarded, String name,
ImTranslator translator, List<ImFunction> deferredAdditions) {
ImVars params = JassIm.ImVars();
List<ImVar> paramVars = new ArrayList<>();
for (ImVar p : bjNative.getParameters()) {
Expand All @@ -920,16 +930,15 @@ private static ImFunction createNilSafeWrapper(ImFunction bjNative, ImTranslator

ImStmts body = JassIm.ImStmts();

// Null-check each required handle param: if param == null then return <default> end
// boolexpr and code params are intentionally skipped because they are optional/nullable
// in Jass (e.g. the filter arg of TriggerRegisterPlayerUnitEvent).
// Null-check each guarded param: if param == null then return <default> end
// A null enum handle is no missing handle: the engine reads it as the handle of id 0, so the
// wrapper passes that one on (measured on the 3.0.0 client: GetUnitState(u, null) is the life,
// IsUnitType(hero, null) is true, GetPlayerState(p, null) is the game result, and
// UnitDamageTarget with a null attack, damage and weapon type deals the damage).
ImExpr returnDefault = defaultValueExpr(bjNative.getReturnType());
for (ImVar param : paramVars) {
if (isHandleType(param.getType()) && !isNullableHandleType(param.getType())) {
for (int i = 0; i < paramVars.size(); i++) {
ImVar param = paramVars.get(i);
if (guarded[i]) {
ImExpr condition = JassIm.ImOperatorCall(WurstOperator.EQ, JassIm.ImExprs(
JassIm.ImVarAccess(param),
JassIm.ImNull(param.getType().copy())
Expand Down Expand Up @@ -973,22 +982,72 @@ private static ImFunction createNilSafeWrapper(ImFunction bjNative, ImTranslator

return JassIm.ImFunction(
bjNative.attrTrace(),
"__wurst_safe_" + bjNative.getName(),
name,
JassIm.ImTypeVars(), params,
bjNative.getReturnType().copy(),
JassIm.ImVars(), body,
Collections.emptyList());
}

private static boolean hasHandleParam(ImFunction f) {
/**
* {@code __wurst_safe_GetUnitState} when every guardable parameter is tested, otherwise with the
* names of the tested ones before the native's ({@code __wurst_safe_whichUnit_GetUnitState}), so a
* call of the wrapper still reads as a call of the native.
*/
private static String nilSafeWrapperName(ImFunction bj, boolean[] guarded) {
StringBuilder name = new StringBuilder("__wurst_safe_");
boolean all = true;
for (int i = 0; i < guarded.length; i++) {
ImVar param = bj.getParameters().get(i);
if (guarded[i]) {
name.append(param.getName()).append('_');
} else if (isGuardedParam(param)) {
all = false;
}
}
return all ? "__wurst_safe_" + bj.getName() : name.append(bj.getName()).toString();
}

private static boolean hasGuardedParam(ImFunction f) {
for (ImVar p : f.getParameters()) {
if (isHandleType(p.getType())) {
if (isGuardedParam(p)) {
return true;
}
}
return false;
}

/**
* A handle parameter which the wrapper tests for null. boolexpr and code params are intentionally skipped
* because they are optional/nullable in Jass (e.g. the filter arg of TriggerRegisterPlayerUnitEvent).
*/
private static boolean isGuardedParam(ImVar param) {
return isHandleType(param.getType()) && !isNullableHandleType(param.getType());
}

/**
* A read of a common.j constant made by its converter ({@code constant unitstate UNIT_STATE_MAX_LIFE =
* ConvertUnitState(1)}). The game defines it before any script runs and nothing can assign it, so it is
* never nil, and an argument which reads it needs no nil test.
*/
private static boolean isNeverNil(ImExpr arg, ImProg prog) {
if (!(arg instanceof ImVarAccess access)) {
return false;
}
ImVar v = access.getVar();
if (!v.getIsBJ() || !(v.getTrace() instanceof GlobalVarDef def) || !def.attrIsConstant()) {
return false;
}
List<ImSet> inits = prog.getGlobalInits().get(v);
return inits != null && inits.size() == 1
&& inits.get(0).getRight() instanceof ImFunctionCall init
&& init.getFunc().isNative() && init.getFunc().isBj()
&& init.getFunc().getName().startsWith("Convert")
&& isHandleType(init.getFunc().getReturnType())
&& init.getArguments().size() == 1
&& init.getArguments().get(0) instanceof ImIntVal;
}

/** Returns true for WC3 handle types (ImSimpleType that is not int/real/boolean/string). */
public static boolean isHandleType(ImType type) {
if (!(type instanceof ImSimpleType imSimpleType)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1219,6 +1219,106 @@ public void aConverterNothingElseCallsIsCreatedForTheNilGuard() throws IOExcepti
assertTrue("a null field is the field of id 0:\n" + wrapper, wrapper.contains("ConvertAbilityIntegerLevelArrayField(0)"));
}

/**
* A common.j constant is never nil, so a native given one is not tested for null there: the guard is chosen
* where the native is called. A local and a global of the program's own may be null and keep the guard, and a
* native whose every guarded argument is a constant is called directly.
*/
@Test
public void aCommonJConstantArgumentIsNotTestedForNil() throws IOException {
test().testLua(true).withStdLib().lines(
"package Test",
"native consume(real r)",
"unitstate userState = UNIT_STATE_MAX_LIFE",
"@noinline function readConstant(unit u)",
" consume(GetUnitState(u, UNIT_STATE_MAX_LIFE))",
"@noinline function readLocal(unit u)",
" var s = UNIT_STATE_LIFE",
" consume(GetUnitState(u, s))",
"@noinline function readUserGlobal(unit u)",
" consume(GetUnitState(u, userState))",
"@noinline function setTime()",
" SetFloatGameState(GAME_STATE_TIME_OF_DAY, 12.)",
"init",
" readConstant(null)",
" readLocal(null)",
" readUserGlobal(null)",
" setTime()");
String compiled = compiledLua("aCommonJConstantArgumentIsNotTestedForNil");

String constant = topLevelFunctionBodyWithPrefix(compiled, "readConstant(");
assertTrue("a constant state takes the wrapper which tests only the unit:\n" + constant,
java.util.regex.Pattern.compile("__wurst_safe_whichUnit_GetUnitState\\(\\w+, UNIT_STATE_MAX_LIFE\\)").matcher(constant).find());
String unitOnly = topLevelFunctionBodyWithPrefix(compiled, "__wurst_safe_whichUnit_GetUnitState(");
assertFalse("no nil test for the constant:\n" + unitOnly, unitOnly.contains("ConvertUnitState"));
assertTrue("the unit is still tested:\n" + unitOnly,
java.util.regex.Pattern.compile("if \\(?\\w+ == nil\\)? then\\s+return 0\\.").matcher(unitOnly).find());

String both = topLevelFunctionBodyWithPrefix(compiled, "__wurst_safe_GetUnitState(");
assertTrue("a state which may be null is still tested:\n" + both,
java.util.regex.Pattern.compile("if \\(?(\\w+) == nil\\)? then\\s+\\1 = ConvertUnitState\\(0\\)").matcher(both).find());
assertTrue("a local keeps the guard:\n" + compiled,
java.util.regex.Pattern.compile("__wurst_safe_GetUnitState\\(\\w+, \\w+\\)")
.matcher(topLevelFunctionBodyWithPrefix(compiled, "readLocal(")).find());
assertTrue("a global of the program's own keeps the guard:\n" + compiled,
java.util.regex.Pattern.compile("__wurst_safe_GetUnitState\\(\\w+, \\w*userState\\)")
.matcher(topLevelFunctionBodyWithPrefix(compiled, "readUserGlobal(")).find());

assertTrue("a native given only constants is called directly:\n" + compiled,
topLevelFunctionBodyWithPrefix(compiled, "setTime(").contains("SetFloatGameState(GAME_STATE_TIME_OF_DAY, 12.)"));
assertFalse("and has no wrapper:\n" + compiled, compiled.contains("__wurst_safe_SetFloatGameState"));
}

/**
* Inlined and optimised, a native given a common.j constant has no nil test before it.
*/
@Test
public void anInlinedCommonJConstantArgumentIsNotTestedForNil() throws IOException {
test().testLua(true).withStdLib().inline().localOptimizations().lines(
"package Test",
"native consume(real r)",
"unit u = null",
"init",
" consume(GetUnitState(u, UNIT_STATE_MAX_LIFE))");
String compiled = compiledLua("anInlinedCommonJConstantArgumentIsNotTestedForNil");
assertTrue("the native is called inline:\n" + compiled,
java.util.regex.Pattern.compile("= GetUnitState\\(\\w+, \\w+\\)").matcher(compiled).find());
assertFalse("no nil test for the constant:\n" + compiled, compiled.contains("ConvertUnitState(0)"));
}

/**
* A common.j constant, a local, a global of the program's own and a null argument read the same player state
* on Lua as on Jass.
*/
@Test
public void aCommonJConstantArgumentReadsTheSameAsAGuardedOne() {
test().withStdLib().executeProg(true).testLua(true).luaOnly(false).lines(
"package Test",
"playerstate userState = PLAYER_STATE_RESOURCE_GOLD",
"@noinline function read(player p, playerstate s) returns int",
" return GetPlayerState(p, s)",
"init",
" let p = Player(1)",
" SetPlayerState(p, PLAYER_STATE_RESOURCE_GOLD, 250)",
" SetPlayerState(p, PLAYER_STATE_RESOURCE_LUMBER, -5)",
" if GetPlayerState(p, PLAYER_STATE_RESOURCE_GOLD) != 250",
" testFail(\"constant gold\")",
" if GetPlayerState(p, PLAYER_STATE_RESOURCE_LUMBER) != 0",
" testFail(\"constant lumber\")",
" if GetPlayerState(p, userState) != 250",
" testFail(\"user global\")",
" if read(p, PLAYER_STATE_RESOURCE_GOLD) != 250",
" testFail(\"parameter\")",
" if read(p, null) != 3",
" testFail(\"null state is the game result\")",
" playerstate noState = null",
" if read(p, noState) != 3",
" testFail(\"null local\")",
" if GetPlayerState(null, PLAYER_STATE_RESOURCE_GOLD) != 0",
" testFail(\"null player\")",
" testSuccess()");
}

/**
* A package whose init fails is reported by the generated script and the program goes on, so a test which
* still reaches testSuccess has run without that package. The harness fails it: 49 tests with the standard
Expand Down
Loading