-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimple_RD_parser.py
160 lines (145 loc) · 3.31 KB
/
Simple_RD_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
import sys
judge_bexpr = 0
token = ''
has_error = False
def getChar():
global token
token = sys.stdin.read(1)
if token == ' ' or token == '\t':
getChar()
def error():
global has_error
print(">> Syntax error!!")
has_error = True
def lex(c):
if token == c:
getChar()
else:
error()
def expr():
return bexpr()
def bexpr():
global judge_bexpr
left = aexpr()
if token in ['=', '!', '<', '>']:
op = relop()
right = aexpr()
judge_bexpr = 1
if op == 0:
return int(left == right)
elif op == 1:
return int(left != right)
elif op == 2:
return int(left < right)
elif op == 3:
return int(left > right)
elif op == 4:
return int(left <= right)
elif op == 5:
return int(left >= right)
else:
error()
return 0
else:
judge_bexpr = -1
return left
def relop():
global token
if token == '=':
lex('=')
if token == '=':
lex('=')
return 0
else:
error()
elif token == '!':
lex('!')
if token == '=':
lex('=')
return 1
elif token == '<':
lex('<')
if token == '=':
lex('=')
return 4
return 2
elif token == '>':
lex('>')
if token == '=':
lex('=')
return 5
return 3
else:
error()
def aexpr():
result = term()
while not has_error and token in ['*', '/']:
if token == '*':
lex('*')
result *= term()
elif token == '/':
lex('/')
result //= term()
return result
def term():
result = factor()
while not has_error and token in ['+', '-']:
if token == '+':
lex('+')
result += factor()
elif token == '-':
lex('-')
result -= factor()
return result
def factor():
global token
if token == '(':
lex('(')
result = aexpr()
if token == ')':
lex(')')
else:
error()
else:
result = number()
return result
def number():
result = dec()
while not has_error and token.isdigit():
result = 10 * result + dec()
return result
def dec():
global token
if not token.isdigit():
error()
return 0
result = int(token)
lex(token)
return result
def print_expr():
global has_error
has_error = False
result = expr()
if has_error:
return 1
if token == '\n':
if judge_bexpr == 1 and result == 1:
print(">> true")
elif judge_bexpr == 1 and result == 0:
print(">> false")
else:
print(">>", result)
return 0
else:
error()
def main():
while True:
print(">> ", end='')
getChar()
if token == '\n':
break
print_expr()
while token != '\n' and token != '':
getChar() # discard the rest of the line
if __name__ == "__main__":
main()