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
21 changes: 13 additions & 8 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,19 +141,19 @@ Notes; finished-work narrative does not.
the tree while validating. The per-function IM passes need a translator whose caches and generated names are per
function and deterministic. Do not start with the attribute protocol: make the caches, the error handler and the
validator per unit first, and measure that against the 2.6 s of attribute evaluation in the warm check.
- **Make the grammars SLL-clean.** The SLL-first parse (`AntlrTokenPipeline`) parses a file again with the full LL
prediction when SLL does not accept it, which also happens to a few valid files: 2 of the 733 `.wurst` files below
castle fight (one is `util/Cinematic.wurst` of the standard library) and `blizzard.j`, whose trees are the same either
way. Find the decisions of the Wurst and Jass grammars which need the context of the calling rule (the syntax
error the SLL pass reports on such a file, with the full-prediction pass switched off, names the place) and
left-factor them. That removes the second parse for valid files, which would then only be paid by broken ones.
- **Devirtualize proven exact receivers before inlining.** Optimized Lua still dispatches an interface
local initialized with `new A()` virtually when the method has sibling implementations.
`LuaMethodCallLowering` currently considers only methods with no submethods. Start with bounded
straight-line exact-type propagation through locals/copies, stopping at possible destruction,
unknown calls and callback/yield barriers, and use existing direct IM calls. Constructors can expose
or destroy the allocation; preserve their effects. Measure useful sites and total compiler cost
before expanding alias/generic analysis. See the investigation note for emitted examples.
or destroy the allocation; preserve their effects. See the investigation note for emitted examples.
Measured on the optimised Lua of two large maps (Oct 2026): 222 and 456 dispatch sites are left, of which 125
and 105 dispatch on a local assigned a fresh allocation in the same function, nearly all the closure of an
inlined higher-order function. Only 83 and 19 of those have no call between the allocation and the dispatch,
mostly code which runs once (building a UI); 11 and 61 are inside a loop (`forEach`), which needs a
whole-program proof that no call in the loop destroys the receiver; the rest have calls in between. A dispatch
costs about 10 ns more than a direct call in stock Lua, so the straight-line version alone does not pay for
an analysis; start from the loop case, and only with evidence that such a loop is hot.
- **Materialize complex Lua dispatch receivers within a locals budget.** A call-valued receiver still
needs a vararg dispatch stub. A disposable nine-line flatten prototype replaced it with a temporary
and direct descriptor call, passed 378 tests, and the isolated stock-Lua shape was about 28% faster.
Expand Down Expand Up @@ -218,6 +218,11 @@ Notes; finished-work narrative does not.
build-time or memory benefit, or evidence of a substantially smaller correct implementation; speculative future
benefits and raw class counts are insufficient.

