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