Can Antlr ignore some of the keyword?

Tags: , , ,



I’m new to Antlr but I’m trying to change some of the Grammar from my existing project. The example of the grammar looks like this

...

factor 
    : ava | NOT^ factor | (LPAREN! expr RPAREN!) ;
    
ava
    : key=ALPHANUM EQUALS value=ALPHANUM ;

AND     
    : ('and' | 'AND');

OR  
    : ('or' | 'OR'); 
    

NOT
    : ('not' | 'NOT');  


ALPHANUM 
    : (ALPHA | DIGIT | LIMITED_SYMBOLS)+ ;
        
    
WHITESPACE 
    : ( 't' | ' ' | 'r' | 'n'| 'u000C' )+ { $channel = HIDDEN; } ;

fragment ALPHA 
        : ('a'..'z' | 'A'..'Z') ;

fragment DIGIT 
    : '0'..'9' ;
    
fragment LIMITED_SYMBOLS
    : ('.' | '!' | '@' | '#' | '$' | '%' | '^' | '&' | '*' | '-' | '_' | '+' | '~' | ':' | '/' | '?' | '|');

The grammar is supposed to parse something like this a=10 AND s=1 AND s=2 or ((a=9 AND s=1) AND s=2).

The question is is it possible to ignore anything that’s not s={ANYTHING}. So from the examples above. The AST will be reduced to

s=1 AND s=2, ((s=1) AND s=2)

Is this even possible by just changing the grammar?

Answer

Is this even possible by just changing the grammar?

No.

For sure there’s something possible with tree rewrites, but it’d involve a lot of target specific code being embedded in your grammar. The best solution would be to just parse the entire input, and after that, walk your AST and discard certain sub-trees that start with s (in plain code).



Source: stackoverflow