-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy patharithmetic.py
57 lines (47 loc) · 1.39 KB
/
arithmetic.py
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
55
56
57
from operator import add, sub, mul, truediv as div, neg
import pe
from pe.actions import Constant
from bench.helpers import reduce_infix
def reduce_prefix(*args):
term = args[-1]
for op in args[:-1]:
term = op(term)
return term
def compile():
parser = pe.compile(
r'''
Start <- Spacing Expr EOL? EOF
Expr <- Term ((PLUS / MINUS) Term)*
Term <- Factor ((TIMES / DIVIDE) Factor)*
Factor <- Sign* (LPAR Expr RPAR
/ INTEGER )
Sign <- NEG / POS
INTEGER <- ~( '0' / [1-9] [0-9]* ) Spacing
PLUS <- '+' Spacing
MINUS <- '-' Spacing
TIMES <- '*' Spacing
DIVIDE <- '/' Spacing
LPAR <- '(' Spacing
RPAR <- ')' Spacing
NEG <- '-' Spacing
POS <- '+' Spacing
Spacing <- [ \t\n\f\v\r]*
EOL <- '\r\n' / [\n\r]
EOF <- !.
''',
actions={
'Expr': reduce_infix,
'Term': reduce_infix,
'Factor': reduce_prefix,
'INTEGER': int,
'PLUS': Constant(add),
'MINUS': Constant(sub),
'TIMES': Constant(mul),
'DIVIDE': Constant(div),
'NEG': Constant(neg),
},
parser='machine',
flags=pe.OPTIMIZE
)
return lambda s: parser.match(s).value()
parse = compile()