5d73bbd88114437297b1bba87de2cd1c19f3d9dd
[cparser] / lexer.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include "adt/strutil.h"
23 #include "input.h"
24 #include "diagnostic.h"
25 #include "lexer.h"
26 #include "symbol_t.h"
27 #include "token_t.h"
28 #include "symbol_table_t.h"
29 #include "adt/error.h"
30 #include "adt/strset.h"
31 #include "adt/util.h"
32 #include "types.h"
33 #include "type_t.h"
34 #include "parser.h"
35 #include "warning.h"
36 #include "lang_features.h"
37
38 #include <assert.h>
39 #include <errno.h>
40 #include <string.h>
41 #include <stdbool.h>
42 #include <ctype.h>
43
44 #ifndef _WIN32
45 #include <strings.h>
46 #endif
47
48 #define MAX_PUTBACK 16    // 3 would be enough, but 16 gives a nicer alignment
49 #define BUF_SIZE    1024
50
51 static input_t           *input;
52 static utf32              input_buf[BUF_SIZE + MAX_PUTBACK];
53 static const utf32       *bufpos;
54 static const utf32       *bufend;
55 static utf32              c;
56 static source_position_t  lexer_pos;
57 token_t                   lexer_token;
58 static symbol_t          *symbol_L;
59 static strset_t           stringset;
60 bool                      allow_dollar_in_symbol = true;
61
62 /**
63  * Prints a parse error message at the current token.
64  *
65  * @param msg   the error message
66  */
67 static void parse_error(const char *msg)
68 {
69         errorf(&lexer_pos, "%s", msg);
70 }
71
72 /**
73  * Prints an internal error message at the current token.
74  *
75  * @param msg   the error message
76  */
77 static NORETURN internal_error(const char *msg)
78 {
79         internal_errorf(&lexer_pos, "%s", msg);
80 }
81
82 static inline void next_real_char(void)
83 {
84         assert(bufpos <= bufend);
85         if (bufpos >= bufend) {
86                 size_t n = decode(input, input_buf+MAX_PUTBACK, BUF_SIZE);
87                 if (n == 0) {
88                         c = EOF;
89                         return;
90                 }
91                 bufpos = input_buf + MAX_PUTBACK;
92                 bufend = bufpos + n;
93         }
94         c = *bufpos++;
95         ++lexer_pos.colno;
96 }
97
98 /**
99  * Put a character back into the buffer.
100  *
101  * @param pc  the character to put back
102  */
103 static inline void put_back(utf32 const pc)
104 {
105         *(--bufpos - input_buf + input_buf) = pc;
106         --lexer_pos.colno;
107 }
108
109 static inline void next_char(void);
110
111 #define MATCH_NEWLINE(code)  \
112         case '\r':               \
113                 next_char();         \
114                 if (c == '\n') {     \
115         case '\n':               \
116                         next_char();     \
117                 }                    \
118                 lexer_pos.lineno++;  \
119                 lexer_pos.colno = 1; \
120                 code
121
122 #define eat(c_type) (assert(c == c_type), next_char())
123
124 static void maybe_concat_lines(void)
125 {
126         eat('\\');
127
128         switch (c) {
129         MATCH_NEWLINE(return;)
130
131         default:
132                 break;
133         }
134
135         put_back(c);
136         c = '\\';
137 }
138
139 /**
140  * Set c to the next input character, ie.
141  * after expanding trigraphs.
142  */
143 static inline void next_char(void)
144 {
145         next_real_char();
146
147         /* filter trigraphs */
148         if (UNLIKELY(c == '\\')) {
149                 maybe_concat_lines();
150                 return;
151         }
152
153         if (LIKELY(c != '?'))
154                 return;
155
156         next_real_char();
157         if (LIKELY(c != '?')) {
158                 put_back(c);
159                 c = '?';
160                 return;
161         }
162
163         next_real_char();
164         switch (c) {
165         case '=': c = '#'; break;
166         case '(': c = '['; break;
167         case '/': c = '\\'; maybe_concat_lines(); break;
168         case ')': c = ']'; break;
169         case '\'': c = '^'; break;
170         case '<': c = '{'; break;
171         case '!': c = '|'; break;
172         case '>': c = '}'; break;
173         case '-': c = '~'; break;
174         default:
175                 put_back(c);
176                 put_back('?');
177                 c = '?';
178                 break;
179         }
180 }
181
182 #define SYMBOL_CHARS  \
183         case '$': if (!allow_dollar_in_symbol) goto dollar_sign; \
184         case 'a':         \
185         case 'b':         \
186         case 'c':         \
187         case 'd':         \
188         case 'e':         \
189         case 'f':         \
190         case 'g':         \
191         case 'h':         \
192         case 'i':         \
193         case 'j':         \
194         case 'k':         \
195         case 'l':         \
196         case 'm':         \
197         case 'n':         \
198         case 'o':         \
199         case 'p':         \
200         case 'q':         \
201         case 'r':         \
202         case 's':         \
203         case 't':         \
204         case 'u':         \
205         case 'v':         \
206         case 'w':         \
207         case 'x':         \
208         case 'y':         \
209         case 'z':         \
210         case 'A':         \
211         case 'B':         \
212         case 'C':         \
213         case 'D':         \
214         case 'E':         \
215         case 'F':         \
216         case 'G':         \
217         case 'H':         \
218         case 'I':         \
219         case 'J':         \
220         case 'K':         \
221         case 'L':         \
222         case 'M':         \
223         case 'N':         \
224         case 'O':         \
225         case 'P':         \
226         case 'Q':         \
227         case 'R':         \
228         case 'S':         \
229         case 'T':         \
230         case 'U':         \
231         case 'V':         \
232         case 'W':         \
233         case 'X':         \
234         case 'Y':         \
235         case 'Z':         \
236         case '_':
237
238 #define DIGITS        \
239         case '0':         \
240         case '1':         \
241         case '2':         \
242         case '3':         \
243         case '4':         \
244         case '5':         \
245         case '6':         \
246         case '7':         \
247         case '8':         \
248         case '9':
249
250 /**
251  * Read a symbol from the input and build
252  * the lexer_token.
253  */
254 static void parse_symbol(void)
255 {
256         obstack_1grow(&symbol_obstack, (char) c);
257         next_char();
258
259         while (true) {
260                 switch (c) {
261                 DIGITS
262                 SYMBOL_CHARS
263                         obstack_1grow(&symbol_obstack, (char) c);
264                         next_char();
265                         break;
266
267                 default:
268 dollar_sign:
269                         goto end_symbol;
270                 }
271         }
272
273 end_symbol:
274         obstack_1grow(&symbol_obstack, '\0');
275
276         char     *string = obstack_finish(&symbol_obstack);
277         symbol_t *symbol = symbol_table_insert(string);
278
279         lexer_token.kind        = symbol->ID;
280         lexer_token.base.symbol = symbol;
281
282         if (symbol->string != string) {
283                 obstack_free(&symbol_obstack, string);
284         }
285 }
286
287 static string_t identify_string(char *string, size_t len)
288 {
289         /* TODO hash */
290 #if 0
291         const char *result = strset_insert(&stringset, concat);
292         if (result != concat) {
293                 obstack_free(&symbol_obstack, concat);
294         }
295 #else
296         const char *result = string;
297 #endif
298         return (string_t) {result, len};
299 }
300
301 /**
302  * parse suffixes like 'LU' or 'f' after numbers
303  */
304 static void parse_number_suffix(void)
305 {
306         assert(obstack_object_size(&symbol_obstack) == 0);
307         while (true) {
308                 switch (c) {
309                 SYMBOL_CHARS
310                         obstack_1grow(&symbol_obstack, (char) c);
311                         next_char();
312                         break;
313                 default:
314                 dollar_sign:
315                         goto finish_suffix;
316                 }
317         }
318 finish_suffix:
319         if (obstack_object_size(&symbol_obstack) == 0) {
320                 lexer_token.number.suffix.begin = NULL;
321                 lexer_token.number.suffix.size  = 0;
322                 return;
323         }
324
325         obstack_1grow(&symbol_obstack, '\0');
326         size_t size   = obstack_object_size(&symbol_obstack) - 1;
327         char  *string = obstack_finish(&symbol_obstack);
328
329         lexer_token.number.suffix = identify_string(string, size);
330 }
331
332 static void parse_exponent(void)
333 {
334         if (c == '-' || c == '+') {
335                 obstack_1grow(&symbol_obstack, (char)c);
336                 next_char();
337         }
338
339         if (isdigit(c)) {
340                 do {
341                         obstack_1grow(&symbol_obstack, (char)c);
342                         next_char();
343                 } while (isdigit(c));
344         } else {
345                 errorf(&lexer_token.base.source_position, "exponent has no digits");
346         }
347 }
348
349 /**
350  * Parses a hex number including hex floats and set the
351  * lexer_token.
352  */
353 static void parse_number_hex(void)
354 {
355         bool is_float   = false;
356         bool has_digits = false;
357
358         while (isxdigit(c)) {
359                 has_digits = true;
360                 obstack_1grow(&symbol_obstack, (char) c);
361                 next_char();
362         }
363
364         if (c == '.') {
365                 is_float = true;
366                 obstack_1grow(&symbol_obstack, (char) c);
367                 next_char();
368
369                 while (isxdigit(c)) {
370                         has_digits = true;
371                         obstack_1grow(&symbol_obstack, (char) c);
372                         next_char();
373                 }
374         }
375         if (c == 'p' || c == 'P') {
376                 is_float = true;
377                 obstack_1grow(&symbol_obstack, (char) c);
378                 next_char();
379                 parse_exponent();
380         } else if (is_float) {
381                 errorf(&lexer_token.base.source_position,
382                        "hexadecimal floatingpoint constant requires an exponent");
383         }
384         obstack_1grow(&symbol_obstack, '\0');
385
386         size_t  size   = obstack_object_size(&symbol_obstack) - 1;
387         char   *string = obstack_finish(&symbol_obstack);
388         lexer_token.number.number = identify_string(string, size);
389
390         lexer_token.kind = is_float ? T_FLOATINGPOINT : T_INTEGER;
391
392         if (!has_digits) {
393                 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
394                 lexer_token.number.number.begin = "0";
395                 lexer_token.number.number.size  = 1;
396         }
397
398         parse_number_suffix();
399 }
400
401 static void parse_number_bin(void)
402 {
403         bool has_digits = false;
404
405         while (c == '0' || c == '1') {
406                 has_digits = true;
407                 obstack_1grow(&symbol_obstack, (char)c);
408                 next_char();
409         }
410         obstack_1grow(&symbol_obstack, '\0');
411
412         size_t  const size   = obstack_object_size(&symbol_obstack) - 1;
413         char   *const string = obstack_finish(&symbol_obstack);
414         lexer_token.number.number = identify_string(string, size);
415         lexer_token.kind          = T_INTEGER;
416
417         if (!has_digits) {
418                 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
419                 lexer_token.number.number.begin = "0";
420                 lexer_token.number.number.size  = 1;
421         }
422
423         parse_number_suffix();
424 }
425
426 /**
427  * Returns true if the given char is a octal digit.
428  *
429  * @param char  the character to check
430  */
431 static bool is_octal_digit(utf32 chr)
432 {
433         return '0' <= chr && chr <= '7';
434 }
435
436 /**
437  * Parses a number and sets the lexer_token.
438  */
439 static void parse_number(void)
440 {
441         bool is_float   = false;
442         bool has_digits = false;
443
444         assert(obstack_object_size(&symbol_obstack) == 0);
445         if (c == '0') {
446                 obstack_1grow(&symbol_obstack, (char)c);
447                 next_char();
448                 if (c == 'x' || c == 'X') {
449                         obstack_1grow(&symbol_obstack, (char)c);
450                         next_char();
451                         parse_number_hex();
452                         return;
453                 } else if (c == 'b' || c == 'B') {
454                         /* GCC extension: binary constant 0x[bB][01]+.  */
455                         obstack_1grow(&symbol_obstack, (char)c);
456                         next_char();
457                         parse_number_bin();
458                         return;
459                 }
460                 has_digits = true;
461         }
462
463         while (isdigit(c)) {
464                 has_digits = true;
465                 obstack_1grow(&symbol_obstack, (char) c);
466                 next_char();
467         }
468
469         if (c == '.') {
470                 is_float = true;
471                 obstack_1grow(&symbol_obstack, '.');
472                 next_char();
473
474                 while (isdigit(c)) {
475                         has_digits = true;
476                         obstack_1grow(&symbol_obstack, (char) c);
477                         next_char();
478                 }
479         }
480         if (c == 'e' || c == 'E') {
481                 is_float = true;
482                 obstack_1grow(&symbol_obstack, 'e');
483                 next_char();
484                 parse_exponent();
485         }
486
487         obstack_1grow(&symbol_obstack, '\0');
488         size_t  size   = obstack_object_size(&symbol_obstack) - 1;
489         char   *string = obstack_finish(&symbol_obstack);
490         lexer_token.number.number = identify_string(string, size);
491
492         if (is_float) {
493                 lexer_token.kind = T_FLOATINGPOINT;
494         } else {
495                 lexer_token.kind = T_INTEGER;
496
497                 if (string[0] == '0') {
498                         /* check for invalid octal digits */
499                         for (size_t i= 0; i < size; ++i) {
500                                 char t = string[i];
501                                 if (t >= '8')
502                                         errorf(&lexer_token.base.source_position, "invalid digit '%c' in octal number", t);
503                         }
504                 }
505         }
506
507         if (!has_digits) {
508                 errorf(&lexer_token.base.source_position, "invalid number literal '%S'",
509                        &lexer_token.number.number);
510         }
511
512         parse_number_suffix();
513 }
514
515 /**
516  * Returns the value of a digit.
517  * The only portable way to do it ...
518  */
519 static int digit_value(utf32 const digit)
520 {
521         switch (digit) {
522         case '0': return 0;
523         case '1': return 1;
524         case '2': return 2;
525         case '3': return 3;
526         case '4': return 4;
527         case '5': return 5;
528         case '6': return 6;
529         case '7': return 7;
530         case '8': return 8;
531         case '9': return 9;
532         case 'a':
533         case 'A': return 10;
534         case 'b':
535         case 'B': return 11;
536         case 'c':
537         case 'C': return 12;
538         case 'd':
539         case 'D': return 13;
540         case 'e':
541         case 'E': return 14;
542         case 'f':
543         case 'F': return 15;
544         default:
545                 internal_error("wrong character given");
546         }
547 }
548
549 /**
550  * Parses an octal character sequence.
551  *
552  * @param first_digit  the already read first digit
553  */
554 static utf32 parse_octal_sequence(utf32 const first_digit)
555 {
556         assert(is_octal_digit(first_digit));
557         utf32 value = digit_value(first_digit);
558         if (!is_octal_digit(c)) return value;
559         value = 8 * value + digit_value(c);
560         next_char();
561         if (!is_octal_digit(c)) return value;
562         value = 8 * value + digit_value(c);
563         next_char();
564         return value;
565 }
566
567 /**
568  * Parses a hex character sequence.
569  */
570 static utf32 parse_hex_sequence(void)
571 {
572         utf32 value = 0;
573         while (isxdigit(c)) {
574                 value = 16 * value + digit_value(c);
575                 next_char();
576         }
577         return value;
578 }
579
580 /**
581  * Parse an escape sequence.
582  */
583 static utf32 parse_escape_sequence(void)
584 {
585         eat('\\');
586
587         utf32 const ec = c;
588         next_char();
589
590         switch (ec) {
591         case '"':  return '"';
592         case '\'': return '\'';
593         case '\\': return '\\';
594         case '?': return '\?';
595         case 'a': return '\a';
596         case 'b': return '\b';
597         case 'f': return '\f';
598         case 'n': return '\n';
599         case 'r': return '\r';
600         case 't': return '\t';
601         case 'v': return '\v';
602         case 'x':
603                 return parse_hex_sequence();
604         case '0':
605         case '1':
606         case '2':
607         case '3':
608         case '4':
609         case '5':
610         case '6':
611         case '7':
612                 return parse_octal_sequence(ec);
613         case EOF:
614                 parse_error("reached end of file while parsing escape sequence");
615                 return EOF;
616         /* \E is not documented, but handled, by GCC.  It is acceptable according
617          * to Â§6.11.4, whereas \e is not. */
618         case 'E':
619         case 'e':
620                 if (c_mode & _GNUC)
621                         return 27;   /* hopefully 27 is ALWAYS the code for ESCAPE */
622                 break;
623         case 'u':
624         case 'U':
625                 parse_error("universal character parsing not implemented yet");
626                 return EOF;
627         default:
628                 break;
629         }
630         /* Â§6.4.4.4:8 footnote 64 */
631         parse_error("unknown escape sequence");
632         return EOF;
633 }
634
635 string_t make_string(const char *string)
636 {
637         size_t      len   = strlen(string) + 1;
638         char *const space = obstack_alloc(&symbol_obstack, len);
639         memcpy(space, string, len);
640
641         return identify_string(space, len);
642 }
643
644 static void parse_string(utf32 const delim, token_kind_t const kind, string_encoding_t const enc, char const *const context)
645 {
646         eat(delim);
647
648         while (true) {
649                 switch (c) {
650                 case '\\': {
651                         utf32 const tc = parse_escape_sequence();
652                         if (enc == STRING_ENCODING_CHAR) {
653                                 if (tc >= 0x100) {
654                                         warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
655                                 }
656                                 obstack_1grow(&symbol_obstack, tc);
657                         } else {
658                                 obstack_grow_symbol(&symbol_obstack, tc);
659                         }
660                         break;
661                 }
662
663                 MATCH_NEWLINE(
664                         errorf(&lexer_pos, "newline while parsing %s", context);
665                         break;
666                 )
667
668                 case EOF:
669                         errorf(&lexer_token.base.source_position, "EOF while parsing %s", context);
670                         goto end_of_string;
671
672                 default:
673                         if (c == delim) {
674                                 next_char();
675                                 goto end_of_string;
676                         } else {
677                                 obstack_grow_symbol(&symbol_obstack, c);
678                                 next_char();
679                                 break;
680                         }
681                 }
682         }
683
684 end_of_string:
685         obstack_1grow(&symbol_obstack, '\0');
686         size_t const size   = obstack_object_size(&symbol_obstack) - 1;
687         char  *const string = obstack_finish(&symbol_obstack);
688
689         lexer_token.kind            = kind;
690         lexer_token.string.encoding = enc;
691         lexer_token.string.string   = identify_string(string, size);
692 }
693
694 /**
695  * Parse a string literal and set lexer_token.
696  */
697 static void parse_string_literal(string_encoding_t const enc)
698 {
699         parse_string('"', T_STRING_LITERAL, enc, "string literal");
700 }
701
702 /**
703  * Parse a character constant and set lexer_token.
704  */
705 static void parse_character_constant(string_encoding_t const enc)
706 {
707         parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
708         if (lexer_token.string.string.size == 0) {
709                 errorf(&lexer_token.base.source_position, "empty character constant");
710         }
711 }
712
713 /**
714  * Skip a multiline comment.
715  */
716 static void skip_multiline_comment(void)
717 {
718         while (true) {
719                 switch (c) {
720                 case '/':
721                         next_char();
722                         if (c == '*') {
723                                 /* nested comment, warn here */
724                                 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
725                         }
726                         break;
727                 case '*':
728                         next_char();
729                         if (c == '/') {
730                                 next_char();
731                                 return;
732                         }
733                         break;
734
735                 MATCH_NEWLINE(break;)
736
737                 case EOF: {
738                         errorf(&lexer_token.base.source_position,
739                                "at end of file while looking for comment end");
740                         return;
741                 }
742
743                 default:
744                         next_char();
745                         break;
746                 }
747         }
748 }
749
750 /**
751  * Skip a single line comment.
752  */
753 static void skip_line_comment(void)
754 {
755         while (true) {
756                 switch (c) {
757                 case EOF:
758                         return;
759
760                 case '\n':
761                 case '\r':
762                         return;
763
764                 case '\\':
765                         next_char();
766                         if (c == '\n' || c == '\r') {
767                                 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
768                                 return;
769                         }
770                         break;
771
772                 default:
773                         next_char();
774                         break;
775                 }
776         }
777 }
778
779 /** The current preprocessor token. */
780 static token_t pp_token;
781
782 /**
783  * Read the next preprocessor token.
784  */
785 static inline void next_pp_token(void)
786 {
787         lexer_next_preprocessing_token();
788         pp_token = lexer_token;
789 }
790
791 /**
792  * Eat all preprocessor tokens until newline.
793  */
794 static void eat_until_newline(void)
795 {
796         while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
797                 next_pp_token();
798         }
799 }
800
801 /**
802  * Parse the line directive.
803  */
804 static void parse_line_directive(void)
805 {
806         if (pp_token.kind != T_INTEGER) {
807                 parse_error("expected integer");
808         } else {
809                 /* use offset -1 as this is about the next line */
810                 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
811                 next_pp_token();
812         }
813         if (pp_token.kind == T_STRING_LITERAL && pp_token.string.encoding == STRING_ENCODING_CHAR) {
814                 lexer_pos.input_name = pp_token.string.string.begin;
815                 lexer_pos.is_system_header = false;
816                 next_pp_token();
817
818                 /* attempt to parse numeric flags as outputted by gcc preprocessor */
819                 while (pp_token.kind == T_INTEGER) {
820                         /* flags:
821                          * 1 - indicates start of a new file
822                          * 2 - indicates return from a file
823                          * 3 - indicates system header
824                          * 4 - indicates implicit extern "C" in C++ mode
825                          *
826                          * currently we're only interested in "3"
827                          */
828                         if (streq(pp_token.number.number.begin, "3")) {
829                                 lexer_pos.is_system_header = true;
830                         }
831                         next_pp_token();
832                 }
833         }
834
835         eat_until_newline();
836 }
837
838 /**
839  * STDC pragmas.
840  */
841 typedef enum stdc_pragma_kind_t {
842         STDC_UNKNOWN,
843         STDC_FP_CONTRACT,
844         STDC_FENV_ACCESS,
845         STDC_CX_LIMITED_RANGE
846 } stdc_pragma_kind_t;
847
848 /**
849  * STDC pragma values.
850  */
851 typedef enum stdc_pragma_value_kind_t {
852         STDC_VALUE_UNKNOWN,
853         STDC_VALUE_ON,
854         STDC_VALUE_OFF,
855         STDC_VALUE_DEFAULT
856 } stdc_pragma_value_kind_t;
857
858 /**
859  * Parse a pragma directive.
860  */
861 static void parse_pragma(void)
862 {
863         next_pp_token();
864         if (pp_token.kind != T_IDENTIFIER) {
865                 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
866                          "expected identifier after #pragma");
867                 eat_until_newline();
868                 return;
869         }
870
871         stdc_pragma_kind_t kind = STDC_UNKNOWN;
872         if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
873                 /* a STDC pragma */
874                 next_pp_token();
875
876                 switch (pp_token.base.symbol->pp_ID) {
877                 case TP_FP_CONTRACT:      kind = STDC_FP_CONTRACT;      break;
878                 case TP_FENV_ACCESS:      kind = STDC_FENV_ACCESS;      break;
879                 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
880                 default:                  break;
881                 }
882                 if (kind != STDC_UNKNOWN) {
883                         next_pp_token();
884                         stdc_pragma_value_kind_t value;
885                         switch (pp_token.base.symbol->pp_ID) {
886                         case TP_ON:      value = STDC_VALUE_ON;      break;
887                         case TP_OFF:     value = STDC_VALUE_OFF;     break;
888                         case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
889                         default:         value = STDC_VALUE_UNKNOWN; break;
890                         }
891                         if (value == STDC_VALUE_UNKNOWN) {
892                                 kind = STDC_UNKNOWN;
893                                 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
894                         }
895                 }
896         }
897         eat_until_newline();
898         if (kind == STDC_UNKNOWN) {
899                 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
900                          "encountered unknown #pragma");
901         }
902 }
903
904 /**
905  * Parse a preprocessor non-null directive.
906  */
907 static void parse_preprocessor_identifier(void)
908 {
909         assert(pp_token.kind == T_IDENTIFIER);
910         switch (pp_token.base.symbol->pp_ID) {
911         case TP_line:
912                 next_pp_token();
913                 parse_line_directive();
914                 break;
915         case TP_pragma:
916                 parse_pragma();
917                 break;
918         case TP_error:
919                 /* TODO; output the rest of the line */
920                 parse_error("#error directive");
921                 break;
922         }
923 }
924
925 /**
926  * Parse a preprocessor directive.
927  */
928 static void parse_preprocessor_directive(void)
929 {
930         next_pp_token();
931
932         switch (pp_token.kind) {
933         case T_IDENTIFIER:
934                 parse_preprocessor_identifier();
935                 break;
936         case T_INTEGER:
937                 parse_line_directive();
938                 break;
939         case '\n':
940                 /* NULL directive, see Â§6.10.7 */
941                 break;
942         default:
943                 parse_error("invalid preprocessor directive");
944                 eat_until_newline();
945                 break;
946         }
947 }
948
949 #define MAYBE_PROLOG                                       \
950                         next_char();                                   \
951                         while (true) {                                 \
952                                 switch (c) {
953
954 #define MAYBE(ch, set_type)                                \
955                                 case ch:                                   \
956                                         next_char();                           \
957                                         lexer_token.kind = set_type;           \
958                                         return;
959
960 /* must use this as last thing */
961 #define MAYBE_MODE(ch, set_type, mode)                     \
962                                 case ch:                                   \
963                                         if (c_mode & mode) {                   \
964                                                 next_char();                       \
965                                                 lexer_token.kind = set_type;       \
966                                                 return;                            \
967                                         }                                      \
968                                         /* fallthrough */
969
970 #define ELSE_CODE(code)                                    \
971                                 default:                                   \
972                                         code                                   \
973                                         return;                                \
974                                 }                                          \
975                         } /* end of while (true) */                    \
976
977 #define ELSE(set_type)                                     \
978                 ELSE_CODE(                                         \
979                         lexer_token.kind = set_type;                   \
980                 )
981
982 void lexer_next_preprocessing_token(void)
983 {
984         while (true) {
985                 lexer_token.base.source_position = lexer_pos;
986                 lexer_token.base.symbol          = NULL;
987
988                 switch (c) {
989                 case ' ':
990                 case '\t':
991                         next_char();
992                         break;
993
994                 MATCH_NEWLINE(
995                         lexer_token.kind = '\n';
996                         return;
997                 )
998
999                 SYMBOL_CHARS {
1000                         parse_symbol();
1001                         /* might be a wide string ( L"string" ) */
1002                         string_encoding_t const enc = STRING_ENCODING_WIDE;
1003                         if (lexer_token.base.symbol == symbol_L) {
1004                                 switch (c) {
1005                                 case '"':  parse_string_literal(enc);     break;
1006                                 case '\'': parse_character_constant(enc); break;
1007                                 }
1008                         }
1009                         return;
1010                 }
1011
1012                 DIGITS
1013                         parse_number();
1014                         return;
1015
1016                 case '"':
1017                         parse_string_literal(STRING_ENCODING_CHAR);
1018                         return;
1019
1020                 case '\'':
1021                         parse_character_constant(STRING_ENCODING_CHAR);
1022                         return;
1023
1024                 case '.':
1025                         MAYBE_PROLOG
1026                                 DIGITS
1027                                         put_back(c);
1028                                         c = '.';
1029                                         parse_number();
1030                                         return;
1031
1032                                 case '.':
1033                                         MAYBE_PROLOG
1034                                         MAYBE('.', T_DOTDOTDOT)
1035                                         ELSE_CODE(
1036                                                 put_back(c);
1037                                                 c = '.';
1038                                                 lexer_token.kind = '.';
1039                                         )
1040                         ELSE('.')
1041                 case '&':
1042                         MAYBE_PROLOG
1043                         MAYBE('&', T_ANDAND)
1044                         MAYBE('=', T_ANDEQUAL)
1045                         ELSE('&')
1046                 case '*':
1047                         MAYBE_PROLOG
1048                         MAYBE('=', T_ASTERISKEQUAL)
1049                         ELSE('*')
1050                 case '+':
1051                         MAYBE_PROLOG
1052                         MAYBE('+', T_PLUSPLUS)
1053                         MAYBE('=', T_PLUSEQUAL)
1054                         ELSE('+')
1055                 case '-':
1056                         MAYBE_PROLOG
1057                         MAYBE('>', T_MINUSGREATER)
1058                         MAYBE('-', T_MINUSMINUS)
1059                         MAYBE('=', T_MINUSEQUAL)
1060                         ELSE('-')
1061                 case '!':
1062                         MAYBE_PROLOG
1063                         MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1064                         ELSE('!')
1065                 case '/':
1066                         MAYBE_PROLOG
1067                         MAYBE('=', T_SLASHEQUAL)
1068                                 case '*':
1069                                         next_char();
1070                                         skip_multiline_comment();
1071                                         lexer_next_preprocessing_token();
1072                                         return;
1073                                 case '/':
1074                                         next_char();
1075                                         skip_line_comment();
1076                                         lexer_next_preprocessing_token();
1077                                         return;
1078                         ELSE('/')
1079                 case '%':
1080                         MAYBE_PROLOG
1081                         MAYBE('>', '}')
1082                         MAYBE('=', T_PERCENTEQUAL)
1083                                 case ':':
1084                                         MAYBE_PROLOG
1085                                                 case '%':
1086                                                         MAYBE_PROLOG
1087                                                         MAYBE(':', T_HASHHASH)
1088                                                         ELSE_CODE(
1089                                                                 put_back(c);
1090                                                                 c = '%';
1091                                                                 lexer_token.kind = '#';
1092                                                         )
1093                                         ELSE('#')
1094                         ELSE('%')
1095                 case '<':
1096                         MAYBE_PROLOG
1097                         MAYBE(':', '[')
1098                         MAYBE('%', '{')
1099                         MAYBE('=', T_LESSEQUAL)
1100                                 case '<':
1101                                         MAYBE_PROLOG
1102                                         MAYBE('=', T_LESSLESSEQUAL)
1103                                         ELSE(T_LESSLESS)
1104                         ELSE('<')
1105                 case '>':
1106                         MAYBE_PROLOG
1107                         MAYBE('=', T_GREATEREQUAL)
1108                                 case '>':
1109                                         MAYBE_PROLOG
1110                                         MAYBE('=', T_GREATERGREATEREQUAL)
1111                                         ELSE(T_GREATERGREATER)
1112                         ELSE('>')
1113                 case '^':
1114                         MAYBE_PROLOG
1115                         MAYBE('=', T_CARETEQUAL)
1116                         ELSE('^')
1117                 case '|':
1118                         MAYBE_PROLOG
1119                         MAYBE('=', T_PIPEEQUAL)
1120                         MAYBE('|', T_PIPEPIPE)
1121                         ELSE('|')
1122                 case ':':
1123                         MAYBE_PROLOG
1124                         MAYBE('>', ']')
1125                         MAYBE_MODE(':', T_COLONCOLON, _CXX)
1126                         ELSE(':')
1127                 case '=':
1128                         MAYBE_PROLOG
1129                         MAYBE('=', T_EQUALEQUAL)
1130                         ELSE('=')
1131                 case '#':
1132                         MAYBE_PROLOG
1133                         MAYBE('#', T_HASHHASH)
1134                         ELSE('#')
1135
1136                 case '?':
1137                 case '[':
1138                 case ']':
1139                 case '(':
1140                 case ')':
1141                 case '{':
1142                 case '}':
1143                 case '~':
1144                 case ';':
1145                 case ',':
1146                 case '\\':
1147                         lexer_token.kind = c;
1148                         next_char();
1149                         return;
1150
1151                 case EOF:
1152                         lexer_token.kind = T_EOF;
1153                         return;
1154
1155                 default:
1156 dollar_sign:
1157                         errorf(&lexer_pos, "unknown character '%c' found", c);
1158                         next_char();
1159                         break;
1160                 }
1161         }
1162 }
1163
1164 void lexer_next_token(void)
1165 {
1166         lexer_next_preprocessing_token();
1167
1168         while (lexer_token.kind == '\n') {
1169 newline_found:
1170                 lexer_next_preprocessing_token();
1171         }
1172
1173         if (lexer_token.kind == '#') {
1174                 parse_preprocessor_directive();
1175                 goto newline_found;
1176         }
1177 }
1178
1179 void init_lexer(void)
1180 {
1181         strset_init(&stringset);
1182         symbol_L = symbol_table_insert("L");
1183 }
1184
1185 static void input_error(unsigned delta_lines, unsigned delta_cols,
1186                         const char *message)
1187 {
1188         lexer_pos.lineno += delta_lines;
1189         lexer_pos.colno  += delta_cols;
1190         errorf(&lexer_pos, "%s", message);
1191 }
1192
1193 void lexer_switch_input(input_t *new_input, const char *input_name)
1194 {
1195         lexer_pos.lineno     = 0;
1196         lexer_pos.colno      = 0;
1197         lexer_pos.input_name = input_name;
1198
1199         set_input_error_callback(input_error);
1200         input  = new_input;
1201         bufpos = NULL;
1202         bufend = NULL;
1203
1204         /* place a virtual \n at the beginning so the lexer knows that we're
1205          * at the beginning of a line */
1206         c = '\n';
1207 }
1208
1209 void exit_lexer(void)
1210 {
1211         strset_destroy(&stringset);
1212 }
1213
1214 static __attribute__((unused))
1215 void dbg_pos(const source_position_t source_position)
1216 {
1217         fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1218                 source_position.lineno, (unsigned)source_position.colno);
1219         fflush(stdout);
1220 }