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
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:
# 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
continue in the target language are fine, but answers which can eliminate
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
continue when designing a language, whereas this question is about how to transpile between existing languages.