我试图在ANTLR中重现龙书中的一个例子:
grammar left_recursion_2;
options {
language = java;
}
program : 'begin'
stmt+
'end'
;
stmt : unmatched_stmt
| matched_stmt
;
matched_stmt : 'if' expr 'then' matched_stmt 'else' matched_stmt
| other
;
unmatched_stmt : 'if' expr 'then' stmt
| 'if' expr 'then' matched_stmt 'else' unmatched_stmt
;
expr : 'expression'
;
other : 'other'
;
问题是错误211:
[致命]规则unmatched_stmt由于可以从alts 1,2到达的递归规则调用而具有非LL(*)决策。通过左因子分解或使用句法谓词或使用backtrack = true选项来解析。
我可以切换回溯,但我想知道如何在没有回溯的情况下解决它。我也没有看到谓词如何在这里有所帮助。我读到了这个:
http://www.antlr.org/wiki/display/ANTLR3/How+to+remove+global+backtracking+from+your+grammar
但仍然不知道。
如何重写语法,使其无需回溯?
提前致谢!
编辑:与此同时,我得出的结论是,这是不可能的。由于LL(*)使用DFA向前看,因此无法确定要应用的规则:“if-else”规则或“if only”规则。但如果有人比使用回溯或后处理AST更了解如何处理它,请告诉我。