-
Notifications
You must be signed in to change notification settings - Fork 0
/
preproc.c
1184 lines (1034 loc) · 36.4 KB
/
preproc.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
#include "mimicc.h"
#include <string.h>
typedef struct Macro Macro;
struct Macro {
Macro *next;
Token *token; // Macro name.
Token *replace; // Replacement-list is tokens, until "TokenNewLine" appears.
int isFunc; // TRUE if macro is function-like macro.
Token *args; // Argument list of function-like macro.
};
// Structure to use in function-like macro expansion. Holds which tokens are
// replacement tokens of a macro arguments.
typedef struct MacroArg MacroArg;
struct MacroArg {
MacroArg *next;
Token *name; // Argument name
Token *begin; // Start of replacement
Token *end; // End of replacement
};
typedef struct Range Range;
struct Range {
Token *begin;
Token *end;
};
typedef struct Preproc Preproc;
struct Preproc {
Macro *macros; // All macro list.
int expandDefined; // If TRUE, expand "define(macro)" macro.
};
static Preproc preproc;
static Macro *newMacro(Token *token, Token *replace) {
Macro *macro = (Macro *)safeAlloc(sizeof(Macro));
macro->token = token;
macro->replace = replace;
return macro;
}
// Search for macro named "name" in all macro list, and returns the matched
// macro object if found. If macro not found, returns NULL instead.
static Macro *findMacro(Token *name) {
for (Macro *macro = preproc.macros; macro; macro = macro->next) {
if (matchToken(macro->token, name->str, name->len)) {
return macro;
}
}
return NULL;
}
static int matchTokenReserved(Token *token, const char *name) {
return token->type == TokenReserved && matchToken(token, name, strlen(name));
}
static int matchTokenIdent(Token *token, const char *name) {
return token->type == TokenIdent && matchToken(token, name, strlen(name));
}
static int consumeTokenReserved(Token **token, const char *name) {
if (matchTokenReserved(*token, name)) {
*token = (*token)->next;
return 1;
}
return 0;
}
static int consumeTokenIdent(Token **token, const char *name) {
if (matchTokenIdent(*token, name)) {
*token = (*token)->next;
return 1;
}
return 0;
}
static Token *consumeTokenAnyIdent(Token **token) {
if ((*token)->type == TokenIdent) {
Token *ident = *token;
*token = (*token)->next;
return ident;
}
return NULL;
}
static int consumeTokenCertainType(Token **token, TokenType type) {
if ((*token)->type == type) {
(*token) = (*token)->next;
return 1;
}
return 0;
}
static Token *newTokenSOF(void) {
Token *token = (Token *)safeAlloc(sizeof(Token));
token->type = TokenSOF;
return token;
}
static Token *newTokenEOF(void) {
Token *token = (Token *)safeAlloc(sizeof(Token));
token->type = TokenEOF;
return token;
}
static Token *newTokenDummyReserved(char *op) {
Token *token = (Token *)safeAlloc(sizeof(Token));
token->type = TokenReserved;
token->str = op;
token->len = strlen(op);
return token;
}
// Clone token, but clears "next" and "prev" entry with NULL.
static Token *cloneToken(Token *token) {
Token *clone = (Token *)safeAlloc(sizeof(Token));
*clone = *token;
clone->next = clone->prev = NULL;
return clone;
}
// Clone token by range [begin, end].
static Token *cloneTokenList(Token *begin, Token *end) {
Token head = {};
Token *clones = &head;
end = end->next;
for (Token *token = begin; token != end; token = token->next) {
Token *next = cloneToken(token);
clones->next = next;
next->prev = clones;
clones = next;
}
if (head.next)
head.next->prev = NULL;
return head.next;
}
static void concatToken(Token *first, Token *second) {
first->next = second;
second->prev = first;
}
static void insertTokens(Token *pos, Token *begin, Token *end) {
// No need to NULL check.
Token *next = pos->next;
pos->next = begin;
begin->prev = pos;
end->next = next;
next->prev = end;
}
static void insertToken(Token *pos, Token *token) {
Token *next = pos->next;
pos->next = token;
token->prev = pos;
token->next = next;
next->prev = token;
}
// Skip tokens until "TokenNewLine" appears, and returns the pointer to it.
static Token *skipUntilNewline(Token *token) {
while (token->type != TokenNewLine)
token = token->next;
return token;
}
// Parse "#define" directive and returns one token after the token at the end
// of this "#define" directive. Note that "token" parameter must points the
// "#" token of "#define".
static Token *parseDefineDirective(Token *token) {
Macro *macro = NULL;
Token *macroName = NULL;
Token *tokenHash = token;
Token *nextLine = NULL;
if (!(consumeTokenReserved(&token, "#") && consumeTokenIdent(&token, "define")))
errorUnreachable();
macroName = consumeTokenAnyIdent(&token);
if (!macroName) {
errorAt(token, "Macro name expected.");
} else if (matchToken(macroName, "defined", 7)) {
errorAt(macroName, "Cannot define macro named \"defined\"");
} else if (findMacro(macroName)) {
errorAt(macroName, "Redefinition of macro.");
}
macro = newMacro(macroName, macroName->next);
macro->next = preproc.macros;
preproc.macros = macro;
// Check for function-like macro. Function-like macro doesn't allow any
// white-spaces between identifier and lbrace, e.g.:
// #define FUNC(args) // Function-like macro
// #define NOT_FUNC (args) // Not a function-like macro
// So, we need to check not only there's a "(" after identifier but also
// there's no white-spaces between identifier and "(".
if (matchTokenReserved(token, "(") &&
(token->prev->str + token->prev->len) == token->str) {
macro->isFunc = 1;
consumeTokenReserved(&token, "(");
if (!consumeTokenReserved(&token, ")")) {
Token head = {};
Token *cur = &head;
for (;;) {
Token *arg = consumeTokenAnyIdent(&token);
if (!arg)
errorAt(token, "An identifier is expected.");
arg = cloneToken(arg);
cur->next = arg;
arg->prev = cur;
cur = cur->next;
if (consumeTokenReserved(&token, ")"))
break;
else if (!consumeTokenReserved(&token, ","))
errorAt(token, "',' or ')' is expected.");
}
macro->args = head.next;
}
macro->replace = token;
}
nextLine = skipUntilNewline(token)->next;
popTokenRange(tokenHash, nextLine->prev);
return nextLine;
}
// Parse "#undef" directive and returns one token after the token at the
// end of this "#undef" directive. Note that "token" parameter must points the
// "#" token of "#define".
static Token *parseUndefDirective(Token *token) {
Token *head = token;
Token *name = NULL;
Token *nextLine = NULL;
Macro *macro = NULL;
if (!(consumeTokenReserved(&token, "#") && consumeTokenIdent(&token, "undef")))
errorUnreachable();
name = consumeTokenAnyIdent(&token);
if (!name)
errorAt(token, "Macro name expected.");
macro = findMacro(name);
if (!macro)
errorAt(name, "Undefined macro.");
if (macro->next) {
Macro *tofree = macro->next;
*macro = *macro->next;
safeFree(tofree);
} else {
// Macro is at the end of entry.
if (preproc.macros != macro) {
Macro *prev = preproc.macros;
while (prev->next != macro)
prev = prev->next;
prev->next = NULL;
} else {
preproc.macros = NULL;
}
safeFree(macro);
}
nextLine = skipUntilNewline(head)->next;
popTokenRange(head, nextLine->prev);
return nextLine;
}
// Parse "#include" directive and returns one token after the token at the end
// of this "#include" directive. Note that "token" parameter must points the
// "#" token of "#include".
static Token *parseIncludeDirective(Token *token) {
Range src = {}; // This "#include" directive
Range dest = {}; // Embedded file contents.
Token *retpos = NULL;
FilePath *file = NULL;
char *source = NULL;
src.begin = token;
src.end = skipUntilNewline(token);
if (!(consumeTokenReserved(&token, "#") && consumeTokenIdent(&token, "include")))
errorUnreachable();
if (!(token->type == TokenLiteralString || matchTokenReserved(token, "<"))) {
// Maybe macro is following after "#include".
// TODO: Implement
}
if (token->type == TokenLiteralString) {
// #include "..."
char *header = token->literalStr->string;
if (header[0] == '/') { // Full path
file = analyzeFilepath(header, header);
} else {
char *path =
(char *)safeAlloc(strlen(token->file->dirname) + strlen(header) + 1);
sprintf(path, "%s%s", token->file->dirname, header);
file = analyzeFilepath(path, header);
}
} else if (consumeTokenReserved(&token, "<")) {
// #include <...>
Range header = {};
char *headerName = NULL;
char *headerPath = NULL;
int headerLen = 0;
header.begin = token;
for (Token *cur = token;; cur = cur->next) {
if (matchTokenReserved(cur, ">")) {
if (cur == token)
errorAt(token->prev, "Missing file name.");
header.end = cur->prev;
break;
} else if (cur->type == TokenNewLine) {
errorAt(cur, "\"#include <FILENAME>\" directive not terminated.");
} else if (cur->type == TokenEOF) {
errorAt(cur, "Unexpected EOF.");
}
}
headerLen = (int)(header.end->next->str - header.begin->str);
headerName = (char *)safeAlloc(headerLen + 1);
memcpy(headerName, header.begin->str, headerLen);
headerName[headerLen] = '\0';
headerPath = (char *)safeAlloc(strlen(globals.includePath) + headerLen + 1);
sprintf(headerPath, "%s%s", globals.includePath, headerName);
file = analyzeFilepath(headerPath, headerName);
} else {
errorAt(token, "Must be <FILENAME> or \"FILENAME\".");
}
source = readFile(file->path);
dest.begin = tokenize(source, file);
dest.end = dest.begin;
while (dest.end->type != TokenEOF)
dest.end = dest.end->next;
retpos = dest.begin->next;
insertTokens(src.end, dest.begin->next, dest.end->prev);
popTokenRange(src.begin, src.end);
return retpos;
}
static Node *newNode(NodeKind kind, Token *token) {
Node *n = (Node *)safeAlloc(sizeof(Node));
n->kind = kind;
n->token = token;
return n;
}
static Node *newNodeBinary(NodeKind kind, Token *token, Node *lhs, Node *rhs) {
Node *n = newNode(kind, token);
n->lhs = lhs;
n->rhs = rhs;
return n;
}
static Node *parseIfCond(Token **token);
static Node *parseIfCondPrimary(Token **token) {
if (consumeTokenReserved(token, "(")) {
Node *n = parseIfCond(token);
if (!consumeTokenReserved(token, ")"))
errorAt(*token, "\")\" is expected.");
return n;
} else if ((*token)->type == TokenNumber) {
Node *n = newNode(NodeNum, *token);
n->val = (*token)->val;
*token = (*token)->next;
return n;
} else {
errorAt(*token, "Unexpected token.");
}
}
static Node *parseIfCondUnary(Token **token) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "+") || consumeTokenReserved(token, "-")) {
Node *lhs = newNode(NodeNum, tokenOp);
Node *rhs = parseIfCondUnary(token);
Node *n = newNodeBinary(NodeAdd, tokenOp, lhs, rhs);
if (tokenOp->str[0] == '-')
n->kind = NodeSub;
return n;
} else if (consumeTokenReserved(token, "!")) {
Node *rhs = parseIfCondUnary(token);
Node *n = newNode(NodeNot, tokenOp);
n->rhs = rhs;
return n;
} else {
return parseIfCondPrimary(token);
}
}
static Node *parseIfCondMul(Token **token) {
Node *n = parseIfCondUnary(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "*") || consumeTokenReserved(token, "/") ||
consumeTokenReserved(token, "%")) {
Node *lhs = n;
Node *rhs = parseIfCondUnary(token);
n = newNodeBinary(NodeMul, tokenOp, lhs, rhs);
if (tokenOp->str[0] == '/')
n->kind = NodeDiv;
else if (tokenOp->str[0] == '%')
n->kind = NodeDivRem;
} else {
return n;
}
}
}
static Node *parseIfCondAdd(Token **token) {
Node *n = parseIfCondMul(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "+") || consumeTokenReserved(token, "-")) {
Node *lhs = n;
Node *rhs = parseIfCondMul(token);
n = newNodeBinary(NodeAdd, tokenOp, lhs, rhs);
if (tokenOp->str[0] == '-')
n->kind = NodeSub;
} else {
return n;
}
}
}
static Node *parseIfCondShift(Token **token) {
Node *n = parseIfCondAdd(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "<<") || consumeTokenReserved(token, ">>")) {
Node *lhs = n;
Node *rhs = parseIfCondAdd(token);
n = newNodeBinary(NodeArithShiftL, tokenOp, lhs, rhs);
if (tokenOp->str[0] == '>')
n->kind = NodeArithShiftR;
} else {
return n;
}
}
}
static Node *parseIfCondRelational(Token **token) {
Node *n = parseIfCondShift(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "<") || consumeTokenReserved(token, "<=")) {
Node *lhs = n;
Node *rhs = parseIfCondShift(token);
n = newNodeBinary(NodeLT, tokenOp, lhs, rhs);
if (tokenOp->len == 2)
n->kind = NodeLE;
} else if (consumeTokenReserved(token, ">") ||
consumeTokenReserved(token, ">=")) {
Node *lhs = parseIfCondShift(token);
Node *rhs = n;
n = newNodeBinary(NodeLT, tokenOp, lhs, rhs);
if (tokenOp->len == 2)
n->kind = NodeLE;
} else {
return n;
}
}
}
static Node *parseIfCondEquality(Token **token) {
Node *n = parseIfCondRelational(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "==") || consumeTokenReserved(token, "!=")) {
n = newNodeBinary(NodeEq, tokenOp, n, parseIfCondRelational(token));
if (tokenOp->str[0] == '!')
n->kind = NodeNeq;
} else {
return n;
}
}
}
static Node *parseIfCondANDexpr(Token **token) {
Node *n = parseIfCondEquality(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "&")) {
n = newNodeBinary(NodeBitwiseAND, tokenOp, n, parseIfCondEquality(token));
} else {
return n;
}
}
}
static Node *parseIfCondORexpr(Token **token) {
Node *n = parseIfCondANDexpr(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "|")) {
n = newNodeBinary(NodeBitwiseOR, tokenOp, n, parseIfCondANDexpr(token));
} else {
return n;
}
}
}
static Node *parseIfCondXORexpr(Token **token) {
Node *n = parseIfCondORexpr(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "^")) {
n = newNodeBinary(NodeBitwiseXOR, tokenOp, n, parseIfCondORexpr(token));
} else {
return n;
}
}
}
static Node *parseIfCondLogicalAND(Token **token) {
Node *n = parseIfCondXORexpr(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "&&")) {
n = newNodeBinary(NodeLogicalAND, tokenOp, n, parseIfCondXORexpr(token));
} else {
return n;
}
}
}
static Node *parseIfCondLogicalOR(Token **token) {
Node *n = parseIfCondLogicalAND(token);
for (;;) {
Token *tokenOp = *token;
if (consumeTokenReserved(token, "||")) {
n = newNodeBinary(NodeLogicalOR, tokenOp, n, parseIfCondLogicalAND(token));
} else {
return n;
}
}
}
static Node *parseIfCondConditional(Token **token) {
Node *n = parseIfCondLogicalOR(token);
Token *tokenOp = *token;
if (consumeTokenReserved(token, "?")) {
Node *cond = n;
Node *lhs = NULL;
Node *rhs = NULL;
lhs = parseIfCond(token);
if (!consumeTokenReserved(token, ":"))
errorAt(*token, "\":\" is expected");
rhs = parseIfCondConditional(token);
n = newNodeBinary(NodeConditional, tokenOp, lhs, rhs);
n->condition = cond;
}
return n;
}
static Node *parseIfCond(Token **token) { return parseIfCondConditional(token); }
static int evalIfCondNodes(Node *node) {
int lhs = 0, rhs = 0;
if (node->kind == NodeLogicalAND) {
lhs = evalIfCondNodes(node->lhs);
if (!lhs)
return 0;
return evalIfCondNodes(node->rhs) ? 1 : 0;
} else if (node->kind == NodeLogicalOR) {
lhs = evalIfCondNodes(node->lhs);
if (lhs)
return 1;
return evalIfCondNodes(node->rhs) ? 1 : 0;
} else if (node->kind == NodeConditional) {
int cond = evalIfCondNodes(node->condition);
if (cond)
return evalIfCondNodes(node->lhs);
else
return evalIfCondNodes(node->rhs);
}
if (node->lhs)
lhs = evalIfCondNodes(node->lhs);
if (node->rhs)
rhs = evalIfCondNodes(node->rhs);
switch (node->kind) {
case NodeNum:
return node->val;
case NodeAdd:
return lhs + rhs;
case NodeSub:
return lhs - rhs;
case NodeNot:
return !rhs;
case NodeMul:
return lhs * rhs;
case NodeDiv:
return lhs / rhs;
case NodeDivRem:
return lhs % rhs;
case NodeArithShiftL:
return lhs << rhs;
case NodeArithShiftR:
return lhs >> rhs;
case NodeLT:
return lhs < rhs;
case NodeLE:
return lhs <= rhs;
case NodeEq:
return lhs == rhs;
case NodeNeq:
return lhs != rhs;
case NodeBitwiseAND:
return lhs & rhs;
case NodeBitwiseOR:
return lhs | rhs;
case NodeBitwiseXOR:
return lhs ^ rhs;
default:
errorUnreachable();
}
}
// Evaluate condition for "#if" and "#elif". Note that this function destroys
// "prev" or "next" member in condition tokens.
static int evalIfCondition(Range *cond) {
Range wrap = {};
Node *node = NULL;
int retval = 0;
// TODO: Clone tokens if I free poped tokens.
// Expand macros
wrap.begin = newTokenSOF();
wrap.end = newTokenEOF();
concatToken(wrap.begin, cond->begin);
concatToken(cond->end, wrap.end);
preproc.expandDefined++;
preprocess(wrap.begin);
preproc.expandDefined--;
safeFree(wrap.begin);
safeFree(wrap.end);
// Parse tokens
node = parseIfCond(&cond->begin);
// Evaluate nodes
retval = evalIfCondNodes(node) ? 1 : 0;
// TODO: Free nodes
return retval;
}
// Parse "#if" directive and returns one token after the token at the end of
// this "#if" directive. Note that "token" parameter must points the "#" token
// of "#if".
static Token *parseIfDirective(Token *token) {
typedef struct Elif Elif;
struct Elif {
Elif *next;
Range cond; // NULL if #else
Range body; // Use [body.begin, body.end) as body statement.
};
typedef struct {
Range cond;
Range body; // Use [body.begin, body.end) as body statement.
Range directive;
Elif *elifs;
} IfDirective;
IfDirective entire = {};
Elif elifHead = {};
Range *curBody = NULL;
Range dest = {};
Token *retpos = NULL;
entire.directive.begin = token;
entire.elifs = &elifHead;
if (!(consumeTokenReserved(&token, "#") && consumeTokenCertainType(&token, TokenIf)))
errorUnreachable();
entire.cond.begin = token;
if (entire.cond.begin->type == TokenNewLine)
errorAt(entire.cond.begin, "An expression is expected.");
token = skipUntilNewline(token)->next;
entire.cond.end = token->prev->prev;
entire.body.begin = token;
curBody = &entire.body;
for (int depth = 0, sawElse = 0;;) {
if (consumeTokenReserved(&token, "#")) {
if (consumeTokenCertainType(&token, TokenIf)) {
depth++;
} else if (depth == 0 && consumeTokenIdent(&token, "elif")) {
if (sawElse)
errorAt(token, "#elif after #else.");
else if (token->type == TokenNewLine)
errorAt(token, "An expression is expected.");
curBody->end = token->prev->prev; // Should points to "#" token
entire.elifs->next = (Elif *)safeAlloc(sizeof(Elif));
entire.elifs = entire.elifs->next;
entire.elifs->cond.begin = token;
token = skipUntilNewline(token);
entire.elifs->cond.end = token->prev;
token = token->next;
curBody = &entire.elifs->body;
curBody->begin = token;
continue;
} else if (depth == 0 && consumeTokenCertainType(&token, TokenElse)) {
if (token->type != TokenNewLine)
errorAt(token, "Unexpected token.");
curBody->end = token->prev->prev; // Should points to "#" token.
token = token->next;
entire.elifs->next = (Elif *)safeAlloc(sizeof(Elif));
entire.elifs = entire.elifs->next;
curBody = &entire.elifs->body;
curBody->begin = token;
sawElse = 1;
continue;
} else if (consumeTokenIdent(&token, "endif")) {
if (token->type != TokenNewLine)
errorAt(token, "Unexpected token.");
if (depth != 0) {
depth--;
} else {
curBody->end = token->prev->prev; // Should points to "#" token.
entire.directive.end = token;
entire.elifs = elifHead.next;
break;
}
}
} else if (token->type == TokenEOF) {
errorAt(token, "Unexpected EOF");
}
token = skipUntilNewline(token)->next;
}
if (evalIfCondition(&entire.cond)) {
dest = entire.body;
} else {
for (Elif *elif = entire.elifs; elif; elif = elif->next) {
// elif->cond.begin is NULL for "#else" directive.
if (elif->cond.begin == NULL || evalIfCondition(&elif->cond)) {
dest = elif->body;
break;
}
}
}
retpos = entire.directive.begin->prev;
popTokenRange(entire.directive.begin, entire.directive.end);
if (dest.begin && dest.begin != dest.end) {
insertTokens(retpos, dest.begin, dest.end->prev);
}
for (Elif *elif = entire.elifs; elif;) {
Elif *tofree = elif;
elif = elif->next;
safeFree(tofree);
}
return retpos->next;
}
// Parse "#ifdef" or "#ifndef" directive and returns one token after the token
// at the end of this "#ifdef" or "#ifndef" directive. Note that "token"
// parameter must points the "#" token of "#ifdef" or "#ifndef".
static Token *parseIfdefDirective(Token *token, int inverse) {
Range directive = {};
Token *ident = NULL;
Token *tokenIf = NULL;
Token *tokenDefined = NULL;
directive.begin = token;
if (!consumeTokenReserved(&token, "#"))
errorUnreachable();
else if (!(inverse && consumeTokenIdent(&token, "ifndef") ||
consumeTokenIdent(&token, "ifdef")))
errorUnreachable();
ident = consumeTokenAnyIdent(&token);
if (!ident)
errorAt(token, "Macro name required after \"#ifdef\".");
else if (token->type != TokenNewLine)
errorAt(token, "Unexpected token");
directive.end = token;
// Pop ["ifdef", "\n") tokens.
popTokenRange(directive.begin->next, directive.end->prev);
tokenIf = (Token *)safeAlloc(sizeof(Token));
tokenIf->type = TokenIf;
tokenDefined = (Token *)safeAlloc(sizeof(Token));
tokenDefined->type = TokenIdent;
tokenDefined->str = "defined";
tokenDefined->len = strlen(tokenDefined->str);
// Insert "if defined(<macro>)" or "if !defined(<macro>)" tokens
concatToken(directive.begin, directive.end);
insertToken(directive.begin, newTokenDummyReserved(")"));
insertToken(directive.begin, ident);
insertToken(directive.begin, newTokenDummyReserved("("));
insertToken(directive.begin, tokenDefined);
if (inverse)
insertToken(directive.begin, newTokenDummyReserved("!"));
insertToken(directive.begin, tokenIf);
return parseIfDirective(directive.begin);
}
// Apply "defined()" macro and returns one token after the token at the end of
// this use of "defined()" macro (If "defined()" macro is not applied, returns
// NULL).
static Token *applyBuiltinDefinedMacro(Token *token) {
Token *macro = NULL;
Token *head = token;
if (!consumeTokenIdent(&token, "defined"))
return NULL;
else if (!consumeTokenReserved(&token, "("))
errorAt(token, "\"(\" is expected.");
else if ((macro = consumeTokenAnyIdent(&token)) == NULL)
errorAt(token, "A identifier is expected.");
else if (!consumeTokenReserved(&token, ")"))
errorAt(token, "\")\" is expected.");
popTokenRange(head->next, token->prev);
head->type = TokenNumber;
head->val = findMacro(macro) != NULL;
return head->next;
}
// Apply predefined macros. Return TRUE if applied.
static int applyPredefinedMacro(Token *token) {
if (matchToken(token, "__LINE__", 8)) {
token->type = TokenNumber;
token->val = token->line;
} else if (matchToken(token, "__FILE__", 8)) {
LiteralString *s = (LiteralString *)safeAlloc(sizeof(LiteralString));
s->string = token->file->display;
s->len = strlen(s->string);
s->id = globals.literalStringCount++;
s->next = globals.strings;
globals.strings = s;
token->type = TokenLiteralString;
token->literalStr = s;
} else {
return 0;
}
return 1;
}
// Stringify tokens in range in range [begin, end]. This is for "#" operator.
#define NEED_SPACING(ptr) \
(isSpace(*((char *)(ptr))) || \
(*((char *)(ptr)) == '/' && strchr("*/", (*((char *)(ptr) + 1)))))
static char *stringifyTokens(Token *begin, Token *end, int *len) {
int totalSize = 0;
int w = 0;
char *buf = NULL;
Token *termination = end->next;
*len = 0;
for (Token *token = begin; token != termination; token = token->next) {
switch (token->type) {
case TokenLiteralString:
*len += token->literalStr->len;
totalSize += token->len;
for (int i = 0; i < token->len; ++i) {
if (strchr("\"\\", token->str[i]))
totalSize++;
}
break;
case TokenNumber:
if (token->str[0] == '\'') {
*len += 3;
totalSize += token->len;
if (token->str[1] == '\\') {
totalSize++;
if (token->str[2] == '\\')
totalSize++;
} else if (token->str[1] == '"') {
totalSize++;
}
} else {
*len += token->len;
totalSize += token->len;
}
break;
default:
*len += token->len;
totalSize += token->len;
break;
}
if (NEED_SPACING(token->str + token->len)) {
totalSize++;
(*len)++;
}
}
if (!NEED_SPACING(end->str + end->len))
totalSize++; // Capture one more size for '\0'.
buf = (char *)safeAlloc(totalSize);
w = 0;
for (Token *token = begin; token != termination; token = token->next) {
switch (token->type) {
case TokenLiteralString: // fallthrough
case TokenNumber:
for (int r = 0; r < token->len; ++r) {
if (strchr("\"\\", token->str[r]))
buf[w++] = '\\';
buf[w++] = token->str[r];
}
break;
default:
memcpy(&buf[w], token->str, token->len);
w += token->len;
break;
}
if (NEED_SPACING(token->str + token->len))
buf[w++] = ' ';
}
buf[w] = '\0';
return buf;
}
#undef NEED_SPACING
// Replace arguments of function-like macro. Target tokens are what in range
// [begin, end].
static void replaceMacroArgs(MacroArg *args, Token *begin, Token *end) {
Token *termination = end->next;
Token *token = begin;
while (token != termination) {
MacroArg *replacement = NULL;
Range src = {};
Range dest = {};
for (MacroArg *arg = args; arg; arg = arg->next) {
if (matchToken(arg->name, token->str, token->len)) {
replacement = arg;
break;
}
}
if (!replacement) {
token = token->next;
continue;
}
src.begin = src.end = token;
if (matchToken(token->prev, "#", 1)) {
LiteralString *s = (LiteralString *)safeAlloc(sizeof(LiteralString));
src.begin = token->prev;
s->string = stringifyTokens(replacement->begin, replacement->end, &s->len);
s->id = globals.literalStringCount++;
s->next = globals.strings;
globals.strings = s;
dest.begin = dest.end = (Token *)safeAlloc(sizeof(Token));
*dest.begin = *token;
dest.begin->type = TokenLiteralString;
dest.begin->literalStr = s;
dest.begin->prev = dest.begin->next = NULL;
} else {
dest.begin = dest.end = cloneTokenList(replacement->begin, replacement->end);
while (dest.end->next)
dest.end = dest.end->next;
}
insertTokens(src.end, dest.begin, dest.end);
popTokenRange(src.begin, src.end);