问题
I have the following the expressions I need to parse
and(true, false)
or(true, false, true)
not(or(true, false, true))
and(and(true, false), false)
or(or(true, false, true), true)
so far I have the following grammar
expr
: orExpr
;
orExpr
: OR '(' andExpr (',' andExpr)+ ')'
| andExpr
;
andExpr
: AND '(' equalityExpr (',' equalityExpr)+ ')'
| equalityExpr
;
equalityExpr
: comparison ((EQUALS | NOT_EQUALS) comparison)*
;
comparison
: notExpr ((GREATER_THAN_EQUALS | LESS_THAN_EQUALS | GREATER_THAN | LESS_THAN ) notExpr)?
;
notExpr
: NOT '(' expr ')'
| primary
;
primary
: '(' expr ')'
| true
| false
;
I am not able to parse and(and(true, false), false)
with the above grammar? where am I going wrong?
Please assume there is precedence between AND
OR
NOT
(although I understand it may look not necessary)
回答1:
But for now, I need to be able to parse
true=and(5=5, 4=4, 3>2)
or vice-versaand(5=5, 4=4, 3>2)=true
?
In that case, there is absolutely no need to complicate things. All you have to do is this:
grammar Test;
parse
: expr EOF
;
expr
: '(' expr ')'
| OR '(' expr (',' expr)+ ')'
| AND '(' expr (',' expr)+ ')'
| NOT '(' expr ')'
| expr (LT | LTE | GT | GTE) expr
| expr (EQ | NEQ) expr
| TRUE
| FALSE
| INT
;
LT : '<';
LTE : '<=';
GT : '>';
GTE : '>=';
NEQ : '!=';
EQ : '=';
NOT : 'not';
TRUE : 'true';
FALSE : 'false';
AND : 'and';
OR : 'or';
INT
: [0-9]+
;
SPACES
: [ \t\r\n] -> skip
;
来源:https://stackoverflow.com/questions/60186343/how-to-write-antlr-rules-in-a-non-recursive-way