-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·1517 lines (1302 loc) · 55.7 KB
/
main.py
File metadata and controls
executable file
·1517 lines (1302 loc) · 55.7 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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3.11
from abc import abstractmethod
from array import array
import copy
import json
import os.path
import subprocess
import time
from typing import List, Tuple, Dict, final
import sys
STATIC_MEMORY_SIZE = 1024 * 1024 * 8
MAX_ARGS = 5
strings = list()
string_length = 0
debug = False
if 'DEBUG' in os.environ:
debug = True
info_cmd = True
if 'NO_CMD_INFO' in os.environ:
info_cmd = False
info = True
if 'NOINFO' in os.environ:
info = False
fasm_loc = 'fasm'
if 'FASM_LOC' in os.environ:
fasm_loc = os.environ['FASM_LOC']
def shift_args(args: List) -> Tuple[str, List]:
return args[0], args[1:]
def usage(program_name: str) -> None:
print(f"{program_name} <input file> <output file>")
def todo():
assert False, "Not implemented yet"
auto_ = 0
def auto(reset=False):
global auto_
if reset:
auto_ = 0
val = auto_
auto_ += 1
return val
class TokenType(int):
COMMA = auto()
OPEN_CURLY_BRACKET = auto()
CLOSE_CURLY_BRACKET = auto()
OPEN_BRACKET = auto()
CLOSE_BRACKET = auto()
OPEN_PAREN = auto()
CLOSE_PAREN = auto()
MULT = auto()
DIV = auto()
MOD = auto()
SEMICOLON = auto()
ADD = auto()
MINUS = auto()
ASSIGN = auto()
IDENTIFIER = auto()
INT = auto()
STRING = auto()
FUNCTION = auto()
PUTC = auto()
NEQ = auto()
EQ = auto()
WHILE = auto()
IF = auto()
RETURN = auto()
LET = auto()
CONST = auto()
LEFT_SHIFT = auto()
RIGHT_SHIFT = auto()
BIT_AND = auto()
BIT_OR = auto()
IMPORT = auto()
COMMENTS = auto()
SYSCALL = auto()
TokenType_NUMBERS = auto()
class Location:
def __init__(self, line, col, file):
self.line = line
self.col = col
self.file = file
def __str__(self):
return f"{self.file}:{self.line}:{self.col}"
def __repr__(self):
return self.__str__()
def to_dict(self):
return dict(
line=self.line,
col=self.col,
file=self.file,
)
class Token:
def __init__(self, literal, type_, location):
self.literal = literal
self.type = type_
self.location = location
def __str__(self):
return f"Token[literal=`{self.literal}`, type={self.type}, location={self.location}"
def __repr__(self):
return self.__str__()
def to_dict(self):
location = self.location.to_dict()
return dict(
literal=self.literal,
type=self.type,
location=location,
)
class Lexer:
def __init__(self, input_file: str, program_string: str):
self.program_string = program_string
self.cursor = 0
self.line = 1
self.cursor_on_line = 1
self.input_file = input_file
def chop_char(self) -> str:
char = self.program_string[self.cursor]
self.cursor += 1
self.cursor_on_line += 1
return char
def __iter__(self):
return self
def trim_left(self):
while self.program_string[self.cursor].isspace():
char = self.chop_char()
if self.cursor >= len(self.program_string):
raise StopIteration
if char == '\n':
self.line += 1
self.cursor_on_line = 1
def drop_line(self):
while self.chop_char() != '\n':
if self.cursor >= len(self.program_string):
raise StopIteration
def __next__(self):
global debug
assert TokenType.TokenType_NUMBERS == 33
if debug:
print(Location(self.line, self.cursor_on_line, self.input_file))
if self.cursor >= len(self.program_string):
raise StopIteration
self.trim_left()
if self.program_string[self.cursor] == '/' and self.program_string[self.cursor +1] == '/':
self.drop_line()
cursor = self.cursor
location = Location(self.line, self.cursor_on_line, self.input_file)
if self.program_string[cursor] == '"':
literal = ""
self.chop_char()
while self.program_string[self.cursor] != '"':
char = self.chop_char()
if char == '\\':
escape = self.chop_char()
if escape == 'n':
char = '\n'
literal += char
self.chop_char()
type_ = TokenType.STRING
return Token(literal, type_, location)
elif self.program_string[self.cursor] == "'":
self.chop_char()
literal = ord(self.chop_char())
self.chop_char()
type_ = TokenType.INT
return Token(literal, type_, location)
elif self.program_string[self.cursor].isalpha() or self.program_string[self.cursor] == '_':
while self.program_string[self.cursor].isalnum() or self.program_string[self.cursor] == '_':
self.chop_char()
literal = self.program_string[cursor:self.cursor]
type_ = TokenType.IDENTIFIER
if literal == 'putc':
type_ = TokenType.PUTC
elif literal == 'if':
type_ = TokenType.IF
elif literal == 'while':
type_ = TokenType.WHILE
elif literal == 'return':
type_ = TokenType.RETURN
elif literal == 'fun':
type_ = TokenType.FUNCTION
elif literal == 'let':
type_ = TokenType.LET
elif literal == 'const':
type_ = TokenType.CONST
elif literal == 'import':
type_ = TokenType.IMPORT
elif literal == 'syscall':
type_ = TokenType.SYSCALL
return Token(literal, type_, location)
elif self.program_string[self.cursor].isnumeric():
while self.program_string[self.cursor].isalnum() or self.program_string[self.cursor] == '_':
self.chop_char()
literal = self.program_string[cursor:self.cursor]
type_ = TokenType.INT
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '!':
self.chop_char()
if self.program_string[self.cursor] == '=':
literal = "!" + self.chop_char()
type_ = TokenType.NEQ
return Token(literal, type_, location)
print(f"{location}:ERROR: `!{self.chop_char()}` is not a valid symbol")
elif self.program_string[self.cursor] == '=':
if self.cursor + 1 < len(self.program_string) and self.program_string[self.cursor + 1] == '=':
literal = self.chop_char() + self.chop_char()
type_ = TokenType.EQ
else:
literal = self.chop_char()
type_ = TokenType.ASSIGN
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '-':
literal = self.chop_char()
type_ = TokenType.MINUS
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '+':
literal = self.chop_char()
type_ = TokenType.ADD
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '/':
literal = self.chop_char()
type_ = TokenType.DIV
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '%':
literal = self.chop_char()
type_ = TokenType.MOD
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '|':
literal = self.chop_char()
type_ = TokenType.BIT_OR
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '&':
literal = self.chop_char()
type_ = TokenType.BIT_AND
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '<':
if self.program_string[self.cursor + 1] == '<':
literal = self.chop_char()
self.chop_char()
type_ = TokenType.LEFT_SHIFT
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '>':
if self.program_string[self.cursor + 1] == '>':
literal = self.chop_char()
self.chop_char()
type_ = TokenType.RIGHT_SHIFT
return Token(literal, type_, location)
elif self.program_string[self.cursor] == ';':
literal = self.chop_char()
type_ = TokenType.SEMICOLON
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '(':
literal = self.chop_char()
type_ = TokenType.OPEN_PAREN
return Token(literal, type_, location)
elif self.program_string[self.cursor] == ')':
literal = self.chop_char()
type_ = TokenType.CLOSE_PAREN
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '*':
literal = self.chop_char()
type_ = TokenType.MULT
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '{':
literal = self.chop_char()
type_ = TokenType.OPEN_CURLY_BRACKET
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '}':
literal = self.chop_char()
type_ = TokenType.CLOSE_CURLY_BRACKET
return Token(literal, type_, location)
elif self.program_string[self.cursor] == '[':
literal = self.chop_char()
type_ = TokenType.OPEN_BRACKET
return Token(literal, type_, location)
elif self.program_string[self.cursor] == ']':
literal = self.chop_char()
type_ = TokenType.CLOSE_BRACKET
return Token(literal, type_, location)
elif self.program_string[self.cursor] == ',':
literal = self.chop_char()
type_ = TokenType.COMMA
return Token(literal, type_, location)
else:
print(self.program_string[self.cursor])
todo()
class AST():
def __init__(self, token: Token):
self.token = token
def to_dict(self):
pass
def __str__(self):
return json.dumps(self.to_dict(), indent=4)
def __repr__(self):
return self.__str__()
@abstractmethod
def generate(self, generator, out_file):
pass
class BinaryOperator(AST):
def __init__(self, token: Token, left: AST, right: AST):
super().__init__(token)
self.left = left
self.right = right
def to_dict(self):
if self.left is None:
ltd = None
else:
ltd = self.left.to_dict()
if self.right is None:
rtd = None
else:
rtd = self.right.to_dict()
return dict(
operator=self.token.literal,
left=ltd,
right=rtd,
)
def generate(self, generator, out_file):
assert TokenType.TokenType_NUMBERS == 33
if self.token.type == TokenType.LEFT_SHIFT:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; SHL", file=out_file)
print(f"mov rcx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
print(f"shl rax, cl", file=out_file)
elif self.token.type == TokenType.RIGHT_SHIFT:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; SRL", file=out_file)
print(f"mov rcx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
print(f"shr rax, cl", file=out_file)
elif self.token.type == TokenType.BIT_OR:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; B OR", file=out_file)
print(f"or rbx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
elif self.token.type == TokenType.BIT_AND:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; B AND", file=out_file)
print(f"and rbx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
elif self.token.type == TokenType.MINUS:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; MINUS", file=out_file)
print(f"sub rbx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
if self.token.type == TokenType.ADD:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; ADD", file=out_file)
print(f"add rax, rbx", file=out_file)
elif self.token.type == TokenType.NEQ:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; NEQ", file=out_file)
print(f"mov rcx, 0", file=out_file)
print(f"mov rdx, 1", file=out_file)
print(f"cmp rax, rbx", file=out_file)
print(f"cmovne rcx, rdx", file=out_file)
print(f"mov rax, rcx", file=out_file)
elif self.token.type == TokenType.EQ:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; EQ", file=out_file)
print(f"mov rcx, 0", file=out_file)
print(f"mov rdx, 1", file=out_file)
print(f"cmp rax, rbx", file=out_file)
print(f"cmove rcx, rbx", file=out_file)
print(f"mov rax, rcx", file=out_file)
elif self.token.type == TokenType.MULT:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"; MULT", file=out_file)
print(f"mul rbx", file=out_file)
elif self.token.type == TokenType.DIV:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"xor rdx, rdx", file=out_file)
print(f"mov rcx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
print(f"mov rbx, rcx", file=out_file)
print(f"div rbx", file=out_file)
elif self.token.type == TokenType.MOD:
self.left.generate(generator, out_file)
print(f"push rax", file=out_file)
self.right.generate(generator, out_file)
print(f"pop rbx", file=out_file)
print(f"xor rdx, rdx", file=out_file)
print(f"mov rcx, rax", file=out_file)
print(f"mov rax, rbx", file=out_file)
print(f"mov rbx, rcx", file=out_file)
print(f"div rbx", file=out_file)
print(f"mov rax, rdx", file=out_file)
class IfNode(AST):
def __init__(self, token: Token, condition: AST, body: AST):
super().__init__(token)
self.condition = condition
self.body = body
def to_dict(self):
return dict(condition=self.condition.to_dict(), body=self.body.to_dict())
def generate(self, generator, out_file):
condition_label = generator.label_count
generator.label_count += 1
end_label = generator.label_count
generator.label_count += 1
print(f"; IF", file=out_file)
print(f".L{condition_label}:", file=out_file)
self.condition.generate(generator, out_file)
print(f"cmp rax, 0", file=out_file)
print(f"je .L{end_label}", file=out_file)
self.body.generate(generator, out_file)
print(f".L{end_label}:", file=out_file)
class WhileNode(AST):
def __init__(self, token: Token, condition: AST, body: AST):
super().__init__(token)
self.condition = condition
self.body = body
def to_dict(self):
return dict(condition=self.condition.to_dict(), body=self.body.to_dict())
def generate(self, generator, out_file):
condition_label = generator.label_count
generator.label_count += 1
end_label = generator.label_count
generator.label_count += 1
print(f"; WHILE", file=out_file)
print(f".L{condition_label}:", file=out_file)
self.condition.generate(generator, out_file)
print(f"cmp rax, 0", file=out_file)
print(f"je .L{end_label}", file=out_file)
self.body.generate(generator, out_file)
print(f"jmp .L{condition_label}", file=out_file)
print(f".L{end_label}:", file=out_file)
class Generator_NASM:
def __init__(self, statements: List[AST], out_file_name="foo.asm"):
self.out_file = None
self.constants: Dict[str, str] = dict()
self.statements = statements
self.table_list: Dict[str, str] = dict()
self.table_length: Dict[str, TableElement] = dict()
self.variables: Dict[str, str] = dict()
self.functions: Dict[str, str] = dict()
self.out_file_name = out_file_name
self.memory_depth = 0
self.label_count = 0
def generate(self):
out_file = open(self.out_file_name, "w")
# Allocate static memory to do operations
print("BITS 64", file=out_file)
print("section .text", file=out_file)
print(" global _start", file=out_file)
for i, statement in enumerate(self.statements):
if i != 0:
print(f".l{i}:", file=out_file)
statement.generate(self, out_file)
print("; STOP", file=out_file)
print("mov rax, 60", file=out_file)
print("xor rdi, rdi", file=out_file)
print("syscall", file=out_file)
print("section .data", file=out_file)
for table in self.table_list:
if self.table_length[table].elements is None:
print(f"{self.table_list[table].removeprefix('[').removesuffix(']')} times {self.table_length[table].length} * 8 {self.table_length[table].data_length} 0", file=out_file)
else:
print(f"{self.table_list[table].removeprefix('[').removesuffix(']')} {self.table_length[table].data_length} ", end="", file=out_file)
assert(self.table_length[table].elements is not None)
for idx, data in enumerate(self.table_length[table].elements):
if idx != 0:
print(",", end="", file=out_file)
print(data, end="", file=out_file)
print("", file=out_file)
print(f"fstack times {8 << MAX_ARGS} db 0", file=out_file)
print(f"mem times {STATIC_MEMORY_SIZE} db 0", file=out_file)
out_file.close()
def deepcopy(self):
statements = copy.deepcopy(self.statements)
out_file_name = copy.deepcopy(self.out_file_name)
gen = Generator_NASM(statements, out_file_name)
gen.functions = copy.deepcopy(self.functions)
gen.memory_depth = copy.deepcopy(self.memory_depth)
gen.label_count = copy.deepcopy(self.label_count)
return gen
class Generator_FASM:
def __init__(self, statements: List[AST], out_file_name="foo.asm"):
self.out_file = None
self.constants: Dict[str, str] = dict()
self.statements = statements
self.table_list: Dict[str, str] = dict()
self.table_length: Dict[str, TableElement] = dict()
self.variables: Dict[str, str] = dict()
self.functions: Dict[str, str] = dict()
self.out_file_name = out_file_name
self.memory_depth = 0
self.label_count = 0
def generate(self):
out_file = open(self.out_file_name, "w")
# Allocate static memory to do operations
print("format ELF64 executable", file=out_file)
print("segment readable executable", file=out_file)
print(" entry start", file=out_file)
for i, statement in enumerate(self.statements):
statement.generate(self, out_file)
print("; STOP", file=out_file)
print("mov rax, 60", file=out_file)
print("xor rdi, rdi", file=out_file)
print("syscall", file=out_file)
print("segment readable writable", file=out_file)
for table in self.table_list:
if self.table_length[table].elements is None:
print(f"{self.table_list[table].removeprefix('[').removesuffix(']')} {self.table_length[table].data_length} {self.table_length[table].length} * 8 dup(0)", file=out_file)
else:
print(f"{self.table_list[table].removeprefix('[').removesuffix(']')} {self.table_length[table].data_length} ", end="", file=out_file)
assert(self.table_length[table].elements is not None)
for idx, data in enumerate(self.table_length[table].elements):
if idx != 0:
print(",", end="", file=out_file)
print(data, end="", file=out_file)
print("", file=out_file)
print(f"fstack rb {8 << MAX_ARGS}", file=out_file)
print(f"mem rb {STATIC_MEMORY_SIZE}", file=out_file)
out_file.close()
def deepcopy(self):
statements = copy.deepcopy(self.statements)
out_file_name = copy.deepcopy(self.out_file_name)
gen = Generator_FASM(statements, out_file_name)
gen.functions = copy.deepcopy(self.functions)
gen.memory_depth = copy.deepcopy(self.memory_depth)
gen.label_count = copy.deepcopy(self.label_count)
return gen
class FunctionNode(AST):
def __init__(self, token: Token, arguments: List[Token],
body: AST, name: Token):
super().__init__(token)
self.name = name
self.arguments = arguments
self.body = body
def to_dict(self):
return dict(name=self.name.literal,
arguments=[a.to_dict() for a in self.arguments], body=self.body.to_dict())
def generate(self, generator, out_file):
function_name = self.name.literal
if function_name in generator.functions:
print(f"{self.token.location}: ERROR: function name already exists")
if function_name in generator.variables:
print(f"{self.token.location}: ERROR: this token already exists. This is a variable.")
asm_func_name = f"FUNC_{function_name}"
if function_name == 'main':
if debug:
asm_func_name = "_start"
else:
asm_func_name = "start"
generator.functions[function_name] = asm_func_name
new_gen = generator
if function_name != 'main':
if debug:
new_gen = Generator_NASM(generator.statements)
else:
new_gen = Generator_FASM(generator.statements)
new_gen.memory_depth = generator.memory_depth
new_gen.functions = generator.functions
new_gen.label_count = generator.label_count
new_gen.table_list = generator.table_list
new_gen.table_length = generator.table_length
print(f"{asm_func_name}:", file=out_file)
function_stack = 0
for arg in self.arguments:
identifier = arg.literal
new_gen.variables[identifier] = f"[mem+{new_gen.memory_depth}]"
print(f"mov r10, qword [fstack+{function_stack}]", file=out_file)
print(f"mov qword {new_gen.variables[identifier]}, r10", file=out_file)
new_gen.memory_deptength= 8
function_stack += 8
self.body.generate(new_gen, out_file)
if function_name != 'main':
print(f"ret", file=out_file)
generator.label_count = new_gen.label_count
generator.memory_depth = new_gen.memory_depth # TODO optimize memory
generator.table_list = new_gen.table_list # TODO optimize memory
generator.table_length = new_gen.table_length # TODO optimize memory
class FunctionCall(AST):
def __init__(self, token: Token, arguments: List[AST]):
super().__init__(token)
self.arguments = arguments
def to_dict(self):
return dict(arguments=[a.to_dict() for a in self.arguments])
def generate(self, generator, out_file):
identifier = self.token.literal
function_stack = 0
if identifier not in generator.functions:
print(f"{self.token.location}: ERROR: no function named `{identifier}`")
exit(1)
for arg in self.arguments:
arg.generate(generator, out_file)
print(f"mov qword [fstack+{function_stack}], rax", file=out_file)
function_stack += 8 # TODO 8 = sizeof int
print(f"call {generator.functions[identifier]}", file=out_file)
class SystemCall(AST):
def __init__(self, token: Token, arguments: List[AST]):
super().__init__(token)
self.arguments = arguments
def to_dict(self):
return dict(arguments=[a.to_dict() for a in self.arguments])
def generate(self, generator, out_file):
# TODO make shure the syscall is legal (args == syscall number)
function_stack = 0
for arg in self.arguments:
arg.generate(generator, out_file)
print(f"mov qword [fstack+{function_stack}], rax", file=out_file)
function_stack += 8 # TODO 8 = sizeof int
if len(self.arguments) < 1:
print(f"{self.token.location}: ERROR: Not enought arguments for syscall")
print(f"mov rax, qword [fstack]", file=out_file)
if len(self.arguments) > 1:
print(f"mov rdi, qword [fstack+8]", file=out_file)
if len(self.arguments) > 2:
print(f"mov rsi, qword [fstack+16]", file=out_file)
if len(self.arguments) > 3:
print(f"mov rdx, qword [fstack+24]", file=out_file)
if len(self.arguments) > 4:
print(f"mov r10, qword [fstack+32]", file=out_file)
if len(self.arguments) > 5:
print(f"mov r8, qword [fstack+40]", file=out_file)
if len(self.arguments) > 6:
print(f"mov r9, qword [fstack+48]", file=out_file)
if len(self.arguments) > 7:
print(f"{self.token.location}: ERROR: Too many arguments for syscall")
print(f"syscall", file=out_file)
class BlockNode(AST):
def __init__(self, token: Token, statements: List[AST]):
super().__init__(token)
self.statements: List[AST] = statements
def to_dict(self):
return dict(statements=[s.to_dict() for s in self.statements])
def generate(self, generator, out_file):
for statement in self.statements:
statement.generate(generator, out_file)
class AssignNode(AST):
def __init__(self, token: Token, variable: AST, expression: AST):
super().__init__(token)
self.variable = variable
self.expression = expression
def to_dict(self):
return dict(variable=self.variable.to_dict(), expression=self.expression.to_dict())
def generate(self, generator, out_file):
identifier = self.variable.token.literal
self.expression.generate(generator, out_file)
if identifier in generator.functions:
print(f"{self.token.location}: ERROR: cannot assign to a function.")
exit(1)
if identifier in generator.variables:
if generator.variables[identifier] is None:
generator.variables[identifier] = f"[mem+{generator.memory_depth}]"
generator.memory_depth += 8
var_to_print = generator.variables[identifier]
elif identifier in generator.table_list:
var_to_print = None
else:
print(f"{self.token.location}: ERROR: unknown word `{identifier}`.")
exit(1)
print(f"; ASSIGN", file=out_file)
if isinstance(self.variable, TableAccessNode):
print("push rax", file=out_file)
self.variable.generate(generator, out_file)
print("pop rax ", file=out_file)
print("mov qword [rbx], rax", file=out_file)
else:
print(f"mov qword {var_to_print}, rax", file=out_file)
class ReturnNode(AST):
def __init__(self, token: Token, expression: AST):
super().__init__(token)
self.expression = expression
def to_dict(self):
return dict(expression=self.expression.to_dict())
def generate(self, generator, out_file):
self.expression.generate(generator, out_file)
print("ret", file=out_file)
class PutcNode(AST):
def __init__(self, token: Token, expression: AST):
super().__init__(token)
self.expression = expression
def to_dict(self):
return dict(expression=self.expression.to_dict())
def generate(self, generator, out_file):
self.expression.generate(generator, out_file)
print(f"; PUTC", file=out_file)
mem_addr = f"[mem+{generator.memory_depth}]"
generator.memory_depth += 8 # TODO optimize memory
print(f"mov qword {mem_addr}, rax", file=out_file)
print(f"lea rsi, {mem_addr}", file=out_file)
print("mov rdx, 8", file=out_file)
print("mov rdi, 1", file=out_file)
print("mov rax, 1", file=out_file)
print("syscall", file=out_file)
class VariableDeclarationNode(AST):
def __init__(self, token: Token, variable: Token):
super().__init__(token)
self.variable = variable
def to_dict(self):
return dict(variable=self.variable.to_dict())
def generate(self, generator, out_file):
out_file = out_file
generator.variables[self.variable.literal] = None
class IntNode(AST):
def __init__(self, token: Token):
super().__init__(token)
self.value = token.literal
def to_dict(self):
return dict(value=self.value)
def generate(self, generator, out_file):
print(f"; INT", file=out_file)
print(f"mov rax, {self.token.literal}", file=out_file)
class IdentifierNode(AST):
def __init__(self, token: Token):
super().__init__(token)
self.value = token.literal
def to_dict(self):
return dict(value=self.value)
def generate(self, generator, out_file):
identifier = self.token.literal
if self.token.literal in generator.constants:
print(f"mov rax, {generator.constants[self.token.literal]}", file=out_file)
return
if identifier not in generator.variables and identifier not in generator.functions:
for idx, table in enumerate(generator.table_list):
if table == identifier:
print(f"mov rax, qword table_{idx}", file=out_file)
return
print(f"{self.token.location}: ERROR: identifier `{identifier}` is not declared")
exit(1)
if generator.variables[identifier] is None:
print(f"{self.token.location}: ERROR: identifier `{identifier}` is not assigned")
exit(1)
print(f"mov rax, qword {generator.variables[identifier]}", file=out_file)
class TableAccessNode(AST):
def __init__(self, token: Token, index: AST):
super().__init__(token)
self.value = token.literal
self.index = index
def to_dict(self):
return dict(value=self.value, index=self.index.to_dict())
def generate(self, generator, out_file):
identifier = self.token.literal
if identifier not in generator.table_list:
print(f"{self.token.location}: ERROR: the identifier is not initialized")
exit(1)
self.index.generate(generator, out_file)
mem_variable = generator.table_list[identifier]
string = False
mem = generator.table_list[identifier]
var = mem.removeprefix('[').removesuffix(']')
print(f"lea r10, qword [{var}]", file=out_file)
string = True
sizeof_var = generator.table_length[identifier].data_length_int # TODO sizeof VAR at compile time (when adding struct ?)
# rax is the index
print(f"mov rcx, {sizeof_var}", file=out_file)
print("mul rcx", file=out_file)
print("add rax, r10", file=out_file)
print(f"mov rbx, rax", file=out_file)
if string:
print(f"mov al, [rbx]", file=out_file)
print(f"movzx rax, al", file=out_file)
else:
print(f"mov rax, qword [rbx]", file=out_file)
class TableElement:
def __init__(self, length: int, data_length: str, data_length_int: int, elements: List[str] | None):
self.length = length
self.data_length = data_length
self.data_length_int = data_length_int
self.elements = elements
class TableDeclarationNode(AST):
def __init__(self, token: Token, variable: Token, length: Token):
super().__init__(token)
self.variable = variable
self.length = length
def to_dict(self):
return dict(variable=self.variable.to_dict(), length=self.length.to_dict())
def generate(self, generator, out_file):
if self.length.type != TokenType.INT and self.length.literal not in generator.constants:
print(f"{self.length.location}: ERROR: The length of the table is not a integer.")
exit(1)
if self.length.literal in generator.constants:
self.length.literal = generator.constants[self.length.literal]
generator.table_list[self.variable.literal] = f"[table_{len(generator.table_list)}]"
generator.table_length[self.variable.literal] = TableElement(
self.length.literal, "dq", 8, None)
class ArrayNode(AST):
def __init__(self, token: Token, array: List[Token]):
super().__init__(token)
self.array = array
self.size = 0
def add(self, item):
self.array.append(item)
self.size += 1
def to_dict(self):
return dict(array=[t.to_dict() for t in self.array])
def generate(self, generator, out_file):
global strings
global string_length
first_raw = generator.memory_depth
print(f"; ARRAYNODE", file=out_file)
if self.token.type == TokenType.STRING:
strings.append([ord_ for ord_ in self.array])
print(f"lea rax, [string_{string_length}]", file=out_file)
string_length += 1
else:
for i in range(len(self.array)):
print(f"mov qword [mem+{generator.memory_depth}], {self.array[i].literal}",
file=out_file)
generator.memory_depth += 8
print(f"lea rax, qword [mem+{first_raw}]", file=out_file)
class DirectTableDeclarationNode(AST):
def __init__(self, token: Token, variable: Token, array_node: ArrayNode):
super().__init__(token)
self.variable = variable
self.array_node = array_node
def to_dict(self):
return dict(variable=self.variable.to_dict(), array=self.array_node.to_dict())
def generate(self, generator, out_file):
if self.array_node.token.type != TokenType.STRING:
generator.table_list[self.variable.literal] = f"[table_{len(generator.table_list)}]"
generator.table_length[self.variable.literal] = TableElement(
len(self.array_node.array),
"dq",
8,
[ide.literal for ide in self.array_node.array]
)
var_to_print = generator.table_list[self.variable.literal]
else:
generator.table_list[self.variable.literal] = f"[table_{len(generator.table_list)}]"