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);
644 static void parse_string(utf32 const delim, token_kind_t const kind, string_encoding_t const enc, char const *const context)
651 utf32 const tc = parse_escape_sequence();
652 if (enc == STRING_ENCODING_CHAR) {
654 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
656 obstack_1grow(&symbol_obstack, tc);
658 obstack_grow_symbol(&symbol_obstack, tc);
664 errorf(&lexer_pos, "newline while parsing %s", context);
669 errorf(&lexer_token.base.source_position, "EOF while parsing %s", context);
677 obstack_grow_symbol(&symbol_obstack, c);
685 obstack_1grow(&symbol_obstack, '\0');
686 size_t const size = obstack_object_size(&symbol_obstack) - 1;
687 char *const string = obstack_finish(&symbol_obstack);
689 lexer_token.kind = kind;
690 lexer_token.string.encoding = enc;
691 lexer_token.string.string = identify_string(string, size);
695 * Parse a string literal and set lexer_token.
697 static void parse_string_literal(string_encoding_t const enc)
699 parse_string('"', T_STRING_LITERAL, enc, "string literal");
703 * Parse a character constant and set lexer_token.
705 static void parse_character_constant(string_encoding_t const enc)
707 parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
708 if (lexer_token.string.string.size == 0) {
709 errorf(&lexer_token.base.source_position, "empty character constant");
714 * Skip a multiline comment.
716 static void skip_multiline_comment(void)
723 /* nested comment, warn here */
724 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
735 MATCH_NEWLINE(break;)
738 errorf(&lexer_token.base.source_position,
739 "at end of file while looking for comment end");
751 * Skip a single line comment.
753 static void skip_line_comment(void)
766 if (c == '\n' || c == '\r') {
767 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
779 /** The current preprocessor token. */
780 static token_t pp_token;
783 * Read the next preprocessor token.
785 static inline void next_pp_token(void)
787 lexer_next_preprocessing_token();
788 pp_token = lexer_token;
792 * Eat all preprocessor tokens until newline.
794 static void eat_until_newline(void)
796 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
802 * Parse the line directive.
804 static void parse_line_directive(void)
806 if (pp_token.kind != T_INTEGER) {
807 parse_error("expected integer");
809 /* use offset -1 as this is about the next line */
810 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
813 if (pp_token.kind == T_STRING_LITERAL && pp_token.string.encoding == STRING_ENCODING_CHAR) {
814 lexer_pos.input_name = pp_token.string.string.begin;
815 lexer_pos.is_system_header = false;
818 /* attempt to parse numeric flags as outputted by gcc preprocessor */
819 while (pp_token.kind == T_INTEGER) {
821 * 1 - indicates start of a new file
822 * 2 - indicates return from a file
823 * 3 - indicates system header
824 * 4 - indicates implicit extern "C" in C++ mode
826 * currently we're only interested in "3"
828 if (streq(pp_token.number.number.begin, "3")) {
829 lexer_pos.is_system_header = true;
841 typedef enum stdc_pragma_kind_t {
845 STDC_CX_LIMITED_RANGE
846 } stdc_pragma_kind_t;
849 * STDC pragma values.
851 typedef enum stdc_pragma_value_kind_t {
856 } stdc_pragma_value_kind_t;
859 * Parse a pragma directive.
861 static void parse_pragma(void)
864 if (pp_token.kind != T_IDENTIFIER) {
865 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
866 "expected identifier after #pragma");
871 stdc_pragma_kind_t kind = STDC_UNKNOWN;
872 if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
876 switch (pp_token.base.symbol->pp_ID) {
877 case TP_FP_CONTRACT: kind = STDC_FP_CONTRACT; break;
878 case TP_FENV_ACCESS: kind = STDC_FENV_ACCESS; break;
879 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
882 if (kind != STDC_UNKNOWN) {
884 stdc_pragma_value_kind_t value;
885 switch (pp_token.base.symbol->pp_ID) {
886 case TP_ON: value = STDC_VALUE_ON; break;
887 case TP_OFF: value = STDC_VALUE_OFF; break;
888 case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
889 default: value = STDC_VALUE_UNKNOWN; break;
891 if (value == STDC_VALUE_UNKNOWN) {
893 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
898 if (kind == STDC_UNKNOWN) {
899 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
900 "encountered unknown #pragma");
905 * Parse a preprocessor non-null directive.
907 static void parse_preprocessor_identifier(void)
909 assert(pp_token.kind == T_IDENTIFIER);
910 switch (pp_token.base.symbol->pp_ID) {
913 parse_line_directive();
919 /* TODO; output the rest of the line */
920 parse_error("#error directive");
926 * Parse a preprocessor directive.
928 static void parse_preprocessor_directive(void)
932 switch (pp_token.kind) {
934 parse_preprocessor_identifier();
937 parse_line_directive();
940 /* NULL directive, see §6.10.7 */
943 parse_error("invalid preprocessor directive");
949 #define MAYBE_PROLOG \
954 #define MAYBE(ch, set_type) \
957 lexer_token.kind = set_type; \
960 /* must use this as last thing */
961 #define MAYBE_MODE(ch, set_type, mode) \
963 if (c_mode & mode) { \
965 lexer_token.kind = set_type; \
970 #define ELSE_CODE(code) \
975 } /* end of while (true) */ \
977 #define ELSE(set_type) \
979 lexer_token.kind = set_type; \
982 void lexer_next_preprocessing_token(void)
985 lexer_token.base.source_position = lexer_pos;
986 lexer_token.base.symbol = NULL;
995 lexer_token.kind = '\n';
1001 /* might be a wide string ( L"string" ) */
1002 string_encoding_t const enc = STRING_ENCODING_WIDE;
1003 if (lexer_token.base.symbol == symbol_L) {
1005 case '"': parse_string_literal(enc); break;
1006 case '\'': parse_character_constant(enc); break;
1017 parse_string_literal(STRING_ENCODING_CHAR);
1021 parse_character_constant(STRING_ENCODING_CHAR);
1034 MAYBE('.', T_DOTDOTDOT)
1038 lexer_token.kind = '.';
1043 MAYBE('&', T_ANDAND)
1044 MAYBE('=', T_ANDEQUAL)
1048 MAYBE('=', T_ASTERISKEQUAL)
1052 MAYBE('+', T_PLUSPLUS)
1053 MAYBE('=', T_PLUSEQUAL)
1057 MAYBE('>', T_MINUSGREATER)
1058 MAYBE('-', T_MINUSMINUS)
1059 MAYBE('=', T_MINUSEQUAL)
1063 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1067 MAYBE('=', T_SLASHEQUAL)
1070 skip_multiline_comment();
1071 lexer_next_preprocessing_token();
1075 skip_line_comment();
1076 lexer_next_preprocessing_token();
1082 MAYBE('=', T_PERCENTEQUAL)
1087 MAYBE(':', T_HASHHASH)
1091 lexer_token.kind = '#';
1099 MAYBE('=', T_LESSEQUAL)
1102 MAYBE('=', T_LESSLESSEQUAL)
1107 MAYBE('=', T_GREATEREQUAL)
1110 MAYBE('=', T_GREATERGREATEREQUAL)
1111 ELSE(T_GREATERGREATER)
1115 MAYBE('=', T_CARETEQUAL)
1119 MAYBE('=', T_PIPEEQUAL)
1120 MAYBE('|', T_PIPEPIPE)
1125 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1129 MAYBE('=', T_EQUALEQUAL)
1133 MAYBE('#', T_HASHHASH)
1147 lexer_token.kind = c;
1152 lexer_token.kind = T_EOF;
1157 errorf(&lexer_pos, "unknown character '%c' found", c);
1164 void lexer_next_token(void)
1166 lexer_next_preprocessing_token();
1168 while (lexer_token.kind == '\n') {
1170 lexer_next_preprocessing_token();
1173 if (lexer_token.kind == '#') {
1174 parse_preprocessor_directive();
1179 void init_lexer(void)
1181 strset_init(&stringset);
1182 symbol_L = symbol_table_insert("L");
1185 static void input_error(unsigned delta_lines, unsigned delta_cols,
1186 const char *message)
1188 lexer_pos.lineno += delta_lines;
1189 lexer_pos.colno += delta_cols;
1190 errorf(&lexer_pos, "%s", message);
1193 void lexer_switch_input(input_t *new_input, const char *input_name)
1195 lexer_pos.lineno = 0;
1196 lexer_pos.colno = 0;
1197 lexer_pos.input_name = input_name;
1199 set_input_error_callback(input_error);
1204 /* place a virtual \n at the beginning so the lexer knows that we're
1205 * at the beginning of a line */
1209 void exit_lexer(void)
1211 strset_destroy(&stringset);
1214 static __attribute__((unused))
1215 void dbg_pos(const source_position_t source_position)
1217 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1218 source_position.lineno, (unsigned)source_position.colno);