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