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 @@ -207,8 +207,16 @@ private ImClass createClass() {
e.getImplementation(), tr, impl, superMethod.attrReturnType());
} else {
translated = e.getImplementation().imTranslateExpr(tr, impl);
WurstType translatedType = e.getImplementation().attrTypRaw();
// A fromIndex conversion already decoded the expression. Keep other
// generic bindings: Lua still needs them to restore primitive defaults
// when adapting an erased result to a concrete closure return type.
if (translatedType instanceof WurstTypeBoundTypeParam boundType
&& boundType.getFromIndex() != null) {
translatedType = translatedType.normalize();
}
translated = ExprTranslation.wrapTranslation(e.getImplementation(), tr, translated,
e.getImplementation().attrTypRaw(), superMethod.attrReturnType());
translatedType, superMethod.attrReturnType());
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,101 @@
package tests.wurstscript.tests;

import org.testng.annotations.Test;
import org.testng.Assert;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ClosureTests extends WurstScriptTest {

@Test
public void oldGenericStringReadInClosure() throws IOException {
test().withStdLib().testLua(true).luaOnly(false).executeProg(true).lines(
"package Repro",
"import LinkedList",
"import Wurstunit",
"interface StringFn",
" function get(int i) returns string",
"let names = asList(\"a\", \"b\")",
"init",
" StringFn f = i -> names.get(i)",
" if f.get(0) == \"a\" and f.get(1) == \"b\"",
" testSuccess()");
String jass = Files.readString(Path.of(TEST_OUTPUT_PATH,
"ClosureTests_oldGenericStringReadInClosure_no_opts.j"));
Assert.assertTrue(jass.contains("return stringFromIndex(dispatch_LinkedList_LinkedList_get("), jass);
Assert.assertFalse(jass.contains("stringFromIndex(stringFromIndex("), jass);
}

@Test
public void newGenericStringReadInClosure() throws IOException {
test().testLua(true).luaOnly(false).executeProg(true).lines(
"package Repro",
"native testSuccess()",
"interface StringFn",
" function get(int i) returns string",
"class Box<T:>",
" T value",
" construct(T value)",
" this.value = value",
" function get(int i) returns T",
" return value",
"let names = new Box<string>(\"a\")",
"init",
" StringFn f = i -> names.get(i)",
" if f.get(0) == \"a\"",
" testSuccess()");
String jass = Files.readString(Path.of(TEST_OUTPUT_PATH,
"ClosureTests_newGenericStringReadInClosure_no_opts.j"));
Assert.assertFalse(jass.contains("stringFromIndex"), jass);
}

@Test
public void oldGenericStringReadInCompiletimeClosure() {
test().withStdLib().testLua(true).luaOnly(false).executeProg(true)
.executeProgOnlyAfterTransforms().lines(
"package Repro",
"import LinkedList",
"import Wurstunit",
"interface StringFn",
" function get(int i) returns string",
"@compiletime let names = asList(\"a\", \"b\")",
"@compiletime string result",
"@compiletime function readName()",
" StringFn f = i -> names.get(i)",
" result = f.get(1)",
"init",
" if result == \"b\"",
" testSuccess()");
}

@Test
public void erasedGenericPrimitiveDefaultsInClosures() {
test().testLua(true).luaOnly(false).executeProg(true).lines(
"package Repro",
"native testSuccess()",
"interface IntSupplier",
" function get() returns int",
"interface RealSupplier",
" function get() returns real",
"interface BoolSupplier",
" function get() returns bool",
"class Box<T:>",
" T value",
" function get() returns T",
" return value",
"init",
" let ints = new Box<int>",
" let reals = new Box<real>",
" let bools = new Box<bool>",
" IntSupplier i = () -> ints.get()",
" RealSupplier r = () -> reals.get()",
" BoolSupplier b = () -> bools.get()",
" if i.get() + 1 == 1 and r.get() + 0.5 == 0.5 and b.get() == false",
" testSuccess()");
}


@Test
public void closure1() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,33 @@ private static File script(Path dir, String name, String content) throws IOExcep
return file.toFile();
}

private static String parameterScript(int parameters, int arguments) {
StringBuilder signature = new StringBuilder();
StringBuilder call = new StringBuilder();
for (int i = 0; i < parameters; i++) {
if (i > 0) signature.append(", ");
signature.append("integer p").append(i);
}
for (int i = 0; i < arguments; i++) {
if (i > 0) call.append(", ");
call.append(i);
}
return "function callee takes " + signature + " returns nothing\nendfunction\n"
+ "function main takes nothing returns nothing\n call callee(" + call + ")\nendfunction\n";
}

@Test
public void checksArgumentCountAndJassCallLimit() throws IOException {
Path dir = Files.createTempDirectory("pjass-parameters");
Result boundary = Pjass.runPjass(script(dir, "boundary.j", parameterScript(31, 31)));
Assert.assertTrue(boundary.isOk(), boundary.getMessage());
Result oversized = Pjass.runPjass(script(dir, "oversized.j", parameterScript(32, 32)));
Assert.assertFalse(oversized.isOk(), oversized.getMessage());
Assert.assertTrue(oversized.getMessage().contains("at most 31 arguments"), oversized.getMessage());
Result mismatch = Pjass.runPjass(script(dir, "mismatch.j", parameterScript(1, 2)));
Assert.assertFalse(mismatch.isOk(), mismatch.getMessage());
}

private static String longStringScript(String extraStatement) {
return "function main takes nothing returns nothing\n"
+ " local string s = \"" + "x".repeat(1024) + "\"\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
-- type declarations carry no runtime information here
TypeDefine = function() end

-- ClosureForGroups creates a filter handle at package initialization.
-- Keep its callback without invoking it, as the native factory does.
function Filter(callback) return { callback = callback } end

-- Enum-like handles (playercolor, race, attacktype, ...): the game returns
-- the same handle for the same integer, so cache by (kind, value) to keep
-- handle identity comparisons working.
Expand Down
5 changes: 5 additions & 0 deletions docs/WC3_RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ A test that passes in the first two columns says nothing about the third where t
* **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** 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

* **measured, 3.0.0.24268 (2026-10-13)** Raw Jass calls with 30 and 31 integer parameters, and with 30 and 31 string parameters, completed and verified every argument against a runtime-derived value. A 31-parameter signature consisting of an integer receiver, 29 strings and a string trace position also completed. Calling the 31-string function during package initialization and again after loading completed too. Separate maps with 32 integer or 32 string parameters initialized, then the client process exited without reporting a result. These measurements support the compiler's 31-parameter limit; they do not reproduce issue #1445's reported crash at 31, or establish another patch's limit.
* **code** The bundled pjass accepts those 31-argument calls and rejects a 32-argument call with "A function call can have at most 31 arguments". Compiler checks must count emitted parameters, including receivers, flattened tuple components and injected stacktrace positions (`ImHelper.JASS_MAX_PARAMETERS`, `VarargEliminator`, `CyclicFunctionRemover`). New generics avoid old-generic conversion overhead but do not remove this Jass call limit.

## 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`.
Expand Down
Loading