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