Don't silently delete unnecessary phi_nodes that were generated by "return".
[smatch.git] / pre-process.c
blob6867d51efcba455b392383d5264ba3a0a834f2ec
1 /*
2 * Do C preprocessing, based on a token list gathered by
3 * the tokenizer.
5 * This may not be the smartest preprocessor on the planet.
7 * Copyright (C) 2003 Transmeta Corp.
8 * 2003-2004 Linus Torvalds
10 * Licensed under the Open Software License version 1.1
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <stddef.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <unistd.h>
19 #include <fcntl.h>
20 #include <limits.h>
22 #include "pre-process.h"
23 #include "lib.h"
24 #include "parse.h"
25 #include "token.h"
26 #include "symbol.h"
27 #include "expression.h"
29 int verbose = 0;
30 int preprocessing = 0;
32 static int true_nesting = 0;
33 static int false_nesting = 0;
34 static struct token *unmatched_if = NULL;
35 #define if_nesting (true_nesting + false_nesting)
37 #define MAX_NEST (256)
38 static unsigned char elif_ignore[MAX_NEST];
39 enum { ELIF_IGNORE = 1, ELIF_SEEN_ELSE = 2 };
41 #define INCLUDEPATHS 300
42 const char *includepath[INCLUDEPATHS+1] = {
43 "/usr/include",
44 "/usr/local/include",
45 GCC_INTERNAL_INCLUDE,
46 NULL
49 static const char **sys_includepath = includepath + 0;
50 static const char **gcc_includepath = includepath + 2;
52 #define MARK_STREAM_NONCONST(pos) do { \
53 if (stream->constant != CONSTANT_FILE_NOPE) { \
54 if (0) \
55 info(pos, "%s triggers non-const", __func__); \
56 stream->constant = CONSTANT_FILE_NOPE; \
57 } \
58 } while (0)
61 static struct token *alloc_token(struct position *pos)
63 struct token *token = __alloc_token(0);
65 token->pos.stream = pos->stream;
66 token->pos.line = pos->line;
67 token->pos.pos = pos->pos;
68 token->pos.whitespace = 1;
69 return token;
72 static const char *show_token_sequence(struct token *token);
74 /* Expand symbol 'sym' at '*list' */
75 static int expand(struct token **, struct symbol *);
77 static void replace_with_string(struct token *token, const char *str)
79 int size = strlen(str) + 1;
80 struct string *s = __alloc_string(size);
82 s->length = size;
83 memcpy(s->data, str, size);
84 token_type(token) = TOKEN_STRING;
85 token->string = s;
88 static void replace_with_integer(struct token *token, unsigned int val)
90 char *buf = __alloc_bytes(11);
91 sprintf(buf, "%u", val);
92 token_type(token) = TOKEN_NUMBER;
93 token->number = buf;
96 static int token_defined(struct token *token)
98 if (token_type(token) == TOKEN_IDENT) {
99 struct symbol *sym = lookup_symbol(token->ident, NS_MACRO);
100 if (sym) {
101 sym->weak = 0;
102 return 1;
104 return 0;
107 warning(token->pos, "expected preprocessor identifier");
108 return 0;
111 static void replace_with_defined(struct token *token)
113 static const char *string[] = { "0", "1" };
114 int defined = token_defined(token);
116 token_type(token) = TOKEN_NUMBER;
117 token->number = string[defined];
120 static int expand_one_symbol(struct token **list)
122 struct token *token = *list;
123 struct symbol *sym;
125 if (token->pos.noexpand)
126 return 1;
128 sym = lookup_symbol(token->ident, NS_MACRO);
129 if (sym) {
130 sym->weak = 0;
131 return expand(list, sym);
133 if (token->ident == &__LINE___ident) {
134 replace_with_integer(token, token->pos.line);
135 } else if (token->ident == &__FILE___ident) {
136 replace_with_string(token, (input_streams + token->pos.stream)->name);
138 return 1;
141 static inline struct token *scan_next(struct token **where)
143 struct token *token = *where;
144 if (token_type(token) != TOKEN_UNTAINT)
145 return token;
146 do {
147 token->ident->tainted = 0;
148 token = token->next;
149 } while (token_type(token) == TOKEN_UNTAINT);
150 *where = token;
151 return token;
154 static void expand_list(struct token **list)
156 struct token *next;
157 while (!eof_token(next = scan_next(list))) {
158 if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list))
159 list = &next->next;
163 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
165 struct token **p = &prev->next;
166 struct token *next;
167 int nesting = 0;
169 while (!eof_token(next = scan_next(p))) {
170 if (match_op(next, '(')) {
171 nesting++;
172 } else if (match_op(next, ')')) {
173 if (!nesting--)
174 break;
175 } else if (match_op(next, ',') && !nesting && !vararg) {
176 break;
178 next->pos.stream = pos->stream;
179 next->pos.line = pos->line;
180 next->pos.pos = pos->pos;
181 p = &next->next;
183 *p = &eof_token_entry;
184 return next;
188 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
191 struct arg {
192 struct token *arg;
193 struct token *expanded;
194 struct token *str;
195 int n_normal;
196 int n_quoted;
197 int n_str;
200 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
202 int wanted = arglist->count.normal;
203 struct token *next = NULL;
204 int count = 0;
206 arglist = arglist->next; /* skip counter */
208 if (!wanted) {
209 next = collect_arg(start, 0, &what->pos);
210 if (eof_token(next))
211 goto Eclosing;
212 if (!eof_token(start->next) || !match_op(next, ')')) {
213 count++;
214 goto Emany;
216 } else {
217 for (count = 0; count < wanted; count++) {
218 struct argcount *p = &arglist->next->count;
219 next = collect_arg(start, p->vararg, &what->pos);
220 arglist = arglist->next->next;
221 if (eof_token(next))
222 goto Eclosing;
223 args[count].arg = start->next;
224 args[count].n_normal = p->normal;
225 args[count].n_quoted = p->quoted;
226 args[count].n_str = p->str;
227 if (match_op(next, ')')) {
228 count++;
229 break;
231 start = next;
233 if (count == wanted && !match_op(next, ')'))
234 goto Emany;
235 if (count == wanted - 1) {
236 struct argcount *p = &arglist->next->count;
237 if (!p->vararg)
238 goto Efew;
239 args[count].arg = NULL;
240 args[count].n_normal = p->normal;
241 args[count].n_quoted = p->quoted;
242 args[count].n_str = p->str;
244 if (count < wanted - 1)
245 goto Efew;
247 what->next = next->next;
248 return 1;
250 Efew:
251 warning(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
252 show_token(what), wanted, count);
253 goto out;
254 Emany:
255 while (match_op(next, ',')) {
256 next = collect_arg(next, 0, &what->pos);
257 count++;
259 if (eof_token(next))
260 goto Eclosing;
261 warning(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
262 show_token(what), count, wanted);
263 goto out;
264 Eclosing:
265 warning(what->pos, "unterminated argument list invoking macro \"%s\"",
266 show_token(what));
267 out:
268 what->next = next->next;
269 return 0;
272 static struct token *dup_list(struct token *list)
274 struct token *res;
275 struct token **p = &res;
277 while (!eof_token(list)) {
278 struct token *newtok = __alloc_token(0);
279 *newtok = *list;
280 *p = newtok;
281 p = &newtok->next;
282 list = list->next;
284 return res;
287 static struct token *stringify(struct token *arg)
289 const char *s = show_token_sequence(arg);
290 int size = strlen(s)+1;
291 struct token *token = __alloc_token(0);
292 struct string *string = __alloc_string(size);
294 memcpy(string->data, s, size);
295 string->length = size;
296 token->pos = arg->pos;
297 token_type(token) = TOKEN_STRING;
298 token->string = string;
299 token->next = &eof_token_entry;
300 return token;
303 static void expand_arguments(int count, struct arg *args)
305 int i;
306 for (i = 0; i < count; i++) {
307 struct token *arg = args[i].arg;
308 if (!arg)
309 arg = &eof_token_entry;
310 if (args[i].n_str)
311 args[i].str = stringify(arg);
312 if (args[i].n_normal) {
313 if (!args[i].n_quoted) {
314 args[i].expanded = arg;
315 args[i].arg = NULL;
316 } else if (eof_token(arg)) {
317 args[i].expanded = arg;
318 } else {
319 args[i].expanded = dup_list(arg);
321 expand_list(&args[i].expanded);
327 * Possibly valid combinations:
328 * - ident + ident -> ident
329 * - ident + number -> ident unless number contains '.', '+' or '-'.
330 * - number + number -> number
331 * - number + ident -> number
332 * - number + '.' -> number
333 * - number + '+' or '-' -> number, if number used to end on [eEpP].
334 * - '.' + number -> number, if number used to start with a digit.
335 * - special + special -> either special or an error.
337 static enum token_type combine(struct token *left, struct token *right, char *p)
339 int len;
340 enum token_type t1 = token_type(left), t2 = token_type(right);
342 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
343 return TOKEN_ERROR;
345 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
346 return TOKEN_ERROR;
348 strcpy(p, show_token(left));
349 strcat(p, show_token(right));
350 len = strlen(p);
352 if (len >= 256)
353 return TOKEN_ERROR;
355 if (t1 == TOKEN_IDENT) {
356 if (t2 == TOKEN_SPECIAL)
357 return TOKEN_ERROR;
358 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
359 return TOKEN_ERROR;
360 return TOKEN_IDENT;
363 if (t1 == TOKEN_NUMBER) {
364 if (t2 == TOKEN_SPECIAL) {
365 switch (right->special) {
366 case '.':
367 break;
368 case '+': case '-':
369 if (strchr("eEpP", p[len - 2]))
370 break;
371 default:
372 return TOKEN_ERROR;
375 return TOKEN_NUMBER;
378 if (p[0] == '.' && isdigit((unsigned char)p[1]))
379 return TOKEN_NUMBER;
381 return TOKEN_SPECIAL;
384 static int merge(struct token *left, struct token *right)
386 extern unsigned char combinations[][3];
387 static char buffer[512];
388 int n;
390 switch (combine(left, right, buffer)) {
391 case TOKEN_IDENT:
392 left->ident = built_in_ident(buffer);
393 left->pos.noexpand = 0;
394 return 1;
396 case TOKEN_NUMBER: {
397 char *number = __alloc_bytes(strlen(buffer) + 1);
398 memcpy(number, buffer, strlen(buffer) + 1);
399 token_type(left) = TOKEN_NUMBER; /* could be . + num */
400 left->number = number;
401 return 1;
404 case TOKEN_SPECIAL:
405 if (buffer[2] && buffer[3])
406 break;
407 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
408 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
409 left->special = n;
410 return 1;
413 default:
416 warning(left->pos, "'##' failed: concatenation is not a valid token");
417 return 0;
420 static struct token *dup_token(struct token *token, struct position *streampos, struct position *pos)
422 struct token *alloc = alloc_token(streampos);
423 token_type(alloc) = token_type(token);
424 alloc->pos.newline = pos->newline;
425 alloc->pos.whitespace = pos->whitespace;
426 alloc->number = token->number;
427 alloc->pos.noexpand = token->pos.noexpand;
428 return alloc;
431 static struct token **copy(struct token **where, struct token *list, int *count)
433 int need_copy = --*count;
434 while (!eof_token(list)) {
435 struct token *token;
436 if (need_copy)
437 token = dup_token(list, &list->pos, &list->pos);
438 else
439 token = list;
440 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
441 token->pos.noexpand = 1;
442 *where = token;
443 where = &token->next;
444 list = list->next;
446 *where = &eof_token_entry;
447 return where;
450 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
452 struct token *token = *list;
453 struct position *base_pos = &token->pos;
454 struct position *pos = base_pos;
455 int *count;
456 enum {Normal, Placeholder, Concat} state = Normal;
458 for (; !eof_token(body); body = body->next, pos = &body->pos) {
459 struct token *added, *arg;
460 struct token **tail;
462 switch (token_type(body)) {
463 case TOKEN_GNU_KLUDGE:
465 * GNU kludge: if we had <comma>##<vararg>, behaviour
466 * depends on whether we had enough arguments to have
467 * a vararg. If we did, ## is just ignored. Otherwise
468 * both , and ## are ignored. Comma should come from
469 * the body of macro and not be an argument of earlier
470 * concatenation.
472 if (!args[body->next->argnum].arg)
473 continue;
474 added = dup_token(body, base_pos, pos);
475 token_type(added) = TOKEN_SPECIAL;
476 tail = &added->next;
477 break;
479 case TOKEN_STR_ARGUMENT:
480 arg = args[body->argnum].str;
481 count = &args[body->argnum].n_str;
482 goto copy_arg;
484 case TOKEN_QUOTED_ARGUMENT:
485 arg = args[body->argnum].arg;
486 count = &args[body->argnum].n_quoted;
487 if (!arg || eof_token(arg)) {
488 if (state == Concat)
489 state = Normal;
490 else
491 state = Placeholder;
492 continue;
494 goto copy_arg;
496 case TOKEN_MACRO_ARGUMENT:
497 arg = args[body->argnum].expanded;
498 count = &args[body->argnum].n_normal;
499 if (eof_token(arg)) {
500 state = Normal;
501 continue;
503 copy_arg:
504 tail = copy(&added, arg, count);
505 added->pos.newline = pos->newline;
506 added->pos.whitespace = pos->whitespace;
507 break;
509 case TOKEN_CONCAT:
510 if (state == Placeholder)
511 state = Normal;
512 else
513 state = Concat;
514 continue;
516 case TOKEN_IDENT:
517 added = dup_token(body, base_pos, pos);
518 if (added->ident->tainted)
519 added->pos.noexpand = 1;
520 tail = &added->next;
521 break;
523 default:
524 added = dup_token(body, base_pos, pos);
525 tail = &added->next;
526 break;
530 * if we got to doing real concatenation, we already have
531 * added something into the list, so containing_token() is OK.
533 if (state == Concat && merge(containing_token(list), added)) {
534 *list = added->next;
535 if (tail != &added->next)
536 list = tail;
537 } else {
538 *list = added;
539 list = tail;
541 state = Normal;
543 *list = &eof_token_entry;
544 return list;
547 static int expand(struct token **list, struct symbol *sym)
549 struct token *last;
550 struct token *token = *list;
551 struct ident *expanding = token->ident;
552 struct token **tail;
553 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
554 struct arg args[nargs];
556 if (expanding->tainted) {
557 token->pos.noexpand = 1;
558 return 1;
561 if (sym->arglist) {
562 if (!match_op(scan_next(&token->next), '('))
563 return 1;
564 if (!collect_arguments(token->next, sym->arglist, args, token))
565 return 1;
566 expand_arguments(nargs, args);
569 expanding->tainted = 1;
571 last = token->next;
572 tail = substitute(list, sym->expansion, args);
573 *tail = last;
575 return 0;
578 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
580 struct token *last;
581 static char buffer[256];
582 char *ptr = buffer;
584 last = token;
585 while (!eof_token(token) && !match_op(token, endop)) {
586 int len;
587 const char *val = token->string->data;
588 if (token_type(token) != TOKEN_STRING)
589 val = show_token(token);
590 len = strlen(val);
591 memcpy(ptr, val, len);
592 ptr += len;
593 token = token->next;
595 *ptr = 0;
596 if (endop && !match_op(token, endop))
597 warning(start->pos, "expected '>' at end of filename");
598 return buffer;
601 static int try_include(const char *path, int plen, const char *filename, int flen, struct token **where, const char **next_path)
603 int fd;
604 static char fullname[PATH_MAX];
606 memcpy(fullname, path, plen);
607 if (plen && path[plen-1] != '/') {
608 fullname[plen] = '/';
609 plen++;
611 memcpy(fullname+plen, filename, flen);
612 fd = open(fullname, O_RDONLY);
613 if (fd >= 0) {
614 char * streamname = __alloc_bytes(plen + flen);
615 memcpy(streamname, fullname, plen + flen);
616 *where = tokenize(streamname, fd, *where, next_path);
617 close(fd);
618 return 1;
620 return 0;
623 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
625 const char *path;
627 while ((path = *pptr++) != NULL) {
628 if (!try_include(path, strlen(path), filename, flen, list, pptr))
629 continue;
630 return 1;
632 return 0;
636 static void do_include(int local, struct stream *stream, struct token **list, struct token *token, const char *filename, const char **path)
638 int flen = strlen(filename) + 1;
640 /* Absolute path? */
641 if (filename[0] == '/') {
642 if (try_include("", 0, filename, flen, list, includepath))
643 return;
644 goto out;
647 /* Same directory as current stream? */
648 if (local) {
649 const char *path;
650 char *slash;
651 int plen;
653 path = stream->name;
654 slash = strrchr(path, '/');
655 plen = slash ? slash - path : 0;
657 if (try_include(path, plen, filename, flen, list, includepath))
658 return;
661 /* Check the standard include paths.. */
662 if (do_include_path(path, list, token, filename, flen))
663 return;
664 out:
665 error_die(token->pos, "unable to open '%s'", filename);
668 static int free_preprocessor_line(struct token *token)
670 do {
671 struct token *free = token;
672 token = token->next;
673 __free_token(free);
674 } while (token_type(token) != TOKEN_EOF);
675 return 1;
678 static int handle_include_path(struct stream *stream, struct token **list, struct token *token, const char **path)
680 const char *filename;
681 struct token *next;
682 int expect;
684 if (false_nesting)
685 return free_preprocessor_line(token);
687 if (stream->constant == CONSTANT_FILE_MAYBE)
688 MARK_STREAM_NONCONST(token->pos);
690 next = token->next;
691 expect = '>';
692 if (!match_op(next, '<')) {
693 expand_list(&token->next);
694 expect = 0;
695 next = token;
696 if (match_op(token->next, '<')) {
697 next = token->next;
698 expect = '>';
701 token = next->next;
702 filename = token_name_sequence(token, expect, token);
703 do_include(!expect, stream, list, token, filename, path);
704 return 1;
707 static int handle_include(struct stream *stream, struct token **list, struct token *token)
709 return handle_include_path(stream, list, token, includepath);
712 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
714 return handle_include_path(stream, list, token, stream->next_path);
717 static int token_different(struct token *t1, struct token *t2)
719 int different;
721 if (token_type(t1) != token_type(t2))
722 return 1;
724 switch (token_type(t1)) {
725 case TOKEN_IDENT:
726 different = t1->ident != t2->ident;
727 break;
728 case TOKEN_ARG_COUNT:
729 case TOKEN_UNTAINT:
730 case TOKEN_CONCAT:
731 case TOKEN_GNU_KLUDGE:
732 different = 0;
733 break;
734 case TOKEN_NUMBER:
735 different = strcmp(t1->number, t2->number);
736 break;
737 case TOKEN_SPECIAL:
738 different = t1->special != t2->special;
739 break;
740 case TOKEN_MACRO_ARGUMENT:
741 case TOKEN_QUOTED_ARGUMENT:
742 case TOKEN_STR_ARGUMENT:
743 different = t1->argnum != t2->argnum;
744 break;
745 case TOKEN_CHAR:
746 different = t1->character != t2->character;
747 break;
748 case TOKEN_STRING: {
749 struct string *s1, *s2;
751 s1 = t1->string;
752 s2 = t2->string;
753 different = 1;
754 if (s1->length != s2->length)
755 break;
756 different = memcmp(s1->data, s2->data, s1->length);
757 break;
759 default:
760 different = 1;
761 break;
763 return different;
766 static int token_list_different(struct token *list1, struct token *list2)
768 for (;;) {
769 if (list1 == list2)
770 return 0;
771 if (!list1 || !list2)
772 return 1;
773 if (token_different(list1, list2))
774 return 1;
775 list1 = list1->next;
776 list2 = list2->next;
780 static inline void set_arg_count(struct token *token)
782 token_type(token) = TOKEN_ARG_COUNT;
783 token->count.normal = token->count.quoted =
784 token->count.str = token->count.vararg = 0;
787 static struct token *parse_arguments(struct token *list)
789 struct token *arg = list->next, *next = list;
790 struct argcount *count = &list->count;
792 set_arg_count(list);
794 if (match_op(arg, ')')) {
795 next = arg->next;
796 list->next = &eof_token_entry;
797 return next;
800 while (token_type(arg) == TOKEN_IDENT) {
801 if (arg->ident == &__VA_ARGS___ident)
802 goto Eva_args;
803 if (!++count->normal)
804 goto Eargs;
805 next = arg->next;
807 if (match_op(next, ',')) {
808 set_arg_count(next);
809 arg = next->next;
810 continue;
813 if (match_op(next, ')')) {
814 set_arg_count(next);
815 next = next->next;
816 arg->next->next = &eof_token_entry;
817 return next;
820 /* normal cases are finished here */
822 if (match_op(next, SPECIAL_ELLIPSIS)) {
823 if (match_op(next->next, ')')) {
824 set_arg_count(next);
825 next->count.vararg = 1;
826 next = next->next;
827 arg->next->next = &eof_token_entry;
828 return next->next;
831 arg = next;
832 goto Enotclosed;
835 if (eof_token(next)) {
836 goto Enotclosed;
837 } else {
838 arg = next;
839 goto Ebadstuff;
843 if (match_op(arg, SPECIAL_ELLIPSIS)) {
844 next = arg->next;
845 token_type(arg) = TOKEN_IDENT;
846 arg->ident = &__VA_ARGS___ident;
847 if (!match_op(next, ')'))
848 goto Enotclosed;
849 if (!++count->normal)
850 goto Eargs;
851 set_arg_count(next);
852 next->count.vararg = 1;
853 next = next->next;
854 arg->next->next = &eof_token_entry;
855 return next;
858 if (eof_token(arg)) {
859 arg = next;
860 goto Enotclosed;
862 if (match_op(arg, ','))
863 goto Emissing;
864 else
865 goto Ebadstuff;
868 Emissing:
869 warning(arg->pos, "parameter name missing");
870 return NULL;
871 Ebadstuff:
872 warning(arg->pos, "\"%s\" may not appear in macro parameter list",
873 show_token(arg));
874 return NULL;
875 Enotclosed:
876 warning(arg->pos, "missing ')' in macro parameter list");
877 return NULL;
878 Eva_args:
879 warning(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
880 return NULL;
881 Eargs:
882 warning(arg->pos, "too many arguments in macro definition");
883 return NULL;
886 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
888 struct ident *ident = token->ident;
889 int nr;
891 if (!arglist || token_type(token) != TOKEN_IDENT)
892 return 0;
894 arglist = arglist->next;
896 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
897 if (arglist->ident == ident) {
898 struct argcount *count = &arglist->next->count;
899 int n;
901 token->argnum = nr;
902 token_type(token) = type;
903 switch (type) {
904 case TOKEN_MACRO_ARGUMENT:
905 n = ++count->normal;
906 break;
907 case TOKEN_QUOTED_ARGUMENT:
908 n = ++count->quoted;
909 break;
910 default:
911 n = ++count->str;
913 if (n)
914 return count->vararg ? 2 : 1;
915 token_type(token) = TOKEN_ERROR;
916 return -1;
919 return 0;
922 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
924 struct token *token = expansion;
925 struct token **p;
926 struct token *last = NULL;
928 if (match_op(token, SPECIAL_HASHHASH))
929 goto Econcat;
931 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
932 if (match_op(token, '#')) {
933 if (arglist) {
934 struct token *next = token->next;
935 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
936 goto Equote;
937 next->pos.whitespace = token->pos.whitespace;
938 token = *p = next;
939 } else {
940 token->pos.noexpand = 1;
942 } else if (match_op(token, SPECIAL_HASHHASH)) {
943 struct token *next = token->next;
944 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
945 token_type(token) = TOKEN_CONCAT;
946 if (arg) {
947 token = next;
948 /* GNU kludge */
949 if (arg == 2 && last && match_op(last, ',')) {
950 token_type(last) = TOKEN_GNU_KLUDGE;
951 last->next = token;
953 } else if (match_op(next, SPECIAL_HASHHASH))
954 token = next;
955 else if (match_op(next, ','))
956 token = next;
957 else if (eof_token(next))
958 goto Econcat;
959 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
960 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
961 } else {
962 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
964 if (token_type(token) == TOKEN_ERROR)
965 goto Earg;
966 last = token;
968 token = alloc_token(&expansion->pos);
969 token_type(token) = TOKEN_UNTAINT;
970 token->ident = name;
971 token->next = *p;
972 *p = token;
973 return expansion;
975 Equote:
976 warning(token->pos, "'#' is not followed by a macro parameter");
977 return NULL;
979 Econcat:
980 warning(token->pos, "'##' cannot appear at the ends of macro expansion");
981 return NULL;
982 Earg:
983 warning(token->pos, "too many instances of argument in body");
984 return NULL;
987 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int weak)
989 struct token *arglist, *expansion;
990 struct token *left = token->next;
991 struct symbol *sym;
992 struct ident *name;
994 if (token_type(left) != TOKEN_IDENT) {
995 warning(token->pos, "expected identifier to 'define'");
996 return 0;
998 if (false_nesting)
999 return free_preprocessor_line(token);
1001 if (stream->constant == CONSTANT_FILE_MAYBE)
1002 MARK_STREAM_NONCONST(token->pos);
1004 __free_token(token); /* Free the "define" token, but not the rest of the line */
1005 name = left->ident;
1007 arglist = NULL;
1008 expansion = left->next;
1009 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
1010 arglist = expansion;
1011 expansion = parse_arguments(expansion);
1012 if (!expansion)
1013 return 1;
1016 expansion = parse_expansion(expansion, arglist, name);
1017 if (!expansion)
1018 return 1;
1020 sym = lookup_symbol(name, NS_MACRO);
1021 if (sym) {
1022 if (token_list_different(sym->expansion, expansion) ||
1023 token_list_different(sym->arglist, arglist)) {
1024 if (sym->weak)
1025 goto replace_it;
1026 if (weak)
1027 return 1;
1028 warning(left->pos, "preprocessor token %.*s redefined",
1029 name->len, name->name);
1030 info(sym->pos, "this was the original definition");
1031 sym->expansion = expansion;
1032 sym->arglist = arglist;
1034 return 1;
1036 sym = alloc_symbol(left->pos, SYM_NODE);
1037 bind_symbol(sym, name, NS_MACRO);
1039 replace_it:
1040 sym->expansion = expansion;
1041 sym->arglist = arglist;
1042 sym->weak = weak;
1043 return 1;
1046 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1048 return do_handle_define(stream, line, token, 0);
1051 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1053 return do_handle_define(stream, line, token, 1);
1056 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1058 struct token *left = token->next;
1059 struct symbol **sym;
1061 if (token_type(left) != TOKEN_IDENT) {
1062 warning(token->pos, "expected identifier to 'undef'");
1063 return 0;
1065 if (false_nesting)
1066 return free_preprocessor_line(token);
1068 if (stream->constant == CONSTANT_FILE_MAYBE)
1069 MARK_STREAM_NONCONST(token->pos);
1071 sym = &left->ident->symbols;
1072 while (*sym) {
1073 struct symbol *t = *sym;
1074 if (t->namespace == NS_MACRO) {
1075 *sym = t->next_id;
1076 return 1;
1078 sym = &t->next_id;
1080 return free_preprocessor_line(token);
1083 static int preprocessor_if(struct token *token, int true)
1085 if (if_nesting == 0)
1086 unmatched_if = token;
1087 if (if_nesting >= MAX_NEST)
1088 error_die(token->pos, "Maximum preprocessor conditional level exhausted");
1089 elif_ignore[if_nesting] = (false_nesting || true) ? ELIF_IGNORE : 0;
1090 if (false_nesting || !true) {
1091 false_nesting++;
1092 return free_preprocessor_line(token);
1094 true_nesting++;
1095 return free_preprocessor_line(token);
1098 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1100 return preprocessor_if(token, token_defined(token->next));
1103 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1105 struct token *next = token->next;
1106 if (stream->constant == CONSTANT_FILE_MAYBE) {
1107 if (token_type(next) == TOKEN_IDENT &&
1108 (!stream->protect || stream->protect == next->ident)) {
1109 stream->constant = CONSTANT_FILE_IFNDEF;
1110 stream->protect = next->ident;
1111 } else
1112 MARK_STREAM_NONCONST(token->pos);
1114 return preprocessor_if(token, !token_defined(next));
1118 * Expression handling for #if and #elif; it differs from normal expansion
1119 * due to special treatment of "defined".
1121 static int expression_value(struct token **where)
1123 struct expression *expr;
1124 struct token *p;
1125 struct token **list = where, **beginning = NULL;
1126 long long value;
1127 int state = 0;
1129 while (!eof_token(p = scan_next(list))) {
1130 switch (state) {
1131 case 0:
1132 if (token_type(p) != TOKEN_IDENT)
1133 break;
1134 if (p->ident == &defined_ident) {
1135 state = 1;
1136 beginning = list;
1137 break;
1139 if (!expand_one_symbol(list))
1140 continue;
1141 if (token_type(p) != TOKEN_IDENT)
1142 break;
1143 if (Wundefined_preprocessor)
1144 warning(p->pos, "undefined preprocessor identifier '%s'", show_ident(p->ident));
1145 replace_with_integer(p, 0);
1146 break;
1147 case 1:
1148 if (match_op(p, '(')) {
1149 state = 2;
1150 } else {
1151 state = 0;
1152 replace_with_defined(p);
1153 *beginning = p;
1155 break;
1156 case 2:
1157 if (token_type(p) == TOKEN_IDENT)
1158 state = 3;
1159 else
1160 state = 0;
1161 replace_with_defined(p);
1162 *beginning = p;
1163 break;
1164 case 3:
1165 state = 0;
1166 if (!match_op(p, ')'))
1167 warning(p->pos, "missing ')' after \"defined\"");
1168 *list = p->next;
1169 continue;
1171 list = &p->next;
1174 p = constant_expression(*where, &expr);
1175 if (!eof_token(p))
1176 warning(p->pos, "garbage at end: %s", show_token_sequence(p));
1177 value = get_expression_value(expr);
1178 return value != 0;
1181 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1183 int value = 0;
1184 if (!false_nesting)
1185 value = expression_value(&token->next);
1187 // This is an approximation. We really only need this if the
1188 // condition does depends on a pre-processor symbol. Note, that
1189 // the important #ifndef case has already changed ->constant.
1190 if (stream->constant == CONSTANT_FILE_MAYBE)
1191 MARK_STREAM_NONCONST(token->pos);
1193 return preprocessor_if(token, value);
1196 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1198 if (stream->nesting == if_nesting)
1199 MARK_STREAM_NONCONST(token->pos);
1201 if (stream->nesting > if_nesting)
1202 warning(token->pos, "unmatched #elif within stream");
1204 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1205 warning(token->pos, "#elif after #else");
1207 if (false_nesting) {
1208 /* If this whole if-thing is if'ed out, an elif cannot help */
1209 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1210 return 1;
1211 if (expression_value(&token->next)) {
1212 false_nesting = 0;
1213 true_nesting++;
1214 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1216 } else {
1217 false_nesting = 1;
1218 true_nesting--;
1220 return free_preprocessor_line(token);
1223 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1225 if (stream->nesting == if_nesting)
1226 MARK_STREAM_NONCONST(token->pos);
1228 if (stream->nesting > if_nesting)
1229 warning(token->pos, "unmatched #else within stream");
1231 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1232 warning(token->pos, "#else after #else");
1233 else
1234 elif_ignore[if_nesting-1] |= ELIF_SEEN_ELSE;
1236 if (false_nesting) {
1237 /* If this whole if-thing is if'ed out, an else cannot help */
1238 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1239 return 1;
1240 false_nesting = 0;
1241 true_nesting++;
1242 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1243 } else {
1244 true_nesting--;
1245 false_nesting = 1;
1247 return free_preprocessor_line(token);
1250 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1252 if (stream->constant == CONSTANT_FILE_IFNDEF && stream->nesting == if_nesting)
1253 stream->constant = CONSTANT_FILE_MAYBE;
1255 if (stream->nesting > if_nesting)
1256 warning(token->pos, "unmatched #endif in stream");
1257 if (false_nesting)
1258 false_nesting--;
1259 else
1260 true_nesting--;
1261 return free_preprocessor_line(token);
1264 static const char *show_token_sequence(struct token *token)
1266 static char buffer[1024];
1267 char *ptr = buffer;
1268 int whitespace = 0;
1270 if (!token)
1271 return "<none>";
1272 while (!eof_token(token)) {
1273 const char *val = show_token(token);
1274 int len = strlen(val);
1276 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
1277 warning(token->pos, "too long token expansion");
1278 break;
1281 if (whitespace)
1282 *ptr++ = ' ';
1283 memcpy(ptr, val, len);
1284 ptr += len;
1285 token = token->next;
1286 whitespace = token->pos.whitespace;
1288 *ptr = 0;
1289 return buffer;
1292 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1294 if (false_nesting)
1295 return free_preprocessor_line(token);
1296 if (stream->constant == CONSTANT_FILE_MAYBE)
1297 MARK_STREAM_NONCONST(token->pos);
1298 warning(token->pos, "%s", show_token_sequence(token->next));
1299 return free_preprocessor_line(token);
1302 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1304 if (false_nesting)
1305 return free_preprocessor_line(token);
1306 if (stream->constant == CONSTANT_FILE_MAYBE)
1307 MARK_STREAM_NONCONST(token->pos);
1308 warning(token->pos, "%s", show_token_sequence(token->next));
1309 return free_preprocessor_line(token);
1312 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1314 int stdinc;
1316 if (false_nesting)
1317 return free_preprocessor_line(token);
1320 * Do we have any non-system includes?
1321 * Clear them out if so..
1323 stdinc = gcc_includepath - sys_includepath;
1324 if (stdinc) {
1325 const char **src = gcc_includepath;
1326 const char **dst = sys_includepath;
1327 for (;;) {
1328 if (!(*dst = *src))
1329 break;
1330 dst++;
1331 src++;
1333 gcc_includepath -= stdinc;
1335 return free_preprocessor_line(token);
1338 static void add_path_entry(struct token *token, const char *path)
1340 const char **dst;
1341 const char *next;
1343 /* Need one free entry.. */
1344 if (includepath[INCLUDEPATHS-2])
1345 error_die(token->pos, "too many include path entries");
1347 next = path;
1348 dst = sys_includepath;
1349 sys_includepath++;
1350 gcc_includepath++;
1353 * Move them all up starting at "sys_includepath",
1354 * insert the new entry..
1356 for (;;) {
1357 const char *tmp = *dst;
1358 *dst = next;
1359 if (!next)
1360 break;
1361 next = tmp;
1362 dst++;
1366 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1368 for (;;) {
1369 token = token->next;
1370 if (eof_token(token))
1371 return 1;
1372 if (token_type(token) != TOKEN_STRING) {
1373 warning(token->pos, "expected path string");
1374 return 1;
1376 add_path_entry(token, token->string->data);
1381 * We replace "#pragma xxx" with "__pragma__" in the token
1382 * stream. Just as an example.
1384 * We'll just #define that away for now, but the theory here
1385 * is that we can use this to insert arbitrary token sequences
1386 * to turn the pragma's into internal front-end sequences for
1387 * when we actually start caring about them.
1389 * So eventually this will turn into some kind of extended
1390 * __attribute__() like thing, except called __pragma__(xxx).
1392 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1394 struct token *next = *line;
1396 token->ident = &pragma_ident;
1397 token->pos.newline = 1;
1398 token->pos.whitespace = 1;
1399 token->pos.pos = 1;
1400 *line = token;
1401 token->next = next;
1402 return 1;
1406 * We ignore #line for now.
1408 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1410 return 1;
1414 void init_preprocessor(void)
1416 int i;
1417 int stream = init_stream("preprocessor", -1, includepath);
1418 static struct {
1419 const char *name;
1420 int (*handler)(struct stream *, struct token **, struct token *);
1421 } handlers[] = {
1422 { "define", handle_define },
1423 { "weak_define",handle_weak_define },
1424 { "undef", handle_undef },
1425 { "ifdef", handle_ifdef },
1426 { "ifndef", handle_ifndef },
1427 { "else", handle_else },
1428 { "endif", handle_endif },
1429 { "if", handle_if },
1430 { "elif", handle_elif },
1431 { "warning", handle_warning },
1432 { "error", handle_error },
1433 { "include", handle_include },
1434 { "include_next",handle_include_next },
1435 { "pragma", handle_pragma },
1436 { "line", handle_line },
1438 // our internal preprocessor tokens
1439 { "nostdinc", handle_nostdinc },
1440 { "add_include", handle_add_include },
1443 for (i = 0; i < (sizeof (handlers) / sizeof (handlers[0])); i++) {
1444 struct symbol *sym;
1445 sym = create_symbol(stream, handlers[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1446 sym->handler = handlers[i].handler;
1450 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
1452 struct token *token = start->next;
1454 if (!token)
1455 return;
1457 if (token_type(token) == TOKEN_NUMBER)
1458 if (handle_line(stream, line, start))
1459 return;
1461 if (token_type(token) == TOKEN_IDENT) {
1462 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
1463 if (sym && sym->handler(stream, line, token))
1464 return;
1467 warning(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1470 static void preprocessor_line(struct stream *stream, struct token **line)
1472 struct token *start = *line, *next;
1473 struct token **tp = &start->next;
1475 for (;;) {
1476 next = *tp;
1477 if (next->pos.newline)
1478 break;
1479 tp = &next->next;
1481 *line = next;
1482 *tp = &eof_token_entry;
1483 handle_preprocessor_line(stream, line, start);
1486 static void do_preprocess(struct token **list)
1488 struct token *next;
1490 while (!eof_token(next = scan_next(list))) {
1491 struct stream *stream = input_streams + next->pos.stream;
1493 if (next->pos.newline && match_op(next, '#')) {
1494 if (!next->pos.noexpand) {
1495 preprocessor_line(stream, list);
1496 __free_token(next); /* Free the '#' token */
1497 continue;
1501 switch (token_type(next)) {
1502 case TOKEN_STREAMEND:
1503 if (stream->nesting < if_nesting + 1) {
1504 warning(unmatched_if->pos, "unterminated preprocessor conditional");
1505 // Pretend to see a series of #endifs
1506 MARK_STREAM_NONCONST(next->pos);
1507 do {
1508 handle_endif (stream, NULL, NULL);
1509 } while (stream->nesting < if_nesting + 1);
1511 if (stream->constant == CONSTANT_FILE_MAYBE && stream->protect) {
1512 stream->constant = CONSTANT_FILE_YES;
1514 *list = next->next;
1515 continue;
1516 case TOKEN_STREAMBEGIN:
1517 stream->nesting = if_nesting + 1;
1518 *list = next->next;
1519 continue;
1521 default:
1522 if (false_nesting) {
1523 *list = next->next;
1524 __free_token(next);
1525 continue;
1528 if (token_type(next) != TOKEN_IDENT ||
1529 expand_one_symbol(list))
1530 list = &next->next;
1533 if (stream->constant == CONSTANT_FILE_MAYBE) {
1535 * Any token expansion (even if it ended up being an
1536 * empty expansion) in this stream implies it can't
1537 * be constant.
1539 MARK_STREAM_NONCONST(next->pos);
1544 struct token * preprocess(struct token *token)
1546 preprocessing = 1;
1547 init_preprocessor();
1548 do_preprocess(&token);
1550 // Drop all expressions from pre-processing, they're not used any more.
1551 clear_expression_alloc();
1552 preprocessing = 0;
1554 return token;