- Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathparser.py
More file actions
Latest commit
41 lines (34 loc) · 1.39 KB
/
Copy pathparser.py
File metadata and controls
41 lines (34 loc) · 1.39 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
fromrplyimportParserGenerator
fromastimportNumber, Sum, Sub, Print
classParser():
def__init__(self, module, builder, printf):
self.pg=ParserGenerator(
# A list of all token names accepted by the parser.
['NUMBER', 'PRINT', 'OPEN_PAREN', 'CLOSE_PAREN',
'SEMI_COLON', 'SUM', 'SUB']
)
self.module=module
self.builder=builder
self.printf=printf
defparse(self):
@self.pg.production('program : PRINT OPEN_PAREN expression CLOSE_PAREN SEMI_COLON')
defprogram(p):
returnPrint(self.builder, self.module, self.printf, p[2])
@self.pg.production('expression : expression SUM expression')
@self.pg.production('expression : expression SUB expression')
defexpression(p):
left=p[0]
right=p[2]
operator=p[1]
ifoperator.gettokentype() =='SUM':
returnSum(self.builder, self.module, left, right)
elifoperator.gettokentype() =='SUB':
returnSub(self.builder, self.module, left, right)
@self.pg.production('expression : NUMBER')
defnumber(p):
returnNumber(self.builder, self.module, p[0].value)
@self.pg.error
deferror_handle(token):
raiseValueError(token)
defget_parser(self):
returnself.pg.build()