A funny anecdote: Some time ago, I was writing a C-to-Python translator.<p>(Why? Just for fun, <a href="https://github.com/albertz/PyCParser">https://github.com/albertz/PyCParser</a>, even more just-for-fun goal was this: <a href="https://github.com/albertz/PyCPython">https://github.com/albertz/PyCPython</a>).<p>It literally would translate the C code in equivalent Python code, using ctypes heavily. It was mostly straight-forward, except for mapping goto (thus related to this control flow structuring problem).<p>Of course, there are some hacks to introduce goto in Python, which in many cases would operate on the Python bytecode, which actually has the JUMP_ABSOLUTE op, but there are also other ways (<a href="https://stackoverflow.com/questions/6959360/goto-in-python" rel="nofollow">https://stackoverflow.com/questions/6959360/goto-in-python</a>).<p>I could also have translated C directly to equivalent Python bytecode and not Python source code, but I really wanted to have Python source code.<p>My ugly solution worked basically like this: Whenever there was some goto in a function, it would translate it as follows:<p>First, we flatten any Python AST into a series of statements,
with even more goto's added for while/for loops, if's, etc.
(We can avoid doing this for all sub-ASTs where there are no
no goto-labels. The goal is to have all goto-labels at
the top-level, not inside a sub-AST.)<p>Only conditional goto's can stay.
All Gotos and Goto-labels are marked somehow as special elements.
So, we end up with sth like:<p><pre><code> x()
y()
<goto-label "a">
z()
<goto-stmnt "a">
w()
if v(): <goto-stmnt "a">
q()
</code></pre>
Now, we can implement the goto-handling based on this flattened code:<p>- Add a big endless loop around it. After the final statement, a break would leave the loop.<p>- Before the loop, we add the statement `goto = None`.<p>- The goto-labels will split the code into multiple part, where
we add some `if goto is None:` before each part
(excluding the goto-labels).<p>- For the goto-labels itself, we add this code:<p><pre><code> if goto == <goto-label>: goto = None
</code></pre>
- For every goto-statement, we add this code:<p><pre><code> goto = <goto-stmnt>; continue
</code></pre>
See here: <a href="https://github.com/albertz/PyCParser/blob/master/goto.py">https://github.com/albertz/PyCParser/blob/master/goto.py</a>