How to do goto in Nim ?
e.g.
echo "from here"
goto here
echo "nowhere"
here:
echo "here we go"
You don't need a macro, you can just use a template.
template label(name, body) =
{.emit: astToStr(name) & ":".}
body
template goto(name) =
{.emit: "goto " & astToStr(name) & ";".}
proc main =
echo "from here"
goto here
echo "nowhere"
label here:
echo "here we go"
main()
Nim's optimizer does not understand control flow hiding in emit and is free to break your program. Instead of goto, use structured programming constructs like if and while (there is also return and break).
Do yourself a favor and read books about basic programming techniques -- you misuse regular expressions to the point that you need to know the used PCRE version, now you ask for goto, and I can already predict your next questions. This is not a comfortable position to be in.
With blocks you could write something similar:
block outer:
echo "from here"
break outer
echo "nowhere"
echo "here we go"
And for state machines there is the (undocumented) {.goto.} pragma:
https://github.com/mratsim/Synthesis/blob/09bef6d/synthesis/factory.nim#L425
(undocumented) {.goto.} pragma
@mratsim what does this do?
Something unspeakable. "Raw" gotos that need to be structured as a case object. Note: the enum vanishes in the C backend and becomes goto Label
type MyState = enum
A, B, C
proc stateMachine() =
var state {.goto.} = A
case state
of A:
doSomething()
if sample([0, 1]) == 1: # throw a coin
state = B # goto B
else:
state = C
of B:
doSomethingElse()
state = A # go back to A
of C:
doLots()
# exit