-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicInterpreter.py
More file actions
355 lines (280 loc) · 12.3 KB
/
BasicInterpreter.py
File metadata and controls
355 lines (280 loc) · 12.3 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
from ExpressionInterpreter import ExpressionInterpreter
from FunctionDefinition import FunctionDefinition
from ValueType import ValueType
from re import split as re_split
from random import seed
from time import sleep
class BasicInterpreter:
_ansi_colors = { 0: 0, 1: 4, 2: 1, 3: 5, 4: 2, 5: 6, 6: 3, 7: 7 }
def __init__(self):
self._program = [] # [(line_number, code)]
self._line_index = {} # line_number -> index in program
self._pc = 0 # program counter
self._num_variables = {}
self._str_variables = {}
self._functions = {}
self._expr_interpreter = ExpressionInterpreter(self._num_variables, self._str_variables, self._functions)
self._stop = False
self._return_stack = []
self._data_buffer = []
self._data_buffer_index = 0
self._restore_line_index = {}
self._bright = False
self._ink_color = 7
self._paper_color = 0
def load(self, stream):
"""
stream: iterable de líneas (archivo, lista, etc.)
"""
self._program = []
self._line_index = {}
self._data_buffer = []
self._data_buffer_index = 0
for raw_line in stream:
raw_line = raw_line.strip()
if not raw_line:
continue
number_str, code = raw_line.split(" ", 1)
code_parts = re_split(r':(?=(?:[^"]*"[^"]*")*[^"]*$)', code)
part_index = 0
number = int(number_str)
for code_part in code_parts:
code_part = code_part.strip()
if code_part.startswith("DATA"):
self.execute_data(number, code_part)
elif code_part.startswith("REM"):
self._program.append((number, part_index, "REM"))
break
else:
self._program.append((number, part_index, code_part))
part_index += 1
# ordenar por número de línea
self._program.sort(key=lambda x: (x[0], x[1]))
# crear índice rápido para GOTO
for idx, (line_number, _, _) in enumerate(self._program):
if not line_number in self._line_index:
self._line_index[line_number] = idx
def run(self, line=0):
self._pc = 0 if line == 0 else self._line_index[line]
self._stop = False
self._return_stack = []
self._data_buffer_index = 0
try:
while not self._stop and self._pc < len(self._program):
line_number, _, code = self._program[self._pc]
self.execute_sentence(code)
self._pc += 1
if self._stop:
print("\r\nProgram stop")
else:
print("\r\nOK")
except (ValueError, RuntimeError) as re:
print(f"\r\nError: {re}\r\n\tat line {line_number} {code}")
except KeyboardInterrupt:
print("\r\nInterrupted program")
finally:
print("\x1b[0m",end="")
def execute_sentence(self, code):
code = code.strip()
code_upper = code.upper()
if code_upper.startswith("PRINT"):
self.execute_print(code)
elif code_upper.startswith("GO TO") or code_upper.startswith("GOTO"):
self.execute_goto(code)
elif code_upper.startswith("LET"):
self.execute_let(code)
elif code_upper.startswith("IF"):
self.execute_if(code)
elif code_upper.startswith("INPUT"):
self.execute_input(code)
elif code_upper.startswith("FOR"):
self.execute_for(code)
elif code_upper.startswith("NEXT"):
self.execute_next(code)
elif code_upper.startswith("REM"):
self.execute_rem(code)
elif code_upper.startswith("STOP"):
self.execute_stop(code)
elif code_upper.startswith("GO SUB") or code_upper.startswith("GOSUB"):
self.execute_gosub(code)
elif code_upper.startswith("RETURN"):
self.execute_return(code)
elif code_upper.startswith("READ"):
self.execute_read(code)
elif code_upper.startswith("RESTORE"):
self.execute_restore(code)
elif code_upper.startswith("RANDOMIZE"):
self.execute_randomize(code)
elif code_upper.startswith("DEF"):
self.execute_def(code)
elif code_upper.startswith("CLS"):
self.execute_cls(code)
elif code_upper.startswith("WAIT"):
self.execute_wait(code)
elif code_upper.startswith("INK"):
self.execute_ink(code)
elif code_upper.startswith("PAPER"):
self.execute_paper(code)
elif code_upper.startswith("BRIGHT"):
self.execute_bright(code)
elif code_upper.startswith("FLASH"):
self.execute_flash(code)
else:
raise RuntimeError(f"Unknown keyword: {code}")
def execute_print(self, code):
if code == "PRINT":
print()
return
_, rest = code.split(" ", 1)
rest = rest.strip()
args = re_split(r';(?=(?:[^"]*"[^"]*")*[^"]*$)', rest)
for arg in args:
if arg != "":
value = self._expr_interpreter.evaluate(arg)
if isinstance(value, (float, int)):
print(f"{value:g}", end="", flush=True)
else:
print(value, end="", flush=True)
if not code.endswith(";"):
print(flush=True)
def execute_goto(self, code):
# GO TO 10
parts = code.split()
target_line = int(parts[-1])
if target_line not in self._line_index:
raise RuntimeError(f"Undefined line number {target_line}")
# -1 porque el loop principal hará pc += 1
self._pc = self._line_index[target_line] - 1
def execute_let(self, code):
_, rest = code.split(" ", 1)
var, expr = rest.split("=", 1)
var = var.strip()
expr = expr.strip()
self._assignVariable(var, expr)
def _assignVariable(self, var_name, expression_value):
value = self._expr_interpreter.evaluate(expression_value)
if var_name.endswith("$"):
if not isinstance(value, str):
raise RuntimeError("Type mismatch. A string was expected.")
self._str_variables[var_name] = value
else:
if not isinstance(value, (int, float)):
raise RuntimeError("Type mismatch. A number was expected.")
self._num_variables[var_name] = value
def execute_if(self, code):
_, rest = code.split(" ", 1)
condition, then = rest.split(" THEN ", 1)
if self._expr_interpreter.evaluate(condition.strip()) != 0:
self.execute_sentence(then.strip())
def execute_input(self, code):
_, rest = code.split(" ", 1)
chunks = re_split(r'[;,](?=(?:[^"]*"[^"]*")*[^"]*$)', rest)
if len(chunks) > 2:
raise ValueError("INPUT: Too much arguments")
elif len(chunks) == 2:
prompt = self._expr_interpreter.evaluate(chunks[0].strip())
variable = chunks[1]
value = input(prompt)
else:
variable = chunks[0]
value = input("? ")
variable = variable.strip()
if variable.endswith("$"):
self._str_variables[variable] = value
else:
self._num_variables[variable] = float(value)
def execute_for(self, code):
_, rest = code.split(" ", 1)
loop_variable, rest = rest.split("=", 1)
loop_init, rest = rest.strip().split("TO", 1)
loop_variable = loop_variable.strip()
if "STEP" in rest:
loop_end, loop_step = rest.strip().split("STEP")
else:
loop_end = rest.strip()
loop_step = "1"
self._num_variables[loop_variable] = self._expr_interpreter.evaluate(loop_init.strip())
self._num_variables[f"for_end_{loop_variable}"] = self._expr_interpreter.evaluate(loop_end.strip())
self._num_variables[f"for_step_{loop_variable}"] = self._expr_interpreter.evaluate(loop_step.strip())
self._num_variables[f"for_num_codeline_{loop_variable}"] = self._pc
if self._num_variables[f"for_step_{loop_variable}"] == 0:
raise ValueError("FOR STEP can not be 0.")
def execute_next(self, code):
_, loop_variable = code.split(" ", 1)
step = self._num_variables[f"for_step_{loop_variable}"]
self._num_variables[loop_variable] += step
if (step > 0 and self._num_variables[loop_variable] <= self._num_variables[f"for_end_{loop_variable}"]) \
or ( step < 0 and self._num_variables[loop_variable] >= self._num_variables[f"for_end_{loop_variable}"]):
self._pc = self._num_variables[f"for_num_codeline_{loop_variable}"]
def execute_rem(self, code):
pass #Do nothing
def execute_stop(self, code):
self._stop = True
def execute_gosub(self, code):
self._return_stack.append(self._pc)
parts = code.split()
target_line = int(parts[-1])
self._pc = self._line_index[target_line] - 1
def execute_return(self, code):
self._pc = self._return_stack.pop()
def execute_data(self, line_number, code):
if not line_number in self._restore_line_index:
self._restore_line_index[line_number] = len(self._data_buffer)
_, row_data = code.split(" ", 1)
for data_element in row_data.split(","):
data_element = data_element.strip()
self._data_buffer.append(data_element)
def execute_read(self, code):
_, params = code.split(" ", 1)
var_names = params.split(",")
for var_name in var_names:
if self._data_buffer_index == len(self._data_buffer):
raise RuntimeError("End of data")
var_name = var_name.strip()
value = self._data_buffer[self._data_buffer_index]
self._assignVariable(var_name, value)
self._data_buffer_index += 1
def execute_restore(self, code):
items = code.split(" ")
self._data_buffer_index = self._restore_line_index[int(items[-1])] if len(items) > 1 else 0
def execute_randomize(self, code):
seed()
def execute_def(self, code):
_, function = code.split("FN")
header, body = function.strip().split("=")
name_raw, params_raw = header.strip().split("(")
name = name_raw.strip()
params = [p.strip() for p in params_raw.strip()[:-1].split(",")]
return_type = ValueType.String if name[-1] == '$' else ValueType.Integer
definition = FunctionDefinition(return_type, params, body.strip())
self._functions[name] = definition
def execute_cls(self, code):
print("\x1b[2J\x1b[H", end="")
def execute_wait(self, code):
_, param = code.split(" ", 1)
seconds = self._expr_interpreter.evaluate(param.strip())
if not isinstance(seconds, (float, int)):
raise ValueError("WAIT: Number expected as parameter")
sleep(seconds)
def _apply_ink_color(self):
print(f"\x1b[{(90 if self._bright else 30) + BasicInterpreter._ansi_colors[self._ink_color]}m", end="")
def execute_ink(self, code):
_, param = code.split(" ", 1)
self._ink_color = int(self._expr_interpreter.evaluate(param.strip()))
self._apply_ink_color()
def _apply_paper_color(self):
print(f"\x1b[{(100 if self._bright else 40) + BasicInterpreter._ansi_colors[self._paper_color]}m", end="")
def execute_paper(self, code):
_, param = code.split(" ", 1)
self._paper_color = int(self._expr_interpreter.evaluate(param.strip()))
self._apply_paper_color()
def execute_bright(self, code):
_, param = code.split(" ", 1)
value = int(self._expr_interpreter.evaluate(param.strip()))
self._bright = value == 1
self._apply_ink_color()
self._apply_paper_color()
def execute_flash(self, code):
_, param = code.split(" ", 1)
value = self._expr_interpreter.evaluate(param.strip())
print(f"\x1b[{5 if value == 1 else 25}m", end="")