-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplementations.py
615 lines (565 loc) · 18.2 KB
/
implementations.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
605
606
607
608
609
610
611
612
613
614
# noqa e302
"""Module with the assembly implementation for each operator."""
import sys
import global_state
from definitions import Token, Operator, PROCEDURE_PREFIX
from parsing_utils import string_to_db
from definitions import PROCEDURE_PREFIX
def _ADD(self):
return [
' pop rax',
' pop rbx',
' add rax, rbx',
' push rax'
]
def _SUB(self):
return [
' pop rax',
' pop rbx',
' sub rbx, rax',
' push rbx'
]
def _MOD(self):
return [
' xor rdx, rdx', # Clear rdx
' pop rbx',
' pop rax',
' idiv rbx',
' push rdx',
]
def _MUL(self):
return [
' pop rax',
' pop rbx',
' imul rax, rbx',
' push rax'
]
def _DIV(self):
return [
' xor rdx, rdx', # Clear rdx
' pop rbx',
' pop rax',
' idiv rbx',
' push rax'
]
def _DROP(self):
return [
' pop rdi'
]
def _ROT2(self):
return [
' pop rax',
' pop rbx',
' push rax',
' push rbx',
]
_SWAP = _ROT2
def _DROT2(self):
return [
# a b c d
# c d a b
' pop rdx',
' pop rcx',
' pop rbx',
' pop rax',
' push rcx',
' push rdx',
' push rax',
' push rbx',
]
def _ROT3(self):
return [
' pop rax',
' pop rbx',
' pop rcx',
' push rbx',
' push rax',
' push rcx',
]
def _DUP(self):
return [
' pop rax',
' push rax',
' push rax'
]
def _DUP2(self):
return [
' pop rbx',
' pop rax',
' push rax',
' push rbx',
' push rax',
' push rbx'
]
def _DUP3(self):
return [
' pop rcx',
' pop rbx',
' pop rax',
' push rax',
' push rbx',
' push rcx',
' push rax',
' push rbx',
' push rcx',
]
def _LOAD1(self):
return [
' pop rax',
' mov rbx, 0', # Clear rbx
' mov bl, [rax]', # Read one byte into rbx
' push rbx',
]
def _STORE1(self):
return [
' pop rax',
' pop rbx',
' mov [rax], bl', # Write one byte from rbx
]
def _LOAD(self):
return [
' pop rax',
' mov rbx, 0', # Clear rbx
' mov rbx, [rax]', # Read into rbx
' push rbx',
]
def _STORE(self):
return [
' pop rax',
' pop rbx',
' mov [rax], rbx', # Write from rbx
]
def _WHERE(self):
# TODO this can be way more efficient
global_state.symbols.extend(self.value)
inst = [f' ;; {global_state.symbols}']
variables = self.value
for i, item in enumerate(variables):
length = len(variables) - 1
stack_location = (length - i) * 8
inst.extend([
f' ;; Bind {item} {stack_location}',
' mov rax, rsp',
f' add rax, {stack_location}', # rax has the address of the variable
' mov rcx, [symbols]', # rcx points to the last free slot
' mov [rcx], rax',
' add rcx, 8', # update symbols so it points
' mov [symbols], rcx' # to a free slot
])
# print()
return inst
def _RETRIEVE(self):
i = global_state.symbols[::-1].index(self.value)
location = i * 8 + 8
return [
f' ;; {global_state.symbols}',
' mov rcx, [symbols]', # rcx points to the last free slot
f' sub rcx, {location}', # rcx points to the variable
' mov rcx, [rcx]',
' mov rax, [rcx]',
f' push rax ;; Push {self.value} onto the stack',
]
def _MUTATE(self):
i = global_state.symbols[::-1].index(self.value)
location = i * 8 + 8
return [
' mov rcx, [symbols]',
f' sub rcx, {location}',
f' mov rbx, [rcx]',
' pop rax',
f' mov [rbx], rax',
' xor rax, rax',
]
def _HARDPEEK(self):
return [
' mov rdi, [rsp]',
' call peek',
' mov rdi, [rsp + 8]',
' call peek',
' mov rdi, [rsp + 16]',
' call peek',
' mov rdi, [rsp + 24]',
' call peek',
]
def _DEREFERENCE(self):
return [
' pop rax',
' mov rbx, [rax]',
' push rbx',
]
def _MEMORY(self):
return [
' push memory',
]
def _EQUAL(self):
return [
' mov rcx, FALSE',
' mov rdx, TRUE',
' pop rax',
' pop rbx',
' cmp rax, rbx',
' cmove rcx, rdx',
' push rcx'
]
def _NOT_EQUAL(self):
return [
' mov rcx, FALSE',
' mov rdx, TRUE',
' pop rax',
' pop rbx',
' cmp rax, rbx',
' cmovne rcx, rdx',
' push rcx'
]
def _LESS_THAN(self):
return [
' mov rcx, FALSE',
' mov rdx, TRUE',
' pop rax',
' pop rbx',
' cmp rbx, rax',
' cmovl rcx, rdx',
' push rcx'
]
def _GREATER_THAN(self):
return [
' mov rcx, FALSE',
' mov rdx, TRUE',
' pop rax',
' pop rbx',
' cmp rbx, rax',
' cmovg rcx, rdx',
' push rcx'
]
def _LESS_OR_EQUAL_THAN(self):
return [
' mov rcx, FALSE',
' mov rdx, TRUE',
' pop rax',
' pop rbx',
' cmp rbx, rax',
' cmovle rcx, rdx',
' push rcx'
]
def _GREATER_OR_EQUAL_THAN(self):
return [
' mov rcx, FALSE',
' mov rdx, TRUE',
' pop rax',
' pop rbx',
' cmp rbx, rax',
' cmovge rcx, rdx',
' push rcx'
]
def _AND(self):
return [
' pop rax',
' pop rbx',
' and rax, rbx',
' push rax'
]
def _OR(self):
return [
' pop rax',
' pop rbx',
' or rax, rbx',
' push rax'
]
def _NOT(self):
return [
' mov rbx, TRUE',
' pop rax',
' not rax',
' and rax, rbx',
' push rax'
]
def _BOOL(self):
return [
' mov rbx, FALSE',
' mov rcx, TRUE',
' pop rax',
' cmp rax, rbx',
' cmove rcx, rbx',
' push rcx'
]
def _IF(self):
return [
'',
# ' pop rax',
# ' cmp rax, TRUE',
# f' jne {self.end_token.label}'
]
def _ELIF(self):
return [
f' jmp {self.end_token.label}',
f'{self.label}:'
]
def _ELSE(self):
return [
f' jmp {self.end_token.label}',
f'{self.label}:'
]
def _END(self):
start_token = self.start_token
assert start_token is not None
if start_token.operator is Operator.IF or start_token.operator is Operator.ELSE:
return [
f'{self.label}:'
]
elif start_token.operator is Operator.DO and start_token.start_token.operator is Operator.WHILE:
while_token = start_token.start_token
assert while_token.operator is Operator.WHILE
return [
f' jmp {while_token.label}',
f'{self.label}:'
]
elif start_token.operator is Operator.DO:
return [
f'{self.label}:'
]
elif start_token.operator is Operator.WHERE:
to_remove = len(start_token.value) * 8
for variable in start_token.value:
global_state.symbols.pop()
return [
' ;; Remove variables from the symbols table',
' mov rcx, [symbols]',
f' sub rcx, {to_remove}',
' mov [symbols], rcx'
]
elif start_token.operator is Operator.PROCEDURE:
if start_token.value == 'main':
return [
' mov rdi, 0 ;; EXIT', # Set exit code to 0
' mov rax, SYS_EXIT',
' syscall'
]
else:
input_variables, return_variables = global_state.procedure_to_variables[start_token.value]
all_variables = return_variables + ['__return_address'] + input_variables
to_remove = len(all_variables)
for variable in all_variables:
global_state.symbols.pop()
return [
' ;; Remove variables from the symbols table',
' mov rcx, [symbols]',
f' sub rcx, {to_remove * 8}',
' mov [symbols], rcx',
' ;; Remove variables from the stack',
f' add rsp, {8 * len(input_variables)}',
' ret',
]
else:
raise RuntimeError('Could not process end token')
def _WHILE(self):
return [
f'{self.label}:'
]
def _DO(self):
return [
' mov rcx, TRUE',
' pop rax',
' cmp rax, TRUE',
f' jne {self.end_token.label}'
]
def _STACK_REFERENCE(self):
return [
' push rsp',
]
# [symbols]
# STACK [var1, var2, addr]
# STACK [ret1, ret2, ret3, addr, var1, var2]
[]
def _PROCEDURE(self):
input_variables, return_variables = global_state.procedure_to_variables[self.value]
original_variables = input_variables + ['__return_address']
input_variables = ['__return_address'] + input_variables
all_variables = return_variables + input_variables
global_state.symbols.extend(all_variables)
inst = [f'{self.label}:', f' ;; {global_state.symbols}']
if self.value == 'main':
inst.extend([
' ;; Setup the symbols table',
' mov rcx, symbols',
' add rcx, 8',
' mov [symbols], rcx'
])
if self.value != 'main':
inst.extend([' ;; Shift everything to make space for the address and return variables'])
inst.extend([
f' ;; {self.value}',
])
shift_amount = (len(return_variables) + 1) * 8
shift_back_amount = len(input_variables) * 8 - shift_amount
if len(input_variables) > 1:
for i, variable in enumerate(original_variables[::-1]):
inst.extend([
f' mov rcx, [rsp {i * 8:+}]',
f' mov [rsp {i * 8 - shift_amount:+}], rcx ;; Move {variable} ahead',
])
inst.extend([
f' mov rcx, [rsp {-shift_amount:+}]',
f' mov [rsp {shift_back_amount:+}], rcx ;; Move return address back'
])
else:
inst.extend([
' mov rcx, [rsp] ;; Take the return address', # Take the return address
f' mov [rsp {-len(return_variables) * 8:+}], rcx ;; Move it forward making space for the return variables'
])
inst.extend([
f' sub rsp, {shift_amount - 8} ;; Resize the stack accordingly',
])
for i, item in enumerate(all_variables):
length = len(all_variables) - 1
stack_location = (length - i) * 8
inst.extend([
f' ;; Bind {item} {stack_location}',
' mov rax, rsp',
f' add rax, {stack_location}', # rax has the address of the variable
' mov rcx, [symbols]', # rcx points to the last free slot
' mov [rcx], rax',
# TODO Do this once after the whole for loop is finished
' add rcx, 8', # update symbols so it points
' mov [symbols], rcx' # to a free slot
])
inst.extend([
f' ;; {self.value}'
])
return inst
def _PROCEDURE_CALL(self):
return [
f' ;; {global_state.symbols}',
' xor rax, rax',
f' call {self.value}',
]
def _SYSCALL(self):
assert 0 <= self.value <= 5
syscall_args = ['rdi', 'rsi', 'rdx', 'r10', 'r8', 'r9']
arguments = syscall_args[:self.value]
start = [
'',
' pop rax',
]
middle = [f' pop {arg}' for arg in arguments]
end = [
' syscall',
' push rax'
]
return start + middle + end
def _PUSH_UINT(self):
return [
f' push {self.value}'
]
def _PUSH_CHAR(self):
return [
f' push {self.value}'
]
def _PUSH_STRING(self):
if self not in global_state.add_symbols:
global_state.add_symbols.append(self)
return [
f' push {self.length}',
f' push {self.label}'
]
# TODO make this a bit more automatic
def _MACRO(self):
raise RuntimeError('Macro operator reached assembly code')
def _MACRO_EXPANSION(self):
raise RuntimeError('Macro expansion operator reached assembly code')
def _IMPORT(self):
raise RuntimeError('Import operator reached assembly code')
def _DEFINE(self):
raise RuntimeError('Define operator reached assembly code')
def operator_to_implementation(operator):
this_module = sys.modules[__name__]
return getattr(this_module, '_' + operator.name)
def get_implementation(operator):
this_module = sys.modules[__name__]
return getattr(this_module, '_' + operator.name)
def lexeme_to_operator(lexeme):
lexeme_to_operator_dict = {item.value: item for item in Operator}
return lexeme_to_operator_dict[lexeme]
def create_token_basic(operator, value, code_iterator, implementation):
token = Token(operator, value=value, implementation=implementation)
return token
def create_token_SWAP(operator, value, code_iterator, implementation):
return operator_to_token(Operator.ROT2, value, code_iterator, implementation)
def create_token_PUSH_STRING(operator, value, code_iterator, implementation):
value = value[1:-1]
value, length = string_to_db(value)
token = Token(Operator.PUSH_STRING,
value=value,
length=length,
label=f'string_literal{global_state.string_literals}',
implementation=implementation)
global_state.string_literals += 1
return token
def create_token_PUSH_CHAR(operator, value, code_iterator, implementation):
value = bytes(value, 'ascii').decode('unicode_escape')
assert len(value) == 3, 'Expected item enclosed by single quotes to be a single character.'
value = ord(value[1])
token = Token(operator, value=value, implementation=implementation)
return token
def create_token_PUSH_UINT(operator, value, code_iterator, implementation):
value = int(value)
token = Token(operator, value=value, implementation=implementation)
return token
def create_token_MUTATE(operator, value, code_iterator, implementation):
value = value[1:]
token = Token(operator, value=value, implementation=implementation)
return token
def create_token_PROCEDURE(operator, value, code_iterator, implementation):
name = next(code_iterator)
if name in global_state.procedures:
raise RuntimeError(f'The procedure {name} was previously defined')
global_state.procedures.append(name)
variables = []
return_variables = []
for variable in code_iterator:
# TODO Check if we find a keyword and report an appropriate error.
if variable == '--':
break
variables.append(variable)
for variable in code_iterator:
# TODO Check if we find a keyword and report an appropriate error.
if variable == 'in':
break
return_variables.append(variable)
global_state.procedure_to_variables[name] = variables, return_variables
token = Token(Operator.PROCEDURE, value=name, implementation=implementation)
return token
def create_token_PROCEDURE_CALL(operator, value, code_iterator, implementation):
procedure_name = value
value = f'{PROCEDURE_PREFIX}{value}'
token = Token(operator, value=value, implementation=implementation)
token.name = procedure_name
return token
def create_token_IMPORT(operator, value, code_iterator, implementation):
filename = next(code_iterator)
global_state.imports[filename] = list()
token = Token(Operator.MACRO, value=filename)
return token
def create_token_MACRO(operator, value, code_iterator, implementation):
value = next(code_iterator)
global_state.macros[value] = list()
token = Token(Operator.MACRO, value=value)
return token
def create_token_MACRO_EXPANSION(operator, value, code_iterator, implementation):
assert value in global_state.macros, f'Unrecognized macro {value}'
token = Token(Operator.MACRO_EXPANSION, value=value)
return token
def create_token_SYSCALL(operator, value, code_iterator, implementation):
value = int(value[-1])
token = Token(Operator.SYSCALL, value=value, implementation=implementation)
return token
def create_token_WHERE(operator, value, code_iterator, implementation):
variables = []
for variable in code_iterator:
if variable == 'in':
break
variables.append(variable)
return Token(operator, value=variables, implementation=implementation)
def operator_to_token(operator, value, code_iterator, implementation):
this_module = sys.modules[__name__]
create_token = getattr(this_module, 'create_token_' + operator.name, create_token_basic)
return create_token(operator, value, code_iterator, implementation)