-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.py
executable file
·77 lines (58 loc) · 2.12 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
from rply import ParserGenerator
from ast import *
from lexer import operators
class Parser():
def __init__(self):
# The list of tokens from the lexer file
self.pg = ParserGenerator(
[token for token in operators.keys()],
precedence=[
("left", ["ADD", "SUBTRACT"]),
("left", ["MULTIPLY", "DIVIDE"]),
]
)
def parse(self):
@self.pg.production('program : expression')
def program(p):
return Program(p[0])
@self.pg.production('expression : expression expression')
def expression(p):
return Expression(p)
@self.pg.production('expression : PRINT expression')
def print_(p):
return Print(p[1])
# Binary operations
@self.pg.production('expression : ADD expression WITH expression')
def add(p):
return Add(p[1], p[3])
@self.pg.production('expression : SUBTRACT expression FROM expression')
def subtract(p):
return Subtract(p[1], p[3])
@self.pg.production('expression : MULTIPLY expression BY expression')
def multiply(p):
return Multiply(p[1], p[3])
@self.pg.production('expression : DIVIDE expression BY expression')
def divide(p):
return Divide(p[1], p[3])
# Handle assinging
@self.pg.production('expression : ASSIGN variable_name TO expression')
def assign(p):
return Assign(p[1], p[3])
# defining expressions
@self.pg.production('variable_name : IDENTIFIER')
def identifier(p):
return Identifier(p[0].value)
@self.pg.production('expression : NUMBER')
def number(p):
return Number(p[0].value)
@self.pg.production('expression : STRING')
def string(p):
return String(p[0].value)
@self.pg.production('expression : RPN')
def rpn(p):
return Rpn(p[0].value)
@self.pg.error
def error_handle(token):
raise ValueError(token)
def get_parser(self):
return self.pg.build()