ANTLR Grammar Mutually Left Recursive

狂风中的少年 提交于 2020-01-24 01:08:11

问题


I do know that this question has been asked a lot of times. I am trying to build a grammar using ANTLR.

Predicate           : LOWERCASE | Predicate VarChars ;

VarChars            : LOWERCASE | UPPERCASE;

fragment LOWERCASE  : [a-z] ;   

fragment UPPERCASE  : [A-Z] ;

I am getting the following error :"The following sets of rules are mutually left-recursive [Predicate]"

Please show me how this is fixed. How to remove the mutual left recursion in my antlr grammar.


回答1:


Get rid of the recursive occurrence of "Predicate" altogether. VarChars alone is sufficient to mean lowercase or uppercase. Use the + suffix to indicate "one or more instances":

fragment LOWERCASE : [a-z];   
fragment UPPERCASE : [A-Z];

VARCHARS  : LOWERCASE | UPPERCASE;
PREDICATE : LOWERCASE VARCHARS+;

Applied to your examples, this would disqualify "p" and "PA" as predicates, and qualify "pA".

Observe how PREDICATE and VARCHARS are still lexer rules (as opposed to syntactical rules) as they describe how a lexeme is formed. Therefore it follows the all-uppercase naming convention (Antlr does not care, but it improves readability).



来源:https://stackoverflow.com/questions/47153634/antlr-grammar-mutually-left-recursive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!