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
164 changes: 79 additions & 85 deletions AGENTS.md

Large diffs are not rendered by default.

16 changes: 14 additions & 2 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,21 @@ Notes; finished-work narrative does not.
The note records the cross-backend key/value contract, existing intrinsic reuse, specialization
requirements, and regression cases; the data structure itself is not implemented.

- **Audit the remaining Lua emission for waste.** The Lua backend began as "make Lua mode usable", and
recent fixes (`git log --grep "Lua"`) keep finding helper calls, allocations and dead bindings that
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).

## Blocked on a decision

- **Is the generated AST the right shape for the passes?** Generated nodes are single-parent mutable
trees: a node that already has a parent cannot be placed elsewhere (`setParent` throws), so the passes
copy (`.copy()`) and splice (`replaceBy`) throughout, and attribute caches are cleared by hand
(`clearAttributes`). Whether an immutable or persistent IM, or a different rewrite API in
abstractsyntaxgen, would make passes simpler or faster has no recorded evaluation. A proposal needs a
baseline (compile time on a large map) and one pass ported as a trial. Do not start it autonomously.

- **Replacing `castTo int` in the old generic containers.** The motivating case is timer data
attachment (`ClosureTimers.wurst`) and the containers behind it: `Table`, `HashList`, `HashSet`,
`HashMap`. These old generics erase values into a shared integer ID space. Removing those casts
Expand All @@ -34,8 +47,7 @@ Notes; finished-work narrative does not.
- `%` 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`).
- Emitted Lua must be byte-identical for identical input (AGENTS.md §8), and emitted Jass can be
diffed across runs too. `LuaTranslationTests.luaOutputIsDeterministicForGenericOverrideSlots`
- Emitted Jass and Lua must be byte-identical for identical input (AGENTS.md §3). `LuaTranslationTests.luaOutputIsDeterministicForGenericOverrideSlots`
failed once on Windows CI and never again in 250 local compiles; the test now writes both scripts
and names the first differing lines, so the next occurrence will say what differed. Do not weaken it.
- A name that looks redundant is usually carrying a distinction. The mangled method name separates
Expand Down
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@AGENTS.md
2 changes: 1 addition & 1 deletion README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ For building the release packages (compiler jar, bundled runtime and the `wursts

You can import the compiler project into any IDE that provides a gradle plugin.
For IntelliJ IDEA, you can simply execute `./gradlew openIdea`.
To run the Test Suite, execute `AllTests.xml` with TestNG.
To run the test suite, execute `./gradlew test` in `de.peeeq.wurstscript`.

### Publishing a new release

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
import java.util.function.Supplier;

/**
* Manages object ids in a queue. This way the time each object is
* inactive is maximized and thus errors should be easier to detect
* Manages object ids, one allocator for each group of classes joined by inheritance
* ({@code ImTranslator.buildClassPartitions}). Despite the name the free list is a stack: the most
* recently freed id is handed out first, so a stale reference to it reads the next object
* (docs/WC3_RUNTIME.md).
*/
public class RecycleCodeGeneratorQueue implements RecycleCodeGenerator {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,119 @@ public void luaErrorWrappersAvoidUnavailableNativeTraceback() throws IOException
assertFalse(compiled.contains("debug.traceback"));
}

/**
* The game's Lua is not the test runtime's Lua. The tests run a stock Lua with every library, while
* the game is reported to withhold debug and collectgarbage, and nothing in emitted code needs io, os,
* package or require, which are not known to exist there. A test which executes the emitted script
* cannot notice a helper that reaches for one, so assert it on the text instead, over a program that
* makes the backend emit its helpers: object management, dispatch, callback boundaries, the error
* handler and stack positions. Helpers emitted only on demand are out of this program's reach:
* {@link #noLuaBackendLiteralNamesALibraryTheGameWithholds} scans for those. See docs/WC3_RUNTIME.md.
*/
@Test
public void emittedLuaUsesOnlyLibrariesTheGameProvides() {
CU errorHandling = new CU("ErrorHandling.wurst", String.join("\n",
"package ErrorHandling",
"public function error(string msg)",
" skip"));
String compiled = compileLuaWithCUs(
"LuaTranslationTests_emittedLuaUsesOnlyLibrariesTheGameProvides",
false,
Collections.singletonList(errorHandling),
"package Test",
Comment thread
Frotty marked this conversation as resolved.
Resolved
Comment thread
Frotty marked this conversation as resolved.
Resolved
"import ErrorHandling",
"native apply(code c)",
"native I2S(int i) returns string",
"interface Shape",
" function area() returns int",
"class Square implements Shape",
" int side",
" construct(int side)",
" this.side = side",
" override function area() returns int",
" return side * side",
" ondestroy",
" skip",
"function describe(Shape s, string label) returns string",
" return label + \": \" + I2S(s.area())",
"init",
" let s = new Square(3)",
" apply(() -> error(\"callback\"))",
" error(describe(s, \"init\"))",
" destroy s"
);
String withheld = firstWithheldLibraryUse(compiled);
if (withheld != null) {
fail("emitted Lua uses `" + withheld + "`, which the game does not provide:\n" + compiled);
}
}

