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
23 #include "diagnostic.h"
27 #include "symbol_table_t.h"
28 #include "adt/error.h"
29 #include "adt/strset.h"
33 #include "target_architecture.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 static char *encoding;
61 bool allow_dollar_in_symbol = true;
64 * Prints a parse error message at the current token.
66 * @param msg the error message
68 static void parse_error(const char *msg)
70 errorf(&lexer_pos, "%s", msg);
74 * Prints an internal error message at the current token.
76 * @param msg the error message
78 static NORETURN internal_error(const char *msg)
80 internal_errorf(&lexer_pos, "%s", msg);
83 static inline void next_real_char(void)
85 assert(bufpos <= bufend);
86 if (bufpos >= bufend) {
87 size_t n = decode(input, input_buf+MAX_PUTBACK, BUF_SIZE);
92 bufpos = input_buf + MAX_PUTBACK;
100 * Put a character back into the buffer.
102 * @param pc the character to put back
104 static inline void put_back(utf32 const pc)
106 *(--bufpos - input_buf + input_buf) = pc;
110 static inline void next_char(void);
112 #define MATCH_NEWLINE(code) \
119 lexer_pos.lineno++; \
120 lexer_pos.colno = 1; \
123 #define eat(c_type) (assert(c == c_type), next_char())
125 static void maybe_concat_lines(void)
130 MATCH_NEWLINE(return;)
141 * Set c to the next input character, ie.
142 * after expanding trigraphs.
144 static inline void next_char(void)
148 /* filter trigraphs */
149 if (UNLIKELY(c == '\\')) {
150 maybe_concat_lines();
154 if (LIKELY(c != '?'))
158 if (LIKELY(c != '?')) {
166 case '=': c = '#'; break;
167 case '(': c = '['; break;
168 case '/': c = '\\'; maybe_concat_lines(); break;
169 case ')': c = ']'; break;
170 case '\'': c = '^'; break;
171 case '<': c = '{'; break;
172 case '!': c = '|'; break;
173 case '>': c = '}'; break;
174 case '-': c = '~'; break;
183 #define SYMBOL_CHARS \
184 case '$': if (!allow_dollar_in_symbol) goto dollar_sign; \
252 * Read a symbol from the input and build
255 static void parse_symbol(void)
257 obstack_1grow(&symbol_obstack, (char) c);
264 obstack_1grow(&symbol_obstack, (char) c);
275 obstack_1grow(&symbol_obstack, '\0');
277 char *string = obstack_finish(&symbol_obstack);
278 symbol_t *symbol = symbol_table_insert(string);
280 lexer_token.kind = symbol->ID;
281 lexer_token.identifier.symbol = symbol;
283 if (symbol->string != string) {
284 obstack_free(&symbol_obstack, string);
288 static string_t identify_string(char *string, size_t len)
292 const char *result = strset_insert(&stringset, concat);
293 if (result != concat) {
294 obstack_free(&symbol_obstack, concat);
297 const char *result = string;
299 return (string_t) {result, len};
303 * parse suffixes like 'LU' or 'f' after numbers
305 static void parse_number_suffix(void)
307 assert(obstack_object_size(&symbol_obstack) == 0);
311 obstack_1grow(&symbol_obstack, (char) c);
320 if (obstack_object_size(&symbol_obstack) == 0) {
321 lexer_token.number.suffix.begin = NULL;
322 lexer_token.number.suffix.size = 0;
326 obstack_1grow(&symbol_obstack, '\0');
327 size_t size = obstack_object_size(&symbol_obstack);
328 char *string = obstack_finish(&symbol_obstack);
330 lexer_token.number.suffix = identify_string(string, size);
334 * Parses a hex number including hex floats and set the
337 static void parse_number_hex(void)
339 bool is_float = false;
340 bool has_digits = false;
342 assert(obstack_object_size(&symbol_obstack) == 0);
343 while (isxdigit(c)) {
345 obstack_1grow(&symbol_obstack, (char) c);
351 obstack_1grow(&symbol_obstack, (char) c);
354 while (isxdigit(c)) {
356 obstack_1grow(&symbol_obstack, (char) c);
360 if (c == 'p' || c == 'P') {
362 obstack_1grow(&symbol_obstack, (char) c);
365 if (c == '-' || c == '+') {
366 obstack_1grow(&symbol_obstack, (char) c);
370 while (isxdigit(c)) {
371 obstack_1grow(&symbol_obstack, (char) c);
374 } else if (is_float) {
375 errorf(&lexer_token.base.source_position,
376 "hexadecimal floatingpoint constant requires an exponent");
378 obstack_1grow(&symbol_obstack, '\0');
380 size_t size = obstack_object_size(&symbol_obstack) - 1;
381 char *string = obstack_finish(&symbol_obstack);
382 lexer_token.number.number = identify_string(string, size);
385 is_float ? T_FLOATINGPOINT_HEXADECIMAL : T_INTEGER_HEXADECIMAL;
388 errorf(&lexer_token.base.source_position,
389 "invalid number literal '0x%S'", &lexer_token.number.number);
390 lexer_token.number.number.begin = "0";
391 lexer_token.number.number.size = 1;
394 parse_number_suffix();
398 * Returns true if the given char is a octal digit.
400 * @param char the character to check
402 static bool is_octal_digit(utf32 chr)
404 return '0' <= chr && chr <= '7';
408 * Parses a number and sets the lexer_token.
410 static void parse_number(void)
412 bool is_float = false;
413 bool has_digits = false;
415 assert(obstack_object_size(&symbol_obstack) == 0);
418 if (c == 'x' || c == 'X') {
425 obstack_1grow(&symbol_obstack, '0');
430 obstack_1grow(&symbol_obstack, (char) c);
436 obstack_1grow(&symbol_obstack, '.');
441 obstack_1grow(&symbol_obstack, (char) c);
445 if (c == 'e' || c == 'E') {
447 obstack_1grow(&symbol_obstack, 'e');
450 if (c == '-' || c == '+') {
451 obstack_1grow(&symbol_obstack, (char) c);
456 obstack_1grow(&symbol_obstack, (char) c);
461 obstack_1grow(&symbol_obstack, '\0');
462 size_t size = obstack_object_size(&symbol_obstack) - 1;
463 char *string = obstack_finish(&symbol_obstack);
464 lexer_token.number.number = identify_string(string, size);
466 /* is it an octal number? */
468 lexer_token.kind = T_FLOATINGPOINT;
469 } else if (string[0] == '0') {
470 lexer_token.kind = T_INTEGER_OCTAL;
472 /* check for invalid octal digits */
473 for (size_t i= 0; i < size; ++i) {
476 errorf(&lexer_token.base.source_position,
477 "invalid digit '%c' in octal number", t);
480 lexer_token.kind = T_INTEGER;
484 errorf(&lexer_token.base.source_position, "invalid number literal '%S'",
485 &lexer_token.number.number);
488 parse_number_suffix();
492 * Returns the value of a digit.
493 * The only portable way to do it ...
495 static int digit_value(utf32 const digit)
521 internal_error("wrong character given");
526 * Parses an octal character sequence.
528 * @param first_digit the already read first digit
530 static utf32 parse_octal_sequence(utf32 const first_digit)
532 assert(is_octal_digit(first_digit));
533 utf32 value = digit_value(first_digit);
534 if (!is_octal_digit(c)) return value;
535 value = 8 * value + digit_value(c);
537 if (!is_octal_digit(c)) return value;
538 value = 8 * value + digit_value(c);
544 * Parses a hex character sequence.
546 static utf32 parse_hex_sequence(void)
549 while (isxdigit(c)) {
550 value = 16 * value + digit_value(c);
557 * Parse an escape sequence.
559 static utf32 parse_escape_sequence(void)
567 case '"': return '"';
568 case '\'': return '\'';
569 case '\\': return '\\';
570 case '?': return '\?';
571 case 'a': return '\a';
572 case 'b': return '\b';
573 case 'f': return '\f';
574 case 'n': return '\n';
575 case 'r': return '\r';
576 case 't': return '\t';
577 case 'v': return '\v';
579 return parse_hex_sequence();
588 return parse_octal_sequence(ec);
590 parse_error("reached end of file while parsing escape sequence");
592 /* \E is not documented, but handled, by GCC. It is acceptable according
593 * to §6.11.4, whereas \e is not. */
597 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
601 parse_error("universal character parsing not implemented yet");
606 /* §6.4.4.4:8 footnote 64 */
607 parse_error("unknown escape sequence");
612 * Concatenate two strings.
614 string_t concat_strings(const string_t *const s1, const string_t *const s2)
616 const size_t len1 = s1->size - 1;
617 const size_t len2 = s2->size - 1;
619 char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
620 memcpy(concat, s1->begin, len1);
621 memcpy(concat + len1, s2->begin, len2 + 1);
623 return identify_string(concat, len1 + len2 + 1);
626 string_t make_string(const char *string)
628 size_t len = strlen(string) + 1;
629 char *const space = obstack_alloc(&symbol_obstack, len);
630 memcpy(space, string, len);
632 return identify_string(space, len);
635 static void grow_symbol(utf32 const tc)
637 struct obstack *const o = &symbol_obstack;
639 obstack_1grow(o, tc);
640 } else if (tc < 0x800) {
641 obstack_1grow(o, 0xC0 | (tc >> 6));
642 obstack_1grow(o, 0x80 | (tc & 0x3F));
643 } else if (tc < 0x10000) {
644 obstack_1grow(o, 0xE0 | ( tc >> 12));
645 obstack_1grow(o, 0x80 | ((tc >> 6) & 0x3F));
646 obstack_1grow(o, 0x80 | ( tc & 0x3F));
648 obstack_1grow(o, 0xF0 | ( tc >> 18));
649 obstack_1grow(o, 0x80 | ((tc >> 12) & 0x3F));
650 obstack_1grow(o, 0x80 | ((tc >> 6) & 0x3F));
651 obstack_1grow(o, 0x80 | ( tc & 0x3F));
656 * Parse a string literal and set lexer_token.
658 static void parse_string_literal(void)
665 utf32 const tc = parse_escape_sequence();
667 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
669 obstack_1grow(&symbol_obstack, tc);
674 errorf(&lexer_token.base.source_position, "string has no end");
675 lexer_token.kind = T_ERROR;
692 /* TODO: concatenate multiple strings separated by whitespace... */
694 /* add finishing 0 to the string */
695 obstack_1grow(&symbol_obstack, '\0');
696 const size_t size = (size_t)obstack_object_size(&symbol_obstack);
697 char *string = obstack_finish(&symbol_obstack);
699 lexer_token.kind = T_STRING_LITERAL;
700 lexer_token.string.string = identify_string(string, size);
704 * Parse a wide character constant and set lexer_token.
706 static void parse_wide_character_constant(void)
713 const utf32 tc = parse_escape_sequence();
719 parse_error("newline while parsing character constant");
725 goto end_of_wide_char_constant;
728 errorf(&lexer_token.base.source_position,
729 "EOF while parsing character constant");
730 lexer_token.kind = T_ERROR;
741 end_of_wide_char_constant:;
742 obstack_1grow(&symbol_obstack, '\0');
743 size_t size = (size_t) obstack_object_size(&symbol_obstack) - 1;
744 char *string = obstack_finish(&symbol_obstack);
746 lexer_token.kind = T_WIDE_CHARACTER_CONSTANT;
747 lexer_token.string.string = identify_string(string, size);
750 errorf(&lexer_token.base.source_position, "empty character constant");
755 * Parse a wide string literal and set lexer_token.
757 static void parse_wide_string_literal(void)
759 parse_string_literal();
760 if (lexer_token.kind == T_STRING_LITERAL)
761 lexer_token.kind = T_WIDE_STRING_LITERAL;
765 * Parse a character constant and set lexer_token.
767 static void parse_character_constant(void)
774 utf32 const tc = parse_escape_sequence();
776 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
778 obstack_1grow(&symbol_obstack, tc);
783 parse_error("newline while parsing character constant");
789 goto end_of_char_constant;
792 errorf(&lexer_token.base.source_position,
793 "EOF while parsing character constant");
794 lexer_token.kind = T_ERROR;
806 end_of_char_constant:;
807 obstack_1grow(&symbol_obstack, '\0');
808 const size_t size = (size_t)obstack_object_size(&symbol_obstack)-1;
809 char *const string = obstack_finish(&symbol_obstack);
811 lexer_token.kind = T_CHARACTER_CONSTANT;
812 lexer_token.string.string = identify_string(string, size);
815 errorf(&lexer_token.base.source_position, "empty character constant");
820 * Skip a multiline comment.
822 static void skip_multiline_comment(void)
829 /* nested comment, warn here */
830 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
841 MATCH_NEWLINE(break;)
844 errorf(&lexer_token.base.source_position,
845 "at end of file while looking for comment end");
857 * Skip a single line comment.
859 static void skip_line_comment(void)
872 if (c == '\n' || c == '\r') {
873 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
885 /** The current preprocessor token. */
886 static token_t pp_token;
889 * Read the next preprocessor token.
891 static inline void next_pp_token(void)
893 lexer_next_preprocessing_token();
894 pp_token = lexer_token;
898 * Eat all preprocessor tokens until newline.
900 static void eat_until_newline(void)
902 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
908 * Handle the define directive.
910 static void define_directive(void)
912 lexer_next_preprocessing_token();
913 if (lexer_token.kind != T_IDENTIFIER) {
914 parse_error("expected identifier after #define\n");
920 * Handle the ifdef directive.
922 static void ifdef_directive(int is_ifndef)
925 lexer_next_preprocessing_token();
926 //expect_identifier();
931 * Handle the endif directive.
933 static void endif_directive(void)
939 * Parse the line directive.
941 static void parse_line_directive(void)
943 if (pp_token.kind != T_INTEGER) {
944 parse_error("expected integer");
946 /* use offset -1 as this is about the next line */
947 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
950 if (pp_token.kind == T_STRING_LITERAL) {
951 lexer_pos.input_name = pp_token.string.string.begin;
961 typedef enum stdc_pragma_kind_t {
965 STDC_CX_LIMITED_RANGE
966 } stdc_pragma_kind_t;
969 * STDC pragma values.
971 typedef enum stdc_pragma_value_kind_t {
976 } stdc_pragma_value_kind_t;
979 * Parse a pragma directive.
981 static void parse_pragma(void)
983 bool unknown_pragma = true;
986 if (pp_token.kind != T_IDENTIFIER) {
987 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
988 "expected identifier after #pragma");
993 symbol_t *symbol = pp_token.identifier.symbol;
994 if (symbol->pp_ID == TP_STDC) {
995 stdc_pragma_kind_t kind = STDC_UNKNOWN;
1000 switch (pp_token.identifier.symbol->pp_ID) {
1001 case TP_FP_CONTRACT:
1002 kind = STDC_FP_CONTRACT;
1004 case TP_FENV_ACCESS:
1005 kind = STDC_FENV_ACCESS;
1007 case TP_CX_LIMITED_RANGE:
1008 kind = STDC_CX_LIMITED_RANGE;
1013 if (kind != STDC_UNKNOWN) {
1014 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
1016 switch (pp_token.identifier.symbol->pp_ID) {
1018 value = STDC_VALUE_ON;
1021 value = STDC_VALUE_OFF;
1024 value = STDC_VALUE_DEFAULT;
1029 if (value != STDC_VALUE_UNKNOWN) {
1030 unknown_pragma = false;
1032 errorf(&pp_token.base.source_position,
1033 "bad STDC pragma argument");
1038 unknown_pragma = true;
1040 eat_until_newline();
1041 if (unknown_pragma) {
1042 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
1043 "encountered unknown #pragma");
1048 * Parse a preprocessor non-null directive.
1050 static void parse_preprocessor_identifier(void)
1052 assert(pp_token.kind == T_IDENTIFIER);
1053 symbol_t *symbol = pp_token.identifier.symbol;
1055 switch (symbol->pp_ID) {
1057 printf("include - enable header name parsing!\n");
1073 parse_line_directive();
1080 /* TODO; output the rest of the line */
1081 parse_error("#error directive: ");
1090 * Parse a preprocessor directive.
1092 static void parse_preprocessor_directive(void)
1096 switch (pp_token.kind) {
1098 parse_preprocessor_identifier();
1101 parse_line_directive();
1104 /* NULL directive, see §6.10.7 */
1107 parse_error("invalid preprocessor directive");
1108 eat_until_newline();
1113 #define MAYBE_PROLOG \
1118 #define MAYBE(ch, set_type) \
1121 lexer_token.kind = set_type; \
1124 /* must use this as last thing */
1125 #define MAYBE_MODE(ch, set_type, mode) \
1127 if (c_mode & mode) { \
1129 lexer_token.kind = set_type; \
1134 #define ELSE_CODE(code) \
1139 } /* end of while (true) */ \
1141 #define ELSE(set_type) \
1143 lexer_token.kind = set_type; \
1146 void lexer_next_preprocessing_token(void)
1149 lexer_token.base.source_position = lexer_pos;
1158 lexer_token.kind = '\n';
1164 /* might be a wide string ( L"string" ) */
1165 if (lexer_token.identifier.symbol == symbol_L) {
1167 case '"': parse_wide_string_literal(); break;
1168 case '\'': parse_wide_character_constant(); break;
1178 parse_string_literal();
1182 parse_character_constant();
1195 MAYBE('.', T_DOTDOTDOT)
1199 lexer_token.kind = '.';
1204 MAYBE('&', T_ANDAND)
1205 MAYBE('=', T_ANDEQUAL)
1209 MAYBE('=', T_ASTERISKEQUAL)
1213 MAYBE('+', T_PLUSPLUS)
1214 MAYBE('=', T_PLUSEQUAL)
1218 MAYBE('>', T_MINUSGREATER)
1219 MAYBE('-', T_MINUSMINUS)
1220 MAYBE('=', T_MINUSEQUAL)
1224 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1228 MAYBE('=', T_SLASHEQUAL)
1231 skip_multiline_comment();
1232 lexer_next_preprocessing_token();
1236 skip_line_comment();
1237 lexer_next_preprocessing_token();
1243 MAYBE('=', T_PERCENTEQUAL)
1248 MAYBE(':', T_HASHHASH)
1252 lexer_token.kind = '#';
1260 MAYBE('=', T_LESSEQUAL)
1263 MAYBE('=', T_LESSLESSEQUAL)
1268 MAYBE('=', T_GREATEREQUAL)
1271 MAYBE('=', T_GREATERGREATEREQUAL)
1272 ELSE(T_GREATERGREATER)
1276 MAYBE('=', T_CARETEQUAL)
1280 MAYBE('=', T_PIPEEQUAL)
1281 MAYBE('|', T_PIPEPIPE)
1286 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1290 MAYBE('=', T_EQUALEQUAL)
1294 MAYBE('#', T_HASHHASH)
1308 lexer_token.kind = c;
1313 lexer_token.kind = T_EOF;
1318 errorf(&lexer_pos, "unknown character '%c' found", c);
1320 lexer_token.kind = T_ERROR;
1326 void lexer_next_token(void)
1328 lexer_next_preprocessing_token();
1330 while (lexer_token.kind == '\n') {
1332 lexer_next_preprocessing_token();
1335 if (lexer_token.kind == '#') {
1336 parse_preprocessor_directive();
1341 void init_lexer(void)
1343 strset_init(&stringset);
1344 symbol_L = symbol_table_insert("L");
1347 static void input_error(unsigned delta_lines, unsigned delta_cols,
1348 const char *message)
1350 lexer_pos.lineno += delta_lines;
1351 lexer_pos.colno += delta_cols;
1352 errorf(&lexer_pos, "%s", message);
1355 void select_input_encoding(char const* new_encoding)
1357 if (encoding != NULL)
1359 encoding = xstrdup(new_encoding);
1362 void lexer_open_stream(FILE *stream, const char *input_name)
1364 if (input != NULL) {
1369 lexer_pos.lineno = 0;
1370 lexer_pos.colno = 0;
1371 lexer_pos.input_name = input_name;
1373 set_input_error_callback(input_error);
1374 input = input_from_stream(stream, encoding);
1378 /* place a virtual \n at the beginning so the lexer knows that we're
1379 * at the beginning of a line */
1383 void exit_lexer(void)
1385 if (input != NULL) {
1389 strset_destroy(&stringset);
1392 static __attribute__((unused))
1393 void dbg_pos(const source_position_t source_position)
1395 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1396 source_position.lineno, source_position.colno);