-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMIPSCodeGeneratorVisitor.java
More file actions
836 lines (750 loc) · 30.4 KB
/
Copy pathMIPSCodeGeneratorVisitor.java
File metadata and controls
836 lines (750 loc) · 30.4 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
import a4out.myLanguageBaseVisitor;
import a4out.myLanguageParser;
import org.antlr.v4.runtime.tree.ParseTree;
import utilities.*;
import utilities.SymbolTable.Types;
import utilities.SymbolTable.VariableInfo;
/**
* Visitor class used for the traversal of the parse tree and generation of MIPS instructions. This class uses objects
* of the "classes" package for utilities as well as for writing to the files.
*/
@SuppressWarnings("SpellCheckingInspection")
public class MIPSCodeGeneratorVisitor extends myLanguageBaseVisitor<VariableInfo> {
private final ParseTree tree;
private final MIPSInstructionsHelper helper;
private final MIPSLabelTracker labels;
private final MIPSStackTracker stackTracker;
private final MIPSWriter writer;
private final SymbolTable symbolTable;
/**
* Passes the String argument to the MIPSWriter object constructor to specify the name of the .asm output file and
* initialises all other fields
*
* @param outputFileName desired file output name
*/
public MIPSCodeGeneratorVisitor(String outputFileName, ParseTree tree) {
super();
this.tree = tree;
helper = new MIPSInstructionsHelper();
labels = new MIPSLabelTracker();
stackTracker = new MIPSStackTracker();
writer = new MIPSWriter(outputFileName);
symbolTable = new SymbolTable();
}
public void start() {
// Create files
writer.initialiseFiles();
// Data initialisation
writer.appendData("_newLine: .asciiz \"\\n\"");
writer.appendData(MyLanguageNumbersHelper.getArithmeticErrorMessageDeclarations());
writer.appendData(stackTracker.getStackDeclarations());
writer.appendData(MyLanguageNumbersHelper.getPrimitiveConstraintDeclarations());
// One time initialisation instructions
writer.appendText(stackTracker.getStackInit());
writer.appendText("j main\n");
// Float exception code
writer.appendText(MyLanguageNumbersHelper.getNumericExceptionInstructions());
// Float underflow/overflow check subprogram
writer.appendText(MyLanguageNumbersHelper.getFloatExceptionCheckSubprogram());
// Int overflow subprogram
writer.appendText(MyLanguageNumbersHelper.getIntOverflowCorrectionSubprogram());
// Program start
writer.appendText("\n\nmain:");
try {
visitProgram((myLanguageParser.ProgramContext) this.tree);
} catch (RuntimeException e) {
writer.abortAndCleanupInitializedFiles();
throw e;
}
declareVariables(symbolTable);
// write program exit
write(helper.getProgramExit());
// create the final file
writer.mergeFiles();
}
/**
* Creates the .asm files, adds boilerplate instructions, visits children and merges the temporary files in the end
*/
@Override
public VariableInfo visitProgram(myLanguageParser.ProgramContext ctx) {
super.visitProgram(ctx);
return null;
}
/**
* Visits all statements
*
* @return null
*/
@Override
public VariableInfo visitComp_stmt(myLanguageParser.Comp_stmtContext ctx) {
for (int i = 1; i < ctx.getChildCount() - 1; i++) {
visit(ctx.getChild(i));
}
return null;
}
/**
* Checks the declaration type and inserts all the non-declared symbols into the symbol table. Throws exception in
* case of multiple declarations of the same id
*
* @return null, as it is a statement
*/
@SuppressWarnings("DuplicateBranchesInSwitch")
@Override
public VariableInfo visitDeclaration(myLanguageParser.DeclarationContext ctx) {
Types decType = switch (ctx.getChild(0).getText()) {
case "int" -> Types.INT;
case "float" -> Types.FLOAT;
default -> Types.INT;
};
// check all IDs
int i = 1; // index of first ID
while (ctx.getChild(i) != null) {
String id = ctx.getChild(i).getText();
if (symbolTable.get(id) == null) {
switch (decType) {
case INT:
symbolTable.insert(id, 0);
break;
case FLOAT:
symbolTable.insert(id, 0.0F);
}
} else {
var offendingToken = ctx.ID((i - 1) / 2).getSymbol();
int line = offendingToken.getLine(), column = offendingToken.getCharPositionInLine() + 1;
throw new RuntimeException("In %d,%d: Variable \"%s\" already defined".formatted(line, column, offendingToken.getText()));
}
i += 2; // skip the ','
}
return null;
}
/**
* Evaluates the parameter expression and calls the corresponding print instruction based on the static type of the
* argument. Prints a newline character at the end
*
* @return null, as it is a statement
*/
@Override
public VariableInfo visitPrintln_stmt(myLanguageParser.Println_stmtContext ctx) {
// Visit expr to evaluate
VariableInfo argumentInfo = visit(ctx.getChild(2));
// Generate appropriate print code
switch (argumentInfo.getType()) {
case INT:
write("li $v0 1");
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$a0"));
break;
case FLOAT:
write("li $v0 3");
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f12"));
break;
}
write("syscall");
// Print newline
write("li $v0, 4");
write("la $a0, _newLine");
write("syscall");
return null;
}
/**
* Visits the expression and resets the stacks at the end as assignment expression values can be left in the stack
*
* @return null, as it is a statement
*/
@Override
public VariableInfo visitAssign_stmt(myLanguageParser.Assign_stmtContext ctx) {
// visit first assign expression
visit(ctx.getChild(0));
// reset stacks in the event a value was not used
stackTracker.resetIntStack();
write(helper.resetIntStack());
stackTracker.resetFloatStack();
write(helper.resetFloatStack());
return null;
}
/**
* Behaves like an assign statement
*
* @return null
*/
@Override
public VariableInfo visitOpassign_expr(myLanguageParser.Opassign_exprContext ctx) {
super.visitOpassign_expr(ctx);
write(helper.resetIntStack());
write(helper.resetFloatStack());
return null;
}
/**
* Checks for declaration of the ID and evaluates the right hand expression. Preforms necessary widening or narrowing
* of the value and stores it into the variable
*
* @return static type of the expression
*/
@Override
public VariableInfo visitAssign_expr(myLanguageParser.Assign_exprContext ctx) {
String id = ctx.getChild(0).getText();
// check if variable has been declared
VariableInfo var1 = symbolTable.get(id);
if (var1 == null) {
var offendingToken = ctx.ID().getSymbol();
int line = offendingToken.getLine(), column = offendingToken.getCharPositionInLine() + 1;
throw new RuntimeException("In %d,%d: Variable \"%s\" referenced but not previously defined".formatted(line, column, id));
}
// evaluate right hand expression and get its type
VariableInfo exprInfo = visit(ctx.getChild(2));
switch (var1.getType()) {
case INT:
// Load the expr value from stack and convert if necessary
switch (exprInfo.getType()) {
case INT:
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$t0"));
break;
case FLOAT:
// get float value
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f4"));
// convert to int
write(helper.floatToInt("$f4", "$f4"));
write("mfc1.d $t0, $f4");
}
// check for overflow
write("move $a0, $t0");
write("jal _intOverflowCheck");
write("move $t0, $v0");
// store the value in the variable
write("sw $t0, " + id);
stackTracker.registerIntStackPush();
// push expression value to the stack
write(helper.pushIntStack("$t0"));
break;
case FLOAT:
switch (exprInfo.getType()) {
case INT:
// load int from stack
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$t0"));
// convert to "float"
write("mtc1.d $t0, $f4");
write(helper.intToFloat("$f4", "$f4"));
break;
case FLOAT:
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f4"));
}
// store value in variable
write("s.d $f4, " + id);
// push expression value to the stack
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f4"));
break;
}
// return the expression type (variable type)
return var1;
}
/**
* Evaluates left and right expressions and converts them to the wider type if conversion is possible, then preforms
* comparison and stores the result in the boolean stack
*
* @return integer type
*/
@Override
public VariableInfo visitBool_expr(myLanguageParser.Bool_exprContext ctx) {
VariableInfo var1 = visit(ctx.getChild(0));
VariableInfo var2 = visit(ctx.getChild(2));
Types prevalentType = Types.getWiderType(var1.getType(), var2.getType());
convertVariablesAndStore(var1.getType(), var2.getType());
String c_op = ctx.getChild(1).getText();
String branchInstruction;
labels.pushNextAfterIf();
switch (prevalentType) {
case INT: // both operands are of int type
branchInstruction = MIPSInstructionsHelper.intBranches.get(c_op);
branchInstruction += String.format(" $t0, $t1, %s", labels.getElse());
break;
case FLOAT: // at least one is float
branchInstruction = switch (c_op) {
case "==" -> {
write("c.eq.d $f4, $f6");
yield "bc1f " + labels.getElse();
}
case "<" -> {
write("c.lt.d $f4, $f6");
yield "bc1f " + labels.getElse();
}
case "<=" -> {
write("c.le.d $f4, $f6");
yield "bc1f " + labels.getElse();
}
case ">" -> {
write("c.le.d $f4, $f6");
yield "bc1t " + labels.getElse();
}
case ">=" -> {
write("c.lt.d $f4, $f6");
yield "bc1t " + labels.getElse();
}
case "!=" -> {
write("c.eq.d $f4, $f6");
yield "bc1t " + labels.getElse();
}
default -> "";
};
break;
default:
branchInstruction = "";
}
write(branchInstruction);
// Depending on the result of the comparison, store 1 or 0 to the boolean stack
// (if instructions part) push 1 to bool stack
write("li $t3, 1");
stackTracker.registerBoolStackPush();
write(helper.pushBoolStack("$t3"));
// exit if
write("j " + labels.getAfterIf());
// else label
write(labels.getElseLabel());
// (else instructions part) push 0 to bool stack
write(helper.pushBoolStack("$zero"));
// afterIf label
write(labels.getAfterIfLabel());
labels.popAfterIf();
return new VariableInfo(1);
}
/**
* Executed when "for" boolean expression is omitted. Evaluates to true
*
* @return int type
*/
@Override
public VariableInfo visitOpBoolAbsent(myLanguageParser.OpBoolAbsentContext ctx) {
// push positive value to the bool stack
write("li $t0, 1");
stackTracker.registerBoolStackPush();
write(helper.pushBoolStack("$t0"));
return new VariableInfo(1);
}
/**
* Evaluates boolean expression and adds code for the branch statement. Then, visits child statements and appends the
* rest of the required labels
*
* @return null, as it is a statement
*/
@Override
public VariableInfo visitPlainIf(myLanguageParser.PlainIfContext ctx) {
// evaluate bool expr
visit(ctx.getChild(2));
// write branch condition
labels.pushNextAfterIf();
stackTracker.registerBoolStackPop();
write(helper.getBoolStackTopAndPop("$t0"));
write(String.format("beq $t0, 0, %s", labels.getAfterIf()));
// visit statements
visit(ctx.getChild(4));
// close if statement
write(labels.getAfterIfLabel());
labels.popAfterIf();
return null;
}
/**
* Similar to the plain "if" visitor, but appends else label and instructions in between
*
* @return null, as it is a statement
*/
@Override
public VariableInfo visitIfElse(myLanguageParser.IfElseContext ctx) {
// evaluate bool expr
visit(ctx.getChild(2));
labels.pushNextAfterIf();
// write branch condition
stackTracker.registerBoolStackPop();
write(helper.getBoolStackTopAndPop("$t0"));
write(String.format("beq $t0, 0, %s", labels.getElse()));
// visit if statements
visit(ctx.getChild(4));
// jump to afterIf
write("j " + labels.getAfterIf());
// else label
write(labels.getElseLabel());
// else statements
visit(ctx.getChild(6));
// afterIf label
write(labels.getAfterIfLabel());
labels.popAfterIf();
return null;
}
/**
* Evaluates boolean expression and writes the while labels and branch instruction, visits statements and appends
* loop jump instruction and exit loop label.
*
* @return null, as it is a statement
*/
@Override
public VariableInfo visitWhile_stmt(myLanguageParser.While_stmtContext ctx) {
// write while label
labels.pushNextWhile();
write(labels.getWhileLabel());
// evaluate boolean expression
visit(ctx.getChild(2));
// write branch condition
stackTracker.registerBoolStackPop();
write(helper.getBoolStackTopAndPop("$t0"));
write("beq $t0, 0, " + labels.getAfterWhile());
// visit while statements
visit(ctx.getChild(4));
// write loop jump
write("j " + labels.getWhile());
// write while exit label
write(labels.getAfterWhileLabel());
labels.popWhile();
return null;
}
/**
* For statement is treated as a while statement with an added assignment before it and a statement being executed
* before the jump to complete the loop.
*
* @return null, as it is a statement
*/
@Override
public VariableInfo visitFor_stmt(myLanguageParser.For_stmtContext ctx) {
// visit declaration first
visit(ctx.getChild(2));
// write while label
labels.pushNextWhile();
write(labels.getWhileLabel());
// evaluate boolean expression
visit(ctx.getChild(4));
// write branch condition
stackTracker.registerBoolStackPop();
write(helper.getBoolStackTopAndPop("$t0"));
write("beq $t0, 0, " + labels.getAfterWhile());
// visit while statements
visit(ctx.getChild(8));
// visit third statement in the parentheses
visit(ctx.getChild(6));
// write loop jump
write("j " + labels.getWhile());
// write while exit label
write(labels.getAfterWhileLabel());
labels.popWhile();
return null;
}
/**
* Evaluates left and right expressions and converts them to the wider type if conversion is possible, then preforms
* addition and stores the result in the appropriate stack
*
* @return Static type of the expression
*/
@Override
public VariableInfo visitRvalPlus(myLanguageParser.RvalPlusContext ctx) {
// visit operand expressions and get their type
VariableInfo var1 = visit(ctx.getChild(0));
VariableInfo var2 = visit(ctx.getChild(2));
Types resultType = Types.getWiderType(var1.getType(), var2.getType());
convertVariablesAndStore(var1.getType(), var2.getType());
switch (resultType) {
case INT: // both values are int type
// preform integer addition and push to int stack
write("add $t0, $t0, $t1");
stackTracker.registerIntStackPush();
write(helper.pushIntStack("$t0"));
break;
case FLOAT: // at least one is float
// preform floating point addition
write("add.d $f4, $f4, $f6");
// save value
write("mov.d $f20, $f4");
// check for float overflow/underflow
write("mfc1.d $a0, $f20");
write("jal _floatOverflowCheck");
// push to stack
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f20"));
}
return resultType == Types.INT ? new VariableInfo(1) : new VariableInfo(1.5F);
}
/**
* Evaluates left and right expressions and converts them to the wider type if conversion is possible, then preforms
* subtraction and stores the result in the appropriate stack
*
* @return Static type of the expression
*/
@Override
public VariableInfo visitRvalMinus(myLanguageParser.RvalMinusContext ctx) {
// visit operand expressions and get their type
VariableInfo var1 = visit(ctx.getChild(0));
VariableInfo var2 = visit(ctx.getChild(2));
Types resultType = Types.getWiderType(var1.getType(), var2.getType());
convertVariablesAndStore(var1.getType(), var2.getType());
switch (resultType) {
case INT: // both values are int type
// preform integer subtraction
write("sub $t0, $t0, $t1");
stackTracker.registerIntStackPush();
write(helper.pushIntStack("$t0"));
break;
case FLOAT: // at least one is float
// preform floating point subtraction
write("sub.d $f4, $f4, $f6");
// save value
write("mov.d $f20, $f4");
// check for float overflow/underflow
write("mfc1.d $a0, $f20");
write("jal _floatOverflowCheck");
// push to stack
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f20"));
break;
}
return resultType == Types.INT ? new VariableInfo(1) : new VariableInfo(1.5F);
}
/**
* Evaluates left and right expressions and converts them to the wider type if conversion is possible, then preforms
* multiplication and stores the result in the appropriate stack
*
* @return Static type of the expression
*/
@Override
public VariableInfo visitTermMultFactor(myLanguageParser.TermMultFactorContext ctx) {
// visit operand expressions and get their type
VariableInfo var1 = visit(ctx.getChild(0));
VariableInfo var2 = visit(ctx.getChild(2));
Types resultType = Types.getWiderType(var1.getType(), var2.getType());
convertVariablesAndStore(var1.getType(), var2.getType());
switch (resultType) {
case INT: // both values are of int type
// preform int multiplication
write("mult $t0, $t1");
write("mflo $t0");
// push result to int stack
stackTracker.registerIntStackPush();
write(helper.pushIntStack("$t0"));
break;
case FLOAT: // at least one operand is of float type
// preform floating point multiplication and push to float stack
write("mul.d $f4, $f4, $f6");
// save value
write("mov.d $f20, $f4");
// check for float overflow/underflow
write("mfc1.d $a0, $f20");
write("jal _floatOverflowCheck");
// push to float stack
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f20"));
break;
}
return resultType == Types.INT ? new VariableInfo(1) : new VariableInfo(1.5F);
}
/**
* Evaluates left and right expressions and converts them to the wider type if conversion is possible, then preforms
* division and stores the result in the appropriate stack
*
* @return Static type of the expression
*/
@Override
public VariableInfo visitTermDivFactor(myLanguageParser.TermDivFactorContext ctx) {
// visit operand expressions and get their type
VariableInfo var1 = visit(ctx.getChild(0));
VariableInfo var2 = visit(ctx.getChild(2));
Types resultType = Types.getWiderType(var1.getType(), var2.getType());
convertVariablesAndStore(var1.getType(), var2.getType());
switch (resultType) {
case INT: // both operands are of int type
// check for division by zero
write("beq $zero, $t1, _divByZero");
// preform integer division and push to int stack
write("div $t0, $t1");
write("mflo $t0");
stackTracker.registerIntStackPush();
write(helper.pushIntStack("$t0"));
break;
case FLOAT: // at least one operand is of float type
// check for division by zero
write("""
mtc1 $zero, $f8
cvt.d.w $f8, $f8
c.eq.d $f6, $f8
bc1t _divByZero""");
// preform floating point division
write("div.d $f4, $f4, $f6");
// save value
write("mov.d $f20, $f4");
// check for float overflow/underflow
write("mfc1.d $a0, $f20");
write("jal _floatOverflowCheck");
// push to float stack
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f20"));
}
// return static type of the expression
return resultType == Types.INT ? new VariableInfo(1) : new VariableInfo(1.5F);
}
/**
* Visits expression within the parentheses
*
* @return static type of the expression
*/
@Override
public VariableInfo visitFactorExpr(myLanguageParser.FactorExprContext ctx) {
return visit(ctx.getChild(1));
}
/**
* Negates the value of the last expression depending on argument type and pushes it to the stack
*
* @return static type of the expression
*/
@Override
public VariableInfo visitFactorNegative(myLanguageParser.FactorNegativeContext ctx) {
// visit expression and get its type
VariableInfo var1 = visit(ctx.getChild(1));
// negate depending on type
switch (var1.getType()) {
case INT:
// get operand from int stack
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$t0"));
// negate
write("subu $t0, $zero, $t0");
stackTracker.registerIntStackPush();
// push result to stack
write(helper.pushIntStack("$t0"));
break;
case FLOAT:
// get operand from float stack
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f4"));
// negate
write("neg.d $f4, $f4");
// push to float stack
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f4"));
}
// return type of the expression
return var1;
}
/**
* Checks the symbol table for declaration of the id and pushes its value to the appropriate stack depending on
* its type
*
* @return VariableInfo object of the variable corresponding to the ID
*/
@Override
public VariableInfo visitFactorID(myLanguageParser.FactorIDContext ctx) {
String id = ctx.getText();
if (symbolTable.get(id) == null) {
var offendingToken = ctx.getStart();
int line = offendingToken.getLine(), column = offendingToken.getCharPositionInLine() + 1;
throw new RuntimeException("In %d,%d: Variable \"%s\" referenced but not previously defined".formatted(line, column, id));
}
VariableInfo info = symbolTable.get(id);
// Load value and push to appropriate stack
switch (info.getType()) {
case INT:
write("lw $t0, " + id);
stackTracker.registerIntStackPush();
write(helper.pushIntStack("$t0"));
break;
case FLOAT:
write("l.d $f4, " + id);
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f4"));
}
return info;
}
/**
* Generates MIPS load immediate code for the int literal, pushes it to the int stack and returns the expression's
* static type (INT)
*
* @return VariableInfo object containing the Types.INT type
*/
@Override
public VariableInfo visitFactorInt(myLanguageParser.FactorIntContext ctx) {
// load immediate int literal and push to int stack
write("li $t0, " + ctx.getText());
stackTracker.registerIntStackPush();
write(helper.pushIntStack("$t0"));
return new VariableInfo(Integer.parseInt(ctx.getText()));
}
/**
* Generates MIPS declaration code for the float literal, pushes it to the float stack and returns the expression's
* static type (FLOAT)
*
* @return VariableInfo object containing the Types.FLOAT type
*/
@Override
public VariableInfo visitFactorFloat(myLanguageParser.FactorFloatContext ctx) {
// declare new float literal
writer.appendData(labels.getNextFloatLiteralDeclaration(ctx.getText()));
// load float value and push to flaot stack
write("l.d $f4, " + labels.getCurrentFloatLiteral());
stackTracker.registerFloatStackPush();
write(helper.pushFloatStack("$f4"));
return new VariableInfo(Float.parseFloat(ctx.getText()));
}
/**
* Utility method that reuses code for when two number operands are involved. Depending on the types of the arguments,
* the method writes code for popping from the appropriate stack and storing in the appropriate registers for the
* values to be used immediately afterward. Any necessary conversions are preformed and the values are stored in
* $t0 and $t1 for the case of two integer values and $f4 and $f6 otherwise
*
* @param t1 Static type of operand 1
* @param t2 Static type of operand 2
*/
private void convertVariablesAndStore(Types t1, Types t2) {
if (t1 == Types.INT && t2 == Types.INT) {
stackTracker.registerIntStackPop();
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$t1")); // op2
write(helper.getIntStackTopAndPop("$t0")); // op1
} else if (t1 == Types.INT) {
// op1 is int, convert and store
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$t0"));
write("mtc1 $t0, $f4");
write(helper.intToFloat("$f4", "$f4"));
// op2 is float, store immediately
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f6"));
} else if (t2 == Types.INT) {
// op1 is float, store immediately
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f4"));
// op2 is int, convert and store
stackTracker.registerIntStackPop();
write(helper.getIntStackTopAndPop("$t0"));
write("mtc1 $t0, $f6");
write(helper.intToFloat("$f6", "$f6"));
} else { // both are of type float
stackTracker.registerFloatStackPop();
stackTracker.registerFloatStackPop();
write(helper.getFloatStackTopAndPop("$f6")); // op2
write(helper.getFloatStackTopAndPop("$f4")); // op1
}
}
/**
* Alias for calling the writer.appendText() method in order to reduce line width
*
* @param s String of instruction to be appended to the text temp file (no newline)
*/
private void write(String s) {
writer.appendText(s);
}
/**
* Declares every variable in the symbol table at the data section. Type and value are recovered from the symbol table
*
* @param table symbolTable from which declarations are to be imported
*/
public void declareVariables(SymbolTable table) {
for (String id : table.getIDs()) {
VariableInfo info = table.get(id);
switch (info.getType()) {
case INT:
writer.appendData(String.format("%s: .align 2\n.word %d", id, info.getIntVal()));
break;
case FLOAT:
writer.appendData(String.format("%s: .align 3\n.double %f", id, info.getFloatVal()));
}
}
}
}