/**
* Everything the backend emits starts as a string literal under translation/, whether or not a program
* makes it emit: a native only when it is referenced, an old-generics cast helper only when a cast cannot
* be written inline. The output of any one program, or of the whole suite, cannot show that no helper
* reaches for a library the game withholds, so scan the literals themselves.
*/
@Test
public void noLuaBackendLiteralNamesALibraryTheGameWithholds() throws IOException {
Pattern literal = Pattern.compile("\"((?:[^\"\\\\]|\\\\.)*)\"");
Pattern bareName = Pattern.compile("os|io|debug|package|require|collectgarbage|dofile|loadfile");
// lists of names to protect or avoid, not emitted code
Set<String> nameLists = Set.of("LuaReservedNames.java", "RestrictedCompressedNames.java");
// The shim which ends a test run. A map never declares testSuccess, so it is not emitted into one.
// Exempt only the os.exit() inside the testSuccess registration, not any other literal in the file.
String testOnlyFile = "LuaNatives.java";
String testOnlyRegistration = "addNative(\"testSuccess\"";
String testOnlyText = "os.exit()";
List<String> found = new ArrayList<>();
try (java.util.stream.Stream<java.nio.file.Path> walk =
java.nio.file.Files.walk(java.nio.file.Paths.get("src/main/java/de/peeeq/wurstscript/translation"))) {
List<java.nio.file.Path> sources = walk.filter(p -> p.toString().endsWith(".java"))
.sorted().collect(Collectors.toList());
for (java.nio.file.Path source : sources) {
String fileName = source.getFileName().toString();
if (nameLists.contains(fileName)) {
continue;
}
List<String> lines = java.nio.file.Files.readAllLines(source);
String registration = ""; // the addNative(...) line whose body is being read
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).contains("addNative(")) {
registration = lines.get(i);
}
String trimmed = lines.get(i).trim();
if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*")) {
continue;
}
Matcher quoted = literal.matcher(lines.get(i));
while (quoted.find()) {
String text = quoted.group(1);
boolean withheld = bareName.matcher(text).matches() || firstWithheldLibraryUse(text) != null;
boolean testOnly = fileName.equals(testOnlyFile) && text.equals(testOnlyText)
&& registration.contains(testOnlyRegistration);
if (withheld && !testOnly) {
found.add(source.getFileName() + ":" + (i + 1) + ": \"" + text + "\"");
}
}
}
}
}
assertTrue("the Lua backend names a library or function the game does not provide. If it only exists "
+ "for tests, exempt it in this test:\n" + String.join("\n", found), found.isEmpty());
}

/**
* The first use of a library or function the game withholds in {@code lua}, or null. Any occurrence
* counts, inside a Lua string or comment too: a string can be run with {@code load}, so skipping strings
* would let a use through unseen, while a false alarm is loud and cheap to exempt in the caller.
*/
private static String firstWithheldLibraryUse(String lua) {
Matcher withheld = Pattern.compile(
"(?<![\\w.])(?:debug|io|package|os)\\s*\\.\\s*\\w+"
+ "|(?<![\\w.])(?:collectgarbage|dofile|loadfile|require)\\s*\\(").matcher(lua);
return withheld.find() ? withheld.group() : null;
}

