Repository navigation
Expand file tree
/
Copy pathcpp.c
More file actions
1517 lines (1294 loc) · 41.9 KB
/
Copy pathcpp.c
File metadata and controls
1517 lines (1294 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License (MIT)
*
* Copyright (c) 2023-2025 Fraser Heavy Software
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* This is the omC (Onramp Minimal C) preprocessor.
*
* It is written in omC, except it depends only on the directive-stripping
* preprocessor (cpp/0-strip), so it can be bootstrapped without needing a
* "real" preprocessor.
*
* It can also be preprocessed with a real preprocessor, and (in combination
* with any cci stage) it is self-hosting, though we don't actually bother to
* build it with itself during the bootstrap process.
*
* Since our linker doesn't yet support file scope, and we don't have any
* mechanism for including other files yet, we have to implement this in a
* single C source file (otherwise generated label names would collide.)
*/
/*
* When bootstrapping, we'll be preprocessing with cpp/0-strip which just
* strips preprocessor directives. We therefore have to declare all our libc
* features ourselves.
*
* We use the below #include and #ifdef so that this file can still be compiled
* with an ordinary C compiler for any platform. This makes it easy to test and
* debug.
*/
/* These #include directives are stripped by cpp/0-strip. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "libo-error.h"
#include "libo-util.h"
/* This macro is never actually defined, but because cpp/0-strip will strip the
* directives, it's equivalent to the condition being true. With any proper C
* preprocessor (including this) the condition will be false and the headers
* above will be included instead. */
#ifdef __onramp_cpp_strip__
/* <ctype.h> */
int isalnum(int);
int isalpha(int);
int isdigit(int);
int isspace(int);
/* <stddef.h> */
typedef int size_t; /* note: size_t is signed int for now because omC doesn't support unsigned. */
/* <stdint.h> */
typedef int intptr_t;
/* <stdbool.h> */
typedef int bool;
int true; // initialized at the top of main()
int false;
/* <stdio.h> */
typedef void FILE;
FILE* fopen(const char* name, const char* mode);
int fclose(FILE* file);
int fgetc(FILE* file);
size_t fwrite(const void* buffer, size_t size, size_t count, FILE* file);
int feof(FILE* file);
int fputc(int c, FILE* file);
int fputs(const char* s, FILE* file);
int puts(const char* s);
int putchar(int c);
extern FILE* stdin;
extern FILE* stdout;
extern FILE* stderr;
/* <stdlib.h> */
void* malloc(size_t size);
void free(void* p);
char* strdup(const char* str);
char* strndup(const char* str, size_t length);
/* <string.h> */
size_t strlen(const char* s);
char* strcpy(char* to, const char* from);
void* memmove(void* dest, const void* src, size_t count);
int strcmp(const char* left, const char* right);
void* memcpy(void* dest, const void* src, size_t count);
int memcmp(const void* a, const void* b, size_t count);
char* strchr(const char* s, int c);
/* "libo-error.h" */
extern char* current_filename;
extern int current_line;
void fatal(const char* message);
/* "libo-util.h" */
void fputd(int number, FILE* file);
#endif
/*
* State
*/
/* The current input file from which we're reading characters. When an #include
* is parsed, this changes and the previous file is stored on the call stack. */
static FILE* current_file;
/* The current character being handled by the preprocessor after the scanner
* has stripped comments and escaped newlines, or 0 on EOF. */
static char current_char;
/* The next character after current_char, which has not yet been scanned. */
static char next_scan_char;
const char* input_filename;
const char* output_filename;
const char* force_include_filename;
static FILE* output_file;
/* Depth of true conditionals */
static int depth;
// options
static bool opt_nostddef;
static bool opt_dump_macros;
// current include guard state
// these constants are assigned in main()
// TODO we need a proper way to do constants in cci/0
int guard_state_outside; // we are outside the include guard
int guard_state_inside; // we are inside an opening #ifndef
int guard_state_fail; // didn't match include guard pattern
static int guard_state;
static char* /*nullable*/ guard_macro;
// table of include guards
// TODO make this a hashtable
static char** guards_filename;
static char** guards_macro;
size_t guards_capacity;
size_t guards_count;
/*
* Forward declarations
*/
static void preprocess(const char* new_filename, FILE* new_file);
/*
* File and error handling helpers
*/
static void write_number(FILE* file, int number) {
fputd(number, file);
}
static void emit_char(char c) {
fputc(c, output_file);
}
static void emit_line_directive(void) {
fputs("#line ", output_file);
write_number(output_file, current_line);
emit_char(' ');
emit_char('"');
fputs(current_filename, output_file);
emit_char('"');
emit_char('\n');
}
/*
* Scanner
*
* The preprocessor doesn't have a tokenizer exactly, but it does have a
* scanner which does these tasks:
*
* - Comments (C and C++ style) are replaced with a single space.
* - Escaped newlines are eliminated.
* - Various line ending formats are converted to line feeds.
* - A newline is appended to the end of the file if one is missing.
*
* The scanner otherwise outputs single characters into `current_char`.
*
* This is equivalent to the first two phases of translation.
*/
/**
* Reads a single character from the current file.
*
* Returns 0 on end of file. (The input file is not allowed to contain null
* bytes.)
*/
static char read_char(void) {
int c = fgetc(current_file);
if (c == -1) {
if (!feof(current_file)) {
fatal("Failed to read input file.");
}
return 0;
}
if (c == 0) {
fatal("Input file cannot contain a null byte.");
}
return c;
}
/**
* Consumes current_char, scans for a new character (stripping comments and so
* on), and places the newly scanned character in current_char.
*
* This is the implementation of the character scanner.
*
* When the end of the file is reached, a null byte is placed in current_char.
* (The input file is not allowed to contain null bytes.)
*/
static void next_char(void) {
// Whenever we consume a newline, bump the line number.
if (current_char == '\n') {
emit_char('\n');
current_line = (current_line + 1);
}
current_char = next_scan_char;
/*
if (current_char == 0) {
return;
}
*/
next_scan_char = read_char();
while (1) {
/* Check for an escaped newline */
if ((current_char == '\\') & ((next_scan_char == '\n') | (next_scan_char == '\r'))) {
current_char = read_char();
if ((next_scan_char == '\r') & (current_char == '\n')) {
/* Backslash was followed by both carriage return and line
* feed; also consume the line feed */
current_char = read_char();
}
if (current_char == 0) {
/* The file ended in an escaped newline. Synthesize a newline. */
current_char = '\n';
next_scan_char = 0;
break;
}
next_scan_char = read_char();
continue;
}
/* Check for a carriage return */
if (current_char == '\r') {
if (next_scan_char == '\n') {
/* CR+LF is replaced by LF */
current_char = '\n';
next_scan_char = read_char();
break;
}
/* CR alone is replaced by LF */
current_char = '\n';
}
/* Check for a C-style comment */
if ((current_char == '/') & (next_scan_char == '*')) {
current_char = ' ';
next_scan_char = read_char();
while (1) {
if (next_scan_char == 0) {
fatal("Unterminated comment");
}
if (next_scan_char == '*') {
next_scan_char = read_char();
if (next_scan_char == '/') {
next_scan_char = read_char();
break;
}
continue;
}
// a carriage return followed by a line feed counts as one line
// ending. otherwise, either a carriage return or a line feed
// is a line ending.
if (next_scan_char == '\r') {
current_line = (current_line + 1);
emit_char('\n');
next_scan_char = read_char();
if (next_scan_char == '\n') {
next_scan_char = read_char();
}
continue;
}
if (next_scan_char == '\n') {
current_line = (current_line + 1);
emit_char('\n');
}
next_scan_char = read_char();
}
continue;
}
/* Check for a C++-style comment */
if ((current_char == '/') & (next_scan_char == '/')) {
current_char = ' ';
next_scan_char = read_char();
while (1) {
if (next_scan_char == 0) {
break;
}
/* Check for an escaped newline */
if (next_scan_char == '\\') {
next_scan_char = read_char();
if (next_scan_char == '\r') {
next_scan_char = read_char();
if (next_scan_char == '\n') {
next_scan_char = read_char();
continue;
}
continue;
}
if (next_scan_char == '\n') {
next_scan_char = read_char();
}
continue;
}
/* Check for the end of the line */
if ((next_scan_char == '\n') | (next_scan_char == '\r')) {
break;
}
next_scan_char = read_char();
}
if (next_scan_char == 0) {
/* The file ended in a C++-style comment without a newline.
* Synthesize a newline. */
next_scan_char = '\n';
}
break;
}
/* Check for lack of newline at end of file */
if (next_scan_char == 0) {
if ((current_char != 0) & ((current_char != '\n') & (current_char != '\r'))) {
/* Insert a synthetic newline */
next_scan_char = '\n';
break;
}
}
/* Done */
break;
}
//printf("next done, char '%c'\n",current_char);
}
static void emit_string_or_character_literal(void) {
// emit opening quote
char quote = current_char;
emit_char(current_char);
next_char();
// emit contents
// (check for newline only; no need to check for EOF, we synthesize a
// newline if missing)
while (current_char != quote) {
if (current_char == '\n') {
fatal("Unclosed single or double quote");
}
if (current_char == '\\') {
emit_char(current_char);
next_char();
if (current_char == '\n') {
fatal("Unclosed single or double quote");
}
}
emit_char(current_char);
next_char();
}
// emit closing quote
if (current_char == '\n') {
fatal("Unclosed single or double quote");
}
emit_char(current_char);
next_char();
}
/*
* Parsing helper functions
*/
/* When accumulating an identifier or expansion, we store it here */
static char* current_string;
static size_t current_string_capacity;
/**
* Consumes any amount of horizontal whitespace, even if there is none.
*/
static void consume_optional_horizontal_whitespace(void) {
while ((current_char == ' ') | (current_char == '\t')) {
next_char();
}
}
/**
* Consumes at least one character of horizontal whitespace.
*/
static void consume_horizontal_whitespace(void) {
if (!((current_char == ' ') | (current_char == '\t'))) {
//printf("current char: %x\n", current_char);
fatal("Expected horizontal whitespace");
}
consume_optional_horizontal_whitespace();
}
/**
* Consumes whitespace up to and including one newline character.
*
* Raises a fatal error if a newline was not found.
*/
static void consume_end_of_line(void) {
consume_optional_horizontal_whitespace();
if (current_char != '\n') {
fatal("Expected end of line");
}
next_char();
}
static bool is_identifier_char(int c, int first_char) {
if (isalpha(c) | (c == '_')) {
return true;
}
// We accept $ in identifiers as an extension.
if (c == '$') {
return true;
}
// Identifiers cannot start with digits.
if (!first_char) {
if (isdigit(c)) {
return true;
}
}
return false;
}
/**
* Consumes an identifier, placing it (null-terminated) in current_string.
*/
static void consume_identifier(void) {
size_t i;
if (!is_identifier_char(current_char, true)) {
fatal("Expected identifier");
}
*current_string = current_char;
i = 1;
while (1) {
next_char();
if (!is_identifier_char(current_char, false)) {
break;
}
*(current_string + i) = current_char;
i = (i + 1);
if (i == current_string_capacity) {
fatal("Identifier is too long.");
}
}
*(current_string + i) = 0;
}
/**
* Consumes a macro expansion string, placing it (null-terminated) in
* current_string.
*/
static void consume_expansion(void) {
size_t i;
i = 0;
while (1) {
if (i == current_string_capacity) {
fatal("Macro expansion is too long.");
}
// no need to check for EOF, we synthesize a newline if missing
if ((current_char == '\n') | (current_char == '\r')) {
break;
}
*(current_string + i) = current_char;
i = (i + 1);
next_char();
}
*(current_string + i) = 0;
}
/*
* We store macros in a linked list.
*
* We'd like our macro struct to look something like this:
*
* struct macro_t {
* struct macro_t* next;
* const char* name;
* const char* expansion;
* bool in_use;
* };
*
* Since we don't have structs, we'll just make it an array of four void
* pointers.
*
* We insert new macros at the front of the linked list, that way if a macro is
* redefined, we find the latest definition first. We don't bother to free()
* replaced macros and #undef is not supported.
*/
int MACRO_NEXT;
int MACRO_NAME;
int MACRO_EXPANSION;
int MACRO_IN_USE;
static void macros_init(void) {
MACRO_NEXT = 0;
MACRO_NAME = 1;
MACRO_EXPANSION = 2;
MACRO_IN_USE = 3;
}
// The linked list of macros.
static void** macros;
static void macro_new(char* name, char* expansion) {
if ((name == 0) | (expansion == 0)) {
fatal("Out of memory.");
}
//printf("define macro %s %s\n", name, expansion);
void** macro = (void**)malloc(sizeof(void*) * 4);
*(macro + MACRO_NEXT) = (void*)macros;
*(macro + MACRO_NAME) = (void*)name;
*(macro + MACRO_EXPANSION) = (void*)expansion;
*(macro + MACRO_IN_USE) = 0;
macros = macro;
}
static void macro_delete(void** macro) {
free(*(macro + MACRO_NAME));
free(*(macro + MACRO_EXPANSION));
free(macro);
}
static void** macro_find(const char* name) {
void** macro = macros;
while (macro != 0) {
char* other_name;
other_name = (char*)*(macro + MACRO_NAME);
if (0 == strcmp(name, other_name)) {
return macro;
}
macro = (void**)*(macro + MACRO_NEXT);
}
return 0;
}
/*
* Include paths are also stored in a linked list.
*
* The struct for an include path would look something like this:
*
* struct include_path_t {
* struct include_path_t* next;
* const char* path;
* };
*
* Like macros, we use an array of two void pointers. Unlike macros, we append
* paths at the end so that priority is in the order specified on the
* command-line.
*/
static void** include_paths;
static void** last_include_path;
static void include_path_new(const char* path) {
if (strlen(path) == 0) {
fatal("Empty include path.");
}
void** entry;
entry = (void**)malloc(sizeof(void*) * 2);
*entry = 0;
*(entry + 1) = (void*)path;
/* The first one goes at the head of the list */
if (last_include_path == 0) {
include_paths = entry;
}
/* Otherwise we append to the end */
if (last_include_path != 0) {
*last_include_path = entry;
}
last_include_path = entry;
}
/*
* Include path searching
*/
static bool try_include(const char* prefix) {
size_t prefix_length;
prefix_length = strlen(prefix);
char* suffix;
size_t suffix_length;
suffix = current_string;
suffix_length = strlen(suffix);
//printf("trying prefix %s suffix %s\n",prefix,suffix);
// Check if the prefix has a trailing slash. If not we need to add one.
// (We've checked in include_path_new() that the prefix is not empty.)
int needs_slash;
needs_slash = 1;
if (*(prefix + (prefix_length - 1)) == '/') {
needs_slash = 0;
}
// Assemble the path
char* path;
size_t path_length;
path = malloc((prefix_length + suffix_length) + 2);
memcpy(path, prefix, prefix_length);
path_length = prefix_length;
if (needs_slash) {
*(path + path_length) = '/';
path_length = (path_length + 1);
}
memcpy(path + path_length, suffix, suffix_length);
path_length = (path_length + suffix_length);
*(path + path_length) = 0;
// Try to open the file
FILE* file;
file = fopen(path, "r");
if (file == 0) {
free(path);
return false;
}
fputs("#pragma onramp file push\n", output_file);
preprocess(path, file);
fputs("#pragma onramp file pop\n", output_file);
// Emit a line directive for the parent file to get us back where we were.
// (The parent file is NULL if we're processing `-include`.)
if (current_filename != 0) {
emit_line_directive();
}
fclose(file);
free(path);
return true;
}
static int find_slash(const char* str) {
// The parent filename is NULL when using `-include`.
if (str == 0) {
return -1;
}
int slash_index;
slash_index = -1;
int i;
i = 0;
while (1) {
char c;
c = *(str + i);
if (c == 0) {
break;
}
if (c == '/') {
slash_index = i;
}
i = (i + 1);
}
return slash_index;
}
static void search_include(char quote_style) {
//printf("search include %s\n", current_string);
// The path is in current_string. If it starts with /, it's an absolute
// path so we just open that file directly.
if (*current_string == '/') {
FILE* file;
file = fopen(current_string, "r");
if (file == 0) {
fatal("Failed to open include file with absolute path.");
}
preprocess(current_string, file);
return;
}
// Only check the path of the current file if we're using quotes, not angle
// brackets.
if (quote_style == '"') {
// Get the path of the current file.
int slash_index;
slash_index = find_slash(current_filename);
// If there's no path, try the current path
if (slash_index == -1) {
if (try_include(".")) {
return;
}
}
// If there is a path, check there.
if (slash_index != -1) {
char* prefix = strndup(current_filename, slash_index);
int found = try_include(prefix);
free(prefix);
if (found) {
return;
}
}
}
// Search through our include paths.
void** entry;
entry = include_paths;
while (entry != 0) {
//printf("entry %s\n", (const char*)*(entry + 1));
if (try_include((const char*)*(entry + 1))) {
return;
}
entry = (void**)*entry;
}
fatal("include file not found.");
}
/*
* Parsing
*/
static void handle_line(void) {
fatal("#line preproc not implemented");
}
static void handle_include(void) {
/* A lack of space between #include and the filename is apparently allowed. */
consume_optional_horizontal_whitespace();
/* The end quote style must match the start quote style */
char end_char;
end_char = 0;
if (current_char == '"') {
end_char = '"';
}
if (current_char == '<') {
end_char = '>';
}
if (end_char == 0) {
fatal("include must be followed by < or a double quote");
}
next_char();
/* Scan until we find the end, accumulating into current_string */
size_t i;
i = 0;
while (current_char != end_char) {
// check for end of line
// (no need to check for EOF, we synthesize a newline if missing)
if ((current_char == 0xA) | (current_char == 0xD)) {
fputs("current_char ", stdout);
fputd(current_char, stdout);
fputs("\n", stdout);
fatal("Unclosed include");
}
*(current_string + i) = current_char;
i = (i + 1);
next_char();
if (i == current_string_capacity) {
fatal("include filename is too long.");
}
}
next_char();
// Finish parsing
if (i == 0) {
fatal("Expected a filename for include.");
}
*(current_string + i) = 0;
consume_end_of_line();
search_include(end_char);
}
static void handle_define(void) {
consume_horizontal_whitespace();
consume_identifier();
char* name;
name = strdup(current_string);
// If the name is followed by an open parenthesis, this is a function-like
// macro.
if (current_char == '(') {
fatal("Function-like macros are not supported by the omC preprocessor.");
}
// If we have a newline without horizontal whitespace, there's no expansion
// string.
if (current_char == '\n') {
macro_new(name, strdup(""));
return;
}
// Otherwise we require horizontal whitespace before the expansion. The
// expansion might still be blank.
consume_horizontal_whitespace();
consume_expansion();
char* expansion;
expansion = strdup(current_string);
consume_end_of_line();
macro_new(name, expansion);
}
static void handle_conditional(int predicate) {
if (predicate) {
/* The #ifdef/#ifndef is true. Keep parsing. */
depth = (depth + 1);
return;
}
/* The #ifdef/#ifndef conditional is false. We have to consume everything
* until the matching #endif, making sure to track nested #if directives. */
int false_depth = 0;
while (1) {
if (current_char == '#') {
next_char();
consume_optional_horizontal_whitespace();
/* Any old nonsense is allowed in untaken conditional branches (and
* in particular we don't want to fail on `##` token pasting and
* other things.) If we don't have an identifier we skip. */
if (!is_identifier_char(current_char, true)) {
next_char();
continue;
}
/* Nested #if directives push our stack. */
consume_identifier();
if (((0 == strcmp(current_string, "ifdef")) |
(0 == strcmp(current_string, "ifndef"))) |
(0 == strcmp(current_string, "if")))
{
false_depth = (false_depth + 1);
continue;
}
/* An #endif directive pops the stack. If it's empty, we're done. */
if (0 == strcmp(current_string, "endif")) {
if (false_depth == 0) {
/* Done. */
return;
}
false_depth = (false_depth - 1);
continue;
}
/* Matching #else directives are not supported. We check for them
* explicitly because ignoring them would silently produce
* different output from a full C compiler. We only care if they
* are at the top level; nested #else directives can be safely
* ignored. See test: ifdef/ifdef-false-else.c */
if ((false_depth == 0) & (((0 == strcmp(current_string, "else")) |
(0 == strcmp(current_string, "elif"))) |
((0 == strcmp(current_string, "elifdef")) |
(0 == strcmp(current_string, "elifndef")))))
{
fatal("`#else` and `#elif` are not supported.");
}
/* No other directives matter. (In fact the C spec requires that we
* ignore whatever we find in preprocessor directives on untaken
* conditional branches.) */
continue;
}
/* If we've reached the end of the file, we're missing an #endif */
if (current_char == 0) {
fatal("Unclosed if; expected endif before end of file");
}
/* We don't care about anything else. */
next_char();
}
}
static void handle_ifdef(void) {
consume_horizontal_whitespace();
consume_identifier();
consume_end_of_line();
handle_conditional(macro_find(current_string) != 0);
}
static void handle_ifndef(void) {
consume_horizontal_whitespace();
consume_identifier();
if (guard_state == guard_state_outside) {
if (guard_macro) {
// second #ifndef block at top-level
guard_state = guard_state_fail;
}
if (!guard_macro) {
// TODO we need to check all the strdup() and other allocs in this
// file for out of memory errors
guard_macro = strdup(current_string);
guard_state = guard_state_inside;
}
}
consume_end_of_line();
handle_conditional(macro_find(current_string) == 0);
}
static void handle_endif(void) {
consume_end_of_line();
if (depth == 1) {
if (guard_state == guard_state_inside) {
guard_state = guard_state_outside;
}
}
if (depth == 0) {
fatal("endif without if");
}
depth = (depth - 1);
}
static void expand_macro(void** macro);