-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.py
287 lines (238 loc) · 9.95 KB
/
parse.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# Author: Jackson szekeres
#purpose: parse incoming data in ezl programming lanugage
import sys
from lex import *
import time
import json
# Parser object keeps track of current token, checks if the code matches the grammar, and emits code along the way.
class Parser:
def __init__(self, lexer, debug=False):
self.lexer = lexer
self.debug = debug
self.line = 1
self.symbols = set() # All variables we have declared so far.
self.labelsDeclared = set() # Keep track of all labels declared
self.labelsGotoed = set() # All labels goto'ed, so we know if they exist or not.
self.curToken = None
self.peekToken = None
self.nextToken()
self.nextToken() # Call this twice to initialize current and peek.
self.hidden = dict({})
self.main = dict({
})
# Return true if the current token matches.
def checkToken(self, kind):
return kind == self.curToken.kind
def string(self, str_var):
return str("\""+str_var+"\"")
def is_integer(self, n):
try:
float(n)
except ValueError:
return False
else:
return True
def is_var(self, ident):
try:
self.hidden[ident]
return True
except:
return False
return False
# Return true if the next token matches.
def checkPeek(self, kind):
return kind == self.peekToken.kind
# Try to match current token. If not, error. Advances the current token.
def match(self, kind):
if not self.checkToken(kind):
self.abort("Expected " + kind.name + ", got " + self.curToken.kind.name+" in line "+str(self.line))
self.nextToken()
# Advances the current token.
def nextToken(self):
self.curToken = self.peekToken
self.peekToken = self.lexer.getToken()
# No need to worry about passing the EOF, lexer handles that.
# Return true if the current token is a comparison operator.
def isComparisonOperator(self):
return self.checkToken(TokenType.GT) or self.checkToken(TokenType.GTEQ) or self.checkToken(TokenType.LT) or self.checkToken(TokenType.LTEQ) or self.checkToken(TokenType.EQEQ) or self.checkToken(TokenType.NOTEQ)
#abort is exit with message
def queryify(self, query):
if self.is_var(self.curToken.text):
if self.is_integer(self.hidden[self.curToken.text]):
query = query+str(self.hidden[self.curToken.text])
else:
query = query + self.string(self.hidden[self.curToken.text])
elif self.isComparisonOperator():
query = query + self.curToken.text
elif self.is_integer(self.curToken.text):
query = query + str(self.curToken.text)
else:
query = query + self.string(self.curToken.text)
return query
def abort(self, message):
sys.exit("Error! " + message)
#this is the main file
def program(self):
# Since some newlines are required in our grammar, need to skip the excess.
while self.checkToken(TokenType.NEWLINE):
self.nextToken()
self.line += 1
# Parse all the statements in the program.
while not self.checkToken(TokenType.EOF):
# print('\033[91m'+self.curToken.text+'\033[0m')
self.statement()
def statement(self):
# Check the first token to see what kind of statement this is.
# "PRINT" (expression | string)
if self.checkToken(TokenType.PRINT):
self.nextToken()
query = ""
while not self.checkToken(TokenType.NEWLINE):
query = self.queryify(query).replace('"', '')
self.nextToken()
try:
print(eval(query))
except:
print(query)
#RAISE (STRING)
#raise error
elif self.checkToken(TokenType.RAISE):
self.nextToken()
self.main["RAISE error line "+str(self.line)] = self.curToken.text
raise SystemError(self.curToken.text)
self.nextToken()
elif self.checkToken(TokenType.IF):
self.nextToken()
#print(self.curToken.text)
query = str("")
while not self.checkToken(TokenType.THEN):
query = self.queryify(query)
self.nextToken()
self.nextToken()
self.main["IF line "+str(self.line)] = str(eval(query))
if eval(query):
self.nl()
while not self.checkToken(TokenType.ENDIF):
self.statement()
self.nextToken()
else:
self.nl()
while not self.checkToken(TokenType.ENDIF):
self.nextToken()
self.nextToken()
#WAIT float
#wait before contining
elif self.checkToken(TokenType.WAIT):
self.nextToken()
try:
self.main["WAIT line "+str(self.line)] = str(self.curToken.text)
time.sleep(float(self.curToken.text))
self.nextToken()
except:
self.abort('Input passed is not a float')
# "LET" ident = expression
elif self.checkToken(TokenType.LET):
self.nextToken()
# Check if ident exists in symbol table. If not, declare it.
if self.curToken.text not in self.symbols:
self.symbols.add(self.curToken.text)
var = self.curToken.text
self.match(TokenType.IDENT)
self.match(TokenType.EQ)
query = ""
while not self.checkToken(TokenType.NEWLINE):
query = self.queryify(query).strip("\"")
self.nextToken()
#print(self.curToken.text)
#self.nextToken()
# "INPUT" ident
elif self.checkToken(TokenType.INPUT):
self.nextToken()
# If variable doesn't already exist, declare it.
if self.curToken.text not in self.symbols:
self.symbols.add(self.curToken.text)
self.hidden[self.curToken.text] = input("")
self.main["varible "+self.curToken.text] = self.hidden[self.curToken.text]
self.match(TokenType.IDENT)
elif self.checkToken(TokenType.EXPORT):
self.nextToken()
if self.checkToken(TokenType.STRING):
with open(self.curToken.text, "w+") as f:
json.dump(self.main, indent = 4, fp = f)
self.nextToken()
elif self.checkToken(TokenType.REPEAT):
self.nextToken()
try:
repeat = int(self.curToken.text)
except:
self.abort('REPEAT has no specified int')
self.nextToken()
self.nl()
for i in range(0, repeat):
while not self.checkToken(TokenType.ENDREPEAT):
self.statement()
self.nextToken()
pass
# This is not a valid statement. Error!
else:
self.abort("Invalid statement at " + self.curToken.text + " (" + self.curToken.kind.name + ") in line "+str(self.line))
#line count so you know the line # for errors
self.line += 1
# Newline.
self.nl()
# comparison ::= expression (("==" | "!=" | ">" | ">=" | "<" | "<=") expression)+
def comparison(self):
self.expression()
# Must be at least one comparison operator and another expression.
if self.isComparisonOperator():
self.nextToken()
self.expression()
# Can have 0 or more comparison operator and expressions.
while self.isComparisonOperator():
yield self.curToken.text
self.nextToken()
self.expression()
# expression ::= term {( "-" | "+" ) term}
def expression(self):
self.term()
# Can have 0 or more +/- and expressions.
while self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS):
yield self.curToken.text
self.nextToken()
self.term()
# term ::= unary {( "/" | "*" ) unary}
def term(self):
self.unary()
# Can have 0 or more *// and expressions.
while self.checkToken(TokenType.ASTERISK) or self.checkToken(TokenType.SLASH) or self.checkToken(TokenType.MOD):
yield self.curToken.text
self.nextToken()
self.unary()
# unary ::= ["+" | "-"] primary
def unary(self):
# Optional unary +/-
if self.checkToken(TokenType.PLUS) or self.checkToken(TokenType.MINUS):
yield self.curToken.text
self.nextToken()
self.primary()
# primary ::= number | ident
def primary(self):
if self.checkToken(TokenType.FLOAT):
yield self.curToken.text
self.nextToken()
elif self.checkToken(TokenType.IDENT):
# Ensure the variable already exists.
if self.curToken.text not in self.symbols:
self.abort("Referencing variable before assignment: " + self.curToken.text)
return self.curToken.text
self.nextToken()
else:
# Error!
self.abort("Unexpected token at " + self.curToken.text)
# nl ::= '\n'+
def nl(self):
# Require at least one newline.
self.match(TokenType.NEWLINE)
# But we will allow extra newlines too, of course.
while self.checkToken(TokenType.NEWLINE):
self.nextToken()