-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
199 lines (158 loc) · 5.1 KB
/
parser.py
File metadata and controls
199 lines (158 loc) · 5.1 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""
AST Nodes:
program = Program(function_definition)
function_definition = Function(identifier name, statement body)
statement = Return(exp)
exp = Constant(int) | Unary(unary_operator, exp)
unary_operator = Complement | Negate
"""
class ASTNode:
pass
class Exp(ASTNode):
pass
class UnaryOperator:
pass
class Complement(UnaryOperator):
pass
class Negate(UnaryOperator):
pass
class Constant(Exp):
def __init__(self, value: int):
self.value = value
class Unary(Exp):
def __init__(self, unary_operator: UnaryOperator, exp: Exp):
self.unary_operator = unary_operator
self.exp = exp
class Statement(ASTNode):
pass
class ReturnStatement(Statement):
def __init__(self, return_value: Exp):
self.return_value = return_value
class Identifier(ASTNode):
def __init__(self, name_str: str):
self.name_str = name_str
class FunctionDefinition(ASTNode):
def __init__(self, name: Identifier, body: Statement):
self.name = name
self.body = body
class Program(ASTNode):
def __init__(self, function_definition: FunctionDefinition):
self.function_definition = function_definition
"""
Formal Grammar:
<program> ::= <function>
<function> ::= "int" <identifier> "(" "void" ")" "{" <statement> "}"
<statement> ::= "return" <exp> ";"
<exp> ::= <int> | <unop> <exp> | "(" <exp> ")"
<unop> ::= "-" | "~"
<identifier> ::= ? An identifier token ?
<int> ::= ? A constant token ?
"""
# Recursive Descent Parsing
from lexer import *
def take_token(tokens):
print(f"took {tokens[0].token_type}, {tokens[0].string}")
try:
x = tokens[0]
del tokens[0]
return x
except IndexError as e:
raise Exception("Invalid end of program!") from e
def expect(expected: TokenType, tokens):
print(f"expected {expected}")
actual = take_token(tokens).token_type
if actual != expected:
raise Exception(f"Expected {expected} but found {actual}!")
def parse_identifier(tokens):
# check if identifier
try:
if tokens[0].token_type != TokenType.identifier:
raise Exception(f"Invalid identifier: {tokens[0].string}!")
except IndexError as e:
raise Exception("Invalid end of program!")
identifier = take_token(tokens).string
return Identifier(identifier)
def parse_int(tokens):
# check if int
try:
if tokens[0].token_type != TokenType.constant:
raise Exception(f"Invalid constant: {tokens[0].string}!")
except IndexError as e:
raise Exception("Invalid end of program!")
int = take_token(tokens).string
return Constant(int)
def parse_unary(tokens):
match tokens[0].token_type:
case TokenType.hyphen:
take_token(tokens)
return Unary(Negate(), parse_exp(tokens))
case TokenType.tilde:
take_token(tokens)
return Unary(Complement(), parse_exp(tokens))
def parse_parenthesized_exp(tokens):
take_token(tokens)
inner_exp = parse_exp(tokens)
expect(TokenType.close_parenthesis, tokens)
return inner_exp
def parse_exp(tokens):
val = None
match tokens[0].token_type:
case TokenType.constant:
val = parse_int(tokens)
case TokenType.tilde | TokenType.hyphen:
val = parse_unary(tokens)
case TokenType.open_parenthesis:
val = parse_parenthesized_exp(tokens)
case _:
raise Exception('No expression found!')
return val
def parse_statement(tokens):
expect(TokenType.return_keyword, tokens)
return_val = parse_exp(tokens)
expect(TokenType.semicolon, tokens)
return ReturnStatement(return_value=return_val)
def parse_function(tokens):
expect(TokenType.int_keyword, tokens)
identifier = parse_identifier(tokens)
expect(TokenType.open_parenthesis, tokens)
expect(TokenType.void_keyword, tokens)
expect(TokenType.close_parenthesis, tokens)
expect(TokenType.open_brace, tokens)
statement = parse_statement(tokens)
expect(TokenType.close_brace, tokens)
return FunctionDefinition(identifier, statement)
def parse_program(tokens):
function = parse_function(tokens)
if len(tokens) != 0:
raise Exception("Invalid end of program!")
return Program(function)
def print_program(program: Program, indent: int = 0):
def print_indent(text):
print(" " * indent + text)
print_indent("Program:")
indent += 2
function_def = program.function_definition
print_indent(f"FunctionDefinition: {function_def.name.name_str}")
indent += 2
body = function_def.body
print_indent("ReturnStatement:")
indent += 2
return_value = body.return_value
if isinstance(return_value, Constant):
print_indent(f"Constant: {return_value.value}")
elif isinstance(return_value, Identifier):
print_indent(f"Identifier: {return_value.name_str}")
else:
print_indent("Unknown return value.")
indent -= 2
indent -= 4
# x = """
# int main(void) {
# return ~-2147483647;
# }
# """
# t = tokenize(x)
# for i in t:
# print(f"'{i.string}' {i.token_type}")
# p = parse_program(t)
# print_program(p)