Home | History | Annotate | Download | only in tests
      1 grammar t015calc;
      2 options {
      3   language = Python;
      4 }
      5 
      6 @header {
      7 import math
      8 }
      9 
     10 @parser::init {
     11 self.reportedErrors = []
     12 }
     13 
     14 @parser::members {
     15 def emitErrorMessage(self, msg):
     16     self.reportedErrors.append(msg)
     17 }
     18 
     19 evaluate returns [result]: r=expression {result = r};
     20 
     21 expression returns [result]: r=mult (
     22     '+' r2=mult {r += r2}
     23   | '-' r2=mult {r -= r2}
     24   )* {result = r};
     25 
     26 mult returns [result]: r=log (
     27     '*' r2=log {r *= r2}
     28   | '/' r2=log {r /= r2}
     29 //  | '%' r2=log {r %= r2}
     30   )* {result = r};
     31 
     32 log returns [result]: 'ln' r=exp {result = math.log(r)}
     33     | r=exp {result = r}
     34     ;
     35 
     36 exp returns [result]: r=atom ('^' r2=atom {r = math.pow(r,r2)} )? {result = r}
     37     ;
     38 
     39 atom returns [result]:
     40     n=INTEGER {result = int($n.text)}
     41   | n=DECIMAL {result = float($n.text)} 
     42   | '(' r=expression {result = r} ')'
     43   | 'PI' {result = math.pi}
     44   | 'E' {result = math.e}
     45   ;
     46 
     47 INTEGER: DIGIT+;
     48 
     49 DECIMAL: DIGIT+ '.' DIGIT+;
     50 
     51 fragment
     52 DIGIT: '0'..'9';
     53 
     54 WS: (' ' | '\n' | '\t')+ {$channel = HIDDEN};
     55