antlrantlr3

ANTLR arithmetic and comparison expressions grammer ANTLR


how to add relational operations to my code

Thanks

My code is

grammar denem1;  
options {    
  output=AST;    
}    

tokens {    
  ROOT;    
}

parse    
  :  stat+ EOF -> ^(ROOT stat+)    
  ;

stat    
  :  expr ';'     
  ;

expr    
  : Id Assign expr -> ^(Assign Id expr)        
  | add    
  ;

add    
  :  mult (('+' | '-')^ mult)*    
  ;

mult    
  :  atom (('*' | '/')^ atom)*    
  ;

atom
  :  Id
  |  Num
  |  '('! expr ')' !
  ;

Assign  :   '=' ;

Comment : '//' ~('\r' | '\n')* {skip();};

Id      : 'a'..'z'+;

Num     : '0'..'9'+;
    
Space   : (' ' | '\t' | '\r' | '\n')+ {skip();};

Solution

  • Like this:

    ...
    
    expr    
      : Id Assign expr -> ^(Assign Id expr)
      | rel
      ;
    
    rel
      : add (('<=' | '<' | '>=' | '>')^ add)?
      ;
    
    add    
      : mult (('+' | '-')^ mult)*
      ;
    
    ...
    

    If possible, use ANTLR v4 instead of the old v3. In v4, you can simply do this:

    stat    
     : expr ';'     
     ;
    
    expr
     : Id Assign expr
     | '-' expr
     | expr ('*' | '/') expr
     | expr ('+' | '-') expr
     | expr ('<=' | '<' | '>=' | '>') expr
     | Id
     | Num
     | '(' expr ')'
     ;