1 grammar t015calc; 2 options { 3 language = JavaScript; 4 } 5 6 @parser::members { 7 this.emitErrorMessage = function(msg) { 8 if (!this.reportedErrors) { 9 this.reportedErrors = [msg]; 10 } else { 11 this.reportedErrors.push(msg) 12 } 13 }; 14 } 15 16 evaluate returns [result]: r=expression {result = r;}; 17 18 expression returns [result]: r=mult ( 19 '+' r2=mult {r += r2;} 20 | '-' r2=mult {r -= r2;} 21 )* {result = r}; 22 23 mult returns [result]: r=log ( 24 '*' r2=log {r *= r2;} 25 | '/' r2=log {r /= r2;} 26 )* {result = r}; 27 28 log returns [result]: 'ln' r=exp {result = Math.log(r);} 29 | r=exp {result = r;} 30 ; 31 32 exp returns [result]: r=atom ('^' r2=atom {r = Math.pow(r,r2);} )? {result = r;} 33 ; 34 35 atom returns [result]: 36 n=INTEGER {result = parseInt($n.text, 10);} 37 | n=DECIMAL {result = parseFloat($n.text);} 38 | '(' r=expression {result = r;} ')' 39 | 'PI' {result = Math.PI;} 40 | 'E' {result = Math.E;} 41 ; 42 43 INTEGER: DIGIT+; 44 45 DECIMAL: DIGIT+ '.' DIGIT+; 46 47 fragment 48 DIGIT: '0'..'9'; 49 50 WS: (' ' | '\n' | '\t')+ {$channel = HIDDEN;}; 51