-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser_tn.py
67 lines (57 loc) · 1.83 KB
/
parser_tn.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
from rply import ParserGenerator
from ast_tn import Divide, Number, Sum, Sub, Print
class Parser():
def __init__(self):
self.pg = ParserGenerator(
# A list of all token names accepted by the parser.
['print',
'if',
'else if',
'else',
'for',
'while',
'int',
'string',
'do_while',
'LPAREN',
'RPAREN',
'COMMA',
'SEMICOLON',
'PLUS',
'MINUS',
'SLASH',
'NUMBER'
]
)
def get_parser(self):
return self.pg.build()
def parse(self):
def program(p):
return Print(p[2])
def expression(p):
left = p[0]
right = p[2]
operator = p[1]
if operator.gettokentype() == 'PLUS':
return Sum(left, right)
elif operator.gettokentype() == 'MINUS':
return Sub(left, right)
elif operator.gettokentype() == 'SLASH':
return Divide(left, right)
def number(p):
return Number(p[0].value)
@self.pg.production('program : print LPAREN expression RPAREN SEMICOLON')
def program_production(p):
return program(p)
@self.pg.production('expression : expression PLUS NUMBER')
def expression_production_sum(p):
return expression(p)
@self.pg.production('expression : expression MINUS NUMBER')
def expression_production_sub(p):
return expression(p)
@self.pg.production('expression : NUMBER')
def number_production(p):
return number(p)
@self.pg.error
def error_handler(token):
raise ValueError(token)