ANTLR4 AST 创建 - 如何创建 AstVistor [英] ANTLR4 AST Creation - How to create an AstVistor
问题描述
借助这个 SO 问题如何使用 ANTLR4 创建 AST? 我能够创建 AST 节点,但我一直坚持编写 BuildAstVisitor
,如已接受的答案示例中所述.
With the help of this SO question How to create AST with ANTLR4? I was able to create the AST Nodes, but I'm stuck at coding the BuildAstVisitor
as depicted in the accepted answer's example.
我有一个这样开头的语法:
I have a grammar that starts like this:
mini: (constDecl | varDef | funcDecl | funcDef)* ;
而且我既不能给块分配标签(antlr4说标签X分配给一个不是集合的块
),我也不知道如何访问下一个节点.>
And I can neither assign a label to the block (antlr4 says label X assigned to a block which is not a set
), and I have no idea how to visit the next node.
public Expr visitMini(MiniCppParser.MiniContext ctx) {
return visitConstDecl(ctx.constDecl());
}
我上面的代码有以下问题:我不知道如何决定它是 constDecl
、varDef
还是任何其他选项和 ctx.constDecl()
返回一个 List
而我只需要一个元素用于 visitConstDecl
函数.
I have the following problems with the code above: I don't know how to decide whether it's a constDecl
, varDef
or any other option and ctx.constDecl()
returns a List<ConstDeclContext>
whereas I only need one element for the visitConstDecl
function.
更多语法规则:
mini: (constDecl | varDef | funcDecl | funcDef)* ;
//--------------------------------------------------
constDecl: 'const' type ident=ID init ';' ;
init: '=' ( value=BOOLEAN | sign=('+' | '-')? value=NUMBER ) ;
// ...
//--------------------------------------------------
OP_ADD: '+';
OP_SUB: '-';
OP_MUL: '*';
OP_DIV: '/';
OP_MOD: '%';
BOOLEAN : 'true' | 'false' ;
NUMBER : '-'? INT ;
fragment INT : '0' | [1-9] [0-9]* ;
ID : [a-zA-Z]+ ;
// ...
我仍然不完全确定如何实现 BuildAstVisitor
.我现在有一些类似于以下内容的内容,但对我来说肯定不正确......
I'm still not entirely sure on how to implement the BuildAstVisitor
. I now have something along the lines of the following, but it certainly doesn't look right to me...
@Override
public Expr visitMini(MiniCppParser.MiniContext ctx) {
for (MiniCppParser.ConstDeclContext constDeclCtx : ctx.constDecl()) {
visit(constDeclCtx);
}
return null;
}
@Override
public Expr visitConstDecl(MiniCppParser.ConstDeclContext ctx) {
visit(ctx.type());
return visit(ctx.init());
}
推荐答案
如果你想获得单独的子规则,那么为它们实现visitXXX函数(visitConstDecl()
, visitVarDef()
等)而不是 visitMini()
函数.只有在输入中确实匹配它们时才会调用它们.因此,您无需对出现的情况进行任何检查.
If you want to get the individual subrules then implement the visitXXX functions for them (visitConstDecl()
, visitVarDef()
etc.) instead of the visitMini()
function. They will only be called if there's really a match for them in the input. Hence you don't need to do any checks for occurences.
这篇关于ANTLR4 AST 创建 - 如何创建 AstVistor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!