Get comparison sizes right.
[smatch.git] / pre-process.c
blobc502074de17efe8f781c8a7b9488c4c2a903bdc5
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"
30 static int true_nesting = 0;
31 static int false_nesting = 0;
32 static struct token *unmatched_if = NULL;
33 #define if_nesting (true_nesting + false_nesting)
35 #define MAX_NEST (256)
36 static unsigned char elif_ignore[MAX_NEST];
37 enum { ELIF_IGNORE = 1, ELIF_SEEN_ELSE = 2 };
39 #define INCLUDEPATHS 300
40 const char *includepath[INCLUDEPATHS+1] = {
41 "/usr/include",
42 "/usr/local/include",
43 GCC_INTERNAL_INCLUDE,
44 NULL
47 static const char **sys_includepath = includepath + 0;
48 static const char **gcc_includepath = includepath + 2;
50 #define MARK_STREAM_NONCONST(pos) do { \
51 if (stream->constant != CONSTANT_FILE_NOPE) { \
52 if (0) \
53 info(pos, "%s triggers non-const", __func__); \
54 stream->constant = CONSTANT_FILE_NOPE; \
55 } \
56 } while (0)
59 static struct token *alloc_token(struct position *pos)
61 struct token *token = __alloc_token(0);
63 token->pos.stream = pos->stream;
64 token->pos.line = pos->line;
65 token->pos.pos = pos->pos;
66 token->pos.whitespace = 1;
67 return token;
70 static const char *show_token_sequence(struct token *token);
72 /* Expand symbol 'sym' at '*list' */
73 static int expand(struct token **, struct symbol *);
75 static void replace_with_string(struct token *token, const char *str)
77 int size = strlen(str) + 1;
78 struct string *s = __alloc_string(size);
80 s->length = size;
81 memcpy(s->data, str, size);
82 token_type(token) = TOKEN_STRING;
83 token->string = s;
86 static void replace_with_integer(struct token *token, unsigned int val)
88 char *buf = __alloc_bytes(11);
89 sprintf(buf, "%u", val);
90 token_type(token) = TOKEN_NUMBER;
91 token->number = buf;
94 static int token_defined(struct token *token)
96 if (token_type(token) == TOKEN_IDENT) {
97 struct symbol *sym = lookup_symbol(token->ident, NS_MACRO);
98 if (sym) {
99 sym->weak = 0;
100 return 1;
102 return 0;
105 warning(token->pos, "expected preprocessor identifier");
106 return 0;
109 static void replace_with_defined(struct token *token)
111 static const char *string[] = { "0", "1" };
112 int defined = token_defined(token);
114 token_type(token) = TOKEN_NUMBER;
115 token->number = string[defined];
118 static int expand_one_symbol(struct token **list)
120 struct token *token = *list;
121 struct symbol *sym;
123 if (token->pos.noexpand)
124 return 1;
126 sym = lookup_symbol(token->ident, NS_MACRO);
127 if (sym) {
128 sym->weak = 0;
129 return expand(list, sym);
131 if (token->ident == &__LINE___ident) {
132 replace_with_integer(token, token->pos.line);
133 } else if (token->ident == &__FILE___ident) {
134 replace_with_string(token, stream_name(token->pos.stream));
136 return 1;
139 static inline struct token *scan_next(struct token **where)
141 struct token *token = *where;
142 if (token_type(token) != TOKEN_UNTAINT)
143 return token;
144 do {
145 token->ident->tainted = 0;
146 token = token->next;
147 } while (token_type(token) == TOKEN_UNTAINT);
148 *where = token;
149 return token;
152 static void expand_list(struct token **list)
154 struct token *next;
155 while (!eof_token(next = scan_next(list))) {
156 if (token_type(next) != TOKEN_IDENT || expand_one_symbol(list))
157 list = &next->next;
161 static struct token *collect_arg(struct token *prev, int vararg, struct position *pos)
163 struct token **p = &prev->next;
164 struct token *next;
165 int nesting = 0;
167 while (!eof_token(next = scan_next(p))) {
168 if (match_op(next, '(')) {
169 nesting++;
170 } else if (match_op(next, ')')) {
171 if (!nesting--)
172 break;
173 } else if (match_op(next, ',') && !nesting && !vararg) {
174 break;
176 next->pos.stream = pos->stream;
177 next->pos.line = pos->line;
178 next->pos.pos = pos->pos;
179 p = &next->next;
181 *p = &eof_token_entry;
182 return next;
186 * We store arglist as <counter> [arg1] <number of uses for arg1> ... eof
189 struct arg {
190 struct token *arg;
191 struct token *expanded;
192 struct token *str;
193 int n_normal;
194 int n_quoted;
195 int n_str;
198 static int collect_arguments(struct token *start, struct token *arglist, struct arg *args, struct token *what)
200 int wanted = arglist->count.normal;
201 struct token *next = NULL;
202 int count = 0;
204 arglist = arglist->next; /* skip counter */
206 if (!wanted) {
207 next = collect_arg(start, 0, &what->pos);
208 if (eof_token(next))
209 goto Eclosing;
210 if (!eof_token(start->next) || !match_op(next, ')')) {
211 count++;
212 goto Emany;
214 } else {
215 for (count = 0; count < wanted; count++) {
216 struct argcount *p = &arglist->next->count;
217 next = collect_arg(start, p->vararg, &what->pos);
218 arglist = arglist->next->next;
219 if (eof_token(next))
220 goto Eclosing;
221 args[count].arg = start->next;
222 args[count].n_normal = p->normal;
223 args[count].n_quoted = p->quoted;
224 args[count].n_str = p->str;
225 if (match_op(next, ')')) {
226 count++;
227 break;
229 start = next;
231 if (count == wanted && !match_op(next, ')'))
232 goto Emany;
233 if (count == wanted - 1) {
234 struct argcount *p = &arglist->next->count;
235 if (!p->vararg)
236 goto Efew;
237 args[count].arg = NULL;
238 args[count].n_normal = p->normal;
239 args[count].n_quoted = p->quoted;
240 args[count].n_str = p->str;
242 if (count < wanted - 1)
243 goto Efew;
245 what->next = next->next;
246 return 1;
248 Efew:
249 warning(what->pos, "macro \"%s\" requires %d arguments, but only %d given",
250 show_token(what), wanted, count);
251 goto out;
252 Emany:
253 while (match_op(next, ',')) {
254 next = collect_arg(next, 0, &what->pos);
255 count++;
257 if (eof_token(next))
258 goto Eclosing;
259 warning(what->pos, "macro \"%s\" passed %d arguments, but takes just %d",
260 show_token(what), count, wanted);
261 goto out;
262 Eclosing:
263 warning(what->pos, "unterminated argument list invoking macro \"%s\"",
264 show_token(what));
265 out:
266 what->next = next->next;
267 return 0;
270 static struct token *dup_list(struct token *list)
272 struct token *res;
273 struct token **p = &res;
275 while (!eof_token(list)) {
276 struct token *newtok = __alloc_token(0);
277 *newtok = *list;
278 *p = newtok;
279 p = &newtok->next;
280 list = list->next;
282 return res;
285 static struct token *stringify(struct token *arg)
287 const char *s = show_token_sequence(arg);
288 int size = strlen(s)+1;
289 struct token *token = __alloc_token(0);
290 struct string *string = __alloc_string(size);
292 memcpy(string->data, s, size);
293 string->length = size;
294 token->pos = arg->pos;
295 token_type(token) = TOKEN_STRING;
296 token->string = string;
297 token->next = &eof_token_entry;
298 return token;
301 static void expand_arguments(int count, struct arg *args)
303 int i;
304 for (i = 0; i < count; i++) {
305 struct token *arg = args[i].arg;
306 if (!arg)
307 arg = &eof_token_entry;
308 if (args[i].n_str)
309 args[i].str = stringify(arg);
310 if (args[i].n_normal) {
311 if (!args[i].n_quoted) {
312 args[i].expanded = arg;
313 args[i].arg = NULL;
314 } else if (eof_token(arg)) {
315 args[i].expanded = arg;
316 } else {
317 args[i].expanded = dup_list(arg);
319 expand_list(&args[i].expanded);
325 * Possibly valid combinations:
326 * - ident + ident -> ident
327 * - ident + number -> ident unless number contains '.', '+' or '-'.
328 * - number + number -> number
329 * - number + ident -> number
330 * - number + '.' -> number
331 * - number + '+' or '-' -> number, if number used to end on [eEpP].
332 * - '.' + number -> number, if number used to start with a digit.
333 * - special + special -> either special or an error.
335 static enum token_type combine(struct token *left, struct token *right, char *p)
337 int len;
338 enum token_type t1 = token_type(left), t2 = token_type(right);
340 if (t1 != TOKEN_IDENT && t1 != TOKEN_NUMBER && t1 != TOKEN_SPECIAL)
341 return TOKEN_ERROR;
343 if (t2 != TOKEN_IDENT && t2 != TOKEN_NUMBER && t2 != TOKEN_SPECIAL)
344 return TOKEN_ERROR;
346 strcpy(p, show_token(left));
347 strcat(p, show_token(right));
348 len = strlen(p);
350 if (len >= 256)
351 return TOKEN_ERROR;
353 if (t1 == TOKEN_IDENT) {
354 if (t2 == TOKEN_SPECIAL)
355 return TOKEN_ERROR;
356 if (t2 == TOKEN_NUMBER && strpbrk(p, "+-."))
357 return TOKEN_ERROR;
358 return TOKEN_IDENT;
361 if (t1 == TOKEN_NUMBER) {
362 if (t2 == TOKEN_SPECIAL) {
363 switch (right->special) {
364 case '.':
365 break;
366 case '+': case '-':
367 if (strchr("eEpP", p[len - 2]))
368 break;
369 default:
370 return TOKEN_ERROR;
373 return TOKEN_NUMBER;
376 if (p[0] == '.' && isdigit((unsigned char)p[1]))
377 return TOKEN_NUMBER;
379 return TOKEN_SPECIAL;
382 static int merge(struct token *left, struct token *right)
384 extern unsigned char combinations[][3];
385 static char buffer[512];
386 int n;
388 switch (combine(left, right, buffer)) {
389 case TOKEN_IDENT:
390 left->ident = built_in_ident(buffer);
391 left->pos.noexpand = 0;
392 return 1;
394 case TOKEN_NUMBER: {
395 char *number = __alloc_bytes(strlen(buffer) + 1);
396 memcpy(number, buffer, strlen(buffer) + 1);
397 token_type(left) = TOKEN_NUMBER; /* could be . + num */
398 left->number = number;
399 return 1;
402 case TOKEN_SPECIAL:
403 if (buffer[2] && buffer[3])
404 break;
405 for (n = SPECIAL_BASE; n < SPECIAL_ARG_SEPARATOR; n++) {
406 if (!memcmp(buffer, combinations[n-SPECIAL_BASE], 3)) {
407 left->special = n;
408 return 1;
411 default:
414 warning(left->pos, "'##' failed: concatenation is not a valid token");
415 return 0;
418 static struct token *dup_token(struct token *token, struct position *streampos, struct position *pos)
420 struct token *alloc = alloc_token(streampos);
421 token_type(alloc) = token_type(token);
422 alloc->pos.newline = pos->newline;
423 alloc->pos.whitespace = pos->whitespace;
424 alloc->number = token->number;
425 alloc->pos.noexpand = token->pos.noexpand;
426 return alloc;
429 static struct token **copy(struct token **where, struct token *list, int *count)
431 int need_copy = --*count;
432 while (!eof_token(list)) {
433 struct token *token;
434 if (need_copy)
435 token = dup_token(list, &list->pos, &list->pos);
436 else
437 token = list;
438 if (token_type(token) == TOKEN_IDENT && token->ident->tainted)
439 token->pos.noexpand = 1;
440 *where = token;
441 where = &token->next;
442 list = list->next;
444 *where = &eof_token_entry;
445 return where;
448 static struct token **substitute(struct token **list, struct token *body, struct arg *args)
450 struct token *token = *list;
451 struct position *base_pos = &token->pos;
452 struct position *pos = base_pos;
453 int *count;
454 enum {Normal, Placeholder, Concat} state = Normal;
456 for (; !eof_token(body); body = body->next, pos = &body->pos) {
457 struct token *added, *arg;
458 struct token **tail;
460 switch (token_type(body)) {
461 case TOKEN_GNU_KLUDGE:
463 * GNU kludge: if we had <comma>##<vararg>, behaviour
464 * depends on whether we had enough arguments to have
465 * a vararg. If we did, ## is just ignored. Otherwise
466 * both , and ## are ignored. Comma should come from
467 * the body of macro and not be an argument of earlier
468 * concatenation.
470 if (!args[body->next->argnum].arg)
471 continue;
472 added = dup_token(body, base_pos, pos);
473 token_type(added) = TOKEN_SPECIAL;
474 tail = &added->next;
475 break;
477 case TOKEN_STR_ARGUMENT:
478 arg = args[body->argnum].str;
479 count = &args[body->argnum].n_str;
480 goto copy_arg;
482 case TOKEN_QUOTED_ARGUMENT:
483 arg = args[body->argnum].arg;
484 count = &args[body->argnum].n_quoted;
485 if (!arg || eof_token(arg)) {
486 if (state == Concat)
487 state = Normal;
488 else
489 state = Placeholder;
490 continue;
492 goto copy_arg;
494 case TOKEN_MACRO_ARGUMENT:
495 arg = args[body->argnum].expanded;
496 count = &args[body->argnum].n_normal;
497 if (eof_token(arg)) {
498 state = Normal;
499 continue;
501 copy_arg:
502 tail = copy(&added, arg, count);
503 added->pos.newline = pos->newline;
504 added->pos.whitespace = pos->whitespace;
505 break;
507 case TOKEN_CONCAT:
508 if (state == Placeholder)
509 state = Normal;
510 else
511 state = Concat;
512 continue;
514 case TOKEN_IDENT:
515 added = dup_token(body, base_pos, pos);
516 if (added->ident->tainted)
517 added->pos.noexpand = 1;
518 tail = &added->next;
519 break;
521 default:
522 added = dup_token(body, base_pos, pos);
523 tail = &added->next;
524 break;
528 * if we got to doing real concatenation, we already have
529 * added something into the list, so containing_token() is OK.
531 if (state == Concat && merge(containing_token(list), added)) {
532 *list = added->next;
533 if (tail != &added->next)
534 list = tail;
535 } else {
536 *list = added;
537 list = tail;
539 state = Normal;
541 *list = &eof_token_entry;
542 return list;
545 static int expand(struct token **list, struct symbol *sym)
547 struct token *last;
548 struct token *token = *list;
549 struct ident *expanding = token->ident;
550 struct token **tail;
551 int nargs = sym->arglist ? sym->arglist->count.normal : 0;
552 struct arg args[nargs];
554 if (expanding->tainted) {
555 token->pos.noexpand = 1;
556 return 1;
559 if (sym->arglist) {
560 if (!match_op(scan_next(&token->next), '('))
561 return 1;
562 if (!collect_arguments(token->next, sym->arglist, args, token))
563 return 1;
564 expand_arguments(nargs, args);
567 expanding->tainted = 1;
569 last = token->next;
570 tail = substitute(list, sym->expansion, args);
571 *tail = last;
573 return 0;
576 static const char *token_name_sequence(struct token *token, int endop, struct token *start)
578 struct token *last;
579 static char buffer[256];
580 char *ptr = buffer;
582 last = token;
583 while (!eof_token(token) && !match_op(token, endop)) {
584 int len;
585 const char *val = token->string->data;
586 if (token_type(token) != TOKEN_STRING)
587 val = show_token(token);
588 len = strlen(val);
589 memcpy(ptr, val, len);
590 ptr += len;
591 token = token->next;
593 *ptr = 0;
594 if (endop && !match_op(token, endop))
595 warning(start->pos, "expected '>' at end of filename");
596 return buffer;
599 static int already_tokenized(const char *path)
601 int i;
602 struct stream *s = input_streams;
604 for (i = input_stream_nr; --i >= 0; s++) {
605 if (s->constant != CONSTANT_FILE_YES)
606 continue;
607 if (strcmp(path, s->name))
608 continue;
609 if (!lookup_symbol(s->protect, NS_MACRO))
610 continue;
611 return 1;
613 return 0;
616 static int try_include(const char *path, int plen, const char *filename, int flen, struct token **where, const char **next_path)
618 int fd;
619 static char fullname[PATH_MAX];
621 memcpy(fullname, path, plen);
622 if (plen && path[plen-1] != '/') {
623 fullname[plen] = '/';
624 plen++;
626 memcpy(fullname+plen, filename, flen);
627 if (already_tokenized(fullname))
628 return 1;
629 fd = open(fullname, O_RDONLY);
630 if (fd >= 0) {
631 char * streamname = __alloc_bytes(plen + flen);
632 memcpy(streamname, fullname, plen + flen);
633 *where = tokenize(streamname, fd, *where, next_path);
634 close(fd);
635 return 1;
637 return 0;
640 static int do_include_path(const char **pptr, struct token **list, struct token *token, const char *filename, int flen)
642 const char *path;
644 while ((path = *pptr++) != NULL) {
645 if (!try_include(path, strlen(path), filename, flen, list, pptr))
646 continue;
647 return 1;
649 return 0;
653 static void do_include(int local, struct stream *stream, struct token **list, struct token *token, const char *filename, const char **path)
655 int flen = strlen(filename) + 1;
657 /* Absolute path? */
658 if (filename[0] == '/') {
659 if (try_include("", 0, filename, flen, list, includepath))
660 return;
661 goto out;
664 /* Same directory as current stream? */
665 if (local) {
666 const char *path;
667 char *slash;
668 int plen;
670 path = stream->name;
671 slash = strrchr(path, '/');
672 plen = slash ? slash - path : 0;
674 if (try_include(path, plen, filename, flen, list, includepath))
675 return;
678 /* Check the standard include paths.. */
679 if (do_include_path(path, list, token, filename, flen))
680 return;
681 out:
682 error_die(token->pos, "unable to open '%s'", filename);
685 static int free_preprocessor_line(struct token *token)
687 do {
688 struct token *free = token;
689 token = token->next;
690 __free_token(free);
691 } while (token_type(token) != TOKEN_EOF);
692 return 1;
695 static int handle_include_path(struct stream *stream, struct token **list, struct token *token, const char **path)
697 const char *filename;
698 struct token *next;
699 int expect;
701 if (false_nesting)
702 return free_preprocessor_line(token);
704 if (stream->constant == CONSTANT_FILE_MAYBE)
705 MARK_STREAM_NONCONST(token->pos);
707 next = token->next;
708 expect = '>';
709 if (!match_op(next, '<')) {
710 expand_list(&token->next);
711 expect = 0;
712 next = token;
713 if (match_op(token->next, '<')) {
714 next = token->next;
715 expect = '>';
718 token = next->next;
719 filename = token_name_sequence(token, expect, token);
720 do_include(!expect, stream, list, token, filename, path);
721 return 1;
724 static int handle_include(struct stream *stream, struct token **list, struct token *token)
726 return handle_include_path(stream, list, token, includepath);
729 static int handle_include_next(struct stream *stream, struct token **list, struct token *token)
731 return handle_include_path(stream, list, token, stream->next_path);
734 static int token_different(struct token *t1, struct token *t2)
736 int different;
738 if (token_type(t1) != token_type(t2))
739 return 1;
741 switch (token_type(t1)) {
742 case TOKEN_IDENT:
743 different = t1->ident != t2->ident;
744 break;
745 case TOKEN_ARG_COUNT:
746 case TOKEN_UNTAINT:
747 case TOKEN_CONCAT:
748 case TOKEN_GNU_KLUDGE:
749 different = 0;
750 break;
751 case TOKEN_NUMBER:
752 different = strcmp(t1->number, t2->number);
753 break;
754 case TOKEN_SPECIAL:
755 different = t1->special != t2->special;
756 break;
757 case TOKEN_MACRO_ARGUMENT:
758 case TOKEN_QUOTED_ARGUMENT:
759 case TOKEN_STR_ARGUMENT:
760 different = t1->argnum != t2->argnum;
761 break;
762 case TOKEN_CHAR:
763 different = t1->character != t2->character;
764 break;
765 case TOKEN_STRING: {
766 struct string *s1, *s2;
768 s1 = t1->string;
769 s2 = t2->string;
770 different = 1;
771 if (s1->length != s2->length)
772 break;
773 different = memcmp(s1->data, s2->data, s1->length);
774 break;
776 default:
777 different = 1;
778 break;
780 return different;
783 static int token_list_different(struct token *list1, struct token *list2)
785 for (;;) {
786 if (list1 == list2)
787 return 0;
788 if (!list1 || !list2)
789 return 1;
790 if (token_different(list1, list2))
791 return 1;
792 list1 = list1->next;
793 list2 = list2->next;
797 static inline void set_arg_count(struct token *token)
799 token_type(token) = TOKEN_ARG_COUNT;
800 token->count.normal = token->count.quoted =
801 token->count.str = token->count.vararg = 0;
804 static struct token *parse_arguments(struct token *list)
806 struct token *arg = list->next, *next = list;
807 struct argcount *count = &list->count;
809 set_arg_count(list);
811 if (match_op(arg, ')')) {
812 next = arg->next;
813 list->next = &eof_token_entry;
814 return next;
817 while (token_type(arg) == TOKEN_IDENT) {
818 if (arg->ident == &__VA_ARGS___ident)
819 goto Eva_args;
820 if (!++count->normal)
821 goto Eargs;
822 next = arg->next;
824 if (match_op(next, ',')) {
825 set_arg_count(next);
826 arg = next->next;
827 continue;
830 if (match_op(next, ')')) {
831 set_arg_count(next);
832 next = next->next;
833 arg->next->next = &eof_token_entry;
834 return next;
837 /* normal cases are finished here */
839 if (match_op(next, SPECIAL_ELLIPSIS)) {
840 if (match_op(next->next, ')')) {
841 set_arg_count(next);
842 next->count.vararg = 1;
843 next = next->next;
844 arg->next->next = &eof_token_entry;
845 return next->next;
848 arg = next;
849 goto Enotclosed;
852 if (eof_token(next)) {
853 goto Enotclosed;
854 } else {
855 arg = next;
856 goto Ebadstuff;
860 if (match_op(arg, SPECIAL_ELLIPSIS)) {
861 next = arg->next;
862 token_type(arg) = TOKEN_IDENT;
863 arg->ident = &__VA_ARGS___ident;
864 if (!match_op(next, ')'))
865 goto Enotclosed;
866 if (!++count->normal)
867 goto Eargs;
868 set_arg_count(next);
869 next->count.vararg = 1;
870 next = next->next;
871 arg->next->next = &eof_token_entry;
872 return next;
875 if (eof_token(arg)) {
876 arg = next;
877 goto Enotclosed;
879 if (match_op(arg, ','))
880 goto Emissing;
881 else
882 goto Ebadstuff;
885 Emissing:
886 warning(arg->pos, "parameter name missing");
887 return NULL;
888 Ebadstuff:
889 warning(arg->pos, "\"%s\" may not appear in macro parameter list",
890 show_token(arg));
891 return NULL;
892 Enotclosed:
893 warning(arg->pos, "missing ')' in macro parameter list");
894 return NULL;
895 Eva_args:
896 warning(arg->pos, "__VA_ARGS__ can only appear in the expansion of a C99 variadic macro");
897 return NULL;
898 Eargs:
899 warning(arg->pos, "too many arguments in macro definition");
900 return NULL;
903 static int try_arg(struct token *token, enum token_type type, struct token *arglist)
905 struct ident *ident = token->ident;
906 int nr;
908 if (!arglist || token_type(token) != TOKEN_IDENT)
909 return 0;
911 arglist = arglist->next;
913 for (nr = 0; !eof_token(arglist); nr++, arglist = arglist->next->next) {
914 if (arglist->ident == ident) {
915 struct argcount *count = &arglist->next->count;
916 int n;
918 token->argnum = nr;
919 token_type(token) = type;
920 switch (type) {
921 case TOKEN_MACRO_ARGUMENT:
922 n = ++count->normal;
923 break;
924 case TOKEN_QUOTED_ARGUMENT:
925 n = ++count->quoted;
926 break;
927 default:
928 n = ++count->str;
930 if (n)
931 return count->vararg ? 2 : 1;
932 token_type(token) = TOKEN_ERROR;
933 return -1;
936 return 0;
939 static struct token *parse_expansion(struct token *expansion, struct token *arglist, struct ident *name)
941 struct token *token = expansion;
942 struct token **p;
943 struct token *last = NULL;
945 if (match_op(token, SPECIAL_HASHHASH))
946 goto Econcat;
948 for (p = &expansion; !eof_token(token); p = &token->next, token = *p) {
949 if (match_op(token, '#')) {
950 if (arglist) {
951 struct token *next = token->next;
952 if (!try_arg(next, TOKEN_STR_ARGUMENT, arglist))
953 goto Equote;
954 next->pos.whitespace = token->pos.whitespace;
955 token = *p = next;
956 } else {
957 token->pos.noexpand = 1;
959 } else if (match_op(token, SPECIAL_HASHHASH)) {
960 struct token *next = token->next;
961 int arg = try_arg(next, TOKEN_QUOTED_ARGUMENT, arglist);
962 token_type(token) = TOKEN_CONCAT;
963 if (arg) {
964 token = next;
965 /* GNU kludge */
966 if (arg == 2 && last && match_op(last, ',')) {
967 token_type(last) = TOKEN_GNU_KLUDGE;
968 last->next = token;
970 } else if (match_op(next, SPECIAL_HASHHASH))
971 token = next;
972 else if (match_op(next, ','))
973 token = next;
974 else if (eof_token(next))
975 goto Econcat;
976 } else if (match_op(token->next, SPECIAL_HASHHASH)) {
977 try_arg(token, TOKEN_QUOTED_ARGUMENT, arglist);
978 } else {
979 try_arg(token, TOKEN_MACRO_ARGUMENT, arglist);
981 if (token_type(token) == TOKEN_ERROR)
982 goto Earg;
983 last = token;
985 token = alloc_token(&expansion->pos);
986 token_type(token) = TOKEN_UNTAINT;
987 token->ident = name;
988 token->next = *p;
989 *p = token;
990 return expansion;
992 Equote:
993 warning(token->pos, "'#' is not followed by a macro parameter");
994 return NULL;
996 Econcat:
997 warning(token->pos, "'##' cannot appear at the ends of macro expansion");
998 return NULL;
999 Earg:
1000 warning(token->pos, "too many instances of argument in body");
1001 return NULL;
1004 static int do_handle_define(struct stream *stream, struct token **line, struct token *token, int weak)
1006 struct token *arglist, *expansion;
1007 struct token *left = token->next;
1008 struct symbol *sym;
1009 struct ident *name;
1011 if (token_type(left) != TOKEN_IDENT) {
1012 warning(token->pos, "expected identifier to 'define'");
1013 return 0;
1015 if (false_nesting)
1016 return free_preprocessor_line(token);
1018 if (stream->constant == CONSTANT_FILE_MAYBE)
1019 MARK_STREAM_NONCONST(token->pos);
1021 __free_token(token); /* Free the "define" token, but not the rest of the line */
1022 name = left->ident;
1024 arglist = NULL;
1025 expansion = left->next;
1026 if (!expansion->pos.whitespace && match_op(expansion, '(')) {
1027 arglist = expansion;
1028 expansion = parse_arguments(expansion);
1029 if (!expansion)
1030 return 1;
1033 expansion = parse_expansion(expansion, arglist, name);
1034 if (!expansion)
1035 return 1;
1037 sym = lookup_symbol(name, NS_MACRO);
1038 if (sym) {
1039 if (token_list_different(sym->expansion, expansion) ||
1040 token_list_different(sym->arglist, arglist)) {
1041 if (sym->weak)
1042 goto replace_it;
1043 if (weak)
1044 return 1;
1045 warning(left->pos, "preprocessor token %.*s redefined",
1046 name->len, name->name);
1047 info(sym->pos, "this was the original definition");
1048 sym->expansion = expansion;
1049 sym->arglist = arglist;
1051 return 1;
1053 sym = alloc_symbol(left->pos, SYM_NODE);
1054 bind_symbol(sym, name, NS_MACRO);
1056 replace_it:
1057 sym->expansion = expansion;
1058 sym->arglist = arglist;
1059 sym->weak = weak;
1060 return 1;
1063 static int handle_define(struct stream *stream, struct token **line, struct token *token)
1065 return do_handle_define(stream, line, token, 0);
1068 static int handle_weak_define(struct stream *stream, struct token **line, struct token *token)
1070 return do_handle_define(stream, line, token, 1);
1073 static int handle_undef(struct stream *stream, struct token **line, struct token *token)
1075 struct token *left = token->next;
1076 struct symbol **sym;
1078 if (token_type(left) != TOKEN_IDENT) {
1079 warning(token->pos, "expected identifier to 'undef'");
1080 return 0;
1082 if (false_nesting)
1083 return free_preprocessor_line(token);
1085 if (stream->constant == CONSTANT_FILE_MAYBE)
1086 MARK_STREAM_NONCONST(token->pos);
1088 sym = &left->ident->symbols;
1089 while (*sym) {
1090 struct symbol *t = *sym;
1091 if (t->namespace == NS_MACRO) {
1092 *sym = t->next_id;
1093 return 1;
1095 sym = &t->next_id;
1097 return free_preprocessor_line(token);
1100 static int preprocessor_if(struct token *token, int true)
1102 if (if_nesting == 0)
1103 unmatched_if = token;
1104 if (if_nesting >= MAX_NEST)
1105 error_die(token->pos, "Maximum preprocessor conditional level exhausted");
1106 elif_ignore[if_nesting] = (false_nesting || true) ? ELIF_IGNORE : 0;
1107 if (false_nesting || !true) {
1108 false_nesting++;
1109 return free_preprocessor_line(token);
1111 true_nesting++;
1112 return free_preprocessor_line(token);
1115 static int handle_ifdef(struct stream *stream, struct token **line, struct token *token)
1117 return preprocessor_if(token, token_defined(token->next));
1120 static int handle_ifndef(struct stream *stream, struct token **line, struct token *token)
1122 struct token *next = token->next;
1123 if (stream->constant == CONSTANT_FILE_MAYBE) {
1124 if (token_type(next) == TOKEN_IDENT &&
1125 (!stream->protect || stream->protect == next->ident)) {
1126 stream->constant = CONSTANT_FILE_IFNDEF;
1127 stream->protect = next->ident;
1128 } else
1129 MARK_STREAM_NONCONST(token->pos);
1131 return preprocessor_if(token, !token_defined(next));
1135 * Expression handling for #if and #elif; it differs from normal expansion
1136 * due to special treatment of "defined".
1138 static int expression_value(struct token **where)
1140 struct expression *expr;
1141 struct token *p;
1142 struct token **list = where, **beginning = NULL;
1143 long long value;
1144 int state = 0;
1146 while (!eof_token(p = scan_next(list))) {
1147 switch (state) {
1148 case 0:
1149 if (token_type(p) != TOKEN_IDENT)
1150 break;
1151 if (p->ident == &defined_ident) {
1152 state = 1;
1153 beginning = list;
1154 break;
1156 if (!expand_one_symbol(list))
1157 continue;
1158 if (token_type(p) != TOKEN_IDENT)
1159 break;
1160 if (Wundefined_preprocessor)
1161 warning(p->pos, "undefined preprocessor identifier '%s'", show_ident(p->ident));
1162 replace_with_integer(p, 0);
1163 break;
1164 case 1:
1165 if (match_op(p, '(')) {
1166 state = 2;
1167 } else {
1168 state = 0;
1169 replace_with_defined(p);
1170 *beginning = p;
1172 break;
1173 case 2:
1174 if (token_type(p) == TOKEN_IDENT)
1175 state = 3;
1176 else
1177 state = 0;
1178 replace_with_defined(p);
1179 *beginning = p;
1180 break;
1181 case 3:
1182 state = 0;
1183 if (!match_op(p, ')'))
1184 warning(p->pos, "missing ')' after \"defined\"");
1185 *list = p->next;
1186 continue;
1188 list = &p->next;
1191 p = constant_expression(*where, &expr);
1192 if (!eof_token(p))
1193 warning(p->pos, "garbage at end: %s", show_token_sequence(p));
1194 value = get_expression_value(expr);
1195 return value != 0;
1198 static int handle_if(struct stream *stream, struct token **line, struct token *token)
1200 int value = 0;
1201 if (!false_nesting)
1202 value = expression_value(&token->next);
1204 // This is an approximation. We really only need this if the
1205 // condition does depends on a pre-processor symbol. Note, that
1206 // the important #ifndef case has already changed ->constant.
1207 if (stream->constant == CONSTANT_FILE_MAYBE)
1208 MARK_STREAM_NONCONST(token->pos);
1210 return preprocessor_if(token, value);
1213 static int handle_elif(struct stream * stream, struct token **line, struct token *token)
1215 if (stream->nesting == if_nesting)
1216 MARK_STREAM_NONCONST(token->pos);
1218 if (stream->nesting > if_nesting)
1219 warning(token->pos, "unmatched #elif within stream");
1221 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1222 warning(token->pos, "#elif after #else");
1224 if (false_nesting) {
1225 /* If this whole if-thing is if'ed out, an elif cannot help */
1226 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1227 return 1;
1228 if (expression_value(&token->next)) {
1229 false_nesting = 0;
1230 true_nesting++;
1231 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1233 } else {
1234 false_nesting = 1;
1235 true_nesting--;
1237 return free_preprocessor_line(token);
1240 static int handle_else(struct stream *stream, struct token **line, struct token *token)
1242 if (stream->nesting == if_nesting)
1243 MARK_STREAM_NONCONST(token->pos);
1245 if (stream->nesting > if_nesting)
1246 warning(token->pos, "unmatched #else within stream");
1248 if (elif_ignore[if_nesting-1] & ELIF_SEEN_ELSE)
1249 warning(token->pos, "#else after #else");
1250 else
1251 elif_ignore[if_nesting-1] |= ELIF_SEEN_ELSE;
1253 if (false_nesting) {
1254 /* If this whole if-thing is if'ed out, an else cannot help */
1255 if (elif_ignore[if_nesting-1] & ELIF_IGNORE)
1256 return 1;
1257 false_nesting = 0;
1258 true_nesting++;
1259 elif_ignore[if_nesting-1] |= ELIF_IGNORE;
1260 } else {
1261 true_nesting--;
1262 false_nesting = 1;
1264 return free_preprocessor_line(token);
1267 static int handle_endif(struct stream *stream, struct token **line, struct token *token)
1269 if (stream->constant == CONSTANT_FILE_IFNDEF && stream->nesting == if_nesting)
1270 stream->constant = CONSTANT_FILE_MAYBE;
1272 if (stream->nesting > if_nesting)
1273 warning(token->pos, "unmatched #endif in stream");
1274 if (false_nesting)
1275 false_nesting--;
1276 else
1277 true_nesting--;
1278 return free_preprocessor_line(token);
1281 static const char *show_token_sequence(struct token *token)
1283 static char buffer[1024];
1284 char *ptr = buffer;
1285 int whitespace = 0;
1287 if (!token)
1288 return "<none>";
1289 while (!eof_token(token)) {
1290 const char *val = show_token(token);
1291 int len = strlen(val);
1293 if (ptr + whitespace + len >= buffer + sizeof(buffer)) {
1294 warning(token->pos, "too long token expansion");
1295 break;
1298 if (whitespace)
1299 *ptr++ = ' ';
1300 memcpy(ptr, val, len);
1301 ptr += len;
1302 token = token->next;
1303 whitespace = token->pos.whitespace;
1305 *ptr = 0;
1306 return buffer;
1309 static int handle_warning(struct stream *stream, struct token **line, struct token *token)
1311 if (false_nesting)
1312 return free_preprocessor_line(token);
1313 if (stream->constant == CONSTANT_FILE_MAYBE)
1314 MARK_STREAM_NONCONST(token->pos);
1315 warning(token->pos, "%s", show_token_sequence(token->next));
1316 return free_preprocessor_line(token);
1319 static int handle_error(struct stream *stream, struct token **line, struct token *token)
1321 if (false_nesting)
1322 return free_preprocessor_line(token);
1323 if (stream->constant == CONSTANT_FILE_MAYBE)
1324 MARK_STREAM_NONCONST(token->pos);
1325 warning(token->pos, "%s", show_token_sequence(token->next));
1326 return free_preprocessor_line(token);
1329 static int handle_nostdinc(struct stream *stream, struct token **line, struct token *token)
1331 int stdinc;
1333 if (false_nesting)
1334 return free_preprocessor_line(token);
1337 * Do we have any non-system includes?
1338 * Clear them out if so..
1340 stdinc = gcc_includepath - sys_includepath;
1341 if (stdinc) {
1342 const char **src = gcc_includepath;
1343 const char **dst = sys_includepath;
1344 for (;;) {
1345 if (!(*dst = *src))
1346 break;
1347 dst++;
1348 src++;
1350 gcc_includepath -= stdinc;
1352 return free_preprocessor_line(token);
1355 static void add_path_entry(struct token *token, const char *path)
1357 const char **dst;
1358 const char *next;
1360 /* Need one free entry.. */
1361 if (includepath[INCLUDEPATHS-2])
1362 error_die(token->pos, "too many include path entries");
1364 next = path;
1365 dst = sys_includepath;
1366 sys_includepath++;
1367 gcc_includepath++;
1370 * Move them all up starting at "sys_includepath",
1371 * insert the new entry..
1373 for (;;) {
1374 const char *tmp = *dst;
1375 *dst = next;
1376 if (!next)
1377 break;
1378 next = tmp;
1379 dst++;
1383 static int handle_add_include(struct stream *stream, struct token **line, struct token *token)
1385 for (;;) {
1386 token = token->next;
1387 if (eof_token(token))
1388 return 1;
1389 if (token_type(token) != TOKEN_STRING) {
1390 warning(token->pos, "expected path string");
1391 return 1;
1393 add_path_entry(token, token->string->data);
1398 * We replace "#pragma xxx" with "__pragma__" in the token
1399 * stream. Just as an example.
1401 * We'll just #define that away for now, but the theory here
1402 * is that we can use this to insert arbitrary token sequences
1403 * to turn the pragma's into internal front-end sequences for
1404 * when we actually start caring about them.
1406 * So eventually this will turn into some kind of extended
1407 * __attribute__() like thing, except called __pragma__(xxx).
1409 static int handle_pragma(struct stream *stream, struct token **line, struct token *token)
1411 struct token *next = *line;
1413 token->ident = &pragma_ident;
1414 token->pos.newline = 1;
1415 token->pos.whitespace = 1;
1416 token->pos.pos = 1;
1417 *line = token;
1418 token->next = next;
1419 return 1;
1423 * We ignore #line for now.
1425 static int handle_line(struct stream *stream, struct token **line, struct token *token)
1427 return 1;
1431 void init_preprocessor(void)
1433 int i;
1434 int stream = init_stream("preprocessor", -1, includepath);
1435 static struct {
1436 const char *name;
1437 int (*handler)(struct stream *, struct token **, struct token *);
1438 } handlers[] = {
1439 { "define", handle_define },
1440 { "weak_define",handle_weak_define },
1441 { "undef", handle_undef },
1442 { "ifdef", handle_ifdef },
1443 { "ifndef", handle_ifndef },
1444 { "else", handle_else },
1445 { "endif", handle_endif },
1446 { "if", handle_if },
1447 { "elif", handle_elif },
1448 { "warning", handle_warning },
1449 { "error", handle_error },
1450 { "include", handle_include },
1451 { "include_next",handle_include_next },
1452 { "pragma", handle_pragma },
1453 { "line", handle_line },
1455 // our internal preprocessor tokens
1456 { "nostdinc", handle_nostdinc },
1457 { "add_include", handle_add_include },
1460 for (i = 0; i < (sizeof (handlers) / sizeof (handlers[0])); i++) {
1461 struct symbol *sym;
1462 sym = create_symbol(stream, handlers[i].name, SYM_PREPROCESSOR, NS_PREPROCESSOR);
1463 sym->handler = handlers[i].handler;
1467 static void handle_preprocessor_line(struct stream *stream, struct token **line, struct token *start)
1469 struct token *token = start->next;
1471 if (!token)
1472 return;
1474 if (token_type(token) == TOKEN_NUMBER)
1475 if (handle_line(stream, line, start))
1476 return;
1478 if (token_type(token) == TOKEN_IDENT) {
1479 struct symbol *sym = lookup_symbol(token->ident, NS_PREPROCESSOR);
1480 if (sym && sym->handler(stream, line, token))
1481 return;
1484 warning(token->pos, "unrecognized preprocessor line '%s'", show_token_sequence(token));
1487 static void preprocessor_line(struct stream *stream, struct token **line)
1489 struct token *start = *line, *next;
1490 struct token **tp = &start->next;
1492 for (;;) {
1493 next = *tp;
1494 if (next->pos.newline)
1495 break;
1496 tp = &next->next;
1498 *line = next;
1499 *tp = &eof_token_entry;
1500 handle_preprocessor_line(stream, line, start);
1503 static void do_preprocess(struct token **list)
1505 struct token *next;
1507 while (!eof_token(next = scan_next(list))) {
1508 struct stream *stream = input_streams + next->pos.stream;
1510 if (next->pos.newline && match_op(next, '#')) {
1511 if (!next->pos.noexpand) {
1512 preprocessor_line(stream, list);
1513 __free_token(next); /* Free the '#' token */
1514 continue;
1518 switch (token_type(next)) {
1519 case TOKEN_STREAMEND:
1520 if (stream->nesting < if_nesting + 1) {
1521 warning(unmatched_if->pos, "unterminated preprocessor conditional");
1522 // Pretend to see a series of #endifs
1523 MARK_STREAM_NONCONST(next->pos);
1524 do {
1525 handle_endif (stream, NULL, NULL);
1526 } while (stream->nesting < if_nesting + 1);
1528 if (stream->constant == CONSTANT_FILE_MAYBE && stream->protect) {
1529 stream->constant = CONSTANT_FILE_YES;
1531 *list = next->next;
1532 continue;
1533 case TOKEN_STREAMBEGIN:
1534 stream->nesting = if_nesting + 1;
1535 *list = next->next;
1536 continue;
1538 default:
1539 if (false_nesting) {
1540 *list = next->next;
1541 __free_token(next);
1542 continue;
1545 if (token_type(next) != TOKEN_IDENT ||
1546 expand_one_symbol(list))
1547 list = &next->next;
1550 if (stream->constant == CONSTANT_FILE_MAYBE) {
1552 * Any token expansion (even if it ended up being an
1553 * empty expansion) in this stream implies it can't
1554 * be constant.
1556 MARK_STREAM_NONCONST(next->pos);
1561 struct token * preprocess(struct token *token)
1563 preprocessing = 1;
1564 init_preprocessor();
1565 do_preprocess(&token);
1567 // Drop all expressions from pre-processing, they're not used any more.
1568 clear_expression_alloc();
1569 preprocessing = 0;
1571 return token;