Can left recursion be eliminated in all cases in ANTLR?

女生的网名这么多〃 提交于 2021-01-28 22:07:14

问题


say I have the following

Grammar #1

expr:
    expr AND expr
    | expr OR expr
    | primary 
;

and is turned into this.

Grammar #2

expr:
    andExpr
    | primary
;
andExpr: orExpr AND orExpr;
orExpr: ... OR ...;

but I still don't see how this would solve the problem? In Grammar #1 I can express

true and false and true and true or false
true or false and true

I can keep chaining like this with Grammar #1. But I am not seeing how to achieve this using grammar #2?


回答1:


You could write it like this:

grammar Test;

parse
 : expr EOF
 ;

expr
 : or_expr
 ;

or_expr
 : and_expr (OR and_expr)*
 ;

and_expr
 : primary (AND primary)*
 ;

primary
 : TRUE
 | FALSE
 | '(' expr ')'
 ;

TRUE  : 'true';
FALSE : 'false';
AND   : 'and';
OR    : 'or';

SPACES
 : [ \t\r\n] -> skip
 ;

This will keep AND expressions have a higher precedence than OR expressions.

Parsing input like this: true and ((false or true) and true or false) results in the following parse tree:



来源:https://stackoverflow.com/questions/60184169/can-left-recursion-be-eliminated-in-all-cases-in-antlr

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