forked from benfowler/c-minus
/
Analyse.c
614 lines (492 loc) · 15 KB
/
Analyse.c
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
/*********************************************************************
* NAME: Benjamin Fowler
* NUMBER: 02251132
* SUBJECT: Modern Compiler Construction
* INSTRUCTOR: Dr Wayne Kelly
*********************************************************************
* MODULE: Analyse.c
* PURPOSE: Defines the implementation of the semantic
* analyser module.
* DATE STARTED: 7th May, 2000.
* LAST EDITED: 11th May, 2000.
*********************************************************************/
#include "Analyse.h"
#include "Globals.h"
#include "SymTab.h"
#include "Util.h"
/*********************************************************************
* Module-static function declarations
*/
/* draw a ruler on the screen */
static void drawRuler(FILE *output, char *string);
/* the guts of buildSymbolTable() */
static void buildSymbolTable2(TreeNode *syntaxTree);
/* flag an error from the type checker */
static void flagSemanticError(char *str);
/* generic tree traversal routine */
static void traverse(TreeNode *syntaxTree,
void (*preProc)(TreeNode *),
void (*postProc)(TreeNode *) );
/* routine to perform the actual type check on a node */
static void checkNode(TreeNode *syntaxTree);
/* dummy do-nothing procedure used to keep traversal() happy */
static void nullProc(TreeNode *syntaxTree);
/* traverse the syntax tree, marking global variables as such */
void markGlobals(TreeNode *tree);
/* declare the C-minus "built-in" input() and output() routines */
static void declarePredefines(void);
/* type-check functions' formal parameters against actual parameters */
static int checkFormalAgainstActualParms(TreeNode *formal, TreeNode *actual);
/*********************************************************************
* Public function definitions
*/
void buildSymbolTable(TreeNode *syntaxTree)
{
/* Format headings */
if (TraceAnalyse)
{
drawRuler(listing, "");
fprintf(listing,
"Scope Identifier Line Is a Symbol type\n");
fprintf(listing,
"depth Decl. parm?\n");
}
declarePredefines(); /* make input() and output() visible in globals */
buildSymbolTable2(syntaxTree);
/* set the isGlobal field in appropriate nodes: needed in code generator */
markGlobals(syntaxTree);
/* Dump the global scope, if it's asked for */
if (TraceAnalyse)
{
drawRuler(listing, "GLOBALS");
dumpCurrentScope();
drawRuler(listing, "");
fprintf(listing, "*** Symbol table dump complete\n");
}
}
void typeCheck(TreeNode *syntaxTree)
{
traverse(syntaxTree, nullProc, checkNode);
}
/*********************************************************************
* Static function declarations
*/
static void declarePredefines(void)
{
TreeNode *input;
TreeNode *output;
TreeNode *temp;
/* define "int input(void)" */
input = newDecNode(FuncDecK);
input->name = copyString("input");
input->functionReturnType = Integer;
input->expressionType = Function;
/* define "void output(int)" */
temp = newDecNode(ScalarDecK);
temp->name = copyString("arg");
temp->variableDataType = Integer;
temp->expressionType = Integer;
output = newDecNode(FuncDecK);
output->name = copyString("output");
output->functionReturnType = Void;
output->expressionType = Function;
output->child[0] = temp;
/* get input() and output() added to global scope */
insertSymbol("input", input, 0);
insertSymbol("output", output, 0);
}
static void buildSymbolTable2(TreeNode *syntaxTree)
{
int i; /* iterate over node children */
HashNodePtr luSymbol; /* symbol being looked up */
char errorMessage[80];
/* used to decorate RETURN nodes with enclosing procedure */
static TreeNode *enclosingFunction = NULL;
while (syntaxTree != NULL)
{
/*
* Examine current symbol: if it's a declaration, insert into
* symbol table.
*/
if (syntaxTree->nodekind == DecK)
insertSymbol(syntaxTree->name, syntaxTree, syntaxTree->lineno);
/* If entering a new function, tell the symbol table */
if ((syntaxTree->nodekind == DecK)
&& (syntaxTree->kind.dec == FuncDecK))
{
/* record the enclosing procedure declaration */
enclosingFunction = syntaxTree;
if (TraceAnalyse)
/*
* For functions at least, it's nice to tell the user
* whereabouts in the program the variable comes into
* scope. We don't bother printing out compound-stmt
* scopes
*/
drawRuler(listing, syntaxTree->name);
newScope();
++scopeDepth;
}
/* If entering a compound-statement, create a new scope as well */
if ((syntaxTree->nodekind == StmtK)
&& (syntaxTree->kind.stmt == CompoundK))
{
newScope();
++scopeDepth;
}
/*
* If the current node is an identifier, it needs to be checked
* against the symbol table, and annotated with a pointer back to
* it's declaration.
*/
if (((syntaxTree->nodekind == ExpK) /* identifier reference... */
&& (syntaxTree->kind.exp == IdK))
|| ((syntaxTree->nodekind == StmtK) /* function call... */
&& (syntaxTree->kind.stmt == CallK)))
{
DEBUG_ONLY(
fprintf(listing,
"*** Annotating identifier \"%s\" on line %d\n",
syntaxTree->name, syntaxTree->lineno); );
luSymbol = lookupSymbol(syntaxTree->name);
if (luSymbol == NULL)
{
/* operation failed; say so to user */
sprintf(errorMessage,
"identifier \"%s\" unknown or out of scope\n",
syntaxTree->name);
flagSemanticError(errorMessage);
}
else
{
/*
* Annotate identifier tree-node with a pointer to it's
* declaration.
*/
syntaxTree->declaration = luSymbol->declaration;
}
}
/*
* If the current node is a RETURN statement, we need to mark
* it with the enclosing procedure's declaration node. This
* information is used later by the type checker to check
* function return types.
*/
if ((syntaxTree->nodekind == StmtK) &&
(syntaxTree->kind.stmt == ReturnK))
{
syntaxTree->declaration = enclosingFunction;
DEBUG_ONLY( fprintf(listing,
"*** Marking return statement on line %d with pointer to "
"%s() declaration\n",
syntaxTree->lineno,
syntaxTree->declaration->name) );
}
for (i=0; i < MAXCHILDREN; ++i)
buildSymbolTable2(syntaxTree->child[i]);
/* If leaving a scope, tell the symbol table */
if (((syntaxTree->nodekind == DecK)
&& (syntaxTree->kind.dec == FuncDecK))
|| ((syntaxTree->nodekind == StmtK)
&& (syntaxTree->kind.stmt == CompoundK)))
{
if (TraceAnalyse)
dumpCurrentScope();
--scopeDepth;
endScope();
}
/* do post-order operations here */
/* visit next sibling */
syntaxTree = syntaxTree->sibling;
}
}
static void drawRuler(FILE *output, char *string)
{
int length;
int numTrailingDashes;
int i;
/* empty string? */
if (strcmp(string, "") == 0)
length = 0;
else
length = strlen(string) + 2;
fprintf(output, "---");
if (length > 0) fprintf(output, " %s ", string);
numTrailingDashes = 45 - length;
for (i=0; i<numTrailingDashes; ++i)
fprintf(output, "-");
fprintf(output, "\n");
}
static void flagSemanticError(char *str)
{
fprintf(listing, ">>> Semantic error (type checker): %s", str);
Error = TRUE;
}
/* generic tree traversal routine */
static void traverse(TreeNode *syntaxTree,
void (*preProc)(TreeNode *),
void (*postProc)(TreeNode *) )
{
int i;
while (syntaxTree != NULL)
{
preProc(syntaxTree);
for (i=0; i < MAXCHILDREN; ++i)
traverse(syntaxTree->child[i], preProc, postProc);
postProc(syntaxTree);
syntaxTree = syntaxTree->sibling;
}
}
/*
* Take a pair of tree nodes whose children contain definitions of formal
* parameters, and expressions-as-actual-parameters respectively.
*
* Compares the lists of formal and actual parameters, returns TRUE if the
* types and number of parameters match, FALSE otherwise.
*/
static int checkFormalAgainstActualParms(TreeNode *formal, TreeNode *actual)
{
TreeNode *firstList;
TreeNode *secondList;
firstList = formal->child[0];
secondList = actual->child[0];
while ((firstList != NULL) && (secondList != NULL))
{
if (firstList->expressionType != secondList->expressionType)
return FALSE;
if (firstList) firstList = firstList->sibling;
if (secondList) secondList = secondList->sibling;
}
if (((firstList == NULL) && (secondList != NULL))
|| ((firstList != NULL) && (secondList == NULL)))
return FALSE;
return TRUE;
}
static void checkNode(TreeNode *syntaxTree)
{
char errorMessage[100];
switch (syntaxTree->nodekind)
{
case DecK:
switch (syntaxTree->kind.dec)
{
case ScalarDecK:
syntaxTree->expressionType = syntaxTree->variableDataType;
break;
case ArrayDecK:
syntaxTree->expressionType = Array;
break;
case FuncDecK:
syntaxTree->expressionType = Function;
break;
}
break; /* case DecK */
case StmtK:
switch (syntaxTree->kind.stmt)
{
case IfK:
if (syntaxTree->child[0]->expressionType != Integer)
{
sprintf(errorMessage,
"IF-expression must be integer (line %d)\n",
syntaxTree->lineno);
flagSemanticError(errorMessage);
}
break;
case WhileK:
if (syntaxTree->child[0]->expressionType != Integer)
{
sprintf(errorMessage,
"WHILE-expression must be integer (line %d)\n",
syntaxTree->lineno);
flagSemanticError(errorMessage);
}
break;
case CallK:
/* Check types and numbers of formal against actual parameters */
if (!checkFormalAgainstActualParms(syntaxTree->declaration,
syntaxTree))
{
sprintf(errorMessage, "formal and actual parameters to "
"function don\'t match (line %d)\n",
syntaxTree->lineno);
flagSemanticError(errorMessage);
}
/*
* The type of this expression (procedure invokation) is that
* of the return type of the procedure being called
*/
syntaxTree->expressionType
= syntaxTree->declaration->functionReturnType;;
break;
case ReturnK:
/*
* The expression attached to the RETURN statement (if any)
* must have the type of the return type of the function.
*/
if (syntaxTree->declaration->functionReturnType == Integer)
{
if ((syntaxTree->child[0] == NULL)
|| (syntaxTree->child[0]->expressionType != Integer))
{
sprintf(errorMessage, "RETURN-expression is either "
"missing or not integer (line %d)\n",
syntaxTree->lineno);
flagSemanticError(errorMessage);
}
}
else if (syntaxTree->declaration->functionReturnType == Void)
{
/* does a return-expression exist? complain */
if (syntaxTree->child[0] != NULL)
{
sprintf(errorMessage, "RETURN-expression must be"
"void (line %d)\n", syntaxTree->lineno);
}
}
break;
case CompoundK:
/*
* I don't think that compound-statement's type attribute
* evaluates to anything in particular... make it "void".
*/
syntaxTree->expressionType = Void;
break;
}
break; /* case StmtK */
case ExpK:
switch (syntaxTree->kind.exp)
{
case OpK:
/*
* This syntactic category includes both arithmetic and relational
* operators.
*/
/* Arithmetic operators */
if ((syntaxTree->op == PLUS) || (syntaxTree->op == MINUS) ||
(syntaxTree->op == TIMES) || (syntaxTree->op == DIVIDE))
{
if ((syntaxTree->child[0]->expressionType == Integer) &&
(syntaxTree->child[1]->expressionType == Integer))
syntaxTree->expressionType = Integer;
else
{
sprintf(errorMessage, "arithmetic operators must have "
"integer operands (line %d)\n", syntaxTree->lineno);
flagSemanticError(errorMessage);
}
}
/* Relational operators */
else if ((syntaxTree->op == GT) || (syntaxTree->op == LT) ||
(syntaxTree->op == LTE) || (syntaxTree->op == GTE) ||
(syntaxTree->op == EQ) || (syntaxTree->op == NE))
{
if ((syntaxTree->child[0]->expressionType == Integer) &&
(syntaxTree->child[1]->expressionType == Integer))
syntaxTree->expressionType = Integer;
else
{
sprintf(errorMessage, "relational operators must have "
"integer operands (line %d)\n", syntaxTree->lineno);
flagSemanticError(errorMessage);
}
}
else
{
sprintf(errorMessage, "error in type checker: unknown operator"
" (line %d)\n", syntaxTree->lineno);
flagSemanticError(errorMessage);
}
break;
case IdK:
/*
* Handle identifiers. We can just have arrays, scalars, or
* array element references.
*/
if (syntaxTree->declaration->expressionType == Integer)
{
if (syntaxTree->child[0] == NULL)
syntaxTree->expressionType = Integer;
else
{
/* only Arrays can be indexed */
sprintf(errorMessage, "can't access an element in "
"somthing that isn\t an array (line %d)\n",
syntaxTree->lineno);
flagSemanticError(errorMessage);
}
}
else if (syntaxTree->declaration->expressionType == Array)
{
if (syntaxTree->child[0] == NULL)
syntaxTree->expressionType = Array;
else
{
/* Identifier is indexed by an expression */
if (syntaxTree->child[0]->expressionType == Integer)
syntaxTree->expressionType = Integer;
else
{
sprintf(errorMessage, "array must be indexed by a "
"scalar (line %d)\n", syntaxTree->lineno);
flagSemanticError(errorMessage);
}
}
}
else
{
sprintf(errorMessage, "identifier is an illegal type "
"(line %d)\n", syntaxTree->lineno);
flagSemanticError(errorMessage);
}
break;
case ConstK:
/* C-minus supports only integers - easy to type check. */
syntaxTree->expressionType = Integer;
break;
case AssignK:
/* Variable assignment */
if ((syntaxTree->child[0]->expressionType == Integer) &&
(syntaxTree->child[1]->expressionType == Integer))
syntaxTree->expressionType = Integer;
else
{
sprintf(errorMessage, "both assigning and assigned expression"
" must be integer (line %d)\n", syntaxTree->lineno);
flagSemanticError(errorMessage);
}
break;
}
break; /* case ExpK */
} /* switch (syntaxTree->nodekind) */
}
void markGlobals(TreeNode *syntaxTree)
{
TreeNode *cursor;
DEBUG_ONLY( char scratch[80]; );
cursor = syntaxTree;
while (cursor != NULL)
{
if ((cursor->nodekind==DecK)&&
((cursor->kind.dec==ScalarDecK)||
(cursor->kind.dec==ArrayDecK)))
{
DEBUG_ONLY(
sprintf(scratch, "*** Marked %s as a global variable\n",
cursor->name);
fprintf(listing, scratch);
);
cursor->isGlobal = TRUE;
}
cursor = cursor->sibling;
}
}
/* dummy do-nothing procedure used to keep traverse() happy */
static void nullProc(TreeNode *syntaxTree)
{
if (syntaxTree == NULL)
return;
else
return;
}
/* END OF FILE */