我正在尝试解析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。工具正在解析语法:
错误(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是否有可能直接支持第一种语法?
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 ')'
;