ast生成时的antlr 4.7错误

时间:2018-03-01 03:26:43

标签: parsing antlr4 abstract-syntax-tree lexer

我正按照 - http://meri-stuff.blogspot.com/2011/08/antlr-tutorial-hello-word.html

尝试逐步执行strp

根据上述网页的原始代码 -

public CommonTree compile(String expression) {
try {
  //lexer splits input into tokens
  ANTLRStringStream input = new ANTLRStringStream(expression);
  TokenStream tokens = new CommonTokenStream( new S001HelloWordLexer( input ) );

  //parser generates abstract syntax tree
  S001HelloWordParser parser = new S001HelloWordParser(tokens);
  S001HelloWordParser.expression_return ret = parser.expression();

  //acquire parse result
  CommonTree ast = (CommonTree) ret.tree;
  printTree(ast);
  return ast;
} catch (RecognitionException e) {
  throw new IllegalStateException("Recognition exception is never thrown, only declared.");
}
}

我修改了下面的部分代码:

public CommonTree compile(String expression) {
    try {
      //lexer splits input into tokens
      ANTLRStringStream input = new ANTLRStringStream(expression);
      TokenStream tokens = new CommonTokenStream( (TokenSource) new S001HelloWordLexer( (CharStream) input ) );

      //parser generates abstract syntax tree
      S001HelloWordParser parser = new S001HelloWordParser((org.antlr.v4.runtime.TokenStream) tokens);
      S001HelloWordParser.expression_return ret = parser.expression();

      //acquire parse result
      CommonTree ast = (CommonTree) ret.tree;
      printTree(ast);
      return ast;
    } catch (RecognitionException e) {
      throw new IllegalStateException("Recognition exception is never thrown, only declared.");
  }
}

问题出在我的S001HelloWordParser文件中,没有方法作为expression(),也没有静态类名' expression_return',所以我无法创建变量' ret&# 39;我可以称之为tree()方法。这里有什么我想念的吗?

我还能如何生成树?或者使用antlr 4.7版本的任何想法?

请帮忙。谢谢!

1 个答案:

答案 0 :(得分:1)

  

我正按照 - http://meri-stuff.blogspot.com/2011/08/antlr-tutorial-hello-word.html

尝试逐步执行strp

别。该教程是关于ANTLR 3的,你需要找到一个ANTLR 4教程。

  

问题出在我的S001HelloWordParser文件中,没有方法作为表达式(),也没有静态类名'expression_return'

这意味着您的S001HelloWord语法不包含名为expression的解析器规则。

从源头开始:https://github.com/antlr/antlr4/blob/master/doc/getting-started.md

这是关于ANTLR4的表达式解析器的Q& A(带完整代码示例):If/else statements in ANTLR using listeners