-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexpr_arpeggio_parser.py
82 lines (72 loc) · 2.74 KB
/
expr_arpeggio_parser.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from expr_arpeggio_grammar import expr_grammar
class ExprArpeggioParser():
"""
These two methods are the "public" API
"""
@classmethod
def parse(cls, expr):
"""Parse the input expression and return a parse tree"""
return expr_grammar.parse(expr)
@classmethod
def parse_to_ast(cls, expr):
"""Parse the input expression and return an AST"""
return cls.to_expr_tree(cls.parse(expr))
"""
Helper methods below
"""
@classmethod
def to_expr_tree(cls, expr):
match expr.rule_name:
case "num_i"|"num_f":
return ExprNode("num", expr.value)
case "var":
return ExprNode("var", expr.value)
case "func":
return ExprNode("func", expr[0].value, [cls.to_expr_tree(p) for p in expr[1:]])
case "unary":
return ExprNode("unary", expr[0].value, [cls.to_expr_tree(expr[1])])
case "term":
# this is RtoL associativity
val = None
tmp = None
subtree = None
for i in range(len(expr)):
if i % 2 == 0:
val = cls.to_expr_tree(expr[i])
else:
foo = ExprNode("binary", str(expr[i]), [val])
if not subtree:
subtree = foo
else:
tmp.nodes.append(foo)
tmp = foo
tmp.nodes.append(val)
return subtree
case "lor"|"land"|"bor"|"xor"|"band"|"eq"|"gtlt"|"shift"|"factor":
# this is LtoR associativity
subtree = None
for i in range(len(expr)):
if i % 2 == 0:
if not subtree:
subtree = cls.to_expr_tree(expr[i])
else:
subtree.nodes.append(cls.to_expr_tree(expr[i]))
else:
subtree = ExprNode("binary", str(expr[i]), [subtree])
return subtree
class ExprNode:
def __init__(self, node_type, value, nodes=[]):
self.type = node_type
self.value = value
self.nodes = nodes
def __str__(self):
"""Output that kinda shows the shape of the tree. This
could be improved, but is better than flying blind.
"""
match self.type:
case "num" | "var":
return f"{{type: {self.type}, value: {self.value}}}"
case _:
return f"""{{type: {self.type}, value: {self.value}
{','.join([str(p) for p in self.nodes])}
}}"""