-
Notifications
You must be signed in to change notification settings - Fork 3
/
cpp.c
2002 lines (1604 loc) · 65.7 KB
/
cpp.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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include "wcc.h"
enum {
MAX_CPP_OUTPUT_SIZE = 10 * 1024 * 1024,
};
enum hchar_lex_state {
HLS_START_OF_LINE,
HLS_SEEN_HASH,
HLS_SEEN_INCLUDE,
HLS_OTHER,
};
typedef struct conditional_include {
int matched; // Is the evaluated controlling expression 1?
int skipping; // Is a group being skipped?
struct conditional_include *prev;
} ConditionalInclude;
// Lexing/parsing state for current file
typedef struct cpp_state {
char * input;
int input_size;
int ip; // Offset in input
char * filename; // Current filename
char * override_filename; // Overridden filename with #line
LineMap * line_map_start; // Start of Linemap
LineMap * line_map; // Current position in linemap
int line_number; // Current line number
int line_number_offset; // Difference in line number set by #line directive
CppToken * token; // Current token
int hchar_lex_state; // State of #include <...> lexing
int output_line_number; // How many lines have been outputted
ConditionalInclude * conditional_include_stack; // Includes
int include_depth; // How deep are we in nested includes
} CppState;
CppState state;
List *allocated_tokens; // Keep track of all wmalloc'd tokens
List *allocated_tokens_duplicates; // Keep track of all wmalloc'd shallow copied tokens
List *allocated_strsets;
List *allocated_strings;
// Output
FILE *cpp_output_file; // Output file handle
StringBuffer *output; // Output string buffer;
static void cpp_next();
static void cpp_parse();
static CppToken *subst(CppToken *is, StrMap *fp, CppToken **ap, StrSet *hs, CppToken *os);
static CppToken *hsadd(StrSet *hs, CppToken *ts);
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
char *BUILTIN_INCLUDE_PATHS[5] = {
BUILD_DIR "/include/", // Set during compilation to local wcc source dir
"/usr/local/include/",
"/usr/include/x86_64-linux-gnu/",
"/usr/include/",
0,
};
void debug_print_cll_token_sequence(CppToken *ts) {
if (!ts) {
printf("|\n");
return;
}
CppToken *head = ts->next;
ts = head;
int c = 0;
printf("|");
do {
if (ts->whitespace) printf("[%s]", ts->whitespace);
if (strcmp("\n", ts->str))
printf("%s|", ts->str);
else
printf("\\n");
ts = ts->next;
if (c == 1024) panic("Exceeded reasonable debug limit");
} while (ts != head);
printf("\n");
}
// Set cur_filename and cur_line globals from CPP state
void get_cpp_filename_and_line() {
cur_line = state.line_number_offset + state.line_number;
cur_filename = state.filename;
}
static void init_cpp_from_fh(FILE *f, char *path) {
fseek(f, 0, SEEK_END);
state.input_size = ftell(f);
fseek(f, 0, SEEK_SET);
state.input = wmalloc(state.input_size + 1);
int read = fread(state.input, 1, state.input_size, f);
if (read != state.input_size) {
printf("Unable to read input file\n");
exit(1);
}
fclose(f);
state.input[state.input_size] = 0;
state.filename = wstrdup(path);
cur_filename = state.filename;
cur_line = 1;
state.hchar_lex_state = HLS_START_OF_LINE;
state.conditional_include_stack = wcalloc(1, sizeof(ConditionalInclude));
}
static void output_line_directive(int offset, int add_eol, CppToken *token) {
if (!token) return;
char *buf = wmalloc(256);
char *filename = state.override_filename ? state.override_filename : state.filename;
sprintf(buf, "# %d \"%s\"%s", state.line_number_offset + token->line_number + offset, filename, add_eol ? "\n" : "");
append_to_string_buffer(output, buf);
wfree(buf);
}
// If the output has an amount newlines > threshold, collapse them into a # line statement
static void collapse_trailing_newlines(int threshold, int output_line, CppToken *token) {
int count = 0;
while (output->position - count > 0 && output->data[output->position - count - 1] == '\n') count++;
if (count > threshold) {
// Rewind output by count -1 characters
output->data[output->position - count + 1] = '\n';
output->position -= count - 1;
if (output_line) output_line_directive(0, 1, token);
}
}
// Run the preprocessor on an opened file handle
static void run_preprocessor_on_file(char *filename, int first_file) {
if (opt_enable_trigraphs) transform_trigraphs();
strip_backslash_newlines();
// Initialize the lexer
state.ip = 0;
state.line_map = state.line_map->next;
state.line_number = 1;
state.line_number_offset = 0;
state.override_filename = 0;
state.include_depth = 0;
cpp_next();
append_to_string_buffer(output, "# 1 \"");
append_to_string_buffer(output, filename);
append_to_string_buffer(output, "\"");
if (!first_file) append_to_string_buffer(output, " 1");
append_to_string_buffer(output, "\n");
cpp_parse();
collapse_trailing_newlines(0, 0, 0);
wfree(state.input);
wfree(state.filename);
LineMap *lm = state.line_map_start;
while (lm) {
LineMap *next = lm->next;
wfree(lm);
lm = next;
} while (lm);
}
void init_cpp_from_string(char *string) {
state.input = wstrdup(string);
state.input_size = strlen(string);
state.filename = 0;
state.ip = 0;
state.line_map = 0;
state.line_number = 1;
}
// Shallow copy a new CPP token
static CppToken *dup_cpp_token(CppToken *tok) {
CppToken *result = wmalloc(sizeof(CppToken));
*result = *tok;
result->next = result;
append_to_list(allocated_tokens_duplicates, result);
return result;
}
// Append a single token to a circular linked list. token is modified.
static CppToken *cll_append_token(CppToken *list, CppToken *token) {
if (!list) {
// Convert token into a CLL and return it
token->next = token;
return token;
}
token->next = list->next;
list->next = token;
return token;
}
// Concatenate two circular linked lists
static CppToken *concat_clls(CppToken *list1, CppToken *list2) {
if (!list1) return list2;
if (!list2) return list1;
CppToken *head = list1->next;
list1->next = list2->next;
list2->next = head;
return list2;
}
// Return the next token in the circular linked list, or zero if at the end
#define cll_next(cll, token) ((cll == token) ? 0 : token->next)
// Make a new cll from token->next, or zero if token is at the end
// Beware, this alters the head of cll.
#define cll_from_next(cll, token) (cll == token ? 0 : (cll->next = token->next, cll))
// Duplicate a circular linked list of tokens, making a shallow copy of each token
static CppToken *dup_cll(CppToken *src) {
if (!src) return 0;
CppToken *dst = 0;
for (CppToken *src_token = src->next; src_token; src_token = cll_next(src, src_token))
dst = cll_append_token(dst, dup_cpp_token(src_token));
return dst;
}
// Free a CPP token
static void free_cpp_token(CppToken *token) {
if (token->str) wfree(token->str);
if (token->whitespace) wfree(token->whitespace);
wfree(token);
}
// Create a new CPP token
static CppToken *new_cpp_token(int kind) {
CppToken *tok = wcalloc(1, sizeof(CppToken));
tok->next = tok;
append_to_list(allocated_tokens, tok);
tok->kind = kind;
return tok;
}
static void add_builtin_directive(char *identifier, DirectiveRenderer renderer) {
Directive *directive = wcalloc(1, sizeof(Directive));
directive->renderer = renderer;
strmap_put(directives, identifier, directive);
}
static CppToken *render_file(CppToken *directive_token) {
CppToken *result = new_cpp_token(CPP_TOK_STRING_LITERAL);
wasprintf(&(result->str), "\"%s\"", state.override_filename ? state.override_filename : state.filename);
return result;
}
static CppToken *render_line(CppToken *directive_token) {
CppToken *result = new_cpp_token(CPP_TOK_NUMBER);
wasprintf(&(result->str), "%d", directive_token->line_number_offset + directive_token->line_number);
return result;
}
static CppToken *render_time(CppToken *directive_token) {
time_t rawtime;
struct tm *info;
time(&rawtime);
info = localtime(&rawtime);
CppToken *result = new_cpp_token(CPP_TOK_STRING_LITERAL);
wasprintf(&(result->str), "\"%02d:%02d:%02d\"", info->tm_hour, info->tm_min, info->tm_sec);
return result;
}
static CppToken *render_date(CppToken *directive_token) {
time_t rawtime;
struct tm *info;
time(&rawtime);
info = localtime(&rawtime);
CppToken *result = new_cpp_token(CPP_TOK_STRING_LITERAL);
wasprintf(&(result->str), "\"%3s %2d %04d\"", months[info->tm_mon], info->tm_mday, info->tm_year + 1900);
return result;
}
static CppToken *render_numeric_token(int value) {
CppToken *result = new_cpp_token(CPP_TOK_NUMBER);
wasprintf(&(result->str), "%d", value);
return result;
}
Directive *make_numeric_directive(int value) {
Directive *directive = wcalloc(1, sizeof(Directive));
directive->tokens = render_numeric_token(value);
return directive;
}
Directive *make_empty_directive(void) {
Directive *directive = wcalloc(1, sizeof(Directive));
return directive;
}
void free_directive(Directive *d) {
if (d) {
if (d->param_identifiers) free_strmap(d->param_identifiers);
wfree(d);
}
}
// Create empty directives strmap and add CLI directives to them
void init_directives(void) {
directives = new_strmap();
CliDirective *cd = cli_directives;
while (cd) {
Directive *existing = strmap_get(directives, cd->identifier);
if (existing) free_directive(existing);
strmap_put(directives, cd->identifier, cd->directive);
cd = cd->next;
}
add_builtin_directive("__FILE__", render_file);
add_builtin_directive("__LINE__", render_line);
add_builtin_directive("__TIME__", render_time);
add_builtin_directive("__DATE__", render_date);
strmap_put(directives, "__STDC__", make_numeric_directive(1));
strmap_put(directives, "__x86_64__", make_numeric_directive(1));
strmap_put(directives, "__LP64__", make_numeric_directive(1));
strmap_put(directives, "__linux__", make_numeric_directive(1));
strmap_put(directives, "__GNUC__", make_numeric_directive(2));
strmap_put(directives, "__USER_LABEL_PREFIX__", make_empty_directive());
}
void free_directives(void) {
for (StrMapIterator it = strmap_iterator(directives); !strmap_iterator_finished(&it); strmap_iterator_next(&it)) {
char *key = strmap_iterator_key(&it);
Directive *d = (Directive *) strmap_get(directives, key);
free_directive(d);
}
free_strmap(directives);
}
char *get_cpp_input(void) {
return state.input;
}
LineMap *get_cpp_linemap(void) {
return state.line_map;
}
static LineMap *add_to_linemap(LineMap *lm, int position, int line_number) {
if (lm->position == position) {
lm->line_number = line_number;
return lm;
}
lm->next = wmalloc(sizeof(LineMap));
lm->next->position = position;
lm->next->line_number = line_number;
lm->next->next = NULL;
return lm->next;
}
void transform_trigraphs(void) {
char *output = wmalloc(state.input_size + 1);
int ip = 0; // Input offset
int op = 0; // Output offset
while (ip < state.input_size) {
if (state.input_size - ip >= 3) {
// Check for trigraphs
char c1 = state.input[ip];
char c2 = state.input[ip + 1];
char c3 = state.input[ip + 2];
if (c1 == '?' && c2 == '?' && c3 == '=') { output[op++] = '#'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '(') { output[op++] = '['; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '/') { output[op++] = '\\'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == ')') { output[op++] = ']'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '\'') { output[op++] = '^'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '<') { output[op++] = '{'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '!') { output[op++] = '|'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '>') { output[op++] = '}'; ip += 3; }
else if (c1 == '?' && c2 == '?' && c3 == '-') { output[op++] = '~'; ip += 3; }
else output[op++] = state.input[ip++];
}
else output[op++] = state.input[ip++];
}
wfree(state.input);
output[op] = 0;
state.input = output;
state.input_size = op;
}
void strip_backslash_newlines(void) {
// Add one for the last zero and another one for a potential trailing newline
char *output = wmalloc(state.input_size + 2); //
int ip = 0; // Input offset
int op = 0; // Output offset
int line_number = 1;
state.line_map_start = wmalloc(sizeof(LineMap));
state.line_map = state.line_map_start;
state.line_map->position = ip;
state.line_map->line_number = line_number;
state.line_map->next = NULL;
LineMap *lm = state.line_map;
if (state.input_size == 0) {
wfree(state.input);
state.input = output;
return;
}
while (ip < state.input_size) {
if (state.input_size - ip >= 2 && state.input[ip] == '\\' && state.input[ip + 1] == '\n') {
// Backslash newline
line_number++;
ip += 2;
lm = add_to_linemap(lm, op, line_number);
}
else if (state.input[ip] == '\n') {
// Newline
output[op++] = '\n';
line_number++;
ip += 1;
lm = add_to_linemap(lm, op, line_number);
}
else
output[op++] = state.input[ip++];
}
// Add final newline if not already there
if (op && output[op - 1] != '\n') {
output[op++] = '\n';
line_number++;
}
wfree(state.input);
output[op] = 0;
state.input = output;
state.input_size = op;
lm->next = 0;
}
// Determine if two tokens that don't have a space in between them already need one.
// The specs are unclear about this, so I followed gcc's cpp_avoid_paste() in lex.c.
static int need_token_space(CppToken *t1, CppToken *t2) {
if (t2->kind == '=') {
switch(t1->kind) {
case '=':
case '!':
case '+':
case '-':
case '*':
case '/':
case '%':
case '<':
case '>':
case '&':
case '|':
case '^':
return 1;
}
}
if (t1->kind == '<' && t2->kind == '<') return 1;
else if (t1->kind == '>' && t2->kind == '>') return 1;
else if (t1->kind == '+' && t2->kind == '+') return 1;
else if (t1->kind == '-' && t2->kind == '-') return 1;
else if (t1->kind == '&' && t2->kind == '&') return 1;
else if (t1->kind == '|' && t2->kind == '|') return 1;
else if (t1->kind == '-' && t2->kind == '>') return 1;
else if (t1->kind == '/' && t2->kind == '*') return 1;
else if (t1->kind == '+' && t2->kind == CPP_TOK_INC) return 1;
else if (t1->kind == '-' && t2->kind == CPP_TOK_DEC) return 1;
else if (t1->kind == '.' && t2->kind == CPP_TOK_NUMBER) return 1;
else if (t1->kind == CPP_TOK_IDENTIFIER && t2->kind == CPP_TOK_IDENTIFIER) return 1;
else if (t1->kind == CPP_TOK_IDENTIFIER && t2->kind == CPP_TOK_NUMBER) return 1;
else if (t1->kind == CPP_TOK_IDENTIFIER && t2->kind == CPP_TOK_STRING_LITERAL) return 1;
else if (t1->kind == CPP_TOK_NUMBER && t2->kind == CPP_TOK_IDENTIFIER) return 1;
else if (t1->kind == CPP_TOK_NUMBER && t2->kind == CPP_TOK_NUMBER) return 1;
else if (t1->kind == CPP_TOK_STRING_LITERAL && t2->kind == CPP_TOK_STRING_LITERAL) return 1;
return 0;
}
static void append_tokens_to_string_buffer(StringBuffer *sb, CppToken *tokens, int collapse_whitespace, int update_output) {
if (!tokens) return;
CppToken *prev = 0;
CppToken *head = tokens->next;
CppToken *token = head;
do {
int is_eol = (token->kind == CPP_TOK_EOL);
int seen_whitespace = is_eol;
// If collapsing whitespace, pretend EOLs don't exist
if (collapse_whitespace) {
is_eol = 0;
while (token && token->kind == CPP_TOK_EOL) {
prev = token;
token = cll_next(tokens, token);
}
}
if (!token) return;
if (!is_eol && token->whitespace && !collapse_whitespace)
append_to_string_buffer(sb, token->whitespace);
else if (!is_eol && token->whitespace && collapse_whitespace)
append_to_string_buffer(sb, " ");
else if (prev && need_token_space(prev, token))
append_to_string_buffer(sb, " ");
else if (seen_whitespace && collapse_whitespace)
append_to_string_buffer(sb, " ");
if (update_output && !is_eol) collapse_trailing_newlines(8, 1, token);
append_to_string_buffer(sb, token->str);
prev = token;
token = token->next;
if (update_output) {
if (is_eol) state.output_line_number++;
if (is_eol && token) {
// Output sufficient newlines to catch up with token->line_number.
// This ensures that each line in the input ends up on the same line
// in the output.
while (state.output_line_number < token->line_number) {
state.output_line_number++;
append_to_string_buffer(sb, "\n");
}
}
}
} while (token != head);
}
static void append_tokens_to_output(CppToken *tokens) {
append_tokens_to_string_buffer(output, tokens, 0, 1);
}
#define advance_ip() do { \
if (state.line_map && state.ip == state.line_map->position) { \
state.line_number = state.line_map->line_number; \
cur_line = state.line_number; \
state.line_map = state.line_map->next; \
} \
state.ip++; \
} while(0)
static void advance_ip_by_count(int count) {
for (int i = 0; i < count; i++)
advance_ip();
}
static void add_to_whitespace(char **whitespace, int *whitespace_pos, char c) {
if (!*whitespace) *whitespace = wmalloc(1024);
if (*whitespace_pos == 1024) panic("Ran out of whitespace buffer");
(*whitespace)[(*whitespace_pos)++] = c;
}
static char *lex_whitespace(void) {
char *whitespace = 0;
int whitespace_pos = 0;
// Process whitespace and comments
while (state.ip < state.input_size) {
char c = state.input[state.ip];
if (c == '\f' || c == '\v' || c == '\r') state.input[state.ip] = ' ';
if ((state.input[state.ip] == '\t' || state.input[state.ip] == ' ')) {
add_to_whitespace(&whitespace, &whitespace_pos, state.input[state.ip]);
advance_ip();
continue;
}
// Process // comment
if (state.input_size - state.ip >= 2 && state.input[state.ip] == '/' && state.input[state.ip + 1] == '/') {
while (state.input[state.ip] != '\n') advance_ip();
add_to_whitespace(&whitespace, &whitespace_pos, ' ');
continue;
}
// Process /* comments */
if (state.input_size - state.ip >= 2 && state.input[state.ip] == '/' && state.input[state.ip + 1] == '*') {
advance_ip();
advance_ip();
while (state.input_size - state.ip >= 2 && (state.input[state.ip] != '*' || state.input[state.ip + 1] != '/'))
advance_ip();
advance_ip();
advance_ip();
add_to_whitespace(&whitespace, &whitespace_pos, ' ');
continue;
}
break;
}
if (whitespace)
whitespace[whitespace_pos] = 0;
return whitespace;
}
static void lex_string_and_char_literal(char delimiter) {
char *i = state.input;
int data_offset = 0;
char *data = wmalloc(MAX_STRING_LITERAL_SIZE + 2);
if (i[state.ip] == 'L') {
advance_ip();
data_offset = 1;
data[0] = 'L';
}
advance_ip();
data[data_offset] = delimiter == '>' ? '<' : delimiter;
int size = 0;
while (state.ip < state.input_size) {
if (i[state.ip] == delimiter) {
advance_ip();
break;
}
if (state.input_size - state.ip >= 2 && i[state.ip] == '\\') {
if (size + 1 >= MAX_STRING_LITERAL_SIZE) panic("Exceeded maximum string literal size %d", MAX_STRING_LITERAL_SIZE);
data[data_offset + 1 + size++] = '\\';
data[data_offset + 1 + size++] = i[state.ip + 1];
advance_ip();
advance_ip();
}
else {
if (size >= MAX_STRING_LITERAL_SIZE) panic("Exceeded maximum string literal size %d", MAX_STRING_LITERAL_SIZE);
data[data_offset + 1 + size++] = i[state.ip];
advance_ip();
}
}
data[data_offset + size + 1] = delimiter;
data[data_offset + size + 2] = 0;
state.token = new_cpp_token(CPP_TOK_STRING_LITERAL);
state.token->str = data;
}
#define is_pp_number(c1, c2) (c1 >= '0' && c1 <= '9') || (state.input_size - state.ip >= 2 && c1 == '.' && (c2 >= '0' && c2 <= '9'))
#define is_non_digit(c1) ((c1 >= 'a' && c1 <= 'z') || (c1 >= 'A' && c1 <= 'Z') || c1 == '_')
#define is_exponent(c1, c2) (c1 == 'E' || c1 == 'e') && (c2 == '+' || c2 == '-')
#define make_token(kind, size) \
do { \
state.token = new_cpp_token(kind); \
copy_token_str(start, size); \
advance_ip_by_count(size); \
} while (0)
#define make_other_token(size) make_token(CPP_TOK_OTHER, size)
#define copy_token_str(start, size) \
do { \
state.token->str = wmalloc(size + 1); \
memcpy(state.token->str, start, size); \
state.token->str[size] = 0; \
} while (0)
// Lex one CPP token, starting with optional whitespace
static void cpp_next() {
char *whitespace = lex_whitespace();
char *i = state.input;
if (state.ip >= state.input_size)
state.token = new_cpp_token(CPP_TOK_EOF);
else {
int left = state.input_size - state.ip;
char c1 = i[state.ip];
char c2 = i[state.ip + 1];
char c3 = left >= 3 ? i[state.ip + 2] : 0;
char *start = &(i[state.ip]);
if (c1 == '\n') {
state.token = new_cpp_token(CPP_TOK_EOL);
state.token->str = wstrdup("\n");
state.token->line_number = state.line_number; // Needs to be the line number of the \n token, not the next token
state.hchar_lex_state = HLS_START_OF_LINE;
advance_ip();
}
else if (c1 == '#' && c2 == '#')
make_token(CPP_TOK_PASTE, 2);
else if (c1 == '#')
make_token(CPP_TOK_HASH, 1);
else if (left >= 2 && c1 == '&' && c2 == '&' ) { make_other_token(2); }
else if (left >= 2 && c1 == '|' && c2 == '|' ) { make_other_token(2); }
else if (left >= 2 && c1 == '=' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '!' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '<' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '>' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '+' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '-' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '*' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '/' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '%' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '&' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '|' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '^' && c2 == '=' ) { make_other_token(2); }
else if (left >= 2 && c1 == '-' && c2 == '>' ) { make_other_token(2); }
else if (left >= 3 && c1 == '>' && c2 == '>' && c3 == '=') { make_other_token(3); }
else if (left >= 3 && c1 == '<' && c2 == '<' && c3 == '=') { make_other_token(3); }
else if (left >= 3 && c1 == '.' && c2 == '.' && c3 == '.') { make_other_token(3); }
else if (left >= 2 && c1 == '<' && c2 == '<' ) { make_other_token(2); }
else if (left >= 2 && c1 == '>' && c2 == '>' ) { make_other_token(2); }
else if (left >= 2 && c1 == '+' && c2 == '+' ) { make_token(CPP_TOK_INC, 2); }
else if (left >= 2 && c1 == '-' && c2 == '-' ) { make_token(CPP_TOK_DEC, 2); }
else if ( c1 == '(' ) { make_token(CPP_TOK_LPAREN, 1); }
else if ( c1 == ')' ) { make_token(CPP_TOK_RPAREN, 1); }
else if ( c1 == ',' ) { make_token(CPP_TOK_COMMA, 1); }
else if ((c1 == '"') || (state.input_size - state.ip >= 2 && c1 == 'L' && c2 == '"'))
lex_string_and_char_literal('"');
else if ((c1 == '\'') || (state.input_size - state.ip >= 2 && c1 == 'L' && c2 == '\''))
lex_string_and_char_literal('\'');
else if (c1 == '<' && state.hchar_lex_state == HLS_SEEN_INCLUDE) {
lex_string_and_char_literal('>');
state.token->kind = CPP_TOK_HCHAR_STRING_LITERAL;
state.hchar_lex_state = HLS_OTHER;
}
else if ((c1 >= 'a' && c1 <= 'z') || (c1 >= 'A' && c1 <= 'Z') || c1 == '_') {
char *identifier = wmalloc(1024);
int j = 0;
while (((i[state.ip] >= 'a' && i[state.ip] <= 'z') || (i[state.ip] >= 'A' && i[state.ip] <= 'Z') || (i[state.ip] >= '0' && i[state.ip] <= '9') || (i[state.ip] == '_')) && state.ip < state.input_size) {
if (j == MAX_IDENTIFIER_SIZE) panic("Exceeded maximum identifier size %d", MAX_IDENTIFIER_SIZE);
identifier[j] = i[state.ip];
j++;
advance_ip();
}
identifier[j] = 0;
#define is_identifier(t) (\
t->kind == CPP_TOK_IDENTIFIER || \
t->kind == CPP_TOK_INCLUDE || \
t->kind == CPP_TOK_DEFINE || \
t->kind == CPP_TOK_UNDEF || \
t->kind == CPP_TOK_IF || \
t->kind == CPP_TOK_IFDEF || \
t->kind == CPP_TOK_IFNDEF || \
t->kind == CPP_TOK_ELIF || \
t->kind == CPP_TOK_ELSE || \
t->kind == CPP_TOK_ENDIF || \
t->kind == CPP_TOK_LINE || \
t->kind == CPP_TOK_DEFINED || \
t->kind == CPP_TOK_WARNING || \
t->kind == CPP_TOK_ERROR || \
t->kind == CPP_TOK_PRAGMA)
if (!strcmp(identifier, "define")) { state.token = new_cpp_token(CPP_TOK_DEFINE); state.token->str = identifier; }
else if (!strcmp(identifier, "include")) { state.token = new_cpp_token(CPP_TOK_INCLUDE); state.token->str = identifier; }
else if (!strcmp(identifier, "undef")) { state.token = new_cpp_token(CPP_TOK_UNDEF); state.token->str = identifier; }
else if (!strcmp(identifier, "if")) { state.token = new_cpp_token(CPP_TOK_IF); state.token->str = identifier; }
else if (!strcmp(identifier, "ifdef")) { state.token = new_cpp_token(CPP_TOK_IFDEF); state.token->str = identifier; }
else if (!strcmp(identifier, "ifndef")) { state.token = new_cpp_token(CPP_TOK_IFNDEF); state.token->str = identifier; }
else if (!strcmp(identifier, "elif")) { state.token = new_cpp_token(CPP_TOK_ELIF); state.token->str = identifier; }
else if (!strcmp(identifier, "else")) { state.token = new_cpp_token(CPP_TOK_ELSE); state.token->str = identifier; }
else if (!strcmp(identifier, "endif")) { state.token = new_cpp_token(CPP_TOK_ENDIF); state.token->str = identifier; }
else if (!strcmp(identifier, "line")) { state.token = new_cpp_token(CPP_TOK_LINE); state.token->str = identifier; }
else if (!strcmp(identifier, "defined")) { state.token = new_cpp_token(CPP_TOK_DEFINED); state.token->str = identifier; }
else if (!strcmp(identifier, "warning")) { state.token = new_cpp_token(CPP_TOK_WARNING); state.token->str = identifier; }
else if (!strcmp(identifier, "error")) { state.token = new_cpp_token(CPP_TOK_ERROR); state.token->str = identifier; }
else if (!strcmp(identifier, "pragma")) { state.token = new_cpp_token(CPP_TOK_PRAGMA); state.token->str = identifier; }
else {
state.token = new_cpp_token(CPP_TOK_IDENTIFIER);
state.token->str = identifier;
}
}
else if (is_pp_number(c1, c2)) {
int size = 1;
char *start = &(i[state.ip]);
advance_ip();
while (
c1 = i[state.ip], c2 = state.input_size - state.ip >= 2 ? i[state.ip + 1] : 0,
(c1 == '.' || is_non_digit(c1)) || (is_pp_number(c1, c2) || is_exponent(c1, c2))) {
if (is_exponent(c1, c2)) { advance_ip(); size++; }
advance_ip();
size++;
}
state.token = new_cpp_token(CPP_TOK_NUMBER);
copy_token_str(start, size);
}
else
make_token(c1, 1);
}
// Set the line number of not already set
if (!state.token->line_number) {
state.token->line_number = state.line_number;
state.token->line_number_offset = state.line_number_offset;
}
state.token->whitespace = whitespace;
if (state.hchar_lex_state == HLS_START_OF_LINE && state.token->kind == CPP_TOK_HASH ) state.hchar_lex_state = HLS_SEEN_HASH;
if (state.hchar_lex_state == HLS_SEEN_HASH && state.token->kind == CPP_TOK_INCLUDE) state.hchar_lex_state = HLS_SEEN_INCLUDE;
return;
}
// Set line number on all tokens in ts
static void set_line_number_on_token_sequence(CppToken *ts, int line_number) {
CppToken *tail = ts;
ts = ts->next;
do {
ts->line_number = line_number;
ts = ts->next;
} while (ts != tail);
}
#define add_token_to_actuals() current_actual = cll_append_token(current_actual, dup_cpp_token(token));
// Parse function-like macro call, starting with the '('
// Loop over ts; ts is advanced up to the enclosing ')'
// Returns a ptr to the token sequences for each actual parameter.
// Nested () are taken into account, for cases like f((1, 2), 3), which
// results in (1, 2) and 3 for the actual parameters.
CppToken **make_function_actual_parameters(CppToken **ts) {
CppToken **result = wcalloc(MAX_CPP_MACRO_PARAM_COUNT, sizeof(CppToken *));
int parenthesis_nesting_level = 0;
CppToken *current_actual = 0;
int index = 0;
while (1) {
CppToken *token = *ts;
if (!token) error("Expected macro function-like parameter or )");
if (token->kind == CPP_TOK_RPAREN && !parenthesis_nesting_level) {
// We're not in nested parentheses
result[index++] = current_actual;
return result;
}
else if (token->kind == CPP_TOK_RPAREN) {
// We're in nested parentheses
add_token_to_actuals();
parenthesis_nesting_level--;
}
else if (token->kind == CPP_TOK_LPAREN) {
// Enter nested parentheses
add_token_to_actuals();
parenthesis_nesting_level++;
}
else if (token->kind == CPP_TOK_COMMA && !parenthesis_nesting_level) {
// Finish current ap and start next ap
result[index++] = current_actual;
current_actual = 0;
}
else {
// It's an ordinary token, append it to current actual
add_token_to_actuals();
}
*ts =(*ts)->next;
}
}
void free_function_actual_parameters(CppToken **actuals) {
wfree(actuals); // The tokens are freed as part of the garbage freeing
}
// Call strset_union and register the allocated strset for freeing later on.
StrSet *cpp_strset_union(StrSet *set1, StrSet *set2) {
StrSet *s = strset_union(set1, set2);
append_to_list(allocated_strsets, s);
return s;
}
// Union two sets. Either or both may be NULL
#define safe_strset_union(set1, set2) \
set1 && set2 \
? cpp_strset_union(set1, set2) \
: set1 \
? set1 \
: set2
// Call strset_intersection and register the allocated strset for freeing later on.
StrSet *cpp_strset_intersection(StrSet *set1, StrSet *set2) {
StrSet *s = strset_intersection(set1, set2);
append_to_list(allocated_strsets, s);
return s;
}
// Intersect two sets. Either or both may be NULL
#define safe_strset_intersection(set1, set2) \
set1 && set2 \
? cpp_strset_intersection(set1, set2) \
: 0;
// Implementation of Dave Prosser's C Preprocessing Algorithm
// This is the main macro expansion function: expand an input sequence into an output sequence.
static CppToken *expand(CppToken *is) {
if (!is) return 0;
// Skip past any non-directives, to eliminate unnecessary recursion
CppToken *left = 0;
CppToken *is_head = is->next;
CppToken *is_tail = is;
CppToken *tok = is_head;
while (tok->str && !strmap_get(directives, tok->str)) {
left = cll_append_token(left, dup_cpp_token(tok));
tok = tok->next;
if (tok == is_head) break;
}
if (left) {
if (tok == is_head) return left;
// Make is the remainder
is_tail->next = tok; // Make tok the head of the cll
CppToken *result = concat_clls(left, expand(is));
return result;
}
CppToken *tok1 = tok->next != is_head ? tok->next : 0;
while (tok1 && tok1->kind == CPP_TOK_EOL) tok1 = cll_next(is, tok1);
if (tok->str && tok->hide_set && strset_in(tok->hide_set, tok->str)) {
// The first token tok in its own hide set, don't expand it
// return the first token + the expanded rest
if (is_tail == is_head) return is_tail; // Only one token
CppToken *t = dup_cpp_token(tok);
return concat_clls(t, expand(cll_from_next(is, tok)));
}
Directive *directive = 0;
if (tok->str) directive = strmap_get(directives, tok->str);
if (directive && !directive->is_function) {
// Object like macro
StrSet *identifier_hs = new_strset();
append_to_list(allocated_strsets, identifier_hs);
strset_add(identifier_hs, tok->str);
StrSet *hs = tok->hide_set ? cpp_strset_union(tok->hide_set, identifier_hs) : identifier_hs;
CppToken *replacement_tokens = directive->renderer ? directive->renderer(tok) : directive->tokens;
CppToken *substituted = subst(replacement_tokens, 0, 0, hs, 0);
if (substituted) {
set_line_number_on_token_sequence(substituted, tok->line_number);
substituted->next->whitespace = tok->whitespace;
}
return expand(concat_clls(substituted, cll_from_next(is, tok)));
}