Skip to content

Commit f95902d

Browse files
chore: comments
1 parent 0867793 commit f95902d

1 file changed

Lines changed: 15 additions & 6 deletions

File tree

src/transformation/visitors/switch.ts

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export const transformSwitchStatement: FunctionVisitor<ts.SwitchStatement> = (st
2525
const switchName = `____switch${scope.id}`;
2626
const switchVariable = lua.createIdentifier(switchName);
2727

28-
// Collect the case clause expressions and accounting for deterministic fallthrough
28+
// Collect all the expressions into a single expression for use in the default clause
2929
let allExpressions: lua.BinaryExpression;
3030
statement.caseBlock.clauses.forEach(clause => {
3131
if (!ts.isDefaultClause(clause)) {
@@ -49,12 +49,18 @@ export const transformSwitchStatement: FunctionVisitor<ts.SwitchStatement> = (st
4949

5050
let statements: lua.Statement[] = [];
5151

52-
// Default will either be the only statement, or the else in the if chain
53-
const defaultIndex = statement.caseBlock.clauses.findIndex(c => ts.isDefaultClause(c));
54-
const defaultBody = defaultIndex >= 0 ? statement.caseBlock.clauses[defaultIndex].statements : undefined;
55-
if (defaultBody && statement.caseBlock.clauses.length === 1) {
56-
statements.push(lua.createDoStatement(context.transformStatements(defaultBody)));
52+
// If the switch only has a default clause, wrap it in a single do.
53+
// Otherwise, we need to generate a set of if statements to emulate the switch.
54+
const clauses = statement.caseBlock.clauses;
55+
if (clauses.length === 1 && ts.isDefaultClause(clauses[0])) {
56+
const defaultClause = clauses[0].statements;
57+
if (defaultClause.length) {
58+
statements.push(lua.createDoStatement(context.transformStatements(defaultClause)));
59+
}
5760
} else {
61+
// Build up the condition for each if statement
62+
// Fallthrough is handled by accepting the last condition as an additional or clause
63+
// Default is the not of all known case expressions
5864
let previousClause: ts.CaseOrDefaultClause;
5965
let condition: lua.Expression;
6066
statement.caseBlock.clauses.forEach(clause => {
@@ -98,11 +104,14 @@ export const transformSwitchStatement: FunctionVisitor<ts.SwitchStatement> = (st
98104
});
99105
}
100106

107+
// Hoist the variable, function, and import statements to the top of the switch
101108
statements = performHoisting(context, statements);
102109
popScope(context);
103110

111+
// Add the switch expression after hoisting
104112
const expression = context.transformExpression(statement.expression);
105113
statements.unshift(lua.createVariableDeclarationStatement(switchVariable, expression));
106114

115+
// Wrap the statements in a repeat until true statement to facilitate dynamic break/returns
107116
return lua.createRepeatStatement(lua.createBlock(statements), lua.createBooleanLiteral(true));
108117
};

0 commit comments

Comments
 (0)