Handle tokenized include-filename with angle brackets.
[smatch.git] / pre-process.c
blob972da27021861915ff71270f2f42d7e875985f4c
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 #define MAX_NEST (256)
33 static int true_nesting = 0;
34 static int false_nesting = 0;
35 static struct token *unmatched_if = NULL;
36 static char elif_ignore[MAX_NEST];
37 #define if_nesting (true_nesting + false_nesting)
39 #define INCLUDEPATHS 32
40 const char *includepath[INCLUDEPATHS+1] = {
41 NULL
44 const char *sys_includepath[] = {
45 "/usr/include",
46 "/usr/local/include",
47 NULL,
50 const char *gcc_includepath[] = {
51 GCC_INTERNAL_INCLUDE,
52 NULL
57 * This is stupid - the tokenizer already guarantees unique
58 * identifiers, so we should just compare identifier pointers
60 int match_string_ident(struct ident *ident, const char *str)
62 return !str[ident->len] && !memcmp(str, ident->name, ident->len);
65 static struct token *alloc_token(struct position *pos)
67 struct token *token = __alloc_token(0);
69 token->pos.stream = pos->stream;
70 token->pos.line = pos->line;
71 token->pos.pos = pos->pos;
72 token->pos.whitespace = 1;
73 return token;
76 static const char *show_token_sequence(struct token *token);
78 /* Expand symbol 'sym' at '*list' */
79 static struct token **expand(struct token **, struct symbol *);
81 static void replace_with_string(struct token *token, const char *str)
83 int size = strlen(str) + 1;
84 struct string *s = __alloc_string(size);
86 s->length = size;
87 memcpy(s->data, str, size);
88 token_type(token) = TOKEN_STRING;
89 token->string = s;
92 static void replace_with_integer(struct token *token, unsigned int val)
94 char *buf = __alloc_bytes(10);
95 sprintf(buf, "%d", val);
96 token_type(token) = TOKEN_NUMBER;
97 token->number = buf;
100 static void replace_with_defined(struct token *token)
102 char *string[] = { "0", "1" };
103 int defined = 0;
104 if (token_type(token) != TOKEN_IDENT)
105 warn(token->pos, "operator \"defined\" requires an identifier");
106 else if (lookup_symbol(token->ident, NS_PREPROCESSOR))
107 defined = 1;
108 token_type(token) = TOKEN_NUMBER;
109 token->number = string[defined];
112 struct token **expand_one_symbol(struct token **list)
114 struct token *token = *list;
115 struct symbol *sym;
117 if (token->pos.noexpand)
118 return &token->next;
120 sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
121 if (sym)
122 return expand(list, sym);
123 if (token->ident == &__LINE___ident) {
124 replace_with_integer(token, token->pos.line);
125 } else if (token->ident == &__FILE___ident) {
126 replace_with_string(token, (input_streams + token->pos.stream)->name);
128 return &token->next;
131 static inline struct token *scan_next(struct token **where)
133 struct token *token = *where;
134 if (token_type(token) != TOKEN_UNTAINT)
135 return token;
136 do {
137 token->ident->tainted = 0;
138 token = token->next;
139 } while (token_type(token) == TOKEN_UNTAINT);
140 *where = token;
141 return token;
144 static struct token **expand_list(struct token **list)
146 struct token *next;
147 while (!eof_token(next = scan_next(list))) {
148 if (token_type(next) == TOKEN_IDENT)
149 list = expand_one_symbol(list);
150 else
151 list = &next->next;
153 return list;
156 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
158 struct token **p = &prev->next;
159 struct token *next;
160 int nesting = 0;
162 while (!eof_token(next = scan_next(p))) {
163 if (match_op(next, '(')) {
164 nesting++;
165 } else if (match_op(next, ')')) {
166 if (!nesting--)
167 break;
168 } else if (match_op(next, ',') && !nesting && !vararg) {
169 break;
171 next->pos.stream = pos->stream;
172 next->pos.line = pos->line;
173 next->pos.pos = pos->pos;
174 p = &next->next;
176 *p = &eof_token_entry;
177 return next;
181 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
184 struct arg {
185 struct token *arg;
186 struct token *expanded;
187 struct token *str;
188 int n_normal;
189 int n_quoted;
190 int n_str;
193 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
195 int wanted = arglist->count.normal;
196 struct token *next = NULL;
197 int count = 0;
199 arglist = arglist->next; /* skip counter */
201 if (!wanted) {
202 next = collect_arg(start, 0, &what->pos);
203 if (eof_token(next))
204 goto Eclosing;
205 if (!eof_token(start->next) || !match_op(next, ')')) {
206 count++;
207 goto Emany;
209 } else {
210 for (count = 0; count < wanted; count++) {
211 struct argcount *p = &arglist->next->count;
212 next = collect_arg(start, p->vararg, &what->pos);
213 arglist = arglist->next->next;
214 if (eof_token(next))
215 goto Eclosing;
216 args[count].arg = start->next;
217 args[count].n_normal = p->normal;
218 args[count].n_quoted = p->quoted;
219 args[count].n_str = p->str;
220 if (match_op(next, ')')) {
221 count++;
222 break;
224 start = next;
226 if (count == wanted && !match_op(next, ')'))
227 goto Emany;
228 if (count == wanted - 1) {
229 struct argcount *p = &arglist->next->count;
230 if (!p->vararg)
231 goto Efew;
232 args[count].arg = NULL;
233 args[count].n_normal = p->normal;
234 args[count].n_quoted = p->quoted;
235 args[count].n_str = p->str;
237 if (count < wanted - 1)
238 goto Efew;
240 what->next = next->next;
241 return 1;
243 Efew:
244 warn(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
245 show_token(what), wanted, count);
246 goto out;
247 Emany:
248 while (match_op(next, ',')) {
249 next = collect_arg(next, 0, &what->pos);
250 count++;
252 if (eof_token(next))
253 goto Eclosing;
254 warn(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
255 show_token(what), count, wanted);
256 goto out;
257 Eclosing:
258 warn(what->pos, "unterminated argument list invoking macro \"%s\"",
259 show_token(what));
260 out:
261 what->next = next->next;
262 return 0;
265 static struct token *dup_list(struct token *list)
267 struct token *res;
268 struct token **p = &res;
270 while (!eof_token(list)) {
271 struct token *newtok = __alloc_token(0);
272 *newtok = *list;
273 *p = newtok;
274 p = &newtok->next;
275 list = list->next;
277 return res;
280 static struct token *stringify(struct token *arg)
282 const char *s = show_token_sequence(arg);
283 int size = strlen(s)+1;
284 struct token *token = __alloc_token(0);
285 struct string *string = __alloc_string(size);
287 memcpy(string->data, s, size);
288 string->length = size;
289 token->pos = arg->pos;
290 token_type(token) = TOKEN_STRING;
291 token->string = string;
292 token->next = &eof_token_entry;
293 return token;
296 static void expand_arguments(int count, struct arg *args)
298 int i;
299 for (i = 0; i < count; i++) {
300 struct token *arg = args[i].arg;
301 if (!arg)
302 arg = &eof_token_entry;
303 if (args[i].n_str)
304 args[i].str = stringify(arg);
305 if (args[i].n_normal) {
306 if (!args[i].n_quoted) {
307 args[i].expanded = arg;
308 args[i].arg = NULL;
309 } else if (eof_token(arg)) {
310 args[i].expanded = arg;
311 } else {
312 args[i].expanded = dup_list(arg);
314 expand_list(&args[i].expanded);
320 * Possibly valid combinations:
321 * - ident + ident -> ident
322 * - ident + number -> ident unless number contains '.', '+' or '-'.
323 * - number + number -> number
324 * - number + ident -> number
325 * - number + '.' -> number
326 * - number + '+' or '-' -> number, if number used to end on [eEpP].
327 * - '.' + number -> number, if number used to start with a digit.
328 * - special + special -> either special or an error.
330 static enum token_type combine(struct token *left, struct token *right, char *p)
332 int len;
333 enum token_type t1 = token_type(left), t2 = token_type(right);
335 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
336 return TOKEN_ERROR;
338 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
339 return TOKEN_ERROR;
341 strcpy(p, show_token(left));
342 strcat(p, show_token(right));
343 len = strlen(p);
345 if (len >= 256)
346 return TOKEN_ERROR;
348 if (t1 == TOKEN_IDENT) {
349 if (t2 == TOKEN_SPECIAL)
350 return TOKEN_ERROR;
351 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
352 return TOKEN_ERROR;
353 return TOKEN_IDENT;
356 if (t1 == TOKEN_NUMBER) {
357 if (t2 == TOKEN_SPECIAL) {
358 switch (right->special) {
359 case '.':
360 break;
361 case '+': case '-':
362 if (strchr("eEpP", p[len - 2]))
363 break;
364 default:
365 return TOKEN_ERROR;
368 return TOKEN_NUMBER;
371 if (p[0] == '.' && isdigit(p[1]))
372 return TOKEN_NUMBER;
374 return TOKEN_SPECIAL;
377 static int merge(struct token *left, struct token *right)
379 extern unsigned char combinations[][3];
380 static char buffer[512];
381 int n;
383 switch (combine(left, right, buffer)) {
384 case TOKEN_IDENT:
385 left->ident = built_in_ident(buffer);
386 left->pos.noexpand = 0;
387 return 1;
389 case TOKEN_NUMBER:
390 token_type(left) = TOKEN_NUMBER; /* could be . + num */
391 left->number = __alloc_bytes(strlen(buffer) + 1);
392 memcpy(left->number, buffer, strlen(buffer) + 1);
393 return 1;
395 case TOKEN_SPECIAL:
396 if (buffer[2] && buffer[3])
397 break;
398 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
399 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
400 left->special = n;
401 return 1;
404 default:
407 warn(left->pos, "'##' failed: concatenation is not a valid token");
408 return 0;
411 static struct token *dup_token(struct token *token, struct position *streampos, struct position *pos)
413 struct token *alloc = alloc_token(streampos);
414 token_type(alloc) = token_type(token);
415 alloc->pos.newline = pos->newline;
416 alloc->pos.whitespace = pos->whitespace;
417 alloc->number = token->number;
418 alloc->pos.noexpand = token->pos.noexpand;
419 return alloc;
422 static struct token **copy(struct token **where, struct token *list, int *count)
424 int need_copy = --*count;
425 while (!eof_token(list)) {
426 struct token *token;
427 if (need_copy)
428 token = dup_token(list, &list->pos, &list->pos);
429 else
430 token = list;
431 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
432 token->pos.noexpand = 1;
433 *where = token;
434 where = &token->next;
435 list = list->next;
437 *where = &eof_token_entry;
438 return where;
441 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
443 struct token *token = *list;
444 struct position *base_pos = &token->pos;
445 struct position *pos = base_pos;
446 int *count;
447 enum {Normal, Placeholder, Concat} state = Normal;
449 for (; !eof_token(body); body = body->next, pos = &body->pos) {
450 struct token *added, *arg;
451 struct token **tail;
453 switch (token_type(body)) {
454 case TOKEN_GNU_KLUDGE:
456 * GNU kludge: if we had <comma>##<vararg>, behaviour
457 * depends on whether we had enough arguments to have
458 * a vararg. If we did, ## is just ignored. Otherwise
459 * both , and ## are ignored. Comma should come from
460 * the body of macro and not be an argument of earlier
461 * concatenation.
463 if (!args[body->next->argnum].arg)
464 continue;
465 added = dup_token(body, base_pos, pos);
466 token_type(added) = TOKEN_SPECIAL;
467 tail = &added->next;
468 break;
470 case TOKEN_STR_ARGUMENT:
471 arg = args[body->argnum].str;
472 count = &args[body->argnum].n_str;
473 goto copy_arg;
475 case TOKEN_QUOTED_ARGUMENT:
476 arg = args[body->argnum].arg;
477 count = &args[body->argnum].n_quoted;
478 if (!arg || eof_token(arg)) {
479 if (state == Concat)
480 state = Normal;
481 else
482 state = Placeholder;
483 continue;
485 goto copy_arg;
487 case TOKEN_MACRO_ARGUMENT:
488 arg = args[body->argnum].expanded;
489 count = &args[body->argnum].n_normal;
490 if (eof_token(arg)) {
491 state = Normal;
492 continue;
494 copy_arg:
495 tail = copy(&added, arg, count);
496 added->pos.newline = pos->newline;
497 added->pos.whitespace = pos->whitespace;
498 break;
500 case TOKEN_CONCAT:
501 if (state == Placeholder)
502 state = Normal;
503 else
504 state = Concat;
505 continue;
507 case TOKEN_IDENT:
508 added = dup_token(body, base_pos, pos);
509 if (added->ident->tainted)
510 added->pos.noexpand = 1;
511 tail = &added->next;
512 break;
514 default:
515 added = dup_token(body, base_pos, pos);
516 tail = &added->next;
517 break;
521 * if we got to doing real concatenation, we already have
522 * added something into the list, so containing_token() is OK.
524 if (state == Concat && merge(containing_token(list), added)) {
525 *list = added->next;
526 if (tail != &added->next)
527 list = tail;
528 } else {
529 *list = added;
530 list = tail;
532 state = Normal;
534 *list = &eof_token_entry;
535 return list;
538 static struct token **expand(struct token **list, struct symbol *sym)
540 struct token *last;
541 struct token *token = *list;
542 struct ident *expanding = token->ident;
543 struct token **tail;
544 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
545 struct arg args[nargs];
547 if (expanding->tainted) {
548 token->pos.noexpand = 1;
549 return &token->next;
552 if (sym->arglist) {
553 if (!match_op(scan_next(&token->next), '('))
554 return &token->next;
555 if (!collect_arguments(token->next, sym->arglist, args, token))
556 return &token->next;
557 expand_arguments(nargs, args);
560 expanding->tainted = 1;
562 last = token->next;
563 tail = substitute(list, sym->expansion, args);
564 *tail = last;
566 return list;
569 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
571 struct token *last;
572 static char buffer[256];
573 char *ptr = buffer;
575 last = token;
576 while (!eof_token(token) && !match_op(token, endop)) {
577 int len;
578 const char *val = token->string->data;
579 if (token_type(token) != TOKEN_STRING)
580 val = show_token(token);
581 len = strlen(val);
582 memcpy(ptr, val, len);
583 ptr += len;
584 token = token->next;
586 *ptr = 0;
587 if (endop && !match_op(token, endop))
588 warn(start->pos, "expected '>' at end of filename");
589 return buffer;
592 static int try_include(const char *path, int plen, const char *filename, int flen, struct token **where)
594 int fd;
595 static char fullname[PATH_MAX];
597 memcpy(fullname, path, plen);
598 if (plen && path[plen-1] != '/') {
599 fullname[plen] = '/';
600 plen++;
602 memcpy(fullname+plen, filename, flen);
603 fd = open(fullname, O_RDONLY);
604 if (fd >= 0) {
605 char * streamname = __alloc_bytes(plen + flen);
606 memcpy(streamname, fullname, plen + flen);
607 *where = tokenize(streamname, fd, *where);
608 close(fd);
609 return 1;
611 return 0;
614 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
616 const char *path;
618 while ((path = *pptr++) != NULL) {
619 if (!try_include(path, strlen(path), filename, flen, list))
620 continue;
621 return 1;
623 return 0;
627 static void do_include(int local, struct stream *stream, struct token **list, struct token *token, const char *filename)
629 int flen = strlen(filename) + 1;
631 /* Same directory as current stream? */
632 if (local) {
633 const char *path;
634 char *slash;
635 int plen;
637 path = stream->name;
638 slash = strrchr(path, '/');
639 plen = slash ? slash - path : 0;
641 if (try_include(path, plen, filename, flen, list))
642 return;
645 /* Check the standard include paths.. */
646 if (do_include_path(includepath, list, token, filename, flen))
647 return;
648 if (do_include_path(sys_includepath, list, token, filename, flen))
649 return;
650 if (do_include_path(gcc_includepath, list, token, filename, flen))
651 return;
653 error(token->pos, "unable to open '%s'", filename);
656 static int handle_include(struct stream *stream, struct token **list, struct token *token)
658 const char *filename;
659 struct token *next;
660 int expect;
662 if (stream->constant == -1)
663 stream->constant = 0;
664 if (false_nesting)
665 return 1;
666 next = token->next;
667 expect = '>';
668 if (!match_op(next, '<')) {
669 expand_list(&token->next);
670 expect = 0;
671 next = token;
672 if (match_op(token->next, '<')) {
673 next = token->next;
674 expect = '>';
677 token = next->next;
678 filename = token_name_sequence(token, expect, token);
679 do_include(!expect, stream, list, token, filename);
680 return 1;
683 static int token_different(struct token *t1, struct token *t2)
685 int different;
687 if (token_type(t1) != token_type(t2))
688 return 1;
690 switch (token_type(t1)) {
691 case TOKEN_IDENT:
692 different = t1->ident != t2->ident;
693 break;
694 case TOKEN_ARG_COUNT:
695 case TOKEN_UNTAINT:
696 case TOKEN_CONCAT:
697 case TOKEN_GNU_KLUDGE:
698 different = 0;
699 break;
700 case TOKEN_NUMBER:
701 different = strcmp(t1->number, t2->number);
702 break;
703 case TOKEN_SPECIAL:
704 different = t1->special != t2->special;
705 break;
706 case TOKEN_MACRO_ARGUMENT:
707 case TOKEN_QUOTED_ARGUMENT:
708 case TOKEN_STR_ARGUMENT:
709 different = t1->argnum != t2->argnum;
710 break;
711 case TOKEN_CHAR:
712 different = t1->character != t2->character;
713 break;
714 case TOKEN_STRING: {
715 struct string *s1, *s2;
717 s1 = t1->string;
718 s2 = t2->string;
719 different = 1;
720 if (s1->length != s2->length)
721 break;
722 different = memcmp(s1->data, s2->data, s1->length);
723 break;
725 default:
726 different = 1;
727 break;
729 return different;
732 static int token_list_different(struct token *list1, struct token *list2)
734 for (;;) {
735 if (list1 == list2)
736 return 0;
737 if (!list1 || !list2)
738 return 1;
739 if (token_different(list1, list2))
740 return 1;
741 list1 = list1->next;
742 list2 = list2->next;
746 static inline void set_arg_count(struct token *token)
748 token_type(token) = TOKEN_ARG_COUNT;
749 token->count.normal = token->count.quoted =
750 token->count.str = token->count.vararg = 0;
753 static struct token *parse_arguments(struct token *list)
755 struct token *arg = list->next, *next = list;
756 struct argcount *count = &list->count;
758 set_arg_count(list);
760 if (match_op(arg, ')')) {
761 next = arg->next;
762 list->next = &eof_token_entry;
763 return next;
766 while (token_type(arg) == TOKEN_IDENT) {
767 if (arg->ident == &__VA_ARGS___ident)
768 goto Eva_args;
769 if (!++count->normal)
770 goto Eargs;
771 next = arg->next;
773 if (match_op(next, ',')) {
774 set_arg_count(next);
775 arg = next->next;
776 continue;
779 if (match_op(next, ')')) {
780 set_arg_count(next);
781 next = next->next;
782 arg->next->next = &eof_token_entry;
783 return next;
786 /* normal cases are finished here */
788 if (match_op(next, SPECIAL_ELLIPSIS)) {
789 if (match_op(next->next, ')')) {
790 set_arg_count(next);
791 next->count.vararg = 1;
792 next = next->next;
793 arg->next->next = &eof_token_entry;
794 return next->next;
797 arg = next;
798 goto Enotclosed;
801 if (eof_token(next)) {
802 goto Enotclosed;
803 } else {
804 arg = next;
805 goto Ebadstuff;
809 if (match_op(arg, SPECIAL_ELLIPSIS)) {
810 next = arg->next;
811 token_type(arg) = TOKEN_IDENT;
812 arg->ident = &__VA_ARGS___ident;
813 if (!match_op(next, ')'))
814 goto Enotclosed;
815 if (!++count->normal)
816 goto Eargs;
817 set_arg_count(next);
818 next->count.vararg = 1;
819 next = next->next;
820 arg->next->next = &eof_token_entry;
821 return next;
824 if (eof_token(arg)) {
825 arg = next;
826 goto Enotclosed;
828 if (match_op(arg, ','))
829 goto Emissing;
830 else
831 goto Ebadstuff;
834 Emissing:
835 warn(arg->pos, "parameter name missing");
836 return NULL;
837 Ebadstuff:
838 warn(arg->pos, "\"%s\" may not appear in macro parameter list",
839 show_token(arg));
840 return NULL;
841 Enotclosed:
842 warn(arg->pos, "missing ')' in macro parameter list");
843 return NULL;
844 Eva_args:
845 warn(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
846 return NULL;
847 Eargs:
848 warn(arg->pos, "too many arguments in macro definition");
849 return NULL;
852 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
854 struct ident *ident = token->ident;
855 int nr;
857 if (!arglist || token_type(token) != TOKEN_IDENT)
858 return 0;
860 arglist = arglist->next;
862 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
863 if (arglist->ident == ident) {
864 struct argcount *count = &arglist->next->count;
865 int n;
867 token->argnum = nr;
868 token_type(token) = type;
869 switch (type) {
870 case TOKEN_MACRO_ARGUMENT:
871 n = ++count->normal;
872 break;
873 case TOKEN_QUOTED_ARGUMENT:
874 n = ++count->quoted;
875 break;
876 default:
877 n = ++count->str;
879 if (n)
880 return count->vararg ? 2 : 1;
881 token_type(token) = TOKEN_ERROR;
882 return -1;
885 return 0;
888 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
890 struct token *token = expansion;
891 struct token **p;
892 struct token *last = NULL;
894 if (match_op(token, SPECIAL_HASHHASH))
895 goto Econcat;
897 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
898 if (match_op(token, '#')) {
899 if (arglist) {
900 struct token *next = token->next;
901 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
902 goto Equote;
903 next->pos.whitespace = token->pos.whitespace;
904 token = *p = next;
905 } else {
906 token->pos.noexpand = 1;
908 } else if (match_op(token, SPECIAL_HASHHASH)) {
909 struct token *next = token->next;
910 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
911 token_type(token) = TOKEN_CONCAT;
912 if (arg) {
913 token = next;
914 /* GNU kludge */
915 if (arg == 2 && last && match_op(last, ',')) {
916 token_type(last) = TOKEN_GNU_KLUDGE;
917 last->next = token;
919 } else if (match_op(next, SPECIAL_HASHHASH))
920 token = next;
921 else if (match_op(next, ','))
922 token = next;
923 else if (eof_token(next))
924 goto Econcat;
925 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
926 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
927 } else {
928 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
930 if (token_type(token) == TOKEN_ERROR)
931 goto Earg;
932 last = token;
934 token = alloc_token(&expansion->pos);
935 token_type(token) = TOKEN_UNTAINT;
936 token->ident = name;
937 token->next = *p;
938 *p = token;
939 return expansion;
941 Equote:
942 warn(token->pos, "'#' is not followed by a macro parameter");
943 return NULL;
945 Econcat:
946 warn(token->pos, "'##' cannot appear at the ends of macro expansion");
947 return NULL;
948 Earg:
949 warn(token->pos, "too many instances of argument in body");
950 return NULL;
953 static int handle_define(struct stream *stream, struct token **line, struct token *token)
955 struct token *arglist, *expansion;
956 struct token *left = token->next;
957 struct symbol *sym;
958 struct ident *name;
960 if (token_type(left) != TOKEN_IDENT) {
961 warn(token->pos, "expected identifier to 'define'");
962 return 0;
964 if (false_nesting)
965 return 1;
966 name = left->ident;
968 arglist = NULL;
969 expansion = left->next;
970 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
971 arglist = expansion;
972 expansion = parse_arguments(expansion);
973 if (!expansion)
974 return 1;
977 expansion = parse_expansion(expansion, arglist, name);
978 if (!expansion)
979 return 1;
981 sym = lookup_symbol(name, NS_PREPROCESSOR);
982 if (sym) {
983 if (token_list_different(sym->expansion, expansion) ||
984 token_list_different(sym->arglist, arglist)) {
985 warn(left->pos, "preprocessor token %.*s redefined",
986 name->len, name->name);
987 info(sym->pos, "this was the original definition");
989 return 1;
991 sym = alloc_symbol(left->pos, SYM_NODE);
992 bind_symbol(sym, name, NS_PREPROCESSOR);
994 sym->expansion = expansion;
995 sym->arglist = arglist;
996 return 1;
999 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1001 struct token *left = token->next;
1002 struct symbol **sym;
1004 if (token_type(left) != TOKEN_IDENT) {
1005 warn(token->pos, "expected identifier to 'undef'");
1006 return 0;
1008 if (false_nesting)
1009 return 1;
1010 sym = &left->ident->symbols;
1011 while (*sym) {
1012 struct symbol *t = *sym;
1013 if (t->namespace == NS_PREPROCESSOR) {
1014 *sym = t->next_id;
1015 return 1;
1017 sym = &t->next_id;
1019 return 1;
1022 static int preprocessor_if(struct token *token, int true)
1024 if (if_nesting == 0)
1025 unmatched_if = token;
1026 if (if_nesting >= MAX_NEST)
1027 error(token->pos, "Maximum preprocessor conditional level exhausted");
1028 elif_ignore[if_nesting] = false_nesting || true;
1029 if (false_nesting || !true) {
1030 false_nesting++;
1031 return 1;
1033 true_nesting++;
1034 return 1;
1037 static int token_defined(struct token *token)
1039 if (token_type(token) == TOKEN_IDENT)
1040 return lookup_symbol(token->ident, NS_PREPROCESSOR) != NULL;
1042 warn(token->pos, "expected identifier for #if[n]def");
1043 return 0;
1046 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1048 return preprocessor_if(token, token_defined(token->next));
1051 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1053 struct token *next = token->next;
1054 if (stream->constant == -1) {
1055 int newconstant = 0;
1056 if (token_type(next) == TOKEN_IDENT) {
1057 if (!stream->protect || stream->protect == next->ident) {
1058 newconstant = -2;
1059 stream->protect = next->ident;
1060 stream->nesting = if_nesting+1;
1063 stream->constant = newconstant;
1065 return preprocessor_if(token, !token_defined(next));
1069 * Expression handling for #if and #elif; it differs from normal expansion
1070 * due to special treatment of "defined".
1072 static int expression_value(struct token **where)
1074 struct expression *expr;
1075 struct token *p;
1076 struct token **list = where, **beginning = NULL;
1077 long long value;
1078 int state = 0;
1080 while (!eof_token(p = scan_next(list))) {
1081 switch (state) {
1082 case 0:
1083 if (token_type(p) == TOKEN_IDENT) {
1084 if (p->ident != &defined_ident) {
1085 list = expand_one_symbol(list);
1086 continue;
1088 state = 1;
1089 beginning = list;
1091 break;
1092 case 1:
1093 if (match_op(p, '(')) {
1094 state = 2;
1095 } else {
1096 state = 0;
1097 replace_with_defined(p);
1098 *beginning = p;
1100 break;
1101 case 2:
1102 if (token_type(p) == TOKEN_IDENT)
1103 state = 3;
1104 else
1105 state = 0;
1106 replace_with_defined(p);
1107 *beginning = p;
1108 break;
1109 case 3:
1110 state = 0;
1111 if (!match_op(p, ')'))
1112 warn(p->pos, "missing ')' after \"defined\"");
1113 *list = p->next;
1114 continue;
1116 list = &p->next;
1119 p = constant_expression(*where, &expr);
1120 if (!eof_token(p))
1121 warn(p->pos, "garbage at end: %s", show_token_sequence(p));
1122 value = get_expression_value(expr);
1123 return value != 0;
1126 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1128 int value = 0;
1129 if (!false_nesting)
1130 value = expression_value(&token->next);
1131 return preprocessor_if(token, value);
1134 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1136 if (stream->nesting == if_nesting)
1137 stream->constant = 0;
1138 if (false_nesting) {
1139 /* If this whole if-thing is if'ed out, an elif cannot help */
1140 if (elif_ignore[if_nesting-1])
1141 return 1;
1142 if (expression_value(&token->next)) {
1143 false_nesting--;
1144 true_nesting++;
1145 elif_ignore[if_nesting-1] = 1;
1147 return 1;
1149 if (true_nesting) {
1150 false_nesting = 1;
1151 true_nesting--;
1152 return 1;
1154 warn(token->pos, "unmatched '#elif'");
1155 return 1;
1158 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1160 if (stream->nesting == if_nesting)
1161 stream->constant = 0;
1162 if (false_nesting) {
1163 /* If this whole if-thing is if'ed out, an else cannot help */
1164 if (elif_ignore[if_nesting-1])
1165 return 1;
1166 false_nesting--;
1167 true_nesting++;
1168 elif_ignore[if_nesting-1] = 1;
1169 return 1;
1171 if (true_nesting) {
1172 true_nesting--;
1173 false_nesting = 1;
1174 return 1;
1176 warn(token->pos, "unmatched #else");
1177 return 1;
1180 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1182 if (stream->constant == -2 && stream->nesting == if_nesting)
1183 stream->constant = -1;
1185 if (false_nesting) {
1186 false_nesting--;
1187 return 1;
1189 if (true_nesting) {
1190 true_nesting--;
1191 return 1;
1193 warn(token->pos, "unmatched #endif");
1194 return 1;
1197 static const char *show_token_sequence(struct token *token)
1199 static char buffer[1024];
1200 char *ptr = buffer;
1201 int whitespace = 0;
1203 if (!token)
1204 return "<none>";
1205 while (!eof_token(token)) {
1206 const char *val = show_token(token);
1207 int len = strlen(val);
1209 if (ptr + whitespace + len > buffer + sizeof(buffer)) {
1210 warn(token->pos, "too long token expansion");
1211 break;
1214 if (whitespace)
1215 *ptr++ = ' ';
1216 memcpy(ptr, val, len);
1217 ptr += len;
1218 token = token->next;
1219 whitespace = token->pos.whitespace;
1221 *ptr = 0;
1222 return buffer;
1225 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1227 if (false_nesting)
1228 return 1;
1229 warn(token->pos, "%s", show_token_sequence(token->next));
1230 return 1;
1233 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1235 if (false_nesting)
1236 return 1;
1237 warn(token->pos, "%s", show_token_sequence(token->next));
1238 return 1;
1241 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1243 if (false_nesting)
1244 return 1;
1245 includepath[0] = NULL;
1246 return 1;
1249 static void add_path_entry(struct token *token, const char *path)
1251 int i;
1253 for (i = 0; i < INCLUDEPATHS; i++) {
1254 if (!includepath[i]) {
1255 includepath[i] = path;
1256 includepath[i+1] = NULL;
1257 return;
1260 warn(token->pos, "too many include path entries");
1263 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1265 for (;;) {
1266 token = token->next;
1267 if (eof_token(token))
1268 return 1;
1269 if (token_type(token) != TOKEN_STRING) {
1270 warn(token->pos, "expected path string");
1271 return 1;
1273 add_path_entry(token, token->string->data);
1278 * We replace "#pragma xxx" with "__pragma__" in the token
1279 * stream. Just as an example.
1281 * We'll just #define that away for now, but the theory here
1282 * is that we can use this to insert arbitrary token sequences
1283 * to turn the pragma's into internal front-end sequences for
1284 * when we actually start caring about them.
1286 * So eventually this will turn into some kind of extended
1287 * __attribute__() like thing, except called __pragma__(xxx).
1289 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1291 struct token *next = *line;
1293 token->ident = &pragma_ident;
1294 token->pos.newline = 1;
1295 token->pos.whitespace = 1;
1296 token->pos.pos = 1;
1297 *line = token;
1298 token->next = next;
1299 return 1;
1302 static int handle_preprocessor_command(struct stream *stream, struct token **line, struct ident *ident, struct token *token)
1304 int i;
1305 static struct {
1306 const char *name;
1307 int (*handler)(struct stream *, struct token **, struct token *);
1308 } handlers[] = {
1309 { "define", handle_define },
1310 { "undef", handle_undef },
1311 { "ifdef", handle_ifdef },
1312 { "ifndef", handle_ifndef },
1313 { "else", handle_else },
1314 { "endif", handle_endif },
1315 { "if", handle_if },
1316 { "elif", handle_elif },
1317 { "warning", handle_warning },
1318 { "error", handle_error },
1319 { "include", handle_include },
1320 { "pragma", handle_pragma },
1322 // our internal preprocessor tokens
1323 { "nostdinc", handle_nostdinc },
1324 { "add_include", handle_add_include },
1327 for (i = 0; i < (sizeof (handlers) / sizeof (handlers[0])); i++) {
1328 if (match_string_ident(ident, handlers[i].name))
1329 return handlers[i].handler(stream, line, token);
1331 return 0;
1334 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *token)
1336 if (!token)
1337 return;
1339 if (token_type(token) == TOKEN_IDENT)
1340 if (handle_preprocessor_command(stream, line, token->ident, token))
1341 return;
1342 warn(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1345 static void preprocessor_line(struct stream *stream, struct token **line)
1347 struct token *start = *line, *next;
1348 struct token **tp = &start->next;
1350 for (;;) {
1351 next = *tp;
1352 if (next->pos.newline)
1353 break;
1354 tp = &next->next;
1356 *line = next;
1357 *tp = &eof_token_entry;
1358 handle_preprocessor_line(stream, line, start->next);
1361 static void do_preprocess(struct token **list)
1363 struct token *next;
1365 while (!eof_token(next = scan_next(list))) {
1366 struct stream *stream = input_streams + next->pos.stream;
1368 if (next->pos.newline && match_op(next, '#')) {
1369 if (!next->pos.noexpand) {
1370 preprocessor_line(stream, list);
1371 continue;
1375 if (false_nesting) {
1376 *list = next->next;
1377 continue;
1380 switch (token_type(next)) {
1381 case TOKEN_STREAMEND:
1382 if (stream->constant == -1 && stream->protect) {
1383 stream->constant = 1;
1385 /* fallthrough */
1386 case TOKEN_STREAMBEGIN:
1387 *list = next->next;
1388 continue;
1390 case TOKEN_IDENT:
1391 list = expand_one_symbol(list);
1392 break;
1393 default:
1394 list = &next->next;
1397 * Any token expansion (even if it ended up being an
1398 * empty expansion) in this stream implies it can't
1399 * be constant.
1401 stream->constant = 0;
1405 struct token * preprocess(struct token *token)
1407 preprocessing = 1;
1408 do_preprocess(&token);
1409 if (if_nesting)
1410 warn(unmatched_if->pos, "unmatched preprocessor conditional");
1412 // Drop all expressions from pre-processing, they're not used any more.
1413 clear_expression_alloc();
1414 preprocessing = 0;
1416 return token;