Correct indentation.
[cparser] / preprocessor.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <stdbool.h>
7 #include <ctype.h>
8
9 #include "token_t.h"
10 #include "symbol_t.h"
11 #include "adt/util.h"
12 #include "adt/error.h"
13 #include "adt/strutil.h"
14 #include "adt/strset.h"
15 #include "lang_features.h"
16 #include "diagnostic.h"
17 #include "string_rep.h"
18 #include "input.h"
19
20 #define MAX_PUTBACK 3
21 #define INCLUDE_LIMIT 199  /* 199 is for gcc "compatibility" */
22
23 struct pp_argument_t {
24         size_t   list_len;
25         token_t *token_list;
26 };
27
28 struct pp_definition_t {
29         symbol_t          *symbol;
30         source_position_t  source_position;
31         pp_definition_t   *parent_expansion;
32         size_t             expand_pos;
33         bool               is_variadic    : 1;
34         bool               is_expanding   : 1;
35         bool               has_parameters : 1;
36         size_t             n_parameters;
37         symbol_t          *parameters;
38
39         /* replacement */
40         size_t             list_len;
41         token_t           *token_list;
42
43 };
44
45 typedef struct pp_conditional_t pp_conditional_t;
46 struct pp_conditional_t {
47         source_position_t  source_position;
48         bool               condition;
49         bool               in_else;
50         bool               skip; /**< conditional in skip mode (then+else gets skipped) */
51         pp_conditional_t  *parent;
52 };
53
54 typedef struct pp_input_t pp_input_t;
55 struct pp_input_t {
56         FILE              *file;
57         input_t           *input;
58         utf32              c;
59         utf32              buf[1024+MAX_PUTBACK];
60         const utf32       *bufend;
61         const utf32       *bufpos;
62         source_position_t  position;
63         pp_input_t        *parent;
64         unsigned           output_line;
65 };
66
67 /** additional info about the current token */
68 typedef struct add_token_info_t {
69         /** whitespace from beginning of line to the token */
70         unsigned whitespace;
71         /** there has been any whitespace before the token */
72         bool     had_whitespace;
73         /** the token is at the beginning of the line */
74         bool     at_line_begin;
75 } add_token_info_t;
76
77 typedef struct searchpath_entry_t searchpath_entry_t;
78 struct searchpath_entry_t {
79         const char         *path;
80         searchpath_entry_t *next;
81 };
82
83 static pp_input_t      input;
84
85 static pp_input_t     *input_stack;
86 static unsigned        n_inputs;
87 static struct obstack  input_obstack;
88
89 static pp_conditional_t *conditional_stack;
90
91 static token_t           pp_token;
92 static bool              resolve_escape_sequences = false;
93 static bool              error_on_unknown_chars   = true;
94 static bool              skip_mode;
95 static FILE             *out;
96 static struct obstack    pp_obstack;
97 static struct obstack    config_obstack;
98 static const char       *printed_input_name = NULL;
99 static source_position_t expansion_pos;
100 static pp_definition_t  *current_expansion  = NULL;
101 static strset_t          stringset;
102 static token_kind_t      last_token;
103
104 static searchpath_entry_t *searchpath;
105
106 static add_token_info_t  info;
107
108 static inline void next_char(void);
109 static void next_preprocessing_token(void);
110 static void print_line_directive(const source_position_t *pos, const char *add);
111
112 static void switch_input(FILE *file, const char *filename)
113 {
114         input.file                = file;
115         input.input               = input_from_stream(file, NULL);
116         input.bufend              = NULL;
117         input.bufpos              = NULL;
118         input.output_line         = 0;
119         input.position.input_name = filename;
120         input.position.lineno     = 1;
121
122         /* indicate that we're at a new input */
123         print_line_directive(&input.position, input_stack != NULL ? "1" : NULL);
124
125         /* place a virtual '\n' so we realize we're at line begin */
126         input.position.lineno = 0;
127         input.c               = '\n';
128         next_preprocessing_token();
129 }
130
131 static void close_input(void)
132 {
133         input_free(input.input);
134         assert(input.file != NULL);
135
136         fclose(input.file);
137         input.input  = NULL;
138         input.file   = NULL;
139         input.bufend = NULL;
140         input.bufpos = NULL;
141         input.c      = EOF;
142 }
143
144 static void push_input(void)
145 {
146         pp_input_t *saved_input
147                 = obstack_alloc(&input_obstack, sizeof(*saved_input));
148
149         memcpy(saved_input, &input, sizeof(*saved_input));
150
151         /* adjust buffer positions */
152         if (input.bufpos != NULL)
153                 saved_input->bufpos = saved_input->buf + (input.bufpos - input.buf);
154         if (input.bufend != NULL)
155                 saved_input->bufend = saved_input->buf + (input.bufend - input.buf);
156
157         saved_input->parent = input_stack;
158         input_stack         = saved_input;
159         ++n_inputs;
160 }
161
162 static void pop_restore_input(void)
163 {
164         assert(n_inputs > 0);
165         assert(input_stack != NULL);
166
167         pp_input_t *saved_input = input_stack;
168
169         memcpy(&input, saved_input, sizeof(input));
170         input.parent = NULL;
171
172         /* adjust buffer positions */
173         if (saved_input->bufpos != NULL)
174                 input.bufpos = input.buf + (saved_input->bufpos - saved_input->buf);
175         if (saved_input->bufend != NULL)
176                 input.bufend = input.buf + (saved_input->bufend - saved_input->buf);
177
178         input_stack = saved_input->parent;
179         obstack_free(&input_obstack, saved_input);
180         --n_inputs;
181 }
182
183 /**
184  * Prints a parse error message at the current token.
185  *
186  * @param msg   the error message
187  */
188 static void parse_error(const char *msg)
189 {
190         errorf(&pp_token.base.source_position,  "%s", msg);
191 }
192
193 static inline void next_real_char(void)
194 {
195         assert(input.bufpos <= input.bufend);
196         if (input.bufpos >= input.bufend) {
197                 size_t const n = decode(input.input, input.buf + MAX_PUTBACK, lengthof(input.buf) - MAX_PUTBACK);
198                 if (n == 0) {
199                         input.c = EOF;
200                         return;
201                 }
202                 input.bufpos = input.buf + MAX_PUTBACK;
203                 input.bufend = input.bufpos + n;
204         }
205         input.c = *input.bufpos++;
206         ++input.position.colno;
207 }
208
209 /**
210  * Put a character back into the buffer.
211  *
212  * @param pc  the character to put back
213  */
214 static inline void put_back(utf32 const pc)
215 {
216         assert(input.bufpos > input.buf);
217         *(--input.bufpos - input.buf + input.buf) = (char) pc;
218         --input.position.colno;
219 }
220
221 #define NEWLINE \
222         '\r': \
223                 next_char(); \
224                 if (input.c == '\n') { \
225         case '\n': \
226                         next_char(); \
227                 } \
228                 info.whitespace = 0; \
229                 ++input.position.lineno; \
230                 input.position.colno = 1; \
231                 goto newline; \
232                 newline // Let it look like an ordinary case label.
233
234 #define eat(c_type) (assert(input.c == c_type), next_char())
235
236 static void maybe_concat_lines(void)
237 {
238         eat('\\');
239
240         switch (input.c) {
241         case NEWLINE:
242                 return;
243
244         default:
245                 break;
246         }
247
248         put_back(input.c);
249         input.c = '\\';
250 }
251
252 /**
253  * Set c to the next input character, ie.
254  * after expanding trigraphs.
255  */
256 static inline void next_char(void)
257 {
258         next_real_char();
259
260         /* filter trigraphs and concatenated lines */
261         if (UNLIKELY(input.c == '\\')) {
262                 maybe_concat_lines();
263                 goto end_of_next_char;
264         }
265
266         if (LIKELY(input.c != '?'))
267                 goto end_of_next_char;
268
269         next_real_char();
270         if (LIKELY(input.c != '?')) {
271                 put_back(input.c);
272                 input.c = '?';
273                 goto end_of_next_char;
274         }
275
276         next_real_char();
277         switch (input.c) {
278         case '=': input.c = '#'; break;
279         case '(': input.c = '['; break;
280         case '/': input.c = '\\'; maybe_concat_lines(); break;
281         case ')': input.c = ']'; break;
282         case '\'': input.c = '^'; break;
283         case '<': input.c = '{'; break;
284         case '!': input.c = '|'; break;
285         case '>': input.c = '}'; break;
286         case '-': input.c = '~'; break;
287         default:
288                 put_back(input.c);
289                 put_back('?');
290                 input.c = '?';
291                 break;
292         }
293
294 end_of_next_char:;
295 #ifdef DEBUG_CHARS
296         printf("nchar '%c'\n", input.c);
297 #endif
298 }
299
300
301
302 /**
303  * Returns true if the given char is a octal digit.
304  *
305  * @param char  the character to check
306  */
307 static inline bool is_octal_digit(int chr)
308 {
309         switch (chr) {
310         case '0':
311         case '1':
312         case '2':
313         case '3':
314         case '4':
315         case '5':
316         case '6':
317         case '7':
318                 return true;
319         default:
320                 return false;
321         }
322 }
323
324 /**
325  * Returns the value of a digit.
326  * The only portable way to do it ...
327  */
328 static int digit_value(int digit)
329 {
330         switch (digit) {
331         case '0': return 0;
332         case '1': return 1;
333         case '2': return 2;
334         case '3': return 3;
335         case '4': return 4;
336         case '5': return 5;
337         case '6': return 6;
338         case '7': return 7;
339         case '8': return 8;
340         case '9': return 9;
341         case 'a':
342         case 'A': return 10;
343         case 'b':
344         case 'B': return 11;
345         case 'c':
346         case 'C': return 12;
347         case 'd':
348         case 'D': return 13;
349         case 'e':
350         case 'E': return 14;
351         case 'f':
352         case 'F': return 15;
353         default:
354                 panic("wrong character given");
355         }
356 }
357
358 /**
359  * Parses an octal character sequence.
360  *
361  * @param first_digit  the already read first digit
362  */
363 static utf32 parse_octal_sequence(const utf32 first_digit)
364 {
365         assert(is_octal_digit(first_digit));
366         utf32 value = digit_value(first_digit);
367         if (!is_octal_digit(input.c)) return value;
368         value = 8 * value + digit_value(input.c);
369         next_char();
370         if (!is_octal_digit(input.c)) return value;
371         value = 8 * value + digit_value(input.c);
372         next_char();
373         return value;
374
375 }
376
377 /**
378  * Parses a hex character sequence.
379  */
380 static utf32 parse_hex_sequence(void)
381 {
382         utf32 value = 0;
383         while (isxdigit(input.c)) {
384                 value = 16 * value + digit_value(input.c);
385                 next_char();
386         }
387         return value;
388 }
389
390 /**
391  * Parse an escape sequence.
392  */
393 static utf32 parse_escape_sequence(void)
394 {
395         eat('\\');
396
397         utf32 const ec = input.c;
398         next_char();
399
400         switch (ec) {
401         case '"':  return '"';
402         case '\'': return '\'';
403         case '\\': return '\\';
404         case '?': return '\?';
405         case 'a': return '\a';
406         case 'b': return '\b';
407         case 'f': return '\f';
408         case 'n': return '\n';
409         case 'r': return '\r';
410         case 't': return '\t';
411         case 'v': return '\v';
412         case 'x':
413                 return parse_hex_sequence();
414         case '0':
415         case '1':
416         case '2':
417         case '3':
418         case '4':
419         case '5':
420         case '6':
421         case '7':
422                 return parse_octal_sequence(ec);
423         case EOF:
424                 parse_error("reached end of file while parsing escape sequence");
425                 return EOF;
426         /* \E is not documented, but handled, by GCC.  It is acceptable according
427          * to Â§6.11.4, whereas \e is not. */
428         case 'E':
429         case 'e':
430                 if (c_mode & _GNUC)
431                         return 27;   /* hopefully 27 is ALWAYS the code for ESCAPE */
432                 break;
433         case 'u':
434         case 'U':
435                 parse_error("universal character parsing not implemented yet");
436                 return EOF;
437         default:
438                 break;
439         }
440         /* Â§6.4.4.4:8 footnote 64 */
441         parse_error("unknown escape sequence");
442         return EOF;
443 }
444
445 static const char *identify_string(char *string)
446 {
447         const char *result = strset_insert(&stringset, string);
448         if (result != string) {
449                 obstack_free(&symbol_obstack, string);
450         }
451         return result;
452 }
453
454 static string_t sym_make_string(string_encoding_t const enc)
455 {
456         obstack_1grow(&symbol_obstack, '\0');
457         size_t      const len    = obstack_object_size(&symbol_obstack) - 1;
458         char       *const string = obstack_finish(&symbol_obstack);
459         char const *const result = identify_string(string);
460         return (string_t){ result, len, enc };
461 }
462
463 static void parse_string(utf32 const delimiter, token_kind_t const kind,
464                          string_encoding_t const enc,
465                          char const *const context)
466 {
467         const unsigned start_linenr = input.position.lineno;
468
469         eat(delimiter);
470
471         while (true) {
472                 switch (input.c) {
473                 case '\\': {
474                         if (resolve_escape_sequences) {
475                                 utf32 const tc = parse_escape_sequence();
476                                 if (enc == STRING_ENCODING_CHAR) {
477                                         if (tc >= 0x100) {
478                                                 warningf(WARN_OTHER, &pp_token.base.source_position, "escape sequence out of range");
479                                         }
480                                         obstack_1grow(&symbol_obstack, tc);
481                                 } else {
482                                         obstack_grow_utf8(&symbol_obstack, tc);
483                                 }
484                         } else {
485                                 obstack_1grow(&symbol_obstack, (char)input.c);
486                                 next_char();
487                                 obstack_1grow(&symbol_obstack, (char)input.c);
488                                 next_char();
489                         }
490                         break;
491                 }
492
493                 case NEWLINE:
494                         errorf(&pp_token.base.source_position, "newline while parsing %s", context);
495                         break;
496
497                 case EOF: {
498                         source_position_t source_position;
499                         source_position.input_name = pp_token.base.source_position.input_name;
500                         source_position.lineno     = start_linenr;
501                         errorf(&source_position, "EOF while parsing %s", context);
502                         goto end_of_string;
503                 }
504
505                 default:
506                         if (input.c == delimiter) {
507                                 next_char();
508                                 goto end_of_string;
509                         } else {
510                                 obstack_grow_utf8(&symbol_obstack, input.c);
511                                 next_char();
512                                 break;
513                         }
514                 }
515         }
516
517 end_of_string:
518         pp_token.kind           = kind;
519         pp_token.literal.string = sym_make_string(enc);
520 }
521
522 static void parse_string_literal(string_encoding_t const enc)
523 {
524         parse_string('"', T_STRING_LITERAL, enc, "string literal");
525 }
526
527 static void parse_character_constant(string_encoding_t const enc)
528 {
529         parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
530         if (pp_token.literal.string.size == 0) {
531                 parse_error("empty character constant");
532         }
533 }
534
535 #define SYMBOL_CASES_WITHOUT_E_P \
536              'a': \
537         case 'b': \
538         case 'c': \
539         case 'd': \
540         case 'f': \
541         case 'g': \
542         case 'h': \
543         case 'i': \
544         case 'j': \
545         case 'k': \
546         case 'l': \
547         case 'm': \
548         case 'n': \
549         case 'o': \
550         case 'q': \
551         case 'r': \
552         case 's': \
553         case 't': \
554         case 'u': \
555         case 'v': \
556         case 'w': \
557         case 'x': \
558         case 'y': \
559         case 'z': \
560         case 'A': \
561         case 'B': \
562         case 'C': \
563         case 'D': \
564         case 'F': \
565         case 'G': \
566         case 'H': \
567         case 'I': \
568         case 'J': \
569         case 'K': \
570         case 'L': \
571         case 'M': \
572         case 'N': \
573         case 'O': \
574         case 'Q': \
575         case 'R': \
576         case 'S': \
577         case 'T': \
578         case 'U': \
579         case 'V': \
580         case 'W': \
581         case 'X': \
582         case 'Y': \
583         case 'Z': \
584         case '_'
585
586 #define SYMBOL_CASES \
587              SYMBOL_CASES_WITHOUT_E_P: \
588         case 'e': \
589         case 'p': \
590         case 'E': \
591         case 'P'
592
593 #define DIGIT_CASES \
594              '0':  \
595         case '1':  \
596         case '2':  \
597         case '3':  \
598         case '4':  \
599         case '5':  \
600         case '6':  \
601         case '7':  \
602         case '8':  \
603         case '9'
604
605 /**
606  * returns next final token from a preprocessor macro expansion
607  */
608 static void expand_next(void)
609 {
610         assert(current_expansion != NULL);
611
612         pp_definition_t *definition = current_expansion;
613
614 restart:
615         if (definition->list_len == 0
616                         || definition->expand_pos >= definition->list_len) {
617                 /* we're finished with the current macro, move up 1 level in the
618                  * expansion stack */
619                 pp_definition_t *parent = definition->parent_expansion;
620                 definition->parent_expansion = NULL;
621                 definition->is_expanding     = false;
622
623                 /* it was the outermost expansion, parse normal pptoken */
624                 if (parent == NULL) {
625                         current_expansion = NULL;
626                         next_preprocessing_token();
627                         return;
628                 }
629                 definition        = parent;
630                 current_expansion = definition;
631                 goto restart;
632         }
633         pp_token = definition->token_list[definition->expand_pos];
634         pp_token.base.source_position = expansion_pos;
635         ++definition->expand_pos;
636
637         if (pp_token.kind != T_IDENTIFIER)
638                 return;
639
640         /* if it was an identifier then we might need to expand again */
641         pp_definition_t *const symbol_definition = pp_token.base.symbol->pp_definition;
642         if (symbol_definition != NULL && !symbol_definition->is_expanding) {
643                 symbol_definition->parent_expansion = definition;
644                 symbol_definition->expand_pos       = 0;
645                 symbol_definition->is_expanding     = true;
646                 definition                          = symbol_definition;
647                 current_expansion                   = definition;
648                 goto restart;
649         }
650 }
651
652 static void skip_line_comment(void)
653 {
654         while (true) {
655                 switch (input.c) {
656                 case EOF:
657                         return;
658
659                 case '\r':
660                 case '\n':
661                         return;
662
663                 default:
664                         next_char();
665                         break;
666                 }
667         }
668 }
669
670 static void skip_multiline_comment(void)
671 {
672         unsigned start_linenr = input.position.lineno;
673         while (true) {
674                 switch (input.c) {
675                 case '/':
676                         next_char();
677                         if (input.c == '*') {
678                                 /* TODO: nested comment, warn here */
679                         }
680                         break;
681                 case '*':
682                         next_char();
683                         if (input.c == '/') {
684                                 if (input.position.lineno != input.output_line)
685                                         info.whitespace = input.position.colno;
686                                 next_char();
687                                 return;
688                         }
689                         break;
690
691                 case NEWLINE:
692                         break;
693
694                 case EOF: {
695                         source_position_t source_position;
696                         source_position.input_name = pp_token.base.source_position.input_name;
697                         source_position.lineno     = start_linenr;
698                         errorf(&source_position, "at end of file while looking for comment end");
699                         return;
700                 }
701
702                 default:
703                         next_char();
704                         break;
705                 }
706         }
707 }
708
709 static void skip_whitespace(void)
710 {
711         while (true) {
712                 switch (input.c) {
713                 case ' ':
714                 case '\t':
715                         next_char();
716                         continue;
717
718                 case NEWLINE:
719                         info.at_line_begin = true;
720                         return;
721
722                 case '/':
723                         next_char();
724                         if (input.c == '/') {
725                                 next_char();
726                                 skip_line_comment();
727                                 continue;
728                         } else if (input.c == '*') {
729                                 next_char();
730                                 skip_multiline_comment();
731                                 continue;
732                         } else {
733                                 put_back(input.c);
734                                 input.c = '/';
735                         }
736                         return;
737                 default:
738                         return;
739                 }
740         }
741 }
742
743 static inline void eat_pp(pp_token_kind_t const kind)
744 {
745         assert(pp_token.base.symbol->pp_ID == kind);
746         (void) kind;
747         next_preprocessing_token();
748 }
749
750 static inline void eat_token(token_kind_t const kind)
751 {
752         assert(pp_token.kind == kind);
753         (void)kind;
754         next_preprocessing_token();
755 }
756
757 static void parse_symbol(void)
758 {
759         obstack_1grow(&symbol_obstack, (char) input.c);
760         next_char();
761
762         while (true) {
763                 switch (input.c) {
764                 case DIGIT_CASES:
765                 case SYMBOL_CASES:
766                         obstack_1grow(&symbol_obstack, (char) input.c);
767                         next_char();
768                         break;
769
770                 default:
771                         goto end_symbol;
772                 }
773         }
774
775 end_symbol:
776         obstack_1grow(&symbol_obstack, '\0');
777         char *string = obstack_finish(&symbol_obstack);
778
779         /* might be a wide string or character constant ( L"string"/L'c' ) */
780         if (input.c == '"' && string[0] == 'L' && string[1] == '\0') {
781                 obstack_free(&symbol_obstack, string);
782                 parse_string_literal(STRING_ENCODING_WIDE);
783                 return;
784         } else if (input.c == '\'' && string[0] == 'L' && string[1] == '\0') {
785                 obstack_free(&symbol_obstack, string);
786                 parse_character_constant(STRING_ENCODING_WIDE);
787                 return;
788         }
789
790         symbol_t *symbol = symbol_table_insert(string);
791
792         pp_token.kind        = symbol->ID;
793         pp_token.base.symbol = symbol;
794
795         /* we can free the memory from symbol obstack if we already had an entry in
796          * the symbol table */
797         if (symbol->string != string) {
798                 obstack_free(&symbol_obstack, string);
799         }
800 }
801
802 static void parse_number(void)
803 {
804         obstack_1grow(&symbol_obstack, (char) input.c);
805         next_char();
806
807         while (true) {
808                 switch (input.c) {
809                 case '.':
810                 case DIGIT_CASES:
811                 case SYMBOL_CASES_WITHOUT_E_P:
812                         obstack_1grow(&symbol_obstack, (char) input.c);
813                         next_char();
814                         break;
815
816                 case 'e':
817                 case 'p':
818                 case 'E':
819                 case 'P':
820                         obstack_1grow(&symbol_obstack, (char) input.c);
821                         next_char();
822                         if (input.c == '+' || input.c == '-') {
823                                 obstack_1grow(&symbol_obstack, (char) input.c);
824                                 next_char();
825                         }
826                         break;
827
828                 default:
829                         goto end_number;
830                 }
831         }
832
833 end_number:
834         pp_token.kind           = T_NUMBER;
835         pp_token.literal.string = sym_make_string(STRING_ENCODING_CHAR);
836 }
837
838
839 #define MAYBE_PROLOG                                       \
840                         next_char();                                   \
841                         while (true) {                                 \
842                                 switch (input.c) {
843
844 #define MAYBE(ch, set_type)                                \
845                                 case ch:                                   \
846                                         next_char();                           \
847                                         pp_token.kind = set_type;              \
848                                         return;
849
850 #define ELSE_CODE(code)                                    \
851                                 default:                                   \
852                                         code                                   \
853                                         return;                                \
854                                 }                                          \
855                         }
856
857 #define ELSE(set_type)                                     \
858                 ELSE_CODE(                                         \
859                         pp_token.kind = set_type;                      \
860                 )
861
862 static void next_preprocessing_token(void)
863 {
864         if (current_expansion != NULL) {
865                 expand_next();
866                 return;
867         }
868
869         info.at_line_begin  = false;
870         info.had_whitespace = false;
871 restart:
872         pp_token.base.source_position = input.position;
873         pp_token.base.symbol          = NULL;
874
875         switch (input.c) {
876         case ' ':
877         case '\t':
878                 ++info.whitespace;
879                 info.had_whitespace = true;
880                 next_char();
881                 goto restart;
882
883         case NEWLINE:
884                 info.at_line_begin = true;
885                 info.had_whitespace = true;
886                 goto restart;
887
888         case SYMBOL_CASES:
889                 parse_symbol();
890                 return;
891
892         case DIGIT_CASES:
893                 parse_number();
894                 return;
895
896         case '"':
897                 parse_string_literal(STRING_ENCODING_CHAR);
898                 return;
899
900         case '\'':
901                 parse_character_constant(STRING_ENCODING_CHAR);
902                 return;
903
904         case '.':
905                 MAYBE_PROLOG
906                         case '0':
907                         case '1':
908                         case '2':
909                         case '3':
910                         case '4':
911                         case '5':
912                         case '6':
913                         case '7':
914                         case '8':
915                         case '9':
916                                 put_back(input.c);
917                                 input.c = '.';
918                                 parse_number();
919                                 return;
920
921                         case '.':
922                                 MAYBE_PROLOG
923                                 MAYBE('.', T_DOTDOTDOT)
924                                 ELSE_CODE(
925                                         put_back(input.c);
926                                         input.c = '.';
927                                         pp_token.kind = '.';
928                                 )
929                 ELSE('.')
930         case '&':
931                 MAYBE_PROLOG
932                 MAYBE('&', T_ANDAND)
933                 MAYBE('=', T_ANDEQUAL)
934                 ELSE('&')
935         case '*':
936                 MAYBE_PROLOG
937                 MAYBE('=', T_ASTERISKEQUAL)
938                 ELSE('*')
939         case '+':
940                 MAYBE_PROLOG
941                 MAYBE('+', T_PLUSPLUS)
942                 MAYBE('=', T_PLUSEQUAL)
943                 ELSE('+')
944         case '-':
945                 MAYBE_PROLOG
946                 MAYBE('>', T_MINUSGREATER)
947                 MAYBE('-', T_MINUSMINUS)
948                 MAYBE('=', T_MINUSEQUAL)
949                 ELSE('-')
950         case '!':
951                 MAYBE_PROLOG
952                 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
953                 ELSE('!')
954         case '/':
955                 MAYBE_PROLOG
956                 MAYBE('=', T_SLASHEQUAL)
957                 case '*':
958                         next_char();
959                         info.had_whitespace = true;
960                         skip_multiline_comment();
961                         goto restart;
962                 case '/':
963                         next_char();
964                         info.had_whitespace = true;
965                         skip_line_comment();
966                         goto restart;
967                 ELSE('/')
968         case '%':
969                 MAYBE_PROLOG
970                 MAYBE('>', '}')
971                 MAYBE('=', T_PERCENTEQUAL)
972                 case ':':
973                         MAYBE_PROLOG
974                         case '%':
975                                 MAYBE_PROLOG
976                                 MAYBE(':', T_HASHHASH)
977                                 ELSE_CODE(
978                                         put_back(input.c);
979                                         input.c = '%';
980                                         pp_token.kind = '#';
981                                 )
982                         ELSE('#')
983                 ELSE('%')
984         case '<':
985                 MAYBE_PROLOG
986                 MAYBE(':', '[')
987                 MAYBE('%', '{')
988                 MAYBE('=', T_LESSEQUAL)
989                 case '<':
990                         MAYBE_PROLOG
991                         MAYBE('=', T_LESSLESSEQUAL)
992                         ELSE(T_LESSLESS)
993                 ELSE('<')
994         case '>':
995                 MAYBE_PROLOG
996                 MAYBE('=', T_GREATEREQUAL)
997                 case '>':
998                         MAYBE_PROLOG
999                         MAYBE('=', T_GREATERGREATEREQUAL)
1000                         ELSE(T_GREATERGREATER)
1001                 ELSE('>')
1002         case '^':
1003                 MAYBE_PROLOG
1004                 MAYBE('=', T_CARETEQUAL)
1005                 ELSE('^')
1006         case '|':
1007                 MAYBE_PROLOG
1008                 MAYBE('=', T_PIPEEQUAL)
1009                 MAYBE('|', T_PIPEPIPE)
1010                 ELSE('|')
1011         case ':':
1012                 MAYBE_PROLOG
1013                 MAYBE('>', ']')
1014                 ELSE(':')
1015         case '=':
1016                 MAYBE_PROLOG
1017                 MAYBE('=', T_EQUALEQUAL)
1018                 ELSE('=')
1019         case '#':
1020                 MAYBE_PROLOG
1021                 MAYBE('#', T_HASHHASH)
1022                 ELSE_CODE(
1023                         pp_token.kind = '#';
1024                 )
1025
1026         case '?':
1027         case '[':
1028         case ']':
1029         case '(':
1030         case ')':
1031         case '{':
1032         case '}':
1033         case '~':
1034         case ';':
1035         case ',':
1036                 pp_token.kind = input.c;
1037                 next_char();
1038                 return;
1039
1040         case EOF:
1041                 if (input_stack != NULL) {
1042                         close_input();
1043                         pop_restore_input();
1044                         fputc('\n', out);
1045                         print_line_directive(&input.position, "2");
1046                         goto restart;
1047                 } else {
1048                         pp_token.base.source_position.lineno++;
1049                         info.at_line_begin = true;
1050                         pp_token.kind      = T_EOF;
1051                 }
1052                 return;
1053
1054         default:
1055                 if (error_on_unknown_chars) {
1056                         errorf(&pp_token.base.source_position,
1057                                "unknown character '%lc' found\n", input.c);
1058                         next_char();
1059                         goto restart;
1060                 } else {
1061                         assert(obstack_object_size(&symbol_obstack) == 0);
1062                         obstack_grow_utf8(&symbol_obstack, input.c);
1063                         obstack_1grow(&symbol_obstack, '\0');
1064                         char     *const string = obstack_finish(&symbol_obstack);
1065                         symbol_t *const symbol = symbol_table_insert(string);
1066                         if (symbol->string != string)
1067                                 obstack_free(&symbol_obstack, string);
1068
1069                         pp_token.kind        = T_UNKNOWN_CHAR;
1070                         pp_token.base.symbol = symbol;
1071                         next_char();
1072                         return;
1073                 }
1074         }
1075 }
1076
1077 static void print_quoted_string(const char *const string)
1078 {
1079         fputc('"', out);
1080         for (const char *c = string; *c != 0; ++c) {
1081                 switch (*c) {
1082                 case '"': fputs("\\\"", out); break;
1083                 case '\\':  fputs("\\\\", out); break;
1084                 case '\a':  fputs("\\a", out); break;
1085                 case '\b':  fputs("\\b", out); break;
1086                 case '\f':  fputs("\\f", out); break;
1087                 case '\n':  fputs("\\n", out); break;
1088                 case '\r':  fputs("\\r", out); break;
1089                 case '\t':  fputs("\\t", out); break;
1090                 case '\v':  fputs("\\v", out); break;
1091                 case '\?':  fputs("\\?", out); break;
1092                 default:
1093                         if (!isprint(*c)) {
1094                                 fprintf(out, "\\%03o", (unsigned)*c);
1095                                 break;
1096                         }
1097                         fputc(*c, out);
1098                         break;
1099                 }
1100         }
1101         fputc('"', out);
1102 }
1103
1104 static void print_line_directive(const source_position_t *pos, const char *add)
1105 {
1106         fprintf(out, "# %u ", pos->lineno);
1107         print_quoted_string(pos->input_name);
1108         if (add != NULL) {
1109                 fputc(' ', out);
1110                 fputs(add, out);
1111         }
1112
1113         printed_input_name = pos->input_name;
1114         input.output_line  = pos->lineno-1;
1115 }
1116
1117 static bool emit_newlines(void)
1118 {
1119         unsigned delta = pp_token.base.source_position.lineno - input.output_line;
1120         if (delta == 0)
1121                 return false;
1122
1123         if (delta >= 9) {
1124                 fputc('\n', out);
1125                 print_line_directive(&pp_token.base.source_position, NULL);
1126                 fputc('\n', out);
1127         } else {
1128                 for (unsigned i = 0; i < delta; ++i) {
1129                         fputc('\n', out);
1130                 }
1131         }
1132         input.output_line = pp_token.base.source_position.lineno;
1133
1134         for (unsigned i = 0; i < info.whitespace; ++i)
1135                 fputc(' ', out);
1136
1137         return true;
1138 }
1139
1140 static void emit_pp_token(void)
1141 {
1142         if (skip_mode)
1143                 return;
1144
1145         if (!emit_newlines() &&
1146             (info.had_whitespace || tokens_would_paste(last_token, pp_token.kind)))
1147                 fputc(' ', out);
1148
1149         switch (pp_token.kind) {
1150         case T_NUMBER:
1151                 fputs(pp_token.literal.string.begin, out);
1152                 break;
1153
1154         case T_STRING_LITERAL:
1155                 fputs(get_string_encoding_prefix(pp_token.literal.string.encoding), out);
1156                 fputc('"', out);
1157                 fputs(pp_token.literal.string.begin, out);
1158                 fputc('"', out);
1159                 break;
1160
1161         case T_CHARACTER_CONSTANT:
1162                 fputs(get_string_encoding_prefix(pp_token.literal.string.encoding), out);
1163                 fputc('\'', out);
1164                 fputs(pp_token.literal.string.begin, out);
1165                 fputc('\'', out);
1166                 break;
1167
1168         default:
1169                 if (pp_token.base.symbol) {
1170                         fputs(pp_token.base.symbol->string, out);
1171                 } else {
1172                         print_token_kind(out, pp_token.kind);
1173                 }
1174                 break;
1175         }
1176         last_token = pp_token.kind;
1177 }
1178
1179 static void eat_pp_directive(void)
1180 {
1181         while (!info.at_line_begin) {
1182                 next_preprocessing_token();
1183         }
1184 }
1185
1186 static bool strings_equal(const string_t *string1, const string_t *string2)
1187 {
1188         size_t size = string1->size;
1189         if (size != string2->size)
1190                 return false;
1191
1192         const char *c1 = string1->begin;
1193         const char *c2 = string2->begin;
1194         for (size_t i = 0; i < size; ++i, ++c1, ++c2) {
1195                 if (*c1 != *c2)
1196                         return false;
1197         }
1198         return true;
1199 }
1200
1201 static bool pp_tokens_equal(const token_t *token1, const token_t *token2)
1202 {
1203         if (token1->kind != token2->kind)
1204                 return false;
1205
1206         switch (token1->kind) {
1207         case T_IDENTIFIER:
1208                 return token1->base.symbol == token2->base.symbol;
1209
1210         case T_NUMBER:
1211         case T_CHARACTER_CONSTANT:
1212         case T_STRING_LITERAL:
1213                 return strings_equal(&token1->literal.string, &token2->literal.string);
1214
1215         default:
1216                 return true;
1217         }
1218 }
1219
1220 static bool pp_definitions_equal(const pp_definition_t *definition1,
1221                                  const pp_definition_t *definition2)
1222 {
1223         if (definition1->list_len != definition2->list_len)
1224                 return false;
1225
1226         size_t         len = definition1->list_len;
1227         const token_t *t1  = definition1->token_list;
1228         const token_t *t2  = definition2->token_list;
1229         for (size_t i = 0; i < len; ++i, ++t1, ++t2) {
1230                 if (!pp_tokens_equal(t1, t2))
1231                         return false;
1232         }
1233         return true;
1234 }
1235
1236 static void parse_define_directive(void)
1237 {
1238         eat_pp(TP_define);
1239         if (skip_mode) {
1240                 eat_pp_directive();
1241                 return;
1242         }
1243
1244         assert(obstack_object_size(&pp_obstack) == 0);
1245
1246         if (pp_token.kind != T_IDENTIFIER || info.at_line_begin) {
1247                 errorf(&pp_token.base.source_position,
1248                        "expected identifier after #define, got %K", &pp_token);
1249                 goto error_out;
1250         }
1251         symbol_t *const symbol = pp_token.base.symbol;
1252
1253         pp_definition_t *new_definition
1254                 = obstack_alloc(&pp_obstack, sizeof(new_definition[0]));
1255         memset(new_definition, 0, sizeof(new_definition[0]));
1256         new_definition->source_position = input.position;
1257
1258         /* this is probably the only place where spaces are significant in the
1259          * lexer (except for the fact that they separate tokens). #define b(x)
1260          * is something else than #define b (x) */
1261         if (input.c == '(') {
1262                 eat_token(T_IDENTIFIER);
1263                 eat_token('(');
1264
1265                 while (true) {
1266                         switch (pp_token.kind) {
1267                         case T_DOTDOTDOT:
1268                                 new_definition->is_variadic = true;
1269                                 eat_token(T_DOTDOTDOT);
1270                                 if (pp_token.kind != ')') {
1271                                         errorf(&input.position,
1272                                                         "'...' not at end of macro argument list");
1273                                         goto error_out;
1274                                 }
1275                                 break;
1276
1277                         case T_IDENTIFIER:
1278                                 obstack_ptr_grow(&pp_obstack, pp_token.base.symbol);
1279                                 eat_token(T_IDENTIFIER);
1280
1281                                 if (pp_token.kind == ',') {
1282                                         eat_token(',');
1283                                         break;
1284                                 }
1285
1286                                 if (pp_token.kind != ')') {
1287                                         errorf(&pp_token.base.source_position,
1288                                                "expected ',' or ')' after identifier, got %K",
1289                                                &pp_token);
1290                                         goto error_out;
1291                                 }
1292                                 break;
1293
1294                         case ')':
1295                                 eat_token(')');
1296                                 goto finish_argument_list;
1297
1298                         default:
1299                                 errorf(&pp_token.base.source_position,
1300                                        "expected identifier, '...' or ')' in #define argument list, got %K",
1301                                        &pp_token);
1302                                 goto error_out;
1303                         }
1304                 }
1305
1306         finish_argument_list:
1307                 new_definition->has_parameters = true;
1308                 new_definition->n_parameters
1309                         = obstack_object_size(&pp_obstack) / sizeof(new_definition->parameters[0]);
1310                 new_definition->parameters = obstack_finish(&pp_obstack);
1311         } else {
1312                 eat_token(T_IDENTIFIER);
1313         }
1314
1315         /* construct a new pp_definition on the obstack */
1316         assert(obstack_object_size(&pp_obstack) == 0);
1317         size_t list_len = 0;
1318         while (!info.at_line_begin) {
1319                 obstack_grow(&pp_obstack, &pp_token, sizeof(pp_token));
1320                 ++list_len;
1321                 next_preprocessing_token();
1322         }
1323
1324         new_definition->list_len   = list_len;
1325         new_definition->token_list = obstack_finish(&pp_obstack);
1326
1327         pp_definition_t *old_definition = symbol->pp_definition;
1328         if (old_definition != NULL) {
1329                 if (!pp_definitions_equal(old_definition, new_definition)) {
1330                         warningf(WARN_OTHER, &input.position, "multiple definition of macro '%Y' (first defined %P)", symbol, &old_definition->source_position);
1331                 } else {
1332                         /* reuse the old definition */
1333                         obstack_free(&pp_obstack, new_definition);
1334                         new_definition = old_definition;
1335                 }
1336         }
1337
1338         symbol->pp_definition = new_definition;
1339         return;
1340
1341 error_out:
1342         if (obstack_object_size(&pp_obstack) > 0) {
1343                 char *ptr = obstack_finish(&pp_obstack);
1344                 obstack_free(&pp_obstack, ptr);
1345         }
1346         eat_pp_directive();
1347 }
1348
1349 static void parse_undef_directive(void)
1350 {
1351         eat_pp(TP_undef);
1352         if (skip_mode) {
1353                 eat_pp_directive();
1354                 return;
1355         }
1356
1357         if (pp_token.kind != T_IDENTIFIER) {
1358                 errorf(&input.position,
1359                        "expected identifier after #undef, got %K", &pp_token);
1360                 eat_pp_directive();
1361                 return;
1362         }
1363
1364         pp_token.base.symbol->pp_definition = NULL;
1365         eat_token(T_IDENTIFIER);
1366
1367         if (!info.at_line_begin) {
1368                 warningf(WARN_OTHER, &input.position, "extra tokens at end of #undef directive");
1369         }
1370         eat_pp_directive();
1371 }
1372
1373 /** behind an #include we can have the special headername lexems.
1374  * They're only allowed behind an #include so they're not recognized
1375  * by the normal next_preprocessing_token. We handle them as a special
1376  * exception here */
1377 static void parse_headername(void)
1378 {
1379         const source_position_t start_position = input.position;
1380         string_t                string         = { NULL, 0, STRING_ENCODING_CHAR };
1381         assert(obstack_object_size(&symbol_obstack) == 0);
1382
1383         if (info.at_line_begin) {
1384                 parse_error("expected headername after #include");
1385                 goto finish_error;
1386         }
1387
1388         /* check wether we have a "... or <... headername */
1389         switch (input.c) {
1390         {
1391                 utf32 delimiter;
1392         case '<': delimiter = '>'; goto parse_name;
1393         case '"': delimiter = '"'; goto parse_name;
1394 parse_name:
1395                 next_char();
1396                 while (true) {
1397                         switch (input.c) {
1398                         case NEWLINE:
1399                         case EOF:
1400                                 errorf(&pp_token.base.source_position, "header name without closing '%c'", (char)delimiter);
1401                                 goto finish_error;
1402
1403                         default:
1404                                 if (input.c == delimiter) {
1405                                         next_char();
1406                                         goto finished_headername;
1407                                 } else {
1408                                         obstack_1grow(&symbol_obstack, (char)input.c);
1409                                         next_char();
1410                                 }
1411                                 break;
1412                         }
1413                 }
1414                 /* we should never be here */
1415         }
1416
1417         default:
1418                 /* TODO: do normal pp_token parsing and concatenate results */
1419                 panic("pp_token concat include not implemented yet");
1420         }
1421
1422 finished_headername:
1423         string = sym_make_string(STRING_ENCODING_CHAR);
1424
1425 finish_error:
1426         pp_token.base.source_position = start_position;
1427         pp_token.kind                 = T_HEADERNAME;
1428         pp_token.literal.string       = string;
1429 }
1430
1431 static bool do_include(bool system_include, const char *headername)
1432 {
1433         size_t headername_len = strlen(headername);
1434         if (!system_include) {
1435                 /* put dirname of current input on obstack */
1436                 const char *filename   = input.position.input_name;
1437                 const char *last_slash = strrchr(filename, '/');
1438                 if (last_slash != NULL) {
1439                         size_t len = last_slash - filename;
1440                         obstack_grow(&symbol_obstack, filename, len + 1);
1441                         obstack_grow0(&symbol_obstack, headername, headername_len);
1442                         char *complete_path = obstack_finish(&symbol_obstack);
1443                         headername = identify_string(complete_path);
1444                 }
1445
1446                 FILE *file = fopen(headername, "r");
1447                 if (file != NULL) {
1448                         switch_input(file, headername);
1449                         return true;
1450                 }
1451         }
1452
1453         assert(obstack_object_size(&symbol_obstack) == 0);
1454         /* check searchpath */
1455         for (searchpath_entry_t *entry = searchpath; entry != NULL;
1456              entry = entry->next) {
1457             const char *path = entry->path;
1458             size_t      len  = strlen(path);
1459                 obstack_grow(&symbol_obstack, path, len);
1460                 if (path[len-1] != '/')
1461                         obstack_1grow(&symbol_obstack, '/');
1462                 obstack_grow(&symbol_obstack, headername, headername_len+1);
1463
1464                 char *complete_path = obstack_finish(&symbol_obstack);
1465                 FILE *file          = fopen(complete_path, "r");
1466                 if (file != NULL) {
1467                         const char *filename = identify_string(complete_path);
1468                         switch_input(file, filename);
1469                         return true;
1470                 } else {
1471                         obstack_free(&symbol_obstack, complete_path);
1472                 }
1473         }
1474
1475         return false;
1476 }
1477
1478 /* read till next newline character, only for parse_include_directive(),
1479  * use eat_pp_directive() in all other cases */
1480 static void skip_till_newline(void)
1481 {
1482         /* skip till newline */
1483         while (true) {
1484                 switch (input.c) {
1485                 case NEWLINE:
1486                 case EOF:
1487                         return;
1488                 }
1489                 next_char();
1490         }
1491 }
1492
1493 static void parse_include_directive(void)
1494 {
1495         if (skip_mode) {
1496                 eat_pp_directive();
1497                 return;
1498         }
1499
1500         /* don't eat the TP_include here!
1501          * we need an alternative parsing for the next token */
1502         skip_whitespace();
1503         bool system_include = input.c == '<';
1504         parse_headername();
1505         string_t headername = pp_token.literal.string;
1506         if (headername.begin == NULL) {
1507                 eat_pp_directive();
1508                 return;
1509         }
1510
1511         skip_whitespace();
1512         if (!info.at_line_begin) {
1513                 warningf(WARN_OTHER, &pp_token.base.source_position,
1514                          "extra tokens at end of #include directive");
1515                 skip_till_newline();
1516         }
1517
1518         if (n_inputs > INCLUDE_LIMIT) {
1519                 errorf(&pp_token.base.source_position, "#include nested too deeply");
1520                 /* eat \n or EOF */
1521                 next_preprocessing_token();
1522                 return;
1523         }
1524
1525         /* switch inputs */
1526         emit_newlines();
1527         push_input();
1528         bool res = do_include(system_include, pp_token.literal.string.begin);
1529         if (!res) {
1530                 errorf(&pp_token.base.source_position, "failed including '%S': %s", &pp_token.literal, strerror(errno));
1531                 pop_restore_input();
1532         }
1533 }
1534
1535 static pp_conditional_t *push_conditional(void)
1536 {
1537         pp_conditional_t *conditional
1538                 = obstack_alloc(&pp_obstack, sizeof(*conditional));
1539         memset(conditional, 0, sizeof(*conditional));
1540
1541         conditional->parent = conditional_stack;
1542         conditional_stack   = conditional;
1543
1544         return conditional;
1545 }
1546
1547 static void pop_conditional(void)
1548 {
1549         assert(conditional_stack != NULL);
1550         conditional_stack = conditional_stack->parent;
1551 }
1552
1553 static void check_unclosed_conditionals(void)
1554 {
1555         while (conditional_stack != NULL) {
1556                 pp_conditional_t *conditional = conditional_stack;
1557
1558                 if (conditional->in_else) {
1559                         errorf(&conditional->source_position, "unterminated #else");
1560                 } else {
1561                         errorf(&conditional->source_position, "unterminated condition");
1562                 }
1563                 pop_conditional();
1564         }
1565 }
1566
1567 static void parse_ifdef_ifndef_directive(bool const is_ifdef)
1568 {
1569         bool condition;
1570         eat_pp(is_ifdef ? TP_ifdef : TP_ifndef);
1571
1572         if (skip_mode) {
1573                 eat_pp_directive();
1574                 pp_conditional_t *conditional = push_conditional();
1575                 conditional->source_position  = pp_token.base.source_position;
1576                 conditional->skip             = true;
1577                 return;
1578         }
1579
1580         if (pp_token.kind != T_IDENTIFIER || info.at_line_begin) {
1581                 errorf(&pp_token.base.source_position,
1582                        "expected identifier after #%s, got %K",
1583                        is_ifdef ? "ifdef" : "ifndef", &pp_token);
1584                 eat_pp_directive();
1585
1586                 /* just take the true case in the hope to avoid further errors */
1587                 condition = true;
1588         } else {
1589                 /* evaluate wether we are in true or false case */
1590                 condition = (bool)pp_token.base.symbol->pp_definition == is_ifdef;
1591                 eat_token(T_IDENTIFIER);
1592
1593                 if (!info.at_line_begin) {
1594                         errorf(&pp_token.base.source_position,
1595                                "extra tokens at end of #%s",
1596                                is_ifdef ? "ifdef" : "ifndef");
1597                         eat_pp_directive();
1598                 }
1599         }
1600
1601         pp_conditional_t *conditional = push_conditional();
1602         conditional->source_position  = pp_token.base.source_position;
1603         conditional->condition        = condition;
1604
1605         if (!condition) {
1606                 skip_mode = true;
1607         }
1608 }
1609
1610 static void parse_else_directive(void)
1611 {
1612         eat_pp(TP_else);
1613
1614         if (!info.at_line_begin) {
1615                 if (!skip_mode) {
1616                         warningf(WARN_OTHER, &pp_token.base.source_position, "extra tokens at end of #else");
1617                 }
1618                 eat_pp_directive();
1619         }
1620
1621         pp_conditional_t *conditional = conditional_stack;
1622         if (conditional == NULL) {
1623                 errorf(&pp_token.base.source_position, "#else without prior #if");
1624                 return;
1625         }
1626
1627         if (conditional->in_else) {
1628                 errorf(&pp_token.base.source_position,
1629                        "#else after #else (condition started %P)",
1630                        &conditional->source_position);
1631                 skip_mode = true;
1632                 return;
1633         }
1634
1635         conditional->in_else = true;
1636         if (!conditional->skip) {
1637                 skip_mode = conditional->condition;
1638         }
1639         conditional->source_position = pp_token.base.source_position;
1640 }
1641
1642 static void parse_endif_directive(void)
1643 {
1644         eat_pp(TP_endif);
1645
1646         if (!info.at_line_begin) {
1647                 if (!skip_mode) {
1648                         warningf(WARN_OTHER, &pp_token.base.source_position, "extra tokens at end of #endif");
1649                 }
1650                 eat_pp_directive();
1651         }
1652
1653         pp_conditional_t *conditional = conditional_stack;
1654         if (conditional == NULL) {
1655                 errorf(&pp_token.base.source_position, "#endif without prior #if");
1656                 return;
1657         }
1658
1659         if (!conditional->skip) {
1660                 skip_mode = false;
1661         }
1662         pop_conditional();
1663 }
1664
1665 static void parse_preprocessing_directive(void)
1666 {
1667         eat_token('#');
1668
1669         if (info.at_line_begin) {
1670                 /* empty directive */
1671                 return;
1672         }
1673
1674         if (pp_token.base.symbol) {
1675                 switch (pp_token.base.symbol->pp_ID) {
1676                 case TP_define:  parse_define_directive();            break;
1677                 case TP_else:    parse_else_directive();              break;
1678                 case TP_endif:   parse_endif_directive();             break;
1679                 case TP_ifdef:   parse_ifdef_ifndef_directive(true);  break;
1680                 case TP_ifndef:  parse_ifdef_ifndef_directive(false); break;
1681                 case TP_include: parse_include_directive();           break;
1682                 case TP_undef:   parse_undef_directive();             break;
1683                 default:         goto skip;
1684                 }
1685         } else {
1686 skip:
1687                 if (!skip_mode) {
1688                         errorf(&pp_token.base.source_position, "invalid preprocessing directive #%K", &pp_token);
1689                 }
1690                 eat_pp_directive();
1691         }
1692
1693         assert(info.at_line_begin);
1694 }
1695
1696 static void prepend_include_path(const char *path)
1697 {
1698         searchpath_entry_t *entry = OALLOCZ(&config_obstack, searchpath_entry_t);
1699         entry->path = path;
1700         entry->next = searchpath;
1701         searchpath  = entry;
1702 }
1703
1704 static void setup_include_path(void)
1705 {
1706         /* built-in paths */
1707         prepend_include_path("/usr/include");
1708
1709         /* parse environment variable */
1710         const char *cpath = getenv("CPATH");
1711         if (cpath != NULL && *cpath != '\0') {
1712                 const char *begin = cpath;
1713                 const char *c;
1714                 do {
1715                         c = begin;
1716                         while (*c != '\0' && *c != ':')
1717                                 ++c;
1718
1719                         size_t len = c-begin;
1720                         if (len == 0) {
1721                                 /* for gcc compatibility (Matze: I would expect that
1722                                  * nothing happens for an empty entry...) */
1723                                 prepend_include_path(".");
1724                         } else {
1725                                 char *string = obstack_alloc(&config_obstack, len+1);
1726                                 memcpy(string, begin, len);
1727                                 string[len] = '\0';
1728
1729                                 prepend_include_path(string);
1730                         }
1731
1732                         begin = c+1;
1733                         /* skip : */
1734                         if (*begin == ':')
1735                                 ++begin;
1736                 } while(*c != '\0');
1737         }
1738 }
1739
1740 int pptest_main(int argc, char **argv);
1741 int pptest_main(int argc, char **argv)
1742 {
1743         init_symbol_table();
1744         init_tokens();
1745
1746         obstack_init(&config_obstack);
1747         obstack_init(&pp_obstack);
1748         obstack_init(&input_obstack);
1749         strset_init(&stringset);
1750
1751         error_on_unknown_chars = false;
1752
1753         setup_include_path();
1754
1755         /* simplistic commandline parser */
1756         const char *filename = NULL;
1757         const char *output = NULL;
1758         for (int i = 1; i < argc; ++i) {
1759                 const char *opt = argv[i];
1760                 if (streq(opt, "-I")) {
1761                         prepend_include_path(argv[++i]);
1762                         continue;
1763                 } else if (streq(opt, "-E")) {
1764                         /* ignore */
1765                 } else if (streq(opt, "-o")) {
1766                         output = argv[++i];
1767                         continue;
1768                 } else if (opt[0] == '-') {
1769                         fprintf(stderr, "Unknown option '%s'\n", opt);
1770                 } else {
1771                         if (filename != NULL)
1772                                 fprintf(stderr, "Multiple inputs not supported\n");
1773                         filename = argv[i];
1774                 }
1775         }
1776         if (filename == NULL) {
1777                 fprintf(stderr, "No input specified\n");
1778                 return 1;
1779         }
1780
1781         if (output == NULL) {
1782                 out = stdout;
1783         } else {
1784                 out = fopen(output, "w");
1785                 if (out == NULL) {
1786                         fprintf(stderr, "Couldn't open output '%s'\n", output);
1787                         return 1;
1788                 }
1789         }
1790
1791         /* just here for gcc compatibility */
1792         fprintf(out, "# 1 \"%s\"\n", filename);
1793         fprintf(out, "# 1 \"<built-in>\"\n");
1794         fprintf(out, "# 1 \"<command-line>\"\n");
1795
1796         FILE *file = fopen(filename, "r");
1797         if (file == NULL) {
1798                 fprintf(stderr, "Couldn't open input '%s'\n", filename);
1799                 return 1;
1800         }
1801         switch_input(file, filename);
1802
1803         while (true) {
1804                 if (pp_token.kind == '#' && info.at_line_begin) {
1805                         parse_preprocessing_directive();
1806                         continue;
1807                 } else if (pp_token.kind == T_EOF) {
1808                         goto end_of_main_loop;
1809                 } else if (pp_token.kind == T_IDENTIFIER) {
1810                         symbol_t        *const symbol        = pp_token.base.symbol;
1811                         pp_definition_t *const pp_definition = symbol->pp_definition;
1812                         if (pp_definition != NULL && !pp_definition->is_expanding) {
1813                                 expansion_pos = pp_token.base.source_position;
1814                                 if (pp_definition->has_parameters) {
1815                                         source_position_t position = pp_token.base.source_position;
1816                                         add_token_info_t old_info = info;
1817                                         eat_token(T_IDENTIFIER);
1818                                         add_token_info_t new_info = info;
1819
1820                                         /* no opening brace -> no expansion */
1821                                         if (pp_token.kind == '(') {
1822                                                 eat_token('(');
1823
1824                                                 /* parse arguments (TODO) */
1825                                                 while (pp_token.kind != T_EOF && pp_token.kind != ')')
1826                                                         next_preprocessing_token();
1827                                         } else {
1828                                                 token_t next_token = pp_token;
1829                                                 /* restore identifier token */
1830                                                 pp_token.kind                 = T_IDENTIFIER;
1831                                                 pp_token.base.symbol          = symbol;
1832                                                 pp_token.base.source_position = position;
1833                                                 info = old_info;
1834                                                 emit_pp_token();
1835
1836                                                 info = new_info;
1837                                                 pp_token = next_token;
1838                                                 continue;
1839                                         }
1840                                         info = old_info;
1841                                 }
1842                                 pp_definition->expand_pos   = 0;
1843                                 pp_definition->is_expanding = true;
1844                                 current_expansion           = pp_definition;
1845                                 expand_next();
1846                                 continue;
1847                         }
1848                 }
1849
1850                 emit_pp_token();
1851                 next_preprocessing_token();
1852         }
1853 end_of_main_loop:
1854
1855         fputc('\n', out);
1856         check_unclosed_conditionals();
1857         close_input();
1858         if (out != stdout)
1859                 fclose(out);
1860
1861         obstack_free(&input_obstack, NULL);
1862         obstack_free(&pp_obstack, NULL);
1863         obstack_free(&config_obstack, NULL);
1864
1865         strset_destroy(&stringset);
1866
1867         exit_tokens();
1868         exit_symbol_table();
1869
1870         return 0;
1871 }