Augment MATCH_NEWLINE() in the preprocessor so its usage looks like an ordinary case...
[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              ignore_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 preprocessor_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 make_string(char *string, size_t len)
455 {
456         const char *result = identify_string(string);
457         return (string_t) {result, len};
458 }
459
460 static void parse_string(utf32 const delimiter, preprocessor_token_kind_t const kind, string_encoding_t const enc, char const *const context)
461 {
462         const unsigned start_linenr = input.position.lineno;
463
464         eat(delimiter);
465
466         while (true) {
467                 switch (input.c) {
468                 case '\\': {
469                         if (resolve_escape_sequences) {
470                                 utf32 const tc = parse_escape_sequence();
471                                 if (enc == STRING_ENCODING_CHAR) {
472                                         if (tc >= 0x100) {
473                                                 warningf(WARN_OTHER, &pp_token.base.source_position, "escape sequence out of range");
474                                         }
475                                         obstack_1grow(&symbol_obstack, tc);
476                                 } else {
477                                         obstack_grow_symbol(&symbol_obstack, tc);
478                                 }
479                         } else {
480                                 obstack_1grow(&symbol_obstack, (char)input.c);
481                                 next_char();
482                                 obstack_1grow(&symbol_obstack, (char)input.c);
483                                 next_char();
484                         }
485                         break;
486                 }
487
488                 case NEWLINE:
489                         errorf(&pp_token.base.source_position, "newline while parsing %s", context);
490                         break;
491
492                 case EOF: {
493                         source_position_t source_position;
494                         source_position.input_name = pp_token.base.source_position.input_name;
495                         source_position.lineno     = start_linenr;
496                         errorf(&source_position, "EOF while parsing %s", context);
497                         goto end_of_string;
498                 }
499
500                 default:
501                         if (input.c == delimiter) {
502                                 next_char();
503                                 goto end_of_string;
504                         } else {
505                                 obstack_grow_symbol(&symbol_obstack, input.c);
506                                 next_char();
507                                 break;
508                         }
509                 }
510         }
511
512 end_of_string:;
513         obstack_1grow(&symbol_obstack, '\0');
514         size_t const size   = obstack_object_size(&symbol_obstack) - 1;
515         char  *const string = obstack_finish(&symbol_obstack);
516
517         pp_token.kind            = kind;
518         pp_token.string.encoding = enc;
519         pp_token.string.string   = make_string(string, size);
520 }
521
522 static void parse_string_literal(string_encoding_t const enc)
523 {
524         parse_string('"', TP_STRING_LITERAL, enc, "string literal");
525 }
526
527 static void parse_character_constant(string_encoding_t const enc)
528 {
529         parse_string('\'', TP_CHARACTER_CONSTANT, enc, "character constant");
530         if (pp_token.string.string.size == 0) {
531                 parse_error("empty character constant");
532         }
533 }
534
535 #define SYMBOL_CHARS_WITHOUT_E_P \
536         case '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_CHARS \
587         SYMBOL_CHARS_WITHOUT_E_P \
588         case 'e': \
589         case 'p': \
590         case 'E': \
591         case 'P':
592
593 #define DIGITS \
594         case '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 != TP_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 void eat_pp(preprocessor_token_kind_t const type)
744 {
745         (void) type;
746         assert(pp_token.kind == type);
747         next_preprocessing_token();
748 }
749
750 static void parse_symbol(void)
751 {
752         obstack_1grow(&symbol_obstack, (char) input.c);
753         next_char();
754
755         while (true) {
756                 switch (input.c) {
757                 DIGITS
758                 SYMBOL_CHARS
759                         obstack_1grow(&symbol_obstack, (char) input.c);
760                         next_char();
761                         break;
762
763                 default:
764                         goto end_symbol;
765                 }
766         }
767
768 end_symbol:
769         obstack_1grow(&symbol_obstack, '\0');
770         char *string = obstack_finish(&symbol_obstack);
771
772         /* might be a wide string or character constant ( L"string"/L'c' ) */
773         if (input.c == '"' && string[0] == 'L' && string[1] == '\0') {
774                 obstack_free(&symbol_obstack, string);
775                 parse_string_literal(STRING_ENCODING_WIDE);
776                 return;
777         } else if (input.c == '\'' && string[0] == 'L' && string[1] == '\0') {
778                 obstack_free(&symbol_obstack, string);
779                 parse_character_constant(STRING_ENCODING_WIDE);
780                 return;
781         }
782
783         symbol_t *symbol = symbol_table_insert(string);
784
785         pp_token.kind        = symbol->pp_ID;
786         pp_token.base.symbol = symbol;
787
788         /* we can free the memory from symbol obstack if we already had an entry in
789          * the symbol table */
790         if (symbol->string != string) {
791                 obstack_free(&symbol_obstack, string);
792         }
793 }
794
795 static void parse_number(void)
796 {
797         obstack_1grow(&symbol_obstack, (char) input.c);
798         next_char();
799
800         while (true) {
801                 switch (input.c) {
802                 case '.':
803                 DIGITS
804                 SYMBOL_CHARS_WITHOUT_E_P
805                         obstack_1grow(&symbol_obstack, (char) input.c);
806                         next_char();
807                         break;
808
809                 case 'e':
810                 case 'p':
811                 case 'E':
812                 case 'P':
813                         obstack_1grow(&symbol_obstack, (char) input.c);
814                         next_char();
815                         if (input.c == '+' || input.c == '-') {
816                                 obstack_1grow(&symbol_obstack, (char) input.c);
817                                 next_char();
818                         }
819                         break;
820
821                 default:
822                         goto end_number;
823                 }
824         }
825
826 end_number:
827         obstack_1grow(&symbol_obstack, '\0');
828         size_t  size   = obstack_object_size(&symbol_obstack);
829         char   *string = obstack_finish(&symbol_obstack);
830
831         pp_token.kind          = TP_NUMBER;
832         pp_token.number.number = make_string(string, size);
833 }
834
835
836 #define MAYBE_PROLOG                                       \
837                         next_char();                                   \
838                         while (true) {                                 \
839                                 switch (input.c) {
840
841 #define MAYBE(ch, set_type)                                \
842                                 case ch:                                   \
843                                         next_char();                           \
844                                         pp_token.kind = set_type;              \
845                                         return;
846
847 #define ELSE_CODE(code)                                    \
848                                 default:                                   \
849                                         code                                   \
850                                         return;                                \
851                                 }                                          \
852                         }
853
854 #define ELSE(set_type)                                     \
855                 ELSE_CODE(                                         \
856                         pp_token.kind = set_type;                      \
857                 )
858
859 static void next_preprocessing_token(void)
860 {
861         if (current_expansion != NULL) {
862                 expand_next();
863                 return;
864         }
865
866         info.at_line_begin  = false;
867         info.had_whitespace = false;
868 restart:
869         pp_token.base.source_position = input.position;
870         pp_token.base.symbol          = NULL;
871
872         switch (input.c) {
873         case ' ':
874         case '\t':
875                 ++info.whitespace;
876                 info.had_whitespace = true;
877                 next_char();
878                 goto restart;
879
880         case NEWLINE:
881                 info.at_line_begin = true;
882                 info.had_whitespace = true;
883                 goto restart;
884
885         SYMBOL_CHARS
886                 parse_symbol();
887                 return;
888
889         DIGITS
890                 parse_number();
891                 return;
892
893         case '"':
894                 parse_string_literal(STRING_ENCODING_CHAR);
895                 return;
896
897         case '\'':
898                 parse_character_constant(STRING_ENCODING_CHAR);
899                 return;
900
901         case '.':
902                 MAYBE_PROLOG
903                         case '0':
904                         case '1':
905                         case '2':
906                         case '3':
907                         case '4':
908                         case '5':
909                         case '6':
910                         case '7':
911                         case '8':
912                         case '9':
913                                 put_back(input.c);
914                                 input.c = '.';
915                                 parse_number();
916                                 return;
917
918                         case '.':
919                                 MAYBE_PROLOG
920                                 MAYBE('.', TP_DOTDOTDOT)
921                                 ELSE_CODE(
922                                         put_back(input.c);
923                                         input.c = '.';
924                                         pp_token.kind = '.';
925                                 )
926                 ELSE('.')
927         case '&':
928                 MAYBE_PROLOG
929                 MAYBE('&', TP_ANDAND)
930                 MAYBE('=', TP_ANDEQUAL)
931                 ELSE('&')
932         case '*':
933                 MAYBE_PROLOG
934                 MAYBE('=', TP_ASTERISKEQUAL)
935                 ELSE('*')
936         case '+':
937                 MAYBE_PROLOG
938                 MAYBE('+', TP_PLUSPLUS)
939                 MAYBE('=', TP_PLUSEQUAL)
940                 ELSE('+')
941         case '-':
942                 MAYBE_PROLOG
943                 MAYBE('>', TP_MINUSGREATER)
944                 MAYBE('-', TP_MINUSMINUS)
945                 MAYBE('=', TP_MINUSEQUAL)
946                 ELSE('-')
947         case '!':
948                 MAYBE_PROLOG
949                 MAYBE('=', TP_EXCLAMATIONMARKEQUAL)
950                 ELSE('!')
951         case '/':
952                 MAYBE_PROLOG
953                 MAYBE('=', TP_SLASHEQUAL)
954                         case '*':
955                                 next_char();
956                                 info.had_whitespace = true;
957                                 skip_multiline_comment();
958                                 goto restart;
959                         case '/':
960                                 next_char();
961                                 info.had_whitespace = true;
962                                 skip_line_comment();
963                                 goto restart;
964                 ELSE('/')
965         case '%':
966                 MAYBE_PROLOG
967                 MAYBE('>', '}')
968                 MAYBE('=', TP_PERCENTEQUAL)
969                         case ':':
970                                 MAYBE_PROLOG
971                                         case '%':
972                                                 MAYBE_PROLOG
973                                                 MAYBE(':', TP_HASHHASH)
974                                                 ELSE_CODE(
975                                                         put_back(input.c);
976                                                         input.c = '%';
977                                                         pp_token.kind = '#';
978                                                 )
979                                 ELSE('#')
980                 ELSE('%')
981         case '<':
982                 MAYBE_PROLOG
983                 MAYBE(':', '[')
984                 MAYBE('%', '{')
985                 MAYBE('=', TP_LESSEQUAL)
986                         case '<':
987                                 MAYBE_PROLOG
988                                 MAYBE('=', TP_LESSLESSEQUAL)
989                                 ELSE(TP_LESSLESS)
990                 ELSE('<')
991         case '>':
992                 MAYBE_PROLOG
993                 MAYBE('=', TP_GREATEREQUAL)
994                         case '>':
995                                 MAYBE_PROLOG
996                                 MAYBE('=', TP_GREATERGREATEREQUAL)
997                                 ELSE(TP_GREATERGREATER)
998                 ELSE('>')
999         case '^':
1000                 MAYBE_PROLOG
1001                 MAYBE('=', TP_CARETEQUAL)
1002                 ELSE('^')
1003         case '|':
1004                 MAYBE_PROLOG
1005                 MAYBE('=', TP_PIPEEQUAL)
1006                 MAYBE('|', TP_PIPEPIPE)
1007                 ELSE('|')
1008         case ':':
1009                 MAYBE_PROLOG
1010                 MAYBE('>', ']')
1011                 ELSE(':')
1012         case '=':
1013                 MAYBE_PROLOG
1014                 MAYBE('=', TP_EQUALEQUAL)
1015                 ELSE('=')
1016         case '#':
1017                 MAYBE_PROLOG
1018                 MAYBE('#', TP_HASHHASH)
1019                 ELSE_CODE(
1020                         pp_token.kind = '#';
1021                 )
1022
1023         case '?':
1024         case '[':
1025         case ']':
1026         case '(':
1027         case ')':
1028         case '{':
1029         case '}':
1030         case '~':
1031         case ';':
1032         case ',':
1033         case '\\':
1034                 pp_token.kind = input.c;
1035                 next_char();
1036                 return;
1037
1038         case EOF:
1039                 if (input_stack != NULL) {
1040                         close_input();
1041                         pop_restore_input();
1042                         fputc('\n', out);
1043                         print_line_directive(&input.position, "2");
1044                         goto restart;
1045                 } else {
1046                         pp_token.base.source_position.lineno++;
1047                         info.at_line_begin = true;
1048                         pp_token.kind = TP_EOF;
1049                 }
1050                 return;
1051
1052         default:
1053                 next_char();
1054                 if (!ignore_unknown_chars) {
1055                         errorf(&pp_token.base.source_position,
1056                                "unknown character '%c' found\n", input.c);
1057                         goto restart;
1058                 } else {
1059                         pp_token.kind = input.c;
1060                         return;
1061                 }
1062         }
1063 }
1064
1065 static void print_quoted_string(const char *const string)
1066 {
1067         fputc('"', out);
1068         for (const char *c = string; *c != 0; ++c) {
1069                 switch (*c) {
1070                 case '"': fputs("\\\"", out); break;
1071                 case '\\':  fputs("\\\\", out); break;
1072                 case '\a':  fputs("\\a", out); break;
1073                 case '\b':  fputs("\\b", out); break;
1074                 case '\f':  fputs("\\f", out); break;
1075                 case '\n':  fputs("\\n", out); break;
1076                 case '\r':  fputs("\\r", out); break;
1077                 case '\t':  fputs("\\t", out); break;
1078                 case '\v':  fputs("\\v", out); break;
1079                 case '\?':  fputs("\\?", out); break;
1080                 default:
1081                         if (!isprint(*c)) {
1082                                 fprintf(out, "\\%03o", (unsigned)*c);
1083                                 break;
1084                         }
1085                         fputc(*c, out);
1086                         break;
1087                 }
1088         }
1089         fputc('"', out);
1090 }
1091
1092 static void print_line_directive(const source_position_t *pos, const char *add)
1093 {
1094         fprintf(out, "# %u ", pos->lineno);
1095         print_quoted_string(pos->input_name);
1096         if (add != NULL) {
1097                 fputc(' ', out);
1098                 fputs(add, out);
1099         }
1100
1101         printed_input_name = pos->input_name;
1102         input.output_line  = pos->lineno-1;
1103 }
1104
1105 static bool emit_newlines(void)
1106 {
1107         unsigned delta = pp_token.base.source_position.lineno - input.output_line;
1108         if (delta == 0)
1109                 return false;
1110
1111         if (delta >= 9) {
1112                 fputc('\n', out);
1113                 print_line_directive(&pp_token.base.source_position, NULL);
1114                 fputc('\n', out);
1115         } else {
1116                 for (unsigned i = 0; i < delta; ++i) {
1117                         fputc('\n', out);
1118                 }
1119         }
1120         input.output_line = pp_token.base.source_position.lineno;
1121
1122         for (unsigned i = 0; i < info.whitespace; ++i)
1123                 fputc(' ', out);
1124
1125         return true;
1126 }
1127
1128 static void emit_pp_token(void)
1129 {
1130         if (skip_mode)
1131                 return;
1132
1133         if (!emit_newlines() &&
1134             (info.had_whitespace || tokens_would_paste(last_token, pp_token.kind)))
1135                 fputc(' ', out);
1136
1137         switch (pp_token.kind) {
1138         case TP_IDENTIFIER:
1139                 fputs(pp_token.base.symbol->string, out);
1140                 break;
1141         case TP_NUMBER:
1142                 fputs(pp_token.number.number.begin, out);
1143                 break;
1144
1145         case TP_STRING_LITERAL:
1146                 fputs(get_string_encoding_prefix(pp_token.string.encoding), out);
1147                 fputc('"', out);
1148                 fputs(pp_token.string.string.begin, out);
1149                 fputc('"', out);
1150                 break;
1151
1152         case TP_CHARACTER_CONSTANT:
1153                 fputs(get_string_encoding_prefix(pp_token.string.encoding), out);
1154                 fputc('\'', out);
1155                 fputs(pp_token.string.string.begin, out);
1156                 fputc('\'', out);
1157                 break;
1158         default:
1159                 print_pp_token_kind(out, pp_token.kind);
1160                 break;
1161         }
1162         last_token = pp_token.kind;
1163 }
1164
1165 static void eat_pp_directive(void)
1166 {
1167         while (!info.at_line_begin) {
1168                 next_preprocessing_token();
1169         }
1170 }
1171
1172 static bool strings_equal(const string_t *string1, const string_t *string2)
1173 {
1174         size_t size = string1->size;
1175         if (size != string2->size)
1176                 return false;
1177
1178         const char *c1 = string1->begin;
1179         const char *c2 = string2->begin;
1180         for (size_t i = 0; i < size; ++i, ++c1, ++c2) {
1181                 if (*c1 != *c2)
1182                         return false;
1183         }
1184         return true;
1185 }
1186
1187 static bool pp_tokens_equal(const token_t *token1, const token_t *token2)
1188 {
1189         if (token1->kind != token2->kind)
1190                 return false;
1191
1192         switch (token1->kind) {
1193         case TP_IDENTIFIER:
1194                 return token1->base.symbol == token2->base.symbol;
1195
1196         case TP_NUMBER:
1197         case TP_CHARACTER_CONSTANT:
1198         case TP_STRING_LITERAL:
1199                 return strings_equal(&token1->string.string, &token2->string.string);
1200
1201         default:
1202                 return true;
1203         }
1204 }
1205
1206 static bool pp_definitions_equal(const pp_definition_t *definition1,
1207                                  const pp_definition_t *definition2)
1208 {
1209         if (definition1->list_len != definition2->list_len)
1210                 return false;
1211
1212         size_t         len = definition1->list_len;
1213         const token_t *t1  = definition1->token_list;
1214         const token_t *t2  = definition2->token_list;
1215         for (size_t i = 0; i < len; ++i, ++t1, ++t2) {
1216                 if (!pp_tokens_equal(t1, t2))
1217                         return false;
1218         }
1219         return true;
1220 }
1221
1222 static void parse_define_directive(void)
1223 {
1224         eat_pp(TP_define);
1225         assert(obstack_object_size(&pp_obstack) == 0);
1226
1227         if (pp_token.kind != TP_IDENTIFIER || info.at_line_begin) {
1228                 errorf(&pp_token.base.source_position,
1229                        "expected identifier after #define, got '%t'", &pp_token);
1230                 goto error_out;
1231         }
1232         symbol_t *const symbol = pp_token.base.symbol;
1233
1234         pp_definition_t *new_definition
1235                 = obstack_alloc(&pp_obstack, sizeof(new_definition[0]));
1236         memset(new_definition, 0, sizeof(new_definition[0]));
1237         new_definition->source_position = input.position;
1238
1239         /* this is probably the only place where spaces are significant in the
1240          * lexer (except for the fact that they separate tokens). #define b(x)
1241          * is something else than #define b (x) */
1242         if (input.c == '(') {
1243                 /* eat the '(' */
1244                 next_preprocessing_token();
1245                 /* get next token after '(' */
1246                 next_preprocessing_token();
1247
1248                 while (true) {
1249                         switch (pp_token.kind) {
1250                         case TP_DOTDOTDOT:
1251                                 new_definition->is_variadic = true;
1252                                 next_preprocessing_token();
1253                                 if (pp_token.kind != ')') {
1254                                         errorf(&input.position,
1255                                                         "'...' not at end of macro argument list");
1256                                         goto error_out;
1257                                 }
1258                                 break;
1259                         case TP_IDENTIFIER:
1260                                 obstack_ptr_grow(&pp_obstack, pp_token.base.symbol);
1261                                 next_preprocessing_token();
1262
1263                                 if (pp_token.kind == ',') {
1264                                         next_preprocessing_token();
1265                                         break;
1266                                 }
1267
1268                                 if (pp_token.kind != ')') {
1269                                         errorf(&pp_token.base.source_position,
1270                                                "expected ',' or ')' after identifier, got '%t'",
1271                                                &pp_token);
1272                                         goto error_out;
1273                                 }
1274                                 break;
1275                         case ')':
1276                                 next_preprocessing_token();
1277                                 goto finish_argument_list;
1278                         default:
1279                                 errorf(&pp_token.base.source_position,
1280                                        "expected identifier, '...' or ')' in #define argument list, got '%t'",
1281                                        &pp_token);
1282                                 goto error_out;
1283                         }
1284                 }
1285
1286         finish_argument_list:
1287                 new_definition->has_parameters = true;
1288                 new_definition->n_parameters
1289                         = obstack_object_size(&pp_obstack) / sizeof(new_definition->parameters[0]);
1290                 new_definition->parameters = obstack_finish(&pp_obstack);
1291         } else {
1292                 next_preprocessing_token();
1293         }
1294
1295         /* construct a new pp_definition on the obstack */
1296         assert(obstack_object_size(&pp_obstack) == 0);
1297         size_t list_len = 0;
1298         while (!info.at_line_begin) {
1299                 obstack_grow(&pp_obstack, &pp_token, sizeof(pp_token));
1300                 ++list_len;
1301                 next_preprocessing_token();
1302         }
1303
1304         new_definition->list_len   = list_len;
1305         new_definition->token_list = obstack_finish(&pp_obstack);
1306
1307         pp_definition_t *old_definition = symbol->pp_definition;
1308         if (old_definition != NULL) {
1309                 if (!pp_definitions_equal(old_definition, new_definition)) {
1310                         warningf(WARN_OTHER, &input.position, "multiple definition of macro '%Y' (first defined %P)", symbol, &old_definition->source_position);
1311                 } else {
1312                         /* reuse the old definition */
1313                         obstack_free(&pp_obstack, new_definition);
1314                         new_definition = old_definition;
1315                 }
1316         }
1317
1318         symbol->pp_definition = new_definition;
1319         return;
1320
1321 error_out:
1322         if (obstack_object_size(&pp_obstack) > 0) {
1323                 char *ptr = obstack_finish(&pp_obstack);
1324                 obstack_free(&pp_obstack, ptr);
1325         }
1326         eat_pp_directive();
1327 }
1328
1329 static void parse_undef_directive(void)
1330 {
1331         eat_pp(TP_undef);
1332
1333         if (pp_token.kind != TP_IDENTIFIER) {
1334                 errorf(&input.position,
1335                        "expected identifier after #undef, got '%t'", &pp_token);
1336                 eat_pp_directive();
1337                 return;
1338         }
1339
1340         pp_token.base.symbol->pp_definition = NULL;
1341         next_preprocessing_token();
1342
1343         if (!info.at_line_begin) {
1344                 warningf(WARN_OTHER, &input.position, "extra tokens at end of #undef directive");
1345         }
1346         eat_pp_directive();
1347 }
1348
1349 static void parse_headername(void)
1350 {
1351         const source_position_t start_position = input.position;
1352         string_t                string         = {NULL, 0};
1353         assert(obstack_object_size(&symbol_obstack) == 0);
1354
1355         /* behind an #include we can have the special headername lexems.
1356          * They're only allowed behind an #include so they're not recognized
1357          * by the normal next_preprocessing_token. We handle them as a special
1358          * exception here */
1359         if (info.at_line_begin) {
1360                 parse_error("expected headername after #include");
1361                 goto finish_error;
1362         }
1363
1364         /* check wether we have a "... or <... headername */
1365         switch (input.c) {
1366         {
1367                 utf32 delimiter;
1368         case '<': delimiter = '>'; goto parse_name;
1369         case '"': delimiter = '"'; goto parse_name;
1370 parse_name:
1371                 next_char();
1372                 while (true) {
1373                         switch (input.c) {
1374                         case NEWLINE:
1375                         case EOF:
1376                                 errorf(&pp_token.base.source_position, "header name without closing '%c'", (char)delimiter);
1377                                 goto finish_error;
1378
1379                         default:
1380                                 if (input.c == delimiter) {
1381                                         next_char();
1382                                         goto finished_headername;
1383                                 } else {
1384                                         obstack_1grow(&symbol_obstack, (char)input.c);
1385                                         next_char();
1386                                 }
1387                                 break;
1388                         }
1389                 }
1390                 /* we should never be here */
1391         }
1392
1393         default:
1394                 /* TODO: do normal pp_token parsing and concatenate results */
1395                 panic("pp_token concat include not implemented yet");
1396         }
1397
1398 finished_headername:
1399         obstack_1grow(&symbol_obstack, '\0');
1400         const size_t size       = (size_t)obstack_object_size(&symbol_obstack);
1401         char *const  headername = obstack_finish(&symbol_obstack);
1402         string                  = make_string(headername, size);
1403
1404 finish_error:
1405         pp_token.base.source_position = start_position;
1406         pp_token.kind                 = TP_HEADERNAME;
1407         pp_token.string.string        = string;
1408 }
1409
1410 static bool do_include(bool system_include, const char *headername)
1411 {
1412         size_t headername_len = strlen(headername);
1413         if (!system_include) {
1414                 /* put dirname of current input on obstack */
1415                 const char *filename   = input.position.input_name;
1416                 const char *last_slash = strrchr(filename, '/');
1417                 if (last_slash != NULL) {
1418                         size_t len = last_slash - filename;
1419                         obstack_grow(&symbol_obstack, filename, len + 1);
1420                         obstack_grow0(&symbol_obstack, headername, headername_len);
1421                         char *complete_path = obstack_finish(&symbol_obstack);
1422                         headername = identify_string(complete_path);
1423                 }
1424
1425                 FILE *file = fopen(headername, "r");
1426                 if (file != NULL) {
1427                         switch_input(file, headername);
1428                         return true;
1429                 }
1430         }
1431
1432         assert(obstack_object_size(&symbol_obstack) == 0);
1433         /* check searchpath */
1434         for (searchpath_entry_t *entry = searchpath; entry != NULL;
1435              entry = entry->next) {
1436             const char *path = entry->path;
1437             size_t      len  = strlen(path);
1438                 obstack_grow(&symbol_obstack, path, len);
1439                 if (path[len-1] != '/')
1440                         obstack_1grow(&symbol_obstack, '/');
1441                 obstack_grow(&symbol_obstack, headername, headername_len+1);
1442
1443                 char *complete_path = obstack_finish(&symbol_obstack);
1444                 FILE *file          = fopen(complete_path, "r");
1445                 if (file != NULL) {
1446                         const char *filename = identify_string(complete_path);
1447                         switch_input(file, filename);
1448                         return true;
1449                 } else {
1450                         obstack_free(&symbol_obstack, complete_path);
1451                 }
1452         }
1453
1454         return false;
1455 }
1456
1457 /* read till next newline character, only for parse_include_directive(),
1458  * use eat_pp_directive() in all other cases */
1459 static void skip_till_newline(void)
1460 {
1461         /* skip till newline */
1462         while (true) {
1463                 switch (input.c) {
1464                 case NEWLINE:
1465                 case EOF:
1466                         return;
1467                 }
1468                 next_char();
1469         }
1470 }
1471
1472 static bool parse_include_directive(void)
1473 {
1474         /* don't eat the TP_include here!
1475          * we need an alternative parsing for the next token */
1476         skip_whitespace();
1477         bool system_include = input.c == '<';
1478         parse_headername();
1479         string_t headername = pp_token.string.string;
1480         if (headername.begin == NULL) {
1481                 eat_pp_directive();
1482                 return false;
1483         }
1484
1485         skip_whitespace();
1486         if (!info.at_line_begin) {
1487                 warningf(WARN_OTHER, &pp_token.base.source_position,
1488                          "extra tokens at end of #include directive");
1489                 skip_till_newline();
1490         }
1491
1492         if (n_inputs > INCLUDE_LIMIT) {
1493                 errorf(&pp_token.base.source_position, "#include nested too deeply");
1494                 /* eat \n or EOF */
1495                 next_preprocessing_token();
1496                 return false;
1497         }
1498
1499         /* switch inputs */
1500         emit_newlines();
1501         push_input();
1502         bool res = do_include(system_include, pp_token.string.string.begin);
1503         if (!res) {
1504                 errorf(&pp_token.base.source_position,
1505                        "failed including '%S': %s", pp_token.string, strerror(errno));
1506                 pop_restore_input();
1507                 return false;
1508         }
1509
1510         return true;
1511 }
1512
1513 static pp_conditional_t *push_conditional(void)
1514 {
1515         pp_conditional_t *conditional
1516                 = obstack_alloc(&pp_obstack, sizeof(*conditional));
1517         memset(conditional, 0, sizeof(*conditional));
1518
1519         conditional->parent = conditional_stack;
1520         conditional_stack   = conditional;
1521
1522         return conditional;
1523 }
1524
1525 static void pop_conditional(void)
1526 {
1527         assert(conditional_stack != NULL);
1528         conditional_stack = conditional_stack->parent;
1529 }
1530
1531 static void check_unclosed_conditionals(void)
1532 {
1533         while (conditional_stack != NULL) {
1534                 pp_conditional_t *conditional = conditional_stack;
1535
1536                 if (conditional->in_else) {
1537                         errorf(&conditional->source_position, "unterminated #else");
1538                 } else {
1539                         errorf(&conditional->source_position, "unterminated condition");
1540                 }
1541                 pop_conditional();
1542         }
1543 }
1544
1545 static void parse_ifdef_ifndef_directive(void)
1546 {
1547         bool is_ifndef = (pp_token.kind == TP_ifndef);
1548         bool condition;
1549         next_preprocessing_token();
1550
1551         if (skip_mode) {
1552                 eat_pp_directive();
1553                 pp_conditional_t *conditional = push_conditional();
1554                 conditional->source_position  = pp_token.base.source_position;
1555                 conditional->skip             = true;
1556                 return;
1557         }
1558
1559         if (pp_token.kind != TP_IDENTIFIER || info.at_line_begin) {
1560                 errorf(&pp_token.base.source_position,
1561                        "expected identifier after #%s, got '%t'",
1562                        is_ifndef ? "ifndef" : "ifdef", &pp_token);
1563                 eat_pp_directive();
1564
1565                 /* just take the true case in the hope to avoid further errors */
1566                 condition = true;
1567         } else {
1568                 /* evaluate wether we are in true or false case */
1569                 condition = !pp_token.base.symbol->pp_definition == is_ifndef;
1570
1571                 next_preprocessing_token();
1572
1573                 if (!info.at_line_begin) {
1574                         errorf(&pp_token.base.source_position,
1575                                "extra tokens at end of #%s",
1576                                is_ifndef ? "ifndef" : "ifdef");
1577                         eat_pp_directive();
1578                 }
1579         }
1580
1581         pp_conditional_t *conditional = push_conditional();
1582         conditional->source_position  = pp_token.base.source_position;
1583         conditional->condition        = condition;
1584
1585         if (!condition) {
1586                 skip_mode = true;
1587         }
1588 }
1589
1590 static void parse_else_directive(void)
1591 {
1592         eat_pp(TP_else);
1593
1594         if (!info.at_line_begin) {
1595                 if (!skip_mode) {
1596                         warningf(WARN_OTHER, &pp_token.base.source_position, "extra tokens at end of #else");
1597                 }
1598                 eat_pp_directive();
1599         }
1600
1601         pp_conditional_t *conditional = conditional_stack;
1602         if (conditional == NULL) {
1603                 errorf(&pp_token.base.source_position, "#else without prior #if");
1604                 return;
1605         }
1606
1607         if (conditional->in_else) {
1608                 errorf(&pp_token.base.source_position,
1609                        "#else after #else (condition started %P)",
1610                        conditional->source_position);
1611                 skip_mode = true;
1612                 return;
1613         }
1614
1615         conditional->in_else = true;
1616         if (!conditional->skip) {
1617                 skip_mode = conditional->condition;
1618         }
1619         conditional->source_position = pp_token.base.source_position;
1620 }
1621
1622 static void parse_endif_directive(void)
1623 {
1624         eat_pp(TP_endif);
1625
1626         if (!info.at_line_begin) {
1627                 if (!skip_mode) {
1628                         warningf(WARN_OTHER, &pp_token.base.source_position, "extra tokens at end of #endif");
1629                 }
1630                 eat_pp_directive();
1631         }
1632
1633         pp_conditional_t *conditional = conditional_stack;
1634         if (conditional == NULL) {
1635                 errorf(&pp_token.base.source_position, "#endif without prior #if");
1636                 return;
1637         }
1638
1639         if (!conditional->skip) {
1640                 skip_mode = false;
1641         }
1642         pop_conditional();
1643 }
1644
1645 static void parse_preprocessing_directive(void)
1646 {
1647         eat_pp('#');
1648
1649         if (info.at_line_begin) {
1650                 /* empty directive */
1651                 return;
1652         }
1653
1654         if (skip_mode) {
1655                 switch (pp_token.kind) {
1656                 case TP_ifdef:
1657                 case TP_ifndef:
1658                         parse_ifdef_ifndef_directive();
1659                         break;
1660                 case TP_else:
1661                         parse_else_directive();
1662                         break;
1663                 case TP_endif:
1664                         parse_endif_directive();
1665                         break;
1666                 default:
1667                         eat_pp_directive();
1668                         break;
1669                 }
1670         } else {
1671                 switch (pp_token.kind) {
1672                 case TP_define:
1673                         parse_define_directive();
1674                         break;
1675                 case TP_undef:
1676                         parse_undef_directive();
1677                         break;
1678                 case TP_ifdef:
1679                 case TP_ifndef:
1680                         parse_ifdef_ifndef_directive();
1681                         break;
1682                 case TP_else:
1683                         parse_else_directive();
1684                         break;
1685                 case TP_endif:
1686                         parse_endif_directive();
1687                         break;
1688                 case TP_include:
1689                         parse_include_directive();
1690                         break;
1691                 default:
1692                         if (info.at_line_begin) {
1693                                 /* the nop directive "#" */
1694                                 break;
1695                         }
1696                         errorf(&pp_token.base.source_position,
1697                                    "invalid preprocessing directive #%t", &pp_token);
1698                         eat_pp_directive();
1699                         break;
1700                 }
1701         }
1702
1703         assert(info.at_line_begin);
1704 }
1705
1706 static void prepend_include_path(const char *path)
1707 {
1708         searchpath_entry_t *entry = OALLOCZ(&config_obstack, searchpath_entry_t);
1709         entry->path = path;
1710         entry->next = searchpath;
1711         searchpath  = entry;
1712 }
1713
1714 static void setup_include_path(void)
1715 {
1716         /* built-in paths */
1717         prepend_include_path("/usr/include");
1718
1719         /* parse environment variable */
1720         const char *cpath = getenv("CPATH");
1721         if (cpath != NULL && *cpath != '\0') {
1722                 const char *begin = cpath;
1723                 const char *c;
1724                 do {
1725                         c = begin;
1726                         while (*c != '\0' && *c != ':')
1727                                 ++c;
1728
1729                         size_t len = c-begin;
1730                         if (len == 0) {
1731                                 /* for gcc compatibility (Matze: I would expect that
1732                                  * nothing happens for an empty entry...) */
1733                                 prepend_include_path(".");
1734                         } else {
1735                                 char *string = obstack_alloc(&config_obstack, len+1);
1736                                 memcpy(string, begin, len);
1737                                 string[len] = '\0';
1738
1739                                 prepend_include_path(string);
1740                         }
1741
1742                         begin = c+1;
1743                         /* skip : */
1744                         if (*begin == ':')
1745                                 ++begin;
1746                 } while(*c != '\0');
1747         }
1748 }
1749
1750 int pptest_main(int argc, char **argv);
1751 int pptest_main(int argc, char **argv)
1752 {
1753         init_symbol_table();
1754         init_tokens();
1755
1756         obstack_init(&config_obstack);
1757         obstack_init(&pp_obstack);
1758         obstack_init(&input_obstack);
1759         strset_init(&stringset);
1760
1761         setup_include_path();
1762
1763         /* simplistic commandline parser */
1764         const char *filename = NULL;
1765         const char *output = NULL;
1766         for (int i = 1; i < argc; ++i) {
1767                 const char *opt = argv[i];
1768                 if (streq(opt, "-I")) {
1769                         prepend_include_path(argv[++i]);
1770                         continue;
1771                 } else if (streq(opt, "-E")) {
1772                         /* ignore */
1773                 } else if (streq(opt, "-o")) {
1774                         output = argv[++i];
1775                         continue;
1776                 } else if (opt[0] == '-') {
1777                         fprintf(stderr, "Unknown option '%s'\n", opt);
1778                 } else {
1779                         if (filename != NULL)
1780                                 fprintf(stderr, "Multiple inputs not supported\n");
1781                         filename = argv[i];
1782                 }
1783         }
1784         if (filename == NULL) {
1785                 fprintf(stderr, "No input specified\n");
1786                 return 1;
1787         }
1788
1789         if (output == NULL) {
1790                 out = stdout;
1791         } else {
1792                 out = fopen(output, "w");
1793                 if (out == NULL) {
1794                         fprintf(stderr, "Couldn't open output '%s'\n", output);
1795                         return 1;
1796                 }
1797         }
1798
1799         /* just here for gcc compatibility */
1800         fprintf(out, "# 1 \"%s\"\n", filename);
1801         fprintf(out, "# 1 \"<built-in>\"\n");
1802         fprintf(out, "# 1 \"<command-line>\"\n");
1803
1804         FILE *file = fopen(filename, "r");
1805         if (file == NULL) {
1806                 fprintf(stderr, "Couldn't open input '%s'\n", filename);
1807                 return 1;
1808         }
1809         switch_input(file, filename);
1810
1811         while (true) {
1812                 if (pp_token.kind == '#' && info.at_line_begin) {
1813                         parse_preprocessing_directive();
1814                         continue;
1815                 } else if (pp_token.kind == TP_EOF) {
1816                         goto end_of_main_loop;
1817                 } else if (pp_token.kind == TP_IDENTIFIER) {
1818                         symbol_t        *const symbol        = pp_token.base.symbol;
1819                         pp_definition_t *const pp_definition = symbol->pp_definition;
1820                         if (pp_definition != NULL && !pp_definition->is_expanding) {
1821                                 expansion_pos = pp_token.base.source_position;
1822                                 if (pp_definition->has_parameters) {
1823                                         source_position_t position = pp_token.base.source_position;
1824                                         add_token_info_t old_info = info;
1825                                         next_preprocessing_token();
1826                                         add_token_info_t new_info = info;
1827
1828                                         /* no opening brace -> no expansion */
1829                                         if (pp_token.kind == '(') {
1830                                                 eat_pp('(');
1831
1832                                                 /* parse arguments (TODO) */
1833                                                 while (pp_token.kind != TP_EOF && pp_token.kind != ')')
1834                                                         next_preprocessing_token();
1835                                         } else {
1836                                                 token_t next_token = pp_token;
1837                                                 /* restore identifier token */
1838                                                 pp_token.kind                 = TP_IDENTIFIER;
1839                                                 pp_token.base.symbol          = symbol;
1840                                                 pp_token.base.source_position = position;
1841                                                 info = old_info;
1842                                                 emit_pp_token();
1843
1844                                                 info = new_info;
1845                                                 pp_token = next_token;
1846                                                 continue;
1847                                         }
1848                                         info = old_info;
1849                                 }
1850                                 pp_definition->expand_pos   = 0;
1851                                 pp_definition->is_expanding = true;
1852                                 current_expansion           = pp_definition;
1853                                 expand_next();
1854                                 continue;
1855                         }
1856                 }
1857
1858                 emit_pp_token();
1859                 next_preprocessing_token();
1860         }
1861 end_of_main_loop:
1862
1863         fputc('\n', out);
1864         check_unclosed_conditionals();
1865         close_input();
1866         if (out != stdout)
1867                 fclose(out);
1868
1869         obstack_free(&input_obstack, NULL);
1870         obstack_free(&pp_obstack, NULL);
1871         obstack_free(&config_obstack, NULL);
1872
1873         strset_destroy(&stringset);
1874
1875         exit_tokens();
1876         exit_symbol_table();
1877
1878         return 0;
1879 }