-
Notifications
You must be signed in to change notification settings - Fork 4
/
to_sympy_parser_sexpr.py
98 lines (81 loc) · 2.75 KB
/
to_sympy_parser_sexpr.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import ply.yacc as yacc
from sympy import symbols, And, Or, Not, Xor, Nand, Nor, Implies, Equivalent
from prop_lexer import PropLexer
class PropParser(object):
tokens = PropLexer.tokens
"""
id: symbol | ( prop )
term : id
prop: term
| ( * prop prop )
| ( + prop prop )
| ( & prop prop )
| ( ! prop )
"""
# Parsing rules
precedence = (
("left", "OR"),
("left", "AND"),
("left", "CONCAT"),
("right", "NOT"),
)
def __init__(self):
self.lexer = PropLexer()
self.lexer.build()
self.atoms = {}
self.concat_spliter = {}
self.concat_spliter_id = 0
# for parsing the proposition
def p_prop_term(self, p):
"prop : term"
p[0] = p[1]
def p_prop_and(self, p):
"prop : LPAREN AND prop prop RPAREN"
p[0] = And(p[3], p[4])
def p_prop_or(self, p):
"prop : LPAREN OR prop prop RPAREN"
p[0] = Or(p[3], p[4])
def p_prop_concat(self, p):
"prop : LPAREN CONCAT prop prop RPAREN"
# if p[3], p[4] both not start with `po`
# if not str(p[3]).startswith("po") and not str(p[4]).startswith("po"):
# p[0] = Xor(p[3], p[4])
# elif str(p[3]).startswith("po") and not str(p[4]).startswith("po"):
# p[0] = Nand(p[3], p[4])
# elif not str(p[3]).startswith("po") and str(p[4]).startswith("po"):
# p[0] = Nand(p[4], p[3])
# else:
# p[0] = Nand(p[3], p[4])
"prop : prop CONCAT prop"
p[0] = Xor(p[3], p[4])
# if self.concat_spliter_id is 0, add p[1] and p[3] to concat_spliter
if self.concat_spliter_id == 0:
self.concat_spliter[self.concat_spliter_id] = p[3]
self.concat_spliter[self.concat_spliter_id + 1] = p[4]
self.concat_spliter_id += 2
else:
self.concat_spliter[self.concat_spliter_id] = p[4]
self.concat_spliter_id += 1
def p_prop_not(self, p):
"prop : LPAREN NOT prop RPAREN"
p[0] = Not(p[3])
def p_term_id(self, p):
"term : id"
p[0] = p[1]
def p_id_symbol(self, p):
"id : SYMBOL"
if p[1] not in self.atoms:
self.atoms[p[1]] = symbols(p[1])
p[0] = self.atoms[p[1]]
def p_error(self, p):
print("Syntax error at '%s'" % p)
def build(self, **kwargs):
self.parser = yacc.yacc(module=self, **kwargs)
def parse(self, data):
self.lexer.input(data)
return self.parser.parse(data, lexer=self.lexer.lexer), self.concat_spliter
# test string
# parser = PropParser()
# parser.build()
# result = parser.parse("(& (* pi2 pi3) pi4)")
# print(result)