@Test
public void continueLoweringInLua() throws IOException {
test().testLua(true).lines(
Expand Down
53 changes: 53 additions & 0 deletions docs/WC3_RUNTIME.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Warcraft III runtime facts for compiler work

What the game does that the compiler, the optimiser and the interpreter mocks have to respect. The game is the specification. The places a reader would look instead (Blizzard.j, the IM interpreter, the Lua test runtime) each differ from it, so every fact here says how it is known:

* **measured**: observed in the real client, version given. Do not overturn one by reading code; measure again.
* **code**: follows from what this repository emits or does; the pointer is the evidence.
* **reported**: community documentation, not measured here. Likely, not proven.

The rules that follow are in [AGENTS.md](../AGENTS.md) §7 and §11.

## Three places code runs, one of them is the game

| | IM interpreter (compile time, `executeProg()`) | Test Lua (`testLua(true).executeProg()`) | The game |
|---|---|---|---|
| Reals | Java `float`, round to nearest (code: `ILconstReal`) | Lua doubles (a stock Lua: 5.3 on Windows and the Linux CI, unchecked elsewhere) | Jass: 32-bit, literals not correctly rounded. Lua: 24-bit mantissa, arithmetic truncates (measured, below) |
| Lua libraries | none | every standard library of that interpreter; `os.exit()` is how `testSuccess` ends a run (code: `LuaNatives`) | Lua 5.3 without some of them (reported, below) |
| Natives | mocks in `wurstio/jassinterpreter/providers` | `wc3shim.lua` plus the Reforged `common.j`/`blizzard.j` Lua dumps (`src/test/resources/luaruntime/README.md`) | the engine |

A test that passes in the first two columns says nothing about the third where they differ. The natives `LuaNatives` defines for a Jass native name (such as `GetRandomInt`) are fallbacks: the script defines one only if the game has not, so the real implementation wins (`LuaTranslator.translateFunc`). The `__wurst_`-prefixed ones are Wurst's own, never pre-defined by the game, and emitted without that guard.

## Objects and memory

* **code** Wurst has no garbage collector. A class instance is an integer id on both targets. `new` takes an id, `destroy` runs `ondestroy` and gives the id back, and a second `destroy` is an error (`Double free: object of type X` on Jass, `Double free or invalid Wurst object.` on Lua). A closure is a class instance too and keeps its id until destroyed. (`RecycleCodeGeneratorQueue`, `LuaTranslator.createObjectManagement`.)
* **code** Both targets reuse the most recently freed id first (a stack, despite the name `RecycleCodeGeneratorQueue`), so `destroy` followed by `new` from the same allocator returns the same id and a stale reference then reads the new object. On Jass each group of classes joined by inheritance (a class with its `superClasses`, `ImTranslator.buildClassPartitions`) has one allocator: a subclass, its siblings and the base class share ids and the cap, so a stale id may come back as an object of a related class. The group runs out at `JASS_MAX_ARRAY_SIZE` live instances (default `Constants.MAX_ARRAY_SIZE`, 32768) with `Out of memory: Could not create X.`. On Lua there is one id space shared by every class and no cap, so a stale id may come back as an object of any class.
* **code** Lua keeps one static table per field, indexed by id, and a class descriptor per live id. `destroy` removes the descriptor and recycles the id; field storage is not cleared, as Jass arrays are not. Until the id is reused a stale reference fails virtual dispatch and `instanceof` is false. Lua's collector therefore frees no Wurst object, and a table stored in a field stays reachable after `destroy`.

## The game's Lua

* **reported** It is Lua 5.3, with `debug` disabled ([Hive guide](https://www.hiveworkshop.com/threads/a-comprehensive-guide-to-mapping-in-lua.341880/)) and `collectgarbage` inaccessible since a patch, "it could cause desync" ([forum post](https://www.hiveworkshop.com/threads/wc3-reforged-lua.326354/)). The repository already treats `debug.traceback` as unavailable (`LuaTranslationTests.luaErrorWrappersAvoidUnavailableNativeTraceback`). Nothing in emitted code needs `io`, `os`, `package` or `require`; they are not known to exist there. `LuaTranslationTests.emittedLuaUsesOnlyLibrariesTheGameProvides` fails if a program's emitted helpers reach for any of these. `noLuaBackendLiteralNamesALibraryTheGameWithholds` scans the string literals under `translation/` (bar two files that only list names), because natives and fallback helpers are emitted only on demand. A name counts anywhere in the text, inside a Lua string or comment too, since a string can be run with `load`. Only the test-only `testSuccess` is exempt: it ends a test run with `os.exit`.
* **code** `debug.traceback` is not used (above), so `-stacktraces` keeps its own call stack in the script (`StackTraceInjector2`: `wurst_stack`, `wurst_stack_depth`). Each call of an instrumented function pays for it: an extra position argument at the call site, a push and a pop in the callee. `main` and `config` are skipped. `wurst_run.args` defaults to `-stacktraces` without `-inline` (`WurstCommands.defaultArgs`).
* **code** A function reference (a `code` value, such as one handed to a native) gets an `xpcall` adapter (`LuaTranslator.callbackAdapterFor`) and package init is `xpcall`-wrapped, so an error is reported through the Wurst error function when the program has one, else through `BJDebugMsg`.
* **code** The reference Lua 5.3 neither inlines a local function call nor caches a global or library lookup: `luac -l` on a loop that calls a one-line local function and reads a global and `math.floor` shows a `CALL` for the function and a `GETTABUP`/`SETTABUP` or `GETTABUP`+`GETTABLE` for each access, every iteration. If the game's VM is the reference 5.3 (reported above), every helper call, global read, table index and allocation the compiler leaves in runs, and the compiler's inliner and local optimisations are the only optimiser.
* **code** Jass has no `throw`. `I2S(1 div 0)` is the deliberate thread abort (`ErrorHandling.error()` ends with it); Lua lowers exactly that shape to `error("__wurst_abort_thread", 0)`, which the callback handlers ignore (`ExprTranslation.isIntentionalThreadAbortCall`, `LuaNativeLowering`). Folding or reshaping it breaks the abort (`LuaBackendAuditTests`, `OptimizerTests`).

## Lockstep

Every client simulates the same game from the same inputs; anything that makes the simulation differ between machines desyncs it.

* **reported** The iteration order of `pairs()` is not the same for different players ([SyncedTable](https://www.hiveworkshop.com/threads/syncedtable.332894/)). So emitted Lua and stdlib code that compiles to Lua never iterate a table whose order is observable. A table is safe as a membership set (`t[k] = true`, `t[k] ~= nil`, `t[k] = nil`); anything iterated needs a separately kept insertion-ordered array, which is what a sparse set's dense array buys.
* **code** The keyed table offers no iteration (`LuaNatives`). `__wurst_keyedMapDestroy` does loop with `pairs`, but only to set every entry to nil, which does not depend on order.
* **code** The compiler's own output must be byte-identical for identical input (AGENTS.md §3).

## Numbers

* **measured, 3.0.0** Jass literals and `S2R` are not correctly rounded and the two disagree: `0.1` reads one float high, `1.1` one float low, `S2R("100.0")` one above 100. Short exact binary fractions (`0.5`, `0.75`, `100.0`, `123456.78125`) read exactly; integer parts past 2^24 are truncated. This is why `SimpleRewrites.foldRealExactly` folds only exact literals and exact results.
* **measured, 3.0.0** Lua reals have a 24-bit mantissa, not 53: `(2^24 + 1) - 2^24` is 0, the literal `16777217.` reads as 16777216, `0.9999999999999999` reads as exactly 1, and `0.7 + 0.1 + 0.1 + 0.1` computes to 1 - 2^-23. Literals are rounded to nearest and each arithmetic result is truncated, which neither double nor 32-bit float arithmetic reproduces. One `R2I` result is not evidence of a precision: `R2I(0.7 + 0.1 + 0.1 + 0.1)` is 0 for that reason, not because of doubles.
* **measured, 3.0.0** `R2I` and the arithmetic `x // 1 | 0` agree on every value probed, the 32-bit edges and values outside the range included (`LuaNativeLowering.lowerRealToInt`).

## Establishing a fact

* Measure in the real client with discriminating values, such as `2^24 + 1` or sums just below an integer, computed at run time from array operands so that nothing is folded, and read the emitted Lua to confirm. State the client version where the fact is recorded.
* Never launch Warcraft III yourself: it needs the maintainer's Battle.net sign-in and an install that matches the pinned patch. Ask for a probe.
* Benchmark Lua output like a shipping map: `-inline -localOptimizations` and no `-stacktraces`, which inflated call-heavy blocks 3-4x. Accumulate inside a timed loop in a local, not a global: a global's lookup cost follows the global table's hash layout, which shifts when identifiers are renamed, so a block whose Lua is byte-identical moved 15% between builds. Compare alternating runs, at least three per build, and treat shifts under 15% in global-touching blocks as noise.
Loading