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