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.type = symbol->ID;
281 lexer_token.symbol = symbol;
283 if (symbol->string != string) {
284 obstack_free(&symbol_obstack, string);
289 * parse suffixes like 'LU' or 'f' after numbers
291 static void parse_number_suffix(void)
293 assert(obstack_object_size(&symbol_obstack) == 0);
297 obstack_1grow(&symbol_obstack, (char) c);
306 if (obstack_object_size(&symbol_obstack) == 0) {
307 lexer_token.symbol = NULL;
311 obstack_1grow(&symbol_obstack, '\0');
312 char *string = obstack_finish(&symbol_obstack);
313 symbol_t *symbol = symbol_table_insert(string);
315 if (symbol->string != string) {
316 obstack_free(&symbol_obstack, string);
318 lexer_token.symbol = symbol;
321 static string_t identify_string(char *string, size_t len)
325 const char *result = strset_insert(&stringset, concat);
326 if (result != concat) {
327 obstack_free(&symbol_obstack, concat);
330 const char *result = string;
332 return (string_t) {result, len};
336 * Parses a hex number including hex floats and set the
339 static void parse_number_hex(void)
341 bool is_float = false;
342 bool has_digits = false;
344 assert(obstack_object_size(&symbol_obstack) == 0);
345 while (isxdigit(c)) {
347 obstack_1grow(&symbol_obstack, (char) c);
353 obstack_1grow(&symbol_obstack, (char) c);
356 while (isxdigit(c)) {
358 obstack_1grow(&symbol_obstack, (char) c);
362 if (c == 'p' || c == 'P') {
364 obstack_1grow(&symbol_obstack, (char) c);
367 if (c == '-' || c == '+') {
368 obstack_1grow(&symbol_obstack, (char) c);
372 while (isxdigit(c)) {
373 obstack_1grow(&symbol_obstack, (char) c);
376 } else if (is_float) {
377 errorf(&lexer_token.source_position,
378 "hexadecimal floatingpoint constant requires an exponent");
380 obstack_1grow(&symbol_obstack, '\0');
382 size_t size = obstack_object_size(&symbol_obstack) - 1;
383 char *string = obstack_finish(&symbol_obstack);
384 lexer_token.literal = identify_string(string, size);
387 is_float ? T_FLOATINGPOINT_HEXADECIMAL : T_INTEGER_HEXADECIMAL;
390 errorf(&lexer_token.source_position, "invalid number literal '0x%S'",
391 &lexer_token.literal);
392 lexer_token.literal.begin = "0";
393 lexer_token.literal.size = 1;
396 parse_number_suffix();
400 * Returns true if the given char is a octal digit.
402 * @param char the character to check
404 static bool is_octal_digit(utf32 chr)
406 return '0' <= chr && chr <= '7';
410 * Parses a number and sets the lexer_token.
412 static void parse_number(void)
414 bool is_float = false;
415 bool has_digits = false;
417 assert(obstack_object_size(&symbol_obstack) == 0);
420 if (c == 'x' || c == 'X') {
427 obstack_1grow(&symbol_obstack, '0');
432 obstack_1grow(&symbol_obstack, (char) c);
438 obstack_1grow(&symbol_obstack, '.');
443 obstack_1grow(&symbol_obstack, (char) c);
447 if (c == 'e' || c == 'E') {
449 obstack_1grow(&symbol_obstack, 'e');
452 if (c == '-' || c == '+') {
453 obstack_1grow(&symbol_obstack, (char) c);
458 obstack_1grow(&symbol_obstack, (char) c);
463 obstack_1grow(&symbol_obstack, '\0');
464 size_t size = obstack_object_size(&symbol_obstack) - 1;
465 char *string = obstack_finish(&symbol_obstack);
466 lexer_token.literal = identify_string(string, size);
468 /* is it an octal number? */
470 lexer_token.type = T_FLOATINGPOINT;
471 } else if (string[0] == '0') {
472 lexer_token.type = T_INTEGER_OCTAL;
474 /* check for invalid octal digits */
475 for (size_t i= 0; i < size; ++i) {
478 errorf(&lexer_token.source_position,
479 "invalid digit '%c' in octal number", t);
482 lexer_token.type = T_INTEGER;
486 errorf(&lexer_token.source_position, "invalid number literal '%S'",
487 &lexer_token.literal);
490 parse_number_suffix();
494 * Returns the value of a digit.
495 * The only portable way to do it ...
497 static int digit_value(utf32 const digit)
523 internal_error("wrong character given");
528 * Parses an octal character sequence.
530 * @param first_digit the already read first digit
532 static utf32 parse_octal_sequence(utf32 const first_digit)
534 assert(is_octal_digit(first_digit));
535 utf32 value = digit_value(first_digit);
536 if (!is_octal_digit(c)) return value;
537 value = 8 * value + digit_value(c);
539 if (!is_octal_digit(c)) return value;
540 value = 8 * value + digit_value(c);
546 * Parses a hex character sequence.
548 static utf32 parse_hex_sequence(void)
551 while (isxdigit(c)) {
552 value = 16 * value + digit_value(c);
559 * Parse an escape sequence.
561 static utf32 parse_escape_sequence(void)
569 case '"': return '"';
570 case '\'': return '\'';
571 case '\\': return '\\';
572 case '?': return '\?';
573 case 'a': return '\a';
574 case 'b': return '\b';
575 case 'f': return '\f';
576 case 'n': return '\n';
577 case 'r': return '\r';
578 case 't': return '\t';
579 case 'v': return '\v';
581 return parse_hex_sequence();
590 return parse_octal_sequence(ec);
592 parse_error("reached end of file while parsing escape sequence");
594 /* \E is not documented, but handled, by GCC. It is acceptable according
595 * to §6.11.4, whereas \e is not. */
599 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
603 parse_error("universal character parsing not implemented yet");
608 /* §6.4.4.4:8 footnote 64 */
609 parse_error("unknown escape sequence");
614 * Concatenate two strings.
616 string_t concat_strings(const string_t *const s1, const string_t *const s2)
618 const size_t len1 = s1->size - 1;
619 const size_t len2 = s2->size - 1;
621 char *const concat = obstack_alloc(&symbol_obstack, len1 + len2 + 1);
622 memcpy(concat, s1->begin, len1);
623 memcpy(concat + len1, s2->begin, len2 + 1);
625 return identify_string(concat, len1 + len2 + 1);
628 string_t make_string(const char *string)
630 size_t len = strlen(string) + 1;
631 char *const space = obstack_alloc(&symbol_obstack, len);
632 memcpy(space, string, len);
634 return identify_string(space, len);
637 static void grow_symbol(utf32 const tc)
639 struct obstack *const o = &symbol_obstack;
641 obstack_1grow(o, tc);
642 } else if (tc < 0x800) {
643 obstack_1grow(o, 0xC0 | (tc >> 6));
644 obstack_1grow(o, 0x80 | (tc & 0x3F));
645 } else if (tc < 0x10000) {
646 obstack_1grow(o, 0xE0 | ( tc >> 12));
647 obstack_1grow(o, 0x80 | ((tc >> 6) & 0x3F));
648 obstack_1grow(o, 0x80 | ( tc & 0x3F));
650 obstack_1grow(o, 0xF0 | ( tc >> 18));
651 obstack_1grow(o, 0x80 | ((tc >> 12) & 0x3F));
652 obstack_1grow(o, 0x80 | ((tc >> 6) & 0x3F));
653 obstack_1grow(o, 0x80 | ( tc & 0x3F));
658 * Parse a string literal and set lexer_token.
660 static void parse_string_literal(void)
667 utf32 const tc = parse_escape_sequence();
669 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
671 obstack_1grow(&symbol_obstack, tc);
676 errorf(&lexer_token.source_position, "string has no end");
677 lexer_token.type = T_ERROR;
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.type = T_STRING_LITERAL;
702 lexer_token.literal = 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();
721 parse_error("newline while parsing character constant");
727 goto end_of_wide_char_constant;
730 errorf(&lexer_token.source_position, "EOF while parsing character constant");
731 lexer_token.type = T_ERROR;
742 end_of_wide_char_constant:;
743 obstack_1grow(&symbol_obstack, '\0');
744 size_t size = (size_t) obstack_object_size(&symbol_obstack) - 1;
745 char *string = obstack_finish(&symbol_obstack);
747 lexer_token.type = T_WIDE_CHARACTER_CONSTANT;
748 lexer_token.literal = identify_string(string, size);
751 errorf(&lexer_token.source_position, "empty character constant");
756 * Parse a wide string literal and set lexer_token.
758 static void parse_wide_string_literal(void)
760 parse_string_literal();
761 if (lexer_token.type == T_STRING_LITERAL)
762 lexer_token.type = T_WIDE_STRING_LITERAL;
766 * Parse a character constant and set lexer_token.
768 static void parse_character_constant(void)
775 utf32 const tc = parse_escape_sequence();
777 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
779 obstack_1grow(&symbol_obstack, tc);
784 parse_error("newline while parsing character constant");
790 goto end_of_char_constant;
793 errorf(&lexer_token.source_position, "EOF while parsing character constant");
794 lexer_token.type = 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.type = T_CHARACTER_CONSTANT;
812 lexer_token.literal = identify_string(string, size);
815 errorf(&lexer_token.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.source_position, "at end of file while looking for comment end");
856 * Skip a single line comment.
858 static void skip_line_comment(void)
871 if (c == '\n' || c == '\r') {
872 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
884 /** The current preprocessor token. */
885 static token_t pp_token;
888 * Read the next preprocessor token.
890 static inline void next_pp_token(void)
892 lexer_next_preprocessing_token();
893 pp_token = lexer_token;
897 * Eat all preprocessor tokens until newline.
899 static void eat_until_newline(void)
901 while (pp_token.type != '\n' && pp_token.type != T_EOF) {
907 * Handle the define directive.
909 static void define_directive(void)
911 lexer_next_preprocessing_token();
912 if (lexer_token.type != T_IDENTIFIER) {
913 parse_error("expected identifier after #define\n");
919 * Handle the ifdef directive.
921 static void ifdef_directive(int is_ifndef)
924 lexer_next_preprocessing_token();
925 //expect_identifier();
930 * Handle the endif directive.
932 static void endif_directive(void)
938 * Parse the line directive.
940 static void parse_line_directive(void)
942 if (pp_token.type != T_INTEGER) {
943 parse_error("expected integer");
945 /* use offset -1 as this is about the next line */
946 lexer_pos.lineno = atoi(pp_token.literal.begin) - 1;
949 if (pp_token.type == T_STRING_LITERAL) {
950 lexer_pos.input_name = pp_token.literal.begin;
960 typedef enum stdc_pragma_kind_t {
964 STDC_CX_LIMITED_RANGE
965 } stdc_pragma_kind_t;
968 * STDC pragma values.
970 typedef enum stdc_pragma_value_kind_t {
975 } stdc_pragma_value_kind_t;
978 * Parse a pragma directive.
980 static void parse_pragma(void)
982 bool unknown_pragma = true;
985 if (pp_token.symbol->pp_ID == TP_STDC) {
986 stdc_pragma_kind_t kind = STDC_UNKNOWN;
991 switch (pp_token.symbol->pp_ID) {
993 kind = STDC_FP_CONTRACT;
996 kind = STDC_FENV_ACCESS;
998 case TP_CX_LIMITED_RANGE:
999 kind = STDC_CX_LIMITED_RANGE;
1004 if (kind != STDC_UNKNOWN) {
1005 stdc_pragma_value_kind_t value = STDC_VALUE_UNKNOWN;
1007 switch (pp_token.symbol->pp_ID) {
1009 value = STDC_VALUE_ON;
1012 value = STDC_VALUE_OFF;
1015 value = STDC_VALUE_DEFAULT;
1020 if (value != STDC_VALUE_UNKNOWN) {
1021 unknown_pragma = false;
1023 errorf(&pp_token.source_position, "bad STDC pragma argument");
1028 unknown_pragma = true;
1030 eat_until_newline();
1031 if (unknown_pragma) {
1032 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.source_position, "encountered unknown #pragma");
1037 * Parse a preprocessor non-null directive.
1039 static void parse_preprocessor_identifier(void)
1041 assert(pp_token.type == T_IDENTIFIER);
1042 symbol_t *symbol = pp_token.symbol;
1044 switch (symbol->pp_ID) {
1046 printf("include - enable header name parsing!\n");
1062 parse_line_directive();
1069 /* TODO; output the rest of the line */
1070 parse_error("#error directive: ");
1079 * Parse a preprocessor directive.
1081 static void parse_preprocessor_directive(void)
1085 switch (pp_token.type) {
1087 parse_preprocessor_identifier();
1090 parse_line_directive();
1093 /* NULL directive, see §6.10.7 */
1096 parse_error("invalid preprocessor directive");
1097 eat_until_newline();
1102 #define MAYBE_PROLOG \
1107 #define MAYBE(ch, set_type) \
1110 lexer_token.type = set_type; \
1113 /* must use this as last thing */
1114 #define MAYBE_MODE(ch, set_type, mode) \
1116 if (c_mode & mode) { \
1118 lexer_token.type = set_type; \
1123 #define ELSE_CODE(code) \
1128 } /* end of while (true) */ \
1130 #define ELSE(set_type) \
1132 lexer_token.type = set_type; \
1135 void lexer_next_preprocessing_token(void)
1138 lexer_token.source_position = lexer_pos;
1147 lexer_token.type = '\n';
1153 /* might be a wide string ( L"string" ) */
1154 if (lexer_token.symbol == symbol_L) {
1156 case '"': parse_wide_string_literal(); break;
1157 case '\'': parse_wide_character_constant(); break;
1167 parse_string_literal();
1171 parse_character_constant();
1184 MAYBE('.', T_DOTDOTDOT)
1188 lexer_token.type = '.';
1193 MAYBE('&', T_ANDAND)
1194 MAYBE('=', T_ANDEQUAL)
1198 MAYBE('=', T_ASTERISKEQUAL)
1202 MAYBE('+', T_PLUSPLUS)
1203 MAYBE('=', T_PLUSEQUAL)
1207 MAYBE('>', T_MINUSGREATER)
1208 MAYBE('-', T_MINUSMINUS)
1209 MAYBE('=', T_MINUSEQUAL)
1213 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1217 MAYBE('=', T_SLASHEQUAL)
1220 skip_multiline_comment();
1221 lexer_next_preprocessing_token();
1225 skip_line_comment();
1226 lexer_next_preprocessing_token();
1232 MAYBE('=', T_PERCENTEQUAL)
1237 MAYBE(':', T_HASHHASH)
1241 lexer_token.type = '#';
1249 MAYBE('=', T_LESSEQUAL)
1252 MAYBE('=', T_LESSLESSEQUAL)
1257 MAYBE('=', T_GREATEREQUAL)
1260 MAYBE('=', T_GREATERGREATEREQUAL)
1261 ELSE(T_GREATERGREATER)
1265 MAYBE('=', T_CARETEQUAL)
1269 MAYBE('=', T_PIPEEQUAL)
1270 MAYBE('|', T_PIPEPIPE)
1275 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1279 MAYBE('=', T_EQUALEQUAL)
1283 MAYBE('#', T_HASHHASH)
1297 lexer_token.type = c;
1302 lexer_token.type = T_EOF;
1307 errorf(&lexer_pos, "unknown character '%c' found", c);
1309 lexer_token.type = T_ERROR;
1315 void lexer_next_token(void)
1317 lexer_next_preprocessing_token();
1319 while (lexer_token.type == '\n') {
1321 lexer_next_preprocessing_token();
1324 if (lexer_token.type == '#') {
1325 parse_preprocessor_directive();
1330 void init_lexer(void)
1332 strset_init(&stringset);
1333 symbol_L = symbol_table_insert("L");
1336 static void input_error(unsigned delta_lines, unsigned delta_cols,
1337 const char *message)
1339 lexer_pos.lineno += delta_lines;
1340 lexer_pos.colno += delta_cols;
1341 errorf(&lexer_pos, "%s", message);
1344 void select_input_encoding(char const* new_encoding)
1346 if (encoding != NULL)
1348 encoding = xstrdup(new_encoding);
1351 void lexer_open_stream(FILE *stream, const char *input_name)
1353 if (input != NULL) {
1358 lexer_pos.lineno = 0;
1359 lexer_pos.colno = 0;
1360 lexer_pos.input_name = input_name;
1362 set_input_error_callback(input_error);
1363 input = input_from_stream(stream, encoding);
1367 /* place a virtual \n at the beginning so the lexer knows that we're
1368 * at the beginning of a line */
1372 void exit_lexer(void)
1374 if (input != NULL) {
1378 strset_destroy(&stringset);
1381 static __attribute__((unused))
1382 void dbg_pos(const source_position_t source_position)
1384 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1385 source_position.lineno, source_position.colno);