- add support for \e escape
[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         case 'e':
782                 if (c_mode & _GNUC)
783                         return 27;   /* hopefully 27 is ALWAYS the code for ESACAPE */
784                 /*fallthrough*/
785         default:
786                 parse_error("unknown escape sequence");
787                 return EOF;
788         }
789 }
790
791 /**
792  * Concatenate two strings.
793  */
794 string_t concat_strings(const string_t *const s1, const string_t *const s2)
795 {
796         const size_t len1 = s1->size - 1;
797         const size_t len2 = s2->size - 1;
798
799         char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
800         memcpy(concat, s1->begin, len1);
801         memcpy(concat + len1, s2->begin, len2 + 1);
802
803 #if 0 /* TODO hash */
804         const char *result = strset_insert(&stringset, concat);
805         if(result != concat) {
806                 obstack_free(&symbol_obstack, concat);
807         }
808
809         return result;
810 #else
811         return (string_t){ concat, len1 + len2 + 1 };
812 #endif
813 }
814
815 /**
816  * Concatenate a string and a wide string.
817  */
818 wide_string_t concat_string_wide_string(const string_t *const s1, const wide_string_t *const s2)
819 {
820         const size_t len1 = s1->size - 1;
821         const size_t len2 = s2->size - 1;
822
823         wchar_rep_t *const concat = obstack_alloc(&symbol_obstack, (len1 + len2 + 1) * sizeof(*concat));
824         const char *const src = s1->begin;
825         for (size_t i = 0; i != len1; ++i) {
826                 concat[i] = src[i];
827         }
828         memcpy(concat + len1, s2->begin, (len2 + 1) * sizeof(*concat));
829
830         return (wide_string_t){ concat, len1 + len2 + 1 };
831 }
832
833 /**
834  * Concatenate two wide strings.
835  */
836 wide_string_t concat_wide_strings(const wide_string_t *const s1, const wide_string_t *const s2)
837 {
838         const size_t len1 = s1->size - 1;
839         const size_t len2 = s2->size - 1;
840
841         wchar_rep_t *const concat = obstack_alloc(&symbol_obstack, (len1 + len2 + 1) * sizeof(*concat));
842         memcpy(concat,        s1->begin, len1       * sizeof(*concat));
843         memcpy(concat + len1, s2->begin, (len2 + 1) * sizeof(*concat));
844
845         return (wide_string_t){ concat, len1 + len2 + 1 };
846 }
847
848 /**
849  * Concatenate a wide string and a string.
850  */
851 wide_string_t concat_wide_string_string(const wide_string_t *const s1, const string_t *const s2)
852 {
853         const size_t len1 = s1->size - 1;
854         const size_t len2 = s2->size - 1;
855
856         wchar_rep_t *const concat = obstack_alloc(&symbol_obstack, (len1 + len2 + 1) * sizeof(*concat));
857         memcpy(concat, s1->begin, len1 * sizeof(*concat));
858         const char *const src = s2->begin;
859         for (size_t i = 0; i != len2 + 1; ++i) {
860                 concat[i] = src[i];
861         }
862
863         return (wide_string_t){ concat, len1 + len2 + 1 };
864 }
865
866 /**
867  * Parse a string literal and set lexer_token.
868  */
869 static void parse_string_literal(void)
870 {
871         const unsigned start_linenr = lexer_token.source_position.linenr;
872
873         eat('"');
874
875         int tc;
876         while(1) {
877                 switch(c) {
878                 case '\\':
879                         tc = parse_escape_sequence();
880                         obstack_1grow(&symbol_obstack, (char) tc);
881                         break;
882
883                 case EOF: {
884                         source_position_t source_position;
885                         source_position.input_name = lexer_token.source_position.input_name;
886                         source_position.linenr     = start_linenr;
887                         errorf(&source_position, "string has no end");
888                         lexer_token.type = T_ERROR;
889                         return;
890                 }
891
892                 case '"':
893                         next_char();
894                         goto end_of_string;
895
896                 default:
897                         obstack_1grow(&symbol_obstack, (char) c);
898                         next_char();
899                         break;
900                 }
901         }
902
903 end_of_string:
904
905         /* TODO: concatenate multiple strings separated by whitespace... */
906
907         /* add finishing 0 to the string */
908         obstack_1grow(&symbol_obstack, '\0');
909         const size_t      size   = (size_t)obstack_object_size(&symbol_obstack);
910         const char *const string = obstack_finish(&symbol_obstack);
911
912 #if 0 /* TODO hash */
913         /* check if there is already a copy of the string */
914         result = strset_insert(&stringset, string);
915         if(result != string) {
916                 obstack_free(&symbol_obstack, string);
917         }
918 #else
919         const char *const result = string;
920 #endif
921
922         lexer_token.type           = T_STRING_LITERAL;
923         lexer_token.v.string.begin = result;
924         lexer_token.v.string.size  = size;
925 }
926
927 /**
928  * Parse a wide character constant and set lexer_token.
929  */
930 static void parse_wide_character_constant(void)
931 {
932         const unsigned start_linenr = lexer_token.source_position.linenr;
933
934         eat('\'');
935
936         while(1) {
937                 switch(c) {
938                 case '\\': {
939                         wchar_rep_t tc = parse_escape_sequence();
940                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
941                         break;
942                 }
943
944                 MATCH_NEWLINE(
945                         parse_error("newline while parsing character constant");
946                         break;
947                 )
948
949                 case '\'':
950                         next_char();
951                         goto end_of_wide_char_constant;
952
953                 case EOF: {
954                         source_position_t source_position = lexer_token.source_position;
955                         source_position.linenr = start_linenr;
956                         errorf(&source_position, "EOF while parsing character constant");
957                         lexer_token.type = T_ERROR;
958                         return;
959                 }
960
961                 default: {
962                         wchar_rep_t tc = (wchar_rep_t) c;
963                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
964                         next_char();
965                         break;
966                 }
967                 }
968         }
969
970 end_of_wide_char_constant:;
971         size_t             size   = (size_t) obstack_object_size(&symbol_obstack);
972         assert(size % sizeof(wchar_rep_t) == 0);
973         size /= sizeof(wchar_rep_t);
974
975         const wchar_rep_t *string = obstack_finish(&symbol_obstack);
976
977         lexer_token.type                = T_WIDE_CHARACTER_CONSTANT;
978         lexer_token.v.wide_string.begin = string;
979         lexer_token.v.wide_string.size  = size;
980         lexer_token.datatype            = type_wchar_t;
981 }
982
983 /**
984  * Parse a wide string literal and set lexer_token.
985  */
986 static void parse_wide_string_literal(void)
987 {
988         const unsigned start_linenr = lexer_token.source_position.linenr;
989
990         assert(c == '"');
991         next_char();
992
993         while(1) {
994                 switch(c) {
995                 case '\\': {
996                         wchar_rep_t tc = parse_escape_sequence();
997                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
998                         break;
999                 }
1000
1001                 case EOF: {
1002                         source_position_t source_position;
1003                         source_position.input_name = lexer_token.source_position.input_name;
1004                         source_position.linenr     = start_linenr;
1005                         errorf(&source_position, "string has no end");
1006                         lexer_token.type = T_ERROR;
1007                         return;
1008                 }
1009
1010                 case '"':
1011                         next_char();
1012                         goto end_of_string;
1013
1014                 default: {
1015                         wchar_rep_t tc = c;
1016                         obstack_grow(&symbol_obstack, &tc, sizeof(tc));
1017                         next_char();
1018                         break;
1019                 }
1020                 }
1021         }
1022
1023 end_of_string:;
1024
1025         /* TODO: concatenate multiple strings separated by whitespace... */
1026
1027         /* add finishing 0 to the string */
1028         wchar_rep_t nul = L'\0';
1029         obstack_grow(&symbol_obstack, &nul, sizeof(nul));
1030         const size_t             size   = (size_t)obstack_object_size(&symbol_obstack) / sizeof(wchar_rep_t);
1031         const wchar_rep_t *const string = obstack_finish(&symbol_obstack);
1032
1033 #if 0 /* TODO hash */
1034         /* check if there is already a copy of the string */
1035         const wchar_rep_t *const result = strset_insert(&stringset, string);
1036         if(result != string) {
1037                 obstack_free(&symbol_obstack, string);
1038         }
1039 #else
1040         const wchar_rep_t *const result = string;
1041 #endif
1042
1043         lexer_token.type                = T_WIDE_STRING_LITERAL;
1044         lexer_token.v.wide_string.begin = result;
1045         lexer_token.v.wide_string.size  = size;
1046 }
1047
1048 /**
1049  * Parse a character constant and set lexer_token.
1050  */
1051 static void parse_character_constant(void)
1052 {
1053         const unsigned start_linenr = lexer_token.source_position.linenr;
1054
1055         eat('\'');
1056
1057         while(1) {
1058                 switch(c) {
1059                 case '\\': {
1060                         int tc = parse_escape_sequence();
1061                         obstack_1grow(&symbol_obstack, (char) tc);
1062                         break;
1063                 }
1064
1065                 MATCH_NEWLINE(
1066                         parse_error("newline while parsing character constant");
1067                         break;
1068                 )
1069
1070                 case '\'':
1071                         next_char();
1072                         goto end_of_char_constant;
1073
1074                 case EOF: {
1075                         source_position_t source_position;
1076                         source_position.input_name = lexer_token.source_position.input_name;
1077                         source_position.linenr     = start_linenr;
1078                         errorf(&source_position, "EOF while parsing character constant");
1079                         lexer_token.type = T_ERROR;
1080                         return;
1081                 }
1082
1083                 default:
1084                         obstack_1grow(&symbol_obstack, (char) c);
1085                         next_char();
1086                         break;
1087
1088                 }
1089         }
1090
1091 end_of_char_constant:;
1092         const size_t      size   = (size_t)obstack_object_size(&symbol_obstack);
1093         const char *const string = obstack_finish(&symbol_obstack);
1094
1095         lexer_token.type           = T_CHARACTER_CONSTANT;
1096         lexer_token.v.string.begin = string;
1097         lexer_token.v.string.size  = size;
1098         lexer_token.datatype       = type_int;
1099 }
1100
1101 /**
1102  * Skip a multiline comment.
1103  */
1104 static void skip_multiline_comment(void)
1105 {
1106         unsigned start_linenr = lexer_token.source_position.linenr;
1107
1108         while(1) {
1109                 switch(c) {
1110                 case '/':
1111                         next_char();
1112                         if (c == '*') {
1113                                 /* TODO: nested comment, warn here */
1114                         }
1115                         break;
1116                 case '*':
1117                         next_char();
1118                         if(c == '/') {
1119                                 next_char();
1120                                 return;
1121                         }
1122                         break;
1123
1124                 MATCH_NEWLINE(break;)
1125
1126                 case EOF: {
1127                         source_position_t source_position;
1128                         source_position.input_name = lexer_token.source_position.input_name;
1129                         source_position.linenr     = start_linenr;
1130                         errorf(&source_position, "at end of file while looking for comment end");
1131                         return;
1132                 }
1133
1134                 default:
1135                         next_char();
1136                         break;
1137                 }
1138         }
1139 }
1140
1141 /**
1142  * Skip a single line comment.
1143  */
1144 static void skip_line_comment(void)
1145 {
1146         while(1) {
1147                 switch(c) {
1148                 case EOF:
1149                         return;
1150
1151                 case '\n':
1152                 case '\r':
1153                         return;
1154
1155                 default:
1156                         next_char();
1157                         break;
1158                 }
1159         }
1160 }
1161
1162 /** The current preprocessor token. */
1163 static token_t pp_token;
1164
1165 /**
1166  * Read the next preprocessor token.
1167  */
1168 static inline void next_pp_token(void)
1169 {
1170         lexer_next_preprocessing_token();
1171         pp_token = lexer_token;
1172 }
1173
1174 /**
1175  * Eat all preprocessor tokens until newline.
1176  */
1177 static void eat_until_newline(void)
1178 {
1179         while(pp_token.type != '\n' && pp_token.type != T_EOF) {
1180                 next_pp_token();
1181         }
1182 }
1183
1184 /**
1185  * Handle the define directive.
1186  */
1187 static void define_directive(void)
1188 {
1189         lexer_next_preprocessing_token();
1190         if(lexer_token.type != T_IDENTIFIER) {
1191                 parse_error("expected identifier after #define\n");
1192                 eat_until_newline();
1193         }
1194 }
1195
1196 /**
1197  * Handle the ifdef directive.
1198  */
1199 static void ifdef_directive(int is_ifndef)
1200 {
1201         (void) is_ifndef;
1202         lexer_next_preprocessing_token();
1203         //expect_identifier();
1204         //extect_newline();
1205 }
1206
1207 /**
1208  * Handle the endif directive.
1209  */
1210 static void endif_directive(void)
1211 {
1212         //expect_newline();
1213 }
1214
1215 /**
1216  * Parse the line directive.
1217  */
1218 static void parse_line_directive(void)
1219 {
1220         if(pp_token.type != T_INTEGER) {
1221                 parse_error("expected integer");
1222         } else {
1223                 lexer_token.source_position.linenr = (unsigned int)(pp_token.v.intvalue - 1);
1224                 next_pp_token();
1225         }
1226         if(pp_token.type == T_STRING_LITERAL) {
1227                 lexer_token.source_position.input_name = pp_token.v.string.begin;
1228                 next_pp_token();
1229         }
1230
1231         eat_until_newline();
1232 }
1233
1234 /**
1235  * STDC pragmas.
1236  */
1237 typedef enum stdc_pragma_kind_t {
1238         STDC_UNKNOWN,
1239         STDC_FP_CONTRACT,
1240         STDC_FENV_ACCESS,
1241         STDC_CX_LIMITED_RANGE
1242 } stdc_pragma_kind_t;
1243
1244 /**
1245  * STDC pragma values.
1246  */
1247 typedef enum stdc_pragma_value_kind_t {
1248         STDC_VALUE_UNKNOWN,
1249         STDC_VALUE_ON,
1250         STDC_VALUE_OFF,
1251         STDC_VALUE_DEFAULT
1252 } stdc_pragma_value_kind_t;
1253
1254 /**
1255  * Parse a pragma directive.
1256  */
1257 static void parse_pragma(void) {
1258         bool unknown_pragma = true;
1259
1260         next_pp_token();
1261         if (pp_token.v.symbol->pp_ID == TP_STDC) {
1262                 stdc_pragma_kind_t kind = STDC_UNKNOWN;
1263                 /* a STDC pragma */
1264                 if (c_mode & _C99) {
1265                         next_pp_token();
1266
1267                         switch (pp_token.v.symbol->pp_ID) {
1268                         case TP_FP_CONTRACT:
1269                                 kind = STDC_FP_CONTRACT;
1270                                 break;
1271                         case TP_FENV_ACCESS:
1272                                 kind = STDC_FENV_ACCESS;
1273                                 break;
1274                         case TP_CX_LIMITED_RANGE:
1275                                 kind = STDC_CX_LIMITED_RANGE;
1276                                 break;
1277                         default:
1278                                 break;
1279                         }
1280                         if (kind != STDC_UNKNOWN) {
1281                                 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
1282                                 next_pp_token();
1283                                 switch (pp_token.v.symbol->pp_ID) {
1284                                 case TP_ON:
1285                                         value = STDC_VALUE_ON;
1286                                         break;
1287                                 case TP_OFF:
1288                                         value = STDC_VALUE_OFF;
1289                                         break;
1290                                 case TP_DEFAULT:
1291                                         value = STDC_VALUE_DEFAULT;
1292                                         break;
1293                                 default:
1294                                         break;
1295                                 }
1296                                 if (value != STDC_VALUE_UNKNOWN) {
1297                                         unknown_pragma = false;
1298                                 } else {
1299                                         errorf(&pp_token.source_position, "bad STDC pragma argument");
1300                                 }
1301                         }
1302                 }
1303         } else {
1304                 unknown_pragma = true;
1305         }
1306         eat_until_newline();
1307         if (unknown_pragma && warning.unknown_pragmas) {
1308                 warningf(&pp_token.source_position, "encountered unknown #pragma");
1309         }
1310 }
1311
1312 /**
1313  * Parse a preprocessor non-null directive.
1314  */
1315 static void parse_preprocessor_identifier(void)
1316 {
1317         assert(pp_token.type == T_IDENTIFIER);
1318         symbol_t *symbol = pp_token.v.symbol;
1319
1320         switch(symbol->pp_ID) {
1321         case TP_include:
1322                 printf("include - enable header name parsing!\n");
1323                 break;
1324         case TP_define:
1325                 define_directive();
1326                 break;
1327         case TP_ifdef:
1328                 ifdef_directive(0);
1329                 break;
1330         case TP_ifndef:
1331                 ifdef_directive(1);
1332                 break;
1333         case TP_endif:
1334                 endif_directive();
1335                 break;
1336         case TP_line:
1337                 next_pp_token();
1338                 parse_line_directive();
1339                 break;
1340         case TP_if:
1341         case TP_else:
1342         case TP_elif:
1343         case TP_undef:
1344         case TP_error:
1345                 /* TODO; output the rest of the line */
1346                 parse_error("#error directive: ");
1347                 break;
1348         case TP_pragma:
1349                 parse_pragma();
1350                 break;
1351         }
1352 }
1353
1354 /**
1355  * Parse a preprocessor directive.
1356  */
1357 static void parse_preprocessor_directive(void)
1358 {
1359         next_pp_token();
1360
1361         switch(pp_token.type) {
1362         case T_IDENTIFIER:
1363                 parse_preprocessor_identifier();
1364                 break;
1365         case T_INTEGER:
1366                 parse_line_directive();
1367                 break;
1368         case '\n':
1369                 /* NULL directive, see Â§ 6.10.7 */
1370                 break;
1371         default:
1372                 parse_error("invalid preprocessor directive");
1373                 eat_until_newline();
1374                 break;
1375         }
1376 }
1377
1378 #define MAYBE_PROLOG                                       \
1379                         next_char();                                   \
1380                         while(1) {                                     \
1381                                 switch(c) {
1382
1383 #define MAYBE(ch, set_type)                                \
1384                                 case ch:                                   \
1385                                         next_char();                           \
1386                                         lexer_token.type = set_type;           \
1387                                         return;
1388
1389 #define ELSE_CODE(code)                                    \
1390                                 default:                                   \
1391                                         code                                   \
1392                                 }                                          \
1393                         } /* end of while(1) */                        \
1394                         break;
1395
1396 #define ELSE(set_type)                                     \
1397                 ELSE_CODE(                                         \
1398                         lexer_token.type = set_type;                   \
1399                         return;                                        \
1400                 )
1401
1402 void lexer_next_preprocessing_token(void)
1403 {
1404         while(1) {
1405                 switch(c) {
1406                 case ' ':
1407                 case '\t':
1408                         next_char();
1409                         break;
1410
1411                 MATCH_NEWLINE(
1412                         lexer_token.type = '\n';
1413                         return;
1414                 )
1415
1416                 SYMBOL_CHARS
1417                         parse_symbol();
1418                         /* might be a wide string ( L"string" ) */
1419                         if(lexer_token.type == T_IDENTIFIER &&
1420                             lexer_token.v.symbol == symbol_L) {
1421                             if(c == '"') {
1422                                         parse_wide_string_literal();
1423                                 } else if(c == '\'') {
1424                                         parse_wide_character_constant();
1425                                 }
1426                         }
1427                         return;
1428
1429                 DIGITS
1430                         parse_number();
1431                         return;
1432
1433                 case '"':
1434                         parse_string_literal();
1435                         return;
1436
1437                 case '\'':
1438                         parse_character_constant();
1439                         return;
1440
1441                 case '.':
1442                         MAYBE_PROLOG
1443                                 DIGITS
1444                                         put_back(c);
1445                                         c = '.';
1446                                         parse_number_dec();
1447                                         return;
1448
1449                                 case '.':
1450                                         MAYBE_PROLOG
1451                                         MAYBE('.', T_DOTDOTDOT)
1452                                         ELSE_CODE(
1453                                                 put_back(c);
1454                                                 c = '.';
1455                                                 lexer_token.type = '.';
1456                                                 return;
1457                                         )
1458                         ELSE('.')
1459                 case '&':
1460                         MAYBE_PROLOG
1461                         MAYBE('&', T_ANDAND)
1462                         MAYBE('=', T_ANDEQUAL)
1463                         ELSE('&')
1464                 case '*':
1465                         MAYBE_PROLOG
1466                         MAYBE('=', T_ASTERISKEQUAL)
1467                         ELSE('*')
1468                 case '+':
1469                         MAYBE_PROLOG
1470                         MAYBE('+', T_PLUSPLUS)
1471                         MAYBE('=', T_PLUSEQUAL)
1472                         ELSE('+')
1473                 case '-':
1474                         MAYBE_PROLOG
1475                         MAYBE('>', T_MINUSGREATER)
1476                         MAYBE('-', T_MINUSMINUS)
1477                         MAYBE('=', T_MINUSEQUAL)
1478                         ELSE('-')
1479                 case '!':
1480                         MAYBE_PROLOG
1481                         MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1482                         ELSE('!')
1483                 case '/':
1484                         MAYBE_PROLOG
1485                         MAYBE('=', T_SLASHEQUAL)
1486                                 case '*':
1487                                         next_char();
1488                                         skip_multiline_comment();
1489                                         lexer_next_preprocessing_token();
1490                                         return;
1491                                 case '/':
1492                                         next_char();
1493                                         skip_line_comment();
1494                                         lexer_next_preprocessing_token();
1495                                         return;
1496                         ELSE('/')
1497                 case '%':
1498                         MAYBE_PROLOG
1499                         MAYBE('>', '}')
1500                         MAYBE('=', T_PERCENTEQUAL)
1501                                 case ':':
1502                                         MAYBE_PROLOG
1503                                                 case '%':
1504                                                         MAYBE_PROLOG
1505                                                         MAYBE(':', T_HASHHASH)
1506                                                         ELSE_CODE(
1507                                                                 put_back(c);
1508                                                                 c = '%';
1509                                                                 lexer_token.type = '#';
1510                                                                 return;
1511                                                         )
1512                                         ELSE('#')
1513                         ELSE('%')
1514                 case '<':
1515                         MAYBE_PROLOG
1516                         MAYBE(':', '[')
1517                         MAYBE('%', '{')
1518                         MAYBE('=', T_LESSEQUAL)
1519                                 case '<':
1520                                         MAYBE_PROLOG
1521                                         MAYBE('=', T_LESSLESSEQUAL)
1522                                         ELSE(T_LESSLESS)
1523                         ELSE('<')
1524                 case '>':
1525                         MAYBE_PROLOG
1526                         MAYBE('=', T_GREATEREQUAL)
1527                                 case '>':
1528                                         MAYBE_PROLOG
1529                                         MAYBE('=', T_GREATERGREATEREQUAL)
1530                                         ELSE(T_GREATERGREATER)
1531                         ELSE('>')
1532                 case '^':
1533                         MAYBE_PROLOG
1534                         MAYBE('=', T_CARETEQUAL)
1535                         ELSE('^')
1536                 case '|':
1537                         MAYBE_PROLOG
1538                         MAYBE('=', T_PIPEEQUAL)
1539                         MAYBE('|', T_PIPEPIPE)
1540                         ELSE('|')
1541                 case ':':
1542                         MAYBE_PROLOG
1543                         MAYBE('>', ']')
1544                         ELSE(':')
1545                 case '=':
1546                         MAYBE_PROLOG
1547                         MAYBE('=', T_EQUALEQUAL)
1548                         ELSE('=')
1549                 case '#':
1550                         MAYBE_PROLOG
1551                         MAYBE('#', T_HASHHASH)
1552                         ELSE('#')
1553
1554                 case '?':
1555                 case '[':
1556                 case ']':
1557                 case '(':
1558                 case ')':
1559                 case '{':
1560                 case '}':
1561                 case '~':
1562                 case ';':
1563                 case ',':
1564                 case '\\':
1565                         lexer_token.type = c;
1566                         next_char();
1567                         return;
1568
1569                 case EOF:
1570                         lexer_token.type = T_EOF;
1571                         return;
1572
1573                 default:
1574 dollar_sign:
1575                         errorf(&lexer_token.source_position, "unknown character '%c' found", c);
1576                         next_char();
1577                         lexer_token.type = T_ERROR;
1578                         return;
1579                 }
1580         }
1581 }
1582
1583 void lexer_next_token(void)
1584 {
1585         lexer_next_preprocessing_token();
1586
1587         while (lexer_token.type == '\n') {
1588 newline_found:
1589                 lexer_next_preprocessing_token();
1590         }
1591
1592         if (lexer_token.type == '#') {
1593                 parse_preprocessor_directive();
1594                 goto newline_found;
1595         }
1596 }
1597
1598 void init_lexer(void)
1599 {
1600         strset_init(&stringset);
1601         symbol_L = symbol_table_insert("L");
1602 }
1603
1604 void lexer_open_stream(FILE *stream, const char *input_name)
1605 {
1606         input                                  = stream;
1607         lexer_token.source_position.linenr     = 0;
1608         lexer_token.source_position.input_name = input_name;
1609
1610         bufpos = NULL;
1611         bufend = NULL;
1612
1613         /* place a virtual \n at the beginning so the lexer knows that we're
1614          * at the beginning of a line */
1615         c = '\n';
1616 }
1617
1618 void lexer_open_buffer(const char *buffer, size_t len, const char *input_name)
1619 {
1620         input                                  = NULL;
1621         lexer_token.source_position.linenr     = 0;
1622         lexer_token.source_position.input_name = input_name;
1623
1624         bufpos = buffer;
1625         bufend = buffer + len;
1626
1627         /* place a virtual \n at the beginning so the lexer knows that we're
1628          * at the beginning of a line */
1629         c = '\n';
1630 }
1631
1632 void exit_lexer(void)
1633 {
1634         strset_destroy(&stringset);
1635 }
1636
1637 static __attribute__((unused))
1638 void dbg_pos(const source_position_t source_position)
1639 {
1640         fprintf(stdout, "%s:%u\n", source_position.input_name,
1641                 source_position.linenr);
1642         fflush(stdout);
1643 }