12 #include "adt/error.h"
13 #include "adt/strutil.h"
14 #include "adt/strset.h"
15 #include "lang_features.h"
16 #include "diagnostic.h"
17 #include "string_rep.h"
21 #define INCLUDE_LIMIT 199 /* 199 is for gcc "compatibility" */
23 struct pp_argument_t {
28 struct pp_definition_t {
30 source_position_t source_position;
31 pp_definition_t *parent_expansion;
34 bool is_expanding : 1;
35 bool has_parameters : 1;
45 typedef struct pp_conditional_t pp_conditional_t;
46 struct pp_conditional_t {
47 source_position_t source_position;
50 bool skip; /**< conditional in skip mode (then+else gets skipped) */
51 pp_conditional_t *parent;
54 typedef struct pp_input_t pp_input_t;
59 utf32 buf[1024+MAX_PUTBACK];
62 source_position_t position;
67 /** additional info about the current token */
68 typedef struct add_token_info_t {
69 /** whitespace from beginning of line to the token */
71 /** there has been any whitespace before the token */
73 /** the token is at the beginning of the line */
77 typedef struct searchpath_entry_t searchpath_entry_t;
78 struct searchpath_entry_t {
80 searchpath_entry_t *next;
83 static pp_input_t input;
85 static pp_input_t *input_stack;
86 static unsigned n_inputs;
87 static struct obstack input_obstack;
89 static pp_conditional_t *conditional_stack;
91 static token_t pp_token;
92 static bool resolve_escape_sequences = false;
93 static bool ignore_unknown_chars = true;
94 static bool skip_mode;
96 static struct obstack pp_obstack;
97 static struct obstack config_obstack;
98 static const char *printed_input_name = NULL;
99 static source_position_t expansion_pos;
100 static pp_definition_t *current_expansion = NULL;
101 static strset_t stringset;
102 static token_kind_t last_token;
104 static searchpath_entry_t *searchpath;
106 static add_token_info_t info;
108 static inline void next_char(void);
109 static void next_preprocessing_token(void);
110 static void print_line_directive(const source_position_t *pos, const char *add);
112 static void switch_input(FILE *file, const char *filename)
115 input.input = input_from_stream(file, NULL);
118 input.output_line = 0;
119 input.position.input_name = filename;
120 input.position.lineno = 1;
122 /* indicate that we're at a new input */
123 print_line_directive(&input.position, input_stack != NULL ? "1" : NULL);
125 /* place a virtual '\n' so we realize we're at line begin */
126 input.position.lineno = 0;
128 next_preprocessing_token();
131 static void close_input(void)
133 input_free(input.input);
134 assert(input.file != NULL);
144 static void push_input(void)
146 pp_input_t *saved_input
147 = obstack_alloc(&input_obstack, sizeof(*saved_input));
149 memcpy(saved_input, &input, sizeof(*saved_input));
151 /* adjust buffer positions */
152 if (input.bufpos != NULL)
153 saved_input->bufpos = saved_input->buf + (input.bufpos - input.buf);
154 if (input.bufend != NULL)
155 saved_input->bufend = saved_input->buf + (input.bufend - input.buf);
157 saved_input->parent = input_stack;
158 input_stack = saved_input;
162 static void pop_restore_input(void)
164 assert(n_inputs > 0);
165 assert(input_stack != NULL);
167 pp_input_t *saved_input = input_stack;
169 memcpy(&input, saved_input, sizeof(input));
172 /* adjust buffer positions */
173 if (saved_input->bufpos != NULL)
174 input.bufpos = input.buf + (saved_input->bufpos - saved_input->buf);
175 if (saved_input->bufend != NULL)
176 input.bufend = input.buf + (saved_input->bufend - saved_input->buf);
178 input_stack = saved_input->parent;
179 obstack_free(&input_obstack, saved_input);
184 * Prints a parse error message at the current token.
186 * @param msg the error message
188 static void parse_error(const char *msg)
190 errorf(&pp_token.base.source_position, "%s", msg);
193 static inline void next_real_char(void)
195 assert(input.bufpos <= input.bufend);
196 if (input.bufpos >= input.bufend) {
197 size_t const n = decode(input.input, input.buf + MAX_PUTBACK, lengthof(input.buf) - MAX_PUTBACK);
202 input.bufpos = input.buf + MAX_PUTBACK;
203 input.bufend = input.bufpos + n;
205 input.c = *input.bufpos++;
206 ++input.position.colno;
210 * Put a character back into the buffer.
212 * @param pc the character to put back
214 static inline void put_back(utf32 const pc)
216 assert(input.bufpos > input.buf);
217 *(--input.bufpos - input.buf + input.buf) = (char) pc;
218 --input.position.colno;
224 if (input.c == '\n') { \
228 info.whitespace = 0; \
229 ++input.position.lineno; \
230 input.position.colno = 1; \
232 newline // Let it look like an ordinary case label.
234 #define eat(c_type) (assert(input.c == c_type), next_char())
236 static void maybe_concat_lines(void)
253 * Set c to the next input character, ie.
254 * after expanding trigraphs.
256 static inline void next_char(void)
260 /* filter trigraphs and concatenated lines */
261 if (UNLIKELY(input.c == '\\')) {
262 maybe_concat_lines();
263 goto end_of_next_char;
266 if (LIKELY(input.c != '?'))
267 goto end_of_next_char;
270 if (LIKELY(input.c != '?')) {
273 goto end_of_next_char;
278 case '=': input.c = '#'; break;
279 case '(': input.c = '['; break;
280 case '/': input.c = '\\'; maybe_concat_lines(); break;
281 case ')': input.c = ']'; break;
282 case '\'': input.c = '^'; break;
283 case '<': input.c = '{'; break;
284 case '!': input.c = '|'; break;
285 case '>': input.c = '}'; break;
286 case '-': input.c = '~'; break;
296 printf("nchar '%c'\n", input.c);
303 * Returns true if the given char is a octal digit.
305 * @param char the character to check
307 static inline bool is_octal_digit(int chr)
325 * Returns the value of a digit.
326 * The only portable way to do it ...
328 static int digit_value(int digit)
354 panic("wrong character given");
359 * Parses an octal character sequence.
361 * @param first_digit the already read first digit
363 static utf32 parse_octal_sequence(const utf32 first_digit)
365 assert(is_octal_digit(first_digit));
366 utf32 value = digit_value(first_digit);
367 if (!is_octal_digit(input.c)) return value;
368 value = 8 * value + digit_value(input.c);
370 if (!is_octal_digit(input.c)) return value;
371 value = 8 * value + digit_value(input.c);
378 * Parses a hex character sequence.
380 static utf32 parse_hex_sequence(void)
383 while (isxdigit(input.c)) {
384 value = 16 * value + digit_value(input.c);
391 * Parse an escape sequence.
393 static utf32 parse_escape_sequence(void)
397 utf32 const ec = input.c;
401 case '"': return '"';
402 case '\'': return '\'';
403 case '\\': return '\\';
404 case '?': return '\?';
405 case 'a': return '\a';
406 case 'b': return '\b';
407 case 'f': return '\f';
408 case 'n': return '\n';
409 case 'r': return '\r';
410 case 't': return '\t';
411 case 'v': return '\v';
413 return parse_hex_sequence();
422 return parse_octal_sequence(ec);
424 parse_error("reached end of file while parsing escape sequence");
426 /* \E is not documented, but handled, by GCC. It is acceptable according
427 * to §6.11.4, whereas \e is not. */
431 return 27; /* hopefully 27 is ALWAYS the code for ESCAPE */
435 parse_error("universal character parsing not implemented yet");
440 /* §6.4.4.4:8 footnote 64 */
441 parse_error("unknown escape sequence");
445 static const char *identify_string(char *string)
447 const char *result = strset_insert(&stringset, string);
448 if (result != string) {
449 obstack_free(&symbol_obstack, string);
454 static string_t sym_make_string(string_encoding_t const enc)
456 obstack_1grow(&symbol_obstack, '\0');
457 size_t const len = obstack_object_size(&symbol_obstack) - 1;
458 char *const string = obstack_finish(&symbol_obstack);
459 char const *const result = identify_string(string);
460 return (string_t){ result, len, enc };
463 static void parse_string(utf32 const delimiter, token_kind_t const kind,
464 string_encoding_t const enc,
465 char const *const context)
467 const unsigned start_linenr = input.position.lineno;
474 if (resolve_escape_sequences) {
475 utf32 const tc = parse_escape_sequence();
476 if (enc == STRING_ENCODING_CHAR) {
478 warningf(WARN_OTHER, &pp_token.base.source_position, "escape sequence out of range");
480 obstack_1grow(&symbol_obstack, tc);
482 obstack_grow_utf8(&symbol_obstack, tc);
485 obstack_1grow(&symbol_obstack, (char)input.c);
487 obstack_1grow(&symbol_obstack, (char)input.c);
494 errorf(&pp_token.base.source_position, "newline while parsing %s", context);
498 source_position_t source_position;
499 source_position.input_name = pp_token.base.source_position.input_name;
500 source_position.lineno = start_linenr;
501 errorf(&source_position, "EOF while parsing %s", context);
506 if (input.c == delimiter) {
510 obstack_grow_utf8(&symbol_obstack, input.c);
518 pp_token.kind = kind;
519 pp_token.literal.string = sym_make_string(enc);
522 static void parse_string_literal(string_encoding_t const enc)
524 parse_string('"', T_STRING_LITERAL, enc, "string literal");
527 static void parse_character_constant(string_encoding_t const enc)
529 parse_string('\'', T_CHARACTER_CONSTANT, enc, "character constant");
530 if (pp_token.literal.string.size == 0) {
531 parse_error("empty character constant");
535 #define SYMBOL_CASES_WITHOUT_E_P \
586 #define SYMBOL_CASES \
587 SYMBOL_CASES_WITHOUT_E_P: \
593 #define DIGIT_CASES \
606 * returns next final token from a preprocessor macro expansion
608 static void expand_next(void)
610 assert(current_expansion != NULL);
612 pp_definition_t *definition = current_expansion;
615 if (definition->list_len == 0
616 || definition->expand_pos >= definition->list_len) {
617 /* we're finished with the current macro, move up 1 level in the
619 pp_definition_t *parent = definition->parent_expansion;
620 definition->parent_expansion = NULL;
621 definition->is_expanding = false;
623 /* it was the outermost expansion, parse normal pptoken */
624 if (parent == NULL) {
625 current_expansion = NULL;
626 next_preprocessing_token();
630 current_expansion = definition;
633 pp_token = definition->token_list[definition->expand_pos];
634 pp_token.base.source_position = expansion_pos;
635 ++definition->expand_pos;
637 if (pp_token.kind != T_IDENTIFIER)
640 /* if it was an identifier then we might need to expand again */
641 pp_definition_t *const symbol_definition = pp_token.base.symbol->pp_definition;
642 if (symbol_definition != NULL && !symbol_definition->is_expanding) {
643 symbol_definition->parent_expansion = definition;
644 symbol_definition->expand_pos = 0;
645 symbol_definition->is_expanding = true;
646 definition = symbol_definition;
647 current_expansion = definition;
652 static void skip_line_comment(void)
670 static void skip_multiline_comment(void)
672 unsigned start_linenr = input.position.lineno;
677 if (input.c == '*') {
678 /* TODO: nested comment, warn here */
683 if (input.c == '/') {
684 if (input.position.lineno != input.output_line)
685 info.whitespace = input.position.colno;
695 source_position_t source_position;
696 source_position.input_name = pp_token.base.source_position.input_name;
697 source_position.lineno = start_linenr;
698 errorf(&source_position, "at end of file while looking for comment end");
709 static void skip_whitespace(void)
719 info.at_line_begin = true;
724 if (input.c == '/') {
728 } else if (input.c == '*') {
730 skip_multiline_comment();
743 static inline void eat_pp(pp_token_kind_t const kind)
745 assert(pp_token.base.symbol->pp_ID == kind);
747 next_preprocessing_token();
750 static inline void eat_token(token_kind_t const kind)
752 assert(pp_token.kind == kind);
754 next_preprocessing_token();
757 static void parse_symbol(void)
759 obstack_1grow(&symbol_obstack, (char) input.c);
766 obstack_1grow(&symbol_obstack, (char) input.c);
776 obstack_1grow(&symbol_obstack, '\0');
777 char *string = obstack_finish(&symbol_obstack);
779 /* might be a wide string or character constant ( L"string"/L'c' ) */
780 if (input.c == '"' && string[0] == 'L' && string[1] == '\0') {
781 obstack_free(&symbol_obstack, string);
782 parse_string_literal(STRING_ENCODING_WIDE);
784 } else if (input.c == '\'' && string[0] == 'L' && string[1] == '\0') {
785 obstack_free(&symbol_obstack, string);
786 parse_character_constant(STRING_ENCODING_WIDE);
790 symbol_t *symbol = symbol_table_insert(string);
792 pp_token.kind = symbol->ID;
793 pp_token.base.symbol = symbol;
795 /* we can free the memory from symbol obstack if we already had an entry in
796 * the symbol table */
797 if (symbol->string != string) {
798 obstack_free(&symbol_obstack, string);
802 static void parse_number(void)
804 obstack_1grow(&symbol_obstack, (char) input.c);
811 case SYMBOL_CASES_WITHOUT_E_P:
812 obstack_1grow(&symbol_obstack, (char) input.c);
820 obstack_1grow(&symbol_obstack, (char) input.c);
822 if (input.c == '+' || input.c == '-') {
823 obstack_1grow(&symbol_obstack, (char) input.c);
834 pp_token.kind = T_NUMBER;
835 pp_token.literal.string = sym_make_string(STRING_ENCODING_CHAR);
839 #define MAYBE_PROLOG \
844 #define MAYBE(ch, set_type) \
847 pp_token.kind = set_type; \
850 #define ELSE_CODE(code) \
857 #define ELSE(set_type) \
859 pp_token.kind = set_type; \
862 static void next_preprocessing_token(void)
864 if (current_expansion != NULL) {
869 info.at_line_begin = false;
870 info.had_whitespace = false;
872 pp_token.base.source_position = input.position;
873 pp_token.base.symbol = NULL;
879 info.had_whitespace = true;
884 info.at_line_begin = true;
885 info.had_whitespace = true;
897 parse_string_literal(STRING_ENCODING_CHAR);
901 parse_character_constant(STRING_ENCODING_CHAR);
923 MAYBE('.', T_DOTDOTDOT)
933 MAYBE('=', T_ANDEQUAL)
937 MAYBE('=', T_ASTERISKEQUAL)
941 MAYBE('+', T_PLUSPLUS)
942 MAYBE('=', T_PLUSEQUAL)
946 MAYBE('>', T_MINUSGREATER)
947 MAYBE('-', T_MINUSMINUS)
948 MAYBE('=', T_MINUSEQUAL)
952 MAYBE('=', T_EXCLAMATIONMARKEQUAL)
956 MAYBE('=', T_SLASHEQUAL)
959 info.had_whitespace = true;
960 skip_multiline_comment();
964 info.had_whitespace = true;
971 MAYBE('=', T_PERCENTEQUAL)
976 MAYBE(':', T_HASHHASH)
988 MAYBE('=', T_LESSEQUAL)
991 MAYBE('=', T_LESSLESSEQUAL)
996 MAYBE('=', T_GREATEREQUAL)
999 MAYBE('=', T_GREATERGREATEREQUAL)
1000 ELSE(T_GREATERGREATER)
1004 MAYBE('=', T_CARETEQUAL)
1008 MAYBE('=', T_PIPEEQUAL)
1009 MAYBE('|', T_PIPEPIPE)
1017 MAYBE('=', T_EQUALEQUAL)
1021 MAYBE('#', T_HASHHASH)
1023 pp_token.kind = '#';
1036 pp_token.kind = input.c;
1041 if (input_stack != NULL) {
1043 pop_restore_input();
1045 print_line_directive(&input.position, "2");
1048 pp_token.base.source_position.lineno++;
1049 info.at_line_begin = true;
1050 pp_token.kind = T_EOF;
1056 if (!ignore_unknown_chars) {
1057 errorf(&pp_token.base.source_position,
1058 "unknown character '%lc' found\n", input.c);
1061 pp_token.kind = input.c;
1067 static void print_quoted_string(const char *const string)
1070 for (const char *c = string; *c != 0; ++c) {
1072 case '"': fputs("\\\"", out); break;
1073 case '\\': fputs("\\\\", out); break;
1074 case '\a': fputs("\\a", out); break;
1075 case '\b': fputs("\\b", out); break;
1076 case '\f': fputs("\\f", out); break;
1077 case '\n': fputs("\\n", out); break;
1078 case '\r': fputs("\\r", out); break;
1079 case '\t': fputs("\\t", out); break;
1080 case '\v': fputs("\\v", out); break;
1081 case '\?': fputs("\\?", out); break;
1084 fprintf(out, "\\%03o", (unsigned)*c);
1094 static void print_line_directive(const source_position_t *pos, const char *add)
1096 fprintf(out, "# %u ", pos->lineno);
1097 print_quoted_string(pos->input_name);
1103 printed_input_name = pos->input_name;
1104 input.output_line = pos->lineno-1;
1107 static bool emit_newlines(void)
1109 unsigned delta = pp_token.base.source_position.lineno - input.output_line;
1115 print_line_directive(&pp_token.base.source_position, NULL);
1118 for (unsigned i = 0; i < delta; ++i) {
1122 input.output_line = pp_token.base.source_position.lineno;
1124 for (unsigned i = 0; i < info.whitespace; ++i)
1130 static void emit_pp_token(void)
1135 if (!emit_newlines() &&
1136 (info.had_whitespace || tokens_would_paste(last_token, pp_token.kind)))
1139 switch (pp_token.kind) {
1141 fputs(pp_token.literal.string.begin, out);
1144 case T_STRING_LITERAL:
1145 fputs(get_string_encoding_prefix(pp_token.literal.string.encoding), out);
1147 fputs(pp_token.literal.string.begin, out);
1151 case T_CHARACTER_CONSTANT:
1152 fputs(get_string_encoding_prefix(pp_token.literal.string.encoding), out);
1154 fputs(pp_token.literal.string.begin, out);
1159 if (pp_token.base.symbol) {
1160 fputs(pp_token.base.symbol->string, out);
1162 print_token_kind(out, pp_token.kind);
1166 last_token = pp_token.kind;
1169 static void eat_pp_directive(void)
1171 while (!info.at_line_begin) {
1172 next_preprocessing_token();
1176 static bool strings_equal(const string_t *string1, const string_t *string2)
1178 size_t size = string1->size;
1179 if (size != string2->size)
1182 const char *c1 = string1->begin;
1183 const char *c2 = string2->begin;
1184 for (size_t i = 0; i < size; ++i, ++c1, ++c2) {
1191 static bool pp_tokens_equal(const token_t *token1, const token_t *token2)
1193 if (token1->kind != token2->kind)
1196 switch (token1->kind) {
1198 return token1->base.symbol == token2->base.symbol;
1201 case T_CHARACTER_CONSTANT:
1202 case T_STRING_LITERAL:
1203 return strings_equal(&token1->literal.string, &token2->literal.string);
1210 static bool pp_definitions_equal(const pp_definition_t *definition1,
1211 const pp_definition_t *definition2)
1213 if (definition1->list_len != definition2->list_len)
1216 size_t len = definition1->list_len;
1217 const token_t *t1 = definition1->token_list;
1218 const token_t *t2 = definition2->token_list;
1219 for (size_t i = 0; i < len; ++i, ++t1, ++t2) {
1220 if (!pp_tokens_equal(t1, t2))
1226 static void parse_define_directive(void)
1234 assert(obstack_object_size(&pp_obstack) == 0);
1236 if (pp_token.kind != T_IDENTIFIER || info.at_line_begin) {
1237 errorf(&pp_token.base.source_position,
1238 "expected identifier after #define, got %K", &pp_token);
1241 symbol_t *const symbol = pp_token.base.symbol;
1243 pp_definition_t *new_definition
1244 = obstack_alloc(&pp_obstack, sizeof(new_definition[0]));
1245 memset(new_definition, 0, sizeof(new_definition[0]));
1246 new_definition->source_position = input.position;
1248 /* this is probably the only place where spaces are significant in the
1249 * lexer (except for the fact that they separate tokens). #define b(x)
1250 * is something else than #define b (x) */
1251 if (input.c == '(') {
1252 eat_token(T_IDENTIFIER);
1256 switch (pp_token.kind) {
1258 new_definition->is_variadic = true;
1259 eat_token(T_DOTDOTDOT);
1260 if (pp_token.kind != ')') {
1261 errorf(&input.position,
1262 "'...' not at end of macro argument list");
1268 obstack_ptr_grow(&pp_obstack, pp_token.base.symbol);
1269 eat_token(T_IDENTIFIER);
1271 if (pp_token.kind == ',') {
1276 if (pp_token.kind != ')') {
1277 errorf(&pp_token.base.source_position,
1278 "expected ',' or ')' after identifier, got %K",
1286 goto finish_argument_list;
1289 errorf(&pp_token.base.source_position,
1290 "expected identifier, '...' or ')' in #define argument list, got %K",
1296 finish_argument_list:
1297 new_definition->has_parameters = true;
1298 new_definition->n_parameters
1299 = obstack_object_size(&pp_obstack) / sizeof(new_definition->parameters[0]);
1300 new_definition->parameters = obstack_finish(&pp_obstack);
1302 eat_token(T_IDENTIFIER);
1305 /* construct a new pp_definition on the obstack */
1306 assert(obstack_object_size(&pp_obstack) == 0);
1307 size_t list_len = 0;
1308 while (!info.at_line_begin) {
1309 obstack_grow(&pp_obstack, &pp_token, sizeof(pp_token));
1311 next_preprocessing_token();
1314 new_definition->list_len = list_len;
1315 new_definition->token_list = obstack_finish(&pp_obstack);
1317 pp_definition_t *old_definition = symbol->pp_definition;
1318 if (old_definition != NULL) {
1319 if (!pp_definitions_equal(old_definition, new_definition)) {
1320 warningf(WARN_OTHER, &input.position, "multiple definition of macro '%Y' (first defined %P)", symbol, &old_definition->source_position);
1322 /* reuse the old definition */
1323 obstack_free(&pp_obstack, new_definition);
1324 new_definition = old_definition;
1328 symbol->pp_definition = new_definition;
1332 if (obstack_object_size(&pp_obstack) > 0) {
1333 char *ptr = obstack_finish(&pp_obstack);
1334 obstack_free(&pp_obstack, ptr);
1339 static void parse_undef_directive(void)
1347 if (pp_token.kind != T_IDENTIFIER) {
1348 errorf(&input.position,
1349 "expected identifier after #undef, got %K", &pp_token);
1354 pp_token.base.symbol->pp_definition = NULL;
1355 eat_token(T_IDENTIFIER);
1357 if (!info.at_line_begin) {
1358 warningf(WARN_OTHER, &input.position, "extra tokens at end of #undef directive");
1363 /** behind an #include we can have the special headername lexems.
1364 * They're only allowed behind an #include so they're not recognized
1365 * by the normal next_preprocessing_token. We handle them as a special
1367 static void parse_headername(void)
1369 const source_position_t start_position = input.position;
1370 string_t string = { NULL, 0, STRING_ENCODING_CHAR };
1371 assert(obstack_object_size(&symbol_obstack) == 0);
1373 if (info.at_line_begin) {
1374 parse_error("expected headername after #include");
1378 /* check wether we have a "... or <... headername */
1382 case '<': delimiter = '>'; goto parse_name;
1383 case '"': delimiter = '"'; goto parse_name;
1390 errorf(&pp_token.base.source_position, "header name without closing '%c'", (char)delimiter);
1394 if (input.c == delimiter) {
1396 goto finished_headername;
1398 obstack_1grow(&symbol_obstack, (char)input.c);
1404 /* we should never be here */
1408 /* TODO: do normal pp_token parsing and concatenate results */
1409 panic("pp_token concat include not implemented yet");
1412 finished_headername:
1413 string = sym_make_string(STRING_ENCODING_CHAR);
1416 pp_token.base.source_position = start_position;
1417 pp_token.kind = T_HEADERNAME;
1418 pp_token.literal.string = string;
1421 static bool do_include(bool system_include, const char *headername)
1423 size_t headername_len = strlen(headername);
1424 if (!system_include) {
1425 /* put dirname of current input on obstack */
1426 const char *filename = input.position.input_name;
1427 const char *last_slash = strrchr(filename, '/');
1428 if (last_slash != NULL) {
1429 size_t len = last_slash - filename;
1430 obstack_grow(&symbol_obstack, filename, len + 1);
1431 obstack_grow0(&symbol_obstack, headername, headername_len);
1432 char *complete_path = obstack_finish(&symbol_obstack);
1433 headername = identify_string(complete_path);
1436 FILE *file = fopen(headername, "r");
1438 switch_input(file, headername);
1443 assert(obstack_object_size(&symbol_obstack) == 0);
1444 /* check searchpath */
1445 for (searchpath_entry_t *entry = searchpath; entry != NULL;
1446 entry = entry->next) {
1447 const char *path = entry->path;
1448 size_t len = strlen(path);
1449 obstack_grow(&symbol_obstack, path, len);
1450 if (path[len-1] != '/')
1451 obstack_1grow(&symbol_obstack, '/');
1452 obstack_grow(&symbol_obstack, headername, headername_len+1);
1454 char *complete_path = obstack_finish(&symbol_obstack);
1455 FILE *file = fopen(complete_path, "r");
1457 const char *filename = identify_string(complete_path);
1458 switch_input(file, filename);
1461 obstack_free(&symbol_obstack, complete_path);
1468 /* read till next newline character, only for parse_include_directive(),
1469 * use eat_pp_directive() in all other cases */
1470 static void skip_till_newline(void)
1472 /* skip till newline */
1483 static bool parse_include_directive(void)
1490 /* don't eat the TP_include here!
1491 * we need an alternative parsing for the next token */
1493 bool system_include = input.c == '<';
1495 string_t headername = pp_token.literal.string;
1496 if (headername.begin == NULL) {
1502 if (!info.at_line_begin) {
1503 warningf(WARN_OTHER, &pp_token.base.source_position,
1504 "extra tokens at end of #include directive");
1505 skip_till_newline();
1508 if (n_inputs > INCLUDE_LIMIT) {
1509 errorf(&pp_token.base.source_position, "#include nested too deeply");
1511 next_preprocessing_token();
1518 bool res = do_include(system_include, pp_token.literal.string.begin);
1520 errorf(&pp_token.base.source_position, "failed including '%S': %s", &pp_token.literal, strerror(errno));
1521 pop_restore_input();
1528 static pp_conditional_t *push_conditional(void)
1530 pp_conditional_t *conditional
1531 = obstack_alloc(&pp_obstack, sizeof(*conditional));
1532 memset(conditional, 0, sizeof(*conditional));
1534 conditional->parent = conditional_stack;
1535 conditional_stack = conditional;
1540 static void pop_conditional(void)
1542 assert(conditional_stack != NULL);
1543 conditional_stack = conditional_stack->parent;
1546 static void check_unclosed_conditionals(void)
1548 while (conditional_stack != NULL) {
1549 pp_conditional_t *conditional = conditional_stack;
1551 if (conditional->in_else) {
1552 errorf(&conditional->source_position, "unterminated #else");
1554 errorf(&conditional->source_position, "unterminated condition");
1560 static void parse_ifdef_ifndef_directive(bool const is_ifdef)
1563 eat_pp(is_ifdef ? TP_ifdef : TP_ifndef);
1567 pp_conditional_t *conditional = push_conditional();
1568 conditional->source_position = pp_token.base.source_position;
1569 conditional->skip = true;
1573 if (pp_token.kind != T_IDENTIFIER || info.at_line_begin) {
1574 errorf(&pp_token.base.source_position,
1575 "expected identifier after #%s, got %K",
1576 is_ifdef ? "ifdef" : "ifndef", &pp_token);
1579 /* just take the true case in the hope to avoid further errors */
1582 /* evaluate wether we are in true or false case */
1583 condition = (bool)pp_token.base.symbol->pp_definition == is_ifdef;
1584 eat_token(T_IDENTIFIER);
1586 if (!info.at_line_begin) {
1587 errorf(&pp_token.base.source_position,
1588 "extra tokens at end of #%s",
1589 is_ifdef ? "ifdef" : "ifndef");
1594 pp_conditional_t *conditional = push_conditional();
1595 conditional->source_position = pp_token.base.source_position;
1596 conditional->condition = condition;
1603 static void parse_else_directive(void)
1607 if (!info.at_line_begin) {
1609 warningf(WARN_OTHER, &pp_token.base.source_position, "extra tokens at end of #else");
1614 pp_conditional_t *conditional = conditional_stack;
1615 if (conditional == NULL) {
1616 errorf(&pp_token.base.source_position, "#else without prior #if");
1620 if (conditional->in_else) {
1621 errorf(&pp_token.base.source_position,
1622 "#else after #else (condition started %P)",
1623 &conditional->source_position);
1628 conditional->in_else = true;
1629 if (!conditional->skip) {
1630 skip_mode = conditional->condition;
1632 conditional->source_position = pp_token.base.source_position;
1635 static void parse_endif_directive(void)
1639 if (!info.at_line_begin) {
1641 warningf(WARN_OTHER, &pp_token.base.source_position, "extra tokens at end of #endif");
1646 pp_conditional_t *conditional = conditional_stack;
1647 if (conditional == NULL) {
1648 errorf(&pp_token.base.source_position, "#endif without prior #if");
1652 if (!conditional->skip) {
1658 static void parse_preprocessing_directive(void)
1662 if (info.at_line_begin) {
1663 /* empty directive */
1667 if (pp_token.base.symbol) {
1668 switch (pp_token.base.symbol->pp_ID) {
1669 case TP_define: parse_define_directive(); break;
1670 case TP_else: parse_else_directive(); break;
1671 case TP_endif: parse_endif_directive(); break;
1672 case TP_ifdef: parse_ifdef_ifndef_directive(true); break;
1673 case TP_ifndef: parse_ifdef_ifndef_directive(false); break;
1674 case TP_include: parse_include_directive(); break;
1675 case TP_undef: parse_undef_directive(); break;
1681 errorf(&pp_token.base.source_position, "invalid preprocessing directive #%K", &pp_token);
1686 assert(info.at_line_begin);
1689 static void prepend_include_path(const char *path)
1691 searchpath_entry_t *entry = OALLOCZ(&config_obstack, searchpath_entry_t);
1693 entry->next = searchpath;
1697 static void setup_include_path(void)
1699 /* built-in paths */
1700 prepend_include_path("/usr/include");
1702 /* parse environment variable */
1703 const char *cpath = getenv("CPATH");
1704 if (cpath != NULL && *cpath != '\0') {
1705 const char *begin = cpath;
1709 while (*c != '\0' && *c != ':')
1712 size_t len = c-begin;
1714 /* for gcc compatibility (Matze: I would expect that
1715 * nothing happens for an empty entry...) */
1716 prepend_include_path(".");
1718 char *string = obstack_alloc(&config_obstack, len+1);
1719 memcpy(string, begin, len);
1722 prepend_include_path(string);
1729 } while(*c != '\0');
1733 int pptest_main(int argc, char **argv);
1734 int pptest_main(int argc, char **argv)
1736 init_symbol_table();
1739 obstack_init(&config_obstack);
1740 obstack_init(&pp_obstack);
1741 obstack_init(&input_obstack);
1742 strset_init(&stringset);
1744 setup_include_path();
1746 /* simplistic commandline parser */
1747 const char *filename = NULL;
1748 const char *output = NULL;
1749 for (int i = 1; i < argc; ++i) {
1750 const char *opt = argv[i];
1751 if (streq(opt, "-I")) {
1752 prepend_include_path(argv[++i]);
1754 } else if (streq(opt, "-E")) {
1756 } else if (streq(opt, "-o")) {
1759 } else if (opt[0] == '-') {
1760 fprintf(stderr, "Unknown option '%s'\n", opt);
1762 if (filename != NULL)
1763 fprintf(stderr, "Multiple inputs not supported\n");
1767 if (filename == NULL) {
1768 fprintf(stderr, "No input specified\n");
1772 if (output == NULL) {
1775 out = fopen(output, "w");
1777 fprintf(stderr, "Couldn't open output '%s'\n", output);
1782 /* just here for gcc compatibility */
1783 fprintf(out, "# 1 \"%s\"\n", filename);
1784 fprintf(out, "# 1 \"<built-in>\"\n");
1785 fprintf(out, "# 1 \"<command-line>\"\n");
1787 FILE *file = fopen(filename, "r");
1789 fprintf(stderr, "Couldn't open input '%s'\n", filename);
1792 switch_input(file, filename);
1795 if (pp_token.kind == '#' && info.at_line_begin) {
1796 parse_preprocessing_directive();
1798 } else if (pp_token.kind == T_EOF) {
1799 goto end_of_main_loop;
1800 } else if (pp_token.kind == T_IDENTIFIER) {
1801 symbol_t *const symbol = pp_token.base.symbol;
1802 pp_definition_t *const pp_definition = symbol->pp_definition;
1803 if (pp_definition != NULL && !pp_definition->is_expanding) {
1804 expansion_pos = pp_token.base.source_position;
1805 if (pp_definition->has_parameters) {
1806 source_position_t position = pp_token.base.source_position;
1807 add_token_info_t old_info = info;
1808 eat_token(T_IDENTIFIER);
1809 add_token_info_t new_info = info;
1811 /* no opening brace -> no expansion */
1812 if (pp_token.kind == '(') {
1815 /* parse arguments (TODO) */
1816 while (pp_token.kind != T_EOF && pp_token.kind != ')')
1817 next_preprocessing_token();
1819 token_t next_token = pp_token;
1820 /* restore identifier token */
1821 pp_token.kind = T_IDENTIFIER;
1822 pp_token.base.symbol = symbol;
1823 pp_token.base.source_position = position;
1828 pp_token = next_token;
1833 pp_definition->expand_pos = 0;
1834 pp_definition->is_expanding = true;
1835 current_expansion = pp_definition;
1842 next_preprocessing_token();
1847 check_unclosed_conditionals();
1852 obstack_free(&input_obstack, NULL);
1853 obstack_free(&pp_obstack, NULL);
1854 obstack_free(&config_obstack, NULL);
1856 strset_destroy(&stringset);
1859 exit_symbol_table();