1ad3b894b13077a97c63a7eaae6d1545d3fee912
[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.identifier.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    =
391                 is_float ? T_FLOATINGPOINT_HEXADECIMAL : T_INTEGER_HEXADECIMAL;
392
393         if (!has_digits) {
394                 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
395                 lexer_token.number.number.begin = "0";
396                 lexer_token.number.number.size  = 1;
397         }
398
399         parse_number_suffix();
400 }
401
402 /**
403  * Returns true if the given char is a octal digit.
404  *
405  * @param char  the character to check
406  */
407 static bool is_octal_digit(utf32 chr)
408 {
409         return '0' <= chr && chr <= '7';
410 }
411
412 /**
413  * Parses a number and sets the lexer_token.
414  */
415 static void parse_number(void)
416 {
417         bool is_float   = false;
418         bool has_digits = false;
419
420         assert(obstack_object_size(&symbol_obstack) == 0);
421         if (c == '0') {
422                 obstack_1grow(&symbol_obstack, (char)c);
423                 next_char();
424                 if (c == 'x' || c == 'X') {
425                         obstack_1grow(&symbol_obstack, (char)c);
426                         next_char();
427                         parse_number_hex();
428                         return;
429                 } else {
430                         has_digits = true;
431                 }
432         }
433
434         while (isdigit(c)) {
435                 has_digits = true;
436                 obstack_1grow(&symbol_obstack, (char) c);
437                 next_char();
438         }
439
440         if (c == '.') {
441                 is_float = true;
442                 obstack_1grow(&symbol_obstack, '.');
443                 next_char();
444
445                 while (isdigit(c)) {
446                         has_digits = true;
447                         obstack_1grow(&symbol_obstack, (char) c);
448                         next_char();
449                 }
450         }
451         if (c == 'e' || c == 'E') {
452                 is_float = true;
453                 obstack_1grow(&symbol_obstack, 'e');
454                 next_char();
455                 parse_exponent();
456         }
457
458         obstack_1grow(&symbol_obstack, '\0');
459         size_t  size   = obstack_object_size(&symbol_obstack) - 1;
460         char   *string = obstack_finish(&symbol_obstack);
461         lexer_token.number.number = identify_string(string, size);
462
463         /* is it an octal number? */
464         if (is_float) {
465                 lexer_token.kind = T_FLOATINGPOINT;
466         } else if (string[0] == '0') {
467                 lexer_token.kind = T_INTEGER_OCTAL;
468
469                 /* check for invalid octal digits */
470                 for (size_t i= 0; i < size; ++i) {
471                         char t = string[i];
472                         if (t >= '8')
473                                 errorf(&lexer_token.base.source_position,
474                                        "invalid digit '%c' in octal number", t);
475                 }
476         } else {
477                 lexer_token.kind = T_INTEGER;
478         }
479
480         if (!has_digits) {
481                 errorf(&lexer_token.base.source_position, "invalid number literal '%S'",
482                        &lexer_token.number.number);
483         }
484
485         parse_number_suffix();
486 }
487
488 /**
489  * Returns the value of a digit.
490  * The only portable way to do it ...
491  */
492 static int digit_value(utf32 const digit)
493 {
494         switch (digit) {
495         case '0': return 0;
496         case '1': return 1;
497         case '2': return 2;
498         case '3': return 3;
499         case '4': return 4;
500         case '5': return 5;
501         case '6': return 6;
502         case '7': return 7;
503         case '8': return 8;
504         case '9': return 9;
505         case 'a':
506         case 'A': return 10;
507         case 'b':
508         case 'B': return 11;
509         case 'c':
510         case 'C': return 12;
511         case 'd':
512         case 'D': return 13;
513         case 'e':
514         case 'E': return 14;
515         case 'f':
516         case 'F': return 15;
517         default:
518                 internal_error("wrong character given");
519         }
520 }
521
522 /**
523  * Parses an octal character sequence.
524  *
525  * @param first_digit  the already read first digit
526  */
527 static utf32 parse_octal_sequence(utf32 const first_digit)
528 {
529         assert(is_octal_digit(first_digit));
530         utf32 value = digit_value(first_digit);
531         if (!is_octal_digit(c)) return value;
532         value = 8 * value + digit_value(c);
533         next_char();
534         if (!is_octal_digit(c)) return value;
535         value = 8 * value + digit_value(c);
536         next_char();
537         return value;
538 }
539
540 /**
541  * Parses a hex character sequence.
542  */
543 static utf32 parse_hex_sequence(void)
544 {
545         utf32 value = 0;
546         while (isxdigit(c)) {
547                 value = 16 * value + digit_value(c);
548                 next_char();
549         }
550         return value;
551 }
552
553 /**
554  * Parse an escape sequence.
555  */
556 static utf32 parse_escape_sequence(void)
557 {
558         eat('\\');
559
560         utf32 const ec = c;
561         next_char();
562
563         switch (ec) {
564         case '"':  return '"';
565         case '\'': return '\'';
566         case '\\': return '\\';
567         case '?': return '\?';
568         case 'a': return '\a';
569         case 'b': return '\b';
570         case 'f': return '\f';
571         case 'n': return '\n';
572         case 'r': return '\r';
573         case 't': return '\t';
574         case 'v': return '\v';
575         case 'x':
576                 return parse_hex_sequence();
577         case '0':
578         case '1':
579         case '2':
580         case '3':
581         case '4':
582         case '5':
583         case '6':
584         case '7':
585                 return parse_octal_sequence(ec);
586         case EOF:
587                 parse_error("reached end of file while parsing escape sequence");
588                 return EOF;
589         /* \E is not documented, but handled, by GCC.  It is acceptable according
590          * to Â§6.11.4, whereas \e is not. */
591         case 'E':
592         case 'e':
593                 if (c_mode & _GNUC)
594                         return 27;   /* hopefully 27 is ALWAYS the code for ESCAPE */
595                 break;
596         case 'u':
597         case 'U':
598                 parse_error("universal character parsing not implemented yet");
599                 return EOF;
600         default:
601                 break;
602         }
603         /* Â§6.4.4.4:8 footnote 64 */
604         parse_error("unknown escape sequence");
605         return EOF;
606 }
607
608 /**
609  * Concatenate two strings.
610  */
611 string_t concat_strings(const string_t *const s1, const string_t *const s2)
612 {
613         const size_t len1 = s1->size - 1;
614         const size_t len2 = s2->size - 1;
615
616         char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
617         memcpy(concat, s1->begin, len1);
618         memcpy(concat + len1, s2->begin, len2 + 1);
619
620         return identify_string(concat, len1 + len2 + 1);
621 }
622
623 string_t make_string(const char *string)
624 {
625         size_t      len   = strlen(string) + 1;
626         char *const space = obstack_alloc(&symbol_obstack, len);
627         memcpy(space, string, len);
628
629         return identify_string(space, len);
630 }
631
632 /**
633  * Parse a string literal and set lexer_token.
634  */
635 static void parse_string_literal(void)
636 {
637         eat('"');
638
639         while (true) {
640                 switch (c) {
641                 case '\\': {
642                         utf32 const tc = parse_escape_sequence();
643                         if (tc >= 0x100) {
644                                 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
645                         }
646                         obstack_1grow(&symbol_obstack, tc);
647                         break;
648                 }
649
650                 case EOF:
651                         errorf(&lexer_token.base.source_position, "string has no end");
652                         goto end_of_string;
653
654                 case '"':
655                         next_char();
656                         goto end_of_string;
657
658                 default:
659                         obstack_grow_symbol(&symbol_obstack, c);
660                         next_char();
661                         break;
662                 }
663         }
664
665 end_of_string:
666
667         /* TODO: concatenate multiple strings separated by whitespace... */
668
669         /* add finishing 0 to the string */
670         obstack_1grow(&symbol_obstack, '\0');
671         const size_t  size   = (size_t)obstack_object_size(&symbol_obstack);
672         char         *string = obstack_finish(&symbol_obstack);
673
674         lexer_token.kind          = T_STRING_LITERAL;
675         lexer_token.string.string = identify_string(string, size);
676 }
677
678 /**
679  * Parse a wide character constant and set lexer_token.
680  */
681 static void parse_wide_character_constant(void)
682 {
683         eat('\'');
684
685         while (true) {
686                 switch (c) {
687                 case '\\': {
688                         const utf32 tc = parse_escape_sequence();
689                         obstack_grow_symbol(&symbol_obstack, tc);
690                         break;
691                 }
692
693                 MATCH_NEWLINE(
694                         parse_error("newline while parsing character constant");
695                         break;
696                 )
697
698                 case '\'':
699                         next_char();
700                         goto end_of_wide_char_constant;
701
702                 case EOF:
703                         errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
704                         goto end_of_wide_char_constant;
705
706                 default:
707                         obstack_grow_symbol(&symbol_obstack, c);
708                         next_char();
709                         break;
710                 }
711         }
712
713 end_of_wide_char_constant:;
714         obstack_1grow(&symbol_obstack, '\0');
715         size_t  size   = (size_t) obstack_object_size(&symbol_obstack) - 1;
716         char   *string = obstack_finish(&symbol_obstack);
717
718         lexer_token.kind          = T_WIDE_CHARACTER_CONSTANT;
719         lexer_token.string.string = identify_string(string, size);
720
721         if (size == 0) {
722                 errorf(&lexer_token.base.source_position, "empty character constant");
723         }
724 }
725
726 /**
727  * Parse a wide string literal and set lexer_token.
728  */
729 static void parse_wide_string_literal(void)
730 {
731         parse_string_literal();
732         if (lexer_token.kind == T_STRING_LITERAL)
733                 lexer_token.kind = T_WIDE_STRING_LITERAL;
734 }
735
736 /**
737  * Parse a character constant and set lexer_token.
738  */
739 static void parse_character_constant(void)
740 {
741         eat('\'');
742
743         while (true) {
744                 switch (c) {
745                 case '\\': {
746                         utf32 const tc = parse_escape_sequence();
747                         if (tc >= 0x100) {
748                                 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
749                         }
750                         obstack_1grow(&symbol_obstack, tc);
751                         break;
752                 }
753
754                 MATCH_NEWLINE(
755                         parse_error("newline while parsing character constant");
756                         break;
757                 )
758
759                 case '\'':
760                         next_char();
761                         goto end_of_char_constant;
762
763                 case EOF:
764                         errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
765                         goto end_of_char_constant;
766
767                 default:
768                         obstack_grow_symbol(&symbol_obstack, c);
769                         next_char();
770                         break;
771
772                 }
773         }
774
775 end_of_char_constant:;
776         obstack_1grow(&symbol_obstack, '\0');
777         const size_t        size   = (size_t)obstack_object_size(&symbol_obstack)-1;
778         char         *const string = obstack_finish(&symbol_obstack);
779
780         lexer_token.kind          = T_CHARACTER_CONSTANT;
781         lexer_token.string.string = identify_string(string, size);
782
783         if (size == 0) {
784                 errorf(&lexer_token.base.source_position, "empty character constant");
785         }
786 }
787
788 /**
789  * Skip a multiline comment.
790  */
791 static void skip_multiline_comment(void)
792 {
793         while (true) {
794                 switch (c) {
795                 case '/':
796                         next_char();
797                         if (c == '*') {
798                                 /* nested comment, warn here */
799                                 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
800                         }
801                         break;
802                 case '*':
803                         next_char();
804                         if (c == '/') {
805                                 next_char();
806                                 return;
807                         }
808                         break;
809
810                 MATCH_NEWLINE(break;)
811
812                 case EOF: {
813                         errorf(&lexer_token.base.source_position,
814                                "at end of file while looking for comment end");
815                         return;
816                 }
817
818                 default:
819                         next_char();
820                         break;
821                 }
822         }
823 }
824
825 /**
826  * Skip a single line comment.
827  */
828 static void skip_line_comment(void)
829 {
830         while (true) {
831                 switch (c) {
832                 case EOF:
833                         return;
834
835                 case '\n':
836                 case '\r':
837                         return;
838
839                 case '\\':
840                         next_char();
841                         if (c == '\n' || c == '\r') {
842                                 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
843                                 return;
844                         }
845                         break;
846
847                 default:
848                         next_char();
849                         break;
850                 }
851         }
852 }
853
854 /** The current preprocessor token. */
855 static token_t pp_token;
856
857 /**
858  * Read the next preprocessor token.
859  */
860 static inline void next_pp_token(void)
861 {
862         lexer_next_preprocessing_token();
863         pp_token = lexer_token;
864 }
865
866 /**
867  * Eat all preprocessor tokens until newline.
868  */
869 static void eat_until_newline(void)
870 {
871         while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
872                 next_pp_token();
873         }
874 }
875
876 /**
877  * Parse the line directive.
878  */
879 static void parse_line_directive(void)
880 {
881         if (pp_token.kind != T_INTEGER) {
882                 parse_error("expected integer");
883         } else {
884                 /* use offset -1 as this is about the next line */
885                 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
886                 next_pp_token();
887         }
888         if (pp_token.kind == T_STRING_LITERAL) {
889                 lexer_pos.input_name = pp_token.string.string.begin;
890                 lexer_pos.is_system_header = false;
891                 next_pp_token();
892
893                 /* attempt to parse numeric flags as outputted by gcc preprocessor */
894                 while (pp_token.kind == T_INTEGER) {
895                         /* flags:
896                          * 1 - indicates start of a new file
897                          * 2 - indicates return from a file
898                          * 3 - indicates system header
899                          * 4 - indicates implicit extern "C" in C++ mode
900                          *
901                          * currently we're only interested in "3"
902                          */
903                         if (streq(pp_token.number.number.begin, "3")) {
904                                 lexer_pos.is_system_header = true;
905                         }
906                         next_pp_token();
907                 }
908         }
909
910         eat_until_newline();
911 }
912
913 /**
914  * STDC pragmas.
915  */
916 typedef enum stdc_pragma_kind_t {
917         STDC_UNKNOWN,
918         STDC_FP_CONTRACT,
919         STDC_FENV_ACCESS,
920         STDC_CX_LIMITED_RANGE
921 } stdc_pragma_kind_t;
922
923 /**
924  * STDC pragma values.
925  */
926 typedef enum stdc_pragma_value_kind_t {
927         STDC_VALUE_UNKNOWN,
928         STDC_VALUE_ON,
929         STDC_VALUE_OFF,
930         STDC_VALUE_DEFAULT
931 } stdc_pragma_value_kind_t;
932
933 /**
934  * Parse a pragma directive.
935  */
936 static void parse_pragma(void)
937 {
938         bool unknown_pragma = true;
939
940         next_pp_token();
941         if (pp_token.kind != T_IDENTIFIER) {
942                 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
943                          "expected identifier after #pragma");
944                 eat_until_newline();
945                 return;
946         }
947
948         symbol_t *symbol = pp_token.identifier.symbol;
949         if (symbol->pp_ID == TP_STDC) {
950                 stdc_pragma_kind_t kind = STDC_UNKNOWN;
951                 /* a STDC pragma */
952                 if (c_mode & _C99) {
953                         next_pp_token();
954
955                         switch (pp_token.identifier.symbol->pp_ID) {
956                         case TP_FP_CONTRACT:
957                                 kind = STDC_FP_CONTRACT;
958                                 break;
959                         case TP_FENV_ACCESS:
960                                 kind = STDC_FENV_ACCESS;
961                                 break;
962                         case TP_CX_LIMITED_RANGE:
963                                 kind = STDC_CX_LIMITED_RANGE;
964                                 break;
965                         default:
966                                 break;
967                         }
968                         if (kind != STDC_UNKNOWN) {
969                                 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
970                                 next_pp_token();
971                                 switch (pp_token.identifier.symbol->pp_ID) {
972                                 case TP_ON:
973                                         value = STDC_VALUE_ON;
974                                         break;
975                                 case TP_OFF:
976                                         value = STDC_VALUE_OFF;
977                                         break;
978                                 case TP_DEFAULT:
979                                         value = STDC_VALUE_DEFAULT;
980                                         break;
981                                 default:
982                                         break;
983                                 }
984                                 if (value != STDC_VALUE_UNKNOWN) {
985                                         unknown_pragma = false;
986                                 } else {
987                                         errorf(&pp_token.base.source_position,
988                                                "bad STDC pragma argument");
989                                 }
990                         }
991                 }
992         } else {
993                 unknown_pragma = true;
994         }
995         eat_until_newline();
996         if (unknown_pragma) {
997                 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
998                          "encountered unknown #pragma");
999         }
1000 }
1001
1002 /**
1003  * Parse a preprocessor non-null directive.
1004  */
1005 static void parse_preprocessor_identifier(void)
1006 {
1007         assert(pp_token.kind == T_IDENTIFIER);
1008         symbol_t *symbol = pp_token.identifier.symbol;
1009
1010         switch (symbol->pp_ID) {
1011         case TP_line:
1012                 next_pp_token();
1013                 parse_line_directive();
1014                 break;
1015         case TP_pragma:
1016                 parse_pragma();
1017                 break;
1018         case TP_error:
1019                 /* TODO; output the rest of the line */
1020                 parse_error("#error directive");
1021                 break;
1022         }
1023 }
1024
1025 /**
1026  * Parse a preprocessor directive.
1027  */
1028 static void parse_preprocessor_directive(void)
1029 {
1030         next_pp_token();
1031
1032         switch (pp_token.kind) {
1033         case T_IDENTIFIER:
1034                 parse_preprocessor_identifier();
1035                 break;
1036         case T_INTEGER:
1037                 parse_line_directive();
1038                 break;
1039         case '\n':
1040                 /* NULL directive, see Â§6.10.7 */
1041                 break;
1042         default:
1043                 parse_error("invalid preprocessor directive");
1044                 eat_until_newline();
1045                 break;
1046         }
1047 }
1048
1049 #define MAYBE_PROLOG                                       \
1050                         next_char();                                   \
1051                         while (true) {                                 \
1052                                 switch (c) {
1053
1054 #define MAYBE(ch, set_type)                                \
1055                                 case ch:                                   \
1056                                         next_char();                           \
1057                                         lexer_token.kind = set_type;           \
1058                                         return;
1059
1060 /* must use this as last thing */
1061 #define MAYBE_MODE(ch, set_type, mode)                     \
1062                                 case ch:                                   \
1063                                         if (c_mode & mode) {                   \
1064                                                 next_char();                       \
1065                                                 lexer_token.kind = set_type;       \
1066                                                 return;                            \
1067                                         }                                      \
1068                                         /* fallthrough */
1069
1070 #define ELSE_CODE(code)                                    \
1071                                 default:                                   \
1072                                         code                                   \
1073                                         return;                                \
1074                                 }                                          \
1075                         } /* end of while (true) */                    \
1076
1077 #define ELSE(set_type)                                     \
1078                 ELSE_CODE(                                         \
1079                         lexer_token.kind = set_type;                   \
1080                 )
1081
1082 void lexer_next_preprocessing_token(void)
1083 {
1084         while (true) {
1085                 lexer_token.base.source_position = lexer_pos;
1086
1087                 switch (c) {
1088                 case ' ':
1089                 case '\t':
1090                         next_char();
1091                         break;
1092
1093                 MATCH_NEWLINE(
1094                         lexer_token.kind = '\n';
1095                         return;
1096                 )
1097
1098                 SYMBOL_CHARS
1099                         parse_symbol();
1100                         /* might be a wide string ( L"string" ) */
1101                         if (lexer_token.identifier.symbol == symbol_L) {
1102                                 switch (c) {
1103                                         case '"':  parse_wide_string_literal();     break;
1104                                         case '\'': parse_wide_character_constant(); break;
1105                                 }
1106                         }
1107                         return;
1108
1109                 DIGITS
1110                         parse_number();
1111                         return;
1112
1113                 case '"':
1114                         parse_string_literal();
1115                         return;
1116
1117                 case '\'':
1118                         parse_character_constant();
1119                         return;
1120
1121                 case '.':
1122                         MAYBE_PROLOG
1123                                 DIGITS
1124                                         put_back(c);
1125                                         c = '.';
1126                                         parse_number();
1127                                         return;
1128
1129                                 case '.':
1130                                         MAYBE_PROLOG
1131                                         MAYBE('.', T_DOTDOTDOT)
1132                                         ELSE_CODE(
1133                                                 put_back(c);
1134                                                 c = '.';
1135                                                 lexer_token.kind = '.';
1136                                         )
1137                         ELSE('.')
1138                 case '&':
1139                         MAYBE_PROLOG
1140                         MAYBE('&', T_ANDAND)
1141                         MAYBE('=', T_ANDEQUAL)
1142                         ELSE('&')
1143                 case '*':
1144                         MAYBE_PROLOG
1145                         MAYBE('=', T_ASTERISKEQUAL)
1146                         ELSE('*')
1147                 case '+':
1148                         MAYBE_PROLOG
1149                         MAYBE('+', T_PLUSPLUS)
1150                         MAYBE('=', T_PLUSEQUAL)
1151                         ELSE('+')
1152                 case '-':
1153                         MAYBE_PROLOG
1154                         MAYBE('>', T_MINUSGREATER)
1155                         MAYBE('-', T_MINUSMINUS)
1156                         MAYBE('=', T_MINUSEQUAL)
1157                         ELSE('-')
1158                 case '!':
1159                         MAYBE_PROLOG
1160                         MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1161                         ELSE('!')
1162                 case '/':
1163                         MAYBE_PROLOG
1164                         MAYBE('=', T_SLASHEQUAL)
1165                                 case '*':
1166                                         next_char();
1167                                         skip_multiline_comment();
1168                                         lexer_next_preprocessing_token();
1169                                         return;
1170                                 case '/':
1171                                         next_char();
1172                                         skip_line_comment();
1173                                         lexer_next_preprocessing_token();
1174                                         return;
1175                         ELSE('/')
1176                 case '%':
1177                         MAYBE_PROLOG
1178                         MAYBE('>', '}')
1179                         MAYBE('=', T_PERCENTEQUAL)
1180                                 case ':':
1181                                         MAYBE_PROLOG
1182                                                 case '%':
1183                                                         MAYBE_PROLOG
1184                                                         MAYBE(':', T_HASHHASH)
1185                                                         ELSE_CODE(
1186                                                                 put_back(c);
1187                                                                 c = '%';
1188                                                                 lexer_token.kind = '#';
1189                                                         )
1190                                         ELSE('#')
1191                         ELSE('%')
1192                 case '<':
1193                         MAYBE_PROLOG
1194                         MAYBE(':', '[')
1195                         MAYBE('%', '{')
1196                         MAYBE('=', T_LESSEQUAL)
1197                                 case '<':
1198                                         MAYBE_PROLOG
1199                                         MAYBE('=', T_LESSLESSEQUAL)
1200                                         ELSE(T_LESSLESS)
1201                         ELSE('<')
1202                 case '>':
1203                         MAYBE_PROLOG
1204                         MAYBE('=', T_GREATEREQUAL)
1205                                 case '>':
1206                                         MAYBE_PROLOG
1207                                         MAYBE('=', T_GREATERGREATEREQUAL)
1208                                         ELSE(T_GREATERGREATER)
1209                         ELSE('>')
1210                 case '^':
1211                         MAYBE_PROLOG
1212                         MAYBE('=', T_CARETEQUAL)
1213                         ELSE('^')
1214                 case '|':
1215                         MAYBE_PROLOG
1216                         MAYBE('=', T_PIPEEQUAL)
1217                         MAYBE('|', T_PIPEPIPE)
1218                         ELSE('|')
1219                 case ':':
1220                         MAYBE_PROLOG
1221                         MAYBE('>', ']')
1222                         MAYBE_MODE(':', T_COLONCOLON, _CXX)
1223                         ELSE(':')
1224                 case '=':
1225                         MAYBE_PROLOG
1226                         MAYBE('=', T_EQUALEQUAL)
1227                         ELSE('=')
1228                 case '#':
1229                         MAYBE_PROLOG
1230                         MAYBE('#', T_HASHHASH)
1231                         ELSE('#')
1232
1233                 case '?':
1234                 case '[':
1235                 case ']':
1236                 case '(':
1237                 case ')':
1238                 case '{':
1239                 case '}':
1240                 case '~':
1241                 case ';':
1242                 case ',':
1243                 case '\\':
1244                         lexer_token.kind = c;
1245                         next_char();
1246                         return;
1247
1248                 case EOF:
1249                         lexer_token.kind = T_EOF;
1250                         return;
1251
1252                 default:
1253 dollar_sign:
1254                         errorf(&lexer_pos, "unknown character '%c' found", c);
1255                         next_char();
1256                         break;
1257                 }
1258         }
1259 }
1260
1261 void lexer_next_token(void)
1262 {
1263         lexer_next_preprocessing_token();
1264
1265         while (lexer_token.kind == '\n') {
1266 newline_found:
1267                 lexer_next_preprocessing_token();
1268         }
1269
1270         if (lexer_token.kind == '#') {
1271                 parse_preprocessor_directive();
1272                 goto newline_found;
1273         }
1274 }
1275
1276 void init_lexer(void)
1277 {
1278         strset_init(&stringset);
1279         symbol_L = symbol_table_insert("L");
1280 }
1281
1282 static void input_error(unsigned delta_lines, unsigned delta_cols,
1283                         const char *message)
1284 {
1285         lexer_pos.lineno += delta_lines;
1286         lexer_pos.colno  += delta_cols;
1287         errorf(&lexer_pos, "%s", message);
1288 }
1289
1290 void lexer_switch_input(input_t *new_input, const char *input_name)
1291 {
1292         lexer_pos.lineno     = 0;
1293         lexer_pos.colno      = 0;
1294         lexer_pos.input_name = input_name;
1295
1296         set_input_error_callback(input_error);
1297         input  = new_input;
1298         bufpos = NULL;
1299         bufend = NULL;
1300
1301         /* place a virtual \n at the beginning so the lexer knows that we're
1302          * at the beginning of a line */
1303         c = '\n';
1304 }
1305
1306 void exit_lexer(void)
1307 {
1308         strset_destroy(&stringset);
1309 }
1310
1311 static __attribute__((unused))
1312 void dbg_pos(const source_position_t source_position)
1313 {
1314         fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1315                 source_position.lineno, (unsigned)source_position.colno);
1316         fflush(stdout);
1317 }