2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
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.
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.
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
22 #include "adt/strutil.h"
24 #include "diagnostic.h"
28 #include "symbol_table_t.h"
29 #include "adt/error.h"
30 #include "adt/strset.h"
36 #include "lang_features.h"
48 #define MAX_PUTBACK 16 // 3 would be enough, but 16 gives a nicer alignment
51 static input_t *input;
52 static utf32 input_buf[BUF_SIZE + MAX_PUTBACK];
53 static const utf32 *bufpos;
54 static const utf32 *bufend;
56 static source_position_t lexer_pos;
58 static symbol_t *symbol_L;
59 static strset_t stringset;
60 bool allow_dollar_in_symbol = true;
63 * Prints a parse error message at the current token.
65 * @param msg the error message
67 static void parse_error(const char *msg)
69 errorf(&lexer_pos, "%s", msg);
73 * Prints an internal error message at the current token.
75 * @param msg the error message
77 static NORETURN internal_error(const char *msg)
79 internal_errorf(&lexer_pos, "%s", msg);
82 static inline void next_real_char(void)
84 assert(bufpos <= bufend);
85 if (bufpos >= bufend) {
86 size_t n = decode(input, input_buf+MAX_PUTBACK, BUF_SIZE);
91 bufpos = input_buf + MAX_PUTBACK;
99 * Put a character back into the buffer.
101 * @param pc the character to put back
103 static inline void put_back(utf32 const pc)
105 *(--bufpos - input_buf + input_buf) = pc;
109 static inline void next_char(void);
118 lexer_pos.lineno++; \
119 lexer_pos.colno = 1; \
121 newline // Let it look like an ordinary case label.
123 #define eat(c_type) (assert(c == c_type), next_char())
125 static void maybe_concat_lines(void)
142 * Set c to the next input character, ie.
143 * after expanding trigraphs.
145 static inline void next_char(void)
149 /* filter trigraphs */
150 if (UNLIKELY(c == '\\')) {
151 maybe_concat_lines();
155 if (LIKELY(c != '?'))
159 if (LIKELY(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;
184 #define SYMBOL_CHARS \
185 case '$': if (!allow_dollar_in_symbol) goto dollar_sign; \
252 static bool is_universal_char_valid(utf32 const v)
255 if (v < 0xA0U && v != 0x24 && v != 0x40 && v != 0x60)
257 if (0xD800 <= v && v <= 0xDFFF)
262 static int digit_value(utf32 digit);
264 static utf32 parse_universal_char(unsigned const n_digits)
267 for (unsigned k = n_digits; k != 0; --k) {
269 v = 16 * v + digit_value(c);
272 errorf(&lexer_pos, "short universal character name, expected %u more digits", k);
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);
282 static bool is_universal_char_valid_identifier(utf32 const v)
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;
333 static bool is_universal_char_valid_identifier_start(utf32 const v)
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;
344 * Read a symbol from the input and build
347 static void parse_symbol(void)
353 obstack_1grow(&symbol_obstack, (char) c);
362 case 'U': n = 8; goto universal;
363 case 'u': n = 4; goto universal;
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);
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);
374 obstack_grow_symbol(&symbol_obstack, v);
392 obstack_1grow(&symbol_obstack, '\0');
394 char *string = obstack_finish(&symbol_obstack);
395 symbol_t *symbol = symbol_table_insert(string);
397 lexer_token.kind = symbol->ID;
398 lexer_token.base.symbol = symbol;
400 if (symbol->string != string) {
401 obstack_free(&symbol_obstack, string);
405 static string_t sym_make_string(void)
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);
413 const char *result = strset_insert(&stringset, concat);
414 if (result != concat) {
415 obstack_free(&symbol_obstack, concat);
418 const char *result = string;
420 return (string_t) {result, len};
424 * parse suffixes like 'LU' or 'f' after numbers
426 static void parse_number_suffix(void)
428 assert(obstack_object_size(&symbol_obstack) == 0);
432 obstack_1grow(&symbol_obstack, (char) c);
441 if (obstack_object_size(&symbol_obstack) == 0) {
442 lexer_token.number.suffix.begin = NULL;
443 lexer_token.number.suffix.size = 0;
447 lexer_token.number.suffix = sym_make_string();
450 static void parse_exponent(void)
452 if (c == '-' || c == '+') {
453 obstack_1grow(&symbol_obstack, (char)c);
459 obstack_1grow(&symbol_obstack, (char)c);
461 } while (isdigit(c));
463 errorf(&lexer_token.base.source_position, "exponent has no digits");
468 * Parses a hex number including hex floats and set the
471 static void parse_number_hex(void)
473 bool is_float = false;
474 bool has_digits = false;
476 while (isxdigit(c)) {
478 obstack_1grow(&symbol_obstack, (char) c);
484 obstack_1grow(&symbol_obstack, (char) c);
487 while (isxdigit(c)) {
489 obstack_1grow(&symbol_obstack, (char) c);
493 if (c == 'p' || c == 'P') {
495 obstack_1grow(&symbol_obstack, (char) c);
498 } else if (is_float) {
499 errorf(&lexer_token.base.source_position,
500 "hexadecimal floatingpoint constant requires an exponent");
503 lexer_token.number.number = sym_make_string();
505 lexer_token.kind = is_float ? T_FLOATINGPOINT : T_INTEGER;
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;
513 parse_number_suffix();
516 static void parse_number_bin(void)
518 bool has_digits = false;
520 while (c == '0' || c == '1') {
522 obstack_1grow(&symbol_obstack, (char)c);
526 lexer_token.number.number = sym_make_string();
527 lexer_token.kind = T_INTEGER;
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;
535 parse_number_suffix();
539 * Returns true if the given char is a octal digit.
541 * @param char the character to check
543 static bool is_octal_digit(utf32 chr)
545 return '0' <= chr && chr <= '7';
549 * Parses a number and sets the lexer_token.
551 static void parse_number(void)
553 bool is_float = false;
554 bool has_digits = false;
556 assert(obstack_object_size(&symbol_obstack) == 0);
558 obstack_1grow(&symbol_obstack, (char)c);
560 if (c == 'x' || c == 'X') {
561 obstack_1grow(&symbol_obstack, (char)c);
565 } else if (c == 'b' || c == 'B') {
566 /* GCC extension: binary constant 0x[bB][01]+. */
567 obstack_1grow(&symbol_obstack, (char)c);
577 obstack_1grow(&symbol_obstack, (char) c);
583 obstack_1grow(&symbol_obstack, '.');
588 obstack_1grow(&symbol_obstack, (char) c);
592 if (c == 'e' || c == 'E') {
594 obstack_1grow(&symbol_obstack, 'e');
599 lexer_token.number.number = sym_make_string();
602 lexer_token.kind = T_FLOATINGPOINT;
604 lexer_token.kind = T_INTEGER;
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];
611 errorf(&lexer_token.base.source_position, "invalid digit '%c' in octal number", t);
617 errorf(&lexer_token.base.source_position, "invalid number literal '%S'",
618 &lexer_token.number.number);
621 parse_number_suffix();
625 * Returns the value of a digit.
626 * The only portable way to do it ...
628 static int digit_value(utf32 const digit)
654 internal_error("wrong character given");
659 * Parses an octal character sequence.
661 * @param first_digit the already read first digit
663 static utf32 parse_octal_sequence(utf32 const first_digit)
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);
670 if (!is_octal_digit(c)) return value;
671 value = 8 * value + digit_value(c);
677 * Parses a hex character sequence.
679 static utf32 parse_hex_sequence(void)
682 while (isxdigit(c)) {
683 value = 16 * value + digit_value(c);
690 * Parse an escape sequence.
692 static utf32 parse_escape_sequence(void)
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';
712 return parse_hex_sequence();
721 return parse_octal_sequence(ec);
723 parse_error("reached end of file while parsing escape sequence");
725 /* \E is not documented, but handled, by GCC. It is acceptable according
726 * to ยง6.11.4, whereas \e is not. */
730 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
733 case 'U': return parse_universal_char(8);
734 case 'u': return parse_universal_char(4);
739 /* ยง6.4.4.4:8 footnote 64 */
740 parse_error("unknown escape sequence");
744 string_t make_string(const char *string)
746 obstack_grow(&symbol_obstack, string, strlen(string));
747 return sym_make_string();
750 static void parse_string(utf32 const delim, token_kind_t const kind, string_encoding_t const enc, char const *const context)
757 utf32 const tc = parse_escape_sequence();
758 if (enc == STRING_ENCODING_CHAR) {
760 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
762 obstack_1grow(&symbol_obstack, tc);
764 obstack_grow_symbol(&symbol_obstack, tc);
770 errorf(&lexer_pos, "newline while parsing %s", context);
774 errorf(&lexer_token.base.source_position, "EOF while parsing %s", context);
782 obstack_grow_symbol(&symbol_obstack, c);
790 lexer_token.kind = kind;
791 lexer_token.string.encoding = enc;
792 lexer_token.string.string = sym_make_string();
796 * Parse a string literal and set lexer_token.
798 static void parse_string_literal(string_encoding_t const enc)
800 parse_string('"', T_STRING_LITERAL, enc, "string literal");
804 * Parse a character constant and set lexer_token.
806 static void parse_character_constant(string_encoding_t const enc)
808 parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
809 if (lexer_token.string.string.size == 0) {
810 errorf(&lexer_token.base.source_position, "empty character constant");
815 * Skip a multiline comment.
817 static void skip_multiline_comment(void)
824 /* nested comment, warn here */
825 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
840 errorf(&lexer_token.base.source_position,
841 "at end of file while looking for comment end");
853 * Skip a single line comment.
855 static void skip_line_comment(void)
868 if (c == '\n' || c == '\r') {
869 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
881 /** The current preprocessor token. */
882 static token_t pp_token;
885 * Read the next preprocessor token.
887 static inline void next_pp_token(void)
889 lexer_next_preprocessing_token();
890 pp_token = lexer_token;
894 * Eat all preprocessor tokens until newline.
896 static void eat_until_newline(void)
898 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
904 * Parse the line directive.
906 static void parse_line_directive(void)
908 if (pp_token.kind != T_INTEGER) {
909 parse_error("expected integer");
911 /* use offset -1 as this is about the next line */
912 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
915 if (pp_token.kind == T_STRING_LITERAL && pp_token.string.encoding == STRING_ENCODING_CHAR) {
916 lexer_pos.input_name = pp_token.string.string.begin;
917 lexer_pos.is_system_header = false;
920 /* attempt to parse numeric flags as outputted by gcc preprocessor */
921 while (pp_token.kind == T_INTEGER) {
923 * 1 - indicates start of a new file
924 * 2 - indicates return from a file
925 * 3 - indicates system header
926 * 4 - indicates implicit extern "C" in C++ mode
928 * currently we're only interested in "3"
930 if (streq(pp_token.number.number.begin, "3")) {
931 lexer_pos.is_system_header = true;
943 typedef enum stdc_pragma_kind_t {
947 STDC_CX_LIMITED_RANGE
948 } stdc_pragma_kind_t;
951 * STDC pragma values.
953 typedef enum stdc_pragma_value_kind_t {
958 } stdc_pragma_value_kind_t;
961 * Parse a pragma directive.
963 static void parse_pragma(void)
966 if (pp_token.kind != T_IDENTIFIER) {
967 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
968 "expected identifier after #pragma");
973 stdc_pragma_kind_t kind = STDC_UNKNOWN;
974 if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
978 switch (pp_token.base.symbol->pp_ID) {
979 case TP_FP_CONTRACT: kind = STDC_FP_CONTRACT; break;
980 case TP_FENV_ACCESS: kind = STDC_FENV_ACCESS; break;
981 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
984 if (kind != STDC_UNKNOWN) {
986 stdc_pragma_value_kind_t value;
987 switch (pp_token.base.symbol->pp_ID) {
988 case TP_ON: value = STDC_VALUE_ON; break;
989 case TP_OFF: value = STDC_VALUE_OFF; break;
990 case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
991 default: value = STDC_VALUE_UNKNOWN; break;
993 if (value == STDC_VALUE_UNKNOWN) {
995 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
1000 if (kind == STDC_UNKNOWN) {
1001 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
1002 "encountered unknown #pragma");
1007 * Parse a preprocessor non-null directive.
1009 static void parse_preprocessor_identifier(void)
1011 assert(pp_token.kind == T_IDENTIFIER);
1012 switch (pp_token.base.symbol->pp_ID) {
1015 parse_line_directive();
1021 /* TODO; output the rest of the line */
1022 parse_error("#error directive");
1028 * Parse a preprocessor directive.
1030 static void parse_preprocessor_directive(void)
1034 switch (pp_token.kind) {
1036 parse_preprocessor_identifier();
1039 parse_line_directive();
1042 /* NULL directive, see ยง6.10.7 */
1045 parse_error("invalid preprocessor directive");
1046 eat_until_newline();
1051 #define MAYBE_PROLOG \
1056 #define MAYBE(ch, set_type) \
1059 lexer_token.kind = set_type; \
1062 /* must use this as last thing */
1063 #define MAYBE_MODE(ch, set_type, mode) \
1065 if (c_mode & mode) { \
1067 lexer_token.kind = set_type; \
1072 #define ELSE_CODE(code) \
1077 } /* end of while (true) */ \
1079 #define ELSE(set_type) \
1081 lexer_token.kind = set_type; \
1084 void lexer_next_preprocessing_token(void)
1087 lexer_token.base.source_position = lexer_pos;
1088 lexer_token.base.symbol = NULL;
1097 lexer_token.kind = '\n';
1102 /* might be a wide string ( L"string" ) */
1103 string_encoding_t const enc = STRING_ENCODING_WIDE;
1104 if (lexer_token.base.symbol == symbol_L) {
1106 case '"': parse_string_literal(enc); break;
1107 case '\'': parse_character_constant(enc); break;
1118 parse_string_literal(STRING_ENCODING_CHAR);
1122 parse_character_constant(STRING_ENCODING_CHAR);
1135 MAYBE('.', T_DOTDOTDOT)
1139 lexer_token.kind = '.';
1144 MAYBE('&', T_ANDAND)
1145 MAYBE('=', T_ANDEQUAL)
1149 MAYBE('=', T_ASTERISKEQUAL)
1153 MAYBE('+', T_PLUSPLUS)
1154 MAYBE('=', T_PLUSEQUAL)
1158 MAYBE('>', T_MINUSGREATER)
1159 MAYBE('-', T_MINUSMINUS)
1160 MAYBE('=', T_MINUSEQUAL)
1164 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1168 MAYBE('=', T_SLASHEQUAL)
1171 skip_multiline_comment();
1172 lexer_next_preprocessing_token();
1176 skip_line_comment();
1177 lexer_next_preprocessing_token();
1183 MAYBE('=', T_PERCENTEQUAL)
1188 MAYBE(':', T_HASHHASH)
1192 lexer_token.kind = '#';
1200 MAYBE('=', T_LESSEQUAL)
1203 MAYBE('=', T_LESSLESSEQUAL)
1208 MAYBE('=', T_GREATEREQUAL)
1211 MAYBE('=', T_GREATERGREATEREQUAL)
1212 ELSE(T_GREATERGREATER)
1216 MAYBE('=', T_CARETEQUAL)
1220 MAYBE('=', T_PIPEEQUAL)
1221 MAYBE('|', T_PIPEPIPE)
1226 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1230 MAYBE('=', T_EQUALEQUAL)
1234 MAYBE('#', T_HASHHASH)
1239 if (c == 'U' || c == 'u') {
1244 lexer_token.kind = '\\';
1258 lexer_token.kind = c;
1263 lexer_token.kind = T_EOF;
1268 errorf(&lexer_pos, "unknown character '%c' found", c);
1275 void lexer_next_token(void)
1277 lexer_next_preprocessing_token();
1279 while (lexer_token.kind == '\n') {
1281 lexer_next_preprocessing_token();
1284 if (lexer_token.kind == '#') {
1285 parse_preprocessor_directive();
1290 void init_lexer(void)
1292 strset_init(&stringset);
1293 symbol_L = symbol_table_insert("L");
1296 static void input_error(unsigned delta_lines, unsigned delta_cols,
1297 const char *message)
1299 lexer_pos.lineno += delta_lines;
1300 lexer_pos.colno += delta_cols;
1301 errorf(&lexer_pos, "%s", message);
1304 void lexer_switch_input(input_t *new_input, const char *input_name)
1306 lexer_pos.lineno = 0;
1307 lexer_pos.colno = 0;
1308 lexer_pos.input_name = input_name;
1310 set_input_error_callback(input_error);
1315 /* place a virtual \n at the beginning so the lexer knows that we're
1316 * at the beginning of a line */
1320 void exit_lexer(void)
1322 strset_destroy(&stringset);
1325 static __attribute__((unused))
1326 void dbg_pos(const source_position_t source_position)
1328 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1329 source_position.lineno, (unsigned)source_position.colno);