Repository navigation
Expand file tree
/
Copy pathSemanticAnalyzer.java
More file actions
506 lines (422 loc) · 15.8 KB
/
Copy pathSemanticAnalyzer.java
File metadata and controls
506 lines (422 loc) · 15.8 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
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Map.Entry;
import absyn.*;
import symbol.FunctionNode;
import symbol.Log;
import symbol.NodeType;
import symbol.Scope;
import symbol.TypeChecker;
import symbol.TypeComparable;
import symbol.Log;
public class SemanticAnalyzer implements AbsynVisitor {
/**
* A reference to keep track of the current scope of variables as a tree structure.
* Also keep a reference to the global scope just in case.
*/
private Scope scope, globalScope;
private boolean newScope = true;
private FunctionDec currentFunction;
public static boolean VERBOSE = false;
private int tcount = 0;
private boolean definedMain = false;
public SemanticAnalyzer() {
globalScope = new Scope(0, "global");
scope = globalScope; // Mark current scope as the global
// Define bult in functions "input" and "output"
List<VarDec> outputParams = new List<VarDec>(new SimpleDec(CMType.INT, "a"));
FunctionDec output = FunctionDec.defineBuiltIn(CMType.VOID, "output", outputParams);
// output.setTemp(temp());
// scope.declare(output);
output.accept(this, 0, false);
FunctionDec input = FunctionDec.defineBuiltIn(CMType.INT, "input", new List<VarDec>());
// input.setTemp(temp());
// scope.declare(input);
input.accept(this, 0, false);
}
private String temp() {
return "t" + (tcount++);
}
public Scope getGlobalScope() {
return globalScope;
}
@Override
public void visit(FunctionDec dec, int level, boolean isAddr) {
if (dec.isPrototype()) {
if (!scope.declare(dec)) {
Log.error(dec, "Already declared function with name. Ignoring prototype for", dec.getName());
}
return;
}
if (scope.hasVariable(dec.getName())) {
NodeType existing = scope.findVariable(dec.getName());
if (!(existing instanceof FunctionNode)) {
Log.error(existing.getDef(), "Already decared variable as function. Ignoring", dec);
} else if (!((FunctionDec)existing.getDef()).isPrototype()) {
Log.error(dec, "Function with name alreay exists. Ignoring function for", dec.getName());
} else {
boolean sigMatch = true;
List<VarDec> params0 = ((FunctionDec)existing.getDef()).getParams(), params1 = dec.getParams();
Iterator<VarDec> iter0 = params0.iterator(), iter1 = params1.iterator();
int count0 = params0.count(), count1 = params1.count();
if (count0 != count1) {
String message = String.format(
"Mismatch parameter count for function \"%s\". Expected %d, received %d",
dec.getName(), count0, count1
);
Log.error(dec, message);
sigMatch = false;
}
int count = Math.min(count0, count1);
for (int i = 0; i < count; ++i) {
VarDec var0 = iter0.next();
VarDec var1 = iter1.next();
// Types for the parameters did not match
if (!var0.sameSignature(var1)) {
String message = String.format(
"Parameter missmatch for function \"%s\". Expected \"%s\" received \"%s\"",
dec.getName(), var0.signature(), var1.signature()
);
Log.error(var1, message);
sigMatch = false;
}
}
if (dec.getExpectedType() != existing.getType()) {
String message = String.format(
"Return type for function \"%s\" does not match prototype. Expected \"%s\" received \"%s\"",
dec.getName(), CMType.toString(existing), CMType.toString(dec)
);
sigMatch = false;
Log.error(dec, message);
}
if (sigMatch) {
scope.replace(dec);
} else if (VERBOSE) { // signatures don't match and verbose setting is on
String message = String.format(
"Mismatch function signatures. Expected \"%s\" but received \"%s\"",
((FunctionDec)existing.getDef()).getSignature(),
dec.getSignature()
);
Log.error(dec, message);
}
}
} else {
scope.declare(dec); // Declare in (assuming global) scope
scope.findVariable(dec.getName()).setTemp(temp());
}
scope = scope.stepIn("function " + dec.getName());
currentFunction = dec;
if (dec.getName().equals("main")) {
definedMain = true;
}
// scope.declare(dec); // Declare self for recursion
dec.getParams().accept(this, ++level, isAddr); // Will declare params
// Will be stepping into a compound expression,
// but make sure NOT to open a new scope.
newScope = false;
dec.getBody().accept(this, level, isAddr);
newScope = true; // Failsafe
scope = scope.stepOut();
}
@Override
public void visit(SimpleDec dec, int level, boolean isAddr) {
if (!scope.declare(dec)) {
Log.error(dec, "Already declared variabe in current scope with name", dec.getName());
} else if (dec.getType().getType() == CMType.VOID) {
Log.error(dec, "Cannot declare variable with type", "void");
} else {
NodeType var = scope.findVariable(dec.getName());
var.setTemp(temp());
// System.out.println(var.getName() + " set temp to " + var.getTemp());
}
}
@Override
public void visit(ArrayDec dec, int level, boolean isAddr) {
if (!scope.declare(dec)) {
Log.error(dec, "Already declared variabe in current scope with name", dec.getName());
} else if (dec.getType().getType() == CMType.VOID) {
Log.error(dec, "Cannot declare variable with type", "void");
} else {
scope.findVariable(dec.getName()).setTemp(temp());
}
}
@Override
public void visit(AssignExp exp, int level, boolean isAddr) {
VarExp left = exp.getLeft();
left.accept(this, level + 1, isAddr);
Exp right = exp.getRight();
right.accept(this, level + 1, isAddr);
if (CMType.isRealType(left) && CMType.isRealType(right)) {
if (left.getExpectedType() != right.getExpectedType()) {
// If they don't match, then throw error
String message = String.format(
"Cannot assign a value of type \"%s\" to variable \"%s\" of type",
CMType.toString(right),
left.getVariable().getName()
);
Log.error(exp, message, CMType.toString(left));
} else {
// Should be mostly fine
exp.setExpectedType(left.getExpectedType());
}
} else {
exp.setExpectedType(CMType.ERROR);
}
}
@Override
public void visit(BoolExp exp, int level, boolean isAddr) {
exp.setExpectedType(CMType.BOOL);
}
@Override
public void visit(CallExp exp, int level, boolean isAddr) {
List<Exp> args = exp.getArgs();
args.accept(this, level, isAddr);
NodeType expected = scope.findVariable(exp.getFunction());
if (expected == null) {
Log.error(exp, "Could not find function with name", exp.getFunction());
exp.setExpectedType(CMType.ERROR);
} else if (!(expected instanceof FunctionNode)) {
Log.error(exp, "Attempted to call variable that is not a function", expected.getName());
exp.setExpectedType(CMType.ERROR);
} else {
boolean sigMatch = true;
List<VarDec> params = ((FunctionDec)expected.getDef()).getParams();
// Todo check params
int argsCount = args.count(), paramsCount = params.count();
if (argsCount != paramsCount) {
String message = String.format(
"Mismatch parameter count for function \"%s\". Expected %d, received %d",
exp.getFunction(), paramsCount, argsCount
);
Log.error(exp, message);
sigMatch = false;
}
int count = Math.min(argsCount, paramsCount);
Iterator<Exp> aIter = args.iterator();
Iterator<VarDec> pIter = params.iterator();
for (int i = 0; i < count; ++i) {
Exp arg = aIter.next();
VarDec param = pIter.next();
// arg.getExpectedType();
if ((arg instanceof VarExp) && ((VarExp)arg).getVariable() instanceof SimpleVar) {
// incase we pass a variable as an argument, ensure that if they are
SimpleVar v = (SimpleVar)((VarExp)arg).getVariable();
// Now check for passing arrays
NodeType var0 = scope.findVariable(v);
if (var0 != null) {
String exsig = var0.getSignature();
String psig = param.signature(); // get sig of param
if (!(exsig.equals(psig))) { // if they don't match, then report error
String message = String.format(
"Argument type missmatch for function \"%s\". Expected \"%s\" received \"%s\"",
exp.getFunction(), param.signature(), exsig
);
Log.error(arg, message);
sigMatch = false;
}
} else {
sigMatch = false;
}
} else if (arg.getExpectedType() != param.getExpectedType()) {
// Log errors for invalid type matches on arguments
String message = String.format(
"Argument type missmatch for function \"%s\". Expected \"%s\" received \"%s\"",
exp.getFunction(), param.signature(),
CMType.toString(arg)
);
Log.error(arg, message);
sigMatch = false;
}
}
if (!sigMatch && VERBOSE) {
Log.error(
exp,
"Invalid signature for call to \"" + exp.getFunction() + "\", expected signature of:",
((FunctionDec)expected.getDef()).getSignature()
);
}
// Still try and continue with the given type of the function
exp.setExpectedType(expected.getType());
exp.setTemp(expected.getTemp());
}
}
@Override
public void visit(CompoundExp exp, int level, boolean isAddr) {
boolean closeNewScope = false;
if (newScope) {
// If we've opened a new scope then we need to remember to close it
// The new scope opened is just a regular block not attached to anything.
scope = scope.stepIn("block");
closeNewScope = true;
}
newScope = true; // always reset going deeper
exp.getDecs().accept(this, ++level, isAddr);
exp.getExps().accept(this, level, isAddr);
if (closeNewScope) {
scope = scope.stepOut();
}
}
@Override
public void visit(IfExp exp, int level, boolean isAddr) {
Exp condition = exp.getCondition();
condition.accept(this, level, isAddr);
if (condition.getExpectedType() == CMType.VOID) {
Log.error(condition, "Expected type of \"int\" or \"bool\" for if condition. Received", "void");
}
// Step into if block
scope = scope.stepIn("if block");
newScope = false; // ensure we don't recreate a new scope
exp.getThen().accept(this, ++level, isAddr);
scope = scope.stepOut();
Exp elseBlock = exp.getElseBlock();
if (elseBlock instanceof NilExp) {
return;
}
// Step into "else" scope
scope = scope.stepIn("else block");
newScope = false;
elseBlock.accept(this, level, isAddr);
scope = scope.stepOut();
}
@Override
public void visit(WhileExp exp, int level, boolean isAddr) {
Exp cond = exp.getCondition();
cond.accept(this, level, isAddr);
if (cond.getExpectedType() != CMType.INT && cond.getExpectedType() != CMType.BOOL) {
Log.error(
cond, "Expected type of \"int\" or \"bool\" for while condition. Received",
CMType.toString(cond)
);
}
// Step into the body of the while loop
scope = scope.stepIn("while loop");
newScope = false;
exp.getBody().accept(this, ++level, isAddr);
newScope = true; // Failsafe
scope = scope.stepOut();
}
@Override
public void visit(IntExp exp, int level, boolean isAddr) {
exp.setExpectedType(CMType.INT);
}
@Override
public void visit(OpExp exp, int level, boolean isAddr) {
Exp left = exp.getLeft();
Exp right = exp.getRight();
left.accept(this, level + 1, isAddr);
right.accept(this, level + 1, isAddr);
int leftType = left.getExpectedType();
// Handle unary operators
if (exp.isUnary()) {
if (leftType == CMType.VOID) {
Log.error(left.getRow(), left.getCol(), "Cannot perform operator on void:", exp.opToString());
exp.setExpectedType(CMType.ERROR);
} else {
exp.setExpectedType(leftType);
}
} else if (CMType.isRealType(leftType) && CMType.isRealType(right)) {
int rightType = right.getExpectedType();
if (leftType != rightType) {
String message = String.format(
"Cannot use operator \"%s\" with types \"%s\" and \"%s\"",
exp.opToString(),
CMType.toString(leftType),
CMType.toString(rightType)
);
Log.error(exp, message, null);
exp.setExpectedType(CMType.ERROR);
} else {
// If all is good then pass type of operator upwards.
// If it's a comparison operator then mark it as a boolean
exp.setExpectedType(exp.isComparison() ? CMType.BOOL : leftType);
}
} else {
// Mark everything else as an error, unless it's a comparison
exp.setExpectedType(exp.isComparison() ? CMType.BOOL : CMType.ERROR);
}
}
@Override
public void visit(VarExp exp, int level, boolean isAddr) {
Var var = exp.getVariable();
var.accept(this, level + 1, isAddr);
// Pass the expected type of the var upward
exp.setExpectedType(var.getExpectedType());
}
@Override
public void visit(ReturnExp exp, int level, boolean isAddr) {
Exp value = exp.getValue();
value.accept(this, level + 1, isAddr);
if (value instanceof NilExp) {
// Set it as void
value.setExpectedType(CMType.VOID);
}
// Pass expected type of value upwards
exp.setExpectedType(value.getExpectedType());
if (CMType.isRealType(value)) {
if (currentFunction.getExpectedType() != value.getExpectedType()) {
// Check return type of the current funtion
String message = String.format(
"Expected return type of \"%s\", received type \"%s\"",
CMType.toString(currentFunction),
CMType.toString(value)
);
Log.error(exp, message);
}
}
}
@Override
public void visit(NilExp exp, int level, boolean isAddr) {
exp.setExpectedType(CMType.NONE);
}
@Override
public void visit(SynError err, int level, boolean isAddr) {
err.setExpectedType(CMType.ERROR);
}
@Override
public void visit(SimpleVar var, int level, boolean isAddr) {
NodeType expected = scope.findVariable(var);
if (expected == null) {
Log.error(var, "Cannot find variable with name", var.getName());
var.setExpectedType(CMType.ERROR);
} else if (expected.isArray()) {
// Depends what we're doing with this the variable.
/**
void funcThatTakesArray(int a[]) {};
int x[10];
funcThatTakesArray(x); // THIS IS OKAY!
int y = x; // THIS IS NOT!
*/
} else if (expected instanceof FunctionNode) {
Log.error(var, "Cannot use function as variable", var.getName());
var.setExpectedType(CMType.ERROR);
} else {
// Everything is ok
var.setExpectedType(expected.getType());
var.setTemp(expected.getTemp());
}
}
@Override
public void visit(IndexVar var, int level, boolean isAddr) {
Exp indexExp = var.getIndex();
indexExp.accept(this, level + 1, isAddr);
NodeType expected = scope.findVariable(var);
if (expected == null) {
Log.error(var, "Cannot find array", var.getName());
var.setExpectedType(CMType.ERROR);
} else if (!(expected.isArray())) {
Log.error(var, "Expected an array with identifier", var.getName());
var.setExpectedType(expected.getType());
} else {
// Everything should be ok!
var.setExpectedType(expected.getType());
var.setTemp(expected.getTemp());
}
if (indexExp.getExpectedType() != CMType.INT) {
Log.error(var, "Indexing requires an integer.");
}
}
@Override
public void visit(NameType type, int level, boolean isAddr) {
// Ignore
}
}