quickjs icon indicating copy to clipboard operation
quickjs copied to clipboard

for (let …) loop: `continue` skips the per-iteration copy of the loop variables

Open trackoor opened this issue 4 weeks ago • 1 comments

Environment

QuickJS 2026-06-04 (bellard.org tarball, sha256 b376e839b322978313d929fd20663b11ba58b75df5a46c126dd19ea2fa70ad2a), make qjs, Debian 12 x86-64, gcc 12.2. Same result with 2024-01-13, 2025-04-26 and 2025-09-13: the bug is long-standing, not a regression.

Reproduction

var fs = [];
for (let i = 0; i < 2; i++) {
  fs.push(() => i);
  continue;
}
console.log(fs.map(f => f()).join());

Expected 0,1 (node v20.20.2 and v26.13.0 print this; other engines not tested); QuickJS prints 2,2. Removing the continue gives 0,1. Conditional, nested-block, labelled (continue outer from an inner loop), try/finally and switch variants fail the same way.

Spec

ECMA-262 ForBodyEvaluation (https://tc39.es/ecma262/#sec-forbodyevaluation): after Evaluation of stmt, a completion for which LoopContinues is true (normal, or continue targeting this loop) is followed by CreatePerIterationEnvironment(perIterationBindings) before the increment, so a closure created in an iteration keeps that iteration's binding.

Cause and patch

quickjs.c, js_parse_statement_or_decl, case TOK_FOR: the body is followed by /* XXX: check continue case */ close_scopes(...), but continue (emit_break) closes scopes only down to the loop-head scope and jumps to label_cont, which is emitted after that close_scopes (the increment code is moved there under OPTIMIZE). Fix: give continue its own label in front of the body-end close_scopes.

-            int label_cont, label_break, label_body, label_test;
+            int label_cont, label_break, label_body, label_test, label_close;
@@
             if (js_parse_expect(s, ')'))
                 goto fail;
 
+            /* `continue` must leave the per-iteration scope as the end of
+               the body does; otherwise closures created in this iteration
+               see the next iteration's bindings */
+            label_close = new_label(s);
+            break_entry.label_cont = label_close;
+
             pos_body = s->cur_func->byte_code.size;
             emit_label(s, label_body);
             if (js_parse_statement(s))
                 goto fail;
 
             /* close the closures before the next iteration */
-            /* XXX: check continue case */
+            emit_label(s, label_close);
             close_scopes(s, s->cur_func->scope_level, block_scope_level);

Applied to 2026-06-04 and rebuilt: a 10-case check (plain/conditional continue, no-increment and no-test loops, body let, labelled continue, try/finally, switch, var loop, for-of) matches node in every case (unpatched: 7 wrong). The same fix for quickjs-ng, with a regression test: quickjs-ng/quickjs#1875, quickjs-ng/quickjs#1876.

Duplicates checked (2026-11-03)

GitHub search in bellard/quickjs (issues and PRs) for "continue", "continue let", "continue closure loop", "for let closure", "per-iteration", "let binding loop closure": nothing matching (hits: #67, #112, #156, #189, #192, #251, #259, #341, #445 — unrelated).

Related: closures share one binding after a caught throw leaves the block

Closures capturing a const/let of a block share one binding across loop iterations if the block exits through a throw that is caught in the same function:

const handlers = [];
for (const item of [{ id: 1 }, { id: 2 }, { id: 3 }]) {
  try {
    const id = item.id;
    handlers.push(() => id);
    if (id < 3) throw new Error("invalid");
  } catch (e) {}
}
console.log(handlers.map((h) => h()).join(","));  // 3,3,3   expected 1,2,3

The same happens for a bare block ({ const k = …; push(() => k); throw 0; }) and for the binding of an inner for…of/for…in left by a throw; there the earlier closures throw ReferenceError: k is not initialized once the outer loop goes on. With break or without the throw the output is right. It looks like the exception path to the handler does not close the captured locals of the scopes it leaves, so the next iteration reuses the slot.

Versions: QuickJS master e5ac135 (2026-11-09), release 2026-06-04; quickjs-emscripten 0.32.0 (2025-09-13 base). node 26.13.0, SpiderMonkey 159 and Boa 0.22 print 1,2,3.

trackoor avatar Nov 04 '26 04:11 trackoor

Correction: the diff above was made against the 2026-06-04 release, and its first hunk does not apply to master (712e8c0) because the declaration line now has is_await_using = FALSE. Here is the patch against master, with a regression test in tests/test_loop.js:

diff --git a/quickjs.c b/quickjs.c
index 6dadfee..573a1b7 100644
--- a/quickjs.c
+++ b/quickjs.c
@@ -30043,7 +30043,7 @@ static __exception int js_parse_statement_or_decl(JSParseState *s,
         break;
     case TOK_FOR:
         {
-            int label_cont, label_break, label_body, label_test;
+            int label_cont, label_break, label_body, label_test, label_close;
             int pos_cont, pos_body, block_scope_level, is_await_using = FALSE;
             BlockEnv break_entry;
             int tok, bits;
@@ -30164,13 +30164,18 @@ static __exception int js_parse_statement_or_decl(JSParseState *s,
             if (js_parse_expect(s, ')'))
                 goto fail;
 
+            /* 'continue' jumps to the end of the body so that it closes the
+               lexical variables of this iteration like a normal completion */
+            label_close = new_label(s);
+            break_entry.label_cont = label_close;
+
             pos_body = s->cur_func->byte_code.size;
             emit_label(s, label_body);
             if (js_parse_statement(s))
                 goto fail;
 
             /* close the closures before the next iteration */
-            /* XXX: check continue case */
+            emit_label(s, label_close);
             close_scopes(s, s->cur_func->scope_level, block_scope_level);
 
             if (OPTIMIZE && label_test != label_body && label_cont != label_test) {
diff --git a/tests/test_loop.js b/tests/test_loop.js
index 8f1934d..50ff8c7 100644
--- a/tests/test_loop.js
+++ b/tests/test_loop.js
@@ -381,11 +381,132 @@ function test_cyclic_labels()
     }
 }
 
+function test_for_let_continue()
+{
+    /* 'continue' must not skip the per-iteration copy of the
+       lexical loop variables */
+    var fs, log;
+    function run(fs) {
+        return fs.map(function (f) { return f(); }).join();
+    }
+
+    fs = [];
+    for (let i = 0; i < 3; i++) {
+        fs.push(() => i);
+        continue;
+    }
+    assert(run(fs), "0,1,2", "continue");
+
+    fs = [];
+    for (let i = 0; i < 4; i++) {
+        fs.push(() => i);
+        if (i & 1)
+            continue;
+    }
+    assert(run(fs), "0,1,2,3", "conditional continue");
+
+    fs = [];
+    for (let i = 0; i < 3;) {
+        fs.push(() => i);
+        i++;
+        continue;
+    }
+    assert(run(fs), "1,2,3", "no increment");
+
+    fs = [];
+    for (let i = 0;; i++) {
+        if (i == 3)
+            break;
+        fs.push(() => i);
+        continue;
+    }
+    assert(run(fs), "0,1,2", "no test");
+
+    fs = [];
+    for (let i = 0, j = 10; i < 3; i++, j--) {
+        let k = i * 2;
+        fs.push(() => i + ":" + j + ":" + k);
+        continue;
+    }
+    assert(run(fs), "0:10:0,1:9:2,2:8:4", "two variables and body let");
+
+    fs = [];
+    L1: for (let i = 0; i < 3; i++) {
+        for (let j = 0; j < 3; j++) {
+            if (j > i)
+                continue L1;
+            fs.push(() => i + ":" + j);
+        }
+    }
+    assert(run(fs), "0:0,1:0,1:1,2:0,2:1,2:2", "labelled continue from for");
+
+    fs = [];
+    L2: for (let i = 0; i < 3; i++) {
+        fs.push(() => i);
+        for (var x of [1, 2]) {
+            continue L2;
+        }
+    }
+    assert(run(fs), "0,1,2", "labelled continue from for-of");
+
+    fs = [];
+    for (let i = 0; i < 3; i++) {
+        try {
+            fs.push(() => i);
+            continue;
+        } finally {
+            fs.push(() => "f" + i);
+        }
+    }
+    assert(run(fs), "0,f0,1,f1,2,f2", "continue in try/finally");
+
+    fs = [];
+    for (let i = 0; i < 3; i++) {
+        switch (i) {
+        case 1:
+            fs.push(() => "s" + i);
+            continue;
+        default:
+            fs.push(() => i);
+        }
+    }
+    assert(run(fs), "0,s1,2", "continue in switch");
+
+    fs = [];
+    for (let i = 0; i < 3; fs.push(() => "u" + i), i++) {
+        fs.push(() => i);
+        continue;
+    }
+    assert(run(fs), "0,u1,1,u2,2,u3", "closure in increment");
+
+    fs = [];
+    for (let i = 0; i < 3; i++) {
+        fs.push(() => i);
+        if (i == 1) {
+            i = 5;
+            continue;
+        }
+    }
+    assert(run(fs), "0,5", "assignment before continue");
+
+    fs = [];
+    function *g() {
+        for (let i = 0; i < 3; i++) {
+            fs.push(() => i);
+            yield i;
+            continue;
+        }
+    }
+    for (var v of g());
+    assert(run(fs), "0,1,2", "generator");
+}
+
 test_while();
 test_while_break();
 test_do_while();
 test_for();
 test_for_break();
+test_for_let_continue();
 test_switch1();
 test_switch2();
 test_for_in();

On master with this patch: make test passes, and full test262 (run-test262 -a, TEST262_COMMIT 91c70759 + test262.patch) gives 19/53021 errors before and after. On the 2026-06-04 release: 58/83558 before and after. The new test_for_let_continue fails before the patch and passes after. A differential run of 3,000 random nested-loop programs against node: 2,225 match unpatched, all 3,000 match patched.

trackoor avatar Nov 04 '26 04:11 trackoor