-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.py
92 lines (73 loc) · 2.18 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from ASTModels import *
from models import Token
keywords = [
('if',''),
('else',''),
('int',''),
('return',''),
]
class ParserError(Exception):
""" Lexer error exception.
pos:
Position in the input line where the error occurred.
"""
def __init__(self, token):
Exception.__init__(self,"Unrecognized Token {}".format(token))
def parser(tokens: [Token]) -> Node:
ast = BaseNode([])
while tokens:
tokens, ast.statements = _parse(tokens,ast.statements)
return ast
def _parse(tokens: [Token], nodes: [Node] = []) -> ([Token],[Node]):
if not tokens:
print("EOF")
return ([],nodes)
elif tokens[0].type == "EOL":
return (tokens[1:],nodes)
elif tokens[0].type == "RPAR":
return (tokens[1:],nodes)
elif tokens[0].type == "LPAR":
return _parse(tokens[1:],nodes)
elif tokens[0].type == "NUMBER":
return (tokens[1:],nodes + [Value("INT",tokens[0].val)])
elif tokens[0].type == "BINOP":
rem_tokens, right = _parse(tokens[1:])
if not nodes:
raise ParserError(nodes)
nodes[-1] = BinOp(
left = nodes[-1],
right = right[0],
operation = tokens[0].val
)
return (rem_tokens,nodes)
raise ParserError(tokens[0])
BaseNode(statements=[
BinOp(
left=BinOp(
left=Value(type='INT', value='3'),
right=Value(type='INT', value='3'),
operation='+'
),
right=BinOp(
left=Value(type='INT', value='3'),
right=Value(type='INT', value='3'),
operation='+'),
operation='/')])
BaseNode(statements=[
BinOp(
left=BinOp(
left=Value(type='INT', value='3'),
right=[Value(type='INT', value='4')],
operation='+'),
right=[Value(type='INT', value='3')],
operation='/')])
BaseNode(statements=[
BinOp(
left=BinOp(
left=Value(type='INT', value='3'),
right=Value(type='INT', value='4'),
operation='+'),
right=Value(type='INT', value='3'),
operation='/')
]
)