Search code examples
c++antlrgotolabeled-statements

ANTLR GOTO statement


I'am working on simple parser for code:

DEF Test( )

a = false
b = false
c = false

IF a THEN
  GOTO LabelA
ENDIF

IF b THEN
  GOTO LabelB
ENDIF

IF c THEN
  GOTO LabelC
ENDIF

GOTO LabelD

LabelA:
$OUT[1]=TRUE

LabelB:
$OUT[2]=TRUE

LabelC:
$OUT[3]=TRUE

LabelD:
$OUT[4]=TRUE

END

For now I am able to write a visitor and evaluate IF statement. But my goal is to be able to execute GOTO and Label statements. Unfortunately I could not find any similar solution for C++. Does anybody could give me a tip how to make GOTO statement in the ANTLR visitor? Or maybe there is another solution?


Solution

  • You can do this with two passes through the tree. On the first pass, collect a list of nodes that correspond to a label. On the second pass, do a tree walk to interpret a statement. This idealized machine has an IP aka "instruction pointer" for a node in the tree of a statement. Most statements are trivial to execute, altering the state of variables, and where the next IP is the next tree node to execute. However, when you visit a goto statement, you will need to adjust the IP to the new node corresponding to the label. In addition to the IP register of this idealized machine, you will need to represent variables, arrays, and basic types. You would need to think about how to find the tree node for the next statement. It isn't clear if you also want to define procedures. If so, you will also need a call stack. If you intend to represent the program as bytecode as opposed to a parse tree, you are writing a translator aka compiler and a virtual machine. As it looks like you new to this, and it's for a small project, I would just recommend you interpret the tree as is. This problem would be something you would see in a first-term compiler course.