-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuckparser2.py
440 lines (348 loc) · 12 KB
/
puckparser2.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import re
import sys
def is_integer(s):
return re.match(r'^[+-]?\d+$', s) is not None
def is_decimal(s):
regex = r'^[+-]?\d+\.\d+$'
return re.match(regex, s) is not None
def is_valid_string(s):
regex = r'^\"[^\"\s]*\"$'
return re.match(regex, s) is not None
def is_keyword(s):
keywords = {'WRITE', '.', '[', ']', '(', ')', ';'}
return s.upper() in keywords
def is_operator(s):
operators = {':=', '~', '<', '>', '=', '#', '+', '-', '&', 'OR', '*', '/', 'AND'}
return s.upper() in operators
def is_identifier(s):
# Regular expression to match valid identifiers
regex = r'^[a-zA-Z_][a-zA-Z0-9_]*$'
# Check if the string is a keyword
keywords = {'WRITE', '.', '[', ']', '(', ')', ';', ':=', '~', '<', '>', '=', '#', '+', '-', '&', 'OR', '*', '/', 'AND',"ELSIF", "WHILE", "IF", "END", "END.", "FUNCTION", ",", "MOD", "DIV"}
if s in keywords:
return False
# Check if the string matches the identifier pattern
return re.match(regex, s) is not None
def is_relation(s):
return s in {"<", ">", "=", "#"}
def is_AddOperator(s):
return s in {"+", "-", "OR", "&"}
def is_MulOperator(s):
return s in {"*", "/", "AND", "MOD", "DIV"}
def is_member_access(s):
return s == "."
def is_assignment(s):
return s == ":="
def error(message, token):
raise ParserError(f'ERROR: "{message}" expected. got "{token}"')
def identifier_isnot_function(ident):
raise ParserError(f"Variable '{ident}' used as function.")
def identifier_isnot_variable(ident):
raise ParserError(f"Function '{ident}' used as variable.")
def identifier_isnot_defined(ident):
raise ParserError(f"Undefined function {ident}")
class ParserError(Exception): pass
def main():
_tokens = sys.stdin.read().split()
symbols = {}
def error2(expected):
raise ParserError(f"ERROR2: Expected {expected} expected. got '{_tokens[0]}'")
def getToken():
nonlocal _tokens
_tokens = _tokens[1:]
def token():
return _tokens[0]
def parse_SimpleExpression():
parse_Term()
while _tokens and is_AddOperator(token()):
getToken()
parse_Term()
def parse_Term():
parse_Factor()
while _tokens and is_MulOperator(token()):
getToken()
parse_Factor()
def parse_Expression():
parse_SimpleExpression()
if _tokens and is_relation(token()):
getToken()
parse_SimpleExpression()
def parse_Selector():
if is_member_access(token()):
getToken()
if is_identifier(token()):
assert token() not in symbols
symbols[token()] = "variable"
getToken()
else:
error("Expected Identifier", token())
return True
elif token() == "[":
getToken()
parse_Expression()
if token() == "]":
getToken()
return True
else:
error("Expected ]", token())
else:
return False
def parse_Assignment():
if is_identifier(token()):
if token() not in symbols:
symbols[token()] = "variable"
elif symbols[token()] == "function":
identifier_isnot_variable(token())
if not parse_Designator():
return False
if is_assignment(token()):
getToken()
parse_Expression()
return True
else:
return False
def parse_WriteStatement():
if token() == "WRITE":
getToken()
if token() == "(":
getToken()
parse_Expression()
if token() == ")":
getToken()
else:
error("Expected )", token())
else:
error("Expected (", token())
return True
else:
return False
def parse_Designator():
if is_identifier(token()):
getToken()
while parse_Selector():
pass
return True
else:
return False
def parse_Factor():
if (is_integer(token())
or is_decimal(token())
or is_valid_string(token())
or is_identifier(token())
):
if not is_identifier(token()):
getToken()
else:
if token() in symbols and symbols[token()] == "function":
identifier_isnot_variable(token())
if _tokens[1] == "." or _tokens[1] == "[":
parse_Designator()
elif _tokens[1] == "(":
parse_FunctionCall()
else:
getToken()
#error("Expected '.', '[', or '('", _tokens[1])
elif token() == "(":
getToken()
parse_Expression()
if token() == ")":
getToken()
else:
error(")", token())
elif token() == "~":
getToken()
parse_Factor()
else:
error("Factor", token())
def parse_Statement():
if token() == "IF":
parse_IfStatement()
return True
elif token() == "WHILE":
parse_WhileStatement()
return True
if len(_tokens) > 1 and _tokens[1] == "(" and token() != "WRITE":
parse_FunctionCall()
return True
elif parse_Assignment():
return True
elif parse_WriteStatement():
return True
return False
def parse_StatementSequence():
if parse_Statement():
while _tokens and token() == ";":
getToken()
parse_Statement()
else:
error("Expected Statement", token())
def parse_IfStatement():
if token() == "IF":
getToken()
parse_Expression()
if token() == "THEN":
getToken()
parse_StatementSequence()
if token() == "ELSE":
getToken()
parse_StatementSequence()
if token() == "END":
getToken()
return True
else:
error("Expected 'END'", token())
elif token() == "ELSIF":
while token() == "ELSIF":
getToken()
parse_Expression()
if token() == "THEN":
getToken()
parse_StatementSequence()
if token() == "END":
getToken()
return
elif token() == "ELSE":
getToken()
parse_StatementSequence()
if token() == "END":
getToken()
return True
else:
error("Expected 'END'", token())
if token() == "END":
getToken()
return
else:
error2("END")
else:
error("Expected 'THEN'", token())
else:
error("Expected IF", token())
def parse_FunctionBody():
if token() == ";":
getToken()
return
parse_StatementSequence()
if token() == "RETURN":
getToken()
if token() == "(":
getToken()
if is_identifier(token()):
getToken()
if token() == ")":
getToken()
else:
error("Expected )", token())
else:
error("Expected identifier", token())
else:
error("EXPECTED (", token())
if token() == "END.":
getToken()
return
else:
error("Expected 'END.'", token())
def parse_FunctionDeclaration():
if token() == "FUNCTION":
getToken()
if is_identifier(token()):
symbols[token()] = "function"
getToken()
if token() == "(":
getToken()
parse_ParamSequence()
if token() == ")":
getToken()
else:
error("Expected )", token())
else:
error("Expected (", token())
parse_FunctionBody()
else:
error("Expected Identifier", token())
else:
error("Expected 'FUNCTION'", token())
def parse_DeclarationSequence():
while _tokens and token() == "FUNCTION":
parse_FunctionDeclaration()
def parse_ParamSequence():
if is_identifier(token()):
if token() in symbols and symbols[token()] != "variable":
identifier_isnot_variable(token())
else:
symbols[token()] = "variable"
getToken()
while token() == ",":
getToken()
if is_identifier(token()):
if token() in symbols and symbols[token()] != "variable":
identifier_isnot_variable(token())
else:
symbols[token()] = "variable"
getToken()
else:
error("Expected identifier", token())
def parse_FunctionCall():
if is_identifier(token()):
if token() not in symbols:
identifier_isnot_defined(token())
elif symbols[token()] == "variable":
identifier_isnot_function(token())
assert symbols[token()] == "function"
getToken()
if token() == "(":
getToken()
parse_ParamSequence()
if token() == ")":
getToken()
else:
error("Expected ')'", token())
else:
error("Expected '('", token())
else:
error("Expected FunctionCall", token())
def parse_WhileStatement():
if token() == "WHILE":
getToken()
parse_Expression()
if token() == "DO":
getToken()
parse_StatementSequence()
if token() == "ELSIF":
getToken()
parse_Expression()
if token() == "DO":
getToken()
parse_StatementSequence()
if token() == "END":
getToken()
else:
error2("END")
else:
error2("DO")
elif token() == "END":
getToken()
else:
error2("ELSIF or END")
else:
error2("DO")
else:
error2("WHILE")
# parse_Assignment()
try:
parse_DeclarationSequence()
if len(_tokens):
error("Expected EOF", token())
return
except ParserError as e:
print("INVALID!")
print(e)
except IndexError:
raise EOFError("Unexpected EOF")
else:
print("CORRECT")
print(f"Symbol Table : size {len(symbols)}")
for s in symbols:
print(f"{s:<11} {symbols[s]}")
if __name__ == "__main__":
main()