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);
645 * Parse a string literal and set lexer_token.
647 static void parse_string_literal(string_encoding_t const enc)
654 utf32 const tc = parse_escape_sequence();
656 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
658 obstack_1grow(&symbol_obstack, tc);
663 errorf(&lexer_token.base.source_position, "string has no end");
671 obstack_grow_symbol(&symbol_obstack, c);
679 /* TODO: concatenate multiple strings separated by whitespace... */
681 /* add finishing 0 to the string */
682 obstack_1grow(&symbol_obstack, '\0');
683 const size_t size = (size_t)obstack_object_size(&symbol_obstack);
684 char *string = obstack_finish(&symbol_obstack);
686 lexer_token.kind = T_STRING_LITERAL;
687 lexer_token.string.encoding = enc;
688 lexer_token.string.string = identify_string(string, size);
692 * Parse a character constant and set lexer_token.
694 static void parse_character_constant(string_encoding_t const enc)
701 utf32 const tc = parse_escape_sequence();
702 if (enc == STRING_ENCODING_CHAR) {
704 warningf(WARN_OTHER, &lexer_pos, "escape sequence out of range");
706 obstack_1grow(&symbol_obstack, tc);
708 obstack_grow_symbol(&symbol_obstack, tc);
714 parse_error("newline while parsing character constant");
720 goto end_of_char_constant;
723 errorf(&lexer_token.base.source_position, "EOF while parsing character constant");
724 goto end_of_char_constant;
727 obstack_grow_symbol(&symbol_obstack, c);
734 end_of_char_constant:;
735 obstack_1grow(&symbol_obstack, '\0');
736 const size_t size = (size_t)obstack_object_size(&symbol_obstack)-1;
737 char *const string = obstack_finish(&symbol_obstack);
739 lexer_token.kind = T_CHARACTER_CONSTANT;
740 lexer_token.string.encoding = enc;
741 lexer_token.string.string = identify_string(string, size);
744 errorf(&lexer_token.base.source_position, "empty character constant");
749 * Skip a multiline comment.
751 static void skip_multiline_comment(void)
758 /* nested comment, warn here */
759 warningf(WARN_COMMENT, &lexer_pos, "'/*' within comment");
770 MATCH_NEWLINE(break;)
773 errorf(&lexer_token.base.source_position,
774 "at end of file while looking for comment end");
786 * Skip a single line comment.
788 static void skip_line_comment(void)
801 if (c == '\n' || c == '\r') {
802 warningf(WARN_COMMENT, &lexer_pos, "multi-line comment");
814 /** The current preprocessor token. */
815 static token_t pp_token;
818 * Read the next preprocessor token.
820 static inline void next_pp_token(void)
822 lexer_next_preprocessing_token();
823 pp_token = lexer_token;
827 * Eat all preprocessor tokens until newline.
829 static void eat_until_newline(void)
831 while (pp_token.kind != '\n' && pp_token.kind != T_EOF) {
837 * Parse the line directive.
839 static void parse_line_directive(void)
841 if (pp_token.kind != T_INTEGER) {
842 parse_error("expected integer");
844 /* use offset -1 as this is about the next line */
845 lexer_pos.lineno = atoi(pp_token.number.number.begin) - 1;
848 if (pp_token.kind == T_STRING_LITERAL && pp_token.string.encoding == STRING_ENCODING_CHAR) {
849 lexer_pos.input_name = pp_token.string.string.begin;
850 lexer_pos.is_system_header = false;
853 /* attempt to parse numeric flags as outputted by gcc preprocessor */
854 while (pp_token.kind == T_INTEGER) {
856 * 1 - indicates start of a new file
857 * 2 - indicates return from a file
858 * 3 - indicates system header
859 * 4 - indicates implicit extern "C" in C++ mode
861 * currently we're only interested in "3"
863 if (streq(pp_token.number.number.begin, "3")) {
864 lexer_pos.is_system_header = true;
876 typedef enum stdc_pragma_kind_t {
880 STDC_CX_LIMITED_RANGE
881 } stdc_pragma_kind_t;
884 * STDC pragma values.
886 typedef enum stdc_pragma_value_kind_t {
891 } stdc_pragma_value_kind_t;
894 * Parse a pragma directive.
896 static void parse_pragma(void)
899 if (pp_token.kind != T_IDENTIFIER) {
900 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
901 "expected identifier after #pragma");
906 stdc_pragma_kind_t kind = STDC_UNKNOWN;
907 if (pp_token.base.symbol->pp_ID == TP_STDC && c_mode & _C99) {
911 switch (pp_token.base.symbol->pp_ID) {
912 case TP_FP_CONTRACT: kind = STDC_FP_CONTRACT; break;
913 case TP_FENV_ACCESS: kind = STDC_FENV_ACCESS; break;
914 case TP_CX_LIMITED_RANGE: kind = STDC_CX_LIMITED_RANGE; break;
917 if (kind != STDC_UNKNOWN) {
919 stdc_pragma_value_kind_t value;
920 switch (pp_token.base.symbol->pp_ID) {
921 case TP_ON: value = STDC_VALUE_ON; break;
922 case TP_OFF: value = STDC_VALUE_OFF; break;
923 case TP_DEFAULT: value = STDC_VALUE_DEFAULT; break;
924 default: value = STDC_VALUE_UNKNOWN; break;
926 if (value == STDC_VALUE_UNKNOWN) {
928 errorf(&pp_token.base.source_position, "bad STDC pragma argument");
933 if (kind == STDC_UNKNOWN) {
934 warningf(WARN_UNKNOWN_PRAGMAS, &pp_token.base.source_position,
935 "encountered unknown #pragma");
940 * Parse a preprocessor non-null directive.
942 static void parse_preprocessor_identifier(void)
944 assert(pp_token.kind == T_IDENTIFIER);
945 switch (pp_token.base.symbol->pp_ID) {
948 parse_line_directive();
954 /* TODO; output the rest of the line */
955 parse_error("#error directive");
961 * Parse a preprocessor directive.
963 static void parse_preprocessor_directive(void)
967 switch (pp_token.kind) {
969 parse_preprocessor_identifier();
972 parse_line_directive();
975 /* NULL directive, see §6.10.7 */
978 parse_error("invalid preprocessor directive");
984 #define MAYBE_PROLOG \
989 #define MAYBE(ch, set_type) \
992 lexer_token.kind = set_type; \
995 /* must use this as last thing */
996 #define MAYBE_MODE(ch, set_type, mode) \
998 if (c_mode & mode) { \
1000 lexer_token.kind = set_type; \
1005 #define ELSE_CODE(code) \
1010 } /* end of while (true) */ \
1012 #define ELSE(set_type) \
1014 lexer_token.kind = set_type; \
1017 void lexer_next_preprocessing_token(void)
1020 lexer_token.base.source_position = lexer_pos;
1021 lexer_token.base.symbol = NULL;
1030 lexer_token.kind = '\n';
1036 /* might be a wide string ( L"string" ) */
1037 string_encoding_t const enc = STRING_ENCODING_WIDE;
1038 if (lexer_token.base.symbol == symbol_L) {
1040 case '"': parse_string_literal(enc); break;
1041 case '\'': parse_character_constant(enc); break;
1052 parse_string_literal(STRING_ENCODING_CHAR);
1056 parse_character_constant(STRING_ENCODING_CHAR);
1069 MAYBE('.', T_DOTDOTDOT)
1073 lexer_token.kind = '.';
1078 MAYBE('&', T_ANDAND)
1079 MAYBE('=', T_ANDEQUAL)
1083 MAYBE('=', T_ASTERISKEQUAL)
1087 MAYBE('+', T_PLUSPLUS)
1088 MAYBE('=', T_PLUSEQUAL)
1092 MAYBE('>', T_MINUSGREATER)
1093 MAYBE('-', T_MINUSMINUS)
1094 MAYBE('=', T_MINUSEQUAL)
1098 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
1102 MAYBE('=', T_SLASHEQUAL)
1105 skip_multiline_comment();
1106 lexer_next_preprocessing_token();
1110 skip_line_comment();
1111 lexer_next_preprocessing_token();
1117 MAYBE('=', T_PERCENTEQUAL)
1122 MAYBE(':', T_HASHHASH)
1126 lexer_token.kind = '#';
1134 MAYBE('=', T_LESSEQUAL)
1137 MAYBE('=', T_LESSLESSEQUAL)
1142 MAYBE('=', T_GREATEREQUAL)
1145 MAYBE('=', T_GREATERGREATEREQUAL)
1146 ELSE(T_GREATERGREATER)
1150 MAYBE('=', T_CARETEQUAL)
1154 MAYBE('=', T_PIPEEQUAL)
1155 MAYBE('|', T_PIPEPIPE)
1160 MAYBE_MODE(':', T_COLONCOLON, _CXX)
1164 MAYBE('=', T_EQUALEQUAL)
1168 MAYBE('#', T_HASHHASH)
1182 lexer_token.kind = c;
1187 lexer_token.kind = T_EOF;
1192 errorf(&lexer_pos, "unknown character '%c' found", c);
1199 void lexer_next_token(void)
1201 lexer_next_preprocessing_token();
1203 while (lexer_token.kind == '\n') {
1205 lexer_next_preprocessing_token();
1208 if (lexer_token.kind == '#') {
1209 parse_preprocessor_directive();
1214 void init_lexer(void)
1216 strset_init(&stringset);
1217 symbol_L = symbol_table_insert("L");
1220 static void input_error(unsigned delta_lines, unsigned delta_cols,
1221 const char *message)
1223 lexer_pos.lineno += delta_lines;
1224 lexer_pos.colno += delta_cols;
1225 errorf(&lexer_pos, "%s", message);
1228 void lexer_switch_input(input_t *new_input, const char *input_name)
1230 lexer_pos.lineno = 0;
1231 lexer_pos.colno = 0;
1232 lexer_pos.input_name = input_name;
1234 set_input_error_callback(input_error);
1239 /* place a virtual \n at the beginning so the lexer knows that we're
1240 * at the beginning of a line */
1244 void exit_lexer(void)
1246 strset_destroy(&stringset);
1249 static __attribute__((unused))
1250 void dbg_pos(const source_position_t source_position)
1252 fprintf(stdout, "%s:%u:%u\n", source_position.input_name,
1253 source_position.lineno, (unsigned)source_position.colno);