-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonolith_interpreter.py
More file actions
335 lines (275 loc) · 9.4 KB
/
monolith_interpreter.py
File metadata and controls
335 lines (275 loc) · 9.4 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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import re
import sys
# Token types
TT_KEYWORD = "KEYWORD"
TT_STRING = "STRING"
TT_IDENTIFIER = "IDENTIFIER"
TT_OPERATOR = "OPERATOR"
TT_NUMBER = "NUMBER"
# Additional token types
TT_ASSIGN = "ASSIGN"
TT_EQUALS = "EQUALS"
# Keywords
keywords = {
"tell",
"ask",
"gather",
"as",
"is",
"with",
"end",
"if",
"else",
"while",
"try",
"catch",
"String",
"Number",
"Boolean",
"Array",
"Dictionary",
"Class",
"Function",
"Bluetell",
"Type",
"init",
"extends",
"of",
"or",
"and",
}
# Lexer Operators
operators = {"+", "-", "*", "/", "==", "!=", "<", ">", "<=", ">=", "&&", "||", "="}
# Add a comma and parenthesis to your operators.
operators.update({",", "(", ")"})
# Lexer: tokenize the input code
def lexer(code):
tokens = []
while code:
match = None
# Skip whitespaces
if match := re.match(r"\s+", code):
pass
# Match keywords and identifiers
elif match := re.match(r"[a-zA-Z_]\w*", code):
identifier = match.group(0)
if identifier in keywords:
tokens.append((TT_KEYWORD, identifier))
else:
tokens.append((TT_IDENTIFIER, identifier))
# Match operators
elif match := re.match(r"==|!=|<=|>=|&&|\|\||[+\-*/<>]", code):
tokens.append((TT_OPERATOR, match.group(0)))
# Match strings
elif match := re.match(r'"[^"]*"', code):
tokens.append((TT_STRING, match.group(0)[1:-1])) # Remove quotation marks
# Match integers
elif match := re.match(r"\d+", code):
tokens.append((TT_NUMBER, int(match.group(0))))
# Match assignment
elif match := re.match(r"=", code):
tokens.append((TT_ASSIGN, match.group(0)))
else:
raise SyntaxError(f"Unknown sequence: {code}")
code = code[match.end() :]
return tokens
# AST Node types
class ASTNode:
pass
class PrintNode(ASTNode):
def __init__(self, value):
self.value = value
def __repr__(self) -> str:
return f"PrintNode({self.value})"
class StringNode(ASTNode):
def __init__(self, value):
self.value = value
def __repr__(self) -> str:
return f"StringNode({self.value})"
class VarAssignNode(ASTNode):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self) -> str:
return f"VarAssignNode({self.name}, {self.value})"
class VarAccessNode(ASTNode):
def __init__(self, name):
self.name = name
def __repr__(self) -> str:
return f"VarAccessNode({self.name})"
class VarDeclNode(ASTNode):
def __init__(self, name, var_type):
self.name = name
self.var_type = var_type
def __repr__(self) -> str:
return f"VarDeclNode({self.name}, {self.var_type})"
class InputNode(ASTNode):
def __init__(self, prompt):
self.prompt = prompt
def __repr__(self) -> str:
return f"InputNode({self.prompt})"
# Parser: create an AST from tokens
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = -1
self.current_token = None
self.advance()
def advance(self):
self.pos += 1
if self.pos < len(self.tokens):
self.current_token = self.tokens[self.pos]
else:
self.current_token = None
def parse(self):
ast = self.statements()
if self.current_token is not None:
raise Exception("Unexpected token: " + self.current_token[1])
return ast
def peek(self):
# Look ahead at the next token without consuming the current one
next_pos = self.pos + 1
if next_pos < len(self.tokens):
return self.tokens[next_pos]
return None
def statements(self):
statements = []
while self.current_token is not None and self.current_token[1] != "end":
if self.current_token[1] == "tell":
statements.append(self.tell_statement())
elif self.current_token[1] == "ask":
statements.append(self.ask_statement())
elif self.current_token[0] == TT_IDENTIFIER:
# Look ahead for 'as'
if self.peek() == ("KEYWORD", "as"):
statements.append(self.var_declaration())
else:
# Handle variable assignment or other expressions that start with an identifier
pass
self.advance()
return statements
def tell_statement(self):
self.advance()
if self.current_token[0] == TT_STRING:
return PrintNode(StringNode(self.current_token[1]))
elif self.current_token[0] == TT_IDENTIFIER:
var_name = self.current_token[1]
return PrintNode(VarAccessNode(var_name)) # Create a variable access node
else:
raise Exception('Expected string or variable name after "tell"')
def ask_statement(self):
self.advance()
# Expecting a string literal for the input prompt
if self.current_token[0] != TT_STRING:
raise Exception("Expected string literal for the input prompt")
prompt = self.current_token[1]
# Advance past the string
# self.advance()
var_name = prompt
# Return a VarAssignNode with the variable name and an InputNode
return VarAssignNode(var_name, InputNode(prompt))
def var_declaration(self):
# Assume current token is the variable identifier
var_name = self.current_token[1]
self.advance() # Consume identifier
if self.current_token is not None and self.current_token[1] == "as":
self.advance() # Consume 'as'
if self.current_token[0] == TT_KEYWORD and self.current_token[1] in {
"String",
"Number",
"Boolean",
"Array",
"Dictionary",
}:
var_type = self.current_token[1]
self.advance() # Consume type
if (
self.current_token is not None
and self.current_token[0] == TT_ASSIGN
):
self.advance() # Consume '='
# Now expecting a value for initialization
if self.current_token[0] in (TT_STRING, TT_NUMBER):
value = self.current_token[1]
return VarAssignNode(
var_name, value
) # Use a VarAssignNode to assign the initial value
else:
raise Exception(
"Expected a value for variable initialization after '='"
)
else:
# If there's no '=', proceed with declaration without initialization
return VarDeclNode(var_name, var_type)
else:
raise Exception("Expected type keyword after 'as'")
else:
raise Exception("Expected 'as' after variable name")
# Evaluator: execute the AST
class Evaluator:
def __init__(self):
self.variables = {}
def visit(self, node):
method_name = "visit_" + type(node).__name__
method = getattr(self, method_name)
return method(node)
def visit_PrintNode(self, node):
value = self.visit(node.value)
print(value)
return value
def visit_VarAccessNode(self, node):
var_name = node.name
if var_name in self.variables:
return self.variables[var_name]
else:
raise Exception(f"Undefined variable '{var_name}'")
def visit_StringNode(self, node):
return node.value
def visit_InputNode(self, node):
return input(node.prompt)
def visit_VarAssignNode(self, node):
if isinstance(node.value, ASTNode):
value = self.visit(node.value)
else:
value = node.value # Directly assign the value
self.variables[node.name] = value
return value
def visit_VarDeclNode(self, node):
# Here, you would set the initial value of the variable based on the type
# For simplicity, we will initialize all variables to None or an empty equivalent
if node.var_type == "String":
initial_value = ""
elif node.var_type == "Number":
initial_value = 0
# Add cases for other types
else:
initial_value = None
self.variables[node.name] = initial_value
return initial_value
# Main function to execute the interpreter
def main():
# Check if a file name is provided as a command-line argument
if len(sys.argv) != 2:
print("Usage: python interpreter.py <filename>")
sys.exit(1)
filename = sys.argv[1]
# Read the content of the file
try:
with open(filename, "r") as file:
code = file.read()
except FileNotFoundError:
print(f"Error: File {filename} not found.")
sys.exit(1)
except IOError as e:
print(f"Error reading file {filename}: {e}")
sys.exit(1)
# Lexing, parsing, and evaluation
tokens = lexer(code)
parser = Parser(tokens)
ast = parser.parse()
evaluator = Evaluator()
for node in ast:
evaluator.visit(node)
# Execute main function
if __name__ == "__main__":
main()