Skip to content

compile: x = A and B into an existing local leaves x unchanged when A is falsy - #569

Open
itsnotyoutoday wants to merge 1 commit into
yuin:masterfrom
waypointmu:pr-and-or-assign
Open

itsnotyoutoday wants to merge 1 commit into
yuin:masterfrom
waypointmu:pr-and-or-assign

Conversation

@itsnotyoutoday

Copy link
Copy Markdown

Branch: itsnotyoutoday/gopher-lua pr-and-or-assign (one commit on upstream master, module path unchanged)

Problem

local function f() return nil end
local x = "old"
x = f() and 1
print(x)  --> old   (Lua 5.1: nil)

When an and/or expression is assigned to an existing local and an operand that is not a
plain local or a comparison (a call, a field, ...) decides the result, the compiler emits
OP_TEST for the jump that ends the expression. The operand is the expression's value in that
case, but OP_TEST never copies it into the target register, so the local keeps its old value.
or happened to work because its path always used OP_TESTSET, but that path also wrote the
target on jumps that go to the next operand, before the expression was finished:

local x = "kept"
x = (g() or f()) and x   -- g() truthy: Lua 5.1 gives "kept"; gopher-lua gave g()'s value

Fix

In compileLogicalOpExprAux, the general operand case now chooses by where the jump goes:
OP_TESTSET target, operand when the jump ends the expression (and the target is another
register), OP_TEST operand otherwise. This is what PUC Lua's code generator does (TESTSET only
for jumps that produce the value).

Tests

_glua-tests/issues.lua gains a case covering and/or with calls, false, nil fields,
chains (f() and 1 or 2) and the early-write case. The whole suite passes; the new case fails
without the change (issues.lua: "x = f() and 1 with f() nil").

Found running Mudlet's Glu library (ThresholdUI, Highlighter, Chatter packages) on gopher-lua.

…ends the expression

x = f() and 1, with x an existing local and f() falsy, left x unchanged: the jump that ends
the expression used OP_TEST, so the falsy operand never reached x. The operand is the
expression's value whenever its jump goes to the end, so that jump now uses OP_TESTSET (for
and as for or). A jump to the next operand carries no value and now only tests, where it used
to write the target early (x = (f() or g()) and x read the new x).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant