简体   繁体   English

ANTLR GOTO 语句

[英]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.现在我可以写一个访问者并评估IF语句。 But my goal is to be able to execute GOTO and Label statements.但我的目标是能够执行GOTOLabel语句。 Unfortunately I could not find any similar solution for C++.不幸的是,我找不到任何类似的 C++ 解决方案。 Does anybody could give me a tip how to make GOTO statement in the ANTLR visitor?有没有人可以给我一个提示如何在 ANTLR 访问者中进行GOTO语句? Or maybe there is another 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.这个理想化的机器有一个 IP 又名“指令指针”,用于语句树中的节点。 Most statements are trivial to execute, altering the state of variables, and where the next IP is the next tree node to execute.大多数语句执行起来都很简单,会改变变量的状态,并且下一个 IP 是下一个要执行的树节点。 However, when you visit a goto statement, you will need to adjust the IP to the new node corresponding to the label.但是,访问goto语句时,需要将IP调整为标签对应的新节点。 In addition to the IP register of this idealized machine, you will need to represent variables, arrays, and basic types.除了这个理想化机器的 IP 寄存器之外,您还需要表示变量、数组和基本类型。 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.你会在第一学期的编译器课程中看到这个问题。

your suggestion to walk through tree twice was the simplest and the best idea.你建议两次穿过树是最简单也是最好的主意。 In my parser I do even more.在我的解析器中,我做得更多。 I walk through my tree so many times as I wish, every time when I have goto statement.每次当我有 goto 语句时,我都可以随心所欲地穿过我的树。 This can cause infinite loop but this is another question if the parsed program is written well.这可能会导致无限循环,但如果解析的程序写得好,这是另一个问题。 This is not the best solution but perfect for my issue.这不是最好的解决方案,但非常适合我的问题。 Thank you all very much for a help.非常感谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM