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_WITHOUT_E_P \
185 '$': if (!allow_dollar_in_symbol) goto dollar_sign; \
236 #define SYMBOL_CHARS_E_P \
242 #define SYMBOL_CHARS \
243 SYMBOL_CHARS_WITHOUT_E_P: \
244 case SYMBOL_CHARS_E_P
258 static bool is_universal_char_valid(utf32 const v)
261 if (v < 0xA0U && v != 0x24 && v != 0x40 && v != 0x60)
263 if (0xD800 <= v && v <= 0xDFFF)
268 static int digit_value(utf32 digit);
270 static utf32 parse_universal_char(unsigned const n_digits)
273 for (unsigned k = n_digits; k != 0; --k) {
275 v = 16 * v + digit_value(c);
278 errorf(&lexer_pos, "short universal character name, expected %u more digits", k);
282 if (!is_universal_char_valid(v)) {
283 errorf(&lexer_pos, "\\%c%0*X is not a valid universal character name", n_digits == 4 ? 'u' : 'U', (int)n_digits, v);
288 static bool is_universal_char_valid_identifier(utf32 const v)
291 if ( v == 0x000A8) return true;
292 if ( v == 0x000AA) return true;
293 if ( v == 0x000AD) return true;
294 if ( v == 0x000AF) return true;
295 if (0x000B2 <= v && v <= 0x000B5) return true;
296 if (0x000B7 <= v && v <= 0x000BA) return true;
297 if (0x000BC <= v && v <= 0x000BE) return true;
298 if (0x000C0 <= v && v <= 0x000D6) return true;
299 if (0x000D8 <= v && v <= 0x000F6) return true;
300 if (0x000F8 <= v && v <= 0x000FF) return true;
301 if (0x00100 <= v && v <= 0x0167F) return true;
302 if (0x01681 <= v && v <= 0x0180D) return true;
303 if (0x0180F <= v && v <= 0x01FFF) return true;
304 if (0x0200B <= v && v <= 0x0200D) return true;
305 if (0x0202A <= v && v <= 0x0202E) return true;
306 if (0x0203F <= v && v <= 0x02040) return true;
307 if ( v == 0x02054) return true;
308 if (0x02060 <= v && v <= 0x0206F) return true;
309 if (0x02070 <= v && v <= 0x0218F) return true;
310 if (0x02460 <= v && v <= 0x024FF) return true;
311 if (0x02776 <= v && v <= 0x02793) return true;
312 if (0x02C00 <= v && v <= 0x02DFF) return true;
313 if (0x02E80 <= v && v <= 0x02FFF) return true;
314 if (0x03004 <= v && v <= 0x03007) return true;
315 if (0x03021 <= v && v <= 0x0302F) return true;
316 if (0x03031 <= v && v <= 0x0303F) return true;
317 if (0x03040 <= v && v <= 0x0D7FF) return true;
318 if (0x0F900 <= v && v <= 0x0FD3D) return true;
319 if (0x0FD40 <= v && v <= 0x0FDCF) return true;
320 if (0x0FDF0 <= v && v <= 0x0FE44) return true;
321 if (0x0FE47 <= v && v <= 0x0FFFD) return true;
322 if (0x10000 <= v && v <= 0x1FFFD) return true;
323 if (0x20000 <= v && v <= 0x2FFFD) return true;
324 if (0x30000 <= v && v <= 0x3FFFD) return true;
325 if (0x40000 <= v && v <= 0x4FFFD) return true;
326 if (0x50000 <= v && v <= 0x5FFFD) return true;
327 if (0x60000 <= v && v <= 0x6FFFD) return true;
328 if (0x70000 <= v && v <= 0x7FFFD) return true;
329 if (0x80000 <= v && v <= 0x8FFFD) return true;
330 if (0x90000 <= v && v <= 0x9FFFD) return true;
331 if (0xA0000 <= v && v <= 0xAFFFD) return true;
332 if (0xB0000 <= v && v <= 0xBFFFD) return true;
333 if (0xC0000 <= v && v <= 0xCFFFD) return true;
334 if (0xD0000 <= v && v <= 0xDFFFD) return true;
335 if (0xE0000 <= v && v <= 0xEFFFD) return true;
339 static bool is_universal_char_valid_identifier_start(utf32 const v)
342 if (0x0300 <= v && v <= 0x036F) return false;
343 if (0x1DC0 <= v && v <= 0x1DFF) return false;
344 if (0x20D0 <= v && v <= 0x20FF) return false;
345 if (0xFE20 <= v && v <= 0xFE2F) return false;
350 * Read a symbol from the input and build
353 static void parse_symbol(void)
359 obstack_1grow(&symbol_obstack, (char) c);
368 case 'U': n = 8; goto universal;
369 case 'u': n = 4; goto universal;
372 utf32 const v = parse_universal_char(n);
373 if (!is_universal_char_valid_identifier(v)) {
374 if (is_universal_char_valid(v)) {
375 errorf(&lexer_pos, "universal character \\%c%0*X is not valid in an identifier", n == 4 ? 'u' : 'U', (int)n, v);
377 } else if (obstack_object_size(&symbol_obstack) == 0 && !is_universal_char_valid_identifier_start(v)) {
378 errorf(&lexer_pos, "universal character \\%c%0*X is not valid as start of an identifier", n == 4 ? 'u' : 'U', (int)n, v);
380 obstack_grow_utf8(&symbol_obstack, v);
398 obstack_1grow(&symbol_obstack, '\0');
400 char *string = obstack_finish(&symbol_obstack);
401 symbol_t *symbol = symbol_table_insert(string);
403 lexer_token.kind = symbol->ID;
404 lexer_token.base.symbol = symbol;
406 if (symbol->string != string) {
407 obstack_free(&symbol_obstack, string);
411 static string_t sym_make_string(string_encoding_t const enc)
413 obstack_1grow(&symbol_obstack, '\0');
414 size_t const len = obstack_object_size(&symbol_obstack) - 1;
415 char *const string = obstack_finish(&symbol_obstack);
419 const char *result = strset_insert(&stringset, concat);
420 if (result != concat) {
421 obstack_free(&symbol_obstack, concat);
424 const char *result = string;
426 return (string_t){ result, len, enc };
429 static void parse_pp_number(void)
433 case SYMBOL_CHARS_E_P:
434 obstack_1grow(&symbol_obstack, (char)c);
436 if (c == '+' || c == '-') {
439 case SYMBOL_CHARS_WITHOUT_E_P:
440 obstack_1grow(&symbol_obstack, (char)c);
447 lexer_token.kind = T_NUMBER;
448 lexer_token.literal.string = sym_make_string(STRING_ENCODING_CHAR);
455 * Returns true if the given char is a octal digit.
457 * @param char the character to check
459 static bool is_octal_digit(utf32 chr)
461 return '0' <= chr && chr <= '7';
465 * Returns the value of a digit.
466 * The only portable way to do it ...
468 static int digit_value(utf32 const digit)
494 internal_error("wrong character given");
499 * Parses an octal character sequence.
501 * @param first_digit the already read first digit
503 static utf32 parse_octal_sequence(utf32 const first_digit)
505 assert(is_octal_digit(first_digit));
506 utf32 value = digit_value(first_digit);
507 if (!is_octal_digit(c)) return value;
508 value = 8 * value + digit_value(c);
510 if (!is_octal_digit(c)) return value;
511 value = 8 * value + digit_value(c);
517 * Parses a hex character sequence.
519 static utf32 parse_hex_sequence(void)
522 while (isxdigit(c)) {
523 value = 16 * value + digit_value(c);
530 * Parse an escape sequence.
532 static utf32 parse_escape_sequence(void)
540 case '"': return '"';
541 case '\'': return '\'';
542 case '\\': return '\\';
543 case '?': return '\?';
544 case 'a': return '\a';
545 case 'b': return '\b';
546 case 'f': return '\f';
547 case 'n': return '\n';
548 case 'r': return '\r';
549 case 't': return '\t';
550 case 'v': return '\v';
552 return parse_hex_sequence();
561 return parse_octal_sequence(ec);
563 parse_error("reached end of file while parsing escape sequence");
565 /* \E is not documented, but handled, by GCC. It is acceptable according
566 * to §6.11.4, whereas \e is not. */
570 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
573 case 'U': return parse_universal_char(8);
574 case 'u': return parse_universal_char(4);
579 /* §6.4.4.4:8 footnote 64 */
580 parse_error("unknown escape sequence");
584 string_t make_string(const char *string)
586 obstack_grow(&symbol_obstack, string, strlen(string));
587 return sym_make_string(STRING_ENCODING_CHAR);
590 static void parse_string(utf32 const delim, token_kind_t const kind, string_encoding_t const enc, char const *const context)
597 utf32 const tc = parse_escape_sequence();
598 if (enc == STRING_ENCODING_CHAR) {
600 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
602 obstack_1grow(&symbol_obstack, tc);
604 obstack_grow_utf8(&symbol_obstack, tc);
610 errorf(&lexer_pos, "newline while parsing %s", context);
614 errorf(&lexer_token.base.source_position, "EOF while parsing %s", context);
622 obstack_grow_utf8(&symbol_obstack, c);
630 lexer_token.kind = kind;
631 lexer_token.literal.string = sym_make_string(enc);
635 * Parse a string literal and set lexer_token.
637 static void parse_string_literal(string_encoding_t const enc)
639 parse_string('"', T_STRING_LITERAL, enc, "string literal");
643 * Parse a character constant and set lexer_token.
645 static void parse_character_constant(string_encoding_t const enc)
647 parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
648 if (lexer_token.literal.string.size == 0) {
649 errorf(&lexer_token.base.source_position, "empty character constant");
654 * Skip a multiline comment.
656 static void skip_multiline_comment(void)
663 /* nested comment, warn here */
664 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
679 errorf(&lexer_token.base.source_position,
680 "at end of file while looking for comment end");
692 * Skip a single line comment.
694 static void skip_line_comment(void)
707 if (c == '\n' || c == '\r') {
708 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
720 /** The current preprocessor token. */
721 static token_t pp_token;
724 * Read the next preprocessor token.
726 static inline void next_pp_token(void)
728 lexer_next_preprocessing_token();
729 pp_token = lexer_token;
733 * Eat all preprocessor tokens until newline.
735 static void eat_until_newline(void)
737 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
743 * Parse the line directive.
745 static void parse_line_directive(void)
747 if (pp_token.kind != T_NUMBER) {
748 parse_error("expected integer");
750 /* use offset -1 as this is about the next line */
752 long const line = strtol(pp_token.literal.string.begin, &end, 0);
754 lexer_pos.lineno = line - 1;
756 errorf(&lexer_pos, "'%S' is not a valid line number", &pp_token.literal.string);
760 if (pp_token.kind == T_STRING_LITERAL && pp_token.literal.string.encoding == STRING_ENCODING_CHAR) {
761 lexer_pos.input_name = pp_token.literal.string.begin;
762 lexer_pos.is_system_header = false;
765 /* attempt to parse numeric flags as outputted by gcc preprocessor */
766 while (pp_token.kind == T_NUMBER) {
768 * 1 - indicates start of a new file
769 * 2 - indicates return from a file
770 * 3 - indicates system header
771 * 4 - indicates implicit extern "C" in C++ mode
773 * currently we're only interested in "3"
775 if (streq(pp_token.literal.string.begin, "3")) {
776 lexer_pos.is_system_header = true;
788 typedef enum stdc_pragma_kind_t {
792 STDC_CX_LIMITED_RANGE
793 } stdc_pragma_kind_t;
796 * STDC pragma values.
798 typedef enum stdc_pragma_value_kind_t {
803 } stdc_pragma_value_kind_t;
806 * Parse a pragma directive.
808 static void parse_pragma(void)
811 if (pp_token.kind != T_IDENTIFIER) {
812 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
813 "expected identifier after #pragma");
818 stdc_pragma_kind_t kind = STDC_UNKNOWN;
819 if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
823 switch (pp_token.base.symbol->pp_ID) {
824 case TP_FP_CONTRACT: kind = STDC_FP_CONTRACT; break;
825 case TP_FENV_ACCESS: kind = STDC_FENV_ACCESS; break;
826 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
829 if (kind != STDC_UNKNOWN) {
831 stdc_pragma_value_kind_t value;
832 switch (pp_token.base.symbol->pp_ID) {
833 case TP_ON: value = STDC_VALUE_ON; break;
834 case TP_OFF: value = STDC_VALUE_OFF; break;
835 case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
836 default: value = STDC_VALUE_UNKNOWN; break;
838 if (value == STDC_VALUE_UNKNOWN) {
840 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
845 if (kind == STDC_UNKNOWN) {
846 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
847 "encountered unknown #pragma");
852 * Parse a preprocessor non-null directive.
854 static void parse_preprocessor_identifier(void)
856 assert(pp_token.kind == T_IDENTIFIER);
857 switch (pp_token.base.symbol->pp_ID) {
860 parse_line_directive();
866 /* TODO; output the rest of the line */
867 parse_error("#error directive");
873 * Parse a preprocessor directive.
875 static void parse_preprocessor_directive(void)
879 switch (pp_token.kind) {
881 parse_preprocessor_identifier();
884 parse_line_directive();
887 /* NULL directive, see §6.10.7 */
890 parse_error("invalid preprocessor directive");
896 #define MAYBE_PROLOG \
901 #define MAYBE(ch, set_type) \
904 lexer_token.kind = set_type; \
907 /* must use this as last thing */
908 #define MAYBE_MODE(ch, set_type, mode) \
910 if (c_mode & mode) { \
912 lexer_token.kind = set_type; \
917 #define ELSE_CODE(code) \
922 } /* end of while (true) */ \
924 #define ELSE(set_type) \
926 lexer_token.kind = set_type; \
929 void lexer_next_preprocessing_token(void)
932 lexer_token.base.source_position = lexer_pos;
933 lexer_token.base.symbol = NULL;
942 lexer_token.kind = '\n';
947 /* might be a wide string ( L"string" ) */
948 string_encoding_t const enc = STRING_ENCODING_WIDE;
949 if (lexer_token.base.symbol == symbol_L) {
951 case '"': parse_string_literal(enc); break;
952 case '\'': parse_character_constant(enc); break;
963 parse_string_literal(STRING_ENCODING_CHAR);
967 parse_character_constant(STRING_ENCODING_CHAR);
980 MAYBE('.', T_DOTDOTDOT)
984 lexer_token.kind = '.';
990 MAYBE('=', T_ANDEQUAL)
994 MAYBE('=', T_ASTERISKEQUAL)
998 MAYBE('+', T_PLUSPLUS)
999 MAYBE('=', T_PLUSEQUAL)
1003 MAYBE('>', T_MINUSGREATER)
1004 MAYBE('-', T_MINUSMINUS)
1005 MAYBE('=', T_MINUSEQUAL)
1009 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1013 MAYBE('=', T_SLASHEQUAL)
1016 skip_multiline_comment();
1017 lexer_next_preprocessing_token();
1021 skip_line_comment();
1022 lexer_next_preprocessing_token();
1028 MAYBE('=', T_PERCENTEQUAL)
1033 MAYBE(':', T_HASHHASH)
1037 lexer_token.kind = '#';
1045 MAYBE('=', T_LESSEQUAL)
1048 MAYBE('=', T_LESSLESSEQUAL)
1053 MAYBE('=', T_GREATEREQUAL)
1056 MAYBE('=', T_GREATERGREATEREQUAL)
1057 ELSE(T_GREATERGREATER)
1061 MAYBE('=', T_CARETEQUAL)
1065 MAYBE('=', T_PIPEEQUAL)
1066 MAYBE('|', T_PIPEPIPE)
1071 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1075 MAYBE('=', T_EQUALEQUAL)
1079 MAYBE('#', T_HASHHASH)
1084 if (c == 'U' || c == 'u') {
1089 lexer_token.kind = '\\';
1103 lexer_token.kind = c;
1108 lexer_token.kind = T_EOF;
1113 errorf(&lexer_pos, "unknown character '%lc' found", c);
1120 void lexer_next_token(void)
1122 lexer_next_preprocessing_token();
1124 while (lexer_token.kind == '\n') {
1126 lexer_next_preprocessing_token();
1129 if (lexer_token.kind == '#') {
1130 parse_preprocessor_directive();
1135 void init_lexer(void)
1137 strset_init(&stringset);
1138 symbol_L = symbol_table_insert("L");
1141 static void input_error(unsigned delta_lines, unsigned delta_cols,
1142 const char *message)
1144 lexer_pos.lineno += delta_lines;
1145 lexer_pos.colno += delta_cols;
1146 errorf(&lexer_pos, "%s", message);
1149 void lexer_switch_input(input_t *new_input, const char *input_name)
1151 lexer_pos.lineno = 0;
1152 lexer_pos.colno = 0;
1153 lexer_pos.input_name = input_name;
1155 set_input_error_callback(input_error);
1160 /* place a virtual \n at the beginning so the lexer knows that we're
1161 * at the beginning of a line */
1165 void exit_lexer(void)
1167 strset_destroy(&stringset);
1170 static __attribute__((unused))
1171 void dbg_pos(const source_position_t source_position)
1173 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1174 source_position.lineno, (unsigned)source_position.colno);