/
parses.py
50 lines (40 loc) · 1.04 KB
/
parses.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
import reader
tokens = reader.read_file("caspalc/tokens")
parser = reader.read_json("parse_table.json")
productions = parser["productions"]
table = parser["table"]
def check(tokens):
stack = ['$', '<S>']
i = 0
current_word = get_token_info(tokens[i])
while stack != ['$']:
if(i >= len(tokens) and stack != ['$']):
print("ERROR: Unexpected end of file.")
return False
print(stack, tokens[i])
if stack[-1] == current_word:
i += 1
if i < len(tokens):
current_word = get_token_info(tokens[i])
del stack[-1]
else:
top = stack[-1]
subs = productions[table[top][current_word]]
if subs == ["ERR"]:
print("ERROR: SYNTAX ERROR NEAR " + current_word)
return False
del stack[-1]
for item in subs:
if item != '&':
stack.append(item)
print("SYNTAX ANALYSIS COMPLETE")
return True
def get_token_info(token):
token = token[1:]
token = token[:-1]
info = token.split(', ')
if info[1] == 'PR' or info[1] == 'SEP' or info[0] == ':=':
return info[0]
else:
return info[1]
print(check(tokens))