forked from jserv/amacc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amacc.c
2243 lines (2104 loc) · 82.4 KB
/
amacc.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
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
/*
* AMaCC is capable of compiling (subset of) C source files into GNU/Linux
* executables or running via just-in-time compilation on 32-bit ARM
* processor-based platforms. There is no preprocessor.
*
* The following options are supported:
* -s : Print source and generated intermediate representation (IR).
* -o : Create executable file and terminate normally.
*
* If -o and -s are omitted, the compiled code is executed immediately (if
* there were no compile errors) with the command line arguments passed
* after the source file parameter.
*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
/* 64-bit host support */
#if defined(__x86_64__) || defined(__aarch64__)
#define int long
#endif
char *freep, *p, *lp; // current position in source code
char *freedata, *data, *_data; // data/bss pointer
char **scnames; // system call names
int *e, *le, *text; // current position in emitted code
int *cas; // case statement patch-up pointer
int *brks; // break statement patch-up pointer
int *def; // default statement patch-up pointer
int *tsize; // array (indexed by type) of type sizes
int tnew; // next available type
int tk; // current token
int ival; // current token value
int ty; // current expression type
int loc; // local variable offset
int line; // current line number
int src; // print source and assembly flag
int signed_char; // use `signed char` for `char`
int elf; // print ELF format
int *n; // current position in emitted abstract syntax tree
// With an AST, the compiler is not limited to generate
// code on the fly with parsing.
// This capability allows function parameter code to be
// emitted and pushed on the stack in the proper
// right-to-left order.
int ld; // local variable depth
// identifier
struct ident_s {
int tk; // type-id or keyword
int hash;
char *name; // name of this identifier
/* fields starting with 'h' were designed to save and restore
* the global class/type/val in order to handle the case if a
* function declares a local with the same name as a global.
*/
int class, hclass; // FUNC, GLO (global var), LOC (local var), Syscall
int type, htype; // data type such as char and int
int val, hval;
int stype;
} *id, // currently parsed identifier
*sym; // symbol table (simple list of identifiers)
struct member_s {
struct ident_s *id;
int offset;
int type;
struct member_s *next;
} **members; // array (indexed by type) of struct member lists
// tokens and classes (operators last and in precedence order)
// ( >= 128 so not to collide with ASCII-valued tokens)
enum {
Num = 128, // the character set of given source is limited to 7-bit ASCII
Func, Syscall, Glo, Par, Loc, Id, Load, Enter,
Break, Case, Char, Default, Else, Enum, If, Int, Return, Sizeof,
Struct, Switch, For, While,
Assign, // operator =, keep Assign as highest priority operator
AddAssign, SubAssign, MulAssign, DivAssign, ModAssign, // +=, -=, *=, /=, %=
Cond, // operator: ?
Lor, Lan, Or, Xor, And, // operator: ||, &&, |, ^, &
Eq, Ne, Lt, Gt, Le, Ge, // operator: ==, !=, <, >, <=, >=
Shl, Shr, Add, Sub, Mul, Div, Mod, // operator: <<, >>, +, -, *, /, %
Inc, Dec, Dot, Arrow, Brak, // operator: ++, --, ., ->, [
};
// opcodes
/* The instruction set is designed for building intermediate representation.
* Expression 10 + 20 will be translated into the following instructions:
* i = 0;
* text[i++] = IMM;
* text[i++] = 10;
* text[i++] = PSH;
* text[i++] = IMM;
* text[i++] = 20;
* text[i++] = ADD;
* text[i++] = PSH;
* text[i++] = EXIT;
* pc = text;
*/
enum {
LEA , /* 0 */
/* LEA addressed the problem how to fetch arguments inside sub-function.
* Let's check out what a calling frame looks like before learning how
* to fetch arguments (Note that arguments are pushed in its calling
* order):
*
* sub_function(arg1, arg2, arg3);
*
* | .... | high address
* +---------------+
* | arg: 1 | new_bp + 4
* +---------------+
* | arg: 2 | new_bp + 3
* +---------------+
* | arg: 3 | new_bp + 2
* +---------------+
* |return address | new_bp + 1
* +---------------+
* | old BP | <- new BP
* +---------------+
* | local var 1 | new_bp - 1
* +---------------+
* | local var 2 | new_bp - 2
* +---------------+
* | .... | low address
*
* If we need to refer to arg1, we need to fetch new_bp + 4, which can not
* be achieved by restricted ADD instruction. Thus another special
* instrcution is introduced to do this: LEA <offset>.
* The following pseudocode illustrates how LEA works.
* if (op == LEA) { ax = (int) (bp + *pc++); } // load address for arguments
* Together with JSR, ENT, ADJ, LEV, and LEA instruction, we are able to make
* function calls.
*/
IMM , /* 1 */
/* IMM <num> to put immediate <num> into general register */
JMP , /* 2 */
/* JMP <addr> will unconditionally set the value PC register to <addr> */
/* The following pseudocode illustrates how JMP works:
* if (op == JMP) { pc = (int *) *pc; } // jump to the address
* Note that PC points to the NEXT instruction to be executed. Thus *pc
* stores the argument of JMP instruction, i.e. the <addr>.
*/
JSR , /* 3 */
/* A function is a block of code, which may be far from the instruction
* we are currently executing. That is reason why JMP instruction exists,
* jumping into starting point of a function. JSR is introduced to perform
* some bookkeeping: store the current execution position so that the
* program can resume after function call returns.
*
* JSR <addr> to invoke the function whose starting point is <addr> and
* LEV to fetch the bookkeeping information to resume previous execution.
*/
BZ , /* 4 : conditional jump if general register is zero */
BNZ , /* 5 : conditional jump if general register is not zero */
ENT , /* 6 */
/* ENT <size> is called when we are about to enter the function call to
* "make a new calling frame". It will store the current PC value onto
* the stack, and save some space(<size> bytes) to store the local
* variables for function.
*/
ADJ , /* 7 */
/* ADJ <size> is to adjust the stack, to "remove arguments from frame"
* The following pseudocode illustrates how ADJ works:
* if (op == ADJ) { sp += *pc++; } // add esp, <size>
*/
LEV , /* 8 */
/* LEV fetches bookkeeping info to resume previous execution.
* There is no POP instruction in our design, and the following pseudocode
* illustrates how LEV works:
* if (op == LEV) { sp = bp; bp = (int *) *sp++;
* pc = (int *) *sp++; } // restore call frame and PC
*/
LI , /* 9 */
/* LI loads an integer into general register from a given memory
* address which is stored in general register before execution.
*/
LC , /* 10 */
/* LC loads a character into general register from a given memory
* address which is stored in general register before execution.
*/
SI , /* 11 */
/* SI stores the integer in general register into the memory whose
* address is stored on the top of the stack.
*/
SC , /* 12 */
/* SC stores the character in general register into the memory whose
* address is stored on the top of the stack.
*/
PSH , /* 13 */
/* PSH pushes the value in general register onto the stack */
OR , /* 14 */ XOR , /* 15 */ AND , /* 16 */
EQ , /* 17 */ NE , /* 18 */
LT , /* 19 */ GT , /* 20 */ LE , /* 21 */ GE , /* 22 */
SHL , /* 23 */ SHR , /* 24 */
ADD , /* 25 */ SUB , /* 26 */ MUL , /* 27 */
/* arithmetic instructions
* Each operator has two arguments: the first one is stored on the top
* of the stack while the second is stored in general register.
* After the calculation is done, the argument on the stack will be poped
* out and the result will be stored in general register.
* So you are not able to fetch the first argument from the stack after
* the calculation.
*/
/* system call shortcuts */
OPEN,READ,WRIT,CLOS,PRTF,MALC,FREE,MSET,MCMP,MCPY,MMAP,DSYM,BSCH,STRT,DLOP,DIV,MOD,EXIT,
CLCA, /* clear cache, used by JIT compilation */
INVALID
};
// types
enum { CHAR, INT, PTR = 256, PTR2 = 512 };
// ELF generation
char **plt_func_addr;
char *append_strtab(char **strtab, char *str)
{
char *s;
for (s = str; *s && (*s != ' '); s++) ; /* ignore trailing space */
int nbytes = s - str + 1;
char *res = *strtab;
memcpy(res, str, nbytes);
res[s - str] = 0; // null terminator
*strtab = res + nbytes;
return res;
}
/* parse next token
* 1. store data into id and then set the id to current lexcial form
* 2. set tk to appropriate type
*/
void next()
{
char *pp;
/* using loop to ignore whitespace characters, but characters that
* cannot be recognized by the lexical analyzer are considered blank
* characters, such as '@' and '$'.
*/
while ((tk = *p)) {
++p;
if ((tk >= 'a' && tk <= 'z') || (tk >= 'A' && tk <= 'Z') ||
(tk == '_')) {
pp = p - 1;
while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') || (*p == '_'))
tk = tk * 147 + *p++; // 147 is the magic number generating hash value
tk = (tk << 6) + (p - pp); // hash plus symbol length
// hash value is used for fast comparison. Since it is inaccurate,
// we have to validate the memory content as well.
for (id = sym; id->tk; id++) { // find one free slot in table
if (tk == id->hash && /* if token is found (hash match), overwrite */
!memcmp(id->name, pp, p - pp)) {
tk = id->tk;
return;
}
}
/* At this point, existing symbol name is not found.
* "id" points to the first unused symbol table entry.
*/
id->name = pp;
id->hash = tk;
tk = id->tk = Id; // token type identifier
return;
}
/* Calculate the constant */
// first byte is a number, and it is considered a numerical value
else if (tk >= '0' && tk <= '9') {
/* Parse with 3 conditions:
* 1) not starting with 0 :=> decimal number;
* 2) starting with 0x :=> hex number;
* 3) starting with 0: octal number;
*/
if ((ival = tk - '0')) {
while (*p >= '0' && *p <= '9')
ival = ival * 10 + *p++ - '0';
}
// first digit is 0 and it starts with 'x', and it is considered
// to be a hexadecimal number
else if (*p == 'x' || *p == 'X') {
while ((tk = *++p) &&
((tk >= '0' && tk <= '9') ||
(tk >= 'a' && tk <= 'f') || (tk >= 'A' && tk <= 'F')))
ival = ival * 16 + (tk & 15) + (tk >= 'A' ? 9 : 0);
}
else { // considered octal
while (*p >= '0' && *p <= '7')
ival = ival * 8 + *p++ - '0';
}
tk = Num; // token is numeric, return
return;
}
switch (tk) {
case '\n':
/* Take an integer (representing an operation) and printing out
* the name of that operation. First thing to say is that "* ++le"
* is the integer representing the operation to perform.
* This basically walks through the array of instructions
* returning each integer in turn.
*
* Starting at the beginning of the line, we have "printf" with
* a format string of "%8.4s". This means print out the first 4
* characters of the string that we are about to pass next (padded
* to 8 characters). There then follows a string containing all of
* the operation names, in numerical order, padded to 4 characters
* and separated by commas (so the start of each is 5 apart).
*
* Finally, we do a lookup into this string (treating it as an
* array) at offset "* ++le * 5", i.e. the integer representing
* the operation multipled by "5", being the number of characters
* between the start of each operation name). Doing this lookup
* gives us a char, but actually we wanted the pointer to this
* char (as we want printf to print out this char and the
* following 3 chars), so we take the address of this char
* (the "&" at the beginning of the whole expression).
*/
if (src) {
printf("%d: %.*s", line, p - lp, lp);
lp = p;
while (le < e) {
printf("%8.4s",
& "LEA IMM JMP JSR BZ BNZ ENT ADJ LEV "
"LI LC SI SC PSH "
"OR XOR AND EQ NE LT GT LE GE "
"SHL SHR ADD SUB MUL "
"OPEN READ WRIT CLOS PRTF MALC FREE "
"MSET MCMP MCPY MMAP "
"DSYM BSCH STRT DLOP DIV MOD EXIT CLCA" [*++le * 5]);
if (*le <= ADJ) printf(" %d\n", *++le); else printf("\n");
}
}
++line;
case ' ':
case '\t':
case '\v':
case '\f':
case '\r':
break;
case '/':
if (*p == '/') { // comment
case '#': // skip #include statement, preprocessor directives ignored
while (*p != 0 && *p != '\n') ++p;
} else if (*p == '*') { // C-style multiline comments
int t = 0;
for (++p; (*p != 0) && (t == 0); ++p) {
pp = p + 1;
if (*p == '\n') line++;
else if (*p == '*' && *pp == '/') t = 1;
}
++p;
} else {
if (*p == '=') { ++p; tk = DivAssign; }
else tk = Div; return;
}
break;
case '\'': // quotes start with character (string)
case '"':
pp = data;
while (*p != 0 && *p != tk) {
if ((ival = *p++) == '\\') {
switch (ival = *p++) {
case 'n': ival = '\n'; break; // new line
case 't': ival = '\t'; break; // horizontal tab
case 'v': ival = '\v'; break; // vertical tab
case 'f': ival = '\f'; break; // form feed
case 'r': ival = '\r'; break; // carriage return
case '0': ival = '\0'; break; // an int with value 0
}
}
// if it is double quotes, it is considered as a string,
// copying characters to data
if (tk == '"') *data++ = ival;
}
++p;
// if .text too big rwdata v_addr will overlap it, add that to stay away from .text
if (tk == '"') ival = (int) pp; else tk = Num;
return;
case '=': if (*p == '=') { ++p; tk = Eq; } else tk = Assign; return;
case '+': if (*p == '+') { ++p; tk = Inc; }
else if (*p == '=') { ++p; tk = AddAssign; }
else tk = Add; return;
case '-': if (*p == '-') { ++p; tk = Dec; }
else if (*p == '>') { ++p; tk = Arrow; }
else if (*p == '=') { ++p; tk = SubAssign; }
else tk = Sub; return;
case '!': if (*p == '=') { ++p; tk = Ne; } return;
case '<': if (*p == '=') { ++p; tk = Le; }
else if (*p == '<') { ++p; tk = Shl; }
else tk = Lt; return;
case '>': if (*p == '=') { ++p; tk = Ge; }
else if (*p == '>') { ++p; tk = Shr; }
else tk = Gt; return;
case '|': if (*p == '|') { ++p; tk = Lor; }
else tk = Or; return;
case '&': if (*p == '&') { ++p; tk = Lan; }
else tk = And; return;
case '^': tk = Xor; return;
case '*': if (*p == '=') { ++p; tk = MulAssign; }
else tk = Mul; return;
case '%': if (*p == '=') { ++p; tk = ModAssign; }
else tk = Mod; return;
case '[': tk = Brak; return;
case '?': tk = Cond; return;
case '.': tk = Dot; return;
default: return;
}
}
}
char fatal(char *msg) { printf("%d: %s\n", line, msg); exit(-1); }
/* expression parsing
* lev represents an operator
* because each operator `token` is arranged in order of priority, so
* large `lev` indicates a high priority.
*/
void expr(int lev)
{
int otk;
int t, *b, sz, *c;
struct ident_s *d;
struct member_s *m;
switch (tk) {
case 0: fatal("unexpected EOF in expression");
// directly take an immediate value as the expression value
// IMM recorded in emit sequence
case Num: *--n = ival; *--n = Num; next(); ty = INT; break;
case '"': // string, as a literal in data segment
*--n = ival; *--n = Num; next();
// continuous `"` handles C-style multiline text such as `"abc" "def"`
while (tk == '"') next();
/* Point "data" to next integer-aligned address.
* e.g. "-sizeof(int)" is -4, i.e. 0b11111100.
* This guarantees to leave at least one '\0' after the string.
*
* append the end of string character '\0', all the data is defaulted
* to 0, so just move data one position forward. Specify result value
* type to char pointer. CHAR + PTR = PTR because CHAR is 0.
*/
data = (char *) (((int) data + sizeof(int)) & (-sizeof(int)));
ty = PTR;
break;
/* SIZEOF_expr -> 'sizeof' '(' 'TYPE' ')'
* sizeof is actually an unary operator.
* now only `sizeof(int)`, `sizeof(char)` and `sizeof(*...)` are supported.
* FIXME: not support "sizeof (Id)".
* In second line will not get next token, match ')' will fail.
*/
case Sizeof:
next();
if (tk == '(') next();
else fatal("open paren expected in sizeof");
ty = INT;
switch (tk) {
case Int: next(); break;
case Char: next(); ty = CHAR; break;
case Struct:
next();
if (tk != Id) fatal("bad struct type");
ty = id->stype; next(); break;
}
// multi-level pointers, plus `PTR` for each level
while (tk == Mul) { next(); ty += PTR; }
if (tk == ')') next();
else fatal("close paren expected in sizeof");
*--n = ty >= PTR ? sizeof(int) : tsize[ty]; *--n = Num;
ty = INT;
break;
case Id:
d = id; next();
// function call
if (tk == '(') {
if (d->class != Syscall && d->class != Func)
fatal("bad function call");
next();
t = 0; b = 0; // parameters count
while (tk != ')') {
expr(Assign); *--n = (int) b; b = n; ++t;
if (tk == ',') {
next();
if (tk == ')') fatal("unexpected comma in function call");
} else if (tk != ')') fatal("missing comma in function call");
}
next();
// function or system call id
*--n = t; *--n = d->val; *--n = (int) b; *--n = d->class;
ty = d->type;
}
// enumeration, only enums have ->class == Num
else if (d->class == Num) { *--n = d->val; *--n = Num; ty = INT; }
else {
// Variable get offset
switch (d->class) {
case Loc: case Par: *--n = loc - d->val; *--n = Loc; break;
case Glo: *--n = d->val; *--n = Num; break;
default: fatal("undefined variable");
}
*--n = ty = d->type; *--n = Load;
}
break;
// Type cast or parenthesis
case '(':
next();
if (tk == Int || tk == Char || tk == Struct) {
switch (tk) {
case Int: next(); t = INT; break;
case Char: next(); t = CHAR; break;
default:
next();
if (tk != Id) fatal("bad struct type");
t = id->stype; next(); break;
}
// t: pointer
while (tk == Mul) { next(); t += PTR; }
if (tk == ')') next();
else fatal("bad cast");
expr(Inc); // cast has precedence as Inc(++)
ty = t;
}
else {
expr(Assign);
if (tk == ')') next();
else fatal("close paren expected");
}
break;
case Mul: // "*", dereferencing the pointer operation
next();
expr(Inc); // dereference has the same precedence as Inc(++)
if (ty >= PTR) ty -= PTR;
else fatal("bad dereference");
if (ty >= CHAR && ty <= PTR) {
*--n = ty; *--n = Load;
} else fatal("unexpected type");
break;
case And: // "&", take the address operation
/* when "token" is a variable, it takes the address first and
* then LI/LC, so `--e` becomes the address of "a".
*/
next(); expr(Inc);
if (*n == Load) n += 2; else fatal("bad address-of");
ty += PTR;
break;
case '!': // "!x" is equivalent to "x == 0"
next(); expr(Inc);
if (*n == Num) n[1] = !n[1];
else { *--n = 0; *--n = Num; --n; *n = (int) (n + 3); *--n = Eq; }
ty = INT;
break;
case '~': // "~x" is equivalent to "x ^ -1"
next(); expr(Inc);
if (*n == Num) n[1] = ~n[1];
else { *--n = -1; *--n = Num; --n; *n = (int) (n + 3); *--n = Xor; }
ty = INT;
break;
case Add:
next(); expr(Inc); ty = INT;
break;
case Sub:
next();
expr(Inc);
if (*n == Num) n[1] = -n[1];
else { *--n = -1; *--n = Num; --n; *n = (int) (n + 3); *--n = Mul; }
ty = INT;
break;
case Div:
case Mod:
break;
// processing ++x and --x. x-- and x++ is handled later
case Inc:
case Dec:
t = tk; next(); expr(Inc);
if (*n == Load) *n = t; else fatal("bad lvalue in pre-increment");
break;
default: fatal("bad expression");
}
// "precedence climbing" or "Top Down Operator Precedence" method
while (tk >= lev) {
// tk is ASCII code will not exceed `Num=128`. Its value may be changed
// during recursion, so back up currently processed expression type
t = ty; b = n;
switch (tk) {
case Assign:
next();
// the left part is processed by the variable part of `tk=ID`
// and pushes the address
if (*n != Load) { fatal("bad lvalue in assignment");}
// get the value of the right part `expr` as the result of `a=expr`
expr(Assign); *--n = (int) (b + 2); *--n = ty = t; *--n = Assign;
break;
case AddAssign: // right associated
case SubAssign:
case MulAssign:
case DivAssign:
case ModAssign:
otk = tk;
*--n=';'; *--n = ty = id->type; *--n = Load;
sz = (ty = t) >= PTR2 ? sizeof(int) :
ty >= PTR ? tsize[ty - PTR] : 1;
next(); c = n; expr(otk);
if (*n == Num) n[1] *= sz;
*--n = (int) c; *--n = Add + (otk - AddAssign);
*--n = (int) (b + 2); *--n = ty = t; *--n = Assign;
ty = INT;
break;
case Cond: // `x?a:b` is similar to if except that it relies on else
next(); expr(Assign);
if (tk == ':') next();
else fatal("conditional missing colon"); c = n;
expr(Cond); --n;
*n = (int) (n + 1); *--n = (int) c; *--n = (int) b; *--n = Cond;
break;
case Lor: // short circuit, the logical or
next(); expr(Lan);
if (*n == Num && *b == Num) n[1] = b[1] || n[1];
else { *--n = (int) b; *--n = Lor; }
ty = INT;
break;
case Lan: // short circuit, logic and
next(); expr(Or);
if (*n == Num && *b == Num) n[1] = b[1] && n[1];
else { *--n = (int) b; *--n = Lan; }
ty = INT;
break;
case Or: // push the current value, calculate the right value
next(); expr(Xor);
if (*n == Num && *b == Num) n[1] = b[1] | n[1];
else { *--n = (int) b; *--n = Or; }
ty = INT;
break;
case Xor:
next(); expr(And);
if (*n == Num && *b == Num) n[1] = b[1] ^ n[1];
else { *--n = (int) b; *--n = Xor; }
ty = INT;
break;
case And:
next(); expr(Eq);
if (*n == Num && *b == Num) n[1] = b[1] & n[1];
else { *--n = (int) b; *--n = And; }
ty = INT;
break;
case Eq:
next(); expr(Lt);
if (*n == Num && *b == Num) n[1] = b[1] == n[1];
else { *--n = (int) b; *--n = Eq; }
ty = INT;
break;
case Ne:
next(); expr(Lt);
if (*n == Num && *b == Num) n[1] = b[1] != n[1];
else { *--n = (int) b; *--n = Ne; }
ty = INT;
break;
case Lt:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] < n[1];
else { *--n = (int) b; *--n = Lt; }
ty = INT;
break;
case Gt:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] > n[1];
else { *--n = (int) b; *--n = Gt; }
ty = INT;
break;
case Le:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] <= n[1];
else { *--n = (int) b; *--n = Le; }
ty = INT;
break;
case Ge:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] >= n[1];
else { *--n = (int) b; *--n = Ge; }
ty = INT;
break;
case Shl:
next(); expr(Add);
if (*n == Num && *b == Num) {
if (n[1] < 0) n[1] = b[1] >> -n[1];
else n[1] = b[1] << n[1];
} else { *--n = (int) b; *--n = Shl; }
ty = INT;
break;
case Shr:
next(); expr(Add);
if (*n == Num && *b == Num) {
if (n[1] < 0) n[1] = b[1] << -n[1];
else n[1] = b[1] >> n[1];
} else { *--n = (int) b; *--n = Shr; }
ty = INT;
break;
case Add:
next(); expr(Mul);
sz = (ty = t) >= PTR2 ? sizeof(int) :
ty >= PTR ? tsize[ty - PTR] : 1;
if (*n == Num) n[1] *= sz;
if (*n == Num && *b == Num) n[1] += b[1];
else { *--n = (int) b; *--n = Add; }
break;
case Sub:
next(); expr(Mul);
sz = t >= PTR2 ? sizeof(int) : t >= PTR ? tsize[t - PTR] : 1;
if (sz > 1 && *n == Num) {
*--n = sz; *--n = Num; --n; *n = (int) (n + 3); *--n = Mul;
}
if (*n == Num && *b == Num) n[1] -= b[1];
else {
*--n = (int) b; *--n = Sub;
if (t == ty && sz > 1) {
switch (sz) {
case 4: *--n = 2; *--n = Num; --n; *n = (int) (n + 3);
*--n = Shr; break;
default: *--n = sz; *--n = Num; --n; *n = (int) (n + 3);
*--n = Sub;
}
}
}
break;
case Mul:
next(); expr(Inc);
if (*n == Num && *b == Num) n[1] *= b[1];
else { *--n = (int) b; *--n = Mul; }
ty = INT;
break;
case Inc:
case Dec:
sz = ty >= PTR2 ? sizeof(int) : ty >= PTR ? tsize[ty - PTR] : 1;
if (*n == Load) *n = tk; else fatal("bad lvalue in post-increment");
*--n = sz; *--n = Num;
*--n = (int) b; *--n = (tk == Inc) ? Sub : Add;
next();
break;
case Div:
next(); expr(Inc);
if (*n == Num && *b == Num) n[1] /= b[1];
else { *--n = (int) b; *--n = Div; }
ty = INT;
break;
case Mod:
next(); expr(Inc);
if (*n == Num && *b == Num) n[1] %= b[1];
else { *--n = (int) b; *--n = Mod; }
ty = INT;
break;
case Dot:
ty += PTR;
case Arrow:
if (ty <= PTR+INT || ty >= PTR2) fatal("structure expected");
next();
if (tk != Id) fatal("structure member expected");
m = members[ty - PTR]; while (m && m->id != id) m = m->next;
if (!m) fatal("structure member not found");
if (m->offset) {
*--n = m->offset; *--n = Num; --n; *n = (int) (n + 3);
*--n = Add;
}
ty = m->type;
if (ty <= INT || ty >= PTR) *--n = (ty == CHAR) ? CHAR : INT;
*--n = Load;
next();
break;
case Brak:
next(); expr(Assign);
if (tk == ']') next();
else fatal("close bracket expected");
if (t < PTR) fatal("pointer type expected");
sz = (t = t - PTR) >= PTR ? sizeof(int) : tsize[t];
if (sz > 1) {
if (*n == Num) n[1] *= sz;
else {
*--n = sz; *--n = Num; --n; *n = (int) (n + 3); *--n = Mul;
}
}
if (*n == Num && *b == Num) n[1] += b[1];
else { *--n = (int) b; *--n = Add; }
if ((ty = t) <= INT || ty >= PTR)
*--n = (ty == CHAR) ? CHAR : INT;
*--n = Load;
break;
default:
printf("%d: compiler error tk=%d\n", line, tk); exit(-1);
}
}
}
// AST parsing for IR generatiion
// With a modular code generator, new targets can be easily supported such as
// native Arm machine code.
void gen(int *n)
{
int i = *n, j, k, l;
int *a, *b, *c, *d;
switch (i) {
case Num: // get the value of integer
*++e = IMM; *++e = n[1];
break;
case Loc: // get the value of variable
*++e = LEA; *++e = n[1];
break;
case Load:
gen(n + 2); // load the value
if (n[1] <= INT || n[1] >= PTR) { *++e = (n[1] == CHAR) ? LC : LI; }
break;
case Assign: // assign the value to variables
gen((int *) n[2]); *++e = PSH; gen(n + 3);
// Add SC/SI instruction to save value in register to variable address
// held on stack.
*++e = (n[1] == CHAR) ? SC : SI;
break;
// increment or decrement variables
case Inc:
case Dec:
gen(n + 2);
*++e = PSH; *++e = (n[1] == CHAR) ? LC : LI; *++e = PSH;
*++e = IMM; *++e = (n[1] >= PTR2) ? sizeof(int) :
n[1] >= PTR ? tsize[n[1] - PTR] : 1;
*++e = (i == Inc) ? ADD : SUB;
*++e = (n[1] == CHAR) ? SC : SI;
break;
case Cond: // if else condition case
gen((int *) n[1]); // condition
// Add jump-if-zero instruction "BZ" to jump to false branch.
// Point "b" to the jump address field to be patched later.
*++e = BZ; b = ++e;
gen((int *) n[2]); // expression
// Patch the jump address field pointed to by "b" to hold the address
// of false branch. "+ 3" counts the "JMP" instruction added below.
//
// Add "JMP" instruction after true branch to jump over false branch.
// Point "b" to the jump address field to be patched later.
if (n[3]) {
*b = (int) (e + 3); *++e = JMP; b = ++e; gen((int *) n[3]);
} // else statment
// Patch the jump address field pointed to by "d" to hold the address
// past the false branch.
*b = (int) (e + 1);
break;
// operators
/* If current token is logical OR operator:
* Add jump-if-nonzero instruction "BNZ" to implement short circuit.
* Point "b" to the jump address field to be patched later.
* Parse RHS expression.
* Patch the jump address field pointed to by "b" to hold the address past
* the RHS expression.
*/
case Lor: gen((int *) n[1]); *++e = BNZ;
b = ++e; gen(n + 2); *b = (int) (e + 1); break;
case Lan: gen((int *) n[1]); *++e = BZ;
b = ++e; gen(n + 2); *b = (int) (e + 1); break;
/* If current token is bitwise OR operator:
* Add "PSH" instruction to push LHS value in register to stack.
* Parse RHS expression.
* Add "OR" instruction to compute the result.
*/
case Or: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = OR; break;
case Xor: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = XOR; break;
case And: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = AND; break;
case Eq: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = EQ; break;
case Ne: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = NE; break;
case Lt: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = LT; break;
case Gt: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = GT; break;
case Le: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = LE; break;
case Ge: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = GE; break;
case Shl: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = SHL; break;
case Shr: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = SHR; break;
case Add: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = ADD; break;
case Sub: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = SUB; break;
case Mul: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = MUL; break;
case Div: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = DIV; break;
case Mod: gen((int *) n[1]); *++e = PSH; gen(n + 2); *++e = MOD; break;
case Syscall:
case Func:
c = b = (int *) n[1]; k = 0; l = 1;
// how many parameters
while (b && l) { ++k; if (!(int *) *b) l = 0; else b = (int *) *b; }
j = 0; a = malloc(sizeof(int *) * k); b = c; l = 1;
while (b && l) {
a[j] = (int) b;
if (!(int *) *b) l = 0; else b = (int *) *b; ++j;
}
if (j > 0) --j;
// push parameters
while (j >= 0 && k > 0) {
gen(b + 1); *++e = PSH; --j; b = (int *) a[j];
}
free(a);
if (i == Func) *++e = JSR; *++e = n[2];
if (n[3]) { *++e = ADJ; *++e = n[3]; }
break;
case While:
d = (e + 1);
gen((int *) n[1]); // condition
*++e = BZ; b = ++e;
gen(n + 2); // expression
*++e = JMP; *++e = (int) d;
*b = (int) (e + 1);
break;
case For:
gen((int *) n[4]);
a = (e + 1);
gen((int *) n[1]);
*++e = BZ; d = ++e;
*++e = JMP; c = ++e;
b = (e + 1);
gen((int *) n[2]); // area b
*++e = JMP; *++e = (int) a;
*c = (int) (e + 1);
gen((int *) n[3]); // area c
*++e = JMP; *++e = (int) b;
*d = (int) (e + 1);
break;
case Switch:
gen((int *) n[1]); // condition
a = cas; *++e = JMP; cas = ++e;
b = brks; d = def; brks = def = 0;
gen((int *) n[2]); // case statment
// deal with no default inside switch case
*cas = def ? (int) def : (int) (e + 1); cas = a;
while (brks) { a = (int *) * brks; *brks = (int) (e + 1); brks = a; }
brks = b; def = d;
break;
case Case:
*++e = JMP; ++e;
a = 0;
*e = (int) (e + 7); *++e = PSH; i = *cas; *cas = (int) e;
gen((int *) n[1]); // condition
if (e[-1] != IMM) fatal("bad case immediate");
*++e = SUB; *++e = BNZ; cas = ++e; *e = i + e[-3];
if (*(int *) n[2] == Switch) a = cas;
gen((int *) n[2]); // expression
if (a != 0) cas = a;
break;
case Break:
// set jump locate
*++e = JMP; *++e = (int) brks; brks = e;
break;
case Default:
def = e + 1;
gen((int *) n[1]); break;
case Return:
if (n[1]) gen((int *) n[1]); *++e = LEV; break; // parse return AST
case '{':
// parse expression or statment from AST
gen((int *) n[1]); gen(n + 2); break;
case Enter: *++e = ENT; *++e = n[1]; gen(n + 2);
if (*e != LEV) *++e = LEV; break;
default:
if (i != ';') {
printf("%d: compiler error gen=%d\n", line, i); exit(-1);
}
}
}
// statement parsing (syntax analysis, except for declarations)
void stmt(int ctx)
{
int *a, *b, *c, *d, *f;
int i, j;
int bt, ty;
struct member_s *m;
switch (tk) {
case Enum:
next();
// If current token is not "{", it means having enum type name.
// Skip the enum type name.
if (tk != '{') next();
if (tk == '{') {
next();
i = 0; // Enum value starts from 0
while (tk != '}') {