-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser_.py
113 lines (85 loc) · 2.76 KB
/
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
'''
Transforms tokens into nodes
At this point, our lexer takes the input and generates a list of tokens, so we're not working on a character level, and work on a token level
The parser builds up a tree of what's going to happen:
ex. 1 + 2 * 3
ADD OPERATION
/ \
NUMBER MULTIPLY OPERATION
value: 1 / \
NUMBER NUMBER
value: 2 value: 3
ex. (1 + 2) * 3
MULTIPLY OPERATION
/ \
ADD OPERATION NUMBER
/ \ value: 3
NUMBER NUMBER
value:1 value: 2
Grammar rules:
Factor - Numbers
v
Term - Multiply & divide operations (Number * Number or Number / Number)
v
Expression - Plus and Minus operations (Term + Term or Term - Term)
Each expression or term can have 0 or more operators
'''
from tokens import TokenType
from nodes import *
class Parser:
def __init__(self, tokens):
self.tokens = iter(tokens)
self.advance()
def raise_error(self):
raise Exception("Invalid Syntax")
def advance(self):
try:
self.current_token = next(self.tokens)
except StopIteration:
self.current_token = None
def parse(self):
if self.current_token == None:
return None
result = self.expr()
if self.current_token != None:
self.raise_error()
return result
def expr(self):
result = self.term()
while self.current_token != None and self.current_token.type in (TokenType.PLUS, TokenType.MINUS):
if self.current_token.type == TokenType.PLUS:
self.advance()
result = AddNode(result, self.term())
elif self.current_token.type == TokenType.MINUS:
self.advance()
result = SubtractNode(result, self.term())
return result
def term(self):
result = self.factor()
while self.current_token != None and self.current_token.type in (TokenType.MULTIPLY, TokenType.DIVIDE):
if self.current_token.type == TokenType.MULTIPLY:
self.advance()
result = MultiplyNode(result, self.term())
elif self.current_token.type == TokenType.DIVIDE:
self.advance()
result = DivideNode(result, self.term())
return result
def factor(self):
token = self.current_token
if token.type == TokenType.LPAREN:
self.advance()
result = self.expr()
if self.current_token.type != TokenType.RPAREN:
self.raise_error()
self.advance()
return result
elif token.type == TokenType.NUMBER:
self.advance()
return NumberNode(token.value)
elif token.type == TokenType.PLUS:
self.advance()
return PlusNode(self.factor())
elif token.type == TokenType.MINUS:
self.advance()
return MinusNode(self.factor())
self.raise_error()