forked from dcolish/BLITZ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cc
1516 lines (1317 loc) · 47.1 KB
/
main.cc
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
// main.cc -- Driver routine for the compiler; basic control routines
//
// KPL Compiler
//
// Copyright 2002-2007, Harry H. Porter III
//
// This file may be freely copied, modified and compiled, on the sole
// condition that if you modify it...
// (1) Your name and the date of modification is added to this comment
// under "Modifications by", and
// (2) Your name and the date of modification is added to the printHelp()
// routine under "Modifications by".
//
// Original Author:
// 06/15/02 - Harry H. Porter III
//
// Modifcations by:
// 03/15/06 - Harry H. Porter III
//
#include <signal.h>
#include "main.h"
#include "printAst.h"
//--------------- Global Variables ---------------
TokenValue currentTokenValue; // Used in lexer only
Token tokenMinusOne, token, token2, token3, token4, token5;
int currentInputFileIndex = -1; // These describe the current position in the file
int currentLineOfToken; // .
int currentCharPosOfToken; // .
int posOfNextToken; // Position of the next token
int eofCount; // Used to check for looping on EOF
char * inputFileNames [MAX_INPUT_FILES+1]; // Array of ptrs to file names
int errorsDetected; // Count of errors detected so far
int tokenPosOfLastError; // Used to suppress extraneous syntax errors
int hashVal = 0; // The running hash code for this file
int hashCount = 0; // Used in computing the hashVal
char * commandPackageName = NULL; // The package name, NULL = missing
char * commandDirectoryName; // The search directory name, NULL = missing
char * headerFileName = NULL; // The header file name, NULL = missing
char * codeFileName = NULL; // The code file name, NULL = missing
char * outputFileName = NULL; // The .s filename, NULL = missing
FILE * inputFile; // The input file, e.g., stdin
FILE * outputFile; // The output file, e.g., stdout
int commandOptionS = 0; // True: print the symbol table
int commandOptionP = 0; // True: pretty-print the AST
int commandOptionAST = 0; // True: print the full AST
int commandOptionTestLexer = 0; // True: stop after lexer & print tokens
int commandOptionTestParser = 0; // True: stop after parser & print AST
int safe = 1; // True: only allow safe constructs
Header * headerList = NULL; // List of all headers
Header * headerListLast = NULL; // .
Mapping <String, Header> * // Strings --> Headers
headerMapping = NULL; // .
Code * code = NULL; // The thing being compiled
Header * mainHeader = NULL; // The corresponding header
Interface * tempInterList = NULL; // Used in topoProcessInterfaces
ClassDef * tempClassList = NULL; // Used in topoProcessClasses
int changed = 0; // Used in assignOffsets
int quo = 0; // Used in integer division
int rem = 0; // .
ClassDef * currentClass = NULL; // The class we are currently processing
Header * currentHeader = NULL; // The header we are currently processing
int recursionCounter = 0; // Used to detect recursive types
IntConst * memoryStart; // Used to compute memory usage by compiler
IR * firstInstruction = NULL; // List of IR instructions
IR * lastInstruction = NULL; // .
int maxArgBytesSoFar = -1; // Used in setting fun/meth->maxArgBytes
DoubleConst * floatList = NULL; // Used during code gen
StringConst * stringList = NULL; // Used during code gen
MethOrFunction * currentFunOrMeth = NULL; // Used during code gen
Offset * firstDispatchOffset = NULL; // Ptr to linked list: 4,8,12,16,...
// The String Table, for all Strings and IDs.
String * stringTableIndex [STRING_TABLE_HASH_SIZE];
char buffer [BUFF_LEN]; // Misc. use, e.g., "_Person__Constructor"
// These are initialized in "initializeConstants"...
String * stringUnaryBang;
String * stringUnaryStar;
String * stringUnaryAmp;
String * stringUnaryMinus;
String * stringPlus;
String * stringMinus;
String * stringStar;
String * stringSlash;
String * stringPercent;
String * stringBar;
String * stringCaret;
String * stringAmp;
String * stringBarBar;
String * stringAmpAmp;
String * stringEqualEqual;
String * stringNotEqual;
String * stringLess;
String * stringLessEqual;
String * stringGreater;
String * stringGreaterEqual;
String * stringLessLess;
String * stringGreaterGreater;
String * stringGreaterGreaterGreater;
String * stringIntToDouble;
String * stringDoubleToInt;
String * stringIntToChar;
String * stringCharToInt;
String * stringPtrToBool;
String * stringPosInf;
String * stringNegInf;
String * stringNegZero;
String * stringIIsZero;
String * stringINotZero;
String * stringObject;
String * stringMain;
CharType * basicCharType;
IntType * basicIntType;
DoubleType * basicDoubleType;
BoolType * basicBoolType;
VoidType * basicVoidType;
TypeOfNullType * basicTypeOfNullType;
AnyType * basicAnyType;
PtrType * basicCharArrayPtrType;
PtrType * basicVoidPtrType;
PtrType * basicAnyPtrType;
IntConst * constantIntZero;
IntConst * constantIntOne;
IntConst * constantIntMinusOne;
BoolConst * constantFalse;
BoolConst * constantTrue;
// main (argc, argv)
//
// The compiler main.
//
int main (int argc, char ** argv) {
Header * hdr, * newHeader;
Uses * uses;
String * newPackName;
AstNode * ast;
int len;
char * fileName;
Type * t;
int saveSafe;
int wantProgress = 0;
memoryStart = new IntConst ();
// printf ("Starting memory address = 0x%08x\n", (int) memoryStart);
errorsDetected = 0;
tokenPosOfLastError = -1; // FF=255, LLLL=65535, PP=255
initKeywords ();
checkHostCompatibility ();
processCommandLine (argc, argv);
initializeConstants ();
// If -testLexer command line option present...
if (commandOptionTestLexer) {
printf("file-name\tline\tchar\ttoken-type\tother-info\n");
printf("=========\t====\t====\t==========\t==========\n");
if (initScanner (headerFileName) != NULL) {
testLexer ();
}
terminateCompiler ();
}
headerMapping = new Mapping<String, Header> (15, NULL);
// If -testParser command line option present...
if (commandOptionTestParser) {
if (initScanner (headerFileName)) {
if (token.type == FUNCTION) {
ast = parseFunction (1); // 1=expecting ID
} else if (token.type == METHOD) {
ast = parseMethod ();
} else if (token.type == HEADER) {
ast = parseHeader ();
} else if (token.type == CODE) {
ast = parseCode ();
} else if (token.type == DO) {
scan ();
ast = parseExpr ("Expecting test expression after 'do'");
}
if (commandOptionAST) {
printAst (6, ast);
}
if (commandOptionP) {
printf ("======== PRETTY PRINT ========\n");
pretty (ast);
printf ("\n================================\n");
}
}
terminateCompiler ();
}
// Make sure the user specified a package name on the command line.
if (commandPackageName == NULL) {
fprintf (stderr, "***** ERROR: Missing package name on command line\n");
errorsDetected++;
terminateCompiler ();
}
if ((codeFileName == NULL) || (headerFileName == NULL)) {
programLogicError ("File names should have been created from package name");
}
if (wantProgress) printf ("Parsing...\n");
// Parse the code file...
if (initScanner (codeFileName)) {
code = parseCode ();
} else {
code = NULL;
}
// Parse the main header file...
fileName = (char *)initScanner (headerFileName);
if (fileName != NULL) {
//mainHeader = parseHeader (commandPackageName);
mainHeader = parseHeader ();
headerList = mainHeader;
headerListLast = mainHeader;
if (mainHeader) {
// headerMapping->enter (mainHeader->packageName, mainHeader);
headerMapping->enter (lookupAndAdd (commandPackageName, ID), mainHeader);
}
} else {
mainHeader = NULL;
headerList = NULL;
headerListLast = NULL;
}
// Run through the headerList. For every header on it, see which
// packages it uses. For each, if it has not already been parsed
// then parse it and add it to the headerMapping.
hdr = headerList;
while (hdr != NULL) {
// Look at the next "hdr"...
// Run through the list of packages this "hdr" uses...
uses = hdr->uses;
while (uses != NULL) {
newPackName = uses->id;
// If this package has not been seen before...
if (! headerMapping->alreadyDefined (newPackName)) {
// Figure out the name of the .h header file...
len = strlen (newPackName->chars);
fileName = (char *) calloc (1, len + 4);
strcpy (fileName, newPackName->chars);
fileName [len] = '.';
fileName [len+1] = 'h';
fileName [len+2] = '\0';
fileName = (char *)initScanner (fileName);
if (fileName != NULL) {
// Parse the new package...
// newHeader = parseHeader (newPackName->chars);
newHeader = parseHeader ();
if (newHeader != NULL) {
// Add the new package to headerMapping...
// (NOTE: the keys will not contain any "-d" directory prefixes.)
// printf ("ADDING TO HEADERMAPPING: filename=%s, newHeader=%s\n",
// newPackName->chars, newHeader->packageName->chars);
headerMapping->enter (newPackName, newHeader);
// Add the new package to the end of headerList...
headerListLast->next = newHeader;
headerListLast = newHeader;
}
}
}
uses = uses->next;
}
// Move to next header on the headerList
hdr = hdr->next;
}
// printAllData ();
// dump ("After parsing...");
// Check for package-uses circularity and re-order all packages...
if (wantProgress) printf ("Finding a topological-sort order for packages...\n");
topoProcessAllPackages ();
// Must stop here if errors, since one error is cyclic package-use. From
// here on out, we're assuming our super-packages have already been done first.
if (errorsDetected) {
terminateCompiler ();
}
saveSafe = safe;
// Run through all headers and process each in turn...
for (hdr=headerList; hdr!=NULL; hdr=hdr->next) {
if (wantProgress) printf ("Processing package \"%s\"...\n", hdr->packageName->chars);
currentHeader = hdr;
if (currentHeader == mainHeader) {
safe = saveSafe;
} else {
safe = 0; // Allow unsafe constructs in any header we are using.
}
// Build the symbol tables...
if (wantProgress) printf (" Building symbol tables...\n");
buildPackageMapping (hdr);
// Topo-process the interfaces...
if (wantProgress) printf (" Topologically sorting interfaces...\n");
topoProcessInterfaces (hdr);
// Topo-process the classes...
if (wantProgress) printf (" Topologically sorting classes...\n");
topoProcessClasses (hdr);
// Bind Types...
if (wantProgress) printf (" Binding types...\n");
bindTypeNames (hdr, NULL);
// Check TypeDef circularity...
if (wantProgress) printf (" Checking type def circularity...\n");
checkTypeDefCircularity (hdr);
// Inherit Class Fields...
if (wantProgress) printf (" Inheriting class fields...\n");
inheritFields (hdr);
// Inherit MethodProtos...
if (wantProgress) printf (" Inheriting method prototypes...\n");
inheritMethodProtos (hdr);
// Inherit messages for interface "extends" hierarchy...
if (wantProgress) printf (" Inheriting messages in interfaces...\n");
inheritMessages (hdr);
// Bind variable names...
if (wantProgress) printf (" Binding variable names...\n");
bindVarNames (hdr, NULL);
// Assign offsets and evaluate expressions...
if (wantProgress) printf (" Assigning offsets and evaluating static expressions...\n");
assignOffsetsAndEvalExprs (hdr);
// The subtype test is operative after this point.
// testSubType (hdr);
// break;
// Check class-interface "implements" hierarchy...
if (wantProgress) printf (" Checking class/interface implements...\n");
checkImplements (hdr);
// Check method prototypes...
if (wantProgress) printf (" Checking method prototypes...\n");
checkMethodProtos (hdr);
// Check interface extends...
if (wantProgress) printf (" Checking interface extends...\n");
checkExtends (hdr);
// printf ("=================== Before checkTypes =========================\n");
// printAst (6, hdr);
// printf ("===============================================================\n");
// Check types...
if (wantProgress) printf (" Checking types...\n");
t = checkTypes (hdr);
// Evaluate expressions again; to handle anything introduced by checkTypes...
if (wantProgress) printf (" Evaluating static expressions...\n");
changed = 1;
while (changed) {
changed = 0;
evalExprsIn (hdr);
// The test called "bizarre" will print this message...
// if (changed) {
// printf ("LOOKS LIKE WE NEEDED A SECOND PASS!!!\n");
// }
}
// Make sure the recursionCounter is OK...
if (recursionCounter != 0) {
printf ("recursionCounter = %d\n", recursionCounter);
programLogicError ("recursionCounter not incremented and decremented equally");
}
// Check flow of control...
if (wantProgress) printf (" Checking flow of control...\n");
fallsThru (hdr);
// Assign Dispatch Table Offsets...
if (wantProgress) printf (" Assigning Dispatch Table Offsets...\n");
assignDispatchTableOffsets (hdr);
// Assign offsets to locals and parms in functions and closures...
// printf (" Asigning offsets to local variables and parameters...\n");
// assignLocalOffsets (hdr);
// printf ("\n========== HERE IS THE PACKAGE WE JUST FINISHED ==========\n");
// hdr->prettyPrint (4);
// printf ("\n============================================================\n");
}
safe = saveSafe;
// Make sure the recursionCounter is OK...
if (recursionCounter != 0) {
printf ("recursionCounter = %d\n", recursionCounter);
programLogicError ("recursionCounter not incremented and decremented equally");
}
// Stop here if errors...
if (commandOptionAST) { // && errorsDetected) {
printAllData ();
}
if (commandOptionP) { // && errorsDetected) {
dump ("After semantic processing...");
}
if (errorsDetected) {
terminateCompiler ();
}
// Generating IR code...
if (wantProgress) printf (" Generating IR code...\n");
generateIR ();
// Assign offsets to locals and parms in functions and closures...
if (wantProgress) printf (" Asigning offsets to local variables and parameters...\n");
assignLocalOffsets (mainHeader);
// Print the IR code...
if (wantProgress) printf (" Writing .s file...\n");
printIR ();
// Print the full AST in all detail, if requested...
if (commandOptionAST) {
printAllData ();
}
// Pretty-print the AST, if requested...
if (commandOptionP) {
dump ("After code generation...");
}
terminateCompiler ();
return 0;
}
// initializeConstants ()
//
// This routine initializes various constants that will be used during the
// compilation.
//
void initializeConstants () {
ArrayType * arrayType;
// The nodes created here will be positioned at "(null):0:"
token.value.svalue = NULL;
token.tokenPos = 0;
stringUnaryBang = lookupAndAdd ("_prefix_!", OPERATOR);
stringUnaryStar = lookupAndAdd ("_prefix_*", OPERATOR);
stringUnaryAmp = lookupAndAdd ("_prefix_&", OPERATOR);
stringUnaryMinus = lookupAndAdd ("_prefix_-", OPERATOR);
stringPlus = lookupAndAdd ("+", OPERATOR);
stringMinus = lookupAndAdd ("-", OPERATOR);
stringStar = lookupAndAdd ("*", OPERATOR);
stringSlash = lookupAndAdd ("/", OPERATOR);
stringPercent = lookupAndAdd ("%", OPERATOR);
stringBar = lookupAndAdd ("|", OPERATOR);
stringCaret = lookupAndAdd ("^", OPERATOR);
stringAmp = lookupAndAdd ("&", OPERATOR);
stringBarBar = lookupAndAdd ("||", OPERATOR);
stringAmpAmp = lookupAndAdd ("&&", OPERATOR);
stringEqualEqual = lookupAndAdd ("==", OPERATOR);
stringNotEqual = lookupAndAdd ("!=", OPERATOR);
stringLess = lookupAndAdd ("<", OPERATOR);
stringLessEqual = lookupAndAdd ("<=", OPERATOR);
stringGreater = lookupAndAdd (">", OPERATOR);
stringGreaterEqual = lookupAndAdd (">=", OPERATOR);
stringLessLess = lookupAndAdd ("<<", OPERATOR);
stringGreaterGreater = lookupAndAdd (">>", OPERATOR);
stringGreaterGreaterGreater = lookupAndAdd (">>>", OPERATOR);
stringIntToDouble = lookupAndAdd ("intToDouble", ID);
stringDoubleToInt = lookupAndAdd ("doubleToInt", ID);
stringIntToChar = lookupAndAdd ("intToChar", ID);
stringCharToInt = lookupAndAdd ("charToInt", ID);
stringPtrToBool = lookupAndAdd ("ptrToBool", ID);
stringPosInf = lookupAndAdd ("posInf", ID);
stringNegInf = lookupAndAdd ("negInf", ID);
stringNegZero = lookupAndAdd ("negZero", ID);
stringIIsZero = lookupAndAdd ("iIsZero", ID); // hidden function
stringINotZero = lookupAndAdd ("iNotZero", ID); // hidden function
stringObject = lookupAndAdd ("Object", ID);
stringMain = lookupAndAdd ("main", ID);
// Initialize nodes corresponding to basic types...
token.type = CHAR;
basicCharType = new CharType ();
token.type = INT;
basicIntType = new IntType ();
token.type = DOUBLE;
basicDoubleType = new DoubleType ();
token.type = BOOL;
basicBoolType = new BoolType ();
token.type = VOID;
basicVoidType = new VoidType ();
token.type = TYPE_OF_NULL;
basicTypeOfNullType = new TypeOfNullType ();
token.type = ANY_TYPE;
basicAnyType = new AnyType ();
token.type = ARRAY; // array [*] of char
arrayType = new ArrayType ();
arrayType->baseType = basicCharType;
arrayType->sizeOfElements = 1;
token.type = PTR; // ptr to array [*] of char
basicCharArrayPtrType = new PtrType ();
basicCharArrayPtrType->baseType = arrayType;
token.type = PTR; // ptr to void
basicVoidPtrType = new PtrType ();
basicVoidPtrType->baseType = basicVoidType;
token.type = PTR; // ptr to anyType
basicAnyPtrType = new PtrType ();
basicAnyPtrType->baseType = basicAnyType;
/*****
printf ("========== Basic Type Nodes ==========\n");
printf ("basicCharType = "); pretty (basicCharType);
printf ("basicIntType = "); pretty (basicIntType);
printf ("basicDoubleType = "); pretty (basicDoubleType);
printf ("basicBoolType = "); pretty (basicBoolType);
printf ("basicVoidType = "); pretty (basicVoidType);
printf ("basicTypeOfNullType = "); pretty (basicTypeOfNullType);
printf ("basicCharArrayPtrType = "); pretty (basicCharArrayPtrType);
printf ("basicVoidPtrType = "); pretty (basicVoidPtrType);
printf ("basicAnyType = "); pretty (basicAnyType);
printf ("========================================\n");
error (basicVoidPtrType, "Testing...");
*****/
// Some functions and messages are "primitives". Examples include "+" and
// "doubleToInt". Mark these symbols so that they can be easily tested later.
stringUnaryBang->primitiveSymbol = UNARY_BANG;
stringUnaryStar->primitiveSymbol = UNARY_STAR;
stringUnaryAmp->primitiveSymbol = UNARY_AMP;
stringUnaryMinus->primitiveSymbol = UNARY_MINUS;
stringPlus->primitiveSymbol = PLUS;
stringMinus->primitiveSymbol = MINUS;
stringStar->primitiveSymbol = STAR;
stringSlash->primitiveSymbol = SLASH;
stringPercent->primitiveSymbol = PERCENT;
stringBar->primitiveSymbol = BAR;
stringCaret->primitiveSymbol = CARET;
stringAmp->primitiveSymbol = AMP;
stringBarBar->primitiveSymbol = BAR_BAR;
stringAmpAmp->primitiveSymbol = AMP_AMP;
stringEqualEqual->primitiveSymbol = EQUAL_EQUAL;
stringNotEqual->primitiveSymbol = NOT_EQUAL;
stringLess->primitiveSymbol = LESS;
stringLessEqual->primitiveSymbol = LESS_EQUAL;
stringGreater->primitiveSymbol = GREATER;
stringGreaterEqual->primitiveSymbol = GREATER_EQUAL;
stringLessLess->primitiveSymbol = LESS_LESS;
stringGreaterGreater->primitiveSymbol = GREATER_GREATER;
stringGreaterGreaterGreater->primitiveSymbol = GREATER_GREATER_GREATER;
stringIntToDouble->primitiveSymbol = INT_TO_DOUBLE;
stringDoubleToInt->primitiveSymbol = DOUBLE_TO_INT;
stringIntToChar->primitiveSymbol = INT_TO_CHAR;
stringCharToInt->primitiveSymbol = CHAR_TO_INT;
stringPtrToBool->primitiveSymbol = PTR_TO_BOOL;
stringPosInf->primitiveSymbol = POS_INF;
stringNegInf->primitiveSymbol = NEG_INF;
stringNegZero->primitiveSymbol = NEG_ZERO;
stringIIsZero->primitiveSymbol = I_IS_ZERO;
stringINotZero->primitiveSymbol = I_NOT_ZERO;
// Set up some constants...
constantIntZero = new IntConst ();
constantIntOne = new IntConst ();
constantIntOne->ivalue = 1;
constantIntMinusOne = new IntConst ();
constantIntMinusOne->ivalue = -1;
constantFalse = new BoolConst (0);
constantTrue = new BoolConst (1);
/*****
constantDoubleZero = new DoubleExpr ();
constantDoubleOne = new DoubleExpr ();
constantDoubleOne->rvalue = 1.0;
constantCharNull = new CharExpr ();
constantNull = new NullExpr ();
stringUninitialized = lookupAndAdd ("<uninitialized string>", ID);
stringGenericDestructor = lookupAndAdd ("_Generic_Destructor", ID);
stringThis = lookupAndAdd ("_this", ID);
*****/
}
// printAllData ()
//
// This routine prints out all the data structures using printAst().
// in full and gory detail.
//
void printAllData () {
fflush (stdout);
printf ("\n================ HEADER LIST ================\n");
printAst (6, headerList);
printf ("================================\n");
// printf ("\n================ CODE ================\n");
// printAst (6, code);
// printf ("================================\n");
/*****
printf ("constantIntZero:\n");
printAst (6, constantIntZero);
printf ("constantIntOne:\n");
printAst (6, constantIntOne);
printf ("constantIntMinusOne:\n");
printAst (6, constantIntMinusOne);
printf ("constantDoubleZero:\n");
printAst (6, constantDoubleZero);
printf ("constantDoubleOne:\n");
printAst (6, constantDoubleOne);
printf ("constantCharNull:\n");
printAst (6, constantCharNull);
printf ("constantFalse:\n");
printAst (6, constantFalse);
printf ("constantTrue:\n");
printAst (6, constantTrue);
printf ("constantNull:\n");
printAst (6, constantNull);
printf ("basicTypeInt:\n");
printAst (6, basicTypeInt);
printf ("basicTypeDouble:\n");
printAst (6, basicTypeDouble);
printf ("basicTypeChar:\n");
printAst (6, basicTypeChar);
printf ("basicTypeBool:\n");
printAst (6, basicTypeBool);
printf ("basicTypeVoid:\n");
printAst (6, basicTypeVoid);
printf ("basicTypeNull:\n");
printAst (6, basicTypeNull);
printf ("basicTypeCharPtr:\n");
printAst (6, basicTypeCharPtr);
printf ("basicTypeVoidPtr:\n");
printAst (6, basicTypeVoidPtr);
*****/
fflush (stdout);
}
// dump (message)
//
// This routine prints out various data structures, using "prettyPrinting".
//
void dump (const char * message) {
Header * hdr;
fflush (stdout);
printf ("\n***************\n");
printf ("** **\n");
printf ("** DUMPING ** %s\n", message);
printf ("** **\n");
printf ("***************\n\n");
// Print out the headerList...
hdr = headerList;
printf ("\n================ HEADER LIST ================\n");
while (hdr) {
hdr->prettyPrint (4);
// if (hdr->packageMapping) {
// hdr->packageMapping->print (4);
// }
printf ("================================\n");
hdr = hdr->next;
}
/*****
if (code) {
printf ("\n================ CODE ================\n");
code->prettyPrint (4);
printf ("================================\n");
}
*****/
// Print out the headerMapping...
// printf ("\n\n");
// headerMapping->print (0);
fflush (stdout);
}
// testLexer ()
//
// This routine can be used to test the lexer portion of the compiler.
//
void testLexer () {
while (1) {
printToken (token);
/*****
printf ("\t\t\t");
printToken (token2);
printf ("\t\t\t\t");
printToken (token3);
printf ("\t\t\t\t\t");
printToken (token4);
printf ("\t\t\t\t\t\t");
printToken (token5);
*****/
if (token.type == EOF) {
break;
}
scan ();
}
// printStringTable ();
}
// printToken (token)
//
// This routine prints a token in a form such as...
// 7 ID abc
// 8 INT 1234
// 9 STRING_CONST "abc"
// 10 CHAR_CONST 0x61 97 'a'
// 11 WHILE
//
void printToken (Token token) {
int i;
printf("%s\t%d\t%d\t%s",
extractFilename (token),
extractLineNumber (token),
extractCharPos (token),
symbolName (token.type));
switch (token.type) {
case ID:
printf("\t");
printString (stdout, token.value.svalue);
break;
case OPERATOR:
printf("\t");
printString (stdout, token.value.svalue);
break;
case STRING_CONST:
printf("\t\"");
printString (stdout, token.value.svalue);
printf("\"");
break;
case CHAR_CONST:
i = token.value.ivalue;
printf("\t%02x\t%d", i, i);
if ((i >= ' ') && (i <= '~')) {
printf("\t\'%c\'", i);
}
break;
case INT_CONST:
printf("\t0x%08x\t%d", token.value.ivalue, token.value.ivalue);
break;
case DOUBLE_CONST:
printf("\t%.16g", token.value.rvalue);
break;
}
printf("\n");
}
// programLogicError (msg)
//
// This routine prints the message and terminates the compiler.
//
void programLogicError (const char * msg) {
fprintf (stderr,
"********************************************************************\n"
"*****\n"
"***** PROGRAM LOGIC ERROR\n"
"*****\n"
"***** It appears that this compiler contains a software bug.\n"
"***** I apologize for the inconvenience it causes you.\n"
"*****\n"
"***** Error message: \"%s\"\n"
"*****\n"
"********************************************************************\n", msg);
errorsDetected++;
terminateCompiler ();
}
// terminateCompiler ()
//
// Print out the number of errors (if any) and terminate of the compiler. If errors, then
// remove the output file (if any). If no errors, the close the output file normally.
//
void terminateCompiler () {
if (errorsDetected == 0) {
if (outputFileName != NULL) {
fclose (outputFile);
}
return;
} else if (errorsDetected == 1) {
fprintf (stderr, "\n********** 1 error detected! **********\n");
} else {
fprintf (stderr, "\n********** %d errors detected! **********\n",
errorsDetected);
}
if (outputFileName != NULL) {
fclose (outputFile);
remove (outputFileName);
}
}
// fatalError (msg)
//
// This routine is called to print an error message and the current line
// number of the curent token. It aborts the compiler.
//
void fatalError (const char *msg) {
errorsDetected++;
doMessage (token, "***** FATAL ERROR", msg);
terminateCompiler ();
}
// error (node, msg)
//
// This routine is called to print an error message. It returns; it
// does not terminate the program after printing. The "node" parameter
// is used to print additional information about the position of the error.
//
void error (AstNode * node, const char * msg) {
errorsDetected++;
doMessage (node->tokn, "***** ERROR", msg);
}
// error2 (node, msg)
//
// This routine is called to print an error message. It returns; it
// does not terminate the program after printing. The "node" parameter
// is used to print additional information about the position of the error.
// It differs from "error()" in that it does not print "***** ERRROR"; it is
// used to print additional info after the initial error message.
//
void error2 (AstNode * node, const char * msg) {
// errorsDetected++;
doMessage (node->tokn, " ", msg);
}
// syntaxError (msg)
//
// This routine is called to print a syntax error message.
//
// This routine returns; it does not terminate the compiler after printing.
//
// It uses the current token to print additional information about the
// position of the error.
//
void syntaxError (const char * msg) {
syntaxErrorWithToken (token, msg);
}
// syntaxErrorWithToken (tok, msg)
//
// This routine is called to do the work of printing a syntax error message,
// position on 'tok'.
//
void syntaxErrorWithToken (Token tok, const char * msg) {
// If the last message was on this token, then suppress this message.
if (tok.tokenPos != tokenPosOfLastError) {
errorsDetected++;
doMessage (tok, "***** SYNTAX ERROR", msg);
}
tokenPosOfLastError = tok.tokenPos;
}
// doMessage (tok, prefix, msg)
//
// Print info about the current token and the given "msg".
//
void doMessage (Token tok, const char * prefix, const char * msg) {
fprintf (stderr, "%s:%d: %s at ",
extractFilename (tok),
extractLineNumber (tok),
prefix);
switch (tok.type) {
case ID:
fprintf (stderr, "\'");
printString (stderr, tok.value.svalue);
fprintf (stderr, "\'");
break;
case STRING_CONST:
fprintf (stderr, "\"");
printString (stderr, tok.value.svalue);
fprintf (stderr, "\"");
break;
case CHAR_CONST:
fprintf (stderr, "\'");
printChar (stderr, tok.value.ivalue);
fprintf (stderr, "\'");
break;
case INT_CONST:
fprintf (stderr, "\'%d\'", tok.value.ivalue);
break;
case DOUBLE_CONST:
fprintf (stderr, "%.16g", tok.value.rvalue);
break;
case OPERATOR:
fprintf (stderr, "\"");
printString (stderr, tok.value.svalue);
fprintf (stderr, "\"");
break;
default:
fprintf (stderr, "%s", symbolName (tok.type));
}
fprintf (stderr, ": %s\n", msg);
fflush (stderr);
if (errorsDetected >= MAX_NUMBER_OF_ERRORS) {
fprintf (stderr, "%s:%d: ***** Too many errors - I'm giving up\n",
extractFilename (tok),
extractLineNumber (tok));
terminateCompiler ();
}
}
// errorWithType (msg, type)
//
// This routine is called to print an error message. It returns; it does not
// terminate the program unless we've had too many errors.
//
// The "type" parameter is printed after the message. For example, if msg is
// "The expected type is"
// the following might get printed:
// test.c:26: The expected type is: ptr to array [*] of char
//
// This routine calls "resolveNamedType" so it prints out the underlying
// type, getting rid of aliases.
//