Make our "__builtin_va_arg()" thing a bit closer to real.
[smatch.git] / pre-process.c
blobe9103c6d90ad673c11097cadeccc958f5b367237
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 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 handle_include_path(struct stream *stream, struct token **list, struct token *token, const char **path)
670 const char *filename;
671 struct token *next;
672 int expect;
674 if (false_nesting)
675 return 1;
677 if (stream->constant == CONSTANT_FILE_MAYBE)
678 MARK_STREAM_NONCONST(token->pos);
680 next = token->next;
681 expect = '>';
682 if (!match_op(next, '<')) {
683 expand_list(&token->next);
684 expect = 0;
685 next = token;
686 if (match_op(token->next, '<')) {
687 next = token->next;
688 expect = '>';
691 token = next->next;
692 filename = token_name_sequence(token, expect, token);
693 do_include(!expect, stream, list, token, filename, path);
694 return 1;
697 static int handle_include(struct stream *stream, struct token **list, struct token *token)
699 return handle_include_path(stream, list, token, includepath);
702 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
704 return handle_include_path(stream, list, token, stream->next_path);
707 static int token_different(struct token *t1, struct token *t2)
709 int different;
711 if (token_type(t1) != token_type(t2))
712 return 1;
714 switch (token_type(t1)) {
715 case TOKEN_IDENT:
716 different = t1->ident != t2->ident;
717 break;
718 case TOKEN_ARG_COUNT:
719 case TOKEN_UNTAINT:
720 case TOKEN_CONCAT:
721 case TOKEN_GNU_KLUDGE:
722 different = 0;
723 break;
724 case TOKEN_NUMBER:
725 different = strcmp(t1->number, t2->number);
726 break;
727 case TOKEN_SPECIAL:
728 different = t1->special != t2->special;
729 break;
730 case TOKEN_MACRO_ARGUMENT:
731 case TOKEN_QUOTED_ARGUMENT:
732 case TOKEN_STR_ARGUMENT:
733 different = t1->argnum != t2->argnum;
734 break;
735 case TOKEN_CHAR:
736 different = t1->character != t2->character;
737 break;
738 case TOKEN_STRING: {
739 struct string *s1, *s2;
741 s1 = t1->string;
742 s2 = t2->string;
743 different = 1;
744 if (s1->length != s2->length)
745 break;
746 different = memcmp(s1->data, s2->data, s1->length);
747 break;
749 default:
750 different = 1;
751 break;
753 return different;
756 static int token_list_different(struct token *list1, struct token *list2)
758 for (;;) {
759 if (list1 == list2)
760 return 0;
761 if (!list1 || !list2)
762 return 1;
763 if (token_different(list1, list2))
764 return 1;
765 list1 = list1->next;
766 list2 = list2->next;
770 static inline void set_arg_count(struct token *token)
772 token_type(token) = TOKEN_ARG_COUNT;
773 token->count.normal = token->count.quoted =
774 token->count.str = token->count.vararg = 0;
777 static struct token *parse_arguments(struct token *list)
779 struct token *arg = list->next, *next = list;
780 struct argcount *count = &list->count;
782 set_arg_count(list);
784 if (match_op(arg, ')')) {
785 next = arg->next;
786 list->next = &eof_token_entry;
787 return next;
790 while (token_type(arg) == TOKEN_IDENT) {
791 if (arg->ident == &__VA_ARGS___ident)
792 goto Eva_args;
793 if (!++count->normal)
794 goto Eargs;
795 next = arg->next;
797 if (match_op(next, ',')) {
798 set_arg_count(next);
799 arg = next->next;
800 continue;
803 if (match_op(next, ')')) {
804 set_arg_count(next);
805 next = next->next;
806 arg->next->next = &eof_token_entry;
807 return next;
810 /* normal cases are finished here */
812 if (match_op(next, SPECIAL_ELLIPSIS)) {
813 if (match_op(next->next, ')')) {
814 set_arg_count(next);
815 next->count.vararg = 1;
816 next = next->next;
817 arg->next->next = &eof_token_entry;
818 return next->next;
821 arg = next;
822 goto Enotclosed;
825 if (eof_token(next)) {
826 goto Enotclosed;
827 } else {
828 arg = next;
829 goto Ebadstuff;
833 if (match_op(arg, SPECIAL_ELLIPSIS)) {
834 next = arg->next;
835 token_type(arg) = TOKEN_IDENT;
836 arg->ident = &__VA_ARGS___ident;
837 if (!match_op(next, ')'))
838 goto Enotclosed;
839 if (!++count->normal)
840 goto Eargs;
841 set_arg_count(next);
842 next->count.vararg = 1;
843 next = next->next;
844 arg->next->next = &eof_token_entry;
845 return next;
848 if (eof_token(arg)) {
849 arg = next;
850 goto Enotclosed;
852 if (match_op(arg, ','))
853 goto Emissing;
854 else
855 goto Ebadstuff;
858 Emissing:
859 warning(arg->pos, "parameter name missing");
860 return NULL;
861 Ebadstuff:
862 warning(arg->pos, "\"%s\" may not appear in macro parameter list",
863 show_token(arg));
864 return NULL;
865 Enotclosed:
866 warning(arg->pos, "missing ')' in macro parameter list");
867 return NULL;
868 Eva_args:
869 warning(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
870 return NULL;
871 Eargs:
872 warning(arg->pos, "too many arguments in macro definition");
873 return NULL;
876 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
878 struct ident *ident = token->ident;
879 int nr;
881 if (!arglist || token_type(token) != TOKEN_IDENT)
882 return 0;
884 arglist = arglist->next;
886 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
887 if (arglist->ident == ident) {
888 struct argcount *count = &arglist->next->count;
889 int n;
891 token->argnum = nr;
892 token_type(token) = type;
893 switch (type) {
894 case TOKEN_MACRO_ARGUMENT:
895 n = ++count->normal;
896 break;
897 case TOKEN_QUOTED_ARGUMENT:
898 n = ++count->quoted;
899 break;
900 default:
901 n = ++count->str;
903 if (n)
904 return count->vararg ? 2 : 1;
905 token_type(token) = TOKEN_ERROR;
906 return -1;
909 return 0;
912 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
914 struct token *token = expansion;
915 struct token **p;
916 struct token *last = NULL;
918 if (match_op(token, SPECIAL_HASHHASH))
919 goto Econcat;
921 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
922 if (match_op(token, '#')) {
923 if (arglist) {
924 struct token *next = token->next;
925 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
926 goto Equote;
927 next->pos.whitespace = token->pos.whitespace;
928 token = *p = next;
929 } else {
930 token->pos.noexpand = 1;
932 } else if (match_op(token, SPECIAL_HASHHASH)) {
933 struct token *next = token->next;
934 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
935 token_type(token) = TOKEN_CONCAT;
936 if (arg) {
937 token = next;
938 /* GNU kludge */
939 if (arg == 2 && last && match_op(last, ',')) {
940 token_type(last) = TOKEN_GNU_KLUDGE;
941 last->next = token;
943 } else if (match_op(next, SPECIAL_HASHHASH))
944 token = next;
945 else if (match_op(next, ','))
946 token = next;
947 else if (eof_token(next))
948 goto Econcat;
949 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
950 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
951 } else {
952 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
954 if (token_type(token) == TOKEN_ERROR)
955 goto Earg;
956 last = token;
958 token = alloc_token(&expansion->pos);
959 token_type(token) = TOKEN_UNTAINT;
960 token->ident = name;
961 token->next = *p;
962 *p = token;
963 return expansion;
965 Equote:
966 warning(token->pos, "'#' is not followed by a macro parameter");
967 return NULL;
969 Econcat:
970 warning(token->pos, "'##' cannot appear at the ends of macro expansion");
971 return NULL;
972 Earg:
973 warning(token->pos, "too many instances of argument in body");
974 return NULL;
977 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int weak)
979 struct token *arglist, *expansion;
980 struct token *left = token->next;
981 struct symbol *sym;
982 struct ident *name;
984 if (token_type(left) != TOKEN_IDENT) {
985 warning(token->pos, "expected identifier to 'define'");
986 return 0;
988 if (false_nesting)
989 return 1;
991 if (stream->constant == CONSTANT_FILE_MAYBE)
992 MARK_STREAM_NONCONST(token->pos);
994 name = left->ident;
996 arglist = NULL;
997 expansion = left->next;
998 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
999 arglist = expansion;
1000 expansion = parse_arguments(expansion);
1001 if (!expansion)
1002 return 1;
1005 expansion = parse_expansion(expansion, arglist, name);
1006 if (!expansion)
1007 return 1;
1009 sym = lookup_symbol(name, NS_MACRO);
1010 if (sym) {
1011 if (token_list_different(sym->expansion, expansion) ||
1012 token_list_different(sym->arglist, arglist)) {
1013 if (sym->weak)
1014 goto replace_it;
1015 if (weak)
1016 return 1;
1017 warning(left->pos, "preprocessor token %.*s redefined",
1018 name->len, name->name);
1019 info(sym->pos, "this was the original definition");
1020 sym->expansion = expansion;
1021 sym->arglist = arglist;
1023 return 1;
1025 sym = alloc_symbol(left->pos, SYM_NODE);
1026 bind_symbol(sym, name, NS_MACRO);
1028 replace_it:
1029 sym->expansion = expansion;
1030 sym->arglist = arglist;
1031 sym->weak = weak;
1032 return 1;
1035 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1037 return do_handle_define(stream, line, token, 0);
1040 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1042 return do_handle_define(stream, line, token, 1);
1045 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1047 struct token *left = token->next;
1048 struct symbol **sym;
1050 if (token_type(left) != TOKEN_IDENT) {
1051 warning(token->pos, "expected identifier to 'undef'");
1052 return 0;
1054 if (false_nesting)
1055 return 1;
1057 if (stream->constant == CONSTANT_FILE_MAYBE)
1058 MARK_STREAM_NONCONST(token->pos);
1060 sym = &left->ident->symbols;
1061 while (*sym) {
1062 struct symbol *t = *sym;
1063 if (t->namespace == NS_MACRO) {
1064 *sym = t->next_id;
1065 return 1;
1067 sym = &t->next_id;
1069 return 1;
1072 static int preprocessor_if(struct token *token, int true)
1074 if (if_nesting == 0)
1075 unmatched_if = token;
1076 if (if_nesting >= MAX_NEST)
1077 error_die(token->pos, "Maximum preprocessor conditional level exhausted");
1078 elif_ignore[if_nesting] = (false_nesting || true) ? ELIF_IGNORE : 0;
1079 if (false_nesting || !true) {
1080 false_nesting++;
1081 return 1;
1083 true_nesting++;
1084 return 1;
1087 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1089 return preprocessor_if(token, token_defined(token->next));
1092 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1094 struct token *next = token->next;
1095 if (stream->constant == CONSTANT_FILE_MAYBE) {
1096 if (token_type(next) == TOKEN_IDENT &&
1097 (!stream->protect || stream->protect == next->ident)) {
1098 stream->constant = CONSTANT_FILE_IFNDEF;
1099 stream->protect = next->ident;
1100 } else
1101 MARK_STREAM_NONCONST(token->pos);
1103 return preprocessor_if(token, !token_defined(next));
1107 * Expression handling for #if and #elif; it differs from normal expansion
1108 * due to special treatment of "defined".
1110 static int expression_value(struct token **where)
1112 struct expression *expr;
1113 struct token *p;
1114 struct token **list = where, **beginning = NULL;
1115 long long value;
1116 int state = 0;
1118 while (!eof_token(p = scan_next(list))) {
1119 switch (state) {
1120 case 0:
1121 if (token_type(p) != TOKEN_IDENT)
1122 break;
1123 if (p->ident == &defined_ident) {
1124 state = 1;
1125 beginning = list;
1126 break;
1128 if (!expand_one_symbol(list))
1129 continue;
1130 if (token_type(p) != TOKEN_IDENT)
1131 break;
1132 if (Wundefined_preprocessor)
1133 warning(p->pos, "undefined preprocessor identifier '%s'", show_ident(p->ident));
1134 replace_with_integer(p, 0);
1135 break;
1136 case 1:
1137 if (match_op(p, '(')) {
1138 state = 2;
1139 } else {
1140 state = 0;
1141 replace_with_defined(p);
1142 *beginning = p;
1144 break;
1145 case 2:
1146 if (token_type(p) == TOKEN_IDENT)
1147 state = 3;
1148 else
1149 state = 0;
1150 replace_with_defined(p);
1151 *beginning = p;
1152 break;
1153 case 3:
1154 state = 0;
1155 if (!match_op(p, ')'))
1156 warning(p->pos, "missing ')' after \"defined\"");
1157 *list = p->next;
1158 continue;
1160 list = &p->next;
1163 p = constant_expression(*where, &expr);
1164 if (!eof_token(p))
1165 warning(p->pos, "garbage at end: %s", show_token_sequence(p));
1166 value = get_expression_value(expr);
1167 return value != 0;
1170 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1172 int value = 0;
1173 if (!false_nesting)
1174 value = expression_value(&token->next);
1176 // This is an approximation. We really only need this if the
1177 // condition does depends on a pre-processor symbol. Note, that
1178 // the important #ifndef case has already changed ->constant.
1179 if (stream->constant == CONSTANT_FILE_MAYBE)
1180 MARK_STREAM_NONCONST(token->pos);
1182 return preprocessor_if(token, value);
1185 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1187 if (stream->nesting == if_nesting)
1188 MARK_STREAM_NONCONST(token->pos);
1190 if (stream->nesting > if_nesting) {
1191 warning(token->pos, "unmatched #elif");
1192 return 1;
1195 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1196 warning(token->pos, "#elif after #else");
1198 if (false_nesting) {
1199 /* If this whole if-thing is if'ed out, an elif cannot help */
1200 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1201 return 1;
1202 if (expression_value(&token->next)) {
1203 false_nesting = 0;
1204 true_nesting++;
1205 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1207 } else {
1208 false_nesting = 1;
1209 true_nesting--;
1211 return 1;
1214 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1216 if (stream->nesting == if_nesting)
1217 MARK_STREAM_NONCONST(token->pos);
1219 if (stream->nesting > if_nesting) {
1220 warning(token->pos, "unmatched #else");
1221 return 1;
1224 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1225 warning(token->pos, "#else after #else");
1226 else
1227 elif_ignore[if_nesting-1] |= ELIF_SEEN_ELSE;
1229 if (false_nesting) {
1230 /* If this whole if-thing is if'ed out, an else cannot help */
1231 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1232 return 1;
1233 false_nesting = 0;
1234 true_nesting++;
1235 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1236 } else {
1237 true_nesting--;
1238 false_nesting = 1;
1240 return 1;
1243 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1245 if (stream->constant == CONSTANT_FILE_IFNDEF && stream->nesting == if_nesting)
1246 stream->constant = CONSTANT_FILE_MAYBE;
1248 if (stream->nesting > if_nesting)
1249 warning(token->pos, "unmatched #endif");
1250 else if (false_nesting)
1251 false_nesting--;
1252 else
1253 true_nesting--;
1254 return 1;
1257 static const char *show_token_sequence(struct token *token)
1259 static char buffer[1024];
1260 char *ptr = buffer;
1261 int whitespace = 0;
1263 if (!token)
1264 return "<none>";
1265 while (!eof_token(token)) {
1266 const char *val = show_token(token);
1267 int len = strlen(val);
1269 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
1270 warning(token->pos, "too long token expansion");
1271 break;
1274 if (whitespace)
1275 *ptr++ = ' ';
1276 memcpy(ptr, val, len);
1277 ptr += len;
1278 token = token->next;
1279 whitespace = token->pos.whitespace;
1281 *ptr = 0;
1282 return buffer;
1285 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1287 if (false_nesting)
1288 return 1;
1289 if (stream->constant == CONSTANT_FILE_MAYBE)
1290 MARK_STREAM_NONCONST(token->pos);
1291 warning(token->pos, "%s", show_token_sequence(token->next));
1292 return 1;
1295 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1297 if (false_nesting)
1298 return 1;
1299 if (stream->constant == CONSTANT_FILE_MAYBE)
1300 MARK_STREAM_NONCONST(token->pos);
1301 warning(token->pos, "%s", show_token_sequence(token->next));
1302 return 1;
1305 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1307 int stdinc;
1309 if (false_nesting)
1310 return 1;
1313 * Do we have any non-system includes?
1314 * Clear them out if so..
1316 stdinc = gcc_includepath - sys_includepath;
1317 if (stdinc) {
1318 const char **src = gcc_includepath;
1319 const char **dst = sys_includepath;
1320 for (;;) {
1321 if (!(*dst = *src))
1322 break;
1323 dst++;
1324 src++;
1326 gcc_includepath -= stdinc;
1328 return 1;
1331 static void add_path_entry(struct token *token, const char *path)
1333 const char **dst;
1334 const char *next;
1336 /* Need one free entry.. */
1337 if (includepath[INCLUDEPATHS-2])
1338 error_die(token->pos, "too many include path entries");
1340 next = path;
1341 dst = sys_includepath;
1342 sys_includepath++;
1343 gcc_includepath++;
1346 * Move them all up starting at "sys_includepath",
1347 * insert the new entry..
1349 for (;;) {
1350 const char *tmp = *dst;
1351 *dst = next;
1352 if (!next)
1353 break;
1354 next = tmp;
1355 dst++;
1359 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1361 for (;;) {
1362 token = token->next;
1363 if (eof_token(token))
1364 return 1;
1365 if (token_type(token) != TOKEN_STRING) {
1366 warning(token->pos, "expected path string");
1367 return 1;
1369 add_path_entry(token, token->string->data);
1374 * We replace "#pragma xxx" with "__pragma__" in the token
1375 * stream. Just as an example.
1377 * We'll just #define that away for now, but the theory here
1378 * is that we can use this to insert arbitrary token sequences
1379 * to turn the pragma's into internal front-end sequences for
1380 * when we actually start caring about them.
1382 * So eventually this will turn into some kind of extended
1383 * __attribute__() like thing, except called __pragma__(xxx).
1385 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1387 struct token *next = *line;
1389 token->ident = &pragma_ident;
1390 token->pos.newline = 1;
1391 token->pos.whitespace = 1;
1392 token->pos.pos = 1;
1393 *line = token;
1394 token->next = next;
1395 return 1;
1399 * We ignore #line for now.
1401 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1403 return 1;
1407 void init_preprocessor(void)
1409 int i;
1410 int stream = init_stream("preprocessor", -1, includepath);
1411 static struct {
1412 const char *name;
1413 int (*handler)(struct stream *, struct token **, struct token *);
1414 } handlers[] = {
1415 { "define", handle_define },
1416 { "weak_define",handle_weak_define },
1417 { "undef", handle_undef },
1418 { "ifdef", handle_ifdef },
1419 { "ifndef", handle_ifndef },
1420 { "else", handle_else },
1421 { "endif", handle_endif },
1422 { "if", handle_if },
1423 { "elif", handle_elif },
1424 { "warning", handle_warning },
1425 { "error", handle_error },
1426 { "include", handle_include },
1427 { "include_next",handle_include_next },
1428 { "pragma", handle_pragma },
1429 { "line", handle_line },
1431 // our internal preprocessor tokens
1432 { "nostdinc", handle_nostdinc },
1433 { "add_include", handle_add_include },
1436 for (i = 0; i < (sizeof (handlers) / sizeof (handlers[0])); i++) {
1437 struct symbol *sym;
1438 sym = create_symbol(stream, handlers[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1439 sym->handler = handlers[i].handler;
1443 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
1445 struct token *token = start->next;
1447 if (!token)
1448 return;
1450 if (token_type(token) == TOKEN_NUMBER)
1451 if (handle_line(stream, line, start))
1452 return;
1454 if (token_type(token) == TOKEN_IDENT) {
1455 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
1456 if (sym && sym->handler(stream, line, token))
1457 return;
1460 warning(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1463 static void preprocessor_line(struct stream *stream, struct token **line)
1465 struct token *start = *line, *next;
1466 struct token **tp = &start->next;
1468 for (;;) {
1469 next = *tp;
1470 if (next->pos.newline)
1471 break;
1472 tp = &next->next;
1474 *line = next;
1475 *tp = &eof_token_entry;
1476 handle_preprocessor_line(stream, line, start);
1479 static void do_preprocess(struct token **list)
1481 struct token *next;
1483 while (!eof_token(next = scan_next(list))) {
1484 struct stream *stream = input_streams + next->pos.stream;
1486 if (next->pos.newline && match_op(next, '#')) {
1487 if (!next->pos.noexpand) {
1488 preprocessor_line(stream, list);
1489 continue;
1493 switch (token_type(next)) {
1494 case TOKEN_STREAMEND:
1495 if (stream->nesting < if_nesting + 1) {
1496 warning(unmatched_if->pos, "unterminated preprocessor conditional");
1497 // Pretend to see a series of #endifs
1498 MARK_STREAM_NONCONST(next->pos);
1499 do {
1500 handle_endif (stream, NULL, NULL);
1501 } while (stream->nesting < if_nesting + 1);
1503 if (stream->constant == CONSTANT_FILE_MAYBE && stream->protect) {
1504 stream->constant = CONSTANT_FILE_YES;
1506 *list = next->next;
1507 continue;
1508 case TOKEN_STREAMBEGIN:
1509 stream->nesting = if_nesting + 1;
1510 *list = next->next;
1511 continue;
1513 default:
1514 if (false_nesting) {
1515 *list = next->next;
1516 continue;
1519 if (token_type(next) != TOKEN_IDENT ||
1520 expand_one_symbol(list))
1521 list = &next->next;
1524 if (stream->constant == CONSTANT_FILE_MAYBE) {
1526 * Any token expansion (even if it ended up being an
1527 * empty expansion) in this stream implies it can't
1528 * be constant.
1530 MARK_STREAM_NONCONST(next->pos);
1535 struct token * preprocess(struct token *token)
1537 preprocessing = 1;
1538 init_preprocessor();
1539 do_preprocess(&token);
1541 // Drop all expressions from pre-processing, they're not used any more.
1542 clear_expression_alloc();
1543 preprocessing = 0;
1545 return token;