Implement a GCC extension: binary constants 0[bB][01]+.
[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 = 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 /**
636  * Concatenate two strings.
637  */
638 string_t concat_strings(const string_t *const s1, const string_t *const s2)
639 {
640         const size_t len1 = s1->size - 1;
641         const size_t len2 = s2->size - 1;
642
643         char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
644         memcpy(concat, s1->begin, len1);
645         memcpy(concat + len1, s2->begin, len2 + 1);
646
647         return identify_string(concat, len1 + len2 + 1);
648 }
649
650 string_t make_string(const char *string)
651 {
652         size_t      len   = strlen(string) + 1;
653         char *const space = obstack_alloc(&symbol_obstack, len);
654         memcpy(space, string, len);
655
656         return identify_string(space, len);
657 }
658
659 /**
660  * Parse a string literal and set lexer_token.
661  */
662 static void parse_string_literal(void)
663 {
664         eat('"');
665
666         while (true) {
667                 switch (c) {
668                 case '\\': {
669                         utf32 const tc = parse_escape_sequence();
670                         if (tc >= 0x100) {
671                                 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
672                         }
673                         obstack_1grow(&symbol_obstack, tc);
674                         break;
675                 }
676
677                 case EOF:
678                         errorf(&lexer_token.base.source_position, "string has no end");
679                         goto end_of_string;
680
681                 case '"':
682                         next_char();
683                         goto end_of_string;
684
685                 default:
686                         obstack_grow_symbol(&symbol_obstack, c);
687                         next_char();
688                         break;
689                 }
690         }
691
692 end_of_string:
693
694         /* TODO: concatenate multiple strings separated by whitespace... */
695
696         /* add finishing 0 to the string */
697         obstack_1grow(&symbol_obstack, '\0');
698         const size_t  size   = (size_t)obstack_object_size(&symbol_obstack);
699         char         *string = obstack_finish(&symbol_obstack);
700
701         lexer_token.kind          = T_STRING_LITERAL;
702         lexer_token.string.string = identify_string(string, size);
703 }
704
705 /**
706  * Parse a wide character constant and set lexer_token.
707  */
708 static void parse_wide_character_constant(void)
709 {
710         eat('\'');
711
712         while (true) {
713                 switch (c) {
714                 case '\\': {
715                         const utf32 tc = parse_escape_sequence();
716                         obstack_grow_symbol(&symbol_obstack, tc);
717                         break;
718                 }
719
720                 MATCH_NEWLINE(
721                         parse_error("newline while parsing character constant");
722                         break;
723                 )
724
725                 case '\'':
726                         next_char();
727                         goto end_of_wide_char_constant;
728
729                 case EOF:
730                         errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
731                         goto end_of_wide_char_constant;
732
733                 default:
734                         obstack_grow_symbol(&symbol_obstack, c);
735                         next_char();
736                         break;
737                 }
738         }
739
740 end_of_wide_char_constant:;
741         obstack_1grow(&symbol_obstack, '\0');
742         size_t  size   = (size_t) obstack_object_size(&symbol_obstack) - 1;
743         char   *string = obstack_finish(&symbol_obstack);
744
745         lexer_token.kind          = T_WIDE_CHARACTER_CONSTANT;
746         lexer_token.string.string = identify_string(string, size);
747
748         if (size == 0) {
749                 errorf(&lexer_token.base.source_position, "empty character constant");
750         }
751 }
752
753 /**
754  * Parse a wide string literal and set lexer_token.
755  */
756 static void parse_wide_string_literal(void)
757 {
758         parse_string_literal();
759         if (lexer_token.kind == T_STRING_LITERAL)
760                 lexer_token.kind = T_WIDE_STRING_LITERAL;
761 }
762
763 /**
764  * Parse a character constant and set lexer_token.
765  */
766 static void parse_character_constant(void)
767 {
768         eat('\'');
769
770         while (true) {
771                 switch (c) {
772                 case '\\': {
773                         utf32 const tc = parse_escape_sequence();
774                         if (tc >= 0x100) {
775                                 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
776                         }
777                         obstack_1grow(&symbol_obstack, tc);
778                         break;
779                 }
780
781                 MATCH_NEWLINE(
782                         parse_error("newline while parsing character constant");
783                         break;
784                 )
785
786                 case '\'':
787                         next_char();
788                         goto end_of_char_constant;
789
790                 case EOF:
791                         errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
792                         goto end_of_char_constant;
793
794                 default:
795                         obstack_grow_symbol(&symbol_obstack, c);
796                         next_char();
797                         break;
798
799                 }
800         }
801
802 end_of_char_constant:;
803         obstack_1grow(&symbol_obstack, '\0');
804         const size_t        size   = (size_t)obstack_object_size(&symbol_obstack)-1;
805         char         *const string = obstack_finish(&symbol_obstack);
806
807         lexer_token.kind          = T_CHARACTER_CONSTANT;
808         lexer_token.string.string = identify_string(string, size);
809
810         if (size == 0) {
811                 errorf(&lexer_token.base.source_position, "empty character constant");
812         }
813 }
814
815 /**
816  * Skip a multiline comment.
817  */
818 static void skip_multiline_comment(void)
819 {
820         while (true) {
821                 switch (c) {
822                 case '/':
823                         next_char();
824                         if (c == '*') {
825                                 /* nested comment, warn here */
826                                 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
827                         }
828                         break;
829                 case '*':
830                         next_char();
831                         if (c == '/') {
832                                 next_char();
833                                 return;
834                         }
835                         break;
836
837                 MATCH_NEWLINE(break;)
838
839                 case EOF: {
840                         errorf(&lexer_token.base.source_position,
841                                "at end of file while looking for comment end");
842                         return;
843                 }
844
845                 default:
846                         next_char();
847                         break;
848                 }
849         }
850 }
851
852 /**
853  * Skip a single line comment.
854  */
855 static void skip_line_comment(void)
856 {
857         while (true) {
858                 switch (c) {
859                 case EOF:
860                         return;
861
862                 case '\n':
863                 case '\r':
864                         return;
865
866                 case '\\':
867                         next_char();
868                         if (c == '\n' || c == '\r') {
869                                 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
870                                 return;
871                         }
872                         break;
873
874                 default:
875                         next_char();
876                         break;
877                 }
878         }
879 }
880
881 /** The current preprocessor token. */
882 static token_t pp_token;
883
884 /**
885  * Read the next preprocessor token.
886  */
887 static inline void next_pp_token(void)
888 {
889         lexer_next_preprocessing_token();
890         pp_token = lexer_token;
891 }
892
893 /**
894  * Eat all preprocessor tokens until newline.
895  */
896 static void eat_until_newline(void)
897 {
898         while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
899                 next_pp_token();
900         }
901 }
902
903 /**
904  * Parse the line directive.
905  */
906 static void parse_line_directive(void)
907 {
908         if (pp_token.kind != T_INTEGER) {
909                 parse_error("expected integer");
910         } else {
911                 /* use offset -1 as this is about the next line */
912                 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
913                 next_pp_token();
914         }
915         if (pp_token.kind == T_STRING_LITERAL) {
916                 lexer_pos.input_name = pp_token.string.string.begin;
917                 lexer_pos.is_system_header = false;
918                 next_pp_token();
919
920                 /* attempt to parse numeric flags as outputted by gcc preprocessor */
921                 while (pp_token.kind == T_INTEGER) {
922                         /* flags:
923                          * 1 - indicates start of a new file
924                          * 2 - indicates return from a file
925                          * 3 - indicates system header
926                          * 4 - indicates implicit extern "C" in C++ mode
927                          *
928                          * currently we're only interested in "3"
929                          */
930                         if (streq(pp_token.number.number.begin, "3")) {
931                                 lexer_pos.is_system_header = true;
932                         }
933                         next_pp_token();
934                 }
935         }
936
937         eat_until_newline();
938 }
939
940 /**
941  * STDC pragmas.
942  */
943 typedef enum stdc_pragma_kind_t {
944         STDC_UNKNOWN,
945         STDC_FP_CONTRACT,
946         STDC_FENV_ACCESS,
947         STDC_CX_LIMITED_RANGE
948 } stdc_pragma_kind_t;
949
950 /**
951  * STDC pragma values.
952  */
953 typedef enum stdc_pragma_value_kind_t {
954         STDC_VALUE_UNKNOWN,
955         STDC_VALUE_ON,
956         STDC_VALUE_OFF,
957         STDC_VALUE_DEFAULT
958 } stdc_pragma_value_kind_t;
959
960 /**
961  * Parse a pragma directive.
962  */
963 static void parse_pragma(void)
964 {
965         bool unknown_pragma = true;
966
967         next_pp_token();
968         if (pp_token.kind != T_IDENTIFIER) {
969                 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
970                          "expected identifier after #pragma");
971                 eat_until_newline();
972                 return;
973         }
974
975         symbol_t *symbol = pp_token.identifier.symbol;
976         if (symbol->pp_ID == TP_STDC) {
977                 stdc_pragma_kind_t kind = STDC_UNKNOWN;
978                 /* a STDC pragma */
979                 if (c_mode & _C99) {
980                         next_pp_token();
981
982                         switch (pp_token.identifier.symbol->pp_ID) {
983                         case TP_FP_CONTRACT:
984                                 kind = STDC_FP_CONTRACT;
985                                 break;
986                         case TP_FENV_ACCESS:
987                                 kind = STDC_FENV_ACCESS;
988                                 break;
989                         case TP_CX_LIMITED_RANGE:
990                                 kind = STDC_CX_LIMITED_RANGE;
991                                 break;
992                         default:
993                                 break;
994                         }
995                         if (kind != STDC_UNKNOWN) {
996                                 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
997                                 next_pp_token();
998                                 switch (pp_token.identifier.symbol->pp_ID) {
999                                 case TP_ON:
1000                                         value = STDC_VALUE_ON;
1001                                         break;
1002                                 case TP_OFF:
1003                                         value = STDC_VALUE_OFF;
1004                                         break;
1005                                 case TP_DEFAULT:
1006                                         value = STDC_VALUE_DEFAULT;
1007                                         break;
1008                                 default:
1009                                         break;
1010                                 }
1011                                 if (value != STDC_VALUE_UNKNOWN) {
1012                                         unknown_pragma = false;
1013                                 } else {
1014                                         errorf(&pp_token.base.source_position,
1015                                                "bad STDC pragma argument");
1016                                 }
1017                         }
1018                 }
1019         } else {
1020                 unknown_pragma = true;
1021         }
1022         eat_until_newline();
1023         if (unknown_pragma) {
1024                 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
1025                          "encountered unknown #pragma");
1026         }
1027 }
1028
1029 /**
1030  * Parse a preprocessor non-null directive.
1031  */
1032 static void parse_preprocessor_identifier(void)
1033 {
1034         assert(pp_token.kind == T_IDENTIFIER);
1035         symbol_t *symbol = pp_token.identifier.symbol;
1036
1037         switch (symbol->pp_ID) {
1038         case TP_line:
1039                 next_pp_token();
1040                 parse_line_directive();
1041                 break;
1042         case TP_pragma:
1043                 parse_pragma();
1044                 break;
1045         case TP_error:
1046                 /* TODO; output the rest of the line */
1047                 parse_error("#error directive");
1048                 break;
1049         }
1050 }
1051
1052 /**
1053  * Parse a preprocessor directive.
1054  */
1055 static void parse_preprocessor_directive(void)
1056 {
1057         next_pp_token();
1058
1059         switch (pp_token.kind) {
1060         case T_IDENTIFIER:
1061                 parse_preprocessor_identifier();
1062                 break;
1063         case T_INTEGER:
1064                 parse_line_directive();
1065                 break;
1066         case '\n':
1067                 /* NULL directive, see Â§6.10.7 */
1068                 break;
1069         default:
1070                 parse_error("invalid preprocessor directive");
1071                 eat_until_newline();
1072                 break;
1073         }
1074 }
1075
1076 #define MAYBE_PROLOG                                       \
1077                         next_char();                                   \
1078                         while (true) {                                 \
1079                                 switch (c) {
1080
1081 #define MAYBE(ch, set_type)                                \
1082                                 case ch:                                   \
1083                                         next_char();                           \
1084                                         lexer_token.kind = set_type;           \
1085                                         return;
1086
1087 /* must use this as last thing */
1088 #define MAYBE_MODE(ch, set_type, mode)                     \
1089                                 case ch:                                   \
1090                                         if (c_mode & mode) {                   \
1091                                                 next_char();                       \
1092                                                 lexer_token.kind = set_type;       \
1093                                                 return;                            \
1094                                         }                                      \
1095                                         /* fallthrough */
1096
1097 #define ELSE_CODE(code)                                    \
1098                                 default:                                   \
1099                                         code                                   \
1100                                         return;                                \
1101                                 }                                          \
1102                         } /* end of while (true) */                    \
1103
1104 #define ELSE(set_type)                                     \
1105                 ELSE_CODE(                                         \
1106                         lexer_token.kind = set_type;                   \
1107                 )
1108
1109 void lexer_next_preprocessing_token(void)
1110 {
1111         while (true) {
1112                 lexer_token.base.source_position = lexer_pos;
1113
1114                 switch (c) {
1115                 case ' ':
1116                 case '\t':
1117                         next_char();
1118                         break;
1119
1120                 MATCH_NEWLINE(
1121                         lexer_token.kind = '\n';
1122                         return;
1123                 )
1124
1125                 SYMBOL_CHARS
1126                         parse_symbol();
1127                         /* might be a wide string ( L"string" ) */
1128                         if (lexer_token.identifier.symbol == symbol_L) {
1129                                 switch (c) {
1130                                         case '"':  parse_wide_string_literal();     break;
1131                                         case '\'': parse_wide_character_constant(); break;
1132                                 }
1133                         }
1134                         return;
1135
1136                 DIGITS
1137                         parse_number();
1138                         return;
1139
1140                 case '"':
1141                         parse_string_literal();
1142                         return;
1143
1144                 case '\'':
1145                         parse_character_constant();
1146                         return;
1147
1148                 case '.':
1149                         MAYBE_PROLOG
1150                                 DIGITS
1151                                         put_back(c);
1152                                         c = '.';
1153                                         parse_number();
1154                                         return;
1155
1156                                 case '.':
1157                                         MAYBE_PROLOG
1158                                         MAYBE('.', T_DOTDOTDOT)
1159                                         ELSE_CODE(
1160                                                 put_back(c);
1161                                                 c = '.';
1162                                                 lexer_token.kind = '.';
1163                                         )
1164                         ELSE('.')
1165                 case '&':
1166                         MAYBE_PROLOG
1167                         MAYBE('&', T_ANDAND)
1168                         MAYBE('=', T_ANDEQUAL)
1169                         ELSE('&')
1170                 case '*':
1171                         MAYBE_PROLOG
1172                         MAYBE('=', T_ASTERISKEQUAL)
1173                         ELSE('*')
1174                 case '+':
1175                         MAYBE_PROLOG
1176                         MAYBE('+', T_PLUSPLUS)
1177                         MAYBE('=', T_PLUSEQUAL)
1178                         ELSE('+')
1179                 case '-':
1180                         MAYBE_PROLOG
1181                         MAYBE('>', T_MINUSGREATER)
1182                         MAYBE('-', T_MINUSMINUS)
1183                         MAYBE('=', T_MINUSEQUAL)
1184                         ELSE('-')
1185                 case '!':
1186                         MAYBE_PROLOG
1187                         MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1188                         ELSE('!')
1189                 case '/':
1190                         MAYBE_PROLOG
1191                         MAYBE('=', T_SLASHEQUAL)
1192                                 case '*':
1193                                         next_char();
1194                                         skip_multiline_comment();
1195                                         lexer_next_preprocessing_token();
1196                                         return;
1197                                 case '/':
1198                                         next_char();
1199                                         skip_line_comment();
1200                                         lexer_next_preprocessing_token();
1201                                         return;
1202                         ELSE('/')
1203                 case '%':
1204                         MAYBE_PROLOG
1205                         MAYBE('>', '}')
1206                         MAYBE('=', T_PERCENTEQUAL)
1207                                 case ':':
1208                                         MAYBE_PROLOG
1209                                                 case '%':
1210                                                         MAYBE_PROLOG
1211                                                         MAYBE(':', T_HASHHASH)
1212                                                         ELSE_CODE(
1213                                                                 put_back(c);
1214                                                                 c = '%';
1215                                                                 lexer_token.kind = '#';
1216                                                         )
1217                                         ELSE('#')
1218                         ELSE('%')
1219                 case '<':
1220                         MAYBE_PROLOG
1221                         MAYBE(':', '[')
1222                         MAYBE('%', '{')
1223                         MAYBE('=', T_LESSEQUAL)
1224                                 case '<':
1225                                         MAYBE_PROLOG
1226                                         MAYBE('=', T_LESSLESSEQUAL)
1227                                         ELSE(T_LESSLESS)
1228                         ELSE('<')
1229                 case '>':
1230                         MAYBE_PROLOG
1231                         MAYBE('=', T_GREATEREQUAL)
1232                                 case '>':
1233                                         MAYBE_PROLOG
1234                                         MAYBE('=', T_GREATERGREATEREQUAL)
1235                                         ELSE(T_GREATERGREATER)
1236                         ELSE('>')
1237                 case '^':
1238                         MAYBE_PROLOG
1239                         MAYBE('=', T_CARETEQUAL)
1240                         ELSE('^')
1241                 case '|':
1242                         MAYBE_PROLOG
1243                         MAYBE('=', T_PIPEEQUAL)
1244                         MAYBE('|', T_PIPEPIPE)
1245                         ELSE('|')
1246                 case ':':
1247                         MAYBE_PROLOG
1248                         MAYBE('>', ']')
1249                         MAYBE_MODE(':', T_COLONCOLON, _CXX)
1250                         ELSE(':')
1251                 case '=':
1252                         MAYBE_PROLOG
1253                         MAYBE('=', T_EQUALEQUAL)
1254                         ELSE('=')
1255                 case '#':
1256                         MAYBE_PROLOG
1257                         MAYBE('#', T_HASHHASH)
1258                         ELSE('#')
1259
1260                 case '?':
1261                 case '[':
1262                 case ']':
1263                 case '(':
1264                 case ')':
1265                 case '{':
1266                 case '}':
1267                 case '~':
1268                 case ';':
1269                 case ',':
1270                 case '\\':
1271                         lexer_token.kind = c;
1272                         next_char();
1273                         return;
1274
1275                 case EOF:
1276                         lexer_token.kind = T_EOF;
1277                         return;
1278
1279                 default:
1280 dollar_sign:
1281                         errorf(&lexer_pos, "unknown character '%c' found", c);
1282                         next_char();
1283                         break;
1284                 }
1285         }
1286 }
1287
1288 void lexer_next_token(void)
1289 {
1290         lexer_next_preprocessing_token();
1291
1292         while (lexer_token.kind == '\n') {
1293 newline_found:
1294                 lexer_next_preprocessing_token();
1295         }
1296
1297         if (lexer_token.kind == '#') {
1298                 parse_preprocessor_directive();
1299                 goto newline_found;
1300         }
1301 }
1302
1303 void init_lexer(void)
1304 {
1305         strset_init(&stringset);
1306         symbol_L = symbol_table_insert("L");
1307 }
1308
1309 static void input_error(unsigned delta_lines, unsigned delta_cols,
1310                         const char *message)
1311 {
1312         lexer_pos.lineno += delta_lines;
1313         lexer_pos.colno  += delta_cols;
1314         errorf(&lexer_pos, "%s", message);
1315 }
1316
1317 void lexer_switch_input(input_t *new_input, const char *input_name)
1318 {
1319         lexer_pos.lineno     = 0;
1320         lexer_pos.colno      = 0;
1321         lexer_pos.input_name = input_name;
1322
1323         set_input_error_callback(input_error);
1324         input  = new_input;
1325         bufpos = NULL;
1326         bufend = NULL;
1327
1328         /* place a virtual \n at the beginning so the lexer knows that we're
1329          * at the beginning of a line */
1330         c = '\n';
1331 }
1332
1333 void exit_lexer(void)
1334 {
1335         strset_destroy(&stringset);
1336 }
1337
1338 static __attribute__((unused))
1339 void dbg_pos(const source_position_t source_position)
1340 {
1341         fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1342                 source_position.lineno, (unsigned)source_position.colno);
1343         fflush(stdout);
1344 }