我正在尝试解析cpp源语法的子集。以下ANTLR4解析器规则直接从c ++语言规范中复制(除了超文本被下划线替换):
abstract_declarator:
ptr_operator abstract_declarator?
| direct_abstract_declarator
;
direct_abstract_declarator:
direct_abstract_declarator? '(' parameter_declaration_clause ')' cv_qualifier_seq? exception_specification?
| direct_abstract_declarator? '[' constant_expression? ']'
| '(' abstract_declarator ')'
;
但是当org.antlr.v4.Tool正在解析语法时我遇到了这个错误:
错误(119):cppProcessor.g4 :::以下几组规则是相互左递归的[direct_abstract_declarator]
左侧的 direct_abstract_declarator?语法似乎会导致错误。我该如何纠正?为什么ANTLR4不能支持它?
手动将规则重构为此表单不会产生错误:
direct_abstract_declarator:
direct_abstract_declarator '(' parameter_declaration_clause ')' cv_qualifier_seq? exception_specification?
| '(' parameter_declaration_clause ')' cv_qualifier_seq? exception_specification?
| direct_abstract_declarator '[' constant_expression? ']'
| '[' constant_expression? ']'
| '(' abstract_declarator ')'
在处理左递归规则时,ANTLR4是否可以直接支持第一种语法?
答案 0 :(得分:4)
ANTLR 4支持直接左递归,但不支持间接或隐藏的左递归。您可以通过显式扩展可选构造来解决上述情况。
direct_abstract_declarator
: direct_abstract_declarator '(' parameter_declaration_clause ')' cv_qualifier_seq? exception_specification?
| direct_abstract_declarator '[' constant_expression? ']'
| '(' parameter_declaration_clause ')' cv_qualifier_seq? exception_specification?
| '[' constant_expression? ']'
| '(' abstract_declarator ')'
;