Skip to content

Fix continue in loops sometimes generating dead code #1640

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 8, 2025
Merged
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
20 changes: 16 additions & 4 deletions src/transformation/visitors/loops/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,25 @@ export function transformLoopBody(
const identifier = lua.createIdentifier(`__continue${scopeId}`);
const literalTrue = lua.createBooleanLiteral(true);

// If there is a break in the body statements, do not include any code afterwards
const transformedBodyStatements = [];
let bodyBroken = false;
for (const statement of body) {
transformedBodyStatements.push(statement);
if (lua.isBreakStatement(statement)) {
bodyBroken = true;
break;
}
}
if (!bodyBroken) {
// Tell loop to continue if not broken
transformedBodyStatements.push(lua.createAssignmentStatement(identifier, literalTrue));
}

return [
lua.createDoStatement([
lua.createVariableDeclarationStatement(identifier),
lua.createRepeatStatement(
lua.createBlock([...body, lua.createAssignmentStatement(identifier, literalTrue)]),
literalTrue
),
lua.createRepeatStatement(lua.createBlock(transformedBodyStatements), literalTrue),
lua.createIfStatement(
lua.createUnaryExpression(identifier, lua.SyntaxKind.NotOperator),
lua.createBlock([lua.createBreakStatement()])
Expand Down
14 changes: 14 additions & 0 deletions test/unit/loops.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,20 @@ for (const testCase of [
});
}

// https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1638
test.each([tstl.LuaTarget.Universal, tstl.LuaTarget.Lua50, tstl.LuaTarget.Lua51])(
"no unreachable code when using continue for target %s (#1638)",
target => {
util.testFunction`
let i = 0;
while(++i < 10) continue;
return i;
`
.setOptions({ luaTarget: target })
.expectToMatchJsResult();
}
);

test("do...while", () => {
util.testFunction`
let result = 0;
Expand Down
Loading