fix 'weak' attribute loss
[smatch.git] / pre-process.c
blob63f83dbb42fbc9203b3621c76484f022b1c13932
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 false_nesting = 0;
33 #define INCLUDEPATHS 300
34 const char *includepath[INCLUDEPATHS+1] = {
35 "",
36 "/usr/include",
37 "/usr/local/include",
38 GCC_INTERNAL_INCLUDE,
39 NULL
42 static const char **quote_includepath = includepath;
43 static const char **angle_includepath = includepath + 1;
44 static const char **sys_includepath = includepath + 1;
46 #define dirty_stream(stream) \
47 do { \
48 if (!stream->dirty) { \
49 stream->dirty = 1; \
50 if (!stream->ifndef) \
51 stream->protect = NULL; \
52 } \
53 } while(0)
55 #define end_group(stream) \
56 do { \
57 if (stream->ifndef == stream->top_if) { \
58 stream->ifndef = NULL; \
59 if (!stream->dirty) \
60 stream->protect = NULL; \
61 else if (stream->protect) \
62 stream->dirty = 0; \
63 } \
64 } while(0)
66 #define nesting_error(stream) \
67 do { \
68 stream->dirty = 1; \
69 stream->ifndef = NULL; \
70 stream->protect = NULL; \
71 } while(0)
73 static struct token *alloc_token(struct position *pos)
75 struct token *token = __alloc_token(0);
77 token->pos.stream = pos->stream;
78 token->pos.line = pos->line;
79 token->pos.pos = pos->pos;
80 token->pos.whitespace = 1;
81 return token;
84 static const char *show_token_sequence(struct token *token);
86 /* Expand symbol 'sym' at '*list' */
87 static int expand(struct token **, struct symbol *);
89 static void replace_with_string(struct token *token, const char *str)
91 int size = strlen(str) + 1;
92 struct string *s = __alloc_string(size);
94 s->length = size;
95 memcpy(s->data, str, size);
96 token_type(token) = TOKEN_STRING;
97 token->string = s;
100 static void replace_with_integer(struct token *token, unsigned int val)
102 char *buf = __alloc_bytes(11);
103 sprintf(buf, "%u", val);
104 token_type(token) = TOKEN_NUMBER;
105 token->number = buf;
108 static struct symbol *lookup_macro(struct ident *ident)
110 struct symbol *sym = lookup_symbol(ident, NS_MACRO | NS_UNDEF);
111 if (sym && sym->namespace != NS_MACRO)
112 sym = NULL;
113 return sym;
116 static int token_defined(struct token *token)
118 if (token_type(token) == TOKEN_IDENT) {
119 struct symbol *sym = lookup_macro(token->ident);
120 if (sym) {
121 sym->used_in = file_scope;
122 return 1;
124 return 0;
127 sparse_error(token->pos, "expected preprocessor identifier");
128 return 0;
131 static void replace_with_defined(struct token *token)
133 static const char *string[] = { "0", "1" };
134 int defined = token_defined(token);
136 token_type(token) = TOKEN_NUMBER;
137 token->number = string[defined];
140 static int expand_one_symbol(struct token **list)
142 struct token *token = *list;
143 struct symbol *sym;
145 if (token->pos.noexpand)
146 return 1;
148 sym = lookup_macro(token->ident);
149 if (sym) {
150 sym->used_in = file_scope;
151 return expand(list, sym);
153 if (token->ident == &__LINE___ident) {
154 replace_with_integer(token, token->pos.line);
155 } else if (token->ident == &__FILE___ident) {
156 replace_with_string(token, stream_name(token->pos.stream));
158 return 1;
161 static inline struct token *scan_next(struct token **where)
163 struct token *token = *where;
164 if (token_type(token) != TOKEN_UNTAINT)
165 return token;
166 do {
167 token->ident->tainted = 0;
168 token = token->next;
169 } while (token_type(token) == TOKEN_UNTAINT);
170 *where = token;
171 return token;
174 static void expand_list(struct token **list)
176 struct token *next;
177 while (!eof_token(next = scan_next(list))) {
178 if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list))
179 list = &next->next;
183 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
185 struct token **p = &prev->next;
186 struct token *next;
187 int nesting = 0;
189 while (!eof_token(next = scan_next(p))) {
190 if (match_op(next, '(')) {
191 nesting++;
192 } else if (match_op(next, ')')) {
193 if (!nesting--)
194 break;
195 } else if (match_op(next, ',') && !nesting && !vararg) {
196 break;
198 next->pos.stream = pos->stream;
199 next->pos.line = pos->line;
200 next->pos.pos = pos->pos;
201 p = &next->next;
203 *p = &eof_token_entry;
204 return next;
208 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
211 struct arg {
212 struct token *arg;
213 struct token *expanded;
214 struct token *str;
215 int n_normal;
216 int n_quoted;
217 int n_str;
220 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
222 int wanted = arglist->count.normal;
223 struct token *next = NULL;
224 int count = 0;
226 arglist = arglist->next; /* skip counter */
228 if (!wanted) {
229 next = collect_arg(start, 0, &what->pos);
230 if (eof_token(next))
231 goto Eclosing;
232 if (!eof_token(start->next) || !match_op(next, ')')) {
233 count++;
234 goto Emany;
236 } else {
237 for (count = 0; count < wanted; count++) {
238 struct argcount *p = &arglist->next->count;
239 next = collect_arg(start, p->vararg, &what->pos);
240 arglist = arglist->next->next;
241 if (eof_token(next))
242 goto Eclosing;
243 args[count].arg = start->next;
244 args[count].n_normal = p->normal;
245 args[count].n_quoted = p->quoted;
246 args[count].n_str = p->str;
247 if (match_op(next, ')')) {
248 count++;
249 break;
251 start = next;
253 if (count == wanted && !match_op(next, ')'))
254 goto Emany;
255 if (count == wanted - 1) {
256 struct argcount *p = &arglist->next->count;
257 if (!p->vararg)
258 goto Efew;
259 args[count].arg = NULL;
260 args[count].n_normal = p->normal;
261 args[count].n_quoted = p->quoted;
262 args[count].n_str = p->str;
264 if (count < wanted - 1)
265 goto Efew;
267 what->next = next->next;
268 return 1;
270 Efew:
271 sparse_error(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
272 show_token(what), wanted, count);
273 goto out;
274 Emany:
275 while (match_op(next, ',')) {
276 next = collect_arg(next, 0, &what->pos);
277 count++;
279 if (eof_token(next))
280 goto Eclosing;
281 sparse_error(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
282 show_token(what), count, wanted);
283 goto out;
284 Eclosing:
285 sparse_error(what->pos, "unterminated argument list invoking macro \"%s\"",
286 show_token(what));
287 out:
288 what->next = next->next;
289 return 0;
292 static struct token *dup_list(struct token *list)
294 struct token *res;
295 struct token **p = &res;
297 while (!eof_token(list)) {
298 struct token *newtok = __alloc_token(0);
299 *newtok = *list;
300 *p = newtok;
301 p = &newtok->next;
302 list = list->next;
304 return res;
307 static struct token *stringify(struct token *arg)
309 const char *s = show_token_sequence(arg);
310 int size = strlen(s)+1;
311 struct token *token = __alloc_token(0);
312 struct string *string = __alloc_string(size);
314 memcpy(string->data, s, size);
315 string->length = size;
316 token->pos = arg->pos;
317 token_type(token) = TOKEN_STRING;
318 token->string = string;
319 token->next = &eof_token_entry;
320 return token;
323 static void expand_arguments(int count, struct arg *args)
325 int i;
326 for (i = 0; i < count; i++) {
327 struct token *arg = args[i].arg;
328 if (!arg)
329 arg = &eof_token_entry;
330 if (args[i].n_str)
331 args[i].str = stringify(arg);
332 if (args[i].n_normal) {
333 if (!args[i].n_quoted) {
334 args[i].expanded = arg;
335 args[i].arg = NULL;
336 } else if (eof_token(arg)) {
337 args[i].expanded = arg;
338 } else {
339 args[i].expanded = dup_list(arg);
341 expand_list(&args[i].expanded);
347 * Possibly valid combinations:
348 * - ident + ident -> ident
349 * - ident + number -> ident unless number contains '.', '+' or '-'.
350 * - number + number -> number
351 * - number + ident -> number
352 * - number + '.' -> number
353 * - number + '+' or '-' -> number, if number used to end on [eEpP].
354 * - '.' + number -> number, if number used to start with a digit.
355 * - special + special -> either special or an error.
357 static enum token_type combine(struct token *left, struct token *right, char *p)
359 int len;
360 enum token_type t1 = token_type(left), t2 = token_type(right);
362 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
363 return TOKEN_ERROR;
365 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
366 return TOKEN_ERROR;
368 strcpy(p, show_token(left));
369 strcat(p, show_token(right));
370 len = strlen(p);
372 if (len >= 256)
373 return TOKEN_ERROR;
375 if (t1 == TOKEN_IDENT) {
376 if (t2 == TOKEN_SPECIAL)
377 return TOKEN_ERROR;
378 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
379 return TOKEN_ERROR;
380 return TOKEN_IDENT;
383 if (t1 == TOKEN_NUMBER) {
384 if (t2 == TOKEN_SPECIAL) {
385 switch (right->special) {
386 case '.':
387 break;
388 case '+': case '-':
389 if (strchr("eEpP", p[len - 2]))
390 break;
391 default:
392 return TOKEN_ERROR;
395 return TOKEN_NUMBER;
398 if (p[0] == '.' && isdigit((unsigned char)p[1]))
399 return TOKEN_NUMBER;
401 return TOKEN_SPECIAL;
404 static int merge(struct token *left, struct token *right)
406 static char buffer[512];
407 int n;
409 switch (combine(left, right, buffer)) {
410 case TOKEN_IDENT:
411 left->ident = built_in_ident(buffer);
412 left->pos.noexpand = 0;
413 return 1;
415 case TOKEN_NUMBER: {
416 char *number = __alloc_bytes(strlen(buffer) + 1);
417 memcpy(number, buffer, strlen(buffer) + 1);
418 token_type(left) = TOKEN_NUMBER; /* could be . + num */
419 left->number = number;
420 return 1;
423 case TOKEN_SPECIAL:
424 if (buffer[2] && buffer[3])
425 break;
426 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
427 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
428 left->special = n;
429 return 1;
432 default:
435 sparse_error(left->pos, "'##' failed: concatenation is not a valid token");
436 return 0;
439 static struct token *dup_token(struct token *token, struct position *streampos, struct position *pos)
441 struct token *alloc = alloc_token(streampos);
442 token_type(alloc) = token_type(token);
443 alloc->pos.newline = pos->newline;
444 alloc->pos.whitespace = pos->whitespace;
445 alloc->number = token->number;
446 alloc->pos.noexpand = token->pos.noexpand;
447 return alloc;
450 static struct token **copy(struct token **where, struct token *list, int *count)
452 int need_copy = --*count;
453 while (!eof_token(list)) {
454 struct token *token;
455 if (need_copy)
456 token = dup_token(list, &list->pos, &list->pos);
457 else
458 token = list;
459 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
460 token->pos.noexpand = 1;
461 *where = token;
462 where = &token->next;
463 list = list->next;
465 *where = &eof_token_entry;
466 return where;
469 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
471 struct token *token = *list;
472 struct position *base_pos = &token->pos;
473 struct position *pos = base_pos;
474 int *count;
475 enum {Normal, Placeholder, Concat} state = Normal;
477 for (; !eof_token(body); body = body->next, pos = &body->pos) {
478 struct token *added, *arg;
479 struct token **tail;
481 switch (token_type(body)) {
482 case TOKEN_GNU_KLUDGE:
484 * GNU kludge: if we had <comma>##<vararg>, behaviour
485 * depends on whether we had enough arguments to have
486 * a vararg. If we did, ## is just ignored. Otherwise
487 * both , and ## are ignored. Comma should come from
488 * the body of macro and not be an argument of earlier
489 * concatenation.
491 if (!args[body->next->argnum].arg)
492 continue;
493 added = dup_token(body, base_pos, pos);
494 token_type(added) = TOKEN_SPECIAL;
495 tail = &added->next;
496 break;
498 case TOKEN_STR_ARGUMENT:
499 arg = args[body->argnum].str;
500 count = &args[body->argnum].n_str;
501 goto copy_arg;
503 case TOKEN_QUOTED_ARGUMENT:
504 arg = args[body->argnum].arg;
505 count = &args[body->argnum].n_quoted;
506 if (!arg || eof_token(arg)) {
507 if (state == Concat)
508 state = Normal;
509 else
510 state = Placeholder;
511 continue;
513 goto copy_arg;
515 case TOKEN_MACRO_ARGUMENT:
516 arg = args[body->argnum].expanded;
517 count = &args[body->argnum].n_normal;
518 if (eof_token(arg)) {
519 state = Normal;
520 continue;
522 copy_arg:
523 tail = copy(&added, arg, count);
524 added->pos.newline = pos->newline;
525 added->pos.whitespace = pos->whitespace;
526 break;
528 case TOKEN_CONCAT:
529 if (state == Placeholder)
530 state = Normal;
531 else
532 state = Concat;
533 continue;
535 case TOKEN_IDENT:
536 added = dup_token(body, base_pos, pos);
537 if (added->ident->tainted)
538 added->pos.noexpand = 1;
539 tail = &added->next;
540 break;
542 default:
543 added = dup_token(body, base_pos, pos);
544 tail = &added->next;
545 break;
549 * if we got to doing real concatenation, we already have
550 * added something into the list, so containing_token() is OK.
552 if (state == Concat && merge(containing_token(list), added)) {
553 *list = added->next;
554 if (tail != &added->next)
555 list = tail;
556 } else {
557 *list = added;
558 list = tail;
560 state = Normal;
562 *list = &eof_token_entry;
563 return list;
566 static int expand(struct token **list, struct symbol *sym)
568 struct token *last;
569 struct token *token = *list;
570 struct ident *expanding = token->ident;
571 struct token **tail;
572 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
573 struct arg args[nargs];
575 if (expanding->tainted) {
576 token->pos.noexpand = 1;
577 return 1;
580 if (sym->arglist) {
581 if (!match_op(scan_next(&token->next), '('))
582 return 1;
583 if (!collect_arguments(token->next, sym->arglist, args, token))
584 return 1;
585 expand_arguments(nargs, args);
588 expanding->tainted = 1;
590 last = token->next;
591 tail = substitute(list, sym->expansion, args);
592 *tail = last;
594 return 0;
597 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
599 struct token *last;
600 static char buffer[256];
601 char *ptr = buffer;
603 last = token;
604 while (!eof_token(token) && !match_op(token, endop)) {
605 int len;
606 const char *val = token->string->data;
607 if (token_type(token) != TOKEN_STRING)
608 val = show_token(token);
609 len = strlen(val);
610 memcpy(ptr, val, len);
611 ptr += len;
612 token = token->next;
614 *ptr = 0;
615 if (endop && !match_op(token, endop))
616 sparse_error(start->pos, "expected '>' at end of filename");
617 return buffer;
620 static int already_tokenized(const char *path)
622 int i;
623 struct stream *s = input_streams;
625 for (i = input_stream_nr; --i >= 0; s++) {
626 if (s->constant != CONSTANT_FILE_YES)
627 continue;
628 if (strcmp(path, s->name))
629 continue;
630 if (s->protect && !lookup_macro(s->protect))
631 continue;
632 return 1;
634 return 0;
637 /* Handle include of header files.
638 * The relevant options are made compatible with gcc. The only options that
639 * are not supported is -withprefix and friends.
641 * Three set of include paths are known:
642 * quote_includepath: Path to search when using #include "file.h"
643 * angle_includepath: Path to search when using #include <file.h>
644 * sys_includepath: Built-in include paths
646 * The above is implmented as one array with pointes
647 * +--------------+
648 * quote_includepath ---> | |
649 * +--------------+
650 * | |
651 * +--------------+
652 * angle_includepath ---> | |
653 * +--------------+
654 * sys_includepath ---> | |
655 * +--------------+
656 * | |
657 * +--------------+
659 * -I dir insert dir just before sys_includepath and move the rest
660 * -I- makes all dirs specified with -I before to quote dirs only and
661 * angle_includepath is set equal to sys_includepath.
662 * -nostdinc removes all sys dirs be storing NULL in entry pointed
663 * to by * sys_includepath. Note this will reset all dirs built-in and added
664 * before -nostdinc by -isystem and -dirafter
665 * -isystem dir adds dir where sys_includepath points adding this dir as
666 * first systemdir
667 * -dirafter dir adds dir to the end of the list
670 static void set_stream_include_path(struct stream *stream)
672 const char *path = stream->path;
673 if (!path) {
674 const char *p = strrchr(stream->name, '/');
675 path = "";
676 if (p) {
677 int len = p - stream->name + 1;
678 char *m = malloc(len+1);
679 /* This includes the final "/" */
680 memcpy(m, stream->name, len);
681 m[len] = 0;
682 path = m;
684 stream->path = path;
686 includepath[0] = path;
689 static int try_include(const char *path, const char *filename, int flen, struct token **where, const char **next_path)
691 int fd;
692 int plen = strlen(path);
693 static char fullname[PATH_MAX];
695 memcpy(fullname, path, plen);
696 if (plen && path[plen-1] != '/') {
697 fullname[plen] = '/';
698 plen++;
700 memcpy(fullname+plen, filename, flen);
701 if (already_tokenized(fullname))
702 return 1;
703 fd = open(fullname, O_RDONLY);
704 if (fd >= 0) {
705 char * streamname = __alloc_bytes(plen + flen);
706 memcpy(streamname, fullname, plen + flen);
707 *where = tokenize(streamname, fd, *where, next_path);
708 close(fd);
709 return 1;
711 return 0;
714 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
716 const char *path;
718 while ((path = *pptr++) != NULL) {
719 if (!try_include(path, filename, flen, list, pptr))
720 continue;
721 return 1;
723 return 0;
726 static void do_include(int local, struct stream *stream, struct token **list, struct token *token, const char *filename, const char **path)
728 int flen = strlen(filename) + 1;
730 /* Absolute path? */
731 if (filename[0] == '/') {
732 if (try_include("", filename, flen, list, includepath))
733 return;
734 goto out;
737 /* Dir of inputfile is first dir to search for quoted includes */
738 set_stream_include_path(stream);
740 if (!path)
741 /* Do not search quote include if <> is in use */
742 path = local ? quote_includepath : angle_includepath;
744 /* Check the standard include paths.. */
745 if (do_include_path(path, list, token, filename, flen))
746 return;
747 out:
748 error_die(token->pos, "unable to open '%s'", filename);
751 static int free_preprocessor_line(struct token *token)
753 do {
754 struct token *free = token;
755 token = token->next;
756 __free_token(free);
757 } while (token_type(token) != TOKEN_EOF);
758 return 1;
761 static int handle_include_path(struct stream *stream, struct token **list, struct token *token, const char **path)
763 const char *filename;
764 struct token *next;
765 int expect;
767 next = token->next;
768 expect = '>';
769 if (!match_op(next, '<')) {
770 expand_list(&token->next);
771 expect = 0;
772 next = token;
773 if (match_op(token->next, '<')) {
774 next = token->next;
775 expect = '>';
778 token = next->next;
779 filename = token_name_sequence(token, expect, token);
780 do_include(!expect, stream, list, token, filename, path);
781 return 0;
784 static int handle_include(struct stream *stream, struct token **list, struct token *token)
786 return handle_include_path(stream, list, token, NULL);
789 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
791 return handle_include_path(stream, list, token, stream->next_path);
794 static int token_different(struct token *t1, struct token *t2)
796 int different;
798 if (token_type(t1) != token_type(t2))
799 return 1;
801 switch (token_type(t1)) {
802 case TOKEN_IDENT:
803 different = t1->ident != t2->ident;
804 break;
805 case TOKEN_ARG_COUNT:
806 case TOKEN_UNTAINT:
807 case TOKEN_CONCAT:
808 case TOKEN_GNU_KLUDGE:
809 different = 0;
810 break;
811 case TOKEN_NUMBER:
812 different = strcmp(t1->number, t2->number);
813 break;
814 case TOKEN_SPECIAL:
815 different = t1->special != t2->special;
816 break;
817 case TOKEN_MACRO_ARGUMENT:
818 case TOKEN_QUOTED_ARGUMENT:
819 case TOKEN_STR_ARGUMENT:
820 different = t1->argnum != t2->argnum;
821 break;
822 case TOKEN_CHAR:
823 different = t1->character != t2->character;
824 break;
825 case TOKEN_STRING: {
826 struct string *s1, *s2;
828 s1 = t1->string;
829 s2 = t2->string;
830 different = 1;
831 if (s1->length != s2->length)
832 break;
833 different = memcmp(s1->data, s2->data, s1->length);
834 break;
836 default:
837 different = 1;
838 break;
840 return different;
843 static int token_list_different(struct token *list1, struct token *list2)
845 for (;;) {
846 if (list1 == list2)
847 return 0;
848 if (!list1 || !list2)
849 return 1;
850 if (token_different(list1, list2))
851 return 1;
852 list1 = list1->next;
853 list2 = list2->next;
857 static inline void set_arg_count(struct token *token)
859 token_type(token) = TOKEN_ARG_COUNT;
860 token->count.normal = token->count.quoted =
861 token->count.str = token->count.vararg = 0;
864 static struct token *parse_arguments(struct token *list)
866 struct token *arg = list->next, *next = list;
867 struct argcount *count = &list->count;
869 set_arg_count(list);
871 if (match_op(arg, ')')) {
872 next = arg->next;
873 list->next = &eof_token_entry;
874 return next;
877 while (token_type(arg) == TOKEN_IDENT) {
878 if (arg->ident == &__VA_ARGS___ident)
879 goto Eva_args;
880 if (!++count->normal)
881 goto Eargs;
882 next = arg->next;
884 if (match_op(next, ',')) {
885 set_arg_count(next);
886 arg = next->next;
887 continue;
890 if (match_op(next, ')')) {
891 set_arg_count(next);
892 next = next->next;
893 arg->next->next = &eof_token_entry;
894 return next;
897 /* normal cases are finished here */
899 if (match_op(next, SPECIAL_ELLIPSIS)) {
900 if (match_op(next->next, ')')) {
901 set_arg_count(next);
902 next->count.vararg = 1;
903 next = next->next;
904 arg->next->next = &eof_token_entry;
905 return next->next;
908 arg = next;
909 goto Enotclosed;
912 if (eof_token(next)) {
913 goto Enotclosed;
914 } else {
915 arg = next;
916 goto Ebadstuff;
920 if (match_op(arg, SPECIAL_ELLIPSIS)) {
921 next = arg->next;
922 token_type(arg) = TOKEN_IDENT;
923 arg->ident = &__VA_ARGS___ident;
924 if (!match_op(next, ')'))
925 goto Enotclosed;
926 if (!++count->normal)
927 goto Eargs;
928 set_arg_count(next);
929 next->count.vararg = 1;
930 next = next->next;
931 arg->next->next = &eof_token_entry;
932 return next;
935 if (eof_token(arg)) {
936 arg = next;
937 goto Enotclosed;
939 if (match_op(arg, ','))
940 goto Emissing;
941 else
942 goto Ebadstuff;
945 Emissing:
946 sparse_error(arg->pos, "parameter name missing");
947 return NULL;
948 Ebadstuff:
949 sparse_error(arg->pos, "\"%s\" may not appear in macro parameter list",
950 show_token(arg));
951 return NULL;
952 Enotclosed:
953 sparse_error(arg->pos, "missing ')' in macro parameter list");
954 return NULL;
955 Eva_args:
956 sparse_error(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
957 return NULL;
958 Eargs:
959 sparse_error(arg->pos, "too many arguments in macro definition");
960 return NULL;
963 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
965 struct ident *ident = token->ident;
966 int nr;
968 if (!arglist || token_type(token) != TOKEN_IDENT)
969 return 0;
971 arglist = arglist->next;
973 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
974 if (arglist->ident == ident) {
975 struct argcount *count = &arglist->next->count;
976 int n;
978 token->argnum = nr;
979 token_type(token) = type;
980 switch (type) {
981 case TOKEN_MACRO_ARGUMENT:
982 n = ++count->normal;
983 break;
984 case TOKEN_QUOTED_ARGUMENT:
985 n = ++count->quoted;
986 break;
987 default:
988 n = ++count->str;
990 if (n)
991 return count->vararg ? 2 : 1;
992 token_type(token) = TOKEN_ERROR;
993 return -1;
996 return 0;
999 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
1001 struct token *token = expansion;
1002 struct token **p;
1003 struct token *last = NULL;
1005 if (match_op(token, SPECIAL_HASHHASH))
1006 goto Econcat;
1008 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
1009 if (match_op(token, '#')) {
1010 if (arglist) {
1011 struct token *next = token->next;
1012 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
1013 goto Equote;
1014 next->pos.whitespace = token->pos.whitespace;
1015 token = *p = next;
1016 } else {
1017 token->pos.noexpand = 1;
1019 } else if (match_op(token, SPECIAL_HASHHASH)) {
1020 struct token *next = token->next;
1021 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
1022 token_type(token) = TOKEN_CONCAT;
1023 if (arg) {
1024 token = next;
1025 /* GNU kludge */
1026 if (arg == 2 && last && match_op(last, ',')) {
1027 token_type(last) = TOKEN_GNU_KLUDGE;
1028 last->next = token;
1030 } else if (match_op(next, SPECIAL_HASHHASH))
1031 token = next;
1032 else if (eof_token(next))
1033 goto Econcat;
1034 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
1035 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
1036 } else {
1037 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
1039 if (token_type(token) == TOKEN_ERROR)
1040 goto Earg;
1041 last = token;
1043 token = alloc_token(&expansion->pos);
1044 token_type(token) = TOKEN_UNTAINT;
1045 token->ident = name;
1046 token->next = *p;
1047 *p = token;
1048 return expansion;
1050 Equote:
1051 sparse_error(token->pos, "'#' is not followed by a macro parameter");
1052 return NULL;
1054 Econcat:
1055 sparse_error(token->pos, "'##' cannot appear at the ends of macro expansion");
1056 return NULL;
1057 Earg:
1058 sparse_error(token->pos, "too many instances of argument in body");
1059 return NULL;
1062 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int weak)
1064 struct token *arglist, *expansion;
1065 struct token *left = token->next;
1066 struct symbol *sym;
1067 struct ident *name;
1068 int ret;
1070 if (token_type(left) != TOKEN_IDENT) {
1071 sparse_error(token->pos, "expected identifier to 'define'");
1072 return 1;
1075 name = left->ident;
1077 arglist = NULL;
1078 expansion = left->next;
1079 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
1080 arglist = expansion;
1081 expansion = parse_arguments(expansion);
1082 if (!expansion)
1083 return 1;
1086 expansion = parse_expansion(expansion, arglist, name);
1087 if (!expansion)
1088 return 1;
1090 ret = 1;
1091 sym = lookup_macro(name);
1092 if (sym) {
1093 int clean;
1095 if (weak > sym->weak)
1096 goto out;
1098 clean = (weak == sym->weak);
1100 if (token_list_different(sym->expansion, expansion) ||
1101 token_list_different(sym->arglist, arglist)) {
1102 ret = 0;
1103 if ((clean && !weak) || sym->used_in == file_scope) {
1104 warning(left->pos, "preprocessor token %.*s redefined",
1105 name->len, name->name);
1106 info(sym->pos, "this was the original definition");
1108 } else if (clean)
1109 goto out;
1112 if (!sym || sym->scope != file_scope) {
1113 sym = alloc_symbol(left->pos, SYM_NODE);
1114 bind_symbol(sym, name, NS_MACRO);
1115 ret = 0;
1118 if (!ret) {
1119 sym->expansion = expansion;
1120 sym->arglist = arglist;
1121 __free_token(token); /* Free the "define" token, but not the rest of the line */
1124 sym->used_in = NULL;
1125 sym->weak = weak;
1126 out:
1127 return ret;
1130 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1132 return do_handle_define(stream, line, token, 0);
1135 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1137 return do_handle_define(stream, line, token, 1);
1140 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1142 struct token *left = token->next;
1143 struct symbol *sym;
1145 if (token_type(left) != TOKEN_IDENT) {
1146 sparse_error(token->pos, "expected identifier to 'undef'");
1147 return 1;
1150 sym = lookup_macro(left->ident);
1151 if (!sym)
1152 return 1;
1154 if (sym->scope != file_scope) {
1155 sym = alloc_symbol(left->pos, SYM_NODE);
1156 bind_symbol(sym, left->ident, NS_MACRO);
1159 sym->namespace = NS_UNDEF;
1160 sym->used_in = NULL;
1162 return 1;
1165 static int preprocessor_if(struct stream *stream, struct token *token, int true)
1167 token_type(token) = false_nesting ? TOKEN_SKIP_GROUPS : TOKEN_IF;
1168 free_preprocessor_line(token->next);
1169 token->next = stream->top_if;
1170 stream->top_if = token;
1171 if (false_nesting || true != 1)
1172 false_nesting++;
1173 return 0;
1176 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1178 struct token *next = token->next;
1179 int arg;
1180 if (token_type(next) == TOKEN_IDENT) {
1181 arg = token_defined(next);
1182 } else {
1183 dirty_stream(stream);
1184 if (!false_nesting)
1185 sparse_error(token->pos, "expected preprocessor identifier");
1186 arg = -1;
1188 return preprocessor_if(stream, token, arg);
1191 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1193 struct token *next = token->next;
1194 int arg;
1195 if (token_type(next) == TOKEN_IDENT) {
1196 if (!stream->dirty && !stream->ifndef) {
1197 if (!stream->protect) {
1198 stream->ifndef = token;
1199 stream->protect = next->ident;
1200 } else if (stream->protect == next->ident) {
1201 stream->ifndef = token;
1202 stream->dirty = 1;
1205 arg = !token_defined(next);
1206 } else {
1207 dirty_stream(stream);
1208 if (!false_nesting)
1209 sparse_error(token->pos, "expected preprocessor identifier");
1210 arg = -1;
1213 return preprocessor_if(stream, token, arg);
1217 * Expression handling for #if and #elif; it differs from normal expansion
1218 * due to special treatment of "defined".
1220 static int expression_value(struct token **where)
1222 struct expression *expr;
1223 struct token *p;
1224 struct token **list = where, **beginning = NULL;
1225 long long value;
1226 int state = 0;
1228 while (!eof_token(p = scan_next(list))) {
1229 switch (state) {
1230 case 0:
1231 if (token_type(p) != TOKEN_IDENT)
1232 break;
1233 if (p->ident == &defined_ident) {
1234 state = 1;
1235 beginning = list;
1236 break;
1238 if (!expand_one_symbol(list))
1239 continue;
1240 if (token_type(p) != TOKEN_IDENT)
1241 break;
1242 token_type(p) = TOKEN_ZERO_IDENT;
1243 break;
1244 case 1:
1245 if (match_op(p, '(')) {
1246 state = 2;
1247 } else {
1248 state = 0;
1249 replace_with_defined(p);
1250 *beginning = p;
1252 break;
1253 case 2:
1254 if (token_type(p) == TOKEN_IDENT)
1255 state = 3;
1256 else
1257 state = 0;
1258 replace_with_defined(p);
1259 *beginning = p;
1260 break;
1261 case 3:
1262 state = 0;
1263 if (!match_op(p, ')'))
1264 sparse_error(p->pos, "missing ')' after \"defined\"");
1265 *list = p->next;
1266 continue;
1268 list = &p->next;
1271 p = constant_expression(*where, &expr);
1272 if (!eof_token(p))
1273 sparse_error(p->pos, "garbage at end: %s", show_token_sequence(p));
1274 value = get_expression_value(expr);
1275 return value != 0;
1278 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1280 int value = 0;
1281 if (!false_nesting)
1282 value = expression_value(&token->next);
1284 dirty_stream(stream);
1285 return preprocessor_if(stream, token, value);
1288 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1290 struct token *top_if = stream->top_if;
1291 end_group(stream);
1293 if (!top_if) {
1294 nesting_error(stream);
1295 sparse_error(token->pos, "unmatched #elif within stream");
1296 return 1;
1299 if (token_type(top_if) == TOKEN_ELSE) {
1300 nesting_error(stream);
1301 sparse_error(token->pos, "#elif after #else");
1302 if (!false_nesting)
1303 false_nesting = 1;
1304 return 1;
1307 dirty_stream(stream);
1308 if (token_type(top_if) != TOKEN_IF)
1309 return 1;
1310 if (false_nesting) {
1311 if (expression_value(&token->next))
1312 false_nesting = 0;
1313 } else {
1314 false_nesting = 1;
1315 token_type(top_if) = TOKEN_SKIP_GROUPS;
1317 return 1;
1320 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1322 struct token *top_if = stream->top_if;
1323 end_group(stream);
1325 if (!top_if) {
1326 nesting_error(stream);
1327 sparse_error(token->pos, "unmatched #else within stream");
1328 return 1;
1331 if (token_type(top_if) == TOKEN_ELSE) {
1332 nesting_error(stream);
1333 sparse_error(token->pos, "#else after #else");
1335 if (false_nesting) {
1336 if (token_type(top_if) == TOKEN_IF)
1337 false_nesting = 0;
1338 } else {
1339 false_nesting = 1;
1341 token_type(top_if) = TOKEN_ELSE;
1342 return 1;
1345 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1347 struct token *top_if = stream->top_if;
1348 end_group(stream);
1349 if (!top_if) {
1350 nesting_error(stream);
1351 sparse_error(token->pos, "unmatched #endif in stream");
1352 return 1;
1354 if (false_nesting)
1355 false_nesting--;
1356 stream->top_if = top_if->next;
1357 __free_token(top_if);
1358 return 1;
1361 static const char *show_token_sequence(struct token *token)
1363 static char buffer[1024];
1364 char *ptr = buffer;
1365 int whitespace = 0;
1367 if (!token)
1368 return "<none>";
1369 while (!eof_token(token)) {
1370 const char *val = show_token(token);
1371 int len = strlen(val);
1373 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
1374 sparse_error(token->pos, "too long token expansion");
1375 break;
1378 if (whitespace)
1379 *ptr++ = ' ';
1380 memcpy(ptr, val, len);
1381 ptr += len;
1382 token = token->next;
1383 whitespace = token->pos.whitespace;
1385 *ptr = 0;
1386 return buffer;
1389 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1391 warning(token->pos, "%s", show_token_sequence(token->next));
1392 return 1;
1395 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1397 sparse_error(token->pos, "%s", show_token_sequence(token->next));
1398 return 1;
1401 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1404 * Do we have any non-system includes?
1405 * Clear them out if so..
1407 *sys_includepath = NULL;
1408 return 1;
1411 static void add_path_entry(struct token *token, const char *path, const char ***where, const char **new_path)
1413 const char **dst;
1414 const char *next;
1416 /* Need one free entry.. */
1417 if (includepath[INCLUDEPATHS-2])
1418 error_die(token->pos, "too many include path entries");
1420 /* check that this is not a duplicate */
1421 dst = includepath;
1422 while (*dst) {
1423 if (strcmp(*dst, path) == 0)
1424 return;
1425 dst++;
1427 next = path;
1428 dst = *where;
1429 *where = new_path;
1432 * Move them all up starting at dst,
1433 * insert the new entry..
1435 for (;;) {
1436 const char *tmp = *dst;
1437 *dst = next;
1438 if (!next)
1439 break;
1440 next = tmp;
1441 dst++;
1445 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1447 for (;;) {
1448 token = token->next;
1449 if (eof_token(token))
1450 return 1;
1451 if (token_type(token) != TOKEN_STRING) {
1452 warning(token->pos, "expected path string");
1453 return 1;
1455 add_path_entry(token, token->string->data, &sys_includepath, sys_includepath + 1);
1459 static int handle_add_isystem(struct stream *stream, struct token **line, struct token *token)
1461 for (;;) {
1462 token = token->next;
1463 if (eof_token(token))
1464 return 1;
1465 if (token_type(token) != TOKEN_STRING) {
1466 sparse_error(token->pos, "expected path string");
1467 return 1;
1469 add_path_entry(token, token->string->data, &sys_includepath, sys_includepath);
1473 /* Add to end on includepath list - no pointer updates */
1474 static void add_dirafter_entry(struct token *token, const char *path)
1476 const char **dst = includepath;
1478 /* Need one free entry.. */
1479 if (includepath[INCLUDEPATHS-2])
1480 error_die(token->pos, "too many include path entries");
1482 /* Add to the end */
1483 while (*dst)
1484 dst++;
1485 *dst = path;
1486 dst++;
1487 *dst = NULL;
1490 static int handle_add_dirafter(struct stream *stream, struct token **line, struct token *token)
1492 for (;;) {
1493 token = token->next;
1494 if (eof_token(token))
1495 return 1;
1496 if (token_type(token) != TOKEN_STRING) {
1497 sparse_error(token->pos, "expected path string");
1498 return 1;
1500 add_dirafter_entry(token, token->string->data);
1504 static int handle_split_include(struct stream *stream, struct token **line, struct token *token)
1507 * -I-
1508 * From info gcc:
1509 * Split the include path. Any directories specified with `-I'
1510 * options before `-I-' are searched only for headers requested with
1511 * `#include "FILE"'; they are not searched for `#include <FILE>'.
1512 * If additional directories are specified with `-I' options after
1513 * the `-I-', those directories are searched for all `#include'
1514 * directives.
1515 * In addition, `-I-' inhibits the use of the directory of the current
1516 * file directory as the first search directory for `#include "FILE"'.
1518 quote_includepath = includepath+1;
1519 angle_includepath = sys_includepath;
1520 return 1;
1524 * We replace "#pragma xxx" with "__pragma__" in the token
1525 * stream. Just as an example.
1527 * We'll just #define that away for now, but the theory here
1528 * is that we can use this to insert arbitrary token sequences
1529 * to turn the pragma's into internal front-end sequences for
1530 * when we actually start caring about them.
1532 * So eventually this will turn into some kind of extended
1533 * __attribute__() like thing, except called __pragma__(xxx).
1535 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1537 struct token *next = *line;
1539 token->ident = &pragma_ident;
1540 token->pos.newline = 1;
1541 token->pos.whitespace = 1;
1542 token->pos.pos = 1;
1543 *line = token;
1544 token->next = next;
1545 return 0;
1549 * We ignore #line for now.
1551 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1553 return 1;
1556 static int handle_nondirective(struct stream *stream, struct token **line, struct token *token)
1558 sparse_error(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1559 return 1;
1563 static void init_preprocessor(void)
1565 int i;
1566 int stream = init_stream("preprocessor", -1, includepath);
1567 static struct {
1568 const char *name;
1569 int (*handler)(struct stream *, struct token **, struct token *);
1570 } normal[] = {
1571 { "define", handle_define },
1572 { "weak_define",handle_weak_define },
1573 { "undef", handle_undef },
1574 { "warning", handle_warning },
1575 { "error", handle_error },
1576 { "include", handle_include },
1577 { "include_next",handle_include_next },
1578 { "pragma", handle_pragma },
1579 { "line", handle_line },
1581 // our internal preprocessor tokens
1582 { "nostdinc", handle_nostdinc },
1583 { "add_include", handle_add_include },
1584 { "add_isystem", handle_add_isystem },
1585 { "add_dirafter", handle_add_dirafter },
1586 { "split_include", handle_split_include },
1587 }, special[] = {
1588 { "ifdef", handle_ifdef },
1589 { "ifndef", handle_ifndef },
1590 { "else", handle_else },
1591 { "endif", handle_endif },
1592 { "if", handle_if },
1593 { "elif", handle_elif },
1596 for (i = 0; i < (sizeof (normal) / sizeof (normal[0])); i++) {
1597 struct symbol *sym;
1598 sym = create_symbol(stream, normal[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1599 sym->handler = normal[i].handler;
1600 sym->normal = 1;
1602 for (i = 0; i < (sizeof (special) / sizeof (special[0])); i++) {
1603 struct symbol *sym;
1604 sym = create_symbol(stream, special[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1605 sym->handler = special[i].handler;
1606 sym->normal = 0;
1611 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
1613 int (*handler)(struct stream *, struct token **, struct token *);
1614 struct token *token = start->next;
1615 int is_normal = 1;
1617 if (eof_token(token))
1618 return;
1620 if (token_type(token) == TOKEN_IDENT) {
1621 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
1622 if (sym) {
1623 handler = sym->handler;
1624 is_normal = sym->normal;
1625 } else {
1626 handler = handle_nondirective;
1628 } else if (token_type(token) == TOKEN_NUMBER) {
1629 handler = handle_line;
1630 } else {
1631 handler = handle_nondirective;
1634 if (is_normal) {
1635 dirty_stream(stream);
1636 if (false_nesting)
1637 goto out;
1639 if (!handler(stream, line, token)) /* all set */
1640 return;
1642 out:
1643 free_preprocessor_line(token);
1646 static void preprocessor_line(struct stream *stream, struct token **line)
1648 struct token *start = *line, *next;
1649 struct token **tp = &start->next;
1651 for (;;) {
1652 next = *tp;
1653 if (next->pos.newline)
1654 break;
1655 tp = &next->next;
1657 *line = next;
1658 *tp = &eof_token_entry;
1659 handle_preprocessor_line(stream, line, start);
1662 static void do_preprocess(struct token **list)
1664 struct token *next;
1666 while (!eof_token(next = scan_next(list))) {
1667 struct stream *stream = input_streams + next->pos.stream;
1669 if (next->pos.newline && match_op(next, '#')) {
1670 if (!next->pos.noexpand) {
1671 preprocessor_line(stream, list);
1672 __free_token(next); /* Free the '#' token */
1673 continue;
1677 switch (token_type(next)) {
1678 case TOKEN_STREAMEND:
1679 if (stream->top_if) {
1680 nesting_error(stream);
1681 sparse_error(stream->top_if->pos, "unterminated preprocessor conditional");
1682 stream->top_if = NULL;
1683 false_nesting = 0;
1685 if (!stream->dirty)
1686 stream->constant = CONSTANT_FILE_YES;
1687 *list = next->next;
1688 continue;
1689 case TOKEN_STREAMBEGIN:
1690 *list = next->next;
1691 continue;
1693 default:
1694 dirty_stream(stream);
1695 if (false_nesting) {
1696 *list = next->next;
1697 __free_token(next);
1698 continue;
1701 if (token_type(next) != TOKEN_IDENT ||
1702 expand_one_symbol(list))
1703 list = &next->next;
1708 struct token * preprocess(struct token *token)
1710 preprocessing = 1;
1711 init_preprocessor();
1712 do_preprocess(&token);
1714 // Drop all expressions from pre-processing, they're not used any more.
1715 // This is not true when we have multiple files, though ;/
1716 // clear_expression_alloc();
1717 preprocessing = 0;
1719 return token;