- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser_.py
More file actions
Latest commit
80 lines (59 loc) · 1.79 KB
/
Copy pathparser_.py
File metadata and controls
80 lines (59 loc) · 1.79 KB
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
fromtokensimportTokenType
fromnodesimport*
classParser:
def__init__(self, tokens):
self.tokens=iter(tokens)
self.advance()
defraise_error(self):
raiseException("Invalid syntax")
defadvance(self):
try:
self.current_token=next(self.tokens)
exceptStopIteration:
self.current_token=None
defparse(self):
ifself.current_token==None:
returnNone
result=self.expr()
ifself.current_token!=None:
self.raise_error()
returnresult
defexpr(self):
result=self.term()
whileself.current_token!=Noneandself.current_token.typein (TokenType.PLUS, TokenType.MINUS):
ifself.current_token.type==TokenType.PLUS:
self.advance()
result=AddNode(result, self.term())
elifself.current_token.type==TokenType.MINUS:
self.advance()
result=SubtractNode(result, self.term())
returnresult
defterm(self):
result=self.factor()
whileself.current_token!=Noneandself.current_token.typein (TokenType.MULTIPLY, TokenType.DIVIDE):
ifself.current_token.type==TokenType.MULTIPLY:
self.advance()
result=MultiplyNode(result, self.factor())
elifself.current_token.type==TokenType.DIVIDE:
self.advance()
result=DivideNode(result, self.factor())
returnresult
deffactor(self):
token=self.current_token
iftoken.type==TokenType.LPAREN:
self.advance()
result=self.expr()
ifself.current_token.type!=TokenType.RPAREN:
self.raise_error()
self.advance()
returnresult
eliftoken.type==TokenType.NUMBER:
self.advance()
returnNumberNode(token.value)
eliftoken.type==TokenType.PLUS:
self.advance()
returnPlusNode(self.factor())
eliftoken.type==TokenType.MINUS:
self.advance()
returnMinusNode(self.factor())
self.raise_error()