Skip to content

Commit e36f9ea

Browse files
authored
Update parser.py
1 parent 4754d45 commit e36f9ea

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

parser.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@ def __init__(self, tokens):
66
self.tokens = iter(tokens)
77
self.advance()
88

9+
def raise_error(self):
10+
raise Exception("Invalid syntax")
11+
912
def advance(self):
1013
try:
1114
self.current_token = next(self.tokens)
1215
except StopIteration:
1316
self.current_token = None
1417

15-
def raise_error(self):
16-
raise Exception("Invalid syntax")
17-
1818
def parse(self):
1919
if self.current_token == None:
2020
return None
@@ -28,6 +28,7 @@ def parse(self):
2828

2929
def expr(self):
3030
result = self.term()
31+
3132
while self.current_token != None and self.current_token.type in (TokenType.PLUS, TokenType.MINUS):
3233
if self.current_token.type == TokenType.PLUS:
3334
self.advance()
@@ -36,29 +37,31 @@ def expr(self):
3637
self.advance()
3738
result = SubtractNode(result, self.term())
3839

39-
return result
40-
40+
return result
41+
4142
def term(self):
42-
result = self.term()
43-
while self.current_token != None and self.current_token.type in (TokenType.MULTIPLY, TokenType.DOIVIDE):
43+
result = self.factor()
44+
45+
while self.current_token != None and self.current_token.type in (TokenType.MULTIPLY, TokenType.DIVIDE):
4446
if self.current_token.type == TokenType.MULTIPLY:
4547
self.advance()
46-
result = MultiplyNode(result, self.term())
47-
elif self.current_token.type == TokenType.DOIVIDE:
48+
result = MultiplyNode(result, self.factor())
49+
elif self.current_token.type == TokenType.DIVIDE:
4850
self.advance()
49-
result = DivideNode(result, self.term())
51+
result = DivideNode(result, self.factor())
52+
53+
return result
5054

51-
return result
52-
5355
def factor(self):
5456
token = self.current_token
5557

56-
if token.type == TokenType.LPARENT:
58+
if token.type == TokenType.LPAREN:
5759
self.advance()
5860
result = self.expr()
61+
5962
if self.current_token.type != TokenType.RPAREN:
6063
self.raise_error()
61-
64+
6265
self.advance()
6366
return result
6467

@@ -69,9 +72,9 @@ def factor(self):
6972
elif token.type == TokenType.PLUS:
7073
self.advance()
7174
return PlusNode(self.factor())
72-
75+
7376
elif token.type == TokenType.MINUS:
7477
self.advance()
7578
return MinusNode(self.factor())
76-
79+
7780
self.raise_error()

0 commit comments

Comments
 (0)