-
Notifications
You must be signed in to change notification settings - Fork 1
/
readGrammar.py
172 lines (133 loc) · 3.38 KB
/
readGrammar.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
169
170
import sys, re
from pygments.lexer import RegexLexer
from pygments.token import *
from pygments.token import Token as PygToken
from compiler import *
inputBuffer = sys.stdin.read()
EOF = -1
def see():
global inputBuffer
if len(inputBuffer) == 0:
return EOF
return inputBuffer[0]
def pick():
global inputBuffer
if len(inputBuffer) == 0:
return EOF
c = inputBuffer[0]
inputBuffer = inputBuffer[1:]
return c
def readStr(term):
s = ""
s += pick()
while True:
c = pick()
s += c
if c == term and s[-1] != '\\':
return s
def readCode():
code = ""
code += pick()
while True:
if see() == '\'':
code += readStr('\'')
if see() == '\"':
code += readStr('\"')
if see() == '}':
code += pick()
return code
code += pick()
class CodeHandler:
def __init__(self):
self.code = []
def readCode(self):
self.code.append(readCode())
return '«' + str(len(self.code)-1) + '»'
def getCode(self):
return self.code
ind = 0
def f(s):
global ind
ind = ind+1
return "«STRING" + str(ind) + "»"
#print('inputBuffer:', inputBuffer, 'END')
inputBuffer = re.sub("\"([^\"\n\\]|\\[^'\n]|(\\[\\\"\'nt])*)*\\?", f, inputBuffer) # TODO: Fix with proper string regex
#inputBuffer = re.sub('"([^\"])*"', f, inputBuffer)
print('inputBuffer:', inputBuffer, 'END')
codeHandler = CodeHandler()
annotatedRules = ''
while True:
if see() == EOF:
break
elif see() == '{':
annotatedRules += codeHandler.readCode()
else:
annotatedRules += pick()
#print(annotatedRules, codeHandler.getCode())
#print(annotatedRules)
Arrow = PygToken.Arrow
VertSlash = PygToken.VertSlash
Code = PygToken.Code
class Lexer(RegexLexer):
name='yaccLexer'
tokens = {
'root': [
(r'->', Arrow),
(r'\|', VertSlash),
(r'«[0-9]+»', Code),
(r'[a-zA-Z]+', Literal),
(r'\+|\-|\=|;|\.|~|\*|/|\\|:', Literal),
(r'[ \n]+', Whitespace)
]
}
names = {Arrow: 'Arrow', Code: 'Code', VertSlash: 'VertSlash', Literal: 'Token'}
lexer = Lexer()
unprocessed_tokens = lexer.get_tokens_unprocessed(annotatedRules)
tokens = []
for i in unprocessed_tokens:
if i[1] in names:
name = names[i[1]]
tokens.append(Token(name, i[2]))
tokens.append(Token('$'))
class GrammarNode(Token):
def __init__(self, type, data):
self.type = type
self.data = data
def isTerminal(self):
return False
def __repr__(self):
return "Node(" + self.type + ')'
rules = []
semanticRules = []
def createRule(symbol, productions):
for p in productions:
print()
rules.append( (symbol.value, tuple([i.value for i in p[0]]) ))
codeId = int(p[1].value[1:-1])
semanticRules.append(codeHandler.getCode()[codeId][1:-1])
def listAppend(l, it):
l.append(it)
return l
def pack(a, b):
return (a, b)
semantic = [
CHILD(0),
[createRule, CHILD(1), CHILD(3)], None,
[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)
parser = LALRParser(g, "S")
print(tokens)
parser.parse(tokens)
print()
print('rules', rules)
codeInp = [Token('Id', 'var'), Token('='), Token('Num', 3), Token('+'), Token('Num', 5), Token('-'), Token('Num', 8), Token(';'), Token('$')]
print('semanticRules', semanticRules)
g2 = Grammar(['Id', 'Num', '=', '-', '+', '$', ';'], rules, semanticRules)
languageParser = LALRParser(g2, 'S', evalSemantic=True)
s = languageParser.parse(codeInp)
print(s)