Repair the order of tokens.
[cparser] / lexer.c
1 #include <config.h>
2
3 #include "lexer.h"
4 #include "token_t.h"
5 #include "symbol_table_t.h"
6 #include "adt/error.h"
7 #include "adt/strset.h"
8 #include "adt/util.h"
9 #include "types.h"
10 #include "type_t.h"
11 #include "target_architecture.h"
12 #include "parser.h"
13
14 #include <assert.h>
15 #include <errno.h>
16 #include <string.h>
17 #include <stdbool.h>
18 #include <ctype.h>
19
20 //#define DEBUG_CHARS
21 #define MAX_PUTBACK 3
22
23 #ifdef _WIN32
24 /* No strtold on windows and no replacement yet */
25 #define strtold(s, e) strtod(s, e)
26 #endif
27
28 #if defined HAS_SIGNED_CHAR
29 typedef signed char char_type;
30 #elif defined HAS_UNSIGNED_CHAR
31 typedef unsigned char char_type;
32 #else
33 #       error signedness of char not determined
34 #endif
35
36 static int         c;
37 token_t            lexer_token;
38 symbol_t          *symbol_L;
39 static FILE       *input;
40 static char        buf[1024 + MAX_PUTBACK];
41 static const char *bufend;
42 static const char *bufpos;
43 static strset_t    stringset;
44
45 static void error_prefix_at(const char *input_name, unsigned linenr)
46 {
47         fprintf(stderr, "%s:%u: Error: ", input_name, linenr);
48 }
49
50 static void error_prefix(void)
51 {
52         error_prefix_at(lexer_token.source_position.input_name,
53                         lexer_token.source_position.linenr);
54 }
55
56 static void parse_error(const char *msg)
57 {
58         error_prefix();
59         fprintf(stderr, "%s\n", msg);
60 }
61
62 static inline void next_real_char(void)
63 {
64         bufpos++;
65         if(bufpos >= bufend) {
66                 size_t s = fread(buf + MAX_PUTBACK, 1, sizeof(buf) - MAX_PUTBACK,
67                                  input);
68                 if(s == 0) {
69                         c = EOF;
70                         return;
71                 }
72                 bufpos = buf + MAX_PUTBACK;
73                 bufend = buf + MAX_PUTBACK + s;
74         }
75         c = *(bufpos);
76 }
77
78 static inline void put_back(int pc)
79 {
80         assert(bufpos >= buf);
81         //assert(bufpos < buf+MAX_PUTBACK || *bufpos == pc);
82
83         char *p = buf + (bufpos - buf);
84         *p = (char) pc;
85
86         /* going backwards in the buffer is legal as long as it's not more often
87          * than MAX_PUTBACK */
88         bufpos--;
89
90 #ifdef DEBUG_CHARS
91         printf("putback '%c'\n", pc);
92 #endif
93 }
94
95 static inline void next_char(void);
96
97 #define MATCH_NEWLINE(code)                   \
98         case '\r':                                \
99                 next_char();                          \
100                 if(c == '\n') {                       \
101                         next_char();                      \
102                 }                                     \
103                 lexer_token.source_position.linenr++; \
104                 code;                                 \
105         case '\n':                                \
106                 next_char();                          \
107                 lexer_token.source_position.linenr++; \
108                 code;
109
110 #define eat(c_type)  do { assert(c == c_type); next_char(); } while(0)
111
112 static void maybe_concat_lines(void)
113 {
114         eat('\\');
115
116         switch(c) {
117         MATCH_NEWLINE(return;)
118
119         default:
120                 break;
121         }
122
123         put_back(c);
124         c = '\\';
125 }
126
127 static inline void next_char(void)
128 {
129         next_real_char();
130
131         /* filter trigraphs */
132         if(UNLIKELY(c == '\\')) {
133                 maybe_concat_lines();
134                 goto end_of_next_char;
135         }
136
137         if(LIKELY(c != '?'))
138                 goto end_of_next_char;
139
140         next_real_char();
141         if(LIKELY(c != '?')) {
142                 put_back(c);
143                 c = '?';
144                 goto end_of_next_char;
145         }
146
147         next_real_char();
148         switch(c) {
149         case '=': c = '#'; break;
150         case '(': c = '['; break;
151         case '/': c = '\\'; maybe_concat_lines(); break;
152         case ')': c = ']'; break;
153         case '\'': c = '^'; break;
154         case '<': c = '{'; break;
155         case '!': c = '|'; break;
156         case '>': c = '}'; break;
157         case '-': c = '~'; break;
158         default:
159                 put_back('?');
160                 put_back(c);
161                 c = '?';
162                 break;
163         }
164
165 end_of_next_char:;
166 #ifdef DEBUG_CHARS
167         printf("nchar '%c'\n", c);
168 #endif
169 }
170
171 #define SYMBOL_CHARS  \
172         case 'a':         \
173         case 'b':         \
174         case 'c':         \
175         case 'd':         \
176         case 'e':         \
177         case 'f':         \
178         case 'g':         \
179         case 'h':         \
180         case 'i':         \
181         case 'j':         \
182         case 'k':         \
183         case 'l':         \
184         case 'm':         \
185         case 'n':         \
186         case 'o':         \
187         case 'p':         \
188         case 'q':         \
189         case 'r':         \
190         case 's':         \
191         case 't':         \
192         case 'u':         \
193         case 'v':         \
194         case 'w':         \
195         case 'x':         \
196         case 'y':         \
197         case 'z':         \
198         case 'A':         \
199         case 'B':         \
200         case 'C':         \
201         case 'D':         \
202         case 'E':         \
203         case 'F':         \
204         case 'G':         \
205         case 'H':         \
206         case 'I':         \
207         case 'J':         \
208         case 'K':         \
209         case 'L':         \
210         case 'M':         \
211         case 'N':         \
212         case 'O':         \
213         case 'P':         \
214         case 'Q':         \
215         case 'R':         \
216         case 'S':         \
217         case 'T':         \
218         case 'U':         \
219         case 'V':         \
220         case 'W':         \
221         case 'X':         \
222         case 'Y':         \
223         case 'Z':         \
224         case '_':
225
226 #define DIGITS        \
227         case '0':         \
228         case '1':         \
229         case '2':         \
230         case '3':         \
231         case '4':         \
232         case '5':         \
233         case '6':         \
234         case '7':         \
235         case '8':         \
236         case '9':
237
238 static void parse_symbol(void)
239 {
240         symbol_t *symbol;
241         char     *string;
242
243         obstack_1grow(&symbol_obstack, (char) c);
244         next_char();
245
246         while(1) {
247                 switch(c) {
248                 DIGITS
249                 SYMBOL_CHARS
250                         obstack_1grow(&symbol_obstack, (char) c);
251                         next_char();
252                         break;
253
254                 default:
255                         goto end_symbol;
256                 }
257         }
258
259 end_symbol:
260         obstack_1grow(&symbol_obstack, '\0');
261
262         string = obstack_finish(&symbol_obstack);
263         symbol = symbol_table_insert(string);
264
265         lexer_token.type     = symbol->ID;
266         lexer_token.v.symbol = symbol;
267
268         if(symbol->string != string) {
269                 obstack_free(&symbol_obstack, string);
270         }
271 }
272
273 static void parse_integer_suffix(bool is_oct_hex)
274 {
275         bool is_unsigned  = false;
276         bool min_long     = false;
277         bool min_longlong = false;
278
279         if(c == 'U' || c == 'u') {
280                 is_unsigned = true;
281                 next_char();
282                 if(c == 'L' || c == 'l') {
283                         min_long = true;
284                         next_char();
285                         if(c == 'L' || c == 'l') {
286                                 min_longlong = true;
287                                 next_char();
288                         }
289                 }
290         } else if(c == 'l' || c == 'L') {
291                 min_long = true;
292                 next_char();
293                 if(c == 'l' || c == 'L') {
294                         min_longlong = true;
295                         next_char();
296                         if(c == 'u' || c == 'U') {
297                                 is_unsigned = true;
298                                 next_char();
299                         }
300                 } else if(c == 'u' || c == 'U') {
301                         is_unsigned = true;
302                         next_char();
303                         lexer_token.datatype = type_unsigned_long;
304                 }
305         }
306
307         if(!is_unsigned) {
308                 long long v = lexer_token.v.intvalue;
309                 if(!min_long) {
310                         if(v >= TARGET_INT_MIN && v <= TARGET_INT_MAX) {
311                                 lexer_token.datatype = type_int;
312                                 return;
313                         } else if(is_oct_hex && v >= 0 && v <= TARGET_UINT_MAX) {
314                                 lexer_token.datatype = type_unsigned_int;
315                                 return;
316                         }
317                 }
318                 if(!min_longlong) {
319                         if(v >= TARGET_LONG_MIN && v <= TARGET_LONG_MAX) {
320                                 lexer_token.datatype = type_long;
321                                 return;
322                         } else if(is_oct_hex && v >= 0 && v <= TARGET_ULONG_MAX) {
323                                 lexer_token.datatype = type_unsigned_long;
324                                 return;
325                         }
326                 }
327                 unsigned long long uv = (unsigned long long) v;
328                 if(is_oct_hex && uv > (unsigned long long) TARGET_LONGLONG_MAX) {
329                         lexer_token.datatype = type_unsigned_long_long;
330                         return;
331                 }
332
333                 lexer_token.datatype = type_long_long;
334         } else {
335                 unsigned long long v = (unsigned long long) lexer_token.v.intvalue;
336                 if(!min_long && v <= TARGET_UINT_MAX) {
337                         lexer_token.datatype = type_unsigned_int;
338                         return;
339                 }
340                 if(!min_longlong && v <= TARGET_ULONG_MAX) {
341                         lexer_token.datatype = type_unsigned_long;
342                         return;
343                 }
344                 lexer_token.datatype = type_unsigned_long_long;
345         }
346 }
347
348 static void parse_floating_suffix(void)
349 {
350         switch(c) {
351         /* TODO: do something usefull with the suffixes... */
352         case 'f':
353         case 'F':
354                 next_char();
355                 lexer_token.datatype = type_float;
356                 break;
357         case 'l':
358         case 'L':
359                 next_char();
360                 lexer_token.datatype = type_long_double;
361                 break;
362         default:
363                 lexer_token.datatype = type_double;
364                 break;
365         }
366 }
367
368 /**
369  * A replacement for strtoull. Only those parts needed for
370  * our parser are implemented.
371  */
372 static unsigned long long parse_int_string(const char *s, const char **endptr, int base) {
373         unsigned long long v = 0;
374
375         switch (base) {
376         case 16:
377                 for (;; ++s) {
378                         /* check for overrun */
379                         if (v >= 0x1000000000000000ULL)
380                                 break;
381                         switch (tolower(*s)) {
382                         case '0': v <<= 4; break;
383                         case '1': v <<= 4; v |= 0x1; break;
384                         case '2': v <<= 4; v |= 0x2; break;
385                         case '3': v <<= 4; v |= 0x3; break;
386                         case '4': v <<= 4; v |= 0x4; break;
387                         case '5': v <<= 4; v |= 0x5; break;
388                         case '6': v <<= 4; v |= 0x6; break;
389                         case '7': v <<= 4; v |= 0x7; break;
390                         case '8': v <<= 4; v |= 0x8; break;
391                         case '9': v <<= 4; v |= 0x9; break;
392                         case 'a': v <<= 4; v |= 0xa; break;
393                         case 'b': v <<= 4; v |= 0xb; break;
394                         case 'c': v <<= 4; v |= 0xc; break;
395                         case 'd': v <<= 4; v |= 0xd; break;
396                         case 'e': v <<= 4; v |= 0xe; break;
397                         case 'f': v <<= 4; v |= 0xf; break;
398                         default:
399                                 goto end;
400                         }
401                 }
402                 break;
403         case 8:
404                 for (;; ++s) {
405                         /* check for overrun */
406                         if (v >= 0x2000000000000000ULL)
407                                 break;
408                         switch (tolower(*s)) {
409                         case '0': v <<= 3; break;
410                         case '1': v <<= 3; v |= 1; break;
411                         case '2': v <<= 3; v |= 2; break;
412                         case '3': v <<= 3; v |= 3; break;
413                         case '4': v <<= 3; v |= 4; break;
414                         case '5': v <<= 3; v |= 5; break;
415                         case '6': v <<= 3; v |= 6; break;
416                         case '7': v <<= 3; v |= 7; break;
417                         default:
418                                 goto end;
419                         }
420                 }
421                 break;
422         case 10:
423                 for (;; ++s) {
424                         /* check for overrun */
425                         if (v > 0x1999999999999999ULL)
426                                 break;
427                         switch (tolower(*s)) {
428                         case '0': v *= 10; break;
429                         case '1': v *= 10; v += 1; break;
430                         case '2': v *= 10; v += 2; break;
431                         case '3': v *= 10; v += 3; break;
432                         case '4': v *= 10; v += 4; break;
433                         case '5': v *= 10; v += 5; break;
434                         case '6': v *= 10; v += 6; break;
435                         case '7': v *= 10; v += 7; break;
436                         case '8': v *= 10; v += 8; break;
437                         case '9': v *= 10; v += 9; break;
438                         default:
439                                 goto end;
440                         }
441                 }
442                 break;
443         default:
444                 assert(0);
445                 break;
446         }
447 end:
448         *endptr = s;
449         return v;
450 }
451
452 static void parse_number_hex(void)
453 {
454         assert(c == 'x' || c == 'X');
455         next_char();
456
457         while(isxdigit(c)) {
458                 obstack_1grow(&symbol_obstack, (char) c);
459                 next_char();
460         }
461         obstack_1grow(&symbol_obstack, '\0');
462         char *string = obstack_finish(&symbol_obstack);
463
464         if(c == '.' || c == 'p' || c == 'P') {
465                 next_char();
466                 panic("Hex floating point numbers not implemented yet");
467         }
468         if(*string == '\0') {
469                 parse_error("invalid hex number");
470                 lexer_token.type = T_ERROR;
471         }
472
473         const char *endptr;
474         lexer_token.type       = T_INTEGER;
475         lexer_token.v.intvalue = parse_int_string(string, &endptr, 16);
476         if(*endptr != '\0') {
477                 parse_error("hex number literal too long");
478         }
479
480         obstack_free(&symbol_obstack, string);
481         parse_integer_suffix(true);
482 }
483
484 static inline bool is_octal_digit(int chr)
485 {
486         return '0' <= chr && chr <= '7';
487 }
488
489 static void parse_number_oct(void)
490 {
491         while(is_octal_digit(c)) {
492                 obstack_1grow(&symbol_obstack, (char) c);
493                 next_char();
494         }
495         obstack_1grow(&symbol_obstack, '\0');
496         char *string = obstack_finish(&symbol_obstack);
497
498         const char *endptr;
499         lexer_token.type       = T_INTEGER;
500         lexer_token.v.intvalue = parse_int_string(string, &endptr, 8);
501         if(*endptr != '\0') {
502                 parse_error("octal number literal too long");
503         }
504
505         obstack_free(&symbol_obstack, string);
506         parse_integer_suffix(true);
507 }
508
509 static void parse_number_dec(void)
510 {
511         bool is_float = false;
512         while(isdigit(c)) {
513                 obstack_1grow(&symbol_obstack, (char) c);
514                 next_char();
515         }
516
517         if(c == '.') {
518                 obstack_1grow(&symbol_obstack, '.');
519                 next_char();
520
521                 while(isdigit(c)) {
522                         obstack_1grow(&symbol_obstack, (char) c);
523                         next_char();
524                 }
525                 is_float = true;
526         }
527         if(c == 'e' || c == 'E') {
528                 obstack_1grow(&symbol_obstack, 'e');
529                 next_char();
530
531                 if(c == '-' || c == '+') {
532                         obstack_1grow(&symbol_obstack, (char) c);
533                         next_char();
534                 }
535
536                 while(isdigit(c)) {
537                         obstack_1grow(&symbol_obstack, (char) c);
538                         next_char();
539                 }
540                 is_float = true;
541         }
542
543         obstack_1grow(&symbol_obstack, '\0');
544         char *string = obstack_finish(&symbol_obstack);
545
546         if(is_float) {
547                 char *endptr;
548                 lexer_token.type         = T_FLOATINGPOINT;
549                 lexer_token.v.floatvalue = strtold(string, &endptr);
550
551                 if(*endptr != '\0') {
552                         parse_error("invalid number literal");
553                 }
554
555                 parse_floating_suffix();
556         } else {
557                 const char *endptr;
558                 lexer_token.type       = T_INTEGER;
559                 lexer_token.v.intvalue = parse_int_string(string, &endptr, 10);
560
561                 if(*endptr != '\0') {
562                         parse_error("invalid number literal");
563                 }
564
565                 parse_integer_suffix(false);
566         }
567         obstack_free(&symbol_obstack, string);
568 }
569
570 static void parse_number(void)
571 {
572         if (c == '0') {
573                 next_char();
574                 switch (c) {
575                         case 'X':
576                         case 'x':
577                                 parse_number_hex();
578                                 break;
579                         case '0':
580                         case '1':
581                         case '2':
582                         case '3':
583                         case '4':
584                         case '5':
585                         case '6':
586                         case '7':
587                                 parse_number_oct();
588                                 break;
589                         case '8':
590                         case '9':
591                                 next_char();
592                                 parse_error("invalid octal number");
593                                 lexer_token.type = T_ERROR;
594                                 return;
595                         case '.':
596                         case 'e':
597                         case 'E':
598                         default:
599                                 obstack_1grow(&symbol_obstack, '0');
600                                 parse_number_dec();
601                                 return;
602                 }
603         } else {
604                 parse_number_dec();
605         }
606 }
607
608 static int parse_octal_sequence(const int first_digit)
609 {
610         assert(is_octal_digit(first_digit));
611         int value = first_digit - '0';
612         if (!is_octal_digit(c)) return value;
613         value = 8 * value + c - '0';
614         next_char();
615         if (!is_octal_digit(c)) return value;
616         value = 8 * value + c - '0';
617         next_char();
618         return (char_type)value;
619 }
620
621 static int parse_hex_sequence(void)
622 {
623         int value = 0;
624         while(1) {
625                 if (c >= '0' && c <= '9') {
626                         value = 16 * value + c - '0';
627                 } else if ('A' <= c && c <= 'F') {
628                         value = 16 * value + c - 'A' + 10;
629                 } else if ('a' <= c && c <= 'f') {
630                         value = 16 * value + c - 'a' + 10;
631                 } else {
632                         break;
633                 }
634                 next_char();
635         }
636
637         return (char_type)value;
638 }
639
640 static int parse_escape_sequence(void)
641 {
642         eat('\\');
643
644         int ec = c;
645         next_char();
646
647         switch(ec) {
648         case '"':  return '"';
649         case '\'': return '\'';
650         case '\\': return '\\';
651         case '?': return '\?';
652         case 'a': return '\a';
653         case 'b': return '\b';
654         case 'f': return '\f';
655         case 'n': return '\n';
656         case 'r': return '\r';
657         case 't': return '\t';
658         case 'v': return '\v';
659         case 'x':
660                 return parse_hex_sequence();
661         case '0':
662         case '1':
663         case '2':
664         case '3':
665         case '4':
666         case '5':
667         case '6':
668         case '7':
669                 return parse_octal_sequence(ec);
670         case EOF:
671                 parse_error("reached end of file while parsing escape sequence");
672                 return EOF;
673         default:
674                 parse_error("unknown escape sequence");
675                 return EOF;
676         }
677 }
678
679 const char *concat_strings(const char *s1, const char *s2)
680 {
681         size_t  len1   = strlen(s1);
682         size_t  len2   = strlen(s2);
683
684         char   *concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
685         memcpy(concat, s1, len1);
686         memcpy(concat + len1, s2, len2 + 1);
687
688         const char *result = strset_insert(&stringset, concat);
689         if(result != concat) {
690                 obstack_free(&symbol_obstack, concat);
691         }
692
693         return result;
694 }
695
696 static void parse_string_literal(void)
697 {
698         unsigned    start_linenr = lexer_token.source_position.linenr;
699         char       *string;
700         const char *result;
701
702         assert(c == '"');
703         next_char();
704
705         int tc;
706         while(1) {
707                 switch(c) {
708                 case '\\':
709                         tc = parse_escape_sequence();
710                         obstack_1grow(&symbol_obstack, (char) tc);
711                         break;
712
713                 case EOF:
714                         error_prefix_at(lexer_token.source_position.input_name,
715                                         start_linenr);
716                         fprintf(stderr, "string has no end\n");
717                         lexer_token.type = T_ERROR;
718                         return;
719
720                 case '"':
721                         next_char();
722                         goto end_of_string;
723
724                 default:
725                         obstack_1grow(&symbol_obstack, (char) c);
726                         next_char();
727                         break;
728                 }
729         }
730
731 end_of_string:
732
733         /* TODO: concatenate multiple strings separated by whitespace... */
734
735         /* add finishing 0 to the string */
736         obstack_1grow(&symbol_obstack, '\0');
737         string = obstack_finish(&symbol_obstack);
738
739         /* check if there is already a copy of the string */
740         result = strset_insert(&stringset, string);
741         if(result != string) {
742                 obstack_free(&symbol_obstack, string);
743         }
744
745         lexer_token.type     = T_STRING_LITERAL;
746         lexer_token.v.string = result;
747 }
748
749 static void parse_wide_character_constant(void)
750 {
751         eat('\'');
752
753         int found_char = 0;
754         while(1) {
755                 switch(c) {
756                 case '\\':
757                         found_char = parse_escape_sequence();
758                         break;
759
760                 MATCH_NEWLINE(
761                         parse_error("newline while parsing character constant");
762                         break;
763                 )
764
765                 case '\'':
766                         next_char();
767                         goto end_of_wide_char_constant;
768
769                 case EOF:
770                         parse_error("EOF while parsing character constant");
771                         lexer_token.type = T_ERROR;
772                         return;
773
774                 default:
775                         if(found_char != 0) {
776                                 parse_error("more than 1 characters in character "
777                                             "constant");
778                                 goto end_of_wide_char_constant;
779                         } else {
780                                 found_char = c;
781                                 next_char();
782                         }
783                         break;
784                 }
785         }
786
787 end_of_wide_char_constant:
788         lexer_token.type       = T_INTEGER;
789         lexer_token.v.intvalue = found_char;
790         lexer_token.datatype   = type_wchar_t;
791 }
792
793 static void parse_wide_string_literal(void)
794 {
795         const unsigned start_linenr = lexer_token.source_position.linenr;
796
797         assert(c == '"');
798         next_char();
799
800         while(1) {
801                 switch(c) {
802                         case '\\': {
803                                 wchar_rep_t tc = parse_escape_sequence();
804                                 obstack_grow(&symbol_obstack, &tc, sizeof(tc));
805                                 break;
806                         }
807
808                         case EOF:
809                                 error_prefix_at(lexer_token.source_position.input_name,
810                                                 start_linenr);
811                                 fprintf(stderr, "string has no end\n");
812                                 lexer_token.type = T_ERROR;
813                                 return;
814
815                         case '"':
816                                 next_char();
817                                 goto end_of_string;
818
819                         default: {
820                                 wchar_rep_t tc = c;
821                                 obstack_grow(&symbol_obstack, &tc, sizeof(tc));
822                                 next_char();
823                                 break;
824                         }
825                 }
826         }
827
828 end_of_string:;
829
830         /* TODO: concatenate multiple strings separated by whitespace... */
831
832         /* add finishing 0 to the string */
833         wchar_rep_t nul = L'\0';
834         obstack_grow(&symbol_obstack, &nul, sizeof(nul));
835         const size_t             size   = (size_t)obstack_object_size(&symbol_obstack) / sizeof(wchar_rep_t);
836         const wchar_rep_t *const string = obstack_finish(&symbol_obstack);
837
838 #if 0 /* TODO hash */
839         /* check if there is already a copy of the string */
840         const wchar_rep_t *const result = strset_insert(&stringset, string);
841         if(result != string) {
842                 obstack_free(&symbol_obstack, string);
843         }
844 #else
845         const wchar_rep_t *const result = string;
846 #endif
847
848         lexer_token.type                = T_WIDE_STRING_LITERAL;
849         lexer_token.v.wide_string.begin = result;
850         lexer_token.v.wide_string.size  = size;
851 }
852
853 static void parse_character_constant(void)
854 {
855         eat('\'');
856
857         int found_char = 0;
858         while(1) {
859                 switch(c) {
860                 case '\\':
861                         found_char = parse_escape_sequence();
862                         break;
863
864                 MATCH_NEWLINE(
865                         parse_error("newline while parsing character constant");
866                         break;
867                 )
868
869                 case '\'':
870                         next_char();
871                         goto end_of_char_constant;
872
873                 case EOF:
874                         parse_error("EOF while parsing character constant");
875                         lexer_token.type = T_ERROR;
876                         return;
877
878                 default:
879                         if(found_char != 0) {
880                                 parse_error("more than 1 characters in character "
881                                             "constant");
882                                 goto end_of_char_constant;
883                         } else {
884                                 found_char = c;
885                                 next_char();
886                         }
887                         break;
888                 }
889         }
890
891 end_of_char_constant:
892         lexer_token.type       = T_INTEGER;
893         lexer_token.v.intvalue = found_char;
894         lexer_token.datatype   = type_int;
895 }
896
897 static void skip_multiline_comment(void)
898 {
899         unsigned start_linenr = lexer_token.source_position.linenr;
900
901         while(1) {
902                 switch(c) {
903                 case '*':
904                         next_char();
905                         if(c == '/') {
906                                 next_char();
907                                 return;
908                         }
909                         break;
910
911                 MATCH_NEWLINE(break;)
912
913                 case EOF:
914                         error_prefix_at(lexer_token.source_position.input_name,
915                                         start_linenr);
916                         fprintf(stderr, "at end of file while looking for comment end\n");
917                         return;
918
919                 default:
920                         next_char();
921                         break;
922                 }
923         }
924 }
925
926 static void skip_line_comment(void)
927 {
928         while(1) {
929                 switch(c) {
930                 case EOF:
931                         return;
932
933                 case '\n':
934                 case '\r':
935                         return;
936
937                 default:
938                         next_char();
939                         break;
940                 }
941         }
942 }
943
944 static token_t pp_token;
945
946 static inline void next_pp_token(void)
947 {
948         lexer_next_preprocessing_token();
949         pp_token = lexer_token;
950 }
951
952 static void eat_until_newline(void)
953 {
954         while(pp_token.type != '\n' && pp_token.type != T_EOF) {
955                 next_pp_token();
956         }
957 }
958
959 static void error_directive(void)
960 {
961         error_prefix();
962         fprintf(stderr, "#error directive: \n");
963
964         /* parse pp-tokens until new-line */
965 }
966
967 static void define_directive(void)
968 {
969         lexer_next_preprocessing_token();
970         if(lexer_token.type != T_IDENTIFIER) {
971                 parse_error("expected identifier after #define\n");
972                 eat_until_newline();
973         }
974 }
975
976 static void ifdef_directive(int is_ifndef)
977 {
978         (void) is_ifndef;
979         lexer_next_preprocessing_token();
980         //expect_identifier();
981         //extect_newline();
982 }
983
984 static void endif_directive(void)
985 {
986         //expect_newline();
987 }
988
989 static void parse_line_directive(void)
990 {
991         if(pp_token.type != T_INTEGER) {
992                 parse_error("expected integer");
993         } else {
994                 lexer_token.source_position.linenr = (unsigned int)(pp_token.v.intvalue - 1);
995                 next_pp_token();
996         }
997         if(pp_token.type == T_STRING_LITERAL) {
998                 lexer_token.source_position.input_name = pp_token.v.string;
999                 next_pp_token();
1000         }
1001
1002         eat_until_newline();
1003 }
1004
1005 static void parse_preprocessor_identifier(void)
1006 {
1007         assert(pp_token.type == T_IDENTIFIER);
1008         symbol_t *symbol = pp_token.v.symbol;
1009
1010         switch(symbol->pp_ID) {
1011         case TP_include:
1012                 printf("include - enable header name parsing!\n");
1013                 break;
1014         case TP_define:
1015                 define_directive();
1016                 break;
1017         case TP_ifdef:
1018                 ifdef_directive(0);
1019                 break;
1020         case TP_ifndef:
1021                 ifdef_directive(1);
1022                 break;
1023         case TP_endif:
1024                 endif_directive();
1025                 break;
1026         case TP_line:
1027                 next_pp_token();
1028                 parse_line_directive();
1029                 break;
1030         case TP_if:
1031         case TP_else:
1032         case TP_elif:
1033         case TP_undef:
1034         case TP_error:
1035                 error_directive();
1036                 break;
1037         case TP_pragma:
1038                 break;
1039         }
1040 }
1041
1042 static void parse_preprocessor_directive(void)
1043 {
1044         next_pp_token();
1045
1046         switch(pp_token.type) {
1047         case T_IDENTIFIER:
1048                 parse_preprocessor_identifier();
1049                 break;
1050         case T_INTEGER:
1051                 parse_line_directive();
1052                 break;
1053         default:
1054                 parse_error("invalid preprocessor directive");
1055                 eat_until_newline();
1056                 break;
1057         }
1058 }
1059
1060 #define MAYBE_PROLOG                                       \
1061                         next_char();                                   \
1062                         while(1) {                                     \
1063                                 switch(c) {
1064
1065 #define MAYBE(ch, set_type)                                \
1066                                 case ch:                                   \
1067                                         next_char();                           \
1068                                         lexer_token.type = set_type;           \
1069                                         return;
1070
1071 #define ELSE_CODE(code)                                    \
1072                                 default:                                   \
1073                                         code;                                  \
1074                                 }                                          \
1075                         } /* end of while(1) */                        \
1076                         break;
1077
1078 #define ELSE(set_type)                                     \
1079                 ELSE_CODE(                                         \
1080                         lexer_token.type = set_type;                   \
1081                         return;                                        \
1082                 )
1083
1084 void lexer_next_preprocessing_token(void)
1085 {
1086         while(1) {
1087                 switch(c) {
1088                 case ' ':
1089                 case '\t':
1090                         next_char();
1091                         break;
1092
1093                 MATCH_NEWLINE(
1094                         lexer_token.type = '\n';
1095                         return;
1096                 )
1097
1098                 SYMBOL_CHARS
1099                         parse_symbol();
1100                         /* might be a wide string ( L"string" ) */
1101                         if(lexer_token.type == T_IDENTIFIER &&
1102                             lexer_token.v.symbol == symbol_L) {
1103                             if(c == '"') {
1104                                         parse_wide_string_literal();
1105                                 } else if(c == '\'') {
1106                                         parse_wide_character_constant();
1107                                 }
1108                         }
1109                         return;
1110
1111                 DIGITS
1112                         parse_number();
1113                         return;
1114
1115                 case '"':
1116                         parse_string_literal();
1117                         return;
1118
1119                 case '\'':
1120                         parse_character_constant();
1121                         return;
1122
1123                 case '.':
1124                         MAYBE_PROLOG
1125                                 case '.':
1126                                         MAYBE_PROLOG
1127                                         MAYBE('.', T_DOTDOTDOT)
1128                                         ELSE_CODE(
1129                                                 put_back(c);
1130                                                 c = '.';
1131                                                 lexer_token.type = '.';
1132                                                 return;
1133                                         )
1134                         ELSE('.')
1135                 case '&':
1136                         MAYBE_PROLOG
1137                         MAYBE('&', T_ANDAND)
1138                         MAYBE('=', T_ANDEQUAL)
1139                         ELSE('&')
1140                 case '*':
1141                         MAYBE_PROLOG
1142                         MAYBE('=', T_ASTERISKEQUAL)
1143                         ELSE('*')
1144                 case '+':
1145                         MAYBE_PROLOG
1146                         MAYBE('+', T_PLUSPLUS)
1147                         MAYBE('=', T_PLUSEQUAL)
1148                         ELSE('+')
1149                 case '-':
1150                         MAYBE_PROLOG
1151                         MAYBE('>', T_MINUSGREATER)
1152                         MAYBE('-', T_MINUSMINUS)
1153                         MAYBE('=', T_MINUSEQUAL)
1154                         ELSE('-')
1155                 case '!':
1156                         MAYBE_PROLOG
1157                         MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1158                         ELSE('!')
1159                 case '/':
1160                         MAYBE_PROLOG
1161                         MAYBE('=', T_SLASHEQUAL)
1162                                 case '*':
1163                                         next_char();
1164                                         skip_multiline_comment();
1165                                         lexer_next_preprocessing_token();
1166                                         return;
1167                                 case '/':
1168                                         next_char();
1169                                         skip_line_comment();
1170                                         lexer_next_preprocessing_token();
1171                                         return;
1172                         ELSE('/')
1173                 case '%':
1174                         MAYBE_PROLOG
1175                         MAYBE('>', T_PERCENTGREATER)
1176                         MAYBE('=', T_PERCENTEQUAL)
1177                                 case ':':
1178                                         MAYBE_PROLOG
1179                                                 case '%':
1180                                                         MAYBE_PROLOG
1181                                                         MAYBE(':', T_PERCENTCOLONPERCENTCOLON)
1182                                                         ELSE_CODE(
1183                                                                 put_back(c);
1184                                                                 c = '%';
1185                                                                 lexer_token.type = T_PERCENTCOLON;
1186                                                                 return;
1187                                                         )
1188                                         ELSE(T_PERCENTCOLON)
1189                         ELSE('%')
1190                 case '<':
1191                         MAYBE_PROLOG
1192                         MAYBE(':', T_LESSCOLON)
1193                         MAYBE('%', T_LESSPERCENT)
1194                         MAYBE('=', T_LESSEQUAL)
1195                                 case '<':
1196                                         MAYBE_PROLOG
1197                                         MAYBE('=', T_LESSLESSEQUAL)
1198                                         ELSE(T_LESSLESS)
1199                         ELSE('<')
1200                 case '>':
1201                         MAYBE_PROLOG
1202                         MAYBE('=', T_GREATEREQUAL)
1203                                 case '>':
1204                                         MAYBE_PROLOG
1205                                         MAYBE('=', T_GREATERGREATEREQUAL)
1206                                         ELSE(T_GREATERGREATER)
1207                         ELSE('>')
1208                 case '^':
1209                         MAYBE_PROLOG
1210                         MAYBE('=', T_CARETEQUAL)
1211                         ELSE('^')
1212                 case '|':
1213                         MAYBE_PROLOG
1214                         MAYBE('=', T_PIPEEQUAL)
1215                         MAYBE('|', T_PIPEPIPE)
1216                         ELSE('|')
1217                 case ':':
1218                         MAYBE_PROLOG
1219                         MAYBE('>', T_COLONGREATER)
1220                         ELSE(':')
1221                 case '=':
1222                         MAYBE_PROLOG
1223                         MAYBE('=', T_EQUALEQUAL)
1224                         ELSE('=')
1225                 case '#':
1226                         MAYBE_PROLOG
1227                         MAYBE('#', T_HASHHASH)
1228                         ELSE('#')
1229
1230                 case '?':
1231                 case '[':
1232                 case ']':
1233                 case '(':
1234                 case ')':
1235                 case '{':
1236                 case '}':
1237                 case '~':
1238                 case ';':
1239                 case ',':
1240                 case '\\':
1241                         lexer_token.type = c;
1242                         next_char();
1243                         return;
1244
1245                 case EOF:
1246                         lexer_token.type = T_EOF;
1247                         return;
1248
1249                 default:
1250                         next_char();
1251                         error_prefix();
1252                         fprintf(stderr, "unknown character '%c' found\n", c);
1253                         lexer_token.type = T_ERROR;
1254                         return;
1255                 }
1256         }
1257 }
1258
1259 void lexer_next_token(void)
1260 {
1261         lexer_next_preprocessing_token();
1262         if(lexer_token.type != '\n')
1263                 return;
1264
1265 newline_found:
1266         do {
1267                 lexer_next_preprocessing_token();
1268         } while(lexer_token.type == '\n');
1269
1270         if(lexer_token.type == '#') {
1271                 parse_preprocessor_directive();
1272                 goto newline_found;
1273         }
1274 }
1275
1276 void init_lexer(void)
1277 {
1278         strset_init(&stringset);
1279 }
1280
1281 void lexer_open_stream(FILE *stream, const char *input_name)
1282 {
1283         input                                  = stream;
1284         lexer_token.source_position.linenr     = 0;
1285         lexer_token.source_position.input_name = input_name;
1286
1287         symbol_L = symbol_table_insert("L");
1288
1289         /* place a virtual \n at the beginning so the lexer knows that we're
1290          * at the beginning of a line */
1291         c = '\n';
1292 }
1293
1294 void exit_lexer(void)
1295 {
1296         strset_destroy(&stringset);
1297 }
1298
1299 static __attribute__((unused))
1300 void dbg_pos(const source_position_t source_position)
1301 {
1302         fprintf(stdout, "%s:%u\n", source_position.input_name,
1303                 source_position.linenr);
1304         fflush(stdout);
1305 }