ANTLR4 AST创建-如何创建AstVistor [英] ANTLR4 AST Creation - How to create an AstVistor

查看:242
本文介绍了ANTLR4 AST创建-如何创建AstVistor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助此问题如何使用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.

我有一个这样的语法:

mini: (constDecl | varDef | funcDecl | funcDef)* ;

而且我都无法为标签分配标签(antlr4说 label 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< ConstDeclContext> ,而 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