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 @@ -6,7 +6,7 @@ public class BitSet_Pows_Standalone_ReproTest extends WurstScriptTest {

@Test
public void highestBit_reset_should_clear_with_buggy_reversePows() {
test().withStdLib().executeProg().lines(
test().withStdLib().testLua(true).luaOnly(false).executeProg().lines(
"package BitSetStandalone",
"",
"constant int BITSET_SIZE = 32",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1499,7 +1499,7 @@ public void number() {

@Test
public void optimizeDuplicateNullSets() throws IOException {
testAssertOkLinesWithStdLib(true,
test().withStdLib().testLua(true).luaOnly(false).executeProg(true).lines(
"package Test",
"var x = 100",
"init",
Expand Down Expand Up @@ -1716,7 +1716,7 @@ private static String initFunctionOf(String outputFile) throws IOException {
*/
@Test
public void inlinerGuardClauseAssignsTheResultOnEveryPath() throws IOException {
testAssertOkLinesWithStdLib(true,
test().withStdLib().testLua(true).luaOnly(false).executeProg(true).lines(
"package test",
"@inline function chooseLoc(boolean c, location a, location b) returns location",
" if c",
Expand Down Expand Up @@ -1748,7 +1748,7 @@ public void inlinerGuardClauseAssignsTheResultOnEveryPath() throws IOException {
@Test
public void inlinerLocationLocalsAreInitializedBeforeUse() throws IOException {
// The return sits in a loop, which keeps the done flag and with it the default write.
testAssertOkLinesWithStdLib(true,
test().withStdLib().testLua(true).luaOnly(false).executeProg(true).lines(
"package test",
"@inline function chooseLoc(boolean c, location a, location b) returns location",
" for i = 0 to 1",
Expand Down Expand Up @@ -1797,7 +1797,7 @@ public void inlinerMultiReturnKeepsPostReturnSideEffectsUnreachableUnderInlopt()

@Test
public void inlinerMultiReturnRewriteIsExplicitInInlAndInloptOutput() throws IOException {
testAssertOkLinesWithStdLib(true,
test().withStdLib().testLua(true).luaOnly(false).executeProg(true).lines(
"package test",
"@inline function maybeAbs(int x) returns int",
" for i = 0 to 0",
Expand Down
9 changes: 7 additions & 2 deletions de.peeeq.wurstscript/src/test/resources/luaruntime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ against the real Blizzard.j implementations instead of minimal mocks.
<https://github.com/wurstscript/jass-history> (`lua-dump/`).
- `wc3shim.lua`: hand-written shim providing the natives those two files need
at load time (TypeDefine, Convert* enum-handle factories, `__jarray`,
FourCC, player-layout constants, text output), and the natives the
standard library's package inits call (timers, forces).
FourCC, player-layout constants, text output), the natives the
standard library's package inits call (timers, forces), and common.j
natives that executing tests call (string, math and bit natives,
`GetHandleId`, player state, units, destructables), kept in step with the
interpreter's mocks. With the standard library the generated script
defines no fallback for a common.j native, so one missing here fails
with `attempt to call a nil value`.

Load order in `WurstScriptTest.translateAndTestLua`:
`wc3shim.lua` → `common.j.lua` → `blizzard.j.lua` → generated script → `main()`.
Expand Down
143 changes: 142 additions & 1 deletion de.peeeq.wurstscript/src/test/resources/luaruntime/wc3shim.lua
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,27 @@ local function enumHandle(kind, value)
return h
end

-- As the interpreter's GetHandleId: a null handle is 0; a converted enum handle is the value
-- it was made from (measured on the 3.0.0 client: GetHandleId(UNIT_STATE_MANA) is 2); any other
-- handle gets the next id from 0x100000, where the game's agent ids start.
local handleIds = {}
local nextHandleId = 0x100000
function GetHandleId(h)
if h == nil then
return 0
end
if h.handleKind ~= nil then
return h.value
end
local id = handleIds[h]
if id == nil then
id = nextHandleId
nextHandleId = nextHandleId + 1
handleIds[h] = id
Comment on lines +42 to +46

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Share opaque handle IDs with the generated helper

When a Lua test compares GetHandleId(u) with GetHandleIdBJ(u) for the same unit, native lowering routes the direct call through __wurst_GetHandleId/__wurst_objectToIndex, whose IDs start at 1, while the preloaded Blizzard.j wrapper reaches this separate map, whose IDs start at 0x100000. The values therefore differ even though Jass and the interpreter use one native identity, potentially invalidating tests or keys that mix the two APIs; non-enum handles should use the generated identity store.

AGENTS.md reference: AGENTS.md:L316-L322

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. The shim models the game's GetHandleId native, and that is what Blizzard.j's GetHandleIdBJ calls in the game too. The split comes from the compiler: LuaNativeLowering routes Wurst's own GetHandleId calls on opaque handles to __wurst_GetHandleId by design. Sharing that store in the test runtime would hide a difference that exists in the game. Whether Wurst calls to GetHandleIdBJ should get the same rewrite is a compiler question that predates this PR, which leaves the compiler alone.

end
return id
end

-- common.j.lua calls ~80 distinct Convert* factories at load time; create
-- them on demand instead of hardcoding the list, so newer dumps keep working.
setmetatable(_G, {
Expand Down Expand Up @@ -62,7 +83,82 @@ function SubString(s, start, stop)
end

function I2S(i) return tostring(math.floor(i)) end
function S2I(s) return math.floor(tonumber(s) or 0) end

-- As the interpreter's S2I and the game (measured on the 3.0.0 client), C's strtol: leading
-- whitespace is skipped, then a sign and digits are read, and the value saturates at the
-- integer limits. S2I(" -4x") is -4, S2I("2147483648") is 2147483647.
function S2I(s)
if s == nil then
return 0
end
local sign, digits = string.match(s, "^%s*([%+%-]?)(%d*)")
local value = 0
for i = 1, #digits do
-- stop growing once past the limit
value = math.min(value * 10 + string.byte(digits, i) - 48, 2147483648)
end
if sign == "-" then
return -value
end
return math.min(value, 2147483647)
end

-- As the interpreter's R2SW (measured on the 3.0.0 client): the sign first, then the integer
-- part left-padded to width - precision, then the fraction rounded half up; precision 0 prints
-- ".0". R2SW(1.5, 8, 2) is " 1.50", R2SW(-1.5, 8, 3) is "- 1.500". The test Lua
-- computes in double, the game in float, so the last digits can differ from the game's.
function R2SW(r, width, precision)
local digits = math.max(0, precision)
if digits > 18 or width - digits > 1000 then
-- As the interpreter: what the game prints there was not measured, and padding that far
-- could exhaust memory.
error("R2SW called with width " .. width .. " and precision " .. precision
.. ", beyond what the test runtime models (precision up to 18, width up to 1000).")
end
local a = math.abs(r)
local whole = math.floor(a)
local limit = 1
for _ = 1, digits do
limit = limit * 10
end
local fraction = math.floor((a - whole) * limit + 0.5)
if fraction >= limit then
whole = whole + 1
fraction = fraction - limit
end
local wholeText = string.format("%.0f", whole)
local sign = r < 0 and "-" or ""
local fractionText = digits == 0 and "0" or string.format("%0" .. digits .. "d", fraction)
return sign .. string.rep(" ", width - digits - #wholeText) .. wholeText .. "." .. fractionText
end

-- Math natives, as the interpreter's MathProvider and IntegerProvider. Measured on the 3.0.0
-- client: SquareRoot of a negative value is 0, not NaN.
function SquareRoot(r)
if r < 0 then
return 0.0
end
return math.sqrt(r)
end

-- Any value between the bounds; the interpreter's generator also counts up from the first
-- bound when the second is below it. Not measured in game, and the game's sequence is not modelled.
function GetRandomInt(low, high)
return low + math.random(0, math.abs(high - low))
end

-- As the interpreter (not measured in game): the natives work on 32 bit integers. The test Lua
-- does not wrap integer arithmetic, so the result is brought back to the signed 32 bit range.
local function signed32(v)
v = v & 0xFFFFFFFF
if v >= 0x80000000 then
return v - 0x100000000
end
return v
end
function BlzBitOr(x, y) return signed32(x | y) end
function BlzBitAnd(x, y) return signed32(x & y) end
function BlzBitXor(x, y) return signed32(x ~ y) end

-- StringHash, over bytes, as the game and the interpreter both compute it. Bob Jenkins'
-- lookup2, with the same normalisation: ascii letters upper-cased and a forward slash read as
Expand Down Expand Up @@ -195,6 +291,41 @@ function GetPlayerId(p)
return p.id
end

-- Player states by the id of the state handle, as the interpreter's PlayerProvider. Measured on
-- the 3.0.0 client: a null state is id 0, the game result, which reads 3 while the game runs;
-- gold (1) and lumber (2) are clamped to 0.
local function playerStateId(state)
if state == nil then
return 0
end
return state.value
end
function SetPlayerState(p, state, value)
local id = playerStateId(state)
if id == 1 or id == 2 then
value = math.max(0, value)
end
p.states = p.states or {}
p.states[id] = value
end
function GetPlayerState(p, state)
local id = playerStateId(state)
local value = p.states and p.states[id]
if value == nil then
return id == 0 and 3 or 0
end
return value
end

-- As the interpreter's mock, unset reads 0; not measured in game.
function SetPlayerTechMaxAllowed(p, techId, maximum)
p.techMaxAllowed = p.techMaxAllowed or {}
p.techMaxAllowed[techId] = maximum
end
function GetPlayerTechMaxAllowed(p, techId)
return p.techMaxAllowed and p.techMaxAllowed[techId] or 0
end

-- Forces hold their members by player id. ForForce visits them in id order (by index, never with
-- pairs, so the order is the same on every run) and GetEnumPlayer answers the one being visited,
-- also inside a nested ForForce. The stdlib's ErrorHandling creates a force at init and runs its
Expand All @@ -221,6 +352,16 @@ function ForForce(f, callback)
end
end

-- Units and destructables keep what they were created with; nothing in a test moves them. Plain
-- records, not a model of the game's units.
function CreateUnit(owner, unitId, x, y, face)
return { owner = owner, typeId = unitId, x = x, y = y, face = face }
end
function GetUnitTypeId(u) return u.typeId end
function CreateDestructable(objectId, x, y, face, scale, variation)
return { typeId = objectId, x = x, y = y, face = face, scale = scale, variation = variation }
end

-- text output: route to stdout so error handlers (BJDebugMsg) work in tests
function GetLocalPlayer() return Player(0) end
function DisplayTimedTextToPlayer(toPlayer, x, y, duration, message)
Expand Down
Loading