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 #define stat(name,stbuf) VMS_stat (name,stbuf)
244 static int VMS_fstat (), VMS_stat ();
245 static char * VMS_strncat ();
246 static int VMS_read ();
247 static int VMS_write ();
248 static int VMS_open ();
249 static FILE * VMS_fopen ();
250 static FILE * VMS_freopen ();
251 static void hack_vms_include_specification ();
252 typedef struct { unsigned :16, :16, :16; } vms_ino_t;
253 #define ino_t vms_ino_t
254 #define INCLUDE_LEN_FUDGE 10 /* leave room for VMS syntax conversion */
256 #define BSTRING /* VMS/GCC supplies the bstring routines */
257 #endif /* __GNUC__ */
266 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
267 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
269 /* Find the largest host integer type and set its size and type. */
271 #ifndef HOST_BITS_PER_WIDE_INT
273 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
274 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
275 #define HOST_WIDE_INT long
277 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
278 #define HOST_WIDE_INT int
284 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
288 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
291 /* Define a generic NULL if one hasn't already been defined. */
298 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
299 #define GENERIC_PTR void *
301 #define GENERIC_PTR char *
306 #define NULL_PTR ((GENERIC_PTR)0)
309 #ifndef INCLUDE_LEN_FUDGE
310 #define INCLUDE_LEN_FUDGE 0
313 /* External declarations. */
315 extern char *version_string;
317 #ifndef HAVE_STRERROR
320 extern const char *const sys_errlist[];
322 extern char *sys_errlist[];
324 #else /* HAVE_STERRROR */
328 char *strerror (int,...);
330 int parse_escape PROTO((char **));
331 HOST_WIDE_INT parse_c_expression PROTO((char *));
337 #ifndef FAILURE_EXIT_CODE
338 #define FAILURE_EXIT_CODE 33 /* gnu cc command understands this */
341 #ifndef SUCCESS_EXIT_CODE
342 #define SUCCESS_EXIT_CODE 0 /* 0 means success on Unix. */
345 /* Name under which this program was invoked. */
347 static char *progname;
349 /* Nonzero means use extra default include directories for C++. */
351 static int cplusplus;
353 /* Nonzero means handle cplusplus style comments */
355 static int cplusplus_comments;
357 /* Nonzero means handle #import, for objective C. */
361 /* Nonzero means this is an assembly file, and allow
362 unknown directives, which could be comments. */
366 /* Current maximum length of directory names in the search path
367 for include files. (Altered as we get more of them.) */
369 static int max_include_len;
371 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
373 static int for_lint = 0;
375 /* Nonzero means copy comments into the output file. */
377 static int put_out_comments = 0;
379 /* Nonzero means don't process the ANSI trigraph sequences. */
381 static int no_trigraphs = 0;
383 /* Nonzero means print the names of included files rather than
384 the preprocessed output. 1 means just the #include "...",
385 2 means #include <...> as well. */
387 static int print_deps = 0;
389 /* Nonzero if missing .h files in -M output are assumed to be generated
390 files and not errors. */
392 static int print_deps_missing_files = 0;
394 /* Nonzero means print names of header files (-H). */
396 static int print_include_names = 0;
398 /* Nonzero means don't output line number information. */
400 static int no_line_directives;
402 /* Nonzero means output the text in failing conditionals,
403 inside #failed ... #endfailed. */
405 static int output_conditionals;
407 /* dump_only means inhibit output of the preprocessed text
408 and instead output the definitions of all user-defined
409 macros in a form suitable for use as input to cccp.
410 dump_names means pass #define and the macro name through to output.
411 dump_definitions means pass the whole definition (plus #define) through
414 static enum {dump_none, dump_only, dump_names, dump_definitions}
415 dump_macros = dump_none;
417 /* Nonzero means pass all #define and #undef directives which we actually
418 process through to the output stream. This feature is used primarily
419 to allow cc1 to record the #defines and #undefs for the sake of
420 debuggers which understand about preprocessor macros, but it may
421 also be useful with -E to figure out how symbols are defined, and
422 where they are defined. */
423 static int debug_output = 0;
425 /* Nonzero indicates special processing used by the pcp program. The
426 special effects of this mode are:
428 Inhibit all macro expansion, except those inside #if directives.
430 Process #define directives normally, and output their contents
433 Output preconditions to pcp_outfile indicating all the relevant
434 preconditions for use of this file in a later cpp run.
436 static FILE *pcp_outfile;
438 /* Nonzero means we are inside an IF during a -pcp run. In this mode
439 macro expansion is done, and preconditions are output for all macro
440 uses requiring them. */
441 static int pcp_inside_if;
443 /* Nonzero means never to include precompiled files.
444 This is 1 since there's no way now to make precompiled files,
445 so it's not worth testing for them. */
446 static int no_precomp = 1;
448 /* Nonzero means give all the error messages the ANSI standard requires. */
452 /* Nonzero means try to make failure to fit ANSI C an error. */
454 static int pedantic_errors;
456 /* Nonzero means don't print warning messages. -w. */
458 static int inhibit_warnings = 0;
460 /* Nonzero means warn if slash-star appears in a comment. */
462 static int warn_comments;
464 /* Nonzero means warn if a macro argument is (or would be)
465 stringified with -traditional. */
467 static int warn_stringify;
469 /* Nonzero means warn if there are any trigraphs. */
471 static int warn_trigraphs;
473 /* Nonzero means warn if #import is used. */
475 static int warn_import = 1;
477 /* Nonzero means turn warnings into errors. */
479 static int warnings_are_errors;
481 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
485 /* Nonzero causes output not to be done,
486 but directives such as #define that have side effects
489 static int no_output;
491 /* Nonzero means this file was included with a -imacros or -include
492 command line and should not be recorded as an include file. */
494 static int no_record_file;
496 /* Nonzero means that we have finished processing the command line options.
497 This flag is used to decide whether or not to issue certain errors
500 static int done_initializing = 0;
502 /* Line where a newline was first seen in a string constant. */
504 static int multiline_string_line = 0;
506 /* I/O buffer structure.
507 The `fname' field is nonzero for source files and #include files
508 and for the dummy text used for -D and -U.
509 It is zero for rescanning results of macro expansion
510 and for expanding macro arguments. */
511 #define INPUT_STACK_MAX 400
512 static struct file_buf {
514 /* Filename specified with #line directive. */
516 /* Record where in the search path this file was found.
517 For #include_next. */
518 struct file_name_list *dir;
523 /* Macro that this level is the expansion of.
524 Included so that we can reenable the macro
525 at the end of this level. */
526 struct hashnode *macro;
527 /* Value of if_stack at start of this file.
528 Used to prohibit unmatched #endif (etc) in an include file. */
529 struct if_stack *if_stack;
530 /* Object to be freed at end of input at this level. */
532 /* True if this is a header file included using <FILENAME>. */
533 char system_header_p;
534 } instack[INPUT_STACK_MAX];
536 static int last_error_tick; /* Incremented each time we print it. */
537 static int input_file_stack_tick; /* Incremented when the status changes. */
539 /* Current nesting level of input sources.
540 `instack[indepth]' is the level currently being read. */
541 static int indepth = -1;
542 #define CHECK_DEPTH(code) \
543 if (indepth >= (INPUT_STACK_MAX - 1)) \
545 error_with_line (line_for_error (instack[indepth].lineno), \
546 "macro or `#include' recursion too deep"); \
550 /* Current depth in #include directives that use <...>. */
551 static int system_include_depth = 0;
553 typedef struct file_buf FILE_BUF;
555 /* The output buffer. Its LENGTH field is the amount of room allocated
556 for the buffer, not the number of chars actually present. To get
557 that, subtract outbuf.buf from outbuf.bufp. */
559 #define OUTBUF_SIZE 10 /* initial size of output buffer */
560 static FILE_BUF outbuf;
562 /* Grow output buffer OBUF points at
563 so it can hold at least NEEDED more chars. */
565 #define check_expand(OBUF, NEEDED) \
566 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
567 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
569 struct file_name_list
571 struct file_name_list *next;
573 /* If the following is nonzero, it is a macro name.
574 Don't include the file again if that macro is defined. */
575 U_CHAR *control_macro;
576 /* If the following is nonzero, it is a C-language system include
578 int c_system_include_path;
579 /* Mapping of file names for this directory. */
580 struct file_name_map *name_map;
581 /* Non-zero if name_map is valid. */
585 /* #include "file" looks in source file dir, then stack. */
586 /* #include <file> just looks in the stack. */
587 /* -I directories are added to the end, then the defaults are added. */
589 static struct default_include {
590 char *fname; /* The name of the directory. */
591 int cplusplus; /* Only look here if we're compiling C++. */
592 int cxx_aware; /* Includes in this directory don't need to
593 be wrapped in extern "C" when compiling
595 } include_defaults_array[]
596 #ifdef INCLUDE_DEFAULTS
600 /* Pick up GNU C++ specific include files. */
601 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
603 /* This is the dir for fixincludes. Put it just before
604 the files that we fix. */
605 { GCC_INCLUDE_DIR, 0, 0 },
606 /* For cross-compilation, this dir name is generated
607 automatically in Makefile.in. */
608 { CROSS_INCLUDE_DIR, 0, 0 },
609 /* This is another place that the target system's headers might be. */
610 { TOOL_INCLUDE_DIR, 0, 0 },
611 #else /* not CROSS_COMPILE */
612 /* This should be /usr/local/include and should come before
613 the fixincludes-fixed header files. */
614 { LOCAL_INCLUDE_DIR, 0, 1 },
615 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
616 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
617 { TOOL_INCLUDE_DIR, 0, 0 },
618 /* This is the dir for fixincludes. Put it just before
619 the files that we fix. */
620 { GCC_INCLUDE_DIR, 0, 0 },
621 /* Some systems have an extra dir of include files. */
622 #ifdef SYSTEM_INCLUDE_DIR
623 { SYSTEM_INCLUDE_DIR, 0, 0 },
625 { STANDARD_INCLUDE_DIR, 0, 0 },
626 #endif /* not CROSS_COMPILE */
629 #endif /* no INCLUDE_DEFAULTS */
631 /* The code looks at the defaults through this pointer, rather than through
632 the constant structure above. This pointer gets changed if an environment
633 variable specifies other defaults. */
634 static struct default_include *include_defaults = include_defaults_array;
636 static struct file_name_list *include = 0; /* First dir to search */
637 /* First dir to search for <file> */
638 /* This is the first element to use for #include <...>.
639 If it is 0, use the entire chain for such includes. */
640 static struct file_name_list *first_bracket_include = 0;
641 /* This is the first element in the chain that corresponds to
642 a directory of system header files. */
643 static struct file_name_list *first_system_include = 0;
644 static struct file_name_list *last_include = 0; /* Last in chain */
646 /* Chain of include directories to put at the end of the other chain. */
647 static struct file_name_list *after_include = 0;
648 static struct file_name_list *last_after_include = 0; /* Last in chain */
650 /* Chain to put at the start of the system include files. */
651 static struct file_name_list *before_system = 0;
652 static struct file_name_list *last_before_system = 0; /* Last in chain */
654 /* List of included files that contained #pragma once. */
655 static struct file_name_list *dont_repeat_files = 0;
657 /* List of other included files.
658 If ->control_macro if nonzero, the file had a #ifndef
659 around the entire contents, and ->control_macro gives the macro name. */
660 static struct file_name_list *all_include_files = 0;
662 /* Directory prefix that should replace `/usr' in the standard
663 include file directories. */
664 static char *include_prefix;
666 /* Global list of strings read in from precompiled files. This list
667 is kept in the order the strings are read in, with new strings being
668 added at the end through stringlist_tailp. We use this list to output
669 the strings at the end of the run.
671 static STRINGDEF *stringlist;
672 static STRINGDEF **stringlist_tailp = &stringlist;
675 /* Structure returned by create_definition */
676 typedef struct macrodef MACRODEF;
679 struct definition *defn;
684 enum sharp_token_type {
685 NO_SHARP_TOKEN, /* token not present */
687 SHARP_TOKEN = '#', /* token spelled with # only */
688 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
690 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
691 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
694 /* Structure allocated for every #define. For a simple replacement
697 nargs = -1, the `pattern' list is null, and the expansion is just
698 the replacement text. Nargs = 0 means a functionlike macro with no args,
700 #define getchar() getc (stdin) .
701 When there are args, the expansion is the replacement text with the
702 args squashed out, and the reflist is a list describing how to
703 build the output from the input: e.g., "3 chars, then the 1st arg,
704 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
705 The chars here come from the expansion. Whatever is left of the
706 expansion after the last arg-occurrence is copied after that arg.
707 Note that the reflist can be arbitrarily long---
708 its length depends on the number of times the arguments appear in
709 the replacement text, not how many args there are. Example:
710 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
712 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
713 where (x, y) means (nchars, argno). */
715 typedef struct definition DEFINITION;
718 int length; /* length of expansion string */
719 int predefined; /* True if the macro was builtin or */
720 /* came from the command line */
722 int line; /* Line number of definition */
723 char *file; /* File of definition */
724 char rest_args; /* Nonzero if last arg. absorbs the rest */
726 struct reflist *next;
728 enum sharp_token_type stringify; /* set if a # operator before arg */
729 enum sharp_token_type raw_before; /* set if a ## operator before arg */
730 enum sharp_token_type raw_after; /* set if a ## operator after arg */
732 char rest_args; /* Nonzero if this arg. absorbs the rest */
733 int nchars; /* Number of literal chars to copy before
734 this arg occurrence. */
735 int argno; /* Number of arg to substitute (origin-0) */
738 /* Names of macro args, concatenated in reverse order
739 with comma-space between them.
740 The only use of this is that we warn on redefinition
741 if this differs between the old and new definitions. */
746 /* different kinds of things that can appear in the value field
747 of a hash node. Actually, this may be useless now. */
755 * special extension string that can be added to the last macro argument to
756 * allow it to absorb the "rest" of the arguments when expanded. Ex:
757 * #define wow(a, b...) process (b, a, b)
758 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
759 * { wow (one, two); } -> { process (two, one, two); }
760 * if this "rest_arg" is used with the concat token '##' and if it is not
761 * supplied then the token attached to with ## will not be outputted. Ex:
762 * #define wow (a, b...) process (b ## , a, ## b)
763 * { wow (1, 2); } -> { process (2, 1, 2); }
764 * { wow (one); } -> { process (one); {
766 static char rest_extension[] = "...";
767 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
769 /* The structure of a node in the hash table. The hash table
770 has entries for all tokens defined by #define directives (type T_MACRO),
771 plus some special tokens like __LINE__ (these each have their own
772 type, and the appropriate code is run when that type of node is seen.
773 It does not contain control words like "#define", which are recognized
774 by a separate piece of code. */
776 /* different flavors of hash nodes --- also used in keyword table */
778 T_DEFINE = 1, /* the `#define' keyword */
779 T_INCLUDE, /* the `#include' keyword */
780 T_INCLUDE_NEXT, /* the `#include_next' keyword */
781 T_IMPORT, /* the `#import' keyword */
782 T_IFDEF, /* the `#ifdef' keyword */
783 T_IFNDEF, /* the `#ifndef' keyword */
784 T_IF, /* the `#if' keyword */
785 T_ELSE, /* `#else' */
786 T_PRAGMA, /* `#pragma' */
787 T_ELIF, /* `#elif' */
788 T_UNDEF, /* `#undef' */
789 T_LINE, /* `#line' */
790 T_ERROR, /* `#error' */
791 T_WARNING, /* `#warning' */
792 T_ENDIF, /* `#endif' */
793 T_SCCS, /* `#sccs', used on system V. */
794 T_IDENT, /* `#ident', used on system V. */
795 T_ASSERT, /* `#assert', taken from system V. */
796 T_UNASSERT, /* `#unassert', taken from system V. */
797 T_SPECLINE, /* special symbol `__LINE__' */
798 T_DATE, /* `__DATE__' */
799 T_FILE, /* `__FILE__' */
800 T_BASE_FILE, /* `__BASE_FILE__' */
801 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
802 T_VERSION, /* `__VERSION__' */
803 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
804 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
805 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
806 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
807 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
808 T_TIME, /* `__TIME__' */
809 T_CONST, /* Constant value, used by `__STDC__' */
810 T_MACRO, /* macro defined by `#define' */
811 T_DISABLED, /* macro temporarily turned off for rescan */
812 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
813 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
814 T_UNUSED /* Used for something not defined. */
818 struct hashnode *next; /* double links for easy deletion */
819 struct hashnode *prev;
820 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
821 chain is kept, in case the node is the head
822 of the chain and gets deleted. */
823 enum node_type type; /* type of special token */
824 int length; /* length of token, for quick comparison */
825 U_CHAR *name; /* the actual name */
826 union hashval value; /* pointer to expansion, or whatever */
829 typedef struct hashnode HASHNODE;
831 /* Some definitions for the hash table. The hash function MUST be
832 computed as shown in hashf () below. That is because the rescan
833 loop computes the hash value `on the fly' for most tokens,
834 in order to avoid the overhead of a lot of procedure calls to
835 the hashf () function. Hashf () only exists for the sake of
836 politeness, for use when speed isn't so important. */
838 #define HASHSIZE 1403
839 static HASHNODE *hashtab[HASHSIZE];
840 #define HASHSTEP(old, c) ((old << 2) + c)
841 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
843 /* Symbols to predefine. */
845 #ifdef CPP_PREDEFINES
846 static char *predefs = CPP_PREDEFINES;
848 static char *predefs = "";
851 /* We let tm.h override the types used here, to handle trivial differences
852 such as the choice of unsigned int or long unsigned int for size_t.
853 When machines start needing nontrivial differences in the size type,
854 it would be best to do something here to figure out automatically
855 from other information what type to use. */
857 /* The string value for __SIZE_TYPE__. */
860 #define SIZE_TYPE "long unsigned int"
863 /* The string value for __PTRDIFF_TYPE__. */
866 #define PTRDIFF_TYPE "long int"
869 /* The string value for __WCHAR_TYPE__. */
872 #define WCHAR_TYPE "int"
874 char * wchar_type = WCHAR_TYPE;
877 /* The string value for __USER_LABEL_PREFIX__ */
879 #ifndef USER_LABEL_PREFIX
880 #define USER_LABEL_PREFIX ""
883 /* The string value for __REGISTER_PREFIX__ */
885 #ifndef REGISTER_PREFIX
886 #define REGISTER_PREFIX ""
889 /* In the definition of a #assert name, this structure forms
890 a list of the individual values asserted.
891 Each value is itself a list of "tokens".
892 These are strings that are compared by name. */
894 struct tokenlist_list {
895 struct tokenlist_list *next;
896 struct arglist *tokens;
899 struct assertion_hashnode {
900 struct assertion_hashnode *next; /* double links for easy deletion */
901 struct assertion_hashnode *prev;
902 /* also, a back pointer to this node's hash
903 chain is kept, in case the node is the head
904 of the chain and gets deleted. */
905 struct assertion_hashnode **bucket_hdr;
906 int length; /* length of token, for quick comparison */
907 U_CHAR *name; /* the actual name */
908 /* List of token-sequences. */
909 struct tokenlist_list *value;
912 typedef struct assertion_hashnode ASSERTION_HASHNODE;
914 /* Some definitions for the hash table. The hash function MUST be
915 computed as shown in hashf below. That is because the rescan
916 loop computes the hash value `on the fly' for most tokens,
917 in order to avoid the overhead of a lot of procedure calls to
918 the hashf function. hashf only exists for the sake of
919 politeness, for use when speed isn't so important. */
921 #define ASSERTION_HASHSIZE 37
922 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
924 /* Nonzero means inhibit macroexpansion of what seem to be
925 assertion tests, in rescan. For #if. */
926 static int assertions_flag;
928 /* `struct directive' defines one #-directive, including how to handle it. */
930 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
933 int length; /* Length of name */
934 int (*func) DO_PROTO; /* Function to handle directive */
935 char *name; /* Name of directive */
936 enum node_type type; /* Code which describes which directive. */
937 char angle_brackets; /* Nonzero => <...> is special. */
938 char traditional_comments; /* Nonzero: keep comments if -traditional. */
939 char pass_thru; /* Copy preprocessed directive to output file. */
942 /* These functions are declared to return int instead of void since they
943 are going to be placed in the table and some old compilers have trouble with
944 pointers to functions returning void. */
946 static int do_assert DO_PROTO;
947 static int do_define DO_PROTO;
948 static int do_elif DO_PROTO;
949 static int do_else DO_PROTO;
950 static int do_endif DO_PROTO;
951 static int do_error DO_PROTO;
952 static int do_ident DO_PROTO;
953 static int do_if DO_PROTO;
954 static int do_include DO_PROTO;
955 static int do_line DO_PROTO;
956 static int do_pragma DO_PROTO;
957 #ifdef SCCS_DIRECTIVE
958 static int do_sccs DO_PROTO;
960 static int do_unassert DO_PROTO;
961 static int do_undef DO_PROTO;
962 static int do_warning DO_PROTO;
963 static int do_xifdef DO_PROTO;
965 /* Here is the actual list of #-directives, most-often-used first. */
967 static struct directive directive_table[] = {
968 { 6, do_define, "define", T_DEFINE, 0, 1},
969 { 2, do_if, "if", T_IF},
970 { 5, do_xifdef, "ifdef", T_IFDEF},
971 { 6, do_xifdef, "ifndef", T_IFNDEF},
972 { 5, do_endif, "endif", T_ENDIF},
973 { 4, do_else, "else", T_ELSE},
974 { 4, do_elif, "elif", T_ELIF},
975 { 4, do_line, "line", T_LINE},
976 { 7, do_include, "include", T_INCLUDE, 1},
977 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
978 { 6, do_include, "import", T_IMPORT, 1},
979 { 5, do_undef, "undef", T_UNDEF},
980 { 5, do_error, "error", T_ERROR},
981 { 7, do_warning, "warning", T_WARNING},
982 #ifdef SCCS_DIRECTIVE
983 { 4, do_sccs, "sccs", T_SCCS},
985 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
986 { 5, do_ident, "ident", T_IDENT},
987 { 6, do_assert, "assert", T_ASSERT},
988 { 8, do_unassert, "unassert", T_UNASSERT},
989 { -1, 0, "", T_UNUSED},
992 /* When a directive handler is called,
993 this points to the # (or the : of the %:) that started the directive. */
994 U_CHAR *directive_start;
996 /* table to tell if char can be part of a C identifier. */
997 U_CHAR is_idchar[256];
998 /* table to tell if char can be first char of a c identifier. */
999 U_CHAR is_idstart[256];
1000 /* table to tell if c is horizontal space. */
1001 U_CHAR is_hor_space[256];
1002 /* table to tell if c is horizontal or vertical space. */
1003 static U_CHAR is_space[256];
1004 /* names of some characters */
1005 static char *char_name[256];
1007 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
1008 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
1010 static int errors = 0; /* Error counter for exit code */
1012 /* Name of output file, for error messages. */
1013 static char *out_fname;
1015 /* Zero means dollar signs are punctuation.
1016 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
1017 This must be 0 for correct processing of this ANSI C program:
1019 #define lose(b) foo (b)
1022 static int dollars_in_ident;
1023 #ifndef DOLLARS_IN_IDENTIFIERS
1024 #define DOLLARS_IN_IDENTIFIERS 1
1028 /* Stack of conditionals currently in progress
1029 (including both successful and failing conditionals). */
1032 struct if_stack *next; /* for chaining to the next stack frame */
1033 char *fname; /* copied from input when frame is made */
1034 int lineno; /* similarly */
1035 int if_succeeded; /* true if a leg of this if-group
1036 has been passed through rescan */
1037 U_CHAR *control_macro; /* For #ifndef at start of file,
1038 this is the macro name tested. */
1039 enum node_type type; /* type of last directive seen in this group */
1041 typedef struct if_stack IF_STACK_FRAME;
1042 static IF_STACK_FRAME *if_stack = NULL;
1044 /* Buffer of -M output. */
1045 static char *deps_buffer;
1047 /* Number of bytes allocated in above. */
1048 static int deps_allocated_size;
1050 /* Number of bytes used. */
1051 static int deps_size;
1053 /* Number of bytes since the last newline. */
1054 static int deps_column;
1056 /* Nonzero means -I- has been seen,
1057 so don't look for #include "foo" the source-file directory. */
1058 static int ignore_srcdir;
1060 static int safe_read PROTO((int, char *, int));
1061 static void safe_write PROTO((int, char *, int));
1063 int main PROTO((int, char **));
1065 static void path_include PROTO((char *));
1067 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
1069 static void trigraph_pcp PROTO((FILE_BUF *));
1071 static void newline_fix PROTO((U_CHAR *));
1072 static void name_newline_fix PROTO((U_CHAR *));
1074 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
1076 static void rescan PROTO((FILE_BUF *, int));
1078 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
1080 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1082 static struct tm *timestamp PROTO((void));
1083 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1085 static int redundant_include_p PROTO((char *));
1086 static is_system_include PROTO((char *));
1088 static char *read_filename_string PROTO((int, FILE *));
1089 static struct file_name_map *read_name_map PROTO((char *));
1090 static int open_include_file PROTO((char *, struct file_name_list *));
1092 static void finclude PROTO((int, char *, FILE_BUF *, int, struct file_name_list *));
1093 static void record_control_macro PROTO((char *, U_CHAR *));
1095 static int import_hash PROTO((char *));
1096 static int lookup_import PROTO((char *, struct file_name_list *));
1097 static void add_import PROTO((int, char *));
1099 static char *check_precompiled PROTO((int, char *, char **));
1100 static int check_preconditions PROTO((char *));
1101 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1102 static void pcstring_used PROTO((HASHNODE *));
1103 static void write_output PROTO((void));
1104 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1106 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1108 static int check_macro_name PROTO((U_CHAR *, char *));
1109 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1110 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1112 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1114 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1115 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1117 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1118 static void free_token_list PROTO((struct arglist *));
1120 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1121 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1122 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1124 static void do_once PROTO((void));
1126 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1127 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1128 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1129 static void validate_else PROTO((U_CHAR *));
1131 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1132 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1133 static char *quote_string PROTO((char *, char *));
1134 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1136 /* Last arg to output_line_directive. */
1137 enum file_change_code {same_file, enter_file, leave_file};
1138 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1140 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1143 static char *macarg PROTO((struct argdata *, int));
1145 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1147 static int discard_comments PROTO((U_CHAR *, int, int));
1149 static int change_newlines PROTO((U_CHAR *, int));
1151 char *my_strerror PROTO((int));
1152 void error PRINTF_PROTO_1((char *, ...));
1153 static void verror PROTO((char *, va_list));
1154 static void error_from_errno PROTO((char *));
1155 void warning PRINTF_PROTO_1((char *, ...));
1156 static void vwarning PROTO((char *, va_list));
1157 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1158 static void verror_with_line PROTO((int, char *, va_list));
1159 static void vwarning_with_line PROTO((int, char *, va_list));
1160 void pedwarn PRINTF_PROTO_1((char *, ...));
1161 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1162 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1164 static void print_containing_files PROTO((void));
1166 static int line_for_error PROTO((int));
1167 static int grow_outbuf PROTO((FILE_BUF *, int));
1169 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1170 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1171 static void delete_macro PROTO((HASHNODE *));
1172 static int hashf PROTO((U_CHAR *, int, int));
1174 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1175 static void dump_all_macros PROTO((void));
1176 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1177 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1179 static void initialize_char_syntax PROTO((void));
1180 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1182 static void make_definition PROTO((char *, FILE_BUF *));
1183 static void make_undef PROTO((char *, FILE_BUF *));
1185 static void make_assertion PROTO((char *, char *));
1187 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1189 static void deps_output PROTO((char *, int));
1191 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1192 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1193 static void perror_with_name PROTO((char *));
1194 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1195 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1197 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1198 GENERIC_PTR xmalloc PROTO((size_t));
1199 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1200 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1201 static char *savestring PROTO((char *));
1203 static int file_size_and_mode PROTO((int, int *, long int *));
1204 static void output_dots PROTO((FILE *, int));
1206 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1207 retrying if necessary. Return a negative value if an error occurs,
1208 otherwise return the actual number of bytes read,
1209 which must be LEN unless end-of-file was reached. */
1212 safe_read (desc, ptr, len)
1219 int nchars = read (desc, ptr, left);
1236 /* Write LEN bytes at PTR to descriptor DESC,
1237 retrying if necessary, and treating any real error as fatal. */
1240 safe_write (desc, ptr, len)
1246 int written = write (desc, ptr, len);
1253 pfatal_with_name (out_fname);
1271 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1272 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1273 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1274 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1275 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1277 /* Record the option used with each element of pend_assertions.
1278 This is preparation for supporting more than one option for making
1280 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1281 int inhibit_predefs = 0;
1282 int no_standard_includes = 0;
1283 int no_standard_cplusplus_includes = 0;
1284 int missing_newline = 0;
1286 /* Non-0 means don't output the preprocessed program. */
1287 int inhibit_output = 0;
1288 /* Non-0 means -v, so print the full set of include dirs. */
1291 /* File name which deps are being written to.
1292 This is 0 if deps are being written to stdout. */
1293 char *deps_file = 0;
1294 /* Fopen file mode to open deps_file with. */
1295 char *deps_mode = "a";
1296 /* Stream on which to print the dependency information. */
1297 FILE *deps_stream = 0;
1298 /* Target-name to write with the dependency information. */
1299 char *deps_target = 0;
1302 /* Get rid of any avoidable limit on stack size. */
1306 /* Set the stack limit huge so that alloca (particularly stringtab
1307 * in dbxread.c) does not fail. */
1308 getrlimit (RLIMIT_STACK, &rlim);
1309 rlim.rlim_cur = rlim.rlim_max;
1310 setrlimit (RLIMIT_STACK, &rlim);
1312 #endif /* RLIMIT_STACK defined */
1315 signal (SIGPIPE, pipe_closed);
1318 cp = argv[0] + strlen (argv[0]);
1319 while (cp != argv[0] && cp[-1] != '/'
1320 #ifdef DIR_SEPARATOR
1321 && cp[-1] != DIR_SEPARATOR
1329 /* Remove directories from PROGNAME. */
1333 if ((p = rindex (s, ':')) != 0) s = p + 1; /* skip device */
1334 if ((p = rindex (s, ']')) != 0) s = p + 1; /* skip directory */
1335 if ((p = rindex (s, '>')) != 0) s = p + 1; /* alternate (int'n'l) dir */
1336 s = progname = savestring (s);
1337 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1338 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1339 && (p[1] == 'e' || p[1] == 'E')
1340 && (p[2] == 'x' || p[2] == 'X')
1341 && (p[3] == 'e' || p[3] == 'E')
1350 /* Initialize is_idchar to allow $. */
1351 dollars_in_ident = 1;
1352 initialize_char_syntax ();
1353 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1355 no_line_directives = 0;
1357 dump_macros = dump_none;
1360 cplusplus_comments = 0;
1362 bzero ((char *) pend_files, argc * sizeof (char *));
1363 bzero ((char *) pend_defs, argc * sizeof (char *));
1364 bzero ((char *) pend_undefs, argc * sizeof (char *));
1365 bzero ((char *) pend_assertions, argc * sizeof (char *));
1366 bzero ((char *) pend_includes, argc * sizeof (char *));
1368 /* Process switches and find input file name. */
1370 for (i = 1; i < argc; i++) {
1371 if (argv[i][0] != '-') {
1372 if (out_fname != NULL)
1373 fatal ("Usage: %s [switches] input output", argv[0]);
1374 else if (in_fname != NULL)
1375 out_fname = argv[i];
1379 switch (argv[i][1]) {
1382 if (!strcmp (argv[i], "-include")) {
1384 fatal ("Filename missing after `-include' option");
1386 pend_includes[i] = argv[i+1], i++;
1388 if (!strcmp (argv[i], "-imacros")) {
1390 fatal ("Filename missing after `-imacros' option");
1392 pend_files[i] = argv[i+1], i++;
1394 if (!strcmp (argv[i], "-iprefix")) {
1396 fatal ("Filename missing after `-iprefix' option");
1398 include_prefix = argv[++i];
1400 if (!strcmp (argv[i], "-ifoutput")) {
1401 output_conditionals = 1;
1403 if (!strcmp (argv[i], "-isystem")) {
1404 struct file_name_list *dirtmp;
1407 fatal ("Filename missing after `-isystem' option");
1409 dirtmp = (struct file_name_list *)
1410 xmalloc (sizeof (struct file_name_list));
1412 dirtmp->control_macro = 0;
1413 dirtmp->c_system_include_path = 1;
1414 dirtmp->fname = xmalloc (strlen (argv[i+1]) + 1);
1415 strcpy (dirtmp->fname, argv[++i]);
1416 dirtmp->got_name_map = 0;
1418 if (before_system == 0)
1419 before_system = dirtmp;
1421 last_before_system->next = dirtmp;
1422 last_before_system = dirtmp; /* Tail follows the last one */
1424 /* Add directory to end of path for includes,
1425 with the default prefix at the front of its name. */
1426 if (!strcmp (argv[i], "-iwithprefix")) {
1427 struct file_name_list *dirtmp;
1430 if (include_prefix != 0)
1431 prefix = include_prefix;
1433 prefix = savestring (GCC_INCLUDE_DIR);
1434 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1435 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1436 prefix[strlen (prefix) - 7] = 0;
1439 dirtmp = (struct file_name_list *)
1440 xmalloc (sizeof (struct file_name_list));
1441 dirtmp->next = 0; /* New one goes on the end */
1442 dirtmp->control_macro = 0;
1443 dirtmp->c_system_include_path = 0;
1445 fatal ("Directory name missing after `-iwithprefix' option");
1447 dirtmp->fname = xmalloc (strlen (argv[i+1]) + strlen (prefix) + 1);
1448 strcpy (dirtmp->fname, prefix);
1449 strcat (dirtmp->fname, argv[++i]);
1450 dirtmp->got_name_map = 0;
1452 if (after_include == 0)
1453 after_include = dirtmp;
1455 last_after_include->next = dirtmp;
1456 last_after_include = dirtmp; /* Tail follows the last one */
1458 /* Add directory to main path for includes,
1459 with the default prefix at the front of its name. */
1460 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1461 struct file_name_list *dirtmp;
1464 if (include_prefix != 0)
1465 prefix = include_prefix;
1467 prefix = savestring (GCC_INCLUDE_DIR);
1468 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1469 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1470 prefix[strlen (prefix) - 7] = 0;
1473 dirtmp = (struct file_name_list *)
1474 xmalloc (sizeof (struct file_name_list));
1475 dirtmp->next = 0; /* New one goes on the end */
1476 dirtmp->control_macro = 0;
1477 dirtmp->c_system_include_path = 0;
1479 fatal ("Directory name missing after `-iwithprefixbefore' option");
1481 dirtmp->fname = xmalloc (strlen (argv[i+1]) + strlen (prefix) + 1);
1482 strcpy (dirtmp->fname, prefix);
1483 strcat (dirtmp->fname, argv[++i]);
1484 dirtmp->got_name_map = 0;
1486 append_include_chain (dirtmp, dirtmp);
1488 /* Add directory to end of path for includes. */
1489 if (!strcmp (argv[i], "-idirafter")) {
1490 struct file_name_list *dirtmp;
1492 dirtmp = (struct file_name_list *)
1493 xmalloc (sizeof (struct file_name_list));
1494 dirtmp->next = 0; /* New one goes on the end */
1495 dirtmp->control_macro = 0;
1496 dirtmp->c_system_include_path = 0;
1498 fatal ("Directory name missing after `-idirafter' option");
1500 dirtmp->fname = argv[++i];
1501 dirtmp->got_name_map = 0;
1503 if (after_include == 0)
1504 after_include = dirtmp;
1506 last_after_include->next = dirtmp;
1507 last_after_include = dirtmp; /* Tail follows the last one */
1512 if (out_fname != NULL)
1513 fatal ("Output filename specified twice");
1515 fatal ("Filename missing after -o option");
1516 out_fname = argv[++i];
1517 if (!strcmp (out_fname, "-"))
1522 if (!strcmp (argv[i], "-pedantic"))
1524 else if (!strcmp (argv[i], "-pedantic-errors")) {
1526 pedantic_errors = 1;
1527 } else if (!strcmp (argv[i], "-pcp")) {
1530 fatal ("Filename missing after -pcp option");
1531 pcp_fname = argv[++i];
1533 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1534 ? fopen (pcp_fname, "w")
1536 if (pcp_outfile == 0)
1537 pfatal_with_name (pcp_fname);
1543 if (!strcmp (argv[i], "-traditional")) {
1545 if (dollars_in_ident > 0)
1546 dollars_in_ident = 1;
1547 } else if (!strcmp (argv[i], "-trigraphs")) {
1553 if (! strcmp (argv[i], "-lang-c"))
1554 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1555 if (! strcmp (argv[i], "-lang-c++"))
1556 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1557 if (! strcmp (argv[i], "-lang-c-c++-comments"))
1558 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1559 if (! strcmp (argv[i], "-lang-objc"))
1560 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1561 if (! strcmp (argv[i], "-lang-objc++"))
1562 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1563 if (! strcmp (argv[i], "-lang-asm"))
1565 if (! strcmp (argv[i], "-lint"))
1570 cplusplus = 1, cplusplus_comments = 1;
1574 inhibit_warnings = 1;
1578 if (!strcmp (argv[i], "-Wtrigraphs"))
1580 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1582 else if (!strcmp (argv[i], "-Wcomment"))
1584 else if (!strcmp (argv[i], "-Wno-comment"))
1586 else if (!strcmp (argv[i], "-Wcomments"))
1588 else if (!strcmp (argv[i], "-Wno-comments"))
1590 else if (!strcmp (argv[i], "-Wtraditional"))
1592 else if (!strcmp (argv[i], "-Wno-traditional"))
1594 else if (!strcmp (argv[i], "-Wimport"))
1596 else if (!strcmp (argv[i], "-Wno-import"))
1598 else if (!strcmp (argv[i], "-Werror"))
1599 warnings_are_errors = 1;
1600 else if (!strcmp (argv[i], "-Wno-error"))
1601 warnings_are_errors = 0;
1602 else if (!strcmp (argv[i], "-Wall"))
1610 /* The style of the choices here is a bit mixed.
1611 The chosen scheme is a hybrid of keeping all options in one string
1612 and specifying each option in a separate argument:
1613 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1614 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1615 -M[M][G][D file]. This is awkward to handle in specs, and is not
1617 /* ??? -MG must be specified in addition to one of -M or -MM.
1618 This can be relaxed in the future without breaking anything.
1619 The converse isn't true. */
1621 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1622 if (!strcmp (argv[i], "-MG"))
1624 print_deps_missing_files = 1;
1627 if (!strcmp (argv[i], "-M"))
1629 else if (!strcmp (argv[i], "-MM"))
1631 else if (!strcmp (argv[i], "-MD"))
1633 else if (!strcmp (argv[i], "-MMD"))
1635 /* For -MD and -MMD options, write deps on file named by next arg. */
1636 if (!strcmp (argv[i], "-MD")
1637 || !strcmp (argv[i], "-MMD")) {
1639 fatal ("Filename missing after %s option", argv[i]);
1641 deps_file = argv[i];
1644 /* For -M and -MM, write deps on standard output
1645 and suppress the usual output. */
1646 deps_stream = stdout;
1653 char *p = argv[i] + 2;
1655 while ((c = *p++)) {
1656 /* Arg to -d specifies what parts of macros to dump */
1659 dump_macros = dump_only;
1663 dump_macros = dump_names;
1666 dump_macros = dump_definitions;
1674 if (argv[i][2] == '3')
1679 fprintf (stderr, "GNU CPP version %s", version_string);
1680 #ifdef TARGET_VERSION
1683 fprintf (stderr, "\n");
1688 print_include_names = 1;
1692 if (argv[i][2] != 0)
1693 pend_defs[i] = argv[i] + 2;
1694 else if (i + 1 == argc)
1695 fatal ("Macro name missing after -D option");
1697 i++, pend_defs[i] = argv[i];
1704 if (argv[i][2] != 0)
1706 else if (i + 1 == argc)
1707 fatal ("Assertion missing after -A option");
1711 if (!strcmp (p, "-")) {
1712 /* -A- eliminates all predefined macros and assertions.
1713 Let's include also any that were specified earlier
1714 on the command line. That way we can get rid of any
1715 that were passed automatically in from GCC. */
1717 inhibit_predefs = 1;
1718 for (j = 0; j < i; j++)
1719 pend_defs[j] = pend_assertions[j] = 0;
1721 pend_assertions[i] = p;
1722 pend_assertion_options[i] = "-A";
1727 case 'U': /* JF #undef something */
1728 if (argv[i][2] != 0)
1729 pend_undefs[i] = argv[i] + 2;
1730 else if (i + 1 == argc)
1731 fatal ("Macro name missing after -U option");
1733 pend_undefs[i] = argv[i+1], i++;
1737 put_out_comments = 1;
1740 case 'E': /* -E comes from cc -E; ignore it. */
1744 no_line_directives = 1;
1747 case '$': /* Don't include $ in identifiers. */
1748 dollars_in_ident = 0;
1751 case 'I': /* Add directory to path for includes. */
1753 struct file_name_list *dirtmp;
1755 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1757 /* Don't use any preceding -I directories for #include <...>. */
1758 first_bracket_include = 0;
1761 dirtmp = (struct file_name_list *)
1762 xmalloc (sizeof (struct file_name_list));
1763 dirtmp->next = 0; /* New one goes on the end */
1764 dirtmp->control_macro = 0;
1765 dirtmp->c_system_include_path = 0;
1766 if (argv[i][2] != 0)
1767 dirtmp->fname = argv[i] + 2;
1768 else if (i + 1 == argc)
1769 fatal ("Directory name missing after -I option");
1771 dirtmp->fname = argv[++i];
1772 dirtmp->got_name_map = 0;
1773 append_include_chain (dirtmp, dirtmp);
1779 if (!strcmp (argv[i], "-nostdinc"))
1780 /* -nostdinc causes no default include directories.
1781 You must specify all include-file directories with -I. */
1782 no_standard_includes = 1;
1783 else if (!strcmp (argv[i], "-nostdinc++"))
1784 /* -nostdinc++ causes no default C++-specific include directories. */
1785 no_standard_cplusplus_includes = 1;
1786 else if (!strcmp (argv[i], "-noprecomp"))
1791 /* Sun compiler passes undocumented switch "-undef".
1792 Let's assume it means to inhibit the predefined symbols. */
1793 inhibit_predefs = 1;
1796 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1797 if (in_fname == NULL) {
1800 } else if (out_fname == NULL) {
1803 } /* else fall through into error */
1806 fatal ("Invalid option `%s'", argv[i]);
1811 /* Add dirs from CPATH after dirs from -I. */
1812 /* There seems to be confusion about what CPATH should do,
1813 so for the moment it is not documented. */
1814 /* Some people say that CPATH should replace the standard include dirs,
1815 but that seems pointless: it comes before them, so it overrides them
1817 cp = getenv ("CPATH");
1818 if (cp && ! no_standard_includes)
1821 /* Now that dollars_in_ident is known, initialize is_idchar. */
1822 initialize_char_syntax ();
1824 /* Initialize output buffer */
1826 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1827 outbuf.bufp = outbuf.buf;
1828 outbuf.length = OUTBUF_SIZE;
1830 /* Do partial setup of input buffer for the sake of generating
1831 early #line directives (when -g is in effect). */
1833 fp = &instack[++indepth];
1834 if (in_fname == NULL)
1836 fp->nominal_fname = fp->fname = in_fname;
1839 /* In C++, wchar_t is a distinct basic type, and we can expect
1840 __wchar_t to be defined by cc1plus. */
1842 wchar_type = "__wchar_t";
1844 /* Install __LINE__, etc. Must follow initialize_char_syntax
1845 and option processing. */
1846 initialize_builtins (fp, &outbuf);
1848 /* Do standard #defines and assertions
1849 that identify system and machine type. */
1851 if (!inhibit_predefs) {
1852 char *p = (char *) alloca (strlen (predefs) + 1);
1853 strcpy (p, predefs);
1856 while (*p == ' ' || *p == '\t')
1858 /* Handle -D options. */
1859 if (p[0] == '-' && p[1] == 'D') {
1861 while (*p && *p != ' ' && *p != '\t')
1866 output_line_directive (fp, &outbuf, 0, same_file);
1867 make_definition (q, &outbuf);
1868 while (*p == ' ' || *p == '\t')
1870 } else if (p[0] == '-' && p[1] == 'A') {
1871 /* Handle -A options (assertions). */
1880 past_name = assertion;
1881 /* Locate end of name. */
1882 while (*past_name && *past_name != ' '
1883 && *past_name != '\t' && *past_name != '(')
1885 /* Locate `(' at start of value. */
1887 while (*value && (*value == ' ' || *value == '\t'))
1889 if (*value++ != '(')
1891 while (*value && (*value == ' ' || *value == '\t'))
1894 /* Locate end of value. */
1895 while (*past_value && *past_value != ' '
1896 && *past_value != '\t' && *past_value != ')')
1898 termination = past_value;
1899 while (*termination && (*termination == ' ' || *termination == '\t'))
1901 if (*termination++ != ')')
1903 if (*termination && *termination != ' ' && *termination != '\t')
1905 /* Temporarily null-terminate the value. */
1906 save_char = *termination;
1907 *termination = '\0';
1908 /* Install the assertion. */
1909 make_assertion ("-A", assertion);
1910 *termination = (char) save_char;
1912 while (*p == ' ' || *p == '\t')
1920 /* Now handle the command line options. */
1922 /* Do -U's, -D's and -A's in the order they were seen. */
1923 for (i = 1; i < argc; i++) {
1924 if (pend_undefs[i]) {
1926 output_line_directive (fp, &outbuf, 0, same_file);
1927 make_undef (pend_undefs[i], &outbuf);
1931 output_line_directive (fp, &outbuf, 0, same_file);
1932 make_definition (pend_defs[i], &outbuf);
1934 if (pend_assertions[i])
1935 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1938 done_initializing = 1;
1940 { /* read the appropriate environment variable and if it exists
1941 replace include_defaults with the listed path. */
1943 switch ((objc << 1) + cplusplus)
1946 epath = getenv ("C_INCLUDE_PATH");
1949 epath = getenv ("CPLUS_INCLUDE_PATH");
1952 epath = getenv ("OBJC_INCLUDE_PATH");
1955 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1958 /* If the environment var for this language is set,
1959 add to the default list of include directories. */
1961 char *nstore = (char *) alloca (strlen (epath) + 2);
1963 char *startp, *endp;
1965 for (num_dirs = 1, startp = epath; *startp; startp++)
1966 if (*startp == PATH_SEPARATOR)
1969 = (struct default_include *) xmalloc ((num_dirs
1970 * sizeof (struct default_include))
1971 + sizeof (include_defaults_array));
1972 startp = endp = epath;
1975 /* Handle cases like c:/usr/lib:d:/gcc/lib */
1976 if ((*endp == PATH_SEPARATOR
1977 #if 0 /* Obsolete, now that we use semicolons as the path separator. */
1979 && (endp-startp != 1 || !isalpha (*startp))
1984 strncpy (nstore, startp, endp-startp);
1986 strcpy (nstore, ".");
1988 nstore[endp-startp] = '\0';
1990 include_defaults[num_dirs].fname = savestring (nstore);
1991 include_defaults[num_dirs].cplusplus = cplusplus;
1992 include_defaults[num_dirs].cxx_aware = 1;
1996 endp = startp = endp + 1;
2000 /* Put the usual defaults back in at the end. */
2001 bcopy ((char *) include_defaults_array,
2002 (char *) &include_defaults[num_dirs],
2003 sizeof (include_defaults_array));
2007 append_include_chain (before_system, last_before_system);
2008 first_system_include = before_system;
2010 /* Unless -fnostdinc,
2011 tack on the standard include file dirs to the specified list */
2012 if (!no_standard_includes) {
2013 struct default_include *p = include_defaults;
2014 char *specd_prefix = include_prefix;
2015 char *default_prefix = savestring (GCC_INCLUDE_DIR);
2016 int default_len = 0;
2017 /* Remove the `include' from /usr/local/lib/gcc.../include. */
2018 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
2019 default_len = strlen (default_prefix) - 7;
2020 default_prefix[default_len] = 0;
2022 /* Search "translated" versions of GNU directories.
2023 These have /usr/local/lib/gcc... replaced by specd_prefix. */
2024 if (specd_prefix != 0 && default_len != 0)
2025 for (p = include_defaults; p->fname; p++) {
2026 /* Some standard dirs are only for C++. */
2027 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2028 /* Does this dir start with the prefix? */
2029 if (!strncmp (p->fname, default_prefix, default_len)) {
2030 /* Yes; change prefix and add to search list. */
2031 struct file_name_list *new
2032 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2033 int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
2034 char *str = xmalloc (this_len + 1);
2035 strcpy (str, specd_prefix);
2036 strcat (str, p->fname + default_len);
2038 new->control_macro = 0;
2039 new->c_system_include_path = !p->cxx_aware;
2040 new->got_name_map = 0;
2041 append_include_chain (new, new);
2042 if (first_system_include == 0)
2043 first_system_include = new;
2047 /* Search ordinary names for GNU include directories. */
2048 for (p = include_defaults; p->fname; p++) {
2049 /* Some standard dirs are only for C++. */
2050 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2051 struct file_name_list *new
2052 = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2053 new->control_macro = 0;
2054 new->c_system_include_path = !p->cxx_aware;
2055 new->fname = p->fname;
2056 new->got_name_map = 0;
2057 append_include_chain (new, new);
2058 if (first_system_include == 0)
2059 first_system_include = new;
2064 /* Tack the after_include chain at the end of the include chain. */
2065 append_include_chain (after_include, last_after_include);
2066 if (first_system_include == 0)
2067 first_system_include = after_include;
2069 /* With -v, print the list of dirs to search. */
2071 struct file_name_list *p;
2072 fprintf (stderr, "#include \"...\" search starts here:\n");
2073 for (p = include; p; p = p->next) {
2074 if (p == first_bracket_include)
2075 fprintf (stderr, "#include <...> search starts here:\n");
2076 fprintf (stderr, " %s\n", p->fname);
2078 fprintf (stderr, "End of search list.\n");
2081 /* Scan the -imacros files before the main input.
2082 Much like #including them, but with no_output set
2083 so that only their macro definitions matter. */
2085 no_output++; no_record_file++;
2086 for (i = 1; i < argc; i++)
2087 if (pend_files[i]) {
2088 int fd = open (pend_files[i], O_RDONLY, 0666);
2090 perror_with_name (pend_files[i]);
2091 return FAILURE_EXIT_CODE;
2093 finclude (fd, pend_files[i], &outbuf, 0, NULL_PTR);
2095 no_output--; no_record_file--;
2097 /* Copy the entire contents of the main input file into
2098 the stacked input buffer previously allocated for it. */
2100 /* JF check for stdin */
2101 if (in_fname == NULL || *in_fname == 0) {
2104 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2107 /* -MG doesn't select the form of output and must be specified with one of
2108 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2109 inhibit compilation. */
2110 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2111 fatal ("-MG must be specified with one of -M or -MM");
2113 /* Either of two environment variables can specify output of deps.
2114 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2115 where OUTPUT_FILE is the file to write deps info to
2116 and DEPS_TARGET is the target to mention in the deps. */
2119 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2120 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2121 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2126 spec = getenv ("SUNPRO_DEPENDENCIES");
2133 /* Find the space before the DEPS_TARGET, if there is one. */
2134 /* This should use index. (mrs) */
2135 while (*s != 0 && *s != ' ') s++;
2137 deps_target = s + 1;
2138 output_file = xmalloc (s - spec + 1);
2139 bcopy (spec, output_file, s - spec);
2140 output_file[s - spec] = 0;
2147 deps_file = output_file;
2151 /* For -M, print the expected object file name
2152 as the target of this Make-rule. */
2154 deps_allocated_size = 200;
2155 deps_buffer = xmalloc (deps_allocated_size);
2161 deps_output (deps_target, ':');
2162 } else if (*in_fname == 0) {
2163 deps_output ("-", ':');
2168 /* Discard all directory prefixes from filename. */
2169 if ((q = rindex (in_fname, '/')) != NULL
2170 #ifdef DIR_SEPARATOR
2171 && (q = rindex (in_fname, DIR_SEPARATOR)) != NULL
2178 /* Copy remainder to mungable area. */
2179 p = (char *) alloca (strlen(q) + 8);
2182 /* Output P, but remove known suffixes. */
2186 && p[len - 2] == '.'
2187 && index("cCsSm", p[len - 1]))
2190 && p[len - 3] == '.'
2191 && p[len - 2] == 'c'
2192 && p[len - 1] == 'c')
2195 && p[len - 4] == '.'
2196 && p[len - 3] == 'c'
2197 && p[len - 2] == 'x'
2198 && p[len - 1] == 'x')
2201 && p[len - 4] == '.'
2202 && p[len - 3] == 'c'
2203 && p[len - 2] == 'p'
2204 && p[len - 1] == 'p')
2207 /* Supply our own suffix. */
2214 deps_output (p, ':');
2215 deps_output (in_fname, ' ');
2219 file_size_and_mode (f, &st_mode, &st_size);
2220 fp->nominal_fname = fp->fname = in_fname;
2222 fp->system_header_p = 0;
2223 /* JF all this is mine about reading pipes and ttys */
2224 if (! S_ISREG (st_mode)) {
2225 /* Read input from a file that is not a normal disk file.
2226 We cannot preallocate a buffer with the correct size,
2227 so we must read in the file a piece at the time and make it bigger. */
2234 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2236 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2237 if (cnt < 0) goto perror; /* error! */
2239 if (size != bsize) break; /* End of file */
2241 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2245 /* Read a file whose size we can determine in advance.
2246 For the sake of VMS, st_size is just an upper bound. */
2247 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2248 fp->length = safe_read (f, (char *) fp->buf, st_size);
2249 if (fp->length < 0) goto perror;
2252 fp->if_stack = if_stack;
2254 /* Make sure data ends with a newline. And put a null after it. */
2256 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2257 /* Backslash-newline at end is not good enough. */
2258 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2259 fp->buf[fp->length++] = '\n';
2260 missing_newline = 1;
2262 fp->buf[fp->length] = '\0';
2264 /* Unless inhibited, convert trigraphs in the input. */
2269 /* Now that we know the input file is valid, open the output. */
2271 if (!out_fname || !strcmp (out_fname, ""))
2272 out_fname = "stdout";
2273 else if (! freopen (out_fname, "w", stdout))
2274 pfatal_with_name (out_fname);
2276 output_line_directive (fp, &outbuf, 0, same_file);
2278 /* Scan the -include files before the main input. */
2281 for (i = 1; i < argc; i++)
2282 if (pend_includes[i]) {
2283 int fd = open (pend_includes[i], O_RDONLY, 0666);
2285 perror_with_name (pend_includes[i]);
2286 return FAILURE_EXIT_CODE;
2288 finclude (fd, pend_includes[i], &outbuf, 0, NULL_PTR);
2292 /* Scan the input, processing macros and directives. */
2294 rescan (&outbuf, 0);
2296 if (missing_newline)
2299 if (pedantic && missing_newline)
2300 pedwarn ("file does not end in newline");
2302 /* Now we have processed the entire input
2303 Write whichever kind of output has been requested. */
2305 if (dump_macros == dump_only)
2307 else if (! inhibit_output) {
2312 /* Don't actually write the deps file if compilation has failed. */
2314 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2315 pfatal_with_name (deps_file);
2316 fputs (deps_buffer, deps_stream);
2317 putc ('\n', deps_stream);
2319 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2320 fatal ("I/O error on output");
2325 if (pcp_outfile && pcp_outfile != stdout
2326 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2327 fatal ("I/O error on `-pcp' output");
2329 if (ferror (stdout) || fclose (stdout) != 0)
2330 fatal ("I/O error on output");
2333 exit (FAILURE_EXIT_CODE);
2334 exit (SUCCESS_EXIT_CODE);
2337 pfatal_with_name (in_fname);
2341 /* Given a colon-separated list of file names PATH,
2342 add all the names to the search path for include files. */
2356 struct file_name_list *dirtmp;
2358 /* Find the end of this name. */
2359 while (*q != 0 && *q != PATH_SEPARATOR) q++;
2361 /* An empty name in the path stands for the current directory. */
2366 /* Otherwise use the directory that is named. */
2367 name = xmalloc (q - p + 1);
2368 bcopy (p, name, q - p);
2372 dirtmp = (struct file_name_list *)
2373 xmalloc (sizeof (struct file_name_list));
2374 dirtmp->next = 0; /* New one goes on the end */
2375 dirtmp->control_macro = 0;
2376 dirtmp->c_system_include_path = 0;
2377 dirtmp->fname = name;
2378 dirtmp->got_name_map = 0;
2379 append_include_chain (dirtmp, dirtmp);
2381 /* Advance past this name. */
2385 /* Skip the colon. */
2390 /* Return the address of the first character in S that equals C.
2391 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2392 Return 0 if there is no such character. Assume that C itself is not '\0'.
2393 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2394 but unfortunately memchr isn't autoconfigured yet. */
2402 char *p = (char *) s;
2404 char *q = index (p, c);
2406 return (U_CHAR *) q;
2408 size_t l = strlen (p);
2418 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2419 before main CCCP processing. Name `pcp' is also in honor of the
2420 drugs the trigraph designers must have been on.
2422 Using an extra pass through the buffer takes a little extra time,
2423 but is infinitely less hairy than trying to handle trigraphs inside
2424 strings, etc. everywhere, and also makes sure that trigraphs are
2425 only translated in the top level of processing. */
2431 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2434 fptr = bptr = sptr = buf->buf;
2435 lptr = fptr + buf->length;
2436 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2473 len = sptr - fptr - 2;
2475 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2476 C, this will be memmove (). */
2477 if (bptr != fptr && len > 0)
2478 bcopy ((char *) fptr, (char *) bptr, len);
2484 len = buf->length - (fptr - buf->buf);
2485 if (bptr != fptr && len > 0)
2486 bcopy ((char *) fptr, (char *) bptr, len);
2487 buf->length -= fptr - bptr;
2488 buf->buf[buf->length] = '\0';
2489 if (warn_trigraphs && fptr != bptr)
2490 warning ("%d trigraph(s) encountered", (fptr - bptr) / 2);
2493 /* Move all backslash-newline pairs out of embarrassing places.
2494 Exchange all such pairs following BP
2495 with any potentially-embarrassing characters that follow them.
2496 Potentially-embarrassing characters are / and *
2497 (because a backslash-newline inside a comment delimiter
2498 would cause it not to be recognized). */
2504 register U_CHAR *p = bp;
2506 /* First count the backslash-newline pairs here. */
2508 while (p[0] == '\\' && p[1] == '\n')
2511 /* What follows the backslash-newlines is not embarrassing. */
2513 if (*p != '/' && *p != '*')
2516 /* Copy all potentially embarrassing characters
2517 that follow the backslash-newline pairs
2518 down to where the pairs originally started. */
2520 while (*p == '*' || *p == '/')
2523 /* Now write the same number of pairs after the embarrassing chars. */
2530 /* Like newline_fix but for use within a directive-name.
2531 Move any backslash-newlines up past any following symbol constituents. */
2534 name_newline_fix (bp)
2537 register U_CHAR *p = bp;
2539 /* First count the backslash-newline pairs here. */
2540 while (p[0] == '\\' && p[1] == '\n')
2543 /* What follows the backslash-newlines is not embarrassing. */
2548 /* Copy all potentially embarrassing characters
2549 that follow the backslash-newline pairs
2550 down to where the pairs originally started. */
2552 while (is_idchar[*p])
2555 /* Now write the same number of pairs after the embarrassing chars. */
2562 /* Look for lint commands in comments.
2564 When we come in here, ibp points into a comment. Limit is as one expects.
2565 scan within the comment -- it should start, after lwsp, with a lint command.
2566 If so that command is returned as a (constant) string.
2568 Upon return, any arg will be pointed to with argstart and will be
2569 arglen long. Note that we don't parse that arg since it will just
2570 be printed out again.
2574 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2575 register U_CHAR *ibp;
2576 register U_CHAR *limit;
2577 U_CHAR **argstart; /* point to command arg */
2578 int *arglen, *cmdlen; /* how long they are */
2581 register U_CHAR *numptr; /* temp for arg parsing */
2585 SKIP_WHITE_SPACE (ibp);
2587 if (ibp >= limit) return NULL;
2589 linsize = limit - ibp;
2591 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2592 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2594 return "NOTREACHED";
2596 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2600 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2602 return "LINTLIBRARY";
2604 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2606 ibp += 7; linsize -= 7;
2607 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2609 /* OK, read a number */
2610 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2612 *arglen = numptr - *argstart;
2619 * The main loop of the program.
2621 * Read characters from the input stack, transferring them to the
2624 * Macros are expanded and push levels on the input stack.
2625 * At the end of such a level it is popped off and we keep reading.
2626 * At the end of any other kind of level, we return.
2627 * #-directives are handled, except within macros.
2629 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2630 * and insert them when appropriate. This is set while scanning macro
2631 * arguments before substitution. It is zero when scanning for final output.
2632 * There are three types of Newline markers:
2633 * * Newline - follows a macro name that was not expanded
2634 * because it appeared inside an expansion of the same macro.
2635 * This marker prevents future expansion of that identifier.
2636 * When the input is rescanned into the final output, these are deleted.
2637 * These are also deleted by ## concatenation.
2638 * * Newline Space (or Newline and any other whitespace character)
2639 * stands for a place that tokens must be separated or whitespace
2640 * is otherwise desirable, but where the ANSI standard specifies there
2641 * is no whitespace. This marker turns into a Space (or whichever other
2642 * whitespace char appears in the marker) in the final output,
2643 * but it turns into nothing in an argument that is stringified with #.
2644 * Such stringified arguments are the only place where the ANSI standard
2645 * specifies with precision that whitespace may not appear.
2647 * During this function, IP->bufp is kept cached in IBP for speed of access.
2648 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2649 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2650 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2651 * explicitly, and before RECACHE, since RECACHE uses OBP.
2655 rescan (op, output_marks)
2659 /* Character being scanned in main loop. */
2662 /* Length of pending accumulated identifier. */
2663 register int ident_length = 0;
2665 /* Hash code of pending accumulated identifier. */
2666 register int hash = 0;
2668 /* Current input level (&instack[indepth]). */
2671 /* Pointer for scanning input. */
2672 register U_CHAR *ibp;
2674 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2675 register U_CHAR *limit;
2677 /* Pointer for storing output. */
2678 register U_CHAR *obp;
2680 /* REDO_CHAR is nonzero if we are processing an identifier
2681 after backing up over the terminating character.
2682 Sometimes we process an identifier without backing up over
2683 the terminating character, if the terminating character
2684 is not special. Backing up is done so that the terminating character
2685 will be dispatched on again once the identifier is dealt with. */
2688 /* 1 if within an identifier inside of which a concatenation
2689 marker (Newline -) has been seen. */
2690 int concatenated = 0;
2692 /* While scanning a comment or a string constant,
2693 this records the line it started on, for error messages. */
2696 /* Record position of last `real' newline. */
2697 U_CHAR *beg_of_line;
2699 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2702 do { ip->macro->type = T_MACRO; \
2703 if (ip->free_ptr) free (ip->free_ptr); \
2704 --indepth; } while (0)
2706 /* Reload `rescan's local variables that describe the current
2707 level of the input stack. */
2710 do { ip = &instack[indepth]; \
2712 limit = ip->buf + ip->length; \
2714 check_expand (op, limit - ibp); \
2716 obp = op->bufp; } while (0)
2718 if (no_output && instack[indepth].fname != 0)
2719 skip_if_group (&instack[indepth], 1, NULL);
2726 /* Our caller must always put a null after the end of
2727 the input at each input stack level. */
2737 if (*ibp == '\n' && !ip->macro) {
2738 /* At the top level, always merge lines ending with backslash-newline,
2739 even in middle of identifier. But do not merge lines in a macro,
2740 since backslash might be followed by a newline-space marker. */
2743 --obp; /* remove backslash from obuf */
2746 /* If ANSI, backslash is just another character outside a string. */
2749 /* Otherwise, backslash suppresses specialness of following char,
2750 so copy it here to prevent the switch from seeing it.
2751 But first get any pending identifier processed. */
2752 if (ident_length > 0)
2759 if (ident_length || ip->macro || traditional)
2761 while (*ibp == '\\' && ibp[1] == '\n') {
2767 /* Treat this %: digraph as if it were #. */
2771 if (assertions_flag) {
2772 /* Copy #foo (bar lose) without macro expansion. */
2773 obp[-1] = '#'; /* In case it was '%'. */
2774 SKIP_WHITE_SPACE (ibp);
2775 while (is_idchar[*ibp])
2777 SKIP_WHITE_SPACE (ibp);
2780 skip_paren_group (ip);
2781 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2782 obp += ip->bufp - ibp;
2787 /* If this is expanding a macro definition, don't recognize
2788 preprocessing directives. */
2791 /* If this is expand_into_temp_buffer,
2792 don't recognize them either. Warn about them
2793 only after an actual newline at this level,
2794 not at the beginning of the input level. */
2796 if (ip->buf != beg_of_line)
2797 warning ("preprocessing directive not recognized within macro arg");
2804 /* # keyword: a # must be first nonblank char on the line */
2805 if (beg_of_line == 0)
2810 /* Scan from start of line, skipping whitespace, comments
2811 and backslash-newlines, and see if we reach this #.
2812 If not, this # is not special. */
2814 /* If -traditional, require # to be at beginning of line. */
2817 if (is_hor_space[*bp])
2819 else if (*bp == '\\' && bp[1] == '\n')
2821 else if (*bp == '/' && bp[1] == '*') {
2823 while (!(*bp == '*' && bp[1] == '/'))
2827 /* There is no point in trying to deal with C++ // comments here,
2828 because if there is one, then this # must be part of the
2829 comment and we would never reach here. */
2835 while (bp[1] == '\\' && bp[2] == '\n')
2839 /* %: appears at start of line; skip past the ':' too. */
2848 /* This # can start a directive. */
2850 --obp; /* Don't copy the '#' */
2854 if (! handle_directive (ip, op)) {
2858 /* Not a known directive: treat it as ordinary text.
2859 IP, OP, IBP, etc. have not been changed. */
2860 if (no_output && instack[indepth].fname) {
2861 /* If not generating expanded output,
2862 what we do with ordinary text is skip it.
2863 Discard everything until next # directive. */
2864 skip_if_group (&instack[indepth], 1, 0);
2869 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2870 /* Don't expand an identifier that could be a macro directive.
2871 (Section 3.8.3 of the ANSI C standard) */
2872 SKIP_WHITE_SPACE (ibp);
2873 if (is_idstart[*ibp])
2876 while (is_idchar[*ibp])
2884 /* A # directive has been successfully processed. */
2885 /* If not generating expanded output, ignore everything until
2886 next # directive. */
2887 if (no_output && instack[indepth].fname)
2888 skip_if_group (&instack[indepth], 1, 0);
2894 case '\"': /* skip quoted string */
2896 /* A single quoted string is treated like a double -- some
2897 programs (e.g., troff) are perverse this way */
2902 start_line = ip->lineno;
2904 /* Skip ahead to a matching quote. */
2908 if (ip->macro != 0) {
2909 /* try harder: this string crosses a macro expansion boundary.
2910 This can happen naturally if -traditional.
2911 Otherwise, only -D can make a macro with an unmatched quote. */
2917 error_with_line (line_for_error (start_line),
2918 "unterminated string or character constant");
2919 error_with_line (multiline_string_line,
2920 "possible real start of unterminated constant");
2921 multiline_string_line = 0;
2930 /* Traditionally, end of line ends a string constant with no error.
2931 So exit the loop and record the new line. */
2937 error_with_line (line_for_error (start_line),
2938 "unterminated character constant");
2941 if (pedantic && multiline_string_line == 0) {
2942 pedwarn_with_line (line_for_error (start_line),
2943 "string constant runs past end of line");
2945 if (multiline_string_line == 0)
2946 multiline_string_line = ip->lineno - 1;
2953 /* Backslash newline is replaced by nothing at all,
2954 but keep the line counts correct. */
2959 /* ANSI stupidly requires that in \\ the second \
2960 is *not* prevented from combining with a newline. */
2961 while (*ibp == '\\' && ibp[1] == '\n') {
2980 if (*ibp == '\\' && ibp[1] == '\n')
2984 && !(cplusplus_comments && *ibp == '/'))
2992 /* C++ style comment... */
2993 start_line = ip->lineno;
2995 --ibp; /* Back over the slash */
2998 /* Comments are equivalent to spaces. */
2999 if (! put_out_comments)
3002 /* must fake up a comment here */
3007 U_CHAR *before_bp = ibp+2;
3009 while (ibp < limit) {
3010 if (ibp[-1] != '\\' && *ibp == '\n') {
3011 if (put_out_comments) {
3012 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3013 obp += ibp - before_bp;
3019 /* Copy the newline into the output buffer, in order to
3020 avoid the pain of a #line every time a multiline comment
3022 if (!put_out_comments)
3033 /* Ordinary C comment. Skip it, optionally copying it to output. */
3035 start_line = ip->lineno;
3037 ++ibp; /* Skip the star. */
3039 /* If this cpp is for lint, we peek inside the comments: */
3043 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
3045 if (lintcmd != NULL) {
3047 check_expand (op, cmdlen + arglen + 14);
3049 /* I believe it is always safe to emit this newline: */
3051 bcopy ("#pragma lint ", (char *) obp, 13);
3053 bcopy (lintcmd, (char *) obp, cmdlen);
3058 bcopy (argbp, (char *) obp, arglen);
3062 /* OK, now bring us back to the state we were in before we entered
3063 this branch. We need #line because the #pragma's newline always
3064 messes up the line count. */
3066 output_line_directive (ip, op, 0, same_file);
3067 check_expand (op, limit - ibp + 2);
3073 /* Comments are equivalent to spaces.
3074 Note that we already output the slash; we might not want it.
3075 For -traditional, a comment is equivalent to nothing. */
3076 if (! put_out_comments) {
3086 U_CHAR *before_bp = ibp;
3088 while (ibp < limit) {
3091 if (warn_comments && *ibp == '*')
3092 warning ("`/*' within comment");
3095 if (*ibp == '\\' && ibp[1] == '\n')
3097 if (ibp >= limit || *ibp == '/')
3102 /* Copy the newline into the output buffer, in order to
3103 avoid the pain of a #line every time a multiline comment
3105 if (!put_out_comments)
3113 error_with_line (line_for_error (start_line),
3114 "unterminated comment");
3117 if (put_out_comments) {
3118 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3119 obp += ibp - before_bp;
3126 if (!dollars_in_ident)
3130 case '0': case '1': case '2': case '3': case '4':
3131 case '5': case '6': case '7': case '8': case '9':
3132 /* If digit is not part of identifier, it starts a number,
3133 which means that following letters are not an identifier.
3134 "0x5" does not refer to an identifier "x5".
3135 So copy all alphanumerics that follow without accumulating
3136 as an identifier. Periods also, for sake of "3.e7". */
3138 if (ident_length == 0) {
3140 while (ibp[0] == '\\' && ibp[1] == '\n') {
3145 if (!is_idchar[c] && c != '.') {
3150 /* A sign can be part of a preprocessing number
3151 if it follows an e. */
3152 if (c == 'e' || c == 'E') {
3153 while (ibp[0] == '\\' && ibp[1] == '\n') {
3157 if (*ibp == '+' || *ibp == '-') {
3159 /* But traditional C does not let the token go past the sign. */
3170 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3171 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3172 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3173 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3175 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3176 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3177 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3178 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3182 /* Compute step of hash function, to avoid a proc call on every token */
3183 hash = HASHSTEP (hash, c);
3187 if (ip->fname == 0 && *ibp == '-') {
3188 /* Newline - inhibits expansion of preceding token.
3189 If expanding a macro arg, we keep the newline -.
3190 In final output, it is deleted.
3191 We recognize Newline - in macro bodies and macro args. */
3192 if (! concatenated) {
3197 if (!output_marks) {
3200 /* If expanding a macro arg, keep the newline -. */
3206 /* If reprocessing a macro expansion, newline is a special marker. */
3207 else if (ip->macro != 0) {
3208 /* Newline White is a "funny space" to separate tokens that are
3209 supposed to be separate but without space between.
3210 Here White means any whitespace character.
3211 Newline - marks a recursive macro use that is not
3212 supposed to be expandable. */
3214 if (is_space[*ibp]) {
3215 /* Newline Space does not prevent expansion of preceding token
3216 so expand the preceding token and then come back. */
3217 if (ident_length > 0)
3220 /* If generating final output, newline space makes a space. */
3221 if (!output_marks) {
3223 /* And Newline Newline makes a newline, so count it. */
3224 if (obp[-1] == '\n')
3227 /* If expanding a macro arg, keep the newline space.
3228 If the arg gets stringified, newline space makes nothing. */
3231 } else abort (); /* Newline followed by something random? */
3235 /* If there is a pending identifier, handle it and come back here. */
3236 if (ident_length > 0)
3241 /* Update the line counts and output a #line if necessary. */
3244 if (ip->lineno != op->lineno) {
3246 output_line_directive (ip, op, 1, same_file);
3247 check_expand (op, limit - ibp);
3252 /* Come here either after (1) a null character that is part of the input
3253 or (2) at the end of the input, because there is a null there. */
3256 /* Our input really contains a null character. */
3259 /* At end of a macro-expansion level, pop it and read next level. */
3260 if (ip->macro != 0) {
3263 /* If traditional, and we have an identifier that ends here,
3264 process it now, so we get the right error for recursion. */
3265 if (traditional && ident_length
3266 && ! is_idchar[*instack[indepth - 1].bufp]) {
3275 /* If we don't have a pending identifier,
3276 return at end of input. */
3277 if (ident_length == 0) {
3285 /* If we do have a pending identifier, just consider this null
3286 a special character and arrange to dispatch on it again.
3287 The second time, IDENT_LENGTH will be zero so we will return. */
3293 /* Handle the case of a character such as /, ', " or null
3294 seen following an identifier. Back over it so that
3295 after the identifier is processed the special char
3296 will be dispatched on again. */
3306 if (ident_length > 0) {
3307 register HASHNODE *hp;
3309 /* We have just seen an identifier end. If it's a macro, expand it.
3311 IDENT_LENGTH is the length of the identifier
3312 and HASH is its hash code.
3314 The identifier has already been copied to the output,
3315 so if it is a macro we must remove it.
3317 If REDO_CHAR is 0, the char that terminated the identifier
3318 has been skipped in the output and the input.
3319 OBP-IDENT_LENGTH-1 points to the identifier.
3320 If the identifier is a macro, we must back over the terminator.
3322 If REDO_CHAR is 1, the terminating char has already been
3323 backed over. OBP-IDENT_LENGTH points to the identifier. */
3325 if (!pcp_outfile || pcp_inside_if) {
3326 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3329 if (hp->length == ident_length) {
3330 int obufp_before_macroname;
3331 int op_lineno_before_macroname;
3332 register int i = ident_length;
3333 register U_CHAR *p = hp->name;
3334 register U_CHAR *q = obp - i;
3340 do { /* All this to avoid a strncmp () */
3345 /* We found a use of a macro name.
3346 see if the context shows it is a macro call. */
3348 /* Back up over terminating character if not already done. */
3354 /* Save this as a displacement from the beginning of the output
3355 buffer. We can not save this as a position in the output
3356 buffer, because it may get realloc'ed by RECACHE. */
3357 obufp_before_macroname = (obp - op->buf) - ident_length;
3358 op_lineno_before_macroname = op->lineno;
3360 if (hp->type == T_PCSTRING) {
3361 pcstring_used (hp); /* Mark the definition of this key
3362 as needed, ensuring that it
3364 break; /* Exit loop, since the key cannot have a
3365 definition any longer. */
3368 /* Record whether the macro is disabled. */
3369 disabled = hp->type == T_DISABLED;
3371 /* This looks like a macro ref, but if the macro was disabled,
3372 just copy its name and put in a marker if requested. */
3376 /* This error check caught useful cases such as
3377 #define foo(x,y) bar (x (y,0), y)
3380 error ("recursive use of macro `%s'", hp->name);
3384 check_expand (op, limit - ibp + 2);
3391 /* If macro wants an arglist, verify that a '(' follows.
3392 first skip all whitespace, copying it to the output
3393 after the macro name. Then, if there is no '(',
3394 decide this is not a macro call and leave things that way. */
3395 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3396 && hp->value.defn->nargs >= 0)
3398 U_CHAR *old_ibp = ibp;
3399 U_CHAR *old_obp = obp;
3400 int old_iln = ip->lineno;
3401 int old_oln = op->lineno;
3404 /* Scan forward over whitespace, copying it to the output. */
3405 if (ibp == limit && ip->macro != 0) {
3410 old_iln = ip->lineno;
3411 old_oln = op->lineno;
3413 /* A comment: copy it unchanged or discard it. */
3414 else if (*ibp == '/' && ibp[1] == '*') {
3415 if (put_out_comments) {
3418 } else if (! traditional) {
3422 while (ibp + 1 != limit
3423 && !(ibp[0] == '*' && ibp[1] == '/')) {
3424 /* We need not worry about newline-marks,
3425 since they are never found in comments. */
3427 /* Newline in a file. Count it. */
3431 if (put_out_comments)
3437 if (put_out_comments) {
3442 else if (is_space[*ibp]) {
3444 if (ibp[-1] == '\n') {
3445 if (ip->macro == 0) {
3446 /* Newline in a file. Count it. */
3449 } else if (!output_marks) {
3450 /* A newline mark, and we don't want marks
3451 in the output. If it is newline-hyphen,
3452 discard it entirely. Otherwise, it is
3453 newline-whitechar, so keep the whitechar. */
3463 /* A newline mark; copy both chars to the output. */
3471 /* It isn't a macro call.
3472 Put back the space that we just skipped. */
3475 ip->lineno = old_iln;
3476 op->lineno = old_oln;
3477 /* Exit the for loop. */
3482 /* This is now known to be a macro call.
3483 Discard the macro name from the output,
3484 along with any following whitespace just copied,
3485 but preserve newlines if not outputting marks since this
3486 is more likely to do the right thing with line numbers. */
3487 obp = op->buf + obufp_before_macroname;
3489 op->lineno = op_lineno_before_macroname;
3491 int newlines = op->lineno - op_lineno_before_macroname;
3492 while (0 < newlines--)
3496 /* Prevent accidental token-pasting with a character
3497 before the macro call. */
3498 if (!traditional && obp != op->buf) {
3500 case '!': case '%': case '&': case '*':
3501 case '+': case '-': case '/': case ':':
3502 case '<': case '=': case '>': case '^':
3504 /* If we are expanding a macro arg, make a newline marker
3505 to separate the tokens. If we are making real output,
3506 a plain space will do. */
3513 /* Expand the macro, reading arguments as needed,
3514 and push the expansion on the input stack. */
3517 macroexpand (hp, op);
3519 /* Reexamine input stack, since macroexpand has pushed
3520 a new level on it. */
3527 } /* End hash-table-search loop */
3529 ident_length = hash = 0; /* Stop collecting identifier */
3532 } /* End if (ident_length > 0) */
3534 } /* End per-char loop */
3536 /* Come here to return -- but first give an error message
3537 if there was an unterminated successful conditional. */
3539 if (if_stack != ip->if_stack)
3543 switch (if_stack->type)
3564 error_with_line (line_for_error (if_stack->lineno),
3565 "unterminated `#%s' conditional", str);
3567 if_stack = ip->if_stack;
3571 * Rescan a string into a temporary buffer and return the result
3572 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3574 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3575 * and insert such markers when appropriate. See `rescan' for details.
3576 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3577 * before substitution; it is 0 for other uses.
3580 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3581 U_CHAR *buf, *limit;
3582 int output_marks, assertions;
3584 register FILE_BUF *ip;
3586 int length = limit - buf;
3588 int odepth = indepth;
3589 int save_assertions_flag = assertions_flag;
3591 assertions_flag = assertions;
3596 /* Set up the input on the input stack. */
3598 buf1 = (U_CHAR *) alloca (length + 1);
3600 register U_CHAR *p1 = buf;
3601 register U_CHAR *p2 = buf1;
3608 /* Set up to receive the output. */
3610 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3611 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3616 CHECK_DEPTH ({return obuf;});
3620 ip = &instack[indepth];
3622 ip->nominal_fname = 0;
3623 ip->system_header_p = 0;
3626 ip->length = length;
3627 ip->buf = ip->bufp = buf1;
3628 ip->if_stack = if_stack;
3630 ip->lineno = obuf.lineno = 1;
3632 /* Scan the input, create the output. */
3633 rescan (&obuf, output_marks);
3635 /* Pop input stack to original state. */
3638 if (indepth != odepth)
3641 /* Record the output. */
3642 obuf.length = obuf.bufp - obuf.buf;
3644 assertions_flag = save_assertions_flag;
3649 * Process a # directive. Expects IP->bufp to point after the '#', as in
3650 * `#define foo bar'. Passes to the directive handler
3651 * (do_define, do_include, etc.): the addresses of the 1st and
3652 * last chars of the directive (starting immediately after the #
3653 * keyword), plus op and the keyword table pointer. If the directive
3654 * contains comments it is copied into a temporary buffer sans comments
3655 * and the temporary buffer is passed to the directive handler instead.
3656 * Likewise for backslash-newlines.
3658 * Returns nonzero if this was a known # directive.
3659 * Otherwise, returns zero, without advancing the input pointer.
3663 handle_directive (ip, op)
3666 register U_CHAR *bp, *cp;
3667 register struct directive *kt;
3668 register int ident_length;
3671 /* Nonzero means we must copy the entire directive
3672 to get rid of comments or backslash-newlines. */
3673 int copy_directive = 0;
3675 U_CHAR *ident, *after_ident;
3679 /* Record where the directive started. do_xifdef needs this. */
3680 directive_start = bp - 1;
3682 /* Skip whitespace and \-newline. */
3684 if (is_hor_space[*bp]) {
3685 if (*bp != ' ' && *bp != '\t' && pedantic)
3686 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3688 } else if (*bp == '/' && (bp[1] == '*'
3689 || (cplusplus_comments && bp[1] == '/'))) {
3691 skip_to_end_of_comment (ip, &ip->lineno, 0);
3693 } else if (*bp == '\\' && bp[1] == '\n') {
3694 bp += 2; ip->lineno++;
3698 /* Now find end of directive name.
3699 If we encounter a backslash-newline, exchange it with any following
3700 symbol-constituents so that we end up with a contiguous name. */
3707 if (*cp == '\\' && cp[1] == '\n')
3708 name_newline_fix (cp);
3714 ident_length = cp - bp;
3718 /* A line of just `#' becomes blank. */
3720 if (ident_length == 0 && *after_ident == '\n') {
3721 ip->bufp = after_ident;
3725 if (ident_length == 0 || !is_idstart[*ident]) {
3727 while (is_idchar[*p]) {
3728 if (*p < '0' || *p > '9')
3732 /* Handle # followed by a line number. */
3733 if (p != ident && !is_idchar[*p]) {
3734 static struct directive line_directive_table[] = {
3735 { 4, do_line, "line", T_LINE},
3738 pedwarn ("`#' followed by integer");
3739 after_ident = ident;
3740 kt = line_directive_table;
3744 /* Avoid error for `###' and similar cases unless -pedantic. */
3746 while (*p == '#' || is_hor_space[*p]) p++;
3748 if (pedantic && !lang_asm)
3749 warning ("invalid preprocessing directive");
3755 error ("invalid preprocessing directive name");
3761 * Decode the keyword and call the appropriate expansion
3762 * routine, after moving the input pointer up to the next line.
3764 for (kt = directive_table; kt->length > 0; kt++) {
3765 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3766 register U_CHAR *buf;
3767 register U_CHAR *limit;
3770 int *already_output;
3772 /* Nonzero means do not delete comments within the directive.
3773 #define needs this when -traditional. */
3778 limit = ip->buf + ip->length;
3781 keep_comments = traditional && kt->traditional_comments;
3782 /* #import is defined only in Objective C, or when on the NeXT. */
3783 if (kt->type == T_IMPORT
3784 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3787 /* Find the end of this directive (first newline not backslashed
3788 and not in a string or comment).
3789 Set COPY_DIRECTIVE if the directive must be copied
3790 (it contains a backslash-newline or a comment). */
3792 buf = bp = after_ident;
3793 while (bp < limit) {
3794 register U_CHAR c = *bp++;
3802 } else if (traditional)
3809 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3810 /* Don't bother calling the directive if we already got an error
3811 message due to unterminated string. Skip everything and pretend
3812 we called the directive. */
3815 /* Traditional preprocessing permits unterminated strings. */
3824 /* <...> is special for #include. */
3826 if (!kt->angle_brackets)
3828 while (bp < limit && *bp != '>' && *bp != '\n') {
3829 if (*bp == '\\' && bp[1] == '\n') {
3839 if (*bp == '\\' && bp[1] == '\n')
3842 || (cplusplus_comments && *bp == '/')) {
3843 U_CHAR *obp = bp - 1;
3845 skip_to_end_of_comment (ip, &ip->lineno, 0);
3847 /* No need to copy the directive because of a comment at the end;
3848 just don't include the comment in the directive. */
3849 if (bp == limit || *bp == '\n') {
3853 /* Don't remove the comments if -traditional. */
3854 if (! keep_comments)
3863 pedwarn ("%s in preprocessing directive", char_name[c]);
3867 --bp; /* Point to the newline */
3875 resume_p = ip->bufp;
3876 /* BP is the end of the directive.
3877 RESUME_P is the next interesting data after the directive.
3878 A comment may come between. */
3880 /* If a directive should be copied through, and -E was given,
3881 pass it through before removing comments. */
3882 if (!no_output && kt->pass_thru && put_out_comments) {
3885 /* Output directive name. */
3886 check_expand (op, kt->length + 2);
3887 /* Make sure # is at the start of a line */
3888 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3893 bcopy (kt->name, op->bufp, kt->length);
3894 op->bufp += kt->length;
3896 /* Output arguments. */
3898 check_expand (op, len);
3899 bcopy (buf, (char *) op->bufp, len);
3901 /* Take account of any (escaped) newlines just output. */
3903 if (buf[len] == '\n')
3906 already_output = &junk;
3907 } /* Don't we need a newline or #line? */
3909 if (copy_directive) {
3910 register U_CHAR *xp = buf;
3911 /* Need to copy entire directive into temp buffer before dispatching */
3913 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3917 /* Copy to the new buffer, deleting comments
3918 and backslash-newlines (and whitespace surrounding the latter). */
3921 register U_CHAR c = *xp++;
3926 abort (); /* A bare newline should never part of the line. */
3929 /* <...> is special for #include. */
3931 if (!kt->angle_brackets)
3933 while (xp < bp && c != '>') {
3935 if (c == '\\' && xp < bp && *xp == '\n')
3946 if (cp != buf && is_space[cp[-1]]) {
3947 while (cp != buf && is_space[cp[-1]]) cp--;
3949 SKIP_WHITE_SPACE (xp);
3950 } else if (is_space[*xp]) {
3952 SKIP_WHITE_SPACE (xp);
3954 } else if (traditional && xp < bp) {
3962 register U_CHAR *bp1
3963 = skip_quoted_string (xp - 1, bp, ip->lineno,
3964 NULL_PTR, NULL_PTR, NULL_PTR);
3978 || (cplusplus_comments && *xp == '/')) {
3980 /* If we already copied the directive through,
3981 already_output != 0 prevents outputting comment now. */
3982 skip_to_end_of_comment (ip, already_output, 0);
3984 while (xp != ip->bufp)
3986 /* Delete or replace the slash. */
3987 else if (traditional)
3996 /* Null-terminate the copy. */
4002 ip->bufp = resume_p;
4004 /* Some directives should be written out for cc1 to process,
4005 just as if they were not defined. And sometimes we're copying
4006 definitions through. */
4008 if (!no_output && already_output == 0
4010 || (kt->type == T_DEFINE
4011 && (dump_macros == dump_names
4012 || dump_macros == dump_definitions)))) {
4015 /* Output directive name. */
4016 check_expand (op, kt->length + 1);
4018 bcopy (kt->name, (char *) op->bufp, kt->length);
4019 op->bufp += kt->length;
4021 if (kt->pass_thru || dump_macros == dump_definitions) {
4022 /* Output arguments. */
4024 check_expand (op, len);
4025 bcopy (buf, (char *) op->bufp, len);
4027 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
4030 SKIP_WHITE_SPACE (xp);
4032 while (is_idchar[*xp]) xp++;
4034 check_expand (op, len + 1);
4036 bcopy (yp, op->bufp, len);
4039 } /* Don't we need a newline or #line? */
4041 /* Call the appropriate directive handler. buf now points to
4042 either the appropriate place in the input buffer, or to
4043 the temp buffer if it was necessary to make one. cp
4044 points to the first char after the contents of the (possibly
4045 copied) directive, in either case. */
4046 (*kt->func) (buf, cp, op, kt);
4047 check_expand (op, ip->length - (ip->bufp - ip->buf));
4053 /* It is deliberate that we don't warn about undefined directives.
4054 That is the responsibility of cc1. */
4061 static struct tm *timebuf;
4063 time_t t = time ((time_t *)0);
4064 timebuf = localtime (&t);
4069 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4070 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4074 * expand things like __FILE__. Place the expansion into the output
4075 * buffer *without* rescanning.
4079 special_symbol (hp, op)
4086 FILE_BUF *ip = NULL;
4089 int paren = 0; /* For special `defined' keyword */
4091 if (pcp_outfile && pcp_inside_if
4092 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4093 error ("Predefined macro `%s' used inside `#if' during precompilation",
4096 for (i = indepth; i >= 0; i--)
4097 if (instack[i].fname != NULL) {
4102 error ("cccp error: not in any file?!");
4103 return; /* the show must go on */
4111 if (hp->type == T_FILE)
4112 string = ip->nominal_fname;
4114 string = instack[0].nominal_fname;
4118 buf = (char *) alloca (3 + 4 * strlen (string));
4119 quote_string (buf, string);
4127 case T_INCLUDE_LEVEL:
4129 for (i = indepth; i >= 0; i--)
4130 if (instack[i].fname != NULL)
4133 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4134 sprintf (buf, "%d", true_indepth - 1);
4138 buf = (char *) alloca (3 + strlen (version_string));
4139 sprintf (buf, "\"%s\"", version_string);
4142 #ifndef NO_BUILTIN_SIZE_TYPE
4148 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4149 case T_PTRDIFF_TYPE:
4158 case T_USER_LABEL_PREFIX_TYPE:
4159 buf = USER_LABEL_PREFIX;
4162 case T_REGISTER_PREFIX_TYPE:
4163 buf = REGISTER_PREFIX;
4167 buf = hp->value.cpval;
4168 if (pcp_inside_if && pcp_outfile)
4169 /* Output a precondition for this macro use */
4170 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4174 buf = (char *) alloca (10);
4175 sprintf (buf, "%d", ip->lineno);
4180 buf = (char *) alloca (20);
4181 timebuf = timestamp ();
4182 if (hp->type == T_DATE)
4183 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4184 timebuf->tm_mday, timebuf->tm_year + 1900);
4186 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4190 case T_SPEC_DEFINED:
4191 buf = " 0 "; /* Assume symbol is not defined */
4192 ip = &instack[indepth];
4193 SKIP_WHITE_SPACE (ip->bufp);
4194 if (*ip->bufp == '(') {
4196 ip->bufp++; /* Skip over the paren */
4197 SKIP_WHITE_SPACE (ip->bufp);
4200 if (!is_idstart[*ip->bufp])
4202 if ((hp = lookup (ip->bufp, -1, -1))) {
4203 if (pcp_outfile && pcp_inside_if
4204 && (hp->type == T_CONST
4205 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4206 /* Output a precondition for this macro use. */
4207 fprintf (pcp_outfile, "#define %s\n", hp->name);
4211 if (pcp_outfile && pcp_inside_if) {
4212 /* Output a precondition for this macro use */
4213 U_CHAR *cp = ip->bufp;
4214 fprintf (pcp_outfile, "#undef ");
4215 while (is_idchar[*cp]) /* Ick! */
4216 fputc (*cp++, pcp_outfile);
4217 putc ('\n', pcp_outfile);
4219 while (is_idchar[*ip->bufp])
4221 SKIP_WHITE_SPACE (ip->bufp);
4223 if (*ip->bufp != ')')
4231 error ("`defined' without an identifier");
4235 error ("cccp error: invalid special hash type"); /* time for gdb */
4239 check_expand (op, len);
4240 bcopy (buf, (char *) op->bufp, len);
4247 /* Routines to handle #directives */
4249 /* Handle #include and #import.
4250 This function expects to see "fname" or <fname> on the input. */
4253 do_include (buf, limit, op, keyword)
4254 U_CHAR *buf, *limit;
4256 struct directive *keyword;
4258 int importing = (keyword->type == T_IMPORT);
4259 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4260 static int import_warning = 0;
4261 char *fname; /* Dynamically allocated fname buffer */
4264 U_CHAR *fbeg, *fend; /* Beginning and end of fname */
4266 struct file_name_list *search_start = include; /* Chain of dirs to search */
4267 struct file_name_list dsp[1]; /* First in chain, if #include "..." */
4268 struct file_name_list *searchptr = 0;
4271 int f; /* file number */
4273 int retried = 0; /* Have already tried macro
4274 expanding the include line*/
4275 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4280 f= -1; /* JF we iz paranoid! */
4282 if (importing && warn_import && !inhibit_warnings
4283 && !instack[indepth].system_header_p && !import_warning) {
4285 warning ("using `#import' is not recommended");
4286 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4287 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4288 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4289 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4290 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4291 fprintf (stderr, " ... <real contents of file> ...\n");
4292 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4293 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4294 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4295 fprintf (stderr, "when it is equipped with such a conditional.\n");
4301 SKIP_WHITE_SPACE (fbeg);
4302 /* Discard trailing whitespace so we can easily see
4303 if we have parsed all the significant chars we were given. */
4304 while (limit != fbeg && is_hor_space[limit[-1]]) limit--;
4310 /* Copy the operand text, concatenating the strings. */
4313 fbeg = (U_CHAR *) alloca (limit - fbeg + 1);
4315 while (fin != limit) {
4316 while (fin != limit && *fin != '\"')
4321 /* If not at the end, there had better be another string. */
4322 /* Skip just horiz space, and don't go past limit. */
4323 while (fin != limit && is_hor_space[*fin]) fin++;
4324 if (fin != limit && *fin == '\"')
4332 /* We have "filename". Figure out directory this source
4333 file is coming from and put it on the front of the list. */
4335 /* If -I- was specified, don't search current dir, only spec'd ones. */
4336 if (ignore_srcdir) break;
4338 for (fp = &instack[indepth]; fp >= instack; fp--)
4343 if ((nam = fp->nominal_fname) != NULL) {
4344 /* Found a named file. Figure out dir of the file,
4345 and put it in front of the search list. */
4346 dsp[0].next = search_start;
4349 ep = rindex (nam, '/');
4350 #ifdef DIR_SEPARATOR
4351 if (ep == NULL) ep = rindex (nam, DIR_SEPARATOR);
4353 char *tmp = rindex (nam, DIR_SEPARATOR);
4354 if (tmp != NULL && tmp > ep) ep = tmp;
4358 ep = rindex (nam, ']');
4359 if (ep == NULL) ep = rindex (nam, '>');
4360 if (ep == NULL) ep = rindex (nam, ':');
4361 if (ep != NULL) ep++;
4365 dsp[0].fname = (char *) alloca (n + 1);
4366 strncpy (dsp[0].fname, nam, n);
4367 dsp[0].fname[n] = '\0';
4368 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4369 max_include_len = n + INCLUDE_LEN_FUDGE;
4371 dsp[0].fname = 0; /* Current directory */
4373 dsp[0].got_name_map = 0;
4382 while (fend != limit && *fend != '>') fend++;
4383 if (*fend == '>' && fend + 1 == limit) {
4385 /* If -I-, start with the first -I dir after the -I-. */
4386 if (first_bracket_include)
4387 search_start = first_bracket_include;
4395 * Support '#include xyz' like VAX-C to allow for easy use of all the
4396 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4397 * code from case '<' is repeated here) and generates a warning.
4398 * (Note: macro expansion of `xyz' takes precedence.)
4400 if (retried && isalpha(*(--fbeg))) {
4402 while (fend != limit && (!isspace(*fend))) fend++;
4403 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4404 if (fend == limit) {
4406 /* If -I-, start with the first -I dir after the -I-. */
4407 if (first_bracket_include)
4408 search_start = first_bracket_include;
4416 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4419 /* Expand buffer and then remove any newline markers.
4420 We can't just tell expand_to_temp_buffer to omit the markers,
4421 since it would put extra spaces in include file names. */
4424 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4426 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4428 while (src != trybuf.bufp) {
4429 switch ((*limit++ = *src++)) {
4438 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4439 NULL_PTR, NULL_PTR, NULL_PTR);
4453 /* For #include_next, skip in the search path
4454 past the dir in which the containing file was found. */
4457 for (fp = &instack[indepth]; fp >= instack; fp--)
4458 if (fp->fname != NULL) {
4459 /* fp->dir is null if the containing file was specified
4460 with an absolute file name. In that case, don't skip anything. */
4462 search_start = fp->dir->next;
4471 error ("empty file name in `#%s'", keyword->name);
4475 /* Allocate this permanently, because it gets stored in the definitions
4477 fname = xmalloc (max_include_len + flen + 4);
4478 /* + 2 above for slash and terminating null. */
4479 /* + 2 added for '.h' on VMS (to support '#include filename') */
4481 /* If specified file name is absolute, just open it. */
4484 #ifdef DIR_SEPARATOR
4485 || *fbeg == DIR_SEPARATOR
4488 strncpy (fname, (char *) fbeg, flen);
4490 if (redundant_include_p (fname))
4493 f = lookup_import (fname, NULL_PTR);
4495 f = open_include_file (fname, NULL_PTR);
4497 return 0; /* Already included this file */
4499 /* Search directory path, trying to open the file.
4500 Copy each filename tried into FNAME. */
4502 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4503 if (searchptr->fname) {
4504 /* The empty string in a search path is ignored.
4505 This makes it possible to turn off entirely
4506 a standard piece of the list. */
4507 if (searchptr->fname[0] == 0)
4509 strcpy (fname, searchptr->fname);
4510 strcat (fname, "/");
4511 fname[strlen (fname) + flen] = 0;
4515 strncat (fname, (char *) fbeg, flen);
4517 /* Change this 1/2 Unix 1/2 VMS file specification into a
4518 full VMS file specification */
4519 if (searchptr->fname && (searchptr->fname[0] != 0)) {
4520 /* Fix up the filename */
4521 hack_vms_include_specification (fname);
4523 /* This is a normal VMS filespec, so use it unchanged. */
4524 strncpy (fname, fbeg, flen);
4526 /* if it's '#include filename', add the missing .h */
4527 if (index(fname,'.')==NULL) {
4528 strcat (fname, ".h");
4532 /* ??? There are currently 3 separate mechanisms for avoiding processing
4533 of redundant include files: #import, #pragma once, and
4534 redundant_include_p. It would be nice if they were unified. */
4535 if (redundant_include_p (fname))
4538 f = lookup_import (fname, searchptr);
4540 f = open_include_file (fname, searchptr);
4542 return 0; /* Already included this file */
4544 else if (f == -1 && errno == EACCES)
4545 warning ("Header file %s exists, but is not readable", fname);
4553 /* A file that was not found. */
4555 strncpy (fname, (char *) fbeg, flen);
4557 /* If generating dependencies and -MG was specified, we assume missing
4558 files are leaf files, living in the same directory as the source file
4559 or other similar place; these missing files may be generated from
4560 other files and may not exist yet (eg: y.tab.h). */
4561 if (print_deps_missing_files
4562 && print_deps > (angle_brackets || (system_include_depth > 0)))
4564 /* If it was requested as a system header file,
4565 then assume it belongs in the first place to look for such. */
4568 for (searchptr = search_start; searchptr; searchptr = searchptr->next)
4570 if (searchptr->fname)
4574 if (searchptr->fname[0] == 0)
4576 p = xmalloc (strlen (searchptr->fname)
4577 + strlen (fname) + 2);
4578 strcpy (p, searchptr->fname);
4581 deps_output (p, ' ');
4588 /* Otherwise, omit the directory, as if the file existed
4589 in the directory with the source. */
4590 deps_output (fname, ' ');
4593 /* If -M was specified, and this header file won't be added to the
4594 dependency list, then don't count this as an error, because we can
4595 still produce correct output. Otherwise, we can't produce correct
4596 output, because there may be dependencies we need inside the missing
4597 file, and we don't know what directory this missing file exists in. */
4599 && (print_deps <= (angle_brackets || (system_include_depth > 0))))
4600 warning ("No include path in which to find %s", fname);
4601 else if (search_start)
4602 error_from_errno (fname);
4604 error ("No include path in which to find %s", fname);
4606 /* Check to see if this include file is a once-only include file.
4609 struct file_name_list* ptr;
4611 for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
4612 if (!strcmp (ptr->fname, fname)) {
4614 return 0; /* This file was once'd. */
4618 for (ptr = all_include_files; ptr; ptr = ptr->next) {
4619 if (!strcmp (ptr->fname, fname))
4620 break; /* This file was included before. */
4624 /* This is the first time for this file. */
4625 /* Add it to list of files included. */
4627 ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
4628 ptr->control_macro = 0;
4629 ptr->c_system_include_path = 0;
4630 ptr->next = all_include_files;
4631 all_include_files = ptr;
4632 ptr->fname = savestring (fname);
4633 ptr->got_name_map = 0;
4635 /* For -M, add this file to the dependencies. */
4636 if (print_deps > (angle_brackets || (system_include_depth > 0)))
4637 deps_output (fname, ' ');
4640 /* Handle -H option. */
4641 if (print_include_names) {
4642 output_dots (stderr, indepth);
4643 fprintf (stderr, "%s\n", fname);
4647 system_include_depth++;
4649 /* Actually process the file. */
4650 add_import (f, fname); /* Record file on "seen" list for #import. */
4652 pcftry = (char *) alloca (strlen (fname) + 30);
4663 sprintf (pcftry, "%s%d", fname, pcfnum++);
4665 pcf = open (pcftry, O_RDONLY, 0666);
4671 if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
4673 || stat_f.st_dev != s.st_dev)
4675 pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
4676 /* Don't need it any more. */
4681 /* Don't need it at all. */
4686 } while (pcf != -1 && !pcfbuf);
4689 /* Actually process the file */
4691 pcfname = xmalloc (strlen (pcftry) + 1);
4692 strcpy (pcfname, pcftry);
4693 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4694 (U_CHAR *) fname, op);
4697 finclude (f, fname, op, is_system_include (fname), searchptr);
4700 system_include_depth--;
4705 /* Return nonzero if there is no need to include file NAME
4706 because it has already been included and it contains a conditional
4707 to make a repeated include do nothing. */
4710 redundant_include_p (name)
4713 struct file_name_list *l = all_include_files;
4714 for (; l; l = l->next)
4715 if (! strcmp (name, l->fname)
4717 && lookup (l->control_macro, -1, -1))
4722 /* Return nonzero if the given FILENAME is an absolute pathname which
4723 designates a file within one of the known "system" include file
4724 directories. We assume here that if the given FILENAME looks like
4725 it is the name of a file which resides either directly in a "system"
4726 include file directory, or within any subdirectory thereof, then the
4727 given file must be a "system" include file. This function tells us
4728 if we should suppress pedantic errors/warnings for the given FILENAME.
4730 The value is 2 if the file is a C-language system header file
4731 for which C++ should (on most systems) assume `extern "C"'. */
4734 is_system_include (filename)
4735 register char *filename;
4737 struct file_name_list *searchptr;
4739 for (searchptr = first_system_include; searchptr;
4740 searchptr = searchptr->next)
4741 if (searchptr->fname) {
4742 register char *sys_dir = searchptr->fname;
4743 register unsigned length = strlen (sys_dir);
4745 if (! strncmp (sys_dir, filename, length)
4746 && (filename[length] == '/'
4747 #ifdef DIR_SEPARATOR
4748 || filename[length] == DIR_SEPARATOR
4751 if (searchptr->c_system_include_path)
4760 /* The file_name_map structure holds a mapping of file names for a
4761 particular directory. This mapping is read from the file named
4762 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4763 map filenames on a file system with severe filename restrictions,
4764 such as DOS. The format of the file name map file is just a series
4765 of lines with two tokens on each line. The first token is the name
4766 to map, and the second token is the actual name to use. */
4768 struct file_name_map
4770 struct file_name_map *map_next;
4775 #define FILE_NAME_MAP_FILE "header.gcc"
4777 /* Read a space delimited string of unlimited length from a stdio
4781 read_filename_string (ch, f)
4789 set = alloc = xmalloc (len + 1);
4793 while ((ch = getc (f)) != EOF && ! is_space[ch])
4795 if (set - alloc == len)
4798 alloc = xrealloc (alloc, len + 1);
4799 set = alloc + len / 2;
4809 /* Read the file name map file for DIRNAME. */
4811 static struct file_name_map *
4812 read_name_map (dirname)
4815 /* This structure holds a linked list of file name maps, one per
4817 struct file_name_map_list
4819 struct file_name_map_list *map_list_next;
4820 char *map_list_name;
4821 struct file_name_map *map_list_map;
4823 static struct file_name_map_list *map_list;
4824 register struct file_name_map_list *map_list_ptr;
4828 for (map_list_ptr = map_list; map_list_ptr;
4829 map_list_ptr = map_list_ptr->map_list_next)
4830 if (! strcmp (map_list_ptr->map_list_name, dirname))
4831 return map_list_ptr->map_list_map;
4833 map_list_ptr = ((struct file_name_map_list *)
4834 xmalloc (sizeof (struct file_name_map_list)));
4835 map_list_ptr->map_list_name = savestring (dirname);
4836 map_list_ptr->map_list_map = NULL;
4838 name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
4839 strcpy (name, dirname);
4842 strcat (name, FILE_NAME_MAP_FILE);
4843 f = fopen (name, "r");
4845 map_list_ptr->map_list_map = NULL;
4849 int dirlen = strlen (dirname);
4851 while ((ch = getc (f)) != EOF)
4854 struct file_name_map *ptr;
4858 from = read_filename_string (ch, f);
4859 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4861 to = read_filename_string (ch, f);
4863 ptr = ((struct file_name_map *)
4864 xmalloc (sizeof (struct file_name_map)));
4865 ptr->map_from = from;
4867 /* Make the real filename absolute. */
4872 ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
4873 strcpy (ptr->map_to, dirname);
4874 ptr->map_to[dirlen] = '/';
4875 strcpy (ptr->map_to + dirlen + 1, to);
4879 ptr->map_next = map_list_ptr->map_list_map;
4880 map_list_ptr->map_list_map = ptr;
4882 while ((ch = getc (f)) != '\n')
4889 map_list_ptr->map_list_next = map_list;
4890 map_list = map_list_ptr;
4892 return map_list_ptr->map_list_map;
4895 /* Try to open include file FILENAME. SEARCHPTR is the directory
4896 being tried from the include file search path. This function maps
4897 filenames on file systems based on information read by
4901 open_include_file (filename, searchptr)
4903 struct file_name_list *searchptr;
4905 register struct file_name_map *map;
4906 register char *from;
4909 if (searchptr && ! searchptr->got_name_map)
4911 searchptr->name_map = read_name_map (searchptr->fname
4912 ? searchptr->fname : ".");
4913 searchptr->got_name_map = 1;
4916 /* First check the mapping for the directory we are using. */
4917 if (searchptr && searchptr->name_map)
4920 if (searchptr->fname)
4921 from += strlen (searchptr->fname) + 1;
4922 for (map = searchptr->name_map; map; map = map->map_next)
4924 if (! strcmp (map->map_from, from))
4926 /* Found a match. */
4927 return open (map->map_to, O_RDONLY, 0666);
4932 /* Try to find a mapping file for the particular directory we are
4933 looking in. Thus #include <sys/types.h> will look up sys/types.h
4934 in /usr/include/header.gcc and look up types.h in
4935 /usr/include/sys/header.gcc. */
4936 p = rindex (filename, '/');
4937 #ifdef DIR_SEPARATOR
4938 if (! p) p = rindex (filename, DIR_SEPARATOR);
4940 char *tmp = rindex (filename, DIR_SEPARATOR);
4941 if (tmp != NULL && tmp > p) p = tmp;
4948 && strlen (searchptr->fname) == p - filename
4949 && ! strncmp (searchptr->fname, filename, p - filename))
4951 /* FILENAME is in SEARCHPTR, which we've already checked. */
4952 return open (filename, O_RDONLY, 0666);
4962 dir = (char *) alloca (p - filename + 1);
4963 bcopy (filename, dir, p - filename);
4964 dir[p - filename] = '\0';
4967 for (map = read_name_map (dir); map; map = map->map_next)
4968 if (! strcmp (map->map_from, from))
4969 return open (map->map_to, O_RDONLY, 0666);
4971 return open (filename, O_RDONLY, 0666);
4974 /* Process the contents of include file FNAME, already open on descriptor F,
4976 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4977 "system" include directories (as decided by the `is_system_include'
4979 DIRPTR is the link in the dir path through which this file was found,
4980 or 0 if the file name was absolute. */
4983 finclude (f, fname, op, system_header_p, dirptr)
4987 int system_header_p;
4988 struct file_name_list *dirptr;
4993 FILE_BUF *fp; /* For input stack frame */
4994 int missing_newline = 0;
4996 CHECK_DEPTH (return;);
4998 if (file_size_and_mode (f, &st_mode, &st_size) < 0)
5000 perror_with_name (fname);
5005 fp = &instack[indepth + 1];
5006 bzero ((char *) fp, sizeof (FILE_BUF));
5007 fp->nominal_fname = fp->fname = fname;
5010 fp->if_stack = if_stack;
5011 fp->system_header_p = system_header_p;
5014 if (S_ISREG (st_mode)) {
5015 fp->buf = (U_CHAR *) xmalloc (st_size + 2);
5018 /* Read the file contents, knowing that st_size is an upper bound
5019 on the number of bytes we can read. */
5020 fp->length = safe_read (f, (char *) fp->buf, st_size);
5021 if (fp->length < 0) goto nope;
5023 else if (S_ISDIR (st_mode)) {
5024 error ("directory `%s' specified in #include", fname);
5028 /* Cannot count its file size before reading.
5029 First read the entire file into heap and
5030 copy them into buffer on stack. */
5035 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5038 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5040 goto nope; /* error! */
5042 if (st_size != bsize)
5043 break; /* End of file */
5045 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5048 fp->length = st_size;
5051 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5052 /* Backslash-newline at end is not good enough. */
5053 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5054 fp->buf[fp->length++] = '\n';
5055 missing_newline = 1;
5057 fp->buf[fp->length] = '\0';
5059 /* Close descriptor now, so nesting does not use lots of descriptors. */
5062 /* Must do this before calling trigraph_pcp, so that the correct file name
5063 will be printed in warning messages. */
5066 input_file_stack_tick++;
5071 output_line_directive (fp, op, 0, enter_file);
5074 if (missing_newline)
5077 if (pedantic && missing_newline)
5078 pedwarn ("file does not end in newline");
5081 input_file_stack_tick++;
5082 output_line_directive (&instack[indepth], op, 0, leave_file);
5088 perror_with_name (fname);
5093 /* Record that inclusion of the file named FILE
5094 should be controlled by the macro named MACRO_NAME.
5095 This means that trying to include the file again
5096 will do something if that macro is defined. */
5099 record_control_macro (file, macro_name)
5103 struct file_name_list *new;
5105 for (new = all_include_files; new; new = new->next) {
5106 if (!strcmp (new->fname, file)) {
5107 new->control_macro = macro_name;
5112 /* If the file is not in all_include_files, something's wrong. */
5116 /* Maintain and search list of included files, for #import. */
5118 #define IMPORT_HASH_SIZE 31
5120 struct import_file {
5124 struct import_file *next;
5127 /* Hash table of files already included with #include or #import. */
5129 static struct import_file *import_hash_table[IMPORT_HASH_SIZE];
5131 /* Hash a file name for import_hash_table. */
5139 while (*f) val += *f++;
5140 return (val%IMPORT_HASH_SIZE);
5143 /* Search for file FILENAME in import_hash_table.
5144 Return -2 if found, either a matching name or a matching inode.
5145 Otherwise, open the file and return a file descriptor if successful
5146 or -1 if unsuccessful. */
5149 lookup_import (filename, searchptr)
5151 struct file_name_list *searchptr;
5153 struct import_file *i;
5159 hashval = import_hash (filename);
5161 /* Attempt to find file in list of already included files */
5162 i = import_hash_table[hashval];
5165 if (!strcmp (filename, i->name))
5166 return -2; /* return found */
5169 /* Open it and try a match on inode/dev */
5170 fd = open_include_file (filename, searchptr);
5174 for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5175 i = import_hash_table[h];
5177 /* Compare the inode and the device.
5178 Supposedly on some systems the inode is not a scalar. */
5179 if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5180 && i->dev == sb.st_dev) {
5182 return -2; /* return found */
5187 return fd; /* Not found, return open file */
5190 /* Add the file FNAME, open on descriptor FD, to import_hash_table. */
5193 add_import (fd, fname)
5197 struct import_file *i;
5201 hashval = import_hash (fname);
5203 i = (struct import_file *)xmalloc (sizeof (struct import_file));
5204 i->name = xmalloc (strlen (fname)+1);
5205 strcpy (i->name, fname);
5206 bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5208 i->next = import_hash_table[hashval];
5209 import_hash_table[hashval] = i;
5212 /* Load the specified precompiled header into core, and verify its
5213 preconditions. PCF indicates the file descriptor to read, which must
5214 be a regular file. FNAME indicates the file name of the original
5215 header. *LIMIT will be set to an address one past the end of the file.
5216 If the preconditions of the file are not satisfied, the buffer is
5217 freed and we return 0. If the preconditions are satisfied, return
5218 the address of the buffer following the preconditions. The buffer, in
5219 this case, should never be freed because various pieces of it will
5220 be referred to until all precompiled strings are output at the end of
5224 check_precompiled (pcf, fname, limit)
5238 if (file_size_and_mode (pcf, &st_mode, &st_size) < 0)
5241 if (S_ISREG (st_mode))
5243 buf = xmalloc (st_size + 2);
5244 length = safe_read (pcf, buf, st_size);
5251 if (length > 0 && buf[length-1] != '\n')
5252 buf[length++] = '\n';
5255 *limit = buf + length;
5257 /* File is in core. Check the preconditions. */
5258 if (!check_preconditions (buf))
5260 for (cp = buf; *cp; cp++)
5263 fprintf (stderr, "Using preinclude %s\n", fname);
5269 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5275 /* PREC (null terminated) points to the preconditions of a
5276 precompiled header. These are a series of #define and #undef
5277 lines which must match the current contents of the hash
5280 check_preconditions (prec)
5287 lineend = index (prec, '\n');
5289 if (*prec++ != '#') {
5290 error ("Bad format encountered while reading precompiled file");
5293 if (!strncmp (prec, "define", 6)) {
5297 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5302 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5303 || (hp->type != T_MACRO && hp->type != T_CONST)
5304 || (hp->type == T_MACRO
5305 && !compare_defs (mdef.defn, hp->value.defn)
5306 && (mdef.defn->length != 2
5307 || mdef.defn->expansion[0] != '\n'
5308 || mdef.defn->expansion[1] != ' ')))
5310 } else if (!strncmp (prec, "undef", 5)) {
5315 while (is_hor_space[(U_CHAR) *prec])
5318 while (is_idchar[(U_CHAR) *prec])
5322 if (lookup ((U_CHAR *) name, len, -1))
5325 error ("Bad format encountered while reading precompiled file");
5330 /* They all passed successfully */
5334 /* Process the main body of a precompiled file. BUF points to the
5335 string section of the file, following the preconditions. LIMIT is one
5336 character past the end. NAME is the name of the file being read
5337 in. OP is the main output buffer */
5339 pcfinclude (buf, limit, name, op)
5340 U_CHAR *buf, *limit, *name;
5347 /* First in the file comes 4 bytes indicating the number of strings, */
5348 /* in network byte order. (MSB first). */
5350 nstrings = (nstrings << 8) | *cp++;
5351 nstrings = (nstrings << 8) | *cp++;
5352 nstrings = (nstrings << 8) | *cp++;
5354 /* Looping over each string... */
5355 while (nstrings--) {
5356 U_CHAR *string_start;
5357 U_CHAR *endofthiskey;
5361 /* Each string starts with a STRINGDEF structure (str), followed */
5362 /* by the text of the string (string_start) */
5364 /* First skip to a longword boundary */
5365 /* ??? Why a 4-byte boundary? On all machines? */
5366 /* NOTE: This works correctly even if HOST_WIDE_INT
5367 is narrower than a pointer.
5368 Do not try risky measures here to get another type to use!
5369 Do not include stddef.h--it will fail! */
5370 if ((HOST_WIDE_INT) cp & 3)
5371 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5373 /* Now get the string. */
5374 str = (STRINGDEF *) (GENERIC_PTR) cp;
5375 string_start = cp += sizeof (STRINGDEF);
5377 for (; *cp; cp++) /* skip the string */
5380 /* We need to macro expand the string here to ensure that the
5381 proper definition environment is in place. If it were only
5382 expanded when we find out it is needed, macros necessary for
5383 its proper expansion might have had their definitions changed. */
5384 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5385 /* Lineno is already set in the precompiled file */
5386 str->contents = tmpbuf.buf;
5387 str->len = tmpbuf.length;
5389 str->filename = name;
5390 str->output_mark = outbuf.bufp - outbuf.buf;
5393 *stringlist_tailp = str;
5394 stringlist_tailp = &str->chain;
5396 /* Next comes a fourbyte number indicating the number of keys */
5397 /* for this string. */
5399 nkeys = (nkeys << 8) | *cp++;
5400 nkeys = (nkeys << 8) | *cp++;
5401 nkeys = (nkeys << 8) | *cp++;
5403 /* If this number is -1, then the string is mandatory. */
5407 /* Otherwise, for each key, */
5408 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5409 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5412 /* It starts with a KEYDEF structure */
5413 cp += sizeof (KEYDEF);
5415 /* Find the end of the key. At the end of this for loop we
5416 advance CP to the start of the next key using this variable. */
5417 endofthiskey = cp + strlen ((char *) cp);
5420 /* Expand the key, and enter it into the hash table. */
5421 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5422 tmpbuf.bufp = tmpbuf.buf;
5424 while (is_hor_space[*tmpbuf.bufp])
5426 if (!is_idstart[*tmpbuf.bufp]
5427 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5432 hp = lookup (tmpbuf.bufp, -1, -1);
5435 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5437 else if (hp->type == T_PCSTRING) {
5438 kp->chain = hp->value.keydef;
5439 hp->value.keydef = kp;
5445 /* This output_line_directive serves to switch us back to the current
5446 input file in case some of these strings get output (which will
5447 result in line directives for the header file being output). */
5448 output_line_directive (&instack[indepth], op, 0, enter_file);
5451 /* Called from rescan when it hits a key for strings. Mark them all */
5452 /* used and clean up. */
5459 for (kp = hp->value.keydef; kp; kp = kp->chain)
5460 kp->str->writeflag = 1;
5464 /* Write the output, interspersing precompiled strings in their */
5465 /* appropriate places. */
5469 STRINGDEF *next_string;
5470 U_CHAR *cur_buf_loc;
5471 int line_directive_len = 80;
5472 char *line_directive = xmalloc (line_directive_len);
5475 /* In each run through the loop, either cur_buf_loc == */
5476 /* next_string_loc, in which case we print a series of strings, or */
5477 /* it is less than next_string_loc, in which case we write some of */
5479 cur_buf_loc = outbuf.buf;
5480 next_string = stringlist;
5482 while (cur_buf_loc < outbuf.bufp || next_string) {
5484 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5485 if (next_string->writeflag) {
5486 len = 4 * strlen ((char *) next_string->filename) + 32;
5487 while (len > line_directive_len)
5488 line_directive = xrealloc (line_directive,
5489 line_directive_len *= 2);
5490 sprintf (line_directive, "\n# %d ", next_string->lineno);
5491 strcpy (quote_string (line_directive + strlen (line_directive),
5492 (char *) next_string->filename),
5494 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5495 safe_write (fileno (stdout),
5496 (char *) next_string->contents, next_string->len);
5498 next_string = next_string->chain;
5502 ? (next_string->output_mark
5503 - (cur_buf_loc - outbuf.buf))
5504 : outbuf.bufp - cur_buf_loc);
5506 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5510 free (line_directive);
5513 /* Pass a directive through to the output file.
5514 BUF points to the contents of the directive, as a contiguous string.
5515 LIMIT points to the first character past the end of the directive.
5516 KEYWORD is the keyword-table entry for the directive. */
5519 pass_thru_directive (buf, limit, op, keyword)
5520 U_CHAR *buf, *limit;
5522 struct directive *keyword;
5524 register unsigned keyword_length = keyword->length;
5526 check_expand (op, 1 + keyword_length + (limit - buf));
5528 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5529 op->bufp += keyword_length;
5530 if (limit != buf && buf[0] != ' ')
5532 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5533 op->bufp += (limit - buf);
5536 /* Count the line we have just made in the output,
5537 to get in sync properly. */
5542 /* The arglist structure is built by do_define to tell
5543 collect_definition where the argument names begin. That
5544 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5545 would contain pointers to the strings x, y, and z.
5546 Collect_definition would then build a DEFINITION node,
5547 with reflist nodes pointing to the places x, y, and z had
5548 appeared. So the arglist is just convenience data passed
5549 between these two routines. It is not kept around after
5550 the current #define has been processed and entered into the
5554 struct arglist *next;
5561 /* Create a DEFINITION node from a #define directive. Arguments are
5562 as for do_define. */
5564 create_definition (buf, limit, op)
5565 U_CHAR *buf, *limit;
5568 U_CHAR *bp; /* temp ptr into input buffer */
5569 U_CHAR *symname; /* remember where symbol name starts */
5570 int sym_length; /* and how long it is */
5571 int line = instack[indepth].lineno;
5572 char *file = instack[indepth].nominal_fname;
5576 int arglengths = 0; /* Accumulate lengths of arg names
5577 plus number of args. */
5582 while (is_hor_space[*bp])
5585 symname = bp; /* remember where it starts */
5586 sym_length = check_macro_name (bp, "macro");
5589 /* Lossage will occur if identifiers or control keywords are broken
5590 across lines using backslash. This is not the right place to take
5594 struct arglist *arg_ptrs = NULL;
5597 bp++; /* skip '(' */
5598 SKIP_WHITE_SPACE (bp);
5600 /* Loop over macro argument names. */
5601 while (*bp != ')') {
5602 struct arglist *temp;
5604 temp = (struct arglist *) alloca (sizeof (struct arglist));
5606 temp->next = arg_ptrs;
5607 temp->argno = argno++;
5608 temp->rest_args = 0;
5612 pedwarn ("another parameter follows `%s'",
5615 if (!is_idstart[*bp])
5616 pedwarn ("invalid character in macro parameter name");
5618 /* Find the end of the arg name. */
5619 while (is_idchar[*bp]) {
5621 /* do we have a "special" rest-args extension here? */
5622 if (limit - bp > REST_EXTENSION_LENGTH &&
5623 bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5625 temp->rest_args = 1;
5629 temp->length = bp - temp->name;
5631 bp += REST_EXTENSION_LENGTH;
5632 arglengths += temp->length + 2;
5633 SKIP_WHITE_SPACE (bp);
5634 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5635 error ("badly punctuated parameter list in `#define'");
5640 SKIP_WHITE_SPACE (bp);
5641 /* A comma at this point can only be followed by an identifier. */
5642 if (!is_idstart[*bp]) {
5643 error ("badly punctuated parameter list in `#define'");
5648 error ("unterminated parameter list in `#define'");
5652 struct arglist *otemp;
5654 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5655 if (temp->length == otemp->length &&
5656 bcmp (temp->name, otemp->name, temp->length) == 0) {
5657 error ("duplicate argument name `%.*s' in `#define'",
5658 temp->length, temp->name);
5664 ++bp; /* skip paren */
5665 SKIP_WHITE_SPACE (bp);
5666 /* now everything from bp before limit is the definition. */
5667 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5668 defn->rest_args = rest_args;
5670 /* Now set defn->args.argnames to the result of concatenating
5671 the argument names in reverse order
5672 with comma-space between them. */
5673 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5675 struct arglist *temp;
5677 for (temp = arg_ptrs; temp; temp = temp->next) {
5678 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5680 if (temp->next != 0) {
5681 defn->args.argnames[i++] = ',';
5682 defn->args.argnames[i++] = ' ';
5685 defn->args.argnames[i] = 0;
5688 /* Simple expansion or empty definition. */
5692 if (is_hor_space[*bp]) {
5694 SKIP_WHITE_SPACE (bp);
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 '\\': case ']': case '^': case '{':
5701 case '|': case '}': case '~':
5702 warning ("missing white space after `#define %.*s'",
5703 sym_length, symname);
5707 pedwarn ("missing white space after `#define %.*s'",
5708 sym_length, symname);
5713 /* Now everything from bp before limit is the definition. */
5714 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5715 defn->args.argnames = (U_CHAR *) "";
5721 /* OP is null if this is a predefinition */
5722 defn->predefined = !op;
5724 mdef.symnam = symname;
5725 mdef.symlen = sym_length;
5734 /* Process a #define directive.
5735 BUF points to the contents of the #define directive, as a contiguous string.
5736 LIMIT points to the first character past the end of the definition.
5737 KEYWORD is the keyword-table entry for #define. */
5740 do_define (buf, limit, op, keyword)
5741 U_CHAR *buf, *limit;
5743 struct directive *keyword;
5748 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5749 if (pcp_outfile && op)
5750 pass_thru_directive (buf, limit, op, keyword);
5752 mdef = create_definition (buf, limit, op);
5756 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5760 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5762 /* Redefining a precompiled key is ok. */
5763 if (hp->type == T_PCSTRING)
5765 /* Redefining a macro is ok if the definitions are the same. */
5766 else if (hp->type == T_MACRO)
5767 ok = ! compare_defs (mdef.defn, hp->value.defn);
5768 /* Redefining a constant is ok with -D. */
5769 else if (hp->type == T_CONST)
5770 ok = ! done_initializing;
5771 /* Print the warning if it's not ok. */
5773 /* If we are passing through #define and #undef directives, do
5774 that for this re-definition now. */
5775 if (debug_output && op)
5776 pass_thru_directive (buf, limit, op, keyword);
5778 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5779 if (hp->type == T_MACRO)
5780 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5781 "this is the location of the previous definition");
5783 /* Replace the old definition. */
5785 hp->value.defn = mdef.defn;
5787 /* If we are passing through #define and #undef directives, do
5788 that for this new definition now. */
5789 if (debug_output && op)
5790 pass_thru_directive (buf, limit, op, keyword);
5791 install (mdef.symnam, mdef.symlen, T_MACRO,
5792 (char *) mdef.defn, hashcode);
5803 /* Check a purported macro name SYMNAME, and yield its length.
5804 USAGE is the kind of name this is intended for. */
5807 check_macro_name (symname, usage)
5814 for (p = symname; is_idchar[*p]; p++)
5816 sym_length = p - symname;
5817 if (sym_length == 0)
5818 error ("invalid %s name", usage);
5819 else if (!is_idstart[*symname]
5820 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5821 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5826 * return zero if two DEFINITIONs are isomorphic
5829 compare_defs (d1, d2)
5830 DEFINITION *d1, *d2;
5832 register struct reflist *a1, *a2;
5833 register U_CHAR *p1 = d1->expansion;
5834 register U_CHAR *p2 = d2->expansion;
5837 if (d1->nargs != d2->nargs)
5839 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5841 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5842 a1 = a1->next, a2 = a2->next) {
5843 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5844 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5845 || a1->argno != a2->argno
5846 || a1->stringify != a2->stringify
5847 || a1->raw_before != a2->raw_before
5848 || a1->raw_after != a2->raw_after)
5856 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5857 p2, d2->length - (p2 - d2->expansion), 1))
5862 /* Return 1 if two parts of two macro definitions are effectively different.
5863 One of the parts starts at BEG1 and has LEN1 chars;
5864 the other has LEN2 chars at BEG2.
5865 Any sequence of whitespace matches any other sequence of whitespace.
5866 FIRST means these parts are the first of a macro definition;
5867 so ignore leading whitespace entirely.
5868 LAST means these parts are the last of a macro definition;
5869 so ignore trailing whitespace entirely. */
5872 comp_def_part (first, beg1, len1, beg2, len2, last)
5874 U_CHAR *beg1, *beg2;
5878 register U_CHAR *end1 = beg1 + len1;
5879 register U_CHAR *end2 = beg2 + len2;
5881 while (beg1 != end1 && is_space[*beg1]) beg1++;
5882 while (beg2 != end2 && is_space[*beg2]) beg2++;
5885 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5886 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5888 while (beg1 != end1 && beg2 != end2) {
5889 if (is_space[*beg1] && is_space[*beg2]) {
5890 while (beg1 != end1 && is_space[*beg1]) beg1++;
5891 while (beg2 != end2 && is_space[*beg2]) beg2++;
5892 } else if (*beg1 == *beg2) {
5896 return (beg1 != end1) || (beg2 != end2);
5899 /* Read a replacement list for a macro with parameters.
5900 Build the DEFINITION structure.
5901 Reads characters of text starting at BUF until END.
5902 ARGLIST specifies the formal parameters to look for
5903 in the text of the definition; NARGS is the number of args
5904 in that list, or -1 for a macro name that wants no argument list.
5905 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5906 and NAMELEN is its length in characters.
5908 Note that comments and backslash-newlines have already been deleted
5909 from the argument. */
5911 /* Leading and trailing Space, Tab, etc. are converted to markers
5912 Newline Space, Newline Tab, etc.
5913 Newline Space makes a space in the final output
5914 but is discarded if stringified. (Newline Tab is similar but
5915 makes a Tab instead.)
5917 If there is no trailing whitespace, a Newline Space is added at the end
5918 to prevent concatenation that would be contrary to the standard. */
5921 collect_expansion (buf, end, nargs, arglist)
5924 struct arglist *arglist;
5927 register U_CHAR *p, *limit, *lastp, *exp_p;
5928 struct reflist *endpat = NULL;
5929 /* Pointer to first nonspace after last ## seen. */
5931 /* Pointer to first nonspace after last single-# seen. */
5932 U_CHAR *stringify = 0;
5933 /* How those tokens were spelled. */
5934 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5935 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5937 int expected_delimiter = '\0';
5939 /* Scan thru the replacement list, ignoring comments and quoted
5940 strings, picking up on the macro calls. It does a linear search
5941 thru the arg list on every potential symbol. Profiling might say
5942 that something smarter should happen. */
5947 /* Find the beginning of the trailing whitespace. */
5948 /* Find end of leading whitespace. */
5951 while (p < limit && is_space[limit[-1]]) limit--;
5952 while (p < limit && is_space[*p]) p++;
5954 /* Allocate space for the text in the macro definition.
5955 Leading and trailing whitespace chars need 2 bytes each.
5956 Each other input char may or may not need 1 byte,
5957 so this is an upper bound.
5958 The extra 2 are for invented trailing newline-marker and final null. */
5959 maxsize = (sizeof (DEFINITION)
5960 + 2 * (end - limit) + 2 * (p - buf)
5962 defn = (DEFINITION *) xcalloc (1, maxsize);
5964 defn->nargs = nargs;
5965 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5970 /* Convert leading whitespace to Newline-markers. */
5971 while (p < limit && is_space[*p]) {
5978 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5979 error ("`##' at start of macro definition");
5980 p += p[0] == '#' ? 2 : 4;
5983 /* Process the main body of the definition. */
5985 int skipped_arg = 0;
5986 register U_CHAR c = *p++;
5994 if (expected_delimiter != '\0') {
5995 if (c == expected_delimiter)
5996 expected_delimiter = '\0';
5998 expected_delimiter = c;
6002 if (p < limit && expected_delimiter) {
6003 /* In a string, backslash goes through
6004 and makes next char ordinary. */
6010 if (!expected_delimiter && *p == ':') {
6011 /* %: is not a digraph if preceded by an odd number of '<'s. */
6013 while (buf < p0 && p0[-1] == '<')
6016 /* Treat %:%: as ## and %: as #. */
6017 if (p[1] == '%' && p[2] == ':') {
6019 goto sharp_sharp_token;
6030 /* # is ordinary inside a string. */
6031 if (expected_delimiter)
6035 /* ##: concatenate preceding and following tokens. */
6036 /* Take out the first #, discard preceding whitespace. */
6038 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6040 /* Skip the second #. */
6042 concat_sharp_token_type = c;
6043 if (is_hor_space[*p]) {
6044 concat_sharp_token_type++;
6046 SKIP_WHITE_SPACE (p);
6050 error ("`##' at end of macro definition");
6051 } else if (nargs >= 0) {
6052 /* Single #: stringify following argument ref.
6053 Don't leave the # in the expansion. */
6056 stringify_sharp_token_type = c;
6057 if (is_hor_space[*p]) {
6058 stringify_sharp_token_type++;
6060 SKIP_WHITE_SPACE (p);
6062 if (! is_idstart[*p] || nargs == 0)
6063 error ("`#' operator is not followed by a macro argument name");
6070 /* In -traditional mode, recognize arguments inside strings and
6071 and character constants, and ignore special properties of #.
6072 Arguments inside strings are considered "stringified", but no
6073 extra quote marks are supplied. */
6077 if (expected_delimiter != '\0') {
6078 if (c == expected_delimiter)
6079 expected_delimiter = '\0';
6081 expected_delimiter = c;
6085 /* Backslash quotes delimiters and itself, but not macro args. */
6086 if (expected_delimiter != 0 && p < limit
6087 && (*p == expected_delimiter || *p == '\\')) {
6094 if (expected_delimiter != '\0') /* No comments inside strings. */
6097 /* If we find a comment that wasn't removed by handle_directive,
6098 this must be -traditional. So replace the comment with
6102 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
6105 /* Mark this as a concatenation-point, as if it had been ##. */
6113 /* Handle the start of a symbol. */
6114 if (is_idchar[c] && nargs > 0) {
6115 U_CHAR *id_beg = p - 1;
6119 while (p != limit && is_idchar[*p]) p++;
6120 id_len = p - id_beg;
6122 if (is_idstart[c]) {
6123 register struct arglist *arg;
6125 for (arg = arglist; arg != NULL; arg = arg->next) {
6126 struct reflist *tpat;
6128 if (arg->name[0] == c
6129 && arg->length == id_len
6130 && bcmp (arg->name, id_beg, id_len) == 0) {
6131 enum sharp_token_type tpat_stringify;
6132 if (expected_delimiter) {
6133 if (warn_stringify) {
6135 warning ("macro argument `%.*s' is stringified.",
6138 warning ("macro arg `%.*s' would be stringified with -traditional.",
6142 /* If ANSI, don't actually substitute inside a string. */
6145 tpat_stringify = SHARP_TOKEN;
6148 = (stringify == id_beg
6149 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6151 /* make a pat node for this arg and append it to the end of
6153 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6156 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6157 tpat->raw_after = NO_SHARP_TOKEN;
6158 tpat->rest_args = arg->rest_args;
6159 tpat->stringify = tpat_stringify;
6162 defn->pattern = tpat;
6164 endpat->next = tpat;
6167 tpat->argno = arg->argno;
6168 tpat->nchars = exp_p - lastp;
6170 register U_CHAR *p1 = p;
6171 SKIP_WHITE_SPACE (p1);
6174 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6175 tpat->raw_after = p1[0] + (p != p1);
6177 lastp = exp_p; /* place to start copying from next time */
6184 /* If this was not a macro arg, copy it into the expansion. */
6185 if (! skipped_arg) {
6186 register U_CHAR *lim1 = p;
6190 if (stringify == id_beg)
6191 error ("`#' operator should be followed by a macro argument name");
6196 if (!traditional && expected_delimiter == 0) {
6197 /* There is no trailing whitespace, so invent some in ANSI mode.
6198 But not if "inside a string" (which in ANSI mode
6199 happens only for -D option). */
6206 defn->length = exp_p - defn->expansion;
6208 /* Crash now if we overrun the allocated size. */
6209 if (defn->length + 1 > maxsize)
6213 /* This isn't worth the time it takes. */
6214 /* give back excess storage */
6215 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6222 do_assert (buf, limit, op, keyword)
6223 U_CHAR *buf, *limit;
6225 struct directive *keyword;
6227 U_CHAR *bp; /* temp ptr into input buffer */
6228 U_CHAR *symname; /* remember where symbol name starts */
6229 int sym_length; /* and how long it is */
6230 struct arglist *tokens = NULL;
6232 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6233 pedwarn ("ANSI C does not allow `#assert'");
6237 while (is_hor_space[*bp])
6240 symname = bp; /* remember where it starts */
6241 sym_length = check_macro_name (bp, "assertion");
6243 /* #define doesn't do this, but we should. */
6244 SKIP_WHITE_SPACE (bp);
6246 /* Lossage will occur if identifiers or control tokens are broken
6247 across lines using backslash. This is not the right place to take
6251 error ("missing token-sequence in `#assert'");
6258 bp++; /* skip '(' */
6259 SKIP_WHITE_SPACE (bp);
6261 tokens = read_token_list (&bp, limit, &error_flag);
6265 error ("empty token-sequence in `#assert'");
6269 ++bp; /* skip paren */
6270 SKIP_WHITE_SPACE (bp);
6273 /* If this name isn't already an assertion name, make it one.
6274 Error if it was already in use in some other way. */
6277 ASSERTION_HASHNODE *hp;
6278 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6279 struct tokenlist_list *value
6280 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6282 hp = assertion_lookup (symname, sym_length, hashcode);
6284 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6285 error ("`defined' redefined as assertion");
6286 hp = assertion_install (symname, sym_length, hashcode);
6289 /* Add the spec'd token-sequence to the list of such. */
6290 value->tokens = tokens;
6291 value->next = hp->value;
6299 do_unassert (buf, limit, op, keyword)
6300 U_CHAR *buf, *limit;
6302 struct directive *keyword;
6304 U_CHAR *bp; /* temp ptr into input buffer */
6305 U_CHAR *symname; /* remember where symbol name starts */
6306 int sym_length; /* and how long it is */
6308 struct arglist *tokens = NULL;
6309 int tokens_specified = 0;
6311 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6312 pedwarn ("ANSI C does not allow `#unassert'");
6316 while (is_hor_space[*bp])
6319 symname = bp; /* remember where it starts */
6320 sym_length = check_macro_name (bp, "assertion");
6322 /* #define doesn't do this, but we should. */
6323 SKIP_WHITE_SPACE (bp);
6325 /* Lossage will occur if identifiers or control tokens are broken
6326 across lines using backslash. This is not the right place to take
6332 bp++; /* skip '(' */
6333 SKIP_WHITE_SPACE (bp);
6335 tokens = read_token_list (&bp, limit, &error_flag);
6339 error ("empty token list in `#unassert'");
6343 tokens_specified = 1;
6345 ++bp; /* skip paren */
6346 SKIP_WHITE_SPACE (bp);
6350 ASSERTION_HASHNODE *hp;
6351 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6352 struct tokenlist_list *tail, *prev;
6354 hp = assertion_lookup (symname, sym_length, hashcode);
6358 /* If no token list was specified, then eliminate this assertion
6360 if (! tokens_specified) {
6361 struct tokenlist_list *next;
6362 for (tail = hp->value; tail; tail = next) {
6364 free_token_list (tail->tokens);
6367 delete_assertion (hp);
6369 /* If a list of tokens was given, then delete any matching list. */
6374 struct tokenlist_list *next = tail->next;
6375 if (compare_token_lists (tail->tokens, tokens)) {
6379 hp->value = tail->next;
6380 free_token_list (tail->tokens);
6393 /* Test whether there is an assertion named NAME
6394 and optionally whether it has an asserted token list TOKENS.
6395 NAME is not null terminated; its length is SYM_LENGTH.
6396 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6399 check_assertion (name, sym_length, tokens_specified, tokens)
6402 int tokens_specified;
6403 struct arglist *tokens;
6405 ASSERTION_HASHNODE *hp;
6406 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6408 if (pedantic && !instack[indepth].system_header_p)
6409 pedwarn ("ANSI C does not allow testing assertions");
6411 hp = assertion_lookup (name, sym_length, hashcode);
6413 /* It is not an assertion; just return false. */
6416 /* If no token list was specified, then value is 1. */
6417 if (! tokens_specified)
6421 struct tokenlist_list *tail;
6425 /* If a list of tokens was given,
6426 then succeed if the assertion records a matching list. */
6429 if (compare_token_lists (tail->tokens, tokens))
6434 /* Fail if the assertion has no matching list. */
6439 /* Compare two lists of tokens for equality including order of tokens. */
6442 compare_token_lists (l1, l2)
6443 struct arglist *l1, *l2;
6446 if (l1->length != l2->length)
6448 if (bcmp (l1->name, l2->name, l1->length))
6454 /* Succeed if both lists end at the same time. */
6458 /* Read a space-separated list of tokens ending in a close parenthesis.
6459 Return a list of strings, in the order they were written.
6460 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6461 Parse the text starting at *BPP, and update *BPP.
6462 Don't parse beyond LIMIT. */
6464 static struct arglist *
6465 read_token_list (bpp, limit, error_flag)
6470 struct arglist *token_ptrs = 0;
6476 /* Loop over the assertion value tokens. */
6478 struct arglist *temp;
6482 /* Find the end of the token. */
6486 } else if (*bp == ')') {
6491 } else if (*bp == '"' || *bp == '\'')
6492 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6494 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6495 && *bp != '"' && *bp != '\'' && bp != limit)
6498 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6499 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6500 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6501 temp->name[bp - beg] = 0;
6502 temp->next = token_ptrs;
6504 temp->length = bp - beg;
6506 SKIP_WHITE_SPACE (bp);
6509 error ("unterminated token sequence in `#assert' or `#unassert'");
6516 /* We accumulated the names in reverse order.
6517 Now reverse them to get the proper order. */
6519 register struct arglist *prev = 0, *this, *next;
6520 for (this = token_ptrs; this; this = next) {
6530 free_token_list (tokens)
6531 struct arglist *tokens;
6534 struct arglist *next = tokens->next;
6535 free (tokens->name);
6542 * Install a name in the assertion hash table.
6544 * If LEN is >= 0, it is the length of the name.
6545 * Otherwise, compute the length by scanning the entire name.
6547 * If HASH is >= 0, it is the precomputed hash code.
6548 * Otherwise, compute the hash code.
6550 static ASSERTION_HASHNODE *
6551 assertion_install (name, len, hash)
6556 register ASSERTION_HASHNODE *hp;
6557 register int i, bucket;
6558 register U_CHAR *p, *q;
6560 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6561 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6563 hp->bucket_hdr = &assertion_hashtab[bucket];
6564 hp->next = assertion_hashtab[bucket];
6565 assertion_hashtab[bucket] = hp;
6567 if (hp->next != NULL)
6568 hp->next->prev = hp;
6571 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6574 for (i = 0; i < len; i++)
6581 * find the most recent hash node for name name (ending with first
6582 * non-identifier char) installed by install
6584 * If LEN is >= 0, it is the length of the name.
6585 * Otherwise, compute the length by scanning the entire name.
6587 * If HASH is >= 0, it is the precomputed hash code.
6588 * Otherwise, compute the hash code.
6590 static ASSERTION_HASHNODE *
6591 assertion_lookup (name, len, hash)
6596 register ASSERTION_HASHNODE *bucket;
6598 bucket = assertion_hashtab[hash];
6600 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6602 bucket = bucket->next;
6608 delete_assertion (hp)
6609 ASSERTION_HASHNODE *hp;
6612 if (hp->prev != NULL)
6613 hp->prev->next = hp->next;
6614 if (hp->next != NULL)
6615 hp->next->prev = hp->prev;
6617 /* make sure that the bucket chain header that
6618 the deleted guy was on points to the right thing afterwards. */
6619 if (hp == *hp->bucket_hdr)
6620 *hp->bucket_hdr = hp->next;
6626 * interpret #line directive. Remembers previously seen fnames
6627 * in its very own hash table.
6629 #define FNAME_HASHSIZE 37
6632 do_line (buf, limit, op, keyword)
6633 U_CHAR *buf, *limit;
6635 struct directive *keyword;
6637 register U_CHAR *bp;
6638 FILE_BUF *ip = &instack[indepth];
6641 enum file_change_code file_change = same_file;
6643 /* Expand any macros. */
6644 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6646 /* Point to macroexpanded line, which is null-terminated now. */
6648 SKIP_WHITE_SPACE (bp);
6650 if (!isdigit (*bp)) {
6651 error ("invalid format `#line' directive");
6655 /* The Newline at the end of this line remains to be processed.
6656 To put the next line at the specified line number,
6657 we must store a line number now that is one less. */
6658 new_lineno = atoi ((char *) bp) - 1;
6660 /* NEW_LINENO is one less than the actual line number here. */
6661 if (pedantic && new_lineno < 0)
6662 pedwarn ("line number out of range in `#line' directive");
6664 /* skip over the line number. */
6665 while (isdigit (*bp))
6668 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6669 if (*bp && !is_space[*bp]) {
6670 error ("invalid format `#line' directive");
6675 SKIP_WHITE_SPACE (bp);
6678 static HASHNODE *fname_table[FNAME_HASHSIZE];
6679 HASHNODE *hp, **hash_bucket;
6685 /* Turn the file name, which is a character string literal,
6686 into a null-terminated string. Do this in place. */
6689 switch ((*p++ = *bp++)) {
6691 error ("invalid format `#line' directive");
6696 char *bpc = (char *) bp;
6697 int c = parse_escape (&bpc);
6698 bp = (U_CHAR *) bpc;
6711 fname_length = p - fname;
6713 SKIP_WHITE_SPACE (bp);
6716 pedwarn ("garbage at end of `#line' directive");
6718 file_change = enter_file;
6719 else if (*bp == '2')
6720 file_change = leave_file;
6721 else if (*bp == '3')
6722 ip->system_header_p = 1;
6723 else if (*bp == '4')
6724 ip->system_header_p = 2;
6726 error ("invalid format `#line' directive");
6731 SKIP_WHITE_SPACE (bp);
6733 ip->system_header_p = 1;
6735 SKIP_WHITE_SPACE (bp);
6738 ip->system_header_p = 2;
6740 SKIP_WHITE_SPACE (bp);
6743 error ("invalid format `#line' directive");
6749 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6750 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6751 if (hp->length == fname_length &&
6752 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6753 ip->nominal_fname = hp->value.cpval;
6757 /* Didn't find it; cons up a new one. */
6758 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6759 hp->next = *hash_bucket;
6762 hp->length = fname_length;
6763 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6764 bcopy (fname, hp->value.cpval, fname_length);
6767 error ("invalid format `#line' directive");
6771 ip->lineno = new_lineno;
6772 output_line_directive (ip, op, 0, file_change);
6773 check_expand (op, ip->length - (ip->bufp - ip->buf));
6778 * remove the definition of a symbol from the symbol table.
6779 * according to un*x /lib/cpp, it is not an error to undef
6780 * something that has no definitions, so it isn't one here either.
6784 do_undef (buf, limit, op, keyword)
6785 U_CHAR *buf, *limit;
6787 struct directive *keyword;
6791 U_CHAR *orig_buf = buf;
6793 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6794 if (pcp_outfile && op)
6795 pass_thru_directive (buf, limit, op, keyword);
6797 SKIP_WHITE_SPACE (buf);
6798 sym_length = check_macro_name (buf, "macro");
6800 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6801 /* If we are generating additional info for debugging (with -g) we
6802 need to pass through all effective #undef directives. */
6803 if (debug_output && op)
6804 pass_thru_directive (orig_buf, limit, op, keyword);
6805 if (hp->type != T_MACRO)
6806 warning ("undefining `%s'", hp->name);
6812 SKIP_WHITE_SPACE (buf);
6814 pedwarn ("garbage after `#undef' directive");
6820 * Report an error detected by the program we are processing.
6821 * Use the text of the line in the error message.
6822 * (We use error because it prints the filename & line#.)
6826 do_error (buf, limit, op, keyword)
6827 U_CHAR *buf, *limit;
6829 struct directive *keyword;
6831 int length = limit - buf;
6832 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6833 bcopy ((char *) buf, (char *) copy, length);
6835 SKIP_WHITE_SPACE (copy);
6836 error ("#error %s", copy);
6841 * Report a warning detected by the program we are processing.
6842 * Use the text of the line in the warning message, then continue.
6843 * (We use error because it prints the filename & line#.)
6847 do_warning (buf, limit, op, keyword)
6848 U_CHAR *buf, *limit;
6850 struct directive *keyword;
6852 int length = limit - buf;
6853 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6854 bcopy ((char *) buf, (char *) copy, length);
6856 SKIP_WHITE_SPACE (copy);
6857 warning ("#warning %s", copy);
6861 /* Remember the name of the current file being read from so that we can
6862 avoid ever including it again. */
6868 FILE_BUF *ip = NULL;
6870 for (i = indepth; i >= 0; i--)
6871 if (instack[i].fname != NULL) {
6877 struct file_name_list *new;
6879 new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
6880 new->next = dont_repeat_files;
6881 dont_repeat_files = new;
6882 new->fname = savestring (ip->fname);
6883 new->control_macro = 0;
6884 new->got_name_map = 0;
6885 new->c_system_include_path = 0;
6889 /* #ident has already been copied to the output file, so just ignore it. */
6892 do_ident (buf, limit, op, keyword)
6893 U_CHAR *buf, *limit;
6895 struct directive *keyword;
6900 /* Allow #ident in system headers, since that's not user's fault. */
6901 if (pedantic && !instack[indepth].system_header_p)
6902 pedwarn ("ANSI C does not allow `#ident'");
6904 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6905 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6906 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6907 limit = buf + (trybuf.bufp - trybuf.buf);
6908 len = (limit - buf);
6911 /* Output directive name. */
6912 check_expand (op, 7);
6913 bcopy ("#ident ", (char *) op->bufp, 7);
6916 /* Output the expanded argument line. */
6917 check_expand (op, len);
6918 bcopy ((char *) buf, (char *) op->bufp, len);
6924 /* #pragma and its argument line have already been copied to the output file.
6925 Just check for some recognized pragmas that need validation here. */
6928 do_pragma (buf, limit, op, keyword)
6929 U_CHAR *buf, *limit;
6931 struct directive *keyword;
6933 SKIP_WHITE_SPACE (buf);
6934 if (!strncmp ((char *) buf, "once", 4)) {
6935 /* Allow #pragma once in system headers, since that's not the user's
6937 if (!instack[indepth].system_header_p)
6938 warning ("`#pragma once' is obsolete");
6942 if (!strncmp ((char *) buf, "implementation", 14)) {
6943 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6944 been included yet. */
6945 struct file_name_list *ptr;
6946 U_CHAR *p = buf + 14, *fname, *inc_fname;
6947 SKIP_WHITE_SPACE (p);
6948 if (*p == '\n' || *p != '\"')
6952 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6955 for (ptr = all_include_files; ptr; ptr = ptr->next) {
6956 inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
6957 inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
6958 if (inc_fname && !strcmp ((char *) inc_fname, (char *) fname))
6959 warning ("`#pragma implementation' for `%s' appears after file is included",
6968 /* This was a fun hack, but #pragma seems to start to be useful.
6969 By failing to recognize it, we pass it through unchanged to cc1. */
6972 * the behavior of the #pragma directive is implementation defined.
6973 * this implementation defines it as follows.
6980 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6983 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6985 execl ("/usr/games/hack", "#pragma", 0);
6986 execl ("/usr/games/rogue", "#pragma", 0);
6987 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6988 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6990 fatal ("You are in a maze of twisty compiler features, all different");
6994 #ifdef SCCS_DIRECTIVE
6996 /* Just ignore #sccs, on systems where we define it at all. */
6999 do_sccs (buf, limit, op, keyword)
7000 U_CHAR *buf, *limit;
7002 struct directive *keyword;
7005 pedwarn ("ANSI C does not allow `#sccs'");
7009 #endif /* defined (SCCS_DIRECTIVE) */
7012 * handle #if directive by
7013 * 1) inserting special `defined' keyword into the hash table
7014 * that gets turned into 0 or 1 by special_symbol (thus,
7015 * if the luser has a symbol called `defined' already, it won't
7016 * work inside the #if directive)
7017 * 2) rescan the input into a temporary output buffer
7018 * 3) pass the output buffer to the yacc parser and collect a value
7019 * 4) clean up the mess left from steps 1 and 2.
7020 * 5) call conditional_skip to skip til the next #endif (etc.),
7021 * or not, depending on the value from step 3.
7025 do_if (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 value = eval_if_expression (buf, limit - buf);
7034 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7039 * handle a #elif directive by not changing if_stack either.
7040 * see the comment above do_else.
7044 do_elif (buf, limit, op, keyword)
7045 U_CHAR *buf, *limit;
7047 struct directive *keyword;
7049 HOST_WIDE_INT value;
7050 FILE_BUF *ip = &instack[indepth];
7052 if (if_stack == instack[indepth].if_stack) {
7053 error ("`#elif' not within a conditional");
7056 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7057 error ("`#elif' after `#else'");
7058 fprintf (stderr, " (matches line %d", if_stack->lineno);
7059 if (if_stack->fname != NULL && ip->fname != NULL &&
7060 strcmp (if_stack->fname, ip->nominal_fname) != 0)
7061 fprintf (stderr, ", file %s", if_stack->fname);
7062 fprintf (stderr, ")\n");
7064 if_stack->type = T_ELIF;
7067 if (if_stack->if_succeeded)
7068 skip_if_group (ip, 0, op);
7070 value = eval_if_expression (buf, limit - buf);
7072 skip_if_group (ip, 0, op);
7074 ++if_stack->if_succeeded; /* continue processing input */
7075 output_line_directive (ip, op, 1, same_file);
7082 * evaluate a #if expression in BUF, of length LENGTH,
7083 * then parse the result as a C expression and return the value as an int.
7085 static HOST_WIDE_INT
7086 eval_if_expression (buf, length)
7091 HASHNODE *save_defined;
7092 HOST_WIDE_INT value;
7094 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7097 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7099 delete_macro (save_defined); /* clean up special symbol */
7101 value = parse_c_expression ((char *) temp_obuf.buf);
7103 free (temp_obuf.buf);
7109 * routine to handle ifdef/ifndef. Try to look up the symbol,
7110 * then do or don't skip to the #endif/#else/#elif depending
7111 * on what directive is actually being processed.
7115 do_xifdef (buf, limit, op, keyword)
7116 U_CHAR *buf, *limit;
7118 struct directive *keyword;
7121 FILE_BUF *ip = &instack[indepth];
7123 int start_of_file = 0;
7124 U_CHAR *control_macro = 0;
7126 /* Detect a #ifndef at start of file (not counting comments). */
7127 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7128 U_CHAR *p = ip->buf;
7129 while (p != directive_start) {
7133 /* Make no special provision for backslash-newline here; this is
7134 slower if backslash-newlines are present, but it's correct,
7135 and it's not worth it to tune for the rare backslash-newline. */
7137 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7138 /* Skip this comment. */
7140 U_CHAR *save_bufp = ip->bufp;
7142 p = skip_to_end_of_comment (ip, &junk, 1);
7143 ip->bufp = save_bufp;
7148 /* If we get here, this conditional is the beginning of the file. */
7153 /* Discard leading and trailing whitespace. */
7154 SKIP_WHITE_SPACE (buf);
7155 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7157 /* Find the end of the identifier at the beginning. */
7158 for (end = buf; is_idchar[*end]; end++);
7161 skip = (keyword->type == T_IFDEF);
7163 pedwarn (end == limit ? "`#%s' with no argument"
7164 : "`#%s' argument starts with punctuation",
7169 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
7170 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7171 else if (end != limit && !traditional)
7172 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7174 hp = lookup (buf, end-buf, -1);
7177 /* Output a precondition for this macro. */
7179 (hp->type == T_CONST
7180 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7181 fprintf (pcp_outfile, "#define %s\n", hp->name);
7184 fprintf (pcp_outfile, "#undef ");
7185 while (is_idchar[*cp]) /* Ick! */
7186 fputc (*cp++, pcp_outfile);
7187 putc ('\n', pcp_outfile);
7191 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7192 if (start_of_file && !skip) {
7193 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7194 bcopy ((char *) buf, (char *) control_macro, end - buf);
7195 control_macro[end - buf] = 0;
7199 conditional_skip (ip, skip, T_IF, control_macro, op);
7203 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7204 If this is a #ifndef starting at the beginning of a file,
7205 CONTROL_MACRO is the macro name tested by the #ifndef.
7206 Otherwise, CONTROL_MACRO is 0. */
7209 conditional_skip (ip, skip, type, control_macro, op)
7212 enum node_type type;
7213 U_CHAR *control_macro;
7216 IF_STACK_FRAME *temp;
7218 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7219 temp->fname = ip->nominal_fname;
7220 temp->lineno = ip->lineno;
7221 temp->next = if_stack;
7222 temp->control_macro = control_macro;
7225 if_stack->type = type;
7228 skip_if_group (ip, 0, op);
7231 ++if_stack->if_succeeded;
7232 output_line_directive (ip, &outbuf, 1, same_file);
7237 * skip to #endif, #else, or #elif. adjust line numbers, etc.
7238 * leaves input ptr at the sharp sign found.
7239 * If ANY is nonzero, return at next directive of any sort.
7242 skip_if_group (ip, any, op)
7247 register U_CHAR *bp = ip->bufp, *cp;
7248 register U_CHAR *endb = ip->buf + ip->length;
7249 struct directive *kt;
7250 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7251 U_CHAR *beg_of_line = bp;
7252 register int ident_length;
7253 U_CHAR *ident, *after_ident;
7254 /* Save info about where the group starts. */
7255 U_CHAR *beg_of_group = bp;
7256 int beg_lineno = ip->lineno;
7258 if (output_conditionals && op != 0) {
7259 char *ptr = "#failed\n";
7260 int len = strlen (ptr);
7262 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7267 check_expand (op, len);
7268 bcopy (ptr, (char *) op->bufp, len);
7271 output_line_directive (ip, op, 1, 0);
7276 case '/': /* possible comment */
7277 if (*bp == '\\' && bp[1] == '\n')
7280 || (cplusplus_comments && *bp == '/')) {
7282 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7287 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7288 NULL_PTR, NULL_PTR);
7291 /* Char after backslash loses its special meaning. */
7294 ++ip->lineno; /* But do update the line-count. */
7303 if (beg_of_line == 0 || traditional)
7306 while (bp[0] == '\\' && bp[1] == '\n')
7312 /* # keyword: a # must be first nonblank char on the line */
7313 if (beg_of_line == 0)
7317 /* Scan from start of line, skipping whitespace, comments
7318 and backslash-newlines, and see if we reach this #.
7319 If not, this # is not special. */
7321 /* If -traditional, require # to be at beginning of line. */
7324 if (is_hor_space[*bp])
7326 else if (*bp == '\\' && bp[1] == '\n')
7328 else if (*bp == '/' && bp[1] == '*') {
7330 while (!(*bp == '*' && bp[1] == '/'))
7334 /* There is no point in trying to deal with C++ // comments here,
7335 because if there is one, then this # must be part of the
7336 comment and we would never reach here. */
7340 if (bp != ip->bufp) {
7341 bp = ip->bufp + 1; /* Reset bp to after the #. */
7345 bp = ip->bufp + 1; /* Point after the '#' */
7346 if (ip->bufp[0] == '%') {
7347 /* Skip past the ':' again. */
7348 while (*bp == '\\') {
7355 /* Skip whitespace and \-newline. */
7357 if (is_hor_space[*bp])
7359 else if (*bp == '\\' && bp[1] == '\n')
7361 else if (*bp == '/' && bp[1] == '*') {
7363 while (!(*bp == '*' && bp[1] == '/')) {
7369 } else if (cplusplus_comments && *bp == '/' && bp[1] == '/') {
7371 while (bp[-1] == '\\' || *bp != '\n') {
7382 /* Now find end of directive name.
7383 If we encounter a backslash-newline, exchange it with any following
7384 symbol-constituents so that we end up with a contiguous name. */
7390 if (*bp == '\\' && bp[1] == '\n')
7391 name_newline_fix (bp);
7397 ident_length = bp - cp;
7401 /* A line of just `#' becomes blank. */
7403 if (ident_length == 0 && *after_ident == '\n') {
7407 if (ident_length == 0 || !is_idstart[*ident]) {
7409 while (is_idchar[*p]) {
7410 if (*p < '0' || *p > '9')
7414 /* Handle # followed by a line number. */
7415 if (p != ident && !is_idchar[*p]) {
7417 pedwarn ("`#' followed by integer");
7421 /* Avoid error for `###' and similar cases unless -pedantic. */
7423 while (*p == '#' || is_hor_space[*p]) p++;
7425 if (pedantic && !lang_asm)
7426 pedwarn ("invalid preprocessing directive");
7431 if (!lang_asm && pedantic)
7432 pedwarn ("invalid preprocessing directive name");
7436 for (kt = directive_table; kt->length >= 0; kt++) {
7437 IF_STACK_FRAME *temp;
7438 if (ident_length == kt->length
7439 && bcmp (cp, kt->name, kt->length) == 0) {
7440 /* If we are asked to return on next directive, do so now. */
7448 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7449 temp->next = if_stack;
7451 temp->lineno = ip->lineno;
7452 temp->fname = ip->nominal_fname;
7453 temp->type = kt->type;
7457 if (pedantic && if_stack != save_if_stack)
7460 if (if_stack == instack[indepth].if_stack) {
7461 error ("`#%s' not within a conditional", kt->name);
7464 else if (if_stack == save_if_stack)
7465 goto done; /* found what we came for */
7467 if (kt->type != T_ENDIF) {
7468 if (if_stack->type == T_ELSE)
7469 error ("`#else' or `#elif' after `#else'");
7470 if_stack->type = kt->type;
7475 if_stack = if_stack->next;
7485 /* Don't let erroneous code go by. */
7486 if (kt->length < 0 && !lang_asm && pedantic)
7487 pedwarn ("invalid preprocessing directive name");
7492 /* after this returns, rescan will exit because ip->bufp
7493 now points to the end of the buffer.
7494 rescan is responsible for the error message also. */
7497 if (output_conditionals && op != 0) {
7498 char *ptr = "#endfailed\n";
7499 int len = strlen (ptr);
7501 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7506 check_expand (op, beg_of_line - beg_of_group);
7507 bcopy ((char *) beg_of_group, (char *) op->bufp,
7508 beg_of_line - beg_of_group);
7509 op->bufp += beg_of_line - beg_of_group;
7510 op->lineno += ip->lineno - beg_lineno;
7511 check_expand (op, len);
7512 bcopy (ptr, (char *) op->bufp, len);
7519 * handle a #else directive. Do this by just continuing processing
7520 * without changing if_stack ; this is so that the error message
7521 * for missing #endif's etc. will point to the original #if. It
7522 * is possible that something different would be better.
7526 do_else (buf, limit, op, keyword)
7527 U_CHAR *buf, *limit;
7529 struct directive *keyword;
7531 FILE_BUF *ip = &instack[indepth];
7534 SKIP_WHITE_SPACE (buf);
7536 pedwarn ("text following `#else' violates ANSI standard");
7539 if (if_stack == instack[indepth].if_stack) {
7540 error ("`#else' not within a conditional");
7543 /* #ifndef can't have its special treatment for containing the whole file
7544 if it has a #else clause. */
7545 if_stack->control_macro = 0;
7547 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7548 error ("`#else' after `#else'");
7549 fprintf (stderr, " (matches line %d", if_stack->lineno);
7550 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7551 fprintf (stderr, ", file %s", if_stack->fname);
7552 fprintf (stderr, ")\n");
7554 if_stack->type = T_ELSE;
7557 if (if_stack->if_succeeded)
7558 skip_if_group (ip, 0, op);
7560 ++if_stack->if_succeeded; /* continue processing input */
7561 output_line_directive (ip, op, 1, same_file);
7567 * unstack after #endif directive
7571 do_endif (buf, limit, op, keyword)
7572 U_CHAR *buf, *limit;
7574 struct directive *keyword;
7577 SKIP_WHITE_SPACE (buf);
7579 pedwarn ("text following `#endif' violates ANSI standard");
7582 if (if_stack == instack[indepth].if_stack)
7583 error ("unbalanced `#endif'");
7585 IF_STACK_FRAME *temp = if_stack;
7586 if_stack = if_stack->next;
7587 if (temp->control_macro != 0) {
7588 /* This #endif matched a #ifndef at the start of the file.
7589 See if it is at the end of the file. */
7590 FILE_BUF *ip = &instack[indepth];
7591 U_CHAR *p = ip->bufp;
7592 U_CHAR *ep = ip->buf + ip->length;
7598 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7599 /* Skip this comment. */
7601 U_CHAR *save_bufp = ip->bufp;
7603 p = skip_to_end_of_comment (ip, &junk, 1);
7604 ip->bufp = save_bufp;
7609 /* If we get here, this #endif ends a #ifndef
7610 that contains all of the file (aside from whitespace).
7611 Arrange not to include the file again
7612 if the macro that was tested is defined.
7614 Do not do this for the top-level file in a -include or any
7615 file in a -imacros. */
7617 && ! (indepth == 1 && no_record_file)
7618 && ! (no_record_file && no_output))
7619 record_control_macro (ip->fname, temp->control_macro);
7623 output_line_directive (&instack[indepth], op, 1, same_file);
7628 /* When an #else or #endif is found while skipping failed conditional,
7629 if -pedantic was specified, this is called to warn about text after
7630 the directive name. P points to the first char after the directive name. */
7636 /* Advance P over whitespace and comments. */
7638 if (*p == '\\' && p[1] == '\n')
7640 if (is_hor_space[*p])
7642 else if (*p == '/') {
7643 if (p[1] == '\\' && p[2] == '\n')
7644 newline_fix (p + 1);
7647 /* Don't bother warning about unterminated comments
7648 since that will happen later. Just be sure to exit. */
7650 if (p[1] == '\\' && p[2] == '\n')
7651 newline_fix (p + 1);
7652 if (*p == '*' && p[1] == '/') {
7659 else if (cplusplus_comments && p[1] == '/') {
7661 while (*p && (*p != '\n' || p[-1] == '\\'))
7666 if (*p && *p != '\n')
7667 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7670 /* Skip a comment, assuming the input ptr immediately follows the
7671 initial slash-star. Bump *LINE_COUNTER for each newline.
7672 (The canonical line counter is &ip->lineno.)
7673 Don't use this routine (or the next one) if bumping the line
7674 counter is not sufficient to deal with newlines in the string.
7676 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7677 This feature is useful when processing a comment that is going to be
7678 processed or was processed at another point in the preprocessor,
7679 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7682 skip_to_end_of_comment (ip, line_counter, nowarn)
7683 register FILE_BUF *ip;
7684 int *line_counter; /* place to remember newlines, or NULL */
7687 register U_CHAR *limit = ip->buf + ip->length;
7688 register U_CHAR *bp = ip->bufp;
7689 FILE_BUF *op = &outbuf; /* JF */
7690 int output = put_out_comments && !line_counter;
7691 int start_line = line_counter ? *line_counter : 0;
7693 /* JF this line_counter stuff is a crock to make sure the
7694 comment is only put out once, no matter how many times
7695 the comment is skipped. It almost works */
7700 if (cplusplus_comments && bp[-1] == '/') {
7702 while (bp < limit) {
7704 if (*bp == '\n' && bp[-1] != '\\')
7716 while (bp < limit) {
7717 if (bp[-1] != '\\' && *bp == '\n') {
7720 if (*bp == '\n' && line_counter)
7729 while (bp < limit) {
7734 if (warn_comments && !nowarn && bp < limit && *bp == '*')
7735 warning ("`/*' within comment");
7738 /* If this is the end of the file, we have an unterminated comment.
7739 Don't swallow the newline. We are guaranteed that there will be a
7740 trailing newline and various pieces assume it's there. */
7747 if (line_counter != NULL)
7753 if (*bp == '\\' && bp[1] == '\n')
7766 error_with_line (line_for_error (start_line), "unterminated comment");
7772 * Skip over a quoted string. BP points to the opening quote.
7773 * Returns a pointer after the closing quote. Don't go past LIMIT.
7774 * START_LINE is the line number of the starting point (but it need
7775 * not be valid if the starting point is inside a macro expansion).
7777 * The input stack state is not changed.
7779 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7780 * for each newline passed.
7782 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7783 * if we pass a backslash-newline.
7785 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7788 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7789 register U_CHAR *bp;
7790 register U_CHAR *limit;
7792 int *count_newlines;
7793 int *backslash_newlines_p;
7796 register U_CHAR c, match;
7801 error_with_line (line_for_error (start_line),
7802 "unterminated string or character constant");
7803 error_with_line (multiline_string_line,
7804 "possible real start of unterminated constant");
7805 multiline_string_line = 0;
7812 while (*bp == '\\' && bp[1] == '\n') {
7813 if (backslash_newlines_p)
7814 *backslash_newlines_p = 1;
7819 if (*bp == '\n' && count_newlines) {
7820 if (backslash_newlines_p)
7821 *backslash_newlines_p = 1;
7825 } else if (c == '\n') {
7827 /* Unterminated strings and character constants are 'valid'. */
7828 bp--; /* Don't consume the newline. */
7833 if (pedantic || match == '\'') {
7834 error_with_line (line_for_error (start_line),
7835 "unterminated string or character constant");
7841 /* If not traditional, then allow newlines inside strings. */
7844 if (multiline_string_line == 0)
7845 multiline_string_line = start_line;
7846 } else if (c == match)
7852 /* Place into DST a quoted string representing the string SRC.
7853 Return the address of DST's terminating null. */
7855 quote_string (dst, src)
7862 switch ((c = *src++))
7869 sprintf (dst, "\\%03o", c);
7887 /* Skip across a group of balanced parens, starting from IP->bufp.
7888 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7890 This does not handle newlines, because it's used for the arg of #if,
7891 where there aren't any newlines. Also, backslash-newline can't appear. */
7894 skip_paren_group (ip)
7895 register FILE_BUF *ip;
7897 U_CHAR *limit = ip->buf + ip->length;
7898 U_CHAR *p = ip->bufp;
7900 int lines_dummy = 0;
7902 while (p != limit) {
7912 return ip->bufp = p;
7918 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7926 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7928 return ip->bufp = p;
7939 * write out a #line directive, for instance, after an #include file.
7940 * If CONDITIONAL is nonzero, we can omit the #line if it would
7941 * appear to be a no-op, and we can output a few newlines instead
7942 * if we want to increase the line number by a small amount.
7943 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7947 output_line_directive (ip, op, conditional, file_change)
7950 enum file_change_code file_change;
7953 char *line_directive_buf, *line_end;
7955 if (no_line_directives
7956 || ip->fname == NULL
7958 op->lineno = ip->lineno;
7963 if (ip->lineno == op->lineno)
7966 /* If the inherited line number is a little too small,
7967 output some newlines instead of a #line directive. */
7968 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7969 check_expand (op, 10);
7970 while (ip->lineno > op->lineno) {
7978 /* Don't output a line number of 0 if we can help it. */
7979 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7980 && *ip->bufp == '\n') {
7985 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7986 sprintf (line_directive_buf, "# %d ", ip->lineno);
7987 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7989 if (file_change != same_file) {
7991 *line_end++ = file_change == enter_file ? '1' : '2';
7993 /* Tell cc1 if following text comes from a system header file. */
7994 if (ip->system_header_p) {
7998 #ifndef NO_IMPLICIT_EXTERN_C
7999 /* Tell cc1plus if following text should be treated as C. */
8000 if (ip->system_header_p == 2 && cplusplus) {
8006 len = line_end - line_directive_buf;
8007 check_expand (op, len + 1);
8008 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8010 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8012 op->lineno = ip->lineno;
8015 /* This structure represents one parsed argument in a macro call.
8016 `raw' points to the argument text as written (`raw_length' is its length).
8017 `expanded' points to the argument's macro-expansion
8018 (its length is `expand_length').
8019 `stringified_length' is the length the argument would have
8021 `use_count' is the number of times this macro arg is substituted
8022 into the macro. If the actual use count exceeds 10,
8023 the value stored is 10.
8024 `free1' and `free2', if nonzero, point to blocks to be freed
8025 when the macro argument data is no longer needed. */
8028 U_CHAR *raw, *expanded;
8029 int raw_length, expand_length;
8030 int stringified_length;
8031 U_CHAR *free1, *free2;
8037 /* Expand a macro call.
8038 HP points to the symbol that is the macro being called.
8039 Put the result of expansion onto the input stack
8040 so that subsequent input by our caller will use it.
8042 If macro wants arguments, caller has already verified that
8043 an argument list follows; arguments come from the input stack. */
8046 macroexpand (hp, op)
8051 DEFINITION *defn = hp->value.defn;
8052 register U_CHAR *xbuf;
8054 int start_line = instack[indepth].lineno;
8055 int rest_args, rest_zero;
8057 CHECK_DEPTH (return;);
8059 /* it might not actually be a macro. */
8060 if (hp->type != T_MACRO) {
8061 special_symbol (hp, op);
8065 /* This macro is being used inside a #if, which means it must be */
8066 /* recorded as a precondition. */
8067 if (pcp_inside_if && pcp_outfile && defn->predefined)
8068 dump_single_macro (hp, pcp_outfile);
8070 nargs = defn->nargs;
8074 struct argdata *args;
8075 char *parse_error = 0;
8077 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8079 for (i = 0; i < nargs; i++) {
8080 args[i].raw = (U_CHAR *) "";
8081 args[i].expanded = 0;
8082 args[i].raw_length = args[i].expand_length
8083 = args[i].stringified_length = 0;
8084 args[i].free1 = args[i].free2 = 0;
8085 args[i].use_count = 0;
8088 /* Parse all the macro args that are supplied. I counts them.
8089 The first NARGS args are stored in ARGS.
8090 The rest are discarded.
8091 If rest_args is set then we assume macarg absorbed the rest of the args.
8096 /* Discard the open-parenthesis or comma before the next arg. */
8097 ++instack[indepth].bufp;
8100 if (i < nargs || (nargs == 0 && i == 0)) {
8101 /* if we are working on last arg which absorbs rest of args... */
8102 if (i == nargs - 1 && defn->rest_args)
8104 parse_error = macarg (&args[i], rest_args);
8107 parse_error = macarg (NULL_PTR, 0);
8109 error_with_line (line_for_error (start_line), parse_error);
8113 } while (*instack[indepth].bufp != ')');
8115 /* If we got one arg but it was just whitespace, call that 0 args. */
8117 register U_CHAR *bp = args[0].raw;
8118 register U_CHAR *lim = bp + args[0].raw_length;
8119 /* cpp.texi says for foo ( ) we provide one argument.
8120 However, if foo wants just 0 arguments, treat this as 0. */
8122 while (bp != lim && is_space[*bp]) bp++;
8127 /* Don't output an error message if we have already output one for
8128 a parse error above. */
8130 if (nargs == 0 && i > 0) {
8132 error ("arguments given to macro `%s'", hp->name);
8133 } else if (i < nargs) {
8134 /* traditional C allows foo() if foo wants one argument. */
8135 if (nargs == 1 && i == 0 && traditional)
8137 /* the rest args token is allowed to absorb 0 tokens */
8138 else if (i == nargs - 1 && defn->rest_args)
8140 else if (parse_error)
8143 error ("macro `%s' used without args", hp->name);
8145 error ("macro `%s' used with just one arg", hp->name);
8147 error ("macro `%s' used with only %d args", hp->name, i);
8148 } else if (i > nargs) {
8150 error ("macro `%s' used with too many (%d) args", hp->name, i);
8153 /* Swallow the closeparen. */
8154 ++instack[indepth].bufp;
8156 /* If macro wants zero args, we parsed the arglist for checking only.
8157 Read directly from the macro definition. */
8159 xbuf = defn->expansion;
8160 xbuf_len = defn->length;
8162 register U_CHAR *exp = defn->expansion;
8163 register int offset; /* offset in expansion,
8164 copied a piece at a time */
8165 register int totlen; /* total amount of exp buffer filled so far */
8167 register struct reflist *ap, *last_ap;
8169 /* Macro really takes args. Compute the expansion of this call. */
8171 /* Compute length in characters of the macro's expansion.
8172 Also count number of times each arg is used. */
8173 xbuf_len = defn->length;
8174 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8176 xbuf_len += args[ap->argno].stringified_length;
8177 else if (ap->raw_before || ap->raw_after || traditional)
8178 /* Add 4 for two newline-space markers to prevent
8179 token concatenation. */
8180 xbuf_len += args[ap->argno].raw_length + 4;
8182 /* We have an ordinary (expanded) occurrence of the arg.
8183 So compute its expansion, if we have not already. */
8184 if (args[ap->argno].expanded == 0) {
8186 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8187 args[ap->argno].raw + args[ap->argno].raw_length,
8190 args[ap->argno].expanded = obuf.buf;
8191 args[ap->argno].expand_length = obuf.length;
8192 args[ap->argno].free2 = obuf.buf;
8195 /* Add 4 for two newline-space markers to prevent
8196 token concatenation. */
8197 xbuf_len += args[ap->argno].expand_length + 4;
8199 if (args[ap->argno].use_count < 10)
8200 args[ap->argno].use_count++;
8203 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8205 /* Generate in XBUF the complete expansion
8206 with arguments substituted in.
8207 TOTLEN is the total size generated so far.
8208 OFFSET is the index in the definition
8209 of where we are copying from. */
8210 offset = totlen = 0;
8211 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8212 last_ap = ap, ap = ap->next) {
8213 register struct argdata *arg = &args[ap->argno];
8214 int count_before = totlen;
8216 /* Add chars to XBUF. */
8217 for (i = 0; i < ap->nchars; i++, offset++)
8218 xbuf[totlen++] = exp[offset];
8220 /* If followed by an empty rest arg with concatenation,
8221 delete the last run of nonwhite chars. */
8222 if (rest_zero && totlen > count_before
8223 && ((ap->rest_args && ap->raw_before)
8224 || (last_ap != NULL && last_ap->rest_args
8225 && last_ap->raw_after))) {
8226 /* Delete final whitespace. */
8227 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8231 /* Delete the nonwhites before them. */
8232 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8237 if (ap->stringify != 0) {
8238 int arglen = arg->raw_length;
8244 && (c = arg->raw[i], is_space[c]))
8247 && (c = arg->raw[arglen - 1], is_space[c]))
8250 xbuf[totlen++] = '\"'; /* insert beginning quote */
8251 for (; i < arglen; i++) {
8254 /* Special markers Newline Space
8255 generate nothing for a stringified argument. */
8256 if (c == '\n' && arg->raw[i+1] != '\n') {
8261 /* Internal sequences of whitespace are replaced by one space
8262 except within an string or char token. */
8264 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8266 /* Note that Newline Space does occur within whitespace
8267 sequences; consider it part of the sequence. */
8268 if (c == '\n' && is_space[arg->raw[i+1]])
8270 else if (c != '\n' && is_space[c])
8287 } else if (c == '\"' || c == '\'')
8291 /* Escape these chars */
8292 if (c == '\"' || (in_string && c == '\\'))
8293 xbuf[totlen++] = '\\';
8297 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8302 xbuf[totlen++] = '\"'; /* insert ending quote */
8303 } else if (ap->raw_before || ap->raw_after || traditional) {
8304 U_CHAR *p1 = arg->raw;
8305 U_CHAR *l1 = p1 + arg->raw_length;
8306 if (ap->raw_before) {
8307 while (p1 != l1 && is_space[*p1]) p1++;
8308 while (p1 != l1 && is_idchar[*p1])
8309 xbuf[totlen++] = *p1++;
8310 /* Delete any no-reexpansion marker that follows
8311 an identifier at the beginning of the argument
8312 if the argument is concatenated with what precedes it. */
8313 if (p1[0] == '\n' && p1[1] == '-')
8315 } else if (!traditional) {
8316 /* Ordinary expanded use of the argument.
8317 Put in newline-space markers to prevent token pasting. */
8318 xbuf[totlen++] = '\n';
8319 xbuf[totlen++] = ' ';
8321 if (ap->raw_after) {
8322 /* Arg is concatenated after: delete trailing whitespace,
8323 whitespace markers, and no-reexpansion markers. */
8325 if (is_space[l1[-1]]) l1--;
8326 else if (l1[-1] == '-') {
8327 U_CHAR *p2 = l1 - 1;
8328 /* If a `-' is preceded by an odd number of newlines then it
8329 and the last newline are a no-reexpansion marker. */
8330 while (p2 != p1 && p2[-1] == '\n') p2--;
8331 if ((l1 - 1 - p2) & 1) {
8340 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8342 if (!traditional && !ap->raw_after) {
8343 /* Ordinary expanded use of the argument.
8344 Put in newline-space markers to prevent token pasting. */
8345 xbuf[totlen++] = '\n';
8346 xbuf[totlen++] = ' ';
8349 /* Ordinary expanded use of the argument.
8350 Put in newline-space markers to prevent token pasting. */
8352 xbuf[totlen++] = '\n';
8353 xbuf[totlen++] = ' ';
8355 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8356 arg->expand_length);
8357 totlen += arg->expand_length;
8359 xbuf[totlen++] = '\n';
8360 xbuf[totlen++] = ' ';
8362 /* If a macro argument with newlines is used multiple times,
8363 then only expand the newlines once. This avoids creating output
8364 lines which don't correspond to any input line, which confuses
8366 if (arg->use_count > 1 && arg->newlines > 0) {
8367 /* Don't bother doing change_newlines for subsequent
8371 = change_newlines (arg->expanded, arg->expand_length);
8375 if (totlen > xbuf_len)
8379 /* if there is anything left of the definition
8380 after handling the arg list, copy that in too. */
8382 for (i = offset; i < defn->length; i++) {
8383 /* if we've reached the end of the macro */
8386 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8387 && last_ap->raw_after))
8388 xbuf[totlen++] = exp[i];
8394 for (i = 0; i < nargs; i++) {
8395 if (args[i].free1 != 0)
8396 free (args[i].free1);
8397 if (args[i].free2 != 0)
8398 free (args[i].free2);
8402 xbuf = defn->expansion;
8403 xbuf_len = defn->length;
8406 /* Now put the expansion on the input stack
8407 so our caller will commence reading from it. */
8409 register FILE_BUF *ip2;
8411 ip2 = &instack[++indepth];
8414 ip2->nominal_fname = 0;
8415 /* This may not be exactly correct, but will give much better error
8416 messages for nested macro calls than using a line number of zero. */
8417 ip2->lineno = start_line;
8419 ip2->length = xbuf_len;
8421 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8423 ip2->if_stack = if_stack;
8424 ip2->system_header_p = 0;
8426 /* Recursive macro use sometimes works traditionally.
8427 #define foo(x,y) bar (x (y,0), y)
8431 hp->type = T_DISABLED;
8436 * Parse a macro argument and store the info on it into *ARGPTR.
8437 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8438 * Return nonzero to indicate a syntax error.
8442 macarg (argptr, rest_args)
8443 register struct argdata *argptr;
8446 FILE_BUF *ip = &instack[indepth];
8451 /* Try to parse as much of the argument as exists at this
8452 input stack level. */
8453 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8454 &paren, &newlines, &comments, rest_args);
8456 /* If we find the end of the argument at this level,
8457 set up *ARGPTR to point at it in the input stack. */
8458 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8459 && bp != ip->buf + ip->length) {
8461 argptr->raw = ip->bufp;
8462 argptr->raw_length = bp - ip->bufp;
8463 argptr->newlines = newlines;
8467 /* This input stack level ends before the macro argument does.
8468 We must pop levels and keep parsing.
8469 Therefore, we must allocate a temporary buffer and copy
8470 the macro argument into it. */
8471 int bufsize = bp - ip->bufp;
8472 int extra = newlines;
8473 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8474 int final_start = 0;
8476 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8478 ip->lineno += newlines;
8480 while (bp == ip->buf + ip->length) {
8481 if (instack[indepth].macro == 0) {
8483 return "unterminated macro call";
8485 ip->macro->type = T_MACRO;
8487 free (ip->free_ptr);
8488 ip = &instack[--indepth];
8491 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8492 &newlines, &comments, rest_args);
8493 final_start = bufsize;
8494 bufsize += bp - ip->bufp;
8496 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8497 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8500 ip->lineno += newlines;
8503 /* Now, if arg is actually wanted, record its raw form,
8504 discarding comments and duplicating newlines in whatever
8505 part of it did not come from a macro expansion.
8506 EXTRA space has been preallocated for duplicating the newlines.
8507 FINAL_START is the index of the start of that part. */
8509 argptr->raw = buffer;
8510 argptr->raw_length = bufsize;
8511 argptr->free1 = buffer;
8512 argptr->newlines = newlines;
8513 argptr->comments = comments;
8514 if ((newlines || comments) && ip->fname != 0)
8517 discard_comments (argptr->raw + final_start,
8518 argptr->raw_length - final_start,
8520 argptr->raw[argptr->raw_length] = 0;
8521 if (argptr->raw_length > bufsize + extra)
8526 /* If we are not discarding this argument,
8527 macroexpand it and compute its length as stringified.
8528 All this info goes into *ARGPTR. */
8531 register U_CHAR *buf, *lim;
8532 register int totlen;
8535 lim = buf + argptr->raw_length;
8537 while (buf != lim && is_space[*buf])
8539 while (buf != lim && is_space[lim[-1]])
8541 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8542 while (buf != lim) {
8543 register U_CHAR c = *buf++;
8545 /* Internal sequences of whitespace are replaced by one space
8546 in most cases, but not always. So count all the whitespace
8547 in case we need to keep it all. */
8550 SKIP_ALL_WHITE_SPACE (buf);
8553 if (c == '\"' || c == '\\') /* escape these chars */
8555 else if (!isprint (c))
8558 argptr->stringified_length = totlen;
8563 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8564 counting parens in *DEPTHPTR,
8565 and return if reach LIMIT
8566 or before a `)' that would make *DEPTHPTR negative
8567 or before a comma when *DEPTHPTR is zero.
8568 Single and double quotes are matched and termination
8569 is inhibited within them. Comments also inhibit it.
8570 Value returned is pointer to stopping place.
8572 Increment *NEWLINES each time a newline is passed.
8573 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8574 Set *COMMENTS to 1 if a comment is seen. */
8577 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8579 register U_CHAR *limit;
8580 int *depthptr, *newlines, *comments;
8583 register U_CHAR *bp = start;
8585 while (bp < limit) {
8591 if (--(*depthptr) < 0)
8595 /* Traditionally, backslash makes following char not special. */
8596 if (bp + 1 < limit && traditional)
8599 /* But count source lines anyway. */
8608 if (bp[1] == '\\' && bp[2] == '\n')
8609 newline_fix (bp + 1);
8610 if (cplusplus_comments && bp[1] == '/') {
8613 while (bp < limit && (*bp != '\n' || bp[-1] == '\\')) {
8614 if (*bp == '\n') ++*newlines;
8617 /* Now count the newline that we are about to skip. */
8621 if (bp[1] != '*' || bp + 1 >= limit)
8625 while (bp + 1 < limit) {
8627 && bp[1] == '\\' && bp[2] == '\n')
8628 newline_fix (bp + 1);
8629 if (bp[0] == '*' && bp[1] == '/')
8631 if (*bp == '\n') ++*newlines;
8639 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8644 while (*bp == '\\' && bp[1] == '\n') {
8647 } else if (*bp == '\n') {
8656 /* if we've returned to lowest level and we aren't absorbing all args */
8657 if ((*depthptr) == 0 && rest_args == 0)
8667 /* Discard comments and duplicate newlines
8668 in the string of length LENGTH at START,
8669 except inside of string constants.
8670 The string is copied into itself with its beginning staying fixed.
8672 NEWLINES is the number of newlines that must be duplicated.
8673 We assume that that much extra space is available past the end
8677 discard_comments (start, length, newlines)
8682 register U_CHAR *ibp;
8683 register U_CHAR *obp;
8684 register U_CHAR *limit;
8687 /* If we have newlines to duplicate, copy everything
8688 that many characters up. Then, in the second part,
8689 we will have room to insert the newlines
8691 NEWLINES may actually be too large, because it counts
8692 newlines in string constants, and we don't duplicate those.
8693 But that does no harm. */
8695 ibp = start + length;
8696 obp = ibp + newlines;
8698 while (limit != ibp)
8702 ibp = start + newlines;
8703 limit = start + length + newlines;
8706 while (ibp < limit) {
8707 *obp++ = c = *ibp++;
8710 /* Duplicate the newline. */
8722 if (*ibp == '\\' && ibp[1] == '\n')
8724 /* Delete any comment. */
8725 if (cplusplus_comments && ibp[0] == '/') {
8726 /* Comments are equivalent to spaces. */
8729 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8733 if (ibp[0] != '*' || ibp + 1 >= limit)
8735 /* Comments are equivalent to spaces.
8736 For -traditional, a comment is equivalent to nothing. */
8742 while (ibp + 1 < limit) {
8744 && ibp[1] == '\\' && ibp[2] == '\n')
8745 newline_fix (ibp + 1);
8746 if (ibp[0] == '*' && ibp[1] == '/')
8755 /* Notice and skip strings, so that we don't
8756 think that comments start inside them,
8757 and so we don't duplicate newlines in them. */
8760 while (ibp < limit) {
8761 *obp++ = c = *ibp++;
8764 if (c == '\n' && quotec == '\'')
8766 if (c == '\\' && ibp < limit) {
8767 while (*ibp == '\\' && ibp[1] == '\n')
8780 /* Turn newlines to spaces in the string of length LENGTH at START,
8781 except inside of string constants.
8782 The string is copied into itself with its beginning staying fixed. */
8785 change_newlines (start, length)
8789 register U_CHAR *ibp;
8790 register U_CHAR *obp;
8791 register U_CHAR *limit;
8795 limit = start + length;
8798 while (ibp < limit) {
8799 *obp++ = c = *ibp++;
8802 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8803 string. Skip past the newline and its duplicate.
8804 Put a space in the output. */
8815 /* Notice and skip strings, so that we don't delete newlines in them. */
8818 while (ibp < limit) {
8819 *obp++ = c = *ibp++;
8822 if (c == '\n' && quotec == '\'')
8834 * my_strerror - return the descriptive text associated with an `errno' code.
8838 my_strerror (errnum)
8844 #ifndef HAVE_STRERROR
8845 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8847 result = strerror (errnum);
8850 /* VAXCRTL's strerror() takes an optional second argument, which only
8851 matters when the first argument is EVMSERR. However, it's simplest
8852 just to pass it unconditionally. `vaxc$errno' is declared in
8853 <errno.h>, and maintained by the library in parallel with `errno'.
8854 We assume that caller's `errnum' either matches the last setting of
8855 `errno' by the library or else does not have the value `EVMSERR'. */
8857 result = strerror (errnum, vaxc$errno);
8861 result = "undocumented I/O error";
8867 * error - print error message and increment count of errors.
8871 error (PRINTF_ALIST (msg))
8876 VA_START (args, msg);
8887 FILE_BUF *ip = NULL;
8889 print_containing_files ();
8891 for (i = indepth; i >= 0; i--)
8892 if (instack[i].fname != NULL) {
8898 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8899 vfprintf (stderr, msg, args);
8900 fprintf (stderr, "\n");
8904 /* Error including a message from `errno'. */
8907 error_from_errno (name)
8911 FILE_BUF *ip = NULL;
8913 print_containing_files ();
8915 for (i = indepth; i >= 0; i--)
8916 if (instack[i].fname != NULL) {
8922 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8924 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8929 /* Print error message but don't count it. */
8932 warning (PRINTF_ALIST (msg))
8937 VA_START (args, msg);
8938 vwarning (msg, args);
8943 vwarning (msg, args)
8948 FILE_BUF *ip = NULL;
8950 if (inhibit_warnings)
8953 if (warnings_are_errors)
8956 print_containing_files ();
8958 for (i = indepth; i >= 0; i--)
8959 if (instack[i].fname != NULL) {
8965 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8966 fprintf (stderr, "warning: ");
8967 vfprintf (stderr, msg, args);
8968 fprintf (stderr, "\n");
8972 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8973 error_with_line (int line, PRINTF_ALIST (msg))
8975 error_with_line (line, PRINTF_ALIST (msg))
8982 VA_START (args, msg);
8983 verror_with_line (line, msg, args);
8988 verror_with_line (line, msg, args)
8994 FILE_BUF *ip = NULL;
8996 print_containing_files ();
8998 for (i = indepth; i >= 0; i--)
8999 if (instack[i].fname != NULL) {
9005 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
9006 vfprintf (stderr, msg, args);
9007 fprintf (stderr, "\n");
9012 vwarning_with_line (line, msg, args)
9018 FILE_BUF *ip = NULL;
9020 if (inhibit_warnings)
9023 if (warnings_are_errors)
9026 print_containing_files ();
9028 for (i = indepth; i >= 0; i--)
9029 if (instack[i].fname != NULL) {
9035 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
9036 fprintf (stderr, "warning: ");
9037 vfprintf (stderr, msg, args);
9038 fprintf (stderr, "\n");
9041 /* print an error message and maybe count it. */
9044 pedwarn (PRINTF_ALIST (msg))
9049 VA_START (args, msg);
9050 if (pedantic_errors)
9053 vwarning (msg, args);
9058 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9059 pedwarn_with_line (int line, PRINTF_ALIST (msg))
9061 pedwarn_with_line (line, PRINTF_ALIST (msg))
9068 VA_START (args, msg);
9069 if (pedantic_errors)
9070 verror_with_line (line, msg, args);
9072 vwarning_with_line (line, msg, args);
9076 /* Report a warning (or an error if pedantic_errors)
9077 giving specified file name and line number, not current. */
9080 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9081 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
9083 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
9091 if (!pedantic_errors && inhibit_warnings)
9094 fprintf (stderr, "%s:%d: ", file, line);
9095 if (pedantic_errors)
9097 if (!pedantic_errors)
9098 fprintf (stderr, "warning: ");
9099 VA_START (args, msg);
9100 vfprintf (stderr, msg, args);
9102 fprintf (stderr, "\n");
9105 /* Print the file names and line numbers of the #include
9106 directives which led to the current file. */
9109 print_containing_files ()
9111 FILE_BUF *ip = NULL;
9115 /* If stack of files hasn't changed since we last printed
9116 this info, don't repeat it. */
9117 if (last_error_tick == input_file_stack_tick)
9120 for (i = indepth; i >= 0; i--)
9121 if (instack[i].fname != NULL) {
9126 /* Give up if we don't find a source file. */
9130 /* Find the other, outer source files. */
9131 for (i--; i >= 0; i--)
9132 if (instack[i].fname != NULL) {
9136 fprintf (stderr, "In file included");
9138 fprintf (stderr, ",\n ");
9141 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9144 fprintf (stderr, ":\n");
9146 /* Record we have printed the status as of this time. */
9147 last_error_tick = input_file_stack_tick;
9150 /* Return the line at which an error occurred.
9151 The error is not necessarily associated with the current spot
9152 in the input stack, so LINE says where. LINE will have been
9153 copied from ip->lineno for the current input level.
9154 If the current level is for a file, we return LINE.
9155 But if the current level is not for a file, LINE is meaningless.
9156 In that case, we return the lineno of the innermost file. */
9159 line_for_error (line)
9165 for (i = indepth; i >= 0; ) {
9166 if (instack[i].fname != 0)
9171 line1 = instack[i].lineno;
9179 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9181 * As things stand, nothing is ever placed in the output buffer to be
9182 * removed again except when it's KNOWN to be part of an identifier,
9183 * so flushing and moving down everything left, instead of expanding,
9187 /* You might think void was cleaner for the return type,
9188 but that would get type mismatch in check_expand in strict ANSI. */
9190 grow_outbuf (obuf, needed)
9191 register FILE_BUF *obuf;
9192 register int needed;
9197 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9200 /* Make it at least twice as big as it is now. */
9202 /* Make it have at least 150% of the free space we will need. */
9203 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9204 if (minsize > obuf->length)
9205 obuf->length = minsize;
9207 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9210 obuf->bufp = p + (obuf->bufp - obuf->buf);
9216 /* Symbol table for macro names and special symbols */
9219 * install a name in the main hash table, even if it is already there.
9220 * name stops with first non alphanumeric, except leading '#'.
9221 * caller must check against redefinition if that is desired.
9222 * delete_macro () removes things installed by install () in fifo order.
9223 * this is important because of the `defined' special symbol used
9224 * in #if, and also if pushdef/popdef directives are ever implemented.
9226 * If LEN is >= 0, it is the length of the name.
9227 * Otherwise, compute the length by scanning the entire name.
9229 * If HASH is >= 0, it is the precomputed hash code.
9230 * Otherwise, compute the hash code.
9233 install (name, len, type, value, hash)
9236 enum node_type type;
9240 register HASHNODE *hp;
9241 register int i, bucket;
9242 register U_CHAR *p, *q;
9246 while (is_idchar[*p])
9252 hash = hashf (name, len, HASHSIZE);
9254 i = sizeof (HASHNODE) + len + 1;
9255 hp = (HASHNODE *) xmalloc (i);
9257 hp->bucket_hdr = &hashtab[bucket];
9258 hp->next = hashtab[bucket];
9259 hashtab[bucket] = hp;
9261 if (hp->next != NULL)
9262 hp->next->prev = hp;
9265 hp->value.cpval = value;
9266 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9269 for (i = 0; i < len; i++)
9276 * find the most recent hash node for name name (ending with first
9277 * non-identifier char) installed by install
9279 * If LEN is >= 0, it is the length of the name.
9280 * Otherwise, compute the length by scanning the entire name.
9282 * If HASH is >= 0, it is the precomputed hash code.
9283 * Otherwise, compute the hash code.
9286 lookup (name, len, hash)
9291 register U_CHAR *bp;
9292 register HASHNODE *bucket;
9295 for (bp = name; is_idchar[*bp]; bp++) ;
9300 hash = hashf (name, len, HASHSIZE);
9302 bucket = hashtab[hash];
9304 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9306 bucket = bucket->next;
9312 * Delete a hash node. Some weirdness to free junk from macros.
9313 * More such weirdness will have to be added if you define more hash
9314 * types that need it.
9317 /* Note that the DEFINITION of a macro is removed from the hash table
9318 but its storage is not freed. This would be a storage leak
9319 except that it is not reasonable to keep undefining and redefining
9320 large numbers of macros many times.
9321 In any case, this is necessary, because a macro can be #undef'd
9322 in the middle of reading the arguments to a call to it.
9323 If #undef freed the DEFINITION, that would crash. */
9330 if (hp->prev != NULL)
9331 hp->prev->next = hp->next;
9332 if (hp->next != NULL)
9333 hp->next->prev = hp->prev;
9335 /* make sure that the bucket chain header that
9336 the deleted guy was on points to the right thing afterwards. */
9337 if (hp == *hp->bucket_hdr)
9338 *hp->bucket_hdr = hp->next;
9341 if (hp->type == T_MACRO) {
9342 DEFINITION *d = hp->value.defn;
9343 struct reflist *ap, *nextap;
9345 for (ap = d->pattern; ap != NULL; ap = nextap) {
9356 * return hash function on name. must be compatible with the one
9357 * computed a step at a time, elsewhere
9360 hashf (name, len, hashsize)
9361 register U_CHAR *name;
9368 r = HASHSTEP (r, *name++);
9370 return MAKE_POS (r) % hashsize;
9374 /* Dump the definition of a single macro HP to OF. */
9376 dump_single_macro (hp, of)
9377 register HASHNODE *hp;
9380 register DEFINITION *defn = hp->value.defn;
9386 /* Print the definition of the macro HP. */
9388 fprintf (of, "#define %s", hp->name);
9390 if (defn->nargs >= 0) {
9394 for (i = 0; i < defn->nargs; i++) {
9395 dump_arg_n (defn, i, of);
9396 if (i + 1 < defn->nargs)
9406 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9407 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9408 offset += ap->nchars;
9410 if (ap->nchars != 0)
9412 if (ap->stringify) {
9413 switch (ap->stringify) {
9414 case SHARP_TOKEN: fprintf (of, "#"); break;
9415 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9416 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9417 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9421 if (ap->raw_before) {
9423 switch (ap->raw_before) {
9424 case WHITE_SHARP_TOKEN:
9425 case WHITE_PERCENT_COLON_TOKEN:
9432 switch (ap->raw_before) {
9433 case SHARP_TOKEN: fprintf (of, "##"); break;
9434 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9435 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9436 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9443 dump_arg_n (defn, ap->argno, of);
9444 if (!traditional && ap->raw_after) {
9445 switch (ap->raw_after) {
9446 case SHARP_TOKEN: fprintf (of, "##"); break;
9447 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9448 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9449 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9455 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9459 /* Dump all macro definitions as #defines to stdout. */
9466 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9467 register HASHNODE *hp;
9469 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9470 if (hp->type == T_MACRO)
9471 dump_single_macro (hp, stdout);
9476 /* Output to OF a substring of a macro definition.
9477 BASE is the beginning of the definition.
9478 Output characters START thru LENGTH.
9479 Unless traditional, discard newlines outside of strings, thus
9480 converting funny-space markers to ordinary spaces. */
9483 dump_defn_1 (base, start, length, of)
9489 U_CHAR *p = base + start;
9490 U_CHAR *limit = base + start + length;
9493 fwrite (p, sizeof (*p), length, of);
9496 if (*p == '\"' || *p =='\'') {
9497 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9498 NULL_PTR, NULL_PTR);
9499 fwrite (p, sizeof (*p), p1 - p, of);
9510 /* Print the name of argument number ARGNUM of macro definition DEFN
9512 Recall that DEFN->args.argnames contains all the arg names
9513 concatenated in reverse order with comma-space in between. */
9516 dump_arg_n (defn, argnum, of)
9521 register U_CHAR *p = defn->args.argnames;
9522 while (argnum + 1 < defn->nargs) {
9523 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9527 while (*p && *p != ',') {
9533 /* Initialize syntactic classifications of characters. */
9536 initialize_char_syntax ()
9541 * Set up is_idchar and is_idstart tables. These should be
9542 * faster than saying (is_alpha (c) || c == '_'), etc.
9543 * Set up these things before calling any routines tthat
9546 for (i = 'a'; i <= 'z'; i++) {
9547 is_idchar[i - 'a' + 'A'] = 1;
9549 is_idstart[i - 'a' + 'A'] = 1;
9552 for (i = '0'; i <= '9'; i++)
9555 is_idstart['_'] = 1;
9556 is_idchar['$'] = dollars_in_ident;
9557 is_idstart['$'] = dollars_in_ident;
9559 /* horizontal space table */
9560 is_hor_space[' '] = 1;
9561 is_hor_space['\t'] = 1;
9562 is_hor_space['\v'] = 1;
9563 is_hor_space['\f'] = 1;
9564 is_hor_space['\r'] = 1;
9573 char_name['\v'] = "vertical tab";
9574 char_name['\f'] = "formfeed";
9575 char_name['\r'] = "carriage return";
9578 /* Initialize the built-in macros. */
9581 initialize_builtins (inp, outp)
9585 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9586 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9587 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9588 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9589 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9590 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9591 #ifndef NO_BUILTIN_SIZE_TYPE
9592 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9594 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9595 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9597 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9598 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9600 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9602 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9604 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9605 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9608 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9609 /* This is supplied using a -D by the compiler driver
9610 so that it is present only when truly compiling with GNU C. */
9611 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9615 char directive[2048];
9616 U_CHAR *udirective = (U_CHAR *) directive;
9617 register struct directive *dp = &directive_table[0];
9618 struct tm *timebuf = timestamp ();
9620 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9621 instack[0].nominal_fname);
9622 output_line_directive (inp, outp, 0, same_file);
9623 pass_thru_directive (udirective, &udirective[strlen (directive)],
9626 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9627 output_line_directive (inp, outp, 0, same_file);
9628 pass_thru_directive (udirective, &udirective[strlen (directive)],
9631 #ifndef NO_BUILTIN_SIZE_TYPE
9632 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9633 output_line_directive (inp, outp, 0, same_file);
9634 pass_thru_directive (udirective, &udirective[strlen (directive)],
9638 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9639 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9640 output_line_directive (inp, outp, 0, same_file);
9641 pass_thru_directive (udirective, &udirective[strlen (directive)],
9645 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9646 output_line_directive (inp, outp, 0, same_file);
9647 pass_thru_directive (udirective, &udirective[strlen (directive)],
9650 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9651 monthnames[timebuf->tm_mon],
9652 timebuf->tm_mday, timebuf->tm_year + 1900);
9653 output_line_directive (inp, outp, 0, same_file);
9654 pass_thru_directive (udirective, &udirective[strlen (directive)],
9657 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9658 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9659 output_line_directive (inp, outp, 0, same_file);
9660 pass_thru_directive (udirective, &udirective[strlen (directive)],
9665 sprintf (directive, " __STDC__ 1");
9666 output_line_directive (inp, outp, 0, same_file);
9667 pass_thru_directive (udirective, &udirective[strlen (directive)],
9672 sprintf (directive, " __OBJC__ 1");
9673 output_line_directive (inp, outp, 0, same_file);
9674 pass_thru_directive (udirective, &udirective[strlen (directive)],
9681 * process a given definition string, for initialization
9682 * If STR is just an identifier, define it with value 1.
9683 * If STR has anything after the identifier, then it should
9684 * be identifier=definition.
9688 make_definition (str, op)
9693 struct directive *kt;
9696 p = buf = (U_CHAR *) str;
9697 if (!is_idstart[*p]) {
9698 error ("malformed option `-D %s'", str);
9701 while (is_idchar[*++p])
9704 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9707 p = (U_CHAR *) str; /* Error */
9710 buf = (U_CHAR *) alloca (p - buf + 4);
9711 strcpy ((char *)buf, str);
9712 strcat ((char *)buf, " 1");
9713 } else if (*p != '=') {
9714 error ("malformed option `-D %s'", str);
9718 /* Copy the entire option so we can modify it. */
9719 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9720 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9721 /* Change the = to a space. */
9722 buf[p - (U_CHAR *) str] = ' ';
9723 /* Scan for any backslash-newline and remove it. */
9725 q = &buf[p - (U_CHAR *) str];
9727 if (*p == '\"' || *p == '\'') {
9728 int unterminated = 0;
9729 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9730 NULL_PTR, NULL_PTR, &unterminated);
9734 if (*p == '\\' && p[1] == '\n')
9738 } else if (*p == '\\' && p[1] == '\n')
9740 /* Change newline chars into newline-markers. */
9741 else if (*p == '\n')
9753 ip = &instack[++indepth];
9754 ip->nominal_fname = ip->fname = "*Initialization*";
9756 ip->buf = ip->bufp = buf;
9757 ip->length = strlen ((char *) buf);
9761 ip->if_stack = if_stack;
9762 ip->system_header_p = 0;
9764 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9767 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9768 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9772 /* JF, this does the work for the -U option */
9775 make_undef (str, op)
9780 struct directive *kt;
9782 ip = &instack[++indepth];
9783 ip->nominal_fname = ip->fname = "*undef*";
9785 ip->buf = ip->bufp = (U_CHAR *) str;
9786 ip->length = strlen (str);
9790 ip->if_stack = if_stack;
9791 ip->system_header_p = 0;
9793 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9796 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9800 /* Process the string STR as if it appeared as the body of a #assert.
9801 OPTION is the option name for which STR was the argument. */
9804 make_assertion (option, str)
9809 struct directive *kt;
9810 U_CHAR *buf, *p, *q;
9812 /* Copy the entire option so we can modify it. */
9813 buf = (U_CHAR *) alloca (strlen (str) + 1);
9814 strcpy ((char *) buf, str);
9815 /* Scan for any backslash-newline and remove it. */
9818 if (*p == '\\' && p[1] == '\n')
9826 if (!is_idstart[*p]) {
9827 error ("malformed option `%s %s'", option, str);
9830 while (is_idchar[*++p])
9832 SKIP_WHITE_SPACE (p);
9833 if (! (*p == 0 || *p == '(')) {
9834 error ("malformed option `%s %s'", option, str);
9838 ip = &instack[++indepth];
9839 ip->nominal_fname = ip->fname = "*Initialization*";
9841 ip->buf = ip->bufp = buf;
9842 ip->length = strlen ((char *) buf);
9846 ip->if_stack = if_stack;
9847 ip->system_header_p = 0;
9849 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9852 /* pass NULL as output ptr to do_define since we KNOW it never
9853 does any output.... */
9854 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9858 /* Append a chain of `struct file_name_list's
9859 to the end of the main include chain.
9860 FIRST is the beginning of the chain to append, and LAST is the end. */
9863 append_include_chain (first, last)
9864 struct file_name_list *first, *last;
9866 struct file_name_list *dir;
9868 if (!first || !last)
9874 last_include->next = first;
9876 if (first_bracket_include == 0)
9877 first_bracket_include = first;
9879 for (dir = first; ; dir = dir->next) {
9880 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9881 if (len > max_include_len)
9882 max_include_len = len;
9888 last_include = last;
9891 /* Add output to `deps_buffer' for the -M switch.
9892 STRING points to the text to be output.
9893 SPACER is ':' for targets, ' ' for dependencies, zero for text
9894 to be inserted literally. */
9897 deps_output (string, spacer)
9901 int size = strlen (string);
9906 #ifndef MAX_OUTPUT_COLUMNS
9907 #define MAX_OUTPUT_COLUMNS 72
9911 && (deps_column + size) > MAX_OUTPUT_COLUMNS)
9913 deps_output (" \\\n ", 0);
9917 if (deps_size + size + 8 > deps_allocated_size) {
9918 deps_allocated_size = (deps_size + size + 50) * 2;
9919 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9921 if (spacer == ' ' && deps_column > 0)
9922 deps_buffer[deps_size++] = ' ';
9923 bcopy (string, &deps_buffer[deps_size], size);
9925 deps_column += size;
9927 deps_buffer[deps_size++] = ':';
9928 deps_buffer[deps_size] = 0;
9932 fatal (PRINTF_ALIST (msg))
9937 fprintf (stderr, "%s: ", progname);
9938 VA_START (args, msg);
9939 vfprintf (stderr, msg, args);
9941 fprintf (stderr, "\n");
9942 exit (FAILURE_EXIT_CODE);
9945 /* More 'friendly' abort that prints the line and file.
9946 config.h can #define abort fancy_abort if you like that sort of thing. */
9951 fatal ("Internal gcc abort.");
9955 perror_with_name (name)
9958 fprintf (stderr, "%s: ", progname);
9959 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9964 pfatal_with_name (name)
9967 perror_with_name (name);
9971 exit (FAILURE_EXIT_CODE);
9975 /* Handler for SIGPIPE. */
9979 /* If this is missing, some compilers complain. */
9982 fatal ("output pipe has been closed");
9988 fatal ("Memory exhausted.");
9996 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10003 xrealloc (old, size)
10007 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10014 xcalloc (number, size)
10015 size_t number, size;
10017 register size_t total = number * size;
10018 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10021 bzero (ptr, total);
10029 size_t size = strlen (input);
10030 char *output = xmalloc (size + 1);
10031 strcpy (output, input);
10035 /* Get the file-mode and data size of the file open on FD
10036 and store them in *MODE_POINTER and *SIZE_POINTER. */
10039 file_size_and_mode (fd, mode_pointer, size_pointer)
10042 long int *size_pointer;
10046 if (fstat (fd, &sbuf) < 0) return (-1);
10047 if (mode_pointer) *mode_pointer = sbuf.st_mode;
10048 if (size_pointer) *size_pointer = sbuf.st_size;
10053 output_dots (fd, depth)
10057 while (depth > 0) {
10066 /* Under VMS we need to fix up the "include" specification
10067 filename so that everything following the 1st slash is
10068 changed into its correct VMS file specification. */
10071 hack_vms_include_specification (fname)
10074 register char *cp, *cp1, *cp2;
10075 int f, check_filename_before_returning, no_prefix_seen;
10078 check_filename_before_returning = 0;
10079 no_prefix_seen = 0;
10081 /* Ignore leading "./"s */
10082 while (fname[0] == '.' && fname[1] == '/') {
10083 strcpy (fname, fname+2);
10084 no_prefix_seen = 1; /* mark this for later */
10086 /* Look for the boundary between the VMS and UNIX filespecs */
10087 cp = rindex (fname, ']'); /* Look for end of dirspec. */
10088 if (cp == 0) cp = rindex (fname, '>'); /* ... Ditto */
10089 if (cp == 0) cp = rindex (fname, ':'); /* Look for end of devspec. */
10093 cp = index (fname, '/'); /* Look for the "/" */
10097 * Check if we have a vax-c style '#include filename'
10098 * and add the missing .h
10101 if (index(fname,'.') == 0)
10102 strcat(fname, ".h");
10104 if (index(cp,'.') == 0)
10108 cp2 = Local; /* initialize */
10110 /* We are trying to do a number of things here. First of all, we are
10111 trying to hammer the filenames into a standard format, such that later
10112 processing can handle them.
10114 If the file name contains something like [dir.], then it recognizes this
10115 as a root, and strips the ".]". Later processing will add whatever is
10116 needed to get things working properly.
10118 If no device is specified, then the first directory name is taken to be
10119 a device name (or a rooted logical). */
10121 /* See if we found that 1st slash */
10122 if (cp == 0) return; /* Nothing to do!!! */
10123 if (*cp != '/') return; /* Nothing to do!!! */
10124 /* Point to the UNIX filename part (which needs to be fixed!) */
10126 /* If the directory spec is not rooted, we can just copy
10127 the UNIX filename part and we are done */
10128 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10129 if (cp[-2] != '.') {
10131 * The VMS part ends in a `]', and the preceding character is not a `.'.
10132 * We strip the `]', and then splice the two parts of the name in the
10133 * usual way. Given the default locations for include files in cccp.c,
10134 * we will only use this code if the user specifies alternate locations
10135 * with the /include (-I) switch on the command line. */
10136 cp -= 1; /* Strip "]" */
10137 cp1--; /* backspace */
10140 * The VMS part has a ".]" at the end, and this will not do. Later
10141 * processing will add a second directory spec, and this would be a syntax
10142 * error. Thus we strip the ".]", and thus merge the directory specs.
10143 * We also backspace cp1, so that it points to a '/'. This inhibits the
10144 * generation of the 000000 root directory spec (which does not belong here
10147 cp -= 2; /* Strip ".]" */
10148 cp1--; }; /* backspace */
10151 /* We drop in here if there is no VMS style directory specification yet.
10152 * If there is no device specification either, we make the first dir a
10153 * device and try that. If we do not do this, then we will be essentially
10154 * searching the users default directory (as if they did a #include "asdf.h").
10156 * Then all we need to do is to push a '[' into the output string. Later
10157 * processing will fill this in, and close the bracket.
10159 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10160 *cp2++ = '['; /* Open the directory specification */
10163 /* at this point we assume that we have the device spec, and (at least
10164 the opening "[" for a directory specification. We may have directories
10165 specified already */
10167 /* If there are no other slashes then the filename will be
10168 in the "root" directory. Otherwise, we need to add
10169 directory specifications. */
10170 if (index (cp1, '/') == 0) {
10171 /* Just add "000000]" as the directory string */
10172 strcpy (cp2, "000000]");
10173 cp2 += strlen (cp2);
10174 check_filename_before_returning = 1; /* we might need to fool with this later */
10176 /* As long as there are still subdirectories to add, do them. */
10177 while (index (cp1, '/') != 0) {
10178 /* If this token is "." we can ignore it */
10179 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10183 /* Add a subdirectory spec. Do not duplicate "." */
10184 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10186 /* If this is ".." then the spec becomes "-" */
10187 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10188 /* Add "-" and skip the ".." */
10193 /* Copy the subdirectory */
10194 while (*cp1 != '/') *cp2++= *cp1++;
10195 cp1++; /* Skip the "/" */
10197 /* Close the directory specification */
10198 if (cp2[-1] == '.') /* no trailing periods */
10202 /* Now add the filename */
10203 while (*cp1) *cp2++ = *cp1++;
10205 /* Now append it to the original VMS spec. */
10206 strcpy (cp, Local);
10208 /* If we put a [000000] in the filename, try to open it first. If this fails,
10209 remove the [000000], and return that name. This provides flexibility
10210 to the user in that they can use both rooted and non-rooted logical names
10211 to point to the location of the file. */
10213 if (check_filename_before_returning && no_prefix_seen) {
10214 f = open (fname, O_RDONLY, 0666);
10216 /* The file name is OK as it is, so return it as is. */
10220 /* The filename did not work. Try to remove the [000000] from the name,
10222 cp = index (fname, '[');
10223 cp2 = index (fname, ']') + 1;
10224 strcpy (cp, cp2); /* this gets rid of it */
10232 /* These are the read/write replacement routines for
10233 VAX-11 "C". They make read/write behave enough
10234 like their UNIX counterparts that CCCP will work */
10237 read (fd, buf, size)
10242 #undef read /* Get back the REAL read routine */
10244 register int total = 0;
10246 /* Read until the buffer is exhausted */
10248 /* Limit each read to 32KB */
10249 i = (size > (32*1024)) ? (32*1024) : size;
10250 i = read (fd, buf, i);
10252 if (i == 0) return (total);
10255 /* Account for this read */
10264 write (fd, buf, size)
10269 #undef write /* Get back the REAL write routine */
10273 /* Limit individual writes to 32Kb */
10276 j = (i > (32*1024)) ? (32*1024) : i;
10277 if (write (fd, buf, j) < 0) return (-1);
10278 /* Account for the data written */
10285 /* The following wrapper functions supply additional arguments to the VMS
10286 I/O routines to optimize performance with file handling. The arguments
10288 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10289 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10290 "fop=tef"- Truncate unused portions of file when closing file.
10291 "shr=nil"- Disallow file sharing while file is open.
10295 freopen (fname, type, oldfile)
10300 #undef freopen /* Get back the REAL fopen routine */
10301 if (strcmp (type, "w") == 0)
10302 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10303 return freopen (fname, type, oldfile, "mbc=16");
10307 fopen (fname, type)
10311 #undef fopen /* Get back the REAL fopen routine */
10312 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10313 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10314 pre-ANSI implmentation. This hack circumvents the mismatch problem. */
10315 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10318 return (*vmslib_fopen) (fname, type, "mbc=32",
10319 "deq=64", "fop=tef", "shr=nil");
10321 return (*vmslib_fopen) (fname, type, "mbc=32");
10325 open (fname, flags, prot)
10330 #undef open /* Get back the REAL open routine */
10331 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10334 /* Avoid run-time library bug, where copying M out of N+M characters with
10335 N >= 65535 results in VAXCRTL's strncat falling into an infinite loop.
10336 gcc-cpp exercises this particular bug. [Fixed in V5.5-2's VAXCRTL.] */
10339 strncat (dst, src, cnt)
10344 register char *d = dst, *s = (char *) src;
10345 register int n = cnt; /* convert to _signed_ type */
10347 while (*d) d++; /* advance to end */
10349 if (!(*d++ = *s++)) break;
10350 if (n < 0) *d = '\0';
10354 /* more VMS hackery */
10358 extern unsigned long sys$parse(), sys$search();
10360 /* Work around another library bug. If a file is located via a searchlist,
10361 and if the device it's on is not the same device as the one specified
10362 in the first element of that searchlist, then both stat() and fstat()
10363 will fail to return info about it. `errno' will be set to EVMSERR, and
10364 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10365 We can get around this by fully parsing the filename and then passing
10366 that absolute name to stat().
10368 Without this fix, we can end up failing to find header files, which is
10369 bad enough, but then compounding the problem by reporting the reason for
10370 failure as "normal successful completion." */
10373 fstat (fd, statbuf)
10375 struct stat *statbuf;
10378 int result = fstat (fd, statbuf);
10383 char nambuf[NAM$C_MAXRSS+1];
10385 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10386 result = stat (nambuf, statbuf);
10387 /* No fclose(fp) here; that would close(fd) as well. */
10394 stat (name, statbuf)
10396 struct stat *statbuf;
10399 int result = stat (name, statbuf);
10405 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10406 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10409 fab.fab$l_fna = (char *) name;
10410 fab.fab$b_fns = (unsigned char) strlen (name);
10411 fab.fab$l_nam = (void *) &nam;
10413 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10414 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10415 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10416 if (sys$parse (&fab) & 1)
10418 if (sys$search (&fab) & 1)
10420 res_nam[nam.nam$b_rsl] = '\0';
10421 result = stat (res_nam, statbuf);
10423 /* Clean up searchlist context cached by the system. */
10424 nam.nam$b_nop = NAM$M_SYNCHK;
10425 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10426 (void) sys$parse (&fab);