Suppose I am writing a source-to-source compiler (also called a transpiler) from one high-level imperative language to another, where the source language allows labelled statements to be targeted by break
and continue
, while the target language doesn't. For example, from Javascript to Python.
Manual translation is possible by inserting a flag variable, but there may be many other places besides the loop conditions where this flag will need to be checked, so it is not as simple as just including the flag in the loop condition. For example:
// Javascript code
outer:
while(cond1) {
foo();
while(cond2) {
bar();
if(cond3) {
break outer;
}
baz();
}
qux();
}
# Translated Python code
flag = True
while flag and cond1:
foo()
while flag and cond2:
bar()
if cond3:
flag = False
if flag:
baz()
if flag:
qux()
How can a program transformation like the above be done automatically ─ either by inserting a flag variable or otherwise? Answers which make use of single-level break
/continue
in the target language are fine, but answers which can eliminate break
/continue
entirely are even better.
Ideally I would like to preserve the original code structure as much as possible, so e.g. replacing the whole outer loop with a loop-and-switch state machine is not a preferred solution.
This question is distinct from What are the different options for breaking out of an inner loop? as that question is about alternatives to labelled break
and continue
when designing a language, whereas this question is about how to transpile between existing languages.