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; \
253 * Read a symbol from the input and build
256 static void parse_symbol(void)
258 obstack_1grow(&symbol_obstack, (char) c);
265 obstack_1grow(&symbol_obstack, (char) c);
276 obstack_1grow(&symbol_obstack, '\0');
278 char *string = obstack_finish(&symbol_obstack);
279 symbol_t *symbol = symbol_table_insert(string);
281 lexer_token.kind = symbol->ID;
282 lexer_token.base.symbol = symbol;
284 if (symbol->string != string) {
285 obstack_free(&symbol_obstack, string);
289 static string_t identify_string(char *string, size_t len)
293 const char *result = strset_insert(&stringset, concat);
294 if (result != concat) {
295 obstack_free(&symbol_obstack, concat);
298 const char *result = string;
300 return (string_t) {result, len};
304 * parse suffixes like 'LU' or 'f' after numbers
306 static void parse_number_suffix(void)
308 assert(obstack_object_size(&symbol_obstack) == 0);
312 obstack_1grow(&symbol_obstack, (char) c);
321 if (obstack_object_size(&symbol_obstack) == 0) {
322 lexer_token.number.suffix.begin = NULL;
323 lexer_token.number.suffix.size = 0;
327 obstack_1grow(&symbol_obstack, '\0');
328 size_t size = obstack_object_size(&symbol_obstack) - 1;
329 char *string = obstack_finish(&symbol_obstack);
331 lexer_token.number.suffix = identify_string(string, size);
334 static void parse_exponent(void)
336 if (c == '-' || c == '+') {
337 obstack_1grow(&symbol_obstack, (char)c);
343 obstack_1grow(&symbol_obstack, (char)c);
345 } while (isdigit(c));
347 errorf(&lexer_token.base.source_position, "exponent has no digits");
352 * Parses a hex number including hex floats and set the
355 static void parse_number_hex(void)
357 bool is_float = false;
358 bool has_digits = false;
360 while (isxdigit(c)) {
362 obstack_1grow(&symbol_obstack, (char) c);
368 obstack_1grow(&symbol_obstack, (char) c);
371 while (isxdigit(c)) {
373 obstack_1grow(&symbol_obstack, (char) c);
377 if (c == 'p' || c == 'P') {
379 obstack_1grow(&symbol_obstack, (char) c);
382 } else if (is_float) {
383 errorf(&lexer_token.base.source_position,
384 "hexadecimal floatingpoint constant requires an exponent");
386 obstack_1grow(&symbol_obstack, '\0');
388 size_t size = obstack_object_size(&symbol_obstack) - 1;
389 char *string = obstack_finish(&symbol_obstack);
390 lexer_token.number.number = identify_string(string, size);
392 lexer_token.kind = is_float ? T_FLOATINGPOINT : T_INTEGER;
395 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
396 lexer_token.number.number.begin = "0";
397 lexer_token.number.number.size = 1;
400 parse_number_suffix();
403 static void parse_number_bin(void)
405 bool has_digits = false;
407 while (c == '0' || c == '1') {
409 obstack_1grow(&symbol_obstack, (char)c);
412 obstack_1grow(&symbol_obstack, '\0');
414 size_t const size = obstack_object_size(&symbol_obstack) - 1;
415 char *const string = obstack_finish(&symbol_obstack);
416 lexer_token.number.number = identify_string(string, size);
417 lexer_token.kind = T_INTEGER;
420 errorf(&lexer_token.base.source_position, "invalid number literal '%S'", &lexer_token.number.number);
421 lexer_token.number.number.begin = "0";
422 lexer_token.number.number.size = 1;
425 parse_number_suffix();
429 * Returns true if the given char is a octal digit.
431 * @param char the character to check
433 static bool is_octal_digit(utf32 chr)
435 return '0' <= chr && chr <= '7';
439 * Parses a number and sets the lexer_token.
441 static void parse_number(void)
443 bool is_float = false;
444 bool has_digits = false;
446 assert(obstack_object_size(&symbol_obstack) == 0);
448 obstack_1grow(&symbol_obstack, (char)c);
450 if (c == 'x' || c == 'X') {
451 obstack_1grow(&symbol_obstack, (char)c);
455 } else if (c == 'b' || c == 'B') {
456 /* GCC extension: binary constant 0x[bB][01]+. */
457 obstack_1grow(&symbol_obstack, (char)c);
467 obstack_1grow(&symbol_obstack, (char) c);
473 obstack_1grow(&symbol_obstack, '.');
478 obstack_1grow(&symbol_obstack, (char) c);
482 if (c == 'e' || c == 'E') {
484 obstack_1grow(&symbol_obstack, 'e');
489 obstack_1grow(&symbol_obstack, '\0');
490 size_t size = obstack_object_size(&symbol_obstack) - 1;
491 char *string = obstack_finish(&symbol_obstack);
492 lexer_token.number.number = identify_string(string, size);
495 lexer_token.kind = T_FLOATINGPOINT;
497 lexer_token.kind = T_INTEGER;
499 if (string[0] == '0') {
500 /* check for invalid octal digits */
501 for (size_t i= 0; i < size; ++i) {
504 errorf(&lexer_token.base.source_position, "invalid digit '%c' in octal number", t);
510 errorf(&lexer_token.base.source_position, "invalid number literal '%S'",
511 &lexer_token.number.number);
514 parse_number_suffix();
518 * Returns the value of a digit.
519 * The only portable way to do it ...
521 static int digit_value(utf32 const digit)
547 internal_error("wrong character given");
552 * Parses an octal character sequence.
554 * @param first_digit the already read first digit
556 static utf32 parse_octal_sequence(utf32 const first_digit)
558 assert(is_octal_digit(first_digit));
559 utf32 value = digit_value(first_digit);
560 if (!is_octal_digit(c)) return value;
561 value = 8 * value + digit_value(c);
563 if (!is_octal_digit(c)) return value;
564 value = 8 * value + digit_value(c);
570 * Parses a hex character sequence.
572 static utf32 parse_hex_sequence(void)
575 while (isxdigit(c)) {
576 value = 16 * value + digit_value(c);
583 * Parse an escape sequence.
585 static utf32 parse_escape_sequence(void)
593 case '"': return '"';
594 case '\'': return '\'';
595 case '\\': return '\\';
596 case '?': return '\?';
597 case 'a': return '\a';
598 case 'b': return '\b';
599 case 'f': return '\f';
600 case 'n': return '\n';
601 case 'r': return '\r';
602 case 't': return '\t';
603 case 'v': return '\v';
605 return parse_hex_sequence();
614 return parse_octal_sequence(ec);
616 parse_error("reached end of file while parsing escape sequence");
618 /* \E is not documented, but handled, by GCC. It is acceptable according
619 * to §6.11.4, whereas \e is not. */
623 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
627 parse_error("universal character parsing not implemented yet");
632 /* §6.4.4.4:8 footnote 64 */
633 parse_error("unknown escape sequence");
637 string_t make_string(const char *string)
639 size_t len = strlen(string) + 1;
640 char *const space = obstack_alloc(&symbol_obstack, len);
641 memcpy(space, string, len);
643 return identify_string(space, len);
646 static void parse_string(utf32 const delim, token_kind_t const kind, string_encoding_t const enc, char const *const context)
653 utf32 const tc = parse_escape_sequence();
654 if (enc == STRING_ENCODING_CHAR) {
656 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
658 obstack_1grow(&symbol_obstack, tc);
660 obstack_grow_symbol(&symbol_obstack, tc);
666 errorf(&lexer_pos, "newline while parsing %s", context);
670 errorf(&lexer_token.base.source_position, "EOF while parsing %s", context);
678 obstack_grow_symbol(&symbol_obstack, c);
686 obstack_1grow(&symbol_obstack, '\0');
687 size_t const size = obstack_object_size(&symbol_obstack) - 1;
688 char *const string = obstack_finish(&symbol_obstack);
690 lexer_token.kind = kind;
691 lexer_token.string.encoding = enc;
692 lexer_token.string.string = identify_string(string, size);
696 * Parse a string literal and set lexer_token.
698 static void parse_string_literal(string_encoding_t const enc)
700 parse_string('"', T_STRING_LITERAL, enc, "string literal");
704 * Parse a character constant and set lexer_token.
706 static void parse_character_constant(string_encoding_t const enc)
708 parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
709 if (lexer_token.string.string.size == 0) {
710 errorf(&lexer_token.base.source_position, "empty character constant");
715 * Skip a multiline comment.
717 static void skip_multiline_comment(void)
724 /* nested comment, warn here */
725 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
740 errorf(&lexer_token.base.source_position,
741 "at end of file while looking for comment end");
753 * Skip a single line comment.
755 static void skip_line_comment(void)
768 if (c == '\n' || c == '\r') {
769 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
781 /** The current preprocessor token. */
782 static token_t pp_token;
785 * Read the next preprocessor token.
787 static inline void next_pp_token(void)
789 lexer_next_preprocessing_token();
790 pp_token = lexer_token;
794 * Eat all preprocessor tokens until newline.
796 static void eat_until_newline(void)
798 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
804 * Parse the line directive.
806 static void parse_line_directive(void)
808 if (pp_token.kind != T_INTEGER) {
809 parse_error("expected integer");
811 /* use offset -1 as this is about the next line */
812 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
815 if (pp_token.kind == T_STRING_LITERAL && pp_token.string.encoding == STRING_ENCODING_CHAR) {
816 lexer_pos.input_name = pp_token.string.string.begin;
817 lexer_pos.is_system_header = false;
820 /* attempt to parse numeric flags as outputted by gcc preprocessor */
821 while (pp_token.kind == T_INTEGER) {
823 * 1 - indicates start of a new file
824 * 2 - indicates return from a file
825 * 3 - indicates system header
826 * 4 - indicates implicit extern "C" in C++ mode
828 * currently we're only interested in "3"
830 if (streq(pp_token.number.number.begin, "3")) {
831 lexer_pos.is_system_header = true;
843 typedef enum stdc_pragma_kind_t {
847 STDC_CX_LIMITED_RANGE
848 } stdc_pragma_kind_t;
851 * STDC pragma values.
853 typedef enum stdc_pragma_value_kind_t {
858 } stdc_pragma_value_kind_t;
861 * Parse a pragma directive.
863 static void parse_pragma(void)
866 if (pp_token.kind != T_IDENTIFIER) {
867 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
868 "expected identifier after #pragma");
873 stdc_pragma_kind_t kind = STDC_UNKNOWN;
874 if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
878 switch (pp_token.base.symbol->pp_ID) {
879 case TP_FP_CONTRACT: kind = STDC_FP_CONTRACT; break;
880 case TP_FENV_ACCESS: kind = STDC_FENV_ACCESS; break;
881 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
884 if (kind != STDC_UNKNOWN) {
886 stdc_pragma_value_kind_t value;
887 switch (pp_token.base.symbol->pp_ID) {
888 case TP_ON: value = STDC_VALUE_ON; break;
889 case TP_OFF: value = STDC_VALUE_OFF; break;
890 case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
891 default: value = STDC_VALUE_UNKNOWN; break;
893 if (value == STDC_VALUE_UNKNOWN) {
895 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
900 if (kind == STDC_UNKNOWN) {
901 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
902 "encountered unknown #pragma");
907 * Parse a preprocessor non-null directive.
909 static void parse_preprocessor_identifier(void)
911 assert(pp_token.kind == T_IDENTIFIER);
912 switch (pp_token.base.symbol->pp_ID) {
915 parse_line_directive();
921 /* TODO; output the rest of the line */
922 parse_error("#error directive");
928 * Parse a preprocessor directive.
930 static void parse_preprocessor_directive(void)
934 switch (pp_token.kind) {
936 parse_preprocessor_identifier();
939 parse_line_directive();
942 /* NULL directive, see §6.10.7 */
945 parse_error("invalid preprocessor directive");
951 #define MAYBE_PROLOG \
956 #define MAYBE(ch, set_type) \
959 lexer_token.kind = set_type; \
962 /* must use this as last thing */
963 #define MAYBE_MODE(ch, set_type, mode) \
965 if (c_mode & mode) { \
967 lexer_token.kind = set_type; \
972 #define ELSE_CODE(code) \
977 } /* end of while (true) */ \
979 #define ELSE(set_type) \
981 lexer_token.kind = set_type; \
984 void lexer_next_preprocessing_token(void)
987 lexer_token.base.source_position = lexer_pos;
988 lexer_token.base.symbol = NULL;
997 lexer_token.kind = '\n';
1002 /* might be a wide string ( L"string" ) */
1003 string_encoding_t const enc = STRING_ENCODING_WIDE;
1004 if (lexer_token.base.symbol == symbol_L) {
1006 case '"': parse_string_literal(enc); break;
1007 case '\'': parse_character_constant(enc); break;
1018 parse_string_literal(STRING_ENCODING_CHAR);
1022 parse_character_constant(STRING_ENCODING_CHAR);
1035 MAYBE('.', T_DOTDOTDOT)
1039 lexer_token.kind = '.';
1044 MAYBE('&', T_ANDAND)
1045 MAYBE('=', T_ANDEQUAL)
1049 MAYBE('=', T_ASTERISKEQUAL)
1053 MAYBE('+', T_PLUSPLUS)
1054 MAYBE('=', T_PLUSEQUAL)
1058 MAYBE('>', T_MINUSGREATER)
1059 MAYBE('-', T_MINUSMINUS)
1060 MAYBE('=', T_MINUSEQUAL)
1064 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1068 MAYBE('=', T_SLASHEQUAL)
1071 skip_multiline_comment();
1072 lexer_next_preprocessing_token();
1076 skip_line_comment();
1077 lexer_next_preprocessing_token();
1083 MAYBE('=', T_PERCENTEQUAL)
1088 MAYBE(':', T_HASHHASH)
1092 lexer_token.kind = '#';
1100 MAYBE('=', T_LESSEQUAL)
1103 MAYBE('=', T_LESSLESSEQUAL)
1108 MAYBE('=', T_GREATEREQUAL)
1111 MAYBE('=', T_GREATERGREATEREQUAL)
1112 ELSE(T_GREATERGREATER)
1116 MAYBE('=', T_CARETEQUAL)
1120 MAYBE('=', T_PIPEEQUAL)
1121 MAYBE('|', T_PIPEPIPE)
1126 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1130 MAYBE('=', T_EQUALEQUAL)
1134 MAYBE('#', T_HASHHASH)
1148 lexer_token.kind = c;
1153 lexer_token.kind = T_EOF;
1158 errorf(&lexer_pos, "unknown character '%c' found", c);
1165 void lexer_next_token(void)
1167 lexer_next_preprocessing_token();
1169 while (lexer_token.kind == '\n') {
1171 lexer_next_preprocessing_token();
1174 if (lexer_token.kind == '#') {
1175 parse_preprocessor_directive();
1180 void init_lexer(void)
1182 strset_init(&stringset);
1183 symbol_L = symbol_table_insert("L");
1186 static void input_error(unsigned delta_lines, unsigned delta_cols,
1187 const char *message)
1189 lexer_pos.lineno += delta_lines;
1190 lexer_pos.colno += delta_cols;
1191 errorf(&lexer_pos, "%s", message);
1194 void lexer_switch_input(input_t *new_input, const char *input_name)
1196 lexer_pos.lineno = 0;
1197 lexer_pos.colno = 0;
1198 lexer_pos.input_name = input_name;
1200 set_input_error_callback(input_error);
1205 /* place a virtual \n at the beginning so the lexer knows that we're
1206 * at the beginning of a line */
1210 void exit_lexer(void)
1212 strset_destroy(&stringset);
1215 static __attribute__((unused))
1216 void dbg_pos(const source_position_t source_position)
1218 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1219 source_position.lineno, (unsigned)source_position.colno);