summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2022-08-24 17:36:47 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2022-08-24 17:36:47 -0300
commit997f11f54322883c3181225f29d101a597f31730 (patch)
tree22628b0ca4632fea24e279bc8ea1cc103a15bcb5
parent02060b7a37d88d4e92cf64a008c0651eae432c12 (diff)
downloadlua-github-997f11f54322883c3181225f29d101a597f31730.tar.gz
Bug: 'break' may not properly close variable in a 'for' loop
Function 'leaveblock' was generating "break" label before removing variables from the closing block. If 'createlabel' created a 'close' instruction (which it did when matching a goto/break that exited the scope of an upvalue), that instruction would use the wrong level.
-rw-r--r--lparser.c16
-rw-r--r--testes/locals.lua20
2 files changed, 28 insertions, 8 deletions
diff --git a/lparser.c b/lparser.c
index a5cd5525..fe693b57 100644
--- a/lparser.c
+++ b/lparser.c
@@ -674,19 +674,19 @@ static void leaveblock (FuncState *fs) {
LexState *ls = fs->ls;
int hasclose = 0;
int stklevel = reglevel(fs, bl->nactvar); /* level outside the block */
- if (bl->isloop) /* fix pending breaks? */
+ removevars(fs, bl->nactvar); /* remove block locals */
+ lua_assert(bl->nactvar == fs->nactvar); /* back to level on entry */
+ if (bl->isloop) /* has to fix pending breaks? */
hasclose = createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0);
- if (!hasclose && bl->previous && bl->upval)
+ if (!hasclose && bl->previous && bl->upval) /* still need a 'close'? */
luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);
- fs->bl = bl->previous;
- removevars(fs, bl->nactvar);
- lua_assert(bl->nactvar == fs->nactvar);
fs->freereg = stklevel; /* free registers */
ls->dyd->label.n = bl->firstlabel; /* remove local labels */
- if (bl->previous) /* inner block? */
- movegotosout(fs, bl); /* update pending gotos to outer block */
+ fs->bl = bl->previous; /* current block now is previous one */
+ if (bl->previous) /* was it a nested block? */
+ movegotosout(fs, bl); /* update pending gotos to enclosing block */
else {
- if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
+ if (bl->firstgoto < ls->dyd->gt.n) /* still pending gotos? */
undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
}
}
diff --git a/testes/locals.lua b/testes/locals.lua
index ddb75054..d50beaa5 100644
--- a/testes/locals.lua
+++ b/testes/locals.lua
@@ -360,6 +360,26 @@ do
end
+do
+ -- bug in 5.4.4: 'break' may generate wrong 'close' instruction when
+ -- leaving a loop block.
+
+ local closed = false
+
+ local o1 = setmetatable({}, {__close=function() closed = true end})
+
+ local function test()
+ for k, v in next, {}, nil, o1 do
+ local function f() return k end -- create an upvalue
+ break
+ end
+ assert(closed)
+ end
+
+ test()
+end
+
+
do print("testing errors in __close")
-- original error is in __close