Skip to content

Unreachable code should be stripped (after break statement) #1122

@Cheatoid

Description

@Cheatoid

Problem description

In TypeScript/Javascript it is fine to have unreachable code after return/break/goto/continue statement.
But in Lua, it is universally not okay. Lua forbids any additional (unreachable) code after return/break statements, and it will halt execution when this happens at runtime.

For more details, see this REPL.

Example code

Playground

/** @noSelfInFile */

function testUnreachableCodeAfterReturn(): void {
  print("testUnreachableCodeAfterReturn");
  return;
  const unreachableCode = "Unreachable code.";
  print(unreachableCode);
}

function testUnreachableCodeAfterBreak(): void {
  print("testUnreachableCodeAfterBreak");
  while (true) {
    break;
    const unreachableCode = "Unreachable code.";
    print(unreachableCode);
  }
}

function testUnreachableCodeAfterContinue(): void {
  print("testUnreachableCodeAfterContinue");
  for (const i of $range(1, 2)) {
    if (i == 1) {
      continue;
      const unreachableCode = "Unreachable code.";
      print(unreachableCode);
    }
  }
}

testUnreachableCodeAfterReturn();
testUnreachableCodeAfterBreak();
testUnreachableCodeAfterContinue();
print("The end.");

Looks like TSTL does already handle testUnreachableCodeAfterReturn case, but is lacking to do this in case of break statement.
It is worth noting, this should be done throughout entire transpilation.

Suggested solution

Leverage code analysis/diagnostics during transpilation process, and strip any unreachable code.

Justification

Besides the point of transpiling to compliant Lua code, by doing this it would also help reduce final code/file size after stripping unreachable code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions