Question

I'm trying to make parser using Antlr4 for the sql select statement, in which contains the following part

expr: '1' | expr('*'|'/'|'+'|'-'|'||') expr; // As the re-factored form of expression: compound expression;
WS :[ \t\r\n]+ -> skip ; 

I suppose this rule will allow the following sets of result:

1
1+1
1+1-1
....

But in the graph it shows that it cannot be parsed

Does anyone get the idea why it cannot be parsed like what i expected?

Was it helpful?

Solution

This slightly adjusted grammar works for me. Tested on input 1+1-1||1*1-1/1. Tested in ANTLRWorks2.1

grammar myGrammar;

top : expr EOF ;

expr : '1'
     | expr '+' expr 
     | expr '*' expr
     | expr '/' expr
     | expr '+' expr
     | expr '-' expr
     | expr '||' expr
     ;

WS :[ \t\r\n]+ -> skip ; 

One : '1' ;
Times : '*' ;
Div : '/' ;
Plus : '+' ;
Minus : '-' ;
Or : '||' ;

enter image description here

EDIT

I was able to get this to work, too, when matching the rule top:

grammar newEmptyCombinedGrammar;

top : expr EOF ;

expr: one 
    | expr op=(Times|Div|Plus|Minus|Or) expr
    ;

one : One ;

One : '1' ;
Times : '*' ;
Div : '/' ;
Plus : '+' ;
Minus : '-' ;
Or : '||' ;

WS :[ \t\r\n]+ -> skip ; 

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top