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