If int/long are the same size, an int that overflows into
[smatch.git] / pre-process.c
blobe5750c2eadf84ff7a08cf365a6dc0500a34f0387
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;
673 token = next->next;
674 filename = token_name_sequence(token, expect, token);
675 do_include(!expect, stream, list, token, filename);
676 return 1;
679 static int token_different(struct token *t1, struct token *t2)
681 int different;
683 if (token_type(t1) != token_type(t2))
684 return 1;
686 switch (token_type(t1)) {
687 case TOKEN_IDENT:
688 different = t1->ident != t2->ident;
689 break;
690 case TOKEN_ARG_COUNT:
691 case TOKEN_UNTAINT:
692 case TOKEN_CONCAT:
693 case TOKEN_GNU_KLUDGE:
694 different = 0;
695 break;
696 case TOKEN_NUMBER:
697 different = strcmp(t1->number, t2->number);
698 break;
699 case TOKEN_SPECIAL:
700 different = t1->special != t2->special;
701 break;
702 case TOKEN_MACRO_ARGUMENT:
703 case TOKEN_QUOTED_ARGUMENT:
704 case TOKEN_STR_ARGUMENT:
705 different = t1->argnum != t2->argnum;
706 break;
707 case TOKEN_CHAR:
708 different = t1->character != t2->character;
709 break;
710 case TOKEN_STRING: {
711 struct string *s1, *s2;
713 s1 = t1->string;
714 s2 = t2->string;
715 different = 1;
716 if (s1->length != s2->length)
717 break;
718 different = memcmp(s1->data, s2->data, s1->length);
719 break;
721 default:
722 different = 1;
723 break;
725 return different;
728 static int token_list_different(struct token *list1, struct token *list2)
730 for (;;) {
731 if (list1 == list2)
732 return 0;
733 if (!list1 || !list2)
734 return 1;
735 if (token_different(list1, list2))
736 return 1;
737 list1 = list1->next;
738 list2 = list2->next;
742 static inline void set_arg_count(struct token *token)
744 token_type(token) = TOKEN_ARG_COUNT;
745 token->count.normal = token->count.quoted =
746 token->count.str = token->count.vararg = 0;
749 static struct token *parse_arguments(struct token *list)
751 struct token *arg = list->next, *next = list;
752 struct argcount *count = &list->count;
754 set_arg_count(list);
756 if (match_op(arg, ')')) {
757 next = arg->next;
758 list->next = &eof_token_entry;
759 return next;
762 while (token_type(arg) == TOKEN_IDENT) {
763 if (arg->ident == &__VA_ARGS___ident)
764 goto Eva_args;
765 if (!++count->normal)
766 goto Eargs;
767 next = arg->next;
769 if (match_op(next, ',')) {
770 set_arg_count(next);
771 arg = next->next;
772 continue;
775 if (match_op(next, ')')) {
776 set_arg_count(next);
777 next = next->next;
778 arg->next->next = &eof_token_entry;
779 return next;
782 /* normal cases are finished here */
784 if (match_op(next, SPECIAL_ELLIPSIS)) {
785 if (match_op(next->next, ')')) {
786 set_arg_count(next);
787 next->count.vararg = 1;
788 next = next->next;
789 arg->next->next = &eof_token_entry;
790 return next->next;
793 arg = next;
794 goto Enotclosed;
797 if (eof_token(next)) {
798 goto Enotclosed;
799 } else {
800 arg = next;
801 goto Ebadstuff;
805 if (match_op(arg, SPECIAL_ELLIPSIS)) {
806 next = arg->next;
807 token_type(arg) = TOKEN_IDENT;
808 arg->ident = &__VA_ARGS___ident;
809 if (!match_op(next, ')'))
810 goto Enotclosed;
811 if (!++count->normal)
812 goto Eargs;
813 set_arg_count(next);
814 next->count.vararg = 1;
815 next = next->next;
816 arg->next->next = &eof_token_entry;
817 return next;
820 if (eof_token(arg)) {
821 arg = next;
822 goto Enotclosed;
824 if (match_op(arg, ','))
825 goto Emissing;
826 else
827 goto Ebadstuff;
830 Emissing:
831 warn(arg->pos, "parameter name missing");
832 return NULL;
833 Ebadstuff:
834 warn(arg->pos, "\"%s\" may not appear in macro parameter list",
835 show_token(arg));
836 return NULL;
837 Enotclosed:
838 warn(arg->pos, "missing ')' in macro parameter list");
839 return NULL;
840 Eva_args:
841 warn(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
842 return NULL;
843 Eargs:
844 warn(arg->pos, "too many arguments in macro definition");
845 return NULL;
848 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
850 struct ident *ident = token->ident;
851 int nr;
853 if (!arglist || token_type(token) != TOKEN_IDENT)
854 return 0;
856 arglist = arglist->next;
858 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
859 if (arglist->ident == ident) {
860 struct argcount *count = &arglist->next->count;
861 int n;
863 token->argnum = nr;
864 token_type(token) = type;
865 switch (type) {
866 case TOKEN_MACRO_ARGUMENT:
867 n = ++count->normal;
868 break;
869 case TOKEN_QUOTED_ARGUMENT:
870 n = ++count->quoted;
871 break;
872 default:
873 n = ++count->str;
875 if (n)
876 return count->vararg ? 2 : 1;
877 token_type(token) = TOKEN_ERROR;
878 return -1;
881 return 0;
884 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
886 struct token *token = expansion;
887 struct token **p;
888 struct token *last = NULL;
890 if (match_op(token, SPECIAL_HASHHASH))
891 goto Econcat;
893 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
894 if (match_op(token, '#')) {
895 if (arglist) {
896 struct token *next = token->next;
897 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
898 goto Equote;
899 next->pos.whitespace = token->pos.whitespace;
900 token = *p = next;
901 } else {
902 token->pos.noexpand = 1;
904 } else if (match_op(token, SPECIAL_HASHHASH)) {
905 struct token *next = token->next;
906 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
907 token_type(token) = TOKEN_CONCAT;
908 if (arg) {
909 token = next;
910 /* GNU kludge */
911 if (arg == 2 && last && match_op(last, ',')) {
912 token_type(last) = TOKEN_GNU_KLUDGE;
913 last->next = token;
915 } else if (match_op(next, SPECIAL_HASHHASH))
916 token = next;
917 else if (match_op(next, ','))
918 token = next;
919 else if (eof_token(next))
920 goto Econcat;
921 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
922 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
923 } else {
924 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
926 if (token_type(token) == TOKEN_ERROR)
927 goto Earg;
928 last = token;
930 token = alloc_token(&expansion->pos);
931 token_type(token) = TOKEN_UNTAINT;
932 token->ident = name;
933 token->next = *p;
934 *p = token;
935 return expansion;
937 Equote:
938 warn(token->pos, "'#' is not followed by a macro parameter");
939 return NULL;
941 Econcat:
942 warn(token->pos, "'##' cannot appear at the ends of macro expansion");
943 return NULL;
944 Earg:
945 warn(token->pos, "too many instances of argument in body");
946 return NULL;
949 static int handle_define(struct stream *stream, struct token **line, struct token *token)
951 struct token *arglist, *expansion;
952 struct token *left = token->next;
953 struct symbol *sym;
954 struct ident *name;
956 if (token_type(left) != TOKEN_IDENT) {
957 warn(token->pos, "expected identifier to 'define'");
958 return 0;
960 if (false_nesting)
961 return 1;
962 name = left->ident;
964 arglist = NULL;
965 expansion = left->next;
966 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
967 arglist = expansion;
968 expansion = parse_arguments(expansion);
969 if (!expansion)
970 return 1;
973 expansion = parse_expansion(expansion, arglist, name);
974 if (!expansion)
975 return 1;
977 sym = lookup_symbol(name, NS_PREPROCESSOR);
978 if (sym) {
979 if (token_list_different(sym->expansion, expansion) ||
980 token_list_different(sym->arglist, arglist)) {
981 warn(left->pos, "preprocessor token %.*s redefined",
982 name->len, name->name);
983 info(sym->pos, "this was the original definition");
985 return 1;
987 sym = alloc_symbol(left->pos, SYM_NODE);
988 bind_symbol(sym, name, NS_PREPROCESSOR);
990 sym->expansion = expansion;
991 sym->arglist = arglist;
992 return 1;
995 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
997 struct token *left = token->next;
998 struct symbol **sym;
1000 if (token_type(left) != TOKEN_IDENT) {
1001 warn(token->pos, "expected identifier to 'undef'");
1002 return 0;
1004 if (false_nesting)
1005 return 1;
1006 sym = &left->ident->symbols;
1007 while (*sym) {
1008 struct symbol *t = *sym;
1009 if (t->namespace == NS_PREPROCESSOR) {
1010 *sym = t->next_id;
1011 return 1;
1013 sym = &t->next_id;
1015 return 1;
1018 static int preprocessor_if(struct token *token, int true)
1020 if (if_nesting == 0)
1021 unmatched_if = token;
1022 if (if_nesting >= MAX_NEST)
1023 error(token->pos, "Maximum preprocessor conditional level exhausted");
1024 elif_ignore[if_nesting] = false_nesting || true;
1025 if (false_nesting || !true) {
1026 false_nesting++;
1027 return 1;
1029 true_nesting++;
1030 return 1;
1033 static int token_defined(struct token *token)
1035 if (token_type(token) == TOKEN_IDENT)
1036 return lookup_symbol(token->ident, NS_PREPROCESSOR) != NULL;
1038 warn(token->pos, "expected identifier for #if[n]def");
1039 return 0;
1042 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1044 return preprocessor_if(token, token_defined(token->next));
1047 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1049 struct token *next = token->next;
1050 if (stream->constant == -1) {
1051 int newconstant = 0;
1052 if (token_type(next) == TOKEN_IDENT) {
1053 if (!stream->protect || stream->protect == next->ident) {
1054 newconstant = -2;
1055 stream->protect = next->ident;
1056 stream->nesting = if_nesting+1;
1059 stream->constant = newconstant;
1061 return preprocessor_if(token, !token_defined(next));
1065 * Expression handling for #if and #elif; it differs from normal expansion
1066 * due to special treatment of "defined".
1068 static int expression_value(struct token **where)
1070 struct expression *expr;
1071 struct token *p;
1072 struct token **list = where, **beginning = NULL;
1073 long long value;
1074 int state = 0;
1076 while (!eof_token(p = scan_next(list))) {
1077 switch (state) {
1078 case 0:
1079 if (token_type(p) == TOKEN_IDENT) {
1080 if (p->ident != &defined_ident) {
1081 list = expand_one_symbol(list);
1082 continue;
1084 state = 1;
1085 beginning = list;
1087 break;
1088 case 1:
1089 if (match_op(p, '(')) {
1090 state = 2;
1091 } else {
1092 state = 0;
1093 replace_with_defined(p);
1094 *beginning = p;
1096 break;
1097 case 2:
1098 if (token_type(p) == TOKEN_IDENT)
1099 state = 3;
1100 else
1101 state = 0;
1102 replace_with_defined(p);
1103 *beginning = p;
1104 break;
1105 case 3:
1106 state = 0;
1107 if (!match_op(p, ')'))
1108 warn(p->pos, "missing ')' after \"defined\"");
1109 *list = p->next;
1110 continue;
1112 list = &p->next;
1115 p = constant_expression(*where, &expr);
1116 if (!eof_token(p))
1117 warn(p->pos, "garbage at end: %s", show_token_sequence(p));
1118 value = get_expression_value(expr);
1119 return value != 0;
1122 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1124 int value = 0;
1125 if (!false_nesting)
1126 value = expression_value(&token->next);
1127 return preprocessor_if(token, value);
1130 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1132 if (stream->nesting == if_nesting)
1133 stream->constant = 0;
1134 if (false_nesting) {
1135 /* If this whole if-thing is if'ed out, an elif cannot help */
1136 if (elif_ignore[if_nesting-1])
1137 return 1;
1138 if (expression_value(&token->next)) {
1139 false_nesting--;
1140 true_nesting++;
1141 elif_ignore[if_nesting-1] = 1;
1143 return 1;
1145 if (true_nesting) {
1146 false_nesting = 1;
1147 true_nesting--;
1148 return 1;
1150 warn(token->pos, "unmatched '#elif'");
1151 return 1;
1154 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1156 if (stream->nesting == if_nesting)
1157 stream->constant = 0;
1158 if (false_nesting) {
1159 /* If this whole if-thing is if'ed out, an else cannot help */
1160 if (elif_ignore[if_nesting-1])
1161 return 1;
1162 false_nesting--;
1163 true_nesting++;
1164 elif_ignore[if_nesting-1] = 1;
1165 return 1;
1167 if (true_nesting) {
1168 true_nesting--;
1169 false_nesting = 1;
1170 return 1;
1172 warn(token->pos, "unmatched #else");
1173 return 1;
1176 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1178 if (stream->constant == -2 && stream->nesting == if_nesting)
1179 stream->constant = -1;
1181 if (false_nesting) {
1182 false_nesting--;
1183 return 1;
1185 if (true_nesting) {
1186 true_nesting--;
1187 return 1;
1189 warn(token->pos, "unmatched #endif");
1190 return 1;
1193 static const char *show_token_sequence(struct token *token)
1195 static char buffer[1024];
1196 char *ptr = buffer;
1197 int whitespace = 0;
1199 if (!token)
1200 return "<none>";
1201 while (!eof_token(token)) {
1202 const char *val = show_token(token);
1203 int len = strlen(val);
1205 if (ptr + whitespace + len > buffer + sizeof(buffer)) {
1206 warn(token->pos, "too long token expansion");
1207 break;
1210 if (whitespace)
1211 *ptr++ = ' ';
1212 memcpy(ptr, val, len);
1213 ptr += len;
1214 token = token->next;
1215 whitespace = token->pos.whitespace;
1217 *ptr = 0;
1218 return buffer;
1221 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1223 if (false_nesting)
1224 return 1;
1225 warn(token->pos, "%s", show_token_sequence(token->next));
1226 return 1;
1229 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1231 if (false_nesting)
1232 return 1;
1233 warn(token->pos, "%s", show_token_sequence(token->next));
1234 return 1;
1237 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1239 if (false_nesting)
1240 return 1;
1241 includepath[0] = NULL;
1242 return 1;
1245 static void add_path_entry(struct token *token, const char *path)
1247 int i;
1249 for (i = 0; i < INCLUDEPATHS; i++) {
1250 if (!includepath[i]) {
1251 includepath[i] = path;
1252 includepath[i+1] = NULL;
1253 return;
1256 warn(token->pos, "too many include path entries");
1259 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1261 for (;;) {
1262 token = token->next;
1263 if (eof_token(token))
1264 return 1;
1265 if (token_type(token) != TOKEN_STRING) {
1266 warn(token->pos, "expected path string");
1267 return 1;
1269 add_path_entry(token, token->string->data);
1274 * We replace "#pragma xxx" with "__pragma__" in the token
1275 * stream. Just as an example.
1277 * We'll just #define that away for now, but the theory here
1278 * is that we can use this to insert arbitrary token sequences
1279 * to turn the pragma's into internal front-end sequences for
1280 * when we actually start caring about them.
1282 * So eventually this will turn into some kind of extended
1283 * __attribute__() like thing, except called __pragma__(xxx).
1285 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1287 struct token *next = *line;
1289 token->ident = &pragma_ident;
1290 token->pos.newline = 1;
1291 token->pos.whitespace = 1;
1292 token->pos.pos = 1;
1293 *line = token;
1294 token->next = next;
1295 return 1;
1298 static int handle_preprocessor_command(struct stream *stream, struct token **line, struct ident *ident, struct token *token)
1300 int i;
1301 static struct {
1302 const char *name;
1303 int (*handler)(struct stream *, struct token **, struct token *);
1304 } handlers[] = {
1305 { "define", handle_define },
1306 { "undef", handle_undef },
1307 { "ifdef", handle_ifdef },
1308 { "ifndef", handle_ifndef },
1309 { "else", handle_else },
1310 { "endif", handle_endif },
1311 { "if", handle_if },
1312 { "elif", handle_elif },
1313 { "warning", handle_warning },
1314 { "error", handle_error },
1315 { "include", handle_include },
1316 { "pragma", handle_pragma },
1318 // our internal preprocessor tokens
1319 { "nostdinc", handle_nostdinc },
1320 { "add_include", handle_add_include },
1323 for (i = 0; i < (sizeof (handlers) / sizeof (handlers[0])); i++) {
1324 if (match_string_ident(ident, handlers[i].name))
1325 return handlers[i].handler(stream, line, token);
1327 return 0;
1330 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *token)
1332 if (!token)
1333 return;
1335 if (token_type(token) == TOKEN_IDENT)
1336 if (handle_preprocessor_command(stream, line, token->ident, token))
1337 return;
1338 warn(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1341 static void preprocessor_line(struct stream *stream, struct token **line)
1343 struct token *start = *line, *next;
1344 struct token **tp = &start->next;
1346 for (;;) {
1347 next = *tp;
1348 if (next->pos.newline)
1349 break;
1350 tp = &next->next;
1352 *line = next;
1353 *tp = &eof_token_entry;
1354 handle_preprocessor_line(stream, line, start->next);
1357 static void do_preprocess(struct token **list)
1359 struct token *next;
1361 while (!eof_token(next = scan_next(list))) {
1362 struct stream *stream = input_streams + next->pos.stream;
1364 if (next->pos.newline && match_op(next, '#')) {
1365 if (!next->pos.noexpand) {
1366 preprocessor_line(stream, list);
1367 continue;
1371 if (false_nesting) {
1372 *list = next->next;
1373 continue;
1376 switch (token_type(next)) {
1377 case TOKEN_STREAMEND:
1378 if (stream->constant == -1 && stream->protect) {
1379 stream->constant = 1;
1381 /* fallthrough */
1382 case TOKEN_STREAMBEGIN:
1383 *list = next->next;
1384 continue;
1386 case TOKEN_IDENT:
1387 list = expand_one_symbol(list);
1388 break;
1389 default:
1390 list = &next->next;
1393 * Any token expansion (even if it ended up being an
1394 * empty expansion) in this stream implies it can't
1395 * be constant.
1397 stream->constant = 0;
1401 struct token * preprocess(struct token *token)
1403 preprocessing = 1;
1404 do_preprocess(&token);
1405 if (if_nesting)
1406 warn(unmatched_if->pos, "unmatched preprocessor conditional");
1408 // Drop all expressions from pre-processing, they're not used any more.
1409 clear_expression_alloc();
1410 preprocessing = 0;
1412 return token;