[PATCH] fix of compound literals on inlining
[smatch.git] / pre-process.c
blob8fde0f01ba0f785cdd0bab96f754bb1bcbcfe0a2
1 /*
2 * Do C preprocessing, based on a token list gathered by
3 * the tokenizer.
5 * This may not be the smartest preprocessor on the planet.
7 * Copyright (C) 2003 Transmeta Corp.
8 * 2003-2004 Linus Torvalds
10 * Licensed under the Open Software License version 1.1
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <stddef.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <unistd.h>
19 #include <fcntl.h>
20 #include <limits.h>
22 #include "pre-process.h"
23 #include "lib.h"
24 #include "allocate.h"
25 #include "parse.h"
26 #include "token.h"
27 #include "symbol.h"
28 #include "expression.h"
29 #include "scope.h"
31 static int true_nesting = 0;
32 static int false_nesting = 0;
33 static struct position unmatched_if_pos;
34 #define if_nesting (true_nesting + false_nesting)
36 #define MAX_NEST (256)
37 static unsigned char elif_ignore[MAX_NEST];
38 enum { ELIF_IGNORE = 1, ELIF_SEEN_ELSE = 2 };
40 #define INCLUDEPATHS 300
41 const char *includepath[INCLUDEPATHS+1] = {
42 "",
43 "/usr/include",
44 "/usr/local/include",
45 GCC_INTERNAL_INCLUDE,
46 NULL
49 static const char **quote_includepath = includepath;
50 static const char **angle_includepath = includepath + 1;
51 static const char **sys_includepath = includepath + 1;
53 #define MARK_STREAM_NONCONST(pos) do { \
54 if (stream->constant != CONSTANT_FILE_NOPE) { \
55 if (0) \
56 info(pos, "%s triggers non-const", __func__); \
57 stream->constant = CONSTANT_FILE_NOPE; \
58 } \
59 } while (0)
62 static struct token *alloc_token(struct position *pos)
64 struct token *token = __alloc_token(0);
66 token->pos.stream = pos->stream;
67 token->pos.line = pos->line;
68 token->pos.pos = pos->pos;
69 token->pos.whitespace = 1;
70 return token;
73 static const char *show_token_sequence(struct token *token);
75 /* Expand symbol 'sym' at '*list' */
76 static int expand(struct token **, struct symbol *);
78 static void replace_with_string(struct token *token, const char *str)
80 int size = strlen(str) + 1;
81 struct string *s = __alloc_string(size);
83 s->length = size;
84 memcpy(s->data, str, size);
85 token_type(token) = TOKEN_STRING;
86 token->string = s;
89 static void replace_with_integer(struct token *token, unsigned int val)
91 char *buf = __alloc_bytes(11);
92 sprintf(buf, "%u", val);
93 token_type(token) = TOKEN_NUMBER;
94 token->number = buf;
97 struct symbol *lookup_macro(struct ident *ident)
99 struct symbol *sym = lookup_symbol(ident, NS_MACRO | NS_INVISIBLEMACRO);
100 if (sym && sym->namespace != NS_MACRO)
101 sym = NULL;
102 return sym;
105 static int token_defined(struct token *token)
107 if (token_type(token) == TOKEN_IDENT) {
108 struct symbol *sym = lookup_macro(token->ident);
109 if (sym) {
110 sym->weak = 0;
111 return 1;
113 return 0;
116 sparse_error(token->pos, "expected preprocessor identifier");
117 return 0;
120 static void replace_with_defined(struct token *token)
122 static const char *string[] = { "0", "1" };
123 int defined = token_defined(token);
125 token_type(token) = TOKEN_NUMBER;
126 token->number = string[defined];
129 static int expand_one_symbol(struct token **list)
131 struct token *token = *list;
132 struct symbol *sym;
134 if (token->pos.noexpand)
135 return 1;
137 sym = lookup_macro(token->ident);
138 if (sym) {
139 sym->weak = 0;
140 return expand(list, sym);
142 if (token->ident == &__LINE___ident) {
143 replace_with_integer(token, token->pos.line);
144 } else if (token->ident == &__FILE___ident) {
145 replace_with_string(token, stream_name(token->pos.stream));
147 return 1;
150 static inline struct token *scan_next(struct token **where)
152 struct token *token = *where;
153 if (token_type(token) != TOKEN_UNTAINT)
154 return token;
155 do {
156 token->ident->tainted = 0;
157 token = token->next;
158 } while (token_type(token) == TOKEN_UNTAINT);
159 *where = token;
160 return token;
163 static void expand_list(struct token **list)
165 struct token *next;
166 while (!eof_token(next = scan_next(list))) {
167 if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list))
168 list = &next->next;
172 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
174 struct token **p = &prev->next;
175 struct token *next;
176 int nesting = 0;
178 while (!eof_token(next = scan_next(p))) {
179 if (match_op(next, '(')) {
180 nesting++;
181 } else if (match_op(next, ')')) {
182 if (!nesting--)
183 break;
184 } else if (match_op(next, ',') && !nesting && !vararg) {
185 break;
187 next->pos.stream = pos->stream;
188 next->pos.line = pos->line;
189 next->pos.pos = pos->pos;
190 p = &next->next;
192 *p = &eof_token_entry;
193 return next;
197 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
200 struct arg {
201 struct token *arg;
202 struct token *expanded;
203 struct token *str;
204 int n_normal;
205 int n_quoted;
206 int n_str;
209 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
211 int wanted = arglist->count.normal;
212 struct token *next = NULL;
213 int count = 0;
215 arglist = arglist->next; /* skip counter */
217 if (!wanted) {
218 next = collect_arg(start, 0, &what->pos);
219 if (eof_token(next))
220 goto Eclosing;
221 if (!eof_token(start->next) || !match_op(next, ')')) {
222 count++;
223 goto Emany;
225 } else {
226 for (count = 0; count < wanted; count++) {
227 struct argcount *p = &arglist->next->count;
228 next = collect_arg(start, p->vararg, &what->pos);
229 arglist = arglist->next->next;
230 if (eof_token(next))
231 goto Eclosing;
232 args[count].arg = start->next;
233 args[count].n_normal = p->normal;
234 args[count].n_quoted = p->quoted;
235 args[count].n_str = p->str;
236 if (match_op(next, ')')) {
237 count++;
238 break;
240 start = next;
242 if (count == wanted && !match_op(next, ')'))
243 goto Emany;
244 if (count == wanted - 1) {
245 struct argcount *p = &arglist->next->count;
246 if (!p->vararg)
247 goto Efew;
248 args[count].arg = NULL;
249 args[count].n_normal = p->normal;
250 args[count].n_quoted = p->quoted;
251 args[count].n_str = p->str;
253 if (count < wanted - 1)
254 goto Efew;
256 what->next = next->next;
257 return 1;
259 Efew:
260 sparse_error(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
261 show_token(what), wanted, count);
262 goto out;
263 Emany:
264 while (match_op(next, ',')) {
265 next = collect_arg(next, 0, &what->pos);
266 count++;
268 if (eof_token(next))
269 goto Eclosing;
270 sparse_error(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
271 show_token(what), count, wanted);
272 goto out;
273 Eclosing:
274 sparse_error(what->pos, "unterminated argument list invoking macro \"%s\"",
275 show_token(what));
276 out:
277 what->next = next->next;
278 return 0;
281 static struct token *dup_list(struct token *list)
283 struct token *res;
284 struct token **p = &res;
286 while (!eof_token(list)) {
287 struct token *newtok = __alloc_token(0);
288 *newtok = *list;
289 *p = newtok;
290 p = &newtok->next;
291 list = list->next;
293 return res;
296 static struct token *stringify(struct token *arg)
298 const char *s = show_token_sequence(arg);
299 int size = strlen(s)+1;
300 struct token *token = __alloc_token(0);
301 struct string *string = __alloc_string(size);
303 memcpy(string->data, s, size);
304 string->length = size;
305 token->pos = arg->pos;
306 token_type(token) = TOKEN_STRING;
307 token->string = string;
308 token->next = &eof_token_entry;
309 return token;
312 static void expand_arguments(int count, struct arg *args)
314 int i;
315 for (i = 0; i < count; i++) {
316 struct token *arg = args[i].arg;
317 if (!arg)
318 arg = &eof_token_entry;
319 if (args[i].n_str)
320 args[i].str = stringify(arg);
321 if (args[i].n_normal) {
322 if (!args[i].n_quoted) {
323 args[i].expanded = arg;
324 args[i].arg = NULL;
325 } else if (eof_token(arg)) {
326 args[i].expanded = arg;
327 } else {
328 args[i].expanded = dup_list(arg);
330 expand_list(&args[i].expanded);
336 * Possibly valid combinations:
337 * - ident + ident -> ident
338 * - ident + number -> ident unless number contains '.', '+' or '-'.
339 * - number + number -> number
340 * - number + ident -> number
341 * - number + '.' -> number
342 * - number + '+' or '-' -> number, if number used to end on [eEpP].
343 * - '.' + number -> number, if number used to start with a digit.
344 * - special + special -> either special or an error.
346 static enum token_type combine(struct token *left, struct token *right, char *p)
348 int len;
349 enum token_type t1 = token_type(left), t2 = token_type(right);
351 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
352 return TOKEN_ERROR;
354 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
355 return TOKEN_ERROR;
357 strcpy(p, show_token(left));
358 strcat(p, show_token(right));
359 len = strlen(p);
361 if (len >= 256)
362 return TOKEN_ERROR;
364 if (t1 == TOKEN_IDENT) {
365 if (t2 == TOKEN_SPECIAL)
366 return TOKEN_ERROR;
367 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
368 return TOKEN_ERROR;
369 return TOKEN_IDENT;
372 if (t1 == TOKEN_NUMBER) {
373 if (t2 == TOKEN_SPECIAL) {
374 switch (right->special) {
375 case '.':
376 break;
377 case '+': case '-':
378 if (strchr("eEpP", p[len - 2]))
379 break;
380 default:
381 return TOKEN_ERROR;
384 return TOKEN_NUMBER;
387 if (p[0] == '.' && isdigit((unsigned char)p[1]))
388 return TOKEN_NUMBER;
390 return TOKEN_SPECIAL;
393 static int merge(struct token *left, struct token *right)
395 static char buffer[512];
396 int n;
398 switch (combine(left, right, buffer)) {
399 case TOKEN_IDENT:
400 left->ident = built_in_ident(buffer);
401 left->pos.noexpand = 0;
402 return 1;
404 case TOKEN_NUMBER: {
405 char *number = __alloc_bytes(strlen(buffer) + 1);
406 memcpy(number, buffer, strlen(buffer) + 1);
407 token_type(left) = TOKEN_NUMBER; /* could be . + num */
408 left->number = number;
409 return 1;
412 case TOKEN_SPECIAL:
413 if (buffer[2] && buffer[3])
414 break;
415 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
416 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
417 left->special = n;
418 return 1;
421 default:
424 sparse_error(left->pos, "'##' failed: concatenation is not a valid token");
425 return 0;
428 static struct token *dup_token(struct token *token, struct position *streampos, struct position *pos)
430 struct token *alloc = alloc_token(streampos);
431 token_type(alloc) = token_type(token);
432 alloc->pos.newline = pos->newline;
433 alloc->pos.whitespace = pos->whitespace;
434 alloc->number = token->number;
435 alloc->pos.noexpand = token->pos.noexpand;
436 return alloc;
439 static struct token **copy(struct token **where, struct token *list, int *count)
441 int need_copy = --*count;
442 while (!eof_token(list)) {
443 struct token *token;
444 if (need_copy)
445 token = dup_token(list, &list->pos, &list->pos);
446 else
447 token = list;
448 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
449 token->pos.noexpand = 1;
450 *where = token;
451 where = &token->next;
452 list = list->next;
454 *where = &eof_token_entry;
455 return where;
458 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
460 struct token *token = *list;
461 struct position *base_pos = &token->pos;
462 struct position *pos = base_pos;
463 int *count;
464 enum {Normal, Placeholder, Concat} state = Normal;
466 for (; !eof_token(body); body = body->next, pos = &body->pos) {
467 struct token *added, *arg;
468 struct token **tail;
470 switch (token_type(body)) {
471 case TOKEN_GNU_KLUDGE:
473 * GNU kludge: if we had <comma>##<vararg>, behaviour
474 * depends on whether we had enough arguments to have
475 * a vararg. If we did, ## is just ignored. Otherwise
476 * both , and ## are ignored. Comma should come from
477 * the body of macro and not be an argument of earlier
478 * concatenation.
480 if (!args[body->next->argnum].arg)
481 continue;
482 added = dup_token(body, base_pos, pos);
483 token_type(added) = TOKEN_SPECIAL;
484 tail = &added->next;
485 break;
487 case TOKEN_STR_ARGUMENT:
488 arg = args[body->argnum].str;
489 count = &args[body->argnum].n_str;
490 goto copy_arg;
492 case TOKEN_QUOTED_ARGUMENT:
493 arg = args[body->argnum].arg;
494 count = &args[body->argnum].n_quoted;
495 if (!arg || eof_token(arg)) {
496 if (state == Concat)
497 state = Normal;
498 else
499 state = Placeholder;
500 continue;
502 goto copy_arg;
504 case TOKEN_MACRO_ARGUMENT:
505 arg = args[body->argnum].expanded;
506 count = &args[body->argnum].n_normal;
507 if (eof_token(arg)) {
508 state = Normal;
509 continue;
511 copy_arg:
512 tail = copy(&added, arg, count);
513 added->pos.newline = pos->newline;
514 added->pos.whitespace = pos->whitespace;
515 break;
517 case TOKEN_CONCAT:
518 if (state == Placeholder)
519 state = Normal;
520 else
521 state = Concat;
522 continue;
524 case TOKEN_IDENT:
525 added = dup_token(body, base_pos, pos);
526 if (added->ident->tainted)
527 added->pos.noexpand = 1;
528 tail = &added->next;
529 break;
531 default:
532 added = dup_token(body, base_pos, pos);
533 tail = &added->next;
534 break;
538 * if we got to doing real concatenation, we already have
539 * added something into the list, so containing_token() is OK.
541 if (state == Concat && merge(containing_token(list), added)) {
542 *list = added->next;
543 if (tail != &added->next)
544 list = tail;
545 } else {
546 *list = added;
547 list = tail;
549 state = Normal;
551 *list = &eof_token_entry;
552 return list;
555 static int expand(struct token **list, struct symbol *sym)
557 struct token *last;
558 struct token *token = *list;
559 struct ident *expanding = token->ident;
560 struct token **tail;
561 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
562 struct arg args[nargs];
564 if (expanding->tainted) {
565 token->pos.noexpand = 1;
566 return 1;
569 if (sym->arglist) {
570 if (!match_op(scan_next(&token->next), '('))
571 return 1;
572 if (!collect_arguments(token->next, sym->arglist, args, token))
573 return 1;
574 expand_arguments(nargs, args);
577 expanding->tainted = 1;
579 last = token->next;
580 tail = substitute(list, sym->expansion, args);
581 *tail = last;
583 return 0;
586 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
588 struct token *last;
589 static char buffer[256];
590 char *ptr = buffer;
592 last = token;
593 while (!eof_token(token) && !match_op(token, endop)) {
594 int len;
595 const char *val = token->string->data;
596 if (token_type(token) != TOKEN_STRING)
597 val = show_token(token);
598 len = strlen(val);
599 memcpy(ptr, val, len);
600 ptr += len;
601 token = token->next;
603 *ptr = 0;
604 if (endop && !match_op(token, endop))
605 sparse_error(start->pos, "expected '>' at end of filename");
606 return buffer;
609 static int already_tokenized(const char *path)
611 int i;
612 struct stream *s = input_streams;
614 for (i = input_stream_nr; --i >= 0; s++) {
615 if (s->constant != CONSTANT_FILE_YES)
616 continue;
617 if (strcmp(path, s->name))
618 continue;
619 if (!lookup_macro(s->protect))
620 continue;
621 return 1;
623 return 0;
626 /* Hande include of header files.
627 * The relevant options are made compatible with gcc. The only options that
628 * are not supported is -withprefix and friends.
630 * Three set of include paths are known:
631 * quote_includepath: Path to search when using #include "file.h"
632 * angle_includepath: Path to search when using #include <file.h>
633 * sys_includepath: Built-in include paths
635 * The above is implmented as one array with pointes
636 * +--------------+
637 * quote_includepath ---> | |
638 * +--------------+
639 * | |
640 * +--------------+
641 * angle_includepath ---> | |
642 * +--------------+
643 * sys_includepath ---> | |
644 * +--------------+
645 * | |
646 * +--------------+
648 * -I dir insert dir just before sys_includepath and move the rest
649 * -I- makes all dirs specified with -I before to quote dirs only and
650 * angle_includepath is set equal to sys_includepath.
651 * -nostdinc removes all sys dirs be storing NULL in entry pointed
652 * to by * sys_includepath. Note this will reset all dirs built-in and added
653 * before -nostdinc by -isystem and -dirafter
654 * -isystem dir adds dir where sys_includepath points adding this dir as
655 * first systemdir
656 * -dirafter dir adds dir to the end of the list
659 static void set_stream_include_path(struct stream *stream)
661 const char *path = stream->path;
662 if (!path) {
663 const char *p = strrchr(stream->name, '/');
664 path = "";
665 if (p) {
666 int len = p - stream->name + 1;
667 char *m = malloc(len+1);
668 /* This includes the final "/" */
669 memcpy(m, stream->name, len);
670 m[len] = 0;
671 path = m;
673 stream->path = path;
675 includepath[0] = path;
678 static int try_include(const char *path, const char *filename, int flen, struct token **where, const char **next_path)
680 int fd;
681 int plen = strlen(path);
682 static char fullname[PATH_MAX];
684 memcpy(fullname, path, plen);
685 if (plen && path[plen-1] != '/') {
686 fullname[plen] = '/';
687 plen++;
689 memcpy(fullname+plen, filename, flen);
690 if (already_tokenized(fullname))
691 return 1;
692 fd = open(fullname, O_RDONLY);
693 if (fd >= 0) {
694 char * streamname = __alloc_bytes(plen + flen);
695 memcpy(streamname, fullname, plen + flen);
696 *where = tokenize(streamname, fd, *where, next_path);
697 close(fd);
698 return 1;
700 return 0;
703 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
705 const char *path;
707 while ((path = *pptr++) != NULL) {
708 if (!try_include(path, filename, flen, list, pptr))
709 continue;
710 return 1;
712 return 0;
715 static void do_include(int local, struct stream *stream, struct token **list, struct token *token, const char *filename, const char **path)
717 int flen = strlen(filename) + 1;
719 /* Absolute path? */
720 if (filename[0] == '/') {
721 if (try_include("", filename, flen, list, includepath))
722 return;
723 goto out;
726 /* Dir of inputfile is first dir to search for quoted includes */
727 set_stream_include_path(stream);
729 if (!path)
730 /* Do not search quote include if <> is in use */
731 path = local ? quote_includepath : angle_includepath;
733 /* Check the standard include paths.. */
734 if (do_include_path(path, list, token, filename, flen))
735 return;
736 out:
737 error_die(token->pos, "unable to open '%s'", filename);
740 static int free_preprocessor_line(struct token *token)
742 do {
743 struct token *free = token;
744 token = token->next;
745 __free_token(free);
746 } while (token_type(token) != TOKEN_EOF);
747 return 1;
750 static int handle_include_path(struct stream *stream, struct token **list, struct token *token, const char **path)
752 const char *filename;
753 struct token *next;
754 int expect;
756 if (false_nesting)
757 return free_preprocessor_line(token);
759 if (stream->constant == CONSTANT_FILE_MAYBE)
760 MARK_STREAM_NONCONST(token->pos);
762 next = token->next;
763 expect = '>';
764 if (!match_op(next, '<')) {
765 expand_list(&token->next);
766 expect = 0;
767 next = token;
768 if (match_op(token->next, '<')) {
769 next = token->next;
770 expect = '>';
773 token = next->next;
774 filename = token_name_sequence(token, expect, token);
775 do_include(!expect, stream, list, token, filename, path);
776 return 1;
779 static int handle_include(struct stream *stream, struct token **list, struct token *token)
781 return handle_include_path(stream, list, token, NULL);
784 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
786 return handle_include_path(stream, list, token, stream->next_path);
789 static int token_different(struct token *t1, struct token *t2)
791 int different;
793 if (token_type(t1) != token_type(t2))
794 return 1;
796 switch (token_type(t1)) {
797 case TOKEN_IDENT:
798 different = t1->ident != t2->ident;
799 break;
800 case TOKEN_ARG_COUNT:
801 case TOKEN_UNTAINT:
802 case TOKEN_CONCAT:
803 case TOKEN_GNU_KLUDGE:
804 different = 0;
805 break;
806 case TOKEN_NUMBER:
807 different = strcmp(t1->number, t2->number);
808 break;
809 case TOKEN_SPECIAL:
810 different = t1->special != t2->special;
811 break;
812 case TOKEN_MACRO_ARGUMENT:
813 case TOKEN_QUOTED_ARGUMENT:
814 case TOKEN_STR_ARGUMENT:
815 different = t1->argnum != t2->argnum;
816 break;
817 case TOKEN_CHAR:
818 different = t1->character != t2->character;
819 break;
820 case TOKEN_STRING: {
821 struct string *s1, *s2;
823 s1 = t1->string;
824 s2 = t2->string;
825 different = 1;
826 if (s1->length != s2->length)
827 break;
828 different = memcmp(s1->data, s2->data, s1->length);
829 break;
831 default:
832 different = 1;
833 break;
835 return different;
838 static int token_list_different(struct token *list1, struct token *list2)
840 for (;;) {
841 if (list1 == list2)
842 return 0;
843 if (!list1 || !list2)
844 return 1;
845 if (token_different(list1, list2))
846 return 1;
847 list1 = list1->next;
848 list2 = list2->next;
852 static inline void set_arg_count(struct token *token)
854 token_type(token) = TOKEN_ARG_COUNT;
855 token->count.normal = token->count.quoted =
856 token->count.str = token->count.vararg = 0;
859 static struct token *parse_arguments(struct token *list)
861 struct token *arg = list->next, *next = list;
862 struct argcount *count = &list->count;
864 set_arg_count(list);
866 if (match_op(arg, ')')) {
867 next = arg->next;
868 list->next = &eof_token_entry;
869 return next;
872 while (token_type(arg) == TOKEN_IDENT) {
873 if (arg->ident == &__VA_ARGS___ident)
874 goto Eva_args;
875 if (!++count->normal)
876 goto Eargs;
877 next = arg->next;
879 if (match_op(next, ',')) {
880 set_arg_count(next);
881 arg = next->next;
882 continue;
885 if (match_op(next, ')')) {
886 set_arg_count(next);
887 next = next->next;
888 arg->next->next = &eof_token_entry;
889 return next;
892 /* normal cases are finished here */
894 if (match_op(next, SPECIAL_ELLIPSIS)) {
895 if (match_op(next->next, ')')) {
896 set_arg_count(next);
897 next->count.vararg = 1;
898 next = next->next;
899 arg->next->next = &eof_token_entry;
900 return next->next;
903 arg = next;
904 goto Enotclosed;
907 if (eof_token(next)) {
908 goto Enotclosed;
909 } else {
910 arg = next;
911 goto Ebadstuff;
915 if (match_op(arg, SPECIAL_ELLIPSIS)) {
916 next = arg->next;
917 token_type(arg) = TOKEN_IDENT;
918 arg->ident = &__VA_ARGS___ident;
919 if (!match_op(next, ')'))
920 goto Enotclosed;
921 if (!++count->normal)
922 goto Eargs;
923 set_arg_count(next);
924 next->count.vararg = 1;
925 next = next->next;
926 arg->next->next = &eof_token_entry;
927 return next;
930 if (eof_token(arg)) {
931 arg = next;
932 goto Enotclosed;
934 if (match_op(arg, ','))
935 goto Emissing;
936 else
937 goto Ebadstuff;
940 Emissing:
941 sparse_error(arg->pos, "parameter name missing");
942 return NULL;
943 Ebadstuff:
944 sparse_error(arg->pos, "\"%s\" may not appear in macro parameter list",
945 show_token(arg));
946 return NULL;
947 Enotclosed:
948 sparse_error(arg->pos, "missing ')' in macro parameter list");
949 return NULL;
950 Eva_args:
951 sparse_error(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
952 return NULL;
953 Eargs:
954 sparse_error(arg->pos, "too many arguments in macro definition");
955 return NULL;
958 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
960 struct ident *ident = token->ident;
961 int nr;
963 if (!arglist || token_type(token) != TOKEN_IDENT)
964 return 0;
966 arglist = arglist->next;
968 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
969 if (arglist->ident == ident) {
970 struct argcount *count = &arglist->next->count;
971 int n;
973 token->argnum = nr;
974 token_type(token) = type;
975 switch (type) {
976 case TOKEN_MACRO_ARGUMENT:
977 n = ++count->normal;
978 break;
979 case TOKEN_QUOTED_ARGUMENT:
980 n = ++count->quoted;
981 break;
982 default:
983 n = ++count->str;
985 if (n)
986 return count->vararg ? 2 : 1;
987 token_type(token) = TOKEN_ERROR;
988 return -1;
991 return 0;
994 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
996 struct token *token = expansion;
997 struct token **p;
998 struct token *last = NULL;
1000 if (match_op(token, SPECIAL_HASHHASH))
1001 goto Econcat;
1003 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
1004 if (match_op(token, '#')) {
1005 if (arglist) {
1006 struct token *next = token->next;
1007 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
1008 goto Equote;
1009 next->pos.whitespace = token->pos.whitespace;
1010 token = *p = next;
1011 } else {
1012 token->pos.noexpand = 1;
1014 } else if (match_op(token, SPECIAL_HASHHASH)) {
1015 struct token *next = token->next;
1016 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
1017 token_type(token) = TOKEN_CONCAT;
1018 if (arg) {
1019 token = next;
1020 /* GNU kludge */
1021 if (arg == 2 && last && match_op(last, ',')) {
1022 token_type(last) = TOKEN_GNU_KLUDGE;
1023 last->next = token;
1025 } else if (match_op(next, SPECIAL_HASHHASH))
1026 token = next;
1027 else if (match_op(next, ','))
1028 token = next;
1029 else if (eof_token(next))
1030 goto Econcat;
1031 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
1032 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
1033 } else {
1034 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
1036 if (token_type(token) == TOKEN_ERROR)
1037 goto Earg;
1038 last = token;
1040 token = alloc_token(&expansion->pos);
1041 token_type(token) = TOKEN_UNTAINT;
1042 token->ident = name;
1043 token->next = *p;
1044 *p = token;
1045 return expansion;
1047 Equote:
1048 sparse_error(token->pos, "'#' is not followed by a macro parameter");
1049 return NULL;
1051 Econcat:
1052 sparse_error(token->pos, "'##' cannot appear at the ends of macro expansion");
1053 return NULL;
1054 Earg:
1055 sparse_error(token->pos, "too many instances of argument in body");
1056 return NULL;
1059 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int weak)
1061 struct token *arglist, *expansion;
1062 struct token *left = token->next;
1063 struct symbol *sym;
1064 struct ident *name;
1066 if (token_type(left) != TOKEN_IDENT) {
1067 sparse_error(token->pos, "expected identifier to 'define'");
1068 return 0;
1070 if (false_nesting)
1071 return free_preprocessor_line(token);
1073 if (stream->constant == CONSTANT_FILE_MAYBE)
1074 MARK_STREAM_NONCONST(token->pos);
1076 __free_token(token); /* Free the "define" token, but not the rest of the line */
1077 name = left->ident;
1079 arglist = NULL;
1080 expansion = left->next;
1081 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
1082 arglist = expansion;
1083 expansion = parse_arguments(expansion);
1084 if (!expansion)
1085 return 1;
1088 expansion = parse_expansion(expansion, arglist, name);
1089 if (!expansion)
1090 return 1;
1092 sym = lookup_macro(name);
1093 if (sym) {
1094 if (token_list_different(sym->expansion, expansion) ||
1095 token_list_different(sym->arglist, arglist)) {
1096 if (sym->weak)
1097 goto replace_it;
1098 if (weak)
1099 return 1;
1100 warning(left->pos, "preprocessor token %.*s redefined",
1101 name->len, name->name);
1102 info(sym->pos, "this was the original definition");
1104 /* Don't overwrite global defs */
1105 if (sym->scope != file_scope)
1106 goto allocate_new;
1107 sym->expansion = expansion;
1108 sym->arglist = arglist;
1110 return 1;
1112 allocate_new:
1113 sym = alloc_symbol(left->pos, SYM_NODE);
1114 bind_symbol(sym, name, NS_MACRO);
1116 replace_it:
1117 sym->expansion = expansion;
1118 sym->arglist = arglist;
1119 sym->weak = weak;
1120 return 1;
1123 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1125 return do_handle_define(stream, line, token, 0);
1128 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1130 return do_handle_define(stream, line, token, 1);
1133 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1135 struct token *left = token->next;
1136 struct symbol **sym;
1138 if (token_type(left) != TOKEN_IDENT) {
1139 sparse_error(token->pos, "expected identifier to 'undef'");
1140 return 0;
1142 if (false_nesting)
1143 return free_preprocessor_line(token);
1145 if (stream->constant == CONSTANT_FILE_MAYBE)
1146 MARK_STREAM_NONCONST(token->pos);
1148 sym = &left->ident->symbols;
1149 while (*sym) {
1150 struct symbol *t = *sym;
1151 if (t->namespace & (NS_MACRO | NS_INVISIBLEMACRO)) {
1152 t->namespace = NS_INVISIBLEMACRO;
1153 return 1;
1155 sym = &t->next_id;
1157 return free_preprocessor_line(token);
1160 static int preprocessor_if(struct token *token, int true)
1162 if (if_nesting == 0)
1163 unmatched_if_pos = token->pos;
1164 if (if_nesting >= MAX_NEST)
1165 error_die(token->pos, "Maximum preprocessor conditional level exhausted");
1166 elif_ignore[if_nesting] = (false_nesting || true) ? ELIF_IGNORE : 0;
1167 if (false_nesting || !true) {
1168 false_nesting++;
1169 return free_preprocessor_line(token);
1171 true_nesting++;
1172 return free_preprocessor_line(token);
1175 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1177 return preprocessor_if(token, token_defined(token->next));
1180 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1182 struct token *next = token->next;
1183 if (stream->constant == CONSTANT_FILE_MAYBE) {
1184 if (token_type(next) == TOKEN_IDENT &&
1185 (!stream->protect || stream->protect == next->ident)) {
1186 stream->constant = CONSTANT_FILE_IFNDEF;
1187 stream->protect = next->ident;
1188 } else
1189 MARK_STREAM_NONCONST(token->pos);
1191 return preprocessor_if(token, !token_defined(next));
1195 * Expression handling for #if and #elif; it differs from normal expansion
1196 * due to special treatment of "defined".
1198 static int expression_value(struct token **where)
1200 struct expression *expr;
1201 struct token *p;
1202 struct token **list = where, **beginning = NULL;
1203 long long value;
1204 int state = 0;
1206 while (!eof_token(p = scan_next(list))) {
1207 switch (state) {
1208 case 0:
1209 if (token_type(p) != TOKEN_IDENT)
1210 break;
1211 if (p->ident == &defined_ident) {
1212 state = 1;
1213 beginning = list;
1214 break;
1216 if (!expand_one_symbol(list))
1217 continue;
1218 if (token_type(p) != TOKEN_IDENT)
1219 break;
1220 token_type(p) = TOKEN_ZERO_IDENT;
1221 break;
1222 case 1:
1223 if (match_op(p, '(')) {
1224 state = 2;
1225 } else {
1226 state = 0;
1227 replace_with_defined(p);
1228 *beginning = p;
1230 break;
1231 case 2:
1232 if (token_type(p) == TOKEN_IDENT)
1233 state = 3;
1234 else
1235 state = 0;
1236 replace_with_defined(p);
1237 *beginning = p;
1238 break;
1239 case 3:
1240 state = 0;
1241 if (!match_op(p, ')'))
1242 sparse_error(p->pos, "missing ')' after \"defined\"");
1243 *list = p->next;
1244 continue;
1246 list = &p->next;
1249 p = constant_expression(*where, &expr);
1250 if (!eof_token(p))
1251 sparse_error(p->pos, "garbage at end: %s", show_token_sequence(p));
1252 value = get_expression_value(expr);
1253 return value != 0;
1256 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1258 int value = 0;
1259 if (!false_nesting)
1260 value = expression_value(&token->next);
1262 // This is an approximation. We really only need this if the
1263 // condition does depends on a pre-processor symbol. Note, that
1264 // the important #ifndef case has already changed ->constant.
1265 if (stream->constant == CONSTANT_FILE_MAYBE)
1266 MARK_STREAM_NONCONST(token->pos);
1268 return preprocessor_if(token, value);
1271 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1273 if (stream->nesting == if_nesting)
1274 MARK_STREAM_NONCONST(token->pos);
1276 if (stream->nesting > if_nesting)
1277 sparse_error(token->pos, "unmatched #elif within stream");
1279 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1280 sparse_error(token->pos, "#elif after #else");
1282 if (false_nesting) {
1283 /* If this whole if-thing is if'ed out, an elif cannot help */
1284 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1285 return 1;
1286 if (expression_value(&token->next)) {
1287 false_nesting = 0;
1288 true_nesting++;
1289 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1291 } else {
1292 false_nesting = 1;
1293 true_nesting--;
1295 return free_preprocessor_line(token);
1298 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1300 if (stream->nesting == if_nesting)
1301 MARK_STREAM_NONCONST(token->pos);
1303 if (stream->nesting > if_nesting)
1304 sparse_error(token->pos, "unmatched #else within stream");
1306 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1307 sparse_error(token->pos, "#else after #else");
1308 else
1309 elif_ignore[if_nesting-1] |= ELIF_SEEN_ELSE;
1311 if (false_nesting) {
1312 /* If this whole if-thing is if'ed out, an else cannot help */
1313 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1314 return 1;
1315 false_nesting = 0;
1316 true_nesting++;
1317 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1318 } else {
1319 true_nesting--;
1320 false_nesting = 1;
1322 return free_preprocessor_line(token);
1325 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1327 if (stream->constant == CONSTANT_FILE_IFNDEF && stream->nesting == if_nesting)
1328 stream->constant = CONSTANT_FILE_MAYBE;
1330 if (stream->nesting > if_nesting)
1331 sparse_error(token->pos, "unmatched #endif in stream");
1332 if (false_nesting)
1333 false_nesting--;
1334 else
1335 true_nesting--;
1336 if (!token)
1337 return 1;
1338 return free_preprocessor_line(token);
1341 static const char *show_token_sequence(struct token *token)
1343 static char buffer[1024];
1344 char *ptr = buffer;
1345 int whitespace = 0;
1347 if (!token)
1348 return "<none>";
1349 while (!eof_token(token)) {
1350 const char *val = show_token(token);
1351 int len = strlen(val);
1353 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
1354 sparse_error(token->pos, "too long token expansion");
1355 break;
1358 if (whitespace)
1359 *ptr++ = ' ';
1360 memcpy(ptr, val, len);
1361 ptr += len;
1362 token = token->next;
1363 whitespace = token->pos.whitespace;
1365 *ptr = 0;
1366 return buffer;
1369 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1371 if (false_nesting)
1372 return free_preprocessor_line(token);
1373 if (stream->constant == CONSTANT_FILE_MAYBE)
1374 MARK_STREAM_NONCONST(token->pos);
1375 warning(token->pos, "%s", show_token_sequence(token->next));
1376 return free_preprocessor_line(token);
1379 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1381 if (false_nesting)
1382 return free_preprocessor_line(token);
1383 if (stream->constant == CONSTANT_FILE_MAYBE)
1384 MARK_STREAM_NONCONST(token->pos);
1385 sparse_error(token->pos, "%s", show_token_sequence(token->next));
1386 return free_preprocessor_line(token);
1389 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1391 if (false_nesting)
1392 return free_preprocessor_line(token);
1395 * Do we have any non-system includes?
1396 * Clear them out if so..
1398 *sys_includepath = NULL;
1399 return free_preprocessor_line(token);
1402 static void add_path_entry(struct token *token, const char *path, const char ***where, const char **new_path)
1404 const char **dst;
1405 const char *next;
1407 /* Need one free entry.. */
1408 if (includepath[INCLUDEPATHS-2])
1409 error_die(token->pos, "too many include path entries");
1411 /* check that this is not a duplicate */
1412 dst = includepath;
1413 while (*dst) {
1414 if (strcmp(*dst, path) == 0)
1415 return;
1416 dst++;
1418 next = path;
1419 dst = *where;
1420 *where = new_path;
1423 * Move them all up starting at dst,
1424 * insert the new entry..
1426 for (;;) {
1427 const char *tmp = *dst;
1428 *dst = next;
1429 if (!next)
1430 break;
1431 next = tmp;
1432 dst++;
1436 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1438 for (;;) {
1439 token = token->next;
1440 if (eof_token(token))
1441 return 1;
1442 if (token_type(token) != TOKEN_STRING) {
1443 warning(token->pos, "expected path string");
1444 return 1;
1446 add_path_entry(token, token->string->data, &sys_includepath, sys_includepath + 1);
1450 static int handle_add_isystem(struct stream *stream, struct token **line, struct token *token)
1452 for (;;) {
1453 token = token->next;
1454 if (eof_token(token))
1455 return 1;
1456 if (token_type(token) != TOKEN_STRING) {
1457 sparse_error(token->pos, "expected path string");
1458 return 1;
1460 add_path_entry(token, token->string->data, &sys_includepath, sys_includepath);
1464 /* Add to end on includepath list - no pointer updates */
1465 static void add_dirafter_entry(struct token *token, const char *path)
1467 const char **dst = includepath;
1469 /* Need one free entry.. */
1470 if (includepath[INCLUDEPATHS-2])
1471 error_die(token->pos, "too many include path entries");
1473 /* Add to the end */
1474 while (*dst)
1475 dst++;
1476 *dst = path;
1477 dst++;
1478 *dst = NULL;
1481 static int handle_add_dirafter(struct stream *stream, struct token **line, struct token *token)
1483 for (;;) {
1484 token = token->next;
1485 if (eof_token(token))
1486 return 1;
1487 if (token_type(token) != TOKEN_STRING) {
1488 sparse_error(token->pos, "expected path string");
1489 return 1;
1491 add_dirafter_entry(token, token->string->data);
1495 static int handle_split_include(struct stream *stream, struct token **line, struct token *token)
1497 if (false_nesting)
1498 return free_preprocessor_line(token);
1501 * -I-
1502 * From info gcc:
1503 * Split the include path. Any directories specified with `-I'
1504 * options before `-I-' are searched only for headers requested with
1505 * `#include "FILE"'; they are not searched for `#include <FILE>'.
1506 * If additional directories are specified with `-I' options after
1507 * the `-I-', those directories are searched for all `#include'
1508 * directives.
1509 * In addition, `-I-' inhibits the use of the directory of the current
1510 * file directory as the first search directory for `#include "FILE"'.
1512 quote_includepath = includepath+1;
1513 angle_includepath = sys_includepath;
1514 return free_preprocessor_line(token);
1518 * We replace "#pragma xxx" with "__pragma__" in the token
1519 * stream. Just as an example.
1521 * We'll just #define that away for now, but the theory here
1522 * is that we can use this to insert arbitrary token sequences
1523 * to turn the pragma's into internal front-end sequences for
1524 * when we actually start caring about them.
1526 * So eventually this will turn into some kind of extended
1527 * __attribute__() like thing, except called __pragma__(xxx).
1529 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1531 struct token *next = *line;
1533 token->ident = &pragma_ident;
1534 token->pos.newline = 1;
1535 token->pos.whitespace = 1;
1536 token->pos.pos = 1;
1537 *line = token;
1538 token->next = next;
1539 return 1;
1543 * We ignore #line for now.
1545 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1547 return 1;
1551 static void init_preprocessor(void)
1553 int i;
1554 int stream = init_stream("preprocessor", -1, includepath);
1555 static struct {
1556 const char *name;
1557 int (*handler)(struct stream *, struct token **, struct token *);
1558 } handlers[] = {
1559 { "define", handle_define },
1560 { "weak_define",handle_weak_define },
1561 { "undef", handle_undef },
1562 { "ifdef", handle_ifdef },
1563 { "ifndef", handle_ifndef },
1564 { "else", handle_else },
1565 { "endif", handle_endif },
1566 { "if", handle_if },
1567 { "elif", handle_elif },
1568 { "warning", handle_warning },
1569 { "error", handle_error },
1570 { "include", handle_include },
1571 { "include_next",handle_include_next },
1572 { "pragma", handle_pragma },
1573 { "line", handle_line },
1575 // our internal preprocessor tokens
1576 { "nostdinc", handle_nostdinc },
1577 { "add_include", handle_add_include },
1578 { "add_isystem", handle_add_isystem },
1579 { "add_dirafter", handle_add_dirafter },
1580 { "split_include", handle_split_include },
1583 for (i = 0; i < (sizeof (handlers) / sizeof (handlers[0])); i++) {
1584 struct symbol *sym;
1585 sym = create_symbol(stream, handlers[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1586 sym->handler = handlers[i].handler;
1590 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
1592 struct token *token = start->next;
1594 if (!token)
1595 return;
1597 if (token_type(token) == TOKEN_NUMBER)
1598 if (handle_line(stream, line, start))
1599 return;
1601 if (token_type(token) == TOKEN_IDENT) {
1602 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
1603 if (sym && sym->handler(stream, line, token))
1604 return;
1607 sparse_error(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1610 static void preprocessor_line(struct stream *stream, struct token **line)
1612 struct token *start = *line, *next;
1613 struct token **tp = &start->next;
1615 for (;;) {
1616 next = *tp;
1617 if (next->pos.newline)
1618 break;
1619 tp = &next->next;
1621 *line = next;
1622 *tp = &eof_token_entry;
1623 handle_preprocessor_line(stream, line, start);
1626 static void do_preprocess(struct token **list)
1628 struct token *next;
1630 while (!eof_token(next = scan_next(list))) {
1631 struct stream *stream = input_streams + next->pos.stream;
1633 if (next->pos.newline && match_op(next, '#')) {
1634 if (!next->pos.noexpand) {
1635 preprocessor_line(stream, list);
1636 __free_token(next); /* Free the '#' token */
1637 continue;
1641 switch (token_type(next)) {
1642 case TOKEN_STREAMEND:
1643 if (stream->nesting < if_nesting + 1) {
1644 sparse_error(unmatched_if_pos, "unterminated preprocessor conditional");
1645 // Pretend to see a series of #endifs
1646 MARK_STREAM_NONCONST(next->pos);
1647 do {
1648 handle_endif (stream, NULL, NULL);
1649 } while (stream->nesting < if_nesting + 1);
1651 if (stream->constant == CONSTANT_FILE_MAYBE && stream->protect) {
1652 stream->constant = CONSTANT_FILE_YES;
1654 *list = next->next;
1655 continue;
1656 case TOKEN_STREAMBEGIN:
1657 stream->nesting = if_nesting + 1;
1658 *list = next->next;
1659 continue;
1661 default:
1662 if (false_nesting) {
1663 *list = next->next;
1664 __free_token(next);
1665 continue;
1668 if (token_type(next) != TOKEN_IDENT ||
1669 expand_one_symbol(list))
1670 list = &next->next;
1673 if (stream->constant == CONSTANT_FILE_MAYBE) {
1675 * Any token expansion (even if it ended up being an
1676 * empty expansion) in this stream implies it can't
1677 * be constant.
1679 MARK_STREAM_NONCONST(next->pos);
1684 struct token * preprocess(struct token *token)
1686 preprocessing = 1;
1687 init_preprocessor();
1688 do_preprocess(&token);
1690 // Drop all expressions from pre-processing, they're not used any more.
1691 // This is not true when we have multiple files, though ;/
1692 // clear_expression_alloc();
1693 preprocessing = 0;
1695 return token;