aboutsummaryrefslogtreecommitdiff
path: root/runtime/Python/tests/t015calc.g
blob: f08e3ce736ce4e3620bcd27cee9a15885856c989 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
grammar t015calc;
options {
  language = Python;
}

@header {
import math
}

@parser::init {
self.reportedErrors = []
}

@parser::members {
def emitErrorMessage(self, msg):
    self.reportedErrors.append(msg)
}

evaluate returns [result]: r=expression {result = r};

expression returns [result]: r=mult (
    '+' r2=mult {r += r2}
  | '-' r2=mult {r -= r2}
  )* {result = r};

mult returns [result]: r=log (
    '*' r2=log {r *= r2}
  | '/' r2=log {r /= r2}
//  | '%' r2=log {r %= r2}
  )* {result = r};

log returns [result]: 'ln' r=exp {result = math.log(r)}
    | r=exp {result = r}
    ;

exp returns [result]: r=atom ('^' r2=atom {r = math.pow(r,r2)} )? {result = r}
    ;

atom returns [result]:
    n=INTEGER {result = int($n.text)}
  | n=DECIMAL {result = float($n.text)} 
  | '(' r=expression {result = r} ')'
  | 'PI' {result = math.pi}
  | 'E' {result = math.e}
  ;

INTEGER: DIGIT+;

DECIMAL: DIGIT+ '.' DIGIT+;

fragment
DIGIT: '0'..'9';

WS: (' ' | '\n' | '\t')+ {$channel = HIDDEN};