1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92, 93, 94, 1995 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
60 /* By default, colon separates directories in a path. */
61 #ifndef PATH_SEPARATOR
62 #define PATH_SEPARATOR ':'
65 /* In case config.h defines these. */
70 #include <sys/types.h>
78 #include <sys/time.h> /* for __DATE__ and __TIME__ */
79 #include <sys/resource.h>
86 /* This defines "errno" properly for VMS, and gives us EACCES. */
89 /* VMS-specific definitions */
93 #define O_RDONLY 0 /* Open arg for Read/Only */
94 #define O_WRONLY 1 /* Open arg for Write/Only */
95 #define read(fd,buf,size) VMS_read (fd,buf,size)
96 #define write(fd,buf,size) VMS_write (fd,buf,size)
97 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
98 #define fopen(fname,mode) VMS_fopen (fname,mode)
99 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
100 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
101 static char * VMS_strncat ();
102 static int VMS_read ();
103 static int VMS_write ();
104 static int VMS_open ();
105 static FILE * VMS_fopen ();
106 static FILE * VMS_freopen ();
107 static void hack_vms_include_specification ();
108 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
109 #define ino_t vms_ino_t
110 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
112 #define BSTRING /* VMS/GCC supplies the bstring routines */
113 #endif /* __GNUC__ */
116 extern char *index ();
117 extern char *rindex ();
125 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
126 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
128 /* Find the largest host integer type and set its size and type. */
130 #ifndef HOST_BITS_PER_WIDE_INT
132 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
133 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
134 #define HOST_WIDE_INT long
136 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
137 #define HOST_WIDE_INT int
143 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
147 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
150 /* Define a generic NULL if one hasn't already been defined. */
157 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
158 #define GENERIC_PTR void *
160 #define GENERIC_PTR char *
165 #define NULL_PTR ((GENERIC_PTR)0)
168 #ifndef INCLUDE_LEN_FUDGE
169 #define INCLUDE_LEN_FUDGE 0
172 /* Forward declarations. */
178 /* External declarations. */
180 extern char *getenv ();
181 extern FILE *fdopen ();
182 extern char *version_string;
183 extern struct tm *localtime ();
185 #ifndef HAVE_STRERROR
188 extern const char *const sys_errlist[];
190 extern char *sys_errlist[];
192 #else /* HAVE_STERRROR */
196 char *strerror (int,...);
198 extern int parse_escape ();
199 extern HOST_WIDE_INT parse_c_expression ();
205 /* Forward declarations. */
212 #if defined(USG) || defined(VMS)
220 /* These functions are declared to return int instead of void since they
221 are going to be placed in a table and some old compilers have trouble with
222 pointers to functions returning void. */
224 static int do_define ();
225 static int do_line ();
226 static int do_include ();
227 static int do_undef ();
228 static int do_error ();
229 static int do_pragma ();
230 static int do_ident ();
232 static int do_xifdef ();
233 static int do_else ();
234 static int do_elif ();
235 static int do_endif ();
236 static int do_sccs ();
237 static int do_once ();
238 static int do_assert ();
239 static int do_unassert ();
240 static int do_warning ();
242 static void add_import ();
243 static void append_include_chain ();
244 static void deps_output ();
245 static void make_undef ();
246 static void make_definition ();
247 static void make_assertion ();
248 static void path_include ();
249 static void initialize_builtins ();
250 static void initialize_char_syntax ();
251 static void dump_arg_n ();
252 static void dump_defn_1 ();
253 static void delete_macro ();
254 static void trigraph_pcp ();
255 static void rescan ();
256 static void finclude ();
257 static void validate_else ();
258 static int comp_def_part ();
259 static void error_from_errno ();
260 static void error_with_line ();
262 void pedwarn_with_line ();
263 static void pedwarn_with_file_and_line ();
264 static void fatal ();
266 static void pfatal_with_name ();
267 static void perror_with_name ();
268 static void pipe_closed ();
269 static void print_containing_files ();
270 static int lookup_import ();
271 static int redundant_include_p ();
272 static is_system_include ();
273 static struct file_name_map *read_name_map ();
274 static char *read_filename_string ();
275 static int open_include_file ();
276 static int check_preconditions ();
277 static void pcfinclude ();
278 static void pcstring_used ();
279 static void write_output ();
280 static int check_macro_name ();
281 static int compare_defs ();
282 static int compare_token_lists ();
283 static HOST_WIDE_INT eval_if_expression ();
284 static int discard_comments ();
285 static int change_newlines ();
286 static int line_for_error ();
288 static int file_size_and_mode ();
290 static struct arglist *read_token_list ();
291 static void free_token_list ();
293 static struct hashnode *install ();
294 struct hashnode *lookup ();
296 static struct assertion_hashnode *assertion_install ();
297 static struct assertion_hashnode *assertion_lookup ();
299 static char *xrealloc ();
300 static char *xcalloc ();
301 static char *savestring ();
303 static void delete_assertion ();
304 static void macroexpand ();
305 static void dump_all_macros ();
306 static void conditional_skip ();
307 static void skip_if_group ();
308 static void output_line_directive ();
310 /* Last arg to output_line_directive. */
311 enum file_change_code {same_file, enter_file, leave_file};
313 static int grow_outbuf ();
314 static int handle_directive ();
315 static void memory_full ();
317 static U_CHAR *macarg1 ();
318 static char *macarg ();
320 static U_CHAR *skip_to_end_of_comment ();
321 static U_CHAR *skip_quoted_string ();
322 static U_CHAR *skip_paren_group ();
323 static char *quote_string ();
325 static char *check_precompiled ();
326 /* static struct macrodef create_definition (); [moved below] */
327 static void dump_single_macro ();
328 static void output_dots ();
330 #ifndef FAILURE_EXIT_CODE
331 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
334 #ifndef SUCCESS_EXIT_CODE
335 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
338 /* Name under which this program was invoked. */
340 static char *progname;
342 /* Nonzero means use extra default include directories for C++. */
344 static int cplusplus;
346 /* Nonzero means handle cplusplus style comments */
348 static int cplusplus_comments;
350 /* Nonzero means handle #import, for objective C. */
354 /* Nonzero means this is an assembly file, and allow
355 unknown directives, which could be comments. */
359 /* Current maximum length of directory names in the search path
360 for include files. (Altered as we get more of them.) */
362 static int max_include_len;
364 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
366 static int for_lint = 0;
368 /* Nonzero means copy comments into the output file. */
370 static int put_out_comments = 0;
372 /* Nonzero means don't process the ANSI trigraph sequences. */
374 static int no_trigraphs = 0;
376 /* Nonzero means print the names of included files rather than
377 the preprocessed output. 1 means just the #include "...",
378 2 means #include <...> as well. */
380 static int print_deps = 0;
382 /* Nonzero if missing .h files in -M output are assumed to be generated
383 files and not errors. */
385 static int print_deps_missing_files = 0;
387 /* Nonzero means print names of header files (-H). */
389 static int print_include_names = 0;
391 /* Nonzero means don't output line number information. */
393 static int no_line_directives;
395 /* Nonzero means output the text in failing conditionals,
396 inside #failed ... #endfailed. */
398 static int output_conditionals;
400 /* dump_only means inhibit output of the preprocessed text
401 and instead output the definitions of all user-defined
402 macros in a form suitable for use as input to cccp.
403 dump_names means pass #define and the macro name through to output.
404 dump_definitions means pass the whole definition (plus #define) through
407 static enum {dump_none, dump_only, dump_names, dump_definitions}
408 dump_macros = dump_none;
410 /* Nonzero means pass all #define and #undef directives which we actually
411 process through to the output stream. This feature is used primarily
412 to allow cc1 to record the #defines and #undefs for the sake of
413 debuggers which understand about preprocessor macros, but it may
414 also be useful with -E to figure out how symbols are defined, and
415 where they are defined. */
416 static int debug_output = 0;
418 /* Nonzero indicates special processing used by the pcp program. The
419 special effects of this mode are:
421 Inhibit all macro expansion, except those inside #if directives.
423 Process #define directives normally, and output their contents
426 Output preconditions to pcp_outfile indicating all the relevant
427 preconditions for use of this file in a later cpp run.
429 static FILE *pcp_outfile;
431 /* Nonzero means we are inside an IF during a -pcp run. In this mode
432 macro expansion is done, and preconditions are output for all macro
433 uses requiring them. */
434 static int pcp_inside_if;
436 /* Nonzero means never to include precompiled files.
437 This is 1 since there's no way now to make precompiled files,
438 so it's not worth testing for them. */
439 static int no_precomp = 1;
441 /* Nonzero means give all the error messages the ANSI standard requires. */
445 /* Nonzero means try to make failure to fit ANSI C an error. */
447 static int pedantic_errors;
449 /* Nonzero means don't print warning messages. -w. */
451 static int inhibit_warnings = 0;
453 /* Nonzero means warn if slash-star appears in a comment. */
455 static int warn_comments;
457 /* Nonzero means warn if a macro argument is (or would be)
458 stringified with -traditional. */
460 static int warn_stringify;
462 /* Nonzero means warn if there are any trigraphs. */
464 static int warn_trigraphs;
466 /* Nonzero means warn if #import is used. */
468 static int warn_import = 1;
470 /* Nonzero means turn warnings into errors. */
472 static int warnings_are_errors;
474 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
478 /* Nonzero causes output not to be done,
479 but directives such as #define that have side effects
482 static int no_output;
484 /* Nonzero means this file was included with a -imacros or -include
485 command line and should not be recorded as an include file. */
487 static int no_record_file;
489 /* Nonzero means that we have finished processing the command line options.
490 This flag is used to decide whether or not to issue certain errors
493 static int done_initializing = 0;
495 /* Line where a newline was first seen in a string constant. */
497 static int multiline_string_line = 0;
499 /* I/O buffer structure.
500 The `fname' field is nonzero for source files and #include files
501 and for the dummy text used for -D and -U.
502 It is zero for rescanning results of macro expansion
503 and for expanding macro arguments. */
504 #define INPUT_STACK_MAX 400
505 static struct file_buf {
507 /* Filename specified with #line directive. */
509 /* Record where in the search path this file was found.
510 For #include_next. */
511 struct file_name_list *dir;
516 /* Macro that this level is the expansion of.
517 Included so that we can reenable the macro
518 at the end of this level. */
519 struct hashnode *macro;
520 /* Value of if_stack at start of this file.
521 Used to prohibit unmatched #endif (etc) in an include file. */
522 struct if_stack *if_stack;
523 /* Object to be freed at end of input at this level. */
525 /* True if this is a header file included using <FILENAME>. */
526 char system_header_p;
527 } instack[INPUT_STACK_MAX];
529 static int last_error_tick; /* Incremented each time we print it. */
530 static int input_file_stack_tick; /* Incremented when the status changes. */
532 /* Current nesting level of input sources.
533 `instack[indepth]' is the level currently being read. */
534 static int indepth = -1;
535 #define CHECK_DEPTH(code) \
536 if (indepth >= (INPUT_STACK_MAX - 1)) \
538 error_with_line (line_for_error (instack[indepth].lineno), \
539 "macro or `#include' recursion too deep"); \
543 /* Current depth in #include directives that use <...>. */
544 static int system_include_depth = 0;
546 typedef struct file_buf FILE_BUF;
548 /* The output buffer. Its LENGTH field is the amount of room allocated
549 for the buffer, not the number of chars actually present. To get
550 that, subtract outbuf.buf from outbuf.bufp. */
552 #define OUTBUF_SIZE 10 /* initial size of output buffer */
553 static FILE_BUF outbuf;
555 /* Grow output buffer OBUF points at
556 so it can hold at least NEEDED more chars. */
558 #define check_expand(OBUF, NEEDED) \
559 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
560 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
562 struct file_name_list
564 struct file_name_list *next;
566 /* If the following is nonzero, it is a macro name.
567 Don't include the file again if that macro is defined. */
568 U_CHAR *control_macro;
569 /* If the following is nonzero, it is a C-language system include
571 int c_system_include_path;
572 /* Mapping of file names for this directory. */
573 struct file_name_map *name_map;
574 /* Non-zero if name_map is valid. */
578 /* #include "file" looks in source file dir, then stack. */
579 /* #include <file> just looks in the stack. */
580 /* -I directories are added to the end, then the defaults are added. */
582 static struct default_include {
583 char *fname; /* The name of the directory. */
584 int cplusplus; /* Only look here if we're compiling C++. */
585 int cxx_aware; /* Includes in this directory don't need to
586 be wrapped in extern "C" when compiling
588 } include_defaults_array[]
589 #ifdef INCLUDE_DEFAULTS
593 /* Pick up GNU C++ specific include files. */
594 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
596 /* This is the dir for fixincludes. Put it just before
597 the files that we fix. */
598 { GCC_INCLUDE_DIR, 0, 0 },
599 /* For cross-compilation, this dir name is generated
600 automatically in Makefile.in. */
601 { CROSS_INCLUDE_DIR, 0, 0 },
602 /* This is another place that the target system's headers might be. */
603 { TOOL_INCLUDE_DIR, 0, 0 },
604 #else /* not CROSS_COMPILE */
605 /* This should be /usr/local/include and should come before
606 the fixincludes-fixed header files. */
607 { LOCAL_INCLUDE_DIR, 0, 1 },
608 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
609 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
610 { TOOL_INCLUDE_DIR, 0, 0 },
611 /* This is the dir for fixincludes. Put it just before
612 the files that we fix. */
613 { GCC_INCLUDE_DIR, 0, 0 },
614 /* Some systems have an extra dir of include files. */
615 #ifdef SYSTEM_INCLUDE_DIR
616 { SYSTEM_INCLUDE_DIR, 0, 0 },
618 { STANDARD_INCLUDE_DIR, 0, 0 },
619 #endif /* not CROSS_COMPILE */
622 #endif /* no INCLUDE_DEFAULTS */
624 /* The code looks at the defaults through this pointer, rather than through
625 the constant structure above. This pointer gets changed if an environment
626 variable specifies other defaults. */
627 static struct default_include *include_defaults = include_defaults_array;
629 static struct file_name_list *include = 0; /* First dir to search */
630 /* First dir to search for <file> */
631 /* This is the first element to use for #include <...>.
632 If it is 0, use the entire chain for such includes. */
633 static struct file_name_list *first_bracket_include = 0;
634 /* This is the first element in the chain that corresponds to
635 a directory of system header files. */
636 static struct file_name_list *first_system_include = 0;
637 static struct file_name_list *last_include = 0; /* Last in chain */
639 /* Chain of include directories to put at the end of the other chain. */
640 static struct file_name_list *after_include = 0;
641 static struct file_name_list *last_after_include = 0; /* Last in chain */
643 /* Chain to put at the start of the system include files. */
644 static struct file_name_list *before_system = 0;
645 static struct file_name_list *last_before_system = 0; /* Last in chain */
647 /* List of included files that contained #pragma once. */
648 static struct file_name_list *dont_repeat_files = 0;
650 /* List of other included files.
651 If ->control_macro if nonzero, the file had a #ifndef
652 around the entire contents, and ->control_macro gives the macro name. */
653 static struct file_name_list *all_include_files = 0;
655 /* Directory prefix that should replace `/usr' in the standard
656 include file directories. */
657 static char *include_prefix;
659 /* Global list of strings read in from precompiled files. This list
660 is kept in the order the strings are read in, with new strings being
661 added at the end through stringlist_tailp. We use this list to output
662 the strings at the end of the run.
664 static STRINGDEF *stringlist;
665 static STRINGDEF **stringlist_tailp = &stringlist;
668 /* Structure returned by create_definition */
669 typedef struct macrodef MACRODEF;
672 struct definition *defn;
677 static struct macrodef create_definition ();
680 enum sharp_token_type {
681 NO_SHARP_TOKEN, /* token not present */
683 SHARP_TOKEN = '#', /* token spelled with # only */
684 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
686 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
687 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
690 /* Structure allocated for every #define. For a simple replacement
693 nargs = -1, the `pattern' list is null, and the expansion is just
694 the replacement text. Nargs = 0 means a functionlike macro with no args,
696 #define getchar() getc (stdin) .
697 When there are args, the expansion is the replacement text with the
698 args squashed out, and the reflist is a list describing how to
699 build the output from the input: e.g., "3 chars, then the 1st arg,
700 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
701 The chars here come from the expansion. Whatever is left of the
702 expansion after the last arg-occurrence is copied after that arg.
703 Note that the reflist can be arbitrarily long---
704 its length depends on the number of times the arguments appear in
705 the replacement text, not how many args there are. Example:
706 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
708 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
709 where (x, y) means (nchars, argno). */
711 typedef struct definition DEFINITION;
714 int length; /* length of expansion string */
715 int predefined; /* True if the macro was builtin or */
716 /* came from the command line */
718 int line; /* Line number of definition */
719 char *file; /* File of definition */
720 char rest_args; /* Nonzero if last arg. absorbs the rest */
722 struct reflist *next;
724 enum sharp_token_type stringify; /* set if a # operator before arg */
725 enum sharp_token_type raw_before; /* set if a ## operator before arg */
726 enum sharp_token_type raw_after; /* set if a ## operator after arg */
728 char rest_args; /* Nonzero if this arg. absorbs the rest */
729 int nchars; /* Number of literal chars to copy before
730 this arg occurrence. */
731 int argno; /* Number of arg to substitute (origin-0) */
734 /* Names of macro args, concatenated in reverse order
735 with comma-space between them.
736 The only use of this is that we warn on redefinition
737 if this differs between the old and new definitions. */
742 /* different kinds of things that can appear in the value field
743 of a hash node. Actually, this may be useless now. */
751 * special extension string that can be added to the last macro argument to
752 * allow it to absorb the "rest" of the arguments when expanded. Ex:
753 * #define wow(a, b...) process (b, a, b)
754 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
755 * { wow (one, two); } -> { process (two, one, two); }
756 * if this "rest_arg" is used with the concat token '##' and if it is not
757 * supplied then the token attached to with ## will not be outputted. Ex:
758 * #define wow (a, b...) process (b ## , a, ## b)
759 * { wow (1, 2); } -> { process (2, 1, 2); }
760 * { wow (one); } -> { process (one); {
762 static char rest_extension[] = "...";
763 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
765 /* The structure of a node in the hash table. The hash table
766 has entries for all tokens defined by #define directives (type T_MACRO),
767 plus some special tokens like __LINE__ (these each have their own
768 type, and the appropriate code is run when that type of node is seen.
769 It does not contain control words like "#define", which are recognized
770 by a separate piece of code. */
772 /* different flavors of hash nodes --- also used in keyword table */
774 T_DEFINE = 1, /* the `#define' keyword */
775 T_INCLUDE, /* the `#include' keyword */
776 T_INCLUDE_NEXT, /* the `#include_next' keyword */
777 T_IMPORT, /* the `#import' keyword */
778 T_IFDEF, /* the `#ifdef' keyword */
779 T_IFNDEF, /* the `#ifndef' keyword */
780 T_IF, /* the `#if' keyword */
781 T_ELSE, /* `#else' */
782 T_PRAGMA, /* `#pragma' */
783 T_ELIF, /* `#elif' */
784 T_UNDEF, /* `#undef' */
785 T_LINE, /* `#line' */
786 T_ERROR, /* `#error' */
787 T_WARNING, /* `#warning' */
788 T_ENDIF, /* `#endif' */
789 T_SCCS, /* `#sccs', used on system V. */
790 T_IDENT, /* `#ident', used on system V. */
791 T_ASSERT, /* `#assert', taken from system V. */
792 T_UNASSERT, /* `#unassert', taken from system V. */
793 T_SPECLINE, /* special symbol `__LINE__' */
794 T_DATE, /* `__DATE__' */
795 T_FILE, /* `__FILE__' */
796 T_BASE_FILE, /* `__BASE_FILE__' */
797 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
798 T_VERSION, /* `__VERSION__' */
799 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
800 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
801 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
802 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
803 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
804 T_TIME, /* `__TIME__' */
805 T_CONST, /* Constant value, used by `__STDC__' */
806 T_MACRO, /* macro defined by `#define' */
807 T_DISABLED, /* macro temporarily turned off for rescan */
808 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
809 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
810 T_UNUSED /* Used for something not defined. */
814 struct hashnode *next; /* double links for easy deletion */
815 struct hashnode *prev;
816 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
817 chain is kept, in case the node is the head
818 of the chain and gets deleted. */
819 enum node_type type; /* type of special token */
820 int length; /* length of token, for quick comparison */
821 U_CHAR *name; /* the actual name */
822 union hashval value; /* pointer to expansion, or whatever */
825 typedef struct hashnode HASHNODE;
827 /* Some definitions for the hash table. The hash function MUST be
828 computed as shown in hashf () below. That is because the rescan
829 loop computes the hash value `on the fly' for most tokens,
830 in order to avoid the overhead of a lot of procedure calls to
831 the hashf () function. Hashf () only exists for the sake of
832 politeness, for use when speed isn't so important. */
834 #define HASHSIZE 1403
835 static HASHNODE *hashtab[HASHSIZE];
836 #define HASHSTEP(old, c) ((old << 2) + c)
837 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
839 /* Symbols to predefine. */
841 #ifdef CPP_PREDEFINES
842 static char *predefs = CPP_PREDEFINES;
844 static char *predefs = "";
847 /* We let tm.h override the types used here, to handle trivial differences
848 such as the choice of unsigned int or long unsigned int for size_t.
849 When machines start needing nontrivial differences in the size type,
850 it would be best to do something here to figure out automatically
851 from other information what type to use. */
853 /* The string value for __SIZE_TYPE__. */
856 #define SIZE_TYPE "long unsigned int"
859 /* The string value for __PTRDIFF_TYPE__. */
862 #define PTRDIFF_TYPE "long int"
865 /* The string value for __WCHAR_TYPE__. */
868 #define WCHAR_TYPE "int"
870 char * wchar_type = WCHAR_TYPE;
873 /* The string value for __USER_LABEL_PREFIX__ */
875 #ifndef USER_LABEL_PREFIX
876 #define USER_LABEL_PREFIX ""
879 /* The string value for __REGISTER_PREFIX__ */
881 #ifndef REGISTER_PREFIX
882 #define REGISTER_PREFIX ""
885 /* In the definition of a #assert name, this structure forms
886 a list of the individual values asserted.
887 Each value is itself a list of "tokens".
888 These are strings that are compared by name. */
890 struct tokenlist_list {
891 struct tokenlist_list *next;
892 struct arglist *tokens;
895 struct assertion_hashnode {
896 struct assertion_hashnode *next; /* double links for easy deletion */
897 struct assertion_hashnode *prev;
898 /* also, a back pointer to this node's hash
899 chain is kept, in case the node is the head
900 of the chain and gets deleted. */
901 struct assertion_hashnode **bucket_hdr;
902 int length; /* length of token, for quick comparison */
903 U_CHAR *name; /* the actual name */
904 /* List of token-sequences. */
905 struct tokenlist_list *value;
908 typedef struct assertion_hashnode ASSERTION_HASHNODE;
910 /* Some definitions for the hash table. The hash function MUST be
911 computed as shown in hashf below. That is because the rescan
912 loop computes the hash value `on the fly' for most tokens,
913 in order to avoid the overhead of a lot of procedure calls to
914 the hashf function. hashf only exists for the sake of
915 politeness, for use when speed isn't so important. */
917 #define ASSERTION_HASHSIZE 37
918 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
920 /* Nonzero means inhibit macroexpansion of what seem to be
921 assertion tests, in rescan. For #if. */
922 static int assertions_flag;
924 /* `struct directive' defines one #-directive, including how to handle it. */
927 int length; /* Length of name */
928 int (*func)(); /* Function to handle directive */
929 char *name; /* Name of directive */
930 enum node_type type; /* Code which describes which directive. */
931 char angle_brackets; /* Nonzero => <...> is special. */
932 char traditional_comments; /* Nonzero: keep comments if -traditional. */
933 char pass_thru; /* Copy preprocessed directive to output file. */
936 /* Here is the actual list of #-directives, most-often-used first. */
938 static struct directive directive_table[] = {
939 { 6, do_define, "define", T_DEFINE, 0, 1},
940 { 2, do_if, "if", T_IF},
941 { 5, do_xifdef, "ifdef", T_IFDEF},
942 { 6, do_xifdef, "ifndef", T_IFNDEF},
943 { 5, do_endif, "endif", T_ENDIF},
944 { 4, do_else, "else", T_ELSE},
945 { 4, do_elif, "elif", T_ELIF},
946 { 4, do_line, "line", T_LINE},
947 { 7, do_include, "include", T_INCLUDE, 1},
948 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
949 { 6, do_include, "import", T_IMPORT, 1},
950 { 5, do_undef, "undef", T_UNDEF},
951 { 5, do_error, "error", T_ERROR},
952 { 7, do_warning, "warning", T_WARNING},
953 #ifdef SCCS_DIRECTIVE
954 { 4, do_sccs, "sccs", T_SCCS},
956 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
957 { 5, do_ident, "ident", T_IDENT},
958 { 6, do_assert, "assert", T_ASSERT},
959 { 8, do_unassert, "unassert", T_UNASSERT},
960 { -1, 0, "", T_UNUSED},
963 /* When a directive handler is called,
964 this points to the # (or the : of the %:) that started the directive. */
965 U_CHAR *directive_start;
967 /* table to tell if char can be part of a C identifier. */
968 U_CHAR is_idchar[256];
969 /* table to tell if char can be first char of a c identifier. */
970 U_CHAR is_idstart[256];
971 /* table to tell if c is horizontal space. */
972 U_CHAR is_hor_space[256];
973 /* table to tell if c is horizontal or vertical space. */
974 static U_CHAR is_space[256];
975 /* names of some characters */
976 static char *char_name[256];
978 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
979 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
981 static int errors = 0; /* Error counter for exit code */
983 /* Name of output file, for error messages. */
984 static char *out_fname;
986 /* Zero means dollar signs are punctuation.
987 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
988 This must be 0 for correct processing of this ANSI C program:
990 #define lose(b) foo (b)
993 static int dollars_in_ident;
994 #ifndef DOLLARS_IN_IDENTIFIERS
995 #define DOLLARS_IN_IDENTIFIERS 1
998 static FILE_BUF expand_to_temp_buffer ();
1000 static DEFINITION *collect_expansion ();
1002 /* Stack of conditionals currently in progress
1003 (including both successful and failing conditionals). */
1006 struct if_stack *next; /* for chaining to the next stack frame */
1007 char *fname; /* copied from input when frame is made */
1008 int lineno; /* similarly */
1009 int if_succeeded; /* true if a leg of this if-group
1010 has been passed through rescan */
1011 U_CHAR *control_macro; /* For #ifndef at start of file,
1012 this is the macro name tested. */
1013 enum node_type type; /* type of last directive seen in this group */
1015 typedef struct if_stack IF_STACK_FRAME;
1016 static IF_STACK_FRAME *if_stack = NULL;
1018 /* Buffer of -M output. */
1019 static char *deps_buffer;
1021 /* Number of bytes allocated in above. */
1022 static int deps_allocated_size;
1024 /* Number of bytes used. */
1025 static int deps_size;
1027 /* Number of bytes since the last newline. */
1028 static int deps_column;
1030 /* Nonzero means -I- has been seen,
1031 so don't look for #include "foo" the source-file directory. */
1032 static int ignore_srcdir;
1034 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1035 retrying if necessary. Return a negative value if an error occurs,
1036 otherwise return the actual number of bytes read,
1037 which must be LEN unless end-of-file was reached. */
1040 safe_read (desc, ptr, len)
1047 int nchars = read (desc, ptr, left);
1064 /* Write LEN bytes at PTR to descriptor DESC,
1065 retrying if necessary, and treating any real error as fatal. */
1068 safe_write (desc, ptr, len)
1074 int written = write (desc, ptr, len);
1081 pfatal_with_name (out_fname);
1099 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1100 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1101 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1102 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1103 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1105 /* Record the option used with each element of pend_assertions.
1106 This is preparation for supporting more than one option for making
1108 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1109 int inhibit_predefs = 0;
1110 int no_standard_includes = 0;
1111 int no_standard_cplusplus_includes = 0;
1112 int missing_newline = 0;
1114 /* Non-0 means don't output the preprocessed program. */
1115 int inhibit_output = 0;
1116 /* Non-0 means -v, so print the full set of include dirs. */
1119 /* File name which deps are being written to.
1120 This is 0 if deps are being written to stdout. */
1121 char *deps_file = 0;
1122 /* Fopen file mode to open deps_file with. */
1123 char *deps_mode = "a";
1124 /* Stream on which to print the dependency information. */
1125 FILE *deps_stream = 0;
1126 /* Target-name to write with the dependency information. */
1127 char *deps_target = 0;
1130 /* Get rid of any avoidable limit on stack size. */
1134 /* Set the stack limit huge so that alloca (particularly stringtab
1135 * in dbxread.c) does not fail. */
1136 getrlimit (RLIMIT_STACK, &rlim);
1137 rlim.rlim_cur = rlim.rlim_max;
1138 setrlimit (RLIMIT_STACK, &rlim);
1140 #endif /* RLIMIT_STACK defined */
1143 signal (SIGPIPE, pipe_closed);
1146 p = argv[0] + strlen (argv[0]);
1147 while (p != argv[0] && p[-1] != '/'
1148 #ifdef DIR_SEPARATOR
1149 && p[-1] != DIR_SEPARATOR
1157 /* Remove directories from PROGNAME. */
1160 if ((p = rindex (s, ':')) != 0) s = p + 1; /* skip device */
1161 if ((p = rindex (s, ']')) != 0) s = p + 1; /* skip directory */
1162 if ((p = rindex (s, '>')) != 0) s = p + 1; /* alternate (int'n'l) dir */
1163 s = progname = savestring (s);
1164 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1165 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1166 && (p[1] == 'e' || p[1] == 'E')
1167 && (p[2] == 'x' || p[2] == 'X')
1168 && (p[3] == 'e' || p[3] == 'E')
1177 /* Initialize is_idchar to allow $. */
1178 dollars_in_ident = 1;
1179 initialize_char_syntax ();
1180 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1182 no_line_directives = 0;
1184 dump_macros = dump_none;
1187 cplusplus_comments = 0;
1189 bzero ((char *) pend_files, argc * sizeof (char *));
1190 bzero ((char *) pend_defs, argc * sizeof (char *));
1191 bzero ((char *) pend_undefs, argc * sizeof (char *));
1192 bzero ((char *) pend_assertions, argc * sizeof (char *));
1193 bzero ((char *) pend_includes, argc * sizeof (char *));
1195 /* Process switches and find input file name. */
1197 for (i = 1; i < argc; i++) {
1198 if (argv[i][0] != '-') {
1199 if (out_fname != NULL)
1200 fatal ("Usage: %s [switches] input output", argv[0]);
1201 else if (in_fname != NULL)
1202 out_fname = argv[i];
1206 switch (argv[i][1]) {
1209 if (!strcmp (argv[i], "-include")) {
1211 fatal ("Filename missing after `-include' option");
1213 pend_includes[i] = argv[i+1], i++;
1215 if (!strcmp (argv[i], "-imacros")) {
1217 fatal ("Filename missing after `-imacros' option");
1219 pend_files[i] = argv[i+1], i++;
1221 if (!strcmp (argv[i], "-iprefix")) {
1223 fatal ("Filename missing after `-iprefix' option");
1225 include_prefix = argv[++i];
1227 if (!strcmp (argv[i], "-ifoutput")) {
1228 output_conditionals = 1;
1230 if (!strcmp (argv[i], "-isystem")) {
1231 struct file_name_list *dirtmp;
1234 fatal ("Filename missing after `-isystem' option");
1236 dirtmp = (struct file_name_list *)
1237 xmalloc (sizeof (struct file_name_list));
1239 dirtmp->control_macro = 0;
1240 dirtmp->c_system_include_path = 1;
1241 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
1242 strcpy (dirtmp->fname, argv[++i]);
1243 dirtmp->got_name_map = 0;
1245 if (before_system == 0)
1246 before_system = dirtmp;
1248 last_before_system->next = dirtmp;
1249 last_before_system = dirtmp; /* Tail follows the last one */
1251 /* Add directory to end of path for includes,
1252 with the default prefix at the front of its name. */
1253 if (!strcmp (argv[i], "-iwithprefix")) {
1254 struct file_name_list *dirtmp;
1257 if (include_prefix != 0)
1258 prefix = include_prefix;
1260 prefix = savestring (GCC_INCLUDE_DIR);
1261 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1262 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1263 prefix[strlen (prefix) - 7] = 0;
1266 dirtmp = (struct file_name_list *)
1267 xmalloc (sizeof (struct file_name_list));
1268 dirtmp->next = 0; /* New one goes on the end */
1269 dirtmp->control_macro = 0;
1270 dirtmp->c_system_include_path = 0;
1272 fatal ("Directory name missing after `-iwithprefix' option");
1274 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1275 + strlen (prefix) + 1);
1276 strcpy (dirtmp->fname, prefix);
1277 strcat (dirtmp->fname, argv[++i]);
1278 dirtmp->got_name_map = 0;
1280 if (after_include == 0)
1281 after_include = dirtmp;
1283 last_after_include->next = dirtmp;
1284 last_after_include = dirtmp; /* Tail follows the last one */
1286 /* Add directory to main path for includes,
1287 with the default prefix at the front of its name. */
1288 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1289 struct file_name_list *dirtmp;
1292 if (include_prefix != 0)
1293 prefix = include_prefix;
1295 prefix = savestring (GCC_INCLUDE_DIR);
1296 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1297 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1298 prefix[strlen (prefix) - 7] = 0;
1301 dirtmp = (struct file_name_list *)
1302 xmalloc (sizeof (struct file_name_list));
1303 dirtmp->next = 0; /* New one goes on the end */
1304 dirtmp->control_macro = 0;
1305 dirtmp->c_system_include_path = 0;
1307 fatal ("Directory name missing after `-iwithprefixbefore' option");
1309 dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
1310 + strlen (prefix) + 1);
1311 strcpy (dirtmp->fname, prefix);
1312 strcat (dirtmp->fname, argv[++i]);
1313 dirtmp->got_name_map = 0;
1315 append_include_chain (dirtmp, dirtmp);
1317 /* Add directory to end of path for includes. */
1318 if (!strcmp (argv[i], "-idirafter")) {
1319 struct file_name_list *dirtmp;
1321 dirtmp = (struct file_name_list *)
1322 xmalloc (sizeof (struct file_name_list));
1323 dirtmp->next = 0; /* New one goes on the end */
1324 dirtmp->control_macro = 0;
1325 dirtmp->c_system_include_path = 0;
1327 fatal ("Directory name missing after `-idirafter' option");
1329 dirtmp->fname = argv[++i];
1330 dirtmp->got_name_map = 0;
1332 if (after_include == 0)
1333 after_include = dirtmp;
1335 last_after_include->next = dirtmp;
1336 last_after_include = dirtmp; /* Tail follows the last one */
1341 if (out_fname != NULL)
1342 fatal ("Output filename specified twice");
1344 fatal ("Filename missing after -o option");
1345 out_fname = argv[++i];
1346 if (!strcmp (out_fname, "-"))
1351 if (!strcmp (argv[i], "-pedantic"))
1353 else if (!strcmp (argv[i], "-pedantic-errors")) {
1355 pedantic_errors = 1;
1356 } else if (!strcmp (argv[i], "-pcp")) {
1359 fatal ("Filename missing after -pcp option");
1360 pcp_fname = argv[++i];
1362 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1363 ? fopen (pcp_fname, "w")
1364 : fdopen (dup (fileno (stdout)), "w"));
1365 if (pcp_outfile == 0)
1366 pfatal_with_name (pcp_fname);
1372 if (!strcmp (argv[i], "-traditional")) {
1374 if (dollars_in_ident > 0)
1375 dollars_in_ident = 1;
1376 } else if (!strcmp (argv[i], "-trigraphs")) {
1382 if (! strcmp (argv[i], "-lang-c"))
1383 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1384 if (! strcmp (argv[i], "-lang-c++"))
1385 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1386 if (! strcmp (argv[i], "-lang-c-c++-comments"))
1387 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1388 if (! strcmp (argv[i], "-lang-objc"))
1389 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1390 if (! strcmp (argv[i], "-lang-objc++"))
1391 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1392 if (! strcmp (argv[i], "-lang-asm"))
1394 if (! strcmp (argv[i], "-lint"))
1399 cplusplus = 1, cplusplus_comments = 1;
1403 inhibit_warnings = 1;
1407 if (!strcmp (argv[i], "-Wtrigraphs"))
1409 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1411 else if (!strcmp (argv[i], "-Wcomment"))
1413 else if (!strcmp (argv[i], "-Wno-comment"))
1415 else if (!strcmp (argv[i], "-Wcomments"))
1417 else if (!strcmp (argv[i], "-Wno-comments"))
1419 else if (!strcmp (argv[i], "-Wtraditional"))
1421 else if (!strcmp (argv[i], "-Wno-traditional"))
1423 else if (!strcmp (argv[i], "-Wimport"))
1425 else if (!strcmp (argv[i], "-Wno-import"))
1427 else if (!strcmp (argv[i], "-Werror"))
1428 warnings_are_errors = 1;
1429 else if (!strcmp (argv[i], "-Wno-error"))
1430 warnings_are_errors = 0;
1431 else if (!strcmp (argv[i], "-Wall"))
1439 /* The style of the choices here is a bit mixed.
1440 The chosen scheme is a hybrid of keeping all options in one string
1441 and specifying each option in a separate argument:
1442 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1443 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1444 -M[M][G][D file]. This is awkward to handle in specs, and is not
1446 /* ??? -MG must be specified in addition to one of -M or -MM.
1447 This can be relaxed in the future without breaking anything.
1448 The converse isn't true. */
1450 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1451 if (!strcmp (argv[i], "-MG"))
1453 print_deps_missing_files = 1;
1456 if (!strcmp (argv[i], "-M"))
1458 else if (!strcmp (argv[i], "-MM"))
1460 else if (!strcmp (argv[i], "-MD"))
1462 else if (!strcmp (argv[i], "-MMD"))
1464 /* For -MD and -MMD options, write deps on file named by next arg. */
1465 if (!strcmp (argv[i], "-MD")
1466 || !strcmp (argv[i], "-MMD")) {
1468 fatal ("Filename missing after %s option", argv[i]);
1470 deps_file = argv[i];
1473 /* For -M and -MM, write deps on standard output
1474 and suppress the usual output. */
1475 deps_stream = stdout;
1482 char *p = argv[i] + 2;
1485 /* Arg to -d specifies what parts of macros to dump */
1488 dump_macros = dump_only;
1492 dump_macros = dump_names;
1495 dump_macros = dump_definitions;
1503 if (argv[i][2] == '3')
1508 fprintf (stderr, "GNU CPP version %s", version_string);
1509 #ifdef TARGET_VERSION
1512 fprintf (stderr, "\n");
1517 print_include_names = 1;
1521 if (argv[i][2] != 0)
1522 pend_defs[i] = argv[i] + 2;
1523 else if (i + 1 == argc)
1524 fatal ("Macro name missing after -D option");
1526 i++, pend_defs[i] = argv[i];
1533 if (argv[i][2] != 0)
1535 else if (i + 1 == argc)
1536 fatal ("Assertion missing after -A option");
1540 if (!strcmp (p, "-")) {
1541 /* -A- eliminates all predefined macros and assertions.
1542 Let's include also any that were specified earlier
1543 on the command line. That way we can get rid of any
1544 that were passed automatically in from GCC. */
1546 inhibit_predefs = 1;
1547 for (j = 0; j < i; j++)
1548 pend_defs[j] = pend_assertions[j] = 0;
1550 pend_assertions[i] = p;
1551 pend_assertion_options[i] = "-A";
1556 case 'U': /* JF #undef something */
1557 if (argv[i][2] != 0)
1558 pend_undefs[i] = argv[i] + 2;
1559 else if (i + 1 == argc)
1560 fatal ("Macro name missing after -U option");
1562 pend_undefs[i] = argv[i+1], i++;
1566 put_out_comments = 1;
1569 case 'E': /* -E comes from cc -E; ignore it. */
1573 no_line_directives = 1;
1576 case '$': /* Don't include $ in identifiers. */
1577 dollars_in_ident = 0;
1580 case 'I': /* Add directory to path for includes. */
1582 struct file_name_list *dirtmp;
1584 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1586 /* Don't use any preceding -I directories for #include <...>. */
1587 first_bracket_include = 0;
1590 dirtmp = (struct file_name_list *)
1591 xmalloc (sizeof (struct file_name_list));
1592 dirtmp->next = 0; /* New one goes on the end */
1593 dirtmp->control_macro = 0;
1594 dirtmp->c_system_include_path = 0;
1595 if (argv[i][2] != 0)
1596 dirtmp->fname = argv[i] + 2;
1597 else if (i + 1 == argc)
1598 fatal ("Directory name missing after -I option");
1600 dirtmp->fname = argv[++i];
1601 dirtmp->got_name_map = 0;
1602 append_include_chain (dirtmp, dirtmp);
1608 if (!strcmp (argv[i], "-nostdinc"))
1609 /* -nostdinc causes no default include directories.
1610 You must specify all include-file directories with -I. */
1611 no_standard_includes = 1;
1612 else if (!strcmp (argv[i], "-nostdinc++"))
1613 /* -nostdinc++ causes no default C++-specific include directories. */
1614 no_standard_cplusplus_includes = 1;
1615 else if (!strcmp (argv[i], "-noprecomp"))
1620 /* Sun compiler passes undocumented switch "-undef".
1621 Let's assume it means to inhibit the predefined symbols. */
1622 inhibit_predefs = 1;
1625 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1626 if (in_fname == NULL) {
1629 } else if (out_fname == NULL) {
1632 } /* else fall through into error */
1635 fatal ("Invalid option `%s'", argv[i]);
1640 /* Add dirs from CPATH after dirs from -I. */
1641 /* There seems to be confusion about what CPATH should do,
1642 so for the moment it is not documented. */
1643 /* Some people say that CPATH should replace the standard include dirs,
1644 but that seems pointless: it comes before them, so it overrides them
1646 p = (char *) getenv ("CPATH");
1647 if (p != 0 && ! no_standard_includes)
1650 /* Now that dollars_in_ident is known, initialize is_idchar. */
1651 initialize_char_syntax ();
1653 /* Initialize output buffer */
1655 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1656 outbuf.bufp = outbuf.buf;
1657 outbuf.length = OUTBUF_SIZE;
1659 /* Do partial setup of input buffer for the sake of generating
1660 early #line directives (when -g is in effect). */
1662 fp = &instack[++indepth];
1663 if (in_fname == NULL)
1665 fp->nominal_fname = fp->fname = in_fname;
1668 /* In C++, wchar_t is a distinct basic type, and we can expect
1669 __wchar_t to be defined by cc1plus. */
1671 wchar_type = "__wchar_t";
1673 /* Install __LINE__, etc. Must follow initialize_char_syntax
1674 and option processing. */
1675 initialize_builtins (fp, &outbuf);
1677 /* Do standard #defines and assertions
1678 that identify system and machine type. */
1680 if (!inhibit_predefs) {
1681 char *p = (char *) alloca (strlen (predefs) + 1);
1682 strcpy (p, predefs);
1685 while (*p == ' ' || *p == '\t')
1687 /* Handle -D options. */
1688 if (p[0] == '-' && p[1] == 'D') {
1690 while (*p && *p != ' ' && *p != '\t')
1695 output_line_directive (fp, &outbuf, 0, same_file);
1696 make_definition (q, &outbuf);
1697 while (*p == ' ' || *p == '\t')
1699 } else if (p[0] == '-' && p[1] == 'A') {
1700 /* Handle -A options (assertions). */
1709 past_name = assertion;
1710 /* Locate end of name. */
1711 while (*past_name && *past_name != ' '
1712 && *past_name != '\t' && *past_name != '(')
1714 /* Locate `(' at start of value. */
1716 while (*value && (*value == ' ' || *value == '\t'))
1718 if (*value++ != '(')
1720 while (*value && (*value == ' ' || *value == '\t'))
1723 /* Locate end of value. */
1724 while (*past_value && *past_value != ' '
1725 && *past_value != '\t' && *past_value != ')')
1727 termination = past_value;
1728 while (*termination && (*termination == ' ' || *termination == '\t'))
1730 if (*termination++ != ')')
1732 if (*termination && *termination != ' ' && *termination != '\t')
1734 /* Temporarily null-terminate the value. */
1735 save_char = *termination;
1736 *termination = '\0';
1737 /* Install the assertion. */
1738 make_assertion ("-A", assertion);
1739 *termination = (char) save_char;
1741 while (*p == ' ' || *p == '\t')
1749 /* Now handle the command line options. */
1751 /* Do -U's, -D's and -A's in the order they were seen. */
1752 for (i = 1; i < argc; i++) {
1753 if (pend_undefs[i]) {
1755 output_line_directive (fp, &outbuf, 0, same_file);
1756 make_undef (pend_undefs[i], &outbuf);
1760 output_line_directive (fp, &outbuf, 0, same_file);
1761 make_definition (pend_defs[i], &outbuf);
1763 if (pend_assertions[i])
1764 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1767 done_initializing = 1;
1769 { /* read the appropriate environment variable and if it exists
1770 replace include_defaults with the listed path. */
1772 switch ((objc << 1) + cplusplus)
1775 epath = getenv ("C_INCLUDE_PATH");
1778 epath = getenv ("CPLUS_INCLUDE_PATH");
1781 epath = getenv ("OBJC_INCLUDE_PATH");
1784 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1787 /* If the environment var for this language is set,
1788 add to the default list of include directories. */
1790 char *nstore = (char *) alloca (strlen (epath) + 2);
1792 char *startp, *endp;
1794 for (num_dirs = 1, startp = epath; *startp; startp++)
1795 if (*startp == PATH_SEPARATOR)
1798 = (struct default_include *) xmalloc ((num_dirs
1799 * sizeof (struct default_include))
1800 + sizeof (include_defaults_array));
1801 startp = endp = epath;
1804 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1805 if ((*endp == PATH_SEPARATOR
1806 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1808 && (endp-startp != 1 || !isalpha (*startp))
1813 strncpy (nstore, startp, endp-startp);
1815 strcpy (nstore, ".");
1817 nstore[endp-startp] = '\0';
1819 include_defaults[num_dirs].fname = savestring (nstore);
1820 include_defaults[num_dirs].cplusplus = cplusplus;
1821 include_defaults[num_dirs].cxx_aware = 1;
1825 endp = startp = endp + 1;
1829 /* Put the usual defaults back in at the end. */
1830 bcopy ((char *) include_defaults_array,
1831 (char *) &include_defaults[num_dirs],
1832 sizeof (include_defaults_array));
1836 append_include_chain (before_system, last_before_system);
1837 first_system_include = before_system;
1839 /* Unless -fnostdinc,
1840 tack on the standard include file dirs to the specified list */
1841 if (!no_standard_includes) {
1842 struct default_include *p = include_defaults;
1843 char *specd_prefix = include_prefix;
1844 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1845 int default_len = 0;
1846 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1847 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1848 default_len = strlen (default_prefix) - 7;
1849 default_prefix[default_len] = 0;
1851 /* Search "translated" versions of GNU directories.
1852 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1853 if (specd_prefix != 0 && default_len != 0)
1854 for (p = include_defaults; p->fname; p++) {
1855 /* Some standard dirs are only for C++. */
1856 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1857 /* Does this dir start with the prefix? */
1858 if (!strncmp (p->fname, default_prefix, default_len)) {
1859 /* Yes; change prefix and add to search list. */
1860 struct file_name_list *new
1861 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1862 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
1863 char *str = (char *) xmalloc (this_len + 1);
1864 strcpy (str, specd_prefix);
1865 strcat (str, p->fname + default_len);
1867 new->control_macro = 0;
1868 new->c_system_include_path = !p->cxx_aware;
1869 new->got_name_map = 0;
1870 append_include_chain (new, new);
1871 if (first_system_include == 0)
1872 first_system_include = new;
1876 /* Search ordinary names for GNU include directories. */
1877 for (p = include_defaults; p->fname; p++) {
1878 /* Some standard dirs are only for C++. */
1879 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1880 struct file_name_list *new
1881 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
1882 new->control_macro = 0;
1883 new->c_system_include_path = !p->cxx_aware;
1884 new->fname = p->fname;
1885 new->got_name_map = 0;
1886 append_include_chain (new, new);
1887 if (first_system_include == 0)
1888 first_system_include = new;
1893 /* Tack the after_include chain at the end of the include chain. */
1894 append_include_chain (after_include, last_after_include);
1895 if (first_system_include == 0)
1896 first_system_include = after_include;
1898 /* With -v, print the list of dirs to search. */
1900 struct file_name_list *p;
1901 fprintf (stderr, "#include \"...\" search starts here:\n");
1902 for (p = include; p; p = p->next) {
1903 if (p == first_bracket_include)
1904 fprintf (stderr, "#include <...> search starts here:\n");
1905 fprintf (stderr, " %s\n", p->fname);
1907 fprintf (stderr, "End of search list.\n");
1910 /* Scan the -imacros files before the main input.
1911 Much like #including them, but with no_output set
1912 so that only their macro definitions matter. */
1914 no_output++; no_record_file++;
1915 for (i = 1; i < argc; i++)
1916 if (pend_files[i]) {
1917 int fd = open (pend_files[i], O_RDONLY, 0666);
1919 perror_with_name (pend_files[i]);
1920 return FAILURE_EXIT_CODE;
1922 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
1924 no_output--; no_record_file--;
1926 /* Copy the entire contents of the main input file into
1927 the stacked input buffer previously allocated for it. */
1929 /* JF check for stdin */
1930 if (in_fname == NULL || *in_fname == 0) {
1933 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
1936 /* -MG doesn't select the form of output and must be specified with one of
1937 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
1938 inhibit compilation. */
1939 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
1940 fatal ("-MG must be specified with one of -M or -MM");
1942 /* Either of two environment variables can specify output of deps.
1943 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1944 where OUTPUT_FILE is the file to write deps info to
1945 and DEPS_TARGET is the target to mention in the deps. */
1948 && (getenv ("SUNPRO_DEPENDENCIES") != 0
1949 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
1950 char *spec = getenv ("DEPENDENCIES_OUTPUT");
1955 spec = getenv ("SUNPRO_DEPENDENCIES");
1962 /* Find the space before the DEPS_TARGET, if there is one. */
1963 /* This should use index. (mrs) */
1964 while (*s != 0 && *s != ' ') s++;
1966 deps_target = s + 1;
1967 output_file = (char *) xmalloc (s - spec + 1);
1968 bcopy (spec, output_file, s - spec);
1969 output_file[s - spec] = 0;
1976 deps_file = output_file;
1980 /* For -M, print the expected object file name
1981 as the target of this Make-rule. */
1983 deps_allocated_size = 200;
1984 deps_buffer = (char *) xmalloc (deps_allocated_size);
1990 deps_output (deps_target, ':');
1991 } else if (*in_fname == 0) {
1992 deps_output ("-", ':');
1997 /* Discard all directory prefixes from filename. */
1998 if ((q = rindex (in_fname, '/')) != NULL
1999 #ifdef DIR_SEPARATOR
2000 && (q = rindex (in_fname, DIR_SEPARATOR)) != NULL
2007 /* Copy remainder to mungable area. */
2008 p = (char *) alloca (strlen(q) + 8);
2011 /* Output P, but remove known suffixes. */
2015 && p[len - 2] == '.'
2016 && index("cCsSm", p[len - 1]))
2019 && p[len - 3] == '.'
2020 && p[len - 2] == 'c'
2021 && p[len - 1] == 'c')
2024 && p[len - 4] == '.'
2025 && p[len - 3] == 'c'
2026 && p[len - 2] == 'x'
2027 && p[len - 1] == 'x')
2030 && p[len - 4] == '.'
2031 && p[len - 3] == 'c'
2032 && p[len - 2] == 'p'
2033 && p[len - 1] == 'p')
2036 /* Supply our own suffix. */
2043 deps_output (p, ':');
2044 deps_output (in_fname, ' ');
2048 file_size_and_mode (f, &st_mode, &st_size);
2049 fp->nominal_fname = fp->fname = in_fname;
2051 fp->system_header_p = 0;
2052 /* JF all this is mine about reading pipes and ttys */
2053 if (! S_ISREG (st_mode)) {
2054 /* Read input from a file that is not a normal disk file.
2055 We cannot preallocate a buffer with the correct size,
2056 so we must read in the file a piece at the time and make it bigger. */
2063 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2065 cnt = safe_read (f, fp->buf + size, bsize - size);
2066 if (cnt < 0) goto perror; /* error! */
2068 if (size != bsize) break; /* End of file */
2070 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2074 /* Read a file whose size we can determine in advance.
2075 For the sake of VMS, st_size is just an upper bound. */
2076 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2077 fp->length = safe_read (f, fp->buf, st_size);
2078 if (fp->length < 0) goto perror;
2081 fp->if_stack = if_stack;
2083 /* Make sure data ends with a newline. And put a null after it. */
2085 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2086 /* Backslash-newline at end is not good enough. */
2087 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2088 fp->buf[fp->length++] = '\n';
2089 missing_newline = 1;
2091 fp->buf[fp->length] = '\0';
2093 /* Unless inhibited, convert trigraphs in the input. */
2098 /* Now that we know the input file is valid, open the output. */
2100 if (!out_fname || !strcmp (out_fname, ""))
2101 out_fname = "stdout";
2102 else if (! freopen (out_fname, "w", stdout))
2103 pfatal_with_name (out_fname);
2105 output_line_directive (fp, &outbuf, 0, same_file);
2107 /* Scan the -include files before the main input. */
2110 for (i = 1; i < argc; i++)
2111 if (pend_includes[i]) {
2112 int fd = open (pend_includes[i], O_RDONLY, 0666);
2114 perror_with_name (pend_includes[i]);
2115 return FAILURE_EXIT_CODE;
2117 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2121 /* Scan the input, processing macros and directives. */
2123 rescan (&outbuf, 0);
2125 if (missing_newline)
2128 if (pedantic && missing_newline)
2129 pedwarn ("file does not end in newline");
2131 /* Now we have processed the entire input
2132 Write whichever kind of output has been requested. */
2134 if (dump_macros == dump_only)
2136 else if (! inhibit_output) {
2141 /* Don't actually write the deps file if compilation has failed. */
2143 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2144 pfatal_with_name (deps_file);
2145 fputs (deps_buffer, deps_stream);
2146 putc ('\n', deps_stream);
2148 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2149 fatal ("I/O error on output");
2154 if (pcp_outfile && pcp_outfile != stdout
2155 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2156 fatal ("I/O error on `-pcp' output");
2158 if (ferror (stdout) || fclose (stdout) != 0)
2159 fatal ("I/O error on output");
2162 exit (FAILURE_EXIT_CODE);
2163 exit (SUCCESS_EXIT_CODE);
2166 pfatal_with_name (in_fname);
2170 /* Given a colon-separated list of file names PATH,
2171 add all the names to the search path for include files. */
2185 struct file_name_list *dirtmp;
2187 /* Find the end of this name. */
2188 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2190 /* An empty name in the path stands for the current directory. */
2191 name = (char *) xmalloc (2);
2195 /* Otherwise use the directory that is named. */
2196 name = (char *) xmalloc (q - p + 1);
2197 bcopy (p, name, q - p);
2201 dirtmp = (struct file_name_list *)
2202 xmalloc (sizeof (struct file_name_list));
2203 dirtmp->next = 0; /* New one goes on the end */
2204 dirtmp->control_macro = 0;
2205 dirtmp->c_system_include_path = 0;
2206 dirtmp->fname = name;
2207 dirtmp->got_name_map = 0;
2208 append_include_chain (dirtmp, dirtmp);
2210 /* Advance past this name. */
2214 /* Skip the colon. */
2219 /* Return the address of the first character in S that equals C.
2220 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2221 Return 0 if there is no such character. Assume that C itself is not '\0'.
2222 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2223 but unfortunately memchr isn't autoconfigured yet. */
2232 char *q = index (s, c);
2234 return (U_CHAR *) q;
2246 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2247 before main CCCP processing. Name `pcp' is also in honor of the
2248 drugs the trigraph designers must have been on.
2250 Using an extra pass through the buffer takes a little extra time,
2251 but is infinitely less hairy than trying to handle trigraphs inside
2252 strings, etc. everywhere, and also makes sure that trigraphs are
2253 only translated in the top level of processing. */
2259 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2262 fptr = bptr = sptr = buf->buf;
2263 lptr = fptr + buf->length;
2264 while ((sptr = (U_CHAR *) index0 (sptr, '?', lptr - sptr)) != NULL) {
2301 len = sptr - fptr - 2;
2303 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2304 C, this will be memmove (). */
2305 if (bptr != fptr && len > 0)
2306 bcopy ((char *) fptr, (char *) bptr, len);
2312 len = buf->length - (fptr - buf->buf);
2313 if (bptr != fptr && len > 0)
2314 bcopy ((char *) fptr, (char *) bptr, len);
2315 buf->length -= fptr - bptr;
2316 buf->buf[buf->length] = '\0';
2317 if (warn_trigraphs && fptr != bptr)
2318 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2321 /* Move all backslash-newline pairs out of embarrassing places.
2322 Exchange all such pairs following BP
2323 with any potentially-embarrassing characters that follow them.
2324 Potentially-embarrassing characters are / and *
2325 (because a backslash-newline inside a comment delimiter
2326 would cause it not to be recognized). */
2332 register U_CHAR *p = bp;
2334 /* First count the backslash-newline pairs here. */
2336 while (p[0] == '\\' && p[1] == '\n')
2339 /* What follows the backslash-newlines is not embarrassing. */
2341 if (*p != '/' && *p != '*')
2344 /* Copy all potentially embarrassing characters
2345 that follow the backslash-newline pairs
2346 down to where the pairs originally started. */
2348 while (*p == '*' || *p == '/')
2351 /* Now write the same number of pairs after the embarrassing chars. */
2358 /* Like newline_fix but for use within a directive-name.
2359 Move any backslash-newlines up past any following symbol constituents. */
2362 name_newline_fix (bp)
2365 register U_CHAR *p = bp;
2367 /* First count the backslash-newline pairs here. */
2368 while (p[0] == '\\' && p[1] == '\n')
2371 /* What follows the backslash-newlines is not embarrassing. */
2376 /* Copy all potentially embarrassing characters
2377 that follow the backslash-newline pairs
2378 down to where the pairs originally started. */
2380 while (is_idchar[*p])
2383 /* Now write the same number of pairs after the embarrassing chars. */
2390 /* Look for lint commands in comments.
2392 When we come in here, ibp points into a comment. Limit is as one expects.
2393 scan within the comment -- it should start, after lwsp, with a lint command.
2394 If so that command is returned as a (constant) string.
2396 Upon return, any arg will be pointed to with argstart and will be
2397 arglen long. Note that we don't parse that arg since it will just
2398 be printed out again.
2402 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2403 register U_CHAR *ibp;
2404 register U_CHAR *limit;
2405 U_CHAR **argstart; /* point to command arg */
2406 int *arglen, *cmdlen; /* how long they are */
2409 register U_CHAR *numptr; /* temp for arg parsing */
2413 SKIP_WHITE_SPACE (ibp);
2415 if (ibp >= limit) return NULL;
2417 linsize = limit - ibp;
2419 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2420 if ((linsize >= 10) && !strncmp (ibp, "NOTREACHED", 10)) {
2422 return "NOTREACHED";
2424 if ((linsize >= 8) && !strncmp (ibp, "ARGSUSED", 8)) {
2428 if ((linsize >= 11) && !strncmp (ibp, "LINTLIBRARY", 11)) {
2430 return "LINTLIBRARY";
2432 if ((linsize >= 7) && !strncmp (ibp, "VARARGS", 7)) {
2434 ibp += 7; linsize -= 7;
2435 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2437 /* OK, read a number */
2438 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2440 *arglen = numptr - *argstart;
2447 * The main loop of the program.
2449 * Read characters from the input stack, transferring them to the
2452 * Macros are expanded and push levels on the input stack.
2453 * At the end of such a level it is popped off and we keep reading.
2454 * At the end of any other kind of level, we return.
2455 * #-directives are handled, except within macros.
2457 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2458 * and insert them when appropriate. This is set while scanning macro
2459 * arguments before substitution. It is zero when scanning for final output.
2460 * There are three types of Newline markers:
2461 * * Newline - follows a macro name that was not expanded
2462 * because it appeared inside an expansion of the same macro.
2463 * This marker prevents future expansion of that identifier.
2464 * When the input is rescanned into the final output, these are deleted.
2465 * These are also deleted by ## concatenation.
2466 * * Newline Space (or Newline and any other whitespace character)
2467 * stands for a place that tokens must be separated or whitespace
2468 * is otherwise desirable, but where the ANSI standard specifies there
2469 * is no whitespace. This marker turns into a Space (or whichever other
2470 * whitespace char appears in the marker) in the final output,
2471 * but it turns into nothing in an argument that is stringified with #.
2472 * Such stringified arguments are the only place where the ANSI standard
2473 * specifies with precision that whitespace may not appear.
2475 * During this function, IP->bufp is kept cached in IBP for speed of access.
2476 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2477 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2478 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2479 * explicitly, and before RECACHE, since RECACHE uses OBP.
2483 rescan (op, output_marks)
2487 /* Character being scanned in main loop. */
2490 /* Length of pending accumulated identifier. */
2491 register int ident_length = 0;
2493 /* Hash code of pending accumulated identifier. */
2494 register int hash = 0;
2496 /* Current input level (&instack[indepth]). */
2499 /* Pointer for scanning input. */
2500 register U_CHAR *ibp;
2502 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2503 register U_CHAR *limit;
2505 /* Pointer for storing output. */
2506 register U_CHAR *obp;
2508 /* REDO_CHAR is nonzero if we are processing an identifier
2509 after backing up over the terminating character.
2510 Sometimes we process an identifier without backing up over
2511 the terminating character, if the terminating character
2512 is not special. Backing up is done so that the terminating character
2513 will be dispatched on again once the identifier is dealt with. */
2516 /* 1 if within an identifier inside of which a concatenation
2517 marker (Newline -) has been seen. */
2518 int concatenated = 0;
2520 /* While scanning a comment or a string constant,
2521 this records the line it started on, for error messages. */
2524 /* Record position of last `real' newline. */
2525 U_CHAR *beg_of_line;
2527 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2530 do { ip->macro->type = T_MACRO; \
2531 if (ip->free_ptr) free (ip->free_ptr); \
2532 --indepth; } while (0)
2534 /* Reload `rescan's local variables that describe the current
2535 level of the input stack. */
2538 do { ip = &instack[indepth]; \
2540 limit = ip->buf + ip->length; \
2542 check_expand (op, limit - ibp); \
2544 obp = op->bufp; } while (0)
2546 if (no_output && instack[indepth].fname != 0)
2547 skip_if_group (&instack[indepth], 1, NULL);
2554 /* Our caller must always put a null after the end of
2555 the input at each input stack level. */
2565 if (*ibp == '\n' && !ip->macro) {
2566 /* At the top level, always merge lines ending with backslash-newline,
2567 even in middle of identifier. But do not merge lines in a macro,
2568 since backslash might be followed by a newline-space marker. */
2571 --obp; /* remove backslash from obuf */
2574 /* If ANSI, backslash is just another character outside a string. */
2577 /* Otherwise, backslash suppresses specialness of following char,
2578 so copy it here to prevent the switch from seeing it.
2579 But first get any pending identifier processed. */
2580 if (ident_length > 0)
2587 if (ident_length || ip->macro || traditional)
2589 while (*ibp == '\\' && ibp[1] == '\n') {
2595 /* Treat this %: digraph as if it were #. */
2599 if (assertions_flag) {
2600 /* Copy #foo (bar lose) without macro expansion. */
2601 obp[-1] = '#'; /* In case it was '%'. */
2602 SKIP_WHITE_SPACE (ibp);
2603 while (is_idchar[*ibp])
2605 SKIP_WHITE_SPACE (ibp);
2608 skip_paren_group (ip);
2609 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2610 obp += ip->bufp - ibp;
2615 /* If this is expanding a macro definition, don't recognize
2616 preprocessing directives. */
2619 /* If this is expand_into_temp_buffer,
2620 don't recognize them either. Warn about them
2621 only after an actual newline at this level,
2622 not at the beginning of the input level. */
2624 if (ip->buf != beg_of_line)
2625 warning ("preprocessing directive not recognized within macro arg");
2632 /* # keyword: a # must be first nonblank char on the line */
2633 if (beg_of_line == 0)
2638 /* Scan from start of line, skipping whitespace, comments
2639 and backslash-newlines, and see if we reach this #.
2640 If not, this # is not special. */
2642 /* If -traditional, require # to be at beginning of line. */
2645 if (is_hor_space[*bp])
2647 else if (*bp == '\\' && bp[1] == '\n')
2649 else if (*bp == '/' && bp[1] == '*') {
2651 while (!(*bp == '*' && bp[1] == '/'))
2655 /* There is no point in trying to deal with C++ // comments here,
2656 because if there is one, then this # must be part of the
2657 comment and we would never reach here. */
2663 while (bp[1] == '\\' && bp[2] == '\n')
2667 /* %: appears at start of line; skip past the ':' too. */
2676 /* This # can start a directive. */
2678 --obp; /* Don't copy the '#' */
2682 if (! handle_directive (ip, op)) {
2686 /* Not a known directive: treat it as ordinary text.
2687 IP, OP, IBP, etc. have not been changed. */
2688 if (no_output && instack[indepth].fname) {
2689 /* If not generating expanded output,
2690 what we do with ordinary text is skip it.
2691 Discard everything until next # directive. */
2692 skip_if_group (&instack[indepth], 1, 0);
2697 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2698 /* Don't expand an identifier that could be a macro directive.
2699 (Section 3.8.3 of the ANSI C standard) */
2700 SKIP_WHITE_SPACE (ibp);
2701 if (is_idstart[*ibp])
2704 while (is_idchar[*ibp])
2712 /* A # directive has been successfully processed. */
2713 /* If not generating expanded output, ignore everything until
2714 next # directive. */
2715 if (no_output && instack[indepth].fname)
2716 skip_if_group (&instack[indepth], 1, 0);
2722 case '\"': /* skip quoted string */
2724 /* A single quoted string is treated like a double -- some
2725 programs (e.g., troff) are perverse this way */
2730 start_line = ip->lineno;
2732 /* Skip ahead to a matching quote. */
2736 if (ip->macro != 0) {
2737 /* try harder: this string crosses a macro expansion boundary.
2738 This can happen naturally if -traditional.
2739 Otherwise, only -D can make a macro with an unmatched quote. */
2745 error_with_line (line_for_error (start_line),
2746 "unterminated string or character constant");
2747 error_with_line (multiline_string_line,
2748 "possible real start of unterminated constant");
2749 multiline_string_line = 0;
2758 /* Traditionally, end of line ends a string constant with no error.
2759 So exit the loop and record the new line. */
2765 error_with_line (line_for_error (start_line),
2766 "unterminated character constant");
2769 if (pedantic && multiline_string_line == 0) {
2770 pedwarn_with_line (line_for_error (start_line),
2771 "string constant runs past end of line");
2773 if (multiline_string_line == 0)
2774 multiline_string_line = ip->lineno - 1;
2781 /* Backslash newline is replaced by nothing at all,
2782 but keep the line counts correct. */
2787 /* ANSI stupidly requires that in \\ the second \
2788 is *not* prevented from combining with a newline. */
2789 while (*ibp == '\\' && ibp[1] == '\n') {
2808 if (*ibp == '\\' && ibp[1] == '\n')
2812 && !(cplusplus_comments && *ibp == '/'))
2820 /* C++ style comment... */
2821 start_line = ip->lineno;
2823 --ibp; /* Back over the slash */
2826 /* Comments are equivalent to spaces. */
2827 if (! put_out_comments)
2830 /* must fake up a comment here */
2835 U_CHAR *before_bp = ibp+2;
2837 while (ibp < limit) {
2838 if (ibp[-1] != '\\' && *ibp == '\n') {
2839 if (put_out_comments) {
2840 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2841 obp += ibp - before_bp;
2847 /* Copy the newline into the output buffer, in order to
2848 avoid the pain of a #line every time a multiline comment
2850 if (!put_out_comments)
2861 /* Ordinary C comment. Skip it, optionally copying it to output. */
2863 start_line = ip->lineno;
2865 ++ibp; /* Skip the star. */
2867 /* If this cpp is for lint, we peek inside the comments: */
2871 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2873 if (lintcmd != NULL) {
2875 check_expand (op, cmdlen + arglen + 14);
2877 /* I believe it is always safe to emit this newline: */
2879 bcopy ("#pragma lint ", (char *) obp, 13);
2881 bcopy (lintcmd, (char *) obp, cmdlen);
2886 bcopy (argbp, (char *) obp, arglen);
2890 /* OK, now bring us back to the state we were in before we entered
2891 this branch. We need #line because the #pragma's newline always
2892 messes up the line count. */
2894 output_line_directive (ip, op, 0, same_file);
2895 check_expand (op, limit - ibp + 2);
2901 /* Comments are equivalent to spaces.
2902 Note that we already output the slash; we might not want it.
2903 For -traditional, a comment is equivalent to nothing. */
2904 if (! put_out_comments) {
2914 U_CHAR *before_bp = ibp;
2916 while (ibp < limit) {
2919 if (warn_comments && *ibp == '*')
2920 warning ("`/*' within comment");
2923 if (*ibp == '\\' && ibp[1] == '\n')
2925 if (ibp >= limit || *ibp == '/')
2930 /* Copy the newline into the output buffer, in order to
2931 avoid the pain of a #line every time a multiline comment
2933 if (!put_out_comments)
2941 error_with_line (line_for_error (start_line),
2942 "unterminated comment");
2945 if (put_out_comments) {
2946 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2947 obp += ibp - before_bp;
2954 if (!dollars_in_ident)
2958 case '0': case '1': case '2': case '3': case '4':
2959 case '5': case '6': case '7': case '8': case '9':
2960 /* If digit is not part of identifier, it starts a number,
2961 which means that following letters are not an identifier.
2962 "0x5" does not refer to an identifier "x5".
2963 So copy all alphanumerics that follow without accumulating
2964 as an identifier. Periods also, for sake of "3.e7". */
2966 if (ident_length == 0) {
2968 while (ibp[0] == '\\' && ibp[1] == '\n') {
2973 if (!is_idchar[c] && c != '.') {
2978 /* A sign can be part of a preprocessing number
2979 if it follows an e. */
2980 if (c == 'e' || c == 'E') {
2981 while (ibp[0] == '\\' && ibp[1] == '\n') {
2985 if (*ibp == '+' || *ibp == '-') {
2987 /* But traditional C does not let the token go past the sign. */
2998 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2999 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3000 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3001 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3003 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3004 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3005 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3006 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3010 /* Compute step of hash function, to avoid a proc call on every token */
3011 hash = HASHSTEP (hash, c);
3015 if (ip->fname == 0 && *ibp == '-') {
3016 /* Newline - inhibits expansion of preceding token.
3017 If expanding a macro arg, we keep the newline -.
3018 In final output, it is deleted.
3019 We recognize Newline - in macro bodies and macro args. */
3020 if (! concatenated) {
3025 if (!output_marks) {
3028 /* If expanding a macro arg, keep the newline -. */
3034 /* If reprocessing a macro expansion, newline is a special marker. */
3035 else if (ip->macro != 0) {
3036 /* Newline White is a "funny space" to separate tokens that are
3037 supposed to be separate but without space between.
3038 Here White means any whitespace character.
3039 Newline - marks a recursive macro use that is not
3040 supposed to be expandable. */
3042 if (is_space[*ibp]) {
3043 /* Newline Space does not prevent expansion of preceding token
3044 so expand the preceding token and then come back. */
3045 if (ident_length > 0)
3048 /* If generating final output, newline space makes a space. */
3049 if (!output_marks) {
3051 /* And Newline Newline makes a newline, so count it. */
3052 if (obp[-1] == '\n')
3055 /* If expanding a macro arg, keep the newline space.
3056 If the arg gets stringified, newline space makes nothing. */
3059 } else abort (); /* Newline followed by something random? */
3063 /* If there is a pending identifier, handle it and come back here. */
3064 if (ident_length > 0)
3069 /* Update the line counts and output a #line if necessary. */
3072 if (ip->lineno != op->lineno) {
3074 output_line_directive (ip, op, 1, same_file);
3075 check_expand (op, limit - ibp);
3080 /* Come here either after (1) a null character that is part of the input
3081 or (2) at the end of the input, because there is a null there. */
3084 /* Our input really contains a null character. */
3087 /* At end of a macro-expansion level, pop it and read next level. */
3088 if (ip->macro != 0) {
3091 /* If traditional, and we have an identifier that ends here,
3092 process it now, so we get the right error for recursion. */
3093 if (traditional && ident_length
3094 && ! is_idchar[*instack[indepth - 1].bufp]) {
3103 /* If we don't have a pending identifier,
3104 return at end of input. */
3105 if (ident_length == 0) {
3113 /* If we do have a pending identifier, just consider this null
3114 a special character and arrange to dispatch on it again.
3115 The second time, IDENT_LENGTH will be zero so we will return. */
3121 /* Handle the case of a character such as /, ', " or null
3122 seen following an identifier. Back over it so that
3123 after the identifier is processed the special char
3124 will be dispatched on again. */
3134 if (ident_length > 0) {
3135 register HASHNODE *hp;
3137 /* We have just seen an identifier end. If it's a macro, expand it.
3139 IDENT_LENGTH is the length of the identifier
3140 and HASH is its hash code.
3142 The identifier has already been copied to the output,
3143 so if it is a macro we must remove it.
3145 If REDO_CHAR is 0, the char that terminated the identifier
3146 has been skipped in the output and the input.
3147 OBP-IDENT_LENGTH-1 points to the identifier.
3148 If the identifier is a macro, we must back over the terminator.
3150 If REDO_CHAR is 1, the terminating char has already been
3151 backed over. OBP-IDENT_LENGTH points to the identifier. */
3153 if (!pcp_outfile || pcp_inside_if) {
3155 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3158 if (hp->length == ident_length) {
3159 int obufp_before_macroname;
3160 int op_lineno_before_macroname;
3161 register int i = ident_length;
3162 register U_CHAR *p = hp->name;
3163 register U_CHAR *q = obp - i;
3169 do { /* All this to avoid a strncmp () */
3174 /* We found a use of a macro name.
3175 see if the context shows it is a macro call. */
3177 /* Back up over terminating character if not already done. */
3183 /* Save this as a displacement from the beginning of the output
3184 buffer. We can not save this as a position in the output
3185 buffer, because it may get realloc'ed by RECACHE. */
3186 obufp_before_macroname = (obp - op->buf) - ident_length;
3187 op_lineno_before_macroname = op->lineno;
3189 if (hp->type == T_PCSTRING) {
3190 pcstring_used (hp); /* Mark the definition of this key
3191 as needed, ensuring that it
3193 break; /* Exit loop, since the key cannot have a
3194 definition any longer. */
3197 /* Record whether the macro is disabled. */
3198 disabled = hp->type == T_DISABLED;
3200 /* This looks like a macro ref, but if the macro was disabled,
3201 just copy its name and put in a marker if requested. */
3205 /* This error check caught useful cases such as
3206 #define foo(x,y) bar (x (y,0), y)
3209 error ("recursive use of macro `%s'", hp->name);
3213 check_expand (op, limit - ibp + 2);
3220 /* If macro wants an arglist, verify that a '(' follows.
3221 first skip all whitespace, copying it to the output
3222 after the macro name. Then, if there is no '(',
3223 decide this is not a macro call and leave things that way. */
3224 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3225 && hp->value.defn->nargs >= 0)
3227 U_CHAR *old_ibp = ibp;
3228 U_CHAR *old_obp = obp;
3229 int old_iln = ip->lineno;
3230 int old_oln = op->lineno;
3233 /* Scan forward over whitespace, copying it to the output. */
3234 if (ibp == limit && ip->macro != 0) {
3239 old_iln = ip->lineno;
3240 old_oln = op->lineno;
3242 /* A comment: copy it unchanged or discard it. */
3243 else if (*ibp == '/' && ibp[1] == '*') {
3244 if (put_out_comments) {
3247 } else if (! traditional) {
3251 while (ibp + 1 != limit
3252 && !(ibp[0] == '*' && ibp[1] == '/')) {
3253 /* We need not worry about newline-marks,
3254 since they are never found in comments. */
3256 /* Newline in a file. Count it. */
3260 if (put_out_comments)
3266 if (put_out_comments) {
3271 else if (is_space[*ibp]) {
3273 if (ibp[-1] == '\n') {
3274 if (ip->macro == 0) {
3275 /* Newline in a file. Count it. */
3278 } else if (!output_marks) {
3279 /* A newline mark, and we don't want marks
3280 in the output. If it is newline-hyphen,
3281 discard it entirely. Otherwise, it is
3282 newline-whitechar, so keep the whitechar. */
3292 /* A newline mark; copy both chars to the output. */
3300 /* It isn't a macro call.
3301 Put back the space that we just skipped. */
3304 ip->lineno = old_iln;
3305 op->lineno = old_oln;
3306 /* Exit the for loop. */
3311 /* This is now known to be a macro call.
3312 Discard the macro name from the output,
3313 along with any following whitespace just copied,
3314 but preserve newlines if not outputting marks since this
3315 is more likely to do the right thing with line numbers. */
3316 obp = op->buf + obufp_before_macroname;
3318 op->lineno = op_lineno_before_macroname;
3320 int newlines = op->lineno - op_lineno_before_macroname;
3321 while (0 < newlines--)
3325 /* Prevent accidental token-pasting with a character
3326 before the macro call. */
3327 if (!traditional && obp != op->buf) {
3329 case '!': case '%': case '&': case '*':
3330 case '+': case '-': case '/': case ':':
3331 case '<': case '=': case '>': case '^':
3333 /* If we are expanding a macro arg, make a newline marker
3334 to separate the tokens. If we are making real output,
3335 a plain space will do. */
3342 /* Expand the macro, reading arguments as needed,
3343 and push the expansion on the input stack. */
3346 macroexpand (hp, op);
3348 /* Reexamine input stack, since macroexpand has pushed
3349 a new level on it. */
3356 } /* End hash-table-search loop */
3358 ident_length = hash = 0; /* Stop collecting identifier */
3361 } /* End if (ident_length > 0) */
3363 } /* End per-char loop */
3365 /* Come here to return -- but first give an error message
3366 if there was an unterminated successful conditional. */
3368 if (if_stack != ip->if_stack)
3370 char *str = "unknown";
3372 switch (if_stack->type)
3391 error_with_line (line_for_error (if_stack->lineno),
3392 "unterminated `#%s' conditional", str);
3394 if_stack = ip->if_stack;
3398 * Rescan a string into a temporary buffer and return the result
3399 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3401 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3402 * and insert such markers when appropriate. See `rescan' for details.
3403 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3404 * before substitution; it is 0 for other uses.
3407 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3408 U_CHAR *buf, *limit;
3409 int output_marks, assertions;
3411 register FILE_BUF *ip;
3413 int length = limit - buf;
3415 int odepth = indepth;
3416 int save_assertions_flag = assertions_flag;
3418 assertions_flag = assertions;
3423 /* Set up the input on the input stack. */
3425 buf1 = (U_CHAR *) alloca (length + 1);
3427 register U_CHAR *p1 = buf;
3428 register U_CHAR *p2 = buf1;
3435 /* Set up to receive the output. */
3437 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3438 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3443 CHECK_DEPTH ({return obuf;});
3447 ip = &instack[indepth];
3449 ip->nominal_fname = 0;
3450 ip->system_header_p = 0;
3453 ip->length = length;
3454 ip->buf = ip->bufp = buf1;
3455 ip->if_stack = if_stack;
3457 ip->lineno = obuf.lineno = 1;
3459 /* Scan the input, create the output. */
3460 rescan (&obuf, output_marks);
3462 /* Pop input stack to original state. */
3465 if (indepth != odepth)
3468 /* Record the output. */
3469 obuf.length = obuf.bufp - obuf.buf;
3471 assertions_flag = save_assertions_flag;
3476 * Process a # directive. Expects IP->bufp to point after the '#', as in
3477 * `#define foo bar'. Passes to the directive handler
3478 * (do_define, do_include, etc.): the addresses of the 1st and
3479 * last chars of the directive (starting immediately after the #
3480 * keyword), plus op and the keyword table pointer. If the directive
3481 * contains comments it is copied into a temporary buffer sans comments
3482 * and the temporary buffer is passed to the directive handler instead.
3483 * Likewise for backslash-newlines.
3485 * Returns nonzero if this was a known # directive.
3486 * Otherwise, returns zero, without advancing the input pointer.
3490 handle_directive (ip, op)
3493 register U_CHAR *bp, *cp;
3494 register struct directive *kt;
3495 register int ident_length;
3498 /* Nonzero means we must copy the entire directive
3499 to get rid of comments or backslash-newlines. */
3500 int copy_directive = 0;
3502 U_CHAR *ident, *after_ident;
3506 /* Record where the directive started. do_xifdef needs this. */
3507 directive_start = bp - 1;
3509 /* Skip whitespace and \-newline. */
3511 if (is_hor_space[*bp]) {
3512 if (*bp != ' ' && *bp != '\t' && pedantic)
3513 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3515 } else if (*bp == '/' && (bp[1] == '*'
3516 || (cplusplus_comments && bp[1] == '/'))) {
3518 skip_to_end_of_comment (ip, &ip->lineno, 0);
3520 } else if (*bp == '\\' && bp[1] == '\n') {
3521 bp += 2; ip->lineno++;
3525 /* Now find end of directive name.
3526 If we encounter a backslash-newline, exchange it with any following
3527 symbol-constituents so that we end up with a contiguous name. */
3534 if (*cp == '\\' && cp[1] == '\n')
3535 name_newline_fix (cp);
3541 ident_length = cp - bp;
3545 /* A line of just `#' becomes blank. */
3547 if (ident_length == 0 && *after_ident == '\n') {
3548 ip->bufp = after_ident;
3552 if (ident_length == 0 || !is_idstart[*ident]) {
3554 while (is_idchar[*p]) {
3555 if (*p < '0' || *p > '9')
3559 /* Handle # followed by a line number. */
3560 if (p != ident && !is_idchar[*p]) {
3561 static struct directive line_directive_table[] = {
3562 { 4, do_line, "line", T_LINE},
3565 pedwarn ("`#' followed by integer");
3566 after_ident = ident;
3567 kt = line_directive_table;
3571 /* Avoid error for `###' and similar cases unless -pedantic. */
3573 while (*p == '#' || is_hor_space[*p]) p++;
3575 if (pedantic && !lang_asm)
3576 warning ("invalid preprocessing directive");
3582 error ("invalid preprocessing directive name");
3588 * Decode the keyword and call the appropriate expansion
3589 * routine, after moving the input pointer up to the next line.
3591 for (kt = directive_table; kt->length > 0; kt++) {
3592 if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) {
3593 register U_CHAR *buf;
3594 register U_CHAR *limit;
3597 int *already_output;
3599 /* Nonzero means do not delete comments within the directive.
3600 #define needs this when -traditional. */
3605 limit = ip->buf + ip->length;
3608 keep_comments = traditional && kt->traditional_comments;
3609 /* #import is defined only in Objective C, or when on the NeXT. */
3610 if (kt->type == T_IMPORT && !(objc || lookup ("__NeXT__", -1, -1)))
3613 /* Find the end of this directive (first newline not backslashed
3614 and not in a string or comment).
3615 Set COPY_DIRECTIVE if the directive must be copied
3616 (it contains a backslash-newline or a comment). */
3618 buf = bp = after_ident;
3619 while (bp < limit) {
3620 register U_CHAR c = *bp++;
3628 } else if (traditional)
3635 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3636 /* Don't bother calling the directive if we already got an error
3637 message due to unterminated string. Skip everything and pretend
3638 we called the directive. */
3641 /* Traditional preprocessing permits unterminated strings. */
3650 /* <...> is special for #include. */
3652 if (!kt->angle_brackets)
3654 while (bp < limit && *bp != '>' && *bp != '\n') {
3655 if (*bp == '\\' && bp[1] == '\n') {
3665 if (*bp == '\\' && bp[1] == '\n')
3668 || (cplusplus_comments && *bp == '/')) {
3669 U_CHAR *obp = bp - 1;
3671 skip_to_end_of_comment (ip, &ip->lineno, 0);
3673 /* No need to copy the directive because of a comment at the end;
3674 just don't include the comment in the directive. */
3675 if (bp == limit || *bp == '\n') {
3679 /* Don't remove the comments if -traditional. */
3680 if (! keep_comments)
3689 pedwarn ("%s in preprocessing directive", char_name[c]);
3693 --bp; /* Point to the newline */
3701 resume_p = ip->bufp;
3702 /* BP is the end of the directive.
3703 RESUME_P is the next interesting data after the directive.
3704 A comment may come between. */
3706 /* If a directive should be copied through, and -E was given,
3707 pass it through before removing comments. */
3708 if (!no_output && kt->pass_thru && put_out_comments) {
3711 /* Output directive name. */
3712 check_expand (op, kt->length + 2);
3713 /* Make sure # is at the start of a line */
3714 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3719 bcopy (kt->name, op->bufp, kt->length);
3720 op->bufp += kt->length;
3722 /* Output arguments. */
3724 check_expand (op, len);
3725 bcopy (buf, (char *) op->bufp, len);
3727 /* Take account of any (escaped) newlines just output. */
3729 if (buf[len] == '\n')
3732 already_output = &junk;
3733 } /* Don't we need a newline or #line? */
3735 if (copy_directive) {
3736 register U_CHAR *xp = buf;
3737 /* Need to copy entire directive into temp buffer before dispatching */
3739 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3743 /* Copy to the new buffer, deleting comments
3744 and backslash-newlines (and whitespace surrounding the latter). */
3747 register U_CHAR c = *xp++;
3752 abort (); /* A bare newline should never part of the line. */
3755 /* <...> is special for #include. */
3757 if (!kt->angle_brackets)
3759 while (xp < bp && c != '>') {
3761 if (c == '\\' && xp < bp && *xp == '\n')
3772 if (cp != buf && is_space[cp[-1]]) {
3773 while (cp != buf && is_space[cp[-1]]) cp--;
3775 SKIP_WHITE_SPACE (xp);
3776 } else if (is_space[*xp]) {
3778 SKIP_WHITE_SPACE (xp);
3780 } else if (traditional && xp < bp) {
3788 register U_CHAR *bp1
3789 = skip_quoted_string (xp - 1, bp, ip->lineno,
3790 NULL_PTR, NULL_PTR, NULL_PTR);
3804 || (cplusplus_comments && *xp == '/')) {
3806 /* If we already copied the directive through,
3807 already_output != 0 prevents outputting comment now. */
3808 skip_to_end_of_comment (ip, already_output, 0);
3810 while (xp != ip->bufp)
3812 /* Delete or replace the slash. */
3813 else if (traditional)
3822 /* Null-terminate the copy. */
3828 ip->bufp = resume_p;
3830 /* Some directives should be written out for cc1 to process,
3831 just as if they were not defined. And sometimes we're copying
3832 definitions through. */
3834 if (!no_output && already_output == 0
3836 || (kt->type == T_DEFINE
3837 && (dump_macros == dump_names
3838 || dump_macros == dump_definitions)))) {
3841 /* Output directive name. */
3842 check_expand (op, kt->length + 1);
3844 bcopy (kt->name, (char *) op->bufp, kt->length);
3845 op->bufp += kt->length;
3847 if (kt->pass_thru || dump_macros == dump_definitions) {
3848 /* Output arguments. */
3850 check_expand (op, len);
3851 bcopy (buf, (char *) op->bufp, len);
3853 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3856 SKIP_WHITE_SPACE (xp);
3858 while (is_idchar[*xp]) xp++;
3860 check_expand (op, len + 1);
3862 bcopy (yp, op->bufp, len);
3865 } /* Don't we need a newline or #line? */
3867 /* Call the appropriate directive handler. buf now points to
3868 either the appropriate place in the input buffer, or to
3869 the temp buffer if it was necessary to make one. cp
3870 points to the first char after the contents of the (possibly
3871 copied) directive, in either case. */
3872 (*kt->func) (buf, cp, op, kt);
3873 check_expand (op, ip->length - (ip->bufp - ip->buf));
3879 /* It is deliberate that we don't warn about undefined directives.
3880 That is the responsibility of cc1. */
3887 static struct tm *timebuf;
3889 time_t t = time ((time_t *)0);
3890 timebuf = localtime (&t);
3895 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
3896 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3900 * expand things like __FILE__. Place the expansion into the output
3901 * buffer *without* rescanning.
3905 special_symbol (hp, op)
3912 FILE_BUF *ip = NULL;
3915 int paren = 0; /* For special `defined' keyword */
3917 if (pcp_outfile && pcp_inside_if
3918 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
3919 error ("Predefined macro `%s' used inside `#if' during precompilation",
3922 for (i = indepth; i >= 0; i--)
3923 if (instack[i].fname != NULL) {
3928 error ("cccp error: not in any file?!");
3929 return; /* the show must go on */
3937 if (hp->type == T_FILE)
3938 string = ip->nominal_fname;
3940 string = instack[0].nominal_fname;
3944 buf = (char *) alloca (3 + 4 * strlen (string));
3945 quote_string (buf, string);
3953 case T_INCLUDE_LEVEL:
3955 for (i = indepth; i >= 0; i--)
3956 if (instack[i].fname != NULL)
3959 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
3960 sprintf (buf, "%d", true_indepth - 1);
3964 buf = (char *) alloca (3 + strlen (version_string));
3965 sprintf (buf, "\"%s\"", version_string);
3968 #ifndef NO_BUILTIN_SIZE_TYPE
3974 #ifndef NO_BUILTIN_PTRDIFF_TYPE
3975 case T_PTRDIFF_TYPE:
3984 case T_USER_LABEL_PREFIX_TYPE:
3985 buf = USER_LABEL_PREFIX;
3988 case T_REGISTER_PREFIX_TYPE:
3989 buf = REGISTER_PREFIX;
3993 buf = hp->value.cpval;
3994 if (pcp_inside_if && pcp_outfile)
3995 /* Output a precondition for this macro use */
3996 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4000 buf = (char *) alloca (10);
4001 sprintf (buf, "%d", ip->lineno);
4006 buf = (char *) alloca (20);
4007 timebuf = timestamp ();
4008 if (hp->type == T_DATE)
4009 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4010 timebuf->tm_mday, timebuf->tm_year + 1900);
4012 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4016 case T_SPEC_DEFINED:
4017 buf = " 0 "; /* Assume symbol is not defined */
4018 ip = &instack[indepth];
4019 SKIP_WHITE_SPACE (ip->bufp);
4020 if (*ip->bufp == '(') {
4022 ip->bufp++; /* Skip over the paren */
4023 SKIP_WHITE_SPACE (ip->bufp);
4026 if (!is_idstart[*ip->bufp])
4028 if (hp = lookup (ip->bufp, -1, -1)) {
4029 if (pcp_outfile && pcp_inside_if
4030 && (hp->type == T_CONST
4031 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4032 /* Output a precondition for this macro use. */
4033 fprintf (pcp_outfile, "#define %s\n", hp->name);
4037 if (pcp_outfile && pcp_inside_if) {
4038 /* Output a precondition for this macro use */
4039 U_CHAR *cp = ip->bufp;
4040 fprintf (pcp_outfile, "#undef ");
4041 while (is_idchar[*cp]) /* Ick! */
4042 fputc (*cp++, pcp_outfile);
4043 putc ('\n', pcp_outfile);
4045 while (is_idchar[*ip->bufp])
4047 SKIP_WHITE_SPACE (ip->bufp);
4049 if (*ip->bufp != ')')
4057 error ("`defined' without an identifier");
4061 error ("cccp error: invalid special hash type"); /* time for gdb */
4065 check_expand (op, len);
4066 bcopy (buf, (char *) op->bufp, len);
4073 /* Routines to handle #directives */
4075 /* Handle #include and #import.
4076 This function expects to see "fname" or <fname> on the input. */
4079 do_include (buf, limit, op, keyword)
4080 U_CHAR *buf, *limit;
4082 struct directive *keyword;
4084 int importing = (keyword->type == T_IMPORT);
4085 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4086 static int import_warning = 0;
4087 char *fname; /* Dynamically allocated fname buffer */
4090 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4092 struct file_name_list *search_start = include; /* Chain of dirs to search */
4093 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4094 struct file_name_list *searchptr = 0;
4097 int f; /* file number */
4099 int retried = 0; /* Have already tried macro
4100 expanding the include line*/
4101 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4106 f= -1; /* JF we iz paranoid! */
4108 if (importing && warn_import && !inhibit_warnings
4109 && !instack[indepth].system_header_p && !import_warning) {
4111 warning ("using `#import' is not recommended");
4112 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4113 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4114 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4115 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4116 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4117 fprintf (stderr, " ... <real contents of file> ...\n");
4118 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4119 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4120 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4121 fprintf (stderr, "when it is equipped with such a conditional.\n");
4127 SKIP_WHITE_SPACE (fbeg);
4128 /* Discard trailing whitespace so we can easily see
4129 if we have parsed all the significant chars we were given. */
4130 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4136 /* Copy the operand text, concatenating the strings. */
4139 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4141 while (fin != limit) {
4142 while (fin != limit && *fin != '\"')
4147 /* If not at the end, there had better be another string. */
4148 /* Skip just horiz space, and don't go past limit. */
4149 while (fin != limit && is_hor_space[*fin]) fin++;
4150 if (fin != limit && *fin == '\"')
4158 /* We have "filename". Figure out directory this source
4159 file is coming from and put it on the front of the list. */
4161 /* If -I- was specified, don't search current dir, only spec'd ones. */
4162 if (ignore_srcdir) break;
4164 for (fp = &instack[indepth]; fp >= instack; fp--)
4169 if ((nam = fp->nominal_fname) != NULL) {
4170 /* Found a named file. Figure out dir of the file,
4171 and put it in front of the search list. */
4172 dsp[0].next = search_start;
4175 ep = rindex (nam, '/');
4176 #ifdef DIR_SEPARATOR
4177 if (ep == NULL) ep = rindex (nam, DIR_SEPARATOR);
4179 char *tmp = rindex (nam, DIR_SEPARATOR);
4180 if (tmp != NULL && tmp > ep) ep = tmp;
4184 ep = rindex (nam, ']');
4185 if (ep == NULL) ep = rindex (nam, '>');
4186 if (ep == NULL) ep = rindex (nam, ':');
4187 if (ep != NULL) ep++;
4191 dsp[0].fname = (char *) alloca (n + 1);
4192 strncpy (dsp[0].fname, nam, n);
4193 dsp[0].fname[n] = '\0';
4194 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4195 max_include_len = n + INCLUDE_LEN_FUDGE;
4197 dsp[0].fname = 0; /* Current directory */
4199 dsp[0].got_name_map = 0;
4208 while (fend != limit && *fend != '>') fend++;
4209 if (*fend == '>' && fend + 1 == limit) {
4211 /* If -I-, start with the first -I dir after the -I-. */
4212 if (first_bracket_include)
4213 search_start = first_bracket_include;
4221 * Support '#include xyz' like VAX-C to allow for easy use of all the
4222 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4223 * code from case '<' is repeated here) and generates a warning.
4224 * (Note: macro expansion of `xyz' takes precedence.)
4226 if (retried && isalpha(*(--fbeg))) {
4228 while (fend != limit && (!isspace(*fend))) fend++;
4229 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4230 if (fend == limit) {
4232 /* If -I-, start with the first -I dir after the -I-. */
4233 if (first_bracket_include)
4234 search_start = first_bracket_include;
4242 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4245 /* Expand buffer and then remove any newline markers.
4246 We can't just tell expand_to_temp_buffer to omit the markers,
4247 since it would put extra spaces in include file names. */
4250 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4252 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4254 while (src != trybuf.bufp) {
4255 switch ((*limit++ = *src++)) {
4264 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4265 NULL_PTR, NULL_PTR, NULL_PTR);
4279 /* For #include_next, skip in the search path
4280 past the dir in which the containing file was found. */
4283 for (fp = &instack[indepth]; fp >= instack; fp--)
4284 if (fp->fname != NULL) {
4285 /* fp->dir is null if the containing file was specified
4286 with an absolute file name. In that case, don't skip anything. */
4288 search_start = fp->dir->next;
4297 error ("empty file name in `#%s'", keyword->name);
4301 /* Allocate this permanently, because it gets stored in the definitions
4303 fname = (char *) xmalloc (max_include_len + flen + 4);
4304 /* + 2 above for slash and terminating null. */
4305 /* + 2 added for '.h' on VMS (to support '#include filename') */
4307 /* If specified file name is absolute, just open it. */
4310 #ifdef DIR_SEPARATOR
4311 || *fbeg == DIR_SEPARATOR
4314 strncpy (fname, fbeg, flen);
4316 if (redundant_include_p (fname))
4319 f = lookup_import (fname, NULL_PTR);
4321 f = open_include_file (fname, NULL_PTR);
4323 return 0; /* Already included this file */
4325 /* Search directory path, trying to open the file.
4326 Copy each filename tried into FNAME. */
4328 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4329 if (searchptr->fname) {
4330 /* The empty string in a search path is ignored.
4331 This makes it possible to turn off entirely
4332 a standard piece of the list. */
4333 if (searchptr->fname[0] == 0)
4335 strcpy (fname, searchptr->fname);
4336 strcat (fname, "/");
4337 fname[strlen (fname) + flen] = 0;
4341 strncat (fname, fbeg, flen);
4343 /* Change this 1/2 Unix 1/2 VMS file specification into a
4344 full VMS file specification */
4345 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4346 /* Fix up the filename */
4347 hack_vms_include_specification (fname);
4349 /* This is a normal VMS filespec, so use it unchanged. */
4350 strncpy (fname, fbeg, flen);
4352 /* if it's '#include filename', add the missing .h */
4353 if (index(fname,'.')==NULL) {
4354 strcat (fname, ".h");
4358 /* ??? There are currently 3 separate mechanisms for avoiding processing
4359 of redundant include files: #import, #pragma once, and
4360 redundant_include_p. It would be nice if they were unified. */
4361 if (redundant_include_p (fname))
4364 f = lookup_import (fname, searchptr);
4366 f = open_include_file (fname, searchptr);
4368 return 0; /* Already included this file */
4370 else if (f == -1 && errno == EACCES)
4371 warning ("Header file %s exists, but is not readable", fname);
4379 /* A file that was not found. */
4381 strncpy (fname, fbeg, flen);
4383 /* If generating dependencies and -MG was specified, we assume missing
4384 files are leaf files, living in the same directory as the source file
4385 or other similar place; these missing files may be generated from
4386 other files and may not exist yet (eg: y.tab.h). */
4387 if (print_deps_missing_files
4388 && print_deps > (angle_brackets || (system_include_depth > 0)))
4390 /* If it was requested as a system header file,
4391 then assume it belongs in the first place to look for such. */
4394 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4396 if (searchptr->fname)
4400 if (searchptr->fname[0] == 0)
4402 p = xmalloc (strlen (searchptr->fname)
4403 + strlen (fname) + 2);
4404 strcpy (p, searchptr->fname);
4407 deps_output (p, ' ');
4414 /* Otherwise, omit the directory, as if the file existed
4415 in the directory with the source. */
4416 deps_output (fname, ' ');
4419 /* If -M was specified, and this header file won't be added to the
4420 dependency list, then don't count this as an error, because we can
4421 still produce correct output. Otherwise, we can't produce correct
4422 output, because there may be dependencies we need inside the missing
4423 file, and we don't know what directory this missing file exists in. */
4425 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4426 warning ("No include path in which to find %s", fname);
4427 else if (search_start)
4428 error_from_errno (fname);
4430 error ("No include path in which to find %s", fname);
4432 /* Check to see if this include file is a once-only include file.
4435 struct file_name_list* ptr;
4437 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4438 if (!strcmp (ptr->fname, fname)) {
4440 return 0; /* This file was once'd. */
4444 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4445 if (!strcmp (ptr->fname, fname))
4446 break; /* This file was included before. */
4450 /* This is the first time for this file. */
4451 /* Add it to list of files included. */
4453 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4454 ptr->control_macro = 0;
4455 ptr->c_system_include_path = 0;
4456 ptr->next = all_include_files;
4457 all_include_files = ptr;
4458 ptr->fname = savestring (fname);
4459 ptr->got_name_map = 0;
4461 /* For -M, add this file to the dependencies. */
4462 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4463 deps_output (fname, ' ');
4466 /* Handle -H option. */
4467 if (print_include_names) {
4468 output_dots (stderr, indepth);
4469 fprintf (stderr, "%s\n", fname);
4473 system_include_depth++;
4475 /* Actually process the file. */
4476 add_import (f, fname); /* Record file on "seen" list for #import. */
4478 pcftry = (char *) alloca (strlen (fname) + 30);
4489 sprintf (pcftry, "%s%d", fname, pcfnum++);
4491 pcf = open (pcftry, O_RDONLY, 0666);
4497 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4499 || stat_f.st_dev != s.st_dev)
4501 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4502 /* Don't need it any more. */
4507 /* Don't need it at all. */
4512 } while (pcf != -1 && !pcfbuf);
4515 /* Actually process the file */
4517 pcfname = xmalloc (strlen (pcftry) + 1);
4518 strcpy (pcfname, pcftry);
4519 pcfinclude (pcfbuf, pcfbuflimit, fname, op);
4522 finclude (f, fname, op, is_system_include (fname), searchptr);
4525 system_include_depth--;
4530 /* Return nonzero if there is no need to include file NAME
4531 because it has already been included and it contains a conditional
4532 to make a repeated include do nothing. */
4535 redundant_include_p (name)
4538 struct file_name_list *l = all_include_files;
4539 for (; l; l = l->next)
4540 if (! strcmp (name, l->fname)
4542 && lookup (l->control_macro, -1, -1))
4547 /* Return nonzero if the given FILENAME is an absolute pathname which
4548 designates a file within one of the known "system" include file
4549 directories. We assume here that if the given FILENAME looks like
4550 it is the name of a file which resides either directly in a "system"
4551 include file directory, or within any subdirectory thereof, then the
4552 given file must be a "system" include file. This function tells us
4553 if we should suppress pedantic errors/warnings for the given FILENAME.
4555 The value is 2 if the file is a C-language system header file
4556 for which C++ should (on most systems) assume `extern "C"'. */
4559 is_system_include (filename)
4560 register char *filename;
4562 struct file_name_list *searchptr;
4564 for (searchptr = first_system_include; searchptr;
4565 searchptr = searchptr->next)
4566 if (searchptr->fname) {
4567 register char *sys_dir = searchptr->fname;
4568 register unsigned length = strlen (sys_dir);
4570 if (! strncmp (sys_dir, filename, length)
4571 && (filename[length] == '/'
4572 #ifdef DIR_SEPARATOR
4573 || filename[length] == DIR_SEPARATOR
4576 if (searchptr->c_system_include_path)
4585 /* The file_name_map structure holds a mapping of file names for a
4586 particular directory. This mapping is read from the file named
4587 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4588 map filenames on a file system with severe filename restrictions,
4589 such as DOS. The format of the file name map file is just a series
4590 of lines with two tokens on each line. The first token is the name
4591 to map, and the second token is the actual name to use. */
4593 struct file_name_map
4595 struct file_name_map *map_next;
4600 #define FILE_NAME_MAP_FILE "header.gcc"
4602 /* Read a space delimited string of unlimited length from a stdio
4606 read_filename_string (ch, f)
4614 set = alloc = xmalloc (len + 1);
4618 while ((ch = getc (f)) != EOF && ! is_space[ch])
4620 if (set - alloc == len)
4623 alloc = xrealloc (alloc, len + 1);
4624 set = alloc + len / 2;
4634 /* Read the file name map file for DIRNAME. */
4636 static struct file_name_map *
4637 read_name_map (dirname)
4640 /* This structure holds a linked list of file name maps, one per
4642 struct file_name_map_list
4644 struct file_name_map_list *map_list_next;
4645 char *map_list_name;
4646 struct file_name_map *map_list_map;
4648 static struct file_name_map_list *map_list;
4649 register struct file_name_map_list *map_list_ptr;
4653 for (map_list_ptr = map_list; map_list_ptr;
4654 map_list_ptr = map_list_ptr->map_list_next)
4655 if (! strcmp (map_list_ptr->map_list_name, dirname))
4656 return map_list_ptr->map_list_map;
4658 map_list_ptr = ((struct file_name_map_list *)
4659 xmalloc (sizeof (struct file_name_map_list)));
4660 map_list_ptr->map_list_name = savestring (dirname);
4661 map_list_ptr->map_list_map = NULL;
4663 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
4664 strcpy (name, dirname);
4667 strcat (name, FILE_NAME_MAP_FILE);
4668 f = fopen (name, "r");
4670 map_list_ptr->map_list_map = NULL;
4674 int dirlen = strlen (dirname);
4676 while ((ch = getc (f)) != EOF)
4679 struct file_name_map *ptr;
4683 from = read_filename_string (ch, f);
4684 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4686 to = read_filename_string (ch, f);
4688 ptr = ((struct file_name_map *)
4689 xmalloc (sizeof (struct file_name_map)));
4690 ptr->map_from = from;
4692 /* Make the real filename absolute. */
4697 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4698 strcpy (ptr->map_to, dirname);
4699 ptr->map_to[dirlen] = '/';
4700 strcpy (ptr->map_to + dirlen + 1, to);
4704 ptr->map_next = map_list_ptr->map_list_map;
4705 map_list_ptr->map_list_map = ptr;
4707 while ((ch = getc (f)) != '\n')
4714 map_list_ptr->map_list_next = map_list;
4715 map_list = map_list_ptr;
4717 return map_list_ptr->map_list_map;
4720 /* Try to open include file FILENAME. SEARCHPTR is the directory
4721 being tried from the include file search path. This function maps
4722 filenames on file systems based on information read by
4726 open_include_file (filename, searchptr)
4728 struct file_name_list *searchptr;
4730 register struct file_name_map *map;
4731 register char *from;
4734 if (searchptr && ! searchptr->got_name_map)
4736 searchptr->name_map = read_name_map (searchptr->fname
4737 ? searchptr->fname : ".");
4738 searchptr->got_name_map = 1;
4741 /* First check the mapping for the directory we are using. */
4742 if (searchptr && searchptr->name_map)
4745 if (searchptr->fname)
4746 from += strlen (searchptr->fname) + 1;
4747 for (map = searchptr->name_map; map; map = map->map_next)
4749 if (! strcmp (map->map_from, from))
4751 /* Found a match. */
4752 return open (map->map_to, O_RDONLY, 0666);
4757 /* Try to find a mapping file for the particular directory we are
4758 looking in. Thus #include <sys/types.h> will look up sys/types.h
4759 in /usr/include/header.gcc and look up types.h in
4760 /usr/include/sys/header.gcc. */
4761 p = rindex (filename, '/');
4762 #ifdef DIR_SEPARATOR
4763 if (! p) p = rindex (filename, DIR_SEPARATOR);
4765 char *tmp = rindex (filename, DIR_SEPARATOR);
4766 if (tmp != NULL && tmp > p) p = tmp;
4773 && strlen (searchptr->fname) == p - filename
4774 && ! strncmp (searchptr->fname, filename, p - filename))
4776 /* FILENAME is in SEARCHPTR, which we've already checked. */
4777 return open (filename, O_RDONLY, 0666);
4787 dir = (char *) alloca (p - filename + 1);
4788 bcopy (filename, dir, p - filename);
4789 dir[p - filename] = '\0';
4792 for (map = read_name_map (dir); map; map = map->map_next)
4793 if (! strcmp (map->map_from, from))
4794 return open (map->map_to, O_RDONLY, 0666);
4796 return open (filename, O_RDONLY, 0666);
4799 /* Process the contents of include file FNAME, already open on descriptor F,
4801 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4802 "system" include directories (as decided by the `is_system_include'
4804 DIRPTR is the link in the dir path through which this file was found,
4805 or 0 if the file name was absolute. */
4808 finclude (f, fname, op, system_header_p, dirptr)
4812 int system_header_p;
4813 struct file_name_list *dirptr;
4818 FILE_BUF *fp; /* For input stack frame */
4819 int missing_newline = 0;
4821 CHECK_DEPTH (return;);
4823 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
4825 perror_with_name (fname);
4830 fp = &instack[indepth + 1];
4831 bzero ((char *) fp, sizeof (FILE_BUF));
4832 fp->nominal_fname = fp->fname = fname;
4835 fp->if_stack = if_stack;
4836 fp->system_header_p = system_header_p;
4839 if (S_ISREG (st_mode)) {
4840 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
4843 /* Read the file contents, knowing that st_size is an upper bound
4844 on the number of bytes we can read. */
4845 fp->length = safe_read (f, fp->buf, st_size);
4846 if (fp->length < 0) goto nope;
4848 else if (S_ISDIR (st_mode)) {
4849 error ("directory `%s' specified in #include", fname);
4853 /* Cannot count its file size before reading.
4854 First read the entire file into heap and
4855 copy them into buffer on stack. */
4860 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
4863 i = safe_read (f, fp->buf + st_size, bsize - st_size);
4865 goto nope; /* error! */
4867 if (st_size != bsize)
4868 break; /* End of file */
4870 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
4873 fp->length = st_size;
4876 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
4877 /* Backslash-newline at end is not good enough. */
4878 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
4879 fp->buf[fp->length++] = '\n';
4880 missing_newline = 1;
4882 fp->buf[fp->length] = '\0';
4884 /* Close descriptor now, so nesting does not use lots of descriptors. */
4887 /* Must do this before calling trigraph_pcp, so that the correct file name
4888 will be printed in warning messages. */
4891 input_file_stack_tick++;
4896 output_line_directive (fp, op, 0, enter_file);
4899 if (missing_newline)
4902 if (pedantic && missing_newline)
4903 pedwarn ("file does not end in newline");
4906 input_file_stack_tick++;
4907 output_line_directive (&instack[indepth], op, 0, leave_file);
4913 perror_with_name (fname);
4918 /* Record that inclusion of the file named FILE
4919 should be controlled by the macro named MACRO_NAME.
4920 This means that trying to include the file again
4921 will do something if that macro is defined. */
4924 record_control_macro (file, macro_name)
4928 struct file_name_list *new;
4930 for (new = all_include_files; new; new = new->next) {
4931 if (!strcmp (new->fname, file)) {
4932 new->control_macro = macro_name;
4937 /* If the file is not in all_include_files, something's wrong. */
4941 /* Maintain and search list of included files, for #import. */
4943 #define IMPORT_HASH_SIZE 31
4945 struct import_file {
4949 struct import_file *next;
4952 /* Hash table of files already included with #include or #import. */
4954 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
4956 /* Hash a file name for import_hash_table. */
4964 while (*f) val += *f++;
4965 return (val%IMPORT_HASH_SIZE);
4968 /* Search for file FILENAME in import_hash_table.
4969 Return -2 if found, either a matching name or a matching inode.
4970 Otherwise, open the file and return a file descriptor if successful
4971 or -1 if unsuccessful. */
4974 lookup_import (filename, searchptr)
4976 struct file_name_list *searchptr;
4978 struct import_file *i;
4984 hashval = import_hash (filename);
4986 /* Attempt to find file in list of already included files */
4987 i = import_hash_table[hashval];
4990 if (!strcmp (filename, i->name))
4991 return -2; /* return found */
4994 /* Open it and try a match on inode/dev */
4995 fd = open_include_file (filename, searchptr);
4999 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5000 i = import_hash_table[h];
5002 /* Compare the inode and the device.
5003 Supposedly on some systems the inode is not a scalar. */
5004 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5005 && i->dev == sb.st_dev) {
5007 return -2; /* return found */
5012 return fd; /* Not found, return open file */
5015 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5018 add_import (fd, fname)
5022 struct import_file *i;
5026 hashval = import_hash (fname);
5028 i = (struct import_file *)xmalloc (sizeof (struct import_file));
5029 i->name = (char *)xmalloc (strlen (fname)+1);
5030 strcpy (i->name, fname);
5031 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5033 i->next = import_hash_table[hashval];
5034 import_hash_table[hashval] = i;
5037 /* Load the specified precompiled header into core, and verify its
5038 preconditions. PCF indicates the file descriptor to read, which must
5039 be a regular file. FNAME indicates the file name of the original
5040 header. *LIMIT will be set to an address one past the end of the file.
5041 If the preconditions of the file are not satisfied, the buffer is
5042 freed and we return 0. If the preconditions are satisfied, return
5043 the address of the buffer following the preconditions. The buffer, in
5044 this case, should never be freed because various pieces of it will
5045 be referred to until all precompiled strings are output at the end of
5049 check_precompiled (pcf, fname, limit)
5063 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
5066 if (S_ISREG (st_mode))
5068 buf = xmalloc (st_size + 2);
5069 length = safe_read (pcf, buf, st_size);
5076 if (length > 0 && buf[length-1] != '\n')
5077 buf[length++] = '\n';
5080 *limit = buf + length;
5082 /* File is in core. Check the preconditions. */
5083 if (!check_preconditions (buf))
5085 for (cp = buf; *cp; cp++)
5088 fprintf (stderr, "Using preinclude %s\n", fname);
5094 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5100 /* PREC (null terminated) points to the preconditions of a
5101 precompiled header. These are a series of #define and #undef
5102 lines which must match the current contents of the hash
5105 check_preconditions (prec)
5112 lineend = (char *) index (prec, '\n');
5114 if (*prec++ != '#') {
5115 error ("Bad format encountered while reading precompiled file");
5118 if (!strncmp (prec, "define", 6)) {
5122 mdef = create_definition (prec, lineend, NULL_PTR);
5127 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5128 || (hp->type != T_MACRO && hp->type != T_CONST)
5129 || (hp->type == T_MACRO
5130 && !compare_defs (mdef.defn, hp->value.defn)
5131 && (mdef.defn->length != 2
5132 || mdef.defn->expansion[0] != '\n'
5133 || mdef.defn->expansion[1] != ' ')))
5135 } else if (!strncmp (prec, "undef", 5)) {
5140 while (is_hor_space[(U_CHAR) *prec])
5143 while (is_idchar[(U_CHAR) *prec])
5147 if (lookup (name, len, -1))
5150 error ("Bad format encountered while reading precompiled file");
5155 /* They all passed successfully */
5159 /* Process the main body of a precompiled file. BUF points to the
5160 string section of the file, following the preconditions. LIMIT is one
5161 character past the end. NAME is the name of the file being read
5162 in. OP is the main output buffer */
5164 pcfinclude (buf, limit, name, op)
5165 U_CHAR *buf, *limit, *name;
5172 /* First in the file comes 4 bytes indicating the number of strings, */
5173 /* in network byte order. (MSB first). */
5175 nstrings = (nstrings << 8) | *cp++;
5176 nstrings = (nstrings << 8) | *cp++;
5177 nstrings = (nstrings << 8) | *cp++;
5179 /* Looping over each string... */
5180 while (nstrings--) {
5181 U_CHAR *string_start;
5182 U_CHAR *endofthiskey;
5186 /* Each string starts with a STRINGDEF structure (str), followed */
5187 /* by the text of the string (string_start) */
5189 /* First skip to a longword boundary */
5190 /* ??? Why a 4-byte boundary? On all machines? */
5191 /* NOTE: This works correctly even if HOST_WIDE_INT
5192 is narrower than a pointer.
5193 Do not try risky measures here to get another type to use!
5194 Do not include stddef.h--it will fail! */
5195 if ((HOST_WIDE_INT) cp & 3)
5196 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5198 /* Now get the string. */
5199 str = (STRINGDEF *) cp;
5200 string_start = cp += sizeof (STRINGDEF);
5202 for (; *cp; cp++) /* skip the string */
5205 /* We need to macro expand the string here to ensure that the
5206 proper definition environment is in place. If it were only
5207 expanded when we find out it is needed, macros necessary for
5208 its proper expansion might have had their definitions changed. */
5209 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5210 /* Lineno is already set in the precompiled file */
5211 str->contents = tmpbuf.buf;
5212 str->len = tmpbuf.length;
5214 str->filename = name;
5215 str->output_mark = outbuf.bufp - outbuf.buf;
5218 *stringlist_tailp = str;
5219 stringlist_tailp = &str->chain;
5221 /* Next comes a fourbyte number indicating the number of keys */
5222 /* for this string. */
5224 nkeys = (nkeys << 8) | *cp++;
5225 nkeys = (nkeys << 8) | *cp++;
5226 nkeys = (nkeys << 8) | *cp++;
5228 /* If this number is -1, then the string is mandatory. */
5232 /* Otherwise, for each key, */
5233 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5234 KEYDEF *kp = (KEYDEF *) cp;
5237 /* It starts with a KEYDEF structure */
5238 cp += sizeof (KEYDEF);
5240 /* Find the end of the key. At the end of this for loop we
5241 advance CP to the start of the next key using this variable. */
5242 endofthiskey = cp + strlen (cp);
5245 /* Expand the key, and enter it into the hash table. */
5246 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5247 tmpbuf.bufp = tmpbuf.buf;
5249 while (is_hor_space[*tmpbuf.bufp])
5251 if (!is_idstart[*tmpbuf.bufp]
5252 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5257 hp = lookup (tmpbuf.bufp, -1, -1);
5260 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5262 else if (hp->type == T_PCSTRING) {
5263 kp->chain = hp->value.keydef;
5264 hp->value.keydef = kp;
5270 /* This output_line_directive serves to switch us back to the current
5271 input file in case some of these strings get output (which will
5272 result in line directives for the header file being output). */
5273 output_line_directive (&instack[indepth], op, 0, enter_file);
5276 /* Called from rescan when it hits a key for strings. Mark them all */
5277 /* used and clean up. */
5284 for (kp = hp->value.keydef; kp; kp = kp->chain)
5285 kp->str->writeflag = 1;
5289 /* Write the output, interspersing precompiled strings in their */
5290 /* appropriate places. */
5294 STRINGDEF *next_string;
5295 U_CHAR *cur_buf_loc;
5296 int line_directive_len = 80;
5297 char *line_directive = xmalloc (line_directive_len);
5300 /* In each run through the loop, either cur_buf_loc == */
5301 /* next_string_loc, in which case we print a series of strings, or */
5302 /* it is less than next_string_loc, in which case we write some of */
5304 cur_buf_loc = outbuf.buf;
5305 next_string = stringlist;
5307 while (cur_buf_loc < outbuf.bufp || next_string) {
5309 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5310 if (next_string->writeflag) {
5311 len = 4 * strlen (next_string->filename) + 32;
5312 while (len > line_directive_len)
5313 line_directive = xrealloc (line_directive,
5314 line_directive_len *= 2);
5315 sprintf (line_directive, "\n# %d ", next_string->lineno);
5316 strcpy (quote_string (line_directive + strlen (line_directive),
5317 next_string->filename),
5319 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5320 safe_write (fileno (stdout), next_string->contents, next_string->len);
5322 next_string = next_string->chain;
5326 ? (next_string->output_mark
5327 - (cur_buf_loc - outbuf.buf))
5328 : outbuf.bufp - cur_buf_loc);
5330 safe_write (fileno (stdout), cur_buf_loc, len);
5334 free (line_directive);
5337 /* Pass a directive through to the output file.
5338 BUF points to the contents of the directive, as a contiguous string.
5339 LIMIT points to the first character past the end of the directive.
5340 KEYWORD is the keyword-table entry for the directive. */
5343 pass_thru_directive (buf, limit, op, keyword)
5344 U_CHAR *buf, *limit;
5346 struct directive *keyword;
5348 register unsigned keyword_length = keyword->length;
5350 check_expand (op, 1 + keyword_length + (limit - buf));
5352 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5353 op->bufp += keyword_length;
5354 if (limit != buf && buf[0] != ' ')
5356 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5357 op->bufp += (limit - buf);
5360 /* Count the line we have just made in the output,
5361 to get in sync properly. */
5366 /* The arglist structure is built by do_define to tell
5367 collect_definition where the argument names begin. That
5368 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5369 would contain pointers to the strings x, y, and z.
5370 Collect_definition would then build a DEFINITION node,
5371 with reflist nodes pointing to the places x, y, and z had
5372 appeared. So the arglist is just convenience data passed
5373 between these two routines. It is not kept around after
5374 the current #define has been processed and entered into the
5378 struct arglist *next;
5385 /* Create a DEFINITION node from a #define directive. Arguments are
5386 as for do_define. */
5388 create_definition (buf, limit, op)
5389 U_CHAR *buf, *limit;
5392 U_CHAR *bp; /* temp ptr into input buffer */
5393 U_CHAR *symname; /* remember where symbol name starts */
5394 int sym_length; /* and how long it is */
5395 int line = instack[indepth].lineno;
5396 char *file = instack[indepth].nominal_fname;
5400 int arglengths = 0; /* Accumulate lengths of arg names
5401 plus number of args. */
5406 while (is_hor_space[*bp])
5409 symname = bp; /* remember where it starts */
5410 sym_length = check_macro_name (bp, "macro");
5413 /* Lossage will occur if identifiers or control keywords are broken
5414 across lines using backslash. This is not the right place to take
5418 struct arglist *arg_ptrs = NULL;
5421 bp++; /* skip '(' */
5422 SKIP_WHITE_SPACE (bp);
5424 /* Loop over macro argument names. */
5425 while (*bp != ')') {
5426 struct arglist *temp;
5428 temp = (struct arglist *) alloca (sizeof (struct arglist));
5430 temp->next = arg_ptrs;
5431 temp->argno = argno++;
5432 temp->rest_args = 0;
5436 pedwarn ("another parameter follows `%s'",
5439 if (!is_idstart[*bp])
5440 pedwarn ("invalid character in macro parameter name");
5442 /* Find the end of the arg name. */
5443 while (is_idchar[*bp]) {
5445 /* do we have a "special" rest-args extension here? */
5446 if (limit - bp > REST_EXTENSION_LENGTH &&
5447 strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5449 temp->rest_args = 1;
5453 temp->length = bp - temp->name;
5455 bp += REST_EXTENSION_LENGTH;
5456 arglengths += temp->length + 2;
5457 SKIP_WHITE_SPACE (bp);
5458 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5459 error ("badly punctuated parameter list in `#define'");
5464 SKIP_WHITE_SPACE (bp);
5465 /* A comma at this point can only be followed by an identifier. */
5466 if (!is_idstart[*bp]) {
5467 error ("badly punctuated parameter list in `#define'");
5472 error ("unterminated parameter list in `#define'");
5476 struct arglist *otemp;
5478 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5479 if (temp->length == otemp->length &&
5480 strncmp (temp->name, otemp->name, temp->length) == 0) {
5483 name = (U_CHAR *) alloca (temp->length + 1);
5484 (void) strncpy (name, temp->name, temp->length);
5485 name[temp->length] = '\0';
5486 error ("duplicate argument name `%s' in `#define'", name);
5492 ++bp; /* skip paren */
5493 SKIP_WHITE_SPACE (bp);
5494 /* now everything from bp before limit is the definition. */
5495 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5496 defn->rest_args = rest_args;
5498 /* Now set defn->args.argnames to the result of concatenating
5499 the argument names in reverse order
5500 with comma-space between them. */
5501 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5503 struct arglist *temp;
5505 for (temp = arg_ptrs; temp; temp = temp->next) {
5506 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5508 if (temp->next != 0) {
5509 defn->args.argnames[i++] = ',';
5510 defn->args.argnames[i++] = ' ';
5513 defn->args.argnames[i] = 0;
5516 /* Simple expansion or empty definition. */
5520 if (is_hor_space[*bp]) {
5522 SKIP_WHITE_SPACE (bp);
5525 case '!': case '"': case '#': case '%': case '&': case '\'':
5526 case ')': case '*': case '+': case ',': case '-': case '.':
5527 case '/': case ':': case ';': case '<': case '=': case '>':
5528 case '?': case '[': case '\\': case ']': case '^': case '{':
5529 case '|': case '}': case '~':
5530 warning ("missing white space after `#define %.*s'",
5531 sym_length, symname);
5535 pedwarn ("missing white space after `#define %.*s'",
5536 sym_length, symname);
5541 /* Now everything from bp before limit is the definition. */
5542 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5543 defn->args.argnames = (U_CHAR *) "";
5549 /* OP is null if this is a predefinition */
5550 defn->predefined = !op;
5552 mdef.symnam = symname;
5553 mdef.symlen = sym_length;
5562 /* Process a #define directive.
5563 BUF points to the contents of the #define directive, as a contiguous string.
5564 LIMIT points to the first character past the end of the definition.
5565 KEYWORD is the keyword-table entry for #define. */
5568 do_define (buf, limit, op, keyword)
5569 U_CHAR *buf, *limit;
5571 struct directive *keyword;
5576 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5577 if (pcp_outfile && op)
5578 pass_thru_directive (buf, limit, op, keyword);
5580 mdef = create_definition (buf, limit, op);
5584 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5588 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5590 /* Redefining a precompiled key is ok. */
5591 if (hp->type == T_PCSTRING)
5593 /* Redefining a macro is ok if the definitions are the same. */
5594 else if (hp->type == T_MACRO)
5595 ok = ! compare_defs (mdef.defn, hp->value.defn);
5596 /* Redefining a constant is ok with -D. */
5597 else if (hp->type == T_CONST)
5598 ok = ! done_initializing;
5599 /* Print the warning if it's not ok. */
5601 U_CHAR *msg; /* what pain... */
5603 /* If we are passing through #define and #undef directives, do
5604 that for this re-definition now. */
5605 if (debug_output && op)
5606 pass_thru_directive (buf, limit, op, keyword);
5608 msg = (U_CHAR *) alloca (mdef.symlen + 22);
5610 bcopy ((char *) mdef.symnam, (char *) (msg + 1), mdef.symlen);
5611 strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
5613 if (hp->type == T_MACRO)
5614 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5615 "this is the location of the previous definition");
5617 /* Replace the old definition. */
5619 hp->value.defn = mdef.defn;
5621 /* If we are passing through #define and #undef directives, do
5622 that for this new definition now. */
5623 if (debug_output && op)
5624 pass_thru_directive (buf, limit, op, keyword);
5625 install (mdef.symnam, mdef.symlen, T_MACRO,
5626 (char *) mdef.defn, hashcode);
5637 /* Check a purported macro name SYMNAME, and yield its length.
5638 USAGE is the kind of name this is intended for. */
5641 check_macro_name (symname, usage)
5648 for (p = symname; is_idchar[*p]; p++)
5650 sym_length = p - symname;
5651 if (sym_length == 0)
5652 error ("invalid %s name", usage);
5653 else if (!is_idstart[*symname]) {
5654 U_CHAR *msg; /* what pain... */
5655 msg = (U_CHAR *) alloca (sym_length + 1);
5656 bcopy ((char *) symname, (char *) msg, sym_length);
5657 msg[sym_length] = 0;
5658 error ("invalid %s name `%s'", usage, msg);
5660 if (! strncmp (symname, "defined", 7) && sym_length == 7)
5661 error ("invalid %s name `defined'", usage);
5667 * return zero if two DEFINITIONs are isomorphic
5670 compare_defs (d1, d2)
5671 DEFINITION *d1, *d2;
5673 register struct reflist *a1, *a2;
5674 register U_CHAR *p1 = d1->expansion;
5675 register U_CHAR *p2 = d2->expansion;
5678 if (d1->nargs != d2->nargs)
5680 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5682 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5683 a1 = a1->next, a2 = a2->next) {
5684 if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
5685 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5686 || a1->argno != a2->argno
5687 || a1->stringify != a2->stringify
5688 || a1->raw_before != a2->raw_before
5689 || a1->raw_after != a2->raw_after)
5697 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5698 p2, d2->length - (p2 - d2->expansion), 1))
5703 /* Return 1 if two parts of two macro definitions are effectively different.
5704 One of the parts starts at BEG1 and has LEN1 chars;
5705 the other has LEN2 chars at BEG2.
5706 Any sequence of whitespace matches any other sequence of whitespace.
5707 FIRST means these parts are the first of a macro definition;
5708 so ignore leading whitespace entirely.
5709 LAST means these parts are the last of a macro definition;
5710 so ignore trailing whitespace entirely. */
5713 comp_def_part (first, beg1, len1, beg2, len2, last)
5715 U_CHAR *beg1, *beg2;
5719 register U_CHAR *end1 = beg1 + len1;
5720 register U_CHAR *end2 = beg2 + len2;
5722 while (beg1 != end1 && is_space[*beg1]) beg1++;
5723 while (beg2 != end2 && is_space[*beg2]) beg2++;
5726 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5727 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5729 while (beg1 != end1 && beg2 != end2) {
5730 if (is_space[*beg1] && is_space[*beg2]) {
5731 while (beg1 != end1 && is_space[*beg1]) beg1++;
5732 while (beg2 != end2 && is_space[*beg2]) beg2++;
5733 } else if (*beg1 == *beg2) {
5737 return (beg1 != end1) || (beg2 != end2);
5740 /* Read a replacement list for a macro with parameters.
5741 Build the DEFINITION structure.
5742 Reads characters of text starting at BUF until END.
5743 ARGLIST specifies the formal parameters to look for
5744 in the text of the definition; NARGS is the number of args
5745 in that list, or -1 for a macro name that wants no argument list.
5746 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5747 and NAMELEN is its length in characters.
5749 Note that comments and backslash-newlines have already been deleted
5750 from the argument. */
5752 /* Leading and trailing Space, Tab, etc. are converted to markers
5753 Newline Space, Newline Tab, etc.
5754 Newline Space makes a space in the final output
5755 but is discarded if stringified. (Newline Tab is similar but
5756 makes a Tab instead.)
5758 If there is no trailing whitespace, a Newline Space is added at the end
5759 to prevent concatenation that would be contrary to the standard. */
5762 collect_expansion (buf, end, nargs, arglist)
5765 struct arglist *arglist;
5768 register U_CHAR *p, *limit, *lastp, *exp_p;
5769 struct reflist *endpat = NULL;
5770 /* Pointer to first nonspace after last ## seen. */
5772 /* Pointer to first nonspace after last single-# seen. */
5773 U_CHAR *stringify = 0;
5774 /* How those tokens were spelled. */
5775 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5776 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5778 int expected_delimiter = '\0';
5780 /* Scan thru the replacement list, ignoring comments and quoted
5781 strings, picking up on the macro calls. It does a linear search
5782 thru the arg list on every potential symbol. Profiling might say
5783 that something smarter should happen. */
5788 /* Find the beginning of the trailing whitespace. */
5789 /* Find end of leading whitespace. */
5792 while (p < limit && is_space[limit[-1]]) limit--;
5793 while (p < limit && is_space[*p]) p++;
5795 /* Allocate space for the text in the macro definition.
5796 Leading and trailing whitespace chars need 2 bytes each.
5797 Each other input char may or may not need 1 byte,
5798 so this is an upper bound.
5799 The extra 2 are for invented trailing newline-marker and final null. */
5800 maxsize = (sizeof (DEFINITION)
5801 + 2 * (end - limit) + 2 * (p - buf)
5803 defn = (DEFINITION *) xcalloc (1, maxsize);
5805 defn->nargs = nargs;
5806 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5811 /* Convert leading whitespace to Newline-markers. */
5812 while (p < limit && is_space[*p]) {
5819 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5820 error ("`##' at start of macro definition");
5821 p += p[0] == '#' ? 2 : 4;
5824 /* Process the main body of the definition. */
5826 int skipped_arg = 0;
5827 register U_CHAR c = *p++;
5835 if (expected_delimiter != '\0') {
5836 if (c == expected_delimiter)
5837 expected_delimiter = '\0';
5839 expected_delimiter = c;
5843 if (p < limit && expected_delimiter) {
5844 /* In a string, backslash goes through
5845 and makes next char ordinary. */
5851 if (!expected_delimiter && *p == ':') {
5852 /* %: is not a digraph if preceded by an odd number of '<'s. */
5854 while (buf < p0 && p0[-1] == '<')
5857 /* Treat %:%: as ## and %: as #. */
5858 if (p[1] == '%' && p[2] == ':') {
5860 goto sharp_sharp_token;
5871 /* # is ordinary inside a string. */
5872 if (expected_delimiter)
5876 /* ##: concatenate preceding and following tokens. */
5877 /* Take out the first #, discard preceding whitespace. */
5879 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5881 /* Skip the second #. */
5883 concat_sharp_token_type = c;
5884 if (is_hor_space[*p]) {
5885 concat_sharp_token_type++;
5887 SKIP_WHITE_SPACE (p);
5891 error ("`##' at end of macro definition");
5892 } else if (nargs >= 0) {
5893 /* Single #: stringify following argument ref.
5894 Don't leave the # in the expansion. */
5897 stringify_sharp_token_type = c;
5898 if (is_hor_space[*p]) {
5899 stringify_sharp_token_type++;
5901 SKIP_WHITE_SPACE (p);
5903 if (! is_idstart[*p] || nargs == 0)
5904 error ("`#' operator is not followed by a macro argument name");
5911 /* In -traditional mode, recognize arguments inside strings and
5912 and character constants, and ignore special properties of #.
5913 Arguments inside strings are considered "stringified", but no
5914 extra quote marks are supplied. */
5918 if (expected_delimiter != '\0') {
5919 if (c == expected_delimiter)
5920 expected_delimiter = '\0';
5922 expected_delimiter = c;
5926 /* Backslash quotes delimiters and itself, but not macro args. */
5927 if (expected_delimiter != 0 && p < limit
5928 && (*p == expected_delimiter || *p == '\\')) {
5935 if (expected_delimiter != '\0') /* No comments inside strings. */
5938 /* If we find a comment that wasn't removed by handle_directive,
5939 this must be -traditional. So replace the comment with
5943 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5946 /* Mark this as a concatenation-point, as if it had been ##. */
5954 /* Handle the start of a symbol. */
5955 if (is_idchar[c] && nargs > 0) {
5956 U_CHAR *id_beg = p - 1;
5960 while (p != limit && is_idchar[*p]) p++;
5961 id_len = p - id_beg;
5963 if (is_idstart[c]) {
5964 register struct arglist *arg;
5966 for (arg = arglist; arg != NULL; arg = arg->next) {
5967 struct reflist *tpat;
5969 if (arg->name[0] == c
5970 && arg->length == id_len
5971 && strncmp (arg->name, id_beg, id_len) == 0) {
5972 if (expected_delimiter && warn_stringify) {
5974 warning ("macro argument `%.*s' is stringified.",
5977 warning ("macro arg `%.*s' would be stringified with -traditional.",
5981 /* If ANSI, don't actually substitute inside a string. */
5982 if (!traditional && expected_delimiter)
5984 /* make a pat node for this arg and append it to the end of
5986 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
5989 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
5990 tpat->raw_after = NO_SHARP_TOKEN;
5991 tpat->rest_args = arg->rest_args;
5993 = ((traditional ? expected_delimiter : stringify == id_beg)
5994 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
5997 defn->pattern = tpat;
5999 endpat->next = tpat;
6002 tpat->argno = arg->argno;
6003 tpat->nchars = exp_p - lastp;
6005 register U_CHAR *p1 = p;
6006 SKIP_WHITE_SPACE (p1);
6009 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6010 tpat->raw_after = p1[0] + (p != p1);
6012 lastp = exp_p; /* place to start copying from next time */
6019 /* If this was not a macro arg, copy it into the expansion. */
6020 if (! skipped_arg) {
6021 register U_CHAR *lim1 = p;
6025 if (stringify == id_beg)
6026 error ("`#' operator should be followed by a macro argument name");
6031 if (!traditional && expected_delimiter == 0) {
6032 /* There is no trailing whitespace, so invent some in ANSI mode.
6033 But not if "inside a string" (which in ANSI mode
6034 happens only for -D option). */
6041 defn->length = exp_p - defn->expansion;
6043 /* Crash now if we overrun the allocated size. */
6044 if (defn->length + 1 > maxsize)
6048 /* This isn't worth the time it takes. */
6049 /* give back excess storage */
6050 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6057 do_assert (buf, limit, op, keyword)
6058 U_CHAR *buf, *limit;
6060 struct directive *keyword;
6062 U_CHAR *bp; /* temp ptr into input buffer */
6063 U_CHAR *symname; /* remember where symbol name starts */
6064 int sym_length; /* and how long it is */
6065 struct arglist *tokens = NULL;
6067 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6068 pedwarn ("ANSI C does not allow `#assert'");
6072 while (is_hor_space[*bp])
6075 symname = bp; /* remember where it starts */
6076 sym_length = check_macro_name (bp, "assertion");
6078 /* #define doesn't do this, but we should. */
6079 SKIP_WHITE_SPACE (bp);
6081 /* Lossage will occur if identifiers or control tokens are broken
6082 across lines using backslash. This is not the right place to take
6086 error ("missing token-sequence in `#assert'");
6093 bp++; /* skip '(' */
6094 SKIP_WHITE_SPACE (bp);
6096 tokens = read_token_list (&bp, limit, &error_flag);
6100 error ("empty token-sequence in `#assert'");
6104 ++bp; /* skip paren */
6105 SKIP_WHITE_SPACE (bp);
6108 /* If this name isn't already an assertion name, make it one.
6109 Error if it was already in use in some other way. */
6112 ASSERTION_HASHNODE *hp;
6113 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6114 struct tokenlist_list *value
6115 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6117 hp = assertion_lookup (symname, sym_length, hashcode);
6119 if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
6120 error ("`defined' redefined as assertion");
6121 hp = assertion_install (symname, sym_length, hashcode);
6124 /* Add the spec'd token-sequence to the list of such. */
6125 value->tokens = tokens;
6126 value->next = hp->value;
6134 do_unassert (buf, limit, op, keyword)
6135 U_CHAR *buf, *limit;
6137 struct directive *keyword;
6139 U_CHAR *bp; /* temp ptr into input buffer */
6140 U_CHAR *symname; /* remember where symbol name starts */
6141 int sym_length; /* and how long it is */
6143 struct arglist *tokens = NULL;
6144 int tokens_specified = 0;
6146 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6147 pedwarn ("ANSI C does not allow `#unassert'");
6151 while (is_hor_space[*bp])
6154 symname = bp; /* remember where it starts */
6155 sym_length = check_macro_name (bp, "assertion");
6157 /* #define doesn't do this, but we should. */
6158 SKIP_WHITE_SPACE (bp);
6160 /* Lossage will occur if identifiers or control tokens are broken
6161 across lines using backslash. This is not the right place to take
6167 bp++; /* skip '(' */
6168 SKIP_WHITE_SPACE (bp);
6170 tokens = read_token_list (&bp, limit, &error_flag);
6174 error ("empty token list in `#unassert'");
6178 tokens_specified = 1;
6180 ++bp; /* skip paren */
6181 SKIP_WHITE_SPACE (bp);
6185 ASSERTION_HASHNODE *hp;
6186 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6187 struct tokenlist_list *tail, *prev;
6189 hp = assertion_lookup (symname, sym_length, hashcode);
6193 /* If no token list was specified, then eliminate this assertion
6195 if (! tokens_specified) {
6196 struct tokenlist_list *next;
6197 for (tail = hp->value; tail; tail = next) {
6199 free_token_list (tail->tokens);
6202 delete_assertion (hp);
6204 /* If a list of tokens was given, then delete any matching list. */
6209 struct tokenlist_list *next = tail->next;
6210 if (compare_token_lists (tail->tokens, tokens)) {
6214 hp->value = tail->next;
6215 free_token_list (tail->tokens);
6228 /* Test whether there is an assertion named NAME
6229 and optionally whether it has an asserted token list TOKENS.
6230 NAME is not null terminated; its length is SYM_LENGTH.
6231 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6234 check_assertion (name, sym_length, tokens_specified, tokens)
6237 int tokens_specified;
6238 struct arglist *tokens;
6240 ASSERTION_HASHNODE *hp;
6241 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6243 if (pedantic && !instack[indepth].system_header_p)
6244 pedwarn ("ANSI C does not allow testing assertions");
6246 hp = assertion_lookup (name, sym_length, hashcode);
6248 /* It is not an assertion; just return false. */
6251 /* If no token list was specified, then value is 1. */
6252 if (! tokens_specified)
6256 struct tokenlist_list *tail;
6260 /* If a list of tokens was given,
6261 then succeed if the assertion records a matching list. */
6264 if (compare_token_lists (tail->tokens, tokens))
6269 /* Fail if the assertion has no matching list. */
6274 /* Compare two lists of tokens for equality including order of tokens. */
6277 compare_token_lists (l1, l2)
6278 struct arglist *l1, *l2;
6281 if (l1->length != l2->length)
6283 if (strncmp (l1->name, l2->name, l1->length))
6289 /* Succeed if both lists end at the same time. */
6293 /* Read a space-separated list of tokens ending in a close parenthesis.
6294 Return a list of strings, in the order they were written.
6295 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6296 Parse the text starting at *BPP, and update *BPP.
6297 Don't parse beyond LIMIT. */
6299 static struct arglist *
6300 read_token_list (bpp, limit, error_flag)
6305 struct arglist *token_ptrs = 0;
6311 /* Loop over the assertion value tokens. */
6313 struct arglist *temp;
6317 /* Find the end of the token. */
6321 } else if (*bp == ')') {
6326 } else if (*bp == '"' || *bp == '\'')
6327 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6329 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6330 && *bp != '"' && *bp != '\'' && bp != limit)
6333 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6334 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6335 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6336 temp->name[bp - beg] = 0;
6337 temp->next = token_ptrs;
6339 temp->length = bp - beg;
6341 SKIP_WHITE_SPACE (bp);
6344 error ("unterminated token sequence in `#assert' or `#unassert'");
6351 /* We accumulated the names in reverse order.
6352 Now reverse them to get the proper order. */
6354 register struct arglist *prev = 0, *this, *next;
6355 for (this = token_ptrs; this; this = next) {
6365 free_token_list (tokens)
6366 struct arglist *tokens;
6369 struct arglist *next = tokens->next;
6370 free (tokens->name);
6377 * Install a name in the assertion hash table.
6379 * If LEN is >= 0, it is the length of the name.
6380 * Otherwise, compute the length by scanning the entire name.
6382 * If HASH is >= 0, it is the precomputed hash code.
6383 * Otherwise, compute the hash code.
6385 static ASSERTION_HASHNODE *
6386 assertion_install (name, len, hash)
6391 register ASSERTION_HASHNODE *hp;
6392 register int i, bucket;
6393 register U_CHAR *p, *q;
6395 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6396 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6398 hp->bucket_hdr = &assertion_hashtab[bucket];
6399 hp->next = assertion_hashtab[bucket];
6400 assertion_hashtab[bucket] = hp;
6402 if (hp->next != NULL)
6403 hp->next->prev = hp;
6406 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6409 for (i = 0; i < len; i++)
6416 * find the most recent hash node for name name (ending with first
6417 * non-identifier char) installed by install
6419 * If LEN is >= 0, it is the length of the name.
6420 * Otherwise, compute the length by scanning the entire name.
6422 * If HASH is >= 0, it is the precomputed hash code.
6423 * Otherwise, compute the hash code.
6425 static ASSERTION_HASHNODE *
6426 assertion_lookup (name, len, hash)
6431 register ASSERTION_HASHNODE *bucket;
6433 bucket = assertion_hashtab[hash];
6435 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
6437 bucket = bucket->next;
6443 delete_assertion (hp)
6444 ASSERTION_HASHNODE *hp;
6447 if (hp->prev != NULL)
6448 hp->prev->next = hp->next;
6449 if (hp->next != NULL)
6450 hp->next->prev = hp->prev;
6452 /* make sure that the bucket chain header that
6453 the deleted guy was on points to the right thing afterwards. */
6454 if (hp == *hp->bucket_hdr)
6455 *hp->bucket_hdr = hp->next;
6461 * interpret #line directive. Remembers previously seen fnames
6462 * in its very own hash table.
6464 #define FNAME_HASHSIZE 37
6467 do_line (buf, limit, op, keyword)
6468 U_CHAR *buf, *limit;
6470 struct directive *keyword;
6472 register U_CHAR *bp;
6473 FILE_BUF *ip = &instack[indepth];
6476 enum file_change_code file_change = same_file;
6478 /* Expand any macros. */
6479 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6481 /* Point to macroexpanded line, which is null-terminated now. */
6483 SKIP_WHITE_SPACE (bp);
6485 if (!isdigit (*bp)) {
6486 error ("invalid format `#line' directive");
6490 /* The Newline at the end of this line remains to be processed.
6491 To put the next line at the specified line number,
6492 we must store a line number now that is one less. */
6493 new_lineno = atoi (bp) - 1;
6495 /* NEW_LINENO is one less than the actual line number here. */
6496 if (pedantic && new_lineno < 0)
6497 pedwarn ("line number out of range in `#line' directive");
6499 /* skip over the line number. */
6500 while (isdigit (*bp))
6503 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6504 if (*bp && !is_space[*bp]) {
6505 error ("invalid format `#line' directive");
6510 SKIP_WHITE_SPACE (bp);
6513 static HASHNODE *fname_table[FNAME_HASHSIZE];
6514 HASHNODE *hp, **hash_bucket;
6520 /* Turn the file name, which is a character string literal,
6521 into a null-terminated string. Do this in place. */
6524 switch ((*p++ = *bp++)) {
6526 error ("invalid format `#line' directive");
6531 char *bpc = (char *) bp;
6532 int c = parse_escape (&bpc);
6533 bp = (U_CHAR *) bpc;
6546 fname_length = p - fname;
6548 SKIP_WHITE_SPACE (bp);
6551 pedwarn ("garbage at end of `#line' directive");
6553 file_change = enter_file;
6554 else if (*bp == '2')
6555 file_change = leave_file;
6556 else if (*bp == '3')
6557 ip->system_header_p = 1;
6558 else if (*bp == '4')
6559 ip->system_header_p = 2;
6561 error ("invalid format `#line' directive");
6566 SKIP_WHITE_SPACE (bp);
6568 ip->system_header_p = 1;
6570 SKIP_WHITE_SPACE (bp);
6573 ip->system_header_p = 2;
6575 SKIP_WHITE_SPACE (bp);
6578 error ("invalid format `#line' directive");
6584 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6585 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6586 if (hp->length == fname_length &&
6587 strncmp (hp->value.cpval, fname, fname_length) == 0) {
6588 ip->nominal_fname = hp->value.cpval;
6592 /* Didn't find it; cons up a new one. */
6593 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6594 hp->next = *hash_bucket;
6597 hp->length = fname_length;
6598 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6599 bcopy (fname, hp->value.cpval, fname_length);
6602 error ("invalid format `#line' directive");
6606 ip->lineno = new_lineno;
6607 output_line_directive (ip, op, 0, file_change);
6608 check_expand (op, ip->length - (ip->bufp - ip->buf));
6613 * remove the definition of a symbol from the symbol table.
6614 * according to un*x /lib/cpp, it is not an error to undef
6615 * something that has no definitions, so it isn't one here either.
6619 do_undef (buf, limit, op, keyword)
6620 U_CHAR *buf, *limit;
6622 struct directive *keyword;
6626 U_CHAR *orig_buf = buf;
6628 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6629 if (pcp_outfile && op)
6630 pass_thru_directive (buf, limit, op, keyword);
6632 SKIP_WHITE_SPACE (buf);
6633 sym_length = check_macro_name (buf, "macro");
6635 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6636 /* If we are generating additional info for debugging (with -g) we
6637 need to pass through all effective #undef directives. */
6638 if (debug_output && op)
6639 pass_thru_directive (orig_buf, limit, op, keyword);
6640 if (hp->type != T_MACRO)
6641 warning ("undefining `%s'", hp->name);
6647 SKIP_WHITE_SPACE (buf);
6649 pedwarn ("garbage after `#undef' directive");
6655 * Report an error detected by the program we are processing.
6656 * Use the text of the line in the error message.
6657 * (We use error because it prints the filename & line#.)
6661 do_error (buf, limit, op, keyword)
6662 U_CHAR *buf, *limit;
6664 struct directive *keyword;
6666 int length = limit - buf;
6667 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6668 bcopy ((char *) buf, (char *) copy, length);
6670 SKIP_WHITE_SPACE (copy);
6671 error ("#error %s", copy);
6676 * Report a warning detected by the program we are processing.
6677 * Use the text of the line in the warning message, then continue.
6678 * (We use error because it prints the filename & line#.)
6682 do_warning (buf, limit, op, keyword)
6683 U_CHAR *buf, *limit;
6685 struct directive *keyword;
6687 int length = limit - buf;
6688 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6689 bcopy ((char *) buf, (char *) copy, length);
6691 SKIP_WHITE_SPACE (copy);
6692 warning ("#warning %s", copy);
6696 /* Remember the name of the current file being read from so that we can
6697 avoid ever including it again. */
6703 FILE_BUF *ip = NULL;
6705 for (i = indepth; i >= 0; i--)
6706 if (instack[i].fname != NULL) {
6712 struct file_name_list *new;
6714 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6715 new->next = dont_repeat_files;
6716 dont_repeat_files = new;
6717 new->fname = savestring (ip->fname);
6718 new->control_macro = 0;
6719 new->got_name_map = 0;
6720 new->c_system_include_path = 0;
6725 /* #ident has already been copied to the output file, so just ignore it. */
6728 do_ident (buf, limit)
6729 U_CHAR *buf, *limit;
6733 FILE_BUF *op = &outbuf;
6735 /* Allow #ident in system headers, since that's not user's fault. */
6736 if (pedantic && !instack[indepth].system_header_p)
6737 pedwarn ("ANSI C does not allow `#ident'");
6739 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6740 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6741 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6742 limit = buf + (trybuf.bufp - trybuf.buf);
6743 len = (limit - buf);
6746 /* Output directive name. */
6747 check_expand (op, 7);
6748 bcopy ("#ident ", (char *) op->bufp, 7);
6751 /* Output the expanded argument line. */
6752 check_expand (op, len);
6753 bcopy ((char *) buf, (char *) op->bufp, len);
6759 /* #pragma and its argument line have already been copied to the output file.
6760 Just check for some recognized pragmas that need validation here. */
6763 do_pragma (buf, limit)
6764 U_CHAR *buf, *limit;
6766 SKIP_WHITE_SPACE (buf);
6767 if (!strncmp (buf, "once", 4)) {
6768 /* Allow #pragma once in system headers, since that's not the user's
6770 if (!instack[indepth].system_header_p)
6771 warning ("`#pragma once' is obsolete");
6775 if (!strncmp (buf, "implementation", 14)) {
6776 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6777 been included yet. */
6778 struct file_name_list *ptr;
6779 U_CHAR *p = buf + 14, *fname, *inc_fname;
6780 SKIP_WHITE_SPACE (p);
6781 if (*p == '\n' || *p != '\"')
6785 if (p = (U_CHAR *) index (fname, '\"'))
6788 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6789 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6790 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6791 if (inc_fname && !strcmp (inc_fname, fname))
6792 warning ("`#pragma implementation' for `%s' appears after file is included",
6801 /* This was a fun hack, but #pragma seems to start to be useful.
6802 By failing to recognize it, we pass it through unchanged to cc1. */
6805 * the behavior of the #pragma directive is implementation defined.
6806 * this implementation defines it as follows.
6813 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6816 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6818 execl ("/usr/games/hack", "#pragma", 0);
6819 execl ("/usr/games/rogue", "#pragma", 0);
6820 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6821 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6823 fatal ("You are in a maze of twisty compiler features, all different");
6827 /* Just ignore #sccs, on systems where we define it at all. */
6833 pedwarn ("ANSI C does not allow `#sccs'");
6838 * handle #if directive by
6839 * 1) inserting special `defined' keyword into the hash table
6840 * that gets turned into 0 or 1 by special_symbol (thus,
6841 * if the luser has a symbol called `defined' already, it won't
6842 * work inside the #if directive)
6843 * 2) rescan the input into a temporary output buffer
6844 * 3) pass the output buffer to the yacc parser and collect a value
6845 * 4) clean up the mess left from steps 1 and 2.
6846 * 5) call conditional_skip to skip til the next #endif (etc.),
6847 * or not, depending on the value from step 3.
6851 do_if (buf, limit, op, keyword)
6852 U_CHAR *buf, *limit;
6854 struct directive *keyword;
6856 HOST_WIDE_INT value;
6857 FILE_BUF *ip = &instack[indepth];
6859 value = eval_if_expression (buf, limit - buf);
6860 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6865 * handle a #elif directive by not changing if_stack either.
6866 * see the comment above do_else.
6870 do_elif (buf, limit, op, keyword)
6871 U_CHAR *buf, *limit;
6873 struct directive *keyword;
6875 HOST_WIDE_INT value;
6876 FILE_BUF *ip = &instack[indepth];
6878 if (if_stack == instack[indepth].if_stack) {
6879 error ("`#elif' not within a conditional");
6882 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6883 error ("`#elif' after `#else'");
6884 fprintf (stderr, " (matches line %d", if_stack->lineno);
6885 if (if_stack->fname != NULL && ip->fname != NULL &&
6886 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6887 fprintf (stderr, ", file %s", if_stack->fname);
6888 fprintf (stderr, ")\n");
6890 if_stack->type = T_ELIF;
6893 if (if_stack->if_succeeded)
6894 skip_if_group (ip, 0, op);
6896 value = eval_if_expression (buf, limit - buf);
6898 skip_if_group (ip, 0, op);
6900 ++if_stack->if_succeeded; /* continue processing input */
6901 output_line_directive (ip, op, 1, same_file);
6908 * evaluate a #if expression in BUF, of length LENGTH,
6909 * then parse the result as a C expression and return the value as an int.
6911 static HOST_WIDE_INT
6912 eval_if_expression (buf, length)
6917 HASHNODE *save_defined;
6918 HOST_WIDE_INT value;
6920 save_defined = install ("defined", -1, T_SPEC_DEFINED, NULL_PTR, -1);
6922 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6924 delete_macro (save_defined); /* clean up special symbol */
6926 value = parse_c_expression (temp_obuf.buf);
6928 free (temp_obuf.buf);
6934 * routine to handle ifdef/ifndef. Try to look up the symbol,
6935 * then do or don't skip to the #endif/#else/#elif depending
6936 * on what directive is actually being processed.
6940 do_xifdef (buf, limit, op, keyword)
6941 U_CHAR *buf, *limit;
6943 struct directive *keyword;
6946 FILE_BUF *ip = &instack[indepth];
6948 int start_of_file = 0;
6949 U_CHAR *control_macro = 0;
6951 /* Detect a #ifndef at start of file (not counting comments). */
6952 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
6953 U_CHAR *p = ip->buf;
6954 while (p != directive_start) {
6958 /* Make no special provision for backslash-newline here; this is
6959 slower if backslash-newlines are present, but it's correct,
6960 and it's not worth it to tune for the rare backslash-newline. */
6962 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
6963 /* Skip this comment. */
6965 U_CHAR *save_bufp = ip->bufp;
6967 p = skip_to_end_of_comment (ip, &junk, 1);
6968 ip->bufp = save_bufp;
6973 /* If we get here, this conditional is the beginning of the file. */
6978 /* Discard leading and trailing whitespace. */
6979 SKIP_WHITE_SPACE (buf);
6980 while (limit != buf && is_hor_space[limit[-1]]) limit--;
6982 /* Find the end of the identifier at the beginning. */
6983 for (end = buf; is_idchar[*end]; end++);
6986 skip = (keyword->type == T_IFDEF);
6988 pedwarn (end == limit ? "`#%s' with no argument"
6989 : "`#%s' argument starts with punctuation",
6994 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
6995 pedwarn ("`#%s' argument starts with a digit", keyword->name);
6996 else if (end != limit && !traditional)
6997 pedwarn ("garbage at end of `#%s' argument", keyword->name);
6999 hp = lookup (buf, end-buf, -1);
7002 /* Output a precondition for this macro. */
7004 (hp->type == T_CONST
7005 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7006 fprintf (pcp_outfile, "#define %s\n", hp->name);
7009 fprintf (pcp_outfile, "#undef ");
7010 while (is_idchar[*cp]) /* Ick! */
7011 fputc (*cp++, pcp_outfile);
7012 putc ('\n', pcp_outfile);
7016 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7017 if (start_of_file && !skip) {
7018 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7019 bcopy ((char *) buf, (char *) control_macro, end - buf);
7020 control_macro[end - buf] = 0;
7024 conditional_skip (ip, skip, T_IF, control_macro, op);
7028 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7029 If this is a #ifndef starting at the beginning of a file,
7030 CONTROL_MACRO is the macro name tested by the #ifndef.
7031 Otherwise, CONTROL_MACRO is 0. */
7034 conditional_skip (ip, skip, type, control_macro, op)
7037 enum node_type type;
7038 U_CHAR *control_macro;
7041 IF_STACK_FRAME *temp;
7043 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7044 temp->fname = ip->nominal_fname;
7045 temp->lineno = ip->lineno;
7046 temp->next = if_stack;
7047 temp->control_macro = control_macro;
7050 if_stack->type = type;
7053 skip_if_group (ip, 0, op);
7056 ++if_stack->if_succeeded;
7057 output_line_directive (ip, &outbuf, 1, same_file);
7062 * skip to #endif, #else, or #elif. adjust line numbers, etc.
7063 * leaves input ptr at the sharp sign found.
7064 * If ANY is nonzero, return at next directive of any sort.
7067 skip_if_group (ip, any, op)
7072 register U_CHAR *bp = ip->bufp, *cp;
7073 register U_CHAR *endb = ip->buf + ip->length;
7074 struct directive *kt;
7075 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7076 U_CHAR *beg_of_line = bp;
7077 register int ident_length;
7078 U_CHAR *ident, *after_ident;
7079 /* Save info about where the group starts. */
7080 U_CHAR *beg_of_group = bp;
7081 int beg_lineno = ip->lineno;
7083 if (output_conditionals && op != 0) {
7084 char *ptr = "#failed\n";
7085 int len = strlen (ptr);
7087 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7092 check_expand (op, len);
7093 bcopy (ptr, (char *) op->bufp, len);
7096 output_line_directive (ip, op, 1, 0);
7101 case '/': /* possible comment */
7102 if (*bp == '\\' && bp[1] == '\n')
7105 || (cplusplus_comments && *bp == '/')) {
7107 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7112 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7113 NULL_PTR, NULL_PTR);
7116 /* Char after backslash loses its special meaning. */
7119 ++ip->lineno; /* But do update the line-count. */
7128 if (beg_of_line == 0 || traditional)
7131 while (bp[0] == '\\' && bp[1] == '\n')
7137 /* # keyword: a # must be first nonblank char on the line */
7138 if (beg_of_line == 0)
7142 /* Scan from start of line, skipping whitespace, comments
7143 and backslash-newlines, and see if we reach this #.
7144 If not, this # is not special. */
7146 /* If -traditional, require # to be at beginning of line. */
7149 if (is_hor_space[*bp])
7151 else if (*bp == '\\' && bp[1] == '\n')
7153 else if (*bp == '/' && bp[1] == '*') {
7155 while (!(*bp == '*' && bp[1] == '/'))
7159 /* There is no point in trying to deal with C++ // comments here,
7160 because if there is one, then this # must be part of the
7161 comment and we would never reach here. */
7165 if (bp != ip->bufp) {
7166 bp = ip->bufp + 1; /* Reset bp to after the #. */
7170 bp = ip->bufp + 1; /* Point after the '#' */
7171 if (ip->bufp[0] == '%') {
7172 /* Skip past the ':' again. */
7173 while (*bp == '\\') {
7180 /* Skip whitespace and \-newline. */
7182 if (is_hor_space[*bp])
7184 else if (*bp == '\\' && bp[1] == '\n')
7186 else if (*bp == '/' && bp[1] == '*') {
7188 while (!(*bp == '*' && bp[1] == '/')) {
7194 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
7196 while (bp[-1] == '\\' || *bp != '\n') {
7207 /* Now find end of directive name.
7208 If we encounter a backslash-newline, exchange it with any following
7209 symbol-constituents so that we end up with a contiguous name. */
7215 if (*bp == '\\' && bp[1] == '\n')
7216 name_newline_fix (bp);
7222 ident_length = bp - cp;
7226 /* A line of just `#' becomes blank. */
7228 if (ident_length == 0 && *after_ident == '\n') {
7232 if (ident_length == 0 || !is_idstart[*ident]) {
7234 while (is_idchar[*p]) {
7235 if (*p < '0' || *p > '9')
7239 /* Handle # followed by a line number. */
7240 if (p != ident && !is_idchar[*p]) {
7242 pedwarn ("`#' followed by integer");
7246 /* Avoid error for `###' and similar cases unless -pedantic. */
7248 while (*p == '#' || is_hor_space[*p]) p++;
7250 if (pedantic && !lang_asm)
7251 pedwarn ("invalid preprocessing directive");
7256 if (!lang_asm && pedantic)
7257 pedwarn ("invalid preprocessing directive name");
7261 for (kt = directive_table; kt->length >= 0; kt++) {
7262 IF_STACK_FRAME *temp;
7263 if (ident_length == kt->length
7264 && strncmp (cp, kt->name, kt->length) == 0) {
7265 /* If we are asked to return on next directive, do so now. */
7273 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7274 temp->next = if_stack;
7276 temp->lineno = ip->lineno;
7277 temp->fname = ip->nominal_fname;
7278 temp->type = kt->type;
7282 if (pedantic && if_stack != save_if_stack)
7285 if (if_stack == instack[indepth].if_stack) {
7286 error ("`#%s' not within a conditional", kt->name);
7289 else if (if_stack == save_if_stack)
7290 goto done; /* found what we came for */
7292 if (kt->type != T_ENDIF) {
7293 if (if_stack->type == T_ELSE)
7294 error ("`#else' or `#elif' after `#else'");
7295 if_stack->type = kt->type;
7300 if_stack = if_stack->next;
7307 /* Don't let erroneous code go by. */
7308 if (kt->length < 0 && !lang_asm && pedantic)
7309 pedwarn ("invalid preprocessing directive name");
7314 /* after this returns, rescan will exit because ip->bufp
7315 now points to the end of the buffer.
7316 rescan is responsible for the error message also. */
7319 if (output_conditionals && op != 0) {
7320 char *ptr = "#endfailed\n";
7321 int len = strlen (ptr);
7323 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7328 check_expand (op, beg_of_line - beg_of_group);
7329 bcopy ((char *) beg_of_group, (char *) op->bufp,
7330 beg_of_line - beg_of_group);
7331 op->bufp += beg_of_line - beg_of_group;
7332 op->lineno += ip->lineno - beg_lineno;
7333 check_expand (op, len);
7334 bcopy (ptr, (char *) op->bufp, len);
7341 * handle a #else directive. Do this by just continuing processing
7342 * without changing if_stack ; this is so that the error message
7343 * for missing #endif's etc. will point to the original #if. It
7344 * is possible that something different would be better.
7348 do_else (buf, limit, op, keyword)
7349 U_CHAR *buf, *limit;
7351 struct directive *keyword;
7353 FILE_BUF *ip = &instack[indepth];
7356 SKIP_WHITE_SPACE (buf);
7358 pedwarn ("text following `#else' violates ANSI standard");
7361 if (if_stack == instack[indepth].if_stack) {
7362 error ("`#else' not within a conditional");
7365 /* #ifndef can't have its special treatment for containing the whole file
7366 if it has a #else clause. */
7367 if_stack->control_macro = 0;
7369 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7370 error ("`#else' after `#else'");
7371 fprintf (stderr, " (matches line %d", if_stack->lineno);
7372 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7373 fprintf (stderr, ", file %s", if_stack->fname);
7374 fprintf (stderr, ")\n");
7376 if_stack->type = T_ELSE;
7379 if (if_stack->if_succeeded)
7380 skip_if_group (ip, 0, op);
7382 ++if_stack->if_succeeded; /* continue processing input */
7383 output_line_directive (ip, op, 1, same_file);
7389 * unstack after #endif directive
7393 do_endif (buf, limit, op, keyword)
7394 U_CHAR *buf, *limit;
7396 struct directive *keyword;
7399 SKIP_WHITE_SPACE (buf);
7401 pedwarn ("text following `#endif' violates ANSI standard");
7404 if (if_stack == instack[indepth].if_stack)
7405 error ("unbalanced `#endif'");
7407 IF_STACK_FRAME *temp = if_stack;
7408 if_stack = if_stack->next;
7409 if (temp->control_macro != 0) {
7410 /* This #endif matched a #ifndef at the start of the file.
7411 See if it is at the end of the file. */
7412 FILE_BUF *ip = &instack[indepth];
7413 U_CHAR *p = ip->bufp;
7414 U_CHAR *ep = ip->buf + ip->length;
7420 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7421 /* Skip this comment. */
7423 U_CHAR *save_bufp = ip->bufp;
7425 p = skip_to_end_of_comment (ip, &junk, 1);
7426 ip->bufp = save_bufp;
7431 /* If we get here, this #endif ends a #ifndef
7432 that contains all of the file (aside from whitespace).
7433 Arrange not to include the file again
7434 if the macro that was tested is defined.
7436 Do not do this for the top-level file in a -include or any
7437 file in a -imacros. */
7439 && ! (indepth == 1 && no_record_file)
7440 && ! (no_record_file && no_output))
7441 record_control_macro (ip->fname, temp->control_macro);
7445 output_line_directive (&instack[indepth], op, 1, same_file);
7450 /* When an #else or #endif is found while skipping failed conditional,
7451 if -pedantic was specified, this is called to warn about text after
7452 the directive name. P points to the first char after the directive name. */
7458 /* Advance P over whitespace and comments. */
7460 if (*p == '\\' && p[1] == '\n')
7462 if (is_hor_space[*p])
7464 else if (*p == '/') {
7465 if (p[1] == '\\' && p[2] == '\n')
7466 newline_fix (p + 1);
7469 /* Don't bother warning about unterminated comments
7470 since that will happen later. Just be sure to exit. */
7472 if (p[1] == '\\' && p[2] == '\n')
7473 newline_fix (p + 1);
7474 if (*p == '*' && p[1] == '/') {
7481 else if (cplusplus_comments && p[1] == '/') {
7483 while (*p && (*p != '\n' || p[-1] == '\\'))
7488 if (*p && *p != '\n')
7489 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7492 /* Skip a comment, assuming the input ptr immediately follows the
7493 initial slash-star. Bump *LINE_COUNTER for each newline.
7494 (The canonical line counter is &ip->lineno.)
7495 Don't use this routine (or the next one) if bumping the line
7496 counter is not sufficient to deal with newlines in the string.
7498 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7499 This feature is useful when processing a comment that is going to be
7500 processed or was processed at another point in the preprocessor,
7501 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7504 skip_to_end_of_comment (ip, line_counter, nowarn)
7505 register FILE_BUF *ip;
7506 int *line_counter; /* place to remember newlines, or NULL */
7509 register U_CHAR *limit = ip->buf + ip->length;
7510 register U_CHAR *bp = ip->bufp;
7511 FILE_BUF *op = &outbuf; /* JF */
7512 int output = put_out_comments && !line_counter;
7513 int start_line = line_counter ? *line_counter : 0;
7515 /* JF this line_counter stuff is a crock to make sure the
7516 comment is only put out once, no matter how many times
7517 the comment is skipped. It almost works */
7522 if (cplusplus_comments && bp[-1] == '/') {
7524 while (bp < limit) {
7526 if (*bp == '\n' && bp[-1] != '\\')
7538 while (bp < limit) {
7539 if (bp[-1] != '\\' && *bp == '\n') {
7542 if (*bp == '\n' && line_counter)
7551 while (bp < limit) {
7556 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7557 warning ("`/*' within comment");
7560 /* If this is the end of the file, we have an unterminated comment.
7561 Don't swallow the newline. We are guaranteed that there will be a
7562 trailing newline and various pieces assume it's there. */
7569 if (line_counter != NULL)
7575 if (*bp == '\\' && bp[1] == '\n')
7588 error_with_line (line_for_error (start_line), "unterminated comment");
7594 * Skip over a quoted string. BP points to the opening quote.
7595 * Returns a pointer after the closing quote. Don't go past LIMIT.
7596 * START_LINE is the line number of the starting point (but it need
7597 * not be valid if the starting point is inside a macro expansion).
7599 * The input stack state is not changed.
7601 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7602 * for each newline passed.
7604 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7605 * if we pass a backslash-newline.
7607 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7610 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7611 register U_CHAR *bp;
7612 register U_CHAR *limit;
7614 int *count_newlines;
7615 int *backslash_newlines_p;
7618 register U_CHAR c, match;
7623 error_with_line (line_for_error (start_line),
7624 "unterminated string or character constant");
7625 error_with_line (multiline_string_line,
7626 "possible real start of unterminated constant");
7627 multiline_string_line = 0;
7634 while (*bp == '\\' && bp[1] == '\n') {
7635 if (backslash_newlines_p)
7636 *backslash_newlines_p = 1;
7641 if (*bp == '\n' && count_newlines) {
7642 if (backslash_newlines_p)
7643 *backslash_newlines_p = 1;
7647 } else if (c == '\n') {
7649 /* Unterminated strings and character constants are 'valid'. */
7650 bp--; /* Don't consume the newline. */
7655 if (pedantic || match == '\'') {
7656 error_with_line (line_for_error (start_line),
7657 "unterminated string or character constant");
7663 /* If not traditional, then allow newlines inside strings. */
7666 if (multiline_string_line == 0)
7667 multiline_string_line = start_line;
7668 } else if (c == match)
7674 /* Place into DST a quoted string representing the string SRC.
7675 Return the address of DST's terminating null. */
7677 quote_string (dst, src)
7684 switch ((c = *src++))
7691 sprintf (dst, "\\%03o", c);
7709 /* Skip across a group of balanced parens, starting from IP->bufp.
7710 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7712 This does not handle newlines, because it's used for the arg of #if,
7713 where there aren't any newlines. Also, backslash-newline can't appear. */
7716 skip_paren_group (ip)
7717 register FILE_BUF *ip;
7719 U_CHAR *limit = ip->buf + ip->length;
7720 U_CHAR *p = ip->bufp;
7722 int lines_dummy = 0;
7724 while (p != limit) {
7734 return ip->bufp = p;
7740 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7748 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7750 return ip->bufp = p;
7761 * write out a #line directive, for instance, after an #include file.
7762 * If CONDITIONAL is nonzero, we can omit the #line if it would
7763 * appear to be a no-op, and we can output a few newlines instead
7764 * if we want to increase the line number by a small amount.
7765 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7769 output_line_directive (ip, op, conditional, file_change)
7772 enum file_change_code file_change;
7775 char *line_directive_buf, *line_end;
7777 if (no_line_directives
7778 || ip->fname == NULL
7780 op->lineno = ip->lineno;
7785 if (ip->lineno == op->lineno)
7788 /* If the inherited line number is a little too small,
7789 output some newlines instead of a #line directive. */
7790 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7791 check_expand (op, 10);
7792 while (ip->lineno > op->lineno) {
7800 /* Don't output a line number of 0 if we can help it. */
7801 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7802 && *ip->bufp == '\n') {
7807 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7808 sprintf (line_directive_buf, "# %d ", ip->lineno);
7809 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7811 if (file_change != same_file) {
7813 *line_end++ = file_change == enter_file ? '1' : '2';
7815 /* Tell cc1 if following text comes from a system header file. */
7816 if (ip->system_header_p) {
7820 #ifndef NO_IMPLICIT_EXTERN_C
7821 /* Tell cc1plus if following text should be treated as C. */
7822 if (ip->system_header_p == 2 && cplusplus) {
7828 len = line_end - line_directive_buf;
7829 check_expand (op, len + 1);
7830 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7832 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7834 op->lineno = ip->lineno;
7837 /* This structure represents one parsed argument in a macro call.
7838 `raw' points to the argument text as written (`raw_length' is its length).
7839 `expanded' points to the argument's macro-expansion
7840 (its length is `expand_length').
7841 `stringified_length' is the length the argument would have
7843 `use_count' is the number of times this macro arg is substituted
7844 into the macro. If the actual use count exceeds 10,
7845 the value stored is 10.
7846 `free1' and `free2', if nonzero, point to blocks to be freed
7847 when the macro argument data is no longer needed. */
7850 U_CHAR *raw, *expanded;
7851 int raw_length, expand_length;
7852 int stringified_length;
7853 U_CHAR *free1, *free2;
7859 /* Expand a macro call.
7860 HP points to the symbol that is the macro being called.
7861 Put the result of expansion onto the input stack
7862 so that subsequent input by our caller will use it.
7864 If macro wants arguments, caller has already verified that
7865 an argument list follows; arguments come from the input stack. */
7868 macroexpand (hp, op)
7873 DEFINITION *defn = hp->value.defn;
7874 register U_CHAR *xbuf;
7876 int start_line = instack[indepth].lineno;
7877 int rest_args, rest_zero;
7879 CHECK_DEPTH (return;);
7881 /* it might not actually be a macro. */
7882 if (hp->type != T_MACRO) {
7883 special_symbol (hp, op);
7887 /* This macro is being used inside a #if, which means it must be */
7888 /* recorded as a precondition. */
7889 if (pcp_inside_if && pcp_outfile && defn->predefined)
7890 dump_single_macro (hp, pcp_outfile);
7892 nargs = defn->nargs;
7896 struct argdata *args;
7897 char *parse_error = 0;
7899 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7901 for (i = 0; i < nargs; i++) {
7902 args[i].raw = (U_CHAR *) "";
7903 args[i].expanded = 0;
7904 args[i].raw_length = args[i].expand_length
7905 = args[i].stringified_length = 0;
7906 args[i].free1 = args[i].free2 = 0;
7907 args[i].use_count = 0;
7910 /* Parse all the macro args that are supplied. I counts them.
7911 The first NARGS args are stored in ARGS.
7912 The rest are discarded.
7913 If rest_args is set then we assume macarg absorbed the rest of the args.
7918 /* Discard the open-parenthesis or comma before the next arg. */
7919 ++instack[indepth].bufp;
7922 if (i < nargs || (nargs == 0 && i == 0)) {
7923 /* if we are working on last arg which absorbs rest of args... */
7924 if (i == nargs - 1 && defn->rest_args)
7926 parse_error = macarg (&args[i], rest_args);
7929 parse_error = macarg (NULL_PTR, 0);
7931 error_with_line (line_for_error (start_line), parse_error);
7935 } while (*instack[indepth].bufp != ')');
7937 /* If we got one arg but it was just whitespace, call that 0 args. */
7939 register U_CHAR *bp = args[0].raw;
7940 register U_CHAR *lim = bp + args[0].raw_length;
7941 /* cpp.texi says for foo ( ) we provide one argument.
7942 However, if foo wants just 0 arguments, treat this as 0. */
7944 while (bp != lim && is_space[*bp]) bp++;
7949 /* Don't output an error message if we have already output one for
7950 a parse error above. */
7952 if (nargs == 0 && i > 0) {
7954 error ("arguments given to macro `%s'", hp->name);
7955 } else if (i < nargs) {
7956 /* traditional C allows foo() if foo wants one argument. */
7957 if (nargs == 1 && i == 0 && traditional)
7959 /* the rest args token is allowed to absorb 0 tokens */
7960 else if (i == nargs - 1 && defn->rest_args)
7962 else if (parse_error)
7965 error ("macro `%s' used without args", hp->name);
7967 error ("macro `%s' used with just one arg", hp->name);
7969 error ("macro `%s' used with only %d args", hp->name, i);
7970 } else if (i > nargs) {
7972 error ("macro `%s' used with too many (%d) args", hp->name, i);
7975 /* Swallow the closeparen. */
7976 ++instack[indepth].bufp;
7978 /* If macro wants zero args, we parsed the arglist for checking only.
7979 Read directly from the macro definition. */
7981 xbuf = defn->expansion;
7982 xbuf_len = defn->length;
7984 register U_CHAR *exp = defn->expansion;
7985 register int offset; /* offset in expansion,
7986 copied a piece at a time */
7987 register int totlen; /* total amount of exp buffer filled so far */
7989 register struct reflist *ap, *last_ap;
7991 /* Macro really takes args. Compute the expansion of this call. */
7993 /* Compute length in characters of the macro's expansion.
7994 Also count number of times each arg is used. */
7995 xbuf_len = defn->length;
7996 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
7998 xbuf_len += args[ap->argno].stringified_length;
7999 else if (ap->raw_before || ap->raw_after || traditional)
8000 /* Add 4 for two newline-space markers to prevent
8001 token concatenation. */
8002 xbuf_len += args[ap->argno].raw_length + 4;
8004 /* We have an ordinary (expanded) occurrence of the arg.
8005 So compute its expansion, if we have not already. */
8006 if (args[ap->argno].expanded == 0) {
8008 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8009 args[ap->argno].raw + args[ap->argno].raw_length,
8012 args[ap->argno].expanded = obuf.buf;
8013 args[ap->argno].expand_length = obuf.length;
8014 args[ap->argno].free2 = obuf.buf;
8017 /* Add 4 for two newline-space markers to prevent
8018 token concatenation. */
8019 xbuf_len += args[ap->argno].expand_length + 4;
8021 if (args[ap->argno].use_count < 10)
8022 args[ap->argno].use_count++;
8025 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8027 /* Generate in XBUF the complete expansion
8028 with arguments substituted in.
8029 TOTLEN is the total size generated so far.
8030 OFFSET is the index in the definition
8031 of where we are copying from. */
8032 offset = totlen = 0;
8033 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8034 last_ap = ap, ap = ap->next) {
8035 register struct argdata *arg = &args[ap->argno];
8036 int count_before = totlen;
8038 /* Add chars to XBUF. */
8039 for (i = 0; i < ap->nchars; i++, offset++)
8040 xbuf[totlen++] = exp[offset];
8042 /* If followed by an empty rest arg with concatenation,
8043 delete the last run of nonwhite chars. */
8044 if (rest_zero && totlen > count_before
8045 && ((ap->rest_args && ap->raw_before)
8046 || (last_ap != NULL && last_ap->rest_args
8047 && last_ap->raw_after))) {
8048 /* Delete final whitespace. */
8049 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8053 /* Delete the nonwhites before them. */
8054 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8059 if (ap->stringify != 0) {
8060 int arglen = arg->raw_length;
8066 && (c = arg->raw[i], is_space[c]))
8069 && (c = arg->raw[arglen - 1], is_space[c]))
8072 xbuf[totlen++] = '\"'; /* insert beginning quote */
8073 for (; i < arglen; i++) {
8076 /* Special markers Newline Space
8077 generate nothing for a stringified argument. */
8078 if (c == '\n' && arg->raw[i+1] != '\n') {
8083 /* Internal sequences of whitespace are replaced by one space
8084 except within an string or char token. */
8086 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8088 /* Note that Newline Space does occur within whitespace
8089 sequences; consider it part of the sequence. */
8090 if (c == '\n' && is_space[arg->raw[i+1]])
8092 else if (c != '\n' && is_space[c])
8109 } else if (c == '\"' || c == '\'')
8113 /* Escape these chars */
8114 if (c == '\"' || (in_string && c == '\\'))
8115 xbuf[totlen++] = '\\';
8119 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8124 xbuf[totlen++] = '\"'; /* insert ending quote */
8125 } else if (ap->raw_before || ap->raw_after || traditional) {
8126 U_CHAR *p1 = arg->raw;
8127 U_CHAR *l1 = p1 + arg->raw_length;
8128 if (ap->raw_before) {
8129 while (p1 != l1 && is_space[*p1]) p1++;
8130 while (p1 != l1 && is_idchar[*p1])
8131 xbuf[totlen++] = *p1++;
8132 /* Delete any no-reexpansion marker that follows
8133 an identifier at the beginning of the argument
8134 if the argument is concatenated with what precedes it. */
8135 if (p1[0] == '\n' && p1[1] == '-')
8137 } else if (!traditional) {
8138 /* Ordinary expanded use of the argument.
8139 Put in newline-space markers to prevent token pasting. */
8140 xbuf[totlen++] = '\n';
8141 xbuf[totlen++] = ' ';
8143 if (ap->raw_after) {
8144 /* Arg is concatenated after: delete trailing whitespace,
8145 whitespace markers, and no-reexpansion markers. */
8147 if (is_space[l1[-1]]) l1--;
8148 else if (l1[-1] == '-') {
8149 U_CHAR *p2 = l1 - 1;
8150 /* If a `-' is preceded by an odd number of newlines then it
8151 and the last newline are a no-reexpansion marker. */
8152 while (p2 != p1 && p2[-1] == '\n') p2--;
8153 if ((l1 - 1 - p2) & 1) {
8162 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8164 if (!traditional && !ap->raw_after) {
8165 /* Ordinary expanded use of the argument.
8166 Put in newline-space markers to prevent token pasting. */
8167 xbuf[totlen++] = '\n';
8168 xbuf[totlen++] = ' ';
8171 /* Ordinary expanded use of the argument.
8172 Put in newline-space markers to prevent token pasting. */
8174 xbuf[totlen++] = '\n';
8175 xbuf[totlen++] = ' ';
8177 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8178 arg->expand_length);
8179 totlen += arg->expand_length;
8181 xbuf[totlen++] = '\n';
8182 xbuf[totlen++] = ' ';
8184 /* If a macro argument with newlines is used multiple times,
8185 then only expand the newlines once. This avoids creating output
8186 lines which don't correspond to any input line, which confuses
8188 if (arg->use_count > 1 && arg->newlines > 0) {
8189 /* Don't bother doing change_newlines for subsequent
8193 = change_newlines (arg->expanded, arg->expand_length);
8197 if (totlen > xbuf_len)
8201 /* if there is anything left of the definition
8202 after handling the arg list, copy that in too. */
8204 for (i = offset; i < defn->length; i++) {
8205 /* if we've reached the end of the macro */
8208 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8209 && last_ap->raw_after))
8210 xbuf[totlen++] = exp[i];
8216 for (i = 0; i < nargs; i++) {
8217 if (args[i].free1 != 0)
8218 free (args[i].free1);
8219 if (args[i].free2 != 0)
8220 free (args[i].free2);
8224 xbuf = defn->expansion;
8225 xbuf_len = defn->length;
8228 /* Now put the expansion on the input stack
8229 so our caller will commence reading from it. */
8231 register FILE_BUF *ip2;
8233 ip2 = &instack[++indepth];
8236 ip2->nominal_fname = 0;
8237 /* This may not be exactly correct, but will give much better error
8238 messages for nested macro calls than using a line number of zero. */
8239 ip2->lineno = start_line;
8241 ip2->length = xbuf_len;
8243 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8245 ip2->if_stack = if_stack;
8246 ip2->system_header_p = 0;
8248 /* Recursive macro use sometimes works traditionally.
8249 #define foo(x,y) bar (x (y,0), y)
8253 hp->type = T_DISABLED;
8258 * Parse a macro argument and store the info on it into *ARGPTR.
8259 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8260 * Return nonzero to indicate a syntax error.
8264 macarg (argptr, rest_args)
8265 register struct argdata *argptr;
8268 FILE_BUF *ip = &instack[indepth];
8273 /* Try to parse as much of the argument as exists at this
8274 input stack level. */
8275 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8276 &paren, &newlines, &comments, rest_args);
8278 /* If we find the end of the argument at this level,
8279 set up *ARGPTR to point at it in the input stack. */
8280 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8281 && bp != ip->buf + ip->length) {
8283 argptr->raw = ip->bufp;
8284 argptr->raw_length = bp - ip->bufp;
8285 argptr->newlines = newlines;
8289 /* This input stack level ends before the macro argument does.
8290 We must pop levels and keep parsing.
8291 Therefore, we must allocate a temporary buffer and copy
8292 the macro argument into it. */
8293 int bufsize = bp - ip->bufp;
8294 int extra = newlines;
8295 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8296 int final_start = 0;
8298 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8300 ip->lineno += newlines;
8302 while (bp == ip->buf + ip->length) {
8303 if (instack[indepth].macro == 0) {
8305 return "unterminated macro call";
8307 ip->macro->type = T_MACRO;
8309 free (ip->free_ptr);
8310 ip = &instack[--indepth];
8313 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8314 &newlines, &comments, rest_args);
8315 final_start = bufsize;
8316 bufsize += bp - ip->bufp;
8318 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8319 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8322 ip->lineno += newlines;
8325 /* Now, if arg is actually wanted, record its raw form,
8326 discarding comments and duplicating newlines in whatever
8327 part of it did not come from a macro expansion.
8328 EXTRA space has been preallocated for duplicating the newlines.
8329 FINAL_START is the index of the start of that part. */
8331 argptr->raw = buffer;
8332 argptr->raw_length = bufsize;
8333 argptr->free1 = buffer;
8334 argptr->newlines = newlines;
8335 argptr->comments = comments;
8336 if ((newlines || comments) && ip->fname != 0)
8339 discard_comments (argptr->raw + final_start,
8340 argptr->raw_length - final_start,
8342 argptr->raw[argptr->raw_length] = 0;
8343 if (argptr->raw_length > bufsize + extra)
8348 /* If we are not discarding this argument,
8349 macroexpand it and compute its length as stringified.
8350 All this info goes into *ARGPTR. */
8353 register U_CHAR *buf, *lim;
8354 register int totlen;
8357 lim = buf + argptr->raw_length;
8359 while (buf != lim && is_space[*buf])
8361 while (buf != lim && is_space[lim[-1]])
8363 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8364 while (buf != lim) {
8365 register U_CHAR c = *buf++;
8367 /* Internal sequences of whitespace are replaced by one space
8368 in most cases, but not always. So count all the whitespace
8369 in case we need to keep it all. */
8372 SKIP_ALL_WHITE_SPACE (buf);
8375 if (c == '\"' || c == '\\') /* escape these chars */
8377 else if (!isprint (c))
8380 argptr->stringified_length = totlen;
8385 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8386 counting parens in *DEPTHPTR,
8387 and return if reach LIMIT
8388 or before a `)' that would make *DEPTHPTR negative
8389 or before a comma when *DEPTHPTR is zero.
8390 Single and double quotes are matched and termination
8391 is inhibited within them. Comments also inhibit it.
8392 Value returned is pointer to stopping place.
8394 Increment *NEWLINES each time a newline is passed.
8395 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8396 Set *COMMENTS to 1 if a comment is seen. */
8399 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8401 register U_CHAR *limit;
8402 int *depthptr, *newlines, *comments;
8405 register U_CHAR *bp = start;
8407 while (bp < limit) {
8413 if (--(*depthptr) < 0)
8417 /* Traditionally, backslash makes following char not special. */
8418 if (bp + 1 < limit && traditional)
8421 /* But count source lines anyway. */
8430 if (bp[1] == '\\' && bp[2] == '\n')
8431 newline_fix (bp + 1);
8432 if (cplusplus_comments && bp[1] == '/') {
8435 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8436 if (*bp == '\n') ++*newlines;
8439 /* Now count the newline that we are about to skip. */
8443 if (bp[1] != '*' || bp + 1 >= limit)
8447 while (bp + 1 < limit) {
8449 && bp[1] == '\\' && bp[2] == '\n')
8450 newline_fix (bp + 1);
8451 if (bp[0] == '*' && bp[1] == '/')
8453 if (*bp == '\n') ++*newlines;
8461 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8466 while (*bp == '\\' && bp[1] == '\n') {
8469 } else if (*bp == '\n') {
8478 /* if we've returned to lowest level and we aren't absorbing all args */
8479 if ((*depthptr) == 0 && rest_args == 0)
8489 /* Discard comments and duplicate newlines
8490 in the string of length LENGTH at START,
8491 except inside of string constants.
8492 The string is copied into itself with its beginning staying fixed.
8494 NEWLINES is the number of newlines that must be duplicated.
8495 We assume that that much extra space is available past the end
8499 discard_comments (start, length, newlines)
8504 register U_CHAR *ibp;
8505 register U_CHAR *obp;
8506 register U_CHAR *limit;
8509 /* If we have newlines to duplicate, copy everything
8510 that many characters up. Then, in the second part,
8511 we will have room to insert the newlines
8513 NEWLINES may actually be too large, because it counts
8514 newlines in string constants, and we don't duplicate those.
8515 But that does no harm. */
8517 ibp = start + length;
8518 obp = ibp + newlines;
8520 while (limit != ibp)
8524 ibp = start + newlines;
8525 limit = start + length + newlines;
8528 while (ibp < limit) {
8529 *obp++ = c = *ibp++;
8532 /* Duplicate the newline. */
8544 if (*ibp == '\\' && ibp[1] == '\n')
8546 /* Delete any comment. */
8547 if (cplusplus_comments && ibp[0] == '/') {
8548 /* Comments are equivalent to spaces. */
8551 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8555 if (ibp[0] != '*' || ibp + 1 >= limit)
8557 /* Comments are equivalent to spaces.
8558 For -traditional, a comment is equivalent to nothing. */
8564 while (ibp + 1 < limit) {
8566 && ibp[1] == '\\' && ibp[2] == '\n')
8567 newline_fix (ibp + 1);
8568 if (ibp[0] == '*' && ibp[1] == '/')
8577 /* Notice and skip strings, so that we don't
8578 think that comments start inside them,
8579 and so we don't duplicate newlines in them. */
8582 while (ibp < limit) {
8583 *obp++ = c = *ibp++;
8586 if (c == '\n' && quotec == '\'')
8588 if (c == '\\' && ibp < limit) {
8589 while (*ibp == '\\' && ibp[1] == '\n')
8602 /* Turn newlines to spaces in the string of length LENGTH at START,
8603 except inside of string constants.
8604 The string is copied into itself with its beginning staying fixed. */
8607 change_newlines (start, length)
8611 register U_CHAR *ibp;
8612 register U_CHAR *obp;
8613 register U_CHAR *limit;
8617 limit = start + length;
8620 while (ibp < limit) {
8621 *obp++ = c = *ibp++;
8624 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8625 string. Skip past the newline and its duplicate.
8626 Put a space in the output. */
8637 /* Notice and skip strings, so that we don't delete newlines in them. */
8640 while (ibp < limit) {
8641 *obp++ = c = *ibp++;
8644 if (c == '\n' && quotec == '\'')
8656 * my_strerror - return the descriptive text associated with an `errno' code.
8660 my_strerror (errnum)
8666 #ifndef HAVE_STRERROR
8667 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8669 result = strerror (errnum);
8672 /* VAXCRTL's strerror() takes an optional second argument, which only
8673 matters when the first argument is EVMSERR. However, it's simplest
8674 just to pass it unconditionally. `vaxc$errno' is declared in
8675 <errno.h>, and maintained by the library in parallel with `errno'.
8676 We assume that caller's `errnum' either matches the last setting of
8677 `errno' by the library or else does not have the value `EVMSERR'. */
8679 result = strerror (errnum, vaxc$errno);
8683 result = "undocumented I/O error";
8689 * error - print error message and increment count of errors.
8693 error (msg, arg1, arg2, arg3)
8695 char *arg1, *arg2, *arg3;
8698 FILE_BUF *ip = NULL;
8700 print_containing_files ();
8702 for (i = indepth; i >= 0; i--)
8703 if (instack[i].fname != NULL) {
8709 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8710 fprintf (stderr, msg, arg1, arg2, arg3);
8711 fprintf (stderr, "\n");
8715 /* Error including a message from `errno'. */
8718 error_from_errno (name)
8722 FILE_BUF *ip = NULL;
8724 print_containing_files ();
8726 for (i = indepth; i >= 0; i--)
8727 if (instack[i].fname != NULL) {
8733 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8735 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8740 /* Print error message but don't count it. */
8743 warning (msg, arg1, arg2, arg3)
8745 char *arg1, *arg2, *arg3;
8748 FILE_BUF *ip = NULL;
8750 if (inhibit_warnings)
8753 if (warnings_are_errors)
8756 print_containing_files ();
8758 for (i = indepth; i >= 0; i--)
8759 if (instack[i].fname != NULL) {
8765 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8766 fprintf (stderr, "warning: ");
8767 fprintf (stderr, msg, arg1, arg2, arg3);
8768 fprintf (stderr, "\n");
8772 error_with_line (line, msg, arg1, arg2, arg3)
8775 char *arg1, *arg2, *arg3;
8778 FILE_BUF *ip = NULL;
8780 print_containing_files ();
8782 for (i = indepth; i >= 0; i--)
8783 if (instack[i].fname != NULL) {
8789 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8790 fprintf (stderr, msg, arg1, arg2, arg3);
8791 fprintf (stderr, "\n");
8796 warning_with_line (line, msg, arg1, arg2, arg3)
8799 char *arg1, *arg2, *arg3;
8802 FILE_BUF *ip = NULL;
8804 if (inhibit_warnings)
8807 if (warnings_are_errors)
8810 print_containing_files ();
8812 for (i = indepth; i >= 0; i--)
8813 if (instack[i].fname != NULL) {
8819 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8820 fprintf (stderr, "warning: ");
8821 fprintf (stderr, msg, arg1, arg2, arg3);
8822 fprintf (stderr, "\n");
8825 /* print an error message and maybe count it. */
8828 pedwarn (msg, arg1, arg2, arg3)
8830 char *arg1, *arg2, *arg3;
8832 if (pedantic_errors)
8833 error (msg, arg1, arg2, arg3);
8835 warning (msg, arg1, arg2, arg3);
8839 pedwarn_with_line (line, msg, arg1, arg2, arg3)
8842 char *arg1, *arg2, *arg3;
8844 if (pedantic_errors)
8845 error_with_line (line, msg, arg1, arg2, arg3);
8847 warning_with_line (line, msg, arg1, arg2, arg3);
8850 /* Report a warning (or an error if pedantic_errors)
8851 giving specified file name and line number, not current. */
8854 pedwarn_with_file_and_line (file, line, msg, arg1, arg2, arg3)
8858 char *arg1, *arg2, *arg3;
8860 if (!pedantic_errors && inhibit_warnings)
8863 fprintf (stderr, "%s:%d: ", file, line);
8864 if (pedantic_errors)
8866 if (!pedantic_errors)
8867 fprintf (stderr, "warning: ");
8868 fprintf (stderr, msg, arg1, arg2, arg3);
8869 fprintf (stderr, "\n");
8872 /* Print the file names and line numbers of the #include
8873 directives which led to the current file. */
8876 print_containing_files ()
8878 FILE_BUF *ip = NULL;
8882 /* If stack of files hasn't changed since we last printed
8883 this info, don't repeat it. */
8884 if (last_error_tick == input_file_stack_tick)
8887 for (i = indepth; i >= 0; i--)
8888 if (instack[i].fname != NULL) {
8893 /* Give up if we don't find a source file. */
8897 /* Find the other, outer source files. */
8898 for (i--; i >= 0; i--)
8899 if (instack[i].fname != NULL) {
8903 fprintf (stderr, "In file included");
8905 fprintf (stderr, ",\n ");
8908 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
8911 fprintf (stderr, ":\n");
8913 /* Record we have printed the status as of this time. */
8914 last_error_tick = input_file_stack_tick;
8917 /* Return the line at which an error occurred.
8918 The error is not necessarily associated with the current spot
8919 in the input stack, so LINE says where. LINE will have been
8920 copied from ip->lineno for the current input level.
8921 If the current level is for a file, we return LINE.
8922 But if the current level is not for a file, LINE is meaningless.
8923 In that case, we return the lineno of the innermost file. */
8926 line_for_error (line)
8932 for (i = indepth; i >= 0; ) {
8933 if (instack[i].fname != 0)
8938 line1 = instack[i].lineno;
8946 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
8948 * As things stand, nothing is ever placed in the output buffer to be
8949 * removed again except when it's KNOWN to be part of an identifier,
8950 * so flushing and moving down everything left, instead of expanding,
8954 /* You might think void was cleaner for the return type,
8955 but that would get type mismatch in check_expand in strict ANSI. */
8957 grow_outbuf (obuf, needed)
8958 register FILE_BUF *obuf;
8959 register int needed;
8964 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
8967 /* Make it at least twice as big as it is now. */
8969 /* Make it have at least 150% of the free space we will need. */
8970 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
8971 if (minsize > obuf->length)
8972 obuf->length = minsize;
8974 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
8977 obuf->bufp = p + (obuf->bufp - obuf->buf);
8983 /* Symbol table for macro names and special symbols */
8986 * install a name in the main hash table, even if it is already there.
8987 * name stops with first non alphanumeric, except leading '#'.
8988 * caller must check against redefinition if that is desired.
8989 * delete_macro () removes things installed by install () in fifo order.
8990 * this is important because of the `defined' special symbol used
8991 * in #if, and also if pushdef/popdef directives are ever implemented.
8993 * If LEN is >= 0, it is the length of the name.
8994 * Otherwise, compute the length by scanning the entire name.
8996 * If HASH is >= 0, it is the precomputed hash code.
8997 * Otherwise, compute the hash code.
9000 install (name, len, type, value, hash)
9003 enum node_type type;
9007 register HASHNODE *hp;
9008 register int i, bucket;
9009 register U_CHAR *p, *q;
9013 while (is_idchar[*p])
9019 hash = hashf (name, len, HASHSIZE);
9021 i = sizeof (HASHNODE) + len + 1;
9022 hp = (HASHNODE *) xmalloc (i);
9024 hp->bucket_hdr = &hashtab[bucket];
9025 hp->next = hashtab[bucket];
9026 hashtab[bucket] = hp;
9028 if (hp->next != NULL)
9029 hp->next->prev = hp;
9032 hp->value.cpval = value;
9033 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9036 for (i = 0; i < len; i++)
9043 * find the most recent hash node for name name (ending with first
9044 * non-identifier char) installed by install
9046 * If LEN is >= 0, it is the length of the name.
9047 * Otherwise, compute the length by scanning the entire name.
9049 * If HASH is >= 0, it is the precomputed hash code.
9050 * Otherwise, compute the hash code.
9053 lookup (name, len, hash)
9058 register U_CHAR *bp;
9059 register HASHNODE *bucket;
9062 for (bp = name; is_idchar[*bp]; bp++) ;
9067 hash = hashf (name, len, HASHSIZE);
9069 bucket = hashtab[hash];
9071 if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
9073 bucket = bucket->next;
9079 * Delete a hash node. Some weirdness to free junk from macros.
9080 * More such weirdness will have to be added if you define more hash
9081 * types that need it.
9084 /* Note that the DEFINITION of a macro is removed from the hash table
9085 but its storage is not freed. This would be a storage leak
9086 except that it is not reasonable to keep undefining and redefining
9087 large numbers of macros many times.
9088 In any case, this is necessary, because a macro can be #undef'd
9089 in the middle of reading the arguments to a call to it.
9090 If #undef freed the DEFINITION, that would crash. */
9097 if (hp->prev != NULL)
9098 hp->prev->next = hp->next;
9099 if (hp->next != NULL)
9100 hp->next->prev = hp->prev;
9102 /* make sure that the bucket chain header that
9103 the deleted guy was on points to the right thing afterwards. */
9104 if (hp == *hp->bucket_hdr)
9105 *hp->bucket_hdr = hp->next;
9108 if (hp->type == T_MACRO) {
9109 DEFINITION *d = hp->value.defn;
9110 struct reflist *ap, *nextap;
9112 for (ap = d->pattern; ap != NULL; ap = nextap) {
9123 * return hash function on name. must be compatible with the one
9124 * computed a step at a time, elsewhere
9127 hashf (name, len, hashsize)
9128 register U_CHAR *name;
9135 r = HASHSTEP (r, *name++);
9137 return MAKE_POS (r) % hashsize;
9141 /* Dump the definition of a single macro HP to OF. */
9143 dump_single_macro (hp, of)
9144 register HASHNODE *hp;
9147 register DEFINITION *defn = hp->value.defn;
9153 /* Print the definition of the macro HP. */
9155 fprintf (of, "#define %s", hp->name);
9157 if (defn->nargs >= 0) {
9161 for (i = 0; i < defn->nargs; i++) {
9162 dump_arg_n (defn, i, of);
9163 if (i + 1 < defn->nargs)
9173 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9174 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9175 offset += ap->nchars;
9177 if (ap->nchars != 0)
9179 if (ap->stringify) {
9180 switch (ap->stringify) {
9181 case SHARP_TOKEN: fprintf (of, "#"); break;
9182 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9183 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9184 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9187 if (ap->raw_before) {
9189 switch (ap->raw_before) {
9190 case WHITE_SHARP_TOKEN:
9191 case WHITE_PERCENT_COLON_TOKEN:
9196 switch (ap->raw_before) {
9197 case SHARP_TOKEN: fprintf (of, "##"); break;
9198 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9199 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9200 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9206 dump_arg_n (defn, ap->argno, of);
9207 if (!traditional && ap->raw_after) {
9208 switch (ap->raw_after) {
9209 case SHARP_TOKEN: fprintf (of, "##"); break;
9210 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9211 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9212 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9217 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9221 /* Dump all macro definitions as #defines to stdout. */
9228 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9229 register HASHNODE *hp;
9231 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9232 if (hp->type == T_MACRO)
9233 dump_single_macro (hp, stdout);
9238 /* Output to OF a substring of a macro definition.
9239 BASE is the beginning of the definition.
9240 Output characters START thru LENGTH.
9241 Unless traditional, discard newlines outside of strings, thus
9242 converting funny-space markers to ordinary spaces. */
9245 dump_defn_1 (base, start, length, of)
9251 U_CHAR *p = base + start;
9252 U_CHAR *limit = base + start + length;
9255 fwrite (p, sizeof (*p), length, of);
9258 if (*p == '\"' || *p =='\'') {
9259 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9260 NULL_PTR, NULL_PTR);
9261 fwrite (p, sizeof (*p), p1 - p, of);
9272 /* Print the name of argument number ARGNUM of macro definition DEFN
9274 Recall that DEFN->args.argnames contains all the arg names
9275 concatenated in reverse order with comma-space in between. */
9278 dump_arg_n (defn, argnum, of)
9283 register U_CHAR *p = defn->args.argnames;
9284 while (argnum + 1 < defn->nargs) {
9285 p = (U_CHAR *) index (p, ' ') + 1;
9289 while (*p && *p != ',') {
9295 /* Initialize syntactic classifications of characters. */
9298 initialize_char_syntax ()
9303 * Set up is_idchar and is_idstart tables. These should be
9304 * faster than saying (is_alpha (c) || c == '_'), etc.
9305 * Set up these things before calling any routines tthat
9308 for (i = 'a'; i <= 'z'; i++) {
9309 is_idchar[i - 'a' + 'A'] = 1;
9311 is_idstart[i - 'a' + 'A'] = 1;
9314 for (i = '0'; i <= '9'; i++)
9317 is_idstart['_'] = 1;
9318 is_idchar['$'] = dollars_in_ident;
9319 is_idstart['$'] = dollars_in_ident;
9321 /* horizontal space table */
9322 is_hor_space[' '] = 1;
9323 is_hor_space['\t'] = 1;
9324 is_hor_space['\v'] = 1;
9325 is_hor_space['\f'] = 1;
9326 is_hor_space['\r'] = 1;
9335 char_name['\v'] = "vertical tab";
9336 char_name['\f'] = "formfeed";
9337 char_name['\r'] = "carriage return";
9340 /* Initialize the built-in macros. */
9343 initialize_builtins (inp, outp)
9347 install ("__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9348 install ("__DATE__", -1, T_DATE, NULL_PTR, -1);
9349 install ("__FILE__", -1, T_FILE, NULL_PTR, -1);
9350 install ("__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9351 install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9352 install ("__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9353 #ifndef NO_BUILTIN_SIZE_TYPE
9354 install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9356 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9357 install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9359 install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9360 install ("__USER_LABEL_PREFIX__",-1,T_USER_LABEL_PREFIX_TYPE, NULL_PTR, -1);
9361 install ("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, NULL_PTR, -1);
9362 install ("__TIME__", -1, T_TIME, NULL_PTR, -1);
9364 install ("__STDC__", -1, T_CONST, "1", -1);
9365 install ("__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9368 install ("__OBJC__", -1, T_CONST, "1", -1);
9369 /* This is supplied using a -D by the compiler driver
9370 so that it is present only when truly compiling with GNU C. */
9371 /* install ("__GNUC__", -1, T_CONST, "2", -1); */
9375 char directive[2048];
9376 register struct directive *dp = &directive_table[0];
9377 struct tm *timebuf = timestamp ();
9379 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9380 instack[0].nominal_fname);
9381 output_line_directive (inp, outp, 0, same_file);
9382 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9384 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9385 output_line_directive (inp, outp, 0, same_file);
9386 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9388 #ifndef NO_BUILTIN_SIZE_TYPE
9389 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9390 output_line_directive (inp, outp, 0, same_file);
9391 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9394 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9395 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9396 output_line_directive (inp, outp, 0, same_file);
9397 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9400 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9401 output_line_directive (inp, outp, 0, same_file);
9402 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9404 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9405 monthnames[timebuf->tm_mon],
9406 timebuf->tm_mday, timebuf->tm_year + 1900);
9407 output_line_directive (inp, outp, 0, same_file);
9408 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9410 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9411 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9412 output_line_directive (inp, outp, 0, same_file);
9413 pass_thru_directive (directive, &directive[strlen (directive)], outp, dp);
9417 sprintf (directive, " __STDC__ 1");
9418 output_line_directive (inp, outp, 0, same_file);
9419 pass_thru_directive (directive, &directive[strlen (directive)],
9424 sprintf (directive, " __OBJC__ 1");
9425 output_line_directive (inp, outp, 0, same_file);
9426 pass_thru_directive (directive, &directive[strlen (directive)],
9433 * process a given definition string, for initialization
9434 * If STR is just an identifier, define it with value 1.
9435 * If STR has anything after the identifier, then it should
9436 * be identifier=definition.
9440 make_definition (str, op)
9445 struct directive *kt;
9450 if (!is_idstart[*p]) {
9451 error ("malformed option `-D %s'", str);
9454 while (is_idchar[*++p])
9457 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9460 p = str; /* Error */
9463 buf = (U_CHAR *) alloca (p - buf + 4);
9464 strcpy ((char *)buf, str);
9465 strcat ((char *)buf, " 1");
9466 } else if (*p != '=') {
9467 error ("malformed option `-D %s'", str);
9471 /* Copy the entire option so we can modify it. */
9472 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9473 strncpy (buf, str, p - str);
9474 /* Change the = to a space. */
9476 /* Scan for any backslash-newline and remove it. */
9480 if (*p == '\"' || *p == '\'') {
9481 int unterminated = 0;
9482 U_CHAR *p1 = skip_quoted_string (p, p + strlen (p), 0,
9483 NULL_PTR, NULL_PTR, &unterminated);
9487 if (*p == '\\' && p[1] == '\n')
9491 } else if (*p == '\\' && p[1] == '\n')
9493 /* Change newline chars into newline-markers. */
9494 else if (*p == '\n')
9506 ip = &instack[++indepth];
9507 ip->nominal_fname = ip->fname = "*Initialization*";
9509 ip->buf = ip->bufp = buf;
9510 ip->length = strlen (buf);
9514 ip->if_stack = if_stack;
9515 ip->system_header_p = 0;
9517 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9520 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9521 do_define (buf, buf + strlen (buf), NULL_PTR, kt);
9525 /* JF, this does the work for the -U option */
9528 make_undef (str, op)
9533 struct directive *kt;
9535 ip = &instack[++indepth];
9536 ip->nominal_fname = ip->fname = "*undef*";
9538 ip->buf = ip->bufp = str;
9539 ip->length = strlen (str);
9543 ip->if_stack = if_stack;
9544 ip->system_header_p = 0;
9546 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9549 do_undef (str, str + strlen (str), op, kt);
9553 /* Process the string STR as if it appeared as the body of a #assert.
9554 OPTION is the option name for which STR was the argument. */
9557 make_assertion (option, str)
9562 struct directive *kt;
9563 U_CHAR *buf, *p, *q;
9565 /* Copy the entire option so we can modify it. */
9566 buf = (U_CHAR *) alloca (strlen (str) + 1);
9567 strcpy ((char *) buf, str);
9568 /* Scan for any backslash-newline and remove it. */
9571 if (*p == '\\' && p[1] == '\n')
9579 if (!is_idstart[*p]) {
9580 error ("malformed option `%s %s'", option, str);
9583 while (is_idchar[*++p])
9585 SKIP_WHITE_SPACE (p);
9586 if (! (*p == 0 || *p == '(')) {
9587 error ("malformed option `%s %s'", option, str);
9591 ip = &instack[++indepth];
9592 ip->nominal_fname = ip->fname = "*Initialization*";
9594 ip->buf = ip->bufp = buf;
9595 ip->length = strlen (buf);
9599 ip->if_stack = if_stack;
9600 ip->system_header_p = 0;
9602 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9605 /* pass NULL as output ptr to do_define since we KNOW it never
9606 does any output.... */
9607 do_assert (buf, buf + strlen (buf) , NULL_PTR, kt);
9611 /* Append a chain of `struct file_name_list's
9612 to the end of the main include chain.
9613 FIRST is the beginning of the chain to append, and LAST is the end. */
9616 append_include_chain (first, last)
9617 struct file_name_list *first, *last;
9619 struct file_name_list *dir;
9621 if (!first || !last)
9627 last_include->next = first;
9629 if (first_bracket_include == 0)
9630 first_bracket_include = first;
9632 for (dir = first; ; dir = dir->next) {
9633 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9634 if (len > max_include_len)
9635 max_include_len = len;
9641 last_include = last;
9644 /* Add output to `deps_buffer' for the -M switch.
9645 STRING points to the text to be output.
9646 SPACER is ':' for targets, ' ' for dependencies, zero for text
9647 to be inserted literally. */
9650 deps_output (string, spacer)
9654 int size = strlen (string);
9659 #ifndef MAX_OUTPUT_COLUMNS
9660 #define MAX_OUTPUT_COLUMNS 72
9664 && (deps_column + size) > MAX_OUTPUT_COLUMNS)
9666 deps_output (" \\\n ", 0);
9670 if (deps_size + size + 8 > deps_allocated_size) {
9671 deps_allocated_size = (deps_size + size + 50) * 2;
9672 deps_buffer = (char *) xrealloc (deps_buffer, deps_allocated_size);
9674 if (spacer == ' ' && deps_column > 0)
9675 deps_buffer[deps_size++] = ' ';
9676 bcopy (string, &deps_buffer[deps_size], size);
9678 deps_column += size;
9680 deps_buffer[deps_size++] = ':';
9681 deps_buffer[deps_size] = 0;
9684 #if defined(USG) || defined(VMS)
9690 register unsigned length;
9692 while (length-- > 0)
9697 bcopy (b1, b2, length)
9700 register unsigned length;
9702 while (length-- > 0)
9707 bcmp (b1, b2, length) /* This could be a macro! */
9710 register unsigned length;
9712 while (length-- > 0)
9718 #endif /* not BSTRING */
9719 #endif /* USG or VMS */
9726 fprintf (stderr, "%s: ", progname);
9727 fprintf (stderr, str, arg);
9728 fprintf (stderr, "\n");
9729 exit (FAILURE_EXIT_CODE);
9732 /* More 'friendly' abort that prints the line and file.
9733 config.h can #define abort fancy_abort if you like that sort of thing. */
9738 fatal ("Internal gcc abort.");
9742 perror_with_name (name)
9745 fprintf (stderr, "%s: ", progname);
9746 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9751 pfatal_with_name (name)
9754 perror_with_name (name);
9758 exit (FAILURE_EXIT_CODE);
9762 /* Handler for SIGPIPE. */
9766 /* If this is missing, some compilers complain. */
9769 fatal ("output pipe has been closed");
9775 fatal ("Memory exhausted.");
9783 register char *ptr = (char *) malloc (size);
9784 if (ptr != 0) return (ptr);
9791 xrealloc (old, size)
9795 register char *ptr = (char *) realloc (old, size);
9796 if (ptr != 0) return (ptr);
9803 xcalloc (number, size)
9804 unsigned number, size;
9806 register unsigned total = number * size;
9807 register char *ptr = (char *) malloc (total);
9812 /* It's not too long, so loop, zeroing by longs.
9813 It must be safe because malloc values are always well aligned. */
9814 register long *zp = (long *) ptr;
9815 register long *zl = (long *) (ptr + total - 4);
9816 register int i = total - 4;
9835 unsigned size = strlen (input);
9836 char *output = xmalloc (size + 1);
9837 strcpy (output, input);
9841 /* Get the file-mode and data size of the file open on FD
9842 and store them in *MODE_POINTER and *SIZE_POINTER. */
9845 file_size_and_mode (fd, mode_pointer, size_pointer)
9848 long int *size_pointer;
9852 if (fstat (fd, &sbuf) < 0) return (-1);
9853 if (mode_pointer) *mode_pointer = sbuf.st_mode;
9854 if (size_pointer) *size_pointer = sbuf.st_size;
9859 output_dots (fd, depth)
9872 /* Under VMS we need to fix up the "include" specification
9873 filename so that everything following the 1st slash is
9874 changed into its correct VMS file specification. */
9877 hack_vms_include_specification (fname)
9880 register char *cp, *cp1, *cp2;
9881 int f, check_filename_before_returning, no_prefix_seen;
9884 check_filename_before_returning = 0;
9887 /* Ignore leading "./"s */
9888 while (fname[0] == '.' && fname[1] == '/') {
9889 strcpy (fname, fname+2);
9890 no_prefix_seen = 1; /* mark this for later */
9892 /* Look for the boundary between the VMS and UNIX filespecs */
9893 cp = rindex (fname, ']'); /* Look for end of dirspec. */
9894 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
9895 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
9899 cp = index (fname, '/'); /* Look for the "/" */
9903 * Check if we have a vax-c style '#include filename'
9904 * and add the missing .h
9907 if (index(fname,'.') == 0)
9908 strcat(fname, ".h");
9910 if (index(cp,'.') == 0)
9914 cp2 = Local; /* initialize */
9916 /* We are trying to do a number of things here. First of all, we are
9917 trying to hammer the filenames into a standard format, such that later
9918 processing can handle them.
9920 If the file name contains something like [dir.], then it recognizes this
9921 as a root, and strips the ".]". Later processing will add whatever is
9922 needed to get things working properly.
9924 If no device is specified, then the first directory name is taken to be
9925 a device name (or a rooted logical). */
9927 /* See if we found that 1st slash */
9928 if (cp == 0) return; /* Nothing to do!!! */
9929 if (*cp != '/') return; /* Nothing to do!!! */
9930 /* Point to the UNIX filename part (which needs to be fixed!) */
9932 /* If the directory spec is not rooted, we can just copy
9933 the UNIX filename part and we are done */
9934 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
9935 if (cp[-2] != '.') {
9937 * The VMS part ends in a `]', and the preceding character is not a `.'.
9938 * We strip the `]', and then splice the two parts of the name in the
9939 * usual way. Given the default locations for include files in cccp.c,
9940 * we will only use this code if the user specifies alternate locations
9941 * with the /include (-I) switch on the command line. */
9942 cp -= 1; /* Strip "]" */
9943 cp1--; /* backspace */
9946 * The VMS part has a ".]" at the end, and this will not do. Later
9947 * processing will add a second directory spec, and this would be a syntax
9948 * error. Thus we strip the ".]", and thus merge the directory specs.
9949 * We also backspace cp1, so that it points to a '/'. This inhibits the
9950 * generation of the 000000 root directory spec (which does not belong here
9953 cp -= 2; /* Strip ".]" */
9954 cp1--; }; /* backspace */
9957 /* We drop in here if there is no VMS style directory specification yet.
9958 * If there is no device specification either, we make the first dir a
9959 * device and try that. If we do not do this, then we will be essentially
9960 * searching the users default directory (as if they did a #include "asdf.h").
9962 * Then all we need to do is to push a '[' into the output string. Later
9963 * processing will fill this in, and close the bracket.
9965 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
9966 *cp2++ = '['; /* Open the directory specification */
9969 /* at this point we assume that we have the device spec, and (at least
9970 the opening "[" for a directory specification. We may have directories
9971 specified already */
9973 /* If there are no other slashes then the filename will be
9974 in the "root" directory. Otherwise, we need to add
9975 directory specifications. */
9976 if (index (cp1, '/') == 0) {
9977 /* Just add "000000]" as the directory string */
9978 strcpy (cp2, "000000]");
9979 cp2 += strlen (cp2);
9980 check_filename_before_returning = 1; /* we might need to fool with this later */
9982 /* As long as there are still subdirectories to add, do them. */
9983 while (index (cp1, '/') != 0) {
9984 /* If this token is "." we can ignore it */
9985 if ((cp1[0] == '.') && (cp1[1] == '/')) {
9989 /* Add a subdirectory spec. Do not duplicate "." */
9990 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
9992 /* If this is ".." then the spec becomes "-" */
9993 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
9994 /* Add "-" and skip the ".." */
9999 /* Copy the subdirectory */
10000 while (*cp1 != '/') *cp2++= *cp1++;
10001 cp1++; /* Skip the "/" */
10003 /* Close the directory specification */
10004 if (cp2[-1] == '.') /* no trailing periods */
10008 /* Now add the filename */
10009 while (*cp1) *cp2++ = *cp1++;
10011 /* Now append it to the original VMS spec. */
10012 strcpy (cp, Local);
10014 /* If we put a [000000] in the filename, try to open it first. If this fails,
10015 remove the [000000], and return that name. This provides flexibility
10016 to the user in that they can use both rooted and non-rooted logical names
10017 to point to the location of the file. */
10019 if (check_filename_before_returning && no_prefix_seen) {
10020 f = open (fname, O_RDONLY, 0666);
10022 /* The file name is OK as it is, so return it as is. */
10026 /* The filename did not work. Try to remove the [000000] from the name,
10028 cp = index (fname, '[');
10029 cp2 = index (fname, ']') + 1;
10030 strcpy (cp, cp2); /* this gets rid of it */
10038 /* These are the read/write replacement routines for
10039 VAX-11 "C". They make read/write behave enough
10040 like their UNIX counterparts that CCCP will work */
10043 read (fd, buf, size)
10048 #undef read /* Get back the REAL read routine */
10050 register int total = 0;
10052 /* Read until the buffer is exhausted */
10054 /* Limit each read to 32KB */
10055 i = (size > (32*1024)) ? (32*1024) : size;
10056 i = read (fd, buf, i);
10058 if (i == 0) return (total);
10061 /* Account for this read */
10070 write (fd, buf, size)
10075 #undef write /* Get back the REAL write routine */
10079 /* Limit individual writes to 32Kb */
10082 j = (i > (32*1024)) ? (32*1024) : i;
10083 if (write (fd, buf, j) < 0) return (-1);
10084 /* Account for the data written */
10091 /* The following wrapper functions supply additional arguments to the VMS
10092 I/O routines to optimize performance with file handling. The arguments
10094 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10095 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10096 "fop=tef"- Truncate unused portions of file when closing file.
10097 "shr=nil"- Disallow file sharing while file is open.
10101 freopen (fname, type, oldfile)
10106 #undef freopen /* Get back the REAL fopen routine */
10107 if (strcmp (type, "w") == 0)
10108 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10109 return freopen (fname, type, oldfile, "mbc=16");
10113 fopen (fname, type)
10117 #undef fopen /* Get back the REAL fopen routine */
10118 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10119 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10120 pre-ANSI implmentation. This hack circumvents the mismatch problem. */
10121 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10124 return (*vmslib_fopen) (fname, type, "mbc=32",
10125 "deq=64", "fop=tef", "shr=nil");
10127 return (*vmslib_fopen) (fname, type, "mbc=32");
10131 open (fname, flags, prot)
10136 #undef open /* Get back the REAL open routine */
10137 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10140 /* Avoid run-time library bug, where copying M out of N+M characters with
10141 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
10142 gcc-cpp exercises this particular bug. */
10145 strncat (dst, src, cnt)
10150 register char *d = dst, *s = (char *) src;
10151 register int n = cnt; /* convert to _signed_ type */
10153 while (*d) d++; /* advance to end */
10155 if (!(*d++ = *s++)) break;
10156 if (n < 0) *d = '\0';