Canonicalize URL in FAQ: add www., add trailing slash
[smatch.git] / pre-process.c
blob2b9cecc6e111b32e5aad17c13e3ed6adfe44e437
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>
21 #include <time.h>
23 #include "pre-process.h"
24 #include "lib.h"
25 #include "allocate.h"
26 #include "parse.h"
27 #include "token.h"
28 #include "symbol.h"
29 #include "expression.h"
30 #include "scope.h"
32 static int false_nesting = 0;
34 #define INCLUDEPATHS 300
35 const char *includepath[INCLUDEPATHS+1] = {
36 "",
37 "/usr/include",
38 "/usr/local/include",
39 GCC_INTERNAL_INCLUDE,
40 NULL
43 static const char **quote_includepath = includepath;
44 static const char **angle_includepath = includepath + 1;
45 static const char **sys_includepath = includepath + 1;
47 #define dirty_stream(stream) \
48 do { \
49 if (!stream->dirty) { \
50 stream->dirty = 1; \
51 if (!stream->ifndef) \
52 stream->protect = NULL; \
53 } \
54 } while(0)
56 #define end_group(stream) \
57 do { \
58 if (stream->ifndef == stream->top_if) { \
59 stream->ifndef = NULL; \
60 if (!stream->dirty) \
61 stream->protect = NULL; \
62 else if (stream->protect) \
63 stream->dirty = 0; \
64 } \
65 } while(0)
67 #define nesting_error(stream) \
68 do { \
69 stream->dirty = 1; \
70 stream->ifndef = NULL; \
71 stream->protect = NULL; \
72 } while(0)
74 static struct token *alloc_token(struct position *pos)
76 struct token *token = __alloc_token(0);
78 token->pos.stream = pos->stream;
79 token->pos.line = pos->line;
80 token->pos.pos = pos->pos;
81 token->pos.whitespace = 1;
82 return token;
85 static const char *show_token_sequence(struct token *token);
87 /* Expand symbol 'sym' at '*list' */
88 static int expand(struct token **, struct symbol *);
90 static void replace_with_string(struct token *token, const char *str)
92 int size = strlen(str) + 1;
93 struct string *s = __alloc_string(size);
95 s->length = size;
96 memcpy(s->data, str, size);
97 token_type(token) = TOKEN_STRING;
98 token->string = s;
101 static void replace_with_integer(struct token *token, unsigned int val)
103 char *buf = __alloc_bytes(11);
104 sprintf(buf, "%u", val);
105 token_type(token) = TOKEN_NUMBER;
106 token->number = buf;
109 static struct symbol *lookup_macro(struct ident *ident)
111 struct symbol *sym = lookup_symbol(ident, NS_MACRO | NS_UNDEF);
112 if (sym && sym->namespace != NS_MACRO)
113 sym = NULL;
114 return sym;
117 static int token_defined(struct token *token)
119 if (token_type(token) == TOKEN_IDENT) {
120 struct symbol *sym = lookup_macro(token->ident);
121 if (sym) {
122 sym->used_in = file_scope;
123 return 1;
125 return 0;
128 sparse_error(token->pos, "expected preprocessor identifier");
129 return 0;
132 static void replace_with_defined(struct token *token)
134 static const char *string[] = { "0", "1" };
135 int defined = token_defined(token);
137 token_type(token) = TOKEN_NUMBER;
138 token->number = string[defined];
141 static int expand_one_symbol(struct token **list)
143 struct token *token = *list;
144 struct symbol *sym;
145 static char buffer[12]; /* __DATE__: 3 + ' ' + 2 + ' ' + 4 + '\0' */
146 static time_t t = 0;
148 if (token->pos.noexpand)
149 return 1;
151 sym = lookup_macro(token->ident);
152 if (sym) {
153 sym->used_in = file_scope;
154 return expand(list, sym);
156 if (token->ident == &__LINE___ident) {
157 replace_with_integer(token, token->pos.line);
158 } else if (token->ident == &__FILE___ident) {
159 replace_with_string(token, stream_name(token->pos.stream));
160 } else if (token->ident == &__DATE___ident) {
161 if (!t)
162 time(&t);
163 strftime(buffer, 12, "%b %e %Y", localtime(&t));
164 replace_with_string(token, buffer);
165 } else if (token->ident == &__TIME___ident) {
166 if (!t)
167 time(&t);
168 strftime(buffer, 9, "%T", localtime(&t));
169 replace_with_string(token, buffer);
171 return 1;
174 static inline struct token *scan_next(struct token **where)
176 struct token *token = *where;
177 if (token_type(token) != TOKEN_UNTAINT)
178 return token;
179 do {
180 token->ident->tainted = 0;
181 token = token->next;
182 } while (token_type(token) == TOKEN_UNTAINT);
183 *where = token;
184 return token;
187 static void expand_list(struct token **list)
189 struct token *next;
190 while (!eof_token(next = scan_next(list))) {
191 if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list))
192 list = &next->next;
196 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
198 struct token **p = &prev->next;
199 struct token *next;
200 int nesting = 0;
202 while (!eof_token(next = scan_next(p))) {
203 if (match_op(next, '(')) {
204 nesting++;
205 } else if (match_op(next, ')')) {
206 if (!nesting--)
207 break;
208 } else if (match_op(next, ',') && !nesting && !vararg) {
209 break;
211 next->pos.stream = pos->stream;
212 next->pos.line = pos->line;
213 next->pos.pos = pos->pos;
214 p = &next->next;
216 *p = &eof_token_entry;
217 return next;
221 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
224 struct arg {
225 struct token *arg;
226 struct token *expanded;
227 struct token *str;
228 int n_normal;
229 int n_quoted;
230 int n_str;
233 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
235 int wanted = arglist->count.normal;
236 struct token *next = NULL;
237 int count = 0;
239 arglist = arglist->next; /* skip counter */
241 if (!wanted) {
242 next = collect_arg(start, 0, &what->pos);
243 if (eof_token(next))
244 goto Eclosing;
245 if (!eof_token(start->next) || !match_op(next, ')')) {
246 count++;
247 goto Emany;
249 } else {
250 for (count = 0; count < wanted; count++) {
251 struct argcount *p = &arglist->next->count;
252 next = collect_arg(start, p->vararg, &what->pos);
253 arglist = arglist->next->next;
254 if (eof_token(next))
255 goto Eclosing;
256 args[count].arg = start->next;
257 args[count].n_normal = p->normal;
258 args[count].n_quoted = p->quoted;
259 args[count].n_str = p->str;
260 if (match_op(next, ')')) {
261 count++;
262 break;
264 start = next;
266 if (count == wanted && !match_op(next, ')'))
267 goto Emany;
268 if (count == wanted - 1) {
269 struct argcount *p = &arglist->next->count;
270 if (!p->vararg)
271 goto Efew;
272 args[count].arg = NULL;
273 args[count].n_normal = p->normal;
274 args[count].n_quoted = p->quoted;
275 args[count].n_str = p->str;
277 if (count < wanted - 1)
278 goto Efew;
280 what->next = next->next;
281 return 1;
283 Efew:
284 sparse_error(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
285 show_token(what), wanted, count);
286 goto out;
287 Emany:
288 while (match_op(next, ',')) {
289 next = collect_arg(next, 0, &what->pos);
290 count++;
292 if (eof_token(next))
293 goto Eclosing;
294 sparse_error(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
295 show_token(what), count, wanted);
296 goto out;
297 Eclosing:
298 sparse_error(what->pos, "unterminated argument list invoking macro \"%s\"",
299 show_token(what));
300 out:
301 what->next = next->next;
302 return 0;
305 static struct token *dup_list(struct token *list)
307 struct token *res = NULL;
308 struct token **p = &res;
310 while (!eof_token(list)) {
311 struct token *newtok = __alloc_token(0);
312 *newtok = *list;
313 *p = newtok;
314 p = &newtok->next;
315 list = list->next;
317 return res;
320 static struct token *stringify(struct token *arg)
322 const char *s = show_token_sequence(arg);
323 int size = strlen(s)+1;
324 struct token *token = __alloc_token(0);
325 struct string *string = __alloc_string(size);
327 memcpy(string->data, s, size);
328 string->length = size;
329 token->pos = arg->pos;
330 token_type(token) = TOKEN_STRING;
331 token->string = string;
332 token->next = &eof_token_entry;
333 return token;
336 static void expand_arguments(int count, struct arg *args)
338 int i;
339 for (i = 0; i < count; i++) {
340 struct token *arg = args[i].arg;
341 if (!arg)
342 arg = &eof_token_entry;
343 if (args[i].n_str)
344 args[i].str = stringify(arg);
345 if (args[i].n_normal) {
346 if (!args[i].n_quoted) {
347 args[i].expanded = arg;
348 args[i].arg = NULL;
349 } else if (eof_token(arg)) {
350 args[i].expanded = arg;
351 } else {
352 args[i].expanded = dup_list(arg);
354 expand_list(&args[i].expanded);
360 * Possibly valid combinations:
361 * - ident + ident -> ident
362 * - ident + number -> ident unless number contains '.', '+' or '-'.
363 * - number + number -> number
364 * - number + ident -> number
365 * - number + '.' -> number
366 * - number + '+' or '-' -> number, if number used to end on [eEpP].
367 * - '.' + number -> number, if number used to start with a digit.
368 * - special + special -> either special or an error.
370 static enum token_type combine(struct token *left, struct token *right, char *p)
372 int len;
373 enum token_type t1 = token_type(left), t2 = token_type(right);
375 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
376 return TOKEN_ERROR;
378 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
379 return TOKEN_ERROR;
381 strcpy(p, show_token(left));
382 strcat(p, show_token(right));
383 len = strlen(p);
385 if (len >= 256)
386 return TOKEN_ERROR;
388 if (t1 == TOKEN_IDENT) {
389 if (t2 == TOKEN_SPECIAL)
390 return TOKEN_ERROR;
391 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
392 return TOKEN_ERROR;
393 return TOKEN_IDENT;
396 if (t1 == TOKEN_NUMBER) {
397 if (t2 == TOKEN_SPECIAL) {
398 switch (right->special) {
399 case '.':
400 break;
401 case '+': case '-':
402 if (strchr("eEpP", p[len - 2]))
403 break;
404 default:
405 return TOKEN_ERROR;
408 return TOKEN_NUMBER;
411 if (p[0] == '.' && isdigit((unsigned char)p[1]))
412 return TOKEN_NUMBER;
414 return TOKEN_SPECIAL;
417 static int merge(struct token *left, struct token *right)
419 static char buffer[512];
420 int n;
422 switch (combine(left, right, buffer)) {
423 case TOKEN_IDENT:
424 left->ident = built_in_ident(buffer);
425 left->pos.noexpand = 0;
426 return 1;
428 case TOKEN_NUMBER: {
429 char *number = __alloc_bytes(strlen(buffer) + 1);
430 memcpy(number, buffer, strlen(buffer) + 1);
431 token_type(left) = TOKEN_NUMBER; /* could be . + num */
432 left->number = number;
433 return 1;
436 case TOKEN_SPECIAL:
437 if (buffer[2] && buffer[3])
438 break;
439 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
440 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
441 left->special = n;
442 return 1;
445 default:
448 sparse_error(left->pos, "'##' failed: concatenation is not a valid token");
449 return 0;
452 static struct token *dup_token(struct token *token, struct position *streampos, struct position *pos)
454 struct token *alloc = alloc_token(streampos);
455 token_type(alloc) = token_type(token);
456 alloc->pos.newline = pos->newline;
457 alloc->pos.whitespace = pos->whitespace;
458 alloc->number = token->number;
459 alloc->pos.noexpand = token->pos.noexpand;
460 return alloc;
463 static struct token **copy(struct token **where, struct token *list, int *count)
465 int need_copy = --*count;
466 while (!eof_token(list)) {
467 struct token *token;
468 if (need_copy)
469 token = dup_token(list, &list->pos, &list->pos);
470 else
471 token = list;
472 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
473 token->pos.noexpand = 1;
474 *where = token;
475 where = &token->next;
476 list = list->next;
478 *where = &eof_token_entry;
479 return where;
482 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
484 struct token *token = *list;
485 struct position *base_pos = &token->pos;
486 struct position *pos = base_pos;
487 int *count;
488 enum {Normal, Placeholder, Concat} state = Normal;
490 for (; !eof_token(body); body = body->next, pos = &body->pos) {
491 struct token *added, *arg;
492 struct token **tail;
494 switch (token_type(body)) {
495 case TOKEN_GNU_KLUDGE:
497 * GNU kludge: if we had <comma>##<vararg>, behaviour
498 * depends on whether we had enough arguments to have
499 * a vararg. If we did, ## is just ignored. Otherwise
500 * both , and ## are ignored. Comma should come from
501 * the body of macro and not be an argument of earlier
502 * concatenation.
504 if (!args[body->next->argnum].arg)
505 continue;
506 added = dup_token(body, base_pos, pos);
507 token_type(added) = TOKEN_SPECIAL;
508 tail = &added->next;
509 break;
511 case TOKEN_STR_ARGUMENT:
512 arg = args[body->argnum].str;
513 count = &args[body->argnum].n_str;
514 goto copy_arg;
516 case TOKEN_QUOTED_ARGUMENT:
517 arg = args[body->argnum].arg;
518 count = &args[body->argnum].n_quoted;
519 if (!arg || eof_token(arg)) {
520 if (state == Concat)
521 state = Normal;
522 else
523 state = Placeholder;
524 continue;
526 goto copy_arg;
528 case TOKEN_MACRO_ARGUMENT:
529 arg = args[body->argnum].expanded;
530 count = &args[body->argnum].n_normal;
531 if (eof_token(arg)) {
532 state = Normal;
533 continue;
535 copy_arg:
536 tail = copy(&added, arg, count);
537 added->pos.newline = pos->newline;
538 added->pos.whitespace = pos->whitespace;
539 break;
541 case TOKEN_CONCAT:
542 if (state == Placeholder)
543 state = Normal;
544 else
545 state = Concat;
546 continue;
548 case TOKEN_IDENT:
549 added = dup_token(body, base_pos, pos);
550 if (added->ident->tainted)
551 added->pos.noexpand = 1;
552 tail = &added->next;
553 break;
555 default:
556 added = dup_token(body, base_pos, pos);
557 tail = &added->next;
558 break;
562 * if we got to doing real concatenation, we already have
563 * added something into the list, so containing_token() is OK.
565 if (state == Concat && merge(containing_token(list), added)) {
566 *list = added->next;
567 if (tail != &added->next)
568 list = tail;
569 } else {
570 *list = added;
571 list = tail;
573 state = Normal;
575 *list = &eof_token_entry;
576 return list;
579 static int expand(struct token **list, struct symbol *sym)
581 struct token *last;
582 struct token *token = *list;
583 struct ident *expanding = token->ident;
584 struct token **tail;
585 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
586 struct arg args[nargs];
588 if (expanding->tainted) {
589 token->pos.noexpand = 1;
590 return 1;
593 if (sym->arglist) {
594 if (!match_op(scan_next(&token->next), '('))
595 return 1;
596 if (!collect_arguments(token->next, sym->arglist, args, token))
597 return 1;
598 expand_arguments(nargs, args);
601 expanding->tainted = 1;
603 last = token->next;
604 tail = substitute(list, sym->expansion, args);
605 *tail = last;
607 return 0;
610 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
612 struct token *last;
613 static char buffer[256];
614 char *ptr = buffer;
616 last = token;
617 while (!eof_token(token) && !match_op(token, endop)) {
618 int len;
619 const char *val = token->string->data;
620 if (token_type(token) != TOKEN_STRING)
621 val = show_token(token);
622 len = strlen(val);
623 memcpy(ptr, val, len);
624 ptr += len;
625 token = token->next;
627 *ptr = 0;
628 if (endop && !match_op(token, endop))
629 sparse_error(start->pos, "expected '>' at end of filename");
630 return buffer;
633 static int already_tokenized(const char *path)
635 int i;
636 struct stream *s = input_streams;
638 for (i = input_stream_nr; --i >= 0; s++) {
639 if (s->constant != CONSTANT_FILE_YES)
640 continue;
641 if (strcmp(path, s->name))
642 continue;
643 if (s->protect && !lookup_macro(s->protect))
644 continue;
645 return 1;
647 return 0;
650 /* Handle include of header files.
651 * The relevant options are made compatible with gcc. The only options that
652 * are not supported is -withprefix and friends.
654 * Three set of include paths are known:
655 * quote_includepath: Path to search when using #include "file.h"
656 * angle_includepath: Path to search when using #include <file.h>
657 * sys_includepath: Built-in include paths
659 * The above is implemented as one array with pointers
660 * +--------------+
661 * quote_includepath ---> | |
662 * +--------------+
663 * | |
664 * +--------------+
665 * angle_includepath ---> | |
666 * +--------------+
667 * sys_includepath ---> | |
668 * +--------------+
669 * | |
670 * +--------------+
672 * -I dir insert dir just before sys_includepath and move the rest
673 * -I- makes all dirs specified with -I before to quote dirs only and
674 * angle_includepath is set equal to sys_includepath.
675 * -nostdinc removes all sys dirs be storing NULL in entry pointed
676 * to by * sys_includepath. Note this will reset all dirs built-in and added
677 * before -nostdinc by -isystem and -dirafter
678 * -isystem dir adds dir where sys_includepath points adding this dir as
679 * first systemdir
680 * -dirafter dir adds dir to the end of the list
683 static void set_stream_include_path(struct stream *stream)
685 const char *path = stream->path;
686 if (!path) {
687 const char *p = strrchr(stream->name, '/');
688 path = "";
689 if (p) {
690 int len = p - stream->name + 1;
691 char *m = malloc(len+1);
692 /* This includes the final "/" */
693 memcpy(m, stream->name, len);
694 m[len] = 0;
695 path = m;
697 stream->path = path;
699 includepath[0] = path;
702 static int try_include(const char *path, const char *filename, int flen, struct token **where, const char **next_path)
704 int fd;
705 int plen = strlen(path);
706 static char fullname[PATH_MAX];
708 memcpy(fullname, path, plen);
709 if (plen && path[plen-1] != '/') {
710 fullname[plen] = '/';
711 plen++;
713 memcpy(fullname+plen, filename, flen);
714 if (already_tokenized(fullname))
715 return 1;
716 fd = open(fullname, O_RDONLY);
717 if (fd >= 0) {
718 char * streamname = __alloc_bytes(plen + flen);
719 memcpy(streamname, fullname, plen + flen);
720 *where = tokenize(streamname, fd, *where, next_path);
721 close(fd);
722 return 1;
724 return 0;
727 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
729 const char *path;
731 while ((path = *pptr++) != NULL) {
732 if (!try_include(path, filename, flen, list, pptr))
733 continue;
734 return 1;
736 return 0;
739 static void do_include(int local, struct stream *stream, struct token **list, struct token *token, const char *filename, const char **path)
741 int flen = strlen(filename) + 1;
743 /* Absolute path? */
744 if (filename[0] == '/') {
745 if (try_include("", filename, flen, list, includepath))
746 return;
747 goto out;
750 /* Dir of input file is first dir to search for quoted includes */
751 set_stream_include_path(stream);
753 if (!path)
754 /* Do not search quote include if <> is in use */
755 path = local ? quote_includepath : angle_includepath;
757 /* Check the standard include paths.. */
758 if (do_include_path(path, list, token, filename, flen))
759 return;
760 out:
761 error_die(token->pos, "unable to open '%s'", filename);
764 static int free_preprocessor_line(struct token *token)
766 do {
767 struct token *free = token;
768 token = token->next;
769 __free_token(free);
770 } while (token_type(token) != TOKEN_EOF);
771 return 1;
774 static int handle_include_path(struct stream *stream, struct token **list, struct token *token, const char **path)
776 const char *filename;
777 struct token *next;
778 int expect;
780 next = token->next;
781 expect = '>';
782 if (!match_op(next, '<')) {
783 expand_list(&token->next);
784 expect = 0;
785 next = token;
786 if (match_op(token->next, '<')) {
787 next = token->next;
788 expect = '>';
791 token = next->next;
792 filename = token_name_sequence(token, expect, token);
793 do_include(!expect, stream, list, token, filename, path);
794 return 0;
797 static int handle_include(struct stream *stream, struct token **list, struct token *token)
799 return handle_include_path(stream, list, token, NULL);
802 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
804 return handle_include_path(stream, list, token, stream->next_path);
807 static int token_different(struct token *t1, struct token *t2)
809 int different;
811 if (token_type(t1) != token_type(t2))
812 return 1;
814 switch (token_type(t1)) {
815 case TOKEN_IDENT:
816 different = t1->ident != t2->ident;
817 break;
818 case TOKEN_ARG_COUNT:
819 case TOKEN_UNTAINT:
820 case TOKEN_CONCAT:
821 case TOKEN_GNU_KLUDGE:
822 different = 0;
823 break;
824 case TOKEN_NUMBER:
825 different = strcmp(t1->number, t2->number);
826 break;
827 case TOKEN_SPECIAL:
828 different = t1->special != t2->special;
829 break;
830 case TOKEN_MACRO_ARGUMENT:
831 case TOKEN_QUOTED_ARGUMENT:
832 case TOKEN_STR_ARGUMENT:
833 different = t1->argnum != t2->argnum;
834 break;
835 case TOKEN_CHAR:
836 different = t1->character != t2->character;
837 break;
838 case TOKEN_STRING: {
839 struct string *s1, *s2;
841 s1 = t1->string;
842 s2 = t2->string;
843 different = 1;
844 if (s1->length != s2->length)
845 break;
846 different = memcmp(s1->data, s2->data, s1->length);
847 break;
849 default:
850 different = 1;
851 break;
853 return different;
856 static int token_list_different(struct token *list1, struct token *list2)
858 for (;;) {
859 if (list1 == list2)
860 return 0;
861 if (!list1 || !list2)
862 return 1;
863 if (token_different(list1, list2))
864 return 1;
865 list1 = list1->next;
866 list2 = list2->next;
870 static inline void set_arg_count(struct token *token)
872 token_type(token) = TOKEN_ARG_COUNT;
873 token->count.normal = token->count.quoted =
874 token->count.str = token->count.vararg = 0;
877 static struct token *parse_arguments(struct token *list)
879 struct token *arg = list->next, *next = list;
880 struct argcount *count = &list->count;
882 set_arg_count(list);
884 if (match_op(arg, ')')) {
885 next = arg->next;
886 list->next = &eof_token_entry;
887 return next;
890 while (token_type(arg) == TOKEN_IDENT) {
891 if (arg->ident == &__VA_ARGS___ident)
892 goto Eva_args;
893 if (!++count->normal)
894 goto Eargs;
895 next = arg->next;
897 if (match_op(next, ',')) {
898 set_arg_count(next);
899 arg = next->next;
900 continue;
903 if (match_op(next, ')')) {
904 set_arg_count(next);
905 next = next->next;
906 arg->next->next = &eof_token_entry;
907 return next;
910 /* normal cases are finished here */
912 if (match_op(next, SPECIAL_ELLIPSIS)) {
913 if (match_op(next->next, ')')) {
914 set_arg_count(next);
915 next->count.vararg = 1;
916 next = next->next;
917 arg->next->next = &eof_token_entry;
918 return next->next;
921 arg = next;
922 goto Enotclosed;
925 if (eof_token(next)) {
926 goto Enotclosed;
927 } else {
928 arg = next;
929 goto Ebadstuff;
933 if (match_op(arg, SPECIAL_ELLIPSIS)) {
934 next = arg->next;
935 token_type(arg) = TOKEN_IDENT;
936 arg->ident = &__VA_ARGS___ident;
937 if (!match_op(next, ')'))
938 goto Enotclosed;
939 if (!++count->normal)
940 goto Eargs;
941 set_arg_count(next);
942 next->count.vararg = 1;
943 next = next->next;
944 arg->next->next = &eof_token_entry;
945 return next;
948 if (eof_token(arg)) {
949 arg = next;
950 goto Enotclosed;
952 if (match_op(arg, ','))
953 goto Emissing;
954 else
955 goto Ebadstuff;
958 Emissing:
959 sparse_error(arg->pos, "parameter name missing");
960 return NULL;
961 Ebadstuff:
962 sparse_error(arg->pos, "\"%s\" may not appear in macro parameter list",
963 show_token(arg));
964 return NULL;
965 Enotclosed:
966 sparse_error(arg->pos, "missing ')' in macro parameter list");
967 return NULL;
968 Eva_args:
969 sparse_error(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
970 return NULL;
971 Eargs:
972 sparse_error(arg->pos, "too many arguments in macro definition");
973 return NULL;
976 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
978 struct ident *ident = token->ident;
979 int nr;
981 if (!arglist || token_type(token) != TOKEN_IDENT)
982 return 0;
984 arglist = arglist->next;
986 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
987 if (arglist->ident == ident) {
988 struct argcount *count = &arglist->next->count;
989 int n;
991 token->argnum = nr;
992 token_type(token) = type;
993 switch (type) {
994 case TOKEN_MACRO_ARGUMENT:
995 n = ++count->normal;
996 break;
997 case TOKEN_QUOTED_ARGUMENT:
998 n = ++count->quoted;
999 break;
1000 default:
1001 n = ++count->str;
1003 if (n)
1004 return count->vararg ? 2 : 1;
1005 token_type(token) = TOKEN_ERROR;
1006 return -1;
1009 return 0;
1012 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
1014 struct token *token = expansion;
1015 struct token **p;
1016 struct token *last = NULL;
1018 if (match_op(token, SPECIAL_HASHHASH))
1019 goto Econcat;
1021 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
1022 if (match_op(token, '#')) {
1023 if (arglist) {
1024 struct token *next = token->next;
1025 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
1026 goto Equote;
1027 next->pos.whitespace = token->pos.whitespace;
1028 token = *p = next;
1029 } else {
1030 token->pos.noexpand = 1;
1032 } else if (match_op(token, SPECIAL_HASHHASH)) {
1033 struct token *next = token->next;
1034 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
1035 token_type(token) = TOKEN_CONCAT;
1036 if (arg) {
1037 token = next;
1038 /* GNU kludge */
1039 if (arg == 2 && last && match_op(last, ',')) {
1040 token_type(last) = TOKEN_GNU_KLUDGE;
1041 last->next = token;
1043 } else if (match_op(next, SPECIAL_HASHHASH))
1044 token = next;
1045 else if (eof_token(next))
1046 goto Econcat;
1047 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
1048 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
1049 } else {
1050 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
1052 if (token_type(token) == TOKEN_ERROR)
1053 goto Earg;
1054 last = token;
1056 token = alloc_token(&expansion->pos);
1057 token_type(token) = TOKEN_UNTAINT;
1058 token->ident = name;
1059 token->next = *p;
1060 *p = token;
1061 return expansion;
1063 Equote:
1064 sparse_error(token->pos, "'#' is not followed by a macro parameter");
1065 return NULL;
1067 Econcat:
1068 sparse_error(token->pos, "'##' cannot appear at the ends of macro expansion");
1069 return NULL;
1070 Earg:
1071 sparse_error(token->pos, "too many instances of argument in body");
1072 return NULL;
1075 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int attr)
1077 struct token *arglist, *expansion;
1078 struct token *left = token->next;
1079 struct symbol *sym;
1080 struct ident *name;
1081 int ret;
1083 if (token_type(left) != TOKEN_IDENT) {
1084 sparse_error(token->pos, "expected identifier to 'define'");
1085 return 1;
1088 name = left->ident;
1090 arglist = NULL;
1091 expansion = left->next;
1092 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
1093 arglist = expansion;
1094 expansion = parse_arguments(expansion);
1095 if (!expansion)
1096 return 1;
1099 expansion = parse_expansion(expansion, arglist, name);
1100 if (!expansion)
1101 return 1;
1103 ret = 1;
1104 sym = lookup_symbol(name, NS_MACRO | NS_UNDEF);
1105 if (sym) {
1106 int clean;
1108 if (attr < sym->attr)
1109 goto out;
1111 clean = (attr == sym->attr && sym->namespace == NS_MACRO);
1113 if (token_list_different(sym->expansion, expansion) ||
1114 token_list_different(sym->arglist, arglist)) {
1115 ret = 0;
1116 if ((clean && attr == SYM_ATTR_NORMAL)
1117 || sym->used_in == file_scope) {
1118 warning(left->pos, "preprocessor token %.*s redefined",
1119 name->len, name->name);
1120 info(sym->pos, "this was the original definition");
1122 } else if (clean)
1123 goto out;
1126 if (!sym || sym->scope != file_scope) {
1127 sym = alloc_symbol(left->pos, SYM_NODE);
1128 bind_symbol(sym, name, NS_MACRO);
1129 ret = 0;
1132 if (!ret) {
1133 sym->expansion = expansion;
1134 sym->arglist = arglist;
1135 __free_token(token); /* Free the "define" token, but not the rest of the line */
1138 sym->namespace = NS_MACRO;
1139 sym->used_in = NULL;
1140 sym->attr = attr;
1141 out:
1142 return ret;
1145 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1147 return do_handle_define(stream, line, token, SYM_ATTR_NORMAL);
1150 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1152 return do_handle_define(stream, line, token, SYM_ATTR_WEAK);
1155 static int handle_strong_define(struct stream *stream, struct token **line, struct token *token)
1157 return do_handle_define(stream, line, token, SYM_ATTR_STRONG);
1160 static int do_handle_undef(struct stream *stream, struct token **line, struct token *token, int attr)
1162 struct token *left = token->next;
1163 struct symbol *sym;
1165 if (token_type(left) != TOKEN_IDENT) {
1166 sparse_error(token->pos, "expected identifier to 'undef'");
1167 return 1;
1170 sym = lookup_symbol(left->ident, NS_MACRO | NS_UNDEF);
1171 if (sym) {
1172 if (attr < sym->attr)
1173 return 1;
1174 if (attr == sym->attr && sym->namespace == NS_UNDEF)
1175 return 1;
1176 } else if (attr <= SYM_ATTR_NORMAL)
1177 return 1;
1179 if (!sym || sym->scope != file_scope) {
1180 sym = alloc_symbol(left->pos, SYM_NODE);
1181 bind_symbol(sym, left->ident, NS_MACRO);
1184 sym->namespace = NS_UNDEF;
1185 sym->used_in = NULL;
1186 sym->attr = attr;
1188 return 1;
1191 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1193 return do_handle_undef(stream, line, token, SYM_ATTR_NORMAL);
1196 static int handle_strong_undef(struct stream *stream, struct token **line, struct token *token)
1198 return do_handle_undef(stream, line, token, SYM_ATTR_STRONG);
1201 static int preprocessor_if(struct stream *stream, struct token *token, int true)
1203 token_type(token) = false_nesting ? TOKEN_SKIP_GROUPS : TOKEN_IF;
1204 free_preprocessor_line(token->next);
1205 token->next = stream->top_if;
1206 stream->top_if = token;
1207 if (false_nesting || true != 1)
1208 false_nesting++;
1209 return 0;
1212 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1214 struct token *next = token->next;
1215 int arg;
1216 if (token_type(next) == TOKEN_IDENT) {
1217 arg = token_defined(next);
1218 } else {
1219 dirty_stream(stream);
1220 if (!false_nesting)
1221 sparse_error(token->pos, "expected preprocessor identifier");
1222 arg = -1;
1224 return preprocessor_if(stream, token, arg);
1227 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1229 struct token *next = token->next;
1230 int arg;
1231 if (token_type(next) == TOKEN_IDENT) {
1232 if (!stream->dirty && !stream->ifndef) {
1233 if (!stream->protect) {
1234 stream->ifndef = token;
1235 stream->protect = next->ident;
1236 } else if (stream->protect == next->ident) {
1237 stream->ifndef = token;
1238 stream->dirty = 1;
1241 arg = !token_defined(next);
1242 } else {
1243 dirty_stream(stream);
1244 if (!false_nesting)
1245 sparse_error(token->pos, "expected preprocessor identifier");
1246 arg = -1;
1249 return preprocessor_if(stream, token, arg);
1253 * Expression handling for #if and #elif; it differs from normal expansion
1254 * due to special treatment of "defined".
1256 static int expression_value(struct token **where)
1258 struct expression *expr;
1259 struct token *p;
1260 struct token **list = where, **beginning = NULL;
1261 long long value;
1262 int state = 0;
1264 while (!eof_token(p = scan_next(list))) {
1265 switch (state) {
1266 case 0:
1267 if (token_type(p) != TOKEN_IDENT)
1268 break;
1269 if (p->ident == &defined_ident) {
1270 state = 1;
1271 beginning = list;
1272 break;
1274 if (!expand_one_symbol(list))
1275 continue;
1276 if (token_type(p) != TOKEN_IDENT)
1277 break;
1278 token_type(p) = TOKEN_ZERO_IDENT;
1279 break;
1280 case 1:
1281 if (match_op(p, '(')) {
1282 state = 2;
1283 } else {
1284 state = 0;
1285 replace_with_defined(p);
1286 *beginning = p;
1288 break;
1289 case 2:
1290 if (token_type(p) == TOKEN_IDENT)
1291 state = 3;
1292 else
1293 state = 0;
1294 replace_with_defined(p);
1295 *beginning = p;
1296 break;
1297 case 3:
1298 state = 0;
1299 if (!match_op(p, ')'))
1300 sparse_error(p->pos, "missing ')' after \"defined\"");
1301 *list = p->next;
1302 continue;
1304 list = &p->next;
1307 p = constant_expression(*where, &expr);
1308 if (!eof_token(p))
1309 sparse_error(p->pos, "garbage at end: %s", show_token_sequence(p));
1310 value = get_expression_value(expr);
1311 return value != 0;
1314 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1316 int value = 0;
1317 if (!false_nesting)
1318 value = expression_value(&token->next);
1320 dirty_stream(stream);
1321 return preprocessor_if(stream, token, value);
1324 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1326 struct token *top_if = stream->top_if;
1327 end_group(stream);
1329 if (!top_if) {
1330 nesting_error(stream);
1331 sparse_error(token->pos, "unmatched #elif within stream");
1332 return 1;
1335 if (token_type(top_if) == TOKEN_ELSE) {
1336 nesting_error(stream);
1337 sparse_error(token->pos, "#elif after #else");
1338 if (!false_nesting)
1339 false_nesting = 1;
1340 return 1;
1343 dirty_stream(stream);
1344 if (token_type(top_if) != TOKEN_IF)
1345 return 1;
1346 if (false_nesting) {
1347 if (expression_value(&token->next))
1348 false_nesting = 0;
1349 } else {
1350 false_nesting = 1;
1351 token_type(top_if) = TOKEN_SKIP_GROUPS;
1353 return 1;
1356 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1358 struct token *top_if = stream->top_if;
1359 end_group(stream);
1361 if (!top_if) {
1362 nesting_error(stream);
1363 sparse_error(token->pos, "unmatched #else within stream");
1364 return 1;
1367 if (token_type(top_if) == TOKEN_ELSE) {
1368 nesting_error(stream);
1369 sparse_error(token->pos, "#else after #else");
1371 if (false_nesting) {
1372 if (token_type(top_if) == TOKEN_IF)
1373 false_nesting = 0;
1374 } else {
1375 false_nesting = 1;
1377 token_type(top_if) = TOKEN_ELSE;
1378 return 1;
1381 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1383 struct token *top_if = stream->top_if;
1384 end_group(stream);
1385 if (!top_if) {
1386 nesting_error(stream);
1387 sparse_error(token->pos, "unmatched #endif in stream");
1388 return 1;
1390 if (false_nesting)
1391 false_nesting--;
1392 stream->top_if = top_if->next;
1393 __free_token(top_if);
1394 return 1;
1397 static const char *show_token_sequence(struct token *token)
1399 static char buffer[1024];
1400 char *ptr = buffer;
1401 int whitespace = 0;
1403 if (!token)
1404 return "<none>";
1405 while (!eof_token(token)) {
1406 const char *val = show_token(token);
1407 int len = strlen(val);
1409 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
1410 sparse_error(token->pos, "too long token expansion");
1411 break;
1414 if (whitespace)
1415 *ptr++ = ' ';
1416 memcpy(ptr, val, len);
1417 ptr += len;
1418 token = token->next;
1419 whitespace = token->pos.whitespace;
1421 *ptr = 0;
1422 return buffer;
1425 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1427 warning(token->pos, "%s", show_token_sequence(token->next));
1428 return 1;
1431 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1433 sparse_error(token->pos, "%s", show_token_sequence(token->next));
1434 return 1;
1437 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1440 * Do we have any non-system includes?
1441 * Clear them out if so..
1443 *sys_includepath = NULL;
1444 return 1;
1447 static void add_path_entry(struct token *token, const char *path, const char ***where, const char **new_path)
1449 const char **dst;
1450 const char *next;
1452 /* Need one free entry.. */
1453 if (includepath[INCLUDEPATHS-2])
1454 error_die(token->pos, "too many include path entries");
1456 /* check that this is not a duplicate */
1457 dst = includepath;
1458 while (*dst) {
1459 if (strcmp(*dst, path) == 0)
1460 return;
1461 dst++;
1463 next = path;
1464 dst = *where;
1465 *where = new_path;
1468 * Move them all up starting at dst,
1469 * insert the new entry..
1471 for (;;) {
1472 const char *tmp = *dst;
1473 *dst = next;
1474 if (!next)
1475 break;
1476 next = tmp;
1477 dst++;
1481 static int handle_add_include(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 warning(token->pos, "expected path string");
1489 return 1;
1491 add_path_entry(token, token->string->data, &sys_includepath, sys_includepath + 1);
1495 static int handle_add_isystem(struct stream *stream, struct token **line, struct token *token)
1497 for (;;) {
1498 token = token->next;
1499 if (eof_token(token))
1500 return 1;
1501 if (token_type(token) != TOKEN_STRING) {
1502 sparse_error(token->pos, "expected path string");
1503 return 1;
1505 add_path_entry(token, token->string->data, &sys_includepath, sys_includepath);
1509 /* Add to end on includepath list - no pointer updates */
1510 static void add_dirafter_entry(struct token *token, const char *path)
1512 const char **dst = includepath;
1514 /* Need one free entry.. */
1515 if (includepath[INCLUDEPATHS-2])
1516 error_die(token->pos, "too many include path entries");
1518 /* Add to the end */
1519 while (*dst)
1520 dst++;
1521 *dst = path;
1522 dst++;
1523 *dst = NULL;
1526 static int handle_add_dirafter(struct stream *stream, struct token **line, struct token *token)
1528 for (;;) {
1529 token = token->next;
1530 if (eof_token(token))
1531 return 1;
1532 if (token_type(token) != TOKEN_STRING) {
1533 sparse_error(token->pos, "expected path string");
1534 return 1;
1536 add_dirafter_entry(token, token->string->data);
1540 static int handle_split_include(struct stream *stream, struct token **line, struct token *token)
1543 * -I-
1544 * From info gcc:
1545 * Split the include path. Any directories specified with `-I'
1546 * options before `-I-' are searched only for headers requested with
1547 * `#include "FILE"'; they are not searched for `#include <FILE>'.
1548 * If additional directories are specified with `-I' options after
1549 * the `-I-', those directories are searched for all `#include'
1550 * directives.
1551 * In addition, `-I-' inhibits the use of the directory of the current
1552 * file directory as the first search directory for `#include "FILE"'.
1554 quote_includepath = includepath+1;
1555 angle_includepath = sys_includepath;
1556 return 1;
1560 * We replace "#pragma xxx" with "__pragma__" in the token
1561 * stream. Just as an example.
1563 * We'll just #define that away for now, but the theory here
1564 * is that we can use this to insert arbitrary token sequences
1565 * to turn the pragmas into internal front-end sequences for
1566 * when we actually start caring about them.
1568 * So eventually this will turn into some kind of extended
1569 * __attribute__() like thing, except called __pragma__(xxx).
1571 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1573 struct token *next = *line;
1575 token->ident = &pragma_ident;
1576 token->pos.newline = 1;
1577 token->pos.whitespace = 1;
1578 token->pos.pos = 1;
1579 *line = token;
1580 token->next = next;
1581 return 0;
1585 * We ignore #line for now.
1587 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1589 return 1;
1592 static int handle_nondirective(struct stream *stream, struct token **line, struct token *token)
1594 sparse_error(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1595 return 1;
1599 static void init_preprocessor(void)
1601 int i;
1602 int stream = init_stream("preprocessor", -1, includepath);
1603 static struct {
1604 const char *name;
1605 int (*handler)(struct stream *, struct token **, struct token *);
1606 } normal[] = {
1607 { "define", handle_define },
1608 { "weak_define", handle_weak_define },
1609 { "strong_define", handle_strong_define },
1610 { "undef", handle_undef },
1611 { "strong_undef", handle_strong_undef },
1612 { "warning", handle_warning },
1613 { "error", handle_error },
1614 { "include", handle_include },
1615 { "include_next", handle_include_next },
1616 { "pragma", handle_pragma },
1617 { "line", handle_line },
1619 // our internal preprocessor tokens
1620 { "nostdinc", handle_nostdinc },
1621 { "add_include", handle_add_include },
1622 { "add_isystem", handle_add_isystem },
1623 { "add_dirafter", handle_add_dirafter },
1624 { "split_include", handle_split_include },
1625 }, special[] = {
1626 { "ifdef", handle_ifdef },
1627 { "ifndef", handle_ifndef },
1628 { "else", handle_else },
1629 { "endif", handle_endif },
1630 { "if", handle_if },
1631 { "elif", handle_elif },
1634 for (i = 0; i < (sizeof (normal) / sizeof (normal[0])); i++) {
1635 struct symbol *sym;
1636 sym = create_symbol(stream, normal[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1637 sym->handler = normal[i].handler;
1638 sym->normal = 1;
1640 for (i = 0; i < (sizeof (special) / sizeof (special[0])); i++) {
1641 struct symbol *sym;
1642 sym = create_symbol(stream, special[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1643 sym->handler = special[i].handler;
1644 sym->normal = 0;
1649 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
1651 int (*handler)(struct stream *, struct token **, struct token *);
1652 struct token *token = start->next;
1653 int is_normal = 1;
1655 if (eof_token(token))
1656 return;
1658 if (token_type(token) == TOKEN_IDENT) {
1659 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
1660 if (sym) {
1661 handler = sym->handler;
1662 is_normal = sym->normal;
1663 } else {
1664 handler = handle_nondirective;
1666 } else if (token_type(token) == TOKEN_NUMBER) {
1667 handler = handle_line;
1668 } else {
1669 handler = handle_nondirective;
1672 if (is_normal) {
1673 dirty_stream(stream);
1674 if (false_nesting)
1675 goto out;
1677 if (!handler(stream, line, token)) /* all set */
1678 return;
1680 out:
1681 free_preprocessor_line(token);
1684 static void preprocessor_line(struct stream *stream, struct token **line)
1686 struct token *start = *line, *next;
1687 struct token **tp = &start->next;
1689 for (;;) {
1690 next = *tp;
1691 if (next->pos.newline)
1692 break;
1693 tp = &next->next;
1695 *line = next;
1696 *tp = &eof_token_entry;
1697 handle_preprocessor_line(stream, line, start);
1700 static void do_preprocess(struct token **list)
1702 struct token *next;
1704 while (!eof_token(next = scan_next(list))) {
1705 struct stream *stream = input_streams + next->pos.stream;
1707 if (next->pos.newline && match_op(next, '#')) {
1708 if (!next->pos.noexpand) {
1709 preprocessor_line(stream, list);
1710 __free_token(next); /* Free the '#' token */
1711 continue;
1715 switch (token_type(next)) {
1716 case TOKEN_STREAMEND:
1717 if (stream->top_if) {
1718 nesting_error(stream);
1719 sparse_error(stream->top_if->pos, "unterminated preprocessor conditional");
1720 stream->top_if = NULL;
1721 false_nesting = 0;
1723 if (!stream->dirty)
1724 stream->constant = CONSTANT_FILE_YES;
1725 *list = next->next;
1726 continue;
1727 case TOKEN_STREAMBEGIN:
1728 *list = next->next;
1729 continue;
1731 default:
1732 dirty_stream(stream);
1733 if (false_nesting) {
1734 *list = next->next;
1735 __free_token(next);
1736 continue;
1739 if (token_type(next) != TOKEN_IDENT ||
1740 expand_one_symbol(list))
1741 list = &next->next;
1746 struct token * preprocess(struct token *token)
1748 preprocessing = 1;
1749 init_preprocessor();
1750 do_preprocess(&token);
1752 // Drop all expressions from preprocessing, they're not used any more.
1753 // This is not true when we have multiple files, though ;/
1754 // clear_expression_alloc();
1755 preprocessing = 0;
1757 return token;