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