Skip to content

Commit 9a9817e

Browse files
authored
Fix continue in loops sometimes generating dead code (#1640)
1 parent 9795e99 commit 9a9817e

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/transformation/visitors/loops/utils.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,25 @@ export function transformLoopBody(
3131
const identifier = lua.createIdentifier(`__continue${scopeId}`);
3232
const literalTrue = lua.createBooleanLiteral(true);
3333

34+
// If there is a break in the body statements, do not include any code afterwards
35+
const transformedBodyStatements = [];
36+
let bodyBroken = false;
37+
for (const statement of body) {
38+
transformedBodyStatements.push(statement);
39+
if (lua.isBreakStatement(statement)) {
40+
bodyBroken = true;
41+
break;
42+
}
43+
}
44+
if (!bodyBroken) {
45+
// Tell loop to continue if not broken
46+
transformedBodyStatements.push(lua.createAssignmentStatement(identifier, literalTrue));
47+
}
48+
3449
return [
3550
lua.createDoStatement([
3651
lua.createVariableDeclarationStatement(identifier),
37-
lua.createRepeatStatement(
38-
lua.createBlock([...body, lua.createAssignmentStatement(identifier, literalTrue)]),
39-
literalTrue
40-
),
52+
lua.createRepeatStatement(lua.createBlock(transformedBodyStatements), literalTrue),
4153
lua.createIfStatement(
4254
lua.createUnaryExpression(identifier, lua.SyntaxKind.NotOperator),
4355
lua.createBlock([lua.createBreakStatement()])

test/unit/loops.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,20 @@ for (const testCase of [
560560
});
561561
}
562562

563+
// https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1638
564+
test.each([tstl.LuaTarget.Universal, tstl.LuaTarget.Lua50, tstl.LuaTarget.Lua51])(
565+
"no unreachable code when using continue for target %s (#1638)",
566+
target => {
567+
util.testFunction`
568+
let i = 0;
569+
while(++i < 10) continue;
570+
return i;
571+
`
572+
.setOptions({ luaTarget: target })
573+
.expectToMatchJsResult();
574+
}
575+
);
576+
563577
test("do...while", () => {
564578
util.testFunction`
565579
let result = 0;

0 commit comments

Comments
 (0)