-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.c
More file actions
2122 lines (1826 loc) · 38.9 KB
/
compiler.c
File metadata and controls
2122 lines (1826 loc) · 38.9 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
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <inttypes.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include "list.h"
#include "lifo.h"
#define OPERATOR_SYMBOLS \
"[","]","(",")",".","->", \
"-","!","~","*","&","@","sizeof", \
"*","/","%", \
"+","-", \
"<<",">>", \
"<","<=",">",">=", \
"==","!=", \
"&", \
"^", \
"|", \
"&&", \
"||", \
"=",
char *operatorSymbols[] = {
OPERATOR_SYMBOLS
};
#define NUM_OPERATOR_SYMBOLS (sizeof(operatorSymbols) / sizeof(*operatorSymbols))
char *symbols[] = {
OPERATOR_SYMBOLS
"u8","u32","void",
"struct",
",",";","{","}",
"if","else",
"while","for","break","continue",
"return",
};
#define NUM_SYMBOLS (sizeof(symbols) / sizeof(*symbols))
#define T_TERMINAL 0x1
#define T_IDENTIFIER 0x2
#define T_LITERAL_HEX 0x4
#define T_LITERAL_DEC 0x8
#define T_LITERAL_STR 0x10
#define T_LITERAL_CHR 0x20
#define T_LITERAL (T_LITERAL_HEX | T_LITERAL_DEC | T_LITERAL_STR | T_LITERAL_CHR)
typedef struct Token {
char *string;
int id;
int type;
int line;
void *private;
} Token;
typedef struct Struct {
char *name;
int size;
// Parameter
List members;
} Struct;
#define TYPE_U8 0x1
#define TYPE_U32 0x2
#define TYPE_STRUCT 0x4
#define TYPE_PTR 0x8
/*
* Arrays are just pointers to a region of memory.
* This type isn't really necessary.
* We do need someway to keep track of the array size.
*/
#define TYPE_ARRAY 0x10
typedef struct Type {
Token *token;
int flags;
int size;
int ptrCount;
int arraySize;
Struct *structType;
} Type;
typedef struct Parameter {
Type type;
char *name;
} Parameter;
typedef struct Variable {
Type type;
char *name;
int address;
Token *value;
} Variable;
typedef struct Argument {
Type type;
char *name;
} Argument;
typedef struct FunctionCall {
char *name;
// Expression
List argExprList;
} FunctionCall;
#define EXPR_OPERATOR 0x1
#define EXPR_LITERAL 0x2
#define EXPR_VAR 0x4
#define EXPR_FUNC 0x8
#define EXPR_OPERAND (EXPR_LITERAL | EXPR_VAR | EXPR_FUNC)
#define ASSOC_LEFT_TO_RIGHT 1
#define ASSOC_RIGHT_TO_LEFT 2
/*
* <operand> := <variable> | <fn>
* <operator> := <math symbol>
*/
typedef struct Oper {
int flags;
Token *token;
FunctionCall *call;
int isBinary;
int precedence;
int associativity;
} Oper;
typedef struct Expression {
// Oper
List postfix;
} Expression;
#define STMT_IF 0x1
#define STMT_ELIF 0x2
#define STMT_ELSE 0x4
#define STMT_WHILE 0x8
#define STMT_RETURN 0x10
#define STMT_VAR_DECL 0x20
#define STMT_EXPR 0x40
typedef struct Statement {
// Token
List tokens;
int flags;
Variable *var;
Expression *expr;
List statements;
} Statement;
typedef struct Function {
Type type;
char *name;
List variables;
// Parameter
List params;
// Statement
List statements;
} Function;
typedef struct Program {
/*
* Raw tokens.
*/
Token **tokenArray;
int tokenCount;
int i;
int lineCount;
// Struct
List structs;
// Variable
List vars;
// Function
List functions;
FILE *outFP;
} Program;
static char *inFile;
static char *outFile;
static int dumpParseTree;
static struct option longopts[] = {
{"help", no_argument, NULL, 'h'},
{"parse-tree", no_argument, NULL, 'p'},
{"output", required_argument, NULL, 'o'},
};
static char *optdesc[] = {
"This help.",
"Dump parse tree.",
"Name of file to write compiled output to.",
};
static char *optstring = NULL;
static void
usage(int argc, char **argv)
{
int i;
int numOptions;
int longest;
printf("%s [OPTION...]\n\n", argv[0]);
numOptions = sizeof(longopts) / sizeof(*longopts);
longest = 0;
for (i = 0; i < numOptions; ++i) {
if (longest < strlen(longopts[i].name)) {
longest = strlen(longopts[i].name);
}
}
for (i = 0; i < numOptions; ++i) {
printf("--%-*s, -%c : %s\n", longest, longopts[i].name, longopts[i].val, optdesc[i]);
}
printf("\n");
}
static void
mainArgs(int argc, char **argv)
{
int c, i;
int longindex;
int numOptions;
numOptions = sizeof(longopts) / sizeof(*longopts);
optstring = malloc(numOptions * 3);
memset(optstring, 0, numOptions * 3);
c = 0;
for (i = 0; i < numOptions; ++i) {
c += sprintf(optstring+c, "%c%s", (char)longopts[i].val,
longopts[i].has_arg == no_argument ? "" :
longopts[i].has_arg == required_argument ? ":" :
"::");
}
while ((c = getopt_long(argc, argv, optstring, longopts, &longindex)) >= 0) {
switch (c) {
case 'h':
usage(argc, argv);
break;
case 'p':
dumpParseTree = 1;
break;
case 'o':
outFile = strdup(optarg);
break;
case '?':
break;
default:
exit(1);
}
}
if (optind < argc) {
inFile = strdup(argv[optind]);
}
if (inFile == NULL) {
fprintf(stderr, "Error: Expected a source file path.\n");
exit(1);
}
if (outFile == NULL) {
fprintf(stderr, "Error: Expected an output file path.\n");
exit(1);
}
}
void
fatal(const char *fmt, ...)
{
va_list args;
fprintf(stderr, "%s(): Error: ", __func__);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
abort();
}
#define ERROR_CONTEXT 5
void
error(Token *token, const char *fmt, ...)
{
va_list args;
/*
* Print lines of context.
*/
fprintf(stderr, "Source context:\n");
Program *prog = token->private;
int first = token->line - (ERROR_CONTEXT / 2);
if (first < 0) {
first = 0;
}
int last = first + ERROR_CONTEXT;
int currentLine = first - 1;
int i;
for (i = 0; i < prog->tokenCount; i++) {
Token *thisToken = prog->tokenArray[i];
if (thisToken->line >= last) {
break;
}
if (thisToken->line >= first) {
if (thisToken->line > currentLine) {
while (thisToken->line > currentLine) {
fprintf(stderr, "\n");
currentLine++;
fprintf(stderr, " %4d: ", currentLine);
}
}
fprintf(stderr, "%s ", thisToken->string);
}
}
fprintf(stderr, "\n\n");
fprintf(stderr, "Line %d: ", token->line);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, " Token: %s\n", token->string);
abort();
}
static Token *
nextToken(Program *prog, int abortOnNull)
{
if (prog->i+1 >= prog->tokenCount) {
if (abortOnNull) {
abort();
}
return NULL;
}
prog->i++;
return prog->tokenArray[prog->i];
}
static int
isAlpha(char c)
{
if (((c >= 0x41) && (c <= 0x5A)) ||
((c >= 0x61) && (c <= 0x7A))) {
return 1;
}
return 0;
}
static int
isNum(char c)
{
if ((c >= 0x30) && (c <= 0x39)) {
return 1;
}
return 0;
}
static int
isIdentifier(char *token)
{
int i;
if ((token[0] != '_') && !isAlpha(token[0])) {
return 0;
}
for (i = 1; token[i] != '\0'; i++) {
if ((token[i] != '_') && !isAlpha(token[i]) && !isNum(token[i])) {
return 0;
}
}
return 1;
}
static int
isHex(char c)
{
if ((((c >= 0x41) && (c <= 0x46)) ||
((c >= 0x61) && (c <= 0x66))) ||
(isNum(c) != 0)) {
return 1;
}
return 0;
}
static int
isLiteralHex(char *token)
{
int i;
if (strncmp(token, "0x", 2) != 0) {
return 0;
}
for (i = 2; token[i] != '\0'; i++) {
if (isHex(token[i]) == 0) {
return 0;
}
}
if (i > 2) {
return 1;
}
return 2;
}
static int
isLiteralDec(char *token)
{
int i;
for (i = 0; token[i] != '\0'; i++) {
if (isNum(token[i]) == 0) {
return 0;
}
}
return 1;
}
static int
isLiteralStr(char *token)
{
int len = strlen(token);
if (len == 0) {
return 0;
}
if (token[0] == '"') {
int i, complete = 0;
for (i = 1; i < len; i++) {
if (token[i] == '\\') {
i++;
continue;
}
if (token[i] == '"') {
i++;
complete = 1;
break;
}
}
if (i < len) {
return 0;
}
if (complete) {
return 1;
}
return 2;
}
return 0;
}
static int
isLiteralChr(char *token)
{
int len = strlen(token);
if (len == 0) {
return 0;
}
if (token[0] == '\'') {
int i, complete = 0, chars = 1;
for (i = 1; i < len && chars < 3; i++) {
chars++;
if (token[i] == '\\') {
i++;
continue;
}
if (token[i] == '\'') {
i++;
complete = 1;
break;
}
}
if (i < len) {
return 0;
}
if (complete) {
return 1;
}
return 2;
}
return 0;
}
/*
* 0 Not a literal.
* 1 A literal.
* 2 An incomplete literal.
*/
static int
isLiteral(char *token, int *type)
{
int len = strlen(token);
int ret = 0;
if (type == NULL) {
fatal("Invalid argument.");
}
*type = 0;
if (len == 0) {
return 0;
}
/*
* Numeric literal.
*/
if ((ret = isLiteralHex(token)) != 0) {
*type = T_LITERAL_HEX;
return ret;
}
if (isLiteralDec(token) != 0) {
*type = T_LITERAL_DEC;
return 1;
}
if ((ret = isLiteralStr(token)) != 0) {
*type = T_LITERAL_STR;
return ret;
}
if ((ret = isLiteralChr(token)) != 0) {
*type = T_LITERAL_CHR;
return ret;
}
return 0;
}
static int
readUntil(Program *prog, FILE *fp, char *sentinel)
{
int c, i;
char token[4096];
int len = 0;
int sentinelLen = strlen(sentinel);
memset(token, 0, sizeof(token));
while (((c = fgetc(fp)) != EOF) && (ferror(fp) == 0)) {
if (c == '\n') {
prog->lineCount++;
}
if (len == sentinelLen) {
/*
* Shift characters left one place.
*/
for (i = 0; i < sentinelLen; i++) {
token[i] = token[i + 1];
}
len--;
}
token[len] = c;
len++;
if (strcmp(token, sentinel) == 0) {
return 0;
}
}
return -1;
}
/*
* Caller must free the token that is returned.
*/
static Token *
readToken(FILE *fp, Program *prog)
{
int c, i;
char buf[4096];
int type = T_TERMINAL;
int len = 0;
int partialMatch = 0;
int line = 0;
memset(buf, 0, sizeof(buf));
while (((c = fgetc(fp)) != EOF) && (ferror(fp) == 0)) {
if (c == '\n') {
prog->lineCount++;
}
if ((c == ' ') || (c == '\n') || (c == '\t')) {
/*
* White space is always a delimiter.
*/
if (partialMatch == 0) {
if (len == 0) {
continue;
}
break;
}
}
/*
* Add the char to the buf before we know if it will match.
* If it causes a mismatch, we will remove it.
*/
buf[len] = c;
len++;
if (len == 1) {
line = prog->lineCount;
}
if (strcmp(buf, "/*") == 0) {
/*
* Skip over multiline comment.
*/
if (readUntil(prog, fp, "*/") < 0) {
fatal("Failed to read until '*/'\n");
}
len = 0;
memset(buf, 0, sizeof(buf));
continue;
}
if (strcmp(buf, "//") == 0) {
/*
* Skip over single line comment.
*/
if (readUntil(prog, fp, "\n") < 0) {
fatal("Failed to read until '\\n'\n");
}
len = 0;
memset(buf, 0, sizeof(buf));
continue;
}
/*
* Find longest matching terminal.
*/
for (i = 0; i < NUM_SYMBOLS; i++) {
if (strcmp(symbols[i], buf) == 0) {
//fprintf(stderr, "Match: (%s) -> %s\n", symbols[i], buf);
break;
}
}
if (i < NUM_SYMBOLS) {
type = T_TERMINAL;
continue;
}
if (isIdentifier(buf) != 0) {
//fprintf(stderr, "Match ident: %s\n", buf);
type = T_IDENTIFIER;
continue;
}
int literalType;
i = isLiteral(buf, &literalType);
if (i != 0) {
type = literalType;
partialMatch = (i == 2) ? 1 : 0;
continue;
}
/*
* We didn't find a match. Remove the last char.
* Seek back and break.
*/
fseek(fp, -1, SEEK_CUR);
len--;
buf[len] = '\0';
break;
}
if (partialMatch != 0) {
fatal("Incomplete match: %s\n", buf);
}
if (ferror(fp) != 0) {
fatal("File error.\n");
}
if (len == 0) {
if (feof(fp) != 0) {
return NULL;
}
fatal("Failed to match next token.\n");
}
Token *token;
if ((token = malloc(sizeof(*token))) == NULL) {
fatal("Can't allocate token: %s\n", strerror(errno));
}
memset(token, 0, sizeof(*token));
token->string = strdup(buf);
token->type = type;
token->line = line;
token->private = prog;
return token;
}
static int
printToken(Token *token, int pretty)
{
char *type = "";
if (pretty == 0) {
fprintf(stderr, "%d ", token->line);
if (token->type == T_TERMINAL) {
type = "t";
}
else if (token->type & T_LITERAL) {
type = "l";
}
else if (token->type == T_IDENTIFIER) {
type = "i";
} else {
fatal("Token does not have a valid type?! %s\n", token->string);
}
fprintf(stderr, "%s: ", type);
}
fprintf(stderr, "%s", token->string);
if (pretty != 0) {
if (!strcmp(token->string, ";") ||
!strcmp(token->string, "{") ||
!strcmp(token->string, "}")) {
fprintf(stderr, "\n");
} else {
fprintf(stderr, " ");
}
} else {
fprintf(stderr, "\n");
}
return 0;
}
static int
lexer(char *path, Program *prog)
{
FILE *fp;
Token *token;
Token **tokenArray = NULL;
int tokenCount = 0;
if ((fp = fopen(path, "r")) == NULL) {
fatal("Can't open %s: %s\n", path, strerror(errno));
}
prog->lineCount = 1;
while (((token = readToken(fp, prog)) != NULL) &&
(token != (Token *)-1)) {
//printToken(token, 1);
/*
* Increase the token array size.
*/
tokenCount++;
tokenArray = realloc(tokenArray, sizeof(*tokenArray) * tokenCount);
if (tokenArray == NULL) {
fatal("Can't grow tokenArray: %s\n", strerror(errno));
abort();
}
tokenArray[tokenCount-1] = token;
}
prog->tokenArray = tokenArray;
prog->tokenCount = tokenCount;
prog->i = -1;
while ((token = nextToken(prog, 0)) != NULL) {
printToken(token, 1);
}
fprintf(stderr, "Read %d tokens on %d lines.\n",
tokenCount, tokenArray[tokenCount-1]->line);
prog->i = -1;
return 0;
}
static void
printType(Type *type, int newline)
{
int i;
printf("%s", type->token->string);
if (type->flags & TYPE_PTR) {
printf(" ");
for (i = 0; i < type->ptrCount; i++) {
printf("*");
}
}
if (newline) {
printf("\n");
}
}
static void
printParameter(Parameter *param)
{
printType(¶m->type, 0);
printf(" %s", param->name);
}
static void
printGlobalVariable(Variable *var)
{
printType(&var->type, 0);
printf(" %s", var->name);
if (var->value != NULL) {
printf(" = %s", var->value->string);
}
printf(";\n");
}
static void
printVariable(Variable *var)
{
printType(&var->type, 0);
printf(" %s", var->name);
if (var->value != NULL) {
printf(" = %s", var->value->string);
}
printf(";\n");
}
static void
printStruct(Struct *s)
{
printf("struct %s {\n", s->name);
ListEntry *entry = NULL;
while (listNext(&s->members, &entry) != NULL) {
Parameter *param = entry->data;
printParameter(param);
printf(";\n");
}
printf("}\n");
}
static void printExpression(Expression *e);
static void
printFunctionCall(FunctionCall *call)
{
printf("%s(", call->name);
ListEntry *entry = NULL;
while (listNext(&call->argExprList, &entry) != NULL) {
Expression *expr = entry->data;
printExpression(expr);
}
printf(")");
}
static void
printExpression(Expression *e)
{
//printf("E: ");
ListEntry *entry = NULL;
while (listNext(&e->postfix, &entry) != NULL) {
Oper *o = entry->data;
if (o->flags & EXPR_FUNC) {
printFunctionCall(o->call);
} else {
printf("%s ", o->token->string);
}
}
}
static void printStatement(Statement *s);
static void
printBlock(Statement *s)
{
printf(" {\n");
ListEntry *entry = NULL;
while (listNext(&s->statements, &entry) != NULL) {
Statement *s = entry->data;
printStatement(s);
}
printf("}\n");
}
static void
printConditionalBlock(Statement *s)
{
printf("(");
printExpression(s->expr);
printf(")");
printBlock(s);
}
static void
printStatement(Statement *s)
{
if (s->flags & STMT_IF) {
printf("if ");
printConditionalBlock(s);
} else if (s->flags & STMT_ELIF) {
printf("elif ");
printConditionalBlock(s);
} else if (s->flags & STMT_ELSE) {
printf("else ");
printBlock(s);
} else if (s->flags & STMT_WHILE) {
printf("while ");
printConditionalBlock(s);
} else if (s->flags & STMT_RETURN) {
printf("return ");
printExpression(s->expr);
printf(";\n");
} else if (s->flags & STMT_VAR_DECL) {
printVariable(s->var);
} else if (s->flags & STMT_EXPR) {
printExpression(s->expr);
printf(";\n");
}
}
static void
printFunction(Function *f)
{
printf("fn %s(", f->name);
ListEntry *entry = NULL;
while (listNext(&f->params, &entry) != NULL) {
Parameter *param = entry->data;
printParameter(param);
if (entry != f->params.tail) {
printf(", ");
}
}
printf(") ");
printType(&f->type, 0);
printf(" {\n");
entry = NULL;
while (listNext(&f->statements, &entry) != NULL) {
Statement *s = entry->data;
printStatement(s);
}
printf("}\n");
}
static void
print(Program *prog)
{
ListEntry *entry;
entry = NULL;
while (listNext(&prog->vars, &entry) != NULL) {
Variable *var = entry->data;
printGlobalVariable(var);
}
entry = NULL;
while (listNext(&prog->structs, &entry) != NULL) {
Struct *s = entry->data;
printStruct(s);
}
entry = NULL;
while (listNext(&prog->functions, &entry) != NULL) {
Function *f = entry->data;
printFunction(f);
}
}
/*
* == 0 on mismatch
* != 0 on match
*/