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