1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92, 93, 1994 Free Software Foundation, Inc.
3 Written by Paul Rubin, June 1986
4 Adapted to ANSI C, Richard Stallman, Jan 1987
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
20 In other words, you are welcome to use, share and improve this program.
21 You are forbidden to forbid anyone else to use, share and improve
22 what you give them. Help stamp out software-hoarding! */
24 typedef unsigned char U_CHAR;
28 #include "../src/config.h"
36 /* The macro EMACS is defined when cpp is distributed as part of Emacs,
37 for the sake of machines with limited C compilers. */
40 #endif /* not EMACS */
42 #ifndef STANDARD_INCLUDE_DIR
43 #define STANDARD_INCLUDE_DIR "/usr/include"
46 #ifndef LOCAL_INCLUDE_DIR
47 #define LOCAL_INCLUDE_DIR "/usr/local/include"
50 #if 0 /* We can't get ptrdiff_t, so I arranged not to need PTR_INT_TYPE. */
52 #define PTR_INT_TYPE ptrdiff_t
54 #define PTR_INT_TYPE long
64 /* By default, colon separates directories in a path. */
65 #ifndef PATH_SEPARATOR
66 #define PATH_SEPARATOR ':'
69 /* In case config.h defines these. */
74 #include <sys/types.h>
82 #include <sys/time.h> /* for __DATE__ and __TIME__ */
83 #include <sys/resource.h>
90 /* This defines "errno" properly for VMS, and gives us EACCES. */
93 /* VMS-specific definitions */
97 #define O_RDONLY 0 /* Open arg for Read/Only */
98 #define O_WRONLY 1 /* Open arg for Write/Only */
99 #define read(fd,buf,size) VMS_read (fd,buf,size)
100 #define write(fd,buf,size) VMS_write (fd,buf,size)
101 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
102 #define fopen(fname,mode) VMS_fopen (fname,mode)
103 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
104 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
105 static char * VMS_strncat ();
106 static int VMS_read ();
107 static int VMS_write ();
108 static int VMS_open ();
109 static FILE * VMS_fopen ();
110 static FILE * VMS_freopen ();
111 static void hack_vms_include_specification ();
112 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
113 #define ino_t vms_ino_t
114 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
116 #define BSTRING /* VMS/GCC supplies the bstring routines */
117 #endif /* __GNUC__ */
120 extern char *index ();
121 extern char *rindex ();
129 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
130 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
132 /* Find the largest host integer type and set its size and type. */
134 #ifndef HOST_BITS_PER_WIDE_INT
136 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
137 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
138 #define HOST_WIDE_INT long
140 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
141 #define HOST_WIDE_INT int
147 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
151 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
154 /* Define a generic NULL if one hasn't already been defined. */
161 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
162 #define GENERIC_PTR void *
164 #define GENERIC_PTR char *
169 #define NULL_PTR ((GENERIC_PTR)0)
172 #ifndef INCLUDE_LEN_FUDGE
173 #define INCLUDE_LEN_FUDGE 0
176 /* Forward declarations. */
182 /* External declarations. */
184 extern char *getenv ();
185 extern FILE *fdopen ();
186 extern char *version_string;
187 extern struct tm *localtime ();
189 #ifndef HAVE_STRERROR
191 #if defined(bsd4_4) || defined(__NetBSD__)
192 extern const char *const sys_errlist[];
194 extern char *sys_errlist[];
196 #else /* HAVE_STERRROR */
200 char *strerror (int,...);
202 extern int parse_escape ();
208 /* Forward declarations. */
215 #if defined(USG) || defined(VMS)
223 /* These functions are declared to return int instead of void since they
224 are going to be placed in a table and some old compilers have trouble with
225 pointers to functions returning void. */
227 static int do_define ();
228 static int do_line ();
229 static int do_include ();
230 static int do_undef ();
231 static int do_error ();
232 static int do_pragma ();
233 static int do_ident ();
235 static int do_xifdef ();
236 static int do_else ();
237 static int do_elif ();
238 static int do_endif ();
239 static int do_sccs ();
240 static int do_once ();
241 static int do_assert ();
242 static int do_unassert ();
243 static int do_warning ();
245 static void add_import ();
246 static void append_include_chain ();
247 static void deps_output ();
248 static void make_undef ();
249 static void make_definition ();
250 static void make_assertion ();
251 static void path_include ();
252 static void initialize_builtins ();
253 static void initialize_char_syntax ();
254 static void dump_arg_n ();
255 static void dump_defn_1 ();
256 static void delete_macro ();
257 static void trigraph_pcp ();
258 static void rescan ();
259 static void finclude ();
260 static void validate_else ();
261 static int comp_def_part ();
262 static void error_from_errno ();
263 static void error_with_line ();
265 void pedwarn_with_line ();
266 static void pedwarn_with_file_and_line ();
267 static void fatal ();
269 static void pfatal_with_name ();
270 static void perror_with_name ();
271 static void pipe_closed ();
272 static void print_containing_files ();
273 static int lookup_import ();
274 static int redundant_include_p ();
275 static is_system_include ();
276 static struct file_name_map *read_name_map ();
277 static char *read_filename_string ();
278 static int open_include_file ();
279 static int check_preconditions ();
280 static void pcfinclude ();
281 static void pcstring_used ();
282 static void write_output ();
283 static int check_macro_name ();
284 static int compare_defs ();
285 static int compare_token_lists ();
286 static int eval_if_expression ();
287 static int discard_comments ();
288 static int change_newlines ();
289 static int line_for_error ();
291 static int file_size_and_mode ();
293 static struct arglist *read_token_list ();
294 static void free_token_list ();
296 static struct hashnode *install ();
297 struct hashnode *lookup ();
299 static struct assertion_hashnode *assertion_install ();
300 static struct assertion_hashnode *assertion_lookup ();
302 static char *xrealloc ();
303 static char *xcalloc ();
304 static char *savestring ();
306 static void delete_assertion ();
307 static void macroexpand ();
308 static void dump_all_macros ();
309 static void conditional_skip ();
310 static void skip_if_group ();
311 static void output_line_command ();
313 /* Last arg to output_line_command. */
314 enum file_change_code {same_file, enter_file, leave_file};
316 static int grow_outbuf ();
317 static int handle_directive ();
318 static void memory_full ();
320 static U_CHAR *macarg1 ();
321 static char *macarg ();
323 static U_CHAR *skip_to_end_of_comment ();
324 static U_CHAR *skip_quoted_string ();
325 static U_CHAR *skip_paren_group ();
326 static char *quote_string ();
328 static char *check_precompiled ();
329 /* static struct macrodef create_definition (); [moved below] */
330 static void dump_single_macro ();
331 static void output_dots ();
333 #ifndef FAILURE_EXIT_CODE
334 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
337 #ifndef SUCCESS_EXIT_CODE
338 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
341 /* Name under which this program was invoked. */
343 static char *progname;
345 /* Nonzero means use extra default include directories for C++. */
347 static int cplusplus;
349 /* Nonzero means handle cplusplus style comments */
351 static int cplusplus_comments;
353 /* Nonzero means handle #import, for objective C. */
357 /* Nonzero means this is an assembly file, and allow
358 unknown directives, which could be comments. */
362 /* Current maximum length of directory names in the search path
363 for include files. (Altered as we get more of them.) */
365 static int max_include_len;
367 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
369 static int for_lint = 0;
371 /* Nonzero means copy comments into the output file. */
373 static int put_out_comments = 0;
375 /* Nonzero means don't process the ANSI trigraph sequences. */
377 static int no_trigraphs = 0;
379 /* Nonzero means print the names of included files rather than
380 the preprocessed output. 1 means just the #include "...",
381 2 means #include <...> as well. */
383 static int print_deps = 0;
385 /* Nonzero if missing .h files in -M output are assumed to be generated
386 files and not errors. */
388 static int print_deps_missing_files = 0;
390 /* Nonzero means print names of header files (-H). */
392 static int print_include_names = 0;
394 /* Nonzero means don't output line number information. */
396 static int no_line_commands;
398 /* dump_only means inhibit output of the preprocessed text
399 and instead output the definitions of all user-defined
400 macros in a form suitable for use as input to cccp.
401 dump_names means pass #define and the macro name through to output.
402 dump_definitions means pass the whole definition (plus #define) through
405 static enum {dump_none, dump_only, dump_names, dump_definitions}
406 dump_macros = dump_none;
408 /* Nonzero means pass all #define and #undef directives which we actually
409 process through to the output stream. This feature is used primarily
410 to allow cc1 to record the #defines and #undefs for the sake of
411 debuggers which understand about preprocessor macros, but it may
412 also be useful with -E to figure out how symbols are defined, and
413 where they are defined. */
414 static int debug_output = 0;
416 /* Nonzero indicates special processing used by the pcp program. The
417 special effects of this mode are:
419 Inhibit all macro expansion, except those inside #if directives.
421 Process #define directives normally, and output their contents
424 Output preconditions to pcp_outfile indicating all the relevant
425 preconditions for use of this file in a later cpp run.
427 static FILE *pcp_outfile;
429 /* Nonzero means we are inside an IF during a -pcp run. In this mode
430 macro expansion is done, and preconditions are output for all macro
431 uses requiring them. */
432 static int pcp_inside_if;
434 /* Nonzero means never to include precompiled files.
435 This is 1 since there's no way now to make precompiled files,
436 so it's not worth testing for them. */
437 static int no_precomp = 1;
439 /* Nonzero means give all the error messages the ANSI standard requires. */
443 /* Nonzero means try to make failure to fit ANSI C an error. */
445 static int pedantic_errors;
447 /* Nonzero means don't print warning messages. -w. */
449 static int inhibit_warnings = 0;
451 /* Nonzero means warn if slash-star appears in a comment. */
453 static int warn_comments;
455 /* Nonzero means warn if a macro argument is (or would be)
456 stringified with -traditional. */
458 static int warn_stringify;
460 /* Nonzero means warn if there are any trigraphs. */
462 static int warn_trigraphs;
464 /* Nonzero means warn if #import is used. */
466 static int warn_import = 1;
468 /* Nonzero means turn warnings into errors. */
470 static int warnings_are_errors;
472 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
476 /* Nonzero causes output not to be done,
477 but directives such as #define that have side effects
480 static int no_output;
482 /* Nonzero means this file was included with a -imacros or -include
483 command line and should not be recorded as an include file. */
485 static int no_record_file;
487 /* Nonzero means that we have finished processing the command line options.
488 This flag is used to decide whether or not to issue certain errors
491 static int done_initializing = 0;
493 /* Line where a newline was first seen in a string constant. */
495 static int multiline_string_line = 0;
497 /* I/O buffer structure.
498 The `fname' field is nonzero for source files and #include files
499 and for the dummy text used for -D and -U.
500 It is zero for rescanning results of macro expansion
501 and for expanding macro arguments. */
502 #define INPUT_STACK_MAX 400
503 static struct file_buf {
505 /* Filename specified with #line command. */
507 /* Record where in the search path this file was found.
508 For #include_next. */
509 struct file_name_list *dir;
514 /* Macro that this level is the expansion of.
515 Included so that we can reenable the macro
516 at the end of this level. */
517 struct hashnode *macro;
518 /* Value of if_stack at start of this file.
519 Used to prohibit unmatched #endif (etc) in an include file. */
520 struct if_stack *if_stack;
521 /* Object to be freed at end of input at this level. */
523 /* True if this is a header file included using <FILENAME>. */
524 char system_header_p;
525 } instack[INPUT_STACK_MAX];
527 static int last_error_tick; /* Incremented each time we print it. */
528 static int input_file_stack_tick; /* Incremented when the status changes. */
530 /* Current nesting level of input sources.
531 `instack[indepth]' is the level currently being read. */
532 static int indepth = -1;
533 #define CHECK_DEPTH(code) \
534 if (indepth >= (INPUT_STACK_MAX - 1)) \
536 error_with_line (line_for_error (instack[indepth].lineno), \
537 "macro or `#include' recursion too deep"); \
541 /* Current depth in #include directives that use <...>. */
542 static int system_include_depth = 0;
544 typedef struct file_buf FILE_BUF;
546 /* The output buffer. Its LENGTH field is the amount of room allocated
547 for the buffer, not the number of chars actually present. To get
548 that, subtract outbuf.buf from outbuf.bufp. */
550 #define OUTBUF_SIZE 10 /* initial size of output buffer */
551 static FILE_BUF outbuf;
553 /* Grow output buffer OBUF points at
554 so it can hold at least NEEDED more chars. */
556 #define check_expand(OBUF, NEEDED) \
557 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
558 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
560 struct file_name_list
562 struct file_name_list *next;
564 /* If the following is nonzero, it is a macro name.
565 Don't include the file again if that macro is defined. */
566 U_CHAR *control_macro;
567 /* If the following is nonzero, it is a C-language system include
569 int c_system_include_path;
570 /* Mapping of file names for this directory. */
571 struct file_name_map *name_map;
572 /* Non-zero if name_map is valid. */
576 /* #include "file" looks in source file dir, then stack. */
577 /* #include <file> just looks in the stack. */
578 /* -I directories are added to the end, then the defaults are added. */
580 static struct default_include {
581 char *fname; /* The name of the directory. */
582 int cplusplus; /* Only look here if we're compiling C++. */
583 int cxx_aware; /* Includes in this directory don't need to
584 be wrapped in extern "C" when compiling
586 } include_defaults_array[]
587 #ifdef INCLUDE_DEFAULTS
591 /* Pick up GNU C++ specific include files. */
592 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
594 /* This is the dir for fixincludes. Put it just before
595 the files that we fix. */
596 { GCC_INCLUDE_DIR, 0, 0 },
597 /* For cross-compilation, this dir name is generated
598 automatically in Makefile.in. */
599 { CROSS_INCLUDE_DIR, 0, 0 },
600 /* This is another place that the target system's headers might be. */
601 { TOOL_INCLUDE_DIR, 0, 1 },
602 #else /* not CROSS_COMPILE */
603 /* This should be /usr/local/include and should come before
604 the fixincludes-fixed header files. */
605 { LOCAL_INCLUDE_DIR, 0, 1 },
606 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
607 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
608 { TOOL_INCLUDE_DIR, 0, 1 },
609 /* This is the dir for fixincludes. Put it just before
610 the files that we fix. */
611 { GCC_INCLUDE_DIR, 0, 0 },
612 /* Some systems have an extra dir of include files. */
613 #ifdef SYSTEM_INCLUDE_DIR
614 { SYSTEM_INCLUDE_DIR, 0, 0 },
616 { STANDARD_INCLUDE_DIR, 0, 0 },
617 #endif /* not CROSS_COMPILE */
620 #endif /* no INCLUDE_DEFAULTS */
622 /* The code looks at the defaults through this pointer, rather than through
623 the constant structure above. This pointer gets changed if an environment
624 variable specifies other defaults. */
625 static struct default_include *include_defaults = include_defaults_array;
627 static struct file_name_list *include = 0; /* First dir to search */
628 /* First dir to search for <file> */
629 /* This is the first element to use for #include <...>.
630 If it is 0, use the entire chain for such includes. */
631 static struct file_name_list *first_bracket_include = 0;
632 /* This is the first element in the chain that corresponds to
633 a directory of system header files. */
634 static struct file_name_list *first_system_include = 0;
635 static struct file_name_list *last_include = 0; /* Last in chain */
637 /* Chain of include directories to put at the end of the other chain. */
638 static struct file_name_list *after_include = 0;
639 static struct file_name_list *last_after_include = 0; /* Last in chain */
641 /* Chain to put at the start of the system include files. */
642 static struct file_name_list *before_system = 0;
643 static struct file_name_list *last_before_system = 0; /* Last in chain */
645 /* List of included files that contained #pragma once. */
646 static struct file_name_list *dont_repeat_files = 0;
648 /* List of other included files.
649 If ->control_macro if nonzero, the file had a #ifndef
650 around the entire contents, and ->control_macro gives the macro name. */
651 static struct file_name_list *all_include_files = 0;
653 /* Directory prefix that should replace `/usr' in the standard
654 include file directories. */
655 static char *include_prefix;
657 /* Global list of strings read in from precompiled files. This list
658 is kept in the order the strings are read in, with new strings being
659 added at the end through stringlist_tailp. We use this list to output
660 the strings at the end of the run.
662 static STRINGDEF *stringlist;
663 static STRINGDEF **stringlist_tailp = &stringlist;
666 /* Structure returned by create_definition */
667 typedef struct macrodef MACRODEF;
670 struct definition *defn;
675 static struct macrodef create_definition ();
678 /* Structure allocated for every #define. For a simple replacement
681 nargs = -1, the `pattern' list is null, and the expansion is just
682 the replacement text. Nargs = 0 means a functionlike macro with no args,
684 #define getchar() getc (stdin) .
685 When there are args, the expansion is the replacement text with the
686 args squashed out, and the reflist is a list describing how to
687 build the output from the input: e.g., "3 chars, then the 1st arg,
688 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
689 The chars here come from the expansion. Whatever is left of the
690 expansion after the last arg-occurrence is copied after that arg.
691 Note that the reflist can be arbitrarily long---
692 its length depends on the number of times the arguments appear in
693 the replacement text, not how many args there are. Example:
694 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
696 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
697 where (x, y) means (nchars, argno). */
699 typedef struct definition DEFINITION;
702 int length; /* length of expansion string */
703 int predefined; /* True if the macro was builtin or */
704 /* came from the command line */
706 int line; /* Line number of definition */
707 char *file; /* File of definition */
708 char rest_args; /* Nonzero if last arg. absorbs the rest */
710 struct reflist *next;
711 char stringify; /* nonzero if this arg was preceded by a
713 char raw_before; /* Nonzero if a ## operator before arg. */
714 char raw_after; /* Nonzero if a ## operator after arg. */
715 char rest_args; /* Nonzero if this arg. absorbs the rest */
716 int nchars; /* Number of literal chars to copy before
717 this arg occurrence. */
718 int argno; /* Number of arg to substitute (origin-0) */
721 /* Names of macro args, concatenated in reverse order
722 with comma-space between them.
723 The only use of this is that we warn on redefinition
724 if this differs between the old and new definitions. */
729 /* different kinds of things that can appear in the value field
730 of a hash node. Actually, this may be useless now. */
739 * special extension string that can be added to the last macro argument to
740 * allow it to absorb the "rest" of the arguments when expanded. Ex:
741 * #define wow(a, b...) process (b, a, b)
742 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
743 * { wow (one, two); } -> { process (two, one, two); }
744 * if this "rest_arg" is used with the concat token '##' and if it is not
745 * supplied then the token attached to with ## will not be outputted. Ex:
746 * #define wow (a, b...) process (b ## , a, ## b)
747 * { wow (1, 2); } -> { process (2, 1, 2); }
748 * { wow (one); } -> { process (one); {
750 static char rest_extension[] = "...";
751 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
753 /* The structure of a node in the hash table. The hash table
754 has entries for all tokens defined by #define commands (type T_MACRO),
755 plus some special tokens like __LINE__ (these each have their own
756 type, and the appropriate code is run when that type of node is seen.
757 It does not contain control words like "#define", which are recognized
758 by a separate piece of code. */
760 /* different flavors of hash nodes --- also used in keyword table */
762 T_DEFINE = 1, /* the `#define' keyword */
763 T_INCLUDE, /* the `#include' keyword */
764 T_INCLUDE_NEXT, /* the `#include_next' keyword */
765 T_IMPORT, /* the `#import' keyword */
766 T_IFDEF, /* the `#ifdef' keyword */
767 T_IFNDEF, /* the `#ifndef' keyword */
768 T_IF, /* the `#if' keyword */
769 T_ELSE, /* `#else' */
770 T_PRAGMA, /* `#pragma' */
771 T_ELIF, /* `#elif' */
772 T_UNDEF, /* `#undef' */
773 T_LINE, /* `#line' */
774 T_ERROR, /* `#error' */
775 T_WARNING, /* `#warning' */
776 T_ENDIF, /* `#endif' */
777 T_SCCS, /* `#sccs', used on system V. */
778 T_IDENT, /* `#ident', used on system V. */
779 T_ASSERT, /* `#assert', taken from system V. */
780 T_UNASSERT, /* `#unassert', taken from system V. */
781 T_SPECLINE, /* special symbol `__LINE__' */
782 T_DATE, /* `__DATE__' */
783 T_FILE, /* `__FILE__' */
784 T_BASE_FILE, /* `__BASE_FILE__' */
785 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
786 T_VERSION, /* `__VERSION__' */
787 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
788 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
789 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
790 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
791 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
792 T_TIME, /* `__TIME__' */
793 T_CONST, /* Constant value, used by `__STDC__' */
794 T_MACRO, /* macro defined by `#define' */
795 T_DISABLED, /* macro temporarily turned off for rescan */
796 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
797 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
798 T_UNUSED /* Used for something not defined. */
802 struct hashnode *next; /* double links for easy deletion */
803 struct hashnode *prev;
804 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
805 chain is kept, in case the node is the head
806 of the chain and gets deleted. */
807 enum node_type type; /* type of special token */
808 int length; /* length of token, for quick comparison */
809 U_CHAR *name; /* the actual name */
810 union hashval value; /* pointer to expansion, or whatever */
813 typedef struct hashnode HASHNODE;
815 /* Some definitions for the hash table. The hash function MUST be
816 computed as shown in hashf () below. That is because the rescan
817 loop computes the hash value `on the fly' for most tokens,
818 in order to avoid the overhead of a lot of procedure calls to
819 the hashf () function. Hashf () only exists for the sake of
820 politeness, for use when speed isn't so important. */
822 #define HASHSIZE 1403
823 static HASHNODE *hashtab[HASHSIZE];
824 #define HASHSTEP(old, c) ((old << 2) + c)
825 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
827 /* Symbols to predefine. */
829 #ifdef CPP_PREDEFINES
830 static char *predefs = CPP_PREDEFINES;
832 static char *predefs = "";
835 /* We let tm.h override the types used here, to handle trivial differences
836 such as the choice of unsigned int or long unsigned int for size_t.
837 When machines start needing nontrivial differences in the size type,
838 it would be best to do something here to figure out automatically
839 from other information what type to use. */
841 /* The string value for __SIZE_TYPE__. */
844 #define SIZE_TYPE "long unsigned int"
847 /* The string value for __PTRDIFF_TYPE__. */
850 #define PTRDIFF_TYPE "long int"
853 /* The string value for __WCHAR_TYPE__. */
856 #define WCHAR_TYPE "int"
858 char * wchar_type = WCHAR_TYPE;
861 /* The string value for __USER_LABEL_PREFIX__ */
863 #ifndef USER_LABEL_PREFIX
864 #define USER_LABEL_PREFIX ""
867 /* The string value for __REGISTER_PREFIX__ */
869 #ifndef REGISTER_PREFIX
870 #define REGISTER_PREFIX ""
873 /* In the definition of a #assert name, this structure forms
874 a list of the individual values asserted.
875 Each value is itself a list of "tokens".
876 These are strings that are compared by name. */
878 struct tokenlist_list {
879 struct tokenlist_list *next;
880 struct arglist *tokens;
883 struct assertion_hashnode {
884 struct assertion_hashnode *next; /* double links for easy deletion */
885 struct assertion_hashnode *prev;
886 /* also, a back pointer to this node's hash
887 chain is kept, in case the node is the head
888 of the chain and gets deleted. */
889 struct assertion_hashnode **bucket_hdr;
890 int length; /* length of token, for quick comparison */
891 U_CHAR *name; /* the actual name */
892 /* List of token-sequences. */
893 struct tokenlist_list *value;
896 typedef struct assertion_hashnode ASSERTION_HASHNODE;
898 /* Some definitions for the hash table. The hash function MUST be
899 computed as shown in hashf below. That is because the rescan
900 loop computes the hash value `on the fly' for most tokens,
901 in order to avoid the overhead of a lot of procedure calls to
902 the hashf function. hashf only exists for the sake of
903 politeness, for use when speed isn't so important. */
905 #define ASSERTION_HASHSIZE 37
906 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
908 /* Nonzero means inhibit macroexpansion of what seem to be
909 assertion tests, in rescan. For #if. */
910 static int assertions_flag;
912 /* `struct directive' defines one #-directive, including how to handle it. */
915 int length; /* Length of name */
916 int (*func)(); /* Function to handle directive */
917 char *name; /* Name of directive */
918 enum node_type type; /* Code which describes which directive. */
919 char angle_brackets; /* Nonzero => <...> is special. */
920 char traditional_comments; /* Nonzero: keep comments if -traditional. */
921 char pass_thru; /* Copy preprocessed directive to output file. */
924 /* Here is the actual list of #-directives, most-often-used first. */
926 static struct directive directive_table[] = {
927 { 6, do_define, "define", T_DEFINE, 0, 1},
928 { 2, do_if, "if", T_IF},
929 { 5, do_xifdef, "ifdef", T_IFDEF},
930 { 6, do_xifdef, "ifndef", T_IFNDEF},
931 { 5, do_endif, "endif", T_ENDIF},
932 { 4, do_else, "else", T_ELSE},
933 { 4, do_elif, "elif", T_ELIF},
934 { 4, do_line, "line", T_LINE},
935 { 7, do_include, "include", T_INCLUDE, 1},
936 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
937 { 6, do_include, "import", T_IMPORT, 1},
938 { 5, do_undef, "undef", T_UNDEF},
939 { 5, do_error, "error", T_ERROR},
940 { 7, do_warning, "warning", T_WARNING},
941 #ifdef SCCS_DIRECTIVE
942 { 4, do_sccs, "sccs", T_SCCS},
944 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
945 { 5, do_ident, "ident", T_IDENT},
946 { 6, do_assert, "assert", T_ASSERT},
947 { 8, do_unassert, "unassert", T_UNASSERT},
948 { -1, 0, "", T_UNUSED},
951 /* When a directive handler is called,
952 this points to the # that started the directive. */
953 U_CHAR *directive_start;
955 /* table to tell if char can be part of a C identifier. */
956 U_CHAR is_idchar[256];
957 /* table to tell if char can be first char of a c identifier. */
958 U_CHAR is_idstart[256];
959 /* table to tell if c is horizontal space. */
960 U_CHAR is_hor_space[256];
961 /* table to tell if c is horizontal or vertical space. */
962 static U_CHAR is_space[256];
964 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
965 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
967 static int errors = 0; /* Error counter for exit code */
969 /* Name of output file, for error messages. */
970 static char *out_fname;
972 /* Zero means dollar signs are punctuation.
973 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
974 This must be 0 for correct processing of this ANSI C program:
976 #define lose(b) foo (b)
979 static int dollars_in_ident;
980 #ifndef DOLLARS_IN_IDENTIFIERS
981 #define DOLLARS_IN_IDENTIFIERS 1
984 static FILE_BUF expand_to_temp_buffer ();
986 static DEFINITION *collect_expansion ();
988 /* Stack of conditionals currently in progress
989 (including both successful and failing conditionals). */
992 struct if_stack *next; /* for chaining to the next stack frame */
993 char *fname; /* copied from input when frame is made */
994 int lineno; /* similarly */
995 int if_succeeded; /* true if a leg of this if-group
996 has been passed through rescan */
997 U_CHAR *control_macro; /* For #ifndef at start of file,
998 this is the macro name tested. */
999 enum node_type type; /* type of last directive seen in this group */
1001 typedef struct if_stack IF_STACK_FRAME;
1002 static IF_STACK_FRAME *if_stack = NULL;
1004 /* Buffer of -M output. */
1005 static char *deps_buffer;
1007 /* Number of bytes allocated in above. */
1008 static int deps_allocated_size;
1010 /* Number of bytes used. */
1011 static int deps_size;
1013 /* Number of bytes since the last newline. */
1014 static int deps_column;
1016 /* Nonzero means -I- has been seen,
1017 so don't look for #include "foo" the source-file directory. */
1018 static int ignore_srcdir;
1020 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1021 retrying if necessary. Return a negative value if an error occurs,
1022 otherwise return the actual number of bytes read,
1023 which must be LEN unless end-of-file was reached. */
1026 safe_read (desc, ptr, len)
1033 int nchars = read (desc, ptr, left);
1050 /* Write LEN bytes at PTR to descriptor DESC,
1051 retrying if necessary, and treating any real error as fatal. */
1054 safe_write (desc, ptr, len)
1060 int written = write (desc, ptr, len);
1067 pfatal_with_name (out_fname);
1085 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1086 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1087 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1088 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1089 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1091 /* Record the option used with each element of pend_assertions.
1092 This is preparation for supporting more than one option for making
1094 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1095 int inhibit_predefs = 0;
1096 int no_standard_includes = 0;
1097 int no_standard_cplusplus_includes = 0;
1098 int missing_newline = 0;
1100 /* Non-0 means don't output the preprocessed program. */
1101 int inhibit_output = 0;
1102 /* Non-0 means -v, so print the full set of include dirs. */
1105 /* File name which deps are being written to.
1106 This is 0 if deps are being written to stdout. */
1107 char *deps_file = 0;
1108 /* Fopen file mode to open deps_file with. */
1109 char *deps_mode = "a";
1110 /* Stream on which to print the dependency information. */
1111 FILE *deps_stream = 0;
1112 /* Target-name to write with the dependency information. */
1113 char *deps_target = 0;
1116 /* Get rid of any avoidable limit on stack size. */
1120 /* Set the stack limit huge so that alloca (particularly stringtab
1121 * in dbxread.c) does not fail. */
1122 getrlimit (RLIMIT_STACK, &rlim);
1123 rlim.rlim_cur = rlim.rlim_max;
1124 setrlimit (RLIMIT_STACK, &rlim);
1126 #endif /* RLIMIT_STACK defined */
1129 signal (SIGPIPE, pipe_closed);
1132 p = argv[0] + strlen (argv[0]);
1133 while (p != argv[0] && p[-1] != '/') --p;
1138 /* Remove directories from PROGNAME. */
1141 progname = savestring (argv[0]);
1143 if (!(s = rindex (progname, ']')))
1144 s = rindex (progname, ':');
1146 strcpy (progname, s+1);
1147 if (s = rindex (progname, '.'))
1155 /* Initialize is_idchar to allow $. */
1156 dollars_in_ident = 1;
1157 initialize_char_syntax ();
1158 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1160 no_line_commands = 0;
1162 dump_macros = dump_none;
1165 cplusplus_comments = 0;
1167 bzero ((char *) pend_files, argc * sizeof (char *));
1168 bzero ((char *) pend_defs, argc * sizeof (char *));
1169 bzero ((char *) pend_undefs, argc * sizeof (char *));
1170 bzero ((char *) pend_assertions, argc * sizeof (char *));
1171 bzero ((char *) pend_includes, argc * sizeof (char *));
1173 /* Process switches and find input file name. */
1175 for (i = 1; i < argc; i++) {
1176 if (argv[i][0] != '-') {
1177 if (out_fname != NULL)
1178 fatal ("Usage: %s [switches] input output", argv[0]);
1179 else if (in_fname != NULL)
1180 out_fname = argv[i];
1184 switch (argv[i][1]) {
1187 if (!strcmp (argv[i], "-include")) {
1189 fatal ("Filename missing after `-include' option");
1191 pend_includes[i] = argv[i+1], i++;
1193 if (!strcmp (argv[i], "-imacros")) {
1195 fatal ("Filename missing after `-imacros' option");
1197 pend_files[i] = argv[i+1], i++;
1199 if (!strcmp (argv[i], "-iprefix")) {
1201 fatal ("Filename missing after `-iprefix' option");
1203 include_prefix = argv[++i];
1205 if (!strcmp (argv[i], "-isystem")) {
1206 struct file_name_list *dirtmp;
1209 fatal ("Filename missing after `-isystem' option");
1211 dirtmp = (struct file_name_list *)
1212 xmalloc (sizeof (struct file_name_list));
1214 dirtmp->control_macro = 0;
1215 dirtmp->c_system_include_path = 1;
1216 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
1217 strcpy (dirtmp->fname, argv[++i]);
1218 dirtmp->got_name_map = 0;
1220 if (before_system == 0)
1221 before_system = dirtmp;
1223 last_before_system->next = dirtmp;
1224 last_before_system = dirtmp; /* Tail follows the last one */
1226 /* Add directory to end of path for includes,
1227 with the default prefix at the front of its name. */
1228 if (!strcmp (argv[i], "-iwithprefix")) {
1229 struct file_name_list *dirtmp;
1232 if (include_prefix != 0)
1233 prefix = include_prefix;
1235 prefix = savestring (GCC_INCLUDE_DIR);
1236 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1237 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1238 prefix[strlen (prefix) - 7] = 0;
1241 dirtmp = (struct file_name_list *)
1242 xmalloc (sizeof (struct file_name_list));
1243 dirtmp->next = 0; /* New one goes on the end */
1244 dirtmp->control_macro = 0;
1245 dirtmp->c_system_include_path = 0;
1247 fatal ("Directory name missing after `-iwithprefix' option");
1249 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1250 + strlen (prefix) + 1);
1251 strcpy (dirtmp->fname, prefix);
1252 strcat (dirtmp->fname, argv[++i]);
1253 dirtmp->got_name_map = 0;
1255 if (after_include == 0)
1256 after_include = dirtmp;
1258 last_after_include->next = dirtmp;
1259 last_after_include = dirtmp; /* Tail follows the last one */
1261 /* Add directory to main path for includes,
1262 with the default prefix at the front of its name. */
1263 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1264 struct file_name_list *dirtmp;
1267 if (include_prefix != 0)
1268 prefix = include_prefix;
1270 prefix = savestring (GCC_INCLUDE_DIR);
1271 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1272 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1273 prefix[strlen (prefix) - 7] = 0;
1276 dirtmp = (struct file_name_list *)
1277 xmalloc (sizeof (struct file_name_list));
1278 dirtmp->next = 0; /* New one goes on the end */
1279 dirtmp->control_macro = 0;
1280 dirtmp->c_system_include_path = 0;
1282 fatal ("Directory name missing after `-iwithprefixbefore' option");
1284 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1285 + strlen (prefix) + 1);
1286 strcpy (dirtmp->fname, prefix);
1287 strcat (dirtmp->fname, argv[++i]);
1288 dirtmp->got_name_map = 0;
1290 append_include_chain (dirtmp, dirtmp);
1292 /* Add directory to end of path for includes. */
1293 if (!strcmp (argv[i], "-idirafter")) {
1294 struct file_name_list *dirtmp;
1296 dirtmp = (struct file_name_list *)
1297 xmalloc (sizeof (struct file_name_list));
1298 dirtmp->next = 0; /* New one goes on the end */
1299 dirtmp->control_macro = 0;
1300 dirtmp->c_system_include_path = 0;
1302 fatal ("Directory name missing after `-idirafter' option");
1304 dirtmp->fname = argv[++i];
1305 dirtmp->got_name_map = 0;
1307 if (after_include == 0)
1308 after_include = dirtmp;
1310 last_after_include->next = dirtmp;
1311 last_after_include = dirtmp; /* Tail follows the last one */
1316 if (out_fname != NULL)
1317 fatal ("Output filename specified twice");
1319 fatal ("Filename missing after -o option");
1320 out_fname = argv[++i];
1321 if (!strcmp (out_fname, "-"))
1326 if (!strcmp (argv[i], "-pedantic"))
1328 else if (!strcmp (argv[i], "-pedantic-errors")) {
1330 pedantic_errors = 1;
1331 } else if (!strcmp (argv[i], "-pcp")) {
1332 char *pcp_fname = argv[++i];
1334 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1335 ? fopen (pcp_fname, "w")
1336 : fdopen (dup (fileno (stdout)), "w"));
1337 if (pcp_outfile == 0)
1338 pfatal_with_name (pcp_fname);
1344 if (!strcmp (argv[i], "-traditional")) {
1346 if (dollars_in_ident > 0)
1347 dollars_in_ident = 1;
1348 } else if (!strcmp (argv[i], "-trigraphs")) {
1354 if (! strcmp (argv[i], "-lang-c"))
1355 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1356 if (! strcmp (argv[i], "-lang-c++"))
1357 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1358 if (! strcmp (argv[i], "-lang-c-c++-comments"))
1359 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1360 if (! strcmp (argv[i], "-lang-objc"))
1361 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1362 if (! strcmp (argv[i], "-lang-objc++"))
1363 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1364 if (! strcmp (argv[i], "-lang-asm"))
1366 if (! strcmp (argv[i], "-lint"))
1371 cplusplus = 1, cplusplus_comments = 1;
1375 inhibit_warnings = 1;
1379 if (!strcmp (argv[i], "-Wtrigraphs"))
1381 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1383 else if (!strcmp (argv[i], "-Wcomment"))
1385 else if (!strcmp (argv[i], "-Wno-comment"))
1387 else if (!strcmp (argv[i], "-Wcomments"))
1389 else if (!strcmp (argv[i], "-Wno-comments"))
1391 else if (!strcmp (argv[i], "-Wtraditional"))
1393 else if (!strcmp (argv[i], "-Wno-traditional"))
1395 else if (!strcmp (argv[i], "-Wimport"))
1397 else if (!strcmp (argv[i], "-Wno-import"))
1399 else if (!strcmp (argv[i], "-Werror"))
1400 warnings_are_errors = 1;
1401 else if (!strcmp (argv[i], "-Wno-error"))
1402 warnings_are_errors = 0;
1403 else if (!strcmp (argv[i], "-Wall"))
1411 /* The style of the choices here is a bit mixed.
1412 The chosen scheme is a hybrid of keeping all options in one string
1413 and specifying each option in a separate argument:
1414 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1415 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1416 -M[M][G][D file]. This is awkward to handle in specs, and is not
1418 /* ??? -MG must be specified in addition to one of -M or -MM.
1419 This can be relaxed in the future without breaking anything.
1420 The converse isn't true. */
1422 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1423 if (!strcmp (argv[i], "-MG"))
1425 print_deps_missing_files = 1;
1428 if (!strcmp (argv[i], "-M"))
1430 else if (!strcmp (argv[i], "-MM"))
1432 else if (!strcmp (argv[i], "-MD"))
1434 else if (!strcmp (argv[i], "-MMD"))
1436 /* For -MD and -MMD options, write deps on file named by next arg. */
1437 if (!strcmp (argv[i], "-MD")
1438 || !strcmp (argv[i], "-MMD")) {
1440 deps_file = argv[i];
1443 /* For -M and -MM, write deps on standard output
1444 and suppress the usual output. */
1445 deps_stream = stdout;
1452 char *p = argv[i] + 2;
1455 /* Arg to -d specifies what parts of macros to dump */
1458 dump_macros = dump_only;
1462 dump_macros = dump_names;
1465 dump_macros = dump_definitions;
1473 if (argv[i][2] == '3')
1478 fprintf (stderr, "GNU CPP version %s", version_string);
1479 #ifdef TARGET_VERSION
1482 fprintf (stderr, "\n");
1487 print_include_names = 1;
1491 if (argv[i][2] != 0)
1492 pend_defs[i] = argv[i] + 2;
1493 else if (i + 1 == argc)
1494 fatal ("Macro name missing after -D option");
1496 i++, pend_defs[i] = argv[i];
1503 if (argv[i][2] != 0)
1505 else if (i + 1 == argc)
1506 fatal ("Assertion missing after -A option");
1510 if (!strcmp (p, "-")) {
1511 /* -A- eliminates all predefined macros and assertions.
1512 Let's include also any that were specified earlier
1513 on the command line. That way we can get rid of any
1514 that were passed automatically in from GCC. */
1516 inhibit_predefs = 1;
1517 for (j = 0; j < i; j++)
1518 pend_defs[j] = pend_assertions[j] = 0;
1520 pend_assertions[i] = p;
1521 pend_assertion_options[i] = "-A";
1526 case 'U': /* JF #undef something */
1527 if (argv[i][2] != 0)
1528 pend_undefs[i] = argv[i] + 2;
1529 else if (i + 1 == argc)
1530 fatal ("Macro name missing after -U option");
1532 pend_undefs[i] = argv[i+1], i++;
1536 put_out_comments = 1;
1539 case 'E': /* -E comes from cc -E; ignore it. */
1543 no_line_commands = 1;
1546 case '$': /* Don't include $ in identifiers. */
1547 dollars_in_ident = 0;
1550 case 'I': /* Add directory to path for includes. */
1552 struct file_name_list *dirtmp;
1554 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1556 /* Don't use any preceding -I directories for #include <...>. */
1557 first_bracket_include = 0;
1560 dirtmp = (struct file_name_list *)
1561 xmalloc (sizeof (struct file_name_list));
1562 dirtmp->next = 0; /* New one goes on the end */
1563 dirtmp->control_macro = 0;
1564 dirtmp->c_system_include_path = 0;
1565 if (argv[i][2] != 0)
1566 dirtmp->fname = argv[i] + 2;
1567 else if (i + 1 == argc)
1568 fatal ("Directory name missing after -I option");
1570 dirtmp->fname = argv[++i];
1571 dirtmp->got_name_map = 0;
1572 append_include_chain (dirtmp, dirtmp);
1578 if (!strcmp (argv[i], "-nostdinc"))
1579 /* -nostdinc causes no default include directories.
1580 You must specify all include-file directories with -I. */
1581 no_standard_includes = 1;
1582 else if (!strcmp (argv[i], "-nostdinc++"))
1583 /* -nostdinc++ causes no default C++-specific include directories. */
1584 no_standard_cplusplus_includes = 1;
1585 else if (!strcmp (argv[i], "-noprecomp"))
1590 /* Sun compiler passes undocumented switch "-undef".
1591 Let's assume it means to inhibit the predefined symbols. */
1592 inhibit_predefs = 1;
1595 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1596 if (in_fname == NULL) {
1599 } else if (out_fname == NULL) {
1602 } /* else fall through into error */
1605 fatal ("Invalid option `%s'", argv[i]);
1610 /* Add dirs from CPATH after dirs from -I. */
1611 /* There seems to be confusion about what CPATH should do,
1612 so for the moment it is not documented. */
1613 /* Some people say that CPATH should replace the standard include dirs,
1614 but that seems pointless: it comes before them, so it overrides them
1616 p = (char *) getenv ("CPATH");
1617 if (p != 0 && ! no_standard_includes)
1620 /* Now that dollars_in_ident is known, initialize is_idchar. */
1621 initialize_char_syntax ();
1623 /* Initialize output buffer */
1625 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1626 outbuf.bufp = outbuf.buf;
1627 outbuf.length = OUTBUF_SIZE;
1629 /* Do partial setup of input buffer for the sake of generating
1630 early #line directives (when -g is in effect). */
1632 fp = &instack[++indepth];
1633 if (in_fname == NULL)
1635 fp->nominal_fname = fp->fname = in_fname;
1638 /* In C++, wchar_t is a distinct basic type, and we can expect
1639 __wchar_t to be defined by cc1plus. */
1641 wchar_type = "__wchar_t";
1643 /* Install __LINE__, etc. Must follow initialize_char_syntax
1644 and option processing. */
1645 initialize_builtins (fp, &outbuf);
1647 /* Do standard #defines and assertions
1648 that identify system and machine type. */
1650 if (!inhibit_predefs) {
1651 char *p = (char *) alloca (strlen (predefs) + 1);
1652 strcpy (p, predefs);
1655 while (*p == ' ' || *p == '\t')
1657 /* Handle -D options. */
1658 if (p[0] == '-' && p[1] == 'D') {
1660 while (*p && *p != ' ' && *p != '\t')
1665 output_line_command (fp, &outbuf, 0, same_file);
1666 make_definition (q, &outbuf);
1667 while (*p == ' ' || *p == '\t')
1669 } else if (p[0] == '-' && p[1] == 'A') {
1670 /* Handle -A options (assertions). */
1679 past_name = assertion;
1680 /* Locate end of name. */
1681 while (*past_name && *past_name != ' '
1682 && *past_name != '\t' && *past_name != '(')
1684 /* Locate `(' at start of value. */
1686 while (*value && (*value == ' ' || *value == '\t'))
1688 if (*value++ != '(')
1690 while (*value && (*value == ' ' || *value == '\t'))
1693 /* Locate end of value. */
1694 while (*past_value && *past_value != ' '
1695 && *past_value != '\t' && *past_value != ')')
1697 termination = past_value;
1698 while (*termination && (*termination == ' ' || *termination == '\t'))
1700 if (*termination++ != ')')
1702 if (*termination && *termination != ' ' && *termination != '\t')
1704 /* Temporarily null-terminate the value. */
1705 save_char = *termination;
1706 *termination = '\0';
1707 /* Install the assertion. */
1708 make_assertion ("-A", assertion);
1709 *termination = (char) save_char;
1711 while (*p == ' ' || *p == '\t')
1719 /* Now handle the command line options. */
1721 /* Do -U's, -D's and -A's in the order they were seen. */
1722 for (i = 1; i < argc; i++) {
1723 if (pend_undefs[i]) {
1725 output_line_command (fp, &outbuf, 0, same_file);
1726 make_undef (pend_undefs[i], &outbuf);
1730 output_line_command (fp, &outbuf, 0, same_file);
1731 make_definition (pend_defs[i], &outbuf);
1733 if (pend_assertions[i])
1734 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1737 done_initializing = 1;
1739 { /* read the appropriate environment variable and if it exists
1740 replace include_defaults with the listed path. */
1742 switch ((objc << 1) + cplusplus)
1745 epath = getenv ("C_INCLUDE_PATH");
1748 epath = getenv ("CPLUS_INCLUDE_PATH");
1751 epath = getenv ("OBJC_INCLUDE_PATH");
1754 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1757 /* If the environment var for this language is set,
1758 add to the default list of include directories. */
1760 char *nstore = (char *) alloca (strlen (epath) + 2);
1762 char *startp, *endp;
1764 for (num_dirs = 1, startp = epath; *startp; startp++)
1765 if (*startp == PATH_SEPARATOR)
1768 = (struct default_include *) xmalloc ((num_dirs
1769 * sizeof (struct default_include))
1770 + sizeof (include_defaults_array));
1771 startp = endp = epath;
1774 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1775 if ((*endp == PATH_SEPARATOR
1776 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1778 && (endp-startp != 1 || !isalpha (*startp))
1783 strncpy (nstore, startp, endp-startp);
1785 strcpy (nstore, ".");
1787 nstore[endp-startp] = '\0';
1789 include_defaults[num_dirs].fname = savestring (nstore);
1790 include_defaults[num_dirs].cplusplus = cplusplus;
1791 include_defaults[num_dirs].cxx_aware = 1;
1795 endp = startp = endp + 1;
1799 /* Put the usual defaults back in at the end. */
1800 bcopy ((char *) include_defaults_array,
1801 (char *) &include_defaults[num_dirs],
1802 sizeof (include_defaults_array));
1806 append_include_chain (before_system, last_before_system);
1807 first_system_include = before_system;
1809 /* Unless -fnostdinc,
1810 tack on the standard include file dirs to the specified list */
1811 if (!no_standard_includes) {
1812 struct default_include *p = include_defaults;
1813 char *specd_prefix = include_prefix;
1814 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1815 int default_len = 0;
1816 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1817 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1818 default_len = strlen (default_prefix) - 7;
1819 default_prefix[default_len] = 0;
1821 /* Search "translated" versions of GNU directories.
1822 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1823 if (specd_prefix != 0 && default_len != 0)
1824 for (p = include_defaults; p->fname; p++) {
1825 /* Some standard dirs are only for C++. */
1826 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1827 /* Does this dir start with the prefix? */
1828 if (!strncmp (p->fname, default_prefix, default_len)) {
1829 /* Yes; change prefix and add to search list. */
1830 struct file_name_list *new
1831 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1832 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
1833 char *str = (char *) xmalloc (this_len + 1);
1834 strcpy (str, specd_prefix);
1835 strcat (str, p->fname + default_len);
1837 new->control_macro = 0;
1838 new->c_system_include_path = !p->cxx_aware;
1839 new->got_name_map = 0;
1840 append_include_chain (new, new);
1841 if (first_system_include == 0)
1842 first_system_include = new;
1846 /* Search ordinary names for GNU include directories. */
1847 for (p = include_defaults; p->fname; p++) {
1848 /* Some standard dirs are only for C++. */
1849 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1850 struct file_name_list *new
1851 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1852 new->control_macro = 0;
1853 new->c_system_include_path = !p->cxx_aware;
1854 new->fname = p->fname;
1855 new->got_name_map = 0;
1856 append_include_chain (new, new);
1857 if (first_system_include == 0)
1858 first_system_include = new;
1863 /* Tack the after_include chain at the end of the include chain. */
1864 append_include_chain (after_include, last_after_include);
1865 if (first_system_include == 0)
1866 first_system_include = after_include;
1868 /* With -v, print the list of dirs to search. */
1870 struct file_name_list *p;
1871 fprintf (stderr, "#include \"...\" search starts here:\n");
1872 for (p = include; p; p = p->next) {
1873 if (p == first_bracket_include)
1874 fprintf (stderr, "#include <...> search starts here:\n");
1875 fprintf (stderr, " %s\n", p->fname);
1877 fprintf (stderr, "End of search list.\n");
1880 /* Scan the -imacros files before the main input.
1881 Much like #including them, but with no_output set
1882 so that only their macro definitions matter. */
1884 no_output++; no_record_file++;
1885 for (i = 1; i < argc; i++)
1886 if (pend_files[i]) {
1887 int fd = open (pend_files[i], O_RDONLY, 0666);
1889 perror_with_name (pend_files[i]);
1890 return FAILURE_EXIT_CODE;
1892 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
1894 no_output--; no_record_file--;
1896 /* Copy the entire contents of the main input file into
1897 the stacked input buffer previously allocated for it. */
1899 /* JF check for stdin */
1900 if (in_fname == NULL || *in_fname == 0) {
1903 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
1906 /* -MG doesn't select the form of output and must be specified with one of
1907 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1908 inhibit compilation. */
1909 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1910 fatal ("-MG must be specified with one of -M or -MM");
1912 /* Either of two environment variables can specify output of deps.
1913 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1914 where OUTPUT_FILE is the file to write deps info to
1915 and DEPS_TARGET is the target to mention in the deps. */
1918 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1919 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1920 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1925 spec = getenv ("SUNPRO_DEPENDENCIES");
1932 /* Find the space before the DEPS_TARGET, if there is one. */
1933 /* This should use index. (mrs) */
1934 while (*s != 0 && *s != ' ') s++;
1936 deps_target = s + 1;
1937 output_file = (char *) xmalloc (s - spec + 1);
1938 bcopy (spec, output_file, s - spec);
1939 output_file[s - spec] = 0;
1946 deps_file = output_file;
1950 /* For -M, print the expected object file name
1951 as the target of this Make-rule. */
1953 deps_allocated_size = 200;
1954 deps_buffer = (char *) xmalloc (deps_allocated_size);
1960 deps_output (deps_target, ':');
1961 } else if (*in_fname == 0) {
1962 deps_output ("-", ':');
1967 /* Discard all directory prefixes from filename. */
1968 if ((q = rindex (in_fname, '/')) != NULL)
1973 /* Copy remainder to mungable area. */
1974 p = (char *) alloca (strlen(q) + 8);
1977 /* Output P, but remove known suffixes. */
1981 && p[len - 2] == '.'
1982 && index("cCsSm", p[len - 1]))
1985 && p[len - 3] == '.'
1986 && p[len - 2] == 'c'
1987 && p[len - 1] == 'c')
1990 && p[len - 4] == '.'
1991 && p[len - 3] == 'c'
1992 && p[len - 2] == 'x'
1993 && p[len - 1] == 'x')
1996 && p[len - 4] == '.'
1997 && p[len - 3] == 'c'
1998 && p[len - 2] == 'p'
1999 && p[len - 1] == 'p')
2002 /* Supply our own suffix. */
2009 deps_output (p, ':');
2010 deps_output (in_fname, ' ');
2014 file_size_and_mode (f, &st_mode, &st_size);
2015 fp->nominal_fname = fp->fname = in_fname;
2017 fp->system_header_p = 0;
2018 /* JF all this is mine about reading pipes and ttys */
2019 if (! S_ISREG (st_mode)) {
2020 /* Read input from a file that is not a normal disk file.
2021 We cannot preallocate a buffer with the correct size,
2022 so we must read in the file a piece at the time and make it bigger. */
2029 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2031 cnt = safe_read (f, fp->buf + size, bsize - size);
2032 if (cnt < 0) goto perror; /* error! */
2034 if (size != bsize) break; /* End of file */
2036 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2040 /* Read a file whose size we can determine in advance.
2041 For the sake of VMS, st_size is just an upper bound. */
2042 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2043 fp->length = safe_read (f, fp->buf, st_size);
2044 if (fp->length < 0) goto perror;
2047 fp->if_stack = if_stack;
2049 /* Make sure data ends with a newline. And put a null after it. */
2051 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2052 /* Backslash-newline at end is not good enough. */
2053 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2054 fp->buf[fp->length++] = '\n';
2055 missing_newline = 1;
2057 fp->buf[fp->length] = '\0';
2059 /* Unless inhibited, convert trigraphs in the input. */
2064 /* Now that we know the input file is valid, open the output. */
2066 if (!out_fname || !strcmp (out_fname, ""))
2067 out_fname = "stdout";
2068 else if (! freopen (out_fname, "w", stdout))
2069 pfatal_with_name (out_fname);
2071 output_line_command (fp, &outbuf, 0, same_file);
2073 /* Scan the -include files before the main input. */
2076 for (i = 1; i < argc; i++)
2077 if (pend_includes[i]) {
2078 int fd = open (pend_includes[i], O_RDONLY, 0666);
2080 perror_with_name (pend_includes[i]);
2081 return FAILURE_EXIT_CODE;
2083 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2087 /* Scan the input, processing macros and directives. */
2089 rescan (&outbuf, 0);
2091 if (missing_newline)
2094 if (pedantic && missing_newline)
2095 pedwarn ("file does not end in newline");
2097 /* Now we have processed the entire input
2098 Write whichever kind of output has been requested. */
2100 if (dump_macros == dump_only)
2102 else if (! inhibit_output) {
2107 /* Don't actually write the deps file if compilation has failed. */
2109 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2110 pfatal_with_name (deps_file);
2111 fputs (deps_buffer, deps_stream);
2112 putc ('\n', deps_stream);
2114 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2115 fatal ("I/O error on output");
2120 if (pcp_outfile && pcp_outfile != stdout
2121 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2122 fatal ("I/O error on `-pcp' output");
2124 if (ferror (stdout) || fclose (stdout) != 0)
2125 fatal ("I/O error on output");
2128 exit (FAILURE_EXIT_CODE);
2129 exit (SUCCESS_EXIT_CODE);
2132 pfatal_with_name (in_fname);
2136 /* Given a colon-separated list of file names PATH,
2137 add all the names to the search path for include files. */
2151 struct file_name_list *dirtmp;
2153 /* Find the end of this name. */
2154 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2156 /* An empty name in the path stands for the current directory. */
2157 name = (char *) xmalloc (2);
2161 /* Otherwise use the directory that is named. */
2162 name = (char *) xmalloc (q - p + 1);
2163 bcopy (p, name, q - p);
2167 dirtmp = (struct file_name_list *)
2168 xmalloc (sizeof (struct file_name_list));
2169 dirtmp->next = 0; /* New one goes on the end */
2170 dirtmp->control_macro = 0;
2171 dirtmp->c_system_include_path = 0;
2172 dirtmp->fname = name;
2173 dirtmp->got_name_map = 0;
2174 append_include_chain (dirtmp, dirtmp);
2176 /* Advance past this name. */
2180 /* Skip the colon. */
2185 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2186 before main CCCP processing. Name `pcp' is also in honor of the
2187 drugs the trigraph designers must have been on.
2189 Using an extra pass through the buffer takes a little extra time,
2190 but is infinitely less hairy than trying to handle trigraphs inside
2191 strings, etc. everywhere, and also makes sure that trigraphs are
2192 only translated in the top level of processing. */
2198 register U_CHAR c, *fptr, *bptr, *sptr;
2201 fptr = bptr = sptr = buf->buf;
2202 while ((sptr = (U_CHAR *) index (sptr, '?')) != NULL) {
2239 len = sptr - fptr - 2;
2241 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2242 C, this will be memmove (). */
2243 if (bptr != fptr && len > 0)
2244 bcopy ((char *) fptr, (char *) bptr, len);
2250 len = buf->length - (fptr - buf->buf);
2251 if (bptr != fptr && len > 0)
2252 bcopy ((char *) fptr, (char *) bptr, len);
2253 buf->length -= fptr - bptr;
2254 buf->buf[buf->length] = '\0';
2255 if (warn_trigraphs && fptr != bptr)
2256 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2259 /* Move all backslash-newline pairs out of embarrassing places.
2260 Exchange all such pairs following BP
2261 with any potentially-embarrassing characters that follow them.
2262 Potentially-embarrassing characters are / and *
2263 (because a backslash-newline inside a comment delimiter
2264 would cause it not to be recognized). */
2270 register U_CHAR *p = bp;
2271 register int count = 0;
2273 /* First count the backslash-newline pairs here. */
2279 else if (p[1] == '\r' && p[2] == '\n')
2287 /* What follows the backslash-newlines is not embarrassing. */
2289 if (count == 0 || (*p != '/' && *p != '*'))
2292 /* Copy all potentially embarrassing characters
2293 that follow the backslash-newline pairs
2294 down to where the pairs originally started. */
2296 while (*p == '*' || *p == '/')
2299 /* Now write the same number of pairs after the embarrassing chars. */
2300 while (count-- > 0) {
2306 /* Like newline_fix but for use within a directive-name.
2307 Move any backslash-newlines up past any following symbol constituents. */
2310 name_newline_fix (bp)
2313 register U_CHAR *p = bp;
2314 register int count = 0;
2316 /* First count the backslash-newline pairs here. */
2321 else if (p[1] == '\r' && p[2] == '\n')
2329 /* What follows the backslash-newlines is not embarrassing. */
2331 if (count == 0 || !is_idchar[*p])
2334 /* Copy all potentially embarrassing characters
2335 that follow the backslash-newline pairs
2336 down to where the pairs originally started. */
2338 while (is_idchar[*p])
2341 /* Now write the same number of pairs after the embarrassing chars. */
2342 while (count-- > 0) {
2348 /* Look for lint commands in comments.
2350 When we come in here, ibp points into a comment. Limit is as one expects.
2351 scan within the comment -- it should start, after lwsp, with a lint command.
2352 If so that command is returned as a (constant) string.
2354 Upon return, any arg will be pointed to with argstart and will be
2355 arglen long. Note that we don't parse that arg since it will just
2356 be printed out again.
2360 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2361 register U_CHAR *ibp;
2362 register U_CHAR *limit;
2363 U_CHAR **argstart; /* point to command arg */
2364 int *arglen, *cmdlen; /* how long they are */
2367 register U_CHAR *numptr; /* temp for arg parsing */
2371 SKIP_WHITE_SPACE (ibp);
2373 if (ibp >= limit) return NULL;
2375 linsize = limit - ibp;
2377 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2378 if ((linsize >= 10) && !strncmp (ibp, "NOTREACHED", 10)) {
2380 return "NOTREACHED";
2382 if ((linsize >= 8) && !strncmp (ibp, "ARGSUSED", 8)) {
2386 if ((linsize >= 11) && !strncmp (ibp, "LINTLIBRARY", 11)) {
2388 return "LINTLIBRARY";
2390 if ((linsize >= 7) && !strncmp (ibp, "VARARGS", 7)) {
2392 ibp += 7; linsize -= 7;
2393 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2395 /* OK, read a number */
2396 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2398 *arglen = numptr - *argstart;
2405 * The main loop of the program.
2407 * Read characters from the input stack, transferring them to the
2410 * Macros are expanded and push levels on the input stack.
2411 * At the end of such a level it is popped off and we keep reading.
2412 * At the end of any other kind of level, we return.
2413 * #-directives are handled, except within macros.
2415 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2416 * and insert them when appropriate. This is set while scanning macro
2417 * arguments before substitution. It is zero when scanning for final output.
2418 * There are three types of Newline markers:
2419 * * Newline - follows a macro name that was not expanded
2420 * because it appeared inside an expansion of the same macro.
2421 * This marker prevents future expansion of that identifier.
2422 * When the input is rescanned into the final output, these are deleted.
2423 * These are also deleted by ## concatenation.
2424 * * Newline Space (or Newline and any other whitespace character)
2425 * stands for a place that tokens must be separated or whitespace
2426 * is otherwise desirable, but where the ANSI standard specifies there
2427 * is no whitespace. This marker turns into a Space (or whichever other
2428 * whitespace char appears in the marker) in the final output,
2429 * but it turns into nothing in an argument that is stringified with #.
2430 * Such stringified arguments are the only place where the ANSI standard
2431 * specifies with precision that whitespace may not appear.
2433 * During this function, IP->bufp is kept cached in IBP for speed of access.
2434 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2435 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2436 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2437 * explicitly, and before RECACHE, since RECACHE uses OBP.
2441 rescan (op, output_marks)
2445 /* Character being scanned in main loop. */
2448 /* Length of pending accumulated identifier. */
2449 register int ident_length = 0;
2451 /* Hash code of pending accumulated identifier. */
2452 register int hash = 0;
2454 /* Current input level (&instack[indepth]). */
2457 /* Pointer for scanning input. */
2458 register U_CHAR *ibp;
2460 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2461 register U_CHAR *limit;
2463 /* Pointer for storing output. */
2464 register U_CHAR *obp;
2466 /* REDO_CHAR is nonzero if we are processing an identifier
2467 after backing up over the terminating character.
2468 Sometimes we process an identifier without backing up over
2469 the terminating character, if the terminating character
2470 is not special. Backing up is done so that the terminating character
2471 will be dispatched on again once the identifier is dealt with. */
2474 /* 1 if within an identifier inside of which a concatenation
2475 marker (Newline -) has been seen. */
2476 int concatenated = 0;
2478 /* While scanning a comment or a string constant,
2479 this records the line it started on, for error messages. */
2482 /* Record position of last `real' newline. */
2483 U_CHAR *beg_of_line;
2485 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2488 do { ip->macro->type = T_MACRO; \
2489 if (ip->free_ptr) free (ip->free_ptr); \
2490 --indepth; } while (0)
2492 /* Reload `rescan's local variables that describe the current
2493 level of the input stack. */
2496 do { ip = &instack[indepth]; \
2498 limit = ip->buf + ip->length; \
2500 check_expand (op, limit - ibp); \
2502 obp = op->bufp; } while (0)
2504 if (no_output && instack[indepth].fname != 0)
2505 skip_if_group (&instack[indepth], 1);
2512 /* Our caller must always put a null after the end of
2513 the input at each input stack level. */
2526 /* Always merge lines ending with backslash-newline,
2527 even in middle of identifier. */
2530 --obp; /* remove backslash from obuf */
2533 /* Otherwise, backslash suppresses specialness of following char,
2534 so copy it here to prevent the switch from seeing it.
2535 But first get any pending identifier processed. */
2536 if (ident_length > 0)
2542 if (assertions_flag) {
2543 /* Copy #foo (bar lose) without macro expansion. */
2544 SKIP_WHITE_SPACE (ibp);
2545 while (is_idchar[*ibp])
2547 SKIP_WHITE_SPACE (ibp);
2550 skip_paren_group (ip);
2551 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2552 obp += ip->bufp - ibp;
2557 /* If this is expanding a macro definition, don't recognize
2558 preprocessor directives. */
2561 /* If this is expand_into_temp_buffer, recognize them
2562 only after an actual newline at this level,
2563 not at the beginning of the input level. */
2564 if (ip->fname == 0 && beg_of_line == ip->buf)
2570 /* # keyword: a # must be first nonblank char on the line */
2571 if (beg_of_line == 0)
2576 /* Scan from start of line, skipping whitespace, comments
2577 and backslash-newlines, and see if we reach this #.
2578 If not, this # is not special. */
2580 /* If -traditional, require # to be at beginning of line. */
2583 if (is_hor_space[*bp])
2585 else if (*bp == '\\' && bp[1] == '\n')
2587 else if (*bp == '/' && bp[1] == '*') {
2589 while (!(*bp == '*' && bp[1] == '/'))
2593 /* There is no point in trying to deal with C++ // comments here,
2594 because if there is one, then this # must be part of the
2595 comment and we would never reach here. */
2602 /* This # can start a directive. */
2604 --obp; /* Don't copy the '#' */
2608 if (! handle_directive (ip, op)) {
2612 /* Not a known directive: treat it as ordinary text.
2613 IP, OP, IBP, etc. have not been changed. */
2614 if (no_output && instack[indepth].fname) {
2615 /* If not generating expanded output,
2616 what we do with ordinary text is skip it.
2617 Discard everything until next # directive. */
2618 skip_if_group (&instack[indepth], 1);
2623 ++obp; /* Copy the '#' after all */
2624 /* Don't expand an identifier that could be a macro directive.
2625 (Section 3.8.3 of the ANSI C standard) */
2626 SKIP_WHITE_SPACE (ibp);
2627 if (is_idstart[*ibp])
2630 while (is_idchar[*ibp])
2638 /* A # directive has been successfully processed. */
2639 /* If not generating expanded output, ignore everything until
2640 next # directive. */
2641 if (no_output && instack[indepth].fname)
2642 skip_if_group (&instack[indepth], 1);
2648 case '\"': /* skip quoted string */
2650 /* A single quoted string is treated like a double -- some
2651 programs (e.g., troff) are perverse this way */
2656 start_line = ip->lineno;
2658 /* Skip ahead to a matching quote. */
2662 if (ip->macro != 0) {
2663 /* try harder: this string crosses a macro expansion boundary.
2664 This can happen naturally if -traditional.
2665 Otherwise, only -D can make a macro with an unmatched quote. */
2671 error_with_line (line_for_error (start_line),
2672 "unterminated string or character constant");
2673 error_with_line (multiline_string_line,
2674 "possible real start of unterminated constant");
2675 multiline_string_line = 0;
2684 /* Traditionally, end of line ends a string constant with no error.
2685 So exit the loop and record the new line. */
2691 error_with_line (line_for_error (start_line),
2692 "unterminated character constant");
2695 if (pedantic && multiline_string_line == 0) {
2696 pedwarn_with_line (line_for_error (start_line),
2697 "string constant runs past end of line");
2699 if (multiline_string_line == 0)
2700 multiline_string_line = ip->lineno - 1;
2707 /* Backslash newline is replaced by nothing at all,
2708 but keep the line counts correct. */
2713 /* ANSI stupidly requires that in \\ the second \
2714 is *not* prevented from combining with a newline. */
2715 while (*ibp == '\\' && ibp[1] == '\n') {
2734 if (*ibp == '\\' && ibp[1] == '\n')
2738 && !(cplusplus_comments && *ibp == '/'))
2746 /* C++ style comment... */
2747 start_line = ip->lineno;
2749 --ibp; /* Back over the slash */
2752 /* Comments are equivalent to spaces. */
2753 if (! put_out_comments)
2756 /* must fake up a comment here */
2761 U_CHAR *before_bp = ibp+2;
2763 while (ibp < limit) {
2764 if (ibp[-1] != '\\' && *ibp == '\n') {
2765 if (put_out_comments) {
2766 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2767 obp += ibp - before_bp;
2773 /* Copy the newline into the output buffer, in order to
2774 avoid the pain of a #line every time a multiline comment
2776 if (!put_out_comments)
2787 /* Ordinary C comment. Skip it, optionally copying it to output. */
2789 start_line = ip->lineno;
2791 ++ibp; /* Skip the star. */
2793 /* If this cpp is for lint, we peek inside the comments: */
2797 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2799 if (lintcmd != NULL) {
2801 check_expand (op, 13 + cmdlen);
2803 /* I believe it is always safe to emit this newline: */
2805 bcopy ("#pragma lint ", (char *) obp, 13);
2807 bcopy (lintcmd, (char *) obp, cmdlen);
2812 bcopy (argbp, (char *) obp, arglen);
2816 /* OK, now bring us back to the state we were in before we entered
2817 this branch. We need #line because the #pragma's newline always
2818 messes up the line count. */
2820 output_line_command (ip, op, 0, same_file);
2821 check_expand (op, ip->length - (ip->bufp - ip->buf));
2827 /* Comments are equivalent to spaces.
2828 Note that we already output the slash; we might not want it.
2829 For -traditional, a comment is equivalent to nothing. */
2830 if (! put_out_comments) {
2840 U_CHAR *before_bp = ibp;
2842 while (ibp < limit) {
2845 if (warn_comments && ibp < limit && *ibp == '*')
2846 warning ("`/*' within comment");
2849 if (*ibp == '\\' && ibp[1] == '\n')
2851 if (ibp >= limit || *ibp == '/')
2856 /* Copy the newline into the output buffer, in order to
2857 avoid the pain of a #line every time a multiline comment
2859 if (!put_out_comments)
2867 error_with_line (line_for_error (start_line),
2868 "unterminated comment");
2871 if (put_out_comments) {
2872 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2873 obp += ibp - before_bp;
2880 if (!dollars_in_ident)
2884 case '0': case '1': case '2': case '3': case '4':
2885 case '5': case '6': case '7': case '8': case '9':
2886 /* If digit is not part of identifier, it starts a number,
2887 which means that following letters are not an identifier.
2888 "0x5" does not refer to an identifier "x5".
2889 So copy all alphanumerics that follow without accumulating
2890 as an identifier. Periods also, for sake of "3.e7". */
2892 if (ident_length == 0) {
2893 while (ibp < limit) {
2894 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
2899 /* ".." terminates a preprocessing number. This is useless for C
2900 code but useful for preprocessing other things. */
2901 if (!isalnum (c) && (c != '.' || *ibp == '.') && c != '_') {
2906 /* A sign can be part of a preprocessing number
2907 if it follows an e. */
2908 if (c == 'e' || c == 'E') {
2909 while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
2913 if (ibp < limit && (*ibp == '+' || *ibp == '-')) {
2915 /* But traditional C does not let the token go past the sign. */
2926 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2927 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2928 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2929 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2931 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2932 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
2933 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
2934 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2938 /* Compute step of hash function, to avoid a proc call on every token */
2939 hash = HASHSTEP (hash, c);
2943 if (ip->fname == 0 && *ibp == '-') {
2944 /* Newline - inhibits expansion of preceding token.
2945 If expanding a macro arg, we keep the newline -.
2946 In final output, it is deleted.
2947 We recognize Newline - in macro bodies and macro args. */
2948 if (! concatenated) {
2953 if (!output_marks) {
2956 /* If expanding a macro arg, keep the newline -. */
2962 /* If reprocessing a macro expansion, newline is a special marker. */
2963 else if (ip->macro != 0) {
2964 /* Newline White is a "funny space" to separate tokens that are
2965 supposed to be separate but without space between.
2966 Here White means any whitespace character.
2967 Newline - marks a recursive macro use that is not
2968 supposed to be expandable. */
2970 if (is_space[*ibp]) {
2971 /* Newline Space does not prevent expansion of preceding token
2972 so expand the preceding token and then come back. */
2973 if (ident_length > 0)
2976 /* If generating final output, newline space makes a space. */
2977 if (!output_marks) {
2979 /* And Newline Newline makes a newline, so count it. */
2980 if (obp[-1] == '\n')
2983 /* If expanding a macro arg, keep the newline space.
2984 If the arg gets stringified, newline space makes nothing. */
2987 } else abort (); /* Newline followed by something random? */
2991 /* If there is a pending identifier, handle it and come back here. */
2992 if (ident_length > 0)
2997 /* Update the line counts and output a #line if necessary. */
3000 if (ip->lineno != op->lineno) {
3002 output_line_command (ip, op, 1, same_file);
3003 check_expand (op, ip->length - (ip->bufp - ip->buf));
3008 /* Come here either after (1) a null character that is part of the input
3009 or (2) at the end of the input, because there is a null there. */
3012 /* Our input really contains a null character. */
3015 /* At end of a macro-expansion level, pop it and read next level. */
3016 if (ip->macro != 0) {
3019 /* If traditional, and we have an identifier that ends here,
3020 process it now, so we get the right error for recursion. */
3021 if (traditional && ident_length
3022 && ! is_idchar[*instack[indepth - 1].bufp]) {
3031 /* If we don't have a pending identifier,
3032 return at end of input. */
3033 if (ident_length == 0) {
3041 /* If we do have a pending identifier, just consider this null
3042 a special character and arrange to dispatch on it again.
3043 The second time, IDENT_LENGTH will be zero so we will return. */
3049 /* Handle the case of a character such as /, ', " or null
3050 seen following an identifier. Back over it so that
3051 after the identifier is processed the special char
3052 will be dispatched on again. */
3062 if (ident_length > 0) {
3063 register HASHNODE *hp;
3065 /* We have just seen an identifier end. If it's a macro, expand it.
3067 IDENT_LENGTH is the length of the identifier
3068 and HASH is its hash code.
3070 The identifier has already been copied to the output,
3071 so if it is a macro we must remove it.
3073 If REDO_CHAR is 0, the char that terminated the identifier
3074 has been skipped in the output and the input.
3075 OBP-IDENT_LENGTH-1 points to the identifier.
3076 If the identifier is a macro, we must back over the terminator.
3078 If REDO_CHAR is 1, the terminating char has already been
3079 backed over. OBP-IDENT_LENGTH points to the identifier. */
3081 if (!pcp_outfile || pcp_inside_if) {
3083 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3086 if (hp->length == ident_length) {
3087 int obufp_before_macroname;
3088 int op_lineno_before_macroname;
3089 register int i = ident_length;
3090 register U_CHAR *p = hp->name;
3091 register U_CHAR *q = obp - i;
3097 do { /* All this to avoid a strncmp () */
3102 /* We found a use of a macro name.
3103 see if the context shows it is a macro call. */
3105 /* Back up over terminating character if not already done. */
3111 /* Save this as a displacement from the beginning of the output
3112 buffer. We can not save this as a position in the output
3113 buffer, because it may get realloc'ed by RECACHE. */
3114 obufp_before_macroname = (obp - op->buf) - ident_length;
3115 op_lineno_before_macroname = op->lineno;
3117 if (hp->type == T_PCSTRING) {
3118 pcstring_used (hp); /* Mark the definition of this key
3119 as needed, ensuring that it
3121 break; /* Exit loop, since the key cannot have a
3122 definition any longer. */
3125 /* Record whether the macro is disabled. */
3126 disabled = hp->type == T_DISABLED;
3128 /* This looks like a macro ref, but if the macro was disabled,
3129 just copy its name and put in a marker if requested. */
3133 /* This error check caught useful cases such as
3134 #define foo(x,y) bar (x (y,0), y)
3137 error ("recursive use of macro `%s'", hp->name);
3141 check_expand (op, limit - ibp + 2);
3148 /* If macro wants an arglist, verify that a '(' follows.
3149 first skip all whitespace, copying it to the output
3150 after the macro name. Then, if there is no '(',
3151 decide this is not a macro call and leave things that way. */
3152 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3153 && hp->value.defn->nargs >= 0)
3155 U_CHAR *old_ibp = ibp;
3156 U_CHAR *old_obp = obp;
3157 int old_iln = ip->lineno;
3158 int old_oln = op->lineno;
3161 /* Scan forward over whitespace, copying it to the output. */
3162 if (ibp == limit && ip->macro != 0) {
3167 old_iln = ip->lineno;
3168 old_oln = op->lineno;
3170 /* A comment: copy it unchanged or discard it. */
3171 else if (*ibp == '/' && ibp+1 != limit && ibp[1] == '*') {
3172 if (put_out_comments) {
3175 } else if (! traditional) {
3179 while (ibp + 1 != limit
3180 && !(ibp[0] == '*' && ibp[1] == '/')) {
3181 /* We need not worry about newline-marks,
3182 since they are never found in comments. */
3184 /* Newline in a file. Count it. */
3188 if (put_out_comments)
3194 if (put_out_comments) {
3199 else if (is_space[*ibp]) {
3201 if (ibp[-1] == '\n') {
3202 if (ip->macro == 0) {
3203 /* Newline in a file. Count it. */
3206 } else if (!output_marks) {
3207 /* A newline mark, and we don't want marks
3208 in the output. If it is newline-hyphen,
3209 discard it entirely. Otherwise, it is
3210 newline-whitechar, so keep the whitechar. */
3220 /* A newline mark; copy both chars to the output. */
3228 /* It isn't a macro call.
3229 Put back the space that we just skipped. */
3232 ip->lineno = old_iln;
3233 op->lineno = old_oln;
3234 /* Exit the for loop. */
3239 /* This is now known to be a macro call.
3240 Discard the macro name from the output,
3241 along with any following whitespace just copied. */
3242 obp = op->buf + obufp_before_macroname;
3243 op->lineno = op_lineno_before_macroname;
3245 /* Prevent accidental token-pasting with a character
3246 before the macro call. */
3247 if (!traditional && obp != op->buf
3248 && (obp[-1] == '-' || obp[1] == '+' || obp[1] == '&'
3249 || obp[-1] == '|' || obp[1] == '<' || obp[1] == '>')) {
3250 /* If we are expanding a macro arg, make a newline marker
3251 to separate the tokens. If we are making real output,
3252 a plain space will do. */
3258 /* Expand the macro, reading arguments as needed,
3259 and push the expansion on the input stack. */
3262 macroexpand (hp, op);
3264 /* Reexamine input stack, since macroexpand has pushed
3265 a new level on it. */
3272 } /* End hash-table-search loop */
3274 ident_length = hash = 0; /* Stop collecting identifier */
3277 } /* End if (ident_length > 0) */
3279 } /* End per-char loop */
3281 /* Come here to return -- but first give an error message
3282 if there was an unterminated successful conditional. */
3284 if (if_stack != ip->if_stack)
3286 char *str = "unknown";
3288 switch (if_stack->type)
3307 error_with_line (line_for_error (if_stack->lineno),
3308 "unterminated `#%s' conditional", str);
3310 if_stack = ip->if_stack;
3314 * Rescan a string into a temporary buffer and return the result
3315 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3317 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3318 * and insert such markers when appropriate. See `rescan' for details.
3319 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3320 * before substitution; it is 0 for other uses.
3323 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3324 U_CHAR *buf, *limit;
3325 int output_marks, assertions;
3327 register FILE_BUF *ip;
3329 int length = limit - buf;
3331 int odepth = indepth;
3332 int save_assertions_flag = assertions_flag;
3334 assertions_flag = assertions;
3339 /* Set up the input on the input stack. */
3341 buf1 = (U_CHAR *) alloca (length + 1);
3343 register U_CHAR *p1 = buf;
3344 register U_CHAR *p2 = buf1;
3351 /* Set up to receive the output. */
3353 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3354 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3359 CHECK_DEPTH ({return obuf;});
3363 ip = &instack[indepth];
3365 ip->nominal_fname = 0;
3366 ip->system_header_p = 0;
3369 ip->length = length;
3370 ip->buf = ip->bufp = buf1;
3371 ip->if_stack = if_stack;
3373 ip->lineno = obuf.lineno = 1;
3375 /* Scan the input, create the output. */
3376 rescan (&obuf, output_marks);
3378 /* Pop input stack to original state. */
3381 if (indepth != odepth)
3384 /* Record the output. */
3385 obuf.length = obuf.bufp - obuf.buf;
3387 assertions_flag = save_assertions_flag;
3392 * Process a # directive. Expects IP->bufp to point after the '#', as in
3393 * `#define foo bar'. Passes to the command handler
3394 * (do_define, do_include, etc.): the addresses of the 1st and
3395 * last chars of the command (starting immediately after the #
3396 * keyword), plus op and the keyword table pointer. If the command
3397 * contains comments it is copied into a temporary buffer sans comments
3398 * and the temporary buffer is passed to the command handler instead.
3399 * Likewise for backslash-newlines.
3401 * Returns nonzero if this was a known # directive.
3402 * Otherwise, returns zero, without advancing the input pointer.
3406 handle_directive (ip, op)
3409 register U_CHAR *bp, *cp;
3410 register struct directive *kt;
3411 register int ident_length;
3414 /* Nonzero means we must copy the entire command
3415 to get rid of comments or backslash-newlines. */
3416 int copy_command = 0;
3418 U_CHAR *ident, *after_ident;
3422 /* Record where the directive started. do_xifdef needs this. */
3423 directive_start = bp - 1;
3425 /* Skip whitespace and \-newline. */
3427 if (is_hor_space[*bp]) {
3428 if ((*bp == '\f' || *bp == '\v') && pedantic)
3429 pedwarn ("%s in preprocessing directive",
3430 *bp == '\f' ? "formfeed" : "vertical tab");
3432 } else if (*bp == '/' && (bp[1] == '*'
3433 || (cplusplus_comments && bp[1] == '/'))) {
3435 skip_to_end_of_comment (ip, &ip->lineno, 0);
3437 } else if (*bp == '\\' && bp[1] == '\n') {
3438 bp += 2; ip->lineno++;
3442 /* Now find end of directive name.
3443 If we encounter a backslash-newline, exchange it with any following
3444 symbol-constituents so that we end up with a contiguous name. */
3451 if (*cp == '\\' && cp[1] == '\n')
3452 name_newline_fix (cp);
3458 ident_length = cp - bp;
3462 /* A line of just `#' becomes blank. */
3464 if (ident_length == 0 && *after_ident == '\n') {
3465 ip->bufp = after_ident;
3469 if (ident_length == 0 || !is_idstart[*ident]) {
3471 while (is_idchar[*p]) {
3472 if (*p < '0' || *p > '9')
3476 /* Handle # followed by a line number. */
3477 if (p != ident && !is_idchar[*p]) {
3478 static struct directive line_directive_table[] = {
3479 { 4, do_line, "line", T_LINE},
3482 pedwarn ("`#' followed by integer");
3483 after_ident = ident;
3484 kt = line_directive_table;
3488 /* Avoid error for `###' and similar cases unless -pedantic. */
3490 while (*p == '#' || is_hor_space[*p]) p++;
3492 if (pedantic && !lang_asm)
3493 warning ("invalid preprocessor directive");
3499 error ("invalid preprocessor directive name");
3505 * Decode the keyword and call the appropriate expansion
3506 * routine, after moving the input pointer up to the next line.
3508 for (kt = directive_table; kt->length > 0; kt++) {
3509 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) {
3510 register U_CHAR *buf;
3511 register U_CHAR *limit;
3514 int *already_output;
3516 /* Nonzero means do not delete comments within the directive.
3517 #define needs this when -traditional. */
3522 limit = ip->buf + ip->length;
3525 keep_comments = traditional && kt->traditional_comments;
3526 /* #import is defined only in Objective C, or when on the NeXT. */
3527 if (kt->type == T_IMPORT && !(objc || lookup ("__NeXT__", -1, -1)))
3530 /* Find the end of this command (first newline not backslashed
3531 and not in a string or comment).
3532 Set COPY_COMMAND if the command must be copied
3533 (it contains a backslash-newline or a comment). */
3535 buf = bp = after_ident;
3536 while (bp < limit) {
3537 register U_CHAR c = *bp++;
3551 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_command, &unterminated);
3552 /* Don't bother calling the directive if we already got an error
3553 message due to unterminated string. Skip everything and pretend
3554 we called the directive. */
3557 /* Traditional preprocessing permits unterminated strings. */
3566 /* <...> is special for #include. */
3568 if (!kt->angle_brackets)
3570 while (*bp && *bp != '>') bp++;
3574 if (*bp == '\\' && bp[1] == '\n')
3577 || (cplusplus_comments && *bp == '/')) {
3578 U_CHAR *obp = bp - 1;
3580 skip_to_end_of_comment (ip, &ip->lineno, 0);
3582 /* No need to copy the command because of a comment at the end;
3583 just don't include the comment in the directive. */
3584 if (bp == limit || *bp == '\n') {
3588 /* Don't remove the comments if -traditional. */
3589 if (! keep_comments)
3597 pedwarn ("%s in preprocessing directive",
3598 c == '\f' ? "formfeed" : "vertical tab");
3602 --bp; /* Point to the newline */
3610 resume_p = ip->bufp;
3611 /* BP is the end of the directive.
3612 RESUME_P is the next interesting data after the directive.
3613 A comment may come between. */
3615 /* If a directive should be copied through, and -E was given,
3616 pass it through before removing comments. */
3617 if (!no_output && kt->pass_thru && put_out_comments) {
3620 /* Output directive name. */
3621 check_expand (op, kt->length + 2);
3622 /* Make sure # is at the start of a line */
3623 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3628 bcopy (kt->name, op->bufp, kt->length);
3629 op->bufp += kt->length;
3631 /* Output arguments. */
3633 check_expand (op, len);
3634 bcopy (buf, (char *) op->bufp, len);
3636 /* Take account of any (escaped) newlines just output. */
3638 if (buf[len] == '\n')
3641 already_output = &junk;
3642 } /* Don't we need a newline or #line? */
3645 register U_CHAR *xp = buf;
3646 /* Need to copy entire command into temp buffer before dispatching */
3648 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
3652 /* Copy to the new buffer, deleting comments
3653 and backslash-newlines (and whitespace surrounding the latter). */
3656 register U_CHAR c = *xp++;
3661 abort (); /* A bare newline should never part of the line. */
3664 /* <...> is special for #include. */
3666 if (!kt->angle_brackets)
3668 while (xp < bp && c != '>') {
3670 if (c == '\\' && xp < bp && *xp == '\n')
3681 if (cp != buf && is_space[cp[-1]]) {
3682 while (cp != buf && is_space[cp[-1]]) cp--;
3684 SKIP_WHITE_SPACE (xp);
3685 } else if (is_space[*xp]) {
3687 SKIP_WHITE_SPACE (xp);
3697 register U_CHAR *bp1
3698 = skip_quoted_string (xp - 1, bp, ip->lineno,
3699 NULL_PTR, NULL_PTR, NULL_PTR);
3713 || (cplusplus_comments && *xp == '/')) {
3715 /* If we already copied the command through,
3716 already_output != 0 prevents outputting comment now. */
3717 skip_to_end_of_comment (ip, already_output, 0);
3719 while (xp != ip->bufp)
3721 /* Delete or replace the slash. */
3722 else if (traditional)
3731 /* Null-terminate the copy. */
3737 ip->bufp = resume_p;
3739 /* Some directives should be written out for cc1 to process,
3740 just as if they were not defined. And sometimes we're copying
3741 definitions through. */
3743 if (!no_output && already_output == 0
3745 || (kt->type == T_DEFINE
3746 && (dump_macros == dump_names
3747 || dump_macros == dump_definitions)))) {
3750 /* Output directive name. */
3751 check_expand (op, kt->length + 1);
3753 bcopy (kt->name, (char *) op->bufp, kt->length);
3754 op->bufp += kt->length;
3756 if (kt->pass_thru || dump_macros == dump_definitions) {
3757 /* Output arguments. */
3759 check_expand (op, len);
3760 bcopy (buf, (char *) op->bufp, len);
3762 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3765 SKIP_WHITE_SPACE (xp);
3767 while (is_idchar[*xp]) xp++;
3769 check_expand (op, len + 1);
3771 bcopy (yp, op->bufp, len);
3774 } /* Don't we need a newline or #line? */
3776 /* Call the appropriate command handler. buf now points to
3777 either the appropriate place in the input buffer, or to
3778 the temp buffer if it was necessary to make one. cp
3779 points to the first char after the contents of the (possibly
3780 copied) command, in either case. */
3781 (*kt->func) (buf, cp, op, kt);
3782 check_expand (op, ip->length - (ip->bufp - ip->buf));
3788 /* It is deliberate that we don't warn about undefined directives.
3789 That is the responsibility of cc1. */
3796 static struct tm *timebuf;
3798 time_t t = time (0);
3799 timebuf = localtime (&t);
3804 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3805 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3809 * expand things like __FILE__. Place the expansion into the output
3810 * buffer *without* rescanning.
3814 special_symbol (hp, op)
3821 FILE_BUF *ip = NULL;
3824 int paren = 0; /* For special `defined' keyword */
3826 if (pcp_outfile && pcp_inside_if
3827 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3828 error ("Predefined macro `%s' used inside `#if' during precompilation",
3831 for (i = indepth; i >= 0; i--)
3832 if (instack[i].fname != NULL) {
3837 error ("cccp error: not in any file?!");
3838 return; /* the show must go on */
3846 if (hp->type == T_FILE)
3847 string = ip->nominal_fname;
3849 string = instack[0].nominal_fname;
3853 buf = (char *) alloca (3 + 4 * strlen (string));
3854 quote_string (buf, string);
3862 case T_INCLUDE_LEVEL:
3864 for (i = indepth; i >= 0; i--)
3865 if (instack[i].fname != NULL)
3868 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
3869 sprintf (buf, "%d", true_indepth - 1);
3873 buf = (char *) alloca (3 + strlen (version_string));
3874 sprintf (buf, "\"%s\"", version_string);
3877 #ifndef NO_BUILTIN_SIZE_TYPE
3883 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3884 case T_PTRDIFF_TYPE:
3893 case T_USER_LABEL_PREFIX_TYPE:
3894 buf = USER_LABEL_PREFIX;
3897 case T_REGISTER_PREFIX_TYPE:
3898 buf = REGISTER_PREFIX;
3902 buf = (char *) alloca (4 * sizeof (int));
3903 sprintf (buf, "%d", hp->value.ival);
3904 if (pcp_inside_if && pcp_outfile)
3905 /* Output a precondition for this macro use */
3906 fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
3910 buf = (char *) alloca (10);
3911 sprintf (buf, "%d", ip->lineno);
3916 buf = (char *) alloca (20);
3917 timebuf = timestamp ();
3918 if (hp->type == T_DATE)
3919 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
3920 timebuf->tm_mday, timebuf->tm_year + 1900);
3922 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
3926 case T_SPEC_DEFINED:
3927 buf = " 0 "; /* Assume symbol is not defined */
3928 ip = &instack[indepth];
3929 SKIP_WHITE_SPACE (ip->bufp);
3930 if (*ip->bufp == '(') {
3932 ip->bufp++; /* Skip over the paren */
3933 SKIP_WHITE_SPACE (ip->bufp);
3936 if (!is_idstart[*ip->bufp])
3938 if (hp = lookup (ip->bufp, -1, -1)) {
3939 if (pcp_outfile && pcp_inside_if
3940 && (hp->type == T_CONST
3941 || (hp->type == T_MACRO && hp->value.defn->predefined)))
3942 /* Output a precondition for this macro use. */
3943 fprintf (pcp_outfile, "#define %s\n", hp->name);
3947 if (pcp_outfile && pcp_inside_if) {
3948 /* Output a precondition for this macro use */
3949 U_CHAR *cp = ip->bufp;
3950 fprintf (pcp_outfile, "#undef ");
3951 while (is_idchar[*cp]) /* Ick! */
3952 fputc (*cp++, pcp_outfile);
3953 putc ('\n', pcp_outfile);
3955 while (is_idchar[*ip->bufp])
3957 SKIP_WHITE_SPACE (ip->bufp);
3959 if (*ip->bufp != ')')
3967 error ("`defined' without an identifier");
3971 error ("cccp error: invalid special hash type"); /* time for gdb */
3975 check_expand (op, len);
3976 bcopy (buf, (char *) op->bufp, len);
3983 /* Routines to handle #directives */
3985 /* Handle #include and #import.
3986 This function expects to see "fname" or <fname> on the input. */
3989 do_include (buf, limit, op, keyword)
3990 U_CHAR *buf, *limit;
3992 struct directive *keyword;
3994 int importing = (keyword->type == T_IMPORT);
3995 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3996 static int import_warning = 0;
3997 char *fname; /* Dynamically allocated fname buffer */
4000 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4002 struct file_name_list *search_start = include; /* Chain of dirs to search */
4003 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4004 struct file_name_list *searchptr = 0;
4007 int f; /* file number */
4009 int retried = 0; /* Have already tried macro
4010 expanding the include line*/
4011 FILE_BUF trybuf; /* It got expanded into here */
4012 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4017 f= -1; /* JF we iz paranoid! */
4019 if (importing && warn_import && !inhibit_warnings
4020 && !instack[indepth].system_header_p && !import_warning) {
4022 warning ("using `#import' is not recommended");
4023 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4024 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4025 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4026 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4027 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4028 fprintf (stderr, " ... <real contents of file> ...\n");
4029 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4030 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4031 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4032 fprintf (stderr, "when it is equipped with such a conditional.\n");
4038 SKIP_WHITE_SPACE (fbeg);
4039 /* Discard trailing whitespace so we can easily see
4040 if we have parsed all the significant chars we were given. */
4041 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4047 /* Copy the operand text, concatenating the strings. */
4050 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4052 while (fin != limit) {
4053 while (fin != limit && *fin != '\"')
4058 /* If not at the end, there had better be another string. */
4059 /* Skip just horiz space, and don't go past limit. */
4060 while (fin != limit && is_hor_space[*fin]) fin++;
4061 if (fin != limit && *fin == '\"')
4069 /* We have "filename". Figure out directory this source
4070 file is coming from and put it on the front of the list. */
4072 /* If -I- was specified, don't search current dir, only spec'd ones. */
4073 if (ignore_srcdir) break;
4075 for (fp = &instack[indepth]; fp >= instack; fp--)
4080 if ((nam = fp->nominal_fname) != NULL) {
4081 /* Found a named file. Figure out dir of the file,
4082 and put it in front of the search list. */
4083 dsp[0].next = search_start;
4086 ep = rindex (nam, '/');
4088 ep = rindex (nam, ']');
4089 if (ep == NULL) ep = rindex (nam, '>');
4090 if (ep == NULL) ep = rindex (nam, ':');
4091 if (ep != NULL) ep++;
4095 dsp[0].fname = (char *) alloca (n + 1);
4096 strncpy (dsp[0].fname, nam, n);
4097 dsp[0].fname[n] = '\0';
4098 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4099 max_include_len = n + INCLUDE_LEN_FUDGE;
4101 dsp[0].fname = 0; /* Current directory */
4103 dsp[0].got_name_map = 0;
4112 while (fend != limit && *fend != '>') fend++;
4113 if (*fend == '>' && fend + 1 == limit) {
4115 /* If -I-, start with the first -I dir after the -I-. */
4116 if (first_bracket_include)
4117 search_start = first_bracket_include;
4125 * Support '#include xyz' like VAX-C to allow for easy use of all the
4126 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4127 * code from case '<' is repeated here) and generates a warning.
4129 if (isalpha(*(--fbeg))) {
4131 while (fend != limit && (!isspace(*fend))) fend++;
4132 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4133 if (fend == limit) {
4135 /* If -I-, start with the first -I dir after the -I-. */
4136 if (first_bracket_include)
4137 search_start = first_bracket_include;
4145 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4148 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
4149 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4150 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
4151 limit = buf + (trybuf.bufp - trybuf.buf);
4158 /* For #include_next, skip in the search path
4159 past the dir in which the containing file was found. */
4162 for (fp = &instack[indepth]; fp >= instack; fp--)
4163 if (fp->fname != NULL) {
4164 /* fp->dir is null if the containing file was specified
4165 with an absolute file name. In that case, don't skip anything. */
4167 search_start = fp->dir->next;
4176 error ("empty file name in `#%s'", keyword->name);
4180 /* Allocate this permanently, because it gets stored in the definitions
4182 fname = (char *) xmalloc (max_include_len + flen + 4);
4183 /* + 2 above for slash and terminating null. */
4184 /* + 2 added for '.h' on VMS (to support '#include filename') */
4186 /* If specified file name is absolute, just open it. */
4189 strncpy (fname, fbeg, flen);
4191 if (redundant_include_p (fname))
4194 f = lookup_import (fname, NULL_PTR);
4196 f = open_include_file (fname, NULL_PTR);
4198 return 0; /* Already included this file */
4200 /* Search directory path, trying to open the file.
4201 Copy each filename tried into FNAME. */
4203 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4204 if (searchptr->fname) {
4205 /* The empty string in a search path is ignored.
4206 This makes it possible to turn off entirely
4207 a standard piece of the list. */
4208 if (searchptr->fname[0] == 0)
4210 strcpy (fname, searchptr->fname);
4211 strcat (fname, "/");
4212 fname[strlen (fname) + flen] = 0;
4216 strncat (fname, fbeg, flen);
4218 /* Change this 1/2 Unix 1/2 VMS file specification into a
4219 full VMS file specification */
4220 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4221 /* Fix up the filename */
4222 hack_vms_include_specification (fname);
4224 /* This is a normal VMS filespec, so use it unchanged. */
4225 strncpy (fname, fbeg, flen);
4227 /* if it's '#include filename', add the missing .h */
4228 if (index(fname,'.')==NULL) {
4229 strcat (fname, ".h");
4234 f = lookup_import (fname, searchptr);
4236 f = open_include_file (fname, searchptr);
4238 return 0; /* Already included this file */
4240 else if (f == -1 && errno == EACCES)
4241 warning ("Header file %s exists, but is not readable", fname);
4243 if (redundant_include_p (fname)) {
4253 /* A file that was not found. */
4255 strncpy (fname, fbeg, flen);
4257 /* If generating dependencies and -MG was specified, we assume missing
4258 files are leaf files, living in the same directory as the source file
4259 or other similar place; these missing files may be generated from
4260 other files and may not exist yet (eg: y.tab.h). */
4261 if (print_deps_missing_files
4262 && print_deps > (angle_brackets || (system_include_depth > 0)))
4264 /* If it was requested as a system header file,
4265 then assume it belongs in the first place to look for such. */
4268 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4270 if (searchptr->fname)
4274 if (searchptr->fname[0] == 0)
4276 p = xmalloc (strlen (searchptr->fname)
4277 + strlen (fname) + 2);
4278 strcpy (p, searchptr->fname);
4281 deps_output (p, ' ');
4288 /* Otherwise, omit the directory, as if the file existed
4289 in the directory with the source. */
4290 deps_output (fname, ' ');
4293 /* If -M was specified, and this header file won't be added to the
4294 dependency list, then don't count this as an error, because we can
4295 still produce correct output. Otherwise, we can't produce correct
4296 output, because there may be dependencies we need inside the missing
4297 file, and we don't know what directory this missing file exists in. */
4299 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4300 warning ("No include path in which to find %s", fname);
4301 else if (search_start)
4302 error_from_errno (fname);
4304 error ("No include path in which to find %s", fname);
4308 /* Check to see if this include file is a once-only include file.
4311 struct file_name_list* ptr;
4313 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4314 if (!strcmp (ptr->fname, fname)) {
4316 return 0; /* This file was once'd. */
4320 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4321 if (!strcmp (ptr->fname, fname))
4322 break; /* This file was included before. */
4326 /* This is the first time for this file. */
4327 /* Add it to list of files included. */
4329 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4330 ptr->control_macro = 0;
4331 ptr->c_system_include_path = 0;
4332 ptr->next = all_include_files;
4333 all_include_files = ptr;
4334 ptr->fname = savestring (fname);
4335 ptr->got_name_map = 0;
4337 /* For -M, add this file to the dependencies. */
4338 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4339 deps_output (fname, ' ');
4342 /* Handle -H option. */
4343 if (print_include_names) {
4344 output_dots (stderr, indepth);
4345 fprintf (stderr, "%s\n", fname);
4349 system_include_depth++;
4351 /* Actually process the file. */
4352 add_import (f, fname); /* Record file on "seen" list for #import. */
4354 pcftry = (char *) alloca (strlen (fname) + 30);
4362 sprintf (pcftry, "%s%d", fname, pcfnum++);
4364 pcf = open (pcftry, O_RDONLY, 0666);
4370 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4372 || stat_f.st_dev != s.st_dev)
4374 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4375 /* Don't need it any more. */
4380 /* Don't need it at all. */
4385 } while (pcf != -1 && !pcfbuf);
4387 /* Actually process the file */
4389 pcfname = xmalloc (strlen (pcftry) + 1);
4390 strcpy (pcfname, pcftry);
4391 pcfinclude (pcfbuf, pcfbuflimit, fname, op);
4394 finclude (f, fname, op, is_system_include (fname), searchptr);
4397 system_include_depth--;
4402 /* Return nonzero if there is no need to include file NAME
4403 because it has already been included and it contains a conditional
4404 to make a repeated include do nothing. */
4407 redundant_include_p (name)
4410 struct file_name_list *l = all_include_files;
4411 for (; l; l = l->next)
4412 if (! strcmp (name, l->fname)
4414 && lookup (l->control_macro, -1, -1))
4419 /* Return nonzero if the given FILENAME is an absolute pathname which
4420 designates a file within one of the known "system" include file
4421 directories. We assume here that if the given FILENAME looks like
4422 it is the name of a file which resides either directly in a "system"
4423 include file directory, or within any subdirectory thereof, then the
4424 given file must be a "system" include file. This function tells us
4425 if we should suppress pedantic errors/warnings for the given FILENAME.
4427 The value is 2 if the file is a C-language system header file
4428 for which C++ should (on most systems) assume `extern "C"'. */
4431 is_system_include (filename)
4432 register char *filename;
4434 struct file_name_list *searchptr;
4436 for (searchptr = first_system_include; searchptr;
4437 searchptr = searchptr->next)
4438 if (searchptr->fname) {
4439 register char *sys_dir = searchptr->fname;
4440 register unsigned length = strlen (sys_dir);
4442 if (! strncmp (sys_dir, filename, length) && filename[length] == '/')
4444 if (searchptr->c_system_include_path)
4453 /* The file_name_map structure holds a mapping of file names for a
4454 particular directory. This mapping is read from the file named
4455 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4456 map filenames on a file system with severe filename restrictions,
4457 such as DOS. The format of the file name map file is just a series
4458 of lines with two tokens on each line. The first token is the name
4459 to map, and the second token is the actual name to use. */
4461 struct file_name_map
4463 struct file_name_map *map_next;
4468 #define FILE_NAME_MAP_FILE "header.gcc"
4470 /* Read a space delimited string of unlimited length from a stdio
4474 read_filename_string (ch, f)
4482 set = alloc = xmalloc (len + 1);
4486 while ((ch = getc (f)) != EOF && ! is_space[ch])
4488 if (set - alloc == len)
4491 alloc = xrealloc (alloc, len + 1);
4492 set = alloc + len / 2;
4502 /* Read the file name map file for DIRNAME. */
4504 static struct file_name_map *
4505 read_name_map (dirname)
4508 /* This structure holds a linked list of file name maps, one per
4510 struct file_name_map_list
4512 struct file_name_map_list *map_list_next;
4513 char *map_list_name;
4514 struct file_name_map *map_list_map;
4516 static struct file_name_map_list *map_list;
4517 register struct file_name_map_list *map_list_ptr;
4521 for (map_list_ptr = map_list; map_list_ptr;
4522 map_list_ptr = map_list_ptr->map_list_next)
4523 if (! strcmp (map_list_ptr->map_list_name, dirname))
4524 return map_list_ptr->map_list_map;
4526 map_list_ptr = ((struct file_name_map_list *)
4527 xmalloc (sizeof (struct file_name_map_list)));
4528 map_list_ptr->map_list_name = savestring (dirname);
4529 map_list_ptr->map_list_map = NULL;
4531 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
4532 strcpy (name, dirname);
4535 strcat (name, FILE_NAME_MAP_FILE);
4536 f = fopen (name, "r");
4538 map_list_ptr->map_list_map = NULL;
4542 int dirlen = strlen (dirname);
4544 while ((ch = getc (f)) != EOF)
4547 struct file_name_map *ptr;
4551 from = read_filename_string (ch, f);
4552 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4554 to = read_filename_string (ch, f);
4556 ptr = ((struct file_name_map *)
4557 xmalloc (sizeof (struct file_name_map)));
4558 ptr->map_from = from;
4560 /* Make the real filename absolute. */
4565 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4566 strcpy (ptr->map_to, dirname);
4567 ptr->map_to[dirlen] = '/';
4568 strcpy (ptr->map_to + dirlen + 1, to);
4572 ptr->map_next = map_list_ptr->map_list_map;
4573 map_list_ptr->map_list_map = ptr;
4575 while ((ch = getc (f)) != '\n')
4582 map_list_ptr->map_list_next = map_list;
4583 map_list = map_list_ptr;
4585 return map_list_ptr->map_list_map;
4588 /* Try to open include file FILENAME. SEARCHPTR is the directory
4589 being tried from the include file search path. This function maps
4590 filenames on file systems based on information read by
4594 open_include_file (filename, searchptr)
4596 struct file_name_list *searchptr;
4598 register struct file_name_map *map;
4599 register char *from;
4602 if (searchptr && ! searchptr->got_name_map)
4604 searchptr->name_map = read_name_map (searchptr->fname
4605 ? searchptr->fname : ".");
4606 searchptr->got_name_map = 1;
4609 /* First check the mapping for the directory we are using. */
4610 if (searchptr && searchptr->name_map)
4613 if (searchptr->fname)
4614 from += strlen (searchptr->fname) + 1;
4615 for (map = searchptr->name_map; map; map = map->map_next)
4617 if (! strcmp (map->map_from, from))
4619 /* Found a match. */
4620 return open (map->map_to, O_RDONLY, 0666);
4625 /* Try to find a mapping file for the particular directory we are
4626 looking in. Thus #include <sys/types.h> will look up sys/types.h
4627 in /usr/include/header.gcc and look up types.h in
4628 /usr/include/sys/header.gcc. */
4629 p = rindex (filename, '/');
4634 && strlen (searchptr->fname) == p - filename
4635 && ! strncmp (searchptr->fname, filename, p - filename))
4637 /* FILENAME is in SEARCHPTR, which we've already checked. */
4638 return open (filename, O_RDONLY, 0666);
4648 dir = (char *) alloca (p - filename + 1);
4649 bcopy (filename, dir, p - filename);
4650 dir[p - filename] = '\0';
4653 for (map = read_name_map (dir); map; map = map->map_next)
4654 if (! strcmp (map->map_from, from))
4655 return open (map->map_to, O_RDONLY, 0666);
4657 return open (filename, O_RDONLY, 0666);
4660 /* Process the contents of include file FNAME, already open on descriptor F,
4662 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4663 "system" include directories (as decided by the `is_system_include'
4665 DIRPTR is the link in the dir path through which this file was found,
4666 or 0 if the file name was absolute. */
4669 finclude (f, fname, op, system_header_p, dirptr)
4673 int system_header_p;
4674 struct file_name_list *dirptr;
4679 FILE_BUF *fp; /* For input stack frame */
4680 int missing_newline = 0;
4682 CHECK_DEPTH (return;);
4684 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
4686 perror_with_name (fname);
4691 fp = &instack[indepth + 1];
4692 bzero ((char *) fp, sizeof (FILE_BUF));
4693 fp->nominal_fname = fp->fname = fname;
4696 fp->if_stack = if_stack;
4697 fp->system_header_p = system_header_p;
4700 if (S_ISREG (st_mode)) {
4701 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
4704 /* Read the file contents, knowing that st_size is an upper bound
4705 on the number of bytes we can read. */
4706 fp->length = safe_read (f, fp->buf, st_size);
4707 if (fp->length < 0) goto nope;
4709 else if (S_ISDIR (st_mode)) {
4710 error ("directory `%s' specified in #include", fname);
4714 /* Cannot count its file size before reading.
4715 First read the entire file into heap and
4716 copy them into buffer on stack. */
4721 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
4724 i = safe_read (f, fp->buf + st_size, bsize - st_size);
4726 goto nope; /* error! */
4728 if (st_size != bsize)
4729 break; /* End of file */
4731 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
4734 fp->length = st_size;
4737 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
4738 /* Backslash-newline at end is not good enough. */
4739 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
4740 fp->buf[fp->length++] = '\n';
4741 missing_newline = 1;
4743 fp->buf[fp->length] = '\0';
4745 /* Close descriptor now, so nesting does not use lots of descriptors. */
4748 /* Must do this before calling trigraph_pcp, so that the correct file name
4749 will be printed in warning messages. */
4752 input_file_stack_tick++;
4757 output_line_command (fp, op, 0, enter_file);
4760 if (missing_newline)
4763 if (pedantic && missing_newline)
4764 pedwarn ("file does not end in newline");
4767 input_file_stack_tick++;
4768 output_line_command (&instack[indepth], op, 0, leave_file);
4774 perror_with_name (fname);
4779 /* Record that inclusion of the file named FILE
4780 should be controlled by the macro named MACRO_NAME.
4781 This means that trying to include the file again
4782 will do something if that macro is defined. */
4785 record_control_macro (file, macro_name)
4789 struct file_name_list *new;
4791 for (new = all_include_files; new; new = new->next) {
4792 if (!strcmp (new->fname, file)) {
4793 new->control_macro = macro_name;
4798 /* If the file is not in all_include_files, something's wrong. */
4802 /* Maintain and search list of included files, for #import. */
4804 #define IMPORT_HASH_SIZE 31
4806 struct import_file {
4810 struct import_file *next;
4813 /* Hash table of files already included with #include or #import. */
4815 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
4817 /* Hash a file name for import_hash_table. */
4825 while (*f) val += *f++;
4826 return (val%IMPORT_HASH_SIZE);
4829 /* Search for file FILENAME in import_hash_table.
4830 Return -2 if found, either a matching name or a matching inode.
4831 Otherwise, open the file and return a file descriptor if successful
4832 or -1 if unsuccessful. */
4835 lookup_import (filename, searchptr)
4837 struct file_name_list *searchptr;
4839 struct import_file *i;
4845 hashval = import_hash (filename);
4847 /* Attempt to find file in list of already included files */
4848 i = import_hash_table[hashval];
4851 if (!strcmp (filename, i->name))
4852 return -2; /* return found */
4855 /* Open it and try a match on inode/dev */
4856 fd = open_include_file (filename, searchptr);
4860 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
4861 i = import_hash_table[h];
4863 /* Compare the inode and the device.
4864 Supposedly on some systems the inode is not a scalar. */
4865 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
4866 && i->dev == sb.st_dev) {
4868 return -2; /* return found */
4873 return fd; /* Not found, return open file */
4876 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
4879 add_import (fd, fname)
4883 struct import_file *i;
4887 hashval = import_hash (fname);
4889 i = (struct import_file *)xmalloc (sizeof (struct import_file));
4890 i->name = (char *)xmalloc (strlen (fname)+1);
4891 strcpy (i->name, fname);
4892 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
4894 i->next = import_hash_table[hashval];
4895 import_hash_table[hashval] = i;
4898 /* Load the specified precompiled header into core, and verify its
4899 preconditions. PCF indicates the file descriptor to read, which must
4900 be a regular file. FNAME indicates the file name of the original
4901 header. *LIMIT will be set to an address one past the end of the file.
4902 If the preconditions of the file are not satisfied, the buffer is
4903 freed and we return 0. If the preconditions are satisfied, return
4904 the address of the buffer following the preconditions. The buffer, in
4905 this case, should never be freed because various pieces of it will
4906 be referred to until all precompiled strings are output at the end of
4910 check_precompiled (pcf, fname, limit)
4924 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
4927 if (S_ISREG (st_mode))
4929 buf = xmalloc (st_size + 2);
4930 length = safe_read (pcf, buf, st_size);
4937 if (length > 0 && buf[length-1] != '\n')
4938 buf[length++] = '\n';
4941 *limit = buf + length;
4943 /* File is in core. Check the preconditions. */
4944 if (!check_preconditions (buf))
4946 for (cp = buf; *cp; cp++)
4949 fprintf (stderr, "Using preinclude %s\n", fname);
4955 fprintf (stderr, "Cannot use preinclude %s\n", fname);
4961 /* PREC (null terminated) points to the preconditions of a
4962 precompiled header. These are a series of #define and #undef
4963 lines which must match the current contents of the hash
4966 check_preconditions (prec)
4973 lineend = (char *) index (prec, '\n');
4975 if (*prec++ != '#') {
4976 error ("Bad format encountered while reading precompiled file");
4979 if (!strncmp (prec, "define", 6)) {
4983 mdef = create_definition (prec, lineend, NULL_PTR);
4988 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
4989 || (hp->type != T_MACRO && hp->type != T_CONST)
4990 || (hp->type == T_MACRO
4991 && !compare_defs (mdef.defn, hp->value.defn)
4992 && (mdef.defn->length != 2
4993 || mdef.defn->expansion[0] != '\n'
4994 || mdef.defn->expansion[1] != ' ')))
4996 } else if (!strncmp (prec, "undef", 5)) {
5001 while (is_hor_space[(U_CHAR) *prec])
5004 while (is_idchar[(U_CHAR) *prec])
5008 if (lookup (name, len, -1))
5011 error ("Bad format encountered while reading precompiled file");
5016 /* They all passed successfully */
5020 /* Process the main body of a precompiled file. BUF points to the
5021 string section of the file, following the preconditions. LIMIT is one
5022 character past the end. NAME is the name of the file being read
5023 in. OP is the main output buffer */
5025 pcfinclude (buf, limit, name, op)
5026 U_CHAR *buf, *limit, *name;
5033 /* First in the file comes 4 bytes indicating the number of strings, */
5034 /* in network byte order. (MSB first). */
5036 nstrings = (nstrings << 8) | *cp++;
5037 nstrings = (nstrings << 8) | *cp++;
5038 nstrings = (nstrings << 8) | *cp++;
5040 /* Looping over each string... */
5041 while (nstrings--) {
5042 U_CHAR *string_start;
5043 U_CHAR *endofthiskey;
5047 /* Each string starts with a STRINGDEF structure (str), followed */
5048 /* by the text of the string (string_start) */
5050 /* First skip to a longword boundary */
5051 /* ??? Why a 4-byte boundary? On all machines? */
5052 /* NOTE: This works correctly even if HOST_WIDE_INT
5053 is narrower than a pointer.
5054 Do not try risky measures here to get another type to use!
5055 Do not include stddef.h--it will fail! */
5056 if ((HOST_WIDE_INT) cp & 3)
5057 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5059 /* Now get the string. */
5060 str = (STRINGDEF *) cp;
5061 string_start = cp += sizeof (STRINGDEF);
5063 for (; *cp; cp++) /* skip the string */
5066 /* We need to macro expand the string here to ensure that the
5067 proper definition environment is in place. If it were only
5068 expanded when we find out it is needed, macros necessary for
5069 its proper expansion might have had their definitions changed. */
5070 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5071 /* Lineno is already set in the precompiled file */
5072 str->contents = tmpbuf.buf;
5073 str->len = tmpbuf.length;
5075 str->filename = name;
5076 str->output_mark = outbuf.bufp - outbuf.buf;
5079 *stringlist_tailp = str;
5080 stringlist_tailp = &str->chain;
5082 /* Next comes a fourbyte number indicating the number of keys */
5083 /* for this string. */
5085 nkeys = (nkeys << 8) | *cp++;
5086 nkeys = (nkeys << 8) | *cp++;
5087 nkeys = (nkeys << 8) | *cp++;
5089 /* If this number is -1, then the string is mandatory. */
5093 /* Otherwise, for each key, */
5094 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5095 KEYDEF *kp = (KEYDEF *) cp;
5098 /* It starts with a KEYDEF structure */
5099 cp += sizeof (KEYDEF);
5101 /* Find the end of the key. At the end of this for loop we
5102 advance CP to the start of the next key using this variable. */
5103 endofthiskey = cp + strlen (cp);
5106 /* Expand the key, and enter it into the hash table. */
5107 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5108 tmpbuf.bufp = tmpbuf.buf;
5110 while (is_hor_space[*tmpbuf.bufp])
5112 if (!is_idstart[*tmpbuf.bufp]
5113 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5118 hp = lookup (tmpbuf.bufp, -1, -1);
5121 install (tmpbuf.bufp, -1, T_PCSTRING, 0, (char *) kp, -1);
5123 else if (hp->type == T_PCSTRING) {
5124 kp->chain = hp->value.keydef;
5125 hp->value.keydef = kp;
5131 /* This output_line_command serves to switch us back to the current
5132 input file in case some of these strings get output (which will
5133 result in line commands for the header file being output). */
5134 output_line_command (&instack[indepth], op, 0, enter_file);
5137 /* Called from rescan when it hits a key for strings. Mark them all */
5138 /* used and clean up. */
5145 for (kp = hp->value.keydef; kp; kp = kp->chain)
5146 kp->str->writeflag = 1;
5150 /* Write the output, interspersing precompiled strings in their */
5151 /* appropriate places. */
5155 STRINGDEF *next_string;
5156 U_CHAR *cur_buf_loc;
5157 int line_command_len = 80;
5158 char *line_command = xmalloc (line_command_len);
5161 /* In each run through the loop, either cur_buf_loc == */
5162 /* next_string_loc, in which case we print a series of strings, or */
5163 /* it is less than next_string_loc, in which case we write some of */
5165 cur_buf_loc = outbuf.buf;
5166 next_string = stringlist;
5168 while (cur_buf_loc < outbuf.bufp || next_string) {
5170 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5171 if (next_string->writeflag) {
5172 len = 4 * strlen (next_string->filename) + 32;
5173 while (len > line_command_len)
5174 line_command = xrealloc (line_command,
5175 line_command_len *= 2);
5176 sprintf (line_command, "\n# %d ", next_string->lineno);
5177 strcpy (quote_string (line_command + strlen (line_command),
5178 next_string->filename),
5180 safe_write (fileno (stdout), line_command, strlen (line_command));
5181 safe_write (fileno (stdout), next_string->contents, next_string->len);
5183 next_string = next_string->chain;
5187 ? (next_string->output_mark
5188 - (cur_buf_loc - outbuf.buf))
5189 : outbuf.bufp - cur_buf_loc);
5191 safe_write (fileno (stdout), cur_buf_loc, len);
5195 free (line_command);
5198 /* Pass a directive through to the output file.
5199 BUF points to the contents of the directive, as a contiguous string.
5200 LIMIT points to the first character past the end of the directive.
5201 KEYWORD is the keyword-table entry for the directive. */
5204 pass_thru_directive (buf, limit, op, keyword)
5205 U_CHAR *buf, *limit;
5207 struct directive *keyword;
5209 register unsigned keyword_length = keyword->length;
5211 check_expand (op, 1 + keyword_length + (limit - buf));
5213 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5214 op->bufp += keyword_length;
5215 if (limit != buf && buf[0] != ' ')
5217 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5218 op->bufp += (limit - buf);
5221 /* Count the line we have just made in the output,
5222 to get in sync properly. */
5227 /* The arglist structure is built by do_define to tell
5228 collect_definition where the argument names begin. That
5229 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5230 would contain pointers to the strings x, y, and z.
5231 Collect_definition would then build a DEFINITION node,
5232 with reflist nodes pointing to the places x, y, and z had
5233 appeared. So the arglist is just convenience data passed
5234 between these two routines. It is not kept around after
5235 the current #define has been processed and entered into the
5239 struct arglist *next;
5246 /* Create a DEFINITION node from a #define directive. Arguments are
5247 as for do_define. */
5249 create_definition (buf, limit, op)
5250 U_CHAR *buf, *limit;
5253 U_CHAR *bp; /* temp ptr into input buffer */
5254 U_CHAR *symname; /* remember where symbol name starts */
5255 int sym_length; /* and how long it is */
5256 int line = instack[indepth].lineno;
5257 char *file = instack[indepth].nominal_fname;
5261 int arglengths = 0; /* Accumulate lengths of arg names
5262 plus number of args. */
5267 while (is_hor_space[*bp])
5270 symname = bp; /* remember where it starts */
5271 sym_length = check_macro_name (bp, "macro");
5274 /* Lossage will occur if identifiers or control keywords are broken
5275 across lines using backslash. This is not the right place to take
5279 struct arglist *arg_ptrs = NULL;
5282 bp++; /* skip '(' */
5283 SKIP_WHITE_SPACE (bp);
5285 /* Loop over macro argument names. */
5286 while (*bp != ')') {
5287 struct arglist *temp;
5289 temp = (struct arglist *) alloca (sizeof (struct arglist));
5291 temp->next = arg_ptrs;
5292 temp->argno = argno++;
5293 temp->rest_args = 0;
5297 pedwarn ("another parameter follows `%s'",
5300 if (!is_idstart[*bp])
5301 pedwarn ("invalid character in macro parameter name");
5303 /* Find the end of the arg name. */
5304 while (is_idchar[*bp]) {
5306 /* do we have a "special" rest-args extension here? */
5307 if (limit - bp > REST_EXTENSION_LENGTH &&
5308 strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5310 temp->rest_args = 1;
5314 temp->length = bp - temp->name;
5316 bp += REST_EXTENSION_LENGTH;
5317 arglengths += temp->length + 2;
5318 SKIP_WHITE_SPACE (bp);
5319 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5320 error ("badly punctuated parameter list in `#define'");
5325 SKIP_WHITE_SPACE (bp);
5328 error ("unterminated parameter list in `#define'");
5332 struct arglist *otemp;
5334 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5335 if (temp->length == otemp->length &&
5336 strncmp (temp->name, otemp->name, temp->length) == 0) {
5339 name = (U_CHAR *) alloca (temp->length + 1);
5340 (void) strncpy (name, temp->name, temp->length);
5341 name[temp->length] = '\0';
5342 error ("duplicate argument name `%s' in `#define'", name);
5348 ++bp; /* skip paren */
5349 /* Skip spaces and tabs if any. */
5350 while (bp < limit && (*bp == ' ' || *bp == '\t'))
5352 /* now everything from bp before limit is the definition. */
5353 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5354 defn->rest_args = rest_args;
5356 /* Now set defn->args.argnames to the result of concatenating
5357 the argument names in reverse order
5358 with comma-space between them. */
5359 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5361 struct arglist *temp;
5363 for (temp = arg_ptrs; temp; temp = temp->next) {
5364 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5366 if (temp->next != 0) {
5367 defn->args.argnames[i++] = ',';
5368 defn->args.argnames[i++] = ' ';
5371 defn->args.argnames[i] = 0;
5374 /* Simple expansion or empty definition. */
5380 case '\t': case ' ':
5381 /* Skip spaces and tabs. */
5382 while (++bp < limit && (*bp == ' ' || *bp == '\t'))
5386 case '!': case '"': case '#': case '%': case '&': case '\'':
5387 case ')': case '*': case '+': case ',': case '-': case '.':
5388 case '/': case ':': case ';': case '<': case '=': case '>':
5389 case '?': case '[': case '\\': case ']': case '^': case '{':
5390 case '|': case '}': case '~':
5391 warning ("missing white space after `#define %.*s'",
5392 sym_length, symname);
5396 pedwarn ("missing white space after `#define %.*s'",
5397 sym_length, symname);
5401 /* Now everything from bp before limit is the definition. */
5402 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5403 defn->args.argnames = (U_CHAR *) "";
5409 /* OP is null if this is a predefinition */
5410 defn->predefined = !op;
5412 mdef.symnam = symname;
5413 mdef.symlen = sym_length;
5422 /* Process a #define command.
5423 BUF points to the contents of the #define command, as a contiguous string.
5424 LIMIT points to the first character past the end of the definition.
5425 KEYWORD is the keyword-table entry for #define. */
5428 do_define (buf, limit, op, keyword)
5429 U_CHAR *buf, *limit;
5431 struct directive *keyword;
5436 /* If this is a precompiler run (with -pcp) pass thru #define commands. */
5437 if (pcp_outfile && op)
5438 pass_thru_directive (buf, limit, op, keyword);
5440 mdef = create_definition (buf, limit, op);
5444 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5448 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5450 /* Redefining a precompiled key is ok. */
5451 if (hp->type == T_PCSTRING)
5453 /* Redefining a macro is ok if the definitions are the same. */
5454 else if (hp->type == T_MACRO)
5455 ok = ! compare_defs (mdef.defn, hp->value.defn);
5456 /* Redefining a constant is ok with -D. */
5457 else if (hp->type == T_CONST)
5458 ok = ! done_initializing;
5459 /* Print the warning if it's not ok. */
5461 U_CHAR *msg; /* what pain... */
5463 /* If we are passing through #define and #undef directives, do
5464 that for this re-definition now. */
5465 if (debug_output && op)
5466 pass_thru_directive (buf, limit, op, keyword);
5468 msg = (U_CHAR *) alloca (mdef.symlen + 22);
5470 bcopy ((char *) mdef.symnam, (char *) (msg + 1), mdef.symlen);
5471 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
5473 if (hp->type == T_MACRO)
5474 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5475 "this is the location of the previous definition");
5477 /* Replace the old definition. */
5479 hp->value.defn = mdef.defn;
5481 /* If we are passing through #define and #undef directives, do
5482 that for this new definition now. */
5483 if (debug_output && op)
5484 pass_thru_directive (buf, limit, op, keyword);
5485 install (mdef.symnam, mdef.symlen, T_MACRO, 0,
5486 (char *) mdef.defn, hashcode);
5497 /* Check a purported macro name SYMNAME, and yield its length.
5498 USAGE is the kind of name this is intended for. */
5501 check_macro_name (symname, usage)
5508 for (p = symname; is_idchar[*p]; p++)
5510 sym_length = p - symname;
5511 if (sym_length == 0)
5512 error ("invalid %s name", usage);
5513 else if (!is_idstart[*symname]) {
5514 U_CHAR *msg; /* what pain... */
5515 msg = (U_CHAR *) alloca (sym_length + 1);
5516 bcopy ((char *) symname, (char *) msg, sym_length);
5517 msg[sym_length] = 0;
5518 error ("invalid %s name `%s'", usage, msg);
5520 if (! strncmp (symname, "defined", 7) && sym_length == 7)
5521 error ("invalid %s name `defined'", usage);
5527 * return zero if two DEFINITIONs are isomorphic
5530 compare_defs (d1, d2)
5531 DEFINITION *d1, *d2;
5533 register struct reflist *a1, *a2;
5534 register U_CHAR *p1 = d1->expansion;
5535 register U_CHAR *p2 = d2->expansion;
5538 if (d1->nargs != d2->nargs)
5540 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5542 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5543 a1 = a1->next, a2 = a2->next) {
5544 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
5545 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5546 || a1->argno != a2->argno
5547 || a1->stringify != a2->stringify
5548 || a1->raw_before != a2->raw_before
5549 || a1->raw_after != a2->raw_after)
5557 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5558 p2, d2->length - (p2 - d2->expansion), 1))
5563 /* Return 1 if two parts of two macro definitions are effectively different.
5564 One of the parts starts at BEG1 and has LEN1 chars;
5565 the other has LEN2 chars at BEG2.
5566 Any sequence of whitespace matches any other sequence of whitespace.
5567 FIRST means these parts are the first of a macro definition;
5568 so ignore leading whitespace entirely.
5569 LAST means these parts are the last of a macro definition;
5570 so ignore trailing whitespace entirely. */
5573 comp_def_part (first, beg1, len1, beg2, len2, last)
5575 U_CHAR *beg1, *beg2;
5579 register U_CHAR *end1 = beg1 + len1;
5580 register U_CHAR *end2 = beg2 + len2;
5582 while (beg1 != end1 && is_space[*beg1]) beg1++;
5583 while (beg2 != end2 && is_space[*beg2]) beg2++;
5586 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5587 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5589 while (beg1 != end1 && beg2 != end2) {
5590 if (is_space[*beg1] && is_space[*beg2]) {
5591 while (beg1 != end1 && is_space[*beg1]) beg1++;
5592 while (beg2 != end2 && is_space[*beg2]) beg2++;
5593 } else if (*beg1 == *beg2) {
5597 return (beg1 != end1) || (beg2 != end2);
5600 /* Read a replacement list for a macro with parameters.
5601 Build the DEFINITION structure.
5602 Reads characters of text starting at BUF until END.
5603 ARGLIST specifies the formal parameters to look for
5604 in the text of the definition; NARGS is the number of args
5605 in that list, or -1 for a macro name that wants no argument list.
5606 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5607 and NAMELEN is its length in characters.
5609 Note that comments and backslash-newlines have already been deleted
5610 from the argument. */
5612 /* Leading and trailing Space, Tab, etc. are converted to markers
5613 Newline Space, Newline Tab, etc.
5614 Newline Space makes a space in the final output
5615 but is discarded if stringified. (Newline Tab is similar but
5616 makes a Tab instead.)
5618 If there is no trailing whitespace, a Newline Space is added at the end
5619 to prevent concatenation that would be contrary to the standard. */
5622 collect_expansion (buf, end, nargs, arglist)
5625 struct arglist *arglist;
5628 register U_CHAR *p, *limit, *lastp, *exp_p;
5629 struct reflist *endpat = NULL;
5630 /* Pointer to first nonspace after last ## seen. */
5632 /* Pointer to first nonspace after last single-# seen. */
5633 U_CHAR *stringify = 0;
5635 int expected_delimiter = '\0';
5637 /* Scan thru the replacement list, ignoring comments and quoted
5638 strings, picking up on the macro calls. It does a linear search
5639 thru the arg list on every potential symbol. Profiling might say
5640 that something smarter should happen. */
5645 /* Find the beginning of the trailing whitespace. */
5646 /* Find end of leading whitespace. */
5649 while (p < limit && is_space[limit[-1]]) limit--;
5650 while (p < limit && is_space[*p]) p++;
5652 /* Allocate space for the text in the macro definition.
5653 Leading and trailing whitespace chars need 2 bytes each.
5654 Each other input char may or may not need 1 byte,
5655 so this is an upper bound.
5656 The extra 2 are for invented trailing newline-marker and final null. */
5657 maxsize = (sizeof (DEFINITION)
5658 + 2 * (end - limit) + 2 * (p - buf)
5660 defn = (DEFINITION *) xcalloc (1, maxsize);
5662 defn->nargs = nargs;
5663 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5668 /* Convert leading whitespace to Newline-markers. */
5669 while (p < limit && is_space[*p]) {
5674 if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
5675 error ("`##' at start of macro definition");
5679 /* Process the main body of the definition. */
5681 int skipped_arg = 0;
5682 register U_CHAR c = *p++;
5690 if (expected_delimiter != '\0') {
5691 if (c == expected_delimiter)
5692 expected_delimiter = '\0';
5694 expected_delimiter = c;
5697 /* Special hack: if a \# is written in the #define
5698 include a # in the definition. This is useless for C code
5699 but useful for preprocessing other things. */
5702 /* \# quotes a # even outside of strings. */
5703 if (p < limit && *p == '#' && !expected_delimiter) {
5706 } else if (p < limit && expected_delimiter) {
5707 /* In a string, backslash goes through
5708 and makes next char ordinary. */
5714 /* # is ordinary inside a string. */
5715 if (expected_delimiter)
5717 if (p < limit && *p == '#') {
5718 /* ##: concatenate preceding and following tokens. */
5719 /* Take out the first #, discard preceding whitespace. */
5721 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5723 /* Skip the second #. */
5725 /* Discard following whitespace. */
5726 SKIP_WHITE_SPACE (p);
5729 error ("`##' at end of macro definition");
5730 } else if (nargs >= 0) {
5731 /* Single #: stringify following argument ref.
5732 Don't leave the # in the expansion. */
5734 SKIP_WHITE_SPACE (p);
5735 if (p == limit || ! is_idstart[*p])
5736 error ("`#' operator is not followed by a macro argument name");
5743 /* In -traditional mode, recognize arguments inside strings and
5744 and character constants, and ignore special properties of #.
5745 Arguments inside strings are considered "stringified", but no
5746 extra quote marks are supplied. */
5750 if (expected_delimiter != '\0') {
5751 if (c == expected_delimiter)
5752 expected_delimiter = '\0';
5754 expected_delimiter = c;
5758 /* Backslash quotes delimiters and itself, but not macro args. */
5759 if (expected_delimiter != 0 && p < limit
5760 && (*p == expected_delimiter || *p == '\\')) {
5767 if (expected_delimiter != '\0') /* No comments inside strings. */
5770 /* If we find a comment that wasn't removed by handle_directive,
5771 this must be -traditional. So replace the comment with
5775 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5778 /* Mark this as a concatenation-point, as if it had been ##. */
5786 /* Handle the start of a symbol. */
5787 if (is_idchar[c] && nargs > 0) {
5788 U_CHAR *id_beg = p - 1;
5792 while (p != limit && is_idchar[*p]) p++;
5793 id_len = p - id_beg;
5795 if (is_idstart[c]) {
5796 register struct arglist *arg;
5798 for (arg = arglist; arg != NULL; arg = arg->next) {
5799 struct reflist *tpat;
5801 if (arg->name[0] == c
5802 && arg->length == id_len
5803 && strncmp (arg->name, id_beg, id_len) == 0) {
5804 if (expected_delimiter && warn_stringify) {
5806 warning ("macro argument `%.*s' is stringified.",
5809 warning ("macro arg `%.*s' would be stringified with -traditional.",
5813 /* If ANSI, don't actually substitute inside a string. */
5814 if (!traditional && expected_delimiter)
5816 /* make a pat node for this arg and append it to the end of
5818 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
5820 tpat->raw_before = concat == id_beg;
5821 tpat->raw_after = 0;
5822 tpat->rest_args = arg->rest_args;
5823 tpat->stringify = (traditional ? expected_delimiter != '\0'
5824 : stringify == id_beg);
5827 defn->pattern = tpat;
5829 endpat->next = tpat;
5832 tpat->argno = arg->argno;
5833 tpat->nchars = exp_p - lastp;
5835 register U_CHAR *p1 = p;
5836 SKIP_WHITE_SPACE (p1);
5837 if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
5838 tpat->raw_after = 1;
5840 lastp = exp_p; /* place to start copying from next time */
5847 /* If this was not a macro arg, copy it into the expansion. */
5848 if (! skipped_arg) {
5849 register U_CHAR *lim1 = p;
5853 if (stringify == id_beg)
5854 error ("`#' operator should be followed by a macro argument name");
5859 if (!traditional && expected_delimiter == 0) {
5860 /* There is no trailing whitespace, so invent some in ANSI mode.
5861 But not if "inside a string" (which in ANSI mode
5862 happens only for -D option). */
5869 defn->length = exp_p - defn->expansion;
5871 /* Crash now if we overrun the allocated size. */
5872 if (defn->length + 1 > maxsize)
5876 /* This isn't worth the time it takes. */
5877 /* give back excess storage */
5878 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
5885 do_assert (buf, limit, op, keyword)
5886 U_CHAR *buf, *limit;
5888 struct directive *keyword;
5890 U_CHAR *bp; /* temp ptr into input buffer */
5891 U_CHAR *symname; /* remember where symbol name starts */
5892 int sym_length; /* and how long it is */
5893 struct arglist *tokens = NULL;
5895 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5896 pedwarn ("ANSI C does not allow `#assert'");
5900 while (is_hor_space[*bp])
5903 symname = bp; /* remember where it starts */
5904 sym_length = check_macro_name (bp, "assertion");
5906 /* #define doesn't do this, but we should. */
5907 SKIP_WHITE_SPACE (bp);
5909 /* Lossage will occur if identifiers or control tokens are broken
5910 across lines using backslash. This is not the right place to take
5914 error ("missing token-sequence in `#assert'");
5921 bp++; /* skip '(' */
5922 SKIP_WHITE_SPACE (bp);
5924 tokens = read_token_list (&bp, limit, &error_flag);
5928 error ("empty token-sequence in `#assert'");
5932 ++bp; /* skip paren */
5933 SKIP_WHITE_SPACE (bp);
5936 /* If this name isn't already an assertion name, make it one.
5937 Error if it was already in use in some other way. */
5940 ASSERTION_HASHNODE *hp;
5941 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
5942 struct tokenlist_list *value
5943 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
5945 hp = assertion_lookup (symname, sym_length, hashcode);
5947 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
5948 error ("`defined' redefined as assertion");
5949 hp = assertion_install (symname, sym_length, hashcode);
5952 /* Add the spec'd token-sequence to the list of such. */
5953 value->tokens = tokens;
5954 value->next = hp->value;
5962 do_unassert (buf, limit, op, keyword)
5963 U_CHAR *buf, *limit;
5965 struct directive *keyword;
5967 U_CHAR *bp; /* temp ptr into input buffer */
5968 U_CHAR *symname; /* remember where symbol name starts */
5969 int sym_length; /* and how long it is */
5971 struct arglist *tokens = NULL;
5972 int tokens_specified = 0;
5974 if (pedantic && done_initializing && !instack[indepth].system_header_p)
5975 pedwarn ("ANSI C does not allow `#unassert'");
5979 while (is_hor_space[*bp])
5982 symname = bp; /* remember where it starts */
5983 sym_length = check_macro_name (bp, "assertion");
5985 /* #define doesn't do this, but we should. */
5986 SKIP_WHITE_SPACE (bp);
5988 /* Lossage will occur if identifiers or control tokens are broken
5989 across lines using backslash. This is not the right place to take
5995 bp++; /* skip '(' */
5996 SKIP_WHITE_SPACE (bp);
5998 tokens = read_token_list (&bp, limit, &error_flag);
6002 error ("empty token list in `#unassert'");
6006 tokens_specified = 1;
6008 ++bp; /* skip paren */
6009 SKIP_WHITE_SPACE (bp);
6013 ASSERTION_HASHNODE *hp;
6014 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6015 struct tokenlist_list *tail, *prev;
6017 hp = assertion_lookup (symname, sym_length, hashcode);
6021 /* If no token list was specified, then eliminate this assertion
6023 if (! tokens_specified) {
6024 struct tokenlist_list *next;
6025 for (tail = hp->value; tail; tail = next) {
6027 free_token_list (tail->tokens);
6030 delete_assertion (hp);
6032 /* If a list of tokens was given, then delete any matching list. */
6037 struct tokenlist_list *next = tail->next;
6038 if (compare_token_lists (tail->tokens, tokens)) {
6042 hp->value = tail->next;
6043 free_token_list (tail->tokens);
6056 /* Test whether there is an assertion named NAME
6057 and optionally whether it has an asserted token list TOKENS.
6058 NAME is not null terminated; its length is SYM_LENGTH.
6059 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6062 check_assertion (name, sym_length, tokens_specified, tokens)
6065 int tokens_specified;
6066 struct arglist *tokens;
6068 ASSERTION_HASHNODE *hp;
6069 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6071 if (pedantic && !instack[indepth].system_header_p)
6072 pedwarn ("ANSI C does not allow testing assertions");
6074 hp = assertion_lookup (name, sym_length, hashcode);
6076 /* It is not an assertion; just return false. */
6079 /* If no token list was specified, then value is 1. */
6080 if (! tokens_specified)
6084 struct tokenlist_list *tail;
6088 /* If a list of tokens was given,
6089 then succeed if the assertion records a matching list. */
6092 if (compare_token_lists (tail->tokens, tokens))
6097 /* Fail if the assertion has no matching list. */
6102 /* Compare two lists of tokens for equality including order of tokens. */
6105 compare_token_lists (l1, l2)
6106 struct arglist *l1, *l2;
6109 if (l1->length != l2->length)
6111 if (strncmp (l1->name, l2->name, l1->length))
6117 /* Succeed if both lists end at the same time. */
6121 /* Read a space-separated list of tokens ending in a close parenthesis.
6122 Return a list of strings, in the order they were written.
6123 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6124 Parse the text starting at *BPP, and update *BPP.
6125 Don't parse beyond LIMIT. */
6127 static struct arglist *
6128 read_token_list (bpp, limit, error_flag)
6133 struct arglist *token_ptrs = 0;
6139 /* Loop over the assertion value tokens. */
6141 struct arglist *temp;
6145 /* Find the end of the token. */
6149 } else if (*bp == ')') {
6154 } else if (*bp == '"' || *bp == '\'')
6155 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6157 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6158 && *bp != '"' && *bp != '\'' && bp != limit)
6161 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6162 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6163 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6164 temp->name[bp - beg] = 0;
6165 temp->next = token_ptrs;
6167 temp->length = bp - beg;
6169 SKIP_WHITE_SPACE (bp);
6172 error ("unterminated token sequence in `#assert' or `#unassert'");
6179 /* We accumulated the names in reverse order.
6180 Now reverse them to get the proper order. */
6182 register struct arglist *prev = 0, *this, *next;
6183 for (this = token_ptrs; this; this = next) {
6193 free_token_list (tokens)
6194 struct arglist *tokens;
6197 struct arglist *next = tokens->next;
6198 free (tokens->name);
6205 * Install a name in the assertion hash table.
6207 * If LEN is >= 0, it is the length of the name.
6208 * Otherwise, compute the length by scanning the entire name.
6210 * If HASH is >= 0, it is the precomputed hash code.
6211 * Otherwise, compute the hash code.
6213 static ASSERTION_HASHNODE *
6214 assertion_install (name, len, hash)
6219 register ASSERTION_HASHNODE *hp;
6220 register int i, bucket;
6221 register U_CHAR *p, *q;
6223 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6224 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6226 hp->bucket_hdr = &assertion_hashtab[bucket];
6227 hp->next = assertion_hashtab[bucket];
6228 assertion_hashtab[bucket] = hp;
6230 if (hp->next != NULL)
6231 hp->next->prev = hp;
6234 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6237 for (i = 0; i < len; i++)
6244 * find the most recent hash node for name name (ending with first
6245 * non-identifier char) installed by install
6247 * If LEN is >= 0, it is the length of the name.
6248 * Otherwise, compute the length by scanning the entire name.
6250 * If HASH is >= 0, it is the precomputed hash code.
6251 * Otherwise, compute the hash code.
6253 static ASSERTION_HASHNODE *
6254 assertion_lookup (name, len, hash)
6259 register ASSERTION_HASHNODE *bucket;
6261 bucket = assertion_hashtab[hash];
6263 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
6265 bucket = bucket->next;
6271 delete_assertion (hp)
6272 ASSERTION_HASHNODE *hp;
6275 if (hp->prev != NULL)
6276 hp->prev->next = hp->next;
6277 if (hp->next != NULL)
6278 hp->next->prev = hp->prev;
6280 /* make sure that the bucket chain header that
6281 the deleted guy was on points to the right thing afterwards. */
6282 if (hp == *hp->bucket_hdr)
6283 *hp->bucket_hdr = hp->next;
6289 * interpret #line command. Remembers previously seen fnames
6290 * in its very own hash table.
6292 #define FNAME_HASHSIZE 37
6295 do_line (buf, limit, op, keyword)
6296 U_CHAR *buf, *limit;
6298 struct directive *keyword;
6300 register U_CHAR *bp;
6301 FILE_BUF *ip = &instack[indepth];
6304 enum file_change_code file_change = same_file;
6306 /* Expand any macros. */
6307 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6309 /* Point to macroexpanded line, which is null-terminated now. */
6311 SKIP_WHITE_SPACE (bp);
6313 if (!isdigit (*bp)) {
6314 error ("invalid format `#line' command");
6318 /* The Newline at the end of this line remains to be processed.
6319 To put the next line at the specified line number,
6320 we must store a line number now that is one less. */
6321 new_lineno = atoi (bp) - 1;
6323 /* NEW_LINENO is one less than the actual line number here. */
6324 if (pedantic && new_lineno < 0)
6325 pedwarn ("line number out of range in `#line' command");
6327 /* skip over the line number. */
6328 while (isdigit (*bp))
6331 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6332 if (*bp && !is_space[*bp]) {
6333 error ("invalid format `#line' command");
6338 SKIP_WHITE_SPACE (bp);
6341 static HASHNODE *fname_table[FNAME_HASHSIZE];
6342 HASHNODE *hp, **hash_bucket;
6348 /* Turn the file name, which is a character string literal,
6349 into a null-terminated string. Do this in place. */
6352 switch ((*p++ = *bp++)) {
6354 error ("invalid format `#line' command");
6359 char *bpc = (char *) bp;
6360 int c = parse_escape (&bpc);
6361 bp = (U_CHAR *) bpc;
6374 fname_length = p - fname;
6376 SKIP_WHITE_SPACE (bp);
6379 pedwarn ("garbage at end of `#line' command");
6381 file_change = enter_file;
6382 else if (*bp == '2')
6383 file_change = leave_file;
6384 else if (*bp == '3')
6385 ip->system_header_p = 1;
6386 else if (*bp == '4')
6387 ip->system_header_p = 2;
6389 error ("invalid format `#line' command");
6394 SKIP_WHITE_SPACE (bp);
6396 ip->system_header_p = 1;
6398 SKIP_WHITE_SPACE (bp);
6401 ip->system_header_p = 2;
6403 SKIP_WHITE_SPACE (bp);
6406 error ("invalid format `#line' command");
6412 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6413 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6414 if (hp->length == fname_length &&
6415 strncmp (hp->value.cpval, fname, fname_length) == 0) {
6416 ip->nominal_fname = hp->value.cpval;
6420 /* Didn't find it; cons up a new one. */
6421 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6422 hp->next = *hash_bucket;
6425 hp->length = fname_length;
6426 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6427 bcopy (fname, hp->value.cpval, fname_length);
6430 error ("invalid format `#line' command");
6434 ip->lineno = new_lineno;
6435 output_line_command (ip, op, 0, file_change);
6436 check_expand (op, ip->length - (ip->bufp - ip->buf));
6441 * remove the definition of a symbol from the symbol table.
6442 * according to un*x /lib/cpp, it is not an error to undef
6443 * something that has no definitions, so it isn't one here either.
6447 do_undef (buf, limit, op, keyword)
6448 U_CHAR *buf, *limit;
6450 struct directive *keyword;
6454 U_CHAR *orig_buf = buf;
6456 /* If this is a precompiler run (with -pcp) pass thru #undef commands. */
6457 if (pcp_outfile && op)
6458 pass_thru_directive (buf, limit, op, keyword);
6460 SKIP_WHITE_SPACE (buf);
6461 sym_length = check_macro_name (buf, "macro");
6463 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6464 /* If we are generating additional info for debugging (with -g) we
6465 need to pass through all effective #undef commands. */
6466 if (debug_output && op)
6467 pass_thru_directive (orig_buf, limit, op, keyword);
6468 if (hp->type != T_MACRO)
6469 warning ("undefining `%s'", hp->name);
6475 SKIP_WHITE_SPACE (buf);
6477 pedwarn ("garbage after `#undef' directive");
6483 * Report an error detected by the program we are processing.
6484 * Use the text of the line in the error message.
6485 * (We use error because it prints the filename & line#.)
6489 do_error (buf, limit, op, keyword)
6490 U_CHAR *buf, *limit;
6492 struct directive *keyword;
6494 int length = limit - buf;
6495 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6496 bcopy ((char *) buf, (char *) copy, length);
6498 SKIP_WHITE_SPACE (copy);
6499 error ("#error %s", copy);
6504 * Report a warning detected by the program we are processing.
6505 * Use the text of the line in the warning message, then continue.
6506 * (We use error because it prints the filename & line#.)
6510 do_warning (buf, limit, op, keyword)
6511 U_CHAR *buf, *limit;
6513 struct directive *keyword;
6515 int length = limit - buf;
6516 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6517 bcopy ((char *) buf, (char *) copy, length);
6519 SKIP_WHITE_SPACE (copy);
6520 warning ("#warning %s", copy);
6524 /* Remember the name of the current file being read from so that we can
6525 avoid ever including it again. */
6531 FILE_BUF *ip = NULL;
6533 for (i = indepth; i >= 0; i--)
6534 if (instack[i].fname != NULL) {
6540 struct file_name_list *new;
6542 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6543 new->next = dont_repeat_files;
6544 dont_repeat_files = new;
6545 new->fname = savestring (ip->fname);
6546 new->control_macro = 0;
6547 new->got_name_map = 0;
6548 new->c_system_include_path = 0;
6553 /* #ident has already been copied to the output file, so just ignore it. */
6556 do_ident (buf, limit)
6557 U_CHAR *buf, *limit;
6561 FILE_BUF *op = &outbuf;
6563 /* Allow #ident in system headers, since that's not user's fault. */
6564 if (pedantic && !instack[indepth].system_header_p)
6565 pedwarn ("ANSI C does not allow `#ident'");
6567 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6568 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6569 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6570 limit = buf + (trybuf.bufp - trybuf.buf);
6571 len = (limit - buf);
6574 /* Output directive name. */
6575 check_expand (op, 8);
6576 bcopy ("#ident ", (char *) op->bufp, 7);
6579 /* Output the expanded argument line. */
6580 check_expand (op, len);
6581 bcopy ((char *) buf, (char *) op->bufp, len);
6587 /* #pragma and its argument line have already been copied to the output file.
6588 Just check for some recognized pragmas that need validation here. */
6591 do_pragma (buf, limit)
6592 U_CHAR *buf, *limit;
6594 while (*buf == ' ' || *buf == '\t')
6596 if (!strncmp (buf, "once", 4)) {
6597 /* Allow #pragma once in system headers, since that's not the user's
6599 if (!instack[indepth].system_header_p)
6600 warning ("`#pragma once' is obsolete");
6604 if (!strncmp (buf, "implementation", 14)) {
6605 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6606 been included yet. */
6607 struct file_name_list *ptr;
6608 U_CHAR *p = buf + 14, *fname, *inc_fname;
6609 SKIP_WHITE_SPACE (p);
6610 if (*p == '\n' || *p != '\"')
6614 if (p = (U_CHAR *) index (fname, '\"'))
6617 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6618 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6619 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6620 if (inc_fname && !strcmp (inc_fname, fname))
6621 warning ("`#pragma implementation' for `%s' appears after file is included",
6630 /* This was a fun hack, but #pragma seems to start to be useful.
6631 By failing to recognize it, we pass it through unchanged to cc1. */
6634 * the behavior of the #pragma directive is implementation defined.
6635 * this implementation defines it as follows.
6642 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6645 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6647 execl ("/usr/games/hack", "#pragma", 0);
6648 execl ("/usr/games/rogue", "#pragma", 0);
6649 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6650 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6652 fatal ("You are in a maze of twisty compiler features, all different");
6656 /* Just ignore #sccs, on systems where we define it at all. */
6662 pedwarn ("ANSI C does not allow `#sccs'");
6667 * handle #if command by
6668 * 1) inserting special `defined' keyword into the hash table
6669 * that gets turned into 0 or 1 by special_symbol (thus,
6670 * if the luser has a symbol called `defined' already, it won't
6671 * work inside the #if command)
6672 * 2) rescan the input into a temporary output buffer
6673 * 3) pass the output buffer to the yacc parser and collect a value
6674 * 4) clean up the mess left from steps 1 and 2.
6675 * 5) call conditional_skip to skip til the next #endif (etc.),
6676 * or not, depending on the value from step 3.
6680 do_if (buf, limit, op, keyword)
6681 U_CHAR *buf, *limit;
6683 struct directive *keyword;
6686 FILE_BUF *ip = &instack[indepth];
6688 value = eval_if_expression (buf, limit - buf);
6689 conditional_skip (ip, value == 0, T_IF, NULL_PTR);
6694 * handle a #elif directive by not changing if_stack either.
6695 * see the comment above do_else.
6699 do_elif (buf, limit, op, keyword)
6700 U_CHAR *buf, *limit;
6702 struct directive *keyword;
6705 FILE_BUF *ip = &instack[indepth];
6707 if (if_stack == instack[indepth].if_stack) {
6708 error ("`#elif' not within a conditional");
6711 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6712 error ("`#elif' after `#else'");
6713 fprintf (stderr, " (matches line %d", if_stack->lineno);
6714 if (if_stack->fname != NULL && ip->fname != NULL &&
6715 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6716 fprintf (stderr, ", file %s", if_stack->fname);
6717 fprintf (stderr, ")\n");
6719 if_stack->type = T_ELIF;
6722 if (if_stack->if_succeeded)
6723 skip_if_group (ip, 0);
6725 value = eval_if_expression (buf, limit - buf);
6727 skip_if_group (ip, 0);
6729 ++if_stack->if_succeeded; /* continue processing input */
6730 output_line_command (ip, op, 1, same_file);
6737 * evaluate a #if expression in BUF, of length LENGTH,
6738 * then parse the result as a C expression and return the value as an int.
6741 eval_if_expression (buf, length)
6746 HASHNODE *save_defined;
6749 save_defined = install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
6751 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6753 delete_macro (save_defined); /* clean up special symbol */
6755 value = parse_c_expression (temp_obuf.buf);
6757 free (temp_obuf.buf);
6763 * routine to handle ifdef/ifndef. Try to look up the symbol,
6764 * then do or don't skip to the #endif/#else/#elif depending
6765 * on what directive is actually being processed.
6769 do_xifdef (buf, limit, op, keyword)
6770 U_CHAR *buf, *limit;
6772 struct directive *keyword;
6775 FILE_BUF *ip = &instack[indepth];
6777 int start_of_file = 0;
6778 U_CHAR *control_macro = 0;
6780 /* Detect a #ifndef at start of file (not counting comments). */
6781 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
6782 U_CHAR *p = ip->buf;
6783 while (p != directive_start) {
6787 else if (c == '/' && p != ip->bufp && *p == '*') {
6788 /* Skip this comment. */
6790 U_CHAR *save_bufp = ip->bufp;
6792 p = skip_to_end_of_comment (ip, &junk, 1);
6793 ip->bufp = save_bufp;
6798 /* If we get here, this conditional is the beginning of the file. */
6803 /* Discard leading and trailing whitespace. */
6804 SKIP_WHITE_SPACE (buf);
6805 while (limit != buf && is_hor_space[limit[-1]]) limit--;
6807 /* Find the end of the identifier at the beginning. */
6808 for (end = buf; is_idchar[*end]; end++);
6811 skip = (keyword->type == T_IFDEF);
6813 pedwarn (end == limit ? "`#%s' with no argument"
6814 : "`#%s' argument starts with punctuation",
6819 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
6820 pedwarn ("`#%s' argument starts with a digit", keyword->name);
6821 else if (end != limit && !traditional)
6822 pedwarn ("garbage at end of `#%s' argument", keyword->name);
6824 hp = lookup (buf, end-buf, -1);
6827 /* Output a precondition for this macro. */
6829 (hp->type == T_CONST
6830 || (hp->type == T_MACRO && hp->value.defn->predefined)))
6831 fprintf (pcp_outfile, "#define %s\n", hp->name);
6834 fprintf (pcp_outfile, "#undef ");
6835 while (is_idchar[*cp]) /* Ick! */
6836 fputc (*cp++, pcp_outfile);
6837 putc ('\n', pcp_outfile);
6841 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
6842 if (start_of_file && !skip) {
6843 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
6844 bcopy ((char *) buf, (char *) control_macro, end - buf);
6845 control_macro[end - buf] = 0;
6849 conditional_skip (ip, skip, T_IF, control_macro);
6853 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
6854 If this is a #ifndef starting at the beginning of a file,
6855 CONTROL_MACRO is the macro name tested by the #ifndef.
6856 Otherwise, CONTROL_MACRO is 0. */
6859 conditional_skip (ip, skip, type, control_macro)
6862 enum node_type type;
6863 U_CHAR *control_macro;
6865 IF_STACK_FRAME *temp;
6867 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
6868 temp->fname = ip->nominal_fname;
6869 temp->lineno = ip->lineno;
6870 temp->next = if_stack;
6871 temp->control_macro = control_macro;
6874 if_stack->type = type;
6877 skip_if_group (ip, 0);
6880 ++if_stack->if_succeeded;
6881 output_line_command (ip, &outbuf, 1, same_file);
6886 * skip to #endif, #else, or #elif. adjust line numbers, etc.
6887 * leaves input ptr at the sharp sign found.
6888 * If ANY is nonzero, return at next directive of any sort.
6891 skip_if_group (ip, any)
6895 register U_CHAR *bp = ip->bufp, *cp;
6896 register U_CHAR *endb = ip->buf + ip->length;
6897 struct directive *kt;
6898 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
6899 U_CHAR *beg_of_line = bp;
6900 register int ident_length;
6901 U_CHAR *ident, *after_ident;
6905 case '/': /* possible comment */
6906 if (*bp == '\\' && bp[1] == '\n')
6909 || (cplusplus_comments && *bp == '/')) {
6911 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
6916 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
6917 NULL_PTR, NULL_PTR);
6920 /* Char after backslash loses its special meaning. */
6923 ++ip->lineno; /* But do update the line-count. */
6934 /* # keyword: a # must be first nonblank char on the line */
6935 if (beg_of_line == 0)
6937 /* Scan from start of line, skipping whitespace, comments
6938 and backslash-newlines, and see if we reach this #.
6939 If not, this # is not special. */
6941 /* If -traditional, require # to be at beginning of line. */
6944 if (is_hor_space[*bp])
6946 else if (*bp == '\\' && bp[1] == '\n')
6948 else if (*bp == '/' && bp[1] == '*') {
6950 while (!(*bp == '*' && bp[1] == '/'))
6954 /* There is no point in trying to deal with C++ // comments here,
6955 because if there is one, then this # must be part of the
6956 comment and we would never reach here. */
6959 if (bp != ip->bufp) {
6960 bp = ip->bufp + 1; /* Reset bp to after the #. */
6964 bp = ip->bufp + 1; /* Point after the '#' */
6966 /* Skip whitespace and \-newline. */
6968 if (is_hor_space[*bp])
6970 else if (*bp == '\\' && bp[1] == '\n')
6972 else if (*bp == '/' && bp[1] == '*') {
6974 while (!(*bp == '*' && bp[1] == '/')) {
6980 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
6982 while (bp[-1] == '\\' || *bp != '\n') {
6993 /* Now find end of directive name.
6994 If we encounter a backslash-newline, exchange it with any following
6995 symbol-constituents so that we end up with a contiguous name. */
7001 if (*bp == '\\' && bp[1] == '\n')
7002 name_newline_fix (bp);
7008 ident_length = bp - cp;
7012 /* A line of just `#' becomes blank. */
7014 if (ident_length == 0 && *after_ident == '\n') {
7018 if (ident_length == 0 || !is_idstart[*ident]) {
7020 while (is_idchar[*p]) {
7021 if (*p < '0' || *p > '9')
7025 /* Handle # followed by a line number. */
7026 if (p != ident && !is_idchar[*p]) {
7028 pedwarn ("`#' followed by integer");
7032 /* Avoid error for `###' and similar cases unless -pedantic. */
7034 while (*p == '#' || is_hor_space[*p]) p++;
7036 if (pedantic && !lang_asm)
7037 pedwarn ("invalid preprocessor directive");
7042 if (!lang_asm && pedantic)
7043 pedwarn ("invalid preprocessor directive name");
7047 for (kt = directive_table; kt->length >= 0; kt++) {
7048 IF_STACK_FRAME *temp;
7049 if (ident_length == kt->length
7050 && strncmp (cp, kt->name, kt->length) == 0) {
7051 /* If we are asked to return on next directive, do so now. */
7059 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7060 temp->next = if_stack;
7062 temp->lineno = ip->lineno;
7063 temp->fname = ip->nominal_fname;
7064 temp->type = kt->type;
7068 if (pedantic && if_stack != save_if_stack)
7071 if (if_stack == instack[indepth].if_stack) {
7072 error ("`#%s' not within a conditional", kt->name);
7075 else if (if_stack == save_if_stack)
7076 return; /* found what we came for */
7078 if (kt->type != T_ENDIF) {
7079 if (if_stack->type == T_ELSE)
7080 error ("`#else' or `#elif' after `#else'");
7081 if_stack->type = kt->type;
7086 if_stack = if_stack->next;
7093 /* Don't let erroneous code go by. */
7094 if (kt->length < 0 && !lang_asm && pedantic)
7095 pedwarn ("invalid preprocessor directive name");
7099 /* after this returns, rescan will exit because ip->bufp
7100 now points to the end of the buffer.
7101 rescan is responsible for the error message also. */
7105 * handle a #else directive. Do this by just continuing processing
7106 * without changing if_stack ; this is so that the error message
7107 * for missing #endif's etc. will point to the original #if. It
7108 * is possible that something different would be better.
7112 do_else (buf, limit, op, keyword)
7113 U_CHAR *buf, *limit;
7115 struct directive *keyword;
7117 FILE_BUF *ip = &instack[indepth];
7120 SKIP_WHITE_SPACE (buf);
7122 pedwarn ("text following `#else' violates ANSI standard");
7125 if (if_stack == instack[indepth].if_stack) {
7126 error ("`#else' not within a conditional");
7129 /* #ifndef can't have its special treatment for containing the whole file
7130 if it has a #else clause. */
7131 if_stack->control_macro = 0;
7133 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7134 error ("`#else' after `#else'");
7135 fprintf (stderr, " (matches line %d", if_stack->lineno);
7136 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7137 fprintf (stderr, ", file %s", if_stack->fname);
7138 fprintf (stderr, ")\n");
7140 if_stack->type = T_ELSE;
7143 if (if_stack->if_succeeded)
7144 skip_if_group (ip, 0);
7146 ++if_stack->if_succeeded; /* continue processing input */
7147 output_line_command (ip, op, 1, same_file);
7153 * unstack after #endif command
7157 do_endif (buf, limit, op, keyword)
7158 U_CHAR *buf, *limit;
7160 struct directive *keyword;
7163 SKIP_WHITE_SPACE (buf);
7165 pedwarn ("text following `#endif' violates ANSI standard");
7168 if (if_stack == instack[indepth].if_stack)
7169 error ("unbalanced `#endif'");
7171 IF_STACK_FRAME *temp = if_stack;
7172 if_stack = if_stack->next;
7173 if (temp->control_macro != 0) {
7174 /* This #endif matched a #ifndef at the start of the file.
7175 See if it is at the end of the file. */
7176 FILE_BUF *ip = &instack[indepth];
7177 U_CHAR *p = ip->bufp;
7178 U_CHAR *ep = ip->buf + ip->length;
7188 if (p != ep && *p == '*') {
7189 /* Skip this comment. */
7191 U_CHAR *save_bufp = ip->bufp;
7193 p = skip_to_end_of_comment (ip, &junk, 1);
7194 ip->bufp = save_bufp;
7201 /* If we get here, this #endif ends a #ifndef
7202 that contains all of the file (aside from whitespace).
7203 Arrange not to include the file again
7204 if the macro that was tested is defined.
7206 Do not do this for the top-level file in a -include or any
7207 file in a -imacros. */
7209 && ! (indepth == 1 && no_record_file)
7210 && ! (no_record_file && no_output))
7211 record_control_macro (ip->fname, temp->control_macro);
7215 output_line_command (&instack[indepth], op, 1, same_file);
7220 /* When an #else or #endif is found while skipping failed conditional,
7221 if -pedantic was specified, this is called to warn about text after
7222 the command name. P points to the first char after the command name. */
7228 /* Advance P over whitespace and comments. */
7230 if (*p == '\\' && p[1] == '\n')
7232 if (is_hor_space[*p])
7234 else if (*p == '/') {
7235 if (p[1] == '\\' && p[2] == '\n')
7236 newline_fix (p + 1);
7239 /* Don't bother warning about unterminated comments
7240 since that will happen later. Just be sure to exit. */
7242 if (p[1] == '\\' && p[2] == '\n')
7243 newline_fix (p + 1);
7244 if (*p == '*' && p[1] == '/') {
7251 else if (cplusplus_comments && p[1] == '/') {
7253 while (*p && (*p != '\n' || p[-1] == '\\'))
7258 if (*p && *p != '\n')
7259 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7262 /* Skip a comment, assuming the input ptr immediately follows the
7263 initial slash-star. Bump *LINE_COUNTER for each newline.
7264 (The canonical line counter is &ip->lineno.)
7265 Don't use this routine (or the next one) if bumping the line
7266 counter is not sufficient to deal with newlines in the string.
7268 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7269 This feature is useful when processing a comment that is going to be
7270 processed or was processed at another point in the preprocessor,
7271 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7274 skip_to_end_of_comment (ip, line_counter, nowarn)
7275 register FILE_BUF *ip;
7276 int *line_counter; /* place to remember newlines, or NULL */
7279 register U_CHAR *limit = ip->buf + ip->length;
7280 register U_CHAR *bp = ip->bufp;
7281 FILE_BUF *op = &outbuf; /* JF */
7282 int output = put_out_comments && !line_counter;
7283 int start_line = line_counter ? *line_counter : 0;
7285 /* JF this line_counter stuff is a crock to make sure the
7286 comment is only put out once, no matter how many times
7287 the comment is skipped. It almost works */
7292 if (cplusplus_comments && bp[-1] == '/') {
7294 while (bp < limit) {
7296 if (*bp == '\n' && bp[-1] != '\\')
7308 while (bp < limit) {
7309 if (bp[-1] != '\\' && *bp == '\n') {
7312 if (*bp == '\n' && line_counter)
7321 while (bp < limit) {
7326 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7327 warning ("`/*' within comment");
7330 /* If this is the end of the file, we have an unterminated comment.
7331 Don't swallow the newline. We are guaranteed that there will be a
7332 trailing newline and various pieces assume it's there. */
7339 if (line_counter != NULL)
7345 if (*bp == '\\' && bp[1] == '\n')
7358 error_with_line (line_for_error (start_line), "unterminated comment");
7364 * Skip over a quoted string. BP points to the opening quote.
7365 * Returns a pointer after the closing quote. Don't go past LIMIT.
7366 * START_LINE is the line number of the starting point (but it need
7367 * not be valid if the starting point is inside a macro expansion).
7369 * The input stack state is not changed.
7371 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7372 * for each newline passed.
7374 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7375 * if we pass a backslash-newline.
7377 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7380 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7381 register U_CHAR *bp;
7382 register U_CHAR *limit;
7384 int *count_newlines;
7385 int *backslash_newlines_p;
7388 register U_CHAR c, match;
7393 error_with_line (line_for_error (start_line),
7394 "unterminated string or character constant");
7395 error_with_line (multiline_string_line,
7396 "possible real start of unterminated constant");
7397 multiline_string_line = 0;
7404 while (*bp == '\\' && bp[1] == '\n') {
7405 if (backslash_newlines_p)
7406 *backslash_newlines_p = 1;
7411 if (*bp == '\n' && count_newlines) {
7412 if (backslash_newlines_p)
7413 *backslash_newlines_p = 1;
7417 } else if (c == '\n') {
7419 /* Unterminated strings and character constants are 'legal'. */
7420 bp--; /* Don't consume the newline. */
7425 if (pedantic || match == '\'') {
7426 error_with_line (line_for_error (start_line),
7427 "unterminated string or character constant");
7433 /* If not traditional, then allow newlines inside strings. */
7436 if (multiline_string_line == 0)
7437 multiline_string_line = start_line;
7438 } else if (c == match)
7444 /* Place into DST a quoted string representing the string SRC.
7445 Return the address of DST's terminating null. */
7447 quote_string (dst, src)
7454 switch ((c = *src++))
7461 sprintf (dst, "\\%03o", c);
7479 /* Skip across a group of balanced parens, starting from IP->bufp.
7480 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7482 This does not handle newlines, because it's used for the arg of #if,
7483 where there aren't any newlines. Also, backslash-newline can't appear. */
7486 skip_paren_group (ip)
7487 register FILE_BUF *ip;
7489 U_CHAR *limit = ip->buf + ip->length;
7490 U_CHAR *p = ip->bufp;
7492 int lines_dummy = 0;
7494 while (p != limit) {
7504 return ip->bufp = p;
7510 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7518 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7520 return ip->bufp = p;
7531 * write out a #line command, for instance, after an #include file.
7532 * If CONDITIONAL is nonzero, we can omit the #line if it would
7533 * appear to be a no-op, and we can output a few newlines instead
7534 * if we want to increase the line number by a small amount.
7535 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7539 output_line_command (ip, op, conditional, file_change)
7542 enum file_change_code file_change;
7545 char *line_cmd_buf, *line_end;
7547 if (no_line_commands
7548 || ip->fname == NULL
7550 op->lineno = ip->lineno;
7555 if (ip->lineno == op->lineno)
7558 /* If the inherited line number is a little too small,
7559 output some newlines instead of a #line command. */
7560 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7561 check_expand (op, 10);
7562 while (ip->lineno > op->lineno) {
7570 /* Don't output a line number of 0 if we can help it. */
7571 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7572 && *ip->bufp == '\n') {
7577 line_cmd_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7578 #ifdef OUTPUT_LINE_COMMANDS
7579 sprintf (line_cmd_buf, "#line %d ", ip->lineno);
7581 sprintf (line_cmd_buf, "# %d ", ip->lineno);
7583 line_end = quote_string (line_cmd_buf + strlen (line_cmd_buf),
7585 if (file_change != same_file) {
7587 *line_end++ = file_change == enter_file ? '1' : '2';
7589 /* Tell cc1 if following text comes from a system header file. */
7590 if (ip->system_header_p) {
7594 #ifndef NO_IMPLICIT_EXTERN_C
7595 /* Tell cc1plus if following text should be treated as C. */
7596 if (ip->system_header_p == 2 && cplusplus) {
7602 len = line_end - line_cmd_buf;
7603 check_expand (op, len + 1);
7604 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7606 bcopy ((char *) line_cmd_buf, (char *) op->bufp, len);
7608 op->lineno = ip->lineno;
7611 /* This structure represents one parsed argument in a macro call.
7612 `raw' points to the argument text as written (`raw_length' is its length).
7613 `expanded' points to the argument's macro-expansion
7614 (its length is `expand_length').
7615 `stringified_length' is the length the argument would have
7617 `use_count' is the number of times this macro arg is substituted
7618 into the macro. If the actual use count exceeds 10,
7619 the value stored is 10.
7620 `free1' and `free2', if nonzero, point to blocks to be freed
7621 when the macro argument data is no longer needed. */
7624 U_CHAR *raw, *expanded;
7625 int raw_length, expand_length;
7626 int stringified_length;
7627 U_CHAR *free1, *free2;
7633 /* Expand a macro call.
7634 HP points to the symbol that is the macro being called.
7635 Put the result of expansion onto the input stack
7636 so that subsequent input by our caller will use it.
7638 If macro wants arguments, caller has already verified that
7639 an argument list follows; arguments come from the input stack. */
7642 macroexpand (hp, op)
7647 DEFINITION *defn = hp->value.defn;
7648 register U_CHAR *xbuf;
7650 int start_line = instack[indepth].lineno;
7651 int rest_args, rest_zero;
7653 CHECK_DEPTH (return;);
7655 /* it might not actually be a macro. */
7656 if (hp->type != T_MACRO) {
7657 special_symbol (hp, op);
7661 /* This macro is being used inside a #if, which means it must be */
7662 /* recorded as a precondition. */
7663 if (pcp_inside_if && pcp_outfile && defn->predefined)
7664 dump_single_macro (hp, pcp_outfile);
7666 nargs = defn->nargs;
7670 struct argdata *args;
7671 char *parse_error = 0;
7673 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7675 for (i = 0; i < nargs; i++) {
7676 args[i].raw = (U_CHAR *) "";
7677 args[i].expanded = 0;
7678 args[i].raw_length = args[i].expand_length
7679 = args[i].stringified_length = 0;
7680 args[i].free1 = args[i].free2 = 0;
7681 args[i].use_count = 0;
7684 /* Parse all the macro args that are supplied. I counts them.
7685 The first NARGS args are stored in ARGS.
7686 The rest are discarded.
7687 If rest_args is set then we assume macarg absorbed the rest of the args.
7692 /* Discard the open-parenthesis or comma before the next arg. */
7693 ++instack[indepth].bufp;
7696 if (i < nargs || (nargs == 0 && i == 0)) {
7697 /* if we are working on last arg which absorbs rest of args... */
7698 if (i == nargs - 1 && defn->rest_args)
7700 parse_error = macarg (&args[i], rest_args);
7703 parse_error = macarg (NULL_PTR, 0);
7705 error_with_line (line_for_error (start_line), parse_error);
7709 } while (*instack[indepth].bufp != ')');
7711 /* If we got one arg but it was just whitespace, call that 0 args. */
7713 register U_CHAR *bp = args[0].raw;
7714 register U_CHAR *lim = bp + args[0].raw_length;
7715 /* cpp.texi says for foo ( ) we provide one argument.
7716 However, if foo wants just 0 arguments, treat this as 0. */
7718 while (bp != lim && is_space[*bp]) bp++;
7723 /* Don't output an error message if we have already output one for
7724 a parse error above. */
7726 if (nargs == 0 && i > 0) {
7728 error ("arguments given to macro `%s'", hp->name);
7729 } else if (i < nargs) {
7730 /* traditional C allows foo() if foo wants one argument. */
7731 if (nargs == 1 && i == 0 && traditional)
7733 /* the rest args token is allowed to absorb 0 tokens */
7734 else if (i == nargs - 1 && defn->rest_args)
7736 else if (parse_error)
7739 error ("macro `%s' used without args", hp->name);
7741 error ("macro `%s' used with just one arg", hp->name);
7743 error ("macro `%s' used with only %d args", hp->name, i);
7744 } else if (i > nargs) {
7746 error ("macro `%s' used with too many (%d) args", hp->name, i);
7749 /* Swallow the closeparen. */
7750 ++instack[indepth].bufp;
7752 /* If macro wants zero args, we parsed the arglist for checking only.
7753 Read directly from the macro definition. */
7755 xbuf = defn->expansion;
7756 xbuf_len = defn->length;
7758 register U_CHAR *exp = defn->expansion;
7759 register int offset; /* offset in expansion,
7760 copied a piece at a time */
7761 register int totlen; /* total amount of exp buffer filled so far */
7763 register struct reflist *ap, *last_ap;
7765 /* Macro really takes args. Compute the expansion of this call. */
7767 /* Compute length in characters of the macro's expansion.
7768 Also count number of times each arg is used. */
7769 xbuf_len = defn->length;
7770 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
7772 xbuf_len += args[ap->argno].stringified_length;
7773 else if (ap->raw_before || ap->raw_after || traditional)
7774 /* Add 4 for two newline-space markers to prevent
7775 token concatenation. */
7776 xbuf_len += args[ap->argno].raw_length + 4;
7778 /* We have an ordinary (expanded) occurrence of the arg.
7779 So compute its expansion, if we have not already. */
7780 if (args[ap->argno].expanded == 0) {
7782 obuf = expand_to_temp_buffer (args[ap->argno].raw,
7783 args[ap->argno].raw + args[ap->argno].raw_length,
7786 args[ap->argno].expanded = obuf.buf;
7787 args[ap->argno].expand_length = obuf.length;
7788 args[ap->argno].free2 = obuf.buf;
7791 /* Add 4 for two newline-space markers to prevent
7792 token concatenation. */
7793 xbuf_len += args[ap->argno].expand_length + 4;
7795 if (args[ap->argno].use_count < 10)
7796 args[ap->argno].use_count++;
7799 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
7801 /* Generate in XBUF the complete expansion
7802 with arguments substituted in.
7803 TOTLEN is the total size generated so far.
7804 OFFSET is the index in the definition
7805 of where we are copying from. */
7806 offset = totlen = 0;
7807 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
7808 last_ap = ap, ap = ap->next) {
7809 register struct argdata *arg = &args[ap->argno];
7810 int count_before = totlen;
7812 /* Add chars to XBUF. */
7813 for (i = 0; i < ap->nchars; i++, offset++)
7814 xbuf[totlen++] = exp[offset];
7816 /* If followed by an empty rest arg with concatenation,
7817 delete the last run of nonwhite chars. */
7818 if (rest_zero && totlen > count_before
7819 && ((ap->rest_args && ap->raw_before)
7820 || (last_ap != NULL && last_ap->rest_args
7821 && last_ap->raw_after))) {
7822 /* Delete final whitespace. */
7823 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
7827 /* Delete the nonwhites before them. */
7828 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
7833 if (ap->stringify != 0) {
7834 int arglen = arg->raw_length;
7840 && (c = arg->raw[i], is_space[c]))
7843 && (c = arg->raw[arglen - 1], is_space[c]))
7846 xbuf[totlen++] = '\"'; /* insert beginning quote */
7847 for (; i < arglen; i++) {
7850 /* Special markers Newline Space
7851 generate nothing for a stringified argument. */
7852 if (c == '\n' && arg->raw[i+1] != '\n') {
7857 /* Internal sequences of whitespace are replaced by one space
7858 except within an string or char token. */
7860 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
7862 /* Note that Newline Space does occur within whitespace
7863 sequences; consider it part of the sequence. */
7864 if (c == '\n' && is_space[arg->raw[i+1]])
7866 else if (c != '\n' && is_space[c])
7883 } else if (c == '\"' || c == '\'')
7887 /* Escape these chars */
7888 if (c == '\"' || (in_string && c == '\\'))
7889 xbuf[totlen++] = '\\';
7893 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
7898 xbuf[totlen++] = '\"'; /* insert ending quote */
7899 } else if (ap->raw_before || ap->raw_after || traditional) {
7900 U_CHAR *p1 = arg->raw;
7901 U_CHAR *l1 = p1 + arg->raw_length;
7902 if (ap->raw_before) {
7903 while (p1 != l1 && is_space[*p1]) p1++;
7904 while (p1 != l1 && is_idchar[*p1])
7905 xbuf[totlen++] = *p1++;
7906 /* Delete any no-reexpansion marker that follows
7907 an identifier at the beginning of the argument
7908 if the argument is concatenated with what precedes it. */
7909 if (p1[0] == '\n' && p1[1] == '-')
7911 } else if (!traditional) {
7912 /* Ordinary expanded use of the argument.
7913 Put in newline-space markers to prevent token pasting. */
7914 xbuf[totlen++] = '\n';
7915 xbuf[totlen++] = ' ';
7917 if (ap->raw_after) {
7918 /* Arg is concatenated after: delete trailing whitespace,
7919 whitespace markers, and no-reexpansion markers. */
7921 if (is_space[l1[-1]]) l1--;
7922 else if (l1[-1] == '-') {
7923 U_CHAR *p2 = l1 - 1;
7924 /* If a `-' is preceded by an odd number of newlines then it
7925 and the last newline are a no-reexpansion marker. */
7926 while (p2 != p1 && p2[-1] == '\n') p2--;
7927 if ((l1 - 1 - p2) & 1) {
7936 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
7938 if (!traditional && !ap->raw_after) {
7939 /* Ordinary expanded use of the argument.
7940 Put in newline-space markers to prevent token pasting. */
7941 xbuf[totlen++] = '\n';
7942 xbuf[totlen++] = ' ';
7945 /* Ordinary expanded use of the argument.
7946 Put in newline-space markers to prevent token pasting. */
7948 xbuf[totlen++] = '\n';
7949 xbuf[totlen++] = ' ';
7951 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
7952 arg->expand_length);
7953 totlen += arg->expand_length;
7955 xbuf[totlen++] = '\n';
7956 xbuf[totlen++] = ' ';
7958 /* If a macro argument with newlines is used multiple times,
7959 then only expand the newlines once. This avoids creating output
7960 lines which don't correspond to any input line, which confuses
7962 if (arg->use_count > 1 && arg->newlines > 0) {
7963 /* Don't bother doing change_newlines for subsequent
7967 = change_newlines (arg->expanded, arg->expand_length);
7971 if (totlen > xbuf_len)
7975 /* if there is anything left of the definition
7976 after handling the arg list, copy that in too. */
7978 for (i = offset; i < defn->length; i++) {
7979 /* if we've reached the end of the macro */
7982 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
7983 && last_ap->raw_after))
7984 xbuf[totlen++] = exp[i];
7990 for (i = 0; i < nargs; i++) {
7991 if (args[i].free1 != 0)
7992 free (args[i].free1);
7993 if (args[i].free2 != 0)
7994 free (args[i].free2);
7998 xbuf = defn->expansion;
7999 xbuf_len = defn->length;
8002 /* Now put the expansion on the input stack
8003 so our caller will commence reading from it. */
8005 register FILE_BUF *ip2;
8007 ip2 = &instack[++indepth];
8010 ip2->nominal_fname = 0;
8011 /* This may not be exactly correct, but will give much better error
8012 messages for nested macro calls than using a line number of zero. */
8013 ip2->lineno = start_line;
8015 ip2->length = xbuf_len;
8017 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8019 ip2->if_stack = if_stack;
8020 ip2->system_header_p = 0;
8022 /* Recursive macro use sometimes works traditionally.
8023 #define foo(x,y) bar (x (y,0), y)
8027 hp->type = T_DISABLED;
8032 * Parse a macro argument and store the info on it into *ARGPTR.
8033 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8034 * Return nonzero to indicate a syntax error.
8038 macarg (argptr, rest_args)
8039 register struct argdata *argptr;
8042 FILE_BUF *ip = &instack[indepth];
8047 /* Try to parse as much of the argument as exists at this
8048 input stack level. */
8049 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8050 &paren, &newlines, &comments, rest_args);
8052 /* If we find the end of the argument at this level,
8053 set up *ARGPTR to point at it in the input stack. */
8054 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8055 && bp != ip->buf + ip->length) {
8057 argptr->raw = ip->bufp;
8058 argptr->raw_length = bp - ip->bufp;
8059 argptr->newlines = newlines;
8063 /* This input stack level ends before the macro argument does.
8064 We must pop levels and keep parsing.
8065 Therefore, we must allocate a temporary buffer and copy
8066 the macro argument into it. */
8067 int bufsize = bp - ip->bufp;
8068 int extra = newlines;
8069 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8070 int final_start = 0;
8072 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8074 ip->lineno += newlines;
8076 while (bp == ip->buf + ip->length) {
8077 if (instack[indepth].macro == 0) {
8079 return "unterminated macro call";
8081 ip->macro->type = T_MACRO;
8083 free (ip->free_ptr);
8084 ip = &instack[--indepth];
8087 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8088 &newlines, &comments, rest_args);
8089 final_start = bufsize;
8090 bufsize += bp - ip->bufp;
8092 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8093 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8096 ip->lineno += newlines;
8099 /* Now, if arg is actually wanted, record its raw form,
8100 discarding comments and duplicating newlines in whatever
8101 part of it did not come from a macro expansion.
8102 EXTRA space has been preallocated for duplicating the newlines.
8103 FINAL_START is the index of the start of that part. */
8105 argptr->raw = buffer;
8106 argptr->raw_length = bufsize;
8107 argptr->free1 = buffer;
8108 argptr->newlines = newlines;
8109 argptr->comments = comments;
8110 if ((newlines || comments) && ip->fname != 0)
8113 discard_comments (argptr->raw + final_start,
8114 argptr->raw_length - final_start,
8116 argptr->raw[argptr->raw_length] = 0;
8117 if (argptr->raw_length > bufsize + extra)
8122 /* If we are not discarding this argument,
8123 macroexpand it and compute its length as stringified.
8124 All this info goes into *ARGPTR. */
8127 register U_CHAR *buf, *lim;
8128 register int totlen;
8131 lim = buf + argptr->raw_length;
8133 while (buf != lim && is_space[*buf])
8135 while (buf != lim && is_space[lim[-1]])
8137 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8138 while (buf != lim) {
8139 register U_CHAR c = *buf++;
8141 /* Internal sequences of whitespace are replaced by one space
8142 in most cases, but not always. So count all the whitespace
8143 in case we need to keep it all. */
8146 SKIP_ALL_WHITE_SPACE (buf);
8149 if (c == '\"' || c == '\\') /* escape these chars */
8151 else if (!isprint (c))
8154 argptr->stringified_length = totlen;
8159 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8160 counting parens in *DEPTHPTR,
8161 and return if reach LIMIT
8162 or before a `)' that would make *DEPTHPTR negative
8163 or before a comma when *DEPTHPTR is zero.
8164 Single and double quotes are matched and termination
8165 is inhibited within them. Comments also inhibit it.
8166 Value returned is pointer to stopping place.
8168 Increment *NEWLINES each time a newline is passed.
8169 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8170 Set *COMMENTS to 1 if a comment is seen. */
8173 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8175 register U_CHAR *limit;
8176 int *depthptr, *newlines, *comments;
8179 register U_CHAR *bp = start;
8181 while (bp < limit) {
8187 if (--(*depthptr) < 0)
8191 /* Traditionally, backslash makes following char not special. */
8192 if (bp + 1 < limit && traditional)
8195 /* But count source lines anyway. */
8204 if (bp[1] == '\\' && bp[2] == '\n')
8205 newline_fix (bp + 1);
8206 if (cplusplus_comments && bp[1] == '/') {
8209 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8210 if (*bp == '\n') ++*newlines;
8215 if (bp[1] != '*' || bp + 1 >= limit)
8219 while (bp + 1 < limit) {
8221 && bp[1] == '\\' && bp[2] == '\n')
8222 newline_fix (bp + 1);
8223 if (bp[0] == '*' && bp[1] == '/')
8225 if (*bp == '\n') ++*newlines;
8233 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8238 while (*bp == '\\' && bp[1] == '\n') {
8241 } else if (*bp == '\n') {
8250 /* if we've returned to lowest level and we aren't absorbing all args */
8251 if ((*depthptr) == 0 && rest_args == 0)
8261 /* Discard comments and duplicate newlines
8262 in the string of length LENGTH at START,
8263 except inside of string constants.
8264 The string is copied into itself with its beginning staying fixed.
8266 NEWLINES is the number of newlines that must be duplicated.
8267 We assume that that much extra space is available past the end
8271 discard_comments (start, length, newlines)
8276 register U_CHAR *ibp;
8277 register U_CHAR *obp;
8278 register U_CHAR *limit;
8281 /* If we have newlines to duplicate, copy everything
8282 that many characters up. Then, in the second part,
8283 we will have room to insert the newlines
8285 NEWLINES may actually be too large, because it counts
8286 newlines in string constants, and we don't duplicate those.
8287 But that does no harm. */
8289 ibp = start + length;
8290 obp = ibp + newlines;
8292 while (limit != ibp)
8296 ibp = start + newlines;
8297 limit = start + length + newlines;
8300 while (ibp < limit) {
8301 *obp++ = c = *ibp++;
8304 /* Duplicate the newline. */
8316 if (*ibp == '\\' && ibp[1] == '\n')
8318 /* Delete any comment. */
8319 if (cplusplus_comments && ibp[0] == '/') {
8320 /* Comments are equivalent to spaces. */
8323 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8327 if (ibp[0] != '*' || ibp + 1 >= limit)
8329 /* Comments are equivalent to spaces. */
8332 while (ibp + 1 < limit) {
8334 && ibp[1] == '\\' && ibp[2] == '\n')
8335 newline_fix (ibp + 1);
8336 if (ibp[0] == '*' && ibp[1] == '/')
8345 /* Notice and skip strings, so that we don't
8346 think that comments start inside them,
8347 and so we don't duplicate newlines in them. */
8350 while (ibp < limit) {
8351 *obp++ = c = *ibp++;
8354 if (c == '\n' && quotec == '\'')
8356 if (c == '\\' && ibp < limit) {
8357 while (*ibp == '\\' && ibp[1] == '\n')
8370 /* Turn newlines to spaces in the string of length LENGTH at START,
8371 except inside of string constants.
8372 The string is copied into itself with its beginning staying fixed. */
8375 change_newlines (start, length)
8379 register U_CHAR *ibp;
8380 register U_CHAR *obp;
8381 register U_CHAR *limit;
8385 limit = start + length;
8388 while (ibp < limit) {
8389 *obp++ = c = *ibp++;
8392 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8393 string. Skip past the newline and its duplicate.
8394 Put a space in the output. */
8405 /* Notice and skip strings, so that we don't delete newlines in them. */
8408 while (ibp < limit) {
8409 *obp++ = c = *ibp++;
8412 if (c == '\n' && quotec == '\'')
8424 * my_strerror - return the descriptive text associated with an `errno' code.
8428 my_strerror (errnum)
8434 #ifndef HAVE_STRERROR
8435 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8437 result = strerror (errnum);
8440 /* VAXCRTL's strerror() takes an optional second argument, which only
8441 matters when the first argument is EVMSERR. However, it's simplest
8442 just to pass it unconditionally. `vaxc$errno' is declared in
8443 <errno.h>, and maintained by the library in parallel with `errno'.
8444 We assume that caller's `errnum' either matches the last setting of
8445 `errno' by the library or else does not have the value `EVMSERR'. */
8447 result = strerror (errnum, vaxc$errno);
8451 result = "undocumented I/O error";
8457 * error - print error message and increment count of errors.
8461 error (msg, arg1, arg2, arg3)
8463 char *arg1, *arg2, *arg3;
8466 FILE_BUF *ip = NULL;
8468 print_containing_files ();
8470 for (i = indepth; i >= 0; i--)
8471 if (instack[i].fname != NULL) {
8477 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8478 fprintf (stderr, msg, arg1, arg2, arg3);
8479 fprintf (stderr, "\n");
8483 /* Error including a message from `errno'. */
8486 error_from_errno (name)
8490 FILE_BUF *ip = NULL;
8492 print_containing_files ();
8494 for (i = indepth; i >= 0; i--)
8495 if (instack[i].fname != NULL) {
8501 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8503 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8508 /* Print error message but don't count it. */
8511 warning (msg, arg1, arg2, arg3)
8513 char *arg1, *arg2, *arg3;
8516 FILE_BUF *ip = NULL;
8518 if (inhibit_warnings)
8521 if (warnings_are_errors)
8524 print_containing_files ();
8526 for (i = indepth; i >= 0; i--)
8527 if (instack[i].fname != NULL) {
8533 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8534 fprintf (stderr, "warning: ");
8535 fprintf (stderr, msg, arg1, arg2, arg3);
8536 fprintf (stderr, "\n");
8540 error_with_line (line, msg, arg1, arg2, arg3)
8543 char *arg1, *arg2, *arg3;
8546 FILE_BUF *ip = NULL;
8548 print_containing_files ();
8550 for (i = indepth; i >= 0; i--)
8551 if (instack[i].fname != NULL) {
8557 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8558 fprintf (stderr, msg, arg1, arg2, arg3);
8559 fprintf (stderr, "\n");
8564 warning_with_line (line, msg, arg1, arg2, arg3)
8567 char *arg1, *arg2, *arg3;
8570 FILE_BUF *ip = NULL;
8572 if (inhibit_warnings)
8575 if (warnings_are_errors)
8578 print_containing_files ();
8580 for (i = indepth; i >= 0; i--)
8581 if (instack[i].fname != NULL) {
8587 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8588 fprintf (stderr, "warning: ");
8589 fprintf (stderr, msg, arg1, arg2, arg3);
8590 fprintf (stderr, "\n");
8593 /* print an error message and maybe count it. */
8596 pedwarn (msg, arg1, arg2, arg3)
8598 char *arg1, *arg2, *arg3;
8600 if (pedantic_errors)
8601 error (msg, arg1, arg2, arg3);
8603 warning (msg, arg1, arg2, arg3);
8607 pedwarn_with_line (line, msg, arg1, arg2, arg3)
8610 char *arg1, *arg2, *arg3;
8612 if (pedantic_errors)
8613 error_with_line (line, msg, arg1, arg2, arg3);
8615 warning_with_line (line, msg, arg1, arg2, arg3);
8618 /* Report a warning (or an error if pedantic_errors)
8619 giving specified file name and line number, not current. */
8622 pedwarn_with_file_and_line (file, line, msg, arg1, arg2, arg3)
8626 char *arg1, *arg2, *arg3;
8628 if (!pedantic_errors && inhibit_warnings)
8631 fprintf (stderr, "%s:%d: ", file, line);
8632 if (pedantic_errors)
8634 if (!pedantic_errors)
8635 fprintf (stderr, "warning: ");
8636 fprintf (stderr, msg, arg1, arg2, arg3);
8637 fprintf (stderr, "\n");
8640 /* Print the file names and line numbers of the #include
8641 commands which led to the current file. */
8644 print_containing_files ()
8646 FILE_BUF *ip = NULL;
8650 /* If stack of files hasn't changed since we last printed
8651 this info, don't repeat it. */
8652 if (last_error_tick == input_file_stack_tick)
8655 for (i = indepth; i >= 0; i--)
8656 if (instack[i].fname != NULL) {
8661 /* Give up if we don't find a source file. */
8665 /* Find the other, outer source files. */
8666 for (i--; i >= 0; i--)
8667 if (instack[i].fname != NULL) {
8671 fprintf (stderr, "In file included");
8673 fprintf (stderr, ",\n ");
8676 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
8679 fprintf (stderr, ":\n");
8681 /* Record we have printed the status as of this time. */
8682 last_error_tick = input_file_stack_tick;
8685 /* Return the line at which an error occurred.
8686 The error is not necessarily associated with the current spot
8687 in the input stack, so LINE says where. LINE will have been
8688 copied from ip->lineno for the current input level.
8689 If the current level is for a file, we return LINE.
8690 But if the current level is not for a file, LINE is meaningless.
8691 In that case, we return the lineno of the innermost file. */
8694 line_for_error (line)
8700 for (i = indepth; i >= 0; ) {
8701 if (instack[i].fname != 0)
8706 line1 = instack[i].lineno;
8714 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
8716 * As things stand, nothing is ever placed in the output buffer to be
8717 * removed again except when it's KNOWN to be part of an identifier,
8718 * so flushing and moving down everything left, instead of expanding,
8722 /* You might think void was cleaner for the return type,
8723 but that would get type mismatch in check_expand in strict ANSI. */
8725 grow_outbuf (obuf, needed)
8726 register FILE_BUF *obuf;
8727 register int needed;
8732 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
8735 /* Make it at least twice as big as it is now. */
8737 /* Make it have at least 150% of the free space we will need. */
8738 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
8739 if (minsize > obuf->length)
8740 obuf->length = minsize;
8742 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
8745 obuf->bufp = p + (obuf->bufp - obuf->buf);
8751 /* Symbol table for macro names and special symbols */
8754 * install a name in the main hash table, even if it is already there.
8755 * name stops with first non alphanumeric, except leading '#'.
8756 * caller must check against redefinition if that is desired.
8757 * delete_macro () removes things installed by install () in fifo order.
8758 * this is important because of the `defined' special symbol used
8759 * in #if, and also if pushdef/popdef directives are ever implemented.
8761 * If LEN is >= 0, it is the length of the name.
8762 * Otherwise, compute the length by scanning the entire name.
8764 * If HASH is >= 0, it is the precomputed hash code.
8765 * Otherwise, compute the hash code.
8768 install (name, len, type, ivalue, value, hash)
8771 enum node_type type;
8776 register HASHNODE *hp;
8777 register int i, bucket;
8778 register U_CHAR *p, *q;
8782 while (is_idchar[*p])
8788 hash = hashf (name, len, HASHSIZE);
8790 i = sizeof (HASHNODE) + len + 1;
8791 hp = (HASHNODE *) xmalloc (i);
8793 hp->bucket_hdr = &hashtab[bucket];
8794 hp->next = hashtab[bucket];
8795 hashtab[bucket] = hp;
8797 if (hp->next != NULL)
8798 hp->next->prev = hp;
8801 if (hp->type == T_CONST)
8802 hp->value.ival = ivalue;
8804 hp->value.cpval = value;
8805 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
8808 for (i = 0; i < len; i++)
8815 * find the most recent hash node for name name (ending with first
8816 * non-identifier char) installed by install
8818 * If LEN is >= 0, it is the length of the name.
8819 * Otherwise, compute the length by scanning the entire name.
8821 * If HASH is >= 0, it is the precomputed hash code.
8822 * Otherwise, compute the hash code.
8825 lookup (name, len, hash)
8830 register U_CHAR *bp;
8831 register HASHNODE *bucket;
8834 for (bp = name; is_idchar[*bp]; bp++) ;
8839 hash = hashf (name, len, HASHSIZE);
8841 bucket = hashtab[hash];
8843 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
8845 bucket = bucket->next;
8851 * Delete a hash node. Some weirdness to free junk from macros.
8852 * More such weirdness will have to be added if you define more hash
8853 * types that need it.
8856 /* Note that the DEFINITION of a macro is removed from the hash table
8857 but its storage is not freed. This would be a storage leak
8858 except that it is not reasonable to keep undefining and redefining
8859 large numbers of macros many times.
8860 In any case, this is necessary, because a macro can be #undef'd
8861 in the middle of reading the arguments to a call to it.
8862 If #undef freed the DEFINITION, that would crash. */
8869 if (hp->prev != NULL)
8870 hp->prev->next = hp->next;
8871 if (hp->next != NULL)
8872 hp->next->prev = hp->prev;
8874 /* make sure that the bucket chain header that
8875 the deleted guy was on points to the right thing afterwards. */
8876 if (hp == *hp->bucket_hdr)
8877 *hp->bucket_hdr = hp->next;
8880 if (hp->type == T_MACRO) {
8881 DEFINITION *d = hp->value.defn;
8882 struct reflist *ap, *nextap;
8884 for (ap = d->pattern; ap != NULL; ap = nextap) {
8895 * return hash function on name. must be compatible with the one
8896 * computed a step at a time, elsewhere
8899 hashf (name, len, hashsize)
8900 register U_CHAR *name;
8907 r = HASHSTEP (r, *name++);
8909 return MAKE_POS (r) % hashsize;
8913 /* Dump the definition of a single macro HP to OF. */
8915 dump_single_macro (hp, of)
8916 register HASHNODE *hp;
8919 register DEFINITION *defn = hp->value.defn;
8925 /* Print the definition of the macro HP. */
8927 fprintf (of, "#define %s", hp->name);
8929 if (defn->nargs >= 0) {
8933 for (i = 0; i < defn->nargs; i++) {
8934 dump_arg_n (defn, i, of);
8935 if (i + 1 < defn->nargs)
8945 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8946 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
8947 if (ap->nchars != 0)
8949 offset += ap->nchars;
8952 if (ap->raw_before && !concat)
8953 fprintf (of, " ## ");
8955 dump_arg_n (defn, ap->argno, of);
8956 if (ap->raw_after) {
8957 fprintf (of, " ## ");
8961 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
8965 /* Dump all macro definitions as #defines to stdout. */
8972 for (bucket = 0; bucket < HASHSIZE; bucket++) {
8973 register HASHNODE *hp;
8975 for (hp = hashtab[bucket]; hp; hp= hp->next) {
8976 if (hp->type == T_MACRO)
8977 dump_single_macro (hp, stdout);
8982 /* Output to OF a substring of a macro definition.
8983 BASE is the beginning of the definition.
8984 Output characters START thru LENGTH.
8985 Discard newlines outside of strings, thus
8986 converting funny-space markers to ordinary spaces. */
8989 dump_defn_1 (base, start, length, of)
8995 U_CHAR *p = base + start;
8996 U_CHAR *limit = base + start + length;
8999 if (*p == '\"' || *p =='\'') {
9000 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9001 NULL_PTR, NULL_PTR);
9002 fwrite (p, p1 - p, 1, of);
9012 /* Print the name of argument number ARGNUM of macro definition DEFN
9014 Recall that DEFN->args.argnames contains all the arg names
9015 concatenated in reverse order with comma-space in between. */
9018 dump_arg_n (defn, argnum, of)
9023 register U_CHAR *p = defn->args.argnames;
9024 while (argnum + 1 < defn->nargs) {
9025 p = (U_CHAR *) index (p, ' ') + 1;
9029 while (*p && *p != ',') {
9035 /* Initialize syntactic classifications of characters. */
9038 initialize_char_syntax ()
9043 * Set up is_idchar and is_idstart tables. These should be
9044 * faster than saying (is_alpha (c) || c == '_'), etc.
9045 * Set up these things before calling any routines tthat
9048 for (i = 'a'; i <= 'z'; i++) {
9049 is_idchar[i - 'a' + 'A'] = 1;
9051 is_idstart[i - 'a' + 'A'] = 1;
9054 for (i = '0'; i <= '9'; i++)
9057 is_idstart['_'] = 1;
9058 is_idchar['$'] = dollars_in_ident;
9059 is_idstart['$'] = dollars_in_ident;
9061 /* horizontal space table */
9062 is_hor_space[' '] = 1;
9063 is_hor_space['\t'] = 1;
9064 is_hor_space['\v'] = 1;
9065 is_hor_space['\f'] = 1;
9066 is_hor_space['\r'] = 1;
9076 /* Initialize the built-in macros. */
9079 initialize_builtins (inp, outp)
9083 install ("__LINE__", -1, T_SPECLINE, 0, 0, -1);
9084 install ("__DATE__", -1, T_DATE, 0, 0, -1);
9085 install ("__FILE__", -1, T_FILE, 0, 0, -1);
9086 install ("__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
9087 install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
9088 install ("__VERSION__", -1, T_VERSION, 0, 0, -1);
9089 #ifndef NO_BUILTIN_SIZE_TYPE
9090 install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
9092 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9093 install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
9095 install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
9096 install ("__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
9097 install ("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
9098 install ("__TIME__", -1, T_TIME, 0, 0, -1);
9100 install ("__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
9102 install ("__OBJC__", -1, T_CONST, 1, 0, -1);
9103 /* This is supplied using a -D by the compiler driver
9104 so that it is present only when truly compiling with GNU C. */
9105 /* install ("__GNUC__", -1, T_CONST, 2, 0, -1); */
9109 char directive[2048];
9110 register struct directive *dp = &directive_table[0];
9111 struct tm *timebuf = timestamp ();
9113 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9114 instack[0].nominal_fname);
9115 output_line_command (inp, outp, 0, same_file);
9116 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9118 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9119 output_line_command (inp, outp, 0, same_file);
9120 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9122 #ifndef NO_BUILTIN_SIZE_TYPE
9123 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9124 output_line_command (inp, outp, 0, same_file);
9125 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9128 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9129 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9130 output_line_command (inp, outp, 0, same_file);
9131 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9134 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9135 output_line_command (inp, outp, 0, same_file);
9136 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9138 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9139 monthnames[timebuf->tm_mon],
9140 timebuf->tm_mday, timebuf->tm_year + 1900);
9141 output_line_command (inp, outp, 0, same_file);
9142 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9144 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9145 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9146 output_line_command (inp, outp, 0, same_file);
9147 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9151 sprintf (directive, " __STDC__ 1");
9152 output_line_command (inp, outp, 0, same_file);
9153 pass_thru_directive (directive, &directive[strlen (directive)],
9158 sprintf (directive, " __OBJC__ 1");
9159 output_line_command (inp, outp, 0, same_file);
9160 pass_thru_directive (directive, &directive[strlen (directive)],
9167 * process a given definition string, for initialization
9168 * If STR is just an identifier, define it with value 1.
9169 * If STR has anything after the identifier, then it should
9170 * be identifier=definition.
9174 make_definition (str, op)
9179 struct directive *kt;
9184 if (!is_idstart[*p]) {
9185 error ("malformed option `-D %s'", str);
9188 while (is_idchar[*++p])
9191 buf = (U_CHAR *) alloca (p - buf + 4);
9192 strcpy ((char *)buf, str);
9193 strcat ((char *)buf, " 1");
9194 } else if (*p != '=') {
9195 error ("malformed option `-D %s'", str);
9199 /* Copy the entire option so we can modify it. */
9200 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9201 strncpy (buf, str, p - str);
9202 /* Change the = to a space. */
9204 /* Scan for any backslash-newline and remove it. */
9208 if (*p == '\\' && p[1] == '\n')
9210 /* Change newline chars into newline-markers. */
9211 else if (*p == '\n')
9223 ip = &instack[++indepth];
9224 ip->nominal_fname = ip->fname = "*Initialization*";
9226 ip->buf = ip->bufp = buf;
9227 ip->length = strlen (buf);
9231 ip->if_stack = if_stack;
9232 ip->system_header_p = 0;
9234 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9237 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9238 do_define (buf, buf + strlen (buf), NULL, kt);
9242 /* JF, this does the work for the -U option */
9245 make_undef (str, op)
9250 struct directive *kt;
9252 ip = &instack[++indepth];
9253 ip->nominal_fname = ip->fname = "*undef*";
9255 ip->buf = ip->bufp = str;
9256 ip->length = strlen (str);
9260 ip->if_stack = if_stack;
9261 ip->system_header_p = 0;
9263 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9266 do_undef (str, str + strlen (str), op, kt);
9270 /* Process the string STR as if it appeared as the body of a #assert.
9271 OPTION is the option name for which STR was the argument. */
9274 make_assertion (option, str)
9279 struct directive *kt;
9280 U_CHAR *buf, *p, *q;
9282 /* Copy the entire option so we can modify it. */
9283 buf = (U_CHAR *) alloca (strlen (str) + 1);
9284 strcpy ((char *) buf, str);
9285 /* Scan for any backslash-newline and remove it. */
9288 if (*p == '\\' && p[1] == '\n')
9296 if (!is_idstart[*p]) {
9297 error ("malformed option `%s %s'", option, str);
9300 while (is_idchar[*++p])
9302 while (*p == ' ' || *p == '\t') p++;
9303 if (! (*p == 0 || *p == '(')) {
9304 error ("malformed option `%s %s'", option, str);
9308 ip = &instack[++indepth];
9309 ip->nominal_fname = ip->fname = "*Initialization*";
9311 ip->buf = ip->bufp = buf;
9312 ip->length = strlen (buf);
9316 ip->if_stack = if_stack;
9317 ip->system_header_p = 0;
9319 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9322 /* pass NULL as output ptr to do_define since we KNOW it never
9323 does any output.... */
9324 do_assert (buf, buf + strlen (buf) , NULL_PTR, kt);
9328 /* Append a chain of `struct file_name_list's
9329 to the end of the main include chain.
9330 FIRST is the beginning of the chain to append, and LAST is the end. */
9333 append_include_chain (first, last)
9334 struct file_name_list *first, *last;
9336 struct file_name_list *dir;
9338 if (!first || !last)
9344 last_include->next = first;
9346 if (first_bracket_include == 0)
9347 first_bracket_include = first;
9349 for (dir = first; ; dir = dir->next) {
9350 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9351 if (len > max_include_len)
9352 max_include_len = len;
9358 last_include = last;
9361 /* Add output to `deps_buffer' for the -M switch.
9362 STRING points to the text to be output.
9363 SPACER is ':' for targets, ' ' for dependencies, zero for text
9364 to be inserted literally. */
9367 deps_output (string, spacer)
9371 int size = strlen (string);
9376 #ifndef MAX_OUTPUT_COLUMNS
9377 #define MAX_OUTPUT_COLUMNS 72
9381 && (deps_column + size) > MAX_OUTPUT_COLUMNS)
9383 deps_output (" \\\n ", 0);
9387 if (deps_size + size + 8 > deps_allocated_size) {
9388 deps_allocated_size = (deps_size + size + 50) * 2;
9389 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
9391 if (spacer == ' ' && deps_column > 0)
9392 deps_buffer[deps_size++] = ' ';
9393 bcopy (string, &deps_buffer[deps_size], size);
9395 deps_column += size;
9397 deps_buffer[deps_size++] = ':';
9398 deps_buffer[deps_size] = 0;
9401 #if defined(USG) || defined(VMS)
9407 register unsigned length;
9409 while (length-- > 0)
9414 bcopy (b1, b2, length)
9417 register unsigned length;
9419 while (length-- > 0)
9424 bcmp (b1, b2, length) /* This could be a macro! */
9427 register unsigned length;
9429 while (length-- > 0)
9435 #endif /* not BSTRING */
9436 #endif /* USG or VMS */
9443 fprintf (stderr, "%s: ", progname);
9444 fprintf (stderr, str, arg);
9445 fprintf (stderr, "\n");
9446 exit (FAILURE_EXIT_CODE);
9449 /* More 'friendly' abort that prints the line and file.
9450 config.h can #define abort fancy_abort if you like that sort of thing. */
9455 fatal ("Internal gcc abort.");
9459 perror_with_name (name)
9462 fprintf (stderr, "%s: ", progname);
9463 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9468 pfatal_with_name (name)
9471 perror_with_name (name);
9475 exit (FAILURE_EXIT_CODE);
9479 /* Handler for SIGPIPE. */
9483 /* If this is missing, some compilers complain. */
9486 fatal ("output pipe has been closed");
9492 fatal ("Memory exhausted.");
9500 register char *ptr = (char *) malloc (size);
9501 if (ptr != 0) return (ptr);
9508 xrealloc (old, size)
9512 register char *ptr = (char *) realloc (old, size);
9513 if (ptr != 0) return (ptr);
9520 xcalloc (number, size)
9521 unsigned number, size;
9523 register unsigned total = number * size;
9524 register char *ptr = (char *) malloc (total);
9529 /* It's not too long, so loop, zeroing by longs.
9530 It must be safe because malloc values are always well aligned. */
9531 register long *zp = (long *) ptr;
9532 register long *zl = (long *) (ptr + total - 4);
9533 register int i = total - 4;
9552 unsigned size = strlen (input);
9553 char *output = xmalloc (size + 1);
9554 strcpy (output, input);
9558 /* Get the file-mode and data size of the file open on FD
9559 and store them in *MODE_POINTER and *SIZE_POINTER. */
9562 file_size_and_mode (fd, mode_pointer, size_pointer)
9565 long int *size_pointer;
9569 if (fstat (fd, &sbuf) < 0) return (-1);
9570 if (mode_pointer) *mode_pointer = sbuf.st_mode;
9571 if (size_pointer) *size_pointer = sbuf.st_size;
9576 output_dots (fd, depth)
9589 /* Under VMS we need to fix up the "include" specification
9590 filename so that everything following the 1st slash is
9591 changed into its correct VMS file specification. */
9594 hack_vms_include_specification (fname)
9597 register char *cp, *cp1, *cp2;
9598 int f, check_filename_before_returning, no_prefix_seen;
9601 check_filename_before_returning = 0;
9604 /* Ignore leading "./"s */
9605 while (fname[0] == '.' && fname[1] == '/') {
9606 strcpy (fname, fname+2);
9607 no_prefix_seen = 1; /* mark this for later */
9609 /* Look for the boundary between the VMS and UNIX filespecs */
9610 cp = rindex (fname, ']'); /* Look for end of dirspec. */
9611 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
9612 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
9616 cp = index (fname, '/'); /* Look for the "/" */
9620 * Check if we have a vax-c style '#include filename'
9621 * and add the missing .h
9624 if (index(fname,'.') == 0)
9625 strcat(fname, ".h");
9627 if (index(cp,'.') == 0)
9631 cp2 = Local; /* initialize */
9633 /* We are trying to do a number of things here. First of all, we are
9634 trying to hammer the filenames into a standard format, such that later
9635 processing can handle them.
9637 If the file name contains something like [dir.], then it recognizes this
9638 as a root, and strips the ".]". Later processing will add whatever is
9639 needed to get things working properly.
9641 If no device is specified, then the first directory name is taken to be
9642 a device name (or a rooted logical). */
9644 /* See if we found that 1st slash */
9645 if (cp == 0) return; /* Nothing to do!!! */
9646 if (*cp != '/') return; /* Nothing to do!!! */
9647 /* Point to the UNIX filename part (which needs to be fixed!) */
9649 /* If the directory spec is not rooted, we can just copy
9650 the UNIX filename part and we are done */
9651 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
9652 if (cp[-2] != '.') {
9654 * The VMS part ends in a `]', and the preceding character is not a `.'.
9655 * We strip the `]', and then splice the two parts of the name in the
9656 * usual way. Given the default locations for include files in cccp.c,
9657 * we will only use this code if the user specifies alternate locations
9658 * with the /include (-I) switch on the command line. */
9659 cp -= 1; /* Strip "]" */
9660 cp1--; /* backspace */
9663 * The VMS part has a ".]" at the end, and this will not do. Later
9664 * processing will add a second directory spec, and this would be a syntax
9665 * error. Thus we strip the ".]", and thus merge the directory specs.
9666 * We also backspace cp1, so that it points to a '/'. This inhibits the
9667 * generation of the 000000 root directory spec (which does not belong here
9670 cp -= 2; /* Strip ".]" */
9671 cp1--; }; /* backspace */
9674 /* We drop in here if there is no VMS style directory specification yet.
9675 * If there is no device specification either, we make the first dir a
9676 * device and try that. If we do not do this, then we will be essentially
9677 * searching the users default directory (as if they did a #include "asdf.h").
9679 * Then all we need to do is to push a '[' into the output string. Later
9680 * processing will fill this in, and close the bracket.
9682 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
9683 *cp2++ = '['; /* Open the directory specification */
9686 /* at this point we assume that we have the device spec, and (at least
9687 the opening "[" for a directory specification. We may have directories
9688 specified already */
9690 /* If there are no other slashes then the filename will be
9691 in the "root" directory. Otherwise, we need to add
9692 directory specifications. */
9693 if (index (cp1, '/') == 0) {
9694 /* Just add "000000]" as the directory string */
9695 strcpy (cp2, "000000]");
9696 cp2 += strlen (cp2);
9697 check_filename_before_returning = 1; /* we might need to fool with this later */
9699 /* As long as there are still subdirectories to add, do them. */
9700 while (index (cp1, '/') != 0) {
9701 /* If this token is "." we can ignore it */
9702 if ((cp1[0] == '.') && (cp1[1] == '/')) {
9706 /* Add a subdirectory spec. Do not duplicate "." */
9707 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
9709 /* If this is ".." then the spec becomes "-" */
9710 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
9711 /* Add "-" and skip the ".." */
9716 /* Copy the subdirectory */
9717 while (*cp1 != '/') *cp2++= *cp1++;
9718 cp1++; /* Skip the "/" */
9720 /* Close the directory specification */
9721 if (cp2[-1] == '.') /* no trailing periods */
9725 /* Now add the filename */
9726 while (*cp1) *cp2++ = *cp1++;
9728 /* Now append it to the original VMS spec. */
9731 /* If we put a [000000] in the filename, try to open it first. If this fails,
9732 remove the [000000], and return that name. This provides flexibility
9733 to the user in that they can use both rooted and non-rooted logical names
9734 to point to the location of the file. */
9736 if (check_filename_before_returning && no_prefix_seen) {
9737 f = open (fname, O_RDONLY, 0666);
9739 /* The file name is OK as it is, so return it as is. */
9743 /* The filename did not work. Try to remove the [000000] from the name,
9745 cp = index (fname, '[');
9746 cp2 = index (fname, ']') + 1;
9747 strcpy (cp, cp2); /* this gets rid of it */
9755 /* These are the read/write replacement routines for
9756 VAX-11 "C". They make read/write behave enough
9757 like their UNIX counterparts that CCCP will work */
9760 read (fd, buf, size)
9765 #undef read /* Get back the REAL read routine */
9767 register int total = 0;
9769 /* Read until the buffer is exhausted */
9771 /* Limit each read to 32KB */
9772 i = (size > (32*1024)) ? (32*1024) : size;
9773 i = read (fd, buf, i);
9775 if (i == 0) return (total);
9778 /* Account for this read */
9787 write (fd, buf, size)
9792 #undef write /* Get back the REAL write routine */
9796 /* Limit individual writes to 32Kb */
9799 j = (i > (32*1024)) ? (32*1024) : i;
9800 if (write (fd, buf, j) < 0) return (-1);
9801 /* Account for the data written */
9808 /* The following wrapper functions supply additional arguments to the VMS
9809 I/O routines to optimize performance with file handling. The arguments
9811 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
9812 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
9813 "fop=tef"- Truncate unused portions of file when closing file.
9814 "shr=nil"- Disallow file sharing while file is open.
9818 freopen (fname, type, oldfile)
9823 #undef freopen /* Get back the REAL fopen routine */
9824 if (strcmp (type, "w") == 0)
9825 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
9826 return freopen (fname, type, oldfile, "mbc=16");
9834 #undef fopen /* Get back the REAL fopen routine */
9835 if (strcmp (type, "w") == 0)
9836 return fopen (fname, type, "mbc=16", "deq=64", "fop=tef", "shr=nil");
9837 return fopen (fname, type, "mbc=16");
9841 open (fname, flags, prot)
9846 #undef open /* Get back the REAL open routine */
9847 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
9850 /* Avoid run-time library bug, where copying M out of N+M characters with
9851 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
9852 gcc-cpp exercises this particular bug. */
9855 strncat (dst, src, cnt)
9860 register char *d = dst, *s = (char *) src;
9861 register int n = cnt; /* convert to _signed_ type */
9863 while (*d) d++; /* advance to end */
9865 if (!(*d++ = *s++)) break;
9866 if (n < 0) *d = '\0';