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);
111 #define MATCH_NEWLINE(code) \
118 lexer_pos.lineno++; \
119 lexer_pos.colno = 1; \
122 #define eat(c_type) (assert(c == c_type), next_char())
124 static void maybe_concat_lines(void)
129 MATCH_NEWLINE(return;)
140 * Set c to the next input character, ie.
141 * after expanding trigraphs.
143 static inline void next_char(void)
147 /* filter trigraphs */
148 if (UNLIKELY(c == '\\')) {
149 maybe_concat_lines();
153 if (LIKELY(c != '?'))
157 if (LIKELY(c != '?')) {
165 case '=': c = '#'; break;
166 case '(': c = '['; break;
167 case '/': c = '\\'; maybe_concat_lines(); break;
168 case ')': c = ']'; break;
169 case '\'': c = '^'; break;
170 case '<': c = '{'; break;
171 case '!': c = '|'; break;
172 case '>': c = '}'; break;
173 case '-': c = '~'; break;
182 #define SYMBOL_CHARS \
183 case '$': if (!allow_dollar_in_symbol) goto dollar_sign; \
251 * Read a symbol from the input and build
254 static void parse_symbol(void)
256 obstack_1grow(&symbol_obstack, (char) c);
263 obstack_1grow(&symbol_obstack, (char) c);
274 obstack_1grow(&symbol_obstack, '\0');
276 char *string = obstack_finish(&symbol_obstack);
277 symbol_t *symbol = symbol_table_insert(string);
279 lexer_token.kind = symbol->ID;
280 lexer_token.base.symbol = symbol;
282 if (symbol->string != string) {
283 obstack_free(&symbol_obstack, string);
287 static string_t identify_string(char *string, size_t len)
291 const char *result = strset_insert(&stringset, concat);
292 if (result != concat) {
293 obstack_free(&symbol_obstack, concat);
296 const char *result = string;
298 return (string_t) {result, len};
302 * parse suffixes like 'LU' or 'f' after numbers
304 static void parse_number_suffix(void)
306 assert(obstack_object_size(&symbol_obstack) == 0);
310 obstack_1grow(&symbol_obstack, (char) c);
319 if (obstack_object_size(&symbol_obstack) == 0) {
320 lexer_token.number.suffix.begin = NULL;
321 lexer_token.number.suffix.size = 0;
325 obstack_1grow(&symbol_obstack, '\0');
326 size_t size = obstack_object_size(&symbol_obstack) - 1;
327 char *string = obstack_finish(&symbol_obstack);
329 lexer_token.number.suffix = identify_string(string, size);
332 static void parse_exponent(void)
334 if (c == '-' || c == '+') {
335 obstack_1grow(&symbol_obstack, (char)c);
341 obstack_1grow(&symbol_obstack, (char)c);
343 } while (isdigit(c));
345 errorf(&lexer_token.base.source_position, "exponent has no digits");
350 * Parses a hex number including hex floats and set the
353 static void parse_number_hex(void)
355 bool is_float = false;
356 bool has_digits = false;
358 while (isxdigit(c)) {
360 obstack_1grow(&symbol_obstack, (char) c);
366 obstack_1grow(&symbol_obstack, (char) c);
369 while (isxdigit(c)) {
371 obstack_1grow(&symbol_obstack, (char) c);
375 if (c == 'p' || c == 'P') {
377 obstack_1grow(&symbol_obstack, (char) c);
380 } else if (is_float) {
381 errorf(&lexer_token.base.source_position,
382 "hexadecimal floatingpoint constant requires an exponent");
384 obstack_1grow(&symbol_obstack, '\0');
386 size_t size = obstack_object_size(&symbol_obstack) - 1;
387 char *string = obstack_finish(&symbol_obstack);
388 lexer_token.number.number = identify_string(string, size);
390 lexer_token.kind = is_float ? T_FLOATINGPOINT : T_INTEGER;
393 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
394 lexer_token.number.number.begin = "0";
395 lexer_token.number.number.size = 1;
398 parse_number_suffix();
401 static void parse_number_bin(void)
403 bool has_digits = false;
405 while (c == '0' || c == '1') {
407 obstack_1grow(&symbol_obstack, (char)c);
410 obstack_1grow(&symbol_obstack, '\0');
412 size_t const size = obstack_object_size(&symbol_obstack) - 1;
413 char *const string = obstack_finish(&symbol_obstack);
414 lexer_token.number.number = identify_string(string, size);
415 lexer_token.kind = T_INTEGER;
418 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
419 lexer_token.number.number.begin = "0";
420 lexer_token.number.number.size = 1;
423 parse_number_suffix();
427 * Returns true if the given char is a octal digit.
429 * @param char the character to check
431 static bool is_octal_digit(utf32 chr)
433 return '0' <= chr && chr <= '7';
437 * Parses a number and sets the lexer_token.
439 static void parse_number(void)
441 bool is_float = false;
442 bool has_digits = false;
444 assert(obstack_object_size(&symbol_obstack) == 0);
446 obstack_1grow(&symbol_obstack, (char)c);
448 if (c == 'x' || c == 'X') {
449 obstack_1grow(&symbol_obstack, (char)c);
453 } else if (c == 'b' || c == 'B') {
454 /* GCC extension: binary constant 0x[bB][01]+. */
455 obstack_1grow(&symbol_obstack, (char)c);
465 obstack_1grow(&symbol_obstack, (char) c);
471 obstack_1grow(&symbol_obstack, '.');
476 obstack_1grow(&symbol_obstack, (char) c);
480 if (c == 'e' || c == 'E') {
482 obstack_1grow(&symbol_obstack, 'e');
487 obstack_1grow(&symbol_obstack, '\0');
488 size_t size = obstack_object_size(&symbol_obstack) - 1;
489 char *string = obstack_finish(&symbol_obstack);
490 lexer_token.number.number = identify_string(string, size);
493 lexer_token.kind = T_FLOATINGPOINT;
495 lexer_token.kind = T_INTEGER;
497 if (string[0] == '0') {
498 /* check for invalid octal digits */
499 for (size_t i= 0; i < size; ++i) {
502 errorf(&lexer_token.base.source_position, "invalid digit '%c' in octal number", t);
508 errorf(&lexer_token.base.source_position, "invalid number literal '%S'",
509 &lexer_token.number.number);
512 parse_number_suffix();
516 * Returns the value of a digit.
517 * The only portable way to do it ...
519 static int digit_value(utf32 const digit)
545 internal_error("wrong character given");
550 * Parses an octal character sequence.
552 * @param first_digit the already read first digit
554 static utf32 parse_octal_sequence(utf32 const first_digit)
556 assert(is_octal_digit(first_digit));
557 utf32 value = digit_value(first_digit);
558 if (!is_octal_digit(c)) return value;
559 value = 8 * value + digit_value(c);
561 if (!is_octal_digit(c)) return value;
562 value = 8 * value + digit_value(c);
568 * Parses a hex character sequence.
570 static utf32 parse_hex_sequence(void)
573 while (isxdigit(c)) {
574 value = 16 * value + digit_value(c);
581 * Parse an escape sequence.
583 static utf32 parse_escape_sequence(void)
591 case '"': return '"';
592 case '\'': return '\'';
593 case '\\': return '\\';
594 case '?': return '\?';
595 case 'a': return '\a';
596 case 'b': return '\b';
597 case 'f': return '\f';
598 case 'n': return '\n';
599 case 'r': return '\r';
600 case 't': return '\t';
601 case 'v': return '\v';
603 return parse_hex_sequence();
612 return parse_octal_sequence(ec);
614 parse_error("reached end of file while parsing escape sequence");
616 /* \E is not documented, but handled, by GCC. It is acceptable according
617 * to §6.11.4, whereas \e is not. */
621 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
625 parse_error("universal character parsing not implemented yet");
630 /* §6.4.4.4:8 footnote 64 */
631 parse_error("unknown escape sequence");
635 string_t make_string(const char *string)
637 size_t len = strlen(string) + 1;
638 char *const space = obstack_alloc(&symbol_obstack, len);
639 memcpy(space, string, len);
641 return identify_string(space, len);
645 * Parse a string literal and set lexer_token.
647 static void parse_string_literal(string_encoding_t const enc)
654 utf32 const tc = parse_escape_sequence();
656 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
658 obstack_1grow(&symbol_obstack, tc);
663 errorf(&lexer_token.base.source_position, "string has no end");
671 obstack_grow_symbol(&symbol_obstack, c);
679 /* TODO: concatenate multiple strings separated by whitespace... */
681 /* add finishing 0 to the string */
682 obstack_1grow(&symbol_obstack, '\0');
683 const size_t size = (size_t)obstack_object_size(&symbol_obstack);
684 char *string = obstack_finish(&symbol_obstack);
686 lexer_token.kind = T_STRING_LITERAL;
687 lexer_token.string.encoding = enc;
688 lexer_token.string.string = identify_string(string, size);
692 * Parse a wide character constant and set lexer_token.
694 static void parse_wide_character_constant(void)
701 const utf32 tc = parse_escape_sequence();
702 obstack_grow_symbol(&symbol_obstack, tc);
707 parse_error("newline while parsing character constant");
713 goto end_of_wide_char_constant;
716 errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
717 goto end_of_wide_char_constant;
720 obstack_grow_symbol(&symbol_obstack, c);
726 end_of_wide_char_constant:;
727 obstack_1grow(&symbol_obstack, '\0');
728 size_t size = (size_t) obstack_object_size(&symbol_obstack) - 1;
729 char *string = obstack_finish(&symbol_obstack);
731 lexer_token.kind = T_WIDE_CHARACTER_CONSTANT;
732 lexer_token.string.string = identify_string(string, size);
735 errorf(&lexer_token.base.source_position, "empty character constant");
740 * Parse a character constant and set lexer_token.
742 static void parse_character_constant(void)
749 utf32 const tc = parse_escape_sequence();
751 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
753 obstack_1grow(&symbol_obstack, tc);
758 parse_error("newline while parsing character constant");
764 goto end_of_char_constant;
767 errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
768 goto end_of_char_constant;
771 obstack_grow_symbol(&symbol_obstack, c);
778 end_of_char_constant:;
779 obstack_1grow(&symbol_obstack, '\0');
780 const size_t size = (size_t)obstack_object_size(&symbol_obstack)-1;
781 char *const string = obstack_finish(&symbol_obstack);
783 lexer_token.kind = T_CHARACTER_CONSTANT;
784 lexer_token.string.string = identify_string(string, size);
787 errorf(&lexer_token.base.source_position, "empty character constant");
792 * Skip a multiline comment.
794 static void skip_multiline_comment(void)
801 /* nested comment, warn here */
802 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
813 MATCH_NEWLINE(break;)
816 errorf(&lexer_token.base.source_position,
817 "at end of file while looking for comment end");
829 * Skip a single line comment.
831 static void skip_line_comment(void)
844 if (c == '\n' || c == '\r') {
845 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
857 /** The current preprocessor token. */
858 static token_t pp_token;
861 * Read the next preprocessor token.
863 static inline void next_pp_token(void)
865 lexer_next_preprocessing_token();
866 pp_token = lexer_token;
870 * Eat all preprocessor tokens until newline.
872 static void eat_until_newline(void)
874 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
880 * Parse the line directive.
882 static void parse_line_directive(void)
884 if (pp_token.kind != T_INTEGER) {
885 parse_error("expected integer");
887 /* use offset -1 as this is about the next line */
888 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
891 if (pp_token.kind == T_STRING_LITERAL && pp_token.string.encoding == STRING_ENCODING_CHAR) {
892 lexer_pos.input_name = pp_token.string.string.begin;
893 lexer_pos.is_system_header = false;
896 /* attempt to parse numeric flags as outputted by gcc preprocessor */
897 while (pp_token.kind == T_INTEGER) {
899 * 1 - indicates start of a new file
900 * 2 - indicates return from a file
901 * 3 - indicates system header
902 * 4 - indicates implicit extern "C" in C++ mode
904 * currently we're only interested in "3"
906 if (streq(pp_token.number.number.begin, "3")) {
907 lexer_pos.is_system_header = true;
919 typedef enum stdc_pragma_kind_t {
923 STDC_CX_LIMITED_RANGE
924 } stdc_pragma_kind_t;
927 * STDC pragma values.
929 typedef enum stdc_pragma_value_kind_t {
934 } stdc_pragma_value_kind_t;
937 * Parse a pragma directive.
939 static void parse_pragma(void)
942 if (pp_token.kind != T_IDENTIFIER) {
943 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
944 "expected identifier after #pragma");
949 stdc_pragma_kind_t kind = STDC_UNKNOWN;
950 if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
954 switch (pp_token.base.symbol->pp_ID) {
955 case TP_FP_CONTRACT: kind = STDC_FP_CONTRACT; break;
956 case TP_FENV_ACCESS: kind = STDC_FENV_ACCESS; break;
957 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
960 if (kind != STDC_UNKNOWN) {
962 stdc_pragma_value_kind_t value;
963 switch (pp_token.base.symbol->pp_ID) {
964 case TP_ON: value = STDC_VALUE_ON; break;
965 case TP_OFF: value = STDC_VALUE_OFF; break;
966 case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
967 default: value = STDC_VALUE_UNKNOWN; break;
969 if (value == STDC_VALUE_UNKNOWN) {
971 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
976 if (kind == STDC_UNKNOWN) {
977 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
978 "encountered unknown #pragma");
983 * Parse a preprocessor non-null directive.
985 static void parse_preprocessor_identifier(void)
987 assert(pp_token.kind == T_IDENTIFIER);
988 switch (pp_token.base.symbol->pp_ID) {
991 parse_line_directive();
997 /* TODO; output the rest of the line */
998 parse_error("#error directive");
1004 * Parse a preprocessor directive.
1006 static void parse_preprocessor_directive(void)
1010 switch (pp_token.kind) {
1012 parse_preprocessor_identifier();
1015 parse_line_directive();
1018 /* NULL directive, see §6.10.7 */
1021 parse_error("invalid preprocessor directive");
1022 eat_until_newline();
1027 #define MAYBE_PROLOG \
1032 #define MAYBE(ch, set_type) \
1035 lexer_token.kind = set_type; \
1038 /* must use this as last thing */
1039 #define MAYBE_MODE(ch, set_type, mode) \
1041 if (c_mode & mode) { \
1043 lexer_token.kind = set_type; \
1048 #define ELSE_CODE(code) \
1053 } /* end of while (true) */ \
1055 #define ELSE(set_type) \
1057 lexer_token.kind = set_type; \
1060 void lexer_next_preprocessing_token(void)
1063 lexer_token.base.source_position = lexer_pos;
1064 lexer_token.base.symbol = NULL;
1073 lexer_token.kind = '\n';
1079 /* might be a wide string ( L"string" ) */
1080 string_encoding_t const enc = STRING_ENCODING_WIDE;
1081 if (lexer_token.base.symbol == symbol_L) {
1083 case '"': parse_string_literal(enc); break;
1084 case '\'': parse_wide_character_constant(); break;
1095 parse_string_literal(STRING_ENCODING_CHAR);
1099 parse_character_constant();
1112 MAYBE('.', T_DOTDOTDOT)
1116 lexer_token.kind = '.';
1121 MAYBE('&', T_ANDAND)
1122 MAYBE('=', T_ANDEQUAL)
1126 MAYBE('=', T_ASTERISKEQUAL)
1130 MAYBE('+', T_PLUSPLUS)
1131 MAYBE('=', T_PLUSEQUAL)
1135 MAYBE('>', T_MINUSGREATER)
1136 MAYBE('-', T_MINUSMINUS)
1137 MAYBE('=', T_MINUSEQUAL)
1141 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1145 MAYBE('=', T_SLASHEQUAL)
1148 skip_multiline_comment();
1149 lexer_next_preprocessing_token();
1153 skip_line_comment();
1154 lexer_next_preprocessing_token();
1160 MAYBE('=', T_PERCENTEQUAL)
1165 MAYBE(':', T_HASHHASH)
1169 lexer_token.kind = '#';
1177 MAYBE('=', T_LESSEQUAL)
1180 MAYBE('=', T_LESSLESSEQUAL)
1185 MAYBE('=', T_GREATEREQUAL)
1188 MAYBE('=', T_GREATERGREATEREQUAL)
1189 ELSE(T_GREATERGREATER)
1193 MAYBE('=', T_CARETEQUAL)
1197 MAYBE('=', T_PIPEEQUAL)
1198 MAYBE('|', T_PIPEPIPE)
1203 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1207 MAYBE('=', T_EQUALEQUAL)
1211 MAYBE('#', T_HASHHASH)
1225 lexer_token.kind = c;
1230 lexer_token.kind = T_EOF;
1235 errorf(&lexer_pos, "unknown character '%c' found", c);
1242 void lexer_next_token(void)
1244 lexer_next_preprocessing_token();
1246 while (lexer_token.kind == '\n') {
1248 lexer_next_preprocessing_token();
1251 if (lexer_token.kind == '#') {
1252 parse_preprocessor_directive();
1257 void init_lexer(void)
1259 strset_init(&stringset);
1260 symbol_L = symbol_table_insert("L");
1263 static void input_error(unsigned delta_lines, unsigned delta_cols,
1264 const char *message)
1266 lexer_pos.lineno += delta_lines;
1267 lexer_pos.colno += delta_cols;
1268 errorf(&lexer_pos, "%s", message);
1271 void lexer_switch_input(input_t *new_input, const char *input_name)
1273 lexer_pos.lineno = 0;
1274 lexer_pos.colno = 0;
1275 lexer_pos.input_name = input_name;
1277 set_input_error_callback(input_error);
1282 /* place a virtual \n at the beginning so the lexer knows that we're
1283 * at the beginning of a line */
1287 void exit_lexer(void)
1289 strset_destroy(&stringset);
1292 static __attribute__((unused))
1293 void dbg_pos(const source_position_t source_position)
1295 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1296 source_position.lineno, (unsigned)source_position.colno);