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