为什么要这么简单的语法
grammar Test;
expr
: Int | expr '+' expr;
Int
: [0-9]+;
与输入的 1+1
不匹配?它说“没有规则 expr 的方法或它有参数”,但在我看来它应该被匹配。
最佳答案
看来我有一段时间没有使用 ANTLR 了……ANTLRv3 不支持左递归规则,but ANTLRv4 does support immediate left recursion .它还支持您在帖子中使用的类似正则表达式的字符类语法。我测试了这个版本,它可以在 ANTLRWorks2 中运行(在 ANTLR4 上运行):
grammar Test;
start : expr
;
expr : expr '+' expr
| INT
;
INT : [0-9]+
;
如果您添加start
规则,那么ANTLR 能够推断出EOF
位于该规则的末尾。它似乎无法为 expr
和 expr2
等更复杂的规则推断 EOF
,因为它们是递归的...
下面有很多评论,所以这里是(ANTLR4的合著者)Sam Harwell的回复(强调已加):
You still want to include an explicit EOF in the start rule. The problem the OP faced with using expr directly is ANTLR 4 internally rewrote it to be expr[int _p] (it does so for all left recursive rules), and the included TestRig is not able to directly execute rules with parameters. Adding a start rule resolves the problem because TestRig is able to execute that rule. :)
我已经发布了关于 EOF
的后续问题:When is EOF needed in ANTLR 4?
关于Antlr:意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17840653/