[英]How to create a custom AST using visitor in Antlr
I want to use the visitor pattern to walk the ParserRuleContext and build an AST using predefined nodes. 我想使用访客模式来遍历ParserRuleContext并使用预定义的节点构建AST。
In my grammar I have the following rule: 在我的语法中,我有以下规则:
expr
: loop
| block
I would like to produce an AST that has the following structure: 我想产生一个具有以下结构的AST:
exprNode
/
loopNode
The BaseVisitor
generated by Antlr has the following method in it: BaseVisitor
生成的BaseVisitor
具有以下方法:
public T visitExpr(MyParser.ExprContext ctx) { return visitChildren(ctx); }
The ASTBuilder
overrides this method and creates a exprNode
. ASTBuilder
重写此方法并创建一个exprNode
。 To this exprNode
I want to append either a loopNode
or a blockNode
by calling my overrode versions of visitLoop
and visitBlock
. 对此exprNode
我要追加无论是loopNode
或blockNode
致电我压倒版本visitLoop
和visitBlock
。 The problem I have is that I don't know the identity of the expr
, as I only obtained exprContext
from the parent. 我遇到的问题是我不知道expr
的身份,因为我仅从父级获得了exprContext
。 How do I check which invocation of the expr
rule was used? 如何检查使用了哪个expr
规则调用?
Don't override visitExpr
. 不要覆盖visitExpr
。 Just override visitLoop
and visitBlock
. 只需覆盖visitLoop
和visitBlock
。
The auto-generated visitExpr
will call the appropriate one of those two (via visitChildren
) and return whatever visitLoop
or visitBlock
returned. 自动生成的visitExpr
将调用这两个中的相应一个(通过visitChildren
),并返回返回的所有visitLoop
或visitBlock
。 So as long as you override those methods to return the proper result, visitExpr
will also return the proper result automatically. 因此,只要您覆盖这些方法以返回正确的结果, visitExpr
也会自动返回正确的结果。
Labeling the rule alts provides convenience contexts for determining identity: 标记规则替代项可为确定身份提供方便的上下文:
expr
: loop #loopExpr
| block #blockExpr
;
The generated parser will now contain LoopExprContext extends ExprContext
and BlockExprContext extends ExprContext
classes with appropriately behaved visitor enter and exit methods. 现在,生成的解析器将包含LoopExprContext extends ExprContext
和BlockExprContext extends ExprContext
类, BlockExprContext extends ExprContext
类具有行为正常的访客enter和exit方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.