-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluator.py
604 lines (459 loc) · 20.8 KB
/
evaluator.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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
from enum import Enum
from isa import Opcode
from translation.evaluation_utils import *
class LispVarType(Enum):
STRING = 3
BOOLEAN = 2
INTEGER = 1
UNDEF = 0
addr = 0
instruction_counter = -1
read_address = 0
read_counter = 0
max_input_size = 0
lisp_vars_addresses = {}
strings_addresses = {}
def get_instruction(name, arg):
global instruction_counter
instruction_counter += 1
return {"opcode": name, "arg": arg, "term": instruction_counter}
def is_lisp_string(lisp_arg):
return isinstance(lisp_arg, str) and lisp_arg[0] == '\"' and lisp_arg[-1] == '\"'
def is_lisp_var(lisp_arg):
return isinstance(lisp_arg, str) and lisp_arg[0] != '\"' and lisp_arg[-1] != '\"'
def lisp_loop(expression: SymbolicExpression):
global addr
global instruction_counter
machine_code = []
loop_start_term = instruction_counter + 1
for exp in expression.args:
machine_code += convert_expression_to_instructions(exp)
machine_code.append(get_instruction(Opcode.JMP, loop_start_term))
loop_end_term = instruction_counter + 1
for code in machine_code:
if code["arg"] == 'go to loop end':
code["arg"] = loop_end_term
return machine_code
def lisp_return(expression: SymbolicExpression):
global addr
machine_code = []
if len(expression.args) > 0:
machine_code += store_args([expression.args[0]])
else:
machine_code += store_args([0])
machine_code.append(get_instruction(Opcode.JMP, 'go to loop end'))
return machine_code
def lisp_if(expression: SymbolicExpression):
assert len(expression.args) <= 3, "Incorrect lisp 'if' syntax"
global addr
machine_code = []
if isinstance(expression.args[0], SymbolicExpression):
machine_code += convert_expression_to_instructions(expression.args[0])
else:
machine_code += push_lisp_val(expression.args[0])
# if
machine_code.append(get_instruction(Opcode.LOAD, addr - 2))
machine_code.append(get_instruction(Opcode.ADD_CONST, - LispVarType.BOOLEAN.value))
machine_code.append(get_instruction(Opcode.JNE, "go to true")) # if not boolean jump to true
machine_code.append(get_instruction(Opcode.LOAD, addr - 1))
machine_code.append(get_instruction(Opcode.JE, "go to false")) # if false go to false
addr -= 2
true_term = machine_code[-1]["term"] + 1
# true
if isinstance(expression.args[1], SymbolicExpression):
machine_code += convert_expression_to_instructions(expression.args[1])
else:
machine_code += push_lisp_val(expression.args[1])
# add jump addresses
machine_code.append(get_instruction(Opcode.JMP, "go to end"))
false_term = machine_code[-1]["term"] + 1
for code in machine_code:
if code["arg"] == "go to true":
code["arg"] = true_term
elif code["arg"] == "go to false":
code["arg"] = false_term
# false
if len(expression.args) == 3:
addr -= 2
if isinstance(expression.args[2], SymbolicExpression):
machine_code += convert_expression_to_instructions(expression.args[2])
else:
machine_code += push_lisp_val(expression.args[2])
# add jump address
end_term = machine_code[-1]["term"] + 1
for code in machine_code:
if code["arg"] == "go to end":
code["arg"] = end_term
return machine_code
def lisp_mod(expression: SymbolicExpression):
global addr
machine_code = []
if isinstance(expression.args[1], int):
machine_code += store_args([expression.args[0]])
machine_code.append(get_instruction(Opcode.LOAD, addr - 1))
loop_term = machine_code[-1]['term'] + 1
machine_code.append(get_instruction(Opcode.STORE, addr))
machine_code.append(get_instruction(Opcode.ADD_CONST, - expression.args[1]))
machine_code.append(get_instruction(Opcode.JL, loop_term + 4))
machine_code.append(get_instruction(Opcode.JMP, loop_term))
machine_code.append(get_instruction(Opcode.LOAD, addr))
machine_code.append(get_instruction(Opcode.STORE, addr - 1))
return machine_code
# сохраним два аргумента в temp
machine_code += store_args(expression.args)
machine_code.append(get_instruction(Opcode.LOAD, addr - 3))
machine_code.append(get_instruction(Opcode.STORE, addr))
# loop
loop_start = machine_code[-1]["term"] + 1
machine_code.append(get_instruction(Opcode.SUB, addr - 1))
machine_code.append(get_instruction(Opcode.JL, loop_start + 4)) # go to save result
machine_code.append(get_instruction(Opcode.STORE, addr))
machine_code.append(get_instruction(Opcode.JMP, loop_start))
# save result
machine_code.append(get_instruction(Opcode.LOAD_CONST, LispVarType.INTEGER.value))
machine_code.append(get_instruction(Opcode.STORE, addr - 4))
machine_code.append(get_instruction(Opcode.LOAD, addr))
machine_code.append(get_instruction(Opcode.STORE, addr - 3))
addr -= 2
return machine_code
def lisp_greater_than(expression: SymbolicExpression, is_greater: bool):
global addr
machine_code = []
calculations_term = 0
if not is_greater: # is lower
expression.args[0], expression.args[1] = expression.args[1], expression.args[0]
if isinstance(expression.args[0], int) or isinstance(expression.args[1], int):
int_index = 0 if isinstance(expression.args[0], int) else 1
machine_code += store_args([expression.args[1 - int_index]])
calculations_term = machine_code[-1]["term"] + 1
# calculations
if int_index == 0:
machine_code.append(get_instruction(Opcode.LOAD_CONST, expression.args[0]))
machine_code.append(get_instruction(Opcode.SUB, addr - 1))
else:
machine_code.append(get_instruction(Opcode.LOAD, addr - 1))
machine_code.append(get_instruction(Opcode.ADD_CONST, - expression.args[1]))
addr += 2
else:
# сохраним два аргумента в temp
machine_code += store_args(expression.args)
# calculations
calculations_term = machine_code[-1]["term"] + 1
machine_code.append(get_instruction(Opcode.LOAD, addr - 3))
machine_code.append(get_instruction(Opcode.SUB, addr - 1))
machine_code.append(get_instruction(Opcode.JG, calculations_term + 5))
# false
machine_code.append(get_instruction(Opcode.LOAD_CONST, 0))
machine_code.append(get_instruction(Opcode.JMP, calculations_term + 6))
# true
machine_code.append(get_instruction(Opcode.LOAD_CONST, 1))
machine_code.append(get_instruction(Opcode.STORE, addr - 3))
machine_code.append(get_instruction(Opcode.LOAD_CONST, LispVarType.BOOLEAN.value))
machine_code.append(get_instruction(Opcode.STORE, addr - 4))
addr -= 2
return machine_code
def lisp_add(expression: SymbolicExpression, is_plus: bool):
global addr
global lisp_vars_addresses
machine_code = []
# считаем результат сразу, если оба аргумента числа
if isinstance(expression.args[0], int) and isinstance(expression.args[1], int):
machine_code += store_const(LispVarType.INTEGER.value)
if is_plus:
machine_code += store_const(expression.args[0] + expression.args[1])
else:
machine_code += store_const(expression.args[0] - expression.args[1])
return machine_code
if isinstance(expression.args[0], int) or isinstance(expression.args[1], int):
int_index = 0 if isinstance(expression.args[0], int) else 1
machine_code += store_args([expression.args[1 - int_index]])
machine_code.append(get_instruction(Opcode.LOAD, addr - 1))
machine_code.append(get_instruction(Opcode.ADD_CONST, expression.args[int_index] * (1 if is_plus else -1)))
addr += 2
else:
# сохраним два аргумента в temp
machine_code += store_args(expression.args)
# сам add
machine_code.append(get_instruction(Opcode.LOAD, addr - 3))
machine_code.append(get_instruction(Opcode.ADD if is_plus else Opcode.SUB, addr - 1))
machine_code.append(get_instruction(Opcode.STORE, addr - 3))
addr -= 2
return machine_code
def lisp_equal(expression: SymbolicExpression):
global addr
global lisp_vars_addresses
machine_code = []
# считаем результат сразу, если оба аргумента числа
if isinstance(expression.args[0], int) and isinstance(expression.args[1], int):
machine_code += store_const(LispVarType.BOOLEAN.value)
machine_code += store_const(1 if expression.args[0] == expression.args[1] else 0)
return machine_code
if isinstance(expression.args[0], int) or isinstance(expression.args[1], int):
int_index = 0 if isinstance(expression.args[0], int) else 1
machine_code += store_args([expression.args[1 - int_index]])
machine_code.append(get_instruction(Opcode.LOAD, addr - 1))
machine_code.append(get_instruction(Opcode.ADD_CONST, - expression.args[int_index]))
addr += 2
else:
# сохраним два аргумента в temp
machine_code += store_args(expression.args)
machine_code.append(get_instruction(Opcode.LOAD, addr - 3))
machine_code.append(get_instruction(Opcode.SUB, addr - 1))
sub_instruction_term = machine_code[-1]["term"]
machine_code.append(get_instruction(Opcode.JE, sub_instruction_term + 4)) # объекты равны, загружаем единицу
machine_code.append(get_instruction(Opcode.LOAD_CONST, 0))
machine_code.append(get_instruction(Opcode.JMP, sub_instruction_term + 5))
machine_code.append(get_instruction(Opcode.LOAD_CONST, 1))
machine_code.append(get_instruction(Opcode.STORE, addr - 3))
machine_code.append(get_instruction(Opcode.LOAD_CONST, LispVarType.BOOLEAN.value))
machine_code.append(get_instruction(Opcode.STORE, addr - 4))
addr -= 2
return machine_code
def lisp_setq(expression: SymbolicExpression):
global addr
global lisp_vars_addresses
machine_code = []
var_name = expression.args[0]
var_addr = lisp_vars_addresses[var_name]
assert is_lisp_var(var_name), f'{var_name} is an incorrect lisp var name'
if isinstance(expression.args[1], int):
machine_code.append(get_instruction(Opcode.LOAD_CONST, expression.args[1]))
machine_code.append(get_instruction(Opcode.STORE, var_addr + 1))
machine_code.append(get_instruction(Opcode.STORE, addr + 1))
machine_code.append(get_instruction(Opcode.LOAD_CONST, LispVarType.INTEGER.value))
machine_code.append(get_instruction(Opcode.STORE, var_addr))
machine_code.append(get_instruction(Opcode.STORE, addr))
addr += 2
return machine_code
if isinstance(expression.args[1], SymbolicExpression):
machine_code += convert_expression_to_instructions(expression.args[1])
else:
machine_code += push_lisp_val(expression.args[1])
addr -= 2
machine_code.append(get_instruction(Opcode.LOAD, addr))
machine_code.append(get_instruction(Opcode.STORE, var_addr))
machine_code.append(get_instruction(Opcode.LOAD, addr + 1))
machine_code.append(get_instruction(Opcode.STORE, var_addr + 1))
addr += 2
return machine_code
def lisp_print(expression: SymbolicExpression):
global addr
global instruction_counter
machine_code = []
if isinstance(expression.args[0], SymbolicExpression):
machine_code += convert_expression_to_instructions(expression.args[0])
else:
machine_code += push_lisp_val(expression.args[0])
lisp_var_addr = addr
lisp_var_type_addr = addr - 2
# копирование значения переменной
machine_code.append(get_instruction(Opcode.LOAD, lisp_var_addr - 1))
machine_code.append(get_instruction(Opcode.STORE, lisp_var_addr))
machine_code.append(get_instruction(Opcode.LOAD, lisp_var_type_addr))
# определение типа переменной
machine_code.append(get_instruction(Opcode.JE, 'false')) # jump на print false
machine_code.append(get_instruction(Opcode.ADD_CONST, -1))
machine_code.append(get_instruction(Opcode.JE, 'integer')) # jump на print integer
machine_code.append(get_instruction(Opcode.ADD_CONST, -1))
machine_code.append(get_instruction(Opcode.JE, 'boolean')) # jump на print boolean
# print string
string_term = machine_code[-1]["term"] + 1
machine_code.append(get_instruction(Opcode.LOAD_INDIRECT, lisp_var_addr))
machine_code.append(get_instruction(Opcode.JE, 'end')) # jump на end
machine_code.append(get_instruction(Opcode.PRINT, ""))
machine_code.append(get_instruction(Opcode.LOAD, lisp_var_addr))
machine_code.append(get_instruction(Opcode.ADD_CONST, 1))
machine_code.append(get_instruction(Opcode.STORE, lisp_var_addr))
machine_code.append(get_instruction(Opcode.JMP, string_term)) # jump в print string
# print boolean
boolean_term = machine_code[-1]['term'] + 1
machine_code.append(get_instruction(Opcode.LOAD, lisp_var_addr))
machine_code.append(get_instruction(Opcode.JNE, 'true')) # jump на print true
# print false
false_term = machine_code[-1]['term'] + 1
machine_code.append(get_instruction(Opcode.LOAD_CONST, ord('N')))
machine_code.append(get_instruction(Opcode.PRINT, ""))
machine_code.append(get_instruction(Opcode.LOAD_CONST, ord('I')))
machine_code.append(get_instruction(Opcode.PRINT, ""))
machine_code.append(get_instruction(Opcode.LOAD_CONST, ord('L')))
machine_code.append(get_instruction(Opcode.PRINT, ""))
machine_code.append(get_instruction(Opcode.JMP, 'end')) # jump в конец принта
# print true
true_term = machine_code[-1]['term'] + 1
machine_code.append(get_instruction(Opcode.LOAD_CONST, ord('t')))
machine_code.append(get_instruction(Opcode.PRINT, ""))
machine_code.append(get_instruction(Opcode.JMP, 'end')) # jump в конец принта
# print integer
integer_term = machine_code[-1]['term'] + 1
machine_code.append(get_instruction(Opcode.LOAD, lisp_var_addr))
machine_code.append(get_instruction(Opcode.PRINT_INT, ""))
end_term = machine_code[-1]['term'] + 1
for inst in machine_code:
if inst['arg'] == 'boolean':
inst['arg'] = boolean_term
elif inst['arg'] == 'false':
inst['arg'] = false_term
elif inst['arg'] == 'true':
inst['arg'] = true_term
elif inst['arg'] == 'end':
inst['arg'] = end_term
elif inst['arg'] == 'integer':
inst['arg'] = integer_term
machine_code.append(get_instruction(Opcode.LOAD_CONST, ord('\n')))
machine_code.append(get_instruction(Opcode.PRINT, ""))
return machine_code
def lisp_read():
global addr
global read_address
global read_counter
global max_input_size
machine_code = []
input_addr = read_address + read_counter * max_input_size
machine_code += store_const(input_addr)
addr -= 1
machine_code.append(get_instruction(Opcode.READ, "")) # прочитали символ в акк
read_command_address = machine_code[-1]["term"]
machine_code.append(get_instruction(Opcode.STORE_INDIRECT, addr)) # сохранили символ
machine_code.append(get_instruction(Opcode.JE, read_command_address + 7)) # перескок на сохранение переменной
machine_code.append(get_instruction(Opcode.LOAD, addr))
machine_code.append(get_instruction(Opcode.ADD_CONST, 1)) # инкремент адреса ячейки для следующего символа
machine_code.append(get_instruction(Opcode.STORE, addr))
machine_code.append(get_instruction(Opcode.JMP, read_command_address))
machine_code += store_const(LispVarType.STRING.value) # сохранение переменной
machine_code += store_const(input_addr)
read_counter += 1
return machine_code
def push_lisp_val(lisp_val):
global strings_addresses
global lisp_vars_addresses
global addr
machine_code = []
if is_lisp_string(lisp_val):
machine_code += store_const(LispVarType.STRING.value)
machine_code += store_const(strings_addresses[convert_lisp_string_to_string(lisp_val)])
elif is_lisp_var(lisp_val):
var_addr = lisp_vars_addresses[lisp_val]
machine_code.append(get_instruction(Opcode.LOAD, var_addr))
machine_code.append(get_instruction(Opcode.STORE, addr))
addr += 1
machine_code.append(get_instruction(Opcode.LOAD, var_addr + 1))
machine_code.append(get_instruction(Opcode.STORE, addr))
addr += 1
elif isinstance(lisp_val, bool):
machine_code += store_const(LispVarType.BOOLEAN.value)
machine_code += store_const(1 if lisp_val else 0)
elif isinstance(lisp_val, int):
machine_code += store_const(LispVarType.INTEGER.value)
machine_code += store_const(lisp_val)
else:
# undefined
machine_code += store_const(LispVarType.UNDEF.value)
machine_code += store_const(0)
return machine_code
def convert_expression_to_instructions(expression: SymbolicExpression):
global addr
machine_code = []
if expression.operator == 'read':
machine_code += lisp_read()
elif expression.operator == 'print':
machine_code += lisp_print(expression)
elif expression.operator == 'setq':
machine_code += lisp_setq(expression)
elif expression.operator == '=':
machine_code += lisp_equal(expression)
elif expression.operator == '+':
machine_code += lisp_add(expression, True)
elif expression.operator == '-':
machine_code += lisp_add(expression, False)
elif expression.operator == '>':
machine_code += lisp_greater_than(expression, True)
elif expression.operator == '<':
machine_code += lisp_greater_than(expression, False)
elif expression.operator == 'mod':
machine_code += lisp_mod(expression)
elif expression.operator == 'if':
machine_code += lisp_if(expression)
elif expression.operator == 'loop':
machine_code += lisp_loop(expression)
elif expression.operator == 'return':
machine_code += lisp_return(expression)
else:
raise RuntimeError(f'"{expression.operator}" operator is not supported by evaluator')
return machine_code
def store_const(const_val: int):
global addr
machine_code = [
get_instruction(Opcode.LOAD_CONST, const_val),
get_instruction(Opcode.STORE, addr)
]
addr += 1
return machine_code
def store_args(args):
machine_code = []
assert len(args) <= 2, "Lisp operator has too many arguments"
for i in range(len(args)):
if isinstance(args[i], SymbolicExpression):
machine_code += convert_expression_to_instructions(args[i])
else:
machine_code += push_lisp_val(args[i])
return machine_code
def load_const_strings(const_strings):
global addr
global strings_addresses
machine_code = []
for const_string in const_strings:
strings_addresses[const_string] = addr
for i in range(len(const_string)):
machine_code += store_const(
ord(const_string[i])
)
machine_code += store_const(0)
return machine_code
def add_buffers(read_amount):
global max_input_size
global addr
global read_address
max_input_size = 100
read_address = addr
addr += max_input_size * read_amount
def add_variables(lisp_variables):
global lisp_vars_addresses
global addr
machine_code = []
for lisp_var in lisp_variables:
lisp_vars_addresses[lisp_var] = addr
addr += 2
return machine_code
def iterate_over_expressions(s_expressions):
global addr
temp_region_addr = addr
machine_code = []
for exp in s_expressions:
machine_code += convert_expression_to_instructions(exp)
addr = temp_region_addr
return machine_code
def evaluate(s_expressions):
global read_counter
global max_input_size
global read_address
global lisp_vars_addresses
global strings_addresses
global addr
global instruction_counter
addr = 0
instruction_counter = -1
read_address = 0
read_counter = 0
max_input_size = 0
lisp_vars_addresses = {}
strings_addresses = {}
machine_code = []
const_strings = get_all_string_values_from_s_expressions(s_expressions)
read_amount = count_read_operations_in_many_expressions(s_expressions)
lisp_variables = get_variables(s_expressions)
machine_code += load_const_strings(const_strings)
add_buffers(read_amount)
machine_code += add_variables(lisp_variables)
machine_code += iterate_over_expressions(s_expressions)
machine_code.append(get_instruction(Opcode.HLT, ''))
return machine_code