Skip to content
Open
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
45 changes: 45 additions & 0 deletions packages/safe-js/src/interp/for-iteration-binding-tdz.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { runInNewContext } from "node:vm";
import { expect, it } from "vitest";
import { run } from "../run.js";

const loops = ["in", "of", "await of"];
const declarations = ["let", "const", "var"];

it.each(loops.flatMap((loop) => declarations.map((declaration) => ({ loop, declaration }))))(
"resolves destructuring defaults in the iteration scope: $declaration $loop",
async ({ loop, declaration }) => {
const source = `var a = "outer";
try {
for ${loop === "await of" ? "await " : ""}(${declaration} { x: a = a } ${loop === "in" ? "in { key: 1 }" : "of [{}]"}) {
return a;
}
} catch (error) { return error.name; }`;
const expected = declaration === "var" ? "outer" : "ReferenceError";
expect(await runInNewContext(`(async () => { ${source} })()`)).toBe(expected);
expect(await run(source)).toMatchObject({ ok: true, returnValue: expected });
}
);

it.each(["let", "const"])("predeclares later %s bindings before defaults", async (declaration) => {
const source = `var b = "outer";
try {
for (${declaration} [a = b, b = 1] of [[]]) { return a; }
} catch (error) { return error.name; }`;
expect(await run(source)).toMatchObject({ ok: true, returnValue: "ReferenceError" });
});

it.each(["let", "const"])(
"allows defaults to read initialized %s bindings",
async (declaration) => {
const source = `const result = [];
for (${declaration} [a, b = a] of [[1], [2]]) { result.push([a, b]); }
return result;`;
expect(await run(source)).toMatchObject({
ok: true,
returnValue: [
[1, 1],
[2, 2]
]
});
}
);
4 changes: 4 additions & 0 deletions packages/safe-js/src/interp/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2805,6 +2805,10 @@ async function bindIterationVariable(
throw new TypeError("for...of declarations must include exactly one declarator.");
}

if (left.kind !== "var") {
predeclareDeclarationBindings(left, scope);
}

if (context.generatorYield !== undefined && left.nodeId !== undefined) {
context = { ...context, generatorExpressionStates: new Map([...(context.generatorExpressionStates ?? []),
[left.nodeId, { kind: "declaration", index: 0 }]]) };
Expand Down