2 * Copyright (C) 1986, 87, 89, 92, 93, 94, 1995 Free Software Foundation, Inc.
3 * Written by Per Bothner, 1994-95.
4 * Based on CCCP program by by Paul Rubin, June 1986
5 * Adapted to ANSI C, Richard Stallman, Jan 1987
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
21 * In other words, you are welcome to use, share and improve this program.
22 * You are forbidden to forbid anyone else to use, share and improve
23 * what you give them. Help stamp out software-hoarding! */
25 const char *version_string = "0.0.0";
33 #ifndef STANDARD_INCLUDE_DIR
34 #define STANDARD_INCLUDE_DIR "/usr/include"
37 #ifndef LOCAL_INCLUDE_DIR
38 #define LOCAL_INCLUDE_DIR "/usr/local/include"
48 /* By default, colon separates directories in a path. */
49 #ifndef PATH_SEPARATOR
50 #define PATH_SEPARATOR ':'
64 #include <sys/types.h>
72 #include <sys/time.h> /* for __DATE__ and __TIME__ */
73 #include <sys/resource.h>
75 #include <sys/param.h> /* CYGNUS LOCAL: shebs -noquiet */
76 #include <sys/times.h>
82 /* This defines "errno" properly for VMS, and gives us EACCES. */
91 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
92 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
95 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
99 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
102 /* Define a generic NULL if one hasn't already been defined. */
105 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
106 #define GENERIC_PTR void *
108 #define GENERIC_PTR char *
112 #ifndef INCLUDE_LEN_FUDGE
113 #define INCLUDE_LEN_FUDGE 0
116 #define USE_FILE_NAME_MAPS 0
118 /* Symbols to predefine. */
120 #ifdef CPP_PREDEFINES
121 static const char *predefs = CPP_PREDEFINES;
124 static const char *predefs = "";
128 /* We let tm.h override the types used here, to handle trivial differences
129 * such as the choice of unsigned int or long unsigned int for size_t.
130 * When machines start needing nontrivial differences in the size type,
131 * it would be best to do something here to figure out automatically
132 * from other information what type to use. */
134 /* The string value for __SIZE_TYPE__. */
137 #define SIZE_TYPE "long unsigned int"
140 /* The string value for __PTRDIFF_TYPE__. */
143 #define PTRDIFF_TYPE "long int"
146 /* The string value for __WCHAR_TYPE__. */
149 #define WCHAR_TYPE "int"
151 #define CPP_WCHAR_TYPE(PFILE) \
152 (CPP_OPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
154 /* The string value for __USER_LABEL_PREFIX__ */
156 #ifndef USER_LABEL_PREFIX
157 #define USER_LABEL_PREFIX ""
160 /* The string value for __REGISTER_PREFIX__ */
162 #ifndef REGISTER_PREFIX
163 #define REGISTER_PREFIX ""
168 int (*func) (cpp_reader * pfile, struct directive * keyword,
169 unsigned char *buf, unsigned char *limit);
172 char command_reads_line;
173 char traditional_comments;
177 /* In the definition of a #assert name, this structure forms
178 * a list of the individual values asserted.
179 * Each value is itself a list of "tokens".
180 * These are strings that are compared by name. */
182 struct tokenlist_list {
183 struct tokenlist_list *next;
184 struct arglist *tokens;
187 struct assertion_hashnode {
188 struct assertion_hashnode *next; /* double links for easy deletion */
189 struct assertion_hashnode *prev;
190 /* also, a back pointer to this node's hash
191 * chain is kept, in case the node is the head
192 * of the chain and gets deleted. */
193 struct assertion_hashnode **bucket_hdr;
194 int length; /* length of token, for quick comparison */
195 char *name; /* the actual name */
196 /* List of token-sequences. */
197 struct tokenlist_list *value;
200 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[(unsigned char)(*p)]) p++; } while (0)
201 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[(unsigned char)(*p)]) p++; } while (0)
203 #define PEEKN(N) (CPP_BUFFER (pfile)->rlimit - CPP_BUFFER (pfile)->cur >= (N) ? CPP_BUFFER (pfile)->cur[N] : EOF)
204 #define FORWARD(N) CPP_FORWARD (CPP_BUFFER (pfile), (N))
205 #define GETC() CPP_BUF_GET (CPP_BUFFER (pfile))
206 #define PEEKC() CPP_BUF_PEEK (CPP_BUFFER (pfile))
207 /* CPP_IS_MACRO_BUFFER is true if the buffer contains macro expansion.
208 * (Note that it is false while we're expanding marco *arguments*.) */
209 #define CPP_IS_MACRO_BUFFER(PBUF) ((PBUF)->cleanup == macro_cleanup)
211 /* Move all backslash-newline pairs out of embarrassing places.
212 * Exchange all such pairs following BP
213 * with any potentially-embarrassing characters that follow them.
214 * Potentially-embarrassing characters are / and *
215 * (because a backslash-newline inside a comment delimiter
216 * would cause it not to be recognized). */
218 #define NEWLINE_FIX \
219 do {while (PEEKC() == '\\' && PEEKN(1) == '\n') FORWARD(2); } while(0)
221 /* Same, but assume we've already read the potential '\\' into C. */
222 #define NEWLINE_FIX1(C) do { \
223 while ((C) == '\\' && PEEKC() == '\n') { FORWARD(1); (C) = GETC(); }\
226 /* Name under which this program was invoked. */
231 struct cpp_pending *next;
236 /* Structure returned by create_definition */
238 struct definition *defn;
243 /* Forward declarations. */
245 static void add_import(cpp_reader * pfile, int fd, char *fname);
246 static int finclude(cpp_reader * pfile, int f, const char *fname,
248 struct file_name_list *dirptr);
249 static void validate_else(cpp_reader * pfile, const char *directive);
250 static int comp_def_part(int first, unsigned char *beg1, int len1,
251 unsigned char *beg2, int len2, int last);
252 static int lookup_import(cpp_reader * pfile, char *filename,
253 struct file_name_list *searchptr);
254 static int redundant_include_p(cpp_reader * pfile, char *name);
256 static int is_system_include(cpp_reader * pfile, char *filename);
258 static int open_include_file(cpp_reader * pfile, char *filename,
259 struct file_name_list *searchptr);
260 static int check_macro_name(cpp_reader * pfile, unsigned char *symname,
263 static int compare_token_lists(struct arglist *l1, struct arglist *l2);
264 static HOST_WIDE_INT eval_if_expression(cpp_reader * pfile, unsigned char *buf,
267 static int file_size_and_mode(int fd, int *mode_pointer,
268 long int *size_pointer);
269 static struct arglist *read_token_list(cpp_reader * pfile, int *error_flag);
270 static void free_token_list(struct arglist *tokens);
271 static int safe_read(int desc, char *ptr, int len);
272 static void push_macro_expansion(cpp_reader * pfile,
274 int xbuf_len, HASHNODE * hp);
276 static struct cpp_pending *nreverse_pending(struct cpp_pending *list);
277 static char *savestring(const char *input);
279 static void conditional_skip(cpp_reader * pfile, int skip,
281 unsigned char *control_macro);
282 static void skip_if_group(cpp_reader * pfile, int any);
284 static void cpp_error_with_line(cpp_reader * pfile, int line,
285 int column, const char *msg);
286 static void cpp_pedwarn_with_line(cpp_reader * pfile, int line,
287 int column, const char *msg);
288 static void cpp_pedwarn_with_file_and_line(cpp_reader * pfile,
289 const char *file, int line,
294 static void cpp_error_from_errno(cpp_reader * pfile, const char *name);
296 static cpp_buffer *cpp_push_buffer(cpp_reader * pfile, unsigned char *buffer,
298 static cpp_buffer *cpp_pop_buffer(cpp_reader * pfile);
300 /* Last arg to output_line_command. */
301 enum file_change_code {
302 same_file, enter_file, leave_file
305 /* These functions are declared to return int instead of void since they
306 * are going to be placed in a table and some old compilers have trouble with
307 * pointers to functions returning void. */
309 static int do_define(cpp_reader * pfile, struct directive *keyword,
310 unsigned char *buf, unsigned char *limit);
312 static int do_line(cpp_reader * pfile, struct directive *keyword,
313 unsigned char *unused1, unsigned char *unused2);
315 static int do_include(cpp_reader * pfile, struct directive *keyword,
316 unsigned char *unused1, unsigned char *unused2);
318 static int do_undef(cpp_reader * pfile, struct directive *keyword,
319 unsigned char *buf, unsigned char *limit);
321 static int do_error(cpp_reader * pfile, struct directive *keyword,
322 unsigned char *buf, unsigned char *limit);
324 static int do_pragma(cpp_reader * pfile, struct directive *keyword,
325 unsigned char *buf, unsigned char *limit);
327 static int do_ident(cpp_reader * pfile, struct directive *keyword,
328 unsigned char *buf, unsigned char *limit);
330 static int do_if(cpp_reader * pfile, struct directive *keyword,
331 unsigned char *buf, unsigned char *limit);
333 static int do_xifdef(cpp_reader * pfile, struct directive *keyword,
334 unsigned char *buf, unsigned char *limit);
336 static int do_else(cpp_reader * pfile, struct directive *keyword,
337 unsigned char *buf, unsigned char *limit);
339 static int do_elif(cpp_reader * pfile, struct directive *keyword,
340 unsigned char *buf, unsigned char *limit);
342 static int do_endif(cpp_reader * pfile, struct directive *keyword,
343 unsigned char *buf, unsigned char *limit);
345 static int do_assert(cpp_reader * pfile, struct directive *keyword,
346 unsigned char *buf, unsigned char *limit);
348 static int do_unassert(cpp_reader * pfile, struct directive *keyword,
349 unsigned char *buf, unsigned char *limit);
351 static int do_warning(cpp_reader * pfile, struct directive *keyword,
352 unsigned char *buf, unsigned char *limit);
354 struct arglist *reverse_token_list(struct arglist *tokens);
356 static int parse_name(cpp_reader * pfile, int c);
358 static void parse_set_mark(struct parse_marker *pmark,
360 static void parse_clear_mark(struct parse_marker *pmark);
361 static void parse_goto_mark(struct parse_marker *pmark,
363 static void parse_move_mark(struct parse_marker *pmark,
366 struct file_name_list {
367 struct file_name_list *next;
369 /* If the following is nonzero, it is a macro name.
370 * Don't include the file again if that macro is defined. */
371 unsigned char *control_macro;
372 /* If the following is nonzero, it is a C-language system include
374 int c_system_include_path;
375 /* Mapping of file names for this directory. */
376 struct file_name_map *name_map;
377 /* Non-zero if name_map is valid. */
381 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
382 * via the same directory as the file that #included it. */
383 #define SELF_DIR_DUMMY ((struct file_name_list*)(~0))
385 /* #include "file" looks in source file dir, then stack. */
386 /* #include <file> just looks in the stack. */
387 /* -I directories are added to the end, then the defaults are added. */
389 static struct default_include {
390 const char *fname; /* The name of the directory. */
391 int cplusplus; /* Only look here if we're compiling C++. */
392 int cxx_aware; /* Includes in this directory don't need to
393 * be wrapped in extern "C" when compiling
395 } include_defaults_array[]
396 #ifdef INCLUDE_DEFAULTS
402 /* Pick up GNU C++ specific include files. */
404 GPLUSPLUS_INCLUDE_DIR, 1, 1}
407 /* This is the dir for fixincludes. Put it just before
408 * the files that we fix. */
410 GCC_INCLUDE_DIR, 0, 0}
412 /* For cross-compilation, this dir name is generated
413 * automatically in Makefile.in. */
415 CROSS_INCLUDE_DIR, 0, 0}
417 /* This is another place that the target system's headers might be. */
419 TOOL_INCLUDE_DIR, 0, 1}
421 #else /* not CROSS_COMPILE */
422 /* This should be /usr/local/include and should come before
423 * the fixincludes-fixed header files. */
425 LOCAL_INCLUDE_DIR, 0, 1}
427 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
428 * Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
430 TOOL_INCLUDE_DIR, 0, 1}
432 /* This is the dir for fixincludes. Put it just before
433 * the files that we fix. */
435 GCC_INCLUDE_DIR, 0, 0}
437 /* Some systems have an extra dir of include files. */
438 #ifdef SYSTEM_INCLUDE_DIR
440 SYSTEM_INCLUDE_DIR, 0, 0}
444 STANDARD_INCLUDE_DIR, 0, 0}
446 #endif /* not CROSS_COMPILE */
451 #endif /* no INCLUDE_DEFAULTS */
453 /* Here is the actual list of #-directives, most-often-used first.
454 * The initialize_builtins function assumes #define is the very first. */
456 static struct directive directive_table[] = {
457 {6, do_define, "define", T_DEFINE, 0, 1, 0},
458 {5, do_xifdef, "ifdef", T_IFDEF, 1, 0, 0},
459 {6, do_xifdef, "ifndef", T_IFNDEF, 1, 0, 0},
460 {7, do_include, "include", T_INCLUDE, 1, 0, 0},
461 {12, do_include, "include_next", T_INCLUDE_NEXT, 1, 0, 0},
462 {6, do_include, "import", T_IMPORT, 1, 0, 0},
463 {5, do_endif, "endif", T_ENDIF, 1, 0, 0},
464 {4, do_else, "else", T_ELSE, 1, 0, 0},
465 {2, do_if, "if", T_IF, 1, 0, 0},
466 {4, do_elif, "elif", T_ELIF, 1, 0, 0},
467 {5, do_undef, "undef", T_UNDEF, 0, 0, 0},
468 {5, do_error, "error", T_ERROR, 0, 0, 0},
469 {7, do_warning, "warning", T_WARNING, 0, 0, 0},
470 {6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
471 {4, do_line, "line", T_LINE, 1, 0, 0},
472 {5, do_ident, "ident", T_IDENT, 1, 0, 1},
473 #ifdef SCCS_DIRECTIVE
474 {4, do_sccs, "sccs", T_SCCS, 0, 0, 0},
476 {6, do_assert, "assert", T_ASSERT, 1, 0, 0},
477 {8, do_unassert, "unassert", T_UNASSERT, 1, 0, 0},
478 {-1, 0, "", T_UNUSED, 0, 0, 0},
481 /* table to tell if char can be part of a C identifier. */
482 unsigned char is_idchar[256];
484 /* table to tell if char can be first char of a c identifier. */
485 unsigned char is_idstart[256];
487 /* table to tell if c is horizontal space. */
488 unsigned char is_hor_space[256];
490 /* table to tell if c is horizontal or vertical space. */
491 static unsigned char is_space[256];
493 /* Initialize syntactic classifications of characters. */
496 initialize_char_syntax(struct cpp_options *opts)
501 * Set up is_idchar and is_idstart tables. These should be
502 * faster than saying (is_alpha (c) || c == '_'), etc.
503 * Set up these things before calling any routines tthat
506 for (i = 'a'; i <= 'z'; i++)
508 is_idchar[i - 'a' + 'A'] = 1;
510 is_idstart[i - 'a' + 'A'] = 1;
513 for (i = '0'; i <= '9'; i++)
515 is_idchar[(unsigned char)'_'] = 1;
516 is_idstart[(unsigned char)'_'] = 1;
517 is_idchar[(unsigned char)'$'] = opts->dollars_in_ident;
518 is_idstart[(unsigned char)'$'] = opts->dollars_in_ident;
520 /* horizontal space table */
521 is_hor_space[(unsigned char)' '] = 1;
522 is_hor_space[(unsigned char)'\t'] = 1;
523 is_hor_space[(unsigned char)'\v'] = 1;
524 is_hor_space[(unsigned char)'\f'] = 1;
525 is_hor_space[(unsigned char)'\r'] = 1;
527 is_space[(unsigned char)' '] = 1;
528 is_space[(unsigned char)'\t'] = 1;
529 is_space[(unsigned char)'\v'] = 1;
530 is_space[(unsigned char)'\f'] = 1;
531 is_space[(unsigned char)'\n'] = 1;
532 is_space[(unsigned char)'\r'] = 1;
535 /* Place into PFILE a quoted string representing the string SRC.
536 * Caller must reserve enough space in pfile->token_buffer. */
538 quote_string(cpp_reader * pfile, const char *src)
542 CPP_PUTC_Q(pfile, '\"');
544 switch ((c = *src++))
548 CPP_PUTC_Q(pfile, c);
551 sprintf((char *)CPP_PWRITTEN(pfile), "\\%03o", c);
552 CPP_ADJUST_WRITTEN(pfile, 4);
558 CPP_PUTC_Q(pfile, '\\');
559 CPP_PUTC_Q(pfile, c);
563 CPP_PUTC_Q(pfile, '\"');
564 CPP_NUL_TERMINATE_Q(pfile);
569 /* Make sure PFILE->token_buffer will hold at least N more chars. */
572 cpp_grow_buffer(cpp_reader * pfile, long n)
574 long old_written = CPP_WRITTEN(pfile);
576 pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
577 pfile->token_buffer =
578 (unsigned char *)xrealloc(pfile->token_buffer, pfile->token_buffer_size);
579 CPP_SET_WRITTEN(pfile, old_written);
583 * process a given definition string, for initialization
584 * If STR is just an identifier, define it with value 1.
585 * If STR has anything after the identifier, then it should
586 * be identifier=definition.
590 cpp_define(cpp_reader * pfile, unsigned char *str)
592 unsigned char *buf, *p;
598 cpp_error(pfile, "malformed option `-D %s'", str);
601 while (is_idchar[*++p])
605 buf = (unsigned char *)alloca(p - buf + 4);
606 strcpy((char *)buf, (const char *)str);
607 strcat((char *)buf, " 1");
611 cpp_error(pfile, "malformed option `-D %s'", str);
618 /* Copy the entire option so we can modify it. */
619 buf = (unsigned char *)alloca(2 * strlen((char *)str) + 1);
620 strncpy((char *)buf, (const char *)str, p - str);
621 /* Change the = to a space. */
623 /* Scan for any backslash-newline and remove it. */
628 if (*p == '\\' && p[1] == '\n')
636 do_define(pfile, NULL, buf, buf + strlen((char *)buf));
639 /* Process the string STR as if it appeared as the body of a #assert.
640 * OPTION is the option name for which STR was the argument. */
643 make_assertion(cpp_reader * pfile, const char *option, const char *str)
646 unsigned char *buf, *p, *q;
648 /* Copy the entire option so we can modify it. */
649 buf = (unsigned char *)alloca(strlen((char *)str) + 1);
650 strcpy((char *)buf, (const char *)str);
651 /* Scan for any backslash-newline and remove it. */
662 cpp_error(pfile, "malformed option `%s %s'", option, str);
665 while (is_idchar[*++p])
667 while (*p == ' ' || *p == '\t')
669 if (!(*p == 0 || *p == '('))
671 cpp_error(pfile, "malformed option `%s %s'", option, str);
674 ip = cpp_push_buffer(pfile, buf, strlen((char *)buf));
675 do_assert(pfile, NULL, NULL, NULL);
676 cpp_pop_buffer(pfile);
679 /* Append a chain of `struct file_name_list's
680 * to the end of the main include chain.
681 * FIRST is the beginning of the chain to append, and LAST is the end. */
684 append_include_chain(cpp_reader * pfile, struct file_name_list *first,
685 struct file_name_list *last)
687 struct cpp_options *opts = CPP_OPTIONS(pfile);
688 struct file_name_list *dir;
693 if (opts->include == 0)
694 opts->include = first;
696 opts->last_include->next = first;
698 if (opts->first_bracket_include == 0)
699 opts->first_bracket_include = first;
701 for (dir = first;; dir = dir->next)
703 int len = strlen(dir->fname) + INCLUDE_LEN_FUDGE;
705 if (len > pfile->max_include_len)
706 pfile->max_include_len = len;
712 opts->last_include = last;
715 /* Add output to `deps_buffer' for the -M switch.
716 * STRING points to the text to be output.
717 * SPACER is ':' for targets, ' ' for dependencies, zero for text
718 * to be inserted literally. */
721 deps_output(cpp_reader * pfile, const char *string, int spacer)
723 int size = strlen(string);
728 #ifndef MAX_OUTPUT_COLUMNS
729 #define MAX_OUTPUT_COLUMNS 72
732 && pfile->deps_column > 0
733 && (pfile->deps_column + size) > MAX_OUTPUT_COLUMNS)
735 deps_output(pfile, " \\\n ", 0);
736 pfile->deps_column = 0;
738 if (pfile->deps_size + size + 8 > pfile->deps_allocated_size)
740 pfile->deps_allocated_size = (pfile->deps_size + size + 50) * 2;
741 pfile->deps_buffer = (char *)xrealloc(pfile->deps_buffer,
742 pfile->deps_allocated_size);
744 if (spacer == ' ' && pfile->deps_column > 0)
745 pfile->deps_buffer[pfile->deps_size++] = ' ';
746 memcpy(&pfile->deps_buffer[pfile->deps_size], string, size);
747 pfile->deps_size += size;
748 pfile->deps_column += size;
750 pfile->deps_buffer[pfile->deps_size++] = ':';
751 pfile->deps_buffer[pfile->deps_size] = 0;
754 /* Given a colon-separated list of file names PATH,
755 * add all the names to the search path for include files. */
758 path_include(cpp_reader * pfile, char *path)
769 struct file_name_list *dirtmp;
771 /* Find the end of this name. */
772 while (*q != 0 && *q != PATH_SEPARATOR)
776 /* An empty name in the path stands for the current directory. */
777 name = (char *)xmalloc(2);
783 /* Otherwise use the directory that is named. */
784 name = (char *)xmalloc(q - p + 1);
785 memcpy(name, p, q - p);
790 (struct file_name_list *)xmalloc(sizeof(struct file_name_list));
792 dirtmp->next = 0; /* New one goes on the end */
793 dirtmp->control_macro = 0;
794 dirtmp->c_system_include_path = 0;
795 dirtmp->fname = name;
796 dirtmp->got_name_map = 0;
797 append_include_chain(pfile, dirtmp, dirtmp);
799 /* Advance past this name. */
803 /* Skip the colon. */
809 init_parse_options(struct cpp_options *opts)
811 memset((char *)opts, 0, sizeof *opts);
812 opts->in_fname = NULL;
813 opts->out_fname = NULL;
815 /* Initialize is_idchar to allow $. */
816 opts->dollars_in_ident = 1;
817 initialize_char_syntax(opts);
818 opts->dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
820 opts->no_line_commands = 0;
821 opts->no_trigraphs = 1;
822 opts->put_out_comments = 0;
823 opts->print_include_names = 0;
824 opts->dump_macros = dump_none;
827 opts->cplusplus_comments = 1;
834 opts->pedantic_errors = 0;
835 opts->inhibit_warnings = 0;
836 opts->warn_comments = 0;
837 opts->warn_import = 1;
838 opts->warnings_are_errors = 0;
841 static enum cpp_token
842 null_underflow(cpp_reader * pfile)
849 null_cleanup(cpp_buffer * pbuf, cpp_reader * pfile)
857 macro_cleanup(cpp_buffer * pbuf, cpp_reader * pfile)
859 HASHNODE *macro = (HASHNODE *) pbuf->data;
862 if (macro->type == T_DISABLED)
863 macro->type = T_MACRO;
864 if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
870 file_cleanup(cpp_buffer * pbuf, cpp_reader * pfile)
881 /* Assuming we have read '/'.
882 * If this is the start of a comment (followed by '*' or '/'),
883 * skip to the end of the comment, and return ' '.
884 * Return EOF if we reached the end of file before the end of the comment.
885 * If not the start of a comment, return '/'. */
888 skip_comment(cpp_reader * pfile, long *linep)
892 while (PEEKC() == '\\' && PEEKN(1) == '\n')
908 while (c == '\\' && PEEKC() == '\n')
912 FORWARD(1), c = GETC();
914 if (prev_c == '*' && c == '/')
916 if (c == '\n' && linep)
920 else if (PEEKC() == '/' && CPP_OPTIONS(pfile)->cplusplus_comments)
927 return ' '; /* Allow // to be terminated by EOF. */
928 while (c == '\\' && PEEKC() == '\n')
937 /* Don't consider final '\n' to be part of comment. */
947 /* Skip whitespace \-newline and comments. Does not macro-expand. */
949 cpp_skip_hspace(cpp_reader * pfile)
959 if ((c == '\f' || c == '\v') && CPP_PEDANTIC(pfile))
960 cpp_pedwarn(pfile, "%s in preprocessing directive",
961 c == '\f' ? "formfeed" : "vertical tab");
967 c = skip_comment(pfile, NULL);
970 if (c == EOF || c == '/')
973 else if (c == '\\' && PEEKN(1) == '\n')
977 else if (c == '@' && CPP_BUFFER(pfile)->has_escapes
978 && is_hor_space[PEEKN(1)])
985 /* Read the rest of the current line.
986 * The line is appended to PFILE's output buffer. */
989 copy_rest_of_line(cpp_reader * pfile)
991 struct cpp_options *opts = CPP_OPTIONS(pfile);
1003 if (PEEKC() == '\n')
1010 goto scan_directive_token;
1014 if (nextc == '*' || (opts->cplusplus_comments && nextc == '*'))
1015 goto scan_directive_token;
1019 if (CPP_PEDANTIC(pfile))
1020 cpp_pedwarn(pfile, "%s in preprocessing directive",
1021 c == '\f' ? "formfeed" : "vertical tab");
1027 scan_directive_token:
1029 cpp_get_token(pfile);
1035 CPP_NUL_TERMINATE(pfile);
1039 skip_rest_of_line(cpp_reader * pfile)
1041 long old = CPP_WRITTEN(pfile);
1043 copy_rest_of_line(pfile);
1044 CPP_SET_WRITTEN(pfile, old);
1047 /* Handle a possible # directive.
1048 * '#' has already been read. */
1051 handle_directive(cpp_reader * pfile)
1054 struct directive *kt;
1056 long after_ident = 0;
1057 unsigned char *ident, *line_end;
1058 long old_written = CPP_WRITTEN(pfile);
1060 cpp_skip_hspace(pfile);
1063 if (c >= '0' && c <= '9')
1065 /* Handle # followed by a line number. */
1066 if (CPP_PEDANTIC(pfile))
1067 cpp_pedwarn(pfile, "`#' followed by integer");
1068 do_line(pfile, NULL, NULL, NULL);
1069 goto done_a_directive;
1071 /* Now find the directive name. */
1072 CPP_PUTC(pfile, '#');
1073 parse_name(pfile, GETC());
1074 ident = pfile->token_buffer + old_written + 1;
1075 ident_length = CPP_PWRITTEN(pfile) - ident;
1076 if (ident_length == 0 && PEEKC() == '\n')
1078 /* A line of just `#' becomes blank. */
1079 goto done_a_directive;
1082 * Decode the keyword and call the appropriate expansion
1083 * routine, after moving the input pointer up to the next line.
1085 for (kt = directive_table;; kt++)
1087 if (kt->length <= 0)
1088 goto not_a_directive;
1089 if (kt->length == ident_length
1090 && !strncmp(kt->name, (const char *)ident, ident_length))
1094 if (!kt->command_reads_line)
1096 /* Nonzero means do not delete comments within the directive.
1097 * #define needs this when -traditional. */
1098 int comments = CPP_TRADITIONAL(pfile)
1099 && kt->traditional_comments;
1100 int save_put_out_comments =
1101 CPP_OPTIONS(pfile)->put_out_comments;
1103 CPP_OPTIONS(pfile)->put_out_comments = comments;
1104 after_ident = CPP_WRITTEN(pfile);
1105 copy_rest_of_line(pfile);
1106 CPP_OPTIONS(pfile)->put_out_comments = save_put_out_comments;
1108 /* For #pragma and #define, we may want to pass through the directive.
1109 * Other directives may create output, but we don't want the directive
1110 * itself out, so we pop it now. For example #include may write a #line
1111 * command (see comment in do_include), and conditionals may emit
1112 * #failed ... #endfailed stuff. But note that popping the buffer
1113 * means the parameters to kt->func may point after pfile->limit
1114 * so these parameters are invalid as soon as something gets appended
1115 * to the token_buffer. */
1117 line_end = CPP_PWRITTEN(pfile);
1118 if (!kt->pass_thru && kt->type != T_DEFINE)
1119 CPP_SET_WRITTEN(pfile, old_written);
1121 (*kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1123 || (kt->type == T_DEFINE
1124 && CPP_OPTIONS(pfile)->dump_macros == dump_definitions))
1126 /* Just leave the entire #define in the output stack. */
1128 else if (kt->type == T_DEFINE
1129 && CPP_OPTIONS(pfile)->dump_macros == dump_names)
1131 unsigned char *p = pfile->token_buffer + old_written + 7; /* Skip "#define". */
1133 SKIP_WHITE_SPACE(p);
1134 while (is_idchar[*p])
1137 CPP_PUTC(pfile, '\n');
1139 else if (kt->type == T_DEFINE)
1140 CPP_SET_WRITTEN(pfile, old_written);
1148 /* Pass a directive through to the output file.
1149 * BUF points to the contents of the directive, as a contiguous string.
1150 * LIMIT points to the first character past the end of the directive.
1151 * KEYWORD is the keyword-table entry for the directive. */
1154 pass_thru_directive(char *buf, char *limit, cpp_reader * pfile,
1155 struct directive *keyword)
1157 unsigned keyword_length = keyword->length;
1159 CPP_RESERVE(pfile, 1 + keyword_length + (limit - buf));
1160 CPP_PUTC_Q(pfile, '#');
1161 CPP_PUTS_Q(pfile, keyword->name, keyword_length);
1162 if (limit != buf && buf[0] != ' ')
1163 CPP_PUTC_Q(pfile, ' ');
1164 CPP_PUTS_Q(pfile, buf, limit - buf);
1167 /* The arglist structure is built by do_define to tell
1168 * collect_definition where the argument names begin. That
1169 * is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
1170 * would contain pointers to the strings x, y, and z.
1171 * Collect_definition would then build a DEFINITION node,
1172 * with reflist nodes pointing to the places x, y, and z had
1173 * appeared. So the arglist is just convenience data passed
1174 * between these two routines. It is not kept around after
1175 * the current #define has been processed and entered into the
1179 struct arglist *next;
1186 /* Read a replacement list for a macro with parameters.
1187 * Build the DEFINITION structure.
1188 * Reads characters of text starting at BUF until END.
1189 * ARGLIST specifies the formal parameters to look for
1190 * in the text of the definition; NARGS is the number of args
1191 * in that list, or -1 for a macro name that wants no argument list.
1192 * MACRONAME is the macro name itself (so we can avoid recursive expansion)
1193 * and NAMELEN is its length in characters.
1195 * Note that comments, backslash-newlines, and leading white space
1196 * have already been deleted from the argument. */
1199 collect_expansion(cpp_reader * pfile, unsigned char *buf, unsigned char *limit,
1200 int nargs, struct arglist *arglist)
1203 unsigned char *p, *lastp, *exp_p;
1204 struct reflist *endpat = NULL;
1206 /* Pointer to first nonspace after last ## seen. */
1207 unsigned char *concat = 0;
1209 /* Pointer to first nonspace after last single-# seen. */
1210 unsigned char *stringify = 0;
1212 int expected_delimiter = '\0';
1214 /* Scan thru the replacement list, ignoring comments and quoted
1215 * strings, picking up on the macro calls. It does a linear search
1216 * thru the arg list on every potential symbol. Profiling might say
1217 * that something smarter should happen. */
1222 /* Find the beginning of the trailing whitespace. */
1224 while (p < limit && is_space[limit[-1]])
1227 /* Allocate space for the text in the macro definition.
1228 * Leading and trailing whitespace chars need 2 bytes each.
1229 * Each other input char may or may not need 1 byte,
1230 * so this is an upper bound. The extra 5 are for invented
1231 * leading and trailing newline-marker and final null. */
1232 maxsize = (sizeof(DEFINITION) + (limit - p) + 5);
1233 /* Occurrences of '@' get doubled, so allocate extra space for them. */
1237 defn = (DEFINITION *) xcalloc(1, maxsize);
1239 defn->nargs = nargs;
1240 exp_p = defn->expansion = (unsigned char *)defn + sizeof(DEFINITION);
1245 /* Add one initial space escape-marker to prevent accidental
1246 * token-pasting (often removed by macroexpand). */
1250 if (limit - p >= 2 && p[0] == '#' && p[1] == '#')
1252 cpp_error(pfile, "`##' at start of macro definition");
1255 /* Process the main body of the definition. */
1258 int skipped_arg = 0;
1259 unsigned char c = *p++;
1263 if (!CPP_TRADITIONAL(pfile))
1269 if (expected_delimiter != '\0')
1271 if (c == expected_delimiter)
1272 expected_delimiter = '\0';
1275 expected_delimiter = c;
1279 if (p < limit && expected_delimiter)
1281 /* In a string, backslash goes through
1282 * and makes next char ordinary. */
1288 /* An '@' in a string or character constant stands for itself,
1289 * and does not need to be escaped. */
1290 if (!expected_delimiter)
1295 /* # is ordinary inside a string. */
1296 if (expected_delimiter)
1298 if (p < limit && *p == '#')
1300 /* ##: concatenate preceding and following tokens. */
1301 /* Take out the first #, discard preceding whitespace. */
1303 while (exp_p > lastp && is_hor_space[exp_p[-1]])
1305 /* Skip the second #. */
1307 /* Discard following whitespace. */
1308 SKIP_WHITE_SPACE(p);
1311 cpp_error(pfile, "`##' at end of macro definition");
1313 else if (nargs >= 0)
1315 /* Single #: stringify following argument ref.
1316 * Don't leave the # in the expansion. */
1318 SKIP_WHITE_SPACE(p);
1319 if (p == limit || !is_idstart[*p])
1321 "`#' operator is not followed by a macro argument name");
1330 /* In -traditional mode, recognize arguments inside strings and
1331 * and character constants, and ignore special properties of #.
1332 * Arguments inside strings are considered "stringified", but no
1333 * extra quote marks are supplied. */
1338 if (expected_delimiter != '\0')
1340 if (c == expected_delimiter)
1341 expected_delimiter = '\0';
1344 expected_delimiter = c;
1348 /* Backslash quotes delimiters and itself, but not macro args. */
1349 if (expected_delimiter != 0 && p < limit
1350 && (*p == expected_delimiter || *p == '\\'))
1358 if (expected_delimiter != '\0') /* No comments inside strings. */
1362 /* If we find a comment that wasn't removed by handle_directive,
1363 * this must be -traditional. So replace the comment with
1364 * nothing at all. */
1367 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1374 /* Handle the start of a symbol. */
1375 if (is_idchar[c] && nargs > 0)
1377 unsigned char *id_beg = p - 1;
1381 while (p != limit && is_idchar[*p])
1383 id_len = p - id_beg;
1387 struct arglist *arg;
1389 for (arg = arglist; arg != NULL; arg = arg->next)
1391 struct reflist *tpat;
1393 if (arg->name[0] == c
1394 && arg->length == id_len
1395 && strncmp((const char *)arg->name,
1396 (const char *)id_beg, id_len) == 0)
1398 if (expected_delimiter
1399 && CPP_OPTIONS(pfile)->warn_stringify)
1401 if (CPP_TRADITIONAL(pfile))
1404 "macro argument `%.*s' is stringified.",
1410 "macro arg `%.*s' would be stringified with -traditional.",
1414 /* If ANSI, don't actually substitute inside a string. */
1415 if (!CPP_TRADITIONAL(pfile) && expected_delimiter)
1417 /* make a pat node for this arg and append it to the end of
1421 xmalloc(sizeof(struct reflist));
1424 tpat->raw_before = concat == id_beg;
1425 tpat->raw_after = 0;
1426 tpat->rest_args = arg->rest_args;
1427 tpat->stringify = (CPP_TRADITIONAL(pfile)
1428 ? expected_delimiter != '\0'
1429 : stringify == id_beg);
1432 defn->pattern = tpat;
1434 endpat->next = tpat;
1437 tpat->argno = arg->argno;
1438 tpat->nchars = exp_p - lastp;
1440 unsigned char *p1 = p;
1442 SKIP_WHITE_SPACE(p1);
1443 if (p1 + 2 <= limit && p1[0] == '#'
1445 tpat->raw_after = 1;
1447 lastp = exp_p; /* place to start copying from next time */
1453 /* If this was not a macro arg, copy it into the expansion. */
1456 unsigned char *lim1 = p;
1461 if (stringify == id_beg)
1463 "`#' operator should be followed by a macro argument name");
1468 if (!CPP_TRADITIONAL(pfile) && expected_delimiter == 0)
1470 /* If ANSI, put in a "@ " marker to prevent token pasting.
1471 * But not if "inside a string" (which in ANSI mode
1472 * happens only for -D option). */
1478 defn->length = exp_p - defn->expansion;
1480 /* Crash now if we overrun the allocated size. */
1481 if (defn->length + 1 > maxsize)
1488 * special extension string that can be added to the last macro argument to
1489 * allow it to absorb the "rest" of the arguments when expanded. Ex:
1490 * #define wow(a, b...) process (b, a, b)
1491 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
1492 * { wow (one, two); } -> { process (two, one, two); }
1493 * if this "rest_arg" is used with the concat token '##' and if it is not
1494 * supplied then the token attached to with ## will not be outputted. Ex:
1495 * #define wow (a, b...) process (b ## , a, ## b)
1496 * { wow (1, 2); } -> { process (2, 1, 2); }
1497 * { wow (one); } -> { process (one); {
1499 static char rest_extension[] = "...";
1501 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
1503 /* Create a DEFINITION node from a #define directive. Arguments are
1504 * as for do_define. */
1506 create_definition(MACRODEF * mdef, unsigned char *buf, unsigned char *limit,
1507 cpp_reader * pfile, int predefinition)
1509 unsigned char *bp; /* temp ptr into input buffer */
1510 unsigned char *symname; /* remember where symbol name starts */
1511 int sym_length; /* and how long it is */
1515 CPP_BUFFER(pfile) ? CPP_BUFFER(pfile)->nominal_fname : "";
1517 int arglengths = 0; /* Accumulate lengths of arg names
1518 * plus number of args. */
1520 cpp_buf_line_and_col(CPP_BUFFER(pfile), &line, &col);
1524 while (is_hor_space[*bp])
1527 symname = bp; /* remember where it starts */
1529 sym_length = check_macro_name(pfile, bp, "macro");
1532 /* Lossage will occur if identifiers or control keywords are broken
1533 * across lines using backslash. This is not the right place to take
1538 struct arglist *arg_ptrs = NULL;
1541 bp++; /* skip '(' */
1542 SKIP_WHITE_SPACE(bp);
1544 /* Loop over macro argument names. */
1547 struct arglist *temp;
1549 temp = (struct arglist *)alloca(sizeof(struct arglist));
1551 temp->name = (char *)bp;
1552 temp->next = arg_ptrs;
1553 temp->argno = argno++;
1554 temp->rest_args = 0;
1558 cpp_pedwarn(pfile, "another parameter follows `%s'",
1561 if (!is_idstart[*bp])
1562 cpp_pedwarn(pfile, "invalid character in macro parameter name");
1564 /* Find the end of the arg name. */
1565 while (is_idchar[*bp])
1568 /* do we have a "special" rest-args extension here? */
1569 if ((unsigned)(limit - bp) > REST_EXTENSION_LENGTH &&
1570 strncmp(rest_extension, (const char *)bp,
1571 REST_EXTENSION_LENGTH) == 0)
1574 temp->rest_args = 1;
1578 temp->length = (char *)bp - temp->name;
1580 bp += REST_EXTENSION_LENGTH;
1581 arglengths += temp->length + 2;
1582 SKIP_WHITE_SPACE(bp);
1583 if (temp->length == 0 || (*bp != ',' && *bp != ')'))
1586 "badly punctuated parameter list in `#define'");
1592 SKIP_WHITE_SPACE(bp);
1596 cpp_error(pfile, "unterminated parameter list in `#define'");
1600 struct arglist *otemp;
1602 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1603 if (temp->length == otemp->length &&
1604 strncmp((const char *)temp->name,
1605 (const char *)otemp->name, temp->length) == 0)
1609 name = (char *)alloca(temp->length + 1);
1610 strncpy(name, (const char *)temp->name, temp->length);
1611 name[temp->length] = '\0';
1613 "duplicate argument name `%s' in `#define'",
1620 ++bp; /* skip paren */
1621 SKIP_WHITE_SPACE(bp);
1622 /* now everything from bp before limit is the definition. */
1623 defn = collect_expansion(pfile, bp, limit, argno, arg_ptrs);
1624 defn->rest_args = rest_args;
1626 /* Now set defn->args.argnames to the result of concatenating
1627 * the argument names in reverse order
1628 * with comma-space between them. */
1629 defn->args.argnames = (unsigned char *)xmalloc(arglengths + 1);
1631 struct arglist *temp;
1634 for (temp = arg_ptrs; temp; temp = temp->next)
1636 memcpy(&defn->args.argnames[i], temp->name, temp->length);
1638 if (temp->next != 0)
1640 defn->args.argnames[i++] = ',';
1641 defn->args.argnames[i++] = ' ';
1644 defn->args.argnames[i] = 0;
1649 /* Simple expansion or empty definition. */
1653 if (is_hor_space[*bp])
1656 SKIP_WHITE_SPACE(bp);
1690 "missing white space after `#define %.*s'",
1691 sym_length, symname);
1696 "missing white space after `#define %.*s'",
1697 sym_length, symname);
1702 /* now everything from bp before limit is the definition. */
1703 defn = collect_expansion(pfile, bp, limit, -1, NULL);
1704 defn->args.argnames = (unsigned char *)"";
1710 /* OP is null if this is a predefinition */
1711 defn->predefined = predefinition;
1713 mdef->symnam = (char *)symname;
1714 mdef->symlen = sym_length;
1722 /* Check a purported macro name SYMNAME, and yield its length.
1723 * USAGE is the kind of name this is intended for. */
1726 check_macro_name(cpp_reader * pfile, unsigned char *symname, const char *usage)
1731 for (p = symname; is_idchar[*p]; p++)
1733 sym_length = p - symname;
1734 if (sym_length == 0)
1736 cpp_error(pfile, "invalid %s name", usage);
1738 else if (!is_idstart[*symname])
1740 unsigned char *msg; /* what pain... */
1742 msg = (unsigned char *)alloca(sym_length + 1);
1743 memcpy(msg, symname, sym_length);
1744 msg[sym_length] = 0;
1745 cpp_error(pfile, "invalid %s name `%s'", usage, msg);
1749 if (!strncmp((const char *)symname, "defined", 7) && sym_length == 7)
1750 cpp_error(pfile, "invalid %s name `defined'", usage);
1756 * return zero if two DEFINITIONs are isomorphic
1759 compare_defs(DEFINITION * d1, DEFINITION * d2)
1761 struct reflist *a1, *a2;
1762 unsigned char *p1 = d1->expansion;
1763 unsigned char *p2 = d2->expansion;
1766 if (d1->nargs != d2->nargs)
1768 if (strcmp((char *)d1->args.argnames, (char *)d2->args.argnames))
1770 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1771 a1 = a1->next, a2 = a2->next)
1774 ((a1->nchars == a2->nchars
1775 && !strncmp((const char *)p1, (const char *)p2, a1->nchars))
1776 || !comp_def_part(first, p1, a1->nchars, p2, a2->nchars, 0))
1777 || a1->argno != a2->argno || a1->stringify != a2->stringify
1778 || a1->raw_before != a2->raw_before
1779 || a1->raw_after != a2->raw_after)
1787 if (comp_def_part(first, p1, d1->length - (p1 - d1->expansion),
1788 p2, d2->length - (p2 - d2->expansion), 1))
1793 /* Return 1 if two parts of two macro definitions are effectively different.
1794 * One of the parts starts at BEG1 and has LEN1 chars;
1795 * the other has LEN2 chars at BEG2.
1796 * Any sequence of whitespace matches any other sequence of whitespace.
1797 * FIRST means these parts are the first of a macro definition;
1798 * so ignore leading whitespace entirely.
1799 * LAST means these parts are the last of a macro definition;
1800 * so ignore trailing whitespace entirely. */
1803 comp_def_part(int first, unsigned char *beg1, int len1,
1804 unsigned char *beg2, int len2, int last)
1806 unsigned char *end1 = beg1 + len1;
1807 unsigned char *end2 = beg2 + len2;
1811 while (beg1 != end1 && is_space[*beg1])
1813 while (beg2 != end2 && is_space[*beg2])
1818 while (beg1 != end1 && is_space[end1[-1]])
1820 while (beg2 != end2 && is_space[end2[-1]])
1823 while (beg1 != end1 && beg2 != end2)
1825 if (is_space[*beg1] && is_space[*beg2])
1827 while (beg1 != end1 && is_space[*beg1])
1829 while (beg2 != end2 && is_space[*beg2])
1832 else if (*beg1 == *beg2)
1840 return (beg1 != end1) || (beg2 != end2);
1843 /* Process a #define command.
1844 * BUF points to the contents of the #define command, as a contiguous string.
1845 * LIMIT points to the first character past the end of the definition.
1846 * KEYWORD is the keyword-table entry for #define,
1847 * or NULL for a "predefined" macro. */
1850 do_define(cpp_reader * pfile, struct directive *keyword,
1851 unsigned char *buf, unsigned char *limit)
1857 create_definition(&mdef, buf, limit, pfile, keyword == NULL);
1861 hashcode = hashf(mdef.symnam, mdef.symlen, HASHSIZE);
1863 if ((hp = cpp_lookup(mdef.symnam, mdef.symlen, hashcode)) != NULL)
1867 /* Redefining a precompiled key is ok. */
1868 if (hp->type == T_PCSTRING)
1870 /* Redefining a macro is ok if the definitions are the same. */
1871 else if (hp->type == T_MACRO)
1872 ok = !compare_defs(mdef.defn, hp->value.defn);
1873 /* Redefining a constant is ok with -D. */
1874 else if (hp->type == T_CONST)
1875 ok = !CPP_OPTIONS(pfile)->done_initializing;
1876 /* Print the warning if it's not ok. */
1879 char *msg; /* what pain... */
1881 /* If we are passing through #define and #undef directives, do
1882 * that for this re-definition now. */
1883 if (CPP_OPTIONS(pfile)->debug_output && keyword)
1884 pass_thru_directive((char *)buf, (char *)limit, pfile, keyword);
1886 msg = (char *)alloca(mdef.symlen + 22);
1888 memcpy(msg + 1, mdef.symnam, mdef.symlen);
1889 strcpy((msg + mdef.symlen + 1), "' redefined");
1890 cpp_pedwarn(pfile, msg);
1891 if (hp->type == T_MACRO)
1892 cpp_pedwarn_with_file_and_line(pfile, hp->value.defn->file,
1893 hp->value.defn->line,
1894 "this is the location of the previous definition",
1897 /* Replace the old definition. */
1899 hp->value.defn = mdef.defn;
1903 /* If we are passing through #define and #undef directives, do
1904 * that for this new definition now. */
1905 if (CPP_OPTIONS(pfile)->debug_output && keyword)
1906 pass_thru_directive((char *)buf, (char *)limit, pfile, keyword);
1907 install(mdef.symnam, mdef.symlen, T_MACRO, 0,
1908 (char *)mdef.defn, hashcode);
1914 /* This structure represents one parsed argument in a macro call.
1915 * `raw' points to the argument text as written (`raw_length' is its length).
1916 * `expanded' points to the argument's macro-expansion
1917 * (its length is `expand_length').
1918 * `stringified_length' is the length the argument would have
1920 * `use_count' is the number of times this macro arg is substituted
1921 * into the macro. If the actual use count exceeds 10,
1922 * the value stored is 10. */
1924 /* raw and expanded are relative to ARG_BASE */
1925 #define ARG_BASE ((pfile)->token_buffer)
1928 /* Strings relative to pfile->token_buffer */
1929 long raw, expanded, stringified;
1930 int raw_length, expand_length;
1931 int stringified_length;
1937 cpp_push_buffer(cpp_reader * pfile, unsigned char *buffer, long length)
1939 #ifdef STATIC_BUFFERS
1940 cpp_buffer *buf = CPP_BUFFER(pfile);
1942 if (buf == pfile->buffer_stack)
1943 cpp_fatal("macro or `#include' recursion too deep");
1945 memset((char *)buf, 0, sizeof(cpp_buffer));
1946 CPP_BUFFER(pfile) = buf;
1948 cpp_buffer *buf = (cpp_buffer *) xmalloc(sizeof(cpp_buffer));
1950 memset((char *)buf, 0, sizeof(cpp_buffer));
1951 CPP_PREV_BUFFER(buf) = CPP_BUFFER(pfile);
1952 CPP_BUFFER(pfile) = buf;
1954 buf->if_stack = pfile->if_stack;
1955 buf->cleanup = null_cleanup;
1956 buf->underflow = null_underflow;
1957 buf->buf = buf->cur = buffer;
1958 buf->alimit = buf->rlimit = buffer + length;
1964 cpp_pop_buffer(cpp_reader * pfile)
1966 cpp_buffer *buf = CPP_BUFFER(pfile);
1968 #ifdef STATIC_BUFFERS
1969 (*buf->cleanup) (buf, pfile);
1970 return ++CPP_BUFFER(pfile);
1972 cpp_buffer *next_buf = CPP_PREV_BUFFER(buf);
1974 (*buf->cleanup) (buf, pfile);
1975 CPP_BUFFER(pfile) = next_buf;
1981 /* Scan until CPP_BUFFER (PFILE) is exhausted into PFILE->token_buffer.
1982 * Pop the buffer when done. */
1985 cpp_scan_buffer(cpp_reader * pfile)
1987 cpp_buffer *buffer = CPP_BUFFER(pfile);
1991 enum cpp_token token = cpp_get_token(pfile);
1993 if (token == CPP_EOF) /* Should not happen ... */
1995 if (token == CPP_POP && CPP_BUFFER(pfile) == buffer)
1997 cpp_pop_buffer(pfile);
2004 * Rescan a string (which may have escape marks) into pfile's buffer.
2005 * Place the result in pfile->token_buffer.
2007 * The input is copied before it is scanned, so it is safe to pass
2008 * it something from the token_buffer that will get overwritten
2009 * (because it follows CPP_WRITTEN). This is used by do_include.
2013 cpp_expand_to_buffer(cpp_reader * pfile, unsigned char *buf, int length)
2016 unsigned char *limit = buf + length;
2017 unsigned char *buf1;
2022 /* Set up the input on the input stack. */
2024 buf1 = (unsigned char *)alloca(length + 1);
2026 unsigned char *p1 = buf;
2027 unsigned char *p2 = buf1;
2034 ip = cpp_push_buffer(pfile, buf1, length);
2035 ip->has_escapes = 1;
2037 /* Scan the input, create the output. */
2038 cpp_scan_buffer(pfile);
2040 CPP_NUL_TERMINATE(pfile);
2044 adjust_position(unsigned char *buf, unsigned char *limit, long *linep,
2049 unsigned char ch = *buf++;
2052 (*linep)++, (*colp) = 1;
2058 /* Move line_base forward, updating lineno and colno. */
2061 update_position(cpp_buffer * pbuf)
2063 unsigned char *old_pos = pbuf->buf + pbuf->line_base;
2064 unsigned char *new_pos = pbuf->cur;
2065 struct parse_marker *mark;
2067 for (mark = pbuf->marks; mark != NULL; mark = mark->next)
2069 if (pbuf->buf + mark->position < new_pos)
2070 new_pos = pbuf->buf + mark->position;
2072 pbuf->line_base += new_pos - old_pos;
2073 adjust_position(old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2077 cpp_buf_line_and_col(cpp_buffer * pbuf, long *linep, long *colp)
2085 *linep = pbuf->lineno;
2086 *colp = pbuf->colno;
2087 adjust_position(pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2096 /* Return the cpp_buffer that corresponds to a file (not a macro). */
2099 cpp_file_buffer(cpp_reader * pfile)
2101 cpp_buffer *ip = CPP_BUFFER(pfile);
2103 for (; ip != CPP_NULL_BUFFER(pfile); ip = CPP_PREV_BUFFER(ip))
2104 if (ip->fname != NULL)
2110 count_newlines(unsigned char *buf, unsigned char *limit)
2116 unsigned char ch = *buf++;
2125 * write out a #line command, for instance, after an #include file.
2126 * If CONDITIONAL is nonzero, we can omit the #line if it would
2127 * appear to be a no-op, and we can output a few newlines instead
2128 * if we want to increase the line number by a small amount.
2129 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2133 output_line_command(cpp_reader * pfile, int conditional,
2134 enum file_change_code file_change)
2137 cpp_buffer *ip = CPP_BUFFER(pfile);
2139 if (CPP_OPTIONS(pfile)->no_line_commands
2140 || ip->fname == NULL || CPP_OPTIONS(pfile)->no_output)
2144 update_position(ip);
2145 line = CPP_BUFFER(pfile)->lineno;
2146 col = CPP_BUFFER(pfile)->colno;
2147 adjust_position(CPP_LINE_BASE(ip), ip->cur, &line, &col);
2151 if (line == pfile->lineno)
2154 /* If the inherited line number is a little too small,
2155 * output some newlines instead of a #line command. */
2156 if (line > pfile->lineno && line < pfile->lineno + 8)
2158 CPP_RESERVE(pfile, 20);
2159 while (line > pfile->lineno)
2161 CPP_PUTC_Q(pfile, '\n');
2168 CPP_RESERVE(pfile, 4 * strlen(ip->nominal_fname) + 50);
2170 #ifdef OUTPUT_LINE_COMMANDS
2171 static char sharp_line[] = "#line ";
2174 static char sharp_line[] = "# ";
2177 CPP_PUTS_Q(pfile, sharp_line, sizeof(sharp_line) - 1);
2180 sprintf((char *)CPP_PWRITTEN(pfile), "%d ", (int)line);
2181 CPP_ADJUST_WRITTEN(pfile, strlen((char *)CPP_PWRITTEN(pfile)));
2183 quote_string(pfile, ip->nominal_fname);
2184 if (file_change != same_file)
2186 CPP_PUTC_Q(pfile, ' ');
2187 CPP_PUTC_Q(pfile, file_change == enter_file ? '1' : '2');
2189 /* Tell cc1 if following text comes from a system header file. */
2190 if (ip->system_header_p)
2192 CPP_PUTC_Q(pfile, ' ');
2193 CPP_PUTC_Q(pfile, '3');
2195 #ifndef NO_IMPLICIT_EXTERN_C
2196 /* Tell cc1plus if following text should be treated as C. */
2197 if (ip->system_header_p == 2 && CPP_OPTIONS(pfile)->cplusplus)
2199 CPP_PUTC_Q(pfile, ' ');
2200 CPP_PUTC_Q(pfile, '4');
2203 CPP_PUTC_Q(pfile, '\n');
2204 pfile->lineno = line;
2208 * Parse a macro argument and append the info on PFILE's token_buffer.
2209 * REST_ARGS means to absorb the rest of the args.
2210 * Return nonzero to indicate a syntax error.
2213 static enum cpp_token
2214 macarg(cpp_reader * pfile, int rest_args)
2217 enum cpp_token token;
2218 char save_put_out_comments =
2219 CPP_OPTIONS(pfile)->put_out_comments;
2221 CPP_OPTIONS(pfile)->put_out_comments = 0;
2224 /* Try to parse as much of the argument as exists at this
2225 * input stack level. */
2226 pfile->no_macro_expand++;
2229 token = cpp_get_token(pfile);
2235 /* If we've hit end of file, it's an error (reported by caller).
2236 * Ditto if it's the end of cpp_expand_to_buffer text.
2237 * If we've hit end of macro, just continue. */
2238 if (!CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
2249 /* if we've returned to lowest level and
2250 * we aren't absorbing all args */
2251 if (paren == 0 && rest_args == 0)
2255 /* Remove ',' or ')' from argument buffer. */
2256 CPP_ADJUST_WRITTEN(pfile, -1);
2263 CPP_OPTIONS(pfile)->put_out_comments = save_put_out_comments;
2264 pfile->no_macro_expand--;
2269 /* Turn newlines to spaces in the string of length LENGTH at START,
2270 * except inside of string constants.
2271 * The string is copied into itself with its beginning staying fixed. */
2274 change_newlines(unsigned char *start, int length)
2278 unsigned char *limit;
2282 limit = start + length;
2287 *obp++ = c = *ibp++;
2293 /* Notice and skip strings, so that we don't delete newlines in them. */
2299 *obp++ = c = *ibp++;
2302 if (c == '\n' && quotec == '\'')
2314 timestamp(cpp_reader * pfile)
2316 if (!pfile->timebuf)
2318 time_t t = time((time_t *) 0);
2320 pfile->timebuf = localtime(&t);
2322 return pfile->timebuf;
2325 static const char *monthnames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2326 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2330 * expand things like __FILE__. Place the expansion into the output
2331 * buffer *without* rescanning.
2335 special_symbol(HASHNODE * hp, cpp_reader * pfile)
2341 cpp_buffer *ip = NULL;
2344 int paren = 0; /* For special `defined' keyword */
2346 for (ip = CPP_BUFFER(pfile);; ip = CPP_PREV_BUFFER(ip))
2350 cpp_error(pfile, "cccp error: not in any file?!");
2351 return; /* the show must go on */
2353 if (ip->fname != NULL)
2364 if (hp->type == T_BASE_FILE)
2366 while (CPP_PREV_BUFFER(ip))
2367 ip = CPP_PREV_BUFFER(ip);
2369 string = ip->nominal_fname;
2373 CPP_RESERVE(pfile, 3 + 4 * strlen(string));
2374 quote_string(pfile, string);
2378 case T_INCLUDE_LEVEL:
2380 for (ip = CPP_BUFFER(pfile); ip != NULL; ip = CPP_PREV_BUFFER(ip))
2381 if (ip->fname != NULL)
2384 bufx = (char *)alloca(8); /* Eight bytes ought to be more than enough */
2385 sprintf(bufx, "%d", true_indepth - 1);
2390 bufx = (char *)alloca(3 + strlen(version_string));
2391 sprintf(bufx, "\"%s\"", version_string);
2395 #ifndef NO_BUILTIN_SIZE_TYPE
2401 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2402 case T_PTRDIFF_TYPE:
2408 buf = CPP_WCHAR_TYPE(pfile);
2411 case T_USER_LABEL_PREFIX_TYPE:
2412 buf = USER_LABEL_PREFIX;
2415 case T_REGISTER_PREFIX_TYPE:
2416 buf = REGISTER_PREFIX;
2420 bufx = (char *)alloca(4 * sizeof(int));
2421 sprintf(bufx, "%d", hp->value.ival);
2427 long line = ip->lineno;
2428 long col = ip->colno;
2430 adjust_position(CPP_LINE_BASE(ip), ip->cur, &line, &col);
2432 bufx = (char *)alloca(10);
2433 sprintf(bufx, "%d", (int)line);
2440 bufx = (char *)alloca(20);
2441 timebuf = timestamp(pfile);
2442 if (hp->type == T_DATE)
2443 sprintf(bufx, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2444 timebuf->tm_mday, timebuf->tm_year + 1900);
2446 sprintf(bufx, "\"%02d:%02d:%02d\"", timebuf->tm_hour,
2447 timebuf->tm_min, timebuf->tm_sec);
2451 case T_SPEC_DEFINED:
2452 buf = " 0 "; /* Assume symbol is not defined */
2453 ip = CPP_BUFFER(pfile);
2454 SKIP_WHITE_SPACE(ip->cur);
2455 if (*ip->cur == '(')
2458 ip->cur++; /* Skip over the paren */
2459 SKIP_WHITE_SPACE(ip->cur);
2461 if (!is_idstart[*ip->cur])
2463 if ((hp = cpp_lookup((const char *)ip->cur, -1, -1)))
2467 while (is_idchar[*ip->cur])
2469 SKIP_WHITE_SPACE(ip->cur);
2472 if (*ip->cur != ')')
2480 cpp_error(pfile, "`defined' without an identifier");
2484 cpp_error(pfile, "cccp error: invalid special hash type"); /* time for gdb */
2488 CPP_RESERVE(pfile, len + 1);
2489 CPP_PUTS_Q(pfile, buf, len);
2490 CPP_NUL_TERMINATE_Q(pfile);
2495 /* Initialize the built-in macros. */
2498 initialize_builtins(cpp_reader * pfile)
2500 install("__LINE__", -1, T_SPECLINE, 0, 0, -1);
2501 install("__DATE__", -1, T_DATE, 0, 0, -1);
2502 install("__FILE__", -1, T_FILE, 0, 0, -1);
2503 install("__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
2504 install("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
2505 install("__VERSION__", -1, T_VERSION, 0, 0, -1);
2506 #ifndef NO_BUILTIN_SIZE_TYPE
2507 install("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
2509 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2510 install("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
2512 install("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
2513 install("__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
2514 install("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
2515 install("__TIME__", -1, T_TIME, 0, 0, -1);
2516 if (!CPP_TRADITIONAL(pfile))
2517 install("__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
2518 if (CPP_OPTIONS(pfile)->objc)
2519 install("__OBJC__", -1, T_CONST, 1, 0, -1);
2520 /* This is supplied using a -D by the compiler driver
2521 * so that it is present only when truly compiling with GNU C. */
2522 /* install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
2524 if (CPP_OPTIONS(pfile)->debug_output)
2526 char directive[2048];
2527 struct directive *dp = &directive_table[0];
2528 struct tm *timebuf = timestamp(pfile);
2529 cpp_buffer *pbuffer = CPP_BUFFER(pfile);
2531 while (CPP_PREV_BUFFER(pbuffer))
2532 pbuffer = CPP_PREV_BUFFER(pbuffer);
2533 sprintf(directive, " __BASE_FILE__ \"%s\"\n", pbuffer->nominal_fname);
2534 output_line_command(pfile, 0, same_file);
2535 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2538 sprintf(directive, " __VERSION__ \"%s\"\n", version_string);
2539 output_line_command(pfile, 0, same_file);
2540 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2543 #ifndef NO_BUILTIN_SIZE_TYPE
2544 sprintf(directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
2545 output_line_command(pfile, 0, same_file);
2546 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2550 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2551 sprintf(directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
2552 output_line_command(pfile, 0, same_file);
2553 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2557 sprintf(directive, " __WCHAR_TYPE__ %s\n", CPP_WCHAR_TYPE(pfile));
2558 output_line_command(pfile, 0, same_file);
2559 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2562 sprintf(directive, " __DATE__ \"%s %2d %4d\"\n",
2563 monthnames[timebuf->tm_mon],
2564 timebuf->tm_mday, timebuf->tm_year + 1900);
2565 output_line_command(pfile, 0, same_file);
2566 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2569 sprintf(directive, " __TIME__ \"%02d:%02d:%02d\"\n",
2570 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
2571 output_line_command(pfile, 0, same_file);
2572 pass_thru_directive(directive, &directive[strlen(directive)], pfile,
2575 if (!CPP_TRADITIONAL(pfile))
2577 sprintf(directive, " __STDC__ 1");
2578 output_line_command(pfile, 0, same_file);
2579 pass_thru_directive(directive, &directive[strlen(directive)],
2582 if (CPP_OPTIONS(pfile)->objc)
2584 sprintf(directive, " __OBJC__ 1");
2585 output_line_command(pfile, 0, same_file);
2586 pass_thru_directive(directive, &directive[strlen(directive)],
2592 /* Return 1 iff a token ending in C1 followed directly by a token C2
2593 * could cause mis-tokenization. */
2596 unsafe_chars(int c1, int c2)
2602 if (c2 == c1 || c2 == '=')
2618 if (c2 == '-' || c2 == '+')
2619 return 1; /* could extend a pre-processing number */
2622 if (c2 == '\'' || c2 == '\"')
2623 return 1; /* Could turn into L"xxx" or L'xxx'. */
2676 /* We're in the middle of either a name or a pre-processing number. */
2677 return (is_idchar[c2] || c2 == '.');
2690 return (c2 == c1 || c2 == '=');
2695 /* Expand a macro call.
2696 * HP points to the symbol that is the macro being called.
2697 * Put the result of expansion onto the input stack
2698 * so that subsequent input by our caller will use it.
2700 * If macro wants arguments, caller has already verified that
2701 * an argument list follows; arguments come from the input stack. */
2704 macroexpand(cpp_reader * pfile, HASHNODE * hp)
2707 DEFINITION *defn = hp->value.defn;
2708 unsigned char *xbuf;
2709 long start_line, start_column;
2711 struct argdata *args;
2712 long old_written = CPP_WRITTEN(pfile);
2714 int rest_args, rest_zero;
2717 pfile->output_escapes++;
2718 cpp_buf_line_and_col(cpp_file_buffer(pfile), &start_line, &start_column);
2722 nargs = defn->nargs;
2726 enum cpp_token token;
2730 args = (struct argdata *)alloca((nargs + 1) * sizeof(struct argdata));
2732 for (i = 0; i < nargs; i++)
2734 args[i].raw = args[i].expanded = 0;
2735 args[i].raw_length = 0;
2736 args[i].expand_length = args[i].stringified_length = -1;
2737 args[i].use_count = 0;
2740 /* Parse all the macro args that are supplied. I counts them.
2741 * The first NARGS args are stored in ARGS.
2742 * The rest are discarded. If rest_args is set then we assume
2743 * macarg absorbed the rest of the args. */
2747 FORWARD(1); /* Discard the open-parenthesis before the first arg. */
2752 if (i < nargs || (nargs == 0 && i == 0))
2754 /* if we are working on last arg which absorbs rest of args... */
2755 if (i == nargs - 1 && defn->rest_args)
2757 args[i].raw = CPP_WRITTEN(pfile);
2758 token = macarg(pfile, rest_args);
2759 args[i].raw_length = CPP_WRITTEN(pfile) - args[i].raw;
2760 args[i].newlines = 0; /* FIXME */
2763 token = macarg(pfile, 0);
2764 if (token == CPP_EOF || token == CPP_POP)
2766 cpp_error_with_line(pfile, start_line, start_column,
2767 "unterminated macro call");
2772 while (token == CPP_COMMA);
2774 /* If we got one arg but it was just whitespace, call that 0 args. */
2777 unsigned char *bp = ARG_BASE + args[0].raw;
2778 unsigned char *lim = bp + args[0].raw_length;
2780 /* cpp.texi says for foo ( ) we provide one argument.
2781 * However, if foo wants just 0 arguments, treat this as 0. */
2783 while (bp != lim && is_space[*bp])
2788 /* Don't output an error message if we have already output one for
2789 * a parse error above. */
2790 if (nargs == 0 && i > 0)
2792 cpp_error(pfile, "arguments given to macro `%s'", hp->name);
2796 /* traditional C allows foo() if foo wants one argument. */
2797 if (nargs == 1 && i == 0 && CPP_TRADITIONAL(pfile));
2798 /* the rest args token is allowed to absorb 0 tokens */
2799 else if (i == nargs - 1 && defn->rest_args)
2802 cpp_error(pfile, "macro `%s' used without args", hp->name);
2804 cpp_error(pfile, "macro `%s' used with just one arg", hp->name);
2806 cpp_error(pfile, "macro `%s' used with only %d args",
2812 "macro `%s' used with too many (%d) args", hp->name, i);
2815 /* If macro wants zero args, we parsed the arglist for checking only.
2816 * Read directly from the macro definition. */
2819 xbuf = defn->expansion;
2820 xbuf_len = defn->length;
2824 unsigned char *exp = defn->expansion;
2825 int offset; /* offset in expansion,
2826 * copied a piece at a time */
2827 int totlen; /* total amount of exp buffer filled so far */
2829 struct reflist *ap, *last_ap;
2831 /* Macro really takes args. Compute the expansion of this call. */
2833 /* Compute length in characters of the macro's expansion.
2834 * Also count number of times each arg is used. */
2835 xbuf_len = defn->length;
2836 for (ap = defn->pattern; ap != NULL; ap = ap->next)
2840 struct argdata *arg = &args[ap->argno];
2842 /* Stringify it it hasn't already been */
2843 if (arg->stringified_length < 0)
2845 int arglen = arg->raw_length;
2850 /* Initially need_space is -1. Otherwise, 1 means the
2851 * previous character was a space, but we suppressed it;
2852 * 0 means the previous character was a non-space. */
2853 int need_space = -1;
2856 arg->stringified = CPP_WRITTEN(pfile);
2857 if (!CPP_TRADITIONAL(pfile))
2858 CPP_PUTC(pfile, '\"'); /* insert beginning quote */
2859 for (; i < arglen; i++)
2861 c = (ARG_BASE + arg->raw)[i];
2865 /* Internal sequences of whitespace are replaced by
2866 * one space except within an string or char token. */
2869 if (CPP_WRITTEN(pfile) > arg->stringified
2870 && (CPP_PWRITTEN(pfile))[-1] == '@')
2872 /* "@ " escape markers are removed */
2873 CPP_ADJUST_WRITTEN(pfile, -1);
2876 if (need_space == 0)
2880 else if (need_space > 0)
2881 CPP_PUTC(pfile, ' ');
2895 else if (c == '\"' || c == '\'')
2899 /* Escape these chars */
2900 if (c == '\"' || (in_string && c == '\\'))
2901 CPP_PUTC(pfile, '\\');
2906 CPP_RESERVE(pfile, 4);
2907 sprintf((char *)CPP_PWRITTEN(pfile), "\\%03o",
2909 CPP_ADJUST_WRITTEN(pfile, 4);
2912 if (!CPP_TRADITIONAL(pfile))
2913 CPP_PUTC(pfile, '\"'); /* insert ending quote */
2914 arg->stringified_length
2915 = CPP_WRITTEN(pfile) - arg->stringified;
2917 xbuf_len += args[ap->argno].stringified_length;
2919 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL(pfile))
2920 /* Add 4 for two newline-space markers to prevent
2921 * token concatenation. */
2922 xbuf_len += args[ap->argno].raw_length + 4;
2925 /* We have an ordinary (expanded) occurrence of the arg.
2926 * So compute its expansion, if we have not already. */
2927 if (args[ap->argno].expand_length < 0)
2929 args[ap->argno].expanded = CPP_WRITTEN(pfile);
2930 cpp_expand_to_buffer(pfile,
2931 ARG_BASE + args[ap->argno].raw,
2932 args[ap->argno].raw_length);
2934 args[ap->argno].expand_length
2935 = CPP_WRITTEN(pfile) - args[ap->argno].expanded;
2937 /* Add 4 for two newline-space markers to prevent
2938 * token concatenation. */
2939 xbuf_len += args[ap->argno].expand_length + 4;
2941 if (args[ap->argno].use_count < 10)
2942 args[ap->argno].use_count++;
2945 xbuf = (unsigned char *)xmalloc(xbuf_len + 1);
2947 /* Generate in XBUF the complete expansion
2948 * with arguments substituted in.
2949 * TOTLEN is the total size generated so far.
2950 * OFFSET is the index in the definition
2951 * of where we are copying from. */
2952 offset = totlen = 0;
2953 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
2954 last_ap = ap, ap = ap->next)
2956 struct argdata *arg = &args[ap->argno];
2957 int count_before = totlen;
2959 /* Add chars to XBUF. */
2960 for (i = 0; i < ap->nchars; i++, offset++)
2961 xbuf[totlen++] = exp[offset];
2963 /* If followed by an empty rest arg with concatenation,
2964 * delete the last run of nonwhite chars. */
2965 if (rest_zero && totlen > count_before
2966 && ((ap->rest_args && ap->raw_before)
2967 || (last_ap != NULL && last_ap->rest_args
2968 && last_ap->raw_after)))
2970 /* Delete final whitespace. */
2971 while (totlen > count_before && is_space[xbuf[totlen - 1]])
2974 /* Delete the nonwhites before them. */
2975 while (totlen > count_before && !is_space[xbuf[totlen - 1]])
2978 if (ap->stringify != 0)
2980 memcpy(xbuf + totlen, ARG_BASE + arg->stringified,
2981 arg->stringified_length);
2982 totlen += arg->stringified_length;
2984 else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL(pfile))
2986 unsigned char *p1 = ARG_BASE + arg->raw;
2987 unsigned char *l1 = p1 + arg->raw_length;
2991 while (p1 != l1 && is_space[*p1])
2993 while (p1 != l1 && is_idchar[*p1])
2994 xbuf[totlen++] = *p1++;
2998 /* Arg is concatenated after: delete trailing whitespace,
2999 * whitespace markers, and no-reexpansion markers. */
3002 if (is_space[l1[-1]])
3004 else if (l1[-1] == '-')
3006 unsigned char *p2 = l1 - 1;
3008 /* If a `-' is preceded by an odd number of newlines then it
3009 * and the last newline are a no-reexpansion marker. */
3010 while (p2 != p1 && p2[-1] == '\n')
3012 if ((l1 - 1 - p2) & 1)
3023 memcpy(xbuf + totlen, p1, l1 - p1);
3028 unsigned char *expanded = ARG_BASE + arg->expanded;
3030 if (!ap->raw_before && totlen > 0 && arg->expand_length
3031 && !CPP_TRADITIONAL(pfile)
3032 && unsafe_chars(xbuf[totlen - 1], expanded[0]))
3034 xbuf[totlen++] = '@';
3035 xbuf[totlen++] = ' ';
3037 memcpy(xbuf + totlen, expanded, arg->expand_length);
3038 totlen += arg->expand_length;
3040 if (!ap->raw_after && totlen > 0 && offset < defn->length
3041 && !CPP_TRADITIONAL(pfile)
3042 && unsafe_chars(xbuf[totlen - 1], exp[offset]))
3044 xbuf[totlen++] = '@';
3045 xbuf[totlen++] = ' ';
3047 /* If a macro argument with newlines is used multiple times,
3048 * then only expand the newlines once. This avoids creating
3049 * output lines which don't correspond to any input line,
3050 * which confuses gdb and gcov. */
3051 if (arg->use_count > 1 && arg->newlines > 0)
3053 /* Don't bother doing change_newlines for subsequent
3057 = change_newlines(expanded, arg->expand_length);
3061 if (totlen > xbuf_len)
3065 /* if there is anything left of the definition
3066 * after handling the arg list, copy that in too. */
3068 for (i = offset; i < defn->length; i++)
3070 /* if we've reached the end of the macro */
3073 if (!(rest_zero && last_ap != NULL && last_ap->rest_args
3074 && last_ap->raw_after))
3075 xbuf[totlen++] = exp[i];
3083 pfile->output_escapes--;
3085 /* Now put the expansion on the input stack
3086 * so our caller will commence reading from it. */
3087 push_macro_expansion(pfile, xbuf, xbuf_len, hp);
3088 CPP_BUFFER(pfile)->has_escapes = 1;
3090 /* Pop the space we've used in the token_buffer for argument expansion. */
3091 CPP_SET_WRITTEN(pfile, old_written);
3093 /* Recursive macro use sometimes works traditionally.
3094 * #define foo(x,y) bar (x (y,0), y)
3097 if (!CPP_TRADITIONAL(pfile))
3098 hp->type = T_DISABLED;
3102 push_macro_expansion(cpp_reader * pfile, unsigned char *xbuf, int xbuf_len,
3105 cpp_buffer *mbuf = cpp_push_buffer(pfile, xbuf, xbuf_len);
3107 mbuf->cleanup = macro_cleanup;
3110 /* The first chars of the expansion should be a "@ " added by
3111 * collect_expansion. This is to prevent accidental token-pasting
3112 * between the text preceding the macro invocation, and the macro
3115 * We would like to avoid adding unneeded spaces (for the sake of
3116 * tools that use cpp, such as imake). In some common cases we can
3117 * tell that it is safe to omit the space.
3119 * The character before the macro invocation cannot have been an
3120 * idchar (or else it would have been pasted with the idchars of
3121 * the macro name). Therefore, if the first non-space character
3122 * of the expansion is an idchar, we do not need the extra space
3123 * to prevent token pasting.
3125 * Also, we don't need the extra space if the first char is '(',
3126 * or some other (less common) characters. */
3128 if (xbuf[0] == '@' && xbuf[1] == ' '
3129 && (is_idchar[xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3130 || xbuf[2] == '\"'))
3134 /* Like cpp_get_token, except that it does not read past end-of-line.
3135 * Also, horizontal space is skipped, and macros are popped. */
3137 static enum cpp_token
3138 get_directive_token(cpp_reader * pfile)
3142 long old_written = CPP_WRITTEN(pfile);
3143 enum cpp_token token;
3145 cpp_skip_hspace(pfile);
3146 if (PEEKC() == '\n')
3148 token = cpp_get_token(pfile);
3152 if (!CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
3154 /* ... else fall though ... */
3157 CPP_SET_WRITTEN(pfile, old_written);
3165 /* Handle #include and #import.
3166 * This function expects to see "fname" or <fname> on the input.
3168 * The input is normally in part of the output_buffer following
3169 * CPP_WRITTEN, and will get overwritten by output_line_command.
3170 * I.e. in input file specification has been popped by handle_directive.
3174 do_include(cpp_reader * pfile, struct directive *keyword,
3175 unsigned char *unused1, unsigned char *unused2)
3177 int importing = (keyword->type == T_IMPORT);
3178 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3179 char *fname; /* Dynamically allocated fname buffer */
3181 unsigned char *fbeg, *fend; /* Beginning and end of fname */
3182 enum cpp_token token;
3184 /* Chain of dirs to search */
3185 struct file_name_list *search_start = CPP_OPTIONS(pfile)->include;
3186 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3187 struct file_name_list *searchptr = 0;
3188 long old_written = CPP_WRITTEN(pfile);
3192 int f; /* file number */
3194 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
3198 f = -1; /* JF we iz paranoid! */
3202 if (importing && CPP_OPTIONS(pfile)->warn_import
3203 && !CPP_OPTIONS(pfile)->inhibit_warnings
3204 && !CPP_BUFFER(pfile)->system_header_p && !pfile->import_warning)
3206 pfile->import_warning = 1;
3207 cpp_warning(pfile, "using `#import' is not recommended");
3209 "The fact that a certain header file need not be processed more than once\n");
3211 "should be indicated in the header file, not where it is used.\n");
3213 "The best way to do this is with a conditional of this form:\n\n");
3214 fprintf(stderr, " #ifndef _FOO_H_INCLUDED\n");
3215 fprintf(stderr, " #define _FOO_H_INCLUDED\n");
3216 fprintf(stderr, " ... <real contents of file> ...\n");
3217 fprintf(stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
3218 fprintf(stderr, "Then users can use `#include' any number of times.\n");
3220 "GNU C automatically avoids processing the file more than once\n");
3221 fprintf(stderr, "when it is equipped with such a conditional.\n");
3223 pfile->parsing_include_directive++;
3224 token = get_directive_token(pfile);
3225 pfile->parsing_include_directive--;
3227 if (token == CPP_STRING)
3229 /* FIXME - check no trailing garbage */
3230 fbeg = pfile->token_buffer + old_written + 1;
3231 fend = CPP_PWRITTEN(pfile) - 1;
3232 if (fbeg[-1] == '<')
3235 /* If -I-, start with the first -I dir after the -I-. */
3236 if (CPP_OPTIONS(pfile)->first_bracket_include)
3237 search_start = CPP_OPTIONS(pfile)->first_bracket_include;
3239 /* If -I- was specified, don't search current dir, only spec'd ones. */
3240 else if (!CPP_OPTIONS(pfile)->ignore_srcdir)
3244 /* We have "filename". Figure out directory this source
3245 * file is coming from and put it on the front of the list. */
3247 for (fp = CPP_BUFFER(pfile); fp != NULL; fp = CPP_PREV_BUFFER(fp))
3250 const char *ep, *nam;
3252 if ((nam = fp->nominal_fname) != NULL)
3254 /* Found a named file. Figure out dir of the file,
3255 * and put it in front of the search list. */
3256 dsp[0].next = search_start;
3259 ep = strrchr(nam, '/');
3261 ep = strrchr(nam, ']');
3263 ep = strrchr(nam, '>');
3265 ep = strrchr(nam, ':');
3272 dsp[0].fname = (char *)alloca(n + 1);
3273 strncpy(dsp[0].fname, nam, n);
3274 dsp[0].fname[n] = '\0';
3275 if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3276 pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3280 dsp[0].fname = 0; /* Current directory */
3282 dsp[0].got_name_map = 0;
3291 "`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
3292 CPP_SET_WRITTEN(pfile, old_written);
3293 skip_rest_of_line(pfile);
3299 token = get_directive_token(pfile);
3300 if (token != CPP_VSPACE)
3302 cpp_error(pfile, "junk at end of `#include'");
3303 while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3304 token = get_directive_token(pfile);
3306 /* For #include_next, skip in the search path
3307 * past the dir in which the containing file was found. */
3312 for (fp = CPP_BUFFER(pfile); fp != NULL; fp = CPP_PREV_BUFFER(fp))
3313 if (fp->fname != NULL)
3315 /* fp->dir is null if the containing file was specified with
3316 * an absolute file name. In that case, don't skip anything. */
3317 if (fp->dir == SELF_DIR_DUMMY)
3318 search_start = CPP_OPTIONS(pfile)->include;
3320 search_start = fp->dir->next;
3324 CPP_SET_WRITTEN(pfile, old_written);
3330 cpp_error(pfile, "empty file name in `#%s'", keyword->name);
3333 /* Allocate this permanently, because it gets stored in the definitions
3335 fname = (char *)xmalloc(pfile->max_include_len + flen + 4);
3336 /* + 2 above for slash and terminating null. */
3337 /* + 2 added for '.h' on VMS (to support '#include filename') */
3339 /* If specified file name is absolute, just open it. */
3347 strncpy(fname, (const char *)fbeg, flen);
3349 if (redundant_include_p(pfile, fname))
3352 f = lookup_import(pfile, fname, NULL);
3354 f = open_include_file(pfile, fname, NULL);
3356 return 0; /* Already included this file */
3360 /* Search directory path, trying to open the file.
3361 * Copy each filename tried into FNAME. */
3363 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
3365 if (searchptr->fname)
3367 /* The empty string in a search path is ignored.
3368 * This makes it possible to turn off entirely
3369 * a standard piece of the list. */
3370 if (searchptr->fname[0] == 0)
3372 strcpy(fname, searchptr->fname);
3374 fname[strlen(fname) + flen] = 0;
3380 strncat(fname, (const char *)fbeg, flen);
3382 /* Change this 1/2 Unix 1/2 VMS file specification into a
3383 * full VMS file specification */
3384 if (searchptr->fname && (searchptr->fname[0] != 0))
3386 /* Fix up the filename */
3387 hack_vms_include_specification(fname);
3391 /* This is a normal VMS filespec, so use it unchanged. */
3392 strncpy(fname, fbeg, flen);
3394 /* if it's '#include filename', add the missing .h */
3395 if (strchr(fname, '.') == NULL)
3397 strcat(fname, ".h");
3401 /* ??? There are currently 3 separate mechanisms for avoiding processing
3402 * of redundant include files: #import, #pragma once, and
3403 * redundant_include_p. It would be nice if they were unified. */
3404 if (redundant_include_p(pfile, fname))
3407 f = lookup_import(pfile, fname, searchptr);
3409 f = open_include_file(pfile, fname, searchptr);
3411 return 0; /* Already included this file */
3413 else if (f == -1 && errno == EACCES)
3414 cpp_warning(pfile, "Header file %s exists, but is not readable",
3424 /* A file that was not found. */
3425 strncpy(fname, (const char *)fbeg, flen);
3427 /* If generating dependencies and -MG was specified, we assume missing
3428 * files are leaf files, living in the same directory as the source file
3429 * or other similar place; these missing files may be generated from
3430 * other files and may not exist yet (eg: y.tab.h). */
3432 if (CPP_OPTIONS(pfile)->print_deps_missing_files
3433 && CPP_PRINT_DEPS(pfile)
3434 > (angle_brackets || (pfile->system_include_depth > 0)))
3436 /* If it was requested as a system header file,
3437 * then assume it belongs in the first place to look for such. */
3440 for (searchptr = search_start; searchptr;
3441 searchptr = searchptr->next)
3443 if (searchptr->fname)
3447 if (searchptr->fname[0] == 0)
3449 p = (char *)alloca(strlen(searchptr->fname)
3450 + strlen(fname) + 2);
3451 strcpy(p, searchptr->fname);
3454 deps_output(pfile, p, ' ');
3461 /* Otherwise, omit the directory, as if the file existed
3462 * in the directory with the source. */
3463 deps_output(pfile, fname, ' ');
3466 /* If -M was specified, and this header file won't be added to the
3467 * dependency list, then don't count this as an error, because we can
3468 * still produce correct output. Otherwise, we can't produce correct
3469 * output, because there may be dependencies we need inside the missing
3470 * file, and we don't know what directory this missing file exists in. */
3471 else if (CPP_PRINT_DEPS(pfile)
3472 && (CPP_PRINT_DEPS(pfile)
3473 <= (angle_brackets || (pfile->system_include_depth > 0))))
3474 cpp_warning(pfile, "No include path in which to find %s", fname);
3475 else if (search_start)
3476 cpp_error_from_errno(pfile, fname);
3478 cpp_error(pfile, "No include path in which to find %s", fname);
3482 /* Check to see if this include file is a once-only include file.
3483 * If so, give up. */
3485 struct file_name_list *ptr;
3487 for (ptr = pfile->dont_repeat_files; ptr; ptr = ptr->next)
3489 if (!strcmp(ptr->fname, fname))
3492 return 0; /* This file was once'd. */
3496 for (ptr = pfile->all_include_files; ptr; ptr = ptr->next)
3498 if (!strcmp(ptr->fname, fname))
3499 break; /* This file was included before. */
3504 /* This is the first time for this file. */
3505 /* Add it to list of files included. */
3508 (struct file_name_list *)xmalloc(sizeof(struct file_name_list));
3510 ptr->control_macro = 0;
3511 ptr->c_system_include_path = 0;
3512 ptr->next = pfile->all_include_files;
3513 pfile->all_include_files = ptr;
3514 ptr->fname = savestring(fname);
3515 ptr->got_name_map = 0;
3517 /* For -M, add this file to the dependencies. */
3518 if (CPP_PRINT_DEPS(pfile)
3519 > (angle_brackets || (pfile->system_include_depth > 0)))
3520 deps_output(pfile, fname, ' ');
3522 /* Handle -H option. */
3523 if (CPP_OPTIONS(pfile)->print_include_names)
3525 cpp_buffer *buf = CPP_BUFFER(pfile);
3527 while ((buf = CPP_PREV_BUFFER(buf)) != NULL)
3529 fprintf(stderr, "%s\n", fname);
3532 pfile->system_include_depth++;
3534 /* Actually process the file. */
3536 /* Record file on "seen" list for #import. */
3537 add_import(pfile, f, fname);
3539 pcftry = (char *)alloca(strlen(fname) + 30);
3543 /* Actually process the file */
3544 cpp_push_buffer(pfile, NULL, 0);
3545 if (finclude(pfile, f, fname, is_system_include(pfile, fname),
3546 searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
3548 output_line_command(pfile, 0, enter_file);
3549 pfile->only_seen_white = 2;
3552 pfile->system_include_depth--;
3557 /* Return nonzero if there is no need to include file NAME
3558 * because it has already been included and it contains a conditional
3559 * to make a repeated include do nothing. */
3562 redundant_include_p(cpp_reader * pfile, char *name)
3564 struct file_name_list *l = pfile->all_include_files;
3566 for (; l; l = l->next)
3567 if (!strcmp(name, l->fname)
3569 && cpp_lookup((const char *)l->control_macro, -1, -1))
3574 /* Return nonzero if the given FILENAME is an absolute pathname which
3575 * designates a file within one of the known "system" include file
3576 * directories. We assume here that if the given FILENAME looks like
3577 * it is the name of a file which resides either directly in a "system"
3578 * include file directory, or within any subdirectory thereof, then the
3579 * given file must be a "system" include file. This function tells us
3580 * if we should suppress pedantic errors/warnings for the given FILENAME.
3582 * The value is 2 if the file is a C-language system header file
3583 * for which C++ should (on most systems) assume `extern "C"'. */
3586 is_system_include(cpp_reader * pfile, char *filename)
3588 struct file_name_list *searchptr;
3590 for (searchptr = CPP_OPTIONS(pfile)->first_system_include; searchptr;
3591 searchptr = searchptr->next)
3592 if (searchptr->fname)
3594 char *sys_dir = searchptr->fname;
3595 unsigned length = strlen(sys_dir);
3597 if (!strncmp(sys_dir, filename, length) && filename[length] == '/')
3599 if (searchptr->c_system_include_path)
3609 * Install a name in the assertion hash table.
3611 * If LEN is >= 0, it is the length of the name.
3612 * Otherwise, compute the length by scanning the entire name.
3614 * If HASH is >= 0, it is the precomputed hash code.
3615 * Otherwise, compute the hash code.
3617 static ASSERTION_HASHNODE *
3618 assertion_install(cpp_reader * pfile, const char *name, int len, int hash)
3620 ASSERTION_HASHNODE *hp;
3623 i = sizeof(ASSERTION_HASHNODE) + len + 1;
3624 hp = (ASSERTION_HASHNODE *) xmalloc(i);
3626 hp->bucket_hdr = &pfile->assertion_hashtab[bucket];
3627 hp->next = pfile->assertion_hashtab[bucket];
3628 pfile->assertion_hashtab[bucket] = hp;
3630 if (hp->next != NULL)
3631 hp->next->prev = hp;
3634 hp->name = ((char *)hp) + sizeof(ASSERTION_HASHNODE);
3635 memcpy(hp->name, name, len);
3640 * find the most recent hash node for name name (ending with first
3641 * non-identifier char) installed by install
3643 * If LEN is >= 0, it is the length of the name.
3644 * Otherwise, compute the length by scanning the entire name.
3646 * If HASH is >= 0, it is the precomputed hash code.
3647 * Otherwise, compute the hash code.
3650 static ASSERTION_HASHNODE *
3651 assertion_lookup(cpp_reader * pfile, const char *name, int len, int hash)
3653 ASSERTION_HASHNODE *bucket;
3655 bucket = pfile->assertion_hashtab[hash];
3658 if (bucket->length == len && strncmp(bucket->name, name, len) == 0)
3660 bucket = bucket->next;
3666 delete_assertion(ASSERTION_HASHNODE * hp)
3668 struct tokenlist_list *tail;
3670 if (hp->prev != NULL)
3671 hp->prev->next = hp->next;
3672 if (hp->next != NULL)
3673 hp->next->prev = hp->prev;
3675 for (tail = hp->value; tail;)
3677 struct tokenlist_list *next = tail->next;
3679 free_token_list(tail->tokens);
3684 /* make sure that the bucket chain header that
3685 * the deleted guy was on points to the right thing afterwards. */
3686 if (hp == *hp->bucket_hdr)
3687 *hp->bucket_hdr = hp->next;
3692 /* Convert a character string literal into a nul-terminated string.
3693 * The input string is [IN ... LIMIT).
3694 * The result is placed in RESULT. RESULT can be the same as IN.
3695 * The value returned in the end of the string written to RESULT,
3696 * or NULL on error. */
3699 convert_string(cpp_reader * pfile, char *result, char *in, char *limit,
3723 (unsigned char)cpp_parse_escape(pfile, &bpc);
3727 *result++ = (unsigned char)c;
3730 /* else fall through */
3740 * interpret #line command. Remembers previously seen fnames
3741 * in its very own hash table.
3743 #define FNAME_HASHSIZE 37
3746 do_line(cpp_reader * pfile, struct directive *keyword,
3747 unsigned char *unused1, unsigned char *unused2)
3749 cpp_buffer *ip = CPP_BUFFER(pfile);
3751 long old_written = CPP_WRITTEN(pfile);
3752 enum file_change_code file_change = same_file;
3753 enum cpp_token token;
3755 token = get_directive_token(pfile);
3758 unused1 = unused2 = NULL;
3760 if (token != CPP_NUMBER || !isdigit(pfile->token_buffer[old_written]))
3762 cpp_error(pfile, "invalid format `#line' command");
3763 goto bad_line_directive;
3765 /* The Newline at the end of this line remains to be processed.
3766 * To put the next line at the specified line number,
3767 * we must store a line number now that is one less. */
3768 new_lineno = atoi((char *)(pfile->token_buffer + old_written)) - 1;
3769 CPP_SET_WRITTEN(pfile, old_written);
3771 /* NEW_LINENO is one less than the actual line number here. */
3772 if (CPP_PEDANTIC(pfile) && new_lineno < 0)
3773 cpp_pedwarn(pfile, "line number out of range in `#line' command");
3775 token = get_directive_token(pfile);
3777 if (token == CPP_STRING)
3779 char *fname = (char *)pfile->token_buffer + old_written;
3781 static HASHNODE *fname_table[FNAME_HASHSIZE];
3782 HASHNODE *hp, **hash_bucket;
3787 /* Turn the file name, which is a character string literal,
3788 * into a null-terminated string. Do this in place. */
3790 convert_string(pfile, fname, fname, (char *)CPP_PWRITTEN(pfile), 1);
3791 if (end_name == NULL)
3793 cpp_error(pfile, "invalid format `#line' command");
3794 goto bad_line_directive;
3796 fname_length = end_name - fname;
3798 num_start = CPP_WRITTEN(pfile);
3799 token = get_directive_token(pfile);
3800 if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3802 p = pfile->token_buffer + num_start;
3803 if (CPP_PEDANTIC(pfile))
3804 cpp_pedwarn(pfile, "garbage at end of `#line' command");
3806 if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
3808 cpp_error(pfile, "invalid format `#line' command");
3809 goto bad_line_directive;
3812 file_change = enter_file;
3814 file_change = leave_file;
3816 ip->system_header_p = 1;
3817 else /* if (*p == 4) */
3818 ip->system_header_p = 2;
3820 CPP_SET_WRITTEN(pfile, num_start);
3821 token = get_directive_token(pfile);
3822 p = pfile->token_buffer + num_start;
3823 if (token == CPP_NUMBER && p[1] == '\0'
3824 && (*p == '3' || *p == '4'))
3826 ip->system_header_p = *p == 3 ? 1 : 2;
3827 token = get_directive_token(pfile);
3829 if (token != CPP_VSPACE)
3831 cpp_error(pfile, "invalid format `#line' command");
3832 goto bad_line_directive;
3835 hash_bucket = &fname_table[hashf(fname, fname_length, FNAME_HASHSIZE)];
3836 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3837 if (hp->length == fname_length &&
3838 strncmp(hp->value.cpval, fname, fname_length) == 0)
3840 ip->nominal_fname = hp->value.cpval;
3845 /* Didn't find it; cons up a new one. */
3846 hp = (HASHNODE *) xcalloc(1, sizeof(HASHNODE) + fname_length + 1);
3847 hp->next = *hash_bucket;
3850 hp->length = fname_length;
3851 ip->nominal_fname = hp->value.cpval =
3852 ((char *)hp) + sizeof(HASHNODE);
3853 memcpy(hp->value.cpval, fname, fname_length);
3856 else if (token != CPP_VSPACE && token != CPP_EOF)
3858 cpp_error(pfile, "invalid format `#line' command");
3859 goto bad_line_directive;
3861 ip->lineno = new_lineno;
3863 skip_rest_of_line(pfile);
3864 CPP_SET_WRITTEN(pfile, old_written);
3865 output_line_command(pfile, 0, file_change);
3870 * remove the definition of a symbol from the symbol table.
3871 * according to un*x /lib/cpp, it is not an error to undef
3872 * something that has no definitions, so it isn't one here either.
3876 do_undef(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3877 unsigned char *limit)
3881 unsigned char *orig_buf = buf;
3883 SKIP_WHITE_SPACE(buf);
3884 sym_length = check_macro_name(pfile, buf, "macro");
3886 while ((hp = cpp_lookup((const char *)buf, sym_length, -1)) != NULL)
3888 /* If we are generating additional info for debugging (with -g) we
3889 * need to pass through all effective #undef commands. */
3890 if (CPP_OPTIONS(pfile)->debug_output && keyword)
3891 pass_thru_directive((char *)orig_buf, (char *)limit, pfile, keyword);
3892 if (hp->type != T_MACRO)
3893 cpp_warning(pfile, "undefining `%s'", hp->name);
3897 if (CPP_PEDANTIC(pfile))
3900 SKIP_WHITE_SPACE(buf);
3902 cpp_pedwarn(pfile, "garbage after `#undef' directive");
3908 * Report an error detected by the program we are processing.
3909 * Use the text of the line in the error message.
3910 * (We use error because it prints the filename & line#.)
3914 do_error(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3915 unsigned char *limit)
3917 int length = limit - buf;
3918 unsigned char *copy = (unsigned char *)xmalloc(length + 1);
3921 memcpy(copy, buf, length);
3923 SKIP_WHITE_SPACE(copy);
3924 cpp_error(pfile, "#error %s", copy);
3929 * Report a warning detected by the program we are processing.
3930 * Use the text of the line in the warning message, then continue.
3931 * (We use error because it prints the filename & line#.)
3935 do_warning(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3936 unsigned char *limit)
3938 int length = limit - buf;
3939 unsigned char *copy = (unsigned char *)xmalloc(length + 1);
3942 memcpy(copy, buf, length);
3944 SKIP_WHITE_SPACE(copy);
3945 cpp_warning(pfile, "#warning %s", copy);
3949 /* Remember the name of the current file being read from so that we can
3950 * avoid ever including it again. */
3953 do_once(cpp_reader * pfile)
3955 cpp_buffer *ip = NULL;
3956 struct file_name_list *new_;
3958 for (ip = CPP_BUFFER(pfile);; ip = CPP_PREV_BUFFER(ip))
3962 if (ip->fname != NULL)
3966 new_ = (struct file_name_list *)xmalloc(sizeof(struct file_name_list));
3968 new_->next = pfile->dont_repeat_files;
3969 pfile->dont_repeat_files = new_;
3970 new_->fname = savestring(ip->fname);
3971 new_->control_macro = 0;
3972 new_->got_name_map = 0;
3973 new_->c_system_include_path = 0;
3978 /* #ident has already been copied to the output file, so just ignore it. */
3981 do_ident(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
3982 unsigned char *limit)
3984 /* long old_written = CPP_WRITTEN (pfile); */
3986 /* Allow #ident in system headers, since that's not user's fault. */
3987 if (CPP_PEDANTIC(pfile) && !CPP_BUFFER(pfile)->system_header_p)
3988 cpp_pedwarn(pfile, "ANSI C does not allow `#ident'");
3993 /* Leave rest of line to be read by later calls to cpp_get_token. */
3998 /* #pragma and its argument line have already been copied to the output file.
3999 * Just check for some recognized pragmas that need validation here. */
4002 do_pragma(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4003 unsigned char *limit)
4005 while (*buf == ' ' || *buf == '\t')
4010 if (!strncmp((const char *)buf, "once", 4))
4012 /* Allow #pragma once in system headers, since that's not the user's
4014 if (!CPP_BUFFER(pfile)->system_header_p)
4015 cpp_warning(pfile, "`#pragma once' is obsolete");
4018 if (!strncmp((const char *)buf, "implementation", 14))
4020 /* Be quiet about `#pragma implementation' for a file only if it hasn't
4021 * been included yet. */
4022 struct file_name_list *ptr;
4023 char *p = (char *)buf + 14, *fname, *inc_fname;
4026 SKIP_WHITE_SPACE(p);
4027 if (*p == '\n' || *p != '\"')
4031 p = strchr(fname, '\"');
4033 (int)(((int)(p != NULL)) ? ((int)(p - fname))
4034 : ((int)(strlen(fname))));
4036 for (ptr = pfile->all_include_files; ptr; ptr = ptr->next)
4038 inc_fname = strrchr(ptr->fname, '/');
4039 inc_fname = inc_fname ? inc_fname + 1 : (char *)ptr->fname;
4040 if (inc_fname && !strncmp(inc_fname, fname, fname_len))
4042 "`#pragma implementation' for `%s' appears after file is included",
4049 /* Just ignore #sccs, on systems where we define it at all. */
4052 * handle #if command by
4053 * 1) inserting special `defined' keyword into the hash table
4054 * that gets turned into 0 or 1 by special_symbol (thus,
4055 * if the luser has a symbol called `defined' already, it won't
4056 * work inside the #if command)
4057 * 2) rescan the input into a temporary output buffer
4058 * 3) pass the output buffer to the yacc parser and collect a value
4059 * 4) clean up the mess left from steps 1 and 2.
4060 * 5) call conditional_skip to skip til the next #endif (etc.),
4061 * or not, depending on the value from step 3.
4065 do_if(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4066 unsigned char *limit)
4068 HOST_WIDE_INT value = eval_if_expression(pfile, buf, limit - buf);
4071 conditional_skip(pfile, value == 0, T_IF, NULL);
4076 * handle a #elif directive by not changing if_stack either.
4077 * see the comment above do_else.
4081 do_elif(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4082 unsigned char *limit)
4087 if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4089 cpp_error(pfile, "`#elif' not within a conditional");
4094 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4096 cpp_error(pfile, "`#elif' after `#else'");
4097 if (pfile->if_stack->fname != NULL
4098 && CPP_BUFFER(pfile)->fname != NULL
4099 && strcmp(pfile->if_stack->fname,
4100 CPP_BUFFER(pfile)->nominal_fname) != 0)
4101 fprintf(stderr, ", file %s", pfile->if_stack->fname);
4102 fprintf(stderr, ")\n");
4104 pfile->if_stack->type = T_ELIF;
4107 if (pfile->if_stack->if_succeeded)
4108 skip_if_group(pfile, 0);
4111 HOST_WIDE_INT value = eval_if_expression(pfile, buf, limit - buf);
4114 skip_if_group(pfile, 0);
4117 ++pfile->if_stack->if_succeeded; /* continue processing input */
4118 output_line_command(pfile, 1, same_file);
4125 * evaluate a #if expression in BUF, of length LENGTH,
4126 * then parse the result as a C expression and return the value as an int.
4128 static HOST_WIDE_INT
4129 eval_if_expression(cpp_reader * pfile, unsigned char *buf, int length)
4131 HASHNODE *save_defined;
4132 HOST_WIDE_INT value;
4133 long old_written = CPP_WRITTEN(pfile);
4137 save_defined = install("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4138 pfile->pcp_inside_if = 1;
4140 value = cpp_parse_expr(pfile);
4141 pfile->pcp_inside_if = 0;
4142 delete_macro(save_defined); /* clean up special symbol */
4144 CPP_SET_WRITTEN(pfile, old_written); /* Pop */
4150 * routine to handle ifdef/ifndef. Try to look up the symbol,
4151 * then do or don't skip to the #endif/#else/#elif depending
4152 * on what directive is actually being processed.
4156 do_xifdef(cpp_reader * pfile, struct directive *keyword, unsigned char *unused1,
4157 unsigned char *unused2)
4160 cpp_buffer *ip = CPP_BUFFER(pfile);
4163 enum cpp_token token;
4164 int start_of_file = 0;
4165 unsigned char *control_macro = 0;
4166 int old_written = CPP_WRITTEN(pfile);
4170 /* Detect a #ifndef at start of file (not counting comments). */
4171 if (ip->fname != 0 && keyword->type == T_IFNDEF)
4172 start_of_file = pfile->only_seen_white == 2;
4174 pfile->no_macro_expand++;
4175 token = get_directive_token(pfile);
4176 pfile->no_macro_expand--;
4178 ident = (char *)pfile->token_buffer + old_written;
4179 ident_length = CPP_WRITTEN(pfile) - old_written;
4180 CPP_SET_WRITTEN(pfile, old_written); /* Pop */
4182 if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4184 skip = (keyword->type == T_IFDEF);
4185 if (!CPP_TRADITIONAL(pfile))
4186 cpp_pedwarn(pfile, "`#%s' with no argument", keyword->name);
4188 else if (token == CPP_NAME)
4190 HASHNODE *hp = cpp_lookup(ident, ident_length, -1);
4192 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
4193 if (start_of_file && !skip)
4195 control_macro = (unsigned char *)xmalloc(ident_length + 1);
4196 memcpy(control_macro, ident, ident_length + 1);
4201 skip = (keyword->type == T_IFDEF);
4202 if (!CPP_TRADITIONAL(pfile))
4203 cpp_error(pfile, "`#%s' with invalid argument", keyword->name);
4206 if (!CPP_TRADITIONAL(pfile))
4210 cpp_skip_hspace(pfile);
4212 if (c != EOF && c != '\n')
4213 cpp_pedwarn(pfile, "garbage at end of `#%s' argument",
4216 skip_rest_of_line(pfile);
4218 conditional_skip(pfile, skip, T_IF, control_macro);
4222 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4223 * If this is a #ifndef starting at the beginning of a file,
4224 * CONTROL_MACRO is the macro name tested by the #ifndef.
4225 * Otherwise, CONTROL_MACRO is 0. */
4228 conditional_skip(cpp_reader * pfile, int skip, enum node_type type,
4229 unsigned char *control_macro)
4231 IF_STACK_FRAME *temp;
4233 temp = (IF_STACK_FRAME *) xcalloc(1, sizeof(IF_STACK_FRAME));
4234 temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4235 temp->next = pfile->if_stack;
4236 temp->control_macro = control_macro;
4237 pfile->if_stack = temp;
4239 pfile->if_stack->type = type;
4243 skip_if_group(pfile, 0);
4248 ++pfile->if_stack->if_succeeded;
4249 output_line_command(pfile, 1, same_file);
4254 * skip to #endif, #else, or #elif. adjust line numbers, etc.
4255 * leaves input ptr at the sharp sign found.
4256 * If ANY is nonzero, return at next directive of any sort.
4260 skip_if_group(cpp_reader * pfile, int any)
4263 struct directive *kt;
4264 IF_STACK_FRAME *save_if_stack = pfile->if_stack; /* don't pop past here */
4268 struct parse_marker line_start_mark;
4270 parse_set_mark(&line_start_mark, pfile);
4272 if (CPP_OPTIONS(pfile)->output_conditionals)
4274 static char failed[] = "#failed\n";
4276 CPP_PUTS(pfile, failed, sizeof(failed) - 1);
4278 output_line_command(pfile, 1, same_file);
4281 if (CPP_OPTIONS(pfile)->output_conditionals)
4283 cpp_buffer *pbuf = CPP_BUFFER(pfile);
4284 unsigned char *start_line = pbuf->buf + line_start_mark.position;
4286 CPP_PUTS(pfile, start_line, pbuf->cur - start_line);
4288 parse_move_mark(&line_start_mark, pfile);
4289 if (!CPP_TRADITIONAL(pfile))
4290 cpp_skip_hspace(pfile);
4294 int old_written = CPP_WRITTEN(pfile);
4296 cpp_skip_hspace(pfile);
4298 parse_name(pfile, GETC());
4299 ident_length = CPP_WRITTEN(pfile) - old_written;
4300 ident = (char *)pfile->token_buffer + old_written;
4301 pfile->limit = (unsigned char *)ident;
4303 for (kt = directive_table; kt->length >= 0; kt++)
4305 IF_STACK_FRAME *temp;
4307 if (ident_length == kt->length
4308 && strncmp(ident, kt->name, kt->length) == 0)
4310 /* If we are asked to return on next directive, do so now. */
4321 (IF_STACK_FRAME *) xcalloc(1, sizeof(IF_STACK_FRAME));
4322 temp->next = pfile->if_stack;
4323 pfile->if_stack = temp;
4324 temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4325 temp->type = kt->type;
4329 if (CPP_PEDANTIC(pfile)
4330 && pfile->if_stack != save_if_stack)
4331 validate_else(pfile,
4333 T_ELSE ? "#else" : "#endif");
4335 if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4338 "`#%s' not within a conditional",
4342 else if (pfile->if_stack == save_if_stack)
4343 goto done; /* found what we came for */
4345 if (kt->type != T_ENDIF)
4347 if (pfile->if_stack->type == T_ELSE)
4349 "`#else' or `#elif' after `#else'");
4350 pfile->if_stack->type = kt->type;
4353 temp = pfile->if_stack;
4354 pfile->if_stack = temp->next;
4361 /* Don't let erroneous code go by. */
4362 if (kt->length < 0 && !CPP_OPTIONS(pfile)->lang_asm
4363 && CPP_PEDANTIC(pfile))
4364 cpp_pedwarn(pfile, "invalid preprocessor directive name");
4368 /* We're in the middle of a line. Skip the rest of it. */
4377 case '/': /* possible comment */
4378 c = skip_comment(pfile, NULL);
4385 old = CPP_WRITTEN(pfile);
4386 cpp_get_token(pfile);
4387 CPP_SET_WRITTEN(pfile, old);
4390 /* Char after backslash loses its special meaning. */
4391 if (PEEKC() == '\n')
4401 if (CPP_OPTIONS(pfile)->output_conditionals)
4403 static char end_failed[] = "#endfailed\n";
4405 CPP_PUTS(pfile, end_failed, sizeof(end_failed) - 1);
4408 pfile->only_seen_white = 1;
4409 parse_goto_mark(&line_start_mark, pfile);
4410 parse_clear_mark(&line_start_mark);
4414 * handle a #else directive. Do this by just continuing processing
4415 * without changing if_stack ; this is so that the error message
4416 * for missing #endif's etc. will point to the original #if. It
4417 * is possible that something different would be better.
4421 do_else(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4422 unsigned char *limit)
4424 cpp_buffer *ip = CPP_BUFFER(pfile);
4430 if (CPP_PEDANTIC(pfile))
4431 validate_else(pfile, "#else");
4432 skip_rest_of_line(pfile);
4434 if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4436 cpp_error(pfile, "`#else' not within a conditional");
4441 /* #ifndef can't have its special treatment for containing the whole file
4442 * if it has a #else clause. */
4443 pfile->if_stack->control_macro = 0;
4445 if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF)
4447 cpp_error(pfile, "`#else' after `#else'");
4448 fprintf(stderr, " (matches line %d", pfile->if_stack->lineno);
4449 if (strcmp(pfile->if_stack->fname, ip->nominal_fname) != 0)
4450 fprintf(stderr, ", file %s", pfile->if_stack->fname);
4451 fprintf(stderr, ")\n");
4453 pfile->if_stack->type = T_ELSE;
4456 if (pfile->if_stack->if_succeeded)
4457 skip_if_group(pfile, 0);
4460 ++pfile->if_stack->if_succeeded; /* continue processing input */
4461 output_line_command(pfile, 1, same_file);
4467 * unstack after #endif command
4471 do_endif(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
4472 unsigned char *limit)
4474 if (CPP_PEDANTIC(pfile))
4475 validate_else(pfile, "#endif");
4476 skip_rest_of_line(pfile);
4482 if (pfile->if_stack == CPP_BUFFER(pfile)->if_stack)
4484 cpp_error(pfile, "unbalanced `#endif'");
4488 IF_STACK_FRAME *temp = pfile->if_stack;
4490 pfile->if_stack = temp->next;
4491 if (temp->control_macro != 0)
4493 /* This #endif matched a #ifndef at the start of the file.
4494 * See if it is at the end of the file. */
4495 struct parse_marker start_mark;
4498 parse_set_mark(&start_mark, pfile);
4502 cpp_skip_hspace(pfile);
4507 parse_goto_mark(&start_mark, pfile);
4508 parse_clear_mark(&start_mark);
4512 /* If we get here, this #endif ends a #ifndef
4513 * that contains all of the file (aside from whitespace).
4514 * Arrange not to include the file again
4515 * if the macro that was tested is defined.
4517 * Do not do this for the top-level file in a -include or any
4518 * file in a -imacros. */
4520 struct file_name_list *ifile = pfile->all_include_files;
4522 for (; ifile != NULL; ifile = ifile->next)
4524 if (!strcmp(ifile->fname, CPP_BUFFER(pfile)->fname))
4526 ifile->control_macro = temp->control_macro;
4534 output_line_command(pfile, 1, same_file);
4539 /* When an #else or #endif is found while skipping failed conditional,
4540 * if -pedantic was specified, this is called to warn about text after
4541 * the command name. P points to the first char after the command name. */
4544 validate_else(cpp_reader * pfile, const char *directive)
4548 cpp_skip_hspace(pfile);
4550 if (c != EOF && c != '\n')
4552 "text following `%s' violates ANSI standard", directive);
4555 /* Get the next token, and add it to the text in pfile->token_buffer.
4556 * Return the kind of token we got. */
4559 cpp_get_token(cpp_reader * pfile)
4562 long old_written = 0;
4563 long start_line, start_column;
4564 enum cpp_token token;
4565 struct cpp_options *opts = CPP_OPTIONS(pfile);
4567 CPP_BUFFER(pfile)->prev = CPP_BUFFER(pfile)->cur;
4573 if (CPP_BUFFER(pfile)->seen_eof)
4575 if (cpp_pop_buffer(pfile) != CPP_NULL_BUFFER(pfile))
4582 cpp_buffer *next_buf = CPP_PREV_BUFFER(CPP_BUFFER(pfile));
4584 CPP_BUFFER(pfile)->seen_eof = 1;
4585 if (CPP_BUFFER(pfile)->nominal_fname && next_buf != 0)
4587 /* We're about to return from an #include file.
4588 * Emit #line information now (as part of the CPP_POP) result.
4589 * But the #line refers to the file we will pop to. */
4590 cpp_buffer *cur_buffer = CPP_BUFFER(pfile);
4592 CPP_BUFFER(pfile) = next_buf;
4593 pfile->input_stack_listing_current = 0;
4594 output_line_command(pfile, 0, leave_file);
4595 CPP_BUFFER(pfile) = cur_buffer;
4605 struct parse_marker start_mark;
4610 if (opts->put_out_comments)
4611 parse_set_mark(&start_mark, pfile);
4613 cpp_buf_line_and_col(cpp_file_buffer(pfile),
4614 &start_line, &start_column);
4615 c = skip_comment(pfile, &newlines);
4616 if (opts->put_out_comments && (c == '/' || c == EOF))
4617 parse_clear_mark(&start_mark);
4622 cpp_error_with_line(pfile, start_line, start_column,
4623 "unterminated comment");
4626 c = '/'; /* Initial letter of comment. */
4628 /* Comments are equivalent to spaces.
4629 * For -traditional, a comment is equivalent to nothing. */
4630 if (opts->put_out_comments)
4632 cpp_buffer *pbuf = CPP_BUFFER(pfile);
4633 unsigned char *start = pbuf->buf + start_mark.position;
4634 int len = pbuf->cur - start;
4636 CPP_RESERVE(pfile, 1 + len);
4637 CPP_PUTC_Q(pfile, c);
4638 CPP_PUTS_Q(pfile, start, len);
4639 pfile->lineno += newlines;
4640 parse_clear_mark(&start_mark);
4643 else if (CPP_TRADITIONAL(pfile))
4649 CPP_RESERVE(pfile, 1);
4650 CPP_PUTC_Q(pfile, ' ');
4655 if (!pfile->only_seen_white)
4657 if (handle_directive(pfile))
4658 return CPP_DIRECTIVE;
4659 pfile->only_seen_white = 0;
4664 /* A single quoted string is treated like a double -- some
4665 * programs (e.g., troff) are perverse this way */
4666 cpp_buf_line_and_col(cpp_file_buffer(pfile),
4667 &start_line, &start_column);
4668 old_written = CPP_WRITTEN(pfile);
4677 if (CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
4679 /* try harder: this string crosses a macro expansion
4680 * boundary. This can happen naturally if -traditional.
4681 * Otherwise, only -D can make a macro with an unmatched
4683 cpp_buffer *next_buf
4684 = CPP_PREV_BUFFER(CPP_BUFFER(pfile));
4686 (*CPP_BUFFER(pfile)->cleanup)
4687 (CPP_BUFFER(pfile), pfile);
4688 CPP_BUFFER(pfile) = next_buf;
4691 if (!CPP_TRADITIONAL(pfile))
4693 cpp_error_with_line(pfile, start_line, start_column,
4694 "unterminated string or character constant");
4695 if (pfile->multiline_string_line != start_line
4696 && pfile->multiline_string_line != 0)
4697 cpp_error_with_line(pfile,
4698 pfile->multiline_string_line,
4700 "possible real start of unterminated constant");
4701 pfile->multiline_string_line = 0;
4705 CPP_PUTC(pfile, cc);
4709 /* Traditionally, end of line ends a string constant with
4710 * no error. So exit the loop and record the new line. */
4711 if (CPP_TRADITIONAL(pfile))
4715 cpp_error_with_line(pfile, start_line, start_column,
4716 "unterminated character constant");
4719 if (CPP_PEDANTIC(pfile)
4720 && pfile->multiline_string_line == 0)
4722 cpp_pedwarn_with_line(pfile, start_line,
4724 "string constant runs past end of line");
4726 if (pfile->multiline_string_line == 0)
4727 pfile->multiline_string_line = start_line;
4734 /* Backslash newline is replaced by nothing at all. */
4735 CPP_ADJUST_WRITTEN(pfile, -1);
4740 /* ANSI stupidly requires that in \\ the second \
4741 * is *not* prevented from combining with a newline. */
4744 CPP_PUTC(pfile, cc);
4756 pfile->lineno += count_newlines(pfile->token_buffer + old_written,
4757 CPP_PWRITTEN(pfile));
4758 pfile->only_seen_white = 0;
4759 return c == '\'' ? CPP_CHAR : CPP_STRING;
4762 if (!opts->dollars_in_ident)
4767 if (opts->cplusplus && PEEKC() == ':')
4776 if (c2 == c || c2 == '=')
4793 if (c2 == '-' && opts->chill)
4795 /* Chill style comment */
4796 if (opts->put_out_comments)
4797 parse_set_mark(&start_mark, pfile);
4798 FORWARD(1); /* Skip second '-'. */
4806 /* Don't consider final '\n' to be part of comment. */
4812 goto return_comment;
4814 if (c2 == '-' || c2 == '=' || c2 == '>')
4819 if (pfile->parsing_include_directive)
4828 if (c == '\n' || c == EOF)
4831 "missing '>' in `#include <FILENAME>'");
4837 /* else fall through */
4846 CPP_RESERVE(pfile, 4);
4848 CPP_PUTC(pfile, c2);
4852 CPP_PUTC_Q(pfile, GETC());
4853 CPP_NUL_TERMINATE_Q(pfile);
4854 pfile->only_seen_white = 0;
4858 if (CPP_BUFFER(pfile)->has_escapes)
4863 if (pfile->output_escapes)
4864 CPP_PUTS(pfile, "@-", 2);
4865 parse_name(pfile, GETC());
4868 else if (is_space[c])
4870 CPP_RESERVE(pfile, 2);
4871 if (pfile->output_escapes)
4872 CPP_PUTC_Q(pfile, '@');
4873 CPP_PUTC_Q(pfile, c);
4877 if (pfile->output_escapes)
4879 CPP_PUTS(pfile, "@@", 2);
4889 CPP_RESERVE(pfile, 2);
4890 CPP_PUTC_Q(pfile, '.');
4894 /* FIXME - misses the case "..\\\n." */
4895 if (c2 == '.' && PEEKN(1) == '.')
4897 CPP_RESERVE(pfile, 4);
4898 CPP_PUTC_Q(pfile, '.');
4899 CPP_PUTC_Q(pfile, '.');
4900 CPP_PUTC_Q(pfile, '.');
4902 CPP_NUL_TERMINATE_Q(pfile);
4903 pfile->only_seen_white = 0;
4910 pfile->only_seen_white = 0;
4912 CPP_RESERVE(pfile, 3);
4913 CPP_PUTC_Q(pfile, c);
4914 CPP_PUTC_Q(pfile, GETC());
4915 CPP_NUL_TERMINATE_Q(pfile);
4921 if ((c2 == '\'' || c2 == '\"') && !CPP_TRADITIONAL(pfile))
4943 CPP_RESERVE(pfile, 2);
4944 CPP_PUTC_Q(pfile, c);
4949 if (!is_idchar[c] && c != '.'
4950 && ((c2 != 'e' && c2 != 'E') || (c != '+' && c != '-')))
4955 CPP_NUL_TERMINATE_Q(pfile);
4956 pfile->only_seen_white = 0;
4968 if (opts->chill && PEEKC() == '\'')
4970 pfile->only_seen_white = 0;
4971 CPP_RESERVE(pfile, 2);
4972 CPP_PUTC_Q(pfile, c);
4973 CPP_PUTC_Q(pfile, '\'');
4979 goto chill_number_eof;
4982 if (c == '\\' && PEEKC() == '\n')
4993 CPP_RESERVE(pfile, 2);
4994 CPP_PUTC_Q(pfile, c);
4995 CPP_NUL_TERMINATE_Q(pfile);
5002 CPP_NUL_TERMINATE(pfile);
5054 int before_name_written = CPP_WRITTEN(pfile);
5057 parse_name(pfile, c);
5058 pfile->only_seen_white = 0;
5059 if (pfile->no_macro_expand)
5061 ident = (char *)pfile->token_buffer + before_name_written;
5062 ident_len = CPP_PWRITTEN(pfile) - (unsigned char *)ident;
5063 hp = cpp_lookup(ident, ident_len, -1);
5066 if (hp->type == T_DISABLED)
5068 if (pfile->output_escapes)
5069 { /* Return "@-IDENT", followed by '\0'. */
5072 CPP_RESERVE(pfile, 3);
5074 (char *)pfile->token_buffer + before_name_written;
5075 CPP_ADJUST_WRITTEN(pfile, 2);
5076 for (i = ident_len; i >= 0; i--)
5077 ident[i + 2] = ident[i];
5083 /* If macro wants an arglist, verify that a '(' follows.
5084 * first skip all whitespace, copying it to the output
5085 * after the macro name. Then, if there is no '(',
5086 * decide this is not a macro call and leave things that way. */
5087 if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5089 struct parse_marker macro_mark;
5092 while (CPP_IS_MACRO_BUFFER(CPP_BUFFER(pfile)))
5094 cpp_buffer *next_buf;
5096 cpp_skip_hspace(pfile);
5099 next_buf = CPP_PREV_BUFFER(CPP_BUFFER(pfile));
5100 (*CPP_BUFFER(pfile)->cleanup) (CPP_BUFFER(pfile),
5102 CPP_BUFFER(pfile) = next_buf;
5104 parse_set_mark(¯o_mark, pfile);
5107 cpp_skip_hspace(pfile);
5109 is_macro_call = c == '(';
5115 parse_goto_mark(¯o_mark, pfile);
5116 parse_clear_mark(¯o_mark);
5120 /* This is now known to be a macro call. */
5122 /* it might not actually be a macro. */
5123 if (hp->type != T_MACRO)
5126 unsigned char *xbuf;
5128 CPP_SET_WRITTEN(pfile, before_name_written);
5129 special_symbol(hp, pfile);
5130 xbuf_len = CPP_WRITTEN(pfile) - before_name_written;
5131 xbuf = (unsigned char *)xmalloc(xbuf_len + 1);
5132 CPP_SET_WRITTEN(pfile, before_name_written);
5133 memcpy(xbuf, CPP_PWRITTEN(pfile), xbuf_len + 1);
5134 push_macro_expansion(pfile, xbuf, xbuf_len, hp);
5138 /* Expand the macro, reading arguments as needed,
5139 * and push the expansion on the input stack. */
5140 macroexpand(pfile, hp);
5141 CPP_SET_WRITTEN(pfile, before_name_written);
5144 /* An extra "@ " is added to the end of a macro expansion
5145 * to prevent accidental token pasting. We prefer to avoid
5146 * unneeded extra spaces (for the sake of cpp-using tools like
5147 * imake). Here we remove the space if it is safe to do so. */
5148 if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5149 && pfile->buffer->rlimit[-2] == '@'
5150 && pfile->buffer->rlimit[-1] == ' ')
5152 int c1 = pfile->buffer->rlimit[-3];
5154 c2 = CPP_BUF_PEEK(CPP_PREV_BUFFER(CPP_BUFFER(pfile)));
5156 if (c2 == EOF || !unsafe_chars(c1, c2))
5157 pfile->buffer->rlimit -= 2;
5170 if (c == EOF || !is_hor_space[c])
5185 if (pfile->only_seen_white == 0)
5186 pfile->only_seen_white = 1;
5188 output_line_command(pfile, 1, same_file);
5207 token = CPP_SEMICOLON;
5214 pfile->only_seen_white = 0;
5222 /* Like cpp_get_token, but skip spaces and comments. */
5224 cpp_get_non_space_token(cpp_reader * pfile)
5226 int old_written = CPP_WRITTEN(pfile);
5230 enum cpp_token token = cpp_get_token(pfile);
5232 if (token != CPP_COMMENT && token != CPP_POP
5233 && token != CPP_HSPACE && token != CPP_VSPACE)
5235 CPP_SET_WRITTEN(pfile, old_written);
5240 /* Parse an identifier starting with C. */
5243 parse_name(cpp_reader * pfile, int c)
5249 if (c == '\\' && PEEKC() == '\n')
5257 CPP_RESERVE(pfile, 2); /* One more for final NUL. */
5258 CPP_PUTC_Q(pfile, c);
5263 CPP_NUL_TERMINATE_Q(pfile);
5267 /* Maintain and search list of included files, for #import. */
5269 /* Hash a file name for import_hash_table. */
5272 import_hash(char *f)
5278 return (val % IMPORT_HASH_SIZE);
5281 /* Search for file FILENAME in import_hash_table.
5282 * Return -2 if found, either a matching name or a matching inode.
5283 * Otherwise, open the file and return a file descriptor if successful
5284 * or -1 if unsuccessful. */
5287 lookup_import(cpp_reader * pfile, char *filename,
5288 struct file_name_list *searchptr)
5290 struct import_file *i;
5296 hashval = import_hash(filename);
5298 /* Attempt to find file in list of already included files */
5299 i = pfile->import_hash_table[hashval];
5303 if (!strcmp(filename, i->name))
5304 return -2; /* return found */
5307 /* Open it and try a match on inode/dev */
5308 fd = open_include_file(pfile, filename, searchptr);
5312 for (h = 0; h < IMPORT_HASH_SIZE; h++)
5314 i = pfile->import_hash_table[h];
5317 /* Compare the inode and the device.
5318 * Supposedly on some systems the inode is not a scalar. */
5320 ((char *)&i->inode, (char *)&sb.st_ino, sizeof(sb.st_ino))
5321 && i->dev == sb.st_dev)
5324 return -2; /* return found */
5329 return fd; /* Not found, return open file */
5332 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5335 add_import(cpp_reader * pfile, int fd, char *fname)
5337 struct import_file *i;
5341 hashval = import_hash(fname);
5343 i = (struct import_file *)xmalloc(sizeof(struct import_file));
5345 i->name = (char *)xmalloc(strlen(fname) + 1);
5346 strcpy(i->name, fname);
5347 memcpy((char *)&i->inode, (char *)&sb.st_ino, sizeof(sb.st_ino));
5349 i->next = pfile->import_hash_table[hashval];
5350 pfile->import_hash_table[hashval] = i;
5353 /* The file_name_map structure holds a mapping of file names for a
5354 * particular directory. This mapping is read from the file named
5355 * FILE_NAME_MAP_FILE in that directory. Such a file can be used to
5356 * map filenames on a file system with severe filename restrictions,
5357 * such as DOS. The format of the file name map file is just a series
5358 * of lines with two tokens on each line. The first token is the name
5359 * to map, and the second token is the actual name to use. */
5361 struct file_name_map {
5362 struct file_name_map *map_next;
5367 #if USE_FILE_NAME_MAPS
5369 #define FILE_NAME_MAP_FILE "header.gcc"
5371 /* Read a space delimited string of unlimited length from a stdio
5375 read_filename_string(int ch, FILE * f)
5381 set = alloc = (char *)xmalloc(len + 1);
5385 while ((ch = getc(f)) != EOF && !is_space[ch])
5387 if (set - alloc == len)
5390 alloc = (char *)xrealloc(alloc, len + 1);
5391 set = alloc + len / 2;
5401 /* This structure holds a linked list of file name maps, one per directory. */
5402 struct file_name_map_list {
5403 struct file_name_map_list *map_list_next;
5404 char *map_list_name;
5405 struct file_name_map *map_list_map;
5408 /* Read the file name map file for DIRNAME. */
5410 static struct file_name_map *
5411 read_name_map(cpp_reader * pfile, const char *dirname)
5413 struct file_name_map_list *map_list_ptr;
5417 for (map_list_ptr = CPP_OPTIONS(pfile)->map_list; map_list_ptr;
5418 map_list_ptr = map_list_ptr->map_list_next)
5419 if (!strcmp(map_list_ptr->map_list_name, dirname))
5420 return map_list_ptr->map_list_map;
5423 ((struct file_name_map_list *)xmalloc(sizeof(struct file_name_map_list)));
5425 map_list_ptr->map_list_name = savestring(dirname);
5426 map_list_ptr->map_list_map = NULL;
5428 name = (char *)alloca(strlen(dirname) + strlen(FILE_NAME_MAP_FILE) + 2);
5429 strcpy(name, dirname);
5432 strcat(name, FILE_NAME_MAP_FILE);
5434 f = fopen(name, "r");
5436 f = fopen(name, "rt");
5439 map_list_ptr->map_list_map = NULL;
5443 int dirlen = strlen(dirname);
5445 while ((ch = getc(f)) != EOF)
5448 struct file_name_map *ptr;
5452 from = read_filename_string(ch, f);
5453 while ((ch = getc(f)) != EOF && is_hor_space[ch]);
5454 to = read_filename_string(ch, f);
5457 ((struct file_name_map *)xmalloc(sizeof(struct file_name_map)));
5459 ptr->map_from = from;
5461 /* Make the real filename absolute. */
5466 ptr->map_to = (char *)xmalloc(dirlen + strlen(to) + 2);
5467 strcpy(ptr->map_to, dirname);
5468 ptr->map_to[dirlen] = '/';
5469 strcpy(ptr->map_to + dirlen + 1, to);
5473 ptr->map_next = map_list_ptr->map_list_map;
5474 map_list_ptr->map_list_map = ptr;
5476 while ((ch = getc(f)) != '\n')
5483 map_list_ptr->map_list_next = CPP_OPTIONS(pfile)->map_list;
5484 CPP_OPTIONS(pfile)->map_list = map_list_ptr;
5486 return map_list_ptr->map_list_map;
5489 /* Try to open include file FILENAME. SEARCHPTR is the directory
5490 * being tried from the include file search path. This function maps
5491 * filenames on file systems based on information read by
5495 open_include_file(cpp_reader * pfile, char *filename,
5496 struct file_name_list *searchptr)
5498 struct file_name_map *map;
5500 const char *p, *dir;
5502 if (searchptr && !searchptr->got_name_map)
5504 searchptr->name_map = read_name_map(pfile,
5506 ? searchptr->fname : ".");
5507 searchptr->got_name_map = 1;
5509 /* First check the mapping for the directory we are using. */
5510 if (searchptr && searchptr->name_map)
5513 if (searchptr->fname)
5514 from += strlen(searchptr->fname) + 1;
5515 for (map = searchptr->name_map; map; map = map->map_next)
5517 if (!strcmp(map->map_from, from))
5519 /* Found a match. */
5520 return open(map->map_to, O_RDONLY, 0666);
5524 /* Try to find a mapping file for the particular directory we are
5525 * looking in. Thus #include <sys/types.h> will look up sys/types.h
5526 * in /usr/include/header.gcc and look up types.h in
5527 * /usr/include/sys/header.gcc. */
5528 p = strrchr(filename, '/');
5533 && strlen(searchptr->fname) == (unsigned)(p - filename)
5534 && !strncmp(searchptr->fname, filename, p - filename))
5536 /* FILENAME is in SEARCHPTR, which we've already checked. */
5537 return open(filename, O_RDONLY, 0666);
5548 s = (char *)alloca(p - filename + 1);
5549 memcpy(s, filename, p - filename);
5550 s[p - filename] = '\0';
5554 for (map = read_name_map(pfile, dir); map; map = map->map_next)
5555 if (!strcmp(map->map_from, from))
5556 return open(map->map_to, O_RDONLY, 0666);
5558 return open(filename, O_RDONLY, 0666);
5564 open_include_file(cpp_reader * pfile, char *filename,
5565 struct file_name_list *searchptr)
5569 return open(filename, O_RDONLY, 0666);
5572 #endif /* USE_FILE_NAME_MAPS */
5574 /* Process the contents of include file FNAME, already open on descriptor F,
5575 * with output to OP.
5576 * SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5577 * "system" include directories (as decided by the `is_system_include'
5579 * DIRPTR is the link in the dir path through which this file was found,
5580 * or 0 if the file name was absolute or via the current directory.
5581 * Return 1 on success, 0 on failure.
5583 * The caller is responsible for the cpp_push_buffer. */
5586 finclude(cpp_reader * pfile, int f, const char *fname, int system_header_p,
5587 struct file_name_list *dirptr)
5593 cpp_buffer *fp; /* For input stack frame */
5595 if (file_size_and_mode(f, &st_mode, &st_size) < 0)
5597 cpp_perror_with_name(pfile, fname);
5599 cpp_pop_buffer(pfile);
5602 fp = CPP_BUFFER(pfile);
5603 fp->nominal_fname = fp->fname = fname;
5605 fp->system_header_p = system_header_p;
5608 fp->cleanup = file_cleanup;
5610 if (S_ISREG(st_mode))
5612 fp->buf = (unsigned char *)xmalloc(st_size + 2);
5613 fp->alimit = fp->buf + st_size + 2;
5616 /* Read the file contents, knowing that st_size is an upper bound
5617 * on the number of bytes we can read. */
5618 length = safe_read(f, (char *)fp->buf, st_size);
5619 fp->rlimit = fp->buf + length;
5623 else if (S_ISDIR(st_mode))
5625 cpp_error(pfile, "directory `%s' specified in #include", fname);
5631 /* Cannot count its file size before reading.
5632 * First read the entire file into heap and
5633 * copy them into buffer on stack. */
5638 fp->buf = (unsigned char *)xmalloc(bsize + 2);
5642 i = safe_read(f, (char *)(fp->buf + st_size), bsize - st_size);
5644 goto nope; /* error! */
5646 if (st_size != bsize)
5647 break; /* End of file */
5649 fp->buf = (unsigned char *)xrealloc(fp->buf, bsize + 2);
5654 if ((length > 0 && fp->buf[length - 1] != '\n')
5655 /* Backslash-newline at end is not good enough. */
5656 || (length > 1 && fp->buf[length - 2] == '\\'))
5658 fp->buf[length++] = '\n';
5660 fp->buf[length] = '\0';
5661 fp->rlimit = fp->buf + length;
5663 /* Close descriptor now, so nesting does not use lots of descriptors. */
5666 /* Must do this before calling trigraph_pcp, so that the correct file name
5667 * will be printed in warning messages. */
5669 pfile->input_stack_listing_current = 0;
5675 cpp_perror_with_name(pfile, fname);
5682 push_parse_file(cpp_reader * pfile, const char *fname)
5684 struct cpp_options *opts = CPP_OPTIONS(pfile);
5685 struct cpp_pending *pend;
5690 /* The code looks at the defaults through this pointer, rather than through
5691 * the constant structure above. This pointer gets changed if an environment
5692 * variable specifies other defaults. */
5693 struct default_include *include_defaults = include_defaults_array;
5695 /* Add dirs from CPATH after dirs from -I. */
5696 /* There seems to be confusion about what CPATH should do,
5697 * so for the moment it is not documented. */
5698 /* Some people say that CPATH should replace the standard include dirs,
5699 * but that seems pointless: it comes before them, so it overrides them
5701 p = (char *)getenv("CPATH");
5702 if (p != 0 && !opts->no_standard_includes)
5703 path_include(pfile, p);
5705 /* Now that dollars_in_ident is known, initialize is_idchar. */
5706 initialize_char_syntax(opts);
5708 /* Do partial setup of input buffer for the sake of generating
5709 * early #line directives (when -g is in effect). */
5710 fp = cpp_push_buffer(pfile, NULL, 0);
5711 if (opts->in_fname == NULL)
5712 opts->in_fname = "";
5713 fp->nominal_fname = fp->fname = opts->in_fname;
5716 /* Install __LINE__, etc. Must follow initialize_char_syntax
5717 * and option processing. */
5718 initialize_builtins(pfile);
5720 /* Do standard #defines and assertions
5721 * that identify system and machine type. */
5723 if (!opts->inhibit_predefs)
5725 p = (char *)alloca(strlen(predefs) + 1);
5732 while (*p == ' ' || *p == '\t')
5734 /* Handle -D options. */
5735 if (p[0] == '-' && p[1] == 'D')
5738 while (*p && *p != ' ' && *p != '\t')
5742 if (opts->debug_output)
5743 output_line_command(pfile, 0, same_file);
5744 cpp_define(pfile, (unsigned char *)q);
5745 while (*p == ' ' || *p == '\t')
5748 else if (p[0] == '-' && p[1] == 'A')
5750 /* Handle -A options (assertions). */
5759 past_name = assertion;
5760 /* Locate end of name. */
5761 while (*past_name && *past_name != ' '
5762 && *past_name != '\t' && *past_name != '(')
5764 /* Locate `(' at start of value. */
5766 while (*value && (*value == ' ' || *value == '\t'))
5768 if (*value++ != '(')
5770 while (*value && (*value == ' ' || *value == '\t'))
5773 /* Locate end of value. */
5774 while (*past_value && *past_value != ' '
5775 && *past_value != '\t' && *past_value != ')')
5777 termination = past_value;
5779 && (*termination == ' ' || *termination == '\t'))
5781 if (*termination++ != ')')
5783 if (*termination && *termination != ' '
5784 && *termination != '\t')
5786 /* Temporarily null-terminate the value. */
5787 save_char = *termination;
5788 *termination = '\0';
5789 /* Install the assertion. */
5790 make_assertion(pfile, "-A", assertion);
5791 *termination = (char)save_char;
5793 while (*p == ' ' || *p == '\t')
5802 /* Now handle the command line options. */
5804 /* Do -U's, -D's and -A's in the order they were seen. */
5805 /* First reverse the list. */
5806 opts->pending = nreverse_pending(opts->pending);
5808 for (pend = opts->pending; pend; pend = pend->next)
5810 if (pend->cmd != NULL && pend->cmd[0] == '-')
5812 switch (pend->cmd[1])
5815 if (opts->debug_output)
5816 output_line_command(pfile, 0, same_file);
5817 do_undef(pfile, NULL, (unsigned char *)pend->arg,
5818 (unsigned char *)pend->arg + strlen(pend->arg));
5821 if (opts->debug_output)
5822 output_line_command(pfile, 0, same_file);
5823 cpp_define(pfile, (unsigned char *)pend->arg);
5826 make_assertion(pfile, "-A", pend->arg);
5832 opts->done_initializing = 1;
5834 { /* read the appropriate environment variable and if it exists
5835 * replace include_defaults with the listed path. */
5838 switch ((opts->objc << 1) + opts->cplusplus)
5841 epath = getenv("C_INCLUDE_PATH");
5844 epath = getenv("CPLUS_INCLUDE_PATH");
5847 epath = getenv("OBJC_INCLUDE_PATH");
5850 epath = getenv("OBJCPLUS_INCLUDE_PATH");
5853 /* If the environment var for this language is set,
5854 * add to the default list of include directories. */
5857 char *nstore = (char *)alloca(strlen(epath) + 2);
5859 char *startp, *endp;
5861 for (num_dirs = 1, startp = epath; *startp; startp++)
5862 if (*startp == PATH_SEPARATOR)
5865 = (struct default_include *)xmalloc((num_dirs
5870 (include_defaults_array));
5872 startp = endp = epath;
5876 /* Handle cases like c:/usr/lib:d:/gcc/lib */
5877 if ((*endp == PATH_SEPARATOR) || *endp == 0)
5879 strncpy(nstore, startp, endp - startp);
5881 strcpy(nstore, ".");
5883 nstore[endp - startp] = '\0';
5885 include_defaults[num_dirs].fname = savestring(nstore);
5886 include_defaults[num_dirs].cplusplus = opts->cplusplus;
5887 include_defaults[num_dirs].cxx_aware = 1;
5891 endp = startp = endp + 1;
5896 /* Put the usual defaults back in at the end. */
5897 memcpy((char *)&include_defaults[num_dirs],
5898 (char *)include_defaults_array,
5899 sizeof(include_defaults_array));
5903 append_include_chain(pfile, opts->before_system, opts->last_before_system);
5904 opts->first_system_include = opts->before_system;
5906 /* Unless -fnostdinc,
5907 * tack on the standard include file dirs to the specified list */
5908 if (!opts->no_standard_includes)
5910 struct default_include *di = include_defaults;
5911 char *specd_prefix = opts->include_prefix;
5912 char *default_prefix = savestring(GCC_INCLUDE_DIR);
5913 int default_len = 0;
5915 /* Remove the `include' from /usr/local/lib/gcc.../include. */
5916 if (!strcmp(default_prefix + strlen(default_prefix) - 8, "/include"))
5918 default_len = strlen(default_prefix) - 7;
5919 default_prefix[default_len] = 0;
5921 /* Search "translated" versions of GNU directories.
5922 * These have /usr/local/lib/gcc... replaced by specd_prefix. */
5923 if (specd_prefix != 0 && default_len != 0)
5924 for (di = include_defaults; di->fname; di++)
5926 /* Some standard dirs are only for C++. */
5929 && !opts->no_standard_cplusplus_includes))
5931 /* Does this dir start with the prefix? */
5932 if (!strncmp(di->fname, default_prefix, default_len))
5934 /* Yes; change prefix and add to search list. */
5935 struct file_name_list *new_
5937 (struct file_name_list *)
5938 xmalloc(sizeof(struct file_name_list));
5940 strlen(specd_prefix) + strlen(di->fname) -
5943 (char *)xmalloc(this_len + 1);
5945 strcpy(str, specd_prefix);
5946 strcat(str, di->fname + default_len);
5948 new_->control_macro = 0;
5949 new_->c_system_include_path = !di->cxx_aware;
5950 new_->got_name_map = 0;
5951 append_include_chain(pfile, new_, new_);
5952 if (opts->first_system_include == 0)
5953 opts->first_system_include = new_;
5957 /* Search ordinary names for GNU include directories. */
5958 for (di = include_defaults; di->fname; di++)
5960 /* Some standard dirs are only for C++. */
5962 || (opts->cplusplus && !opts->no_standard_cplusplus_includes))
5964 struct file_name_list *new_
5965 = (struct file_name_list *)
5966 xmalloc(sizeof(struct file_name_list));
5968 new_->control_macro = 0;
5969 new_->c_system_include_path = !di->cxx_aware;
5970 new_->fname = (char *)di->fname;
5971 new_->got_name_map = 0;
5972 append_include_chain(pfile, new_, new_);
5973 if (opts->first_system_include == 0)
5974 opts->first_system_include = new_;
5978 /* Tack the after_include chain at the end of the include chain. */
5979 append_include_chain(pfile, opts->after_include, opts->last_after_include);
5980 if (opts->first_system_include == 0)
5981 opts->first_system_include = opts->after_include;
5983 /* With -v, print the list of dirs to search. */
5986 struct file_name_list *fl;
5988 fprintf(stderr, "#include \"...\" search starts here:\n");
5989 for (fl = opts->include; fl; fl = fl->next)
5991 if (fl == opts->first_bracket_include)
5992 fprintf(stderr, "#include <...> search starts here:\n");
5993 fprintf(stderr, " %s\n", fl->fname);
5995 fprintf(stderr, "End of search list.\n");
5997 /* Scan the -imacros files before the main input.
5998 * Much like #including them, but with no_output set
5999 * so that only their macro definitions matter. */
6002 pfile->no_record_file++;
6003 for (pend = opts->pending; pend; pend = pend->next)
6005 if (pend->cmd != NULL && strcmp(pend->cmd, "-imacros") == 0)
6007 int fd = open(pend->arg, O_RDONLY, 0666);
6011 cpp_perror_with_name(pfile, pend->arg);
6012 return FATAL_EXIT_CODE;
6014 cpp_push_buffer(pfile, NULL, 0);
6015 finclude(pfile, fd, pend->arg, 0, NULL);
6016 cpp_scan_buffer(pfile);
6020 pfile->no_record_file--;
6022 /* Copy the entire contents of the main input file into
6023 * the stacked input buffer previously allocated for it. */
6024 if (fname == NULL || *fname == 0)
6029 else if ((f = open(fname, O_RDONLY, 0666)) < 0)
6030 cpp_pfatal_with_name(pfile, fname);
6032 /* -MG doesn't select the form of output and must be specified with one of
6033 * -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
6034 * inhibit compilation. */
6035 if (opts->print_deps_missing_files
6036 && (opts->print_deps == 0 || !opts->no_output))
6037 cpp_fatal("-MG must be specified with one of -M or -MM");
6039 /* Either of two environment variables can specify output of deps.
6040 * Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
6041 * where OUTPUT_FILE is the file to write deps info to
6042 * and DEPS_TARGET is the target to mention in the deps. */
6044 if (opts->print_deps == 0
6045 && (getenv("SUNPRO_DEPENDENCIES") != 0
6046 || getenv("DEPENDENCIES_OUTPUT") != 0))
6048 char *spec = getenv("DEPENDENCIES_OUTPUT");
6054 spec = getenv("SUNPRO_DEPENDENCIES");
6055 opts->print_deps = 2;
6058 opts->print_deps = 1;
6061 /* Find the space before the DEPS_TARGET, if there is one. */
6062 /* This should use index. (mrs) */
6063 while (*s != 0 && *s != ' ')
6067 opts->deps_target = s + 1;
6068 output_file = (char *)xmalloc(s - spec + 1);
6069 memcpy(output_file, spec, s - spec);
6070 output_file[s - spec] = 0;
6074 opts->deps_target = 0;
6078 opts->deps_file = output_file;
6079 opts->print_deps_append = 1;
6081 /* For -M, print the expected object file name
6082 * as the target of this Make-rule. */
6083 if (opts->print_deps)
6085 pfile->deps_allocated_size = 200;
6086 pfile->deps_buffer = (char *)xmalloc(pfile->deps_allocated_size);
6087 pfile->deps_buffer[0] = 0;
6088 pfile->deps_size = 0;
6089 pfile->deps_column = 0;
6091 if (opts->deps_target)
6092 deps_output(pfile, opts->deps_target, ':');
6093 else if (*opts->in_fname == 0)
6094 deps_output(pfile, "-", ':');
6100 /* Discard all directory prefixes from filename. */
6101 if ((q = (char *)strrchr(opts->in_fname, '/')) != NULL
6102 #ifdef DIR_SEPARATOR
6103 && (q = strrchr(opts->in_fname, DIR_SEPARATOR)) != NULL
6108 q = (char *)opts->in_fname;
6110 /* Copy remainder to mungable area. */
6111 p = (char *)alloca(strlen(q) + 8);
6114 /* Output P, but remove known suffixes. */
6117 if (len >= 2 && p[len - 2] == '.' && strchr("cCsSm", p[len - 1]))
6120 && p[len - 3] == '.'
6121 && p[len - 2] == 'c' && p[len - 1] == 'c')
6124 && p[len - 4] == '.'
6125 && p[len - 3] == 'c'
6126 && p[len - 2] == 'x' && p[len - 1] == 'x')
6129 && p[len - 4] == '.'
6130 && p[len - 3] == 'c'
6131 && p[len - 2] == 'p' && p[len - 1] == 'p')
6134 /* Supply our own suffix. */
6137 deps_output(pfile, p, ':');
6138 deps_output(pfile, opts->in_fname, ' ');
6142 /* Scan the -include files before the main input.
6143 * We push these in reverse order, so that the first one is handled first. */
6145 pfile->no_record_file++;
6146 opts->pending = nreverse_pending(opts->pending);
6147 for (pend = opts->pending; pend; pend = pend->next)
6149 if (pend->cmd != NULL && strcmp(pend->cmd, "-include") == 0)
6151 int fd = open(pend->arg, O_RDONLY, 0666);
6155 cpp_perror_with_name(pfile, pend->arg);
6156 return FATAL_EXIT_CODE;
6158 cpp_push_buffer(pfile, NULL, 0);
6159 finclude(pfile, fd, pend->arg, 0, NULL);
6162 pfile->no_record_file--;
6164 /* Free the pending list. */
6165 for (pend = opts->pending; pend;)
6167 struct cpp_pending *next = pend->next;
6172 opts->pending = NULL;
6174 if (finclude(pfile, f, fname, 0, NULL))
6175 output_line_command(pfile, 0, same_file);
6176 return SUCCESS_EXIT_CODE;
6180 init_parse_file(cpp_reader * pfile)
6182 memset((char *)pfile, 0, sizeof(cpp_reader));
6183 pfile->get_token = cpp_get_token;
6185 pfile->token_buffer_size = 200;
6186 pfile->token_buffer = (unsigned char *)xmalloc(pfile->token_buffer_size);
6187 CPP_SET_WRITTEN(pfile, 0);
6189 pfile->system_include_depth = 0;
6190 pfile->dont_repeat_files = 0;
6191 pfile->all_include_files = 0;
6192 pfile->max_include_len = 0;
6193 pfile->timebuf = NULL;
6194 pfile->only_seen_white = 1;
6195 pfile->buffer = CPP_NULL_BUFFER(pfile);
6198 static struct cpp_pending *
6199 nreverse_pending(struct cpp_pending *list)
6201 struct cpp_pending *prev = 0, *next, *pend;
6203 for (pend = list; pend; pend = next)
6213 push_pending(cpp_reader * pfile, const char *cmd, const char *arg)
6215 struct cpp_pending *pend
6216 = (struct cpp_pending *)xmalloc(sizeof(struct cpp_pending));
6220 pend->next = CPP_OPTIONS(pfile)->pending;
6221 CPP_OPTIONS(pfile)->pending = pend;
6224 /* Handle command-line options in (argc, argv).
6225 * Can be called multiple times, to handle multiple sets of options.
6226 * Returns if an unrecognized option is seen.
6227 * Returns number of handled arguments. */
6230 cpp_handle_options(cpp_reader * pfile, int argc, char **argv)
6233 struct cpp_options *opts = CPP_OPTIONS(pfile);
6235 for (i = 0; i < argc; i++)
6237 if (argv[i][0] != '-')
6239 if (opts->out_fname != NULL)
6240 cpp_fatal("Usage: %s [switches] input output", argv[0]);
6241 else if (opts->in_fname != NULL)
6242 opts->out_fname = argv[i];
6244 opts->in_fname = argv[i];
6252 if (!strcmp(argv[i], "-include")
6253 || !strcmp(argv[i], "-imacros"))
6256 cpp_fatal("Filename missing after `%s' option",
6259 push_pending(pfile, argv[i], argv[i + 1]), i++;
6261 if (!strcmp(argv[i], "-iprefix"))
6264 cpp_fatal("Filename missing after `-iprefix' option");
6266 opts->include_prefix = argv[++i];
6268 if (!strcmp(argv[i], "-ifoutput"))
6270 opts->output_conditionals = 1;
6272 if (!strcmp(argv[i], "-isystem"))
6274 struct file_name_list *dirtmp;
6277 cpp_fatal("Filename missing after `-isystem' option");
6280 (struct file_name_list
6281 *)xmalloc(sizeof(struct file_name_list));
6284 dirtmp->control_macro = 0;
6285 dirtmp->c_system_include_path = 1;
6286 dirtmp->fname = (char *)xmalloc(strlen(argv[i + 1]) + 1);
6287 strcpy(dirtmp->fname, argv[++i]);
6288 dirtmp->got_name_map = 0;
6290 if (opts->before_system == 0)
6291 opts->before_system = dirtmp;
6293 opts->last_before_system->next = dirtmp;
6294 opts->last_before_system = dirtmp; /* Tail follows the last one */
6296 /* Add directory to end of path for includes,
6297 * with the default prefix at the front of its name. */
6298 if (!strcmp(argv[i], "-iwithprefix"))
6300 struct file_name_list *dirtmp;
6303 if (opts->include_prefix != 0)
6304 prefix = opts->include_prefix;
6307 prefix = savestring(GCC_INCLUDE_DIR);
6308 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6310 (prefix + strlen(prefix) - 8, "/include"))
6311 prefix[strlen(prefix) - 7] = 0;
6315 (struct file_name_list
6316 *)xmalloc(sizeof(struct file_name_list));
6318 dirtmp->next = 0; /* New one goes on the end */
6319 dirtmp->control_macro = 0;
6320 dirtmp->c_system_include_path = 0;
6323 ("Directory name missing after `-iwithprefix' option");
6325 dirtmp->fname = (char *)xmalloc(strlen(argv[i + 1])
6326 + strlen(prefix) + 1);
6327 strcpy(dirtmp->fname, prefix);
6328 strcat(dirtmp->fname, argv[++i]);
6329 dirtmp->got_name_map = 0;
6331 if (opts->after_include == 0)
6332 opts->after_include = dirtmp;
6334 opts->last_after_include->next = dirtmp;
6335 opts->last_after_include = dirtmp; /* Tail follows the last one */
6337 /* Add directory to main path for includes,
6338 * with the default prefix at the front of its name. */
6339 if (!strcmp(argv[i], "-iwithprefixbefore"))
6341 struct file_name_list *dirtmp;
6344 if (opts->include_prefix != 0)
6345 prefix = opts->include_prefix;
6348 prefix = savestring(GCC_INCLUDE_DIR);
6349 /* Remove the `include' from /usr/local/lib/gcc.../include. */
6351 (prefix + strlen(prefix) - 8, "/include"))
6352 prefix[strlen(prefix) - 7] = 0;
6356 (struct file_name_list
6357 *)xmalloc(sizeof(struct file_name_list));
6359 dirtmp->next = 0; /* New one goes on the end */
6360 dirtmp->control_macro = 0;
6361 dirtmp->c_system_include_path = 0;
6364 ("Directory name missing after `-iwithprefixbefore' option");
6366 dirtmp->fname = (char *)xmalloc(strlen(argv[i + 1])
6367 + strlen(prefix) + 1);
6368 strcpy(dirtmp->fname, prefix);
6369 strcat(dirtmp->fname, argv[++i]);
6370 dirtmp->got_name_map = 0;
6372 append_include_chain(pfile, dirtmp, dirtmp);
6374 /* Add directory to end of path for includes. */
6375 if (!strcmp(argv[i], "-idirafter"))
6377 struct file_name_list *dirtmp;
6380 (struct file_name_list
6381 *)xmalloc(sizeof(struct file_name_list));
6383 dirtmp->next = 0; /* New one goes on the end */
6384 dirtmp->control_macro = 0;
6385 dirtmp->c_system_include_path = 0;
6388 ("Directory name missing after `-idirafter' option");
6390 dirtmp->fname = argv[++i];
6391 dirtmp->got_name_map = 0;
6393 if (opts->after_include == 0)
6394 opts->after_include = dirtmp;
6396 opts->last_after_include->next = dirtmp;
6397 opts->last_after_include = dirtmp; /* Tail follows the last one */
6402 if (opts->out_fname != NULL)
6403 cpp_fatal("Output filename specified twice");
6405 cpp_fatal("Filename missing after -o option");
6406 opts->out_fname = argv[++i];
6407 if (!strcmp(opts->out_fname, "-"))
6408 opts->out_fname = "";
6412 if (!strcmp(argv[i], "-pedantic"))
6413 CPP_PEDANTIC(pfile) = 1;
6414 else if (!strcmp(argv[i], "-pedantic-errors"))
6416 CPP_PEDANTIC(pfile) = 1;
6417 opts->pedantic_errors = 1;
6422 if (!strcmp(argv[i], "-traditional"))
6424 opts->traditional = 1;
6425 if (opts->dollars_in_ident > 0)
6426 opts->dollars_in_ident = 1;
6428 else if (!strcmp(argv[i], "-trigraphs"))
6431 opts->no_trigraphs = 0;
6436 if (!strcmp(argv[i], "-lang-c"))
6437 opts->cplusplus = 0, opts->cplusplus_comments =
6439 if (!strcmp(argv[i], "-lang-c++"))
6440 opts->cplusplus = 1, opts->cplusplus_comments =
6442 if (!strcmp(argv[i], "-lang-c-c++-comments"))
6443 opts->cplusplus = 0, opts->cplusplus_comments =
6445 if (!strcmp(argv[i], "-lang-objc"))
6446 opts->objc = 1, opts->cplusplus =
6447 0, opts->cplusplus_comments = 1;
6448 if (!strcmp(argv[i], "-lang-objc++"))
6449 opts->objc = 1, opts->cplusplus =
6450 1, opts->cplusplus_comments = 1;
6451 if (!strcmp(argv[i], "-lang-asm"))
6453 if (!strcmp(argv[i], "-lint"))
6455 if (!strcmp(argv[i], "-lang-chill"))
6456 opts->objc = 0, opts->cplusplus = 0, opts->chill = 1,
6457 opts->traditional = 1, opts->no_trigraphs = 1;
6461 opts->cplusplus = 1, opts->cplusplus_comments = 1;
6465 opts->inhibit_warnings = 1;
6469 if (!strcmp(argv[i], "-Wtrigraphs"))
6470 opts->warn_trigraphs = 1;
6471 else if (!strcmp(argv[i], "-Wno-trigraphs"))
6472 opts->warn_trigraphs = 0;
6473 else if (!strcmp(argv[i], "-Wcomment"))
6474 opts->warn_comments = 1;
6475 else if (!strcmp(argv[i], "-Wno-comment"))
6476 opts->warn_comments = 0;
6477 else if (!strcmp(argv[i], "-Wcomments"))
6478 opts->warn_comments = 1;
6479 else if (!strcmp(argv[i], "-Wno-comments"))
6480 opts->warn_comments = 0;
6481 else if (!strcmp(argv[i], "-Wtraditional"))
6482 opts->warn_stringify = 1;
6483 else if (!strcmp(argv[i], "-Wno-traditional"))
6484 opts->warn_stringify = 0;
6485 else if (!strcmp(argv[i], "-Wimport"))
6486 opts->warn_import = 1;
6487 else if (!strcmp(argv[i], "-Wno-import"))
6488 opts->warn_import = 0;
6489 else if (!strcmp(argv[i], "-Werror"))
6490 opts->warnings_are_errors = 1;
6491 else if (!strcmp(argv[i], "-Wno-error"))
6492 opts->warnings_are_errors = 0;
6493 else if (!strcmp(argv[i], "-Wall"))
6495 opts->warn_trigraphs = 1;
6496 opts->warn_comments = 1;
6501 /* The style of the choices here is a bit mixed.
6502 * The chosen scheme is a hybrid of keeping all options in one string
6503 * and specifying each option in a separate argument:
6504 * -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
6505 * -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
6506 * -M[M][G][D file]. This is awkward to handle in specs, and is not
6508 /* ??? -MG must be specified in addition to one of -M or -MM.
6509 * This can be relaxed in the future without breaking anything.
6510 * The converse isn't true. */
6512 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
6513 if (!strcmp(argv[i], "-MG"))
6515 opts->print_deps_missing_files = 1;
6518 if (!strcmp(argv[i], "-M"))
6519 opts->print_deps = 2;
6520 else if (!strcmp(argv[i], "-MM"))
6521 opts->print_deps = 1;
6522 else if (!strcmp(argv[i], "-MD"))
6523 opts->print_deps = 2;
6524 else if (!strcmp(argv[i], "-MMD"))
6525 opts->print_deps = 1;
6526 /* For -MD and -MMD options, write deps on file named by next arg. */
6527 if (!strcmp(argv[i], "-MD") || !strcmp(argv[i], "-MMD"))
6530 cpp_fatal("Filename missing after %s option",
6532 opts->deps_file = argv[++i];
6536 /* For -M and -MM, write deps on standard output
6537 * and suppress the usual output. */
6538 opts->no_output = 1;
6544 char *p = argv[i] + 2;
6547 while ((c = *p++) != 0)
6549 /* Arg to -d specifies what parts of macros to dump */
6553 opts->dump_macros = dump_only;
6554 opts->no_output = 1;
6557 opts->dump_macros = dump_names;
6560 opts->dump_macros = dump_definitions;
6568 if (argv[i][2] == '3')
6569 opts->debug_output = 1;
6573 fprintf(stderr, "GNU CPP version %s", version_string);
6574 #ifdef TARGET_VERSION
6577 fprintf(stderr, "\n");
6582 opts->print_include_names = 1;
6586 if (argv[i][2] != 0)
6587 push_pending(pfile, "-D", argv[i] + 2);
6588 else if (i + 1 == argc)
6589 cpp_fatal("Macro name missing after -D option");
6591 i++, push_pending(pfile, "-D", argv[i]);
6598 if (argv[i][2] != 0)
6600 else if (i + 1 == argc)
6601 cpp_fatal("Assertion missing after -A option");
6605 if (!strcmp(p, "-"))
6607 struct cpp_pending **ptr;
6609 /* -A- eliminates all predefined macros and assertions.
6610 * Let's include also any that were specified earlier
6611 * on the command line. That way we can get rid of any
6612 * that were passed automatically in from GCC. */
6614 opts->inhibit_predefs = 1;
6615 for (ptr = &opts->pending; *ptr != NULL;)
6617 struct cpp_pending *pend = *ptr;
6619 if (pend->cmd && pend->cmd[0] == '-'
6620 && (pend->cmd[1] == 'D'
6621 || pend->cmd[1] == 'A'))
6632 push_pending(pfile, "-A", p);
6637 case 'U': /* JF #undef something */
6638 if (argv[i][2] != 0)
6639 push_pending(pfile, "-U", argv[i] + 2);
6640 else if (i + 1 == argc)
6641 cpp_fatal("Macro name missing after -U option");
6643 push_pending(pfile, "-U", argv[i + 1]), i++;
6647 opts->put_out_comments = 1;
6650 case 'E': /* -E comes from cc -E; ignore it. */
6654 opts->no_line_commands = 1;
6657 case '$': /* Don't include $ in identifiers. */
6658 opts->dollars_in_ident = 0;
6661 case 'I': /* Add directory to path for includes. */
6663 struct file_name_list *dirtmp;
6665 if (!CPP_OPTIONS(pfile)->ignore_srcdir
6666 && !strcmp(argv[i] + 2, "-"))
6668 CPP_OPTIONS(pfile)->ignore_srcdir = 1;
6669 /* Don't use any preceding -I directories for #include <...>. */
6670 CPP_OPTIONS(pfile)->first_bracket_include = 0;
6675 (struct file_name_list
6676 *)xmalloc(sizeof(struct file_name_list));
6678 dirtmp->next = 0; /* New one goes on the end */
6679 dirtmp->control_macro = 0;
6680 dirtmp->c_system_include_path = 0;
6681 if (argv[i][2] != 0)
6682 dirtmp->fname = argv[i] + 2;
6683 else if (i + 1 == argc)
6685 ("Directory name missing after -I option");
6687 dirtmp->fname = argv[++i];
6688 dirtmp->got_name_map = 0;
6689 append_include_chain(pfile, dirtmp, dirtmp);
6695 if (!strcmp(argv[i], "-nostdinc"))
6696 /* -nostdinc causes no default include directories.
6697 * You must specify all include-file directories with -I. */
6698 opts->no_standard_includes = 1;
6699 else if (!strcmp(argv[i], "-nostdinc++"))
6700 /* -nostdinc++ causes no default C++-specific include directories. */
6701 opts->no_standard_cplusplus_includes = 1;
6705 /* Sun compiler passes undocumented switch "-undef".
6706 * Let's assume it means to inhibit the predefined symbols. */
6707 opts->inhibit_predefs = 1;
6710 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
6711 if (opts->in_fname == NULL)
6713 opts->in_fname = "";
6716 else if (opts->out_fname == NULL)
6718 opts->out_fname = "";
6720 } /* else fall through into error */
6730 cpp_finish(cpp_reader * pfile)
6732 struct cpp_options *opts = CPP_OPTIONS(pfile);
6734 if (opts->print_deps)
6736 /* Stream on which to print the dependency information. */
6739 /* Don't actually write the deps file if compilation has failed. */
6740 if (pfile->errors == 0)
6742 const char *deps_mode =
6743 opts->print_deps_append ? "a" : "w";
6745 if (opts->deps_file == 0)
6746 deps_stream = stdout;
6747 else if ((deps_stream = fopen(opts->deps_file, deps_mode)) == 0)
6748 cpp_pfatal_with_name(pfile, opts->deps_file);
6749 fputs(pfile->deps_buffer, deps_stream);
6750 putc('\n', deps_stream);
6751 if (opts->deps_file)
6753 if (ferror(deps_stream) || fclose(deps_stream) != 0)
6754 cpp_fatal("I/O error on output");
6761 do_assert(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
6762 unsigned char *limit)
6764 long symstart; /* remember where symbol name starts */
6766 int sym_length; /* and how long it is */
6767 struct arglist *tokens = NULL;
6769 if (CPP_PEDANTIC(pfile) && CPP_OPTIONS(pfile)->done_initializing
6770 && !CPP_BUFFER(pfile)->system_header_p)
6771 cpp_pedwarn(pfile, "ANSI C does not allow `#assert'");
6777 cpp_skip_hspace(pfile);
6778 symstart = CPP_WRITTEN(pfile); /* remember where it starts */
6779 parse_name(pfile, GETC());
6780 sym_length = check_macro_name(pfile, pfile->token_buffer + symstart,
6783 cpp_skip_hspace(pfile);
6786 cpp_error(pfile, "missing token-sequence in `#assert'");
6792 tokens = read_token_list(pfile, &error_flag);
6797 cpp_error(pfile, "empty token-sequence in `#assert'");
6800 cpp_skip_hspace(pfile);
6802 if (c != EOF && c != '\n')
6803 cpp_pedwarn(pfile, "junk at end of `#assert'");
6804 skip_rest_of_line(pfile);
6807 /* If this name isn't already an assertion name, make it one.
6808 * Error if it was already in use in some other way. */
6811 ASSERTION_HASHNODE *hp;
6812 const char *symname = (char *)pfile->token_buffer + symstart;
6814 hashf(symname, sym_length, ASSERTION_HASHSIZE);
6815 struct tokenlist_list *value =
6816 (struct tokenlist_list *)xmalloc(sizeof(struct tokenlist_list));
6818 hp = assertion_lookup(pfile, symname, sym_length, hashcode);
6821 if (sym_length == 7 && !strncmp(symname, "defined", sym_length))
6822 cpp_error(pfile, "`defined' redefined as assertion");
6823 hp = assertion_install(pfile, symname, sym_length, hashcode);
6825 /* Add the spec'd token-sequence to the list of such. */
6826 value->tokens = tokens;
6827 value->next = hp->value;
6830 CPP_SET_WRITTEN(pfile, symstart); /* Pop */
6833 CPP_SET_WRITTEN(pfile, symstart); /* Pop */
6834 skip_rest_of_line(pfile);
6839 do_unassert(cpp_reader * pfile, struct directive *keyword, unsigned char *buf,
6840 unsigned char *limit)
6842 long symstart; /* remember where symbol name starts */
6843 int sym_length; /* and how long it is */
6846 struct arglist *tokens = NULL;
6847 int tokens_specified = 0;
6853 if (CPP_PEDANTIC(pfile) && CPP_OPTIONS(pfile)->done_initializing
6854 && !CPP_BUFFER(pfile)->system_header_p)
6855 cpp_pedwarn(pfile, "ANSI C does not allow `#unassert'");
6857 cpp_skip_hspace(pfile);
6859 symstart = CPP_WRITTEN(pfile); /* remember where it starts */
6860 parse_name(pfile, GETC());
6861 sym_length = check_macro_name(pfile, pfile->token_buffer + symstart,
6864 cpp_skip_hspace(pfile);
6869 tokens = read_token_list(pfile, &error_flag);
6874 cpp_error(pfile, "empty token list in `#unassert'");
6877 tokens_specified = 1;
6879 cpp_skip_hspace(pfile);
6881 if (c != EOF && c != '\n')
6882 cpp_error(pfile, "junk at end of `#unassert'");
6883 skip_rest_of_line(pfile);
6886 ASSERTION_HASHNODE *hp;
6887 const char *symname = (char *)pfile->token_buffer + symstart;
6889 hashf(symname, sym_length, ASSERTION_HASHSIZE);
6890 struct tokenlist_list *tail, *prev;
6892 hp = assertion_lookup(pfile, symname, sym_length, hashcode);
6896 /* If no token list was specified, then eliminate this assertion
6898 if (!tokens_specified)
6899 delete_assertion(hp);
6902 /* If a list of tokens was given, then delete any matching list. */
6908 struct tokenlist_list *next = tail->next;
6910 if (compare_token_lists(tail->tokens, tokens))
6915 hp->value = tail->next;
6916 free_token_list(tail->tokens);
6928 CPP_SET_WRITTEN(pfile, symstart); /* Pop */
6931 CPP_SET_WRITTEN(pfile, symstart); /* Pop */
6932 skip_rest_of_line(pfile);
6936 /* Test whether there is an assertion named NAME
6937 * and optionally whether it has an asserted token list TOKENS.
6938 * NAME is not null terminated; its length is SYM_LENGTH.
6939 * If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6942 check_assertion(cpp_reader * pfile, const char *name, int sym_length,
6943 int tokens_specified, struct arglist *tokens)
6945 ASSERTION_HASHNODE *hp;
6946 int hashcode = hashf(name, sym_length, ASSERTION_HASHSIZE);
6948 if (CPP_PEDANTIC(pfile) && !CPP_BUFFER(pfile)->system_header_p)
6949 cpp_pedwarn(pfile, "ANSI C does not allow testing assertions");
6951 hp = assertion_lookup(pfile, name, sym_length, hashcode);
6953 /* It is not an assertion; just return false. */
6956 /* If no token list was specified, then value is 1. */
6957 if (!tokens_specified)
6961 struct tokenlist_list *tail;
6965 /* If a list of tokens was given,
6966 * then succeed if the assertion records a matching list. */
6970 if (compare_token_lists(tail->tokens, tokens))
6975 /* Fail if the assertion has no matching list. */
6980 /* Compare two lists of tokens for equality including order of tokens. */
6983 compare_token_lists(struct arglist *l1, struct arglist *l2)
6987 if (l1->length != l2->length)
6989 if (strncmp(l1->name, l2->name, l1->length))
6995 /* Succeed if both lists end at the same time. */
7000 reverse_token_list(struct arglist *tokens)
7002 struct arglist *prev = 0, *cur, *next;
7004 for (cur = tokens; cur; cur = next)
7013 /* Read a space-separated list of tokens ending in a close parenthesis.
7014 * Return a list of strings, in the order they were written.
7015 * (In case of error, return 0 and store -1 in *ERROR_FLAG.) */
7017 static struct arglist *
7018 read_token_list(cpp_reader * pfile, int *error_flag)
7020 struct arglist *token_ptrs = 0;
7025 FORWARD(1); /* Skip '(' */
7027 /* Loop over the assertion value tokens. */
7030 struct arglist *temp;
7031 long name_written = CPP_WRITTEN(pfile);
7034 cpp_skip_hspace(pfile);
7038 /* Find the end of the token. */
7051 else if (c == '"' || c == '\'')
7054 cpp_get_token(pfile);
7060 while (c != EOF && !is_space[c] && c != '(' && c != ')'
7061 && c != '"' && c != '\'')
7070 length = CPP_WRITTEN(pfile) - name_written;
7071 temp = (struct arglist *)xmalloc(sizeof(struct arglist) + length + 1);
7073 temp->name = (char *)(temp + 1);
7074 memcpy(temp->name, (char *)(pfile->token_buffer + name_written),
7076 temp->name[length] = 0;
7077 temp->next = token_ptrs;
7079 temp->length = length;
7081 CPP_ADJUST_WRITTEN(pfile, -length); /* pop */
7083 if (c == EOF || c == '\n')
7086 "unterminated token sequence following `#' operator");
7091 /* We accumulated the names in reverse order.
7092 * Now reverse them to get the proper order. */
7093 return reverse_token_list(token_ptrs);
7097 free_token_list(struct arglist *tokens)
7101 struct arglist *next = tokens->next;
7109 /* Get the file-mode and data size of the file open on FD
7110 * and store them in *MODE_POINTER and *SIZE_POINTER. */
7113 file_size_and_mode(int fd, int *mode_pointer, long int *size_pointer)
7117 if (fstat(fd, &sbuf) < 0)
7120 *mode_pointer = sbuf.st_mode;
7122 *size_pointer = sbuf.st_size;
7126 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7127 * retrying if necessary. Return a negative value if an error occurs,
7128 * otherwise return the actual number of bytes read,
7129 * which must be LEN unless end-of-file was reached. */
7132 safe_read(int desc, char *ptr, int len)
7138 int nchars = read(desc, ptr, left);
7157 savestring(const char *input)
7159 unsigned size = strlen(input);
7160 char *output = (char *)xmalloc(size + 1);
7162 strcpy(output, input);
7166 /* Initialize PMARK to remember the current position of PFILE. */
7168 parse_set_mark(struct parse_marker *pmark, cpp_reader * pfile)
7170 cpp_buffer *pbuf = CPP_BUFFER(pfile);
7172 pmark->next = pbuf->marks;
7173 pbuf->marks = pmark;
7175 pmark->position = pbuf->cur - pbuf->buf;
7178 /* Cleanup PMARK - we no longer need it. */
7180 parse_clear_mark(struct parse_marker *pmark)
7182 struct parse_marker **pp = &pmark->buf->marks;
7184 for (;; pp = &(*pp)->next)
7187 cpp_fatal("internal error", "in parse_set_mark");
7194 /* Backup the current position of PFILE to that saved in PMARK. */
7197 parse_goto_mark(struct parse_marker *pmark, cpp_reader * pfile)
7199 cpp_buffer *pbuf = CPP_BUFFER(pfile);
7201 if (pbuf != pmark->buf)
7202 cpp_fatal("internal error %s", "parse_goto_mark");
7203 pbuf->cur = pbuf->buf + pmark->position;
7206 /* Reset PMARK to point to the current position of PFILE. (Same
7207 * as parse_clear_mark (PMARK), parse_set_mark (PMARK, PFILE) but faster. */
7210 parse_move_mark(struct parse_marker *pmark, cpp_reader * pfile)
7212 cpp_buffer *pbuf = CPP_BUFFER(pfile);
7214 if (pbuf != pmark->buf)
7215 cpp_fatal("internal error %s", "parse_move_mark");
7216 pmark->position = pbuf->cur - pbuf->buf;
7220 cpp_read_check_assertion(cpp_reader * pfile)
7222 int name_start = CPP_WRITTEN(pfile);
7223 int name_length, name_written;
7226 FORWARD(1); /* Skip '#' */
7227 cpp_skip_hspace(pfile);
7228 parse_name(pfile, GETC());
7229 name_written = CPP_WRITTEN(pfile);
7230 name_length = name_written - name_start;
7231 cpp_skip_hspace(pfile);
7232 if (CPP_BUF_PEEK(CPP_BUFFER(pfile)) == '(')
7235 struct arglist *token_ptrs = read_token_list(pfile, &error_flag);
7237 result = check_assertion(pfile,
7238 (char *)pfile->token_buffer + name_start,
7239 name_length, 1, token_ptrs);
7242 result = check_assertion(pfile,
7243 (char *)pfile->token_buffer + name_start,
7244 name_length, 0, NULL);
7245 CPP_ADJUST_WRITTEN(pfile, -name_length); /* pop */
7250 cpp_print_file_and_line(cpp_reader * pfile)
7252 cpp_buffer *ip = cpp_file_buffer(pfile);
7258 cpp_buf_line_and_col(ip, &line, &col);
7259 cpp_file_line_for_message(pfile, ip->nominal_fname,
7260 line, pfile->show_column ? col : -1);
7265 cpp_error_v(cpp_reader * pfile, const char *msg, va_list args)
7267 cpp_print_containing_files(pfile);
7268 cpp_print_file_and_line(pfile);
7269 cpp_message_v(pfile, 1, msg, args);
7273 cpp_error(cpp_reader * pfile, const char *msg, ...)
7277 va_start(args, msg);
7279 cpp_error_v(pfile, msg, args);
7284 /* Print error message but don't count it. */
7287 cpp_warning_v(cpp_reader * pfile, const char *msg, va_list args)
7289 if (CPP_OPTIONS(pfile)->inhibit_warnings)
7292 if (CPP_OPTIONS(pfile)->warnings_are_errors)
7295 cpp_print_containing_files(pfile);
7296 cpp_print_file_and_line(pfile);
7297 cpp_message_v(pfile, 0, msg, args);
7301 cpp_warning(cpp_reader * pfile, const char *msg, ...)
7305 va_start(args, msg);
7307 cpp_warning_v(pfile, msg, args);
7312 /* Print an error message and maybe count it. */
7315 cpp_pedwarn(cpp_reader * pfile, const char *msg, ...)
7319 va_start(args, msg);
7321 if (CPP_OPTIONS(pfile)->pedantic_errors)
7322 cpp_error_v(pfile, msg, args);
7324 cpp_warning_v(pfile, msg, args);
7330 cpp_error_with_line(cpp_reader * pfile, int line, int column, const char *msg)
7332 cpp_buffer *ip = cpp_file_buffer(pfile);
7334 cpp_print_containing_files(pfile);
7337 cpp_file_line_for_message(pfile, ip->nominal_fname, line, column);
7339 cpp_message(pfile, 1, msg, NULL, NULL, NULL);
7343 cpp_warning_with_line(cpp_reader * pfile, int line, int column, const char *msg)
7347 if (CPP_OPTIONS(pfile)->inhibit_warnings)
7350 if (CPP_OPTIONS(pfile)->warnings_are_errors)
7353 cpp_print_containing_files(pfile);
7355 ip = cpp_file_buffer(pfile);
7358 cpp_file_line_for_message(pfile, ip->nominal_fname, line, column);
7360 cpp_message(pfile, 0, msg, NULL, NULL, NULL);
7364 cpp_pedwarn_with_line(cpp_reader * pfile, int line, int column, const char *msg)
7366 if (CPP_OPTIONS(pfile)->pedantic_errors)
7367 cpp_error_with_line(pfile, column, line, msg);
7369 cpp_warning_with_line(pfile, line, column, msg);
7372 /* Report a warning (or an error if pedantic_errors)
7373 * giving specified file name and line number, not current. */
7376 cpp_pedwarn_with_file_and_line(cpp_reader * pfile,
7377 const char *file, int line,
7378 const char *msg, const char *arg1,
7379 const char *arg2, const char *arg3)
7381 if (!CPP_OPTIONS(pfile)->pedantic_errors
7382 && CPP_OPTIONS(pfile)->inhibit_warnings)
7385 cpp_file_line_for_message(pfile, file, line, -1);
7386 cpp_message(pfile, CPP_OPTIONS(pfile)->pedantic_errors,
7387 msg, arg1, arg2, arg3);
7390 /* This defines "errno" properly for VMS, and gives us EACCES. */
7397 #ifndef HAVE_STRERROR
7398 extern int sys_nerr;
7401 extern const char *const sys_errlist[];
7404 extern char *sys_errlist[];
7407 #endif /* HAVE_STRERROR */
7410 * my_strerror - return the descriptive text associated with an `errno' code.
7414 my_strerror(int errnum)
7418 #ifndef HAVE_STRERROR
7419 result = ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
7421 result = strerror(errnum);
7425 result = "undocumented I/O error";
7430 /* Error including a message from `errno'. */
7433 cpp_error_from_errno(cpp_reader * pfile, const char *name)
7435 cpp_buffer *ip = cpp_file_buffer(pfile);
7437 cpp_print_containing_files(pfile);
7440 cpp_file_line_for_message(pfile, ip->nominal_fname, ip->lineno, -1);
7442 cpp_message(pfile, 1, "%s: %s", name, my_strerror(errno), NULL);
7446 cpp_perror_with_name(cpp_reader * pfile, const char *name)
7448 cpp_message(pfile, 1, "%s: %s: %s", progname, name, my_strerror(errno));
7452 * No pre-compiled header file support.
7454 * Possibly different enum token codes for each C/C++ token.
7456 * Should clean up remaining directives to that do_XXX functions
7457 * only take two arguments and all have command_reads_line.
7459 * Find and cleanup remaining uses of static variables,
7461 * Support for trigraphs.
7463 * Support -dM flag (dump_all_macros).
7465 * Support for_lint flag.