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, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
21 In other words, you are welcome to use, share and improve this program.
22 You are forbidden to forbid anyone else to use, share and improve
23 what you give them. Help stamp out software-hoarding! */
25 typedef unsigned char U_CHAR;
29 #include "../src/config.h"
37 /* The macro EMACS is defined when cpp is distributed as part of Emacs,
38 for the sake of machines with limited C compilers. */
41 #endif /* not EMACS */
43 #ifndef STANDARD_INCLUDE_DIR
44 #define STANDARD_INCLUDE_DIR "/usr/include"
47 #ifndef LOCAL_INCLUDE_DIR
48 #define LOCAL_INCLUDE_DIR "/usr/local/include"
51 #if 0 /* We can't get ptrdiff_t, so I arranged not to need PTR_INT_TYPE. */
53 #define PTR_INT_TYPE ptrdiff_t
55 #define PTR_INT_TYPE long
61 /* By default, colon separates directories in a path. */
62 #ifndef PATH_SEPARATOR
63 #define PATH_SEPARATOR ':'
66 #include <sys/types.h>
72 /* The following symbols should be autoconfigured:
79 In the mean time, we'll get by with approximations based
80 on existing GCC configuration symbols. */
83 # ifndef HAVE_STDLIB_H
84 # define HAVE_STDLIB_H 1
86 # ifndef HAVE_UNISTD_H
87 # define HAVE_UNISTD_H 1
90 # define STDC_HEADERS 1
92 #endif /* defined (POSIX) */
94 #if defined (POSIX) || (defined (USG) && !defined (VMS))
96 # define HAVE_FCNTL_H 1
103 # if TIME_WITH_SYS_TIME
104 # include <sys/time.h>
108 # include <sys/time.h>
113 # include <sys/resource.h>
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 fstat(fd,stbuf) VMS_fstat (fd,stbuf)
242 static int VMS_fstat (), VMS_stat ();
243 static int VMS_read ();
244 static int VMS_write ();
245 static int VMS_open ();
246 static FILE * VMS_fopen ();
247 static FILE * VMS_freopen ();
248 static void hack_vms_include_specification ();
249 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
250 #define INO_T_HASH(a) 0
251 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
253 #define BSTRING /* VMS/GCC supplies the bstring routines */
254 #endif /* __GNUC__ */
263 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
264 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
266 /* Find the largest host integer type and set its size and type. */
268 #ifndef HOST_BITS_PER_WIDE_INT
270 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
271 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
272 #define HOST_WIDE_INT long
274 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
275 #define HOST_WIDE_INT int
281 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
285 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
289 #define INO_T_EQ(a, b) ((a) == (b))
293 #define INO_T_HASH(a) (a)
296 /* Define a generic NULL if one hasn't already been defined. */
303 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
304 #define GENERIC_PTR void *
306 #define GENERIC_PTR char *
311 #define NULL_PTR ((GENERIC_PTR)0)
314 #ifndef INCLUDE_LEN_FUDGE
315 #define INCLUDE_LEN_FUDGE 0
318 /* External declarations. */
320 extern char *version_string;
322 #ifndef HAVE_STRERROR
325 extern const char *const sys_errlist[];
327 extern char *sys_errlist[];
329 #else /* HAVE_STRERROR */
333 char *strerror (int,...);
335 int parse_escape PROTO((char **));
336 HOST_WIDE_INT parse_c_expression PROTO((char *));
342 /* Name under which this program was invoked. */
344 static char *progname;
346 /* Nonzero means use extra default include directories for C++. */
348 static int cplusplus;
350 /* Nonzero means handle cplusplus style comments */
352 static int cplusplus_comments;
354 /* Nonzero means handle #import, for objective C. */
358 /* Nonzero means this is an assembly file, and allow
359 unknown directives, which could be comments. */
363 /* Current maximum length of directory names in the search path
364 for include files. (Altered as we get more of them.) */
366 static int max_include_len;
368 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
370 static int for_lint = 0;
372 /* Nonzero means copy comments into the output file. */
374 static int put_out_comments = 0;
376 /* Nonzero means don't process the ANSI trigraph sequences. */
378 static int no_trigraphs = 0;
380 /* Nonzero means print the names of included files rather than
381 the preprocessed output. 1 means just the #include "...",
382 2 means #include <...> as well. */
384 static int print_deps = 0;
386 /* Nonzero if missing .h files in -M output are assumed to be generated
387 files and not errors. */
389 static int print_deps_missing_files = 0;
391 /* Nonzero means print names of header files (-H). */
393 static int print_include_names = 0;
395 /* Nonzero means don't output line number information. */
397 static int no_line_directives;
399 /* Nonzero means output the text in failing conditionals,
400 inside #failed ... #endfailed. */
402 static int output_conditionals;
404 /* dump_only means inhibit output of the preprocessed text
405 and instead output the definitions of all user-defined
406 macros in a form suitable for use as input to cccp.
407 dump_names means pass #define and the macro name through to output.
408 dump_definitions means pass the whole definition (plus #define) through
411 static enum {dump_none, dump_only, dump_names, dump_definitions}
412 dump_macros = dump_none;
414 /* Nonzero means pass all #define and #undef directives which we actually
415 process through to the output stream. This feature is used primarily
416 to allow cc1 to record the #defines and #undefs for the sake of
417 debuggers which understand about preprocessor macros, but it may
418 also be useful with -E to figure out how symbols are defined, and
419 where they are defined. */
420 static int debug_output = 0;
422 /* Nonzero indicates special processing used by the pcp program. The
423 special effects of this mode are:
425 Inhibit all macro expansion, except those inside #if directives.
427 Process #define directives normally, and output their contents
430 Output preconditions to pcp_outfile indicating all the relevant
431 preconditions for use of this file in a later cpp run.
433 static FILE *pcp_outfile;
435 /* Nonzero means we are inside an IF during a -pcp run. In this mode
436 macro expansion is done, and preconditions are output for all macro
437 uses requiring them. */
438 static int pcp_inside_if;
440 /* Nonzero means never to include precompiled files.
441 This is 1 since there's no way now to make precompiled files,
442 so it's not worth testing for them. */
443 static int no_precomp = 1;
445 /* Nonzero means give all the error messages the ANSI standard requires. */
449 /* Nonzero means try to make failure to fit ANSI C an error. */
451 static int pedantic_errors;
453 /* Nonzero means don't print warning messages. -w. */
455 static int inhibit_warnings = 0;
457 /* Nonzero means warn if slash-star appears in a slash-star comment,
458 or if newline-backslash appears in a slash-slash comment. */
460 static int warn_comments;
462 /* Nonzero means warn if a macro argument is (or would be)
463 stringified with -traditional. */
465 static int warn_stringify;
467 /* Nonzero means warn if there are any trigraphs. */
469 static int warn_trigraphs;
471 /* Nonzero means warn if #import is used. */
473 static int warn_import = 1;
475 /* Nonzero means turn warnings into errors. */
477 static int warnings_are_errors;
479 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
483 /* Nonzero causes output not to be done,
484 but directives such as #define that have side effects
487 static int no_output;
489 /* Nonzero means this file was included with a -imacros or -include
490 command line and should not be recorded as an include file. */
492 static int no_record_file;
494 /* Nonzero means that we have finished processing the command line options.
495 This flag is used to decide whether or not to issue certain errors
498 static int done_initializing = 0;
500 /* Line where a newline was first seen in a string constant. */
502 static int multiline_string_line = 0;
504 /* I/O buffer structure.
505 The `fname' field is nonzero for source files and #include files
506 and for the dummy text used for -D and -U.
507 It is zero for rescanning results of macro expansion
508 and for expanding macro arguments. */
509 #define INPUT_STACK_MAX 400
510 static struct file_buf {
512 /* Filename specified with #line directive. */
514 /* Include file description. */
515 struct include_file *inc;
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;
572 /* If the following is 1, it is a C-language system include
574 int c_system_include_path;
575 /* Mapping of file names for this directory. */
576 struct file_name_map *name_map;
577 /* Non-zero if name_map is valid. */
579 /* The include directory status. */
581 /* The include prefix: "" denotes the working directory,
582 otherwise fname must end in '/'.
583 The actual size is dynamically allocated. */
587 /* #include "file" looks in source file dir, then stack. */
588 /* #include <file> just looks in the stack. */
589 /* -I directories are added to the end, then the defaults are added. */
591 static struct default_include {
592 char *fname; /* The name of the directory. */
593 int cplusplus; /* Only look here if we're compiling C++. */
594 int cxx_aware; /* Includes in this directory don't need to
595 be wrapped in extern "C" when compiling
597 } include_defaults_array[]
598 #ifdef INCLUDE_DEFAULTS
602 /* Pick up GNU C++ specific include files. */
603 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
605 /* This is the dir for fixincludes. Put it just before
606 the files that we fix. */
607 { GCC_INCLUDE_DIR, 0, 0 },
608 /* For cross-compilation, this dir name is generated
609 automatically in Makefile.in. */
610 { CROSS_INCLUDE_DIR, 0, 0 },
611 /* This is another place that the target system's headers might be. */
612 { TOOL_INCLUDE_DIR, 0, 0 },
613 #else /* not CROSS_COMPILE */
614 /* This should be /usr/local/include and should come before
615 the fixincludes-fixed header files. */
616 { LOCAL_INCLUDE_DIR, 0, 1 },
617 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
618 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
619 { TOOL_INCLUDE_DIR, 0, 0 },
620 /* This is the dir for fixincludes. Put it just before
621 the files that we fix. */
622 { GCC_INCLUDE_DIR, 0, 0 },
623 /* Some systems have an extra dir of include files. */
624 #ifdef SYSTEM_INCLUDE_DIR
625 { SYSTEM_INCLUDE_DIR, 0, 0 },
627 { STANDARD_INCLUDE_DIR, 0, 0 },
628 #endif /* not CROSS_COMPILE */
631 #endif /* no INCLUDE_DEFAULTS */
633 /* The code looks at the defaults through this pointer, rather than through
634 the constant structure above. This pointer gets changed if an environment
635 variable specifies other defaults. */
636 static struct default_include *include_defaults = include_defaults_array;
638 static struct file_name_list *include = 0; /* First dir to search */
639 /* First dir to search for <file> */
640 /* This is the first element to use for #include <...>.
641 If it is 0, use the entire chain for such includes. */
642 static struct file_name_list *first_bracket_include = 0;
643 /* This is the first element in the chain that corresponds to
644 a directory of system header files. */
645 static struct file_name_list *first_system_include = 0;
646 static struct file_name_list *last_include = 0; /* Last in chain */
648 /* Chain of include directories to put at the end of the other chain. */
649 static struct file_name_list *after_include = 0;
650 static struct file_name_list *last_after_include = 0; /* Last in chain */
652 /* Chain to put at the start of the system include files. */
653 static struct file_name_list *before_system = 0;
654 static struct file_name_list *last_before_system = 0; /* Last in chain */
656 /* Directory prefix that should replace `/usr' in the standard
657 include file directories. */
658 static char *include_prefix;
660 /* Maintain and search list of included files. */
662 struct include_file {
663 struct include_file *next; /* for include_hashtab */
664 struct include_file *next_ino; /* for include_ino_hashtab */
666 /* If the following is the empty string, it means #pragma once
667 was seen in this include file, or #import was applied to the file.
668 Otherwise, if it is nonzero, it is a macro name.
669 Don't include the file again if that macro is defined. */
670 U_CHAR *control_macro;
671 /* Nonzero if the dependency on this include file has been output. */
676 /* Hash tables of files already included with #include or #import.
677 include_hashtab is by full name; include_ino_hashtab is by inode number. */
679 #define INCLUDE_HASHSIZE 61
680 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
681 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
683 /* Global list of strings read in from precompiled files. This list
684 is kept in the order the strings are read in, with new strings being
685 added at the end through stringlist_tailp. We use this list to output
686 the strings at the end of the run.
688 static STRINGDEF *stringlist;
689 static STRINGDEF **stringlist_tailp = &stringlist;
692 /* Structure returned by create_definition */
693 typedef struct macrodef MACRODEF;
696 struct definition *defn;
701 enum sharp_token_type {
702 NO_SHARP_TOKEN = 0, /* token not present */
704 SHARP_TOKEN = '#', /* token spelled with # only */
705 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
707 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
708 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
711 /* Structure allocated for every #define. For a simple replacement
714 nargs = -1, the `pattern' list is null, and the expansion is just
715 the replacement text. Nargs = 0 means a functionlike macro with no args,
717 #define getchar() getc (stdin) .
718 When there are args, the expansion is the replacement text with the
719 args squashed out, and the reflist is a list describing how to
720 build the output from the input: e.g., "3 chars, then the 1st arg,
721 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
722 The chars here come from the expansion. Whatever is left of the
723 expansion after the last arg-occurrence is copied after that arg.
724 Note that the reflist can be arbitrarily long---
725 its length depends on the number of times the arguments appear in
726 the replacement text, not how many args there are. Example:
727 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
729 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
730 where (x, y) means (nchars, argno). */
732 typedef struct definition DEFINITION;
735 int length; /* length of expansion string */
736 int predefined; /* True if the macro was builtin or */
737 /* came from the command line */
739 int line; /* Line number of definition */
740 char *file; /* File of definition */
741 char rest_args; /* Nonzero if last arg. absorbs the rest */
743 struct reflist *next;
745 enum sharp_token_type stringify; /* set if a # operator before arg */
746 enum sharp_token_type raw_before; /* set if a ## operator before arg */
747 enum sharp_token_type raw_after; /* set if a ## operator after arg */
749 char rest_args; /* Nonzero if this arg. absorbs the rest */
750 int nchars; /* Number of literal chars to copy before
751 this arg occurrence. */
752 int argno; /* Number of arg to substitute (origin-0) */
755 /* Names of macro args, concatenated in reverse order
756 with comma-space between them.
757 The only use of this is that we warn on redefinition
758 if this differs between the old and new definitions. */
763 /* different kinds of things that can appear in the value field
764 of a hash node. Actually, this may be useless now. */
772 * special extension string that can be added to the last macro argument to
773 * allow it to absorb the "rest" of the arguments when expanded. Ex:
774 * #define wow(a, b...) process (b, a, b)
775 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
776 * { wow (one, two); } -> { process (two, one, two); }
777 * if this "rest_arg" is used with the concat token '##' and if it is not
778 * supplied then the token attached to with ## will not be outputted. Ex:
779 * #define wow (a, b...) process (b ## , a, ## b)
780 * { wow (1, 2); } -> { process (2, 1, 2); }
781 * { wow (one); } -> { process (one); {
783 static char rest_extension[] = "...";
784 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
786 /* The structure of a node in the hash table. The hash table
787 has entries for all tokens defined by #define directives (type T_MACRO),
788 plus some special tokens like __LINE__ (these each have their own
789 type, and the appropriate code is run when that type of node is seen.
790 It does not contain control words like "#define", which are recognized
791 by a separate piece of code. */
793 /* different flavors of hash nodes --- also used in keyword table */
795 T_DEFINE = 1, /* the `#define' keyword */
796 T_INCLUDE, /* the `#include' keyword */
797 T_INCLUDE_NEXT, /* the `#include_next' keyword */
798 T_IMPORT, /* the `#import' keyword */
799 T_IFDEF, /* the `#ifdef' keyword */
800 T_IFNDEF, /* the `#ifndef' keyword */
801 T_IF, /* the `#if' keyword */
802 T_ELSE, /* `#else' */
803 T_PRAGMA, /* `#pragma' */
804 T_ELIF, /* `#elif' */
805 T_UNDEF, /* `#undef' */
806 T_LINE, /* `#line' */
807 T_ERROR, /* `#error' */
808 T_WARNING, /* `#warning' */
809 T_ENDIF, /* `#endif' */
810 T_SCCS, /* `#sccs', used on system V. */
811 T_IDENT, /* `#ident', used on system V. */
812 T_ASSERT, /* `#assert', taken from system V. */
813 T_UNASSERT, /* `#unassert', taken from system V. */
814 T_SPECLINE, /* special symbol `__LINE__' */
815 T_DATE, /* `__DATE__' */
816 T_FILE, /* `__FILE__' */
817 T_BASE_FILE, /* `__BASE_FILE__' */
818 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
819 T_VERSION, /* `__VERSION__' */
820 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
821 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
822 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
823 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
824 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
825 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
826 T_TIME, /* `__TIME__' */
827 T_CONST, /* Constant value, used by `__STDC__' */
828 T_MACRO, /* macro defined by `#define' */
829 T_DISABLED, /* macro temporarily turned off for rescan */
830 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
831 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
832 T_UNUSED /* Used for something not defined. */
836 struct hashnode *next; /* double links for easy deletion */
837 struct hashnode *prev;
838 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
839 chain is kept, in case the node is the head
840 of the chain and gets deleted. */
841 enum node_type type; /* type of special token */
842 int length; /* length of token, for quick comparison */
843 U_CHAR *name; /* the actual name */
844 union hashval value; /* pointer to expansion, or whatever */
847 typedef struct hashnode HASHNODE;
849 /* Some definitions for the hash table. The hash function MUST be
850 computed as shown in hashf () below. That is because the rescan
851 loop computes the hash value `on the fly' for most tokens,
852 in order to avoid the overhead of a lot of procedure calls to
853 the hashf () function. Hashf () only exists for the sake of
854 politeness, for use when speed isn't so important. */
856 #define HASHSIZE 1403
857 static HASHNODE *hashtab[HASHSIZE];
858 #define HASHSTEP(old, c) ((old << 2) + c)
859 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
861 /* Symbols to predefine. */
863 #ifdef CPP_PREDEFINES
864 static char *predefs = CPP_PREDEFINES;
866 static char *predefs = "";
869 /* We let tm.h override the types used here, to handle trivial differences
870 such as the choice of unsigned int or long unsigned int for size_t.
871 When machines start needing nontrivial differences in the size type,
872 it would be best to do something here to figure out automatically
873 from other information what type to use. */
875 /* The string value for __SIZE_TYPE__. */
878 #define SIZE_TYPE "long unsigned int"
881 /* The string value for __PTRDIFF_TYPE__. */
884 #define PTRDIFF_TYPE "long int"
887 /* The string value for __WCHAR_TYPE__. */
890 #define WCHAR_TYPE "int"
892 char * wchar_type = WCHAR_TYPE;
895 /* The string value for __USER_LABEL_PREFIX__ */
897 #ifndef USER_LABEL_PREFIX
898 #define USER_LABEL_PREFIX ""
901 /* The string value for __REGISTER_PREFIX__ */
903 #ifndef REGISTER_PREFIX
904 #define REGISTER_PREFIX ""
907 /* The string value for __IMMEDIATE_PREFIX__ */
909 #ifndef IMMEDIATE_PREFIX
910 #define IMMEDIATE_PREFIX ""
913 /* In the definition of a #assert name, this structure forms
914 a list of the individual values asserted.
915 Each value is itself a list of "tokens".
916 These are strings that are compared by name. */
918 struct tokenlist_list {
919 struct tokenlist_list *next;
920 struct arglist *tokens;
923 struct assertion_hashnode {
924 struct assertion_hashnode *next; /* double links for easy deletion */
925 struct assertion_hashnode *prev;
926 /* also, a back pointer to this node's hash
927 chain is kept, in case the node is the head
928 of the chain and gets deleted. */
929 struct assertion_hashnode **bucket_hdr;
930 int length; /* length of token, for quick comparison */
931 U_CHAR *name; /* the actual name */
932 /* List of token-sequences. */
933 struct tokenlist_list *value;
936 typedef struct assertion_hashnode ASSERTION_HASHNODE;
938 /* Some definitions for the hash table. The hash function MUST be
939 computed as shown in hashf below. That is because the rescan
940 loop computes the hash value `on the fly' for most tokens,
941 in order to avoid the overhead of a lot of procedure calls to
942 the hashf function. hashf only exists for the sake of
943 politeness, for use when speed isn't so important. */
945 #define ASSERTION_HASHSIZE 37
946 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
948 /* Nonzero means inhibit macroexpansion of what seem to be
949 assertion tests, in rescan. For #if. */
950 static int assertions_flag;
952 /* `struct directive' defines one #-directive, including how to handle it. */
954 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
957 int length; /* Length of name */
958 int (*func) DO_PROTO; /* Function to handle directive */
959 char *name; /* Name of directive */
960 enum node_type type; /* Code which describes which directive. */
961 char angle_brackets; /* Nonzero => <...> is special. */
962 char traditional_comments; /* Nonzero: keep comments if -traditional. */
963 char pass_thru; /* Copy preprocessed directive to output file. */
966 /* These functions are declared to return int instead of void since they
967 are going to be placed in the table and some old compilers have trouble with
968 pointers to functions returning void. */
970 static int do_assert DO_PROTO;
971 static int do_define DO_PROTO;
972 static int do_elif DO_PROTO;
973 static int do_else DO_PROTO;
974 static int do_endif DO_PROTO;
975 static int do_error DO_PROTO;
976 static int do_ident DO_PROTO;
977 static int do_if DO_PROTO;
978 static int do_include DO_PROTO;
979 static int do_line DO_PROTO;
980 static int do_pragma DO_PROTO;
981 #ifdef SCCS_DIRECTIVE
982 static int do_sccs DO_PROTO;
984 static int do_unassert DO_PROTO;
985 static int do_undef DO_PROTO;
986 static int do_warning DO_PROTO;
987 static int do_xifdef DO_PROTO;
989 /* Here is the actual list of #-directives, most-often-used first. */
991 static struct directive directive_table[] = {
992 { 6, do_define, "define", T_DEFINE, 0, 1},
993 { 2, do_if, "if", T_IF},
994 { 5, do_xifdef, "ifdef", T_IFDEF},
995 { 6, do_xifdef, "ifndef", T_IFNDEF},
996 { 5, do_endif, "endif", T_ENDIF},
997 { 4, do_else, "else", T_ELSE},
998 { 4, do_elif, "elif", T_ELIF},
999 { 4, do_line, "line", T_LINE},
1000 { 7, do_include, "include", T_INCLUDE, 1},
1001 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
1002 { 6, do_include, "import", T_IMPORT, 1},
1003 { 5, do_undef, "undef", T_UNDEF},
1004 { 5, do_error, "error", T_ERROR},
1005 { 7, do_warning, "warning", T_WARNING},
1006 #ifdef SCCS_DIRECTIVE
1007 { 4, do_sccs, "sccs", T_SCCS},
1009 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
1010 { 5, do_ident, "ident", T_IDENT},
1011 { 6, do_assert, "assert", T_ASSERT},
1012 { 8, do_unassert, "unassert", T_UNASSERT},
1013 { -1, 0, "", T_UNUSED},
1016 /* When a directive handler is called,
1017 this points to the # (or the : of the %:) that started the directive. */
1018 U_CHAR *directive_start;
1020 /* table to tell if char can be part of a C identifier. */
1021 U_CHAR is_idchar[256];
1022 /* table to tell if char can be first char of a c identifier. */
1023 U_CHAR is_idstart[256];
1024 /* table to tell if c is horizontal space. */
1025 U_CHAR is_hor_space[256];
1026 /* table to tell if c is horizontal or vertical space. */
1027 static U_CHAR is_space[256];
1028 /* names of some characters */
1029 static char *char_name[256];
1031 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
1032 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
1034 static int errors = 0; /* Error counter for exit code */
1036 /* Name of output file, for error messages. */
1037 static char *out_fname;
1039 /* Zero means dollar signs are punctuation.
1040 -$ stores 0; -traditional may store 1. Default is 1 for VMS, 0 otherwise.
1041 This must be 0 for correct processing of this ANSI C program:
1043 #define lose(b) foo (b)
1046 static int dollars_in_ident;
1047 #ifndef DOLLARS_IN_IDENTIFIERS
1048 #define DOLLARS_IN_IDENTIFIERS 1
1052 /* Stack of conditionals currently in progress
1053 (including both successful and failing conditionals). */
1056 struct if_stack *next; /* for chaining to the next stack frame */
1057 char *fname; /* copied from input when frame is made */
1058 int lineno; /* similarly */
1059 int if_succeeded; /* true if a leg of this if-group
1060 has been passed through rescan */
1061 U_CHAR *control_macro; /* For #ifndef at start of file,
1062 this is the macro name tested. */
1063 enum node_type type; /* type of last directive seen in this group */
1065 typedef struct if_stack IF_STACK_FRAME;
1066 static IF_STACK_FRAME *if_stack = NULL;
1068 /* Buffer of -M output. */
1069 static char *deps_buffer;
1071 /* Number of bytes allocated in above. */
1072 static int deps_allocated_size;
1074 /* Number of bytes used. */
1075 static int deps_size;
1077 /* Number of bytes since the last newline. */
1078 static int deps_column;
1080 /* Nonzero means -I- has been seen,
1081 so don't look for #include "foo" the source-file directory. */
1082 static int ignore_srcdir;
1084 static int safe_read PROTO((int, char *, int));
1085 static void safe_write PROTO((int, char *, int));
1087 int main PROTO((int, char **));
1089 static void path_include PROTO((char *));
1091 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
1093 static void trigraph_pcp PROTO((FILE_BUF *));
1095 static void newline_fix PROTO((U_CHAR *));
1096 static void name_newline_fix PROTO((U_CHAR *));
1098 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
1100 static void rescan PROTO((FILE_BUF *, int));
1102 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
1104 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1106 static struct tm *timestamp PROTO((void));
1107 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1109 static int is_system_include PROTO((char *));
1110 static char *base_name PROTO((char *));
1111 static int absolute_filename PROTO((char *));
1112 static size_t simplify_filename PROTO((char *));
1114 static char *read_filename_string PROTO((int, FILE *));
1115 static struct file_name_map *read_name_map PROTO((char *));
1116 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
1117 static char *remap_include_file PROTO((char *, struct file_name_list *));
1118 static int lookup_ino_include PROTO((struct include_file *));
1120 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
1121 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
1123 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
1124 static int check_preconditions PROTO((char *));
1125 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1126 static void pcstring_used PROTO((HASHNODE *));
1127 static void write_output PROTO((void));
1128 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1130 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1132 static int check_macro_name PROTO((U_CHAR *, char *));
1133 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1134 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1136 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1138 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1139 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1141 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1142 static void free_token_list PROTO((struct arglist *));
1144 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1145 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1146 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1148 static void do_once PROTO((void));
1150 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1151 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1152 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1153 static void validate_else PROTO((U_CHAR *));
1155 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1156 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1157 static char *quote_string PROTO((char *, char *));
1158 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1160 /* Last arg to output_line_directive. */
1161 enum file_change_code {same_file, enter_file, leave_file};
1162 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1164 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1167 static char *macarg PROTO((struct argdata *, int));
1169 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1171 static int discard_comments PROTO((U_CHAR *, int, int));
1173 static int change_newlines PROTO((U_CHAR *, int));
1175 char *my_strerror PROTO((int));
1176 void error PRINTF_PROTO_1((char *, ...));
1177 static void verror PROTO((char *, va_list));
1178 static void error_from_errno PROTO((char *));
1179 void warning PRINTF_PROTO_1((char *, ...));
1180 static void vwarning PROTO((char *, va_list));
1181 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1182 static void verror_with_line PROTO((int, char *, va_list));
1183 static void vwarning_with_line PROTO((int, char *, va_list));
1184 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1185 void pedwarn PRINTF_PROTO_1((char *, ...));
1186 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1187 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1189 static void print_containing_files PROTO((void));
1191 static int line_for_error PROTO((int));
1192 static int grow_outbuf PROTO((FILE_BUF *, int));
1194 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1195 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1196 static void delete_macro PROTO((HASHNODE *));
1197 static int hashf PROTO((U_CHAR *, int, int));
1199 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1200 static void dump_all_macros PROTO((void));
1201 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1202 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1204 static void initialize_char_syntax PROTO((void));
1205 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1207 static void make_definition PROTO((char *, FILE_BUF *));
1208 static void make_undef PROTO((char *, FILE_BUF *));
1210 static void make_assertion PROTO((char *, char *));
1212 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *));
1213 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1215 static void deps_output PROTO((char *, int));
1217 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1218 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1219 static void perror_with_name PROTO((char *));
1220 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1221 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1223 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1224 GENERIC_PTR xmalloc PROTO((size_t));
1225 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1226 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1227 static char *savestring PROTO((char *));
1229 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1230 retrying if necessary. Return a negative value if an error occurs,
1231 otherwise return the actual number of bytes read,
1232 which must be LEN unless end-of-file was reached. */
1235 safe_read (desc, ptr, len)
1242 int nchars = read (desc, ptr, left);
1259 /* Write LEN bytes at PTR to descriptor DESC,
1260 retrying if necessary, and treating any real error as fatal. */
1263 safe_write (desc, ptr, len)
1269 int written = write (desc, ptr, len);
1276 pfatal_with_name (out_fname);
1293 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1294 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1295 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1296 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1297 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1299 /* Record the option used with each element of pend_assertions.
1300 This is preparation for supporting more than one option for making
1302 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1303 int inhibit_predefs = 0;
1304 int no_standard_includes = 0;
1305 int no_standard_cplusplus_includes = 0;
1306 int missing_newline = 0;
1308 /* Non-0 means don't output the preprocessed program. */
1309 int inhibit_output = 0;
1310 /* Non-0 means -v, so print the full set of include dirs. */
1313 /* File name which deps are being written to.
1314 This is 0 if deps are being written to stdout. */
1315 char *deps_file = 0;
1316 /* Fopen file mode to open deps_file with. */
1317 char *deps_mode = "a";
1318 /* Stream on which to print the dependency information. */
1319 FILE *deps_stream = 0;
1320 /* Target-name to write with the dependency information. */
1321 char *deps_target = 0;
1324 /* Get rid of any avoidable limit on stack size. */
1328 /* Set the stack limit huge so that alloca (particularly stringtab
1329 * in dbxread.c) does not fail. */
1330 getrlimit (RLIMIT_STACK, &rlim);
1331 rlim.rlim_cur = rlim.rlim_max;
1332 setrlimit (RLIMIT_STACK, &rlim);
1334 #endif /* RLIMIT_STACK defined */
1337 signal (SIGPIPE, pipe_closed);
1340 progname = base_name (argv[0]);
1344 /* Remove extension from PROGNAME. */
1346 char *s = progname = savestring (progname);
1348 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1349 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1350 && (p[1] == 'e' || p[1] == 'E')
1351 && (p[2] == 'x' || p[2] == 'X')
1352 && (p[3] == 'e' || p[3] == 'E')
1361 /* Initialize is_idchar to allow $. */
1362 dollars_in_ident = 1;
1363 initialize_char_syntax ();
1364 dollars_in_ident = DOLLARS_IN_IDENTIFIERS > 0;
1366 no_line_directives = 0;
1368 dump_macros = dump_none;
1371 cplusplus_comments = 1;
1373 bzero ((char *) pend_files, argc * sizeof (char *));
1374 bzero ((char *) pend_defs, argc * sizeof (char *));
1375 bzero ((char *) pend_undefs, argc * sizeof (char *));
1376 bzero ((char *) pend_assertions, argc * sizeof (char *));
1377 bzero ((char *) pend_includes, argc * sizeof (char *));
1379 /* Process switches and find input file name. */
1381 for (i = 1; i < argc; i++) {
1382 if (argv[i][0] != '-') {
1383 if (out_fname != NULL)
1384 fatal ("Usage: %s [switches] input output", argv[0]);
1385 else if (in_fname != NULL)
1386 out_fname = argv[i];
1390 switch (argv[i][1]) {
1393 if (!strcmp (argv[i], "-include")) {
1395 fatal ("Filename missing after `-include' option");
1397 simplify_filename (pend_includes[i] = argv[++i]);
1399 if (!strcmp (argv[i], "-imacros")) {
1401 fatal ("Filename missing after `-imacros' option");
1403 simplify_filename (pend_files[i] = argv[++i]);
1405 if (!strcmp (argv[i], "-iprefix")) {
1407 fatal ("Filename missing after `-iprefix' option");
1409 include_prefix = argv[++i];
1411 if (!strcmp (argv[i], "-ifoutput")) {
1412 output_conditionals = 1;
1414 if (!strcmp (argv[i], "-isystem")) {
1415 struct file_name_list *dirtmp;
1417 if (! (dirtmp = new_include_prefix (NULL_PTR, "", argv[++i])))
1419 dirtmp->c_system_include_path = 1;
1421 if (before_system == 0)
1422 before_system = dirtmp;
1424 last_before_system->next = dirtmp;
1425 last_before_system = dirtmp; /* Tail follows the last one */
1427 /* Add directory to end of path for includes,
1428 with the default prefix at the front of its name. */
1429 if (!strcmp (argv[i], "-iwithprefix")) {
1430 struct file_name_list *dirtmp;
1433 if (include_prefix != 0)
1434 prefix = include_prefix;
1436 prefix = savestring (GCC_INCLUDE_DIR);
1437 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1438 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1439 prefix[strlen (prefix) - 7] = 0;
1442 if (! (dirtmp = new_include_prefix (NULL_PTR, prefix, argv[++i])))
1445 if (after_include == 0)
1446 after_include = dirtmp;
1448 last_after_include->next = dirtmp;
1449 last_after_include = dirtmp; /* Tail follows the last one */
1451 /* Add directory to main path for includes,
1452 with the default prefix at the front of its name. */
1453 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1454 struct file_name_list *dirtmp;
1457 if (include_prefix != 0)
1458 prefix = include_prefix;
1460 prefix = savestring (GCC_INCLUDE_DIR);
1461 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1462 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1463 prefix[strlen (prefix) - 7] = 0;
1466 dirtmp = new_include_prefix (NULL_PTR, prefix, argv[++i]);
1467 append_include_chain (dirtmp, dirtmp);
1469 /* Add directory to end of path for includes. */
1470 if (!strcmp (argv[i], "-idirafter")) {
1471 struct file_name_list *dirtmp;
1473 if (! (dirtmp = new_include_prefix (NULL_PTR, "", argv[++i])))
1476 if (after_include == 0)
1477 after_include = dirtmp;
1479 last_after_include->next = dirtmp;
1480 last_after_include = dirtmp; /* Tail follows the last one */
1485 if (out_fname != NULL)
1486 fatal ("Output filename specified twice");
1488 fatal ("Filename missing after -o option");
1489 out_fname = argv[++i];
1490 if (!strcmp (out_fname, "-"))
1495 if (!strcmp (argv[i], "-pedantic"))
1497 else if (!strcmp (argv[i], "-pedantic-errors")) {
1499 pedantic_errors = 1;
1500 } else if (!strcmp (argv[i], "-pcp")) {
1503 fatal ("Filename missing after -pcp option");
1504 pcp_fname = argv[++i];
1506 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1507 ? fopen (pcp_fname, "w")
1509 if (pcp_outfile == 0)
1510 pfatal_with_name (pcp_fname);
1516 if (!strcmp (argv[i], "-traditional")) {
1518 cplusplus_comments = 0;
1519 if (dollars_in_ident > 0)
1520 dollars_in_ident = 1;
1521 } else if (!strcmp (argv[i], "-trigraphs")) {
1527 if (! strcmp (argv[i], "-lang-c"))
1528 cplusplus = 0, cplusplus_comments = 1, objc = 0;
1529 if (! strcmp (argv[i], "-lang-c89"))
1530 cplusplus = 0, cplusplus_comments = 0, objc = 0;
1531 if (! strcmp (argv[i], "-lang-c++"))
1532 cplusplus = 1, cplusplus_comments = 1, objc = 0;
1533 if (! strcmp (argv[i], "-lang-objc"))
1534 objc = 1, cplusplus = 0, cplusplus_comments = 1;
1535 if (! strcmp (argv[i], "-lang-objc++"))
1536 objc = 1, cplusplus = 1, cplusplus_comments = 1;
1537 if (! strcmp (argv[i], "-lang-asm"))
1539 if (! strcmp (argv[i], "-lint"))
1544 cplusplus = 1, cplusplus_comments = 1;
1548 inhibit_warnings = 1;
1552 if (!strcmp (argv[i], "-Wtrigraphs"))
1554 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1556 else if (!strcmp (argv[i], "-Wcomment"))
1558 else if (!strcmp (argv[i], "-Wno-comment"))
1560 else if (!strcmp (argv[i], "-Wcomments"))
1562 else if (!strcmp (argv[i], "-Wno-comments"))
1564 else if (!strcmp (argv[i], "-Wtraditional"))
1566 else if (!strcmp (argv[i], "-Wno-traditional"))
1568 else if (!strcmp (argv[i], "-Wimport"))
1570 else if (!strcmp (argv[i], "-Wno-import"))
1572 else if (!strcmp (argv[i], "-Werror"))
1573 warnings_are_errors = 1;
1574 else if (!strcmp (argv[i], "-Wno-error"))
1575 warnings_are_errors = 0;
1576 else if (!strcmp (argv[i], "-Wall"))
1584 /* The style of the choices here is a bit mixed.
1585 The chosen scheme is a hybrid of keeping all options in one string
1586 and specifying each option in a separate argument:
1587 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1588 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1589 -M[M][G][D file]. This is awkward to handle in specs, and is not
1591 /* ??? -MG must be specified in addition to one of -M or -MM.
1592 This can be relaxed in the future without breaking anything.
1593 The converse isn't true. */
1595 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1596 if (!strcmp (argv[i], "-MG"))
1598 print_deps_missing_files = 1;
1601 if (!strcmp (argv[i], "-M"))
1603 else if (!strcmp (argv[i], "-MM"))
1605 else if (!strcmp (argv[i], "-MD"))
1607 else if (!strcmp (argv[i], "-MMD"))
1609 /* For -MD and -MMD options, write deps on file named by next arg. */
1610 if (!strcmp (argv[i], "-MD")
1611 || !strcmp (argv[i], "-MMD")) {
1613 fatal ("Filename missing after %s option", argv[i]);
1615 deps_file = argv[i];
1618 /* For -M and -MM, write deps on standard output
1619 and suppress the usual output. */
1620 deps_stream = stdout;
1627 char *p = argv[i] + 2;
1629 while ((c = *p++)) {
1630 /* Arg to -d specifies what parts of macros to dump */
1633 dump_macros = dump_only;
1637 dump_macros = dump_names;
1640 dump_macros = dump_definitions;
1648 if (argv[i][2] == '3')
1653 fprintf (stderr, "GNU CPP version %s", version_string);
1654 #ifdef TARGET_VERSION
1657 fprintf (stderr, "\n");
1662 print_include_names = 1;
1666 if (argv[i][2] != 0)
1667 pend_defs[i] = argv[i] + 2;
1668 else if (i + 1 == argc)
1669 fatal ("Macro name missing after -D option");
1671 i++, pend_defs[i] = argv[i];
1678 if (argv[i][2] != 0)
1680 else if (i + 1 == argc)
1681 fatal ("Assertion missing after -A option");
1685 if (!strcmp (p, "-")) {
1686 /* -A- eliminates all predefined macros and assertions.
1687 Let's include also any that were specified earlier
1688 on the command line. That way we can get rid of any
1689 that were passed automatically in from GCC. */
1691 inhibit_predefs = 1;
1692 for (j = 0; j < i; j++)
1693 pend_defs[j] = pend_assertions[j] = 0;
1695 pend_assertions[i] = p;
1696 pend_assertion_options[i] = "-A";
1701 case 'U': /* JF #undef something */
1702 if (argv[i][2] != 0)
1703 pend_undefs[i] = argv[i] + 2;
1704 else if (i + 1 == argc)
1705 fatal ("Macro name missing after -U option");
1707 pend_undefs[i] = argv[i+1], i++;
1711 put_out_comments = 1;
1714 case 'E': /* -E comes from cc -E; ignore it. */
1718 no_line_directives = 1;
1721 case '$': /* Don't include $ in identifiers. */
1722 dollars_in_ident = 0;
1725 case 'I': /* Add directory to path for includes. */
1727 struct file_name_list *dirtmp;
1729 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1731 /* Don't use any preceding -I directories for #include <...>. */
1732 first_bracket_include = 0;
1735 dirtmp = new_include_prefix (last_include, "",
1736 argv[i][2] ? argv[i] + 2 : argv[++i]);
1737 append_include_chain (dirtmp, dirtmp);
1743 if (!strcmp (argv[i], "-nostdinc"))
1744 /* -nostdinc causes no default include directories.
1745 You must specify all include-file directories with -I. */
1746 no_standard_includes = 1;
1747 else if (!strcmp (argv[i], "-nostdinc++"))
1748 /* -nostdinc++ causes no default C++-specific include directories. */
1749 no_standard_cplusplus_includes = 1;
1750 else if (!strcmp (argv[i], "-noprecomp"))
1755 /* Sun compiler passes undocumented switch "-undef".
1756 Let's assume it means to inhibit the predefined symbols. */
1757 inhibit_predefs = 1;
1760 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1761 if (in_fname == NULL) {
1764 } else if (out_fname == NULL) {
1767 } /* else fall through into error */
1770 fatal ("Invalid option `%s'", argv[i]);
1775 /* Add dirs from CPATH after dirs from -I. */
1776 /* There seems to be confusion about what CPATH should do,
1777 so for the moment it is not documented. */
1778 /* Some people say that CPATH should replace the standard include dirs,
1779 but that seems pointless: it comes before them, so it overrides them
1781 cp = getenv ("CPATH");
1782 if (cp && ! no_standard_includes)
1785 /* Now that dollars_in_ident is known, initialize is_idchar. */
1786 initialize_char_syntax ();
1788 /* Initialize output buffer */
1790 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1791 outbuf.bufp = outbuf.buf;
1792 outbuf.length = OUTBUF_SIZE;
1794 /* Do partial setup of input buffer for the sake of generating
1795 early #line directives (when -g is in effect). */
1797 fp = &instack[++indepth];
1798 if (in_fname == NULL)
1800 fp->nominal_fname = fp->fname = in_fname;
1803 /* In C++, wchar_t is a distinct basic type, and we can expect
1804 __wchar_t to be defined by cc1plus. */
1806 wchar_type = "__wchar_t";
1808 /* Install __LINE__, etc. Must follow initialize_char_syntax
1809 and option processing. */
1810 initialize_builtins (fp, &outbuf);
1812 /* Do standard #defines and assertions
1813 that identify system and machine type. */
1815 if (!inhibit_predefs) {
1816 char *p = (char *) alloca (strlen (predefs) + 1);
1817 strcpy (p, predefs);
1820 while (*p == ' ' || *p == '\t')
1822 /* Handle -D options. */
1823 if (p[0] == '-' && p[1] == 'D') {
1825 while (*p && *p != ' ' && *p != '\t')
1830 output_line_directive (fp, &outbuf, 0, same_file);
1831 make_definition (q, &outbuf);
1832 while (*p == ' ' || *p == '\t')
1834 } else if (p[0] == '-' && p[1] == 'A') {
1835 /* Handle -A options (assertions). */
1844 past_name = assertion;
1845 /* Locate end of name. */
1846 while (*past_name && *past_name != ' '
1847 && *past_name != '\t' && *past_name != '(')
1849 /* Locate `(' at start of value. */
1851 while (*value && (*value == ' ' || *value == '\t'))
1853 if (*value++ != '(')
1855 while (*value && (*value == ' ' || *value == '\t'))
1858 /* Locate end of value. */
1859 while (*past_value && *past_value != ' '
1860 && *past_value != '\t' && *past_value != ')')
1862 termination = past_value;
1863 while (*termination && (*termination == ' ' || *termination == '\t'))
1865 if (*termination++ != ')')
1867 if (*termination && *termination != ' ' && *termination != '\t')
1869 /* Temporarily null-terminate the value. */
1870 save_char = *termination;
1871 *termination = '\0';
1872 /* Install the assertion. */
1873 make_assertion ("-A", assertion);
1874 *termination = (char) save_char;
1876 while (*p == ' ' || *p == '\t')
1884 /* Now handle the command line options. */
1886 /* Do -U's, -D's and -A's in the order they were seen. */
1887 for (i = 1; i < argc; i++) {
1888 if (pend_undefs[i]) {
1890 output_line_directive (fp, &outbuf, 0, same_file);
1891 make_undef (pend_undefs[i], &outbuf);
1895 output_line_directive (fp, &outbuf, 0, same_file);
1896 make_definition (pend_defs[i], &outbuf);
1898 if (pend_assertions[i])
1899 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1902 done_initializing = 1;
1904 { /* read the appropriate environment variable and if it exists
1905 replace include_defaults with the listed path. */
1907 switch ((objc << 1) + cplusplus)
1910 epath = getenv ("C_INCLUDE_PATH");
1913 epath = getenv ("CPLUS_INCLUDE_PATH");
1916 epath = getenv ("OBJC_INCLUDE_PATH");
1919 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1922 /* If the environment var for this language is set,
1923 add to the default list of include directories. */
1926 char *startp, *endp;
1928 for (num_dirs = 1, startp = epath; *startp; startp++)
1929 if (*startp == PATH_SEPARATOR)
1932 = (struct default_include *) xmalloc ((num_dirs
1933 * sizeof (struct default_include))
1934 + sizeof (include_defaults_array));
1935 startp = endp = epath;
1939 if (c == PATH_SEPARATOR || !c) {
1941 include_defaults[num_dirs].fname
1942 = startp == endp ? "." : savestring (startp);
1944 include_defaults[num_dirs].cplusplus = cplusplus;
1945 include_defaults[num_dirs].cxx_aware = 1;
1952 /* Put the usual defaults back in at the end. */
1953 bcopy ((char *) include_defaults_array,
1954 (char *) &include_defaults[num_dirs],
1955 sizeof (include_defaults_array));
1959 append_include_chain (before_system, last_before_system);
1960 first_system_include = before_system;
1962 /* Unless -fnostdinc,
1963 tack on the standard include file dirs to the specified list */
1964 if (!no_standard_includes) {
1965 struct default_include *p = include_defaults;
1966 char *specd_prefix = include_prefix;
1967 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1968 int default_len = 0;
1969 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1970 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1971 default_len = strlen (default_prefix) - 7;
1972 default_prefix[default_len] = 0;
1974 /* Search "translated" versions of GNU directories.
1975 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1976 if (specd_prefix != 0 && default_len != 0)
1977 for (p = include_defaults; p->fname; p++) {
1978 /* Some standard dirs are only for C++. */
1979 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1980 /* Does this dir start with the prefix? */
1981 if (!strncmp (p->fname, default_prefix, default_len)) {
1982 /* Yes; change prefix and add to search list. */
1983 struct file_name_list *new
1984 = new_include_prefix (NULL_PTR, specd_prefix,
1985 p->fname + default_len);
1987 new->c_system_include_path = !p->cxx_aware;
1988 append_include_chain (new, new);
1989 if (first_system_include == 0)
1990 first_system_include = new;
1995 /* Search ordinary names for GNU include directories. */
1996 for (p = include_defaults; p->fname; p++) {
1997 /* Some standard dirs are only for C++. */
1998 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1999 struct file_name_list *new
2000 = new_include_prefix (NULL_PTR, "", p->fname);
2002 new->c_system_include_path = !p->cxx_aware;
2003 append_include_chain (new, new);
2004 if (first_system_include == 0)
2005 first_system_include = new;
2011 /* Tack the after_include chain at the end of the include chain. */
2012 append_include_chain (after_include, last_after_include);
2013 if (first_system_include == 0)
2014 first_system_include = after_include;
2016 /* With -v, print the list of dirs to search. */
2018 struct file_name_list *p;
2019 fprintf (stderr, "#include \"...\" search starts here:\n");
2020 for (p = include; p; p = p->next) {
2021 if (p == first_bracket_include)
2022 fprintf (stderr, "#include <...> search starts here:\n");
2024 fprintf (stderr, " .\n");
2025 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
2026 fprintf (stderr, " %s\n", p->fname);
2028 /* Omit trailing '/'. */
2029 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
2031 fprintf (stderr, "End of search list.\n");
2034 /* -MG doesn't select the form of output and must be specified with one of
2035 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2036 inhibit compilation. */
2037 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2038 fatal ("-MG must be specified with one of -M or -MM");
2040 /* Either of two environment variables can specify output of deps.
2041 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2042 where OUTPUT_FILE is the file to write deps info to
2043 and DEPS_TARGET is the target to mention in the deps. */
2046 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2047 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2048 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2053 spec = getenv ("SUNPRO_DEPENDENCIES");
2060 /* Find the space before the DEPS_TARGET, if there is one. */
2061 /* This should use index. (mrs) */
2062 while (*s != 0 && *s != ' ') s++;
2064 deps_target = s + 1;
2065 output_file = xmalloc (s - spec + 1);
2066 bcopy (spec, output_file, s - spec);
2067 output_file[s - spec] = 0;
2074 deps_file = output_file;
2078 /* For -M, print the expected object file name
2079 as the target of this Make-rule. */
2081 deps_allocated_size = 200;
2082 deps_buffer = xmalloc (deps_allocated_size);
2088 deps_output (deps_target, ':');
2089 } else if (*in_fname == 0) {
2090 deps_output ("-", ':');
2095 q = base_name (in_fname);
2097 /* Copy remainder to mungable area. */
2098 p = (char *) alloca (strlen(q) + 8);
2101 /* Output P, but remove known suffixes. */
2105 && p[len - 2] == '.'
2106 && index("cCsSm", p[len - 1]))
2109 && p[len - 3] == '.'
2110 && p[len - 2] == 'c'
2111 && p[len - 1] == 'c')
2114 && p[len - 4] == '.'
2115 && p[len - 3] == 'c'
2116 && p[len - 2] == 'x'
2117 && p[len - 1] == 'x')
2120 && p[len - 4] == '.'
2121 && p[len - 3] == 'c'
2122 && p[len - 2] == 'p'
2123 && p[len - 1] == 'p')
2126 /* Supply our own suffix. */
2133 deps_output (p, ':');
2134 deps_output (in_fname, ' ');
2138 /* Scan the -imacros files before the main input.
2139 Much like #including them, but with no_output set
2140 so that only their macro definitions matter. */
2142 no_output++; no_record_file++;
2143 for (i = 1; i < argc; i++)
2144 if (pend_files[i]) {
2145 struct include_file *inc;
2146 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2148 perror_with_name (pend_files[i]);
2149 return FATAL_EXIT_CODE;
2151 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2153 no_output--; no_record_file--;
2155 /* Copy the entire contents of the main input file into
2156 the stacked input buffer previously allocated for it. */
2158 /* JF check for stdin */
2159 if (in_fname == NULL || *in_fname == 0) {
2162 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2165 if (fstat (f, &st) != 0)
2166 pfatal_with_name (in_fname);
2167 fp->nominal_fname = fp->fname = in_fname;
2169 fp->system_header_p = 0;
2170 /* JF all this is mine about reading pipes and ttys */
2171 if (! S_ISREG (st.st_mode)) {
2172 /* Read input from a file that is not a normal disk file.
2173 We cannot preallocate a buffer with the correct size,
2174 so we must read in the file a piece at the time and make it bigger. */
2179 if (S_ISDIR (st.st_mode))
2180 fatal ("Input file `%s' is a directory", in_fname);
2184 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2186 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2187 if (cnt < 0) goto perror; /* error! */
2189 if (size != bsize) break; /* End of file */
2191 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2195 /* Read a file whose size we can determine in advance.
2196 For the sake of VMS, st.st_size is just an upper bound. */
2197 fp->buf = (U_CHAR *) xmalloc (st.st_size + 2);
2198 fp->length = safe_read (f, (char *) fp->buf, st.st_size);
2199 if (fp->length < 0) goto perror;
2202 fp->if_stack = if_stack;
2204 /* Make sure data ends with a newline. And put a null after it. */
2206 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2207 /* Backslash-newline at end is not good enough. */
2208 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2209 fp->buf[fp->length++] = '\n';
2210 missing_newline = 1;
2212 fp->buf[fp->length] = '\0';
2214 /* Unless inhibited, convert trigraphs in the input. */
2219 /* Now that we know the input file is valid, open the output. */
2221 if (!out_fname || !strcmp (out_fname, ""))
2222 out_fname = "stdout";
2223 else if (! freopen (out_fname, "w", stdout))
2224 pfatal_with_name (out_fname);
2226 output_line_directive (fp, &outbuf, 0, same_file);
2228 /* Scan the -include files before the main input. */
2231 for (i = 1; i < argc; i++)
2232 if (pend_includes[i]) {
2233 struct include_file *inc;
2234 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2236 perror_with_name (pend_includes[i]);
2237 return FATAL_EXIT_CODE;
2239 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2243 /* Scan the input, processing macros and directives. */
2245 rescan (&outbuf, 0);
2247 if (missing_newline)
2250 if (pedantic && missing_newline)
2251 pedwarn ("file does not end in newline");
2253 /* Now we have processed the entire input
2254 Write whichever kind of output has been requested. */
2256 if (dump_macros == dump_only)
2258 else if (! inhibit_output) {
2263 /* Don't actually write the deps file if compilation has failed. */
2265 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2266 pfatal_with_name (deps_file);
2267 fputs (deps_buffer, deps_stream);
2268 putc ('\n', deps_stream);
2270 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2271 fatal ("I/O error on output");
2276 if (pcp_outfile && pcp_outfile != stdout
2277 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2278 fatal ("I/O error on `-pcp' output");
2280 if (ferror (stdout) || fclose (stdout) != 0)
2281 fatal ("I/O error on output");
2284 exit (FATAL_EXIT_CODE);
2285 exit (SUCCESS_EXIT_CODE);
2288 pfatal_with_name (in_fname);
2292 /* Given a colon-separated list of file names PATH,
2293 add all the names to the search path for include files. */
2307 struct file_name_list *dirtmp;
2309 /* Find the end of this name. */
2310 while ((c = *q++) != PATH_SEPARATOR && c)
2314 dirtmp = new_include_prefix (last_include, "", p == q ? "." : p);
2316 append_include_chain (dirtmp, dirtmp);
2318 /* Advance past this name. */
2325 /* Return the address of the first character in S that equals C.
2326 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2327 Return 0 if there is no such character. Assume that C itself is not '\0'.
2328 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2329 but unfortunately memchr isn't autoconfigured yet. */
2337 char *p = (char *) s;
2339 char *q = index (p, c);
2341 return (U_CHAR *) q;
2343 size_t l = strlen (p);
2353 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2354 before main CCCP processing. Name `pcp' is also in honor of the
2355 drugs the trigraph designers must have been on.
2357 Using an extra pass through the buffer takes a little extra time,
2358 but is infinitely less hairy than trying to handle trigraphs inside
2359 strings, etc. everywhere, and also makes sure that trigraphs are
2360 only translated in the top level of processing. */
2366 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2369 fptr = bptr = sptr = buf->buf;
2370 lptr = fptr + buf->length;
2371 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2408 len = sptr - fptr - 2;
2410 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2411 C, this will be memmove (). */
2412 if (bptr != fptr && len > 0)
2413 bcopy ((char *) fptr, (char *) bptr, len);
2419 len = buf->length - (fptr - buf->buf);
2420 if (bptr != fptr && len > 0)
2421 bcopy ((char *) fptr, (char *) bptr, len);
2422 buf->length -= fptr - bptr;
2423 buf->buf[buf->length] = '\0';
2424 if (warn_trigraphs && fptr != bptr)
2425 warning_with_line (0, "%d trigraph(s) encountered", (fptr - bptr) / 2);
2428 /* Move all backslash-newline pairs out of embarrassing places.
2429 Exchange all such pairs following BP
2430 with any potentially-embarrassing characters that follow them.
2431 Potentially-embarrassing characters are / and *
2432 (because a backslash-newline inside a comment delimiter
2433 would cause it not to be recognized). */
2439 register U_CHAR *p = bp;
2441 /* First count the backslash-newline pairs here. */
2443 while (p[0] == '\\' && p[1] == '\n')
2446 /* What follows the backslash-newlines is not embarrassing. */
2448 if (*p != '/' && *p != '*')
2451 /* Copy all potentially embarrassing characters
2452 that follow the backslash-newline pairs
2453 down to where the pairs originally started. */
2455 while (*p == '*' || *p == '/')
2458 /* Now write the same number of pairs after the embarrassing chars. */
2465 /* Like newline_fix but for use within a directive-name.
2466 Move any backslash-newlines up past any following symbol constituents. */
2469 name_newline_fix (bp)
2472 register U_CHAR *p = bp;
2474 /* First count the backslash-newline pairs here. */
2475 while (p[0] == '\\' && p[1] == '\n')
2478 /* What follows the backslash-newlines is not embarrassing. */
2483 /* Copy all potentially embarrassing characters
2484 that follow the backslash-newline pairs
2485 down to where the pairs originally started. */
2487 while (is_idchar[*p])
2490 /* Now write the same number of pairs after the embarrassing chars. */
2497 /* Look for lint commands in comments.
2499 When we come in here, ibp points into a comment. Limit is as one expects.
2500 scan within the comment -- it should start, after lwsp, with a lint command.
2501 If so that command is returned as a (constant) string.
2503 Upon return, any arg will be pointed to with argstart and will be
2504 arglen long. Note that we don't parse that arg since it will just
2505 be printed out again.
2509 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2510 register U_CHAR *ibp;
2511 register U_CHAR *limit;
2512 U_CHAR **argstart; /* point to command arg */
2513 int *arglen, *cmdlen; /* how long they are */
2516 register U_CHAR *numptr; /* temp for arg parsing */
2520 SKIP_WHITE_SPACE (ibp);
2522 if (ibp >= limit) return NULL;
2524 linsize = limit - ibp;
2526 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2527 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2529 return "NOTREACHED";
2531 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2535 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2537 return "LINTLIBRARY";
2539 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2541 ibp += 7; linsize -= 7;
2542 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2544 /* OK, read a number */
2545 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2547 *arglen = numptr - *argstart;
2554 * The main loop of the program.
2556 * Read characters from the input stack, transferring them to the
2559 * Macros are expanded and push levels on the input stack.
2560 * At the end of such a level it is popped off and we keep reading.
2561 * At the end of any other kind of level, we return.
2562 * #-directives are handled, except within macros.
2564 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2565 * and insert them when appropriate. This is set while scanning macro
2566 * arguments before substitution. It is zero when scanning for final output.
2567 * There are three types of Newline markers:
2568 * * Newline - follows a macro name that was not expanded
2569 * because it appeared inside an expansion of the same macro.
2570 * This marker prevents future expansion of that identifier.
2571 * When the input is rescanned into the final output, these are deleted.
2572 * These are also deleted by ## concatenation.
2573 * * Newline Space (or Newline and any other whitespace character)
2574 * stands for a place that tokens must be separated or whitespace
2575 * is otherwise desirable, but where the ANSI standard specifies there
2576 * is no whitespace. This marker turns into a Space (or whichever other
2577 * whitespace char appears in the marker) in the final output,
2578 * but it turns into nothing in an argument that is stringified with #.
2579 * Such stringified arguments are the only place where the ANSI standard
2580 * specifies with precision that whitespace may not appear.
2582 * During this function, IP->bufp is kept cached in IBP for speed of access.
2583 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2584 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2585 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2586 * explicitly, and before RECACHE, since RECACHE uses OBP.
2590 rescan (op, output_marks)
2594 /* Character being scanned in main loop. */
2597 /* Length of pending accumulated identifier. */
2598 register int ident_length = 0;
2600 /* Hash code of pending accumulated identifier. */
2601 register int hash = 0;
2603 /* Current input level (&instack[indepth]). */
2606 /* Pointer for scanning input. */
2607 register U_CHAR *ibp;
2609 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2610 register U_CHAR *limit;
2612 /* Pointer for storing output. */
2613 register U_CHAR *obp;
2615 /* REDO_CHAR is nonzero if we are processing an identifier
2616 after backing up over the terminating character.
2617 Sometimes we process an identifier without backing up over
2618 the terminating character, if the terminating character
2619 is not special. Backing up is done so that the terminating character
2620 will be dispatched on again once the identifier is dealt with. */
2623 /* 1 if within an identifier inside of which a concatenation
2624 marker (Newline -) has been seen. */
2625 int concatenated = 0;
2627 /* While scanning a comment or a string constant,
2628 this records the line it started on, for error messages. */
2631 /* Record position of last `real' newline. */
2632 U_CHAR *beg_of_line;
2634 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2637 do { ip->macro->type = T_MACRO; \
2638 if (ip->free_ptr) free (ip->free_ptr); \
2639 --indepth; } while (0)
2641 /* Reload `rescan's local variables that describe the current
2642 level of the input stack. */
2645 do { ip = &instack[indepth]; \
2647 limit = ip->buf + ip->length; \
2649 check_expand (op, limit - ibp); \
2651 obp = op->bufp; } while (0)
2653 if (no_output && instack[indepth].fname != 0)
2654 skip_if_group (&instack[indepth], 1, NULL);
2661 /* Our caller must always put a null after the end of
2662 the input at each input stack level. */
2672 if (*ibp == '\n' && !ip->macro) {
2673 /* At the top level, always merge lines ending with backslash-newline,
2674 even in middle of identifier. But do not merge lines in a macro,
2675 since backslash might be followed by a newline-space marker. */
2678 --obp; /* remove backslash from obuf */
2681 /* If ANSI, backslash is just another character outside a string. */
2684 /* Otherwise, backslash suppresses specialness of following char,
2685 so copy it here to prevent the switch from seeing it.
2686 But first get any pending identifier processed. */
2687 if (ident_length > 0)
2694 if (ident_length || ip->macro || traditional)
2696 while (*ibp == '\\' && ibp[1] == '\n') {
2702 /* Treat this %: digraph as if it were #. */
2706 if (assertions_flag) {
2709 /* Copy #foo (bar lose) without macro expansion. */
2710 obp[-1] = '#'; /* In case it was '%'. */
2711 SKIP_WHITE_SPACE (ibp);
2712 while (is_idchar[*ibp])
2714 SKIP_WHITE_SPACE (ibp);
2717 skip_paren_group (ip);
2718 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2719 obp += ip->bufp - ibp;
2725 /* If this is expanding a macro definition, don't recognize
2726 preprocessing directives. */
2729 /* If this is expand_into_temp_buffer,
2730 don't recognize them either. Warn about them
2731 only after an actual newline at this level,
2732 not at the beginning of the input level. */
2734 if (ip->buf != beg_of_line)
2735 warning ("preprocessing directive not recognized within macro arg");
2742 /* # keyword: a # must be first nonblank char on the line */
2743 if (beg_of_line == 0)
2748 /* Scan from start of line, skipping whitespace, comments
2749 and backslash-newlines, and see if we reach this #.
2750 If not, this # is not special. */
2752 /* If -traditional, require # to be at beginning of line. */
2755 if (is_hor_space[*bp])
2757 else if (*bp == '\\' && bp[1] == '\n')
2759 else if (*bp == '/' && bp[1] == '*') {
2761 while (!(*bp == '*' && bp[1] == '/'))
2765 /* There is no point in trying to deal with C++ // comments here,
2766 because if there is one, then this # must be part of the
2767 comment and we would never reach here. */
2773 while (bp[1] == '\\' && bp[2] == '\n')
2777 /* %: appears at start of line; skip past the ':' too. */
2786 /* This # can start a directive. */
2788 --obp; /* Don't copy the '#' */
2792 if (! handle_directive (ip, op)) {
2796 /* Not a known directive: treat it as ordinary text.
2797 IP, OP, IBP, etc. have not been changed. */
2798 if (no_output && instack[indepth].fname) {
2799 /* If not generating expanded output,
2800 what we do with ordinary text is skip it.
2801 Discard everything until next # directive. */
2802 skip_if_group (&instack[indepth], 1, 0);
2807 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2808 /* Don't expand an identifier that could be a macro directive.
2809 (Section 3.8.3 of the ANSI C standard) */
2810 SKIP_WHITE_SPACE (ibp);
2811 if (is_idstart[*ibp])
2814 while (is_idchar[*ibp])
2822 /* A # directive has been successfully processed. */
2823 /* If not generating expanded output, ignore everything until
2824 next # directive. */
2825 if (no_output && instack[indepth].fname)
2826 skip_if_group (&instack[indepth], 1, 0);
2832 case '\"': /* skip quoted string */
2834 /* A single quoted string is treated like a double -- some
2835 programs (e.g., troff) are perverse this way */
2840 start_line = ip->lineno;
2842 /* Skip ahead to a matching quote. */
2846 if (ip->macro != 0) {
2847 /* try harder: this string crosses a macro expansion boundary.
2848 This can happen naturally if -traditional.
2849 Otherwise, only -D can make a macro with an unmatched quote. */
2855 error_with_line (line_for_error (start_line),
2856 "unterminated string or character constant");
2857 error_with_line (multiline_string_line,
2858 "possible real start of unterminated constant");
2859 multiline_string_line = 0;
2868 /* Traditionally, end of line ends a string constant with no error.
2869 So exit the loop and record the new line. */
2875 error_with_line (line_for_error (start_line),
2876 "unterminated character constant");
2879 if (pedantic && multiline_string_line == 0) {
2880 pedwarn_with_line (line_for_error (start_line),
2881 "string constant runs past end of line");
2883 if (multiline_string_line == 0)
2884 multiline_string_line = ip->lineno - 1;
2891 /* Backslash newline is replaced by nothing at all,
2892 but keep the line counts correct. */
2897 /* ANSI stupidly requires that in \\ the second \
2898 is *not* prevented from combining with a newline. */
2899 while (*ibp == '\\' && ibp[1] == '\n') {
2918 if (*ibp == '\\' && ibp[1] == '\n')
2922 && !(cplusplus_comments && *ibp == '/'))
2930 /* C++ style comment... */
2931 start_line = ip->lineno;
2933 /* Comments are equivalent to spaces. */
2934 if (! put_out_comments)
2938 U_CHAR *before_bp = ibp;
2940 while (++ibp < limit) {
2942 if (ibp[-1] != '\\') {
2943 if (put_out_comments) {
2944 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2945 obp += ibp - before_bp;
2950 warning ("multiline `//' comment");
2952 /* Copy the newline into the output buffer, in order to
2953 avoid the pain of a #line every time a multiline comment
2955 if (!put_out_comments)
2964 /* Ordinary C comment. Skip it, optionally copying it to output. */
2966 start_line = ip->lineno;
2968 ++ibp; /* Skip the star. */
2970 /* If this cpp is for lint, we peek inside the comments: */
2974 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2976 if (lintcmd != NULL) {
2978 check_expand (op, cmdlen + arglen + 14);
2980 /* I believe it is always safe to emit this newline: */
2982 bcopy ("#pragma lint ", (char *) obp, 13);
2984 bcopy (lintcmd, (char *) obp, cmdlen);
2989 bcopy (argbp, (char *) obp, arglen);
2993 /* OK, now bring us back to the state we were in before we entered
2994 this branch. We need #line because the #pragma's newline always
2995 messes up the line count. */
2997 output_line_directive (ip, op, 0, same_file);
2998 check_expand (op, limit - ibp + 2);
3004 /* Comments are equivalent to spaces.
3005 Note that we already output the slash; we might not want it.
3006 For -traditional, a comment is equivalent to nothing. */
3007 if (! put_out_comments) {
3017 U_CHAR *before_bp = ibp;
3022 if (ibp[-2] == '/' && warn_comments)
3023 warning ("`/*' within comment");
3024 if (*ibp == '\\' && ibp[1] == '\n')
3032 /* Copy the newline into the output buffer, in order to
3033 avoid the pain of a #line every time a multiline comment
3035 if (!put_out_comments)
3042 error_with_line (line_for_error (start_line),
3043 "unterminated comment");
3052 if (put_out_comments) {
3053 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3054 obp += ibp - before_bp;
3060 if (!dollars_in_ident)
3064 case '0': case '1': case '2': case '3': case '4':
3065 case '5': case '6': case '7': case '8': case '9':
3066 /* If digit is not part of identifier, it starts a number,
3067 which means that following letters are not an identifier.
3068 "0x5" does not refer to an identifier "x5".
3069 So copy all alphanumerics that follow without accumulating
3070 as an identifier. Periods also, for sake of "3.e7". */
3072 if (ident_length == 0) {
3074 while (ibp[0] == '\\' && ibp[1] == '\n') {
3079 if (!is_idchar[c] && c != '.') {
3084 /* A sign can be part of a preprocessing number
3085 if it follows an e. */
3086 if (c == 'e' || c == 'E') {
3087 while (ibp[0] == '\\' && ibp[1] == '\n') {
3091 if (*ibp == '+' || *ibp == '-') {
3093 /* But traditional C does not let the token go past the sign. */
3104 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3105 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3106 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3107 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3109 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3110 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3111 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3112 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3116 /* Compute step of hash function, to avoid a proc call on every token */
3117 hash = HASHSTEP (hash, c);
3121 if (ip->fname == 0 && *ibp == '-') {
3122 /* Newline - inhibits expansion of preceding token.
3123 If expanding a macro arg, we keep the newline -.
3124 In final output, it is deleted.
3125 We recognize Newline - in macro bodies and macro args. */
3126 if (! concatenated) {
3131 if (!output_marks) {
3134 /* If expanding a macro arg, keep the newline -. */
3140 /* If reprocessing a macro expansion, newline is a special marker. */
3141 else if (ip->macro != 0) {
3142 /* Newline White is a "funny space" to separate tokens that are
3143 supposed to be separate but without space between.
3144 Here White means any whitespace character.
3145 Newline - marks a recursive macro use that is not
3146 supposed to be expandable. */
3148 if (is_space[*ibp]) {
3149 /* Newline Space does not prevent expansion of preceding token
3150 so expand the preceding token and then come back. */
3151 if (ident_length > 0)
3154 /* If generating final output, newline space makes a space. */
3155 if (!output_marks) {
3157 /* And Newline Newline makes a newline, so count it. */
3158 if (obp[-1] == '\n')
3161 /* If expanding a macro arg, keep the newline space.
3162 If the arg gets stringified, newline space makes nothing. */
3165 } else abort (); /* Newline followed by something random? */
3169 /* If there is a pending identifier, handle it and come back here. */
3170 if (ident_length > 0)
3175 /* Update the line counts and output a #line if necessary. */
3178 if (ip->lineno != op->lineno) {
3180 output_line_directive (ip, op, 1, same_file);
3181 check_expand (op, limit - ibp);
3186 /* Come here either after (1) a null character that is part of the input
3187 or (2) at the end of the input, because there is a null there. */
3190 /* Our input really contains a null character. */
3194 /* At end of a macro-expansion level, pop it and read next level. */
3195 if (ip->macro != 0) {
3198 /* If traditional, and we have an identifier that ends here,
3199 process it now, so we get the right error for recursion. */
3200 if (traditional && ident_length
3201 && ! is_idchar[*instack[indepth - 1].bufp]) {
3210 /* If we don't have a pending identifier,
3211 return at end of input. */
3212 if (ident_length == 0) {
3220 /* If we do have a pending identifier, just consider this null
3221 a special character and arrange to dispatch on it again.
3222 The second time, IDENT_LENGTH will be zero so we will return. */
3228 /* Handle the case of a character such as /, ', " or null
3229 seen following an identifier. Back over it so that
3230 after the identifier is processed the special char
3231 will be dispatched on again. */
3241 if (ident_length > 0) {
3242 register HASHNODE *hp;
3244 /* We have just seen an identifier end. If it's a macro, expand it.
3246 IDENT_LENGTH is the length of the identifier
3247 and HASH is its hash code.
3249 The identifier has already been copied to the output,
3250 so if it is a macro we must remove it.
3252 If REDO_CHAR is 0, the char that terminated the identifier
3253 has been skipped in the output and the input.
3254 OBP-IDENT_LENGTH-1 points to the identifier.
3255 If the identifier is a macro, we must back over the terminator.
3257 If REDO_CHAR is 1, the terminating char has already been
3258 backed over. OBP-IDENT_LENGTH points to the identifier. */
3260 if (!pcp_outfile || pcp_inside_if) {
3261 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3264 if (hp->length == ident_length) {
3265 int obufp_before_macroname;
3266 int op_lineno_before_macroname;
3267 register int i = ident_length;
3268 register U_CHAR *p = hp->name;
3269 register U_CHAR *q = obp - i;
3275 do { /* All this to avoid a strncmp () */
3280 /* We found a use of a macro name.
3281 see if the context shows it is a macro call. */
3283 /* Back up over terminating character if not already done. */
3289 /* Save this as a displacement from the beginning of the output
3290 buffer. We can not save this as a position in the output
3291 buffer, because it may get realloc'ed by RECACHE. */
3292 obufp_before_macroname = (obp - op->buf) - ident_length;
3293 op_lineno_before_macroname = op->lineno;
3295 if (hp->type == T_PCSTRING) {
3296 pcstring_used (hp); /* Mark the definition of this key
3297 as needed, ensuring that it
3299 break; /* Exit loop, since the key cannot have a
3300 definition any longer. */
3303 /* Record whether the macro is disabled. */
3304 disabled = hp->type == T_DISABLED;
3306 /* This looks like a macro ref, but if the macro was disabled,
3307 just copy its name and put in a marker if requested. */
3311 /* This error check caught useful cases such as
3312 #define foo(x,y) bar (x (y,0), y)
3315 error ("recursive use of macro `%s'", hp->name);
3319 check_expand (op, limit - ibp + 2);
3326 /* If macro wants an arglist, verify that a '(' follows.
3327 first skip all whitespace, copying it to the output
3328 after the macro name. Then, if there is no '(',
3329 decide this is not a macro call and leave things that way. */
3330 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3331 && hp->value.defn->nargs >= 0)
3333 U_CHAR *old_ibp = ibp;
3334 U_CHAR *old_obp = obp;
3335 int old_iln = ip->lineno;
3336 int old_oln = op->lineno;
3339 /* Scan forward over whitespace, copying it to the output. */
3340 if (ibp == limit && ip->macro != 0) {
3345 old_iln = ip->lineno;
3346 old_oln = op->lineno;
3348 /* A comment: copy it unchanged or discard it. */
3349 else if (*ibp == '/' && ibp[1] == '*') {
3350 if (put_out_comments) {
3353 } else if (! traditional) {
3357 while (ibp + 1 != limit
3358 && !(ibp[0] == '*' && ibp[1] == '/')) {
3359 /* We need not worry about newline-marks,
3360 since they are never found in comments. */
3362 /* Newline in a file. Count it. */
3366 if (put_out_comments)
3372 if (put_out_comments) {
3377 else if (is_space[*ibp]) {
3379 if (ibp[-1] == '\n') {
3380 if (ip->macro == 0) {
3381 /* Newline in a file. Count it. */
3384 } else if (!output_marks) {
3385 /* A newline mark, and we don't want marks
3386 in the output. If it is newline-hyphen,
3387 discard it entirely. Otherwise, it is
3388 newline-whitechar, so keep the whitechar. */
3398 /* A newline mark; copy both chars to the output. */
3406 /* It isn't a macro call.
3407 Put back the space that we just skipped. */
3410 ip->lineno = old_iln;
3411 op->lineno = old_oln;
3412 /* Exit the for loop. */
3417 /* This is now known to be a macro call.
3418 Discard the macro name from the output,
3419 along with any following whitespace just copied,
3420 but preserve newlines if not outputting marks since this
3421 is more likely to do the right thing with line numbers. */
3422 obp = op->buf + obufp_before_macroname;
3424 op->lineno = op_lineno_before_macroname;
3426 int newlines = op->lineno - op_lineno_before_macroname;
3427 while (0 < newlines--)
3431 /* Prevent accidental token-pasting with a character
3432 before the macro call. */
3433 if (!traditional && obp != op->buf) {
3435 case '!': case '%': case '&': case '*':
3436 case '+': case '-': case '/': case ':':
3437 case '<': case '=': case '>': case '^':
3439 /* If we are expanding a macro arg, make a newline marker
3440 to separate the tokens. If we are making real output,
3441 a plain space will do. */
3448 /* Expand the macro, reading arguments as needed,
3449 and push the expansion on the input stack. */
3452 macroexpand (hp, op);
3454 /* Reexamine input stack, since macroexpand has pushed
3455 a new level on it. */
3462 } /* End hash-table-search loop */
3464 ident_length = hash = 0; /* Stop collecting identifier */
3467 } /* End if (ident_length > 0) */
3469 } /* End per-char loop */
3471 /* Come here to return -- but first give an error message
3472 if there was an unterminated successful conditional. */
3474 if (if_stack != ip->if_stack)
3478 switch (if_stack->type)
3499 error_with_line (line_for_error (if_stack->lineno),
3500 "unterminated `#%s' conditional", str);
3502 if_stack = ip->if_stack;
3506 * Rescan a string into a temporary buffer and return the result
3507 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3509 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3510 * and insert such markers when appropriate. See `rescan' for details.
3511 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3512 * before substitution; it is 0 for other uses.
3515 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3516 U_CHAR *buf, *limit;
3517 int output_marks, assertions;
3519 register FILE_BUF *ip;
3521 int length = limit - buf;
3523 int odepth = indepth;
3524 int save_assertions_flag = assertions_flag;
3526 assertions_flag = assertions;
3531 /* Set up the input on the input stack. */
3533 buf1 = (U_CHAR *) alloca (length + 1);
3535 register U_CHAR *p1 = buf;
3536 register U_CHAR *p2 = buf1;
3543 /* Set up to receive the output. */
3545 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3546 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3551 CHECK_DEPTH ({return obuf;});
3555 ip = &instack[indepth];
3557 ip->nominal_fname = 0;
3559 ip->system_header_p = 0;
3562 ip->length = length;
3563 ip->buf = ip->bufp = buf1;
3564 ip->if_stack = if_stack;
3566 ip->lineno = obuf.lineno = 1;
3568 /* Scan the input, create the output. */
3569 rescan (&obuf, output_marks);
3571 /* Pop input stack to original state. */
3574 if (indepth != odepth)
3577 /* Record the output. */
3578 obuf.length = obuf.bufp - obuf.buf;
3580 assertions_flag = save_assertions_flag;
3585 * Process a # directive. Expects IP->bufp to point after the '#', as in
3586 * `#define foo bar'. Passes to the directive handler
3587 * (do_define, do_include, etc.): the addresses of the 1st and
3588 * last chars of the directive (starting immediately after the #
3589 * keyword), plus op and the keyword table pointer. If the directive
3590 * contains comments it is copied into a temporary buffer sans comments
3591 * and the temporary buffer is passed to the directive handler instead.
3592 * Likewise for backslash-newlines.
3594 * Returns nonzero if this was a known # directive.
3595 * Otherwise, returns zero, without advancing the input pointer.
3599 handle_directive (ip, op)
3602 register U_CHAR *bp, *cp;
3603 register struct directive *kt;
3604 register int ident_length;
3607 /* Nonzero means we must copy the entire directive
3608 to get rid of comments or backslash-newlines. */
3609 int copy_directive = 0;
3611 U_CHAR *ident, *after_ident;
3615 /* Record where the directive started. do_xifdef needs this. */
3616 directive_start = bp - 1;
3618 /* Skip whitespace and \-newline. */
3620 if (is_hor_space[*bp]) {
3621 if (*bp != ' ' && *bp != '\t' && pedantic)
3622 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3624 } else if (*bp == '/' && (bp[1] == '*'
3625 || (cplusplus_comments && bp[1] == '/'))) {
3627 skip_to_end_of_comment (ip, &ip->lineno, 0);
3629 } else if (*bp == '\\' && bp[1] == '\n') {
3630 bp += 2; ip->lineno++;
3634 /* Now find end of directive name.
3635 If we encounter a backslash-newline, exchange it with any following
3636 symbol-constituents so that we end up with a contiguous name. */
3643 if (*cp == '\\' && cp[1] == '\n')
3644 name_newline_fix (cp);
3650 ident_length = cp - bp;
3654 /* A line of just `#' becomes blank. */
3656 if (ident_length == 0 && *after_ident == '\n') {
3657 ip->bufp = after_ident;
3661 if (ident_length == 0 || !is_idstart[*ident]) {
3663 while (is_idchar[*p]) {
3664 if (*p < '0' || *p > '9')
3668 /* Handle # followed by a line number. */
3669 if (p != ident && !is_idchar[*p]) {
3670 static struct directive line_directive_table[] = {
3671 { 4, do_line, "line", T_LINE},
3674 pedwarn ("`#' followed by integer");
3675 after_ident = ident;
3676 kt = line_directive_table;
3680 /* Avoid error for `###' and similar cases unless -pedantic. */
3682 while (*p == '#' || is_hor_space[*p]) p++;
3684 if (pedantic && !lang_asm)
3685 warning ("invalid preprocessing directive");
3691 error ("invalid preprocessing directive name");
3697 * Decode the keyword and call the appropriate expansion
3698 * routine, after moving the input pointer up to the next line.
3700 for (kt = directive_table; kt->length > 0; kt++) {
3701 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3702 register U_CHAR *buf;
3703 register U_CHAR *limit;
3706 int *already_output;
3708 /* Nonzero means do not delete comments within the directive.
3709 #define needs this when -traditional. */
3714 limit = ip->buf + ip->length;
3717 keep_comments = traditional && kt->traditional_comments;
3718 /* #import is defined only in Objective C, or when on the NeXT. */
3719 if (kt->type == T_IMPORT
3720 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3723 /* Find the end of this directive (first newline not backslashed
3724 and not in a string or comment).
3725 Set COPY_DIRECTIVE if the directive must be copied
3726 (it contains a backslash-newline or a comment). */
3728 buf = bp = after_ident;
3729 while (bp < limit) {
3730 register U_CHAR c = *bp++;
3738 } else if (traditional)
3745 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3746 /* Don't bother calling the directive if we already got an error
3747 message due to unterminated string. Skip everything and pretend
3748 we called the directive. */
3751 /* Traditional preprocessing permits unterminated strings. */
3760 /* <...> is special for #include. */
3762 if (!kt->angle_brackets)
3764 while (bp < limit && *bp != '>' && *bp != '\n') {
3765 if (*bp == '\\' && bp[1] == '\n') {
3775 if (*bp == '\\' && bp[1] == '\n')
3778 || (cplusplus_comments && *bp == '/')) {
3779 U_CHAR *obp = bp - 1;
3781 skip_to_end_of_comment (ip, &ip->lineno, 0);
3783 /* No need to copy the directive because of a comment at the end;
3784 just don't include the comment in the directive. */
3785 if (bp == limit || *bp == '\n') {
3789 /* Don't remove the comments if -traditional. */
3790 if (! keep_comments)
3799 pedwarn ("%s in preprocessing directive", char_name[c]);
3803 --bp; /* Point to the newline */
3811 resume_p = ip->bufp;
3812 /* BP is the end of the directive.
3813 RESUME_P is the next interesting data after the directive.
3814 A comment may come between. */
3816 /* If a directive should be copied through, and -E was given,
3817 pass it through before removing comments. */
3818 if (!no_output && kt->pass_thru && put_out_comments) {
3821 /* Output directive name. */
3822 check_expand (op, kt->length + 2);
3823 /* Make sure # is at the start of a line */
3824 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3829 bcopy (kt->name, op->bufp, kt->length);
3830 op->bufp += kt->length;
3832 /* Output arguments. */
3834 check_expand (op, len);
3835 bcopy (buf, (char *) op->bufp, len);
3837 /* Take account of any (escaped) newlines just output. */
3839 if (buf[len] == '\n')
3842 already_output = &junk;
3843 } /* Don't we need a newline or #line? */
3845 if (copy_directive) {
3846 register U_CHAR *xp = buf;
3847 /* Need to copy entire directive into temp buffer before dispatching */
3849 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3853 /* Copy to the new buffer, deleting comments
3854 and backslash-newlines (and whitespace surrounding the latter). */
3857 register U_CHAR c = *xp++;
3862 abort (); /* A bare newline should never part of the line. */
3865 /* <...> is special for #include. */
3867 if (!kt->angle_brackets)
3869 while (xp < bp && c != '>') {
3871 if (c == '\\' && xp < bp && *xp == '\n')
3882 if (cp != buf && is_hor_space[cp[-1]]) {
3883 while (cp - 1 != buf && is_hor_space[cp[-2]])
3885 SKIP_WHITE_SPACE (xp);
3886 } else if (is_hor_space[*xp]) {
3888 SKIP_WHITE_SPACE (xp);
3890 } else if (traditional && xp < bp) {
3898 register U_CHAR *bp1
3899 = skip_quoted_string (xp - 1, bp, ip->lineno,
3900 NULL_PTR, NULL_PTR, NULL_PTR);
3914 || (cplusplus_comments && *xp == '/')) {
3916 /* If we already copied the directive through,
3917 already_output != 0 prevents outputting comment now. */
3918 skip_to_end_of_comment (ip, already_output, 0);
3920 while (xp != ip->bufp)
3922 /* Delete or replace the slash. */
3923 else if (traditional)
3932 /* Null-terminate the copy. */
3938 ip->bufp = resume_p;
3940 /* Some directives should be written out for cc1 to process,
3941 just as if they were not defined. And sometimes we're copying
3942 definitions through. */
3944 if (!no_output && already_output == 0
3946 || (kt->type == T_DEFINE
3947 && (dump_macros == dump_names
3948 || dump_macros == dump_definitions)))) {
3951 /* Output directive name. */
3952 check_expand (op, kt->length + 1);
3954 bcopy (kt->name, (char *) op->bufp, kt->length);
3955 op->bufp += kt->length;
3957 if (kt->pass_thru || dump_macros == dump_definitions) {
3958 /* Output arguments. */
3960 check_expand (op, len);
3961 bcopy (buf, (char *) op->bufp, len);
3963 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3966 SKIP_WHITE_SPACE (xp);
3968 while (is_idchar[*xp]) xp++;
3970 check_expand (op, len + 1);
3972 bcopy (yp, op->bufp, len);
3975 } /* Don't we need a newline or #line? */
3977 /* Call the appropriate directive handler. buf now points to
3978 either the appropriate place in the input buffer, or to
3979 the temp buffer if it was necessary to make one. cp
3980 points to the first char after the contents of the (possibly
3981 copied) directive, in either case. */
3982 (*kt->func) (buf, cp, op, kt);
3983 check_expand (op, ip->length - (ip->bufp - ip->buf));
3989 /* It is deliberate that we don't warn about undefined directives.
3990 That is the responsibility of cc1. */
3997 static struct tm *timebuf;
3999 time_t t = time ((time_t *)0);
4000 timebuf = localtime (&t);
4005 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4006 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4010 * expand things like __FILE__. Place the expansion into the output
4011 * buffer *without* rescanning.
4015 special_symbol (hp, op)
4022 FILE_BUF *ip = NULL;
4025 int paren = 0; /* For special `defined' keyword */
4027 if (pcp_outfile && pcp_inside_if
4028 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4029 error ("Predefined macro `%s' used inside `#if' during precompilation",
4032 for (i = indepth; i >= 0; i--)
4033 if (instack[i].fname != NULL) {
4038 error ("cccp error: not in any file?!");
4039 return; /* the show must go on */
4047 if (hp->type == T_FILE)
4048 string = ip->nominal_fname;
4050 string = instack[0].nominal_fname;
4054 buf = (char *) alloca (3 + 4 * strlen (string));
4055 quote_string (buf, string);
4063 case T_INCLUDE_LEVEL:
4065 for (i = indepth; i >= 0; i--)
4066 if (instack[i].fname != NULL)
4069 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4070 sprintf (buf, "%d", true_indepth - 1);
4074 buf = (char *) alloca (3 + strlen (version_string));
4075 sprintf (buf, "\"%s\"", version_string);
4078 #ifndef NO_BUILTIN_SIZE_TYPE
4084 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4085 case T_PTRDIFF_TYPE:
4094 case T_USER_LABEL_PREFIX_TYPE:
4095 buf = USER_LABEL_PREFIX;
4098 case T_REGISTER_PREFIX_TYPE:
4099 buf = REGISTER_PREFIX;
4102 case T_IMMEDIATE_PREFIX_TYPE:
4103 buf = IMMEDIATE_PREFIX;
4107 buf = hp->value.cpval;
4108 if (pcp_inside_if && pcp_outfile)
4109 /* Output a precondition for this macro use */
4110 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4114 buf = (char *) alloca (10);
4115 sprintf (buf, "%d", ip->lineno);
4120 buf = (char *) alloca (20);
4121 timebuf = timestamp ();
4122 if (hp->type == T_DATE)
4123 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4124 timebuf->tm_mday, timebuf->tm_year + 1900);
4126 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4130 case T_SPEC_DEFINED:
4131 buf = " 0 "; /* Assume symbol is not defined */
4132 ip = &instack[indepth];
4133 SKIP_WHITE_SPACE (ip->bufp);
4134 if (*ip->bufp == '(') {
4136 ip->bufp++; /* Skip over the paren */
4137 SKIP_WHITE_SPACE (ip->bufp);
4140 if (!is_idstart[*ip->bufp])
4142 if ((hp = lookup (ip->bufp, -1, -1))) {
4143 if (pcp_outfile && pcp_inside_if
4144 && (hp->type == T_CONST
4145 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4146 /* Output a precondition for this macro use. */
4147 fprintf (pcp_outfile, "#define %s\n", hp->name);
4151 if (pcp_outfile && pcp_inside_if) {
4152 /* Output a precondition for this macro use */
4153 U_CHAR *cp = ip->bufp;
4154 fprintf (pcp_outfile, "#undef ");
4155 while (is_idchar[*cp]) /* Ick! */
4156 fputc (*cp++, pcp_outfile);
4157 putc ('\n', pcp_outfile);
4159 while (is_idchar[*ip->bufp])
4161 SKIP_WHITE_SPACE (ip->bufp);
4163 if (*ip->bufp != ')')
4171 error ("`defined' without an identifier");
4175 error ("cccp error: invalid special hash type"); /* time for gdb */
4179 check_expand (op, len);
4180 bcopy (buf, (char *) op->bufp, len);
4187 /* Routines to handle #directives */
4189 /* Handle #include and #import.
4190 This function expects to see "fname" or <fname> on the input. */
4193 do_include (buf, limit, op, keyword)
4194 U_CHAR *buf, *limit;
4196 struct directive *keyword;
4198 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4199 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4200 static int import_warning = 0;
4201 char *fname; /* Dynamically allocated fname buffer */
4204 char *fbeg, *fend; /* Beginning and end of fname */
4207 struct file_name_list *search_start = include; /* Chain of dirs to search */
4208 struct file_name_list *dsp; /* First in chain, if #include "..." */
4209 struct file_name_list *searchptr = 0;
4212 int f = -3; /* file number */
4213 struct include_file *inc = 0;
4215 int retried = 0; /* Have already tried macro
4216 expanding the include line*/
4217 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4223 if (importing && warn_import && !inhibit_warnings
4224 && !instack[indepth].system_header_p && !import_warning) {
4226 warning ("using `#import' is not recommended");
4227 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4228 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4229 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4230 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4231 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4232 fprintf (stderr, " ... <real contents of file> ...\n");
4233 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4234 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4235 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4236 fprintf (stderr, "when it is equipped with such a conditional.\n");
4242 SKIP_WHITE_SPACE (fin);
4243 /* Discard trailing whitespace so we can easily see
4244 if we have parsed all the significant chars we were given. */
4245 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4246 fbeg = fend = (char *) alloca (limit - fin);
4252 /* Copy the operand text, concatenating the strings. */
4254 while (fin != limit) {
4255 while (fin != limit && *fin != '\"')
4260 /* If not at the end, there had better be another string. */
4261 /* Skip just horiz space, and don't go past limit. */
4262 while (fin != limit && is_hor_space[*fin]) fin++;
4263 if (fin != limit && *fin == '\"')
4270 /* We have "filename". Figure out directory this source
4271 file is coming from and put it on the front of the list. */
4273 /* If -I- was specified, don't search current dir, only spec'd ones. */
4274 if (ignore_srcdir) break;
4276 for (fp = &instack[indepth]; fp >= instack; fp--)
4281 if ((nam = fp->nominal_fname) != NULL) {
4282 /* Found a named file. Figure out dir of the file,
4283 and put it in front of the search list. */
4284 dsp = ((struct file_name_list *)
4285 alloca (sizeof (struct file_name_list) + strlen (nam)));
4286 strcpy (dsp->fname, nam);
4287 simplify_filename (dsp->fname);
4288 nam = base_name (dsp->fname);
4290 /* But for efficiency's sake, do not insert the dir
4291 if it matches the search list's first dir. */
4292 dsp->next = search_start;
4293 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4295 n = nam - dsp->fname;
4296 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4297 max_include_len = n + INCLUDE_LEN_FUDGE;
4299 dsp[0].got_name_map = 0;
4307 while (fin != limit && *fin != '>')
4309 if (*fin == '>' && fin + 1 == limit) {
4311 /* If -I-, start with the first -I dir after the -I-. */
4312 search_start = first_bracket_include;
4320 * Support '#include xyz' like VAX-C to allow for easy use of all the
4321 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4322 * code from case '<' is repeated here) and generates a warning.
4323 * (Note: macro expansion of `xyz' takes precedence.)
4325 if (retried && isalpha(*(U_CHAR *)(--fbeg))) {
4326 while (fin != limit && (!isspace(*fin)))
4328 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4331 /* If -I-, start with the first -I dir after the -I-. */
4332 search_start = first_bracket_include;
4340 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4343 /* Expand buffer and then remove any newline markers.
4344 We can't just tell expand_to_temp_buffer to omit the markers,
4345 since it would put extra spaces in include file names. */
4348 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4350 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4352 while (src != trybuf.bufp) {
4353 switch ((*limit++ = *src++)) {
4362 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4363 NULL_PTR, NULL_PTR, NULL_PTR);
4377 /* For #include_next, skip in the search path
4378 past the dir in which the containing file was found. */
4381 for (fp = &instack[indepth]; fp >= instack; fp--)
4382 if (fp->fname != NULL) {
4383 /* fp->dir is null if the containing file was specified
4384 with an absolute file name. In that case, don't skip anything. */
4386 search_start = fp->dir->next;
4392 flen = simplify_filename (fbeg);
4396 error ("empty file name in `#%s'", keyword->name);
4400 /* Allocate this permanently, because it gets stored in the definitions
4402 fname = xmalloc (max_include_len + flen + 1);
4403 /* + 1 above for terminating null. */
4405 system_include_depth += angle_brackets;
4407 /* If specified file name is absolute, just open it. */
4409 if (absolute_filename (fbeg)) {
4410 strcpy (fname, fbeg);
4411 f = open_include_file (fname, NULL_PTR, importing, &inc);
4415 struct bypass_dir *next;
4417 struct file_name_list *searchptr;
4418 } **bypass_slot = 0;
4420 /* Search directory path, trying to open the file.
4421 Copy each filename tried into FNAME. */
4423 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4425 if (searchptr == first_bracket_include) {
4426 /* Go to bypass directory if we know we've seen this file before. */
4427 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4428 struct bypass_dir *p;
4429 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4431 for (p = *bypass_slot; p; p = p->next)
4432 if (!strcmp (fbeg, p->fname)) {
4433 searchptr = p->searchptr;
4439 strcpy (fname, searchptr->fname);
4440 strcat (fname, fbeg);
4442 /* Change this 1/2 Unix 1/2 VMS file specification into a
4443 full VMS file specification */
4444 if (searchptr->fname[0]) {
4445 /* Fix up the filename */
4446 hack_vms_include_specification (fname);
4448 /* This is a normal VMS filespec, so use it unchanged. */
4449 strcpy (fname, fbeg);
4450 /* if it's '#include filename', add the missing .h */
4451 if (index(fname,'.')==NULL) {
4452 strcat (fname, ".h");
4456 f = open_include_file (fname, searchptr, importing, &inc);
4458 if (bypass_slot && searchptr != first_bracket_include) {
4459 /* This is the first time we found this include file,
4460 and we found it after first_bracket_include.
4461 Record its location so that we can bypass to here next time. */
4462 struct bypass_dir *p
4463 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4464 p->next = *bypass_slot;
4465 p->fname = fname + strlen (searchptr->fname);
4466 p->searchptr = searchptr;
4472 /* Our VMS hacks can produce invalid filespecs, so don't worry
4473 about errors other than EACCES. */
4474 if (errno == EACCES)
4477 if (errno != ENOENT)
4487 /* The file was already included. */
4489 /* If generating dependencies and -MG was specified, we assume missing
4490 files are leaf files, living in the same directory as the source file
4491 or other similar place; these missing files may be generated from
4492 other files and may not exist yet (eg: y.tab.h). */
4493 } else if (print_deps_missing_files
4494 && (system_include_depth != 0) < print_deps)
4496 /* If it was requested as a system header file,
4497 then assume it belongs in the first place to look for such. */
4501 char *p = (char *) alloca (strlen (search_start->fname)
4502 + strlen (fbeg) + 1);
4503 strcpy (p, search_start->fname);
4505 deps_output (p, ' ');
4510 /* Otherwise, omit the directory, as if the file existed
4511 in the directory with the source. */
4512 deps_output (fbeg, ' ');
4515 /* If -M was specified, and this header file won't be added to the
4516 dependency list, then don't count this as an error, because we can
4517 still produce correct output. Otherwise, we can't produce correct
4518 output, because there may be dependencies we need inside the missing
4519 file, and we don't know what directory this missing file exists in. */
4520 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4521 warning ("No include path in which to find %s", fbeg);
4523 error_from_errno (fbeg);
4525 error ("No include path in which to find %s", fbeg);
4529 /* Actually process the file. */
4531 pcftry = (char *) alloca (strlen (fname) + 30);
4538 sprintf (pcftry, "%s%d", fname, pcfnum++);
4540 pcf = open (pcftry, O_RDONLY, 0666);
4545 if (fstat (pcf, &s) != 0)
4546 pfatal_with_name (pcftry);
4547 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4548 || inc->st.st_dev != s.st_dev)
4550 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4551 /* Don't need it any more. */
4556 /* Don't need it at all. */
4561 } while (pcf != -1 && !pcfbuf);
4564 /* Actually process the file */
4566 pcfname = xmalloc (strlen (pcftry) + 1);
4567 strcpy (pcfname, pcftry);
4568 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4569 (U_CHAR *) fname, op);
4572 finclude (f, inc, op, is_system_include (fname), searchptr);
4575 system_include_depth -= angle_brackets;
4580 /* Return nonzero if the given FILENAME is an absolute pathname which
4581 designates a file within one of the known "system" include file
4582 directories. We assume here that if the given FILENAME looks like
4583 it is the name of a file which resides either directly in a "system"
4584 include file directory, or within any subdirectory thereof, then the
4585 given file must be a "system" include file. This function tells us
4586 if we should suppress pedantic errors/warnings for the given FILENAME.
4588 The value is 2 if the file is a C-language system header file
4589 for which C++ should (on most systems) assume `extern "C"'. */
4592 is_system_include (filename)
4593 register char *filename;
4595 struct file_name_list *searchptr;
4597 for (searchptr = first_system_include; searchptr;
4598 searchptr = searchptr->next)
4599 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4600 return searchptr->c_system_include_path + 1;
4604 /* Yield the non-directory suffix of a file name. */
4612 #if defined (__MSDOS__) || defined (_WIN32)
4613 if (isalpha (s[0]) && s[1] == ':') s += 2;
4616 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4617 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4618 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4622 if ((p = rindex (s, '/'))) s = p + 1;
4623 #ifdef DIR_SEPARATOR
4624 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4629 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4631 absolute_filename (filename)
4634 #if defined (__MSDOS__) || defined (_WIN32)
4635 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4637 if (filename[0] == '/') return 1;
4638 #ifdef DIR_SEPARATOR
4639 if (filename[0] == DIR_SEPARATOR) return 1;
4644 /* Remove unnecessary characters from FILENAME in place,
4645 to avoid unnecessary filename aliasing.
4646 Return the length of the resulting string.
4648 Do only the simplifications allowed by Posix.
4649 It is OK to miss simplifications on non-Posix hosts,
4650 since this merely leads to suboptimial results. */
4653 simplify_filename (filename)
4656 register char *from = filename;
4657 register char *to = filename;
4660 /* Remove redundant initial /s. */
4663 if (*++from == '/') {
4664 if (*++from == '/') {
4665 /* 3 or more initial /s are equivalent to 1 /. */
4666 while (*++from == '/')
4669 /* On some hosts // differs from /; Posix allows this. */
4670 static int slashslash_vs_slash;
4671 if (slashslash_vs_slash == 0) {
4673 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4674 && INO_T_EQ (s1.st_ino, s2.st_ino)
4675 && s1.st_dev == s2.st_dev)
4678 if (slashslash_vs_slash < 0)
4686 if (from[0] == '.' && from[1] == '/')
4689 /* Copy this component and trailing /, if any. */
4690 while ((*to++ = *from++) != '/') {
4692 /* Trim . component at end of nonempty name. */
4693 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4695 /* Trim unnecessary trailing /s. */
4696 while (to0 < --to && to[-1] == '/')
4700 return to - filename;
4705 /* Skip /s after a /. */
4706 while (*from == '/')
4711 /* The file_name_map structure holds a mapping of file names for a
4712 particular directory. This mapping is read from the file named
4713 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4714 map filenames on a file system with severe filename restrictions,
4715 such as DOS. The format of the file name map file is just a series
4716 of lines with two tokens on each line. The first token is the name
4717 to map, and the second token is the actual name to use. */
4719 struct file_name_map
4721 struct file_name_map *map_next;
4726 #define FILE_NAME_MAP_FILE "header.gcc"
4728 /* Read a space delimited string of unlimited length from a stdio
4732 read_filename_string (ch, f)
4740 set = alloc = xmalloc (len + 1);
4744 while ((ch = getc (f)) != EOF && ! is_space[ch])
4746 if (set - alloc == len)
4749 alloc = xrealloc (alloc, len + 1);
4750 set = alloc + len / 2;
4760 /* Read the file name map file for DIRNAME.
4761 If DIRNAME is empty, read the map file for the working directory;
4762 otherwise DIRNAME must end in '/'. */
4764 static struct file_name_map *
4765 read_name_map (dirname)
4768 /* This structure holds a linked list of file name maps, one per
4770 struct file_name_map_list
4772 struct file_name_map_list *map_list_next;
4773 char *map_list_name;
4774 struct file_name_map *map_list_map;
4776 static struct file_name_map_list *map_list;
4777 register struct file_name_map_list *map_list_ptr;
4782 for (map_list_ptr = map_list; map_list_ptr;
4783 map_list_ptr = map_list_ptr->map_list_next)
4784 if (! strcmp (map_list_ptr->map_list_name, dirname))
4785 return map_list_ptr->map_list_map;
4787 map_list_ptr = ((struct file_name_map_list *)
4788 xmalloc (sizeof (struct file_name_map_list)));
4789 map_list_ptr->map_list_name = savestring (dirname);
4790 map_list_ptr->map_list_map = NULL;
4792 dirlen = strlen (dirname);
4793 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4794 strcpy (name, dirname);
4795 strcat (name, FILE_NAME_MAP_FILE);
4796 f = fopen (name, "r");
4798 map_list_ptr->map_list_map = NULL;
4803 while ((ch = getc (f)) != EOF)
4806 struct file_name_map *ptr;
4811 from = read_filename_string (ch, f);
4812 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4814 to = read_filename_string (ch, f);
4816 simplify_filename (from);
4817 tolen = simplify_filename (to);
4819 ptr = ((struct file_name_map *)
4820 xmalloc (sizeof (struct file_name_map)));
4821 ptr->map_from = from;
4823 /* Make the real filename absolute. */
4824 if (absolute_filename (to))
4828 ptr->map_to = xmalloc (dirlen + tolen + 1);
4829 strcpy (ptr->map_to, dirname);
4830 strcat (ptr->map_to, to);
4834 ptr->map_next = map_list_ptr->map_list_map;
4835 map_list_ptr->map_list_map = ptr;
4837 while ((ch = getc (f)) != '\n')
4844 map_list_ptr->map_list_next = map_list;
4845 map_list = map_list_ptr;
4847 return map_list_ptr->map_list_map;
4850 /* Try to open include file FILENAME. SEARCHPTR is the directory
4851 being tried from the include file search path.
4852 IMPORTING is "" if we are importing, null otherwise.
4853 Return -2 if found, either a matching name or a matching inode.
4854 Otherwise, open the file and return a file descriptor if successful
4855 or -1 if unsuccessful.
4856 Unless unsuccessful, put a descriptor of the included file into *PINC.
4857 This function maps filenames on file systems based on information read by
4861 open_include_file (filename, searchptr, importing, pinc)
4863 struct file_name_list *searchptr;
4865 struct include_file **pinc;
4867 char *fname = remap_include_file (filename, searchptr);
4870 /* Look up FNAME in include_hashtab. */
4871 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4874 struct include_file *inc, *head = *phead;
4875 for (inc = head; inc; inc = inc->next)
4876 if (!strcmp (fname, inc->fname))
4880 || ! inc->control_macro
4881 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4883 fd = open (fname, O_RDONLY, 0);
4889 /* FNAME was not in include_hashtab; insert a new entry. */
4890 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4893 inc->control_macro = 0;
4894 inc->deps_output = 0;
4895 if (fstat (fd, &inc->st) != 0)
4896 pfatal_with_name (fname);
4899 /* Look for another file with the same inode and device. */
4900 if (lookup_ino_include (inc)
4901 && inc->control_macro
4902 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4908 /* For -M, add this file to the dependencies. */
4909 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4910 inc->deps_output = 1;
4911 deps_output (fname, ' ');
4914 /* Handle -H option. */
4915 if (print_include_names)
4916 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4920 inc->control_macro = importing;
4926 /* Return the remapped name of the the include file FILENAME.
4927 SEARCHPTR is the directory being tried from the include file path. */
4930 remap_include_file (filename, searchptr)
4932 struct file_name_list *searchptr;
4934 register struct file_name_map *map;
4935 register char *from;
4939 if (! searchptr->got_name_map)
4941 searchptr->name_map = read_name_map (searchptr->fname);
4942 searchptr->got_name_map = 1;
4945 /* Check the mapping for the directory we are using. */
4946 from = filename + strlen (searchptr->fname);
4947 for (map = searchptr->name_map; map; map = map->map_next)
4948 if (! strcmp (map->map_from, from))
4952 from = base_name (filename);
4954 if (from != filename || !searchptr)
4956 /* Try to find a mapping file for the particular directory we are
4957 looking in. Thus #include <sys/types.h> will look up sys/types.h
4958 in /usr/include/header.gcc and look up types.h in
4959 /usr/include/sys/header.gcc. */
4961 char *dir = (char *) alloca (from - filename + 1);
4962 bcopy (filename, dir, from - filename);
4963 dir[from - filename] = '\0';
4965 for (map = read_name_map (dir); map; map = map->map_next)
4966 if (! strcmp (map->map_from, from))
4973 /* Insert INC into the include file table, hashed by device and inode number.
4974 If a file with different name but same dev+ino was already in the table,
4975 return 1 and set INC's control macro to the already-known macro. */
4978 lookup_ino_include (inc)
4979 struct include_file *inc;
4981 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
4982 % INCLUDE_HASHSIZE);
4983 struct include_file *i = include_ino_hashtab[hash];
4985 include_ino_hashtab[hash] = inc;
4987 for (; i; i = i->next_ino)
4988 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
4989 && inc->st.st_dev == i->st.st_dev) {
4990 inc->control_macro = i->control_macro;
4997 /* Process file descriptor F, which corresponds to include file INC,
4999 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5000 "system" include directories (as decided by the `is_system_include'
5002 DIRPTR is the link in the dir path through which this file was found,
5003 or 0 if the file name was absolute. */
5006 finclude (f, inc, op, system_header_p, dirptr)
5008 struct include_file *inc;
5010 int system_header_p;
5011 struct file_name_list *dirptr;
5013 char *fname = inc->fname;
5015 FILE_BUF *fp; /* For input stack frame */
5016 int missing_newline = 0;
5018 CHECK_DEPTH (return;);
5020 fp = &instack[indepth + 1];
5021 bzero ((char *) fp, sizeof (FILE_BUF));
5022 fp->nominal_fname = fp->fname = fname;
5026 fp->if_stack = if_stack;
5027 fp->system_header_p = system_header_p;
5030 if (S_ISREG (inc->st.st_mode)) {
5031 fp->buf = (U_CHAR *) xmalloc (inc->st.st_size + 2);
5034 /* Read the file contents, knowing that inc->st.st_size is an upper bound
5035 on the number of bytes we can read. */
5036 fp->length = safe_read (f, (char *) fp->buf, inc->st.st_size);
5037 if (fp->length < 0) goto nope;
5039 else if (S_ISDIR (inc->st.st_mode)) {
5040 error ("directory `%s' specified in #include", fname);
5044 /* Cannot count its file size before reading.
5045 First read the entire file into heap and
5046 copy them into buffer on stack. */
5051 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5054 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5056 goto nope; /* error! */
5058 if (st_size != bsize)
5059 break; /* End of file */
5061 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5064 fp->length = st_size;
5067 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5068 /* Backslash-newline at end is not good enough. */
5069 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5070 fp->buf[fp->length++] = '\n';
5071 missing_newline = 1;
5073 fp->buf[fp->length] = '\0';
5075 /* Close descriptor now, so nesting does not use lots of descriptors. */
5078 /* Must do this before calling trigraph_pcp, so that the correct file name
5079 will be printed in warning messages. */
5082 input_file_stack_tick++;
5087 output_line_directive (fp, op, 0, enter_file);
5090 if (missing_newline)
5093 if (pedantic && missing_newline)
5094 pedwarn ("file does not end in newline");
5097 input_file_stack_tick++;
5098 output_line_directive (&instack[indepth], op, 0, leave_file);
5104 perror_with_name (fname);
5109 /* Record that inclusion of the include file INC
5110 should be controlled by the macro named MACRO_NAME.
5111 This means that trying to include the file again
5112 will do something if that macro is defined. */
5115 record_control_macro (inc, macro_name)
5116 struct include_file *inc;
5119 if (!inc->control_macro || inc->control_macro[0])
5120 inc->control_macro = macro_name;
5123 /* Load the specified precompiled header into core, and verify its
5124 preconditions. PCF indicates the file descriptor to read, which must
5125 be a regular file. *ST is its file status.
5126 FNAME indicates the file name of the original header.
5127 *LIMIT will be set to an address one past the end of the file.
5128 If the preconditions of the file are not satisfied, the buffer is
5129 freed and we return 0. If the preconditions are satisfied, return
5130 the address of the buffer following the preconditions. The buffer, in
5131 this case, should never be freed because various pieces of it will
5132 be referred to until all precompiled strings are output at the end of
5136 check_precompiled (pcf, st, fname, limit)
5149 if (S_ISREG (st->st_mode))
5151 buf = xmalloc (st->st_size + 2);
5152 length = safe_read (pcf, buf, st->st_size);
5159 if (length > 0 && buf[length-1] != '\n')
5160 buf[length++] = '\n';
5163 *limit = buf + length;
5165 /* File is in core. Check the preconditions. */
5166 if (!check_preconditions (buf))
5168 for (cp = buf; *cp; cp++)
5171 fprintf (stderr, "Using preinclude %s\n", fname);
5177 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5183 /* PREC (null terminated) points to the preconditions of a
5184 precompiled header. These are a series of #define and #undef
5185 lines which must match the current contents of the hash
5188 check_preconditions (prec)
5195 lineend = index (prec, '\n');
5197 if (*prec++ != '#') {
5198 error ("Bad format encountered while reading precompiled file");
5201 if (!strncmp (prec, "define", 6)) {
5205 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5210 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5211 || (hp->type != T_MACRO && hp->type != T_CONST)
5212 || (hp->type == T_MACRO
5213 && !compare_defs (mdef.defn, hp->value.defn)
5214 && (mdef.defn->length != 2
5215 || mdef.defn->expansion[0] != '\n'
5216 || mdef.defn->expansion[1] != ' ')))
5218 } else if (!strncmp (prec, "undef", 5)) {
5223 while (is_hor_space[(U_CHAR) *prec])
5226 while (is_idchar[(U_CHAR) *prec])
5230 if (lookup ((U_CHAR *) name, len, -1))
5233 error ("Bad format encountered while reading precompiled file");
5238 /* They all passed successfully */
5242 /* Process the main body of a precompiled file. BUF points to the
5243 string section of the file, following the preconditions. LIMIT is one
5244 character past the end. NAME is the name of the file being read
5245 in. OP is the main output buffer */
5247 pcfinclude (buf, limit, name, op)
5248 U_CHAR *buf, *limit, *name;
5255 /* First in the file comes 4 bytes indicating the number of strings, */
5256 /* in network byte order. (MSB first). */
5258 nstrings = (nstrings << 8) | *cp++;
5259 nstrings = (nstrings << 8) | *cp++;
5260 nstrings = (nstrings << 8) | *cp++;
5262 /* Looping over each string... */
5263 while (nstrings--) {
5264 U_CHAR *string_start;
5265 U_CHAR *endofthiskey;
5269 /* Each string starts with a STRINGDEF structure (str), followed */
5270 /* by the text of the string (string_start) */
5272 /* First skip to a longword boundary */
5273 /* ??? Why a 4-byte boundary? On all machines? */
5274 /* NOTE: This works correctly even if HOST_WIDE_INT
5275 is narrower than a pointer.
5276 Do not try risky measures here to get another type to use!
5277 Do not include stddef.h--it will fail! */
5278 if ((HOST_WIDE_INT) cp & 3)
5279 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5281 /* Now get the string. */
5282 str = (STRINGDEF *) (GENERIC_PTR) cp;
5283 string_start = cp += sizeof (STRINGDEF);
5285 for (; *cp; cp++) /* skip the string */
5288 /* We need to macro expand the string here to ensure that the
5289 proper definition environment is in place. If it were only
5290 expanded when we find out it is needed, macros necessary for
5291 its proper expansion might have had their definitions changed. */
5292 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5293 /* Lineno is already set in the precompiled file */
5294 str->contents = tmpbuf.buf;
5295 str->len = tmpbuf.length;
5297 str->filename = name;
5298 str->output_mark = outbuf.bufp - outbuf.buf;
5301 *stringlist_tailp = str;
5302 stringlist_tailp = &str->chain;
5304 /* Next comes a fourbyte number indicating the number of keys */
5305 /* for this string. */
5307 nkeys = (nkeys << 8) | *cp++;
5308 nkeys = (nkeys << 8) | *cp++;
5309 nkeys = (nkeys << 8) | *cp++;
5311 /* If this number is -1, then the string is mandatory. */
5315 /* Otherwise, for each key, */
5316 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5317 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5320 /* It starts with a KEYDEF structure */
5321 cp += sizeof (KEYDEF);
5323 /* Find the end of the key. At the end of this for loop we
5324 advance CP to the start of the next key using this variable. */
5325 endofthiskey = cp + strlen ((char *) cp);
5328 /* Expand the key, and enter it into the hash table. */
5329 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5330 tmpbuf.bufp = tmpbuf.buf;
5332 while (is_hor_space[*tmpbuf.bufp])
5334 if (!is_idstart[*tmpbuf.bufp]
5335 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5340 hp = lookup (tmpbuf.bufp, -1, -1);
5343 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5345 else if (hp->type == T_PCSTRING) {
5346 kp->chain = hp->value.keydef;
5347 hp->value.keydef = kp;
5353 /* This output_line_directive serves to switch us back to the current
5354 input file in case some of these strings get output (which will
5355 result in line directives for the header file being output). */
5356 output_line_directive (&instack[indepth], op, 0, enter_file);
5359 /* Called from rescan when it hits a key for strings. Mark them all */
5360 /* used and clean up. */
5367 for (kp = hp->value.keydef; kp; kp = kp->chain)
5368 kp->str->writeflag = 1;
5372 /* Write the output, interspersing precompiled strings in their */
5373 /* appropriate places. */
5377 STRINGDEF *next_string;
5378 U_CHAR *cur_buf_loc;
5379 int line_directive_len = 80;
5380 char *line_directive = xmalloc (line_directive_len);
5383 /* In each run through the loop, either cur_buf_loc == */
5384 /* next_string_loc, in which case we print a series of strings, or */
5385 /* it is less than next_string_loc, in which case we write some of */
5387 cur_buf_loc = outbuf.buf;
5388 next_string = stringlist;
5390 while (cur_buf_loc < outbuf.bufp || next_string) {
5392 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5393 if (next_string->writeflag) {
5394 len = 4 * strlen ((char *) next_string->filename) + 32;
5395 while (len > line_directive_len)
5396 line_directive = xrealloc (line_directive,
5397 line_directive_len *= 2);
5398 sprintf (line_directive, "\n# %d ", next_string->lineno);
5399 strcpy (quote_string (line_directive + strlen (line_directive),
5400 (char *) next_string->filename),
5402 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5403 safe_write (fileno (stdout),
5404 (char *) next_string->contents, next_string->len);
5406 next_string = next_string->chain;
5410 ? (next_string->output_mark
5411 - (cur_buf_loc - outbuf.buf))
5412 : outbuf.bufp - cur_buf_loc);
5414 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5418 free (line_directive);
5421 /* Pass a directive through to the output file.
5422 BUF points to the contents of the directive, as a contiguous string.
5423 LIMIT points to the first character past the end of the directive.
5424 KEYWORD is the keyword-table entry for the directive. */
5427 pass_thru_directive (buf, limit, op, keyword)
5428 U_CHAR *buf, *limit;
5430 struct directive *keyword;
5432 register unsigned keyword_length = keyword->length;
5434 check_expand (op, 1 + keyword_length + (limit - buf));
5436 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5437 op->bufp += keyword_length;
5438 if (limit != buf && buf[0] != ' ')
5440 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5441 op->bufp += (limit - buf);
5444 /* Count the line we have just made in the output,
5445 to get in sync properly. */
5450 /* The arglist structure is built by do_define to tell
5451 collect_definition where the argument names begin. That
5452 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5453 would contain pointers to the strings x, y, and z.
5454 Collect_definition would then build a DEFINITION node,
5455 with reflist nodes pointing to the places x, y, and z had
5456 appeared. So the arglist is just convenience data passed
5457 between these two routines. It is not kept around after
5458 the current #define has been processed and entered into the
5462 struct arglist *next;
5469 /* Create a DEFINITION node from a #define directive. Arguments are
5470 as for do_define. */
5472 create_definition (buf, limit, op)
5473 U_CHAR *buf, *limit;
5476 U_CHAR *bp; /* temp ptr into input buffer */
5477 U_CHAR *symname; /* remember where symbol name starts */
5478 int sym_length; /* and how long it is */
5479 int line = instack[indepth].lineno;
5480 char *file = instack[indepth].nominal_fname;
5484 int arglengths = 0; /* Accumulate lengths of arg names
5485 plus number of args. */
5490 while (is_hor_space[*bp])
5493 symname = bp; /* remember where it starts */
5494 sym_length = check_macro_name (bp, "macro");
5497 /* Lossage will occur if identifiers or control keywords are broken
5498 across lines using backslash. This is not the right place to take
5502 struct arglist *arg_ptrs = NULL;
5505 bp++; /* skip '(' */
5506 SKIP_WHITE_SPACE (bp);
5508 /* Loop over macro argument names. */
5509 while (*bp != ')') {
5510 struct arglist *temp;
5512 temp = (struct arglist *) alloca (sizeof (struct arglist));
5514 temp->next = arg_ptrs;
5515 temp->argno = argno++;
5516 temp->rest_args = 0;
5520 pedwarn ("another parameter follows `%s'",
5523 if (!is_idstart[*bp])
5524 pedwarn ("invalid character in macro parameter name");
5526 /* Find the end of the arg name. */
5527 while (is_idchar[*bp]) {
5529 /* do we have a "special" rest-args extension here? */
5530 if (limit - bp > REST_EXTENSION_LENGTH &&
5531 bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5533 temp->rest_args = 1;
5537 temp->length = bp - temp->name;
5539 bp += REST_EXTENSION_LENGTH;
5540 arglengths += temp->length + 2;
5541 SKIP_WHITE_SPACE (bp);
5542 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5543 error ("badly punctuated parameter list in `#define'");
5548 SKIP_WHITE_SPACE (bp);
5549 /* A comma at this point can only be followed by an identifier. */
5550 if (!is_idstart[*bp]) {
5551 error ("badly punctuated parameter list in `#define'");
5556 error ("unterminated parameter list in `#define'");
5560 struct arglist *otemp;
5562 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5563 if (temp->length == otemp->length &&
5564 bcmp (temp->name, otemp->name, temp->length) == 0) {
5565 error ("duplicate argument name `%.*s' in `#define'",
5566 temp->length, temp->name);
5572 ++bp; /* skip paren */
5573 SKIP_WHITE_SPACE (bp);
5574 /* now everything from bp before limit is the definition. */
5575 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5576 defn->rest_args = rest_args;
5578 /* Now set defn->args.argnames to the result of concatenating
5579 the argument names in reverse order
5580 with comma-space between them. */
5581 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5583 struct arglist *temp;
5585 for (temp = arg_ptrs; temp; temp = temp->next) {
5586 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5588 if (temp->next != 0) {
5589 defn->args.argnames[i++] = ',';
5590 defn->args.argnames[i++] = ' ';
5593 defn->args.argnames[i] = 0;
5596 /* Simple expansion or empty definition. */
5600 if (is_hor_space[*bp]) {
5602 SKIP_WHITE_SPACE (bp);
5605 case '!': case '"': case '#': case '%': case '&': case '\'':
5606 case ')': case '*': case '+': case ',': case '-': case '.':
5607 case '/': case ':': case ';': case '<': case '=': case '>':
5608 case '?': case '[': case '\\': case ']': case '^': case '{':
5609 case '|': case '}': case '~':
5610 warning ("missing white space after `#define %.*s'",
5611 sym_length, symname);
5615 pedwarn ("missing white space after `#define %.*s'",
5616 sym_length, symname);
5621 /* Now everything from bp before limit is the definition. */
5622 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5623 defn->args.argnames = (U_CHAR *) "";
5629 /* OP is null if this is a predefinition */
5630 defn->predefined = !op;
5632 mdef.symnam = symname;
5633 mdef.symlen = sym_length;
5642 /* Process a #define directive.
5643 BUF points to the contents of the #define directive, as a contiguous string.
5644 LIMIT points to the first character past the end of the definition.
5645 KEYWORD is the keyword-table entry for #define. */
5648 do_define (buf, limit, op, keyword)
5649 U_CHAR *buf, *limit;
5651 struct directive *keyword;
5656 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5657 if (pcp_outfile && op)
5658 pass_thru_directive (buf, limit, op, keyword);
5660 mdef = create_definition (buf, limit, op);
5664 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5668 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5670 /* Redefining a precompiled key is ok. */
5671 if (hp->type == T_PCSTRING)
5673 /* Redefining a macro is ok if the definitions are the same. */
5674 else if (hp->type == T_MACRO)
5675 ok = ! compare_defs (mdef.defn, hp->value.defn);
5676 /* Redefining a constant is ok with -D. */
5677 else if (hp->type == T_CONST)
5678 ok = ! done_initializing;
5679 /* Print the warning if it's not ok. */
5681 /* If we are passing through #define and #undef directives, do
5682 that for this re-definition now. */
5683 if (debug_output && op)
5684 pass_thru_directive (buf, limit, op, keyword);
5686 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5687 if (hp->type == T_MACRO)
5688 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5689 "this is the location of the previous definition");
5691 /* Replace the old definition. */
5693 hp->value.defn = mdef.defn;
5695 /* If we are passing through #define and #undef directives, do
5696 that for this new definition now. */
5697 if (debug_output && op)
5698 pass_thru_directive (buf, limit, op, keyword);
5699 install (mdef.symnam, mdef.symlen, T_MACRO,
5700 (char *) mdef.defn, hashcode);
5711 /* Check a purported macro name SYMNAME, and yield its length.
5712 USAGE is the kind of name this is intended for. */
5715 check_macro_name (symname, usage)
5722 for (p = symname; is_idchar[*p]; p++)
5724 sym_length = p - symname;
5725 if (sym_length == 0)
5726 error ("invalid %s name", usage);
5727 else if (!is_idstart[*symname]
5728 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5729 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5734 * return zero if two DEFINITIONs are isomorphic
5737 compare_defs (d1, d2)
5738 DEFINITION *d1, *d2;
5740 register struct reflist *a1, *a2;
5741 register U_CHAR *p1 = d1->expansion;
5742 register U_CHAR *p2 = d2->expansion;
5745 if (d1->nargs != d2->nargs)
5747 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5749 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5750 a1 = a1->next, a2 = a2->next) {
5751 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5752 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5753 || a1->argno != a2->argno
5754 || a1->stringify != a2->stringify
5755 || a1->raw_before != a2->raw_before
5756 || a1->raw_after != a2->raw_after)
5764 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5765 p2, d2->length - (p2 - d2->expansion), 1))
5770 /* Return 1 if two parts of two macro definitions are effectively different.
5771 One of the parts starts at BEG1 and has LEN1 chars;
5772 the other has LEN2 chars at BEG2.
5773 Any sequence of whitespace matches any other sequence of whitespace.
5774 FIRST means these parts are the first of a macro definition;
5775 so ignore leading whitespace entirely.
5776 LAST means these parts are the last of a macro definition;
5777 so ignore trailing whitespace entirely. */
5780 comp_def_part (first, beg1, len1, beg2, len2, last)
5782 U_CHAR *beg1, *beg2;
5786 register U_CHAR *end1 = beg1 + len1;
5787 register U_CHAR *end2 = beg2 + len2;
5789 while (beg1 != end1 && is_space[*beg1]) beg1++;
5790 while (beg2 != end2 && is_space[*beg2]) beg2++;
5793 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5794 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5796 while (beg1 != end1 && beg2 != end2) {
5797 if (is_space[*beg1] && is_space[*beg2]) {
5798 while (beg1 != end1 && is_space[*beg1]) beg1++;
5799 while (beg2 != end2 && is_space[*beg2]) beg2++;
5800 } else if (*beg1 == *beg2) {
5804 return (beg1 != end1) || (beg2 != end2);
5807 /* Read a replacement list for a macro with parameters.
5808 Build the DEFINITION structure.
5809 Reads characters of text starting at BUF until END.
5810 ARGLIST specifies the formal parameters to look for
5811 in the text of the definition; NARGS is the number of args
5812 in that list, or -1 for a macro name that wants no argument list.
5813 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5814 and NAMELEN is its length in characters.
5816 Note that comments, backslash-newlines, and leading white space
5817 have already been deleted from the argument. */
5819 /* If there is no trailing whitespace, a Newline Space is added at the end
5820 to prevent concatenation that would be contrary to the standard. */
5823 collect_expansion (buf, end, nargs, arglist)
5826 struct arglist *arglist;
5829 register U_CHAR *p, *limit, *lastp, *exp_p;
5830 struct reflist *endpat = NULL;
5831 /* Pointer to first nonspace after last ## seen. */
5833 /* Pointer to first nonspace after last single-# seen. */
5834 U_CHAR *stringify = 0;
5835 /* How those tokens were spelled. */
5836 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5837 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5839 int expected_delimiter = '\0';
5841 /* Scan thru the replacement list, ignoring comments and quoted
5842 strings, picking up on the macro calls. It does a linear search
5843 thru the arg list on every potential symbol. Profiling might say
5844 that something smarter should happen. */
5849 /* Find the beginning of the trailing whitespace. */
5852 while (p < limit && is_space[limit[-1]]) limit--;
5854 /* Allocate space for the text in the macro definition.
5855 Each input char may or may not need 1 byte,
5856 so this is an upper bound.
5857 The extra 3 are for invented trailing newline-marker and final null. */
5858 maxsize = (sizeof (DEFINITION)
5860 defn = (DEFINITION *) xcalloc (1, maxsize);
5862 defn->nargs = nargs;
5863 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5868 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5869 error ("`##' at start of macro definition");
5870 p += p[0] == '#' ? 2 : 4;
5873 /* Process the main body of the definition. */
5875 int skipped_arg = 0;
5876 register U_CHAR c = *p++;
5884 if (expected_delimiter != '\0') {
5885 if (c == expected_delimiter)
5886 expected_delimiter = '\0';
5888 expected_delimiter = c;
5892 if (p < limit && expected_delimiter) {
5893 /* In a string, backslash goes through
5894 and makes next char ordinary. */
5900 if (!expected_delimiter && *p == ':') {
5901 /* %: is not a digraph if preceded by an odd number of '<'s. */
5903 while (buf < p0 && p0[-1] == '<')
5906 /* Treat %:%: as ## and %: as #. */
5907 if (p[1] == '%' && p[2] == ':') {
5909 goto sharp_sharp_token;
5920 /* # is ordinary inside a string. */
5921 if (expected_delimiter)
5925 /* ##: concatenate preceding and following tokens. */
5926 /* Take out the first #, discard preceding whitespace. */
5928 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5930 /* Skip the second #. */
5932 concat_sharp_token_type = c;
5933 if (is_hor_space[*p]) {
5934 concat_sharp_token_type = c + 1;
5936 SKIP_WHITE_SPACE (p);
5940 error ("`##' at end of macro definition");
5941 } else if (nargs >= 0) {
5942 /* Single #: stringify following argument ref.
5943 Don't leave the # in the expansion. */
5946 stringify_sharp_token_type = c;
5947 if (is_hor_space[*p]) {
5948 stringify_sharp_token_type = c + 1;
5950 SKIP_WHITE_SPACE (p);
5952 if (! is_idstart[*p] || nargs == 0)
5953 error ("`#' operator is not followed by a macro argument name");
5960 /* In -traditional mode, recognize arguments inside strings and
5961 and character constants, and ignore special properties of #.
5962 Arguments inside strings are considered "stringified", but no
5963 extra quote marks are supplied. */
5967 if (expected_delimiter != '\0') {
5968 if (c == expected_delimiter)
5969 expected_delimiter = '\0';
5971 expected_delimiter = c;
5975 /* Backslash quotes delimiters and itself, but not macro args. */
5976 if (expected_delimiter != 0 && p < limit
5977 && (*p == expected_delimiter || *p == '\\')) {
5984 if (expected_delimiter != '\0') /* No comments inside strings. */
5987 /* If we find a comment that wasn't removed by handle_directive,
5988 this must be -traditional. So replace the comment with
5992 while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5995 /* Mark this as a concatenation-point, as if it had been ##. */
6003 /* Handle the start of a symbol. */
6004 if (is_idchar[c] && nargs > 0) {
6005 U_CHAR *id_beg = p - 1;
6009 while (p != limit && is_idchar[*p]) p++;
6010 id_len = p - id_beg;
6012 if (is_idstart[c]) {
6013 register struct arglist *arg;
6015 for (arg = arglist; arg != NULL; arg = arg->next) {
6016 struct reflist *tpat;
6018 if (arg->name[0] == c
6019 && arg->length == id_len
6020 && bcmp (arg->name, id_beg, id_len) == 0) {
6021 enum sharp_token_type tpat_stringify;
6022 if (expected_delimiter) {
6023 if (warn_stringify) {
6025 warning ("macro argument `%.*s' is stringified.",
6028 warning ("macro arg `%.*s' would be stringified with -traditional.",
6032 /* If ANSI, don't actually substitute inside a string. */
6035 tpat_stringify = SHARP_TOKEN;
6038 = (stringify == id_beg
6039 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6041 /* make a pat node for this arg and append it to the end of
6043 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6046 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6047 tpat->raw_after = NO_SHARP_TOKEN;
6048 tpat->rest_args = arg->rest_args;
6049 tpat->stringify = tpat_stringify;
6052 defn->pattern = tpat;
6054 endpat->next = tpat;
6057 tpat->argno = arg->argno;
6058 tpat->nchars = exp_p - lastp;
6060 register U_CHAR *p1 = p;
6061 SKIP_WHITE_SPACE (p1);
6064 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6065 tpat->raw_after = p1[0] + (p != p1);
6067 lastp = exp_p; /* place to start copying from next time */
6074 /* If this was not a macro arg, copy it into the expansion. */
6075 if (! skipped_arg) {
6076 register U_CHAR *lim1 = p;
6080 if (stringify == id_beg)
6081 error ("`#' operator should be followed by a macro argument name");
6086 if (!traditional && expected_delimiter == 0) {
6087 /* If ANSI, put in a newline-space marker to prevent token pasting.
6088 But not if "inside a string" (which in ANSI mode happens only for
6096 defn->length = exp_p - defn->expansion;
6098 /* Crash now if we overrun the allocated size. */
6099 if (defn->length + 1 > maxsize)
6103 /* This isn't worth the time it takes. */
6104 /* give back excess storage */
6105 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6112 do_assert (buf, limit, op, keyword)
6113 U_CHAR *buf, *limit;
6115 struct directive *keyword;
6117 U_CHAR *bp; /* temp ptr into input buffer */
6118 U_CHAR *symname; /* remember where symbol name starts */
6119 int sym_length; /* and how long it is */
6120 struct arglist *tokens = NULL;
6122 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6123 pedwarn ("ANSI C does not allow `#assert'");
6127 while (is_hor_space[*bp])
6130 symname = bp; /* remember where it starts */
6131 sym_length = check_macro_name (bp, "assertion");
6133 /* #define doesn't do this, but we should. */
6134 SKIP_WHITE_SPACE (bp);
6136 /* Lossage will occur if identifiers or control tokens are broken
6137 across lines using backslash. This is not the right place to take
6141 error ("missing token-sequence in `#assert'");
6148 bp++; /* skip '(' */
6149 SKIP_WHITE_SPACE (bp);
6151 tokens = read_token_list (&bp, limit, &error_flag);
6155 error ("empty token-sequence in `#assert'");
6159 ++bp; /* skip paren */
6160 SKIP_WHITE_SPACE (bp);
6163 /* If this name isn't already an assertion name, make it one.
6164 Error if it was already in use in some other way. */
6167 ASSERTION_HASHNODE *hp;
6168 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6169 struct tokenlist_list *value
6170 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6172 hp = assertion_lookup (symname, sym_length, hashcode);
6174 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6175 error ("`defined' redefined as assertion");
6176 hp = assertion_install (symname, sym_length, hashcode);
6179 /* Add the spec'd token-sequence to the list of such. */
6180 value->tokens = tokens;
6181 value->next = hp->value;
6189 do_unassert (buf, limit, op, keyword)
6190 U_CHAR *buf, *limit;
6192 struct directive *keyword;
6194 U_CHAR *bp; /* temp ptr into input buffer */
6195 U_CHAR *symname; /* remember where symbol name starts */
6196 int sym_length; /* and how long it is */
6198 struct arglist *tokens = NULL;
6199 int tokens_specified = 0;
6201 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6202 pedwarn ("ANSI C does not allow `#unassert'");
6206 while (is_hor_space[*bp])
6209 symname = bp; /* remember where it starts */
6210 sym_length = check_macro_name (bp, "assertion");
6212 /* #define doesn't do this, but we should. */
6213 SKIP_WHITE_SPACE (bp);
6215 /* Lossage will occur if identifiers or control tokens are broken
6216 across lines using backslash. This is not the right place to take
6222 bp++; /* skip '(' */
6223 SKIP_WHITE_SPACE (bp);
6225 tokens = read_token_list (&bp, limit, &error_flag);
6229 error ("empty token list in `#unassert'");
6233 tokens_specified = 1;
6235 ++bp; /* skip paren */
6236 SKIP_WHITE_SPACE (bp);
6240 ASSERTION_HASHNODE *hp;
6241 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6242 struct tokenlist_list *tail, *prev;
6244 hp = assertion_lookup (symname, sym_length, hashcode);
6248 /* If no token list was specified, then eliminate this assertion
6250 if (! tokens_specified) {
6251 struct tokenlist_list *next;
6252 for (tail = hp->value; tail; tail = next) {
6254 free_token_list (tail->tokens);
6257 delete_assertion (hp);
6259 /* If a list of tokens was given, then delete any matching list. */
6264 struct tokenlist_list *next = tail->next;
6265 if (compare_token_lists (tail->tokens, tokens)) {
6269 hp->value = tail->next;
6270 free_token_list (tail->tokens);
6283 /* Test whether there is an assertion named NAME
6284 and optionally whether it has an asserted token list TOKENS.
6285 NAME is not null terminated; its length is SYM_LENGTH.
6286 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6289 check_assertion (name, sym_length, tokens_specified, tokens)
6292 int tokens_specified;
6293 struct arglist *tokens;
6295 ASSERTION_HASHNODE *hp;
6296 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6298 if (pedantic && !instack[indepth].system_header_p)
6299 pedwarn ("ANSI C does not allow testing assertions");
6301 hp = assertion_lookup (name, sym_length, hashcode);
6303 /* It is not an assertion; just return false. */
6306 /* If no token list was specified, then value is 1. */
6307 if (! tokens_specified)
6311 struct tokenlist_list *tail;
6315 /* If a list of tokens was given,
6316 then succeed if the assertion records a matching list. */
6319 if (compare_token_lists (tail->tokens, tokens))
6324 /* Fail if the assertion has no matching list. */
6329 /* Compare two lists of tokens for equality including order of tokens. */
6332 compare_token_lists (l1, l2)
6333 struct arglist *l1, *l2;
6336 if (l1->length != l2->length)
6338 if (bcmp (l1->name, l2->name, l1->length))
6344 /* Succeed if both lists end at the same time. */
6348 /* Read a space-separated list of tokens ending in a close parenthesis.
6349 Return a list of strings, in the order they were written.
6350 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6351 Parse the text starting at *BPP, and update *BPP.
6352 Don't parse beyond LIMIT. */
6354 static struct arglist *
6355 read_token_list (bpp, limit, error_flag)
6360 struct arglist *token_ptrs = 0;
6366 /* Loop over the assertion value tokens. */
6368 struct arglist *temp;
6372 /* Find the end of the token. */
6376 } else if (*bp == ')') {
6381 } else if (*bp == '"' || *bp == '\'')
6382 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6384 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6385 && *bp != '"' && *bp != '\'' && bp != limit)
6388 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6389 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6390 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6391 temp->name[bp - beg] = 0;
6392 temp->next = token_ptrs;
6394 temp->length = bp - beg;
6396 SKIP_WHITE_SPACE (bp);
6399 error ("unterminated token sequence in `#assert' or `#unassert'");
6406 /* We accumulated the names in reverse order.
6407 Now reverse them to get the proper order. */
6409 register struct arglist *prev = 0, *this, *next;
6410 for (this = token_ptrs; this; this = next) {
6420 free_token_list (tokens)
6421 struct arglist *tokens;
6424 struct arglist *next = tokens->next;
6425 free (tokens->name);
6432 * Install a name in the assertion hash table.
6434 * If LEN is >= 0, it is the length of the name.
6435 * Otherwise, compute the length by scanning the entire name.
6437 * If HASH is >= 0, it is the precomputed hash code.
6438 * Otherwise, compute the hash code.
6440 static ASSERTION_HASHNODE *
6441 assertion_install (name, len, hash)
6446 register ASSERTION_HASHNODE *hp;
6447 register int i, bucket;
6448 register U_CHAR *p, *q;
6450 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6451 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6453 hp->bucket_hdr = &assertion_hashtab[bucket];
6454 hp->next = assertion_hashtab[bucket];
6455 assertion_hashtab[bucket] = hp;
6457 if (hp->next != NULL)
6458 hp->next->prev = hp;
6461 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6464 for (i = 0; i < len; i++)
6471 * find the most recent hash node for name name (ending with first
6472 * non-identifier char) installed by install
6474 * If LEN is >= 0, it is the length of the name.
6475 * Otherwise, compute the length by scanning the entire name.
6477 * If HASH is >= 0, it is the precomputed hash code.
6478 * Otherwise, compute the hash code.
6480 static ASSERTION_HASHNODE *
6481 assertion_lookup (name, len, hash)
6486 register ASSERTION_HASHNODE *bucket;
6488 bucket = assertion_hashtab[hash];
6490 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6492 bucket = bucket->next;
6498 delete_assertion (hp)
6499 ASSERTION_HASHNODE *hp;
6502 if (hp->prev != NULL)
6503 hp->prev->next = hp->next;
6504 if (hp->next != NULL)
6505 hp->next->prev = hp->prev;
6507 /* make sure that the bucket chain header that
6508 the deleted guy was on points to the right thing afterwards. */
6509 if (hp == *hp->bucket_hdr)
6510 *hp->bucket_hdr = hp->next;
6516 * interpret #line directive. Remembers previously seen fnames
6517 * in its very own hash table.
6519 #define FNAME_HASHSIZE 37
6522 do_line (buf, limit, op, keyword)
6523 U_CHAR *buf, *limit;
6525 struct directive *keyword;
6527 register U_CHAR *bp;
6528 FILE_BUF *ip = &instack[indepth];
6531 enum file_change_code file_change = same_file;
6533 /* Expand any macros. */
6534 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6536 /* Point to macroexpanded line, which is null-terminated now. */
6538 SKIP_WHITE_SPACE (bp);
6540 if (!isdigit (*bp)) {
6541 error ("invalid format `#line' directive");
6545 /* The Newline at the end of this line remains to be processed.
6546 To put the next line at the specified line number,
6547 we must store a line number now that is one less. */
6548 new_lineno = atoi ((char *) bp) - 1;
6550 /* NEW_LINENO is one less than the actual line number here. */
6551 if (pedantic && new_lineno < 0)
6552 pedwarn ("line number out of range in `#line' directive");
6554 /* skip over the line number. */
6555 while (isdigit (*bp))
6558 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6559 if (*bp && !is_space[*bp]) {
6560 error ("invalid format `#line' directive");
6565 SKIP_WHITE_SPACE (bp);
6568 static HASHNODE *fname_table[FNAME_HASHSIZE];
6569 HASHNODE *hp, **hash_bucket;
6575 /* Turn the file name, which is a character string literal,
6576 into a null-terminated string. Do this in place. */
6579 switch ((*p++ = *bp++)) {
6581 error ("invalid format `#line' directive");
6586 char *bpc = (char *) bp;
6587 int c = parse_escape (&bpc);
6588 bp = (U_CHAR *) bpc;
6601 fname_length = p - fname;
6603 SKIP_WHITE_SPACE (bp);
6606 pedwarn ("garbage at end of `#line' directive");
6608 file_change = enter_file;
6609 else if (*bp == '2')
6610 file_change = leave_file;
6611 else if (*bp == '3')
6612 ip->system_header_p = 1;
6613 else if (*bp == '4')
6614 ip->system_header_p = 2;
6616 error ("invalid format `#line' directive");
6621 SKIP_WHITE_SPACE (bp);
6623 ip->system_header_p = 1;
6625 SKIP_WHITE_SPACE (bp);
6628 ip->system_header_p = 2;
6630 SKIP_WHITE_SPACE (bp);
6633 error ("invalid format `#line' directive");
6639 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6640 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6641 if (hp->length == fname_length &&
6642 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6643 ip->nominal_fname = hp->value.cpval;
6647 /* Didn't find it; cons up a new one. */
6648 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6649 hp->next = *hash_bucket;
6652 hp->length = fname_length;
6653 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6654 bcopy (fname, hp->value.cpval, fname_length);
6657 error ("invalid format `#line' directive");
6661 ip->lineno = new_lineno;
6662 output_line_directive (ip, op, 0, file_change);
6663 check_expand (op, ip->length - (ip->bufp - ip->buf));
6668 * remove the definition of a symbol from the symbol table.
6669 * according to un*x /lib/cpp, it is not an error to undef
6670 * something that has no definitions, so it isn't one here either.
6674 do_undef (buf, limit, op, keyword)
6675 U_CHAR *buf, *limit;
6677 struct directive *keyword;
6681 U_CHAR *orig_buf = buf;
6683 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6684 if (pcp_outfile && op)
6685 pass_thru_directive (buf, limit, op, keyword);
6687 SKIP_WHITE_SPACE (buf);
6688 sym_length = check_macro_name (buf, "macro");
6690 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6691 /* If we are generating additional info for debugging (with -g) we
6692 need to pass through all effective #undef directives. */
6693 if (debug_output && op)
6694 pass_thru_directive (orig_buf, limit, op, keyword);
6695 if (hp->type != T_MACRO)
6696 warning ("undefining `%s'", hp->name);
6702 SKIP_WHITE_SPACE (buf);
6704 pedwarn ("garbage after `#undef' directive");
6710 * Report an error detected by the program we are processing.
6711 * Use the text of the line in the error message.
6712 * (We use error because it prints the filename & line#.)
6716 do_error (buf, limit, op, keyword)
6717 U_CHAR *buf, *limit;
6719 struct directive *keyword;
6721 int length = limit - buf;
6722 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6723 bcopy ((char *) buf, (char *) copy, length);
6725 SKIP_WHITE_SPACE (copy);
6726 error ("#error %s", copy);
6731 * Report a warning detected by the program we are processing.
6732 * Use the text of the line in the warning message, then continue.
6733 * (We use error because it prints the filename & line#.)
6737 do_warning (buf, limit, op, keyword)
6738 U_CHAR *buf, *limit;
6740 struct directive *keyword;
6742 int length = limit - buf;
6743 U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6744 bcopy ((char *) buf, (char *) copy, length);
6746 SKIP_WHITE_SPACE (copy);
6747 warning ("#warning %s", copy);
6751 /* Remember the name of the current file being read from so that we can
6752 avoid ever including it again. */
6759 for (i = indepth; i >= 0; i--)
6760 if (instack[i].inc) {
6761 record_control_macro (instack[i].inc, (U_CHAR *) "");
6766 /* #ident has already been copied to the output file, so just ignore it. */
6769 do_ident (buf, limit, op, keyword)
6770 U_CHAR *buf, *limit;
6772 struct directive *keyword;
6777 /* Allow #ident in system headers, since that's not user's fault. */
6778 if (pedantic && !instack[indepth].system_header_p)
6779 pedwarn ("ANSI C does not allow `#ident'");
6781 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6782 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6783 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6784 limit = buf + (trybuf.bufp - trybuf.buf);
6785 len = (limit - buf);
6788 /* Output directive name. */
6789 check_expand (op, 7);
6790 bcopy ("#ident ", (char *) op->bufp, 7);
6793 /* Output the expanded argument line. */
6794 check_expand (op, len);
6795 bcopy ((char *) buf, (char *) op->bufp, len);
6801 /* #pragma and its argument line have already been copied to the output file.
6802 Just check for some recognized pragmas that need validation here. */
6805 do_pragma (buf, limit, op, keyword)
6806 U_CHAR *buf, *limit;
6808 struct directive *keyword;
6810 SKIP_WHITE_SPACE (buf);
6811 if (!strncmp ((char *) buf, "once", 4)) {
6812 /* Allow #pragma once in system headers, since that's not the user's
6814 if (!instack[indepth].system_header_p)
6815 warning ("`#pragma once' is obsolete");
6819 if (!strncmp ((char *) buf, "implementation", 14)) {
6820 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6821 been included yet. */
6824 U_CHAR *p = buf + 14, *fname;
6825 SKIP_WHITE_SPACE (p);
6826 if (*p == '\n' || *p != '\"')
6830 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6833 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6834 struct include_file *inc;
6835 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6836 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6837 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6847 /* This was a fun hack, but #pragma seems to start to be useful.
6848 By failing to recognize it, we pass it through unchanged to cc1. */
6851 * the behavior of the #pragma directive is implementation defined.
6852 * this implementation defines it as follows.
6859 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6862 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6864 execl ("/usr/games/hack", "#pragma", 0);
6865 execl ("/usr/games/rogue", "#pragma", 0);
6866 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6867 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6869 fatal ("You are in a maze of twisty compiler features, all different");
6873 #ifdef SCCS_DIRECTIVE
6875 /* Just ignore #sccs, on systems where we define it at all. */
6878 do_sccs (buf, limit, op, keyword)
6879 U_CHAR *buf, *limit;
6881 struct directive *keyword;
6884 pedwarn ("ANSI C does not allow `#sccs'");
6888 #endif /* defined (SCCS_DIRECTIVE) */
6891 * handle #if directive by
6892 * 1) inserting special `defined' keyword into the hash table
6893 * that gets turned into 0 or 1 by special_symbol (thus,
6894 * if the luser has a symbol called `defined' already, it won't
6895 * work inside the #if directive)
6896 * 2) rescan the input into a temporary output buffer
6897 * 3) pass the output buffer to the yacc parser and collect a value
6898 * 4) clean up the mess left from steps 1 and 2.
6899 * 5) call conditional_skip to skip til the next #endif (etc.),
6900 * or not, depending on the value from step 3.
6904 do_if (buf, limit, op, keyword)
6905 U_CHAR *buf, *limit;
6907 struct directive *keyword;
6909 HOST_WIDE_INT value;
6910 FILE_BUF *ip = &instack[indepth];
6912 value = eval_if_expression (buf, limit - buf);
6913 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6918 * handle a #elif directive by not changing if_stack either.
6919 * see the comment above do_else.
6923 do_elif (buf, limit, op, keyword)
6924 U_CHAR *buf, *limit;
6926 struct directive *keyword;
6928 HOST_WIDE_INT value;
6929 FILE_BUF *ip = &instack[indepth];
6931 if (if_stack == instack[indepth].if_stack) {
6932 error ("`#elif' not within a conditional");
6935 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6936 error ("`#elif' after `#else'");
6937 fprintf (stderr, " (matches line %d", if_stack->lineno);
6938 if (if_stack->fname != NULL && ip->fname != NULL &&
6939 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6940 fprintf (stderr, ", file %s", if_stack->fname);
6941 fprintf (stderr, ")\n");
6943 if_stack->type = T_ELIF;
6946 if (if_stack->if_succeeded)
6947 skip_if_group (ip, 0, op);
6949 value = eval_if_expression (buf, limit - buf);
6951 skip_if_group (ip, 0, op);
6953 ++if_stack->if_succeeded; /* continue processing input */
6954 output_line_directive (ip, op, 1, same_file);
6961 * evaluate a #if expression in BUF, of length LENGTH,
6962 * then parse the result as a C expression and return the value as an int.
6964 static HOST_WIDE_INT
6965 eval_if_expression (buf, length)
6970 HASHNODE *save_defined;
6971 HOST_WIDE_INT value;
6973 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6976 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6978 delete_macro (save_defined); /* clean up special symbol */
6980 value = parse_c_expression ((char *) temp_obuf.buf);
6982 free (temp_obuf.buf);
6988 * routine to handle ifdef/ifndef. Try to look up the symbol,
6989 * then do or don't skip to the #endif/#else/#elif depending
6990 * on what directive is actually being processed.
6994 do_xifdef (buf, limit, op, keyword)
6995 U_CHAR *buf, *limit;
6997 struct directive *keyword;
7000 FILE_BUF *ip = &instack[indepth];
7002 int start_of_file = 0;
7003 U_CHAR *control_macro = 0;
7005 /* Detect a #ifndef at start of file (not counting comments). */
7006 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7007 U_CHAR *p = ip->buf;
7008 while (p != directive_start) {
7012 /* Make no special provision for backslash-newline here; this is
7013 slower if backslash-newlines are present, but it's correct,
7014 and it's not worth it to tune for the rare backslash-newline. */
7016 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7017 /* Skip this comment. */
7019 U_CHAR *save_bufp = ip->bufp;
7021 p = skip_to_end_of_comment (ip, &junk, 1);
7022 ip->bufp = save_bufp;
7027 /* If we get here, this conditional is the beginning of the file. */
7032 /* Discard leading and trailing whitespace. */
7033 SKIP_WHITE_SPACE (buf);
7034 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7036 /* Find the end of the identifier at the beginning. */
7037 for (end = buf; is_idchar[*end]; end++);
7040 skip = (keyword->type == T_IFDEF);
7042 pedwarn (end == limit ? "`#%s' with no argument"
7043 : "`#%s' argument starts with punctuation",
7048 if (pedantic && buf[0] >= '0' && buf[0] <= '9')
7049 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7050 else if (end != limit && !traditional)
7051 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7053 hp = lookup (buf, end-buf, -1);
7056 /* Output a precondition for this macro. */
7058 (hp->type == T_CONST
7059 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7060 fprintf (pcp_outfile, "#define %s\n", hp->name);
7063 fprintf (pcp_outfile, "#undef ");
7064 while (is_idchar[*cp]) /* Ick! */
7065 fputc (*cp++, pcp_outfile);
7066 putc ('\n', pcp_outfile);
7070 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7071 if (start_of_file && !skip) {
7072 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7073 bcopy ((char *) buf, (char *) control_macro, end - buf);
7074 control_macro[end - buf] = 0;
7078 conditional_skip (ip, skip, T_IF, control_macro, op);
7082 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7083 If this is a #ifndef starting at the beginning of a file,
7084 CONTROL_MACRO is the macro name tested by the #ifndef.
7085 Otherwise, CONTROL_MACRO is 0. */
7088 conditional_skip (ip, skip, type, control_macro, op)
7091 enum node_type type;
7092 U_CHAR *control_macro;
7095 IF_STACK_FRAME *temp;
7097 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7098 temp->fname = ip->nominal_fname;
7099 temp->lineno = ip->lineno;
7100 temp->next = if_stack;
7101 temp->control_macro = control_macro;
7104 if_stack->type = type;
7107 skip_if_group (ip, 0, op);
7110 ++if_stack->if_succeeded;
7111 output_line_directive (ip, &outbuf, 1, same_file);
7116 * skip to #endif, #else, or #elif. adjust line numbers, etc.
7117 * leaves input ptr at the sharp sign found.
7118 * If ANY is nonzero, return at next directive of any sort.
7121 skip_if_group (ip, any, op)
7126 register U_CHAR *bp = ip->bufp, *cp;
7127 register U_CHAR *endb = ip->buf + ip->length;
7128 struct directive *kt;
7129 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7130 U_CHAR *beg_of_line = bp;
7131 register int ident_length;
7132 U_CHAR *ident, *after_ident;
7133 /* Save info about where the group starts. */
7134 U_CHAR *beg_of_group = bp;
7135 int beg_lineno = ip->lineno;
7137 if (output_conditionals && op != 0) {
7138 char *ptr = "#failed\n";
7139 int len = strlen (ptr);
7141 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7146 check_expand (op, len);
7147 bcopy (ptr, (char *) op->bufp, len);
7150 output_line_directive (ip, op, 1, 0);
7155 case '/': /* possible comment */
7156 if (*bp == '\\' && bp[1] == '\n')
7159 || (cplusplus_comments && *bp == '/')) {
7161 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7166 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7167 NULL_PTR, NULL_PTR);
7170 /* Char after backslash loses its special meaning. */
7173 ++ip->lineno; /* But do update the line-count. */
7182 if (beg_of_line == 0 || traditional)
7185 while (bp[0] == '\\' && bp[1] == '\n')
7191 /* # keyword: a # must be first nonblank char on the line */
7192 if (beg_of_line == 0)
7196 /* Scan from start of line, skipping whitespace, comments
7197 and backslash-newlines, and see if we reach this #.
7198 If not, this # is not special. */
7200 /* If -traditional, require # to be at beginning of line. */
7203 if (is_hor_space[*bp])
7205 else if (*bp == '\\' && bp[1] == '\n')
7207 else if (*bp == '/' && bp[1] == '*') {
7209 while (!(*bp == '*' && bp[1] == '/'))
7213 /* There is no point in trying to deal with C++ // comments here,
7214 because if there is one, then this # must be part of the
7215 comment and we would never reach here. */
7219 if (bp != ip->bufp) {
7220 bp = ip->bufp + 1; /* Reset bp to after the #. */
7224 bp = ip->bufp + 1; /* Point after the '#' */
7225 if (ip->bufp[0] == '%') {
7226 /* Skip past the ':' again. */
7227 while (*bp == '\\') {
7234 /* Skip whitespace and \-newline. */
7236 if (is_hor_space[*bp])
7238 else if (*bp == '\\' && bp[1] == '\n')
7240 else if (*bp == '/') {
7242 for (bp += 2; ; bp++) {
7245 else if (*bp == '*') {
7246 if (bp[-1] == '/' && warn_comments)
7247 warning ("`/*' within comment");
7253 } else if (bp[1] == '/' && cplusplus_comments) {
7254 for (bp += 2; ; bp++) {
7259 warning ("multiline `//' comment");
7271 /* Now find end of directive name.
7272 If we encounter a backslash-newline, exchange it with any following
7273 symbol-constituents so that we end up with a contiguous name. */
7279 if (*bp == '\\' && bp[1] == '\n')
7280 name_newline_fix (bp);
7286 ident_length = bp - cp;
7290 /* A line of just `#' becomes blank. */
7292 if (ident_length == 0 && *after_ident == '\n') {
7296 if (ident_length == 0 || !is_idstart[*ident]) {
7298 while (is_idchar[*p]) {
7299 if (*p < '0' || *p > '9')
7303 /* Handle # followed by a line number. */
7304 if (p != ident && !is_idchar[*p]) {
7306 pedwarn ("`#' followed by integer");
7310 /* Avoid error for `###' and similar cases unless -pedantic. */
7312 while (*p == '#' || is_hor_space[*p]) p++;
7314 if (pedantic && !lang_asm)
7315 pedwarn ("invalid preprocessing directive");
7320 if (!lang_asm && pedantic)
7321 pedwarn ("invalid preprocessing directive name");
7325 for (kt = directive_table; kt->length >= 0; kt++) {
7326 IF_STACK_FRAME *temp;
7327 if (ident_length == kt->length
7328 && bcmp (cp, kt->name, kt->length) == 0) {
7329 /* If we are asked to return on next directive, do so now. */
7337 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7338 temp->next = if_stack;
7340 temp->lineno = ip->lineno;
7341 temp->fname = ip->nominal_fname;
7342 temp->type = kt->type;
7346 if (pedantic && if_stack != save_if_stack)
7349 if (if_stack == instack[indepth].if_stack) {
7350 error ("`#%s' not within a conditional", kt->name);
7353 else if (if_stack == save_if_stack)
7354 goto done; /* found what we came for */
7356 if (kt->type != T_ENDIF) {
7357 if (if_stack->type == T_ELSE)
7358 error ("`#else' or `#elif' after `#else'");
7359 if_stack->type = kt->type;
7364 if_stack = if_stack->next;
7374 /* Don't let erroneous code go by. */
7375 if (kt->length < 0 && !lang_asm && pedantic)
7376 pedwarn ("invalid preprocessing directive name");
7381 /* after this returns, rescan will exit because ip->bufp
7382 now points to the end of the buffer.
7383 rescan is responsible for the error message also. */
7386 if (output_conditionals && op != 0) {
7387 char *ptr = "#endfailed\n";
7388 int len = strlen (ptr);
7390 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7395 check_expand (op, beg_of_line - beg_of_group);
7396 bcopy ((char *) beg_of_group, (char *) op->bufp,
7397 beg_of_line - beg_of_group);
7398 op->bufp += beg_of_line - beg_of_group;
7399 op->lineno += ip->lineno - beg_lineno;
7400 check_expand (op, len);
7401 bcopy (ptr, (char *) op->bufp, len);
7408 * handle a #else directive. Do this by just continuing processing
7409 * without changing if_stack ; this is so that the error message
7410 * for missing #endif's etc. will point to the original #if. It
7411 * is possible that something different would be better.
7415 do_else (buf, limit, op, keyword)
7416 U_CHAR *buf, *limit;
7418 struct directive *keyword;
7420 FILE_BUF *ip = &instack[indepth];
7423 SKIP_WHITE_SPACE (buf);
7425 pedwarn ("text following `#else' violates ANSI standard");
7428 if (if_stack == instack[indepth].if_stack) {
7429 error ("`#else' not within a conditional");
7432 /* #ifndef can't have its special treatment for containing the whole file
7433 if it has a #else clause. */
7434 if_stack->control_macro = 0;
7436 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7437 error ("`#else' after `#else'");
7438 fprintf (stderr, " (matches line %d", if_stack->lineno);
7439 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7440 fprintf (stderr, ", file %s", if_stack->fname);
7441 fprintf (stderr, ")\n");
7443 if_stack->type = T_ELSE;
7446 if (if_stack->if_succeeded)
7447 skip_if_group (ip, 0, op);
7449 ++if_stack->if_succeeded; /* continue processing input */
7450 output_line_directive (ip, op, 1, same_file);
7456 * unstack after #endif directive
7460 do_endif (buf, limit, op, keyword)
7461 U_CHAR *buf, *limit;
7463 struct directive *keyword;
7466 SKIP_WHITE_SPACE (buf);
7468 pedwarn ("text following `#endif' violates ANSI standard");
7471 if (if_stack == instack[indepth].if_stack)
7472 error ("unbalanced `#endif'");
7474 IF_STACK_FRAME *temp = if_stack;
7475 if_stack = if_stack->next;
7476 if (temp->control_macro != 0) {
7477 /* This #endif matched a #ifndef at the start of the file.
7478 See if it is at the end of the file. */
7479 FILE_BUF *ip = &instack[indepth];
7480 U_CHAR *p = ip->bufp;
7481 U_CHAR *ep = ip->buf + ip->length;
7487 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7488 /* Skip this comment. */
7490 U_CHAR *save_bufp = ip->bufp;
7492 p = skip_to_end_of_comment (ip, &junk, 1);
7493 ip->bufp = save_bufp;
7498 /* If we get here, this #endif ends a #ifndef
7499 that contains all of the file (aside from whitespace).
7500 Arrange not to include the file again
7501 if the macro that was tested is defined.
7503 Do not do this for the top-level file in a -include or any
7504 file in a -imacros. */
7506 && ! (indepth == 1 && no_record_file)
7507 && ! (no_record_file && no_output))
7508 record_control_macro (ip->inc, temp->control_macro);
7512 output_line_directive (&instack[indepth], op, 1, same_file);
7517 /* When an #else or #endif is found while skipping failed conditional,
7518 if -pedantic was specified, this is called to warn about text after
7519 the directive name. P points to the first char after the directive name. */
7525 /* Advance P over whitespace and comments. */
7527 if (*p == '\\' && p[1] == '\n')
7529 if (is_hor_space[*p])
7531 else if (*p == '/') {
7532 if (p[1] == '\\' && p[2] == '\n')
7533 newline_fix (p + 1);
7536 /* Don't bother warning about unterminated comments
7537 since that will happen later. Just be sure to exit. */
7539 if (p[1] == '\\' && p[2] == '\n')
7540 newline_fix (p + 1);
7541 if (*p == '*' && p[1] == '/') {
7548 else if (cplusplus_comments && p[1] == '/') {
7550 while (*p && (*p != '\n' || p[-1] == '\\'))
7555 if (*p && *p != '\n')
7556 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7559 /* Skip a comment, assuming the input ptr immediately follows the
7560 initial slash-star. Bump *LINE_COUNTER for each newline.
7561 (The canonical line counter is &ip->lineno.)
7562 Don't use this routine (or the next one) if bumping the line
7563 counter is not sufficient to deal with newlines in the string.
7565 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7566 This feature is useful when processing a comment that is going to be
7567 processed or was processed at another point in the preprocessor,
7568 to avoid a duplicate warning. Likewise for unterminated comment errors. */
7571 skip_to_end_of_comment (ip, line_counter, nowarn)
7572 register FILE_BUF *ip;
7573 int *line_counter; /* place to remember newlines, or NULL */
7576 register U_CHAR *limit = ip->buf + ip->length;
7577 register U_CHAR *bp = ip->bufp;
7578 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7579 int start_line = line_counter ? *line_counter : 0;
7581 /* JF this line_counter stuff is a crock to make sure the
7582 comment is only put out once, no matter how many times
7583 the comment is skipped. It almost works */
7586 *op->bufp++ = bp[-1];
7588 if (cplusplus_comments && bp[-1] == '/') {
7589 for (; bp < limit; bp++) {
7595 if (!nowarn && warn_comments)
7596 warning ("multiline `//' comment");
7606 while (bp < limit) {
7611 /* If this is the end of the file, we have an unterminated comment.
7612 Don't swallow the newline. We are guaranteed that there will be a
7613 trailing newline and various pieces assume it's there. */
7620 if (line_counter != NULL)
7626 if (bp[-2] == '/' && !nowarn && warn_comments)
7627 warning ("`/*' within comment");
7628 if (*bp == '\\' && bp[1] == '\n')
7641 error_with_line (line_for_error (start_line), "unterminated comment");
7647 * Skip over a quoted string. BP points to the opening quote.
7648 * Returns a pointer after the closing quote. Don't go past LIMIT.
7649 * START_LINE is the line number of the starting point (but it need
7650 * not be valid if the starting point is inside a macro expansion).
7652 * The input stack state is not changed.
7654 * If COUNT_NEWLINES is nonzero, it points to an int to increment
7655 * for each newline passed.
7657 * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7658 * if we pass a backslash-newline.
7660 * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7663 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7664 register U_CHAR *bp;
7665 register U_CHAR *limit;
7667 int *count_newlines;
7668 int *backslash_newlines_p;
7671 register U_CHAR c, match;
7676 error_with_line (line_for_error (start_line),
7677 "unterminated string or character constant");
7678 error_with_line (multiline_string_line,
7679 "possible real start of unterminated constant");
7680 multiline_string_line = 0;
7687 while (*bp == '\\' && bp[1] == '\n') {
7688 if (backslash_newlines_p)
7689 *backslash_newlines_p = 1;
7694 if (*bp == '\n' && count_newlines) {
7695 if (backslash_newlines_p)
7696 *backslash_newlines_p = 1;
7700 } else if (c == '\n') {
7702 /* Unterminated strings and character constants are 'valid'. */
7703 bp--; /* Don't consume the newline. */
7708 if (pedantic || match == '\'') {
7709 error_with_line (line_for_error (start_line),
7710 "unterminated string or character constant");
7716 /* If not traditional, then allow newlines inside strings. */
7719 if (multiline_string_line == 0)
7720 multiline_string_line = start_line;
7721 } else if (c == match)
7727 /* Place into DST a quoted string representing the string SRC.
7728 Return the address of DST's terminating null. */
7730 quote_string (dst, src)
7737 switch ((c = *src++))
7744 sprintf (dst, "\\%03o", c);
7762 /* Skip across a group of balanced parens, starting from IP->bufp.
7763 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7765 This does not handle newlines, because it's used for the arg of #if,
7766 where there aren't any newlines. Also, backslash-newline can't appear. */
7769 skip_paren_group (ip)
7770 register FILE_BUF *ip;
7772 U_CHAR *limit = ip->buf + ip->length;
7773 U_CHAR *p = ip->bufp;
7775 int lines_dummy = 0;
7777 while (p != limit) {
7787 return ip->bufp = p;
7793 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7801 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7803 return ip->bufp = p;
7814 * write out a #line directive, for instance, after an #include file.
7815 * If CONDITIONAL is nonzero, we can omit the #line if it would
7816 * appear to be a no-op, and we can output a few newlines instead
7817 * if we want to increase the line number by a small amount.
7818 * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7822 output_line_directive (ip, op, conditional, file_change)
7825 enum file_change_code file_change;
7828 char *line_directive_buf, *line_end;
7830 if (no_line_directives
7831 || ip->fname == NULL
7833 op->lineno = ip->lineno;
7838 if (ip->lineno == op->lineno)
7841 /* If the inherited line number is a little too small,
7842 output some newlines instead of a #line directive. */
7843 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7844 check_expand (op, 10);
7845 while (ip->lineno > op->lineno) {
7853 /* Don't output a line number of 0 if we can help it. */
7854 if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7855 && *ip->bufp == '\n') {
7860 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7861 sprintf (line_directive_buf, "# %d ", ip->lineno);
7862 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7864 if (file_change != same_file) {
7866 *line_end++ = file_change == enter_file ? '1' : '2';
7868 /* Tell cc1 if following text comes from a system header file. */
7869 if (ip->system_header_p) {
7873 #ifndef NO_IMPLICIT_EXTERN_C
7874 /* Tell cc1plus if following text should be treated as C. */
7875 if (ip->system_header_p == 2 && cplusplus) {
7881 len = line_end - line_directive_buf;
7882 check_expand (op, len + 1);
7883 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7885 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7887 op->lineno = ip->lineno;
7890 /* This structure represents one parsed argument in a macro call.
7891 `raw' points to the argument text as written (`raw_length' is its length).
7892 `expanded' points to the argument's macro-expansion
7893 (its length is `expand_length').
7894 `stringified_length' is the length the argument would have
7896 `use_count' is the number of times this macro arg is substituted
7897 into the macro. If the actual use count exceeds 10,
7898 the value stored is 10.
7899 `free1' and `free2', if nonzero, point to blocks to be freed
7900 when the macro argument data is no longer needed. */
7903 U_CHAR *raw, *expanded;
7904 int raw_length, expand_length;
7905 int stringified_length;
7906 U_CHAR *free1, *free2;
7911 /* Expand a macro call.
7912 HP points to the symbol that is the macro being called.
7913 Put the result of expansion onto the input stack
7914 so that subsequent input by our caller will use it.
7916 If macro wants arguments, caller has already verified that
7917 an argument list follows; arguments come from the input stack. */
7920 macroexpand (hp, op)
7925 DEFINITION *defn = hp->value.defn;
7926 register U_CHAR *xbuf;
7928 int start_line = instack[indepth].lineno;
7929 int rest_args, rest_zero;
7931 CHECK_DEPTH (return;);
7933 /* it might not actually be a macro. */
7934 if (hp->type != T_MACRO) {
7935 special_symbol (hp, op);
7939 /* This macro is being used inside a #if, which means it must be */
7940 /* recorded as a precondition. */
7941 if (pcp_inside_if && pcp_outfile && defn->predefined)
7942 dump_single_macro (hp, pcp_outfile);
7944 nargs = defn->nargs;
7948 struct argdata *args;
7949 char *parse_error = 0;
7951 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7953 for (i = 0; i < nargs; i++) {
7954 args[i].raw = (U_CHAR *) "";
7955 args[i].expanded = 0;
7956 args[i].raw_length = args[i].expand_length
7957 = args[i].stringified_length = 0;
7958 args[i].free1 = args[i].free2 = 0;
7959 args[i].use_count = 0;
7962 /* Parse all the macro args that are supplied. I counts them.
7963 The first NARGS args are stored in ARGS.
7964 The rest are discarded.
7965 If rest_args is set then we assume macarg absorbed the rest of the args.
7970 /* Discard the open-parenthesis or comma before the next arg. */
7971 ++instack[indepth].bufp;
7974 if (i < nargs || (nargs == 0 && i == 0)) {
7975 /* if we are working on last arg which absorbs rest of args... */
7976 if (i == nargs - 1 && defn->rest_args)
7978 parse_error = macarg (&args[i], rest_args);
7981 parse_error = macarg (NULL_PTR, 0);
7983 error_with_line (line_for_error (start_line), parse_error);
7987 } while (*instack[indepth].bufp != ')');
7989 /* If we got one arg but it was just whitespace, call that 0 args. */
7991 register U_CHAR *bp = args[0].raw;
7992 register U_CHAR *lim = bp + args[0].raw_length;
7993 /* cpp.texi says for foo ( ) we provide one argument.
7994 However, if foo wants just 0 arguments, treat this as 0. */
7996 while (bp != lim && is_space[*bp]) bp++;
8001 /* Don't output an error message if we have already output one for
8002 a parse error above. */
8004 if (nargs == 0 && i > 0) {
8006 error ("arguments given to macro `%s'", hp->name);
8007 } else if (i < nargs) {
8008 /* traditional C allows foo() if foo wants one argument. */
8009 if (nargs == 1 && i == 0 && traditional)
8011 /* the rest args token is allowed to absorb 0 tokens */
8012 else if (i == nargs - 1 && defn->rest_args)
8014 else if (parse_error)
8017 error ("macro `%s' used without args", hp->name);
8019 error ("macro `%s' used with just one arg", hp->name);
8021 error ("macro `%s' used with only %d args", hp->name, i);
8022 } else if (i > nargs) {
8024 error ("macro `%s' used with too many (%d) args", hp->name, i);
8027 /* Swallow the closeparen. */
8028 ++instack[indepth].bufp;
8030 /* If macro wants zero args, we parsed the arglist for checking only.
8031 Read directly from the macro definition. */
8033 xbuf = defn->expansion;
8034 xbuf_len = defn->length;
8036 register U_CHAR *exp = defn->expansion;
8037 register int offset; /* offset in expansion,
8038 copied a piece at a time */
8039 register int totlen; /* total amount of exp buffer filled so far */
8041 register struct reflist *ap, *last_ap;
8043 /* Macro really takes args. Compute the expansion of this call. */
8045 /* Compute length in characters of the macro's expansion.
8046 Also count number of times each arg is used. */
8047 xbuf_len = defn->length;
8048 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8050 xbuf_len += args[ap->argno].stringified_length;
8051 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8052 /* Add 4 for two newline-space markers to prevent
8053 token concatenation. */
8054 xbuf_len += args[ap->argno].raw_length + 4;
8056 /* We have an ordinary (expanded) occurrence of the arg.
8057 So compute its expansion, if we have not already. */
8058 if (args[ap->argno].expanded == 0) {
8060 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8061 args[ap->argno].raw + args[ap->argno].raw_length,
8064 args[ap->argno].expanded = obuf.buf;
8065 args[ap->argno].expand_length = obuf.length;
8066 args[ap->argno].free2 = obuf.buf;
8069 /* Add 4 for two newline-space markers to prevent
8070 token concatenation. */
8071 xbuf_len += args[ap->argno].expand_length + 4;
8073 if (args[ap->argno].use_count < 10)
8074 args[ap->argno].use_count++;
8077 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8079 /* Generate in XBUF the complete expansion
8080 with arguments substituted in.
8081 TOTLEN is the total size generated so far.
8082 OFFSET is the index in the definition
8083 of where we are copying from. */
8084 offset = totlen = 0;
8085 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8086 last_ap = ap, ap = ap->next) {
8087 register struct argdata *arg = &args[ap->argno];
8088 int count_before = totlen;
8090 /* Add chars to XBUF. */
8091 for (i = 0; i < ap->nchars; i++, offset++)
8092 xbuf[totlen++] = exp[offset];
8094 /* If followed by an empty rest arg with concatenation,
8095 delete the last run of nonwhite chars. */
8096 if (rest_zero && totlen > count_before
8097 && ((ap->rest_args && ap->raw_before != 0)
8098 || (last_ap != NULL && last_ap->rest_args
8099 && last_ap->raw_after != 0))) {
8100 /* Delete final whitespace. */
8101 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8105 /* Delete the nonwhites before them. */
8106 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8111 if (ap->stringify != 0) {
8112 int arglen = arg->raw_length;
8118 && (c = arg->raw[i], is_space[c]))
8121 && (c = arg->raw[arglen - 1], is_space[c]))
8124 xbuf[totlen++] = '\"'; /* insert beginning quote */
8125 for (; i < arglen; i++) {
8128 /* Special markers Newline Space
8129 generate nothing for a stringified argument. */
8130 if (c == '\n' && arg->raw[i+1] != '\n') {
8135 /* Internal sequences of whitespace are replaced by one space
8136 except within an string or char token. */
8138 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8140 /* Note that Newline Space does occur within whitespace
8141 sequences; consider it part of the sequence. */
8142 if (c == '\n' && is_space[arg->raw[i+1]])
8144 else if (c != '\n' && is_space[c])
8161 } else if (c == '\"' || c == '\'')
8165 /* Escape these chars */
8166 if (c == '\"' || (in_string && c == '\\'))
8167 xbuf[totlen++] = '\\';
8171 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8176 xbuf[totlen++] = '\"'; /* insert ending quote */
8177 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8178 U_CHAR *p1 = arg->raw;
8179 U_CHAR *l1 = p1 + arg->raw_length;
8180 if (ap->raw_before != 0) {
8181 while (p1 != l1 && is_space[*p1]) p1++;
8182 while (p1 != l1 && is_idchar[*p1])
8183 xbuf[totlen++] = *p1++;
8184 /* Delete any no-reexpansion marker that follows
8185 an identifier at the beginning of the argument
8186 if the argument is concatenated with what precedes it. */
8187 if (p1[0] == '\n' && p1[1] == '-')
8189 } else if (!traditional) {
8190 /* Ordinary expanded use of the argument.
8191 Put in newline-space markers to prevent token pasting. */
8192 xbuf[totlen++] = '\n';
8193 xbuf[totlen++] = ' ';
8195 if (ap->raw_after != 0) {
8196 /* Arg is concatenated after: delete trailing whitespace,
8197 whitespace markers, and no-reexpansion markers. */
8199 if (is_space[l1[-1]]) l1--;
8200 else if (l1[-1] == '-') {
8201 U_CHAR *p2 = l1 - 1;
8202 /* If a `-' is preceded by an odd number of newlines then it
8203 and the last newline are a no-reexpansion marker. */
8204 while (p2 != p1 && p2[-1] == '\n') p2--;
8205 if ((l1 - 1 - p2) & 1) {
8214 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8216 if (!traditional && ap->raw_after == 0) {
8217 /* Ordinary expanded use of the argument.
8218 Put in newline-space markers to prevent token pasting. */
8219 xbuf[totlen++] = '\n';
8220 xbuf[totlen++] = ' ';
8223 /* Ordinary expanded use of the argument.
8224 Put in newline-space markers to prevent token pasting. */
8226 xbuf[totlen++] = '\n';
8227 xbuf[totlen++] = ' ';
8229 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8230 arg->expand_length);
8231 totlen += arg->expand_length;
8233 xbuf[totlen++] = '\n';
8234 xbuf[totlen++] = ' ';
8236 /* If a macro argument with newlines is used multiple times,
8237 then only expand the newlines once. This avoids creating output
8238 lines which don't correspond to any input line, which confuses
8240 if (arg->use_count > 1 && arg->newlines > 0) {
8241 /* Don't bother doing change_newlines for subsequent
8245 = change_newlines (arg->expanded, arg->expand_length);
8249 if (totlen > xbuf_len)
8253 /* if there is anything left of the definition
8254 after handling the arg list, copy that in too. */
8256 for (i = offset; i < defn->length; i++) {
8257 /* if we've reached the end of the macro */
8260 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8261 && last_ap->raw_after != 0))
8262 xbuf[totlen++] = exp[i];
8268 for (i = 0; i < nargs; i++) {
8269 if (args[i].free1 != 0)
8270 free (args[i].free1);
8271 if (args[i].free2 != 0)
8272 free (args[i].free2);
8276 xbuf = defn->expansion;
8277 xbuf_len = defn->length;
8280 /* Now put the expansion on the input stack
8281 so our caller will commence reading from it. */
8283 register FILE_BUF *ip2;
8285 ip2 = &instack[++indepth];
8288 ip2->nominal_fname = 0;
8290 /* This may not be exactly correct, but will give much better error
8291 messages for nested macro calls than using a line number of zero. */
8292 ip2->lineno = start_line;
8294 ip2->length = xbuf_len;
8296 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8298 ip2->if_stack = if_stack;
8299 ip2->system_header_p = 0;
8301 /* Recursive macro use sometimes works traditionally.
8302 #define foo(x,y) bar (x (y,0), y)
8306 hp->type = T_DISABLED;
8311 * Parse a macro argument and store the info on it into *ARGPTR.
8312 * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8313 * Return nonzero to indicate a syntax error.
8317 macarg (argptr, rest_args)
8318 register struct argdata *argptr;
8321 FILE_BUF *ip = &instack[indepth];
8327 /* Try to parse as much of the argument as exists at this
8328 input stack level. */
8329 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8330 &paren, &newlines, &comments, rest_args);
8332 /* If we find the end of the argument at this level,
8333 set up *ARGPTR to point at it in the input stack. */
8334 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8335 && bp != ip->buf + ip->length) {
8337 argptr->raw = ip->bufp;
8338 argptr->raw_length = bp - ip->bufp;
8339 argptr->newlines = newlines;
8343 /* This input stack level ends before the macro argument does.
8344 We must pop levels and keep parsing.
8345 Therefore, we must allocate a temporary buffer and copy
8346 the macro argument into it. */
8347 int bufsize = bp - ip->bufp;
8348 int extra = newlines;
8349 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8350 int final_start = 0;
8352 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8354 ip->lineno += newlines;
8356 while (bp == ip->buf + ip->length) {
8357 if (instack[indepth].macro == 0) {
8358 result = "unterminated macro call";
8361 ip->macro->type = T_MACRO;
8363 free (ip->free_ptr);
8364 ip = &instack[--indepth];
8367 bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8368 &newlines, &comments, rest_args);
8369 final_start = bufsize;
8370 bufsize += bp - ip->bufp;
8372 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8373 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8376 ip->lineno += newlines;
8379 /* Now, if arg is actually wanted, record its raw form,
8380 discarding comments and duplicating newlines in whatever
8381 part of it did not come from a macro expansion.
8382 EXTRA space has been preallocated for duplicating the newlines.
8383 FINAL_START is the index of the start of that part. */
8385 argptr->raw = buffer;
8386 argptr->raw_length = bufsize;
8387 argptr->free1 = buffer;
8388 argptr->newlines = newlines;
8389 if ((newlines || comments) && ip->fname != 0)
8392 discard_comments (argptr->raw + final_start,
8393 argptr->raw_length - final_start,
8395 argptr->raw[argptr->raw_length] = 0;
8396 if (argptr->raw_length > bufsize + extra)
8401 /* If we are not discarding this argument,
8402 macroexpand it and compute its length as stringified.
8403 All this info goes into *ARGPTR. */
8406 register U_CHAR *buf, *lim;
8407 register int totlen;
8410 lim = buf + argptr->raw_length;
8412 while (buf != lim && is_space[*buf])
8414 while (buf != lim && is_space[lim[-1]])
8416 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8417 while (buf != lim) {
8418 register U_CHAR c = *buf++;
8420 /* Internal sequences of whitespace are replaced by one space
8421 in most cases, but not always. So count all the whitespace
8422 in case we need to keep it all. */
8425 SKIP_ALL_WHITE_SPACE (buf);
8428 if (c == '\"' || c == '\\') /* escape these chars */
8430 else if (!isprint (c))
8433 argptr->stringified_length = totlen;
8438 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8439 counting parens in *DEPTHPTR,
8440 and return if reach LIMIT
8441 or before a `)' that would make *DEPTHPTR negative
8442 or before a comma when *DEPTHPTR is zero.
8443 Single and double quotes are matched and termination
8444 is inhibited within them. Comments also inhibit it.
8445 Value returned is pointer to stopping place.
8447 Increment *NEWLINES each time a newline is passed.
8448 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8449 Set *COMMENTS to 1 if a comment is seen. */
8452 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8454 register U_CHAR *limit;
8455 int *depthptr, *newlines, *comments;
8458 register U_CHAR *bp = start;
8460 while (bp < limit) {
8466 if (--(*depthptr) < 0)
8470 /* Traditionally, backslash makes following char not special. */
8471 if (bp + 1 < limit && traditional)
8474 /* But count source lines anyway. */
8483 if (bp[1] == '\\' && bp[2] == '\n')
8484 newline_fix (bp + 1);
8487 for (bp += 2; bp < limit; bp++) {
8490 else if (*bp == '*') {
8491 if (bp[-1] == '/' && warn_comments)
8492 warning ("`/*' within comment");
8493 if (bp[1] == '\\' && bp[2] == '\n')
8494 newline_fix (bp + 1);
8499 } else if (bp[1] == '/' && cplusplus_comments) {
8501 for (bp += 2; bp < limit; bp++) {
8507 warning ("multiline `//' comment");
8516 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8521 while (*bp == '\\' && bp[1] == '\n') {
8524 } else if (*bp == '\n') {
8533 /* if we've returned to lowest level and we aren't absorbing all args */
8534 if ((*depthptr) == 0 && rest_args == 0)
8544 /* Discard comments and duplicate newlines
8545 in the string of length LENGTH at START,
8546 except inside of string constants.
8547 The string is copied into itself with its beginning staying fixed.
8549 NEWLINES is the number of newlines that must be duplicated.
8550 We assume that that much extra space is available past the end
8554 discard_comments (start, length, newlines)
8559 register U_CHAR *ibp;
8560 register U_CHAR *obp;
8561 register U_CHAR *limit;
8564 /* If we have newlines to duplicate, copy everything
8565 that many characters up. Then, in the second part,
8566 we will have room to insert the newlines
8568 NEWLINES may actually be too large, because it counts
8569 newlines in string constants, and we don't duplicate those.
8570 But that does no harm. */
8572 ibp = start + length;
8573 obp = ibp + newlines;
8575 while (limit != ibp)
8579 ibp = start + newlines;
8580 limit = start + length + newlines;
8583 while (ibp < limit) {
8584 *obp++ = c = *ibp++;
8587 /* Duplicate the newline. */
8599 if (*ibp == '\\' && ibp[1] == '\n')
8601 /* Delete any comment. */
8602 if (cplusplus_comments && ibp[0] == '/') {
8603 /* Comments are equivalent to spaces. */
8606 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8610 if (ibp[0] != '*' || ibp + 1 >= limit)
8612 /* Comments are equivalent to spaces.
8613 For -traditional, a comment is equivalent to nothing. */
8619 while (ibp + 1 < limit) {
8621 && ibp[1] == '\\' && ibp[2] == '\n')
8622 newline_fix (ibp + 1);
8623 if (ibp[0] == '*' && ibp[1] == '/')
8632 /* Notice and skip strings, so that we don't
8633 think that comments start inside them,
8634 and so we don't duplicate newlines in them. */
8637 while (ibp < limit) {
8638 *obp++ = c = *ibp++;
8641 if (c == '\n' && quotec == '\'')
8643 if (c == '\\' && ibp < limit) {
8644 while (*ibp == '\\' && ibp[1] == '\n')
8657 /* Turn newlines to spaces in the string of length LENGTH at START,
8658 except inside of string constants.
8659 The string is copied into itself with its beginning staying fixed. */
8662 change_newlines (start, length)
8666 register U_CHAR *ibp;
8667 register U_CHAR *obp;
8668 register U_CHAR *limit;
8672 limit = start + length;
8675 while (ibp < limit) {
8676 *obp++ = c = *ibp++;
8679 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8680 string. Skip past the newline and its duplicate.
8681 Put a space in the output. */
8692 /* Notice and skip strings, so that we don't delete newlines in them. */
8695 while (ibp < limit) {
8696 *obp++ = c = *ibp++;
8699 if (c == '\n' && quotec == '\'')
8711 * my_strerror - return the descriptive text associated with an `errno' code.
8715 my_strerror (errnum)
8721 #ifndef HAVE_STRERROR
8722 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8724 result = strerror (errnum);
8727 /* VAXCRTL's strerror() takes an optional second argument, which only
8728 matters when the first argument is EVMSERR. However, it's simplest
8729 just to pass it unconditionally. `vaxc$errno' is declared in
8730 <errno.h>, and maintained by the library in parallel with `errno'.
8731 We assume that caller's `errnum' either matches the last setting of
8732 `errno' by the library or else does not have the value `EVMSERR'. */
8734 result = strerror (errnum, vaxc$errno);
8738 result = "undocumented I/O error";
8744 * error - print error message and increment count of errors.
8748 error (PRINTF_ALIST (msg))
8753 VA_START (args, msg);
8764 FILE_BUF *ip = NULL;
8766 print_containing_files ();
8768 for (i = indepth; i >= 0; i--)
8769 if (instack[i].fname != NULL) {
8775 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8776 vfprintf (stderr, msg, args);
8777 fprintf (stderr, "\n");
8781 /* Error including a message from `errno'. */
8784 error_from_errno (name)
8788 FILE_BUF *ip = NULL;
8790 print_containing_files ();
8792 for (i = indepth; i >= 0; i--)
8793 if (instack[i].fname != NULL) {
8799 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8801 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8806 /* Print error message but don't count it. */
8809 warning (PRINTF_ALIST (msg))
8814 VA_START (args, msg);
8815 vwarning (msg, args);
8820 vwarning (msg, args)
8825 FILE_BUF *ip = NULL;
8827 if (inhibit_warnings)
8830 if (warnings_are_errors)
8833 print_containing_files ();
8835 for (i = indepth; i >= 0; i--)
8836 if (instack[i].fname != NULL) {
8842 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8843 fprintf (stderr, "warning: ");
8844 vfprintf (stderr, msg, args);
8845 fprintf (stderr, "\n");
8849 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8850 error_with_line (int line, PRINTF_ALIST (msg))
8852 error_with_line (line, PRINTF_ALIST (msg))
8859 VA_START (args, msg);
8860 verror_with_line (line, msg, args);
8865 verror_with_line (line, msg, args)
8871 FILE_BUF *ip = NULL;
8873 print_containing_files ();
8875 for (i = indepth; i >= 0; i--)
8876 if (instack[i].fname != NULL) {
8882 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8883 vfprintf (stderr, msg, args);
8884 fprintf (stderr, "\n");
8889 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8890 warning_with_line (int line, PRINTF_ALIST (msg))
8892 warning_with_line (line, PRINTF_ALIST (msg))
8899 VA_START (args, msg);
8900 vwarning_with_line (line, msg, args);
8905 vwarning_with_line (line, msg, args)
8911 FILE_BUF *ip = NULL;
8913 if (inhibit_warnings)
8916 if (warnings_are_errors)
8919 print_containing_files ();
8921 for (i = indepth; i >= 0; i--)
8922 if (instack[i].fname != NULL) {
8928 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8929 fprintf (stderr, "warning: ");
8930 vfprintf (stderr, msg, args);
8931 fprintf (stderr, "\n");
8934 /* print an error message and maybe count it. */
8937 pedwarn (PRINTF_ALIST (msg))
8942 VA_START (args, msg);
8943 if (pedantic_errors)
8946 vwarning (msg, args);
8951 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8952 pedwarn_with_line (int line, PRINTF_ALIST (msg))
8954 pedwarn_with_line (line, PRINTF_ALIST (msg))
8961 VA_START (args, msg);
8962 if (pedantic_errors)
8963 verror_with_line (line, msg, args);
8965 vwarning_with_line (line, msg, args);
8969 /* Report a warning (or an error if pedantic_errors)
8970 giving specified file name and line number, not current. */
8973 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8974 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
8976 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
8984 if (!pedantic_errors && inhibit_warnings)
8987 fprintf (stderr, "%s:%d: ", file, line);
8988 if (pedantic_errors)
8990 if (!pedantic_errors)
8991 fprintf (stderr, "warning: ");
8992 VA_START (args, msg);
8993 vfprintf (stderr, msg, args);
8995 fprintf (stderr, "\n");
8998 /* Print the file names and line numbers of the #include
8999 directives which led to the current file. */
9002 print_containing_files ()
9004 FILE_BUF *ip = NULL;
9008 /* If stack of files hasn't changed since we last printed
9009 this info, don't repeat it. */
9010 if (last_error_tick == input_file_stack_tick)
9013 for (i = indepth; i >= 0; i--)
9014 if (instack[i].fname != NULL) {
9019 /* Give up if we don't find a source file. */
9023 /* Find the other, outer source files. */
9024 for (i--; i >= 0; i--)
9025 if (instack[i].fname != NULL) {
9029 fprintf (stderr, "In file included");
9031 fprintf (stderr, ",\n ");
9034 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9037 fprintf (stderr, ":\n");
9039 /* Record we have printed the status as of this time. */
9040 last_error_tick = input_file_stack_tick;
9043 /* Return the line at which an error occurred.
9044 The error is not necessarily associated with the current spot
9045 in the input stack, so LINE says where. LINE will have been
9046 copied from ip->lineno for the current input level.
9047 If the current level is for a file, we return LINE.
9048 But if the current level is not for a file, LINE is meaningless.
9049 In that case, we return the lineno of the innermost file. */
9052 line_for_error (line)
9058 for (i = indepth; i >= 0; ) {
9059 if (instack[i].fname != 0)
9064 line1 = instack[i].lineno;
9072 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9074 * As things stand, nothing is ever placed in the output buffer to be
9075 * removed again except when it's KNOWN to be part of an identifier,
9076 * so flushing and moving down everything left, instead of expanding,
9080 /* You might think void was cleaner for the return type,
9081 but that would get type mismatch in check_expand in strict ANSI. */
9083 grow_outbuf (obuf, needed)
9084 register FILE_BUF *obuf;
9085 register int needed;
9090 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9093 /* Make it at least twice as big as it is now. */
9095 /* Make it have at least 150% of the free space we will need. */
9096 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9097 if (minsize > obuf->length)
9098 obuf->length = minsize;
9100 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9103 obuf->bufp = p + (obuf->bufp - obuf->buf);
9109 /* Symbol table for macro names and special symbols */
9112 * install a name in the main hash table, even if it is already there.
9113 * name stops with first non alphanumeric, except leading '#'.
9114 * caller must check against redefinition if that is desired.
9115 * delete_macro () removes things installed by install () in fifo order.
9116 * this is important because of the `defined' special symbol used
9117 * in #if, and also if pushdef/popdef directives are ever implemented.
9119 * If LEN is >= 0, it is the length of the name.
9120 * Otherwise, compute the length by scanning the entire name.
9122 * If HASH is >= 0, it is the precomputed hash code.
9123 * Otherwise, compute the hash code.
9126 install (name, len, type, value, hash)
9129 enum node_type type;
9133 register HASHNODE *hp;
9134 register int i, bucket;
9135 register U_CHAR *p, *q;
9139 while (is_idchar[*p])
9145 hash = hashf (name, len, HASHSIZE);
9147 i = sizeof (HASHNODE) + len + 1;
9148 hp = (HASHNODE *) xmalloc (i);
9150 hp->bucket_hdr = &hashtab[bucket];
9151 hp->next = hashtab[bucket];
9152 hashtab[bucket] = hp;
9154 if (hp->next != NULL)
9155 hp->next->prev = hp;
9158 hp->value.cpval = value;
9159 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9162 for (i = 0; i < len; i++)
9169 * find the most recent hash node for name name (ending with first
9170 * non-identifier char) installed by install
9172 * If LEN is >= 0, it is the length of the name.
9173 * Otherwise, compute the length by scanning the entire name.
9175 * If HASH is >= 0, it is the precomputed hash code.
9176 * Otherwise, compute the hash code.
9179 lookup (name, len, hash)
9184 register U_CHAR *bp;
9185 register HASHNODE *bucket;
9188 for (bp = name; is_idchar[*bp]; bp++) ;
9193 hash = hashf (name, len, HASHSIZE);
9195 bucket = hashtab[hash];
9197 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9199 bucket = bucket->next;
9205 * Delete a hash node. Some weirdness to free junk from macros.
9206 * More such weirdness will have to be added if you define more hash
9207 * types that need it.
9210 /* Note that the DEFINITION of a macro is removed from the hash table
9211 but its storage is not freed. This would be a storage leak
9212 except that it is not reasonable to keep undefining and redefining
9213 large numbers of macros many times.
9214 In any case, this is necessary, because a macro can be #undef'd
9215 in the middle of reading the arguments to a call to it.
9216 If #undef freed the DEFINITION, that would crash. */
9223 if (hp->prev != NULL)
9224 hp->prev->next = hp->next;
9225 if (hp->next != NULL)
9226 hp->next->prev = hp->prev;
9228 /* make sure that the bucket chain header that
9229 the deleted guy was on points to the right thing afterwards. */
9230 if (hp == *hp->bucket_hdr)
9231 *hp->bucket_hdr = hp->next;
9234 if (hp->type == T_MACRO) {
9235 DEFINITION *d = hp->value.defn;
9236 struct reflist *ap, *nextap;
9238 for (ap = d->pattern; ap != NULL; ap = nextap) {
9249 * return hash function on name. must be compatible with the one
9250 * computed a step at a time, elsewhere
9253 hashf (name, len, hashsize)
9254 register U_CHAR *name;
9261 r = HASHSTEP (r, *name++);
9263 return MAKE_POS (r) % hashsize;
9267 /* Dump the definition of a single macro HP to OF. */
9269 dump_single_macro (hp, of)
9270 register HASHNODE *hp;
9273 register DEFINITION *defn = hp->value.defn;
9279 /* Print the definition of the macro HP. */
9281 fprintf (of, "#define %s", hp->name);
9283 if (defn->nargs >= 0) {
9287 for (i = 0; i < defn->nargs; i++) {
9288 dump_arg_n (defn, i, of);
9289 if (i + 1 < defn->nargs)
9299 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9300 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9301 offset += ap->nchars;
9303 if (ap->nchars != 0)
9305 if (ap->stringify) {
9306 switch (ap->stringify) {
9307 case SHARP_TOKEN: fprintf (of, "#"); break;
9308 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9309 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9310 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9314 if (ap->raw_before != 0) {
9316 switch (ap->raw_before) {
9317 case WHITE_SHARP_TOKEN:
9318 case WHITE_PERCENT_COLON_TOKEN:
9325 switch (ap->raw_before) {
9326 case SHARP_TOKEN: fprintf (of, "##"); break;
9327 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9328 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9329 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9336 dump_arg_n (defn, ap->argno, of);
9337 if (!traditional && ap->raw_after != 0) {
9338 switch (ap->raw_after) {
9339 case SHARP_TOKEN: fprintf (of, "##"); break;
9340 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9341 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9342 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9348 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9352 /* Dump all macro definitions as #defines to stdout. */
9359 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9360 register HASHNODE *hp;
9362 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9363 if (hp->type == T_MACRO)
9364 dump_single_macro (hp, stdout);
9369 /* Output to OF a substring of a macro definition.
9370 BASE is the beginning of the definition.
9371 Output characters START thru LENGTH.
9372 Unless traditional, discard newlines outside of strings, thus
9373 converting funny-space markers to ordinary spaces. */
9376 dump_defn_1 (base, start, length, of)
9382 U_CHAR *p = base + start;
9383 U_CHAR *limit = base + start + length;
9386 fwrite (p, sizeof (*p), length, of);
9389 if (*p == '\"' || *p =='\'') {
9390 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9391 NULL_PTR, NULL_PTR);
9392 fwrite (p, sizeof (*p), p1 - p, of);
9403 /* Print the name of argument number ARGNUM of macro definition DEFN
9405 Recall that DEFN->args.argnames contains all the arg names
9406 concatenated in reverse order with comma-space in between. */
9409 dump_arg_n (defn, argnum, of)
9414 register U_CHAR *p = defn->args.argnames;
9415 while (argnum + 1 < defn->nargs) {
9416 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9420 while (*p && *p != ',') {
9426 /* Initialize syntactic classifications of characters. */
9429 initialize_char_syntax ()
9434 * Set up is_idchar and is_idstart tables. These should be
9435 * faster than saying (is_alpha (c) || c == '_'), etc.
9436 * Set up these things before calling any routines tthat
9439 for (i = 'a'; i <= 'z'; i++) {
9440 is_idchar[i - 'a' + 'A'] = 1;
9442 is_idstart[i - 'a' + 'A'] = 1;
9445 for (i = '0'; i <= '9'; i++)
9448 is_idstart['_'] = 1;
9449 is_idchar['$'] = dollars_in_ident;
9450 is_idstart['$'] = dollars_in_ident;
9452 /* horizontal space table */
9453 is_hor_space[' '] = 1;
9454 is_hor_space['\t'] = 1;
9455 is_hor_space['\v'] = 1;
9456 is_hor_space['\f'] = 1;
9457 is_hor_space['\r'] = 1;
9466 char_name['\v'] = "vertical tab";
9467 char_name['\f'] = "formfeed";
9468 char_name['\r'] = "carriage return";
9471 /* Initialize the built-in macros. */
9474 initialize_builtins (inp, outp)
9478 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9479 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9480 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9481 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9482 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9483 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9484 #ifndef NO_BUILTIN_SIZE_TYPE
9485 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9487 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9488 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9490 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9491 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9493 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9495 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9497 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9499 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9500 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9503 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9504 /* This is supplied using a -D by the compiler driver
9505 so that it is present only when truly compiling with GNU C. */
9506 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9510 char directive[2048];
9511 U_CHAR *udirective = (U_CHAR *) directive;
9512 register struct directive *dp = &directive_table[0];
9513 struct tm *timebuf = timestamp ();
9515 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9516 instack[0].nominal_fname);
9517 output_line_directive (inp, outp, 0, same_file);
9518 pass_thru_directive (udirective, &udirective[strlen (directive)],
9521 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9522 output_line_directive (inp, outp, 0, same_file);
9523 pass_thru_directive (udirective, &udirective[strlen (directive)],
9526 #ifndef NO_BUILTIN_SIZE_TYPE
9527 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9528 output_line_directive (inp, outp, 0, same_file);
9529 pass_thru_directive (udirective, &udirective[strlen (directive)],
9533 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9534 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9535 output_line_directive (inp, outp, 0, same_file);
9536 pass_thru_directive (udirective, &udirective[strlen (directive)],
9540 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9541 output_line_directive (inp, outp, 0, same_file);
9542 pass_thru_directive (udirective, &udirective[strlen (directive)],
9545 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9546 monthnames[timebuf->tm_mon],
9547 timebuf->tm_mday, timebuf->tm_year + 1900);
9548 output_line_directive (inp, outp, 0, same_file);
9549 pass_thru_directive (udirective, &udirective[strlen (directive)],
9552 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9553 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9554 output_line_directive (inp, outp, 0, same_file);
9555 pass_thru_directive (udirective, &udirective[strlen (directive)],
9560 sprintf (directive, " __STDC__ 1");
9561 output_line_directive (inp, outp, 0, same_file);
9562 pass_thru_directive (udirective, &udirective[strlen (directive)],
9567 sprintf (directive, " __OBJC__ 1");
9568 output_line_directive (inp, outp, 0, same_file);
9569 pass_thru_directive (udirective, &udirective[strlen (directive)],
9576 * process a given definition string, for initialization
9577 * If STR is just an identifier, define it with value 1.
9578 * If STR has anything after the identifier, then it should
9579 * be identifier=definition.
9583 make_definition (str, op)
9588 struct directive *kt;
9591 p = buf = (U_CHAR *) str;
9592 if (!is_idstart[*p]) {
9593 error ("malformed option `-D %s'", str);
9596 while (is_idchar[*++p])
9599 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9602 p = (U_CHAR *) str; /* Error */
9605 buf = (U_CHAR *) alloca (p - buf + 4);
9606 strcpy ((char *)buf, str);
9607 strcat ((char *)buf, " 1");
9608 } else if (*p != '=') {
9609 error ("malformed option `-D %s'", str);
9613 /* Copy the entire option so we can modify it. */
9614 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9615 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9616 /* Change the = to a space. */
9617 buf[p - (U_CHAR *) str] = ' ';
9618 /* Scan for any backslash-newline and remove it. */
9620 q = &buf[p - (U_CHAR *) str];
9622 if (*p == '\"' || *p == '\'') {
9623 int unterminated = 0;
9624 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9625 NULL_PTR, NULL_PTR, &unterminated);
9629 if (*p == '\\' && p[1] == '\n')
9633 } else if (*p == '\\' && p[1] == '\n')
9635 /* Change newline chars into newline-markers. */
9636 else if (*p == '\n')
9648 ip = &instack[++indepth];
9649 ip->nominal_fname = ip->fname = "*Initialization*";
9651 ip->buf = ip->bufp = buf;
9652 ip->length = strlen ((char *) buf);
9656 ip->if_stack = if_stack;
9657 ip->system_header_p = 0;
9659 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9662 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9663 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9667 /* JF, this does the work for the -U option */
9670 make_undef (str, op)
9675 struct directive *kt;
9677 ip = &instack[++indepth];
9678 ip->nominal_fname = ip->fname = "*undef*";
9680 ip->buf = ip->bufp = (U_CHAR *) str;
9681 ip->length = strlen (str);
9685 ip->if_stack = if_stack;
9686 ip->system_header_p = 0;
9688 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9691 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9695 /* Process the string STR as if it appeared as the body of a #assert.
9696 OPTION is the option name for which STR was the argument. */
9699 make_assertion (option, str)
9704 struct directive *kt;
9705 U_CHAR *buf, *p, *q;
9707 /* Copy the entire option so we can modify it. */
9708 buf = (U_CHAR *) alloca (strlen (str) + 1);
9709 strcpy ((char *) buf, str);
9710 /* Scan for any backslash-newline and remove it. */
9713 if (*p == '\\' && p[1] == '\n')
9721 if (!is_idstart[*p]) {
9722 error ("malformed option `%s %s'", option, str);
9725 while (is_idchar[*++p])
9727 SKIP_WHITE_SPACE (p);
9728 if (! (*p == 0 || *p == '(')) {
9729 error ("malformed option `%s %s'", option, str);
9733 ip = &instack[++indepth];
9734 ip->nominal_fname = ip->fname = "*Initialization*";
9736 ip->buf = ip->bufp = buf;
9737 ip->length = strlen ((char *) buf);
9741 ip->if_stack = if_stack;
9742 ip->system_header_p = 0;
9744 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9747 /* pass NULL as output ptr to do_define since we KNOW it never
9748 does any output.... */
9749 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9753 /* The previous include prefix, if any, is PREV_FILE_NAME.
9754 Allocate a new include prefix whose name is the
9755 simplified concatenation of PREFIX and NAME,
9756 with a trailing / added if needed.
9757 But return 0 if the include prefix should be ignored,
9758 e.g. because it is a duplicate of PREV_FILE_NAME. */
9760 static struct file_name_list *
9761 new_include_prefix (prev_file_name, prefix, name)
9762 struct file_name_list *prev_file_name;
9767 fatal ("Directory name missing after command line option");
9770 /* Ignore the empty string. */
9773 struct file_name_list *dir
9774 = ((struct file_name_list *)
9775 xmalloc (sizeof (struct file_name_list)
9776 + strlen (prefix) + strlen (name) + 1 /* for trailing / */));
9778 strcpy (dir->fname, prefix);
9779 strcat (dir->fname, name);
9780 len = simplify_filename (dir->fname);
9782 /* Convert directory name to a prefix. */
9783 if (dir->fname[len - 1] != '/') {
9784 if (len == 1 && dir->fname[len - 1] == '.')
9787 dir->fname[len++] = '/';
9788 dir->fname[len] = 0;
9791 /* Ignore a directory whose name matches the previous one. */
9792 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9793 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9794 if (!first_bracket_include)
9795 first_bracket_include = prev_file_name;
9801 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9803 /* Ignore a nonexistent directory. */
9804 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9805 if (errno != ENOENT)
9806 error_from_errno (dir->fname);
9811 /* Ignore a directory whose identity matches the previous one. */
9813 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9814 && prev_file_name->st.st_dev == dir->st.st_dev) {
9815 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9816 if (!first_bracket_include)
9817 first_bracket_include = prev_file_name;
9824 dir->c_system_include_path = 0;
9825 dir->got_name_map = 0;
9831 /* Append a chain of `struct file_name_list's
9832 to the end of the main include chain.
9833 FIRST is the beginning of the chain to append, and LAST is the end. */
9836 append_include_chain (first, last)
9837 struct file_name_list *first, *last;
9839 struct file_name_list *dir;
9841 if (!first || !last)
9847 last_include->next = first;
9849 if (first_bracket_include == 0)
9850 first_bracket_include = first;
9852 for (dir = first; ; dir = dir->next) {
9853 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9854 if (len > max_include_len)
9855 max_include_len = len;
9861 last_include = last;
9864 /* Add output to `deps_buffer' for the -M switch.
9865 STRING points to the text to be output.
9866 SPACER is ':' for targets, ' ' for dependencies. */
9869 deps_output (string, spacer)
9873 int size = strlen (string);
9878 #ifndef MAX_OUTPUT_COLUMNS
9879 #define MAX_OUTPUT_COLUMNS 72
9881 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9882 && 1 < deps_column) {
9883 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9890 if (deps_size + size + 8 > deps_allocated_size) {
9891 deps_allocated_size = (deps_size + size + 50) * 2;
9892 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9894 if (spacer == ' ') {
9895 deps_buffer[deps_size++] = ' ';
9898 bcopy (string, &deps_buffer[deps_size], size);
9900 deps_column += size;
9901 if (spacer == ':') {
9902 deps_buffer[deps_size++] = ':';
9905 deps_buffer[deps_size] = 0;
9909 fatal (PRINTF_ALIST (msg))
9914 fprintf (stderr, "%s: ", progname);
9915 VA_START (args, msg);
9916 vfprintf (stderr, msg, args);
9918 fprintf (stderr, "\n");
9919 exit (FATAL_EXIT_CODE);
9922 /* More 'friendly' abort that prints the line and file.
9923 config.h can #define abort fancy_abort if you like that sort of thing. */
9928 fatal ("Internal gcc abort.");
9932 perror_with_name (name)
9935 fprintf (stderr, "%s: ", progname);
9936 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9941 pfatal_with_name (name)
9944 perror_with_name (name);
9948 exit (FATAL_EXIT_CODE);
9952 /* Handler for SIGPIPE. */
9956 /* If this is missing, some compilers complain. */
9959 fatal ("output pipe has been closed");
9965 fatal ("Memory exhausted.");
9973 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
9980 xrealloc (old, size)
9984 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
9991 xcalloc (number, size)
9992 size_t number, size;
9994 register size_t total = number * size;
9995 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10006 size_t size = strlen (input);
10007 char *output = xmalloc (size + 1);
10008 strcpy (output, input);
10014 /* Under VMS we need to fix up the "include" specification
10015 filename so that everything following the 1st slash is
10016 changed into its correct VMS file specification. */
10019 hack_vms_include_specification (fname)
10022 register char *cp, *cp1, *cp2;
10023 int f, check_filename_before_returning;
10026 check_filename_before_returning = 0;
10028 cp = base_name (fname);
10031 * Check if we have a vax-c style '#include filename'
10032 * and add the missing .h
10034 if (!index (cp,'.'))
10037 cp2 = Local; /* initialize */
10039 /* We are trying to do a number of things here. First of all, we are
10040 trying to hammer the filenames into a standard format, such that later
10041 processing can handle them.
10043 If the file name contains something like [dir.], then it recognizes this
10044 as a root, and strips the ".]". Later processing will add whatever is
10045 needed to get things working properly.
10047 If no device is specified, then the first directory name is taken to be
10048 a device name (or a rooted logical). */
10050 /* See if we found that 1st slash */
10051 if (cp == 0) return; /* Nothing to do!!! */
10052 if (*cp != '/') return; /* Nothing to do!!! */
10053 /* Point to the UNIX filename part (which needs to be fixed!) */
10055 /* If the directory spec is not rooted, we can just copy
10056 the UNIX filename part and we are done */
10057 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10058 if (cp[-2] != '.') {
10060 * The VMS part ends in a `]', and the preceding character is not a `.'.
10061 * We strip the `]', and then splice the two parts of the name in the
10062 * usual way. Given the default locations for include files in cccp.c,
10063 * we will only use this code if the user specifies alternate locations
10064 * with the /include (-I) switch on the command line. */
10065 cp -= 1; /* Strip "]" */
10066 cp1--; /* backspace */
10069 * The VMS part has a ".]" at the end, and this will not do. Later
10070 * processing will add a second directory spec, and this would be a syntax
10071 * error. Thus we strip the ".]", and thus merge the directory specs.
10072 * We also backspace cp1, so that it points to a '/'. This inhibits the
10073 * generation of the 000000 root directory spec (which does not belong here
10076 cp -= 2; /* Strip ".]" */
10077 cp1--; }; /* backspace */
10080 /* We drop in here if there is no VMS style directory specification yet.
10081 * If there is no device specification either, we make the first dir a
10082 * device and try that. If we do not do this, then we will be essentially
10083 * searching the users default directory (as if they did a #include "asdf.h").
10085 * Then all we need to do is to push a '[' into the output string. Later
10086 * processing will fill this in, and close the bracket.
10088 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10089 *cp2++ = '['; /* Open the directory specification */
10092 /* at this point we assume that we have the device spec, and (at least
10093 the opening "[" for a directory specification. We may have directories
10094 specified already */
10096 /* If there are no other slashes then the filename will be
10097 in the "root" directory. Otherwise, we need to add
10098 directory specifications. */
10099 if (index (cp1, '/') == 0) {
10100 /* Just add "000000]" as the directory string */
10101 strcpy (cp2, "000000]");
10102 cp2 += strlen (cp2);
10103 check_filename_before_returning = 1; /* we might need to fool with this later */
10105 /* As long as there are still subdirectories to add, do them. */
10106 while (index (cp1, '/') != 0) {
10107 /* If this token is "." we can ignore it */
10108 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10112 /* Add a subdirectory spec. Do not duplicate "." */
10113 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10115 /* If this is ".." then the spec becomes "-" */
10116 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10117 /* Add "-" and skip the ".." */
10122 /* Copy the subdirectory */
10123 while (*cp1 != '/') *cp2++= *cp1++;
10124 cp1++; /* Skip the "/" */
10126 /* Close the directory specification */
10127 if (cp2[-1] == '.') /* no trailing periods */
10131 /* Now add the filename */
10132 while (*cp1) *cp2++ = *cp1++;
10134 /* Now append it to the original VMS spec. */
10135 strcpy (cp, Local);
10137 /* If we put a [000000] in the filename, try to open it first. If this fails,
10138 remove the [000000], and return that name. This provides flexibility
10139 to the user in that they can use both rooted and non-rooted logical names
10140 to point to the location of the file. */
10142 if (check_filename_before_returning) {
10143 f = open (fname, O_RDONLY, 0666);
10145 /* The file name is OK as it is, so return it as is. */
10149 /* The filename did not work. Try to remove the [000000] from the name,
10151 cp = index (fname, '[');
10152 cp2 = index (fname, ']') + 1;
10153 strcpy (cp, cp2); /* this gets rid of it */
10161 /* These are the read/write replacement routines for
10162 VAX-11 "C". They make read/write behave enough
10163 like their UNIX counterparts that CCCP will work */
10166 read (fd, buf, size)
10171 #undef read /* Get back the REAL read routine */
10173 register int total = 0;
10175 /* Read until the buffer is exhausted */
10177 /* Limit each read to 32KB */
10178 i = (size > (32*1024)) ? (32*1024) : size;
10179 i = read (fd, buf, i);
10181 if (i == 0) return (total);
10184 /* Account for this read */
10193 write (fd, buf, size)
10198 #undef write /* Get back the REAL write routine */
10202 /* Limit individual writes to 32Kb */
10205 j = (i > (32*1024)) ? (32*1024) : i;
10206 if (write (fd, buf, j) < 0) return (-1);
10207 /* Account for the data written */
10214 /* The following wrapper functions supply additional arguments to the VMS
10215 I/O routines to optimize performance with file handling. The arguments
10217 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10218 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10219 "fop=tef"- Truncate unused portions of file when closing file.
10220 "shr=nil"- Disallow file sharing while file is open.
10224 freopen (fname, type, oldfile)
10229 #undef freopen /* Get back the REAL fopen routine */
10230 if (strcmp (type, "w") == 0)
10231 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10232 return freopen (fname, type, oldfile, "mbc=16");
10236 fopen (fname, type)
10240 #undef fopen /* Get back the REAL fopen routine */
10241 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10242 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10243 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10244 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10247 return (*vmslib_fopen) (fname, type, "mbc=32",
10248 "deq=64", "fop=tef", "shr=nil");
10250 return (*vmslib_fopen) (fname, type, "mbc=32");
10254 open (fname, flags, prot)
10259 #undef open /* Get back the REAL open routine */
10260 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10263 /* more VMS hackery */
10267 extern unsigned long sys$parse(), sys$search();
10269 /* Work around another library bug. If a file is located via a searchlist,
10270 and if the device it's on is not the same device as the one specified
10271 in the first element of that searchlist, then both stat() and fstat()
10272 will fail to return info about it. `errno' will be set to EVMSERR, and
10273 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10274 We can get around this by fully parsing the filename and then passing
10275 that absolute name to stat().
10277 Without this fix, we can end up failing to find header files, which is
10278 bad enough, but then compounding the problem by reporting the reason for
10279 failure as "normal successful completion." */
10281 #undef fstat /* get back to library version */
10284 VMS_fstat (fd, statbuf)
10286 struct stat *statbuf;
10288 int result = fstat (fd, statbuf);
10293 char nambuf[NAM$C_MAXRSS+1];
10295 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10296 result = VMS_stat (nambuf, statbuf);
10297 /* No fclose(fp) here; that would close(fd) as well. */
10304 VMS_stat (name, statbuf)
10306 struct stat *statbuf;
10308 int result = stat (name, statbuf);
10314 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10315 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10318 fab.fab$l_fna = (char *) name;
10319 fab.fab$b_fns = (unsigned char) strlen (name);
10320 fab.fab$l_nam = (void *) &nam;
10322 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10323 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10324 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10325 if (sys$parse (&fab) & 1)
10327 if (sys$search (&fab) & 1)
10329 res_nam[nam.nam$b_rsl] = '\0';
10330 result = stat (res_nam, statbuf);
10332 /* Clean up searchlist context cached by the system. */
10333 nam.nam$b_nop = NAM$M_SYNCHK;
10334 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10335 (void) sys$parse (&fab);