-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcodegen.py
More file actions
1781 lines (1449 loc) · 67.3 KB
/
Copy pathcodegen.py
File metadata and controls
1781 lines (1449 loc) · 67.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
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
# -----------------------------------------------------------------------------
# codegen.py
#
# Author: Ahmad Alhour (aalhour.com).
# Date: 2024
# Description: MIPS 32-bit code generator for COOL programs.
#
# This module translates a type-checked COOL AST into MIPS assembly that
# can be executed on the SPIM simulator.
# -----------------------------------------------------------------------------
"""
# COOL Object Layout (MIPS 32-bit)
Each COOL object has the following memory layout:
Offset Field
------ -----
0 Class tag (unique integer per class)
4 Object size (in bytes)
8 Dispatch pointer (address of dispatch table)
12+ Attributes (4 bytes each, in inheritance order)
# Dispatch Tables
Each class has a dispatch table containing pointers to method implementations.
Methods are ordered by first appearance in inheritance chain.
# Register Conventions
$a0 Self pointer (current object)
$a1-$a3 Method arguments
$sp Stack pointer
$fp Frame pointer
$ra Return address
$v0 Return value / syscall number
$t0-$t9 Temporaries (caller-saved)
$s0-$s7 Saved registers (callee-saved)
# Stack Frame Layout
Higher addresses
+---------------+
| Argument n |
| ... |
| Argument 1 |
| Return address|
| Old $fp | <- $fp points here
| Local 1 |
| ... |
| Local n |
| Temporaries | <- $sp points here
+---------------+
Lower addresses
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TextIO
import pycoolc.ast as AST
from pycoolc.semanalyser import (
BOOLEAN_CLASS,
INTEGER_CLASS,
IO_CLASS,
OBJECT_CLASS,
SELF_TYPE,
STRING_CLASS,
PyCoolSemanticAnalyser,
)
# -----------------------------------------------------------------------------
# CONSTANTS
# -----------------------------------------------------------------------------
# Word size in bytes (MIPS 32-bit)
WORD_SIZE = 4
# Object header size: class_tag + size + dispatch_ptr
OBJECT_HEADER_SIZE = 3 * WORD_SIZE
# Default values for primitive types
DEFAULT_INT = 0
DEFAULT_BOOL = False
DEFAULT_STRING = ""
# Label prefixes
CLASS_INIT_PREFIX = "_init_"
CLASS_PROTOBJ_PREFIX = "_protObj_"
CLASS_DISPTAB_PREFIX = "_dispTab_"
METHOD_PREFIX = "_method_"
STRING_CONST_PREFIX = "_str_const_"
INT_CONST_PREFIX = "_int_const_"
BOOL_CONST_PREFIX = "_bool_const_"
# -----------------------------------------------------------------------------
# DATA STRUCTURES
# -----------------------------------------------------------------------------
@dataclass
class ClassInfo:
"""Information about a class needed for code generation."""
name: str
tag: int # Unique class identifier
size: int # Object size in bytes
parent: str | None
attributes: list[tuple[str, str]] # (name, type) pairs in order
methods: list[tuple[str, str]] # (name, defining_class) pairs in order
@dataclass
class StringConstant:
"""A string constant in the data segment."""
label: str
value: str
length: int
@dataclass
class IntConstant:
"""An integer constant in the data segment."""
label: str
value: int
# -----------------------------------------------------------------------------
# CODE GENERATOR
# -----------------------------------------------------------------------------
class MIPSCodeGenerator:
"""
MIPS code generator for COOL programs.
Takes a semantically analyzed COOL program and generates MIPS assembly
that can be run on the SPIM simulator.
"""
def __init__(self, analyzer: PyCoolSemanticAnalyser) -> None:
self.analyzer = analyzer
self.program: AST.Program | None = None
# Class information indexed by name
self.class_info: dict[str, ClassInfo] = {}
# Class tags (for runtime type checking)
self.class_tags: dict[str, int] = {}
# Constants pool
self.string_constants: dict[str, StringConstant] = {}
self.int_constants: dict[int, IntConstant] = {}
# Label counter for unique labels
self._label_counter = 0
# Output buffer
self._output: list[str] = []
# Current class/method context
self._current_class: str = ""
self._current_method: str = ""
# Local variable offsets from $fp
self._locals: dict[str, int] = {}
self._next_local_offset = 0
# Local variable types for dispatch type resolution
self._local_types: dict[str, str] = {}
# Self offset from $fp (depends on frame size)
self._self_offset = 0
def _get_expr_type(self, expr: AST.AST) -> str:
"""
Get the static type of an expression for method dispatch.
This is a simplified version of type inference for codegen purposes.
We only need to handle the cases that affect method lookup.
"""
match expr:
case AST.Self():
return self._current_class
case AST.Object(name=name):
# Check local variables first
if name in self._local_types:
return self._local_types[name]
# Check attributes
info = self.class_info.get(self._current_class)
if info:
for attr_name, attr_type in info.attributes:
if attr_name == name:
return attr_type
return OBJECT_CLASS
case AST.NewObject(type=type_name):
return type_name if type_name != SELF_TYPE else self._current_class
case AST.DynamicDispatch(instance=obj, method=method_name):
# Get the type of the object, then find the method return type
obj_type = self._get_expr_type(obj)
return_type = self._find_method_return_type(obj_type, method_name)
return return_type if return_type != SELF_TYPE else obj_type
case AST.StaticDispatch(instance=obj, dispatch_type=dtype, method=method_name):
return_type = self._find_method_return_type(dtype, method_name)
return return_type if return_type != SELF_TYPE else self._get_expr_type(obj)
case AST.Integer():
return INTEGER_CLASS
case AST.String():
return STRING_CLASS
case AST.Boolean():
return BOOLEAN_CLASS
case _:
return OBJECT_CLASS
def _find_method_return_type(self, class_name: str, method_name: str) -> str:
"""Find the return type of a method in a class or its ancestors."""
if self.program is None:
return OBJECT_CLASS
# Search up the inheritance chain
current: str | None = class_name
while current:
for klass in self.program.classes:
if klass.name == current:
for feature in klass.features:
if isinstance(feature, AST.ClassMethod) and feature.name == method_name:
return feature.return_type
# Move to parent
current = klass.parent
break
else:
# Class not found in program (might be builtin)
break
# Check builtin methods
builtin_methods = {
("Object", "abort"): OBJECT_CLASS,
("Object", "copy"): SELF_TYPE,
("Object", "type_name"): STRING_CLASS,
("IO", "out_string"): SELF_TYPE,
("IO", "out_int"): SELF_TYPE,
("IO", "in_string"): STRING_CLASS,
("IO", "in_int"): INTEGER_CLASS,
("String", "length"): INTEGER_CLASS,
("String", "concat"): STRING_CLASS,
("String", "substr"): STRING_CLASS,
}
# Check if method is inherited from a builtin
ancestors = self._get_ancestors(class_name)
for ancestor in ancestors:
if (ancestor, method_name) in builtin_methods:
return builtin_methods[(ancestor, method_name)]
return OBJECT_CLASS
def _get_ancestors(self, class_name: str) -> list[str]:
"""Get list of ancestors including the class itself."""
result = [class_name]
current: str | None = class_name
if self.program is None:
return result
while current and current != OBJECT_CLASS:
for klass in self.program.classes:
if klass.name == current:
if klass.parent:
result.append(klass.parent)
current = klass.parent
else:
current = None
break
else:
# Check builtin parents
builtin_parents = {
IO_CLASS: OBJECT_CLASS,
INTEGER_CLASS: OBJECT_CLASS,
STRING_CLASS: OBJECT_CLASS,
BOOLEAN_CLASS: OBJECT_CLASS,
}
if current in builtin_parents:
result.append(builtin_parents[current])
current = builtin_parents[current]
else:
break
return result
def generate(self, program: AST.Program) -> str:
"""
Generate MIPS assembly for a COOL program.
Returns the complete assembly as a string.
"""
self.program = program
self._output = []
# Build class information
self._build_class_info()
# Collect all constants from the program BEFORE generating code
# This is necessary because we emit .data before .text
self._collect_all_constants()
# Generate data segment
self._emit_data_segment()
# Generate text segment
self._emit_text_segment()
return "\n".join(self._output)
def _collect_all_constants(self) -> None:
"""
Traverse the entire AST to collect all string and integer constants.
This must be done before emitting the data segment so that all
constant labels are available when generating code.
"""
if self.program is None:
return
for klass in self.program.classes:
# Skip built-in classes
if klass.name in {OBJECT_CLASS, IO_CLASS, INTEGER_CLASS, BOOLEAN_CLASS, STRING_CLASS}:
continue
for feature in klass.features:
if isinstance(feature, AST.ClassAttribute):
if feature.init_expr is not None:
self._collect_constants_from_expr(feature.init_expr)
elif isinstance(feature, AST.ClassMethod):
if feature.body is not None:
self._collect_constants_from_expr(feature.body)
def _collect_constants_from_expr(self, expr: AST.AST) -> None:
"""Recursively collect all constants from an expression."""
match expr:
case AST.Integer(content=value):
if value not in self.int_constants:
label = f"{INT_CONST_PREFIX}{len(self.int_constants)}"
self.int_constants[value] = IntConstant(label=label, value=value)
case AST.String(content=value):
if value not in self.string_constants:
label = f"{STRING_CONST_PREFIX}{len(self.string_constants)}"
self.string_constants[value] = StringConstant(
label=label, value=value, length=len(value)
)
case AST.Block(expr_list=exprs):
for e in exprs:
self._collect_constants_from_expr(e)
case AST.If(predicate=pred, then_body=then_expr, else_body=else_expr):
self._collect_constants_from_expr(pred)
self._collect_constants_from_expr(then_expr)
self._collect_constants_from_expr(else_expr)
case AST.WhileLoop(predicate=pred, body=body):
self._collect_constants_from_expr(pred)
self._collect_constants_from_expr(body)
case AST.Let(init_expr=init, body=body):
if init is not None:
self._collect_constants_from_expr(init)
self._collect_constants_from_expr(body)
case AST.Case(expr=case_expr, actions=actions):
self._collect_constants_from_expr(case_expr)
for action in actions:
self._collect_constants_from_expr(action.body)
case AST.DynamicDispatch(instance=obj, arguments=args):
self._collect_constants_from_expr(obj)
if args:
for arg in args:
self._collect_constants_from_expr(arg)
case AST.StaticDispatch(instance=obj, arguments=args):
self._collect_constants_from_expr(obj)
if args:
for arg in args:
self._collect_constants_from_expr(arg)
case AST.Assignment(expr=value):
self._collect_constants_from_expr(value)
case AST.NewObject():
pass
case AST.IsVoid(expr=inner):
self._collect_constants_from_expr(inner)
case AST.IntegerComplement(integer_expr=operand):
self._collect_constants_from_expr(operand)
case AST.BooleanComplement(boolean_expr=operand):
self._collect_constants_from_expr(operand)
case AST.Addition(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case AST.Subtraction(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case AST.Multiplication(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case AST.Division(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case AST.LessThan(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case AST.LessThanOrEqual(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case AST.Equal(first=left, second=right):
self._collect_constants_from_expr(left)
self._collect_constants_from_expr(right)
case _:
# Boolean, Self, Object, etc. - no nested expressions
pass
def generate_to_file(self, program: AST.Program, output_file: TextIO) -> None:
"""Generate MIPS assembly to a file."""
code = self.generate(program)
output_file.write(code)
# =========================================================================
# CLASS INFO BUILDING
# =========================================================================
def _build_class_info(self) -> None:
"""Build class information for all classes."""
if self.program is None:
return
# Assign class tags in inheritance order
# Object = 0, then children in DFS order
self._assign_class_tags()
# Build info for each class
for klass in self.program.classes:
self._build_single_class_info(klass)
def _assign_class_tags(self) -> None:
"""Assign unique tags to each class."""
# Built-in classes get fixed tags
self.class_tags = {
OBJECT_CLASS: 0,
IO_CLASS: 1,
INTEGER_CLASS: 2,
BOOLEAN_CLASS: 3,
STRING_CLASS: 4,
}
next_tag = 5
if self.program is None:
return
for klass in self.program.classes:
if klass.name not in self.class_tags:
self.class_tags[klass.name] = next_tag
next_tag += 1
def _build_single_class_info(self, klass: AST.Class) -> None:
"""Build info for a single class."""
# Collect all attributes including inherited
attrs = self._collect_attributes(klass.name)
# Collect all methods including inherited
methods = self._collect_methods(klass.name)
# Calculate object size
size = OBJECT_HEADER_SIZE + len(attrs) * WORD_SIZE
self.class_info[klass.name] = ClassInfo(
name=klass.name,
tag=self.class_tags[klass.name],
size=size,
parent=klass.parent,
attributes=attrs,
methods=methods,
)
def _collect_attributes(self, class_name: str) -> list[tuple[str, str]]:
"""Collect all attributes for a class, including inherited ones."""
attrs: list[tuple[str, str]] = []
# Get inheritance chain (child to Object)
chain = self.analyzer.get_ancestors(class_name)
# Process from Object down to child
for ancestor_name in reversed(chain):
klass = self.analyzer._classes_map.get(ancestor_name)
if klass is None:
continue
for feature in klass.features:
if isinstance(feature, AST.ClassAttribute):
attrs.append((feature.name, feature.attr_type))
return attrs
def _collect_methods(self, class_name: str) -> list[tuple[str, str]]:
"""
Collect all methods for a class in dispatch table order.
Returns (method_name, defining_class) pairs.
"""
methods: list[tuple[str, str]] = []
method_names_seen: set[str] = set()
# Get inheritance chain (child to Object)
chain = self.analyzer.get_ancestors(class_name)
# Process from Object down to child
for ancestor_name in reversed(chain):
klass = self.analyzer._classes_map.get(ancestor_name)
if klass is None:
continue
for feature in klass.features:
if isinstance(feature, AST.ClassMethod):
if feature.name not in method_names_seen:
# New method
methods.append((feature.name, ancestor_name))
method_names_seen.add(feature.name)
else:
# Override - update defining class
for i, (name, _) in enumerate(methods):
if name == feature.name:
methods[i] = (feature.name, ancestor_name)
break
return methods
# =========================================================================
# LABEL GENERATION
# =========================================================================
def _new_label(self, prefix: str = "label") -> str:
"""Generate a unique label."""
self._label_counter += 1
return f"_{prefix}_{self._label_counter}"
# =========================================================================
# OUTPUT HELPERS
# =========================================================================
def _emit(self, line: str) -> None:
"""Emit a line of assembly."""
self._output.append(line)
def _emit_label(self, label: str) -> None:
"""Emit a label."""
self._emit(f"{label}:")
def _emit_comment(self, comment: str) -> None:
"""Emit a comment."""
self._emit(f"# {comment}")
def _emit_blank(self) -> None:
"""Emit a blank line."""
self._emit("")
def _emit_instr(self, op: str, *args: str) -> None:
"""Emit an instruction."""
if args:
self._emit(f" {op} {', '.join(args)}")
else:
self._emit(f" {op}")
# =========================================================================
# DATA SEGMENT
# =========================================================================
def _emit_data_segment(self) -> None:
"""Emit the .data segment with class objects and constants."""
self._emit(".data")
self._emit_blank()
# Emit class name strings
self._emit_comment("Class name strings")
self._emit_class_name_strings()
self._emit_blank()
# Emit class dispatch tables
self._emit_comment("Dispatch tables")
self._emit_dispatch_tables()
self._emit_blank()
# Emit prototype objects
self._emit_comment("Prototype objects")
self._emit_prototype_objects()
self._emit_blank()
# Emit string constants
self._emit_comment("String constants")
self._emit_string_constants()
self._emit_blank()
# Emit integer constants
self._emit_comment("Integer constants")
self._emit_int_constants()
self._emit_blank()
# Emit boolean constants
self._emit_comment("Boolean constants")
self._emit_bool_constants()
self._emit_blank()
# Heap pointer
self._emit_comment("Heap management")
self._emit("_heap_start:")
self._emit(" .word 0")
self._emit_blank()
def _emit_class_name_strings(self) -> None:
"""Emit string constants for class names (for type_name)."""
# Emit String objects for each class name
for class_name, _info in self.class_info.items():
name_len = len(class_name)
self._emit_label(f"_class_name_{class_name}")
self._emit(f" .word {self.class_tags[STRING_CLASS]}") # String tag
self._emit(f" .word {OBJECT_HEADER_SIZE + WORD_SIZE + name_len + 1}") # Size
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{STRING_CLASS}") # Dispatch
self._emit(f" .word {name_len}") # Length
self._emit(f' .asciiz "{class_name}"')
self._emit(" .align 2")
# Emit lookup table: class_tag -> class_name_string
self._emit_label("_class_name_table")
# Emit in tag order (0 = Object, 1 = IO, 2 = Int, 3 = Bool, 4 = String, then user classes)
sorted_classes = sorted(self.class_info.items(), key=lambda x: x[1].tag)
for class_name, _info in sorted_classes:
self._emit(f" .word _class_name_{class_name}")
def _emit_dispatch_tables(self) -> None:
"""Emit dispatch tables for all classes."""
for class_name, info in self.class_info.items():
self._emit_label(f"{CLASS_DISPTAB_PREFIX}{class_name}")
for method_name, defining_class in info.methods:
self._emit(f" .word {METHOD_PREFIX}{defining_class}_{method_name}")
def _emit_prototype_objects(self) -> None:
"""Emit prototype objects for object creation."""
for class_name, info in self.class_info.items():
self._emit_label(f"{CLASS_PROTOBJ_PREFIX}{class_name}")
self._emit(f" .word {info.tag}") # Class tag
self._emit(f" .word {info.size}") # Object size
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{class_name}") # Dispatch table
# Attribute slots (initialized to 0/void)
for attr_name, attr_type in info.attributes:
if attr_type in (INTEGER_CLASS, BOOLEAN_CLASS):
self._emit(f" .word 0 # {attr_name}")
elif attr_type == STRING_CLASS:
self._emit(f" .word _str_const_empty # {attr_name}")
else:
self._emit(f" .word 0 # {attr_name} (void)")
def _emit_string_constants(self) -> None:
"""Emit string constants."""
# Always emit empty string
self._emit("_str_const_empty:")
self._emit(f" .word {self.class_tags[STRING_CLASS]}") # Class tag
self._emit(f" .word {OBJECT_HEADER_SIZE + WORD_SIZE}") # Size
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{STRING_CLASS}") # Dispatch
self._emit(" .word 0") # Length
self._emit(' .asciiz ""')
self._emit(" .align 2")
# Emit collected string constants
for value, const in self.string_constants.items():
self._emit_label(const.label)
self._emit(f" .word {self.class_tags[STRING_CLASS]}")
self._emit(f" .word {OBJECT_HEADER_SIZE + 2 * WORD_SIZE}")
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{STRING_CLASS}")
self._emit(f" .word {const.length}")
# Escape the string for MIPS/SPIM
# SPIM doesn't interpret \\ as escaped backslash - it outputs literally
# So we only escape quotes, newlines, and tabs
# For backslashes, we use .byte directives for problematic cases
if "\\" in value and (value.endswith("\\") or '\\"' in value):
# Use .byte for strings with problematic backslash positions
self._emit_string_as_bytes(value)
else:
escaped = value.replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t")
self._emit(f' .asciiz "{escaped}"')
self._emit(" .align 2")
def _emit_string_as_bytes(self, value: str) -> None:
"""Emit a string using .byte directives for problematic escape sequences."""
bytes_list = [str(ord(c)) for c in value]
bytes_list.append("0") # Null terminator
# Emit in chunks of 16 bytes per line
for i in range(0, len(bytes_list), 16):
chunk = bytes_list[i : i + 16]
self._emit(f" .byte {', '.join(chunk)}")
def _emit_int_constants(self) -> None:
"""Emit integer constants."""
for value, const in self.int_constants.items():
self._emit_label(const.label)
self._emit(f" .word {self.class_tags[INTEGER_CLASS]}")
self._emit(f" .word {OBJECT_HEADER_SIZE + WORD_SIZE}")
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{INTEGER_CLASS}")
self._emit(f" .word {value}")
def _emit_bool_constants(self) -> None:
"""Emit boolean constants (true and false)."""
# False
self._emit("_bool_const_false:")
self._emit(f" .word {self.class_tags[BOOLEAN_CLASS]}")
self._emit(f" .word {OBJECT_HEADER_SIZE + WORD_SIZE}")
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{BOOLEAN_CLASS}")
self._emit(" .word 0")
# True
self._emit("_bool_const_true:")
self._emit(f" .word {self.class_tags[BOOLEAN_CLASS]}")
self._emit(f" .word {OBJECT_HEADER_SIZE + WORD_SIZE}")
self._emit(f" .word {CLASS_DISPTAB_PREFIX}{BOOLEAN_CLASS}")
self._emit(" .word 1")
# =========================================================================
# TEXT SEGMENT
# =========================================================================
def _emit_text_segment(self) -> None:
"""Emit the .text segment with all code."""
self._emit(".text")
self._emit_blank()
# Entry point
self._emit_entry_point()
self._emit_blank()
# Runtime support routines
self._emit_runtime_support()
self._emit_blank()
# Built-in methods
self._emit_builtin_methods()
self._emit_blank()
# Class initializers
self._emit_class_initializers()
self._emit_blank()
# User-defined methods
self._emit_user_methods()
def _emit_entry_point(self) -> None:
"""Emit the program entry point."""
self._emit_comment("Program entry point")
self._emit(".globl main")
self._emit_label("main")
# Set up heap
self._emit_instr("la", "$t0", "_heap_start")
self._emit_instr("sw", "$gp", "0($t0)")
# Create Main object
self._emit_instr("la", "$a0", f"{CLASS_PROTOBJ_PREFIX}Main")
self._emit_instr("jal", "_Object_copy")
# Initialize Main object
self._emit_instr("jal", f"{CLASS_INIT_PREFIX}Main")
# Call main method
self._emit_instr("jal", f"{METHOD_PREFIX}Main_main")
# Exit
self._emit_instr("li", "$v0", "10")
self._emit_instr("syscall")
def _emit_runtime_support(self) -> None:
"""Emit runtime support routines."""
self._emit_comment("Runtime support routines")
# Object.copy - allocate and copy an object
self._emit_label("_Object_copy")
# $a0 = prototype object pointer
# Returns new object in $a0
# Get object size
self._emit_instr("lw", "$t0", "4($a0)") # Size is at offset 4
# Allocate memory (using sbrk syscall)
self._emit_instr("move", "$t1", "$a0") # Save prototype pointer
self._emit_instr("move", "$a0", "$t0") # Size to allocate
self._emit_instr("li", "$v0", "9") # sbrk syscall
self._emit_instr("syscall")
# $v0 now has new object address
# Copy prototype to new object
self._emit_instr("move", "$t2", "$v0") # New object pointer
self._emit_instr("lw", "$t3", "4($t1)") # Get size again
self._emit_label("_Object_copy_loop")
self._emit_instr("beqz", "$t3", "_Object_copy_done")
self._emit_instr("lw", "$t4", "0($t1)")
self._emit_instr("sw", "$t4", "0($t2)")
self._emit_instr("addiu", "$t1", "$t1", "4")
self._emit_instr("addiu", "$t2", "$t2", "4")
self._emit_instr("addiu", "$t3", "$t3", "-4")
self._emit_instr("j", "_Object_copy_loop")
self._emit_label("_Object_copy_done")
self._emit_instr("move", "$a0", "$v0")
self._emit_instr("jr", "$ra")
self._emit_blank()
# Equality comparison for objects
self._emit_label("_equality_test")
# $a0 = first object, $a1 = second object
# Returns boolean in $a0
self._emit_instr("beq", "$a0", "$a1", "_eq_true") # Same pointer
# Check if both are Int, Bool, or String for value comparison
self._emit_instr("beqz", "$a0", "_eq_false")
self._emit_instr("beqz", "$a1", "_eq_false")
self._emit_instr("lw", "$t0", "0($a0)") # Class tag of first
self._emit_instr("lw", "$t1", "0($a1)") # Class tag of second
self._emit_instr("bne", "$t0", "$t1", "_eq_false") # Different types
# Check if Int (tag 2) - compare values
self._emit_instr("li", "$t2", "2")
self._emit_instr("bne", "$t0", "$t2", "_eq_check_bool")
self._emit_instr("lw", "$t0", "12($a0)")
self._emit_instr("lw", "$t1", "12($a1)")
self._emit_instr("beq", "$t0", "$t1", "_eq_true")
self._emit_instr("j", "_eq_false")
# Check if Bool (tag 3) - compare values
self._emit_label("_eq_check_bool")
self._emit_instr("li", "$t2", "3")
self._emit_instr("bne", "$t0", "$t2", "_eq_check_string")
self._emit_instr("lw", "$t0", "12($a0)")
self._emit_instr("lw", "$t1", "12($a1)")
self._emit_instr("beq", "$t0", "$t1", "_eq_true")
self._emit_instr("j", "_eq_false")
# Check if String (tag 4) - compare contents
self._emit_label("_eq_check_string")
self._emit_instr("li", "$t2", "4")
self._emit_instr("bne", "$t0", "$t2", "_eq_false")
# String comparison - compare lengths first
self._emit_instr("lw", "$t0", "12($a0)") # Length of first
self._emit_instr("lw", "$t1", "12($a1)") # Length of second
self._emit_instr("bne", "$t0", "$t1", "_eq_false")
# Compare string contents byte by byte
# $t0 = length (same for both), $a0/$a1 = string objects
self._emit_instr("addiu", "$t2", "$a0", "16") # ptr to first string data
self._emit_instr("addiu", "$t3", "$a1", "16") # ptr to second string data
self._emit_label("_eq_string_loop")
self._emit_instr("beqz", "$t0", "_eq_true") # All bytes matched
self._emit_instr("lb", "$t4", "0($t2)")
self._emit_instr("lb", "$t5", "0($t3)")
self._emit_instr("bne", "$t4", "$t5", "_eq_false")
self._emit_instr("addiu", "$t2", "$t2", "1")
self._emit_instr("addiu", "$t3", "$t3", "1")
self._emit_instr("addiu", "$t0", "$t0", "-1")
self._emit_instr("j", "_eq_string_loop")
self._emit_label("_eq_true")
self._emit_instr("la", "$a0", "_bool_const_true")
self._emit_instr("jr", "$ra")
self._emit_label("_eq_false")
self._emit_instr("la", "$a0", "_bool_const_false")
self._emit_instr("jr", "$ra")
self._emit_blank()
# Dispatch on void error
self._emit_label("_dispatch_void")
self._emit_instr("la", "$a0", "_dispatch_void_msg")
self._emit_instr("li", "$v0", "4")
self._emit_instr("syscall")
self._emit_instr("li", "$v0", "10")
self._emit_instr("syscall")
self._emit(".data")
self._emit("_dispatch_void_msg:")
self._emit(' .asciiz "Error: Dispatch on void\\n"')
self._emit(".text")
self._emit_blank()
def _emit_builtin_methods(self) -> None:
"""Emit built-in methods for Object, IO, String, Int, Bool."""
self._emit_comment("Built-in methods")
# Object.abort
self._emit_label(f"{METHOD_PREFIX}Object_abort")
self._emit_instr("li", "$v0", "10") # Exit syscall
self._emit_instr("syscall")
# Object.type_name - returns String with class name
self._emit_label(f"{METHOD_PREFIX}Object_type_name")
self._emit_instr("lw", "$t0", "0($a0)") # Get class tag
self._emit_instr("sll", "$t0", "$t0", "2") # Multiply by 4 (word size)
self._emit_instr("la", "$t1", "_class_name_table")
self._emit_instr("add", "$t0", "$t0", "$t1") # Address in table
self._emit_instr("lw", "$a0", "0($t0)") # Load String object pointer
self._emit_instr("jr", "$ra")
# Object.copy - already defined as _Object_copy
self._emit_label(f"{METHOD_PREFIX}Object_copy")
self._emit_instr("j", "_Object_copy")
# IO.out_string
self._emit_label(f"{METHOD_PREFIX}IO_out_string")
# $a0 = self, $a1 = string object
self._emit_instr("move", "$t0", "$a0") # Save self
self._emit_instr("addiu", "$a0", "$a1", "16") # String data starts at offset 16
self._emit_instr("li", "$v0", "4") # Print string syscall
self._emit_instr("syscall")
self._emit_instr("move", "$a0", "$t0") # Return self
self._emit_instr("jr", "$ra")
# IO.out_int
self._emit_label(f"{METHOD_PREFIX}IO_out_int")
# $a0 = self, $a1 = int object
self._emit_instr("move", "$t0", "$a0") # Save self
self._emit_instr("lw", "$a0", "12($a1)") # Get int value
self._emit_instr("li", "$v0", "1") # Print int syscall
self._emit_instr("syscall")
self._emit_instr("move", "$a0", "$t0") # Return self
self._emit_instr("jr", "$ra")
# IO.in_string
# String object layout: [tag, size, dispatch, length, ...chars..., null]
# We allocate a String object inline with the chars after it
self._emit_label(f"{METHOD_PREFIX}IO_in_string")
# Save $ra and self
self._emit_instr("addiu", "$sp", "$sp", "-16")
self._emit_instr("sw", "$ra", "12($sp)")
self._emit_instr("sw", "$a0", "8($sp)") # Save self
# Allocate buffer for input (1024 bytes)
self._emit_instr("li", "$a0", "1024")
self._emit_instr("li", "$v0", "9") # sbrk syscall
self._emit_instr("syscall")
self._emit_instr("sw", "$v0", "4($sp)") # Save buffer address
# Read string into buffer (syscall 8)
self._emit_instr("move", "$a0", "$v0") # Buffer address
self._emit_instr("li", "$a1", "1024") # Max length
self._emit_instr("li", "$v0", "8") # Read string syscall
self._emit_instr("syscall")
# Calculate string length (find null or newline)
self._emit_instr("lw", "$t0", "4($sp)") # Buffer address
self._emit_instr("move", "$t1", "$t0") # Current position
self._emit_instr("li", "$t2", "0") # Length counter
self._emit_label("_in_string_len_loop")
self._emit_instr("lb", "$t3", "0($t1)")
self._emit_instr("beqz", "$t3", "_in_string_len_done")
self._emit_instr("li", "$t4", "10") # Newline
self._emit_instr("beq", "$t3", "$t4", "_in_string_len_done")
self._emit_instr("addiu", "$t1", "$t1", "1")
self._emit_instr("addiu", "$t2", "$t2", "1")
self._emit_instr("j", "_in_string_len_loop")
self._emit_label("_in_string_len_done")
self._emit_instr("sb", "$zero", "0($t1)") # Null terminate
self._emit_instr("sw", "$t2", "0($sp)") # Save length
# Allocate String object: 16 bytes header + string + 1 null + padding
# Size = 16 (header) + length + 1, rounded up to 4
self._emit_instr("addiu", "$t2", "$t2", "20") # 16 + len + 1 + 3 for align
self._emit_instr("li", "$t3", "-4")
self._emit_instr("and", "$a0", "$t2", "$t3") # Round down to 4
self._emit_instr("li", "$v0", "9") # sbrk