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 #include <sys/types.h>
71 /* The following symbols should be autoconfigured:
78 In the mean time, we'll get by with approximations based
79 on existing GCC configuration symbols. */
82 # ifndef HAVE_STDLIB_H
83 # define HAVE_STDLIB_H 1
85 # ifndef HAVE_UNISTD_H
86 # define HAVE_UNISTD_H 1
89 # define STDC_HEADERS 1
91 #endif /* defined (POSIX) */
93 #if defined (POSIX) || (defined (USG) && !defined (VMS))
95 # define HAVE_FCNTL_H 1
102 # if TIME_WITH_SYS_TIME
103 # include <sys/time.h>
107 # include <sys/time.h>
112 # include <sys/resource.h>
119 /* This defines "errno" properly for VMS, and gives us EACCES. */
131 # define bcmp(a, b, n) memcmp (a, b, n)
134 # define bcopy(s, d, n) memcpy (d, s, n)
137 # define bzero(d, n) memset (d, 0, n)
139 #else /* !STDC_HEADERS */
143 # if !defined (BSTRING) && (defined (USG) || defined (VMS))
146 # define bcmp my_bcmp
159 # endif /* !defined (bcmp) */
162 # define bcopy my_bcopy
172 # endif /* !defined (bcopy) */
175 # define bzero my_bzero
179 register unsigned length;
184 # endif /* !defined (bzero) */
186 # endif /* !defined (BSTRING) && (defined (USG) || defined (VMS)) */
187 #endif /* ! STDC_HEADERS */
189 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 6)
190 # define __attribute__(x)
194 # if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
195 # define PROTO(ARGS) ARGS
197 # define PROTO(ARGS) ()
201 #if defined (__STDC__) && defined (HAVE_VPRINTF)
203 # define VA_START(va_list, var) va_start (va_list, var)
204 # define PRINTF_ALIST(msg) char *msg, ...
205 # define PRINTF_DCL(msg)
206 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (printf, m, n)))
208 # include <varargs.h>
209 # define VA_START(va_list, var) va_start (va_list)
210 # define PRINTF_ALIST(msg) msg, va_alist
211 # define PRINTF_DCL(msg) char *msg; va_dcl
212 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (printf, m, n)))
213 # define vfprintf(file, msg, args) \
215 char *a0 = va_arg(args, char *); \
216 char *a1 = va_arg(args, char *); \
217 char *a2 = va_arg(args, char *); \
218 char *a3 = va_arg(args, char *); \
219 fprintf (file, msg, a0, a1, a2, a3); \
223 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
224 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
225 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
231 /* VMS-specific definitions */
234 #define O_RDONLY 0 /* Open arg for Read/Only */
235 #define O_WRONLY 1 /* Open arg for Write/Only */
236 #define read(fd,buf,size) VMS_read (fd,buf,size)
237 #define write(fd,buf,size) VMS_write (fd,buf,size)
238 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
239 #define fopen(fname,mode) VMS_fopen (fname,mode)
240 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
241 #define strncat(dst,src,cnt) VMS_strncat (dst,src,cnt)
242 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
243 static int VMS_fstat (), VMS_stat ();
244 static char * VMS_strncat ();
245 static int VMS_read ();
246 static int VMS_write ();
247 static int VMS_open ();
248 static FILE * VMS_fopen ();
249 static FILE * VMS_freopen ();
250 static void hack_vms_include_specification ();
251 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
252 #define ino_t vms_ino_t
253 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
255 #define BSTRING /* VMS/GCC supplies the bstring routines */
256 #endif /* __GNUC__ */
265 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
266 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
268 /* Find the largest host integer type and set its size and type. */
270 #ifndef HOST_BITS_PER_WIDE_INT
272 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
273 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
274 #define HOST_WIDE_INT long
276 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
277 #define HOST_WIDE_INT int
283 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
287 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
290 /* Define a generic NULL if one hasn't already been defined. */
297 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
298 #define GENERIC_PTR void *
300 #define GENERIC_PTR char *
305 #define NULL_PTR ((GENERIC_PTR)0)
308 #ifndef INCLUDE_LEN_FUDGE
309 #define INCLUDE_LEN_FUDGE 0
312 /* External declarations. */
314 extern char *version_string;
316 #ifndef HAVE_STRERROR
319 extern const char *const sys_errlist[];
321 extern char *sys_errlist[];
323 #else /* HAVE_STERRROR */
327 char *strerror (int,...);
329 int parse_escape PROTO((char **));
330 HOST_WIDE_INT parse_c_expression PROTO((char *));
336 #ifndef FAILURE_EXIT_CODE
337 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
340 #ifndef SUCCESS_EXIT_CODE
341 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
344 /* Name under which this program was invoked. */
346 static char *progname;
348 /* Nonzero means use extra default include directories for C++. */
350 static int cplusplus;
352 /* Nonzero means handle cplusplus style comments */
354 static int cplusplus_comments;
356 /* Nonzero means handle #import, for objective C. */
360 /* Nonzero means this is an assembly file, and allow
361 unknown directives, which could be comments. */
365 /* Current maximum length of directory names in the search path
366 for include files. (Altered as we get more of them.) */
368 static int max_include_len;
370 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
372 static int for_lint = 0;
374 /* Nonzero means copy comments into the output file. */
376 static int put_out_comments = 0;
378 /* Nonzero means don't process the ANSI trigraph sequences. */
380 static int no_trigraphs = 0;
382 /* Nonzero means print the names of included files rather than
383 the preprocessed output. 1 means just the #include "...",
384 2 means #include <...> as well. */
386 static int print_deps = 0;
388 /* Nonzero if missing .h files in -M output are assumed to be generated
389 files and not errors. */
391 static int print_deps_missing_files = 0;
393 /* Nonzero means print names of header files (-H). */
395 static int print_include_names = 0;
397 /* Nonzero means don't output line number information. */
399 static int no_line_directives;
401 /* Nonzero means output the text in failing conditionals,
402 inside #failed ... #endfailed. */
404 static int output_conditionals;
406 /* dump_only means inhibit output of the preprocessed text
407 and instead output the definitions of all user-defined
408 macros in a form suitable for use as input to cccp.
409 dump_names means pass #define and the macro name through to output.
410 dump_definitions means pass the whole definition (plus #define) through
413 static enum {dump_none, dump_only, dump_names, dump_definitions}
414 dump_macros = dump_none;
416 /* Nonzero means pass all #define and #undef directives which we actually
417 process through to the output stream. This feature is used primarily
418 to allow cc1 to record the #defines and #undefs for the sake of
419 debuggers which understand about preprocessor macros, but it may
420 also be useful with -E to figure out how symbols are defined, and
421 where they are defined. */
422 static int debug_output = 0;
424 /* Nonzero indicates special processing used by the pcp program. The
425 special effects of this mode are:
427 Inhibit all macro expansion, except those inside #if directives.
429 Process #define directives normally, and output their contents
432 Output preconditions to pcp_outfile indicating all the relevant
433 preconditions for use of this file in a later cpp run.
435 static FILE *pcp_outfile;
437 /* Nonzero means we are inside an IF during a -pcp run. In this mode
438 macro expansion is done, and preconditions are output for all macro
439 uses requiring them. */
440 static int pcp_inside_if;
442 /* Nonzero means never to include precompiled files.
443 This is 1 since there's no way now to make precompiled files,
444 so it's not worth testing for them. */
445 static int no_precomp = 1;
447 /* Nonzero means give all the error messages the ANSI standard requires. */
451 /* Nonzero means try to make failure to fit ANSI C an error. */
453 static int pedantic_errors;
455 /* Nonzero means don't print warning messages. -w. */
457 static int inhibit_warnings = 0;
459 /* Nonzero means warn if slash-star appears in a comment. */
461 static int warn_comments;
463 /* Nonzero means warn if a macro argument is (or would be)
464 stringified with -traditional. */
466 static int warn_stringify;
468 /* Nonzero means warn if there are any trigraphs. */
470 static int warn_trigraphs;
472 /* Nonzero means warn if #import is used. */
474 static int warn_import = 1;
476 /* Nonzero means turn warnings into errors. */
478 static int warnings_are_errors;
480 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
484 /* Nonzero causes output not to be done,
485 but directives such as #define that have side effects
488 static int no_output;
490 /* Nonzero means this file was included with a -imacros or -include
491 command line and should not be recorded as an include file. */
493 static int no_record_file;
495 /* Nonzero means that we have finished processing the command line options.
496 This flag is used to decide whether or not to issue certain errors
499 static int done_initializing = 0;
501 /* Line where a newline was first seen in a string constant. */
503 static int multiline_string_line = 0;
505 /* I/O buffer structure.
506 The `fname' field is nonzero for source files and #include files
507 and for the dummy text used for -D and -U.
508 It is zero for rescanning results of macro expansion
509 and for expanding macro arguments. */
510 #define INPUT_STACK_MAX 400
511 static struct file_buf {
513 /* Filename specified with #line directive. */
515 /* Record where in the search path this file was found.
516 For #include_next. */
517 struct file_name_list *dir;
522 /* Macro that this level is the expansion of.
523 Included so that we can reenable the macro
524 at the end of this level. */
525 struct hashnode *macro;
526 /* Value of if_stack at start of this file.
527 Used to prohibit unmatched #endif (etc) in an include file. */
528 struct if_stack *if_stack;
529 /* Object to be freed at end of input at this level. */
531 /* True if this is a header file included using <FILENAME>. */
532 char system_header_p;
533 } instack[INPUT_STACK_MAX];
535 static int last_error_tick; /* Incremented each time we print it. */
536 static int input_file_stack_tick; /* Incremented when the status changes. */
538 /* Current nesting level of input sources.
539 `instack[indepth]' is the level currently being read. */
540 static int indepth = -1;
541 #define CHECK_DEPTH(code) \
542 if (indepth >= (INPUT_STACK_MAX - 1)) \
544 error_with_line (line_for_error (instack[indepth].lineno), \
545 "macro or `#include' recursion too deep"); \
549 /* Current depth in #include directives that use <...>. */
550 static int system_include_depth = 0;
552 typedef struct file_buf FILE_BUF;
554 /* The output buffer. Its LENGTH field is the amount of room allocated
555 for the buffer, not the number of chars actually present. To get
556 that, subtract outbuf.buf from outbuf.bufp. */
558 #define OUTBUF_SIZE 10 /* initial size of output buffer */
559 static FILE_BUF outbuf;
561 /* Grow output buffer OBUF points at
562 so it can hold at least NEEDED more chars. */
564 #define check_expand(OBUF, NEEDED) \
565 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
566 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
568 struct file_name_list
570 struct file_name_list *next;
572 /* If the following is nonzero, it is a macro name.
573 Don't include the file again if that macro is defined. */
574 U_CHAR *control_macro;
575 /* If the following is nonzero, it is a C-language system include
577 int c_system_include_path;
578 /* Mapping of file names for this directory. */
579 struct file_name_map *name_map;
580 /* Non-zero if name_map is valid. */
584 /* #include "file" looks in source file dir, then stack. */
585 /* #include <file> just looks in the stack. */
586 /* -I directories are added to the end, then the defaults are added. */
588 static struct default_include {
589 char *fname; /* The name of the directory. */
590 int cplusplus; /* Only look here if we're compiling C++. */
591 int cxx_aware; /* Includes in this directory don't need to
592 be wrapped in extern "C" when compiling
594 } include_defaults_array[]
595 #ifdef INCLUDE_DEFAULTS
599 /* Pick up GNU C++ specific include files. */
600 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
602 /* This is the dir for fixincludes. Put it just before
603 the files that we fix. */
604 { GCC_INCLUDE_DIR, 0, 0 },
605 /* For cross-compilation, this dir name is generated
606 automatically in Makefile.in. */
607 { CROSS_INCLUDE_DIR, 0, 0 },
608 /* This is another place that the target system's headers might be. */
609 { TOOL_INCLUDE_DIR, 0, 0 },
610 #else /* not CROSS_COMPILE */
611 /* This should be /usr/local/include and should come before
612 the fixincludes-fixed header files. */
613 { LOCAL_INCLUDE_DIR, 0, 1 },
614 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
615 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
616 { TOOL_INCLUDE_DIR, 0, 0 },
617 /* This is the dir for fixincludes. Put it just before
618 the files that we fix. */
619 { GCC_INCLUDE_DIR, 0, 0 },
620 /* Some systems have an extra dir of include files. */
621 #ifdef SYSTEM_INCLUDE_DIR
622 { SYSTEM_INCLUDE_DIR, 0, 0 },
624 { STANDARD_INCLUDE_DIR, 0, 0 },
625 #endif /* not CROSS_COMPILE */
628 #endif /* no INCLUDE_DEFAULTS */
630 /* The code looks at the defaults through this pointer, rather than through
631 the constant structure above. This pointer gets changed if an environment
632 variable specifies other defaults. */
633 static struct default_include *include_defaults = include_defaults_array;
635 static struct file_name_list *include = 0; /* First dir to search */
636 /* First dir to search for <file> */
637 /* This is the first element to use for #include <...>.
638 If it is 0, use the entire chain for such includes. */
639 static struct file_name_list *first_bracket_include = 0;
640 /* This is the first element in the chain that corresponds to
641 a directory of system header files. */
642 static struct file_name_list *first_system_include = 0;
643 static struct file_name_list *last_include = 0; /* Last in chain */
645 /* Chain of include directories to put at the end of the other chain. */
646 static struct file_name_list *after_include = 0;
647 static struct file_name_list *last_after_include = 0; /* Last in chain */
649 /* Chain to put at the start of the system include files. */
650 static struct file_name_list *before_system = 0;
651 static struct file_name_list *last_before_system = 0; /* Last in chain */
653 /* List of included files that contained #pragma once. */
654 static struct file_name_list *dont_repeat_files = 0;
656 /* List of other included files.
657 If ->control_macro if nonzero, the file had a #ifndef
658 around the entire contents, and ->control_macro gives the macro name. */
659 static struct file_name_list *all_include_files = 0;
661 /* Directory prefix that should replace `/usr' in the standard
662 include file directories. */
663 static char *include_prefix;
665 /* Global list of strings read in from precompiled files. This list
666 is kept in the order the strings are read in, with new strings being
667 added at the end through stringlist_tailp. We use this list to output
668 the strings at the end of the run.
670 static STRINGDEF *stringlist;
671 static STRINGDEF **stringlist_tailp = &stringlist;
674 /* Structure returned by create_definition */
675 typedef struct macrodef MACRODEF;
678 struct definition *defn;
683 enum sharp_token_type {
684 NO_SHARP_TOKEN = 0, /* token not present */
686 SHARP_TOKEN = '#', /* token spelled with # only */
687 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
689 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
690 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
693 /* Structure allocated for every #define. For a simple replacement
696 nargs = -1, the `pattern' list is null, and the expansion is just
697 the replacement text. Nargs = 0 means a functionlike macro with no args,
699 #define getchar() getc (stdin) .
700 When there are args, the expansion is the replacement text with the
701 args squashed out, and the reflist is a list describing how to
702 build the output from the input: e.g., "3 chars, then the 1st arg,
703 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
704 The chars here come from the expansion. Whatever is left of the
705 expansion after the last arg-occurrence is copied after that arg.
706 Note that the reflist can be arbitrarily long---
707 its length depends on the number of times the arguments appear in
708 the replacement text, not how many args there are. Example:
709 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
711 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
712 where (x, y) means (nchars, argno). */
714 typedef struct definition DEFINITION;
717 int length; /* length of expansion string */
718 int predefined; /* True if the macro was builtin or */
719 /* came from the command line */
721 int line; /* Line number of definition */
722 char *file; /* File of definition */
723 char rest_args; /* Nonzero if last arg. absorbs the rest */
725 struct reflist *next;
727 enum sharp_token_type stringify; /* set if a # operator before arg */
728 enum sharp_token_type raw_before; /* set if a ## operator before arg */
729 enum sharp_token_type raw_after; /* set if a ## operator after arg */
731 char rest_args; /* Nonzero if this arg. absorbs the rest */
732 int nchars; /* Number of literal chars to copy before
733 this arg occurrence. */
734 int argno; /* Number of arg to substitute (origin-0) */
737 /* Names of macro args, concatenated in reverse order
738 with comma-space between them.
739 The only use of this is that we warn on redefinition
740 if this differs between the old and new definitions. */
745 /* different kinds of things that can appear in the value field
746 of a hash node. Actually, this may be useless now. */
754 * special extension string that can be added to the last macro argument to
755 * allow it to absorb the "rest" of the arguments when expanded. Ex:
756 * #define wow(a, b...) process (b, a, b)
757 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
758 * { wow (one, two); } -> { process (two, one, two); }
759 * if this "rest_arg" is used with the concat token '##' and if it is not
760 * supplied then the token attached to with ## will not be outputted. Ex:
761 * #define wow (a, b...) process (b ## , a, ## b)
762 * { wow (1, 2); } -> { process (2, 1, 2); }
763 * { wow (one); } -> { process (one); {
765 static char rest_extension[] = "...";
766 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
768 /* The structure of a node in the hash table. The hash table
769 has entries for all tokens defined by #define directives (type T_MACRO),
770 plus some special tokens like __LINE__ (these each have their own
771 type, and the appropriate code is run when that type of node is seen.
772 It does not contain control words like "#define", which are recognized
773 by a separate piece of code. */
775 /* different flavors of hash nodes --- also used in keyword table */
777 T_DEFINE = 1, /* the `#define' keyword */
778 T_INCLUDE, /* the `#include' keyword */
779 T_INCLUDE_NEXT, /* the `#include_next' keyword */
780 T_IMPORT, /* the `#import' keyword */
781 T_IFDEF, /* the `#ifdef' keyword */
782 T_IFNDEF, /* the `#ifndef' keyword */
783 T_IF, /* the `#if' keyword */
784 T_ELSE, /* `#else' */
785 T_PRAGMA, /* `#pragma' */
786 T_ELIF, /* `#elif' */
787 T_UNDEF, /* `#undef' */
788 T_LINE, /* `#line' */
789 T_ERROR, /* `#error' */
790 T_WARNING, /* `#warning' */
791 T_ENDIF, /* `#endif' */
792 T_SCCS, /* `#sccs', used on system V. */
793 T_IDENT, /* `#ident', used on system V. */
794 T_ASSERT, /* `#assert', taken from system V. */
795 T_UNASSERT, /* `#unassert', taken from system V. */
796 T_SPECLINE, /* special symbol `__LINE__' */
797 T_DATE, /* `__DATE__' */
798 T_FILE, /* `__FILE__' */
799 T_BASE_FILE, /* `__BASE_FILE__' */
800 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
801 T_VERSION, /* `__VERSION__' */
802 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
803 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
804 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
805 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
806 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
807 T_TIME, /* `__TIME__' */
808 T_CONST, /* Constant value, used by `__STDC__' */
809 T_MACRO, /* macro defined by `#define' */
810 T_DISABLED, /* macro temporarily turned off for rescan */
811 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
812 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
813 T_UNUSED /* Used for something not defined. */
817 struct hashnode *next; /* double links for easy deletion */
818 struct hashnode *prev;
819 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
820 chain is kept, in case the node is the head
821 of the chain and gets deleted. */
822 enum node_type type; /* type of special token */
823 int length; /* length of token, for quick comparison */
824 U_CHAR *name; /* the actual name */
825 union hashval value; /* pointer to expansion, or whatever */
828 typedef struct hashnode HASHNODE;
830 /* Some definitions for the hash table. The hash function MUST be
831 computed as shown in hashf () below. That is because the rescan
832 loop computes the hash value `on the fly' for most tokens,
833 in order to avoid the overhead of a lot of procedure calls to
834 the hashf () function. Hashf () only exists for the sake of
835 politeness, for use when speed isn't so important. */
837 #define HASHSIZE 1403
838 static HASHNODE *hashtab[HASHSIZE];
839 #define HASHSTEP(old, c) ((old << 2) + c)
840 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
842 /* Symbols to predefine. */
844 #ifdef CPP_PREDEFINES
845 static char *predefs = CPP_PREDEFINES;
847 static char *predefs = "";
850 /* We let tm.h override the types used here, to handle trivial differences
851 such as the choice of unsigned int or long unsigned int for size_t.
852 When machines start needing nontrivial differences in the size type,
853 it would be best to do something here to figure out automatically
854 from other information what type to use. */
856 /* The string value for __SIZE_TYPE__. */
859 #define SIZE_TYPE "long unsigned int"
862 /* The string value for __PTRDIFF_TYPE__. */
865 #define PTRDIFF_TYPE "long int"
868 /* The string value for __WCHAR_TYPE__. */
871 #define WCHAR_TYPE "int"
873 char * wchar_type = WCHAR_TYPE;
876 /* The string value for __USER_LABEL_PREFIX__ */
878 #ifndef USER_LABEL_PREFIX
879 #define USER_LABEL_PREFIX ""
882 /* The string value for __REGISTER_PREFIX__ */
884 #ifndef REGISTER_PREFIX
885 #define REGISTER_PREFIX ""
888 /* In the definition of a #assert name, this structure forms
889 a list of the individual values asserted.
890 Each value is itself a list of "tokens".
891 These are strings that are compared by name. */
893 struct tokenlist_list {
894 struct tokenlist_list *next;
895 struct arglist *tokens;
898 struct assertion_hashnode {
899 struct assertion_hashnode *next; /* double links for easy deletion */
900 struct assertion_hashnode *prev;
901 /* also, a back pointer to this node's hash
902 chain is kept, in case the node is the head
903 of the chain and gets deleted. */
904 struct assertion_hashnode **bucket_hdr;
905 int length; /* length of token, for quick comparison */
906 U_CHAR *name; /* the actual name */
907 /* List of token-sequences. */
908 struct tokenlist_list *value;
911 typedef struct assertion_hashnode ASSERTION_HASHNODE;
913 /* Some definitions for the hash table. The hash function MUST be
914 computed as shown in hashf below. That is because the rescan
915 loop computes the hash value `on the fly' for most tokens,
916 in order to avoid the overhead of a lot of procedure calls to
917 the hashf function. hashf only exists for the sake of
918 politeness, for use when speed isn't so important. */
920 #define ASSERTION_HASHSIZE 37
921 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
923 /* Nonzero means inhibit macroexpansion of what seem to be
924 assertion tests, in rescan. For #if. */
925 static int assertions_flag;
927 /* `struct directive' defines one #-directive, including how to handle it. */
929 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
932 int length; /* Length of name */
933 int (*func) DO_PROTO; /* Function to handle directive */
934 char *name; /* Name of directive */
935 enum node_type type; /* Code which describes which directive. */
936 char angle_brackets; /* Nonzero => <...> is special. */
937 char traditional_comments; /* Nonzero: keep comments if -traditional. */
938 char pass_thru; /* Copy preprocessed directive to output file. */
941 /* These functions are declared to return int instead of void since they
942 are going to be placed in the table and some old compilers have trouble with
943 pointers to functions returning void. */
945 static int do_assert DO_PROTO;
946 static int do_define DO_PROTO;
947 static int do_elif DO_PROTO;
948 static int do_else DO_PROTO;
949 static int do_endif DO_PROTO;
950 static int do_error DO_PROTO;
951 static int do_ident DO_PROTO;
952 static int do_if DO_PROTO;
953 static int do_include DO_PROTO;
954 static int do_line DO_PROTO;
955 static int do_pragma DO_PROTO;
956 #ifdef SCCS_DIRECTIVE
957 static int do_sccs DO_PROTO;
959 static int do_unassert DO_PROTO;
960 static int do_undef DO_PROTO;
961 static int do_warning DO_PROTO;
962 static int do_xifdef DO_PROTO;
964 /* Here is the actual list of #-directives, most-often-used first. */
966 static struct directive directive_table[] = {
967 { 6, do_define, "define", T_DEFINE, 0, 1},
968 { 2, do_if, "if", T_IF},
969 { 5, do_xifdef, "ifdef", T_IFDEF},
970 { 6, do_xifdef, "ifndef", T_IFNDEF},
971 { 5, do_endif, "endif", T_ENDIF},
972 { 4, do_else, "else", T_ELSE},
973 { 4, do_elif, "elif", T_ELIF},
974 { 4, do_line, "line", T_LINE},
975 { 7, do_include, "include", T_INCLUDE, 1},
976 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
977 { 6, do_include, "import", T_IMPORT, 1},
978 { 5, do_undef, "undef", T_UNDEF},
979 { 5, do_error, "error", T_ERROR},
980 { 7, do_warning, "warning", T_WARNING},
981 #ifdef SCCS_DIRECTIVE
982 { 4, do_sccs, "sccs", T_SCCS},
984 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
985 { 5, do_ident, "ident", T_IDENT},
986 { 6, do_assert, "assert", T_ASSERT},
987 { 8, do_unassert, "unassert", T_UNASSERT},
988 { -1, 0, "", T_UNUSED},
991 /* When a directive handler is called,
992 this points to the # (or the : of the %:) that started the directive. */
993 U_CHAR *directive_start;
995 /* table to tell if char can be part of a C identifier. */
996 U_CHAR is_idchar[256];
997 /* table to tell if char can be first char of a c identifier. */
998 U_CHAR is_idstart[256];
999 /* table to tell if c is horizontal space. */
1000 U_CHAR is_hor_space[256];
1001 /* table to tell if c is horizontal or vertical space. */
1002 static U_CHAR is_space[256];
1003 /* names of some characters */
1004 static char *char_name[256];
1006 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
1007 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
1009 static int errors = 0; /* Error counter for exit code */
1011 /* Name of output file, for error messages. */
1012 static char *out_fname;
1014 /* Zero means dollar signs are punctuation.
1015 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
1016 This must be 0 for correct processing of this ANSI C program:
1018 #define lose(b) foo (b)
1021 static int dollars_in_ident;
1022 #ifndef DOLLARS_IN_IDENTIFIERS
1023 #define DOLLARS_IN_IDENTIFIERS 1
1027 /* Stack of conditionals currently in progress
1028 (including both successful and failing conditionals). */
1031 struct if_stack *next; /* for chaining to the next stack frame */
1032 char *fname; /* copied from input when frame is made */
1033 int lineno; /* similarly */
1034 int if_succeeded; /* true if a leg of this if-group
1035 has been passed through rescan */
1036 U_CHAR *control_macro; /* For #ifndef at start of file,
1037 this is the macro name tested. */
1038 enum node_type type; /* type of last directive seen in this group */
1040 typedef struct if_stack IF_STACK_FRAME;
1041 static IF_STACK_FRAME *if_stack = NULL;
1043 /* Buffer of -M output. */
1044 static char *deps_buffer;
1046 /* Number of bytes allocated in above. */
1047 static int deps_allocated_size;
1049 /* Number of bytes used. */
1050 static int deps_size;
1052 /* Number of bytes since the last newline. */
1053 static int deps_column;
1055 /* Nonzero means -I- has been seen,
1056 so don't look for #include "foo" the source-file directory. */
1057 static int ignore_srcdir;
1059 static int safe_read PROTO((int, char *, int));
1060 static void safe_write PROTO((int, char *, int));
1062 int main PROTO((int, char **));
1064 static void path_include PROTO((char *));
1066 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
1068 static void trigraph_pcp PROTO((FILE_BUF *));
1070 static void newline_fix PROTO((U_CHAR *));
1071 static void name_newline_fix PROTO((U_CHAR *));
1073 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
1075 static void rescan PROTO((FILE_BUF *, int));
1077 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
1079 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1081 static struct tm *timestamp PROTO((void));
1082 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1084 static int redundant_include_p PROTO((char *));
1085 static is_system_include PROTO((char *));
1087 static char *read_filename_string PROTO((int, FILE *));
1088 static struct file_name_map *read_name_map PROTO((char *));
1089 static int open_include_file PROTO((char *, struct file_name_list *));
1091 static void finclude PROTO((int, char *, FILE_BUF *, int, struct file_name_list *));
1092 static void record_control_macro PROTO((char *, U_CHAR *));
1094 static int import_hash PROTO((char *));
1095 static int lookup_import PROTO((char *, struct file_name_list *));
1096 static void add_import PROTO((int, char *));
1098 static char *check_precompiled PROTO((int, char *, char **));
1099 static int check_preconditions PROTO((char *));
1100 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1101 static void pcstring_used PROTO((HASHNODE *));
1102 static void write_output PROTO((void));
1103 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1105 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1107 static int check_macro_name PROTO((U_CHAR *, char *));
1108 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1109 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1111 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1113 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1114 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1116 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1117 static void free_token_list PROTO((struct arglist *));
1119 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1120 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1121 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1123 static void do_once PROTO((void));
1125 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1126 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1127 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1128 static void validate_else PROTO((U_CHAR *));
1130 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1131 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1132 static char *quote_string PROTO((char *, char *));
1133 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1135 /* Last arg to output_line_directive. */
1136 enum file_change_code {same_file, enter_file, leave_file};
1137 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1139 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1142 static char *macarg PROTO((struct argdata *, int));
1144 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1146 static int discard_comments PROTO((U_CHAR *, int, int));
1148 static int change_newlines PROTO((U_CHAR *, int));
1150 char *my_strerror PROTO((int));
1151 void error PRINTF_PROTO_1((char *, ...));
1152 static void verror PROTO((char *, va_list));
1153 static void error_from_errno PROTO((char *));
1154 void warning PRINTF_PROTO_1((char *, ...));
1155 static void vwarning PROTO((char *, va_list));
1156 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1157 static void verror_with_line PROTO((int, char *, va_list));
1158 static void vwarning_with_line PROTO((int, char *, va_list));
1159 void pedwarn PRINTF_PROTO_1((char *, ...));
1160 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1161 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1163 static void print_containing_files PROTO((void));
1165 static int line_for_error PROTO((int));
1166 static int grow_outbuf PROTO((FILE_BUF *, int));
1168 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1169 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1170 static void delete_macro PROTO((HASHNODE *));
1171 static int hashf PROTO((U_CHAR *, int, int));
1173 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1174 static void dump_all_macros PROTO((void));
1175 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1176 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1178 static void initialize_char_syntax PROTO((void));
1179 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1181 static void make_definition PROTO((char *, FILE_BUF *));
1182 static void make_undef PROTO((char *, FILE_BUF *));
1184 static void make_assertion PROTO((char *, char *));
1186 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1188 static void deps_output PROTO((char *, int));
1190 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1191 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1192 static void perror_with_name PROTO((char *));
1193 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1194 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1196 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1197 GENERIC_PTR xmalloc PROTO((size_t));
1198 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1199 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1200 static char *savestring PROTO((char *));
1202 static int file_size_and_mode PROTO((int, int *, long int *));
1203 static void output_dots PROTO((FILE *, int));
1205 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1206 retrying if necessary. Return a negative value if an error occurs,
1207 otherwise return the actual number of bytes read,
1208 which must be LEN unless end-of-file was reached. */
1211 safe_read (desc, ptr, len)
1218 int nchars = read (desc, ptr, left);
1235 /* Write LEN bytes at PTR to descriptor DESC,
1236 retrying if necessary, and treating any real error as fatal. */
1239 safe_write (desc, ptr, len)
1245 int written = write (desc, ptr, len);
1252 pfatal_with_name (out_fname);
1270 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1271 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1272 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1273 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1274 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1276 /* Record the option used with each element of pend_assertions.
1277 This is preparation for supporting more than one option for making
1279 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1280 int inhibit_predefs = 0;
1281 int no_standard_includes = 0;
1282 int no_standard_cplusplus_includes = 0;
1283 int missing_newline = 0;
1285 /* Non-0 means don't output the preprocessed program. */
1286 int inhibit_output = 0;
1287 /* Non-0 means -v, so print the full set of include dirs. */
1290 /* File name which deps are being written to.
1291 This is 0 if deps are being written to stdout. */
1292 char *deps_file = 0;
1293 /* Fopen file mode to open deps_file with. */
1294 char *deps_mode = "a";
1295 /* Stream on which to print the dependency information. */
1296 FILE *deps_stream = 0;
1297 /* Target-name to write with the dependency information. */
1298 char *deps_target = 0;
1301 /* Get rid of any avoidable limit on stack size. */
1305 /* Set the stack limit huge so that alloca (particularly stringtab
1306 * in dbxread.c) does not fail. */
1307 getrlimit (RLIMIT_STACK, &rlim);
1308 rlim.rlim_cur = rlim.rlim_max;
1309 setrlimit (RLIMIT_STACK, &rlim);
1311 #endif /* RLIMIT_STACK defined */
1314 signal (SIGPIPE, pipe_closed);
1317 cp = argv[0] + strlen (argv[0]);
1318 while (cp != argv[0] && cp[-1] != '/'
1319 #ifdef DIR_SEPARATOR
1320 && cp[-1] != DIR_SEPARATOR
1328 /* Remove directories from PROGNAME. */
1332 if ((p = rindex (s, ':')) != 0) s = p + 1; /* skip device */
1333 if ((p = rindex (s, ']')) != 0) s = p + 1; /* skip directory */
1334 if ((p = rindex (s, '>')) != 0) s = p + 1; /* alternate (int'n'l) dir */
1335 s = progname = savestring (s);
1336 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1337 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1338 && (p[1] == 'e' || p[1] == 'E')
1339 && (p[2] == 'x' || p[2] == 'X')
1340 && (p[3] == 'e' || p[3] == 'E')
1349 /* Initialize is_idchar to allow $. */
1350 dollars_in_ident = 1;
1351 initialize_char_syntax ();
1352 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1354 no_line_directives = 0;
1356 dump_macros = dump_none;
1359 cplusplus_comments = 0;
1361 bzero ((char *) pend_files, argc * sizeof (char *));
1362 bzero ((char *) pend_defs, argc * sizeof (char *));
1363 bzero ((char *) pend_undefs, argc * sizeof (char *));
1364 bzero ((char *) pend_assertions, argc * sizeof (char *));
1365 bzero ((char *) pend_includes, argc * sizeof (char *));
1367 /* Process switches and find input file name. */
1369 for (i = 1; i < argc; i++) {
1370 if (argv[i][0] != '-') {
1371 if (out_fname != NULL)
1372 fatal ("Usage: %s [switches] input output", argv[0]);
1373 else if (in_fname != NULL)
1374 out_fname = argv[i];
1378 switch (argv[i][1]) {
1381 if (!strcmp (argv[i], "-include")) {
1383 fatal ("Filename missing after `-include' option");
1385 pend_includes[i] = argv[i+1], i++;
1387 if (!strcmp (argv[i], "-imacros")) {
1389 fatal ("Filename missing after `-imacros' option");
1391 pend_files[i] = argv[i+1], i++;
1393 if (!strcmp (argv[i], "-iprefix")) {
1395 fatal ("Filename missing after `-iprefix' option");
1397 include_prefix = argv[++i];
1399 if (!strcmp (argv[i], "-ifoutput")) {
1400 output_conditionals = 1;
1402 if (!strcmp (argv[i], "-isystem")) {
1403 struct file_name_list *dirtmp;
1406 fatal ("Filename missing after `-isystem' option");
1408 dirtmp = (struct file_name_list *)
1409 xmalloc (sizeof (struct file_name_list));
1411 dirtmp->control_macro = 0;
1412 dirtmp->c_system_include_path = 1;
1413 dirtmp->fname = xmalloc (strlen (argv[i+1]) + 1);
1414 strcpy (dirtmp->fname, argv[++i]);
1415 dirtmp->got_name_map = 0;
1417 if (before_system == 0)
1418 before_system = dirtmp;
1420 last_before_system->next = dirtmp;
1421 last_before_system = dirtmp; /* Tail follows the last one */
1423 /* Add directory to end of path for includes,
1424 with the default prefix at the front of its name. */
1425 if (!strcmp (argv[i], "-iwithprefix")) {
1426 struct file_name_list *dirtmp;
1429 if (include_prefix != 0)
1430 prefix = include_prefix;
1432 prefix = savestring (GCC_INCLUDE_DIR);
1433 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1434 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1435 prefix[strlen (prefix) - 7] = 0;
1438 dirtmp = (struct file_name_list *)
1439 xmalloc (sizeof (struct file_name_list));
1440 dirtmp->next = 0; /* New one goes on the end */
1441 dirtmp->control_macro = 0;
1442 dirtmp->c_system_include_path = 0;
1444 fatal ("Directory name missing after `-iwithprefix' option");
1446 dirtmp->fname = xmalloc (strlen (argv[i+1]) + strlen (prefix) + 1);
1447 strcpy (dirtmp->fname, prefix);
1448 strcat (dirtmp->fname, argv[++i]);
1449 dirtmp->got_name_map = 0;
1451 if (after_include == 0)
1452 after_include = dirtmp;
1454 last_after_include->next = dirtmp;
1455 last_after_include = dirtmp; /* Tail follows the last one */
1457 /* Add directory to main path for includes,
1458 with the default prefix at the front of its name. */
1459 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1460 struct file_name_list *dirtmp;
1463 if (include_prefix != 0)
1464 prefix = include_prefix;
1466 prefix = savestring (GCC_INCLUDE_DIR);
1467 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1468 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1469 prefix[strlen (prefix) - 7] = 0;
1472 dirtmp = (struct file_name_list *)
1473 xmalloc (sizeof (struct file_name_list));
1474 dirtmp->next = 0; /* New one goes on the end */
1475 dirtmp->control_macro = 0;
1476 dirtmp->c_system_include_path = 0;
1478 fatal ("Directory name missing after `-iwithprefixbefore' option");
1480 dirtmp->fname = xmalloc (strlen (argv[i+1]) + strlen (prefix) + 1);
1481 strcpy (dirtmp->fname, prefix);
1482 strcat (dirtmp->fname, argv[++i]);
1483 dirtmp->got_name_map = 0;
1485 append_include_chain (dirtmp, dirtmp);
1487 /* Add directory to end of path for includes. */
1488 if (!strcmp (argv[i], "-idirafter")) {
1489 struct file_name_list *dirtmp;
1491 dirtmp = (struct file_name_list *)
1492 xmalloc (sizeof (struct file_name_list));
1493 dirtmp->next = 0; /* New one goes on the end */
1494 dirtmp->control_macro = 0;
1495 dirtmp->c_system_include_path = 0;
1497 fatal ("Directory name missing after `-idirafter' option");
1499 dirtmp->fname = argv[++i];
1500 dirtmp->got_name_map = 0;
1502 if (after_include == 0)
1503 after_include = dirtmp;
1505 last_after_include->next = dirtmp;
1506 last_after_include = dirtmp; /* Tail follows the last one */
1511 if (out_fname != NULL)
1512 fatal ("Output filename specified twice");
1514 fatal ("Filename missing after -o option");
1515 out_fname = argv[++i];
1516 if (!strcmp (out_fname, "-"))
1521 if (!strcmp (argv[i], "-pedantic"))
1523 else if (!strcmp (argv[i], "-pedantic-errors")) {
1525 pedantic_errors = 1;
1526 } else if (!strcmp (argv[i], "-pcp")) {
1529 fatal ("Filename missing after -pcp option");
1530 pcp_fname = argv[++i];
1532 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1533 ? fopen (pcp_fname, "w")
1535 if (pcp_outfile == 0)
1536 pfatal_with_name (pcp_fname);
1542 if (!strcmp (argv[i], "-traditional")) {
1544 if (dollars_in_ident > 0)
1545 dollars_in_ident = 1;
1546 } else if (!strcmp (argv[i], "-trigraphs")) {
1552 if (! strcmp (argv[i], "-lang-c"))
1553 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1554 if (! strcmp (argv[i], "-lang-c++"))
1555 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1556 if (! strcmp (argv[i], "-lang-c-c++-comments"))
1557 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1558 if (! strcmp (argv[i], "-lang-objc"))
1559 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1560 if (! strcmp (argv[i], "-lang-objc++"))
1561 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1562 if (! strcmp (argv[i], "-lang-asm"))
1564 if (! strcmp (argv[i], "-lint"))
1569 cplusplus = 1, cplusplus_comments = 1;
1573 inhibit_warnings = 1;
1577 if (!strcmp (argv[i], "-Wtrigraphs"))
1579 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1581 else if (!strcmp (argv[i], "-Wcomment"))
1583 else if (!strcmp (argv[i], "-Wno-comment"))
1585 else if (!strcmp (argv[i], "-Wcomments"))
1587 else if (!strcmp (argv[i], "-Wno-comments"))
1589 else if (!strcmp (argv[i], "-Wtraditional"))
1591 else if (!strcmp (argv[i], "-Wno-traditional"))
1593 else if (!strcmp (argv[i], "-Wimport"))
1595 else if (!strcmp (argv[i], "-Wno-import"))
1597 else if (!strcmp (argv[i], "-Werror"))
1598 warnings_are_errors = 1;
1599 else if (!strcmp (argv[i], "-Wno-error"))
1600 warnings_are_errors = 0;
1601 else if (!strcmp (argv[i], "-Wall"))
1609 /* The style of the choices here is a bit mixed.
1610 The chosen scheme is a hybrid of keeping all options in one string
1611 and specifying each option in a separate argument:
1612 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1613 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1614 -M[M][G][D file]. This is awkward to handle in specs, and is not
1616 /* ??? -MG must be specified in addition to one of -M or -MM.
1617 This can be relaxed in the future without breaking anything.
1618 The converse isn't true. */
1620 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1621 if (!strcmp (argv[i], "-MG"))
1623 print_deps_missing_files = 1;
1626 if (!strcmp (argv[i], "-M"))
1628 else if (!strcmp (argv[i], "-MM"))
1630 else if (!strcmp (argv[i], "-MD"))
1632 else if (!strcmp (argv[i], "-MMD"))
1634 /* For -MD and -MMD options, write deps on file named by next arg. */
1635 if (!strcmp (argv[i], "-MD")
1636 || !strcmp (argv[i], "-MMD")) {
1638 fatal ("Filename missing after %s option", argv[i]);
1640 deps_file = argv[i];
1643 /* For -M and -MM, write deps on standard output
1644 and suppress the usual output. */
1645 deps_stream = stdout;
1652 char *p = argv[i] + 2;
1654 while ((c = *p++)) {
1655 /* Arg to -d specifies what parts of macros to dump */
1658 dump_macros = dump_only;
1662 dump_macros = dump_names;
1665 dump_macros = dump_definitions;
1673 if (argv[i][2] == '3')
1678 fprintf (stderr, "GNU CPP version %s", version_string);
1679 #ifdef TARGET_VERSION
1682 fprintf (stderr, "\n");
1687 print_include_names = 1;
1691 if (argv[i][2] != 0)
1692 pend_defs[i] = argv[i] + 2;
1693 else if (i + 1 == argc)
1694 fatal ("Macro name missing after -D option");
1696 i++, pend_defs[i] = argv[i];
1703 if (argv[i][2] != 0)
1705 else if (i + 1 == argc)
1706 fatal ("Assertion missing after -A option");
1710 if (!strcmp (p, "-")) {
1711 /* -A- eliminates all predefined macros and assertions.
1712 Let's include also any that were specified earlier
1713 on the command line. That way we can get rid of any
1714 that were passed automatically in from GCC. */
1716 inhibit_predefs = 1;
1717 for (j = 0; j < i; j++)
1718 pend_defs[j] = pend_assertions[j] = 0;
1720 pend_assertions[i] = p;
1721 pend_assertion_options[i] = "-A";
1726 case 'U': /* JF #undef something */
1727 if (argv[i][2] != 0)
1728 pend_undefs[i] = argv[i] + 2;
1729 else if (i + 1 == argc)
1730 fatal ("Macro name missing after -U option");
1732 pend_undefs[i] = argv[i+1], i++;
1736 put_out_comments = 1;
1739 case 'E': /* -E comes from cc -E; ignore it. */
1743 no_line_directives = 1;
1746 case '$': /* Don't include $ in identifiers. */
1747 dollars_in_ident = 0;
1750 case 'I': /* Add directory to path for includes. */
1752 struct file_name_list *dirtmp;
1754 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1756 /* Don't use any preceding -I directories for #include <...>. */
1757 first_bracket_include = 0;
1760 dirtmp = (struct file_name_list *)
1761 xmalloc (sizeof (struct file_name_list));
1762 dirtmp->next = 0; /* New one goes on the end */
1763 dirtmp->control_macro = 0;
1764 dirtmp->c_system_include_path = 0;
1765 if (argv[i][2] != 0)
1766 dirtmp->fname = argv[i] + 2;
1767 else if (i + 1 == argc)
1768 fatal ("Directory name missing after -I option");
1770 dirtmp->fname = argv[++i];
1771 dirtmp->got_name_map = 0;
1772 append_include_chain (dirtmp, dirtmp);
1778 if (!strcmp (argv[i], "-nostdinc"))
1779 /* -nostdinc causes no default include directories.
1780 You must specify all include-file directories with -I. */
1781 no_standard_includes = 1;
1782 else if (!strcmp (argv[i], "-nostdinc++"))
1783 /* -nostdinc++ causes no default C++-specific include directories. */
1784 no_standard_cplusplus_includes = 1;
1785 else if (!strcmp (argv[i], "-noprecomp"))
1790 /* Sun compiler passes undocumented switch "-undef".
1791 Let's assume it means to inhibit the predefined symbols. */
1792 inhibit_predefs = 1;
1795 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1796 if (in_fname == NULL) {
1799 } else if (out_fname == NULL) {
1802 } /* else fall through into error */
1805 fatal ("Invalid option `%s'", argv[i]);
1810 /* Add dirs from CPATH after dirs from -I. */
1811 /* There seems to be confusion about what CPATH should do,
1812 so for the moment it is not documented. */
1813 /* Some people say that CPATH should replace the standard include dirs,
1814 but that seems pointless: it comes before them, so it overrides them
1816 cp = getenv ("CPATH");
1817 if (cp && ! no_standard_includes)
1820 /* Now that dollars_in_ident is known, initialize is_idchar. */
1821 initialize_char_syntax ();
1823 /* Initialize output buffer */
1825 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1826 outbuf.bufp = outbuf.buf;
1827 outbuf.length = OUTBUF_SIZE;
1829 /* Do partial setup of input buffer for the sake of generating
1830 early #line directives (when -g is in effect). */
1832 fp = &instack[++indepth];
1833 if (in_fname == NULL)
1835 fp->nominal_fname = fp->fname = in_fname;
1838 /* In C++, wchar_t is a distinct basic type, and we can expect
1839 __wchar_t to be defined by cc1plus. */
1841 wchar_type = "__wchar_t";
1843 /* Install __LINE__, etc. Must follow initialize_char_syntax
1844 and option processing. */
1845 initialize_builtins (fp, &outbuf);
1847 /* Do standard #defines and assertions
1848 that identify system and machine type. */
1850 if (!inhibit_predefs) {
1851 char *p = (char *) alloca (strlen (predefs) + 1);
1852 strcpy (p, predefs);
1855 while (*p == ' ' || *p == '\t')
1857 /* Handle -D options. */
1858 if (p[0] == '-' && p[1] == 'D') {
1860 while (*p && *p != ' ' && *p != '\t')
1865 output_line_directive (fp, &outbuf, 0, same_file);
1866 make_definition (q, &outbuf);
1867 while (*p == ' ' || *p == '\t')
1869 } else if (p[0] == '-' && p[1] == 'A') {
1870 /* Handle -A options (assertions). */
1879 past_name = assertion;
1880 /* Locate end of name. */
1881 while (*past_name && *past_name != ' '
1882 && *past_name != '\t' && *past_name != '(')
1884 /* Locate `(' at start of value. */
1886 while (*value && (*value == ' ' || *value == '\t'))
1888 if (*value++ != '(')
1890 while (*value && (*value == ' ' || *value == '\t'))
1893 /* Locate end of value. */
1894 while (*past_value && *past_value != ' '
1895 && *past_value != '\t' && *past_value != ')')
1897 termination = past_value;
1898 while (*termination && (*termination == ' ' || *termination == '\t'))
1900 if (*termination++ != ')')
1902 if (*termination && *termination != ' ' && *termination != '\t')
1904 /* Temporarily null-terminate the value. */
1905 save_char = *termination;
1906 *termination = '\0';
1907 /* Install the assertion. */
1908 make_assertion ("-A", assertion);
1909 *termination = (char) save_char;
1911 while (*p == ' ' || *p == '\t')
1919 /* Now handle the command line options. */
1921 /* Do -U's, -D's and -A's in the order they were seen. */
1922 for (i = 1; i < argc; i++) {
1923 if (pend_undefs[i]) {
1925 output_line_directive (fp, &outbuf, 0, same_file);
1926 make_undef (pend_undefs[i], &outbuf);
1930 output_line_directive (fp, &outbuf, 0, same_file);
1931 make_definition (pend_defs[i], &outbuf);
1933 if (pend_assertions[i])
1934 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1937 done_initializing = 1;
1939 { /* read the appropriate environment variable and if it exists
1940 replace include_defaults with the listed path. */
1942 switch ((objc << 1) + cplusplus)
1945 epath = getenv ("C_INCLUDE_PATH");
1948 epath = getenv ("CPLUS_INCLUDE_PATH");
1951 epath = getenv ("OBJC_INCLUDE_PATH");
1954 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1957 /* If the environment var for this language is set,
1958 add to the default list of include directories. */
1960 char *nstore = (char *) alloca (strlen (epath) + 2);
1962 char *startp, *endp;
1964 for (num_dirs = 1, startp = epath; *startp; startp++)
1965 if (*startp == PATH_SEPARATOR)
1968 = (struct default_include *) xmalloc ((num_dirs
1969 * sizeof (struct default_include))
1970 + sizeof (include_defaults_array));
1971 startp = endp = epath;
1974 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1975 if ((*endp == PATH_SEPARATOR
1976 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1978 && (endp-startp != 1 || !isalpha (*startp))
1983 strncpy (nstore, startp, endp-startp);
1985 strcpy (nstore, ".");
1987 nstore[endp-startp] = '\0';
1989 include_defaults[num_dirs].fname = savestring (nstore);
1990 include_defaults[num_dirs].cplusplus = cplusplus;
1991 include_defaults[num_dirs].cxx_aware = 1;
1995 endp = startp = endp + 1;
1999 /* Put the usual defaults back in at the end. */
2000 bcopy ((char *) include_defaults_array,
2001 (char *) &include_defaults[num_dirs],
2002 sizeof (include_defaults_array));
2006 append_include_chain (before_system, last_before_system);
2007 first_system_include = before_system;
2009 /* Unless -fnostdinc,
2010 tack on the standard include file dirs to the specified list */
2011 if (!no_standard_includes) {
2012 struct default_include *p = include_defaults;
2013 char *specd_prefix = include_prefix;
2014 char *default_prefix = savestring (GCC_INCLUDE_DIR);
2015 int default_len = 0;
2016 /* Remove the `include' from /usr/local/lib/gcc.../include. */
2017 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
2018 default_len = strlen (default_prefix) - 7;
2019 default_prefix[default_len] = 0;
2021 /* Search "translated" versions of GNU directories.
2022 These have /usr/local/lib/gcc... replaced by specd_prefix. */
2023 if (specd_prefix != 0 && default_len != 0)
2024 for (p = include_defaults; p->fname; p++) {
2025 /* Some standard dirs are only for C++. */
2026 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2027 /* Does this dir start with the prefix? */
2028 if (!strncmp (p->fname, default_prefix, default_len)) {
2029 /* Yes; change prefix and add to search list. */
2030 struct file_name_list *new
2031 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2032 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
2033 char *str = xmalloc (this_len + 1);
2034 strcpy (str, specd_prefix);
2035 strcat (str, p->fname + default_len);
2037 new->control_macro = 0;
2038 new->c_system_include_path = !p->cxx_aware;
2039 new->got_name_map = 0;
2040 append_include_chain (new, new);
2041 if (first_system_include == 0)
2042 first_system_include = new;
2046 /* Search ordinary names for GNU include directories. */
2047 for (p = include_defaults; p->fname; p++) {
2048 /* Some standard dirs are only for C++. */
2049 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2050 struct file_name_list *new
2051 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2052 new->control_macro = 0;
2053 new->c_system_include_path = !p->cxx_aware;
2054 new->fname = p->fname;
2055 new->got_name_map = 0;
2056 append_include_chain (new, new);
2057 if (first_system_include == 0)
2058 first_system_include = new;
2063 /* Tack the after_include chain at the end of the include chain. */
2064 append_include_chain (after_include, last_after_include);
2065 if (first_system_include == 0)
2066 first_system_include = after_include;
2068 /* With -v, print the list of dirs to search. */
2070 struct file_name_list *p;
2071 fprintf (stderr, "#include \"...\" search starts here:\n");
2072 for (p = include; p; p = p->next) {
2073 if (p == first_bracket_include)
2074 fprintf (stderr, "#include <...> search starts here:\n");
2075 fprintf (stderr, " %s\n", p->fname);
2077 fprintf (stderr, "End of search list.\n");
2080 /* Scan the -imacros files before the main input.
2081 Much like #including them, but with no_output set
2082 so that only their macro definitions matter. */
2084 no_output++; no_record_file++;
2085 for (i = 1; i < argc; i++)
2086 if (pend_files[i]) {
2087 int fd = open (pend_files[i], O_RDONLY, 0666);
2089 perror_with_name (pend_files[i]);
2090 return FAILURE_EXIT_CODE;
2092 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
2094 no_output--; no_record_file--;
2096 /* Copy the entire contents of the main input file into
2097 the stacked input buffer previously allocated for it. */
2099 /* JF check for stdin */
2100 if (in_fname == NULL || *in_fname == 0) {
2103 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2106 /* -MG doesn't select the form of output and must be specified with one of
2107 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2108 inhibit compilation. */
2109 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2110 fatal ("-MG must be specified with one of -M or -MM");
2112 /* Either of two environment variables can specify output of deps.
2113 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2114 where OUTPUT_FILE is the file to write deps info to
2115 and DEPS_TARGET is the target to mention in the deps. */
2118 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2119 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2120 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2125 spec = getenv ("SUNPRO_DEPENDENCIES");
2132 /* Find the space before the DEPS_TARGET, if there is one. */
2133 /* This should use index. (mrs) */
2134 while (*s != 0 && *s != ' ') s++;
2136 deps_target = s + 1;
2137 output_file = xmalloc (s - spec + 1);
2138 bcopy (spec, output_file, s - spec);
2139 output_file[s - spec] = 0;
2146 deps_file = output_file;
2150 /* For -M, print the expected object file name
2151 as the target of this Make-rule. */
2153 deps_allocated_size = 200;
2154 deps_buffer = xmalloc (deps_allocated_size);
2160 deps_output (deps_target, ':');
2161 } else if (*in_fname == 0) {
2162 deps_output ("-", ':');
2167 /* Discard all directory prefixes from filename. */
2168 if ((q = rindex (in_fname, '/')) != NULL
2169 #ifdef DIR_SEPARATOR
2170 && (q = rindex (in_fname, DIR_SEPARATOR)) != NULL
2177 /* Copy remainder to mungable area. */
2178 p = (char *) alloca (strlen(q) + 8);
2181 /* Output P, but remove known suffixes. */
2185 && p[len - 2] == '.'
2186 && index("cCsSm", p[len - 1]))
2189 && p[len - 3] == '.'
2190 && p[len - 2] == 'c'
2191 && p[len - 1] == 'c')
2194 && p[len - 4] == '.'
2195 && p[len - 3] == 'c'
2196 && p[len - 2] == 'x'
2197 && p[len - 1] == 'x')
2200 && p[len - 4] == '.'
2201 && p[len - 3] == 'c'
2202 && p[len - 2] == 'p'
2203 && p[len - 1] == 'p')
2206 /* Supply our own suffix. */
2213 deps_output (p, ':');
2214 deps_output (in_fname, ' ');
2218 file_size_and_mode (f, &st_mode, &st_size);
2219 fp->nominal_fname = fp->fname = in_fname;
2221 fp->system_header_p = 0;
2222 /* JF all this is mine about reading pipes and ttys */
2223 if (! S_ISREG (st_mode)) {
2224 /* Read input from a file that is not a normal disk file.
2225 We cannot preallocate a buffer with the correct size,
2226 so we must read in the file a piece at the time and make it bigger. */
2233 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2235 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2236 if (cnt < 0) goto perror; /* error! */
2238 if (size != bsize) break; /* End of file */
2240 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2244 /* Read a file whose size we can determine in advance.
2245 For the sake of VMS, st_size is just an upper bound. */
2246 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2247 fp->length = safe_read (f, (char *) fp->buf, st_size);
2248 if (fp->length < 0) goto perror;
2251 fp->if_stack = if_stack;
2253 /* Make sure data ends with a newline. And put a null after it. */
2255 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2256 /* Backslash-newline at end is not good enough. */
2257 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2258 fp->buf[fp->length++] = '\n';
2259 missing_newline = 1;
2261 fp->buf[fp->length] = '\0';
2263 /* Unless inhibited, convert trigraphs in the input. */
2268 /* Now that we know the input file is valid, open the output. */
2270 if (!out_fname || !strcmp (out_fname, ""))
2271 out_fname = "stdout";
2272 else if (! freopen (out_fname, "w", stdout))
2273 pfatal_with_name (out_fname);
2275 output_line_directive (fp, &outbuf, 0, same_file);
2277 /* Scan the -include files before the main input. */
2280 for (i = 1; i < argc; i++)
2281 if (pend_includes[i]) {
2282 int fd = open (pend_includes[i], O_RDONLY, 0666);
2284 perror_with_name (pend_includes[i]);
2285 return FAILURE_EXIT_CODE;
2287 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2291 /* Scan the input, processing macros and directives. */
2293 rescan (&outbuf, 0);
2295 if (missing_newline)
2298 if (pedantic && missing_newline)
2299 pedwarn ("file does not end in newline");
2301 /* Now we have processed the entire input
2302 Write whichever kind of output has been requested. */
2304 if (dump_macros == dump_only)
2306 else if (! inhibit_output) {
2311 /* Don't actually write the deps file if compilation has failed. */
2313 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2314 pfatal_with_name (deps_file);
2315 fputs (deps_buffer, deps_stream);
2316 putc ('\n', deps_stream);
2318 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2319 fatal ("I/O error on output");
2324 if (pcp_outfile && pcp_outfile != stdout
2325 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2326 fatal ("I/O error on `-pcp' output");
2328 if (ferror (stdout) || fclose (stdout) != 0)
2329 fatal ("I/O error on output");
2332 exit (FAILURE_EXIT_CODE);
2333 exit (SUCCESS_EXIT_CODE);
2336 pfatal_with_name (in_fname);
2340 /* Given a colon-separated list of file names PATH,
2341 add all the names to the search path for include files. */
2355 struct file_name_list *dirtmp;
2357 /* Find the end of this name. */
2358 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2360 /* An empty name in the path stands for the current directory. */
2365 /* Otherwise use the directory that is named. */
2366 name = xmalloc (q - p + 1);
2367 bcopy (p, name, q - p);
2371 dirtmp = (struct file_name_list *)
2372 xmalloc (sizeof (struct file_name_list));
2373 dirtmp->next = 0; /* New one goes on the end */
2374 dirtmp->control_macro = 0;
2375 dirtmp->c_system_include_path = 0;
2376 dirtmp->fname = name;
2377 dirtmp->got_name_map = 0;
2378 append_include_chain (dirtmp, dirtmp);
2380 /* Advance past this name. */
2384 /* Skip the colon. */
2389 /* Return the address of the first character in S that equals C.
2390 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2391 Return 0 if there is no such character. Assume that C itself is not '\0'.
2392 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2393 but unfortunately memchr isn't autoconfigured yet. */
2401 char *p = (char *) s;
2403 char *q = index (p, c);
2405 return (U_CHAR *) q;
2407 size_t l = strlen (p);
2417 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2418 before main CCCP processing. Name `pcp' is also in honor of the
2419 drugs the trigraph designers must have been on.
2421 Using an extra pass through the buffer takes a little extra time,
2422 but is infinitely less hairy than trying to handle trigraphs inside
2423 strings, etc. everywhere, and also makes sure that trigraphs are
2424 only translated in the top level of processing. */
2430 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2433 fptr = bptr = sptr = buf->buf;
2434 lptr = fptr + buf->length;
2435 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2472 len = sptr - fptr - 2;
2474 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2475 C, this will be memmove (). */
2476 if (bptr != fptr && len > 0)
2477 bcopy ((char *) fptr, (char *) bptr, len);
2483 len = buf->length - (fptr - buf->buf);
2484 if (bptr != fptr && len > 0)
2485 bcopy ((char *) fptr, (char *) bptr, len);
2486 buf->length -= fptr - bptr;
2487 buf->buf[buf->length] = '\0';
2488 if (warn_trigraphs && fptr != bptr)
2489 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2492 /* Move all backslash-newline pairs out of embarrassing places.
2493 Exchange all such pairs following BP
2494 with any potentially-embarrassing characters that follow them.
2495 Potentially-embarrassing characters are / and *
2496 (because a backslash-newline inside a comment delimiter
2497 would cause it not to be recognized). */
2503 register U_CHAR *p = bp;
2505 /* First count the backslash-newline pairs here. */
2507 while (p[0] == '\\' && p[1] == '\n')
2510 /* What follows the backslash-newlines is not embarrassing. */
2512 if (*p != '/' && *p != '*')
2515 /* Copy all potentially embarrassing characters
2516 that follow the backslash-newline pairs
2517 down to where the pairs originally started. */
2519 while (*p == '*' || *p == '/')
2522 /* Now write the same number of pairs after the embarrassing chars. */
2529 /* Like newline_fix but for use within a directive-name.
2530 Move any backslash-newlines up past any following symbol constituents. */
2533 name_newline_fix (bp)
2536 register U_CHAR *p = bp;
2538 /* First count the backslash-newline pairs here. */
2539 while (p[0] == '\\' && p[1] == '\n')
2542 /* What follows the backslash-newlines is not embarrassing. */
2547 /* Copy all potentially embarrassing characters
2548 that follow the backslash-newline pairs
2549 down to where the pairs originally started. */
2551 while (is_idchar[*p])
2554 /* Now write the same number of pairs after the embarrassing chars. */
2561 /* Look for lint commands in comments.
2563 When we come in here, ibp points into a comment. Limit is as one expects.
2564 scan within the comment -- it should start, after lwsp, with a lint command.
2565 If so that command is returned as a (constant) string.
2567 Upon return, any arg will be pointed to with argstart and will be
2568 arglen long. Note that we don't parse that arg since it will just
2569 be printed out again.
2573 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2574 register U_CHAR *ibp;
2575 register U_CHAR *limit;
2576 U_CHAR **argstart; /* point to command arg */
2577 int *arglen, *cmdlen; /* how long they are */
2580 register U_CHAR *numptr; /* temp for arg parsing */
2584 SKIP_WHITE_SPACE (ibp);
2586 if (ibp >= limit) return NULL;
2588 linsize = limit - ibp;
2590 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2591 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2593 return "NOTREACHED";
2595 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2599 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2601 return "LINTLIBRARY";
2603 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2605 ibp += 7; linsize -= 7;
2606 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2608 /* OK, read a number */
2609 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2611 *arglen = numptr - *argstart;
2618 * The main loop of the program.
2620 * Read characters from the input stack, transferring them to the
2623 * Macros are expanded and push levels on the input stack.
2624 * At the end of such a level it is popped off and we keep reading.
2625 * At the end of any other kind of level, we return.
2626 * #-directives are handled, except within macros.
2628 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2629 * and insert them when appropriate. This is set while scanning macro
2630 * arguments before substitution. It is zero when scanning for final output.
2631 * There are three types of Newline markers:
2632 * * Newline - follows a macro name that was not expanded
2633 * because it appeared inside an expansion of the same macro.
2634 * This marker prevents future expansion of that identifier.
2635 * When the input is rescanned into the final output, these are deleted.
2636 * These are also deleted by ## concatenation.
2637 * * Newline Space (or Newline and any other whitespace character)
2638 * stands for a place that tokens must be separated or whitespace
2639 * is otherwise desirable, but where the ANSI standard specifies there
2640 * is no whitespace. This marker turns into a Space (or whichever other
2641 * whitespace char appears in the marker) in the final output,
2642 * but it turns into nothing in an argument that is stringified with #.
2643 * Such stringified arguments are the only place where the ANSI standard
2644 * specifies with precision that whitespace may not appear.
2646 * During this function, IP->bufp is kept cached in IBP for speed of access.
2647 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2648 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2649 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2650 * explicitly, and before RECACHE, since RECACHE uses OBP.
2654 rescan (op, output_marks)
2658 /* Character being scanned in main loop. */
2661 /* Length of pending accumulated identifier. */
2662 register int ident_length = 0;
2664 /* Hash code of pending accumulated identifier. */
2665 register int hash = 0;
2667 /* Current input level (&instack[indepth]). */
2670 /* Pointer for scanning input. */
2671 register U_CHAR *ibp;
2673 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2674 register U_CHAR *limit;
2676 /* Pointer for storing output. */
2677 register U_CHAR *obp;
2679 /* REDO_CHAR is nonzero if we are processing an identifier
2680 after backing up over the terminating character.
2681 Sometimes we process an identifier without backing up over
2682 the terminating character, if the terminating character
2683 is not special. Backing up is done so that the terminating character
2684 will be dispatched on again once the identifier is dealt with. */
2687 /* 1 if within an identifier inside of which a concatenation
2688 marker (Newline -) has been seen. */
2689 int concatenated = 0;
2691 /* While scanning a comment or a string constant,
2692 this records the line it started on, for error messages. */
2695 /* Record position of last `real' newline. */
2696 U_CHAR *beg_of_line;
2698 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2701 do { ip->macro->type = T_MACRO; \
2702 if (ip->free_ptr) free (ip->free_ptr); \
2703 --indepth; } while (0)
2705 /* Reload `rescan's local variables that describe the current
2706 level of the input stack. */
2709 do { ip = &instack[indepth]; \
2711 limit = ip->buf + ip->length; \
2713 check_expand (op, limit - ibp); \
2715 obp = op->bufp; } while (0)
2717 if (no_output && instack[indepth].fname != 0)
2718 skip_if_group (&instack[indepth], 1, NULL);
2725 /* Our caller must always put a null after the end of
2726 the input at each input stack level. */
2736 if (*ibp == '\n' && !ip->macro) {
2737 /* At the top level, always merge lines ending with backslash-newline,
2738 even in middle of identifier. But do not merge lines in a macro,
2739 since backslash might be followed by a newline-space marker. */
2742 --obp; /* remove backslash from obuf */
2745 /* If ANSI, backslash is just another character outside a string. */
2748 /* Otherwise, backslash suppresses specialness of following char,
2749 so copy it here to prevent the switch from seeing it.
2750 But first get any pending identifier processed. */
2751 if (ident_length > 0)
2758 if (ident_length || ip->macro || traditional)
2760 while (*ibp == '\\' && ibp[1] == '\n') {
2766 /* Treat this %: digraph as if it were #. */
2770 if (assertions_flag) {
2771 /* Copy #foo (bar lose) without macro expansion. */
2772 obp[-1] = '#'; /* In case it was '%'. */
2773 SKIP_WHITE_SPACE (ibp);
2774 while (is_idchar[*ibp])
2776 SKIP_WHITE_SPACE (ibp);
2779 skip_paren_group (ip);
2780 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2781 obp += ip->bufp - ibp;
2786 /* If this is expanding a macro definition, don't recognize
2787 preprocessing directives. */
2790 /* If this is expand_into_temp_buffer,
2791 don't recognize them either. Warn about them
2792 only after an actual newline at this level,
2793 not at the beginning of the input level. */
2795 if (ip->buf != beg_of_line)
2796 warning ("preprocessing directive not recognized within macro arg");
2803 /* # keyword: a # must be first nonblank char on the line */
2804 if (beg_of_line == 0)
2809 /* Scan from start of line, skipping whitespace, comments
2810 and backslash-newlines, and see if we reach this #.
2811 If not, this # is not special. */
2813 /* If -traditional, require # to be at beginning of line. */
2816 if (is_hor_space[*bp])
2818 else if (*bp == '\\' && bp[1] == '\n')
2820 else if (*bp == '/' && bp[1] == '*') {
2822 while (!(*bp == '*' && bp[1] == '/'))
2826 /* There is no point in trying to deal with C++ // comments here,
2827 because if there is one, then this # must be part of the
2828 comment and we would never reach here. */
2834 while (bp[1] == '\\' && bp[2] == '\n')
2838 /* %: appears at start of line; skip past the ':' too. */
2847 /* This # can start a directive. */
2849 --obp; /* Don't copy the '#' */
2853 if (! handle_directive (ip, op)) {
2857 /* Not a known directive: treat it as ordinary text.
2858 IP, OP, IBP, etc. have not been changed. */
2859 if (no_output && instack[indepth].fname) {
2860 /* If not generating expanded output,
2861 what we do with ordinary text is skip it.
2862 Discard everything until next # directive. */
2863 skip_if_group (&instack[indepth], 1, 0);
2868 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2869 /* Don't expand an identifier that could be a macro directive.
2870 (Section 3.8.3 of the ANSI C standard) */
2871 SKIP_WHITE_SPACE (ibp);
2872 if (is_idstart[*ibp])
2875 while (is_idchar[*ibp])
2883 /* A # directive has been successfully processed. */
2884 /* If not generating expanded output, ignore everything until
2885 next # directive. */
2886 if (no_output && instack[indepth].fname)
2887 skip_if_group (&instack[indepth], 1, 0);
2893 case '\"': /* skip quoted string */
2895 /* A single quoted string is treated like a double -- some
2896 programs (e.g., troff) are perverse this way */
2901 start_line = ip->lineno;
2903 /* Skip ahead to a matching quote. */
2907 if (ip->macro != 0) {
2908 /* try harder: this string crosses a macro expansion boundary.
2909 This can happen naturally if -traditional.
2910 Otherwise, only -D can make a macro with an unmatched quote. */
2916 error_with_line (line_for_error (start_line),
2917 "unterminated string or character constant");
2918 error_with_line (multiline_string_line,
2919 "possible real start of unterminated constant");
2920 multiline_string_line = 0;
2929 /* Traditionally, end of line ends a string constant with no error.
2930 So exit the loop and record the new line. */
2936 error_with_line (line_for_error (start_line),
2937 "unterminated character constant");
2940 if (pedantic && multiline_string_line == 0) {
2941 pedwarn_with_line (line_for_error (start_line),
2942 "string constant runs past end of line");
2944 if (multiline_string_line == 0)
2945 multiline_string_line = ip->lineno - 1;
2952 /* Backslash newline is replaced by nothing at all,
2953 but keep the line counts correct. */
2958 /* ANSI stupidly requires that in \\ the second \
2959 is *not* prevented from combining with a newline. */
2960 while (*ibp == '\\' && ibp[1] == '\n') {
2979 if (*ibp == '\\' && ibp[1] == '\n')
2983 && !(cplusplus_comments && *ibp == '/'))
2991 /* C++ style comment... */
2992 start_line = ip->lineno;
2994 --ibp; /* Back over the slash */
2997 /* Comments are equivalent to spaces. */
2998 if (! put_out_comments)
3001 /* must fake up a comment here */
3006 U_CHAR *before_bp = ibp+2;
3008 while (ibp < limit) {
3009 if (ibp[-1] != '\\' && *ibp == '\n') {
3010 if (put_out_comments) {
3011 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3012 obp += ibp - before_bp;
3018 /* Copy the newline into the output buffer, in order to
3019 avoid the pain of a #line every time a multiline comment
3021 if (!put_out_comments)
3032 /* Ordinary C comment. Skip it, optionally copying it to output. */
3034 start_line = ip->lineno;
3036 ++ibp; /* Skip the star. */
3038 /* If this cpp is for lint, we peek inside the comments: */
3042 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
3044 if (lintcmd != NULL) {
3046 check_expand (op, cmdlen + arglen + 14);
3048 /* I believe it is always safe to emit this newline: */
3050 bcopy ("#pragma lint ", (char *) obp, 13);
3052 bcopy (lintcmd, (char *) obp, cmdlen);
3057 bcopy (argbp, (char *) obp, arglen);
3061 /* OK, now bring us back to the state we were in before we entered
3062 this branch. We need #line because the #pragma's newline always
3063 messes up the line count. */
3065 output_line_directive (ip, op, 0, same_file);
3066 check_expand (op, limit - ibp + 2);
3072 /* Comments are equivalent to spaces.
3073 Note that we already output the slash; we might not want it.
3074 For -traditional, a comment is equivalent to nothing. */
3075 if (! put_out_comments) {
3085 U_CHAR *before_bp = ibp;
3087 while (ibp < limit) {
3090 if (warn_comments && *ibp == '*')
3091 warning ("`/*' within comment");
3094 if (*ibp == '\\' && ibp[1] == '\n')
3096 if (ibp >= limit || *ibp == '/')
3101 /* Copy the newline into the output buffer, in order to
3102 avoid the pain of a #line every time a multiline comment
3104 if (!put_out_comments)
3112 error_with_line (line_for_error (start_line),
3113 "unterminated comment");
3116 if (put_out_comments) {
3117 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3118 obp += ibp - before_bp;
3125 if (!dollars_in_ident)
3129 case '0': case '1': case '2': case '3': case '4':
3130 case '5': case '6': case '7': case '8': case '9':
3131 /* If digit is not part of identifier, it starts a number,
3132 which means that following letters are not an identifier.
3133 "0x5" does not refer to an identifier "x5".
3134 So copy all alphanumerics that follow without accumulating
3135 as an identifier. Periods also, for sake of "3.e7". */
3137 if (ident_length == 0) {
3139 while (ibp[0] == '\\' && ibp[1] == '\n') {
3144 if (!is_idchar[c] && c != '.') {
3149 /* A sign can be part of a preprocessing number
3150 if it follows an e. */
3151 if (c == 'e' || c == 'E') {
3152 while (ibp[0] == '\\' && ibp[1] == '\n') {
3156 if (*ibp == '+' || *ibp == '-') {
3158 /* But traditional C does not let the token go past the sign. */
3169 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3170 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3171 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3172 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3174 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3175 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3176 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3177 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3181 /* Compute step of hash function, to avoid a proc call on every token */
3182 hash = HASHSTEP (hash, c);
3186 if (ip->fname == 0 && *ibp == '-') {
3187 /* Newline - inhibits expansion of preceding token.
3188 If expanding a macro arg, we keep the newline -.
3189 In final output, it is deleted.
3190 We recognize Newline - in macro bodies and macro args. */
3191 if (! concatenated) {
3196 if (!output_marks) {
3199 /* If expanding a macro arg, keep the newline -. */
3205 /* If reprocessing a macro expansion, newline is a special marker. */
3206 else if (ip->macro != 0) {
3207 /* Newline White is a "funny space" to separate tokens that are
3208 supposed to be separate but without space between.
3209 Here White means any whitespace character.
3210 Newline - marks a recursive macro use that is not
3211 supposed to be expandable. */
3213 if (is_space[*ibp]) {
3214 /* Newline Space does not prevent expansion of preceding token
3215 so expand the preceding token and then come back. */
3216 if (ident_length > 0)
3219 /* If generating final output, newline space makes a space. */
3220 if (!output_marks) {
3222 /* And Newline Newline makes a newline, so count it. */
3223 if (obp[-1] == '\n')
3226 /* If expanding a macro arg, keep the newline space.
3227 If the arg gets stringified, newline space makes nothing. */
3230 } else abort (); /* Newline followed by something random? */
3234 /* If there is a pending identifier, handle it and come back here. */
3235 if (ident_length > 0)
3240 /* Update the line counts and output a #line if necessary. */
3243 if (ip->lineno != op->lineno) {
3245 output_line_directive (ip, op, 1, same_file);
3246 check_expand (op, limit - ibp);
3251 /* Come here either after (1) a null character that is part of the input
3252 or (2) at the end of the input, because there is a null there. */
3255 /* Our input really contains a null character. */
3258 /* At end of a macro-expansion level, pop it and read next level. */
3259 if (ip->macro != 0) {
3262 /* If traditional, and we have an identifier that ends here,
3263 process it now, so we get the right error for recursion. */
3264 if (traditional && ident_length
3265 && ! is_idchar[*instack[indepth - 1].bufp]) {
3274 /* If we don't have a pending identifier,
3275 return at end of input. */
3276 if (ident_length == 0) {
3284 /* If we do have a pending identifier, just consider this null
3285 a special character and arrange to dispatch on it again.
3286 The second time, IDENT_LENGTH will be zero so we will return. */
3292 /* Handle the case of a character such as /, ', " or null
3293 seen following an identifier. Back over it so that
3294 after the identifier is processed the special char
3295 will be dispatched on again. */
3305 if (ident_length > 0) {
3306 register HASHNODE *hp;
3308 /* We have just seen an identifier end. If it's a macro, expand it.
3310 IDENT_LENGTH is the length of the identifier
3311 and HASH is its hash code.
3313 The identifier has already been copied to the output,
3314 so if it is a macro we must remove it.
3316 If REDO_CHAR is 0, the char that terminated the identifier
3317 has been skipped in the output and the input.
3318 OBP-IDENT_LENGTH-1 points to the identifier.
3319 If the identifier is a macro, we must back over the terminator.
3321 If REDO_CHAR is 1, the terminating char has already been
3322 backed over. OBP-IDENT_LENGTH points to the identifier. */
3324 if (!pcp_outfile || pcp_inside_if) {
3325 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3328 if (hp->length == ident_length) {
3329 int obufp_before_macroname;
3330 int op_lineno_before_macroname;
3331 register int i = ident_length;
3332 register U_CHAR *p = hp->name;
3333 register U_CHAR *q = obp - i;
3339 do { /* All this to avoid a strncmp () */
3344 /* We found a use of a macro name.
3345 see if the context shows it is a macro call. */
3347 /* Back up over terminating character if not already done. */
3353 /* Save this as a displacement from the beginning of the output
3354 buffer. We can not save this as a position in the output
3355 buffer, because it may get realloc'ed by RECACHE. */
3356 obufp_before_macroname = (obp - op->buf) - ident_length;
3357 op_lineno_before_macroname = op->lineno;
3359 if (hp->type == T_PCSTRING) {
3360 pcstring_used (hp); /* Mark the definition of this key
3361 as needed, ensuring that it
3363 break; /* Exit loop, since the key cannot have a
3364 definition any longer. */
3367 /* Record whether the macro is disabled. */
3368 disabled = hp->type == T_DISABLED;
3370 /* This looks like a macro ref, but if the macro was disabled,
3371 just copy its name and put in a marker if requested. */
3375 /* This error check caught useful cases such as
3376 #define foo(x,y) bar (x (y,0), y)
3379 error ("recursive use of macro `%s'", hp->name);
3383 check_expand (op, limit - ibp + 2);
3390 /* If macro wants an arglist, verify that a '(' follows.
3391 first skip all whitespace, copying it to the output
3392 after the macro name. Then, if there is no '(',
3393 decide this is not a macro call and leave things that way. */
3394 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3395 && hp->value.defn->nargs >= 0)
3397 U_CHAR *old_ibp = ibp;
3398 U_CHAR *old_obp = obp;
3399 int old_iln = ip->lineno;
3400 int old_oln = op->lineno;
3403 /* Scan forward over whitespace, copying it to the output. */
3404 if (ibp == limit && ip->macro != 0) {
3409 old_iln = ip->lineno;
3410 old_oln = op->lineno;
3412 /* A comment: copy it unchanged or discard it. */
3413 else if (*ibp == '/' && ibp[1] == '*') {
3414 if (put_out_comments) {
3417 } else if (! traditional) {
3421 while (ibp + 1 != limit
3422 && !(ibp[0] == '*' && ibp[1] == '/')) {
3423 /* We need not worry about newline-marks,
3424 since they are never found in comments. */
3426 /* Newline in a file. Count it. */
3430 if (put_out_comments)
3436 if (put_out_comments) {
3441 else if (is_space[*ibp]) {
3443 if (ibp[-1] == '\n') {
3444 if (ip->macro == 0) {
3445 /* Newline in a file. Count it. */
3448 } else if (!output_marks) {
3449 /* A newline mark, and we don't want marks
3450 in the output. If it is newline-hyphen,
3451 discard it entirely. Otherwise, it is
3452 newline-whitechar, so keep the whitechar. */
3462 /* A newline mark; copy both chars to the output. */
3470 /* It isn't a macro call.
3471 Put back the space that we just skipped. */
3474 ip->lineno = old_iln;
3475 op->lineno = old_oln;
3476 /* Exit the for loop. */
3481 /* This is now known to be a macro call.
3482 Discard the macro name from the output,
3483 along with any following whitespace just copied,
3484 but preserve newlines if not outputting marks since this
3485 is more likely to do the right thing with line numbers. */
3486 obp = op->buf + obufp_before_macroname;
3488 op->lineno = op_lineno_before_macroname;
3490 int newlines = op->lineno - op_lineno_before_macroname;
3491 while (0 < newlines--)
3495 /* Prevent accidental token-pasting with a character
3496 before the macro call. */
3497 if (!traditional && obp != op->buf) {
3499 case '!': case '%': case '&': case '*':
3500 case '+': case '-': case '/': case ':':
3501 case '<': case '=': case '>': case '^':
3503 /* If we are expanding a macro arg, make a newline marker
3504 to separate the tokens. If we are making real output,
3505 a plain space will do. */
3512 /* Expand the macro, reading arguments as needed,
3513 and push the expansion on the input stack. */
3516 macroexpand (hp, op);
3518 /* Reexamine input stack, since macroexpand has pushed
3519 a new level on it. */
3526 } /* End hash-table-search loop */
3528 ident_length = hash = 0; /* Stop collecting identifier */
3531 } /* End if (ident_length > 0) */
3533 } /* End per-char loop */
3535 /* Come here to return -- but first give an error message
3536 if there was an unterminated successful conditional. */
3538 if (if_stack != ip->if_stack)
3542 switch (if_stack->type)
3563 error_with_line (line_for_error (if_stack->lineno),
3564 "unterminated `#%s' conditional", str);
3566 if_stack = ip->if_stack;
3570 * Rescan a string into a temporary buffer and return the result
3571 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3573 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3574 * and insert such markers when appropriate. See `rescan' for details.
3575 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3576 * before substitution; it is 0 for other uses.
3579 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3580 U_CHAR *buf, *limit;
3581 int output_marks, assertions;
3583 register FILE_BUF *ip;
3585 int length = limit - buf;
3587 int odepth = indepth;
3588 int save_assertions_flag = assertions_flag;
3590 assertions_flag = assertions;
3595 /* Set up the input on the input stack. */
3597 buf1 = (U_CHAR *) alloca (length + 1);
3599 register U_CHAR *p1 = buf;
3600 register U_CHAR *p2 = buf1;
3607 /* Set up to receive the output. */
3609 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3610 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3615 CHECK_DEPTH ({return obuf;});
3619 ip = &instack[indepth];
3621 ip->nominal_fname = 0;
3622 ip->system_header_p = 0;
3625 ip->length = length;
3626 ip->buf = ip->bufp = buf1;
3627 ip->if_stack = if_stack;
3629 ip->lineno = obuf.lineno = 1;
3631 /* Scan the input, create the output. */
3632 rescan (&obuf, output_marks);
3634 /* Pop input stack to original state. */
3637 if (indepth != odepth)
3640 /* Record the output. */
3641 obuf.length = obuf.bufp - obuf.buf;
3643 assertions_flag = save_assertions_flag;
3648 * Process a # directive. Expects IP->bufp to point after the '#', as in
3649 * `#define foo bar'. Passes to the directive handler
3650 * (do_define, do_include, etc.): the addresses of the 1st and
3651 * last chars of the directive (starting immediately after the #
3652 * keyword), plus op and the keyword table pointer. If the directive
3653 * contains comments it is copied into a temporary buffer sans comments
3654 * and the temporary buffer is passed to the directive handler instead.
3655 * Likewise for backslash-newlines.
3657 * Returns nonzero if this was a known # directive.
3658 * Otherwise, returns zero, without advancing the input pointer.
3662 handle_directive (ip, op)
3665 register U_CHAR *bp, *cp;
3666 register struct directive *kt;
3667 register int ident_length;
3670 /* Nonzero means we must copy the entire directive
3671 to get rid of comments or backslash-newlines. */
3672 int copy_directive = 0;
3674 U_CHAR *ident, *after_ident;
3678 /* Record where the directive started. do_xifdef needs this. */
3679 directive_start = bp - 1;
3681 /* Skip whitespace and \-newline. */
3683 if (is_hor_space[*bp]) {
3684 if (*bp != ' ' && *bp != '\t' && pedantic)
3685 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3687 } else if (*bp == '/' && (bp[1] == '*'
3688 || (cplusplus_comments && bp[1] == '/'))) {
3690 skip_to_end_of_comment (ip, &ip->lineno, 0);
3692 } else if (*bp == '\\' && bp[1] == '\n') {
3693 bp += 2; ip->lineno++;
3697 /* Now find end of directive name.
3698 If we encounter a backslash-newline, exchange it with any following
3699 symbol-constituents so that we end up with a contiguous name. */
3706 if (*cp == '\\' && cp[1] == '\n')
3707 name_newline_fix (cp);
3713 ident_length = cp - bp;
3717 /* A line of just `#' becomes blank. */
3719 if (ident_length == 0 && *after_ident == '\n') {
3720 ip->bufp = after_ident;
3724 if (ident_length == 0 || !is_idstart[*ident]) {
3726 while (is_idchar[*p]) {
3727 if (*p < '0' || *p > '9')
3731 /* Handle # followed by a line number. */
3732 if (p != ident && !is_idchar[*p]) {
3733 static struct directive line_directive_table[] = {
3734 { 4, do_line, "line", T_LINE},
3737 pedwarn ("`#' followed by integer");
3738 after_ident = ident;
3739 kt = line_directive_table;
3743 /* Avoid error for `###' and similar cases unless -pedantic. */
3745 while (*p == '#' || is_hor_space[*p]) p++;
3747 if (pedantic && !lang_asm)
3748 warning ("invalid preprocessing directive");
3754 error ("invalid preprocessing directive name");
3760 * Decode the keyword and call the appropriate expansion
3761 * routine, after moving the input pointer up to the next line.
3763 for (kt = directive_table; kt->length > 0; kt++) {
3764 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3765 register U_CHAR *buf;
3766 register U_CHAR *limit;
3769 int *already_output;
3771 /* Nonzero means do not delete comments within the directive.
3772 #define needs this when -traditional. */
3777 limit = ip->buf + ip->length;
3780 keep_comments = traditional && kt->traditional_comments;
3781 /* #import is defined only in Objective C, or when on the NeXT. */
3782 if (kt->type == T_IMPORT
3783 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3786 /* Find the end of this directive (first newline not backslashed
3787 and not in a string or comment).
3788 Set COPY_DIRECTIVE if the directive must be copied
3789 (it contains a backslash-newline or a comment). */
3791 buf = bp = after_ident;
3792 while (bp < limit) {
3793 register U_CHAR c = *bp++;
3801 } else if (traditional)
3808 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3809 /* Don't bother calling the directive if we already got an error
3810 message due to unterminated string. Skip everything and pretend
3811 we called the directive. */
3814 /* Traditional preprocessing permits unterminated strings. */
3823 /* <...> is special for #include. */
3825 if (!kt->angle_brackets)
3827 while (bp < limit && *bp != '>' && *bp != '\n') {
3828 if (*bp == '\\' && bp[1] == '\n') {
3838 if (*bp == '\\' && bp[1] == '\n')
3841 || (cplusplus_comments && *bp == '/')) {
3842 U_CHAR *obp = bp - 1;
3844 skip_to_end_of_comment (ip, &ip->lineno, 0);
3846 /* No need to copy the directive because of a comment at the end;
3847 just don't include the comment in the directive. */
3848 if (bp == limit || *bp == '\n') {
3852 /* Don't remove the comments if -traditional. */
3853 if (! keep_comments)
3862 pedwarn ("%s in preprocessing directive", char_name[c]);
3866 --bp; /* Point to the newline */
3874 resume_p = ip->bufp;
3875 /* BP is the end of the directive.
3876 RESUME_P is the next interesting data after the directive.
3877 A comment may come between. */
3879 /* If a directive should be copied through, and -E was given,
3880 pass it through before removing comments. */
3881 if (!no_output && kt->pass_thru && put_out_comments) {
3884 /* Output directive name. */
3885 check_expand (op, kt->length + 2);
3886 /* Make sure # is at the start of a line */
3887 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3892 bcopy (kt->name, op->bufp, kt->length);
3893 op->bufp += kt->length;
3895 /* Output arguments. */
3897 check_expand (op, len);
3898 bcopy (buf, (char *) op->bufp, len);
3900 /* Take account of any (escaped) newlines just output. */
3902 if (buf[len] == '\n')
3905 already_output = &junk;
3906 } /* Don't we need a newline or #line? */
3908 if (copy_directive) {
3909 register U_CHAR *xp = buf;
3910 /* Need to copy entire directive into temp buffer before dispatching */
3912 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3916 /* Copy to the new buffer, deleting comments
3917 and backslash-newlines (and whitespace surrounding the latter). */
3920 register U_CHAR c = *xp++;
3925 abort (); /* A bare newline should never part of the line. */
3928 /* <...> is special for #include. */
3930 if (!kt->angle_brackets)
3932 while (xp < bp && c != '>') {
3934 if (c == '\\' && xp < bp && *xp == '\n')
3945 if (cp != buf && is_space[cp[-1]]) {
3946 while (cp != buf && is_space[cp[-1]]) cp--;
3948 SKIP_WHITE_SPACE (xp);
3949 } else if (is_space[*xp]) {
3951 SKIP_WHITE_SPACE (xp);
3953 } else if (traditional && xp < bp) {
3961 register U_CHAR *bp1
3962 = skip_quoted_string (xp - 1, bp, ip->lineno,
3963 NULL_PTR, NULL_PTR, NULL_PTR);
3977 || (cplusplus_comments && *xp == '/')) {
3979 /* If we already copied the directive through,
3980 already_output != 0 prevents outputting comment now. */
3981 skip_to_end_of_comment (ip, already_output, 0);
3983 while (xp != ip->bufp)
3985 /* Delete or replace the slash. */
3986 else if (traditional)
3995 /* Null-terminate the copy. */
4001 ip->bufp = resume_p;
4003 /* Some directives should be written out for cc1 to process,
4004 just as if they were not defined. And sometimes we're copying
4005 definitions through. */
4007 if (!no_output && already_output == 0
4009 || (kt->type == T_DEFINE
4010 && (dump_macros == dump_names
4011 || dump_macros == dump_definitions)))) {
4014 /* Output directive name. */
4015 check_expand (op, kt->length + 1);
4017 bcopy (kt->name, (char *) op->bufp, kt->length);
4018 op->bufp += kt->length;
4020 if (kt->pass_thru || dump_macros == dump_definitions) {
4021 /* Output arguments. */
4023 check_expand (op, len);
4024 bcopy (buf, (char *) op->bufp, len);
4026 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
4029 SKIP_WHITE_SPACE (xp);
4031 while (is_idchar[*xp]) xp++;
4033 check_expand (op, len + 1);
4035 bcopy (yp, op->bufp, len);
4038 } /* Don't we need a newline or #line? */
4040 /* Call the appropriate directive handler. buf now points to
4041 either the appropriate place in the input buffer, or to
4042 the temp buffer if it was necessary to make one. cp
4043 points to the first char after the contents of the (possibly
4044 copied) directive, in either case. */
4045 (*kt->func) (buf, cp, op, kt);
4046 check_expand (op, ip->length - (ip->bufp - ip->buf));
4052 /* It is deliberate that we don't warn about undefined directives.
4053 That is the responsibility of cc1. */
4060 static struct tm *timebuf;
4062 time_t t = time ((time_t *)0);
4063 timebuf = localtime (&t);
4068 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4069 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4073 * expand things like __FILE__. Place the expansion into the output
4074 * buffer *without* rescanning.
4078 special_symbol (hp, op)
4085 FILE_BUF *ip = NULL;
4088 int paren = 0; /* For special `defined' keyword */
4090 if (pcp_outfile && pcp_inside_if
4091 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4092 error ("Predefined macro `%s' used inside `#if' during precompilation",
4095 for (i = indepth; i >= 0; i--)
4096 if (instack[i].fname != NULL) {
4101 error ("cccp error: not in any file?!");
4102 return; /* the show must go on */
4110 if (hp->type == T_FILE)
4111 string = ip->nominal_fname;
4113 string = instack[0].nominal_fname;
4117 buf = (char *) alloca (3 + 4 * strlen (string));
4118 quote_string (buf, string);
4126 case T_INCLUDE_LEVEL:
4128 for (i = indepth; i >= 0; i--)
4129 if (instack[i].fname != NULL)
4132 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4133 sprintf (buf, "%d", true_indepth - 1);
4137 buf = (char *) alloca (3 + strlen (version_string));
4138 sprintf (buf, "\"%s\"", version_string);
4141 #ifndef NO_BUILTIN_SIZE_TYPE
4147 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4148 case T_PTRDIFF_TYPE:
4157 case T_USER_LABEL_PREFIX_TYPE:
4158 buf = USER_LABEL_PREFIX;
4161 case T_REGISTER_PREFIX_TYPE:
4162 buf = REGISTER_PREFIX;
4166 buf = hp->value.cpval;
4167 if (pcp_inside_if && pcp_outfile)
4168 /* Output a precondition for this macro use */
4169 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4173 buf = (char *) alloca (10);
4174 sprintf (buf, "%d", ip->lineno);
4179 buf = (char *) alloca (20);
4180 timebuf = timestamp ();
4181 if (hp->type == T_DATE)
4182 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4183 timebuf->tm_mday, timebuf->tm_year + 1900);
4185 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4189 case T_SPEC_DEFINED:
4190 buf = " 0 "; /* Assume symbol is not defined */
4191 ip = &instack[indepth];
4192 SKIP_WHITE_SPACE (ip->bufp);
4193 if (*ip->bufp == '(') {
4195 ip->bufp++; /* Skip over the paren */
4196 SKIP_WHITE_SPACE (ip->bufp);
4199 if (!is_idstart[*ip->bufp])
4201 if ((hp = lookup (ip->bufp, -1, -1))) {
4202 if (pcp_outfile && pcp_inside_if
4203 && (hp->type == T_CONST
4204 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4205 /* Output a precondition for this macro use. */
4206 fprintf (pcp_outfile, "#define %s\n", hp->name);
4210 if (pcp_outfile && pcp_inside_if) {
4211 /* Output a precondition for this macro use */
4212 U_CHAR *cp = ip->bufp;
4213 fprintf (pcp_outfile, "#undef ");
4214 while (is_idchar[*cp]) /* Ick! */
4215 fputc (*cp++, pcp_outfile);
4216 putc ('\n', pcp_outfile);
4218 while (is_idchar[*ip->bufp])
4220 SKIP_WHITE_SPACE (ip->bufp);
4222 if (*ip->bufp != ')')
4230 error ("`defined' without an identifier");
4234 error ("cccp error: invalid special hash type"); /* time for gdb */
4238 check_expand (op, len);
4239 bcopy (buf, (char *) op->bufp, len);
4246 /* Routines to handle #directives */
4248 /* Handle #include and #import.
4249 This function expects to see "fname" or <fname> on the input. */
4252 do_include (buf, limit, op, keyword)
4253 U_CHAR *buf, *limit;
4255 struct directive *keyword;
4257 int importing = (keyword->type == T_IMPORT);
4258 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4259 static int import_warning = 0;
4260 char *fname; /* Dynamically allocated fname buffer */
4263 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4265 struct file_name_list *search_start = include; /* Chain of dirs to search */
4266 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4267 struct file_name_list *searchptr = 0;
4270 int f; /* file number */
4272 int retried = 0; /* Have already tried macro
4273 expanding the include line*/
4274 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4279 f= -1; /* JF we iz paranoid! */
4281 if (importing && warn_import && !inhibit_warnings
4282 && !instack[indepth].system_header_p && !import_warning) {
4284 warning ("using `#import' is not recommended");
4285 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4286 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4287 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4288 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4289 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4290 fprintf (stderr, " ... <real contents of file> ...\n");
4291 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4292 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4293 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4294 fprintf (stderr, "when it is equipped with such a conditional.\n");
4300 SKIP_WHITE_SPACE (fbeg);
4301 /* Discard trailing whitespace so we can easily see
4302 if we have parsed all the significant chars we were given. */
4303 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4309 /* Copy the operand text, concatenating the strings. */
4312 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4314 while (fin != limit) {
4315 while (fin != limit && *fin != '\"')
4320 /* If not at the end, there had better be another string. */
4321 /* Skip just horiz space, and don't go past limit. */
4322 while (fin != limit && is_hor_space[*fin]) fin++;
4323 if (fin != limit && *fin == '\"')
4331 /* We have "filename". Figure out directory this source
4332 file is coming from and put it on the front of the list. */
4334 /* If -I- was specified, don't search current dir, only spec'd ones. */
4335 if (ignore_srcdir) break;
4337 for (fp = &instack[indepth]; fp >= instack; fp--)
4342 if ((nam = fp->nominal_fname) != NULL) {
4343 /* Found a named file. Figure out dir of the file,
4344 and put it in front of the search list. */
4345 dsp[0].next = search_start;
4348 ep = rindex (nam, '/');
4349 #ifdef DIR_SEPARATOR
4350 if (ep == NULL) ep = rindex (nam, DIR_SEPARATOR);
4352 char *tmp = rindex (nam, DIR_SEPARATOR);
4353 if (tmp != NULL && tmp > ep) ep = tmp;
4357 ep = rindex (nam, ']');
4358 if (ep == NULL) ep = rindex (nam, '>');
4359 if (ep == NULL) ep = rindex (nam, ':');
4360 if (ep != NULL) ep++;
4364 dsp[0].fname = (char *) alloca (n + 1);
4365 strncpy (dsp[0].fname, nam, n);
4366 dsp[0].fname[n] = '\0';
4367 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4368 max_include_len = n + INCLUDE_LEN_FUDGE;
4370 dsp[0].fname = 0; /* Current directory */
4372 dsp[0].got_name_map = 0;
4381 while (fend != limit && *fend != '>') fend++;
4382 if (*fend == '>' && fend + 1 == limit) {
4384 /* If -I-, start with the first -I dir after the -I-. */
4385 if (first_bracket_include)
4386 search_start = first_bracket_include;
4394 * Support '#include xyz' like VAX-C to allow for easy use of all the
4395 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4396 * code from case '<' is repeated here) and generates a warning.
4397 * (Note: macro expansion of `xyz' takes precedence.)
4399 if (retried && isalpha(*(--fbeg))) {
4401 while (fend != limit && (!isspace(*fend))) fend++;
4402 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4403 if (fend == limit) {
4405 /* If -I-, start with the first -I dir after the -I-. */
4406 if (first_bracket_include)
4407 search_start = first_bracket_include;
4415 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4418 /* Expand buffer and then remove any newline markers.
4419 We can't just tell expand_to_temp_buffer to omit the markers,
4420 since it would put extra spaces in include file names. */
4423 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4425 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4427 while (src != trybuf.bufp) {
4428 switch ((*limit++ = *src++)) {
4437 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4438 NULL_PTR, NULL_PTR, NULL_PTR);
4452 /* For #include_next, skip in the search path
4453 past the dir in which the containing file was found. */
4456 for (fp = &instack[indepth]; fp >= instack; fp--)
4457 if (fp->fname != NULL) {
4458 /* fp->dir is null if the containing file was specified
4459 with an absolute file name. In that case, don't skip anything. */
4461 search_start = fp->dir->next;
4470 error ("empty file name in `#%s'", keyword->name);
4474 /* Allocate this permanently, because it gets stored in the definitions
4476 fname = xmalloc (max_include_len + flen + 4);
4477 /* + 2 above for slash and terminating null. */
4478 /* + 2 added for '.h' on VMS (to support '#include filename') */
4480 /* If specified file name is absolute, just open it. */
4483 #ifdef DIR_SEPARATOR
4484 || *fbeg == DIR_SEPARATOR
4487 strncpy (fname, (char *) fbeg, flen);
4489 if (redundant_include_p (fname))
4492 f = lookup_import (fname, NULL_PTR);
4494 f = open_include_file (fname, NULL_PTR);
4496 return 0; /* Already included this file */
4498 /* Search directory path, trying to open the file.
4499 Copy each filename tried into FNAME. */
4501 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4502 if (searchptr->fname) {
4503 /* The empty string in a search path is ignored.
4504 This makes it possible to turn off entirely
4505 a standard piece of the list. */
4506 if (searchptr->fname[0] == 0)
4508 strcpy (fname, searchptr->fname);
4509 strcat (fname, "/");
4510 fname[strlen (fname) + flen] = 0;
4514 strncat (fname, (char *) fbeg, flen);
4516 /* Change this 1/2 Unix 1/2 VMS file specification into a
4517 full VMS file specification */
4518 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4519 /* Fix up the filename */
4520 hack_vms_include_specification (fname);
4522 /* This is a normal VMS filespec, so use it unchanged. */
4523 strncpy (fname, fbeg, flen);
4525 /* if it's '#include filename', add the missing .h */
4526 if (index(fname,'.')==NULL) {
4527 strcat (fname, ".h");
4531 /* ??? There are currently 3 separate mechanisms for avoiding processing
4532 of redundant include files: #import, #pragma once, and
4533 redundant_include_p. It would be nice if they were unified. */
4534 if (redundant_include_p (fname))
4537 f = lookup_import (fname, searchptr);
4539 f = open_include_file (fname, searchptr);
4541 return 0; /* Already included this file */
4543 else if (f == -1 && errno == EACCES)
4544 warning ("Header file %s exists, but is not readable", fname);
4552 /* A file that was not found. */
4554 strncpy (fname, (char *) fbeg, flen);
4556 /* If generating dependencies and -MG was specified, we assume missing
4557 files are leaf files, living in the same directory as the source file
4558 or other similar place; these missing files may be generated from
4559 other files and may not exist yet (eg: y.tab.h). */
4560 if (print_deps_missing_files
4561 && print_deps > (angle_brackets || (system_include_depth > 0)))
4563 /* If it was requested as a system header file,
4564 then assume it belongs in the first place to look for such. */
4567 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4569 if (searchptr->fname)
4573 if (searchptr->fname[0] == 0)
4575 p = (char *) alloca (strlen (searchptr->fname)
4576 + strlen (fname) + 2);
4577 strcpy (p, searchptr->fname);
4580 deps_output (p, ' ');
4587 /* Otherwise, omit the directory, as if the file existed
4588 in the directory with the source. */
4589 deps_output (fname, ' ');
4592 /* If -M was specified, and this header file won't be added to the
4593 dependency list, then don't count this as an error, because we can
4594 still produce correct output. Otherwise, we can't produce correct
4595 output, because there may be dependencies we need inside the missing
4596 file, and we don't know what directory this missing file exists in. */
4598 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4599 warning ("No include path in which to find %s", fname);
4600 else if (search_start)
4601 error_from_errno (fname);
4603 error ("No include path in which to find %s", fname);
4605 /* Check to see if this include file is a once-only include file.
4608 struct file_name_list* ptr;
4610 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4611 if (!strcmp (ptr->fname, fname)) {
4613 return 0; /* This file was once'd. */
4617 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4618 if (!strcmp (ptr->fname, fname))
4619 break; /* This file was included before. */
4623 /* This is the first time for this file. */
4624 /* Add it to list of files included. */
4626 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4627 ptr->control_macro = 0;
4628 ptr->c_system_include_path = 0;
4629 ptr->next = all_include_files;
4630 all_include_files = ptr;
4631 ptr->fname = savestring (fname);
4632 ptr->got_name_map = 0;
4634 /* For -M, add this file to the dependencies. */
4635 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4636 deps_output (fname, ' ');
4639 /* Handle -H option. */
4640 if (print_include_names) {
4641 output_dots (stderr, indepth);
4642 fprintf (stderr, "%s\n", fname);
4646 system_include_depth++;
4648 /* Actually process the file. */
4649 add_import (f, fname); /* Record file on "seen" list for #import. */
4651 pcftry = (char *) alloca (strlen (fname) + 30);
4662 sprintf (pcftry, "%s%d", fname, pcfnum++);
4664 pcf = open (pcftry, O_RDONLY, 0666);
4670 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4672 || stat_f.st_dev != s.st_dev)
4674 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4675 /* Don't need it any more. */
4680 /* Don't need it at all. */
4685 } while (pcf != -1 && !pcfbuf);
4688 /* Actually process the file */
4690 pcfname = xmalloc (strlen (pcftry) + 1);
4691 strcpy (pcfname, pcftry);
4692 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4693 (U_CHAR *) fname, op);
4696 finclude (f, fname, op, is_system_include (fname), searchptr);
4699 system_include_depth--;
4704 /* Return nonzero if there is no need to include file NAME
4705 because it has already been included and it contains a conditional
4706 to make a repeated include do nothing. */
4709 redundant_include_p (name)
4712 struct file_name_list *l = all_include_files;
4713 for (; l; l = l->next)
4714 if (! strcmp (name, l->fname)
4716 && lookup (l->control_macro, -1, -1))
4721 /* Return nonzero if the given FILENAME is an absolute pathname which
4722 designates a file within one of the known "system" include file
4723 directories. We assume here that if the given FILENAME looks like
4724 it is the name of a file which resides either directly in a "system"
4725 include file directory, or within any subdirectory thereof, then the
4726 given file must be a "system" include file. This function tells us
4727 if we should suppress pedantic errors/warnings for the given FILENAME.
4729 The value is 2 if the file is a C-language system header file
4730 for which C++ should (on most systems) assume `extern "C"'. */
4733 is_system_include (filename)
4734 register char *filename;
4736 struct file_name_list *searchptr;
4738 for (searchptr = first_system_include; searchptr;
4739 searchptr = searchptr->next)
4740 if (searchptr->fname) {
4741 register char *sys_dir = searchptr->fname;
4742 register unsigned length = strlen (sys_dir);
4744 if (! strncmp (sys_dir, filename, length)
4745 && (filename[length] == '/'
4746 #ifdef DIR_SEPARATOR
4747 || filename[length] == DIR_SEPARATOR
4750 if (searchptr->c_system_include_path)
4759 /* The file_name_map structure holds a mapping of file names for a
4760 particular directory. This mapping is read from the file named
4761 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4762 map filenames on a file system with severe filename restrictions,
4763 such as DOS. The format of the file name map file is just a series
4764 of lines with two tokens on each line. The first token is the name
4765 to map, and the second token is the actual name to use. */
4767 struct file_name_map
4769 struct file_name_map *map_next;
4774 #define FILE_NAME_MAP_FILE "header.gcc"
4776 /* Read a space delimited string of unlimited length from a stdio
4780 read_filename_string (ch, f)
4788 set = alloc = xmalloc (len + 1);
4792 while ((ch = getc (f)) != EOF && ! is_space[ch])
4794 if (set - alloc == len)
4797 alloc = xrealloc (alloc, len + 1);
4798 set = alloc + len / 2;
4808 /* Read the file name map file for DIRNAME. */
4810 static struct file_name_map *
4811 read_name_map (dirname)
4814 /* This structure holds a linked list of file name maps, one per
4816 struct file_name_map_list
4818 struct file_name_map_list *map_list_next;
4819 char *map_list_name;
4820 struct file_name_map *map_list_map;
4822 static struct file_name_map_list *map_list;
4823 register struct file_name_map_list *map_list_ptr;
4827 for (map_list_ptr = map_list; map_list_ptr;
4828 map_list_ptr = map_list_ptr->map_list_next)
4829 if (! strcmp (map_list_ptr->map_list_name, dirname))
4830 return map_list_ptr->map_list_map;
4832 map_list_ptr = ((struct file_name_map_list *)
4833 xmalloc (sizeof (struct file_name_map_list)));
4834 map_list_ptr->map_list_name = savestring (dirname);
4835 map_list_ptr->map_list_map = NULL;
4837 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
4838 strcpy (name, dirname);
4841 strcat (name, FILE_NAME_MAP_FILE);
4842 f = fopen (name, "r");
4844 map_list_ptr->map_list_map = NULL;
4848 int dirlen = strlen (dirname);
4850 while ((ch = getc (f)) != EOF)
4853 struct file_name_map *ptr;
4857 from = read_filename_string (ch, f);
4858 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4860 to = read_filename_string (ch, f);
4862 ptr = ((struct file_name_map *)
4863 xmalloc (sizeof (struct file_name_map)));
4864 ptr->map_from = from;
4866 /* Make the real filename absolute. */
4871 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4872 strcpy (ptr->map_to, dirname);
4873 ptr->map_to[dirlen] = '/';
4874 strcpy (ptr->map_to + dirlen + 1, to);
4878 ptr->map_next = map_list_ptr->map_list_map;
4879 map_list_ptr->map_list_map = ptr;
4881 while ((ch = getc (f)) != '\n')
4888 map_list_ptr->map_list_next = map_list;
4889 map_list = map_list_ptr;
4891 return map_list_ptr->map_list_map;
4894 /* Try to open include file FILENAME. SEARCHPTR is the directory
4895 being tried from the include file search path. This function maps
4896 filenames on file systems based on information read by
4900 open_include_file (filename, searchptr)
4902 struct file_name_list *searchptr;
4904 register struct file_name_map *map;
4905 register char *from;
4908 if (searchptr && ! searchptr->got_name_map)
4910 searchptr->name_map = read_name_map (searchptr->fname
4911 ? searchptr->fname : ".");
4912 searchptr->got_name_map = 1;
4915 /* First check the mapping for the directory we are using. */
4916 if (searchptr && searchptr->name_map)
4919 if (searchptr->fname)
4920 from += strlen (searchptr->fname) + 1;
4921 for (map = searchptr->name_map; map; map = map->map_next)
4923 if (! strcmp (map->map_from, from))
4925 /* Found a match. */
4926 return open (map->map_to, O_RDONLY, 0666);
4931 /* Try to find a mapping file for the particular directory we are
4932 looking in. Thus #include <sys/types.h> will look up sys/types.h
4933 in /usr/include/header.gcc and look up types.h in
4934 /usr/include/sys/header.gcc. */
4935 p = rindex (filename, '/');
4936 #ifdef DIR_SEPARATOR
4937 if (! p) p = rindex (filename, DIR_SEPARATOR);
4939 char *tmp = rindex (filename, DIR_SEPARATOR);
4940 if (tmp != NULL && tmp > p) p = tmp;
4947 && strlen (searchptr->fname) == p - filename
4948 && ! strncmp (searchptr->fname, filename, p - filename))
4950 /* FILENAME is in SEARCHPTR, which we've already checked. */
4951 return open (filename, O_RDONLY, 0666);
4961 dir = (char *) alloca (p - filename + 1);
4962 bcopy (filename, dir, p - filename);
4963 dir[p - filename] = '\0';
4966 for (map = read_name_map (dir); map; map = map->map_next)
4967 if (! strcmp (map->map_from, from))
4968 return open (map->map_to, O_RDONLY, 0666);
4970 return open (filename, O_RDONLY, 0666);
4973 /* Process the contents of include file FNAME, already open on descriptor F,
4975 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4976 "system" include directories (as decided by the `is_system_include'
4978 DIRPTR is the link in the dir path through which this file was found,
4979 or 0 if the file name was absolute. */
4982 finclude (f, fname, op, system_header_p, dirptr)
4986 int system_header_p;
4987 struct file_name_list *dirptr;
4992 FILE_BUF *fp; /* For input stack frame */
4993 int missing_newline = 0;
4995 CHECK_DEPTH (return;);
4997 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
4999 perror_with_name (fname);
5004 fp = &instack[indepth + 1];
5005 bzero ((char *) fp, sizeof (FILE_BUF));
5006 fp->nominal_fname = fp->fname = fname;
5009 fp->if_stack = if_stack;
5010 fp->system_header_p = system_header_p;
5013 if (S_ISREG (st_mode)) {
5014 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
5017 /* Read the file contents, knowing that st_size is an upper bound
5018 on the number of bytes we can read. */
5019 fp->length = safe_read (f, (char *) fp->buf, st_size);
5020 if (fp->length < 0) goto nope;
5022 else if (S_ISDIR (st_mode)) {
5023 error ("directory `%s' specified in #include", fname);
5027 /* Cannot count its file size before reading.
5028 First read the entire file into heap and
5029 copy them into buffer on stack. */
5034 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5037 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5039 goto nope; /* error! */
5041 if (st_size != bsize)
5042 break; /* End of file */
5044 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5047 fp->length = st_size;
5050 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5051 /* Backslash-newline at end is not good enough. */
5052 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5053 fp->buf[fp->length++] = '\n';
5054 missing_newline = 1;
5056 fp->buf[fp->length] = '\0';
5058 /* Close descriptor now, so nesting does not use lots of descriptors. */
5061 /* Must do this before calling trigraph_pcp, so that the correct file name
5062 will be printed in warning messages. */
5065 input_file_stack_tick++;
5070 output_line_directive (fp, op, 0, enter_file);
5073 if (missing_newline)
5076 if (pedantic && missing_newline)
5077 pedwarn ("file does not end in newline");
5080 input_file_stack_tick++;
5081 output_line_directive (&instack[indepth], op, 0, leave_file);
5087 perror_with_name (fname);
5092 /* Record that inclusion of the file named FILE
5093 should be controlled by the macro named MACRO_NAME.
5094 This means that trying to include the file again
5095 will do something if that macro is defined. */
5098 record_control_macro (file, macro_name)
5102 struct file_name_list *new;
5104 for (new = all_include_files; new; new = new->next) {
5105 if (!strcmp (new->fname, file)) {
5106 new->control_macro = macro_name;
5111 /* If the file is not in all_include_files, something's wrong. */
5115 /* Maintain and search list of included files, for #import. */
5117 #define IMPORT_HASH_SIZE 31
5119 struct import_file {
5123 struct import_file *next;
5126 /* Hash table of files already included with #include or #import. */
5128 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
5130 /* Hash a file name for import_hash_table. */
5138 while (*f) val += *f++;
5139 return (val%IMPORT_HASH_SIZE);
5142 /* Search for file FILENAME in import_hash_table.
5143 Return -2 if found, either a matching name or a matching inode.
5144 Otherwise, open the file and return a file descriptor if successful
5145 or -1 if unsuccessful. */
5148 lookup_import (filename, searchptr)
5150 struct file_name_list *searchptr;
5152 struct import_file *i;
5158 hashval = import_hash (filename);
5160 /* Attempt to find file in list of already included files */
5161 i = import_hash_table[hashval];
5164 if (!strcmp (filename, i->name))
5165 return -2; /* return found */
5168 /* Open it and try a match on inode/dev */
5169 fd = open_include_file (filename, searchptr);
5173 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5174 i = import_hash_table[h];
5176 /* Compare the inode and the device.
5177 Supposedly on some systems the inode is not a scalar. */
5178 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5179 && i->dev == sb.st_dev) {
5181 return -2; /* return found */
5186 return fd; /* Not found, return open file */
5189 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5192 add_import (fd, fname)
5196 struct import_file *i;
5200 hashval = import_hash (fname);
5202 i = (struct import_file *)xmalloc (sizeof (struct import_file));
5203 i->name = xmalloc (strlen (fname)+1);
5204 strcpy (i->name, fname);
5205 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5207 i->next = import_hash_table[hashval];
5208 import_hash_table[hashval] = i;
5211 /* Load the specified precompiled header into core, and verify its
5212 preconditions. PCF indicates the file descriptor to read, which must
5213 be a regular file. FNAME indicates the file name of the original
5214 header. *LIMIT will be set to an address one past the end of the file.
5215 If the preconditions of the file are not satisfied, the buffer is
5216 freed and we return 0. If the preconditions are satisfied, return
5217 the address of the buffer following the preconditions. The buffer, in
5218 this case, should never be freed because various pieces of it will
5219 be referred to until all precompiled strings are output at the end of
5223 check_precompiled (pcf, fname, limit)
5237 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
5240 if (S_ISREG (st_mode))
5242 buf = xmalloc (st_size + 2);
5243 length = safe_read (pcf, buf, st_size);
5250 if (length > 0 && buf[length-1] != '\n')
5251 buf[length++] = '\n';
5254 *limit = buf + length;
5256 /* File is in core. Check the preconditions. */
5257 if (!check_preconditions (buf))
5259 for (cp = buf; *cp; cp++)
5262 fprintf (stderr, "Using preinclude %s\n", fname);
5268 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5274 /* PREC (null terminated) points to the preconditions of a
5275 precompiled header. These are a series of #define and #undef
5276 lines which must match the current contents of the hash
5279 check_preconditions (prec)
5286 lineend = index (prec, '\n');
5288 if (*prec++ != '#') {
5289 error ("Bad format encountered while reading precompiled file");
5292 if (!strncmp (prec, "define", 6)) {
5296 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5301 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5302 || (hp->type != T_MACRO && hp->type != T_CONST)
5303 || (hp->type == T_MACRO
5304 && !compare_defs (mdef.defn, hp->value.defn)
5305 && (mdef.defn->length != 2
5306 || mdef.defn->expansion[0] != '\n'
5307 || mdef.defn->expansion[1] != ' ')))
5309 } else if (!strncmp (prec, "undef", 5)) {
5314 while (is_hor_space[(U_CHAR) *prec])
5317 while (is_idchar[(U_CHAR) *prec])
5321 if (lookup ((U_CHAR *) name, len, -1))
5324 error ("Bad format encountered while reading precompiled file");
5329 /* They all passed successfully */
5333 /* Process the main body of a precompiled file. BUF points to the
5334 string section of the file, following the preconditions. LIMIT is one
5335 character past the end. NAME is the name of the file being read
5336 in. OP is the main output buffer */
5338 pcfinclude (buf, limit, name, op)
5339 U_CHAR *buf, *limit, *name;
5346 /* First in the file comes 4 bytes indicating the number of strings, */
5347 /* in network byte order. (MSB first). */
5349 nstrings = (nstrings << 8) | *cp++;
5350 nstrings = (nstrings << 8) | *cp++;
5351 nstrings = (nstrings << 8) | *cp++;
5353 /* Looping over each string... */
5354 while (nstrings--) {
5355 U_CHAR *string_start;
5356 U_CHAR *endofthiskey;
5360 /* Each string starts with a STRINGDEF structure (str), followed */
5361 /* by the text of the string (string_start) */
5363 /* First skip to a longword boundary */
5364 /* ??? Why a 4-byte boundary? On all machines? */
5365 /* NOTE: This works correctly even if HOST_WIDE_INT
5366 is narrower than a pointer.
5367 Do not try risky measures here to get another type to use!
5368 Do not include stddef.h--it will fail! */
5369 if ((HOST_WIDE_INT) cp & 3)
5370 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5372 /* Now get the string. */
5373 str = (STRINGDEF *) (GENERIC_PTR) cp;
5374 string_start = cp += sizeof (STRINGDEF);
5376 for (; *cp; cp++) /* skip the string */
5379 /* We need to macro expand the string here to ensure that the
5380 proper definition environment is in place. If it were only
5381 expanded when we find out it is needed, macros necessary for
5382 its proper expansion might have had their definitions changed. */
5383 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5384 /* Lineno is already set in the precompiled file */
5385 str->contents = tmpbuf.buf;
5386 str->len = tmpbuf.length;
5388 str->filename = name;
5389 str->output_mark = outbuf.bufp - outbuf.buf;
5392 *stringlist_tailp = str;
5393 stringlist_tailp = &str->chain;
5395 /* Next comes a fourbyte number indicating the number of keys */
5396 /* for this string. */
5398 nkeys = (nkeys << 8) | *cp++;
5399 nkeys = (nkeys << 8) | *cp++;
5400 nkeys = (nkeys << 8) | *cp++;
5402 /* If this number is -1, then the string is mandatory. */
5406 /* Otherwise, for each key, */
5407 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5408 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5411 /* It starts with a KEYDEF structure */
5412 cp += sizeof (KEYDEF);
5414 /* Find the end of the key. At the end of this for loop we
5415 advance CP to the start of the next key using this variable. */
5416 endofthiskey = cp + strlen ((char *) cp);
5419 /* Expand the key, and enter it into the hash table. */
5420 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5421 tmpbuf.bufp = tmpbuf.buf;
5423 while (is_hor_space[*tmpbuf.bufp])
5425 if (!is_idstart[*tmpbuf.bufp]
5426 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5431 hp = lookup (tmpbuf.bufp, -1, -1);
5434 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5436 else if (hp->type == T_PCSTRING) {
5437 kp->chain = hp->value.keydef;
5438 hp->value.keydef = kp;
5444 /* This output_line_directive serves to switch us back to the current
5445 input file in case some of these strings get output (which will
5446 result in line directives for the header file being output). */
5447 output_line_directive (&instack[indepth], op, 0, enter_file);
5450 /* Called from rescan when it hits a key for strings. Mark them all */
5451 /* used and clean up. */
5458 for (kp = hp->value.keydef; kp; kp = kp->chain)
5459 kp->str->writeflag = 1;
5463 /* Write the output, interspersing precompiled strings in their */
5464 /* appropriate places. */
5468 STRINGDEF *next_string;
5469 U_CHAR *cur_buf_loc;
5470 int line_directive_len = 80;
5471 char *line_directive = xmalloc (line_directive_len);
5474 /* In each run through the loop, either cur_buf_loc == */
5475 /* next_string_loc, in which case we print a series of strings, or */
5476 /* it is less than next_string_loc, in which case we write some of */
5478 cur_buf_loc = outbuf.buf;
5479 next_string = stringlist;
5481 while (cur_buf_loc < outbuf.bufp || next_string) {
5483 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5484 if (next_string->writeflag) {
5485 len = 4 * strlen ((char *) next_string->filename) + 32;
5486 while (len > line_directive_len)
5487 line_directive = xrealloc (line_directive,
5488 line_directive_len *= 2);
5489 sprintf (line_directive, "\n# %d ", next_string->lineno);
5490 strcpy (quote_string (line_directive + strlen (line_directive),
5491 (char *) next_string->filename),
5493 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5494 safe_write (fileno (stdout),
5495 (char *) next_string->contents, next_string->len);
5497 next_string = next_string->chain;
5501 ? (next_string->output_mark
5502 - (cur_buf_loc - outbuf.buf))
5503 : outbuf.bufp - cur_buf_loc);
5505 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5509 free (line_directive);
5512 /* Pass a directive through to the output file.
5513 BUF points to the contents of the directive, as a contiguous string.
5514 LIMIT points to the first character past the end of the directive.
5515 KEYWORD is the keyword-table entry for the directive. */
5518 pass_thru_directive (buf, limit, op, keyword)
5519 U_CHAR *buf, *limit;
5521 struct directive *keyword;
5523 register unsigned keyword_length = keyword->length;
5525 check_expand (op, 1 + keyword_length + (limit - buf));
5527 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5528 op->bufp += keyword_length;
5529 if (limit != buf && buf[0] != ' ')
5531 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5532 op->bufp += (limit - buf);
5535 /* Count the line we have just made in the output,
5536 to get in sync properly. */
5541 /* The arglist structure is built by do_define to tell
5542 collect_definition where the argument names begin. That
5543 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5544 would contain pointers to the strings x, y, and z.
5545 Collect_definition would then build a DEFINITION node,
5546 with reflist nodes pointing to the places x, y, and z had
5547 appeared. So the arglist is just convenience data passed
5548 between these two routines. It is not kept around after
5549 the current #define has been processed and entered into the
5553 struct arglist *next;
5560 /* Create a DEFINITION node from a #define directive. Arguments are
5561 as for do_define. */
5563 create_definition (buf, limit, op)
5564 U_CHAR *buf, *limit;
5567 U_CHAR *bp; /* temp ptr into input buffer */
5568 U_CHAR *symname; /* remember where symbol name starts */
5569 int sym_length; /* and how long it is */
5570 int line = instack[indepth].lineno;
5571 char *file = instack[indepth].nominal_fname;
5575 int arglengths = 0; /* Accumulate lengths of arg names
5576 plus number of args. */
5581 while (is_hor_space[*bp])
5584 symname = bp; /* remember where it starts */
5585 sym_length = check_macro_name (bp, "macro");
5588 /* Lossage will occur if identifiers or control keywords are broken
5589 across lines using backslash. This is not the right place to take
5593 struct arglist *arg_ptrs = NULL;
5596 bp++; /* skip '(' */
5597 SKIP_WHITE_SPACE (bp);
5599 /* Loop over macro argument names. */
5600 while (*bp != ')') {
5601 struct arglist *temp;
5603 temp = (struct arglist *) alloca (sizeof (struct arglist));
5605 temp->next = arg_ptrs;
5606 temp->argno = argno++;
5607 temp->rest_args = 0;
5611 pedwarn ("another parameter follows `%s'",
5614 if (!is_idstart[*bp])
5615 pedwarn ("invalid character in macro parameter name");
5617 /* Find the end of the arg name. */
5618 while (is_idchar[*bp]) {
5620 /* do we have a "special" rest-args extension here? */
5621 if (limit - bp > REST_EXTENSION_LENGTH &&
5622 bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5624 temp->rest_args = 1;
5628 temp->length = bp - temp->name;
5630 bp += REST_EXTENSION_LENGTH;
5631 arglengths += temp->length + 2;
5632 SKIP_WHITE_SPACE (bp);
5633 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5634 error ("badly punctuated parameter list in `#define'");
5639 SKIP_WHITE_SPACE (bp);
5640 /* A comma at this point can only be followed by an identifier. */
5641 if (!is_idstart[*bp]) {
5642 error ("badly punctuated parameter list in `#define'");
5647 error ("unterminated parameter list in `#define'");
5651 struct arglist *otemp;
5653 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5654 if (temp->length == otemp->length &&
5655 bcmp (temp->name, otemp->name, temp->length) == 0) {
5656 error ("duplicate argument name `%.*s' in `#define'",
5657 temp->length, temp->name);
5663 ++bp; /* skip paren */
5664 SKIP_WHITE_SPACE (bp);
5665 /* now everything from bp before limit is the definition. */
5666 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5667 defn->rest_args = rest_args;
5669 /* Now set defn->args.argnames to the result of concatenating
5670 the argument names in reverse order
5671 with comma-space between them. */
5672 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5674 struct arglist *temp;
5676 for (temp = arg_ptrs; temp; temp = temp->next) {
5677 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5679 if (temp->next != 0) {
5680 defn->args.argnames[i++] = ',';
5681 defn->args.argnames[i++] = ' ';
5684 defn->args.argnames[i] = 0;
5687 /* Simple expansion or empty definition. */
5691 if (is_hor_space[*bp]) {
5693 SKIP_WHITE_SPACE (bp);
5696 case '!': case '"': case '#': case '%': case '&': case '\'':
5697 case ')': case '*': case '+': case ',': case '-': case '.':
5698 case '/': case ':': case ';': case '<': case '=': case '>':
5699 case '?': case '[': case '\\': case ']': case '^': case '{':
5700 case '|': case '}': case '~':
5701 warning ("missing white space after `#define %.*s'",
5702 sym_length, symname);
5706 pedwarn ("missing white space after `#define %.*s'",
5707 sym_length, symname);
5712 /* Now everything from bp before limit is the definition. */
5713 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5714 defn->args.argnames = (U_CHAR *) "";
5720 /* OP is null if this is a predefinition */
5721 defn->predefined = !op;
5723 mdef.symnam = symname;
5724 mdef.symlen = sym_length;
5733 /* Process a #define directive.
5734 BUF points to the contents of the #define directive, as a contiguous string.
5735 LIMIT points to the first character past the end of the definition.
5736 KEYWORD is the keyword-table entry for #define. */
5739 do_define (buf, limit, op, keyword)
5740 U_CHAR *buf, *limit;
5742 struct directive *keyword;
5747 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5748 if (pcp_outfile && op)
5749 pass_thru_directive (buf, limit, op, keyword);
5751 mdef = create_definition (buf, limit, op);
5755 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5759 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5761 /* Redefining a precompiled key is ok. */
5762 if (hp->type == T_PCSTRING)
5764 /* Redefining a macro is ok if the definitions are the same. */
5765 else if (hp->type == T_MACRO)
5766 ok = ! compare_defs (mdef.defn, hp->value.defn);
5767 /* Redefining a constant is ok with -D. */
5768 else if (hp->type == T_CONST)
5769 ok = ! done_initializing;
5770 /* Print the warning if it's not ok. */
5772 /* If we are passing through #define and #undef directives, do
5773 that for this re-definition now. */
5774 if (debug_output && op)
5775 pass_thru_directive (buf, limit, op, keyword);
5777 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5778 if (hp->type == T_MACRO)
5779 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5780 "this is the location of the previous definition");
5782 /* Replace the old definition. */
5784 hp->value.defn = mdef.defn;
5786 /* If we are passing through #define and #undef directives, do
5787 that for this new definition now. */
5788 if (debug_output && op)
5789 pass_thru_directive (buf, limit, op, keyword);
5790 install (mdef.symnam, mdef.symlen, T_MACRO,
5791 (char *) mdef.defn, hashcode);
5802 /* Check a purported macro name SYMNAME, and yield its length.
5803 USAGE is the kind of name this is intended for. */
5806 check_macro_name (symname, usage)
5813 for (p = symname; is_idchar[*p]; p++)
5815 sym_length = p - symname;
5816 if (sym_length == 0)
5817 error ("invalid %s name", usage);
5818 else if (!is_idstart[*symname]
5819 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5820 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5825 * return zero if two DEFINITIONs are isomorphic
5828 compare_defs (d1, d2)
5829 DEFINITION *d1, *d2;
5831 register struct reflist *a1, *a2;
5832 register U_CHAR *p1 = d1->expansion;
5833 register U_CHAR *p2 = d2->expansion;
5836 if (d1->nargs != d2->nargs)
5838 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5840 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5841 a1 = a1->next, a2 = a2->next) {
5842 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5843 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5844 || a1->argno != a2->argno
5845 || a1->stringify != a2->stringify
5846 || a1->raw_before != a2->raw_before
5847 || a1->raw_after != a2->raw_after)
5855 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5856 p2, d2->length - (p2 - d2->expansion), 1))
5861 /* Return 1 if two parts of two macro definitions are effectively different.
5862 One of the parts starts at BEG1 and has LEN1 chars;
5863 the other has LEN2 chars at BEG2.
5864 Any sequence of whitespace matches any other sequence of whitespace.
5865 FIRST means these parts are the first of a macro definition;
5866 so ignore leading whitespace entirely.
5867 LAST means these parts are the last of a macro definition;
5868 so ignore trailing whitespace entirely. */
5871 comp_def_part (first, beg1, len1, beg2, len2, last)
5873 U_CHAR *beg1, *beg2;
5877 register U_CHAR *end1 = beg1 + len1;
5878 register U_CHAR *end2 = beg2 + len2;
5880 while (beg1 != end1 && is_space[*beg1]) beg1++;
5881 while (beg2 != end2 && is_space[*beg2]) beg2++;
5884 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5885 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5887 while (beg1 != end1 && beg2 != end2) {
5888 if (is_space[*beg1] && is_space[*beg2]) {
5889 while (beg1 != end1 && is_space[*beg1]) beg1++;
5890 while (beg2 != end2 && is_space[*beg2]) beg2++;
5891 } else if (*beg1 == *beg2) {
5895 return (beg1 != end1) || (beg2 != end2);
5898 /* Read a replacement list for a macro with parameters.
5899 Build the DEFINITION structure.
5900 Reads characters of text starting at BUF until END.
5901 ARGLIST specifies the formal parameters to look for
5902 in the text of the definition; NARGS is the number of args
5903 in that list, or -1 for a macro name that wants no argument list.
5904 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5905 and NAMELEN is its length in characters.
5907 Note that comments, backslash-newlines, and leading white space
5908 have already been deleted from the argument. */
5910 /* If there is no trailing whitespace, a Newline Space is added at the end
5911 to prevent concatenation that would be contrary to the standard. */
5914 collect_expansion (buf, end, nargs, arglist)
5917 struct arglist *arglist;
5920 register U_CHAR *p, *limit, *lastp, *exp_p;
5921 struct reflist *endpat = NULL;
5922 /* Pointer to first nonspace after last ## seen. */
5924 /* Pointer to first nonspace after last single-# seen. */
5925 U_CHAR *stringify = 0;
5926 /* How those tokens were spelled. */
5927 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5928 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5930 int expected_delimiter = '\0';
5932 /* Scan thru the replacement list, ignoring comments and quoted
5933 strings, picking up on the macro calls. It does a linear search
5934 thru the arg list on every potential symbol. Profiling might say
5935 that something smarter should happen. */
5940 /* Find the beginning of the trailing whitespace. */
5943 while (p < limit && is_space[limit[-1]]) limit--;
5945 /* Allocate space for the text in the macro definition.
5946 Each input char may or may not need 1 byte,
5947 so this is an upper bound.
5948 The extra 3 are for invented trailing newline-marker and final null. */
5949 maxsize = (sizeof (DEFINITION)
5951 defn = (DEFINITION *) xcalloc (1, maxsize);
5953 defn->nargs = nargs;
5954 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5959 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5960 error ("`##' at start of macro definition");
5961 p += p[0] == '#' ? 2 : 4;
5964 /* Process the main body of the definition. */
5966 int skipped_arg = 0;
5967 register U_CHAR c = *p++;
5975 if (expected_delimiter != '\0') {
5976 if (c == expected_delimiter)
5977 expected_delimiter = '\0';
5979 expected_delimiter = c;
5983 if (p < limit && expected_delimiter) {
5984 /* In a string, backslash goes through
5985 and makes next char ordinary. */
5991 if (!expected_delimiter && *p == ':') {
5992 /* %: is not a digraph if preceded by an odd number of '<'s. */
5994 while (buf < p0 && p0[-1] == '<')
5997 /* Treat %:%: as ## and %: as #. */
5998 if (p[1] == '%' && p[2] == ':') {
6000 goto sharp_sharp_token;
6011 /* # is ordinary inside a string. */
6012 if (expected_delimiter)
6016 /* ##: concatenate preceding and following tokens. */
6017 /* Take out the first #, discard preceding whitespace. */
6019 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6021 /* Skip the second #. */
6023 concat_sharp_token_type = c;
6024 if (is_hor_space[*p]) {
6025 concat_sharp_token_type++;
6027 SKIP_WHITE_SPACE (p);
6031 error ("`##' at end of macro definition");
6032 } else if (nargs >= 0) {
6033 /* Single #: stringify following argument ref.
6034 Don't leave the # in the expansion. */
6037 stringify_sharp_token_type = c;
6038 if (is_hor_space[*p]) {
6039 stringify_sharp_token_type++;
6041 SKIP_WHITE_SPACE (p);
6043 if (! is_idstart[*p] || nargs == 0)
6044 error ("`#' operator is not followed by a macro argument name");
6051 /* In -traditional mode, recognize arguments inside strings and
6052 and character constants, and ignore special properties of #.
6053 Arguments inside strings are considered "stringified", but no
6054 extra quote marks are supplied. */
6058 if (expected_delimiter != '\0') {
6059 if (c == expected_delimiter)
6060 expected_delimiter = '\0';
6062 expected_delimiter = c;
6066 /* Backslash quotes delimiters and itself, but not macro args. */
6067 if (expected_delimiter != 0 && p < limit
6068 && (*p == expected_delimiter || *p == '\\')) {
6075 if (expected_delimiter != '\0') /* No comments inside strings. */
6078 /* If we find a comment that wasn't removed by handle_directive,
6079 this must be -traditional. So replace the comment with
6083 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
6086 /* Mark this as a concatenation-point, as if it had been ##. */
6094 /* Handle the start of a symbol. */
6095 if (is_idchar[c] && nargs > 0) {
6096 U_CHAR *id_beg = p - 1;
6100 while (p != limit && is_idchar[*p]) p++;
6101 id_len = p - id_beg;
6103 if (is_idstart[c]) {
6104 register struct arglist *arg;
6106 for (arg = arglist; arg != NULL; arg = arg->next) {
6107 struct reflist *tpat;
6109 if (arg->name[0] == c
6110 && arg->length == id_len
6111 && bcmp (arg->name, id_beg, id_len) == 0) {
6112 enum sharp_token_type tpat_stringify;
6113 if (expected_delimiter) {
6114 if (warn_stringify) {
6116 warning ("macro argument `%.*s' is stringified.",
6119 warning ("macro arg `%.*s' would be stringified with -traditional.",
6123 /* If ANSI, don't actually substitute inside a string. */
6126 tpat_stringify = SHARP_TOKEN;
6129 = (stringify == id_beg
6130 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6132 /* make a pat node for this arg and append it to the end of
6134 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6137 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6138 tpat->raw_after = NO_SHARP_TOKEN;
6139 tpat->rest_args = arg->rest_args;
6140 tpat->stringify = tpat_stringify;
6143 defn->pattern = tpat;
6145 endpat->next = tpat;
6148 tpat->argno = arg->argno;
6149 tpat->nchars = exp_p - lastp;
6151 register U_CHAR *p1 = p;
6152 SKIP_WHITE_SPACE (p1);
6155 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6156 tpat->raw_after = p1[0] + (p != p1);
6158 lastp = exp_p; /* place to start copying from next time */
6165 /* If this was not a macro arg, copy it into the expansion. */
6166 if (! skipped_arg) {
6167 register U_CHAR *lim1 = p;
6171 if (stringify == id_beg)
6172 error ("`#' operator should be followed by a macro argument name");
6177 if (!traditional && expected_delimiter == 0) {
6178 /* If ANSI, put in a newline-space marker to prevent token pasting.
6179 But not if "inside a string" (which in ANSI mode happens only for
6187 defn->length = exp_p - defn->expansion;
6189 /* Crash now if we overrun the allocated size. */
6190 if (defn->length + 1 > maxsize)
6194 /* This isn't worth the time it takes. */
6195 /* give back excess storage */
6196 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6203 do_assert (buf, limit, op, keyword)
6204 U_CHAR *buf, *limit;
6206 struct directive *keyword;
6208 U_CHAR *bp; /* temp ptr into input buffer */
6209 U_CHAR *symname; /* remember where symbol name starts */
6210 int sym_length; /* and how long it is */
6211 struct arglist *tokens = NULL;
6213 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6214 pedwarn ("ANSI C does not allow `#assert'");
6218 while (is_hor_space[*bp])
6221 symname = bp; /* remember where it starts */
6222 sym_length = check_macro_name (bp, "assertion");
6224 /* #define doesn't do this, but we should. */
6225 SKIP_WHITE_SPACE (bp);
6227 /* Lossage will occur if identifiers or control tokens are broken
6228 across lines using backslash. This is not the right place to take
6232 error ("missing token-sequence in `#assert'");
6239 bp++; /* skip '(' */
6240 SKIP_WHITE_SPACE (bp);
6242 tokens = read_token_list (&bp, limit, &error_flag);
6246 error ("empty token-sequence in `#assert'");
6250 ++bp; /* skip paren */
6251 SKIP_WHITE_SPACE (bp);
6254 /* If this name isn't already an assertion name, make it one.
6255 Error if it was already in use in some other way. */
6258 ASSERTION_HASHNODE *hp;
6259 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6260 struct tokenlist_list *value
6261 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6263 hp = assertion_lookup (symname, sym_length, hashcode);
6265 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6266 error ("`defined' redefined as assertion");
6267 hp = assertion_install (symname, sym_length, hashcode);
6270 /* Add the spec'd token-sequence to the list of such. */
6271 value->tokens = tokens;
6272 value->next = hp->value;
6280 do_unassert (buf, limit, op, keyword)
6281 U_CHAR *buf, *limit;
6283 struct directive *keyword;
6285 U_CHAR *bp; /* temp ptr into input buffer */
6286 U_CHAR *symname; /* remember where symbol name starts */
6287 int sym_length; /* and how long it is */
6289 struct arglist *tokens = NULL;
6290 int tokens_specified = 0;
6292 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6293 pedwarn ("ANSI C does not allow `#unassert'");
6297 while (is_hor_space[*bp])
6300 symname = bp; /* remember where it starts */
6301 sym_length = check_macro_name (bp, "assertion");
6303 /* #define doesn't do this, but we should. */
6304 SKIP_WHITE_SPACE (bp);
6306 /* Lossage will occur if identifiers or control tokens are broken
6307 across lines using backslash. This is not the right place to take
6313 bp++; /* skip '(' */
6314 SKIP_WHITE_SPACE (bp);
6316 tokens = read_token_list (&bp, limit, &error_flag);
6320 error ("empty token list in `#unassert'");
6324 tokens_specified = 1;
6326 ++bp; /* skip paren */
6327 SKIP_WHITE_SPACE (bp);
6331 ASSERTION_HASHNODE *hp;
6332 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6333 struct tokenlist_list *tail, *prev;
6335 hp = assertion_lookup (symname, sym_length, hashcode);
6339 /* If no token list was specified, then eliminate this assertion
6341 if (! tokens_specified) {
6342 struct tokenlist_list *next;
6343 for (tail = hp->value; tail; tail = next) {
6345 free_token_list (tail->tokens);
6348 delete_assertion (hp);
6350 /* If a list of tokens was given, then delete any matching list. */
6355 struct tokenlist_list *next = tail->next;
6356 if (compare_token_lists (tail->tokens, tokens)) {
6360 hp->value = tail->next;
6361 free_token_list (tail->tokens);
6374 /* Test whether there is an assertion named NAME
6375 and optionally whether it has an asserted token list TOKENS.
6376 NAME is not null terminated; its length is SYM_LENGTH.
6377 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6380 check_assertion (name, sym_length, tokens_specified, tokens)
6383 int tokens_specified;
6384 struct arglist *tokens;
6386 ASSERTION_HASHNODE *hp;
6387 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6389 if (pedantic && !instack[indepth].system_header_p)
6390 pedwarn ("ANSI C does not allow testing assertions");
6392 hp = assertion_lookup (name, sym_length, hashcode);
6394 /* It is not an assertion; just return false. */
6397 /* If no token list was specified, then value is 1. */
6398 if (! tokens_specified)
6402 struct tokenlist_list *tail;
6406 /* If a list of tokens was given,
6407 then succeed if the assertion records a matching list. */
6410 if (compare_token_lists (tail->tokens, tokens))
6415 /* Fail if the assertion has no matching list. */
6420 /* Compare two lists of tokens for equality including order of tokens. */
6423 compare_token_lists (l1, l2)
6424 struct arglist *l1, *l2;
6427 if (l1->length != l2->length)
6429 if (bcmp (l1->name, l2->name, l1->length))
6435 /* Succeed if both lists end at the same time. */
6439 /* Read a space-separated list of tokens ending in a close parenthesis.
6440 Return a list of strings, in the order they were written.
6441 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6442 Parse the text starting at *BPP, and update *BPP.
6443 Don't parse beyond LIMIT. */
6445 static struct arglist *
6446 read_token_list (bpp, limit, error_flag)
6451 struct arglist *token_ptrs = 0;
6457 /* Loop over the assertion value tokens. */
6459 struct arglist *temp;
6463 /* Find the end of the token. */
6467 } else if (*bp == ')') {
6472 } else if (*bp == '"' || *bp == '\'')
6473 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6475 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6476 && *bp != '"' && *bp != '\'' && bp != limit)
6479 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6480 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6481 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6482 temp->name[bp - beg] = 0;
6483 temp->next = token_ptrs;
6485 temp->length = bp - beg;
6487 SKIP_WHITE_SPACE (bp);
6490 error ("unterminated token sequence in `#assert' or `#unassert'");
6497 /* We accumulated the names in reverse order.
6498 Now reverse them to get the proper order. */
6500 register struct arglist *prev = 0, *this, *next;
6501 for (this = token_ptrs; this; this = next) {
6511 free_token_list (tokens)
6512 struct arglist *tokens;
6515 struct arglist *next = tokens->next;
6516 free (tokens->name);
6523 * Install a name in the assertion hash table.
6525 * If LEN is >= 0, it is the length of the name.
6526 * Otherwise, compute the length by scanning the entire name.
6528 * If HASH is >= 0, it is the precomputed hash code.
6529 * Otherwise, compute the hash code.
6531 static ASSERTION_HASHNODE *
6532 assertion_install (name, len, hash)
6537 register ASSERTION_HASHNODE *hp;
6538 register int i, bucket;
6539 register U_CHAR *p, *q;
6541 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6542 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6544 hp->bucket_hdr = &assertion_hashtab[bucket];
6545 hp->next = assertion_hashtab[bucket];
6546 assertion_hashtab[bucket] = hp;
6548 if (hp->next != NULL)
6549 hp->next->prev = hp;
6552 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6555 for (i = 0; i < len; i++)
6562 * find the most recent hash node for name name (ending with first
6563 * non-identifier char) installed by install
6565 * If LEN is >= 0, it is the length of the name.
6566 * Otherwise, compute the length by scanning the entire name.
6568 * If HASH is >= 0, it is the precomputed hash code.
6569 * Otherwise, compute the hash code.
6571 static ASSERTION_HASHNODE *
6572 assertion_lookup (name, len, hash)
6577 register ASSERTION_HASHNODE *bucket;
6579 bucket = assertion_hashtab[hash];
6581 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6583 bucket = bucket->next;
6589 delete_assertion (hp)
6590 ASSERTION_HASHNODE *hp;
6593 if (hp->prev != NULL)
6594 hp->prev->next = hp->next;
6595 if (hp->next != NULL)
6596 hp->next->prev = hp->prev;
6598 /* make sure that the bucket chain header that
6599 the deleted guy was on points to the right thing afterwards. */
6600 if (hp == *hp->bucket_hdr)
6601 *hp->bucket_hdr = hp->next;
6607 * interpret #line directive. Remembers previously seen fnames
6608 * in its very own hash table.
6610 #define FNAME_HASHSIZE 37
6613 do_line (buf, limit, op, keyword)
6614 U_CHAR *buf, *limit;
6616 struct directive *keyword;
6618 register U_CHAR *bp;
6619 FILE_BUF *ip = &instack[indepth];
6622 enum file_change_code file_change = same_file;
6624 /* Expand any macros. */
6625 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6627 /* Point to macroexpanded line, which is null-terminated now. */
6629 SKIP_WHITE_SPACE (bp);
6631 if (!isdigit (*bp)) {
6632 error ("invalid format `#line' directive");
6636 /* The Newline at the end of this line remains to be processed.
6637 To put the next line at the specified line number,
6638 we must store a line number now that is one less. */
6639 new_lineno = atoi ((char *) bp) - 1;
6641 /* NEW_LINENO is one less than the actual line number here. */
6642 if (pedantic && new_lineno < 0)
6643 pedwarn ("line number out of range in `#line' directive");
6645 /* skip over the line number. */
6646 while (isdigit (*bp))
6649 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6650 if (*bp && !is_space[*bp]) {
6651 error ("invalid format `#line' directive");
6656 SKIP_WHITE_SPACE (bp);
6659 static HASHNODE *fname_table[FNAME_HASHSIZE];
6660 HASHNODE *hp, **hash_bucket;
6666 /* Turn the file name, which is a character string literal,
6667 into a null-terminated string. Do this in place. */
6670 switch ((*p++ = *bp++)) {
6672 error ("invalid format `#line' directive");
6677 char *bpc = (char *) bp;
6678 int c = parse_escape (&bpc);
6679 bp = (U_CHAR *) bpc;
6692 fname_length = p - fname;
6694 SKIP_WHITE_SPACE (bp);
6697 pedwarn ("garbage at end of `#line' directive");
6699 file_change = enter_file;
6700 else if (*bp == '2')
6701 file_change = leave_file;
6702 else if (*bp == '3')
6703 ip->system_header_p = 1;
6704 else if (*bp == '4')
6705 ip->system_header_p = 2;
6707 error ("invalid format `#line' directive");
6712 SKIP_WHITE_SPACE (bp);
6714 ip->system_header_p = 1;
6716 SKIP_WHITE_SPACE (bp);
6719 ip->system_header_p = 2;
6721 SKIP_WHITE_SPACE (bp);
6724 error ("invalid format `#line' directive");
6730 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6731 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6732 if (hp->length == fname_length &&
6733 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6734 ip->nominal_fname = hp->value.cpval;
6738 /* Didn't find it; cons up a new one. */
6739 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6740 hp->next = *hash_bucket;
6743 hp->length = fname_length;
6744 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6745 bcopy (fname, hp->value.cpval, fname_length);
6748 error ("invalid format `#line' directive");
6752 ip->lineno = new_lineno;
6753 output_line_directive (ip, op, 0, file_change);
6754 check_expand (op, ip->length - (ip->bufp - ip->buf));
6759 * remove the definition of a symbol from the symbol table.
6760 * according to un*x /lib/cpp, it is not an error to undef
6761 * something that has no definitions, so it isn't one here either.
6765 do_undef (buf, limit, op, keyword)
6766 U_CHAR *buf, *limit;
6768 struct directive *keyword;
6772 U_CHAR *orig_buf = buf;
6774 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6775 if (pcp_outfile && op)
6776 pass_thru_directive (buf, limit, op, keyword);
6778 SKIP_WHITE_SPACE (buf);
6779 sym_length = check_macro_name (buf, "macro");
6781 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6782 /* If we are generating additional info for debugging (with -g) we
6783 need to pass through all effective #undef directives. */
6784 if (debug_output && op)
6785 pass_thru_directive (orig_buf, limit, op, keyword);
6786 if (hp->type != T_MACRO)
6787 warning ("undefining `%s'", hp->name);
6793 SKIP_WHITE_SPACE (buf);
6795 pedwarn ("garbage after `#undef' directive");
6801 * Report an error detected by the program we are processing.
6802 * Use the text of the line in the error message.
6803 * (We use error because it prints the filename & line#.)
6807 do_error (buf, limit, op, keyword)
6808 U_CHAR *buf, *limit;
6810 struct directive *keyword;
6812 int length = limit - buf;
6813 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6814 bcopy ((char *) buf, (char *) copy, length);
6816 SKIP_WHITE_SPACE (copy);
6817 error ("#error %s", copy);
6822 * Report a warning detected by the program we are processing.
6823 * Use the text of the line in the warning message, then continue.
6824 * (We use error because it prints the filename & line#.)
6828 do_warning (buf, limit, op, keyword)
6829 U_CHAR *buf, *limit;
6831 struct directive *keyword;
6833 int length = limit - buf;
6834 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6835 bcopy ((char *) buf, (char *) copy, length);
6837 SKIP_WHITE_SPACE (copy);
6838 warning ("#warning %s", copy);
6842 /* Remember the name of the current file being read from so that we can
6843 avoid ever including it again. */
6849 FILE_BUF *ip = NULL;
6851 for (i = indepth; i >= 0; i--)
6852 if (instack[i].fname != NULL) {
6858 struct file_name_list *new;
6860 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6861 new->next = dont_repeat_files;
6862 dont_repeat_files = new;
6863 new->fname = savestring (ip->fname);
6864 new->control_macro = 0;
6865 new->got_name_map = 0;
6866 new->c_system_include_path = 0;
6870 /* #ident has already been copied to the output file, so just ignore it. */
6873 do_ident (buf, limit, op, keyword)
6874 U_CHAR *buf, *limit;
6876 struct directive *keyword;
6881 /* Allow #ident in system headers, since that's not user's fault. */
6882 if (pedantic && !instack[indepth].system_header_p)
6883 pedwarn ("ANSI C does not allow `#ident'");
6885 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6886 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6887 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6888 limit = buf + (trybuf.bufp - trybuf.buf);
6889 len = (limit - buf);
6892 /* Output directive name. */
6893 check_expand (op, 7);
6894 bcopy ("#ident ", (char *) op->bufp, 7);
6897 /* Output the expanded argument line. */
6898 check_expand (op, len);
6899 bcopy ((char *) buf, (char *) op->bufp, len);
6905 /* #pragma and its argument line have already been copied to the output file.
6906 Just check for some recognized pragmas that need validation here. */
6909 do_pragma (buf, limit, op, keyword)
6910 U_CHAR *buf, *limit;
6912 struct directive *keyword;
6914 SKIP_WHITE_SPACE (buf);
6915 if (!strncmp ((char *) buf, "once", 4)) {
6916 /* Allow #pragma once in system headers, since that's not the user's
6918 if (!instack[indepth].system_header_p)
6919 warning ("`#pragma once' is obsolete");
6923 if (!strncmp ((char *) buf, "implementation", 14)) {
6924 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6925 been included yet. */
6926 struct file_name_list *ptr;
6927 U_CHAR *p = buf + 14, *fname, *inc_fname;
6928 SKIP_WHITE_SPACE (p);
6929 if (*p == '\n' || *p != '\"')
6933 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6936 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6937 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6938 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6939 if (inc_fname && !strcmp ((char *) inc_fname, (char *) fname))
6940 warning ("`#pragma implementation' for `%s' appears after file is included",
6949 /* This was a fun hack, but #pragma seems to start to be useful.
6950 By failing to recognize it, we pass it through unchanged to cc1. */
6953 * the behavior of the #pragma directive is implementation defined.
6954 * this implementation defines it as follows.
6961 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6964 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6966 execl ("/usr/games/hack", "#pragma", 0);
6967 execl ("/usr/games/rogue", "#pragma", 0);
6968 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6969 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6971 fatal ("You are in a maze of twisty compiler features, all different");
6975 #ifdef SCCS_DIRECTIVE
6977 /* Just ignore #sccs, on systems where we define it at all. */
6980 do_sccs (buf, limit, op, keyword)
6981 U_CHAR *buf, *limit;
6983 struct directive *keyword;
6986 pedwarn ("ANSI C does not allow `#sccs'");
6990 #endif /* defined (SCCS_DIRECTIVE) */
6993 * handle #if directive by
6994 * 1) inserting special `defined' keyword into the hash table
6995 * that gets turned into 0 or 1 by special_symbol (thus,
6996 * if the luser has a symbol called `defined' already, it won't
6997 * work inside the #if directive)
6998 * 2) rescan the input into a temporary output buffer
6999 * 3) pass the output buffer to the yacc parser and collect a value
7000 * 4) clean up the mess left from steps 1 and 2.
7001 * 5) call conditional_skip to skip til the next #endif (etc.),
7002 * or not, depending on the value from step 3.
7006 do_if (buf, limit, op, keyword)
7007 U_CHAR *buf, *limit;
7009 struct directive *keyword;
7011 HOST_WIDE_INT value;
7012 FILE_BUF *ip = &instack[indepth];
7014 value = eval_if_expression (buf, limit - buf);
7015 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7020 * handle a #elif directive by not changing if_stack either.
7021 * see the comment above do_else.
7025 do_elif (buf, limit, op, keyword)
7026 U_CHAR *buf, *limit;
7028 struct directive *keyword;
7030 HOST_WIDE_INT value;
7031 FILE_BUF *ip = &instack[indepth];
7033 if (if_stack == instack[indepth].if_stack) {
7034 error ("`#elif' not within a conditional");
7037 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7038 error ("`#elif' after `#else'");
7039 fprintf (stderr, " (matches line %d", if_stack->lineno);
7040 if (if_stack->fname != NULL && ip->fname != NULL &&
7041 strcmp (if_stack->fname, ip->nominal_fname) != 0)
7042 fprintf (stderr, ", file %s", if_stack->fname);
7043 fprintf (stderr, ")\n");
7045 if_stack->type = T_ELIF;
7048 if (if_stack->if_succeeded)
7049 skip_if_group (ip, 0, op);
7051 value = eval_if_expression (buf, limit - buf);
7053 skip_if_group (ip, 0, op);
7055 ++if_stack->if_succeeded; /* continue processing input */
7056 output_line_directive (ip, op, 1, same_file);
7063 * evaluate a #if expression in BUF, of length LENGTH,
7064 * then parse the result as a C expression and return the value as an int.
7066 static HOST_WIDE_INT
7067 eval_if_expression (buf, length)
7072 HASHNODE *save_defined;
7073 HOST_WIDE_INT value;
7075 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7078 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7080 delete_macro (save_defined); /* clean up special symbol */
7082 value = parse_c_expression ((char *) temp_obuf.buf);
7084 free (temp_obuf.buf);
7090 * routine to handle ifdef/ifndef. Try to look up the symbol,
7091 * then do or don't skip to the #endif/#else/#elif depending
7092 * on what directive is actually being processed.
7096 do_xifdef (buf, limit, op, keyword)
7097 U_CHAR *buf, *limit;
7099 struct directive *keyword;
7102 FILE_BUF *ip = &instack[indepth];
7104 int start_of_file = 0;
7105 U_CHAR *control_macro = 0;
7107 /* Detect a #ifndef at start of file (not counting comments). */
7108 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7109 U_CHAR *p = ip->buf;
7110 while (p != directive_start) {
7114 /* Make no special provision for backslash-newline here; this is
7115 slower if backslash-newlines are present, but it's correct,
7116 and it's not worth it to tune for the rare backslash-newline. */
7118 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7119 /* Skip this comment. */
7121 U_CHAR *save_bufp = ip->bufp;
7123 p = skip_to_end_of_comment (ip, &junk, 1);
7124 ip->bufp = save_bufp;
7129 /* If we get here, this conditional is the beginning of the file. */
7134 /* Discard leading and trailing whitespace. */
7135 SKIP_WHITE_SPACE (buf);
7136 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7138 /* Find the end of the identifier at the beginning. */
7139 for (end = buf; is_idchar[*end]; end++);
7142 skip = (keyword->type == T_IFDEF);
7144 pedwarn (end == limit ? "`#%s' with no argument"
7145 : "`#%s' argument starts with punctuation",
7150 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
7151 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7152 else if (end != limit && !traditional)
7153 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7155 hp = lookup (buf, end-buf, -1);
7158 /* Output a precondition for this macro. */
7160 (hp->type == T_CONST
7161 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7162 fprintf (pcp_outfile, "#define %s\n", hp->name);
7165 fprintf (pcp_outfile, "#undef ");
7166 while (is_idchar[*cp]) /* Ick! */
7167 fputc (*cp++, pcp_outfile);
7168 putc ('\n', pcp_outfile);
7172 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7173 if (start_of_file && !skip) {
7174 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7175 bcopy ((char *) buf, (char *) control_macro, end - buf);
7176 control_macro[end - buf] = 0;
7180 conditional_skip (ip, skip, T_IF, control_macro, op);
7184 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7185 If this is a #ifndef starting at the beginning of a file,
7186 CONTROL_MACRO is the macro name tested by the #ifndef.
7187 Otherwise, CONTROL_MACRO is 0. */
7190 conditional_skip (ip, skip, type, control_macro, op)
7193 enum node_type type;
7194 U_CHAR *control_macro;
7197 IF_STACK_FRAME *temp;
7199 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7200 temp->fname = ip->nominal_fname;
7201 temp->lineno = ip->lineno;
7202 temp->next = if_stack;
7203 temp->control_macro = control_macro;
7206 if_stack->type = type;
7209 skip_if_group (ip, 0, op);
7212 ++if_stack->if_succeeded;
7213 output_line_directive (ip, &outbuf, 1, same_file);
7218 * skip to #endif, #else, or #elif. adjust line numbers, etc.
7219 * leaves input ptr at the sharp sign found.
7220 * If ANY is nonzero, return at next directive of any sort.
7223 skip_if_group (ip, any, op)
7228 register U_CHAR *bp = ip->bufp, *cp;
7229 register U_CHAR *endb = ip->buf + ip->length;
7230 struct directive *kt;
7231 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7232 U_CHAR *beg_of_line = bp;
7233 register int ident_length;
7234 U_CHAR *ident, *after_ident;
7235 /* Save info about where the group starts. */
7236 U_CHAR *beg_of_group = bp;
7237 int beg_lineno = ip->lineno;
7239 if (output_conditionals && op != 0) {
7240 char *ptr = "#failed\n";
7241 int len = strlen (ptr);
7243 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7248 check_expand (op, len);
7249 bcopy (ptr, (char *) op->bufp, len);
7252 output_line_directive (ip, op, 1, 0);
7257 case '/': /* possible comment */
7258 if (*bp == '\\' && bp[1] == '\n')
7261 || (cplusplus_comments && *bp == '/')) {
7263 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7268 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7269 NULL_PTR, NULL_PTR);
7272 /* Char after backslash loses its special meaning. */
7275 ++ip->lineno; /* But do update the line-count. */
7284 if (beg_of_line == 0 || traditional)
7287 while (bp[0] == '\\' && bp[1] == '\n')
7293 /* # keyword: a # must be first nonblank char on the line */
7294 if (beg_of_line == 0)
7298 /* Scan from start of line, skipping whitespace, comments
7299 and backslash-newlines, and see if we reach this #.
7300 If not, this # is not special. */
7302 /* If -traditional, require # to be at beginning of line. */
7305 if (is_hor_space[*bp])
7307 else if (*bp == '\\' && bp[1] == '\n')
7309 else if (*bp == '/' && bp[1] == '*') {
7311 while (!(*bp == '*' && bp[1] == '/'))
7315 /* There is no point in trying to deal with C++ // comments here,
7316 because if there is one, then this # must be part of the
7317 comment and we would never reach here. */
7321 if (bp != ip->bufp) {
7322 bp = ip->bufp + 1; /* Reset bp to after the #. */
7326 bp = ip->bufp + 1; /* Point after the '#' */
7327 if (ip->bufp[0] == '%') {
7328 /* Skip past the ':' again. */
7329 while (*bp == '\\') {
7336 /* Skip whitespace and \-newline. */
7338 if (is_hor_space[*bp])
7340 else if (*bp == '\\' && bp[1] == '\n')
7342 else if (*bp == '/' && bp[1] == '*') {
7344 while (!(*bp == '*' && bp[1] == '/')) {
7350 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
7352 while (bp[-1] == '\\' || *bp != '\n') {
7363 /* Now find end of directive name.
7364 If we encounter a backslash-newline, exchange it with any following
7365 symbol-constituents so that we end up with a contiguous name. */
7371 if (*bp == '\\' && bp[1] == '\n')
7372 name_newline_fix (bp);
7378 ident_length = bp - cp;
7382 /* A line of just `#' becomes blank. */
7384 if (ident_length == 0 && *after_ident == '\n') {
7388 if (ident_length == 0 || !is_idstart[*ident]) {
7390 while (is_idchar[*p]) {
7391 if (*p < '0' || *p > '9')
7395 /* Handle # followed by a line number. */
7396 if (p != ident && !is_idchar[*p]) {
7398 pedwarn ("`#' followed by integer");
7402 /* Avoid error for `###' and similar cases unless -pedantic. */
7404 while (*p == '#' || is_hor_space[*p]) p++;
7406 if (pedantic && !lang_asm)
7407 pedwarn ("invalid preprocessing directive");
7412 if (!lang_asm && pedantic)
7413 pedwarn ("invalid preprocessing directive name");
7417 for (kt = directive_table; kt->length >= 0; kt++) {
7418 IF_STACK_FRAME *temp;
7419 if (ident_length == kt->length
7420 && bcmp (cp, kt->name, kt->length) == 0) {
7421 /* If we are asked to return on next directive, do so now. */
7429 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7430 temp->next = if_stack;
7432 temp->lineno = ip->lineno;
7433 temp->fname = ip->nominal_fname;
7434 temp->type = kt->type;
7438 if (pedantic && if_stack != save_if_stack)
7441 if (if_stack == instack[indepth].if_stack) {
7442 error ("`#%s' not within a conditional", kt->name);
7445 else if (if_stack == save_if_stack)
7446 goto done; /* found what we came for */
7448 if (kt->type != T_ENDIF) {
7449 if (if_stack->type == T_ELSE)
7450 error ("`#else' or `#elif' after `#else'");
7451 if_stack->type = kt->type;
7456 if_stack = if_stack->next;
7466 /* Don't let erroneous code go by. */
7467 if (kt->length < 0 && !lang_asm && pedantic)
7468 pedwarn ("invalid preprocessing directive name");
7473 /* after this returns, rescan will exit because ip->bufp
7474 now points to the end of the buffer.
7475 rescan is responsible for the error message also. */
7478 if (output_conditionals && op != 0) {
7479 char *ptr = "#endfailed\n";
7480 int len = strlen (ptr);
7482 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7487 check_expand (op, beg_of_line - beg_of_group);
7488 bcopy ((char *) beg_of_group, (char *) op->bufp,
7489 beg_of_line - beg_of_group);
7490 op->bufp += beg_of_line - beg_of_group;
7491 op->lineno += ip->lineno - beg_lineno;
7492 check_expand (op, len);
7493 bcopy (ptr, (char *) op->bufp, len);
7500 * handle a #else directive. Do this by just continuing processing
7501 * without changing if_stack ; this is so that the error message
7502 * for missing #endif's etc. will point to the original #if. It
7503 * is possible that something different would be better.
7507 do_else (buf, limit, op, keyword)
7508 U_CHAR *buf, *limit;
7510 struct directive *keyword;
7512 FILE_BUF *ip = &instack[indepth];
7515 SKIP_WHITE_SPACE (buf);
7517 pedwarn ("text following `#else' violates ANSI standard");
7520 if (if_stack == instack[indepth].if_stack) {
7521 error ("`#else' not within a conditional");
7524 /* #ifndef can't have its special treatment for containing the whole file
7525 if it has a #else clause. */
7526 if_stack->control_macro = 0;
7528 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7529 error ("`#else' after `#else'");
7530 fprintf (stderr, " (matches line %d", if_stack->lineno);
7531 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7532 fprintf (stderr, ", file %s", if_stack->fname);
7533 fprintf (stderr, ")\n");
7535 if_stack->type = T_ELSE;
7538 if (if_stack->if_succeeded)
7539 skip_if_group (ip, 0, op);
7541 ++if_stack->if_succeeded; /* continue processing input */
7542 output_line_directive (ip, op, 1, same_file);
7548 * unstack after #endif directive
7552 do_endif (buf, limit, op, keyword)
7553 U_CHAR *buf, *limit;
7555 struct directive *keyword;
7558 SKIP_WHITE_SPACE (buf);
7560 pedwarn ("text following `#endif' violates ANSI standard");
7563 if (if_stack == instack[indepth].if_stack)
7564 error ("unbalanced `#endif'");
7566 IF_STACK_FRAME *temp = if_stack;
7567 if_stack = if_stack->next;
7568 if (temp->control_macro != 0) {
7569 /* This #endif matched a #ifndef at the start of the file.
7570 See if it is at the end of the file. */
7571 FILE_BUF *ip = &instack[indepth];
7572 U_CHAR *p = ip->bufp;
7573 U_CHAR *ep = ip->buf + ip->length;
7579 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7580 /* Skip this comment. */
7582 U_CHAR *save_bufp = ip->bufp;
7584 p = skip_to_end_of_comment (ip, &junk, 1);
7585 ip->bufp = save_bufp;
7590 /* If we get here, this #endif ends a #ifndef
7591 that contains all of the file (aside from whitespace).
7592 Arrange not to include the file again
7593 if the macro that was tested is defined.
7595 Do not do this for the top-level file in a -include or any
7596 file in a -imacros. */
7598 && ! (indepth == 1 && no_record_file)
7599 && ! (no_record_file && no_output))
7600 record_control_macro (ip->fname, temp->control_macro);
7604 output_line_directive (&instack[indepth], op, 1, same_file);
7609 /* When an #else or #endif is found while skipping failed conditional,
7610 if -pedantic was specified, this is called to warn about text after
7611 the directive name. P points to the first char after the directive name. */
7617 /* Advance P over whitespace and comments. */
7619 if (*p == '\\' && p[1] == '\n')
7621 if (is_hor_space[*p])
7623 else if (*p == '/') {
7624 if (p[1] == '\\' && p[2] == '\n')
7625 newline_fix (p + 1);
7628 /* Don't bother warning about unterminated comments
7629 since that will happen later. Just be sure to exit. */
7631 if (p[1] == '\\' && p[2] == '\n')
7632 newline_fix (p + 1);
7633 if (*p == '*' && p[1] == '/') {
7640 else if (cplusplus_comments && p[1] == '/') {
7642 while (*p && (*p != '\n' || p[-1] == '\\'))
7647 if (*p && *p != '\n')
7648 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7651 /* Skip a comment, assuming the input ptr immediately follows the
7652 initial slash-star. Bump *LINE_COUNTER for each newline.
7653 (The canonical line counter is &ip->lineno.)
7654 Don't use this routine (or the next one) if bumping the line
7655 counter is not sufficient to deal with newlines in the string.
7657 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7658 This feature is useful when processing a comment that is going to be
7659 processed or was processed at another point in the preprocessor,
7660 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7663 skip_to_end_of_comment (ip, line_counter, nowarn)
7664 register FILE_BUF *ip;
7665 int *line_counter; /* place to remember newlines, or NULL */
7668 register U_CHAR *limit = ip->buf + ip->length;
7669 register U_CHAR *bp = ip->bufp;
7670 FILE_BUF *op = &outbuf; /* JF */
7671 int output = put_out_comments && !line_counter;
7672 int start_line = line_counter ? *line_counter : 0;
7674 /* JF this line_counter stuff is a crock to make sure the
7675 comment is only put out once, no matter how many times
7676 the comment is skipped. It almost works */
7681 if (cplusplus_comments && bp[-1] == '/') {
7683 while (bp < limit) {
7685 if (*bp == '\n' && bp[-1] != '\\')
7697 while (bp < limit) {
7698 if (bp[-1] != '\\' && *bp == '\n') {
7701 if (*bp == '\n' && line_counter)
7710 while (bp < limit) {
7715 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7716 warning ("`/*' within comment");
7719 /* If this is the end of the file, we have an unterminated comment.
7720 Don't swallow the newline. We are guaranteed that there will be a
7721 trailing newline and various pieces assume it's there. */
7728 if (line_counter != NULL)
7734 if (*bp == '\\' && bp[1] == '\n')
7747 error_with_line (line_for_error (start_line), "unterminated comment");
7753 * Skip over a quoted string. BP points to the opening quote.
7754 * Returns a pointer after the closing quote. Don't go past LIMIT.
7755 * START_LINE is the line number of the starting point (but it need
7756 * not be valid if the starting point is inside a macro expansion).
7758 * The input stack state is not changed.
7760 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7761 * for each newline passed.
7763 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7764 * if we pass a backslash-newline.
7766 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7769 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7770 register U_CHAR *bp;
7771 register U_CHAR *limit;
7773 int *count_newlines;
7774 int *backslash_newlines_p;
7777 register U_CHAR c, match;
7782 error_with_line (line_for_error (start_line),
7783 "unterminated string or character constant");
7784 error_with_line (multiline_string_line,
7785 "possible real start of unterminated constant");
7786 multiline_string_line = 0;
7793 while (*bp == '\\' && bp[1] == '\n') {
7794 if (backslash_newlines_p)
7795 *backslash_newlines_p = 1;
7800 if (*bp == '\n' && count_newlines) {
7801 if (backslash_newlines_p)
7802 *backslash_newlines_p = 1;
7806 } else if (c == '\n') {
7808 /* Unterminated strings and character constants are 'valid'. */
7809 bp--; /* Don't consume the newline. */
7814 if (pedantic || match == '\'') {
7815 error_with_line (line_for_error (start_line),
7816 "unterminated string or character constant");
7822 /* If not traditional, then allow newlines inside strings. */
7825 if (multiline_string_line == 0)
7826 multiline_string_line = start_line;
7827 } else if (c == match)
7833 /* Place into DST a quoted string representing the string SRC.
7834 Return the address of DST's terminating null. */
7836 quote_string (dst, src)
7843 switch ((c = *src++))
7850 sprintf (dst, "\\%03o", c);
7868 /* Skip across a group of balanced parens, starting from IP->bufp.
7869 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7871 This does not handle newlines, because it's used for the arg of #if,
7872 where there aren't any newlines. Also, backslash-newline can't appear. */
7875 skip_paren_group (ip)
7876 register FILE_BUF *ip;
7878 U_CHAR *limit = ip->buf + ip->length;
7879 U_CHAR *p = ip->bufp;
7881 int lines_dummy = 0;
7883 while (p != limit) {
7893 return ip->bufp = p;
7899 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7907 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7909 return ip->bufp = p;
7920 * write out a #line directive, for instance, after an #include file.
7921 * If CONDITIONAL is nonzero, we can omit the #line if it would
7922 * appear to be a no-op, and we can output a few newlines instead
7923 * if we want to increase the line number by a small amount.
7924 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7928 output_line_directive (ip, op, conditional, file_change)
7931 enum file_change_code file_change;
7934 char *line_directive_buf, *line_end;
7936 if (no_line_directives
7937 || ip->fname == NULL
7939 op->lineno = ip->lineno;
7944 if (ip->lineno == op->lineno)
7947 /* If the inherited line number is a little too small,
7948 output some newlines instead of a #line directive. */
7949 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7950 check_expand (op, 10);
7951 while (ip->lineno > op->lineno) {
7959 /* Don't output a line number of 0 if we can help it. */
7960 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7961 && *ip->bufp == '\n') {
7966 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7967 sprintf (line_directive_buf, "# %d ", ip->lineno);
7968 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7970 if (file_change != same_file) {
7972 *line_end++ = file_change == enter_file ? '1' : '2';
7974 /* Tell cc1 if following text comes from a system header file. */
7975 if (ip->system_header_p) {
7979 #ifndef NO_IMPLICIT_EXTERN_C
7980 /* Tell cc1plus if following text should be treated as C. */
7981 if (ip->system_header_p == 2 && cplusplus) {
7987 len = line_end - line_directive_buf;
7988 check_expand (op, len + 1);
7989 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7991 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7993 op->lineno = ip->lineno;
7996 /* This structure represents one parsed argument in a macro call.
7997 `raw' points to the argument text as written (`raw_length' is its length).
7998 `expanded' points to the argument's macro-expansion
7999 (its length is `expand_length').
8000 `stringified_length' is the length the argument would have
8002 `use_count' is the number of times this macro arg is substituted
8003 into the macro. If the actual use count exceeds 10,
8004 the value stored is 10.
8005 `free1' and `free2', if nonzero, point to blocks to be freed
8006 when the macro argument data is no longer needed. */
8009 U_CHAR *raw, *expanded;
8010 int raw_length, expand_length;
8011 int stringified_length;
8012 U_CHAR *free1, *free2;
8017 /* Expand a macro call.
8018 HP points to the symbol that is the macro being called.
8019 Put the result of expansion onto the input stack
8020 so that subsequent input by our caller will use it.
8022 If macro wants arguments, caller has already verified that
8023 an argument list follows; arguments come from the input stack. */
8026 macroexpand (hp, op)
8031 DEFINITION *defn = hp->value.defn;
8032 register U_CHAR *xbuf;
8034 int start_line = instack[indepth].lineno;
8035 int rest_args, rest_zero;
8037 CHECK_DEPTH (return;);
8039 /* it might not actually be a macro. */
8040 if (hp->type != T_MACRO) {
8041 special_symbol (hp, op);
8045 /* This macro is being used inside a #if, which means it must be */
8046 /* recorded as a precondition. */
8047 if (pcp_inside_if && pcp_outfile && defn->predefined)
8048 dump_single_macro (hp, pcp_outfile);
8050 nargs = defn->nargs;
8054 struct argdata *args;
8055 char *parse_error = 0;
8057 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8059 for (i = 0; i < nargs; i++) {
8060 args[i].raw = (U_CHAR *) "";
8061 args[i].expanded = 0;
8062 args[i].raw_length = args[i].expand_length
8063 = args[i].stringified_length = 0;
8064 args[i].free1 = args[i].free2 = 0;
8065 args[i].use_count = 0;
8068 /* Parse all the macro args that are supplied. I counts them.
8069 The first NARGS args are stored in ARGS.
8070 The rest are discarded.
8071 If rest_args is set then we assume macarg absorbed the rest of the args.
8076 /* Discard the open-parenthesis or comma before the next arg. */
8077 ++instack[indepth].bufp;
8080 if (i < nargs || (nargs == 0 && i == 0)) {
8081 /* if we are working on last arg which absorbs rest of args... */
8082 if (i == nargs - 1 && defn->rest_args)
8084 parse_error = macarg (&args[i], rest_args);
8087 parse_error = macarg (NULL_PTR, 0);
8089 error_with_line (line_for_error (start_line), parse_error);
8093 } while (*instack[indepth].bufp != ')');
8095 /* If we got one arg but it was just whitespace, call that 0 args. */
8097 register U_CHAR *bp = args[0].raw;
8098 register U_CHAR *lim = bp + args[0].raw_length;
8099 /* cpp.texi says for foo ( ) we provide one argument.
8100 However, if foo wants just 0 arguments, treat this as 0. */
8102 while (bp != lim && is_space[*bp]) bp++;
8107 /* Don't output an error message if we have already output one for
8108 a parse error above. */
8110 if (nargs == 0 && i > 0) {
8112 error ("arguments given to macro `%s'", hp->name);
8113 } else if (i < nargs) {
8114 /* traditional C allows foo() if foo wants one argument. */
8115 if (nargs == 1 && i == 0 && traditional)
8117 /* the rest args token is allowed to absorb 0 tokens */
8118 else if (i == nargs - 1 && defn->rest_args)
8120 else if (parse_error)
8123 error ("macro `%s' used without args", hp->name);
8125 error ("macro `%s' used with just one arg", hp->name);
8127 error ("macro `%s' used with only %d args", hp->name, i);
8128 } else if (i > nargs) {
8130 error ("macro `%s' used with too many (%d) args", hp->name, i);
8133 /* Swallow the closeparen. */
8134 ++instack[indepth].bufp;
8136 /* If macro wants zero args, we parsed the arglist for checking only.
8137 Read directly from the macro definition. */
8139 xbuf = defn->expansion;
8140 xbuf_len = defn->length;
8142 register U_CHAR *exp = defn->expansion;
8143 register int offset; /* offset in expansion,
8144 copied a piece at a time */
8145 register int totlen; /* total amount of exp buffer filled so far */
8147 register struct reflist *ap, *last_ap;
8149 /* Macro really takes args. Compute the expansion of this call. */
8151 /* Compute length in characters of the macro's expansion.
8152 Also count number of times each arg is used. */
8153 xbuf_len = defn->length;
8154 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8156 xbuf_len += args[ap->argno].stringified_length;
8157 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8158 /* Add 4 for two newline-space markers to prevent
8159 token concatenation. */
8160 xbuf_len += args[ap->argno].raw_length + 4;
8162 /* We have an ordinary (expanded) occurrence of the arg.
8163 So compute its expansion, if we have not already. */
8164 if (args[ap->argno].expanded == 0) {
8166 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8167 args[ap->argno].raw + args[ap->argno].raw_length,
8170 args[ap->argno].expanded = obuf.buf;
8171 args[ap->argno].expand_length = obuf.length;
8172 args[ap->argno].free2 = obuf.buf;
8175 /* Add 4 for two newline-space markers to prevent
8176 token concatenation. */
8177 xbuf_len += args[ap->argno].expand_length + 4;
8179 if (args[ap->argno].use_count < 10)
8180 args[ap->argno].use_count++;
8183 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8185 /* Generate in XBUF the complete expansion
8186 with arguments substituted in.
8187 TOTLEN is the total size generated so far.
8188 OFFSET is the index in the definition
8189 of where we are copying from. */
8190 offset = totlen = 0;
8191 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8192 last_ap = ap, ap = ap->next) {
8193 register struct argdata *arg = &args[ap->argno];
8194 int count_before = totlen;
8196 /* Add chars to XBUF. */
8197 for (i = 0; i < ap->nchars; i++, offset++)
8198 xbuf[totlen++] = exp[offset];
8200 /* If followed by an empty rest arg with concatenation,
8201 delete the last run of nonwhite chars. */
8202 if (rest_zero && totlen > count_before
8203 && ((ap->rest_args && ap->raw_before != 0)
8204 || (last_ap != NULL && last_ap->rest_args
8205 && last_ap->raw_after != 0))) {
8206 /* Delete final whitespace. */
8207 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8211 /* Delete the nonwhites before them. */
8212 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8217 if (ap->stringify != 0) {
8218 int arglen = arg->raw_length;
8224 && (c = arg->raw[i], is_space[c]))
8227 && (c = arg->raw[arglen - 1], is_space[c]))
8230 xbuf[totlen++] = '\"'; /* insert beginning quote */
8231 for (; i < arglen; i++) {
8234 /* Special markers Newline Space
8235 generate nothing for a stringified argument. */
8236 if (c == '\n' && arg->raw[i+1] != '\n') {
8241 /* Internal sequences of whitespace are replaced by one space
8242 except within an string or char token. */
8244 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8246 /* Note that Newline Space does occur within whitespace
8247 sequences; consider it part of the sequence. */
8248 if (c == '\n' && is_space[arg->raw[i+1]])
8250 else if (c != '\n' && is_space[c])
8267 } else if (c == '\"' || c == '\'')
8271 /* Escape these chars */
8272 if (c == '\"' || (in_string && c == '\\'))
8273 xbuf[totlen++] = '\\';
8277 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8282 xbuf[totlen++] = '\"'; /* insert ending quote */
8283 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8284 U_CHAR *p1 = arg->raw;
8285 U_CHAR *l1 = p1 + arg->raw_length;
8286 if (ap->raw_before != 0) {
8287 while (p1 != l1 && is_space[*p1]) p1++;
8288 while (p1 != l1 && is_idchar[*p1])
8289 xbuf[totlen++] = *p1++;
8290 /* Delete any no-reexpansion marker that follows
8291 an identifier at the beginning of the argument
8292 if the argument is concatenated with what precedes it. */
8293 if (p1[0] == '\n' && p1[1] == '-')
8295 } else if (!traditional) {
8296 /* Ordinary expanded use of the argument.
8297 Put in newline-space markers to prevent token pasting. */
8298 xbuf[totlen++] = '\n';
8299 xbuf[totlen++] = ' ';
8301 if (ap->raw_after != 0) {
8302 /* Arg is concatenated after: delete trailing whitespace,
8303 whitespace markers, and no-reexpansion markers. */
8305 if (is_space[l1[-1]]) l1--;
8306 else if (l1[-1] == '-') {
8307 U_CHAR *p2 = l1 - 1;
8308 /* If a `-' is preceded by an odd number of newlines then it
8309 and the last newline are a no-reexpansion marker. */
8310 while (p2 != p1 && p2[-1] == '\n') p2--;
8311 if ((l1 - 1 - p2) & 1) {
8320 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8322 if (!traditional && ap->raw_after == 0) {
8323 /* Ordinary expanded use of the argument.
8324 Put in newline-space markers to prevent token pasting. */
8325 xbuf[totlen++] = '\n';
8326 xbuf[totlen++] = ' ';
8329 /* Ordinary expanded use of the argument.
8330 Put in newline-space markers to prevent token pasting. */
8332 xbuf[totlen++] = '\n';
8333 xbuf[totlen++] = ' ';
8335 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8336 arg->expand_length);
8337 totlen += arg->expand_length;
8339 xbuf[totlen++] = '\n';
8340 xbuf[totlen++] = ' ';
8342 /* If a macro argument with newlines is used multiple times,
8343 then only expand the newlines once. This avoids creating output
8344 lines which don't correspond to any input line, which confuses
8346 if (arg->use_count > 1 && arg->newlines > 0) {
8347 /* Don't bother doing change_newlines for subsequent
8351 = change_newlines (arg->expanded, arg->expand_length);
8355 if (totlen > xbuf_len)
8359 /* if there is anything left of the definition
8360 after handling the arg list, copy that in too. */
8362 for (i = offset; i < defn->length; i++) {
8363 /* if we've reached the end of the macro */
8366 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8367 && last_ap->raw_after != 0))
8368 xbuf[totlen++] = exp[i];
8374 for (i = 0; i < nargs; i++) {
8375 if (args[i].free1 != 0)
8376 free (args[i].free1);
8377 if (args[i].free2 != 0)
8378 free (args[i].free2);
8382 xbuf = defn->expansion;
8383 xbuf_len = defn->length;
8386 /* Now put the expansion on the input stack
8387 so our caller will commence reading from it. */
8389 register FILE_BUF *ip2;
8391 ip2 = &instack[++indepth];
8394 ip2->nominal_fname = 0;
8395 /* This may not be exactly correct, but will give much better error
8396 messages for nested macro calls than using a line number of zero. */
8397 ip2->lineno = start_line;
8399 ip2->length = xbuf_len;
8401 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8403 ip2->if_stack = if_stack;
8404 ip2->system_header_p = 0;
8406 /* Recursive macro use sometimes works traditionally.
8407 #define foo(x,y) bar (x (y,0), y)
8411 hp->type = T_DISABLED;
8416 * Parse a macro argument and store the info on it into *ARGPTR.
8417 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8418 * Return nonzero to indicate a syntax error.
8422 macarg (argptr, rest_args)
8423 register struct argdata *argptr;
8426 FILE_BUF *ip = &instack[indepth];
8432 /* Try to parse as much of the argument as exists at this
8433 input stack level. */
8434 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8435 &paren, &newlines, &comments, rest_args);
8437 /* If we find the end of the argument at this level,
8438 set up *ARGPTR to point at it in the input stack. */
8439 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8440 && bp != ip->buf + ip->length) {
8442 argptr->raw = ip->bufp;
8443 argptr->raw_length = bp - ip->bufp;
8444 argptr->newlines = newlines;
8448 /* This input stack level ends before the macro argument does.
8449 We must pop levels and keep parsing.
8450 Therefore, we must allocate a temporary buffer and copy
8451 the macro argument into it. */
8452 int bufsize = bp - ip->bufp;
8453 int extra = newlines;
8454 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8455 int final_start = 0;
8457 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8459 ip->lineno += newlines;
8461 while (bp == ip->buf + ip->length) {
8462 if (instack[indepth].macro == 0) {
8463 result = "unterminated macro call";
8466 ip->macro->type = T_MACRO;
8468 free (ip->free_ptr);
8469 ip = &instack[--indepth];
8472 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8473 &newlines, &comments, rest_args);
8474 final_start = bufsize;
8475 bufsize += bp - ip->bufp;
8477 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8478 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8481 ip->lineno += newlines;
8484 /* Now, if arg is actually wanted, record its raw form,
8485 discarding comments and duplicating newlines in whatever
8486 part of it did not come from a macro expansion.
8487 EXTRA space has been preallocated for duplicating the newlines.
8488 FINAL_START is the index of the start of that part. */
8490 argptr->raw = buffer;
8491 argptr->raw_length = bufsize;
8492 argptr->free1 = buffer;
8493 argptr->newlines = newlines;
8494 if ((newlines || comments) && ip->fname != 0)
8497 discard_comments (argptr->raw + final_start,
8498 argptr->raw_length - final_start,
8500 argptr->raw[argptr->raw_length] = 0;
8501 if (argptr->raw_length > bufsize + extra)
8506 /* If we are not discarding this argument,
8507 macroexpand it and compute its length as stringified.
8508 All this info goes into *ARGPTR. */
8511 register U_CHAR *buf, *lim;
8512 register int totlen;
8515 lim = buf + argptr->raw_length;
8517 while (buf != lim && is_space[*buf])
8519 while (buf != lim && is_space[lim[-1]])
8521 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8522 while (buf != lim) {
8523 register U_CHAR c = *buf++;
8525 /* Internal sequences of whitespace are replaced by one space
8526 in most cases, but not always. So count all the whitespace
8527 in case we need to keep it all. */
8530 SKIP_ALL_WHITE_SPACE (buf);
8533 if (c == '\"' || c == '\\') /* escape these chars */
8535 else if (!isprint (c))
8538 argptr->stringified_length = totlen;
8543 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8544 counting parens in *DEPTHPTR,
8545 and return if reach LIMIT
8546 or before a `)' that would make *DEPTHPTR negative
8547 or before a comma when *DEPTHPTR is zero.
8548 Single and double quotes are matched and termination
8549 is inhibited within them. Comments also inhibit it.
8550 Value returned is pointer to stopping place.
8552 Increment *NEWLINES each time a newline is passed.
8553 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8554 Set *COMMENTS to 1 if a comment is seen. */
8557 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8559 register U_CHAR *limit;
8560 int *depthptr, *newlines, *comments;
8563 register U_CHAR *bp = start;
8565 while (bp < limit) {
8571 if (--(*depthptr) < 0)
8575 /* Traditionally, backslash makes following char not special. */
8576 if (bp + 1 < limit && traditional)
8579 /* But count source lines anyway. */
8588 if (bp[1] == '\\' && bp[2] == '\n')
8589 newline_fix (bp + 1);
8590 if (cplusplus_comments && bp[1] == '/') {
8593 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8594 if (*bp == '\n') ++*newlines;
8597 /* Now count the newline that we are about to skip. */
8601 if (bp[1] != '*' || bp + 1 >= limit)
8605 while (bp + 1 < limit) {
8607 && bp[1] == '\\' && bp[2] == '\n')
8608 newline_fix (bp + 1);
8609 if (bp[0] == '*' && bp[1] == '/')
8611 if (*bp == '\n') ++*newlines;
8619 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8624 while (*bp == '\\' && bp[1] == '\n') {
8627 } else if (*bp == '\n') {
8636 /* if we've returned to lowest level and we aren't absorbing all args */
8637 if ((*depthptr) == 0 && rest_args == 0)
8647 /* Discard comments and duplicate newlines
8648 in the string of length LENGTH at START,
8649 except inside of string constants.
8650 The string is copied into itself with its beginning staying fixed.
8652 NEWLINES is the number of newlines that must be duplicated.
8653 We assume that that much extra space is available past the end
8657 discard_comments (start, length, newlines)
8662 register U_CHAR *ibp;
8663 register U_CHAR *obp;
8664 register U_CHAR *limit;
8667 /* If we have newlines to duplicate, copy everything
8668 that many characters up. Then, in the second part,
8669 we will have room to insert the newlines
8671 NEWLINES may actually be too large, because it counts
8672 newlines in string constants, and we don't duplicate those.
8673 But that does no harm. */
8675 ibp = start + length;
8676 obp = ibp + newlines;
8678 while (limit != ibp)
8682 ibp = start + newlines;
8683 limit = start + length + newlines;
8686 while (ibp < limit) {
8687 *obp++ = c = *ibp++;
8690 /* Duplicate the newline. */
8702 if (*ibp == '\\' && ibp[1] == '\n')
8704 /* Delete any comment. */
8705 if (cplusplus_comments && ibp[0] == '/') {
8706 /* Comments are equivalent to spaces. */
8709 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8713 if (ibp[0] != '*' || ibp + 1 >= limit)
8715 /* Comments are equivalent to spaces.
8716 For -traditional, a comment is equivalent to nothing. */
8722 while (ibp + 1 < limit) {
8724 && ibp[1] == '\\' && ibp[2] == '\n')
8725 newline_fix (ibp + 1);
8726 if (ibp[0] == '*' && ibp[1] == '/')
8735 /* Notice and skip strings, so that we don't
8736 think that comments start inside them,
8737 and so we don't duplicate newlines in them. */
8740 while (ibp < limit) {
8741 *obp++ = c = *ibp++;
8744 if (c == '\n' && quotec == '\'')
8746 if (c == '\\' && ibp < limit) {
8747 while (*ibp == '\\' && ibp[1] == '\n')
8760 /* Turn newlines to spaces in the string of length LENGTH at START,
8761 except inside of string constants.
8762 The string is copied into itself with its beginning staying fixed. */
8765 change_newlines (start, length)
8769 register U_CHAR *ibp;
8770 register U_CHAR *obp;
8771 register U_CHAR *limit;
8775 limit = start + length;
8778 while (ibp < limit) {
8779 *obp++ = c = *ibp++;
8782 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8783 string. Skip past the newline and its duplicate.
8784 Put a space in the output. */
8795 /* Notice and skip strings, so that we don't delete newlines in them. */
8798 while (ibp < limit) {
8799 *obp++ = c = *ibp++;
8802 if (c == '\n' && quotec == '\'')
8814 * my_strerror - return the descriptive text associated with an `errno' code.
8818 my_strerror (errnum)
8824 #ifndef HAVE_STRERROR
8825 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8827 result = strerror (errnum);
8830 /* VAXCRTL's strerror() takes an optional second argument, which only
8831 matters when the first argument is EVMSERR. However, it's simplest
8832 just to pass it unconditionally. `vaxc$errno' is declared in
8833 <errno.h>, and maintained by the library in parallel with `errno'.
8834 We assume that caller's `errnum' either matches the last setting of
8835 `errno' by the library or else does not have the value `EVMSERR'. */
8837 result = strerror (errnum, vaxc$errno);
8841 result = "undocumented I/O error";
8847 * error - print error message and increment count of errors.
8851 error (PRINTF_ALIST (msg))
8856 VA_START (args, msg);
8867 FILE_BUF *ip = NULL;
8869 print_containing_files ();
8871 for (i = indepth; i >= 0; i--)
8872 if (instack[i].fname != NULL) {
8878 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8879 vfprintf (stderr, msg, args);
8880 fprintf (stderr, "\n");
8884 /* Error including a message from `errno'. */
8887 error_from_errno (name)
8891 FILE_BUF *ip = NULL;
8893 print_containing_files ();
8895 for (i = indepth; i >= 0; i--)
8896 if (instack[i].fname != NULL) {
8902 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8904 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8909 /* Print error message but don't count it. */
8912 warning (PRINTF_ALIST (msg))
8917 VA_START (args, msg);
8918 vwarning (msg, args);
8923 vwarning (msg, args)
8928 FILE_BUF *ip = NULL;
8930 if (inhibit_warnings)
8933 if (warnings_are_errors)
8936 print_containing_files ();
8938 for (i = indepth; i >= 0; i--)
8939 if (instack[i].fname != NULL) {
8945 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8946 fprintf (stderr, "warning: ");
8947 vfprintf (stderr, msg, args);
8948 fprintf (stderr, "\n");
8952 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8953 error_with_line (int line, PRINTF_ALIST (msg))
8955 error_with_line (line, PRINTF_ALIST (msg))
8962 VA_START (args, msg);
8963 verror_with_line (line, msg, args);
8968 verror_with_line (line, msg, args)
8974 FILE_BUF *ip = NULL;
8976 print_containing_files ();
8978 for (i = indepth; i >= 0; i--)
8979 if (instack[i].fname != NULL) {
8985 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8986 vfprintf (stderr, msg, args);
8987 fprintf (stderr, "\n");
8992 vwarning_with_line (line, msg, args)
8998 FILE_BUF *ip = NULL;
9000 if (inhibit_warnings)
9003 if (warnings_are_errors)
9006 print_containing_files ();
9008 for (i = indepth; i >= 0; i--)
9009 if (instack[i].fname != NULL) {
9015 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
9016 fprintf (stderr, "warning: ");
9017 vfprintf (stderr, msg, args);
9018 fprintf (stderr, "\n");
9021 /* print an error message and maybe count it. */
9024 pedwarn (PRINTF_ALIST (msg))
9029 VA_START (args, msg);
9030 if (pedantic_errors)
9033 vwarning (msg, args);
9038 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9039 pedwarn_with_line (int line, PRINTF_ALIST (msg))
9041 pedwarn_with_line (line, PRINTF_ALIST (msg))
9048 VA_START (args, msg);
9049 if (pedantic_errors)
9050 verror_with_line (line, msg, args);
9052 vwarning_with_line (line, msg, args);
9056 /* Report a warning (or an error if pedantic_errors)
9057 giving specified file name and line number, not current. */
9060 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9061 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
9063 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
9071 if (!pedantic_errors && inhibit_warnings)
9074 fprintf (stderr, "%s:%d: ", file, line);
9075 if (pedantic_errors)
9077 if (!pedantic_errors)
9078 fprintf (stderr, "warning: ");
9079 VA_START (args, msg);
9080 vfprintf (stderr, msg, args);
9082 fprintf (stderr, "\n");
9085 /* Print the file names and line numbers of the #include
9086 directives which led to the current file. */
9089 print_containing_files ()
9091 FILE_BUF *ip = NULL;
9095 /* If stack of files hasn't changed since we last printed
9096 this info, don't repeat it. */
9097 if (last_error_tick == input_file_stack_tick)
9100 for (i = indepth; i >= 0; i--)
9101 if (instack[i].fname != NULL) {
9106 /* Give up if we don't find a source file. */
9110 /* Find the other, outer source files. */
9111 for (i--; i >= 0; i--)
9112 if (instack[i].fname != NULL) {
9116 fprintf (stderr, "In file included");
9118 fprintf (stderr, ",\n ");
9121 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9124 fprintf (stderr, ":\n");
9126 /* Record we have printed the status as of this time. */
9127 last_error_tick = input_file_stack_tick;
9130 /* Return the line at which an error occurred.
9131 The error is not necessarily associated with the current spot
9132 in the input stack, so LINE says where. LINE will have been
9133 copied from ip->lineno for the current input level.
9134 If the current level is for a file, we return LINE.
9135 But if the current level is not for a file, LINE is meaningless.
9136 In that case, we return the lineno of the innermost file. */
9139 line_for_error (line)
9145 for (i = indepth; i >= 0; ) {
9146 if (instack[i].fname != 0)
9151 line1 = instack[i].lineno;
9159 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9161 * As things stand, nothing is ever placed in the output buffer to be
9162 * removed again except when it's KNOWN to be part of an identifier,
9163 * so flushing and moving down everything left, instead of expanding,
9167 /* You might think void was cleaner for the return type,
9168 but that would get type mismatch in check_expand in strict ANSI. */
9170 grow_outbuf (obuf, needed)
9171 register FILE_BUF *obuf;
9172 register int needed;
9177 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9180 /* Make it at least twice as big as it is now. */
9182 /* Make it have at least 150% of the free space we will need. */
9183 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9184 if (minsize > obuf->length)
9185 obuf->length = minsize;
9187 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9190 obuf->bufp = p + (obuf->bufp - obuf->buf);
9196 /* Symbol table for macro names and special symbols */
9199 * install a name in the main hash table, even if it is already there.
9200 * name stops with first non alphanumeric, except leading '#'.
9201 * caller must check against redefinition if that is desired.
9202 * delete_macro () removes things installed by install () in fifo order.
9203 * this is important because of the `defined' special symbol used
9204 * in #if, and also if pushdef/popdef directives are ever implemented.
9206 * If LEN is >= 0, it is the length of the name.
9207 * Otherwise, compute the length by scanning the entire name.
9209 * If HASH is >= 0, it is the precomputed hash code.
9210 * Otherwise, compute the hash code.
9213 install (name, len, type, value, hash)
9216 enum node_type type;
9220 register HASHNODE *hp;
9221 register int i, bucket;
9222 register U_CHAR *p, *q;
9226 while (is_idchar[*p])
9232 hash = hashf (name, len, HASHSIZE);
9234 i = sizeof (HASHNODE) + len + 1;
9235 hp = (HASHNODE *) xmalloc (i);
9237 hp->bucket_hdr = &hashtab[bucket];
9238 hp->next = hashtab[bucket];
9239 hashtab[bucket] = hp;
9241 if (hp->next != NULL)
9242 hp->next->prev = hp;
9245 hp->value.cpval = value;
9246 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9249 for (i = 0; i < len; i++)
9256 * find the most recent hash node for name name (ending with first
9257 * non-identifier char) installed by install
9259 * If LEN is >= 0, it is the length of the name.
9260 * Otherwise, compute the length by scanning the entire name.
9262 * If HASH is >= 0, it is the precomputed hash code.
9263 * Otherwise, compute the hash code.
9266 lookup (name, len, hash)
9271 register U_CHAR *bp;
9272 register HASHNODE *bucket;
9275 for (bp = name; is_idchar[*bp]; bp++) ;
9280 hash = hashf (name, len, HASHSIZE);
9282 bucket = hashtab[hash];
9284 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9286 bucket = bucket->next;
9292 * Delete a hash node. Some weirdness to free junk from macros.
9293 * More such weirdness will have to be added if you define more hash
9294 * types that need it.
9297 /* Note that the DEFINITION of a macro is removed from the hash table
9298 but its storage is not freed. This would be a storage leak
9299 except that it is not reasonable to keep undefining and redefining
9300 large numbers of macros many times.
9301 In any case, this is necessary, because a macro can be #undef'd
9302 in the middle of reading the arguments to a call to it.
9303 If #undef freed the DEFINITION, that would crash. */
9310 if (hp->prev != NULL)
9311 hp->prev->next = hp->next;
9312 if (hp->next != NULL)
9313 hp->next->prev = hp->prev;
9315 /* make sure that the bucket chain header that
9316 the deleted guy was on points to the right thing afterwards. */
9317 if (hp == *hp->bucket_hdr)
9318 *hp->bucket_hdr = hp->next;
9321 if (hp->type == T_MACRO) {
9322 DEFINITION *d = hp->value.defn;
9323 struct reflist *ap, *nextap;
9325 for (ap = d->pattern; ap != NULL; ap = nextap) {
9336 * return hash function on name. must be compatible with the one
9337 * computed a step at a time, elsewhere
9340 hashf (name, len, hashsize)
9341 register U_CHAR *name;
9348 r = HASHSTEP (r, *name++);
9350 return MAKE_POS (r) % hashsize;
9354 /* Dump the definition of a single macro HP to OF. */
9356 dump_single_macro (hp, of)
9357 register HASHNODE *hp;
9360 register DEFINITION *defn = hp->value.defn;
9366 /* Print the definition of the macro HP. */
9368 fprintf (of, "#define %s", hp->name);
9370 if (defn->nargs >= 0) {
9374 for (i = 0; i < defn->nargs; i++) {
9375 dump_arg_n (defn, i, of);
9376 if (i + 1 < defn->nargs)
9386 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9387 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9388 offset += ap->nchars;
9390 if (ap->nchars != 0)
9392 if (ap->stringify) {
9393 switch (ap->stringify) {
9394 case SHARP_TOKEN: fprintf (of, "#"); break;
9395 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9396 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9397 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9401 if (ap->raw_before != 0) {
9403 switch (ap->raw_before) {
9404 case WHITE_SHARP_TOKEN:
9405 case WHITE_PERCENT_COLON_TOKEN:
9412 switch (ap->raw_before) {
9413 case SHARP_TOKEN: fprintf (of, "##"); break;
9414 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9415 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9416 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9423 dump_arg_n (defn, ap->argno, of);
9424 if (!traditional && ap->raw_after != 0) {
9425 switch (ap->raw_after) {
9426 case SHARP_TOKEN: fprintf (of, "##"); break;
9427 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9428 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9429 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9435 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9439 /* Dump all macro definitions as #defines to stdout. */
9446 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9447 register HASHNODE *hp;
9449 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9450 if (hp->type == T_MACRO)
9451 dump_single_macro (hp, stdout);
9456 /* Output to OF a substring of a macro definition.
9457 BASE is the beginning of the definition.
9458 Output characters START thru LENGTH.
9459 Unless traditional, discard newlines outside of strings, thus
9460 converting funny-space markers to ordinary spaces. */
9463 dump_defn_1 (base, start, length, of)
9469 U_CHAR *p = base + start;
9470 U_CHAR *limit = base + start + length;
9473 fwrite (p, sizeof (*p), length, of);
9476 if (*p == '\"' || *p =='\'') {
9477 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9478 NULL_PTR, NULL_PTR);
9479 fwrite (p, sizeof (*p), p1 - p, of);
9490 /* Print the name of argument number ARGNUM of macro definition DEFN
9492 Recall that DEFN->args.argnames contains all the arg names
9493 concatenated in reverse order with comma-space in between. */
9496 dump_arg_n (defn, argnum, of)
9501 register U_CHAR *p = defn->args.argnames;
9502 while (argnum + 1 < defn->nargs) {
9503 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9507 while (*p && *p != ',') {
9513 /* Initialize syntactic classifications of characters. */
9516 initialize_char_syntax ()
9521 * Set up is_idchar and is_idstart tables. These should be
9522 * faster than saying (is_alpha (c) || c == '_'), etc.
9523 * Set up these things before calling any routines tthat
9526 for (i = 'a'; i <= 'z'; i++) {
9527 is_idchar[i - 'a' + 'A'] = 1;
9529 is_idstart[i - 'a' + 'A'] = 1;
9532 for (i = '0'; i <= '9'; i++)
9535 is_idstart['_'] = 1;
9536 is_idchar['$'] = dollars_in_ident;
9537 is_idstart['$'] = dollars_in_ident;
9539 /* horizontal space table */
9540 is_hor_space[' '] = 1;
9541 is_hor_space['\t'] = 1;
9542 is_hor_space['\v'] = 1;
9543 is_hor_space['\f'] = 1;
9544 is_hor_space['\r'] = 1;
9553 char_name['\v'] = "vertical tab";
9554 char_name['\f'] = "formfeed";
9555 char_name['\r'] = "carriage return";
9558 /* Initialize the built-in macros. */
9561 initialize_builtins (inp, outp)
9565 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9566 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9567 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9568 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9569 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9570 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9571 #ifndef NO_BUILTIN_SIZE_TYPE
9572 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9574 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9575 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9577 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9578 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9580 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9582 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9584 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9585 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9588 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9589 /* This is supplied using a -D by the compiler driver
9590 so that it is present only when truly compiling with GNU C. */
9591 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9595 char directive[2048];
9596 U_CHAR *udirective = (U_CHAR *) directive;
9597 register struct directive *dp = &directive_table[0];
9598 struct tm *timebuf = timestamp ();
9600 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9601 instack[0].nominal_fname);
9602 output_line_directive (inp, outp, 0, same_file);
9603 pass_thru_directive (udirective, &udirective[strlen (directive)],
9606 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9607 output_line_directive (inp, outp, 0, same_file);
9608 pass_thru_directive (udirective, &udirective[strlen (directive)],
9611 #ifndef NO_BUILTIN_SIZE_TYPE
9612 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9613 output_line_directive (inp, outp, 0, same_file);
9614 pass_thru_directive (udirective, &udirective[strlen (directive)],
9618 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9619 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9620 output_line_directive (inp, outp, 0, same_file);
9621 pass_thru_directive (udirective, &udirective[strlen (directive)],
9625 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9626 output_line_directive (inp, outp, 0, same_file);
9627 pass_thru_directive (udirective, &udirective[strlen (directive)],
9630 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9631 monthnames[timebuf->tm_mon],
9632 timebuf->tm_mday, timebuf->tm_year + 1900);
9633 output_line_directive (inp, outp, 0, same_file);
9634 pass_thru_directive (udirective, &udirective[strlen (directive)],
9637 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9638 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9639 output_line_directive (inp, outp, 0, same_file);
9640 pass_thru_directive (udirective, &udirective[strlen (directive)],
9645 sprintf (directive, " __STDC__ 1");
9646 output_line_directive (inp, outp, 0, same_file);
9647 pass_thru_directive (udirective, &udirective[strlen (directive)],
9652 sprintf (directive, " __OBJC__ 1");
9653 output_line_directive (inp, outp, 0, same_file);
9654 pass_thru_directive (udirective, &udirective[strlen (directive)],
9661 * process a given definition string, for initialization
9662 * If STR is just an identifier, define it with value 1.
9663 * If STR has anything after the identifier, then it should
9664 * be identifier=definition.
9668 make_definition (str, op)
9673 struct directive *kt;
9676 p = buf = (U_CHAR *) str;
9677 if (!is_idstart[*p]) {
9678 error ("malformed option `-D %s'", str);
9681 while (is_idchar[*++p])
9684 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9687 p = (U_CHAR *) str; /* Error */
9690 buf = (U_CHAR *) alloca (p - buf + 4);
9691 strcpy ((char *)buf, str);
9692 strcat ((char *)buf, " 1");
9693 } else if (*p != '=') {
9694 error ("malformed option `-D %s'", str);
9698 /* Copy the entire option so we can modify it. */
9699 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9700 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9701 /* Change the = to a space. */
9702 buf[p - (U_CHAR *) str] = ' ';
9703 /* Scan for any backslash-newline and remove it. */
9705 q = &buf[p - (U_CHAR *) str];
9707 if (*p == '\"' || *p == '\'') {
9708 int unterminated = 0;
9709 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9710 NULL_PTR, NULL_PTR, &unterminated);
9714 if (*p == '\\' && p[1] == '\n')
9718 } else if (*p == '\\' && p[1] == '\n')
9720 /* Change newline chars into newline-markers. */
9721 else if (*p == '\n')
9733 ip = &instack[++indepth];
9734 ip->nominal_fname = ip->fname = "*Initialization*";
9736 ip->buf = ip->bufp = buf;
9737 ip->length = strlen ((char *) buf);
9741 ip->if_stack = if_stack;
9742 ip->system_header_p = 0;
9744 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9747 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9748 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9752 /* JF, this does the work for the -U option */
9755 make_undef (str, op)
9760 struct directive *kt;
9762 ip = &instack[++indepth];
9763 ip->nominal_fname = ip->fname = "*undef*";
9765 ip->buf = ip->bufp = (U_CHAR *) str;
9766 ip->length = strlen (str);
9770 ip->if_stack = if_stack;
9771 ip->system_header_p = 0;
9773 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9776 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9780 /* Process the string STR as if it appeared as the body of a #assert.
9781 OPTION is the option name for which STR was the argument. */
9784 make_assertion (option, str)
9789 struct directive *kt;
9790 U_CHAR *buf, *p, *q;
9792 /* Copy the entire option so we can modify it. */
9793 buf = (U_CHAR *) alloca (strlen (str) + 1);
9794 strcpy ((char *) buf, str);
9795 /* Scan for any backslash-newline and remove it. */
9798 if (*p == '\\' && p[1] == '\n')
9806 if (!is_idstart[*p]) {
9807 error ("malformed option `%s %s'", option, str);
9810 while (is_idchar[*++p])
9812 SKIP_WHITE_SPACE (p);
9813 if (! (*p == 0 || *p == '(')) {
9814 error ("malformed option `%s %s'", option, str);
9818 ip = &instack[++indepth];
9819 ip->nominal_fname = ip->fname = "*Initialization*";
9821 ip->buf = ip->bufp = buf;
9822 ip->length = strlen ((char *) buf);
9826 ip->if_stack = if_stack;
9827 ip->system_header_p = 0;
9829 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9832 /* pass NULL as output ptr to do_define since we KNOW it never
9833 does any output.... */
9834 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9838 /* Append a chain of `struct file_name_list's
9839 to the end of the main include chain.
9840 FIRST is the beginning of the chain to append, and LAST is the end. */
9843 append_include_chain (first, last)
9844 struct file_name_list *first, *last;
9846 struct file_name_list *dir;
9848 if (!first || !last)
9854 last_include->next = first;
9856 if (first_bracket_include == 0)
9857 first_bracket_include = first;
9859 for (dir = first; ; dir = dir->next) {
9860 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9861 if (len > max_include_len)
9862 max_include_len = len;
9868 last_include = last;
9871 /* Add output to `deps_buffer' for the -M switch.
9872 STRING points to the text to be output.
9873 SPACER is ':' for targets, ' ' for dependencies. */
9876 deps_output (string, spacer)
9880 int size = strlen (string);
9885 #ifndef MAX_OUTPUT_COLUMNS
9886 #define MAX_OUTPUT_COLUMNS 72
9888 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9889 && 1 < deps_column) {
9890 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9897 if (deps_size + size + 8 > deps_allocated_size) {
9898 deps_allocated_size = (deps_size + size + 50) * 2;
9899 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9901 if (spacer == ' ') {
9902 deps_buffer[deps_size++] = ' ';
9905 bcopy (string, &deps_buffer[deps_size], size);
9907 deps_column += size;
9908 if (spacer == ':') {
9909 deps_buffer[deps_size++] = ':';
9912 deps_buffer[deps_size] = 0;
9916 fatal (PRINTF_ALIST (msg))
9921 fprintf (stderr, "%s: ", progname);
9922 VA_START (args, msg);
9923 vfprintf (stderr, msg, args);
9925 fprintf (stderr, "\n");
9926 exit (FAILURE_EXIT_CODE);
9929 /* More 'friendly' abort that prints the line and file.
9930 config.h can #define abort fancy_abort if you like that sort of thing. */
9935 fatal ("Internal gcc abort.");
9939 perror_with_name (name)
9942 fprintf (stderr, "%s: ", progname);
9943 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9948 pfatal_with_name (name)
9951 perror_with_name (name);
9955 exit (FAILURE_EXIT_CODE);
9959 /* Handler for SIGPIPE. */
9963 /* If this is missing, some compilers complain. */
9966 fatal ("output pipe has been closed");
9972 fatal ("Memory exhausted.");
9980 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
9987 xrealloc (old, size)
9991 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
9998 xcalloc (number, size)
9999 size_t number, size;
10001 register size_t total = number * size;
10002 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10005 bzero (ptr, total);
10013 size_t size = strlen (input);
10014 char *output = xmalloc (size + 1);
10015 strcpy (output, input);
10019 /* Get the file-mode and data size of the file open on FD
10020 and store them in *MODE_POINTER and *SIZE_POINTER. */
10023 file_size_and_mode (fd, mode_pointer, size_pointer)
10026 long int *size_pointer;
10030 if (fstat (fd, &sbuf) < 0) return (-1);
10031 if (mode_pointer) *mode_pointer = sbuf.st_mode;
10032 if (size_pointer) *size_pointer = sbuf.st_size;
10037 output_dots (fd, depth)
10041 while (depth > 0) {
10050 /* Under VMS we need to fix up the "include" specification
10051 filename so that everything following the 1st slash is
10052 changed into its correct VMS file specification. */
10055 hack_vms_include_specification (fname)
10058 register char *cp, *cp1, *cp2;
10059 int f, check_filename_before_returning, no_prefix_seen;
10062 check_filename_before_returning = 0;
10063 no_prefix_seen = 0;
10065 /* Ignore leading "./"s */
10066 while (fname[0] == '.' && fname[1] == '/') {
10067 strcpy (fname, fname+2);
10068 no_prefix_seen = 1; /* mark this for later */
10070 /* Look for the boundary between the VMS and UNIX filespecs */
10071 cp = rindex (fname, ']'); /* Look for end of dirspec. */
10072 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
10073 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
10077 cp = index (fname, '/'); /* Look for the "/" */
10081 * Check if we have a vax-c style '#include filename'
10082 * and add the missing .h
10085 if (index(fname,'.') == 0)
10086 strcat(fname, ".h");
10088 if (index(cp,'.') == 0)
10092 cp2 = Local; /* initialize */
10094 /* We are trying to do a number of things here. First of all, we are
10095 trying to hammer the filenames into a standard format, such that later
10096 processing can handle them.
10098 If the file name contains something like [dir.], then it recognizes this
10099 as a root, and strips the ".]". Later processing will add whatever is
10100 needed to get things working properly.
10102 If no device is specified, then the first directory name is taken to be
10103 a device name (or a rooted logical). */
10105 /* See if we found that 1st slash */
10106 if (cp == 0) return; /* Nothing to do!!! */
10107 if (*cp != '/') return; /* Nothing to do!!! */
10108 /* Point to the UNIX filename part (which needs to be fixed!) */
10110 /* If the directory spec is not rooted, we can just copy
10111 the UNIX filename part and we are done */
10112 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10113 if (cp[-2] != '.') {
10115 * The VMS part ends in a `]', and the preceding character is not a `.'.
10116 * We strip the `]', and then splice the two parts of the name in the
10117 * usual way. Given the default locations for include files in cccp.c,
10118 * we will only use this code if the user specifies alternate locations
10119 * with the /include (-I) switch on the command line. */
10120 cp -= 1; /* Strip "]" */
10121 cp1--; /* backspace */
10124 * The VMS part has a ".]" at the end, and this will not do. Later
10125 * processing will add a second directory spec, and this would be a syntax
10126 * error. Thus we strip the ".]", and thus merge the directory specs.
10127 * We also backspace cp1, so that it points to a '/'. This inhibits the
10128 * generation of the 000000 root directory spec (which does not belong here
10131 cp -= 2; /* Strip ".]" */
10132 cp1--; }; /* backspace */
10135 /* We drop in here if there is no VMS style directory specification yet.
10136 * If there is no device specification either, we make the first dir a
10137 * device and try that. If we do not do this, then we will be essentially
10138 * searching the users default directory (as if they did a #include "asdf.h").
10140 * Then all we need to do is to push a '[' into the output string. Later
10141 * processing will fill this in, and close the bracket.
10143 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10144 *cp2++ = '['; /* Open the directory specification */
10147 /* at this point we assume that we have the device spec, and (at least
10148 the opening "[" for a directory specification. We may have directories
10149 specified already */
10151 /* If there are no other slashes then the filename will be
10152 in the "root" directory. Otherwise, we need to add
10153 directory specifications. */
10154 if (index (cp1, '/') == 0) {
10155 /* Just add "000000]" as the directory string */
10156 strcpy (cp2, "000000]");
10157 cp2 += strlen (cp2);
10158 check_filename_before_returning = 1; /* we might need to fool with this later */
10160 /* As long as there are still subdirectories to add, do them. */
10161 while (index (cp1, '/') != 0) {
10162 /* If this token is "." we can ignore it */
10163 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10167 /* Add a subdirectory spec. Do not duplicate "." */
10168 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10170 /* If this is ".." then the spec becomes "-" */
10171 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10172 /* Add "-" and skip the ".." */
10177 /* Copy the subdirectory */
10178 while (*cp1 != '/') *cp2++= *cp1++;
10179 cp1++; /* Skip the "/" */
10181 /* Close the directory specification */
10182 if (cp2[-1] == '.') /* no trailing periods */
10186 /* Now add the filename */
10187 while (*cp1) *cp2++ = *cp1++;
10189 /* Now append it to the original VMS spec. */
10190 strcpy (cp, Local);
10192 /* If we put a [000000] in the filename, try to open it first. If this fails,
10193 remove the [000000], and return that name. This provides flexibility
10194 to the user in that they can use both rooted and non-rooted logical names
10195 to point to the location of the file. */
10197 if (check_filename_before_returning && no_prefix_seen) {
10198 f = open (fname, O_RDONLY, 0666);
10200 /* The file name is OK as it is, so return it as is. */
10204 /* The filename did not work. Try to remove the [000000] from the name,
10206 cp = index (fname, '[');
10207 cp2 = index (fname, ']') + 1;
10208 strcpy (cp, cp2); /* this gets rid of it */
10216 /* These are the read/write replacement routines for
10217 VAX-11 "C". They make read/write behave enough
10218 like their UNIX counterparts that CCCP will work */
10221 read (fd, buf, size)
10226 #undef read /* Get back the REAL read routine */
10228 register int total = 0;
10230 /* Read until the buffer is exhausted */
10232 /* Limit each read to 32KB */
10233 i = (size > (32*1024)) ? (32*1024) : size;
10234 i = read (fd, buf, i);
10236 if (i == 0) return (total);
10239 /* Account for this read */
10248 write (fd, buf, size)
10253 #undef write /* Get back the REAL write routine */
10257 /* Limit individual writes to 32Kb */
10260 j = (i > (32*1024)) ? (32*1024) : i;
10261 if (write (fd, buf, j) < 0) return (-1);
10262 /* Account for the data written */
10269 /* The following wrapper functions supply additional arguments to the VMS
10270 I/O routines to optimize performance with file handling. The arguments
10272 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10273 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10274 "fop=tef"- Truncate unused portions of file when closing file.
10275 "shr=nil"- Disallow file sharing while file is open.
10279 freopen (fname, type, oldfile)
10284 #undef freopen /* Get back the REAL fopen routine */
10285 if (strcmp (type, "w") == 0)
10286 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10287 return freopen (fname, type, oldfile, "mbc=16");
10291 fopen (fname, type)
10295 #undef fopen /* Get back the REAL fopen routine */
10296 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10297 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10298 pre-ANSI implmentation. This hack circumvents the mismatch problem. */
10299 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10302 return (*vmslib_fopen) (fname, type, "mbc=32",
10303 "deq=64", "fop=tef", "shr=nil");
10305 return (*vmslib_fopen) (fname, type, "mbc=32");
10309 open (fname, flags, prot)
10314 #undef open /* Get back the REAL open routine */
10315 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10318 /* Avoid run-time library bug, where copying M out of N+M characters with
10319 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
10320 gcc-cpp exercises this particular bug. [Fixed in V5.5-2's VAXCRTL.] */
10323 strncat (dst, src, cnt)
10328 register char *d = dst, *s = (char *) src;
10329 register int n = cnt; /* convert to _signed_ type */
10331 while (*d) d++; /* advance to end */
10333 if (!(*d++ = *s++)) break;
10334 if (n < 0) *d = '\0';
10338 /* more VMS hackery */
10342 extern unsigned long sys$parse(), sys$search();
10344 /* Work around another library bug. If a file is located via a searchlist,
10345 and if the device it's on is not the same device as the one specified
10346 in the first element of that searchlist, then both stat() and fstat()
10347 will fail to return info about it. `errno' will be set to EVMSERR, and
10348 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10349 We can get around this by fully parsing the filename and then passing
10350 that absolute name to stat().
10352 Without this fix, we can end up failing to find header files, which is
10353 bad enough, but then compounding the problem by reporting the reason for
10354 failure as "normal successful completion." */
10356 #undef fstat /* get back to library version */
10359 VMS_fstat (fd, statbuf)
10361 struct stat *statbuf;
10363 int result = fstat (fd, statbuf);
10368 char nambuf[NAM$C_MAXRSS+1];
10370 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10371 result = VMS_stat (nambuf, statbuf);
10372 /* No fclose(fp) here; that would close(fd) as well. */
10379 VMS_stat (name, statbuf)
10381 struct stat *statbuf;
10383 int result = stat (name, statbuf);
10389 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10390 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10393 fab.fab$l_fna = (char *) name;
10394 fab.fab$b_fns = (unsigned char) strlen (name);
10395 fab.fab$l_nam = (void *) &nam;
10397 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10398 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10399 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10400 if (sys$parse (&fab) & 1)
10402 if (sys$search (&fab) & 1)
10404 res_nam[nam.nam$b_rsl] = '\0';
10405 result = stat (res_nam, statbuf);
10407 /* Clean up searchlist context cached by the system. */
10408 nam.nam$b_nop = NAM$M_SYNCHK;
10409 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10410 (void) sys$parse (&fab);