-
Notifications
You must be signed in to change notification settings - Fork 5
/
arithmetic.py
42 lines (32 loc) · 1.11 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
from lark import Lark, Transformer, v_args
from bench.helpers import apply_infix
def compile():
arithmetic_grammar = r'''
?start: expr ";"
?expr: term
| expr "+" term -> add
| expr "-" term -> sub
?term: factor
| term "*" factor -> mul
| term "/" factor -> div
?factor: "-" factor -> neg
| "+" factor
| INTEGER -> number
| "(" expr ")"
INTEGER: "0" | "1".."9" INT?
%import common.INT
%import common.WS_INLINE
%ignore WS_INLINE
'''
@v_args(inline=True)
class TreeToResult(Transformer):
from operator import add, sub, mul, truediv as div, neg
number = int
arithmetic_parser = Lark(arithmetic_grammar,
parser='lalr',
lexer='basic',
propagate_positions=False,
maybe_placeholders=False,
transformer=TreeToResult())
return lambda s: arithmetic_parser.parse(s + ';')
parse = compile()