-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.py
169 lines (137 loc) · 4 KB
/
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
from pygments.token import _TokenType, Token as _PygToken
from lexer import GenericLexer, LexToken as LT, LexToken
from compiler import *
EOF = -1
class Buffer:
def __init__(self, s):
self.inputBuffer = s
def see(self):
if len(self.inputBuffer) == 0:
return EOF
return self.inputBuffer[0]
def pick(self):
if len(self.inputBuffer) == 0:
return EOF
c = self.inputBuffer[0]
self.inputBuffer = self.inputBuffer[1:]
return c
def readStr(self, term):
s = ""
s += self.pick()
while True:
c = self.pick()
s += c
if c == term and s[-1] != '\\':
return s
def readCode(self):
code = ""
code += self.pick()
while True:
if self.see() == '\'':
code += self.readStr('\'')
if self.see() == '\"':
code += self.readStr('\"')
if self.see() == '}':
code += self.pick()
return code
code += self.pick()
class CodeHandler:
def __init__(self, inputBuffer):
self.code = []
self.inputBuffer = inputBuffer
def readCode(self):
self.code.append(self.inputBuffer.readCode())
return '«' + str(len(self.code)-1) + '»'
def getCode(self):
return self.code
class YaccLexer(GenericLexer):
name='yaccLexer'
tokens = {
'root': [
(r'[a-zA-Z]+[ \n\t]+->', LT.Left),
(r'\|', LT.VertSlash),
(r'%[a-zA-Z]+', LT.Macro),
(r'«[0-9]+»', LT.Code),
(r'[a-zA-Z]+', LT.Token),
(r'\+|\-|\=|;|\.|~|\*|/|\\|:', LT.Token),
]
}
class InvalidGrammar(Exception):
def __init__(self):
Exception.__init__(self, "InvalidGrammar: The grammar provided could not be parsed.")
class Parser():
def __init__(self):
self.lexicalRules = None
self.inputFile = None
self.rules = []
self.semanticRules = []
self.codeHandler = None
self.precedence = []
self.assoc = {}
self.languageParser = None
self.loadYaccParser()
def loadYaccParser(self):
def createRule(symbol, productions):
symbol = symbol.value.split()[0]
for p in productions:
self.rules.append( (symbol, tuple([i.value for i in p[0]]) ))
codeId = int(p[1].value[1:-1])
self.semanticRules.append(self.codeHandler.getCode()[codeId][1:-1])
def createMacro(macro, ops):
macro = macro.value
ops = [o.value for o in ops]
if macro == '%priority':
for op1 in range(len(ops)):
for op2 in range(op1+1, len(ops)):
self.precedence.append((ops[op1], ops[op2]))
elif macro == '%right' or macro == '%left':
m = macro[1:]
for op in ops:
self.assoc[op] = m
else:
print('Invalid macro ', macro)
def listAppend(l, it):
l.append(it)
return l
def pack(a, b):
return (a, b)
semantic = [
CHILD(0),
None, None,
[createRule, CHILD(0), CHILD(1)], [createMacro, CHILD(0), CHILD(1)],
[listAppend, CHILD(0), CHILD(1)],
[listAppend, CHILD(0), CHILD(1)], [],
[pack, CHILD(0), CHILD(1)],
CHILD(0), None,
[listAppend, CHILD(0), CHILD(1)], [CHILD(0)]
]
g = readGrammar("yaccRules.grammar", semantic=semantic)
self.yaccParser = LALRParser(g, "S")
def loadGrammar(self, filename, terminals):
try:
data = open(filename).read()
#data = re.sub("\"([^\"\n\\]|\\[^'\n]|(\\[\\\"\'nt])*)*\\?", f, data) # TODO: Fix with proper string regex
#print('inputBuffer:', data, 'END')
inputBuffer = Buffer(data)
self.codeHandler = CodeHandler(inputBuffer)
annotatedRules = ''
while True:
if inputBuffer.see() == EOF:
break
elif inputBuffer.see() == '{':
annotatedRules += self.codeHandler.readCode()
else:
annotatedRules += inputBuffer.pick()
tokenNames = [LT.Left, LT.Code, LT.VertSlash, LT.Token, LT.Macro]
lexer = YaccLexer()
tokens = lexer.parseString(annotatedRules)
self.yaccParser.parse(tokens)
self.grammar = Grammar(terminals, self.rules, self.semanticRules)
self.grammar.setPrecedence(self.precedence)
self.grammar.setAssoc(self.assoc)
self.languageParser = LALRParser(self.grammar, 'S', evalSemantic=True)
except Exception as e:
raise InvalidGrammar()
def parseTokens(self, tokens=None):
# TODO: with or without lexical analysis
return self.languageParser.parse(tokens)