-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
88 lines (71 loc) · 2.36 KB
/
parser.py
File metadata and controls
88 lines (71 loc) · 2.36 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
81
82
83
84
85
86
87
88
#!/usr/bin/env python3
import token as spi_token
class AST(object):
pass
class BinOp(AST):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.token = op
self.right = right
class UnaryOp(AST):
def __init__(self, op, expr):
self.op = op
self.token = op
self.expr = expr
class Num(AST):
def __init__(self, token):
self.token = token
self.value = token.value
class Parser(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):
if self.current_token.type == token_type:
self.current_token = self.lexer.get_next_token()
else:
self.error()
def factor(self):
'''factor : (PLUS | MINUS) factor | INTEGER | LPAREN expr RPAREN'''
token = self.current_token
if token.type == spi_token.PLUS:
self.eat(spi_token.PLUS)
node = UnaryOp(token, self.factor())
return node
elif token.type == spi_token.MINUS:
self.eat(spi_token.MINUS)
node = UnaryOp(token, self.factor())
return node
elif token.type == spi_token.INTEGER:
self.eat(spi_token.INTEGER)
return Num(token)
elif token.type == spi_token.LPAREN:
self.eat(spi_token.LPAREN)
node = self.expr()
self.eat(spi_token.RPAREN)
return node
def term(self):
'''term: factor ((MUL | DIV) factor)*'''
node = self.factor()
while self.current_token.type in (spi_token.MUL, spi_token.DIV):
token = self.current_token
self.eat(token.type)
node = BinOp(left=node, op=token, right=self.factor())
return node
def expr(self):
'''
expr : term ((PLUS | MINUS) term)*
term : factor ((MUL | DIV) factor)*
factor : INTEGER | LPAREN expr RPAREN
'''
node = self.term()
while self.current_token.type in (spi_token.PLUS, spi_token.MINUS):
token = self.current_token
self.eat(token.type)
node = BinOp(left=node, op=token, right=self.term())
return node
def parse(self):
return self.expr()