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.identifier.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");
636 * Concatenate two strings.
638 string_t concat_strings(const string_t *const s1, const string_t *const s2)
640 const size_t len1 = s1->size - 1;
641 const size_t len2 = s2->size - 1;
643 char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
644 memcpy(concat, s1->begin, len1);
645 memcpy(concat + len1, s2->begin, len2 + 1);
647 return identify_string(concat, len1 + len2 + 1);
650 string_t make_string(const char *string)
652 size_t len = strlen(string) + 1;
653 char *const space = obstack_alloc(&symbol_obstack, len);
654 memcpy(space, string, len);
656 return identify_string(space, len);
660 * Parse a string literal and set lexer_token.
662 static void parse_string_literal(void)
669 utf32 const tc = parse_escape_sequence();
671 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
673 obstack_1grow(&symbol_obstack, tc);
678 errorf(&lexer_token.base.source_position, "string has no end");
686 obstack_grow_symbol(&symbol_obstack, c);
694 /* TODO: concatenate multiple strings separated by whitespace... */
696 /* add finishing 0 to the string */
697 obstack_1grow(&symbol_obstack, '\0');
698 const size_t size = (size_t)obstack_object_size(&symbol_obstack);
699 char *string = obstack_finish(&symbol_obstack);
701 lexer_token.kind = T_STRING_LITERAL;
702 lexer_token.string.string = identify_string(string, size);
706 * Parse a wide character constant and set lexer_token.
708 static void parse_wide_character_constant(void)
715 const utf32 tc = parse_escape_sequence();
716 obstack_grow_symbol(&symbol_obstack, tc);
721 parse_error("newline while parsing character constant");
727 goto end_of_wide_char_constant;
730 errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
731 goto end_of_wide_char_constant;
734 obstack_grow_symbol(&symbol_obstack, c);
740 end_of_wide_char_constant:;
741 obstack_1grow(&symbol_obstack, '\0');
742 size_t size = (size_t) obstack_object_size(&symbol_obstack) - 1;
743 char *string = obstack_finish(&symbol_obstack);
745 lexer_token.kind = T_WIDE_CHARACTER_CONSTANT;
746 lexer_token.string.string = identify_string(string, size);
749 errorf(&lexer_token.base.source_position, "empty character constant");
754 * Parse a wide string literal and set lexer_token.
756 static void parse_wide_string_literal(void)
758 parse_string_literal();
759 if (lexer_token.kind == T_STRING_LITERAL)
760 lexer_token.kind = T_WIDE_STRING_LITERAL;
764 * Parse a character constant and set lexer_token.
766 static void parse_character_constant(void)
773 utf32 const tc = parse_escape_sequence();
775 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
777 obstack_1grow(&symbol_obstack, tc);
782 parse_error("newline while parsing character constant");
788 goto end_of_char_constant;
791 errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
792 goto end_of_char_constant;
795 obstack_grow_symbol(&symbol_obstack, c);
802 end_of_char_constant:;
803 obstack_1grow(&symbol_obstack, '\0');
804 const size_t size = (size_t)obstack_object_size(&symbol_obstack)-1;
805 char *const string = obstack_finish(&symbol_obstack);
807 lexer_token.kind = T_CHARACTER_CONSTANT;
808 lexer_token.string.string = identify_string(string, size);
811 errorf(&lexer_token.base.source_position, "empty character constant");
816 * Skip a multiline comment.
818 static void skip_multiline_comment(void)
825 /* nested comment, warn here */
826 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
837 MATCH_NEWLINE(break;)
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) {
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)
965 bool unknown_pragma = true;
968 if (pp_token.kind != T_IDENTIFIER) {
969 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
970 "expected identifier after #pragma");
975 symbol_t *symbol = pp_token.identifier.symbol;
976 if (symbol->pp_ID == TP_STDC) {
977 stdc_pragma_kind_t kind = STDC_UNKNOWN;
982 switch (pp_token.identifier.symbol->pp_ID) {
984 kind = STDC_FP_CONTRACT;
987 kind = STDC_FENV_ACCESS;
989 case TP_CX_LIMITED_RANGE:
990 kind = STDC_CX_LIMITED_RANGE;
995 if (kind != STDC_UNKNOWN) {
996 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
998 switch (pp_token.identifier.symbol->pp_ID) {
1000 value = STDC_VALUE_ON;
1003 value = STDC_VALUE_OFF;
1006 value = STDC_VALUE_DEFAULT;
1011 if (value != STDC_VALUE_UNKNOWN) {
1012 unknown_pragma = false;
1014 errorf(&pp_token.base.source_position,
1015 "bad STDC pragma argument");
1020 unknown_pragma = true;
1022 eat_until_newline();
1023 if (unknown_pragma) {
1024 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
1025 "encountered unknown #pragma");
1030 * Parse a preprocessor non-null directive.
1032 static void parse_preprocessor_identifier(void)
1034 assert(pp_token.kind == T_IDENTIFIER);
1035 symbol_t *symbol = pp_token.identifier.symbol;
1037 switch (symbol->pp_ID) {
1040 parse_line_directive();
1046 /* TODO; output the rest of the line */
1047 parse_error("#error directive");
1053 * Parse a preprocessor directive.
1055 static void parse_preprocessor_directive(void)
1059 switch (pp_token.kind) {
1061 parse_preprocessor_identifier();
1064 parse_line_directive();
1067 /* NULL directive, see §6.10.7 */
1070 parse_error("invalid preprocessor directive");
1071 eat_until_newline();
1076 #define MAYBE_PROLOG \
1081 #define MAYBE(ch, set_type) \
1084 lexer_token.kind = set_type; \
1087 /* must use this as last thing */
1088 #define MAYBE_MODE(ch, set_type, mode) \
1090 if (c_mode & mode) { \
1092 lexer_token.kind = set_type; \
1097 #define ELSE_CODE(code) \
1102 } /* end of while (true) */ \
1104 #define ELSE(set_type) \
1106 lexer_token.kind = set_type; \
1109 void lexer_next_preprocessing_token(void)
1112 lexer_token.base.source_position = lexer_pos;
1121 lexer_token.kind = '\n';
1127 /* might be a wide string ( L"string" ) */
1128 if (lexer_token.identifier.symbol == symbol_L) {
1130 case '"': parse_wide_string_literal(); break;
1131 case '\'': parse_wide_character_constant(); break;
1141 parse_string_literal();
1145 parse_character_constant();
1158 MAYBE('.', T_DOTDOTDOT)
1162 lexer_token.kind = '.';
1167 MAYBE('&', T_ANDAND)
1168 MAYBE('=', T_ANDEQUAL)
1172 MAYBE('=', T_ASTERISKEQUAL)
1176 MAYBE('+', T_PLUSPLUS)
1177 MAYBE('=', T_PLUSEQUAL)
1181 MAYBE('>', T_MINUSGREATER)
1182 MAYBE('-', T_MINUSMINUS)
1183 MAYBE('=', T_MINUSEQUAL)
1187 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1191 MAYBE('=', T_SLASHEQUAL)
1194 skip_multiline_comment();
1195 lexer_next_preprocessing_token();
1199 skip_line_comment();
1200 lexer_next_preprocessing_token();
1206 MAYBE('=', T_PERCENTEQUAL)
1211 MAYBE(':', T_HASHHASH)
1215 lexer_token.kind = '#';
1223 MAYBE('=', T_LESSEQUAL)
1226 MAYBE('=', T_LESSLESSEQUAL)
1231 MAYBE('=', T_GREATEREQUAL)
1234 MAYBE('=', T_GREATERGREATEREQUAL)
1235 ELSE(T_GREATERGREATER)
1239 MAYBE('=', T_CARETEQUAL)
1243 MAYBE('=', T_PIPEEQUAL)
1244 MAYBE('|', T_PIPEPIPE)
1249 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1253 MAYBE('=', T_EQUALEQUAL)
1257 MAYBE('#', T_HASHHASH)
1271 lexer_token.kind = c;
1276 lexer_token.kind = T_EOF;
1281 errorf(&lexer_pos, "unknown character '%c' found", c);
1288 void lexer_next_token(void)
1290 lexer_next_preprocessing_token();
1292 while (lexer_token.kind == '\n') {
1294 lexer_next_preprocessing_token();
1297 if (lexer_token.kind == '#') {
1298 parse_preprocessor_directive();
1303 void init_lexer(void)
1305 strset_init(&stringset);
1306 symbol_L = symbol_table_insert("L");
1309 static void input_error(unsigned delta_lines, unsigned delta_cols,
1310 const char *message)
1312 lexer_pos.lineno += delta_lines;
1313 lexer_pos.colno += delta_cols;
1314 errorf(&lexer_pos, "%s", message);
1317 void lexer_switch_input(input_t *new_input, const char *input_name)
1319 lexer_pos.lineno = 0;
1320 lexer_pos.colno = 0;
1321 lexer_pos.input_name = input_name;
1323 set_input_error_callback(input_error);
1328 /* place a virtual \n at the beginning so the lexer knows that we're
1329 * at the beginning of a line */
1333 void exit_lexer(void)
1335 strset_destroy(&stringset);
1338 static __attribute__((unused))
1339 void dbg_pos(const source_position_t source_position)
1341 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1342 source_position.lineno, (unsigned)source_position.colno);