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