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