简体   繁体   English

如何在Antlr中使用访问者创建自定义AST

[英]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我要追加无论是loopNodeblockNode致电我压倒版本visitLoopvisitBlock 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 . 只需覆盖visitLoopvisitBlock

The auto-generated visitExpr will call the appropriate one of those two (via visitChildren ) and return whatever visitLoop or visitBlock returned. 自动生成的visitExpr将调用这两个中的相应一个(通过visitChildren ),并返回返回的所有visitLoopvisitBlock 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 ExprContextBlockExprContext extends ExprContext类, BlockExprContext extends ExprContext类具有行为正常的访客enter和exit方法。

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

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