- **Making the grammars SLL-clean is not worth it.** The SLL-first parse (`AntlrTokenPipeline`) parses a file again
with the full LL prediction when SLL does not accept it, which also happens to a few valid files (`blizzard.j`,
the standard library's `util/Cinematic.wurst`). In an unoptimised build of a large map that second parse was 2 of
417 samples of the parse threads and none of the main thread's (Oct 2026).

- `%` is real modulo in Wurst; `mod` is integer modulo. `int % 8` types as `real`. `div` and `mod`
return the left operand's type, so `real r = 7 div 2` compiles and is meant to
(`ExpressionTests.integerDivisionOfLiteralsIsStillAssignableToReal`).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import de.peeeq.wurstscript.jassprinter.JassPrinter;
import de.peeeq.wurstscript.luaAst.LuaCompilationUnit;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import de.peeeq.wurstscript.translation.lua.translation.LuaTranslator;
import de.peeeq.wurstscript.translation.lua.translation.LuaAssertions;
import org.eclipse.jdt.annotation.Nullable;

import java.io.File;
Expand Down Expand Up @@ -102,8 +102,7 @@ public CompilationProcess(WurstGui gui, RunArgs runArgs) {
StringBuilder luaOutput = new StringBuilder();
timeTaker.measure("Print Lua", () -> luaCode.print(luaOutput, 0));
mapScript = luaOutput;
LuaTranslator.assertNoLeakedHashtableNativeCalls(mapScript.toString());
LuaTranslator.assertNoLeakedGetHandleIdCalls(mapScript.toString());
LuaAssertions.assertNoLeakedNativeCalls(mapScript.toString());
CharSequence compiledLua = mapScript;
outputMapscript = timeTaker.measure("Write Lua",
() -> writeMapscript(compiledLua));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import de.peeeq.wurstscript.jassprinter.JassPrinter;
import de.peeeq.wurstscript.luaAst.LuaCompilationUnit;
import de.peeeq.wurstscript.parser.WPos;
import de.peeeq.wurstscript.translation.lua.translation.LuaTranslator;
import de.peeeq.wurstscript.translation.lua.translation.LuaAssertions;
import de.peeeq.wurstscript.utils.LineOffsets;
import de.peeeq.wurstscript.utils.Utils;
import net.moonlightflower.wc3libs.bin.app.W3I;
Expand Down Expand Up @@ -263,8 +263,7 @@ protected File compileMap(ModelManager modelManager, File projectFolder, WurstGu
timeTaker.measure("Print Lua", () -> luaCode.get().print(sb, 0));

String compiledMapScript = sb.toString();
LuaTranslator.assertNoLeakedHashtableNativeCalls(compiledMapScript);
LuaTranslator.assertNoLeakedGetHandleIdCalls(compiledMapScript);
LuaAssertions.assertNoLeakedNativeCalls(compiledMapScript);
File buildDir = getBuildDir();
File outFile = new File(buildDir, BUILD_COMPILED_LUA_NAME);
Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,28 @@ private static boolean isDescriptorLookup(LuaExpr receiver, LuaVariable objectCl
|| (variable.getInitialValue() instanceof LuaExprVarAccess alias && alias.getVar() == objectClass);
}

/**
* The checks of {@link #assertNoLeakedHashtableNativeCalls} and {@link #assertNoLeakedGetHandleIdCalls} on one
* scan of the text: what a build runs on its finished script, which is several megabytes for a large map.
*/
public static void assertNoLeakedNativeCalls(String luaCode) {
FunctionNames names = collectFunctionNames(luaCode);
assertNoLeakedHashtableNativeCalls(names);
assertNoLeakedGetHandleIdCalls(names);
}

/**
* Asserts that every emitted call to {@code __wurst_GetHandleId} has a helper definition.
*
* The Lua backend now rewrites only selected opaque runtime-handle families and
* intentionally leaves enum-like handle families on native {@code GetHandleId}.
*/
public static void assertNoLeakedGetHandleIdCalls(String luaCode) {
Set<String> called = collectCalledFunctionNames(luaCode);
Set<String> defined = collectDefinedFunctionNames(luaCode);
if (called.contains("__wurst_GetHandleId") && !defined.contains("__wurst_GetHandleId")) {
assertNoLeakedGetHandleIdCalls(collectFunctionNames(luaCode));
}

private static void assertNoLeakedGetHandleIdCalls(FunctionNames names) {
if (names.called().contains("__wurst_GetHandleId") && !names.defined().contains("__wurst_GetHandleId")) {
throw new RuntimeException(
"Wurst Lua backend assertion failed: __wurst_GetHandleId() call found in generated Lua "
+ "without a matching helper definition.");
Expand All @@ -156,21 +168,23 @@ public static void assertNoLeakedGetHandleIdCalls(String luaCode) {
* save only where one is.
*/
public static void assertNoLeakedHashtableNativeCalls(String luaCode) {
assertNoLeakedHashtableNativeCalls(collectFunctionNames(luaCode));
}

private static void assertNoLeakedHashtableNativeCalls(FunctionNames names) {
List<String> leaked = new ArrayList<>();
List<String> missingHelpers = new ArrayList<>();
Set<String> calledFunctionNames = collectCalledFunctionNames(luaCode);
Set<String> definedFunctionNames = collectDefinedFunctionNames(luaCode);
List<String> helperNames = new ArrayList<>();
for (String nativeName : LuaTranslator.allHashtableNativeNames()) {
if (calledFunctionNames.contains(nativeName)) {
if (names.called().contains(nativeName)) {
leaked.add(nativeName);
}
helperNames.add("__wurst_" + nativeName);
}
helperNames.add(LuaHashtableTranslation.NEW_CHILD);
for (String helperName : helperNames) {
boolean helperCalled = calledFunctionNames.contains(helperName);
boolean helperDefined = definedFunctionNames.contains(helperName);
boolean helperCalled = names.called().contains(helperName);
boolean helperDefined = names.defined().contains(helperName);
if (helperCalled && !helperDefined) {
missingHelpers.add(helperName);
}
Expand All @@ -185,15 +199,22 @@ public static void assertNoLeakedHashtableNativeCalls(String luaCode) {
}
}

/** The names a Lua text calls, and the names it defines as functions. */
record FunctionNames(Set<String> called, Set<String> defined) {
}

/**
* Collects all function names that appear as CALLS in the Lua source.
* Collects the function names that appear as CALLS in the Lua source, and those that
* appear as DEFINITIONS, in one pass.
*
* Skips string literals, comments, and function declaration names (including
* method-syntax declarations like {@code function Foo:bar()} or
* {@code function Foo.bar()}) to avoid false positives.
* A call is an identifier followed by {@code (}. A definition is the last name after the
* {@code function} keyword, simple ({@code function name(}) or method syntax
* ({@code function A:name(} or {@code function A.name(}); the names of a declaration are
* not calls. String literals and comments are skipped.
*/
static Set<String> collectCalledFunctionNames(String text) {
Set<String> result = new HashSet<>();
static FunctionNames collectFunctionNames(String text) {
Set<String> called = new HashSet<>();
Set<String> defined = new HashSet<>();
int length = text.length();
int index = 0;
while (index < length) {
Expand Down Expand Up @@ -228,101 +249,51 @@ static Set<String> collectCalledFunctionNames(String text) {
}
}

// Skip function declarations: after the 'function' keyword the name tokens
// (including A.B or A:B method syntax) are NOT calls.
if (matchesWord(text, index, "function")) {
index = skipFunctionDeclarationName(text, index + "function".length());
continue;
}

// Check identifier followed by '(' → function call
if (isIdentifierStart(ch)) {
// A function declaration: its last name is defined, and none of its names is a call.
if (matchesWord(text, index, "function")) {
String name = declaredFunctionName(text, index + "function".length());
if (name != null) {
defined.add(name);
}
index = skipFunctionDeclarationName(text, index + "function".length());
continue;
}
// An identifier followed by '(' is a call.
int end = scanIdentifierEnd(text, index + 1);
int next = skipWhitespace(text, end);
if (next < length && text.charAt(next) == '(') {
result.add(text.substring(index, end));
called.add(text.substring(index, end));
}
index = end;
continue;
}

index++;
}
return result;
return new FunctionNames(called, defined);
}

/**
* Collects function names that appear as DEFINITIONS in the Lua source.
*
* Handles both simple ({@code function name(}) and method-syntax
* ({@code function A:name(} or {@code function A.name(}) declarations.
* Skips string literals and comments.
* The name a declaration defines: after the {@code function} keyword, the last name of an
* {@code A.B.c} or {@code A:b} chain when a {@code (} follows it, otherwise null.
*/
static Set<String> collectDefinedFunctionNames(String text) {
Set<String> result = new HashSet<>();
private static String declaredFunctionName(String text, int index) {
int length = text.length();
int index = 0;
while (index < length) {
char ch = text.charAt(index);

// Skip comments
if (ch == '-' && index + 1 < length && text.charAt(index + 1) == '-') {
int longLevel = countLongBracketLevel(text, index + 2);
if (longLevel >= 0) {
index = skipLongString(text, index + 2, longLevel);
} else {
while (index < length && text.charAt(index) != '\n') {
index++;
}
}
continue;
}

// Skip string literals
if (ch == '"' || ch == '\'') {
index = skipQuotedString(text, index, ch);
continue;
}
if (ch == '[') {
int longLevel = countLongBracketLevel(text, index);
if (longLevel >= 0) {
index = skipLongString(text, index, longLevel);
continue;
}
}

if (!matchesWord(text, index, "function")) {
index++;
continue;
}

// Skip past 'function', then scan the name
int pos = skipWhitespace(text, index + "function".length());
if (pos >= length || !isIdentifierStart(text.charAt(pos))) {
index++;
continue;
}

// Walk A.B.C or A:B chains, keeping track of the last identifier
String lastName = null;
while (pos < length && isIdentifierStart(text.charAt(pos))) {
int nameEnd = scanIdentifierEnd(text, pos + 1);
lastName = text.substring(pos, nameEnd);
pos = nameEnd;
if (pos < length && (text.charAt(pos) == '.' || text.charAt(pos) == ':')) {
pos++; // consume '.' or ':'
} else {
break;
}
}

int next = skipWhitespace(text, pos);
if (lastName != null && next < length && text.charAt(next) == '(') {
result.add(lastName);
int pos = skipWhitespace(text, index);
String lastName = null;
while (pos < length && isIdentifierStart(text.charAt(pos))) {
int nameEnd = scanIdentifierEnd(text, pos + 1);
lastName = text.substring(pos, nameEnd);
pos = nameEnd;
if (pos < length && (text.charAt(pos) == '.' || text.charAt(pos) == ':')) {
pos++; // consume '.' or ':'
} else {
break;
}
index = pos;
}
return result;
int next = skipWhitespace(text, pos);
return lastName != null && next < length && text.charAt(next) == '(' ? lastName : null;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4378,6 +4378,43 @@ public void getHandleIdAssertionDoesNotFalsePositiveOnDeclarations() {
.assertNoLeakedGetHandleIdCalls("function __wurst_GetHandleId(h) return 0 end\n__wurst_GetHandleId(x)");
}

/** A build runs both checks on one scan of its script: it rejects what either check rejects, with its message. */
@Test
public void combinedNativeCallCheckRejectsWhatEitherCheckRejects() {
String[] scripts = {
"GetHandleId(x)",
"__wurst_GetHandleId(x)",
"function __wurst_GetHandleId(h) return 0 end\n__wurst_GetHandleId(x)",
"SaveInteger(h, 1, 2, 3)",
"local s = \"SaveInteger(h, 1, 2, 3)\"",
"-- LoadInteger(h, 1, 2)",
"function Foo.SaveInteger(h) end",
"__wurst_SaveInteger(h, 1, 2, 3)",
"function __wurst_SaveInteger(h, p, c, v) end\n__wurst_SaveInteger(h, 1, 2, 3)",
"SaveInteger(h, 1, 2, 3)\n__wurst_GetHandleId(x)",
};
boolean[] rejected = {false, true, false, true, false, false, false, true, false, true};
for (int i = 0; i < scripts.length; i++) {
String script = scripts[i];
String separately = rejection(() -> {
LuaAssertions.assertNoLeakedHashtableNativeCalls(script);
LuaAssertions.assertNoLeakedGetHandleIdCalls(script);
});
String combined = rejection(() -> LuaAssertions.assertNoLeakedNativeCalls(script));
assertEquals(script, rejected[i], separately != null);
assertEquals(script, separately, combined);
}
}

private static String rejection(Runnable check) {
try {
check.run();
return null;
} catch (RuntimeException e) {
return e.getMessage();
}
}

// ----- Null-safe extern native wrappers -----

@Test
Expand Down
Loading