- BugFix: function types have not size 0, so condition must be changed
[cparser] / lexer.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 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 "diagnostic.h"
23 #include "lexer.h"
24 #include "symbol_t.h"
25 #include "token_t.h"
26 #include "symbol_table_t.h"
27 #include "adt/error.h"
28 #include "adt/strset.h"
29 #include "adt/util.h"
30 #include "types.h"
31 #include "type_t.h"
32 #include "target_architecture.h"
33 #include "parser.h"
34 #include "warning.h"
35 #include "lang_features.h"
36
37 #include <assert.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <stdbool.h>
41 #include <ctype.h>
42
43 //#define DEBUG_CHARS
44 #define MAX_PUTBACK 3
45
46 #ifdef _WIN32
47 /* No strtold on windows and no replacement yet */
48 #define strtold(s, e) strtod(s, e)
49 #endif
50
51 static int         c;
52 token_t            lexer_token;
53 symbol_t          *symbol_L;
54 static FILE       *input;
55 static char        buf[1024 + MAX_PUTBACK];
56 static const char *bufend;
57 static const char *bufpos;
58 static strset_t    stringset;
59 bool               allow_dollar_in_symbol = true;
60
61 /**
62  * Prints a parse error message at the current token.
63  *
64  * @param msg   the error message
65  */
66 static void parse_error(const char *msg)
67 {
68         errorf(&lexer_token.source_position,  "%s", msg);
69 }
70
71 /**
72  * Prints an internal error message at the current token.
73  *
74  * @param msg   the error message
75  */
76 static NORETURN internal_error(const char *msg)
77 {
78         internal_errorf(&lexer_token.source_position,  "%s", msg);
79 }
80
81 static inline void next_real_char(void)
82 {
83         assert(bufpos <= bufend);
84         if (bufpos >= bufend) {
85                 if (input == NULL) {
86                         c = EOF;
87                         return;
88                 }
89
90                 size_t s = fread(buf + MAX_PUTBACK, 1, sizeof(buf) - MAX_PUTBACK,
91                                  input);
92                 if(s == 0) {
93                         c = EOF;
94                         return;
95                 }
96                 bufpos = buf + MAX_PUTBACK;
97                 bufend = buf + MAX_PUTBACK + s;
98         }
99         c = *bufpos++;
100 }
101
102 /**
103  * Put a character back into the buffer.
104  *
105  * @param pc  the character to put back
106  */
107 static inline void put_back(int pc)
108 {
109         assert(bufpos > buf);
110         *(--bufpos - buf + buf) = (char) pc;
111
112 #ifdef DEBUG_CHARS
113         printf("putback '%c'\n", pc);
114 #endif
115 }
116
117 static inline void next_char(void);
118
119 #define MATCH_NEWLINE(code)                   \
120         case '\r':                                \
121                 next_char();                          \
122                 if(c == '\n') {                       \
123                         next_char();                      \
124                 }                                     \
125                 lexer_token.source_position.linenr++; \
126                 code                                  \
127         case '\n':                                \
128                 next_char();                          \
129                 lexer_token.source_position.linenr++; \
130                 code
131
132 #define eat(c_type)  do { assert(c == c_type); next_char(); } while(0)
133
134 static void maybe_concat_lines(void)
135 {
136         eat('\\');
137
138         switch(c) {
139         MATCH_NEWLINE(return;)
140
141         default:
142                 break;
143         }
144
145         put_back(c);
146         c = '\\';
147 }
148
149 /**
150  * Set c to the next input character, ie.
151  * after expanding trigraphs.
152  */
153 static inline void next_char(void)
154 {
155         next_real_char();
156
157         /* filter trigraphs */
158         if(UNLIKELY(c == '\\')) {
159                 maybe_concat_lines();
160                 goto end_of_next_char;
161         }
162
163         if(LIKELY(c != '?'))
164                 goto end_of_next_char;
165
166         next_real_char();
167         if(LIKELY(c != '?')) {
168                 put_back(c);
169                 c = '?';
170                 goto end_of_next_char;
171         }
172
173         next_real_char();
174         switch(c) {
175         case '=': c = '#'; break;
176         case '(': c = '['; break;
177         case '/': c = '\\'; maybe_concat_lines(); break;
178         case ')': c = ']'; break;
179         case '\'': c = '^'; break;
180         case '<': c = '{'; break;
181         case '!': c = '|'; break;
182         case '>': c = '}'; break;
183         case '-': c = '~'; break;
184         default:
185                 put_back(c);
186                 put_back('?');
187                 c = '?';
188                 break;
189         }
190
191 end_of_next_char:;
192 #ifdef DEBUG_CHARS
193         printf("nchar '%c'\n", c);
194 #endif
195 }
196
197 #define SYMBOL_CHARS  \
198         case '$': if (!allow_dollar_in_symbol) goto dollar_sign; \
199         case 'a':         \
200         case 'b':         \
201         case 'c':         \
202         case 'd':         \
203         case 'e':         \
204         case 'f':         \
205         case 'g':         \
206         case 'h':         \
207         case 'i':         \
208         case 'j':         \
209         case 'k':         \
210         case 'l':         \
211         case 'm':         \
212         case 'n':         \
213         case 'o':         \
214         case 'p':         \
215         case 'q':         \
216         case 'r':         \
217         case 's':         \
218         case 't':         \
219         case 'u':         \
220         case 'v':         \
221         case 'w':         \
222         case 'x':         \
223         case 'y':         \
224         case 'z':         \
225         case 'A':         \
226         case 'B':         \
227         case 'C':         \
228         case 'D':         \
229         case 'E':         \
230         case 'F':         \
231         case 'G':         \
232         case 'H':         \
233         case 'I':         \
234         case 'J':         \
235         case 'K':         \
236         case 'L':         \
237         case 'M':         \
238         case 'N':         \
239         case 'O':         \
240         case 'P':         \
241         case 'Q':         \
242         case 'R':         \
243         case 'S':         \
244         case 'T':         \
245         case 'U':         \
246         case 'V':         \
247         case 'W':         \
248         case 'X':         \
249         case 'Y':         \
250         case 'Z':         \
251         case '_':
252
253 #define DIGITS        \
254         case '0':         \
255         case '1':         \
256         case '2':         \
257         case '3':         \
258         case '4':         \
259         case '5':         \
260         case '6':         \
261         case '7':         \
262         case '8':         \
263         case '9':
264
265 /**
266  * Read a symbol from the input and build
267  * the lexer_token.
268  */
269 static void parse_symbol(void)
270 {
271         symbol_t *symbol;
272         char     *string;
273
274         obstack_1grow(&symbol_obstack, (char) c);
275         next_char();
276
277         while(1) {
278                 switch(c) {
279                 DIGITS
280                 SYMBOL_CHARS
281                         obstack_1grow(&symbol_obstack, (char) c);
282                         next_char();
283                         break;
284
285                 default:
286 dollar_sign:
287                         goto end_symbol;
288                 }
289         }
290
291 end_symbol:
292         obstack_1grow(&symbol_obstack, '\0');
293
294         string = obstack_finish(&symbol_obstack);
295         symbol = symbol_table_insert(string);
296
297         lexer_token.type     = symbol->ID;
298         lexer_token.v.symbol = symbol;
299
300         if(symbol->string != string) {
301                 obstack_free(&symbol_obstack, string);
302         }
303 }
304
305 static void parse_integer_suffix(bool is_oct_hex)
306 {
307         bool is_unsigned  = false;
308         bool min_long     = false;
309         bool min_longlong = false;
310
311         if(c == 'U' || c == 'u') {
312                 is_unsigned = true;
313                 next_char();
314                 if(c == 'L' || c == 'l') {
315                         min_long = true;
316                         next_char();
317                         if(c == 'L' || c == 'l') {
318                                 min_longlong = true;
319                                 next_char();
320                         }
321                 }
322         } else if(c == 'l' || c == 'L') {
323                 min_long = true;
324                 next_char();
325                 if(c == 'l' || c == 'L') {
326                         min_longlong = true;
327                         next_char();
328                         if(c == 'u' || c == 'U') {
329                                 is_unsigned = true;
330                                 next_char();
331                         }
332                 } else if(c == 'u' || c == 'U') {
333                         is_unsigned = true;
334                         next_char();
335                         lexer_token.datatype = type_unsigned_long;
336                 }
337         }
338
339         if(!is_unsigned) {
340                 long long v = lexer_token.v.intvalue;
341                 if(!min_long) {
342                         if(v >= TARGET_INT_MIN && v <= TARGET_INT_MAX) {
343                                 lexer_token.datatype = type_int;
344                                 return;
345                         } else if(is_oct_hex && v >= 0 && v <= TARGET_UINT_MAX) {
346                                 lexer_token.datatype = type_unsigned_int;
347                                 return;
348                         }
349                 }
350                 if(!min_longlong) {
351                         if(v >= TARGET_LONG_MIN && v <= TARGET_LONG_MAX) {
352                                 lexer_token.datatype = type_long;
353                                 return;
354                         } else if(is_oct_hex && v >= 0 && (unsigned long long)v <= (unsigned long long)TARGET_ULONG_MAX) {
355                                 lexer_token.datatype = type_unsigned_long;
356                                 return;
357                         }
358                 }
359                 unsigned long long uv = (unsigned long long) v;
360                 if(is_oct_hex && uv > (unsigned long long) TARGET_LONGLONG_MAX) {
361                         lexer_token.datatype = type_unsigned_long_long;
362                         return;
363                 }
364
365                 lexer_token.datatype = type_long_long;
366         } else {
367                 unsigned long long v = (unsigned long long) lexer_token.v.intvalue;
368                 if(!min_long && v <= TARGET_UINT_MAX) {
369                         lexer_token.datatype = type_unsigned_int;
370                         return;
371                 }
372                 if(!min_longlong && v <= TARGET_ULONG_MAX) {
373                         lexer_token.datatype = type_unsigned_long;
374                         return;
375                 }
376                 lexer_token.datatype = type_unsigned_long_long;
377         }
378 }
379
380 static void parse_floating_suffix(void)
381 {
382         switch(c) {
383         /* TODO: do something useful with the suffixes... */
384         case 'f':
385         case 'F':
386                 next_char();
387                 lexer_token.datatype = type_float;
388                 break;
389         case 'l':
390         case 'L':
391                 next_char();
392                 lexer_token.datatype = type_long_double;
393                 break;
394         default:
395                 lexer_token.datatype = type_double;
396                 break;
397         }
398 }
399
400 /**
401  * A replacement for strtoull. Only those parts needed for
402  * our parser are implemented.
403  */
404 static unsigned long long parse_int_string(const char *s, const char **endptr, int base) {
405         unsigned long long v = 0;
406
407         switch (base) {
408         case 16:
409                 for (;; ++s) {
410                         /* check for overrun */
411                         if (v >= 0x1000000000000000ULL)
412                                 break;
413                         switch (tolower(*s)) {
414                         case '0': v <<= 4; break;
415                         case '1': v <<= 4; v |= 0x1; break;
416                         case '2': v <<= 4; v |= 0x2; break;
417                         case '3': v <<= 4; v |= 0x3; break;
418                         case '4': v <<= 4; v |= 0x4; break;
419                         case '5': v <<= 4; v |= 0x5; break;
420                         case '6': v <<= 4; v |= 0x6; break;
421                         case '7': v <<= 4; v |= 0x7; break;
422                         case '8': v <<= 4; v |= 0x8; break;
423                         case '9': v <<= 4; v |= 0x9; break;
424                         case 'a': v <<= 4; v |= 0xa; break;
425                         case 'b': v <<= 4; v |= 0xb; break;
426                         case 'c': v <<= 4; v |= 0xc; break;
427                         case 'd': v <<= 4; v |= 0xd; break;
428                         case 'e': v <<= 4; v |= 0xe; break;
429                         case 'f': v <<= 4; v |= 0xf; break;
430                         default:
431                                 goto end;
432                         }
433                 }
434                 break;
435         case 8:
436                 for (;; ++s) {
437                         /* check for overrun */
438                         if (v >= 0x2000000000000000ULL)
439                                 break;
440                         switch (tolower(*s)) {
441                         case '0': v <<= 3; break;
442                         case '1': v <<= 3; v |= 1; break;
443                         case '2': v <<= 3; v |= 2; break;
444                         case '3': v <<= 3; v |= 3; break;
445                         case '4': v <<= 3; v |= 4; break;
446                         case '5': v <<= 3; v |= 5; break;
447                         case '6': v <<= 3; v |= 6; break;
448                         case '7': v <<= 3; v |= 7; break;
449                         default:
450                                 goto end;
451                         }
452                 }
453                 break;
454         case 10:
455                 for (;; ++s) {
456                         /* check for overrun */
457                         if (v > 0x1999999999999999ULL)
458                                 break;
459                         switch (tolower(*s)) {
460                         case '0': v *= 10; break;
461                         case '1': v *= 10; v += 1; break;
462                         case '2': v *= 10; v += 2; break;
463                         case '3': v *= 10; v += 3; break;
464                         case '4': v *= 10; v += 4; break;
465                         case '5': v *= 10; v += 5; break;
466                         case '6': v *= 10; v += 6; break;
467                         case '7': v *= 10; v += 7; break;
468                         case '8': v *= 10; v += 8; break;
469                         case '9': v *= 10; v += 9; break;
470                         default:
471                                 goto end;
472                         }
473                 }
474                 break;
475         default:
476                 assert(0);
477                 break;
478         }
479 end:
480         *endptr = s;
481         return v;
482 }
483
484 /**
485  * Parses a hex number including hex floats and set the
486  * lexer_token.
487  */
488 static void parse_number_hex(void)
489 {
490         assert(c == 'x' || c == 'X');
491         next_char();
492
493         while(isxdigit(c)) {
494                 obstack_1grow(&symbol_obstack, (char) c);
495                 next_char();
496         }
497         obstack_1grow(&symbol_obstack, '\0');
498         char *string = obstack_finish(&symbol_obstack);
499
500         if(c == '.' || c == 'p' || c == 'P') {
501                 next_char();
502                 internal_error("Hex floating point numbers not implemented yet");
503         }
504         if(*string == '\0') {
505                 parse_error("invalid hex number");
506                 lexer_token.type = T_ERROR;
507         }
508
509         const char *endptr;
510         lexer_token.type       = T_INTEGER;
511         lexer_token.v.intvalue = parse_int_string(string, &endptr, 16);
512         if(*endptr != '\0') {
513                 parse_error("hex number literal too long");
514         }
515
516         obstack_free(&symbol_obstack, string);
517         parse_integer_suffix(true);
518 }
519
520 /**
521  * Returns true if the given char is a octal digit.
522  *
523  * @param char  the character to check
524  */
525 static inline bool is_octal_digit(int chr)
526 {
527         switch(chr) {
528         case '0':
529         case '1':
530         case '2':
531         case '3':
532         case '4':
533         case '5':
534         case '6':
535         case '7':
536                 return true;
537         default:
538                 return false;
539         }
540 }
541
542 /**
543  * Parses a octal number and set the lexer_token.
544  */
545 static void parse_number_oct(void)
546 {
547         while(is_octal_digit(c)) {
548                 obstack_1grow(&symbol_obstack, (char) c);
549                 next_char();
550         }
551         obstack_1grow(&symbol_obstack, '\0');
552         char *string = obstack_finish(&symbol_obstack);
553
554         const char *endptr;
555         lexer_token.type       = T_INTEGER;
556         lexer_token.v.intvalue = parse_int_string(string, &endptr, 8);
557         if(*endptr != '\0') {
558                 parse_error("octal number literal too long");
559         }
560
561         obstack_free(&symbol_obstack, string);
562         parse_integer_suffix(true);
563 }
564
565 /**
566  * Parses a decimal including float number and set the
567  * lexer_token.
568  */
569 static void parse_number_dec(void)
570 {
571         bool is_float = false;
572         while(isdigit(c)) {
573                 obstack_1grow(&symbol_obstack, (char) c);
574                 next_char();
575         }
576
577         if(c == '.') {
578                 obstack_1grow(&symbol_obstack, '.');
579                 next_char();
580
581                 while(isdigit(c)) {
582                         obstack_1grow(&symbol_obstack, (char) c);
583                         next_char();
584                 }
585                 is_float = true;
586         }
587         if(c == 'e' || c == 'E') {
588                 obstack_1grow(&symbol_obstack, 'e');
589                 next_char();
590
591                 if(c == '-' || c == '+') {
592                         obstack_1grow(&symbol_obstack, (char) c);
593                         next_char();
594                 }
595
596                 while(isdigit(c)) {
597                         obstack_1grow(&symbol_obstack, (char) c);
598                         next_char();
599                 }
600                 is_float = true;
601         }
602
603         obstack_1grow(&symbol_obstack, '\0');
604         char *string = obstack_finish(&symbol_obstack);
605
606         if(is_float) {
607                 char *endptr;
608                 lexer_token.type         = T_FLOATINGPOINT;
609                 lexer_token.v.floatvalue = strtold(string, &endptr);
610
611                 if(*endptr != '\0') {
612                         parse_error("invalid number literal");
613                 }
614
615                 parse_floating_suffix();
616         } else {
617                 const char *endptr;
618                 lexer_token.type       = T_INTEGER;
619                 lexer_token.v.intvalue = parse_int_string(string, &endptr, 10);
620
621                 if(*endptr != '\0') {
622                         parse_error("invalid number literal");
623                 }
624
625                 parse_integer_suffix(false);
626         }
627         obstack_free(&symbol_obstack, string);
628 }
629
630 /**
631  * Parses a number and sets the lexer_token.
632  */
633 static void parse_number(void)
634 {
635         if (c == '0') {
636                 next_char();
637                 switch (c) {
638                         case 'X':
639                         case 'x':
640                                 parse_number_hex();
641                                 break;
642                         case '0':
643                         case '1':
644                         case '2':
645                         case '3':
646                         case '4':
647                         case '5':
648                         case '6':
649                         case '7':
650                                 parse_number_oct();
651                                 break;
652                         case '8':
653                         case '9':
654                                 next_char();
655                                 parse_error("invalid octal number");
656                                 lexer_token.type = T_ERROR;
657                                 return;
658                         case '.':
659                         case 'e':
660                         case 'E':
661                         default:
662                                 obstack_1grow(&symbol_obstack, '0');
663                                 parse_number_dec();
664                                 return;
665                 }
666         } else {
667                 parse_number_dec();
668         }
669 }
670
671 /**
672  * Returns the value of a digit.
673  * The only portable way to do it ...
674  */
675 static int digit_value(int digit) {
676         switch (digit) {
677         case '0': return 0;
678         case '1': return 1;
679         case '2': return 2;
680         case '3': return 3;
681         case '4': return 4;
682         case '5': return 5;
683         case '6': return 6;
684         case '7': return 7;
685         case '8': return 8;
686         case '9': return 9;
687         case 'a':
688         case 'A': return 10;
689         case 'b':
690         case 'B': return 11;
691         case 'c':
692         case 'C': return 12;
693         case 'd':
694         case 'D': return 13;
695         case 'e':
696         case 'E': return 14;
697         case 'f':
698         case 'F': return 15;
699         default:
700                 internal_error("wrong character given");
701         }
702 }
703
704 /**
705  * Parses an octal character sequence.
706  *
707  * @param first_digit  the already read first digit
708  */
709 static int parse_octal_sequence(const int first_digit)
710 {
711         assert(is_octal_digit(first_digit));
712         int value = digit_value(first_digit);
713         if (!is_octal_digit(c)) return value;
714         value = 8 * value + digit_value(c);
715         next_char();
716         if (!is_octal_digit(c)) return value;
717         value = 8 * value + digit_value(c);
718         next_char();
719
720         if(char_is_signed) {
721                 return (signed char) value;
722         } else {
723                 return (unsigned char) value;
724         }
725 }
726
727 /**
728  * Parses a hex character sequence.
729  */
730 static int parse_hex_sequence(void)
731 {
732         int value = 0;
733         while(isxdigit(c)) {
734                 value = 16 * value + digit_value(c);
735                 next_char();
736         }
737
738         if(char_is_signed) {
739                 return (signed char) value;
740         } else {
741                 return (unsigned char) value;
742         }
743 }
744
745 /**
746  * Parse an escape sequence.
747  */
748 static int parse_escape_sequence(void)
749 {
750         eat('\\');
751
752         int ec = c;
753         next_char();
754
755         switch(ec) {
756         case '"':  return '"';
757         case '\'': return '\'';
758         case '\\': return '\\';
759         case '?': return '\?';
760         case 'a': return '\a';
761         case 'b': return '\b';
762         case 'f': return '\f';
763         case 'n': return '\n';
764         case 'r': return '\r';
765         case 't': return '\t';
766         case 'v': return '\v';
767         case 'x':
768                 return parse_hex_sequence();
769         case '0':
770         case '1':
771         case '2':
772         case '3':
773         case '4':
774         case '5':
775         case '6':
776         case '7':
777                 return parse_octal_sequence(ec);
778         case EOF:
779                 parse_error("reached end of file while parsing escape sequence");
780                 return EOF;
781         default:
782                 parse_error("unknown escape sequence");
783                 return EOF;
784         }
785 }
786
787 /**
788  * Concatenate two strings.
789  */
790 string_t concat_strings(const string_t *const s1, const string_t *const s2)
791 {
792         const size_t len1 = s1->size - 1;
793         const size_t len2 = s2->size - 1;
794
795         char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
796         memcpy(concat, s1->begin, len1);
797         memcpy(concat + len1, s2->begin, len2 + 1);
798
799 #if 0 /* TODO hash */
800         const char *result = strset_insert(&stringset, concat);
801         if(result != concat) {
802                 obstack_free(&symbol_obstack, concat);
803         }
804
805         return result;
806 #else
807         return (string_t){ concat, len1 + len2 + 1 };
808 #endif
809 }
810
811 /**
812  * Concatenate a string and a wide string.
813  */
814 wide_string_t concat_string_wide_string(const string_t *const s1, const wide_string_t *const s2)
815 {
816         const size_t len1 = s1->size - 1;
817         const size_t len2 = s2->size - 1;
818
819         wchar_rep_t *const concat = obstack_alloc(&symbol_obstack, (len1 + len2 + 1) * sizeof(*concat));
820         const char *const src = s1->begin;
821         for (size_t i = 0; i != len1; ++i) {
822                 concat[i] = src[i];
823         }
824         memcpy(concat + len1, s2->begin, (len2 + 1) * sizeof(*concat));
825
826         return (wide_string_t){ concat, len1 + len2 + 1 };
827 }
828
829 /**
830  * Concatenate two wide strings.
831  */
832 wide_string_t concat_wide_strings(const wide_string_t *const s1, const wide_string_t *const s2)
833 {
834         const size_t len1 = s1->size - 1;
835         const size_t len2 = s2->size - 1;
836
837         wchar_rep_t *const concat = obstack_alloc(&symbol_obstack, (len1 + len2 + 1) * sizeof(*concat));
838         memcpy(concat,        s1->begin, len1       * sizeof(*concat));
839         memcpy(concat + len1, s2->begin, (len2 + 1) * sizeof(*concat));
840
841         return (wide_string_t){ concat, len1 + len2 + 1 };
842 }
843
844 /**
845  * Concatenate a wide string and a string.
846  */
847 wide_string_t concat_wide_string_string(const wide_string_t *const s1, const string_t *const s2)
848 {
849         const size_t len1 = s1->size - 1;
850         const size_t len2 = s2->size - 1;
851
852         wchar_rep_t *const concat = obstack_alloc(&symbol_obstack, (len1 + len2 + 1) * sizeof(*concat));
853         memcpy(concat, s1->begin, len1 * sizeof(*concat));
854         const char *const src = s2->begin;
855         for (size_t i = 0; i != len2 + 1; ++i) {
856                 concat[i] = src[i];
857         }
858
859         return (wide_string_t){ concat, len1 + len2 + 1 };
860 }
861
862 /**
863  * Parse a string literal and set lexer_token.
864  */
865 static void parse_string_literal(void)
866 {
867         const unsigned start_linenr = lexer_token.source_position.linenr;
868
869         eat('"');
870
871         int tc;
872         while(1) {
873                 switch(c) {
874                 case '\\':
875                         tc = parse_escape_sequence();
876                         obstack_1grow(&symbol_obstack, (char) tc);
877                         break;
878
879                 case EOF: {
880                         source_position_t source_position;
881                         source_position.input_name = lexer_token.source_position.input_name;
882                         source_position.linenr     = start_linenr;
883                         errorf(&source_position, "string has no end");
884                         lexer_token.type = T_ERROR;
885                         return;
886                 }
887
888                 case '"':
889                         next_char();
890                         goto end_of_string;
891
892                 default:
893                         obstack_1grow(&symbol_obstack, (char) c);
894                         next_char();
895                         break;
896                 }
897         }
898
899 end_of_string:
900
901         /* TODO: concatenate multiple strings separated by whitespace... */
902
903         /* add finishing 0 to the string */
904         obstack_1grow(&symbol_obstack, '\0');
905         const size_t      size   = (size_t)obstack_object_size(&symbol_obstack);
906         const char *const string = obstack_finish(&symbol_obstack);
907
908 #if 0 /* TODO hash */
909         /* check if there is already a copy of the string */
910         result = strset_insert(&stringset, string);
911         if(result != string) {
912                 obstack_free(&symbol_obstack, string);
913         }
914 #else
915         const char *const result = string;
916 #endif
917
918         lexer_token.type           = T_STRING_LITERAL;
919         lexer_token.v.string.begin = result;
920         lexer_token.v.string.size  = size;
921 }
922
923 /**
924  * Parse a wide character constant and set lexer_token.
925  */
926 static void parse_wide_character_constant(void)
927 {
928         const unsigned start_linenr = lexer_token.source_position.linenr;
929
930         eat('\'');
931
932         while(1) {
933                 switch(c) {
934                 case '\\': {
935                         wchar_rep_t tc = parse_escape_sequence();
936                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
937                         break;
938                 }
939
940                 MATCH_NEWLINE(
941                         parse_error("newline while parsing character constant");
942                         break;
943                 )
944
945                 case '\'':
946                         next_char();
947                         goto end_of_wide_char_constant;
948
949                 case EOF: {
950                         source_position_t source_position = lexer_token.source_position;
951                         source_position.linenr = start_linenr;
952                         errorf(&source_position, "EOF while parsing character constant");
953                         lexer_token.type = T_ERROR;
954                         return;
955                 }
956
957                 default: {
958                         wchar_rep_t tc = (wchar_rep_t) c;
959                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
960                         next_char();
961                         break;
962                 }
963                 }
964         }
965
966 end_of_wide_char_constant:;
967         size_t             size   = (size_t) obstack_object_size(&symbol_obstack);
968         assert(size % sizeof(wchar_rep_t) == 0);
969         size /= sizeof(wchar_rep_t);
970
971         const wchar_rep_t *string = obstack_finish(&symbol_obstack);
972
973         lexer_token.type                = T_WIDE_CHARACTER_CONSTANT;
974         lexer_token.v.wide_string.begin = string;
975         lexer_token.v.wide_string.size  = size;
976         lexer_token.datatype            = type_wchar_t;
977 }
978
979 /**
980  * Parse a wide string literal and set lexer_token.
981  */
982 static void parse_wide_string_literal(void)
983 {
984         const unsigned start_linenr = lexer_token.source_position.linenr;
985
986         assert(c == '"');
987         next_char();
988
989         while(1) {
990                 switch(c) {
991                 case '\\': {
992                         wchar_rep_t tc = parse_escape_sequence();
993                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
994                         break;
995                 }
996
997                 case EOF: {
998                         source_position_t source_position;
999                         source_position.input_name = lexer_token.source_position.input_name;
1000                         source_position.linenr     = start_linenr;
1001                         errorf(&source_position, "string has no end");
1002                         lexer_token.type = T_ERROR;
1003                         return;
1004                 }
1005
1006                 case '"':
1007                         next_char();
1008                         goto end_of_string;
1009
1010                 default: {
1011                         wchar_rep_t tc = c;
1012                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
1013                         next_char();
1014                         break;
1015                 }
1016                 }
1017         }
1018
1019 end_of_string:;
1020
1021         /* TODO: concatenate multiple strings separated by whitespace... */
1022
1023         /* add finishing 0 to the string */
1024         wchar_rep_t nul = L'\0';
1025         obstack_grow(&symbol_obstack, &nul, sizeof(nul));
1026         const size_t             size   = (size_t)obstack_object_size(&symbol_obstack) / sizeof(wchar_rep_t);
1027         const wchar_rep_t *const string = obstack_finish(&symbol_obstack);
1028
1029 #if 0 /* TODO hash */
1030         /* check if there is already a copy of the string */
1031         const wchar_rep_t *const result = strset_insert(&stringset, string);
1032         if(result != string) {
1033                 obstack_free(&symbol_obstack, string);
1034         }
1035 #else
1036         const wchar_rep_t *const result = string;
1037 #endif
1038
1039         lexer_token.type                = T_WIDE_STRING_LITERAL;
1040         lexer_token.v.wide_string.begin = result;
1041         lexer_token.v.wide_string.size  = size;
1042 }
1043
1044 /**
1045  * Parse a character constant and set lexer_token.
1046  */
1047 static void parse_character_constant(void)
1048 {
1049         const unsigned start_linenr = lexer_token.source_position.linenr;
1050
1051         eat('\'');
1052
1053         while(1) {
1054                 switch(c) {
1055                 case '\\': {
1056                         int tc = parse_escape_sequence();
1057                         obstack_1grow(&symbol_obstack, (char) tc);
1058                         break;
1059                 }
1060
1061                 MATCH_NEWLINE(
1062                         parse_error("newline while parsing character constant");
1063                         break;
1064                 )
1065
1066                 case '\'':
1067                         next_char();
1068                         goto end_of_char_constant;
1069
1070                 case EOF: {
1071                         source_position_t source_position;
1072                         source_position.input_name = lexer_token.source_position.input_name;
1073                         source_position.linenr     = start_linenr;
1074                         errorf(&source_position, "EOF while parsing character constant");
1075                         lexer_token.type = T_ERROR;
1076                         return;
1077                 }
1078
1079                 default:
1080                         obstack_1grow(&symbol_obstack, (char) c);
1081                         next_char();
1082                         break;
1083
1084                 }
1085         }
1086
1087 end_of_char_constant:;
1088         const size_t      size   = (size_t)obstack_object_size(&symbol_obstack);
1089         const char *const string = obstack_finish(&symbol_obstack);
1090
1091         lexer_token.type           = T_CHARACTER_CONSTANT;
1092         lexer_token.v.string.begin = string;
1093         lexer_token.v.string.size  = size;
1094         lexer_token.datatype       = type_int;
1095 }
1096
1097 /**
1098  * Skip a multiline comment.
1099  */
1100 static void skip_multiline_comment(void)
1101 {
1102         unsigned start_linenr = lexer_token.source_position.linenr;
1103
1104         while(1) {
1105                 switch(c) {
1106                 case '/':
1107                         next_char();
1108                         if (c == '*') {
1109                                 /* TODO: nested comment, warn here */
1110                         }
1111                         break;
1112                 case '*':
1113                         next_char();
1114                         if(c == '/') {
1115                                 next_char();
1116                                 return;
1117                         }
1118                         break;
1119
1120                 MATCH_NEWLINE(break;)
1121
1122                 case EOF: {
1123                         source_position_t source_position;
1124                         source_position.input_name = lexer_token.source_position.input_name;
1125                         source_position.linenr     = start_linenr;
1126                         errorf(&source_position, "at end of file while looking for comment end");
1127                         return;
1128                 }
1129
1130                 default:
1131                         next_char();
1132                         break;
1133                 }
1134         }
1135 }
1136
1137 /**
1138  * Skip a single line comment.
1139  */
1140 static void skip_line_comment(void)
1141 {
1142         while(1) {
1143                 switch(c) {
1144                 case EOF:
1145                         return;
1146
1147                 case '\n':
1148                 case '\r':
1149                         return;
1150
1151                 default:
1152                         next_char();
1153                         break;
1154                 }
1155         }
1156 }
1157
1158 /** The current preprocessor token. */
1159 static token_t pp_token;
1160
1161 /**
1162  * Read the next preprocessor token.
1163  */
1164 static inline void next_pp_token(void)
1165 {
1166         lexer_next_preprocessing_token();
1167         pp_token = lexer_token;
1168 }
1169
1170 /**
1171  * Eat all preprocessor tokens until newline.
1172  */
1173 static void eat_until_newline(void)
1174 {
1175         while(pp_token.type != '\n' && pp_token.type != T_EOF) {
1176                 next_pp_token();
1177         }
1178 }
1179
1180 /**
1181  * Handle the define directive.
1182  */
1183 static void define_directive(void)
1184 {
1185         lexer_next_preprocessing_token();
1186         if(lexer_token.type != T_IDENTIFIER) {
1187                 parse_error("expected identifier after #define\n");
1188                 eat_until_newline();
1189         }
1190 }
1191
1192 /**
1193  * Handle the ifdef directive.
1194  */
1195 static void ifdef_directive(int is_ifndef)
1196 {
1197         (void) is_ifndef;
1198         lexer_next_preprocessing_token();
1199         //expect_identifier();
1200         //extect_newline();
1201 }
1202
1203 /**
1204  * Handle the endif directive.
1205  */
1206 static void endif_directive(void)
1207 {
1208         //expect_newline();
1209 }
1210
1211 /**
1212  * Parse the line directive.
1213  */
1214 static void parse_line_directive(void)
1215 {
1216         if(pp_token.type != T_INTEGER) {
1217                 parse_error("expected integer");
1218         } else {
1219                 lexer_token.source_position.linenr = (unsigned int)(pp_token.v.intvalue - 1);
1220                 next_pp_token();
1221         }
1222         if(pp_token.type == T_STRING_LITERAL) {
1223                 lexer_token.source_position.input_name = pp_token.v.string.begin;
1224                 next_pp_token();
1225         }
1226
1227         eat_until_newline();
1228 }
1229
1230 /**
1231  * STDC pragmas.
1232  */
1233 typedef enum stdc_pragma_kind_t {
1234         STDC_UNKNOWN,
1235         STDC_FP_CONTRACT,
1236         STDC_FENV_ACCESS,
1237         STDC_CX_LIMITED_RANGE
1238 } stdc_pragma_kind_t;
1239
1240 /**
1241  * STDC pragma values.
1242  */
1243 typedef enum stdc_pragma_value_kind_t {
1244         STDC_VALUE_UNKNOWN,
1245         STDC_VALUE_ON,
1246         STDC_VALUE_OFF,
1247         STDC_VALUE_DEFAULT
1248 } stdc_pragma_value_kind_t;
1249
1250 /**
1251  * Parse a pragma directive.
1252  */
1253 static void parse_pragma(void) {
1254         bool unknown_pragma = true;
1255
1256         next_pp_token();
1257         if (pp_token.v.symbol->pp_ID == TP_STDC) {
1258                 stdc_pragma_kind_t kind = STDC_UNKNOWN;
1259                 /* a STDC pragma */
1260                 if (c_mode & _C99) {
1261                         next_pp_token();
1262
1263                         switch (pp_token.v.symbol->pp_ID) {
1264                         case TP_FP_CONTRACT:
1265                                 kind = STDC_FP_CONTRACT;
1266                                 break;
1267                         case TP_FENV_ACCESS:
1268                                 kind = STDC_FENV_ACCESS;
1269                                 break;
1270                         case TP_CX_LIMITED_RANGE:
1271                                 kind = STDC_CX_LIMITED_RANGE;
1272                                 break;
1273                         default:
1274                                 break;
1275                         }
1276                         if (kind != STDC_UNKNOWN) {
1277                                 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
1278                                 next_pp_token();
1279                                 switch (pp_token.v.symbol->pp_ID) {
1280                                 case TP_ON:
1281                                         value = STDC_VALUE_ON;
1282                                         break;
1283                                 case TP_OFF:
1284                                         value = STDC_VALUE_OFF;
1285                                         break;
1286                                 case TP_DEFAULT:
1287                                         value = STDC_VALUE_DEFAULT;
1288                                         break;
1289                                 default:
1290                                         break;
1291                                 }
1292                                 if (value != STDC_VALUE_UNKNOWN) {
1293                                         unknown_pragma = false;
1294                                 } else {
1295                                         errorf(&pp_token.source_position, "bad STDC pragma argument");
1296                                 }
1297                         }
1298                 }
1299         } else {
1300                 unknown_pragma = true;
1301         }
1302         eat_until_newline();
1303         if (unknown_pragma && warning.unknown_pragmas) {
1304                 warningf(&pp_token.source_position, "encountered unknown #pragma");
1305         }
1306 }
1307
1308 /**
1309  * Parse a preprocessor non-null directive.
1310  */
1311 static void parse_preprocessor_identifier(void)
1312 {
1313         assert(pp_token.type == T_IDENTIFIER);
1314         symbol_t *symbol = pp_token.v.symbol;
1315
1316         switch(symbol->pp_ID) {
1317         case TP_include:
1318                 printf("include - enable header name parsing!\n");
1319                 break;
1320         case TP_define:
1321                 define_directive();
1322                 break;
1323         case TP_ifdef:
1324                 ifdef_directive(0);
1325                 break;
1326         case TP_ifndef:
1327                 ifdef_directive(1);
1328                 break;
1329         case TP_endif:
1330                 endif_directive();
1331                 break;
1332         case TP_line:
1333                 next_pp_token();
1334                 parse_line_directive();
1335                 break;
1336         case TP_if:
1337         case TP_else:
1338         case TP_elif:
1339         case TP_undef:
1340         case TP_error:
1341                 /* TODO; output the rest of the line */
1342                 parse_error("#error directive: ");
1343                 break;
1344         case TP_pragma:
1345                 parse_pragma();
1346                 break;
1347         }
1348 }
1349
1350 /**
1351  * Parse a preprocessor directive.
1352  */
1353 static void parse_preprocessor_directive(void)
1354 {
1355         next_pp_token();
1356
1357         switch(pp_token.type) {
1358         case T_IDENTIFIER:
1359                 parse_preprocessor_identifier();
1360                 break;
1361         case T_INTEGER:
1362                 parse_line_directive();
1363                 break;
1364         case '\n':
1365                 /* NULL directive, see Â§ 6.10.7 */
1366                 break;
1367         default:
1368                 parse_error("invalid preprocessor directive");
1369                 eat_until_newline();
1370                 break;
1371         }
1372 }
1373
1374 #define MAYBE_PROLOG                                       \
1375                         next_char();                                   \
1376                         while(1) {                                     \
1377                                 switch(c) {
1378
1379 #define MAYBE(ch, set_type)                                \
1380                                 case ch:                                   \
1381                                         next_char();                           \
1382                                         lexer_token.type = set_type;           \
1383                                         return;
1384
1385 #define ELSE_CODE(code)                                    \
1386                                 default:                                   \
1387                                         code                                   \
1388                                 }                                          \
1389                         } /* end of while(1) */                        \
1390                         break;
1391
1392 #define ELSE(set_type)                                     \
1393                 ELSE_CODE(                                         \
1394                         lexer_token.type = set_type;                   \
1395                         return;                                        \
1396                 )
1397
1398 void lexer_next_preprocessing_token(void)
1399 {
1400         while(1) {
1401                 switch(c) {
1402                 case ' ':
1403                 case '\t':
1404                         next_char();
1405                         break;
1406
1407                 MATCH_NEWLINE(
1408                         lexer_token.type = '\n';
1409                         return;
1410                 )
1411
1412                 SYMBOL_CHARS
1413                         parse_symbol();
1414                         /* might be a wide string ( L"string" ) */
1415                         if(lexer_token.type == T_IDENTIFIER &&
1416                             lexer_token.v.symbol == symbol_L) {
1417                             if(c == '"') {
1418                                         parse_wide_string_literal();
1419                                 } else if(c == '\'') {
1420                                         parse_wide_character_constant();
1421                                 }
1422                         }
1423                         return;
1424
1425                 DIGITS
1426                         parse_number();
1427                         return;
1428
1429                 case '"':
1430                         parse_string_literal();
1431                         return;
1432
1433                 case '\'':
1434                         parse_character_constant();
1435                         return;
1436
1437                 case '.':
1438                         MAYBE_PROLOG
1439                                 DIGITS
1440                                         put_back(c);
1441                                         c = '.';
1442                                         parse_number_dec();
1443                                         return;
1444
1445                                 case '.':
1446                                         MAYBE_PROLOG
1447                                         MAYBE('.', T_DOTDOTDOT)
1448                                         ELSE_CODE(
1449                                                 put_back(c);
1450                                                 c = '.';
1451                                                 lexer_token.type = '.';
1452                                                 return;
1453                                         )
1454                         ELSE('.')
1455                 case '&':
1456                         MAYBE_PROLOG
1457                         MAYBE('&', T_ANDAND)
1458                         MAYBE('=', T_ANDEQUAL)
1459                         ELSE('&')
1460                 case '*':
1461                         MAYBE_PROLOG
1462                         MAYBE('=', T_ASTERISKEQUAL)
1463                         ELSE('*')
1464                 case '+':
1465                         MAYBE_PROLOG
1466                         MAYBE('+', T_PLUSPLUS)
1467                         MAYBE('=', T_PLUSEQUAL)
1468                         ELSE('+')
1469                 case '-':
1470                         MAYBE_PROLOG
1471                         MAYBE('>', T_MINUSGREATER)
1472                         MAYBE('-', T_MINUSMINUS)
1473                         MAYBE('=', T_MINUSEQUAL)
1474                         ELSE('-')
1475                 case '!':
1476                         MAYBE_PROLOG
1477                         MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1478                         ELSE('!')
1479                 case '/':
1480                         MAYBE_PROLOG
1481                         MAYBE('=', T_SLASHEQUAL)
1482                                 case '*':
1483                                         next_char();
1484                                         skip_multiline_comment();
1485                                         lexer_next_preprocessing_token();
1486                                         return;
1487                                 case '/':
1488                                         next_char();
1489                                         skip_line_comment();
1490                                         lexer_next_preprocessing_token();
1491                                         return;
1492                         ELSE('/')
1493                 case '%':
1494                         MAYBE_PROLOG
1495                         MAYBE('>', '}')
1496                         MAYBE('=', T_PERCENTEQUAL)
1497                                 case ':':
1498                                         MAYBE_PROLOG
1499                                                 case '%':
1500                                                         MAYBE_PROLOG
1501                                                         MAYBE(':', T_HASHHASH)
1502                                                         ELSE_CODE(
1503                                                                 put_back(c);
1504                                                                 c = '%';
1505                                                                 lexer_token.type = '#';
1506                                                                 return;
1507                                                         )
1508                                         ELSE('#')
1509                         ELSE('%')
1510                 case '<':
1511                         MAYBE_PROLOG
1512                         MAYBE(':', '[')
1513                         MAYBE('%', '{')
1514                         MAYBE('=', T_LESSEQUAL)
1515                                 case '<':
1516                                         MAYBE_PROLOG
1517                                         MAYBE('=', T_LESSLESSEQUAL)
1518                                         ELSE(T_LESSLESS)
1519                         ELSE('<')
1520                 case '>':
1521                         MAYBE_PROLOG
1522                         MAYBE('=', T_GREATEREQUAL)
1523                                 case '>':
1524                                         MAYBE_PROLOG
1525                                         MAYBE('=', T_GREATERGREATEREQUAL)
1526                                         ELSE(T_GREATERGREATER)
1527                         ELSE('>')
1528                 case '^':
1529                         MAYBE_PROLOG
1530                         MAYBE('=', T_CARETEQUAL)
1531                         ELSE('^')
1532                 case '|':
1533                         MAYBE_PROLOG
1534                         MAYBE('=', T_PIPEEQUAL)
1535                         MAYBE('|', T_PIPEPIPE)
1536                         ELSE('|')
1537                 case ':':
1538                         MAYBE_PROLOG
1539                         MAYBE('>', ']')
1540                         ELSE(':')
1541                 case '=':
1542                         MAYBE_PROLOG
1543                         MAYBE('=', T_EQUALEQUAL)
1544                         ELSE('=')
1545                 case '#':
1546                         MAYBE_PROLOG
1547                         MAYBE('#', T_HASHHASH)
1548                         ELSE('#')
1549
1550                 case '?':
1551                 case '[':
1552                 case ']':
1553                 case '(':
1554                 case ')':
1555                 case '{':
1556                 case '}':
1557                 case '~':
1558                 case ';':
1559                 case ',':
1560                 case '\\':
1561                         lexer_token.type = c;
1562                         next_char();
1563                         return;
1564
1565                 case EOF:
1566                         lexer_token.type = T_EOF;
1567                         return;
1568
1569                 default:
1570 dollar_sign:
1571                         errorf(&lexer_token.source_position, "unknown character '%c' found", c);
1572                         next_char();
1573                         lexer_token.type = T_ERROR;
1574                         return;
1575                 }
1576         }
1577 }
1578
1579 void lexer_next_token(void)
1580 {
1581         lexer_next_preprocessing_token();
1582
1583         while (lexer_token.type == '\n') {
1584 newline_found:
1585                 lexer_next_preprocessing_token();
1586         }
1587
1588         if (lexer_token.type == '#') {
1589                 parse_preprocessor_directive();
1590                 goto newline_found;
1591         }
1592 }
1593
1594 void init_lexer(void)
1595 {
1596         strset_init(&stringset);
1597         symbol_L = symbol_table_insert("L");
1598 }
1599
1600 void lexer_open_stream(FILE *stream, const char *input_name)
1601 {
1602         input                                  = stream;
1603         lexer_token.source_position.linenr     = 0;
1604         lexer_token.source_position.input_name = input_name;
1605
1606         bufpos = NULL;
1607         bufend = NULL;
1608
1609         /* place a virtual \n at the beginning so the lexer knows that we're
1610          * at the beginning of a line */
1611         c = '\n';
1612 }
1613
1614 void lexer_open_buffer(const char *buffer, size_t len, const char *input_name)
1615 {
1616         input                                  = NULL;
1617         lexer_token.source_position.linenr     = 0;
1618         lexer_token.source_position.input_name = input_name;
1619
1620         bufpos = buffer;
1621         bufend = buffer + len;
1622
1623         /* place a virtual \n at the beginning so the lexer knows that we're
1624          * at the beginning of a line */
1625         c = '\n';
1626 }
1627
1628 void exit_lexer(void)
1629 {
1630         strset_destroy(&stringset);
1631 }
1632
1633 static __attribute__((unused))
1634 void dbg_pos(const source_position_t source_position)
1635 {
1636         fprintf(stdout, "%s:%u\n", source_position.input_name,
1637                 source_position.linenr);
1638         fflush(stdout);
1639 }