Envin
Envin

Reputation: 1523

Attempting to get an ANTLR grammar to follow AND/OR statements

I have the following input as an example of the format I want.

(A = 'a' AND B != 'something') OR (C != 'abc*') OR (D != 'xyz' AND D != 'wui')

I have the following ANTLR grammar, unfortunately it isn't working for what I need.

grammar Parser;

prog: expr*;
expr: LEFTPAREN expr RIGHTPAREN
    | expr (AND|OR) expr
    | LEFTPAREN equation RIGHTPAREN
    | equation
    ;
equation : identifier equality value
         | LEFTPAREN equation RIGHTPAREN
         ;
equality : (EQUALS | NOTEQUALS);
identifier : ID;
value : STRING;

LEFTPAREN : '(';
RIGHTPAREN : ')';
AND : '&&';
OR : '||';
EQUALS : '=';
NOTEQUALS : '!=';
NEWLINE : [\r\n]+ ;
STRING : ('"'|'\'') ('a'..'z'|'A'..'Z'|'0'..'9'|'*'|'_'|'-')* ('"'|'\'');
ID  :   ('a'..'z'|'A'..'Z')+;
INT :   '0'..'9'+;
WS  :   [ \t\n\r]+ -> skip ;

When I run antlr4 utility to run this

line 1:9 no viable alternative at input '(A='a'AND' line 1:13 extraneous input 'B' expecting {'=', '!='} line 1:29 mismatched input ')' expecting STRING line 1:34 mismatched input '(' expecting {'=', '!='} line 1:51 mismatched input '(' expecting {'=', '!='} line 1:67 extraneous input 'D' expecting {'=', '!='} line 1:77 mismatched input ')' expecting STRING

and I get this tree Generated Parse Tree

I'm still trying to understand and learn ANTLR4 but can anyone give me some pointers on getting this to work?

Upvotes: 0

Views: 142

Answers (1)

Lee Meador
Lee Meador

Reputation: 12985

Did you use AND and OR or did you use && and ||? The grammar wants && and ||.

Upvotes: 1

Related Questions