ast生成时的antlr 4.7错误

问题描述 投票:0回答:1

我试图按照qazxsw poi一步一步地进行操作

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

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

我修改了以下代码的一部分:

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.");
}
}

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

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

请帮忙。谢谢!

parsing antlr4 abstract-syntax-tree lexer
1个回答
1
投票

我试图按照qazxsw poi一步一步地进行操作

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

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

这意味着你的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."); } } 语法不包含名为http://meri-stuff.blogspot.com/2011/08/antlr-tutorial-hello-word.html的解析器规则。

从源头开始:S001HelloWord

这是关于ANTLR4的表达式解析器的问答(包含完整的代码示例):expression

© www.soinside.com 2019 - 2024. All rights reserved.