/
calc6.py
227 lines (181 loc) · 6.67 KB
/
calc6.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
# Version 0.6
# Time: Dec,2,2015
# Auther: Jason Luo
# Content: An easy Interpreter that can interpret fundamental expression
# (Plus, Minus, Multiplication, Division, Parentheses)
#
#*************************= New Features =**************************
# v0.6 Add parentheses support for the interpreter *
#------------------------------------------------------------------*
# v0.5 Modify code for interpreting plus, minus, multiply and *
# integer division expression *
#------------------------------------------------------------------*
# v0.4 Modify code for interpret multiplication and integer *
# division expression *
#------------------------------------------------------------------*
# v0.3 Support interpreting more than one mutidigits *
#------------------------------------------------------------------*
# v0.2 Support mutidigit calculation *
# Support minus operation *
#*******************************************************************
# Token Types:
# EOF: End-Of-File
INTEGER, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, EOF = (
'INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', '(', ')', 'EOF'
)
class Token(object):
def __init__(self, type, value):
# Token types: INTEGER, PLUS, MINUS, MUL, DIV, EOF
self.type = type
# Token value: 0,1,2,3,4,5,6,7,8,9,,+,-,*,/,None
self.value = value
def __str__(self):
"""
The format of the print infomation
For examle:
Token(INTEGER, 3)
Token(PLUS, '+')
Token(MINUS, '-')
TOKEN(MUL, '*')
TOEKN(LPAREN, ')')
"""
return 'Token({type},{value})'.format(
type = self.type,
value = repr(self.value)
)
def __repr__(self):
return self.__str__()
class Lexer(object):
def __init__(self, text):
# Process the whole input
# e.g. 3+ 5 * 2 - 4/2
self.text = text
self.pos = 0
self.current_char = self.text[self.pos]
def error(self):
raise Exception('Invalid character!')
def advance(self):
# Advance the pos and set current_char
self.pos += 1
if self.pos > len(self.text)-1:
self.current_char = None
else:
self.current_char = self.text[self.pos]
def skip_whitespace(self):
# Skip space
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
# Support mutidigit integer
result = ''
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()
return int(result)
def get_next_token(self):
"""
Lexical Analyzer:
Parsing the input into tokens.
Strategy:
1. dictate current char
2. if it is a space, advance the pos
3. if it is a digit, then convert it to integer and return INTEGER token
4. if it is a '+', then return PLUS token
5. if it is a '-', then return MINUS token
6. if it is a '*', then return MUL token
7. if it is a '/', then return DIV token
8. if it is a '(', then return LPAREN token
9. if it is a ')', then return RPAREN token
"""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
return Token(INTEGER, self.integer())
if self.current_char == '+':
self.advance()
return Token(PLUS, '+')
if self.current_char == '-':
self.advance()
return Token(MINUS, '-')
if self.current_char == '*':
self.advance()
return Token(MUL, '*')
if self.current_char == '/':
self.advance()
return Token(DIV, '/')
if self.current_char == '(':
self.advance()
return Token(LPAREN, '(')
if self.current_char == ')':
self.advance()
return Token(RPAREN, ')')
self.error()
return Token(EOF, None)
class Interpreter(object):
def __init__(self, lexer):
self.lexer = lexer
self.current_token = self.lexer.get_next_token()
def error(self):
raise Exception('Invalid Syntax')
def eat(self, token_type):
# compare the current token with the passed token type
# if they match then eat the current token and assign next token to the self.current_token
# otherwise raise an Exception
if self.current_token.type == token_type:
self.current_token = self.lexer.get_next_token()
else:
self.error()
def factor(self):
# factor: Integer | LPAREN expr RPAREN
token = self.current_token
if token.type == INTEGER:
self.eat(INTEGER)
return token.value
if token.type == LPAREN:
self.eat(LPAREN)
result = self.expr()
self.eat(RPAREN)
return result
def term(self):
# term: factor( (MUL | DIV) factor)*
# factor: Integer
result = self.factor()
while self.current_token.type in (MUL, DIV):
token = self.current_token
if token.type == MUL:
self.eat(MUL)
result = result * self.factor()
elif token.type == DIV:
self.eat(DIV)
result = result / self.factor()
return result
def expr(self):
# expr: term( (PLUS | MINUS) term)*
# term: factor( (MUL | DIV) factor)*
# factor: Integer
result = self.term()
while self.current_token.type in (PLUS, MINUS):
token = self.current_token
if token.type == PLUS:
self.eat(PLUS)
result = result + self.term()
elif token.type == MINUS:
self.eat(MINUS)
result = result - self.term()
return result
def main():
while True:
try:
text = raw_input('cal> ')
except EOFError:
break
if not text:
continue
lexer = Lexer(text)
interpreter = Interpreter(lexer)
result = interpreter.expr()
print(result)
if __name__ == '__main__':
main()