1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-96, 1997 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"
49 /* By default, colon separates directories in a path. */
50 #ifndef PATH_SEPARATOR
51 #define PATH_SEPARATOR ':'
54 #include <sys/types.h>
60 /* The following symbols should be autoconfigured:
67 In the mean time, we'll get by with approximations based
68 on existing GCC configuration symbols. */
71 # ifndef HAVE_STDLIB_H
72 # define HAVE_STDLIB_H 1
74 # ifndef HAVE_UNISTD_H
75 # define HAVE_UNISTD_H 1
78 # define STDC_HEADERS 1
80 #endif /* defined (POSIX) */
82 #if defined (POSIX) || (defined (USG) && !defined (VMS))
84 # define HAVE_FCNTL_H 1
91 # if TIME_WITH_SYS_TIME
92 # include <sys/time.h>
96 # include <sys/time.h>
101 # include <sys/resource.h>
119 # define bcmp(a, b, n) memcmp (a, b, n)
122 # define bcopy(s, d, n) memcpy (d, s, n)
125 # define bzero(d, n) memset (d, 0, n)
127 #else /* !STDC_HEADERS */
131 # if !defined (BSTRING) && (defined (USG) || defined (VMS))
134 # define bcmp my_bcmp
147 # endif /* !defined (bcmp) */
150 # define bcopy my_bcopy
160 # endif /* !defined (bcopy) */
163 # define bzero my_bzero
167 register unsigned length;
172 # endif /* !defined (bzero) */
174 # endif /* !defined (BSTRING) && (defined (USG) || defined (VMS)) */
175 #endif /* ! STDC_HEADERS */
177 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
178 # define __attribute__(x)
182 # if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
183 # define PROTO(ARGS) ARGS
185 # define PROTO(ARGS) ()
189 #if defined (__STDC__) && defined (HAVE_VPRINTF)
191 # define VA_START(va_list, var) va_start (va_list, var)
192 # define PRINTF_ALIST(msg) char *msg, ...
193 # define PRINTF_DCL(msg)
194 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (__printf__, m, n)))
196 # include <varargs.h>
197 # define VA_START(va_list, var) va_start (va_list)
198 # define PRINTF_ALIST(msg) msg, va_alist
199 # define PRINTF_DCL(msg) char *msg; va_dcl
200 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (__printf__, m, n)))
201 # define vfprintf(file, msg, args) \
203 char *a0 = va_arg(args, char *); \
204 char *a1 = va_arg(args, char *); \
205 char *a2 = va_arg(args, char *); \
206 char *a3 = va_arg(args, char *); \
207 fprintf (file, msg, a0, a1, a2, a3); \
211 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
212 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
213 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
219 /* VMS-specific definitions */
222 #define read(fd,buf,size) VMS_read (fd,buf,size)
223 #define write(fd,buf,size) VMS_write (fd,buf,size)
224 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
225 #define fopen(fname,mode) VMS_fopen (fname,mode)
226 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
227 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
228 static int VMS_fstat (), VMS_stat ();
229 static int VMS_read ();
230 static int VMS_write ();
231 static int VMS_open ();
232 static FILE * VMS_fopen ();
233 static FILE * VMS_freopen ();
234 static void hack_vms_include_specification ();
235 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
236 #define INO_T_HASH(a) 0
237 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
246 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
247 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
249 /* Find the largest host integer type and set its size and type.
250 Don't blindly use `long'; on some crazy hosts it is shorter than `int'. */
252 #ifndef HOST_BITS_PER_WIDE_INT
254 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
255 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
256 #define HOST_WIDE_INT long
258 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
259 #define HOST_WIDE_INT int
265 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
269 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
273 #define INO_T_EQ(a, b) ((a) == (b))
277 #define INO_T_HASH(a) (a)
280 /* Define a generic NULL if one hasn't already been defined. */
287 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
288 #define GENERIC_PTR void *
290 #define GENERIC_PTR char *
295 #define NULL_PTR ((GENERIC_PTR) 0)
298 #ifndef INCLUDE_LEN_FUDGE
299 #define INCLUDE_LEN_FUDGE 0
302 /* External declarations. */
304 extern char *version_string;
306 #ifndef HAVE_STRERROR
309 extern const char *const sys_errlist[];
311 extern char *sys_errlist[];
313 #else /* HAVE_STRERROR */
317 char *strerror (int,...);
319 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
320 HOST_WIDE_INT parse_c_expression PROTO((char *));
326 /* Name under which this program was invoked. */
328 static char *progname;
330 /* Nonzero means use extra default include directories for C++. */
332 static int cplusplus;
334 /* Nonzero means handle cplusplus style comments */
336 static int cplusplus_comments;
338 /* Nonzero means handle #import, for objective C. */
342 /* Nonzero means this is an assembly file, and allow
343 unknown directives, which could be comments. */
347 /* Current maximum length of directory names in the search path
348 for include files. (Altered as we get more of them.) */
350 static int max_include_len;
352 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
354 static int for_lint = 0;
356 /* Nonzero means copy comments into the output file. */
358 static int put_out_comments = 0;
360 /* Nonzero means don't process the ANSI trigraph sequences. */
362 static int no_trigraphs = 0;
364 /* Nonzero means print the names of included files rather than
365 the preprocessed output. 1 means just the #include "...",
366 2 means #include <...> as well. */
368 static int print_deps = 0;
370 /* Nonzero if missing .h files in -M output are assumed to be generated
371 files and not errors. */
373 static int print_deps_missing_files = 0;
375 /* Nonzero means print names of header files (-H). */
377 static int print_include_names = 0;
379 /* Nonzero means don't output line number information. */
381 static int no_line_directives;
383 /* Nonzero means output the text in failing conditionals,
384 inside #failed ... #endfailed. */
386 static int output_conditionals;
388 /* dump_only means inhibit output of the preprocessed text
389 and instead output the definitions of all user-defined
390 macros in a form suitable for use as input to cccp.
391 dump_names means pass #define and the macro name through to output.
392 dump_definitions means pass the whole definition (plus #define) through
395 static enum {dump_none, dump_only, dump_names, dump_definitions}
396 dump_macros = dump_none;
398 /* Nonzero means pass all #define and #undef directives which we actually
399 process through to the output stream. This feature is used primarily
400 to allow cc1 to record the #defines and #undefs for the sake of
401 debuggers which understand about preprocessor macros, but it may
402 also be useful with -E to figure out how symbols are defined, and
403 where they are defined. */
404 static int debug_output = 0;
406 /* Nonzero indicates special processing used by the pcp program. The
407 special effects of this mode are:
409 Inhibit all macro expansion, except those inside #if directives.
411 Process #define directives normally, and output their contents
414 Output preconditions to pcp_outfile indicating all the relevant
415 preconditions for use of this file in a later cpp run.
417 static FILE *pcp_outfile;
419 /* Nonzero means we are inside an IF during a -pcp run. In this mode
420 macro expansion is done, and preconditions are output for all macro
421 uses requiring them. */
422 static int pcp_inside_if;
424 /* Nonzero means never to include precompiled files.
425 This is 1 since there's no way now to make precompiled files,
426 so it's not worth testing for them. */
427 static int no_precomp = 1;
429 /* Nonzero means give all the error messages the ANSI standard requires. */
433 /* Nonzero means try to make failure to fit ANSI C an error. */
435 static int pedantic_errors;
437 /* Nonzero means don't print warning messages. -w. */
439 static int inhibit_warnings = 0;
441 /* Nonzero means warn if slash-star appears in a slash-star comment,
442 or if newline-backslash appears in a slash-slash comment. */
444 static int warn_comments;
446 /* Nonzero means warn if a macro argument is (or would be)
447 stringified with -traditional. */
449 static int warn_stringify;
451 /* Nonzero means warn if there are any trigraphs. */
453 static int warn_trigraphs;
455 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
459 /* Nonzero means warn if #import is used. */
461 static int warn_import = 1;
463 /* Nonzero means turn warnings into errors. */
465 static int warnings_are_errors;
467 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
471 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
475 /* Nonzero causes output not to be done,
476 but directives such as #define that have side effects
479 static int no_output;
481 /* Nonzero means this file was included with a -imacros or -include
482 command line and should not be recorded as an include file. */
484 static int no_record_file;
486 /* Nonzero means that we have finished processing the command line options.
487 This flag is used to decide whether or not to issue certain errors
490 static int done_initializing = 0;
492 /* Line where a newline was first seen in a string constant. */
494 static int multiline_string_line = 0;
496 /* I/O buffer structure.
497 The `fname' field is nonzero for source files and #include files
498 and for the dummy text used for -D and -U.
499 It is zero for rescanning results of macro expansion
500 and for expanding macro arguments. */
501 #define INPUT_STACK_MAX 400
502 static struct file_buf {
504 /* Filename specified with #line directive. */
506 /* Include file description. */
507 struct include_file *inc;
508 /* Record where in the search path this file was found.
509 For #include_next. */
510 struct file_name_list *dir;
515 /* Macro that this level is the expansion of.
516 Included so that we can reenable the macro
517 at the end of this level. */
518 struct hashnode *macro;
519 /* Value of if_stack at start of this file.
520 Used to prohibit unmatched #endif (etc) in an include file. */
521 struct if_stack *if_stack;
522 /* Object to be freed at end of input at this level. */
524 /* True if this is a header file included using <FILENAME>. */
525 char system_header_p;
526 } instack[INPUT_STACK_MAX];
528 static int last_error_tick; /* Incremented each time we print it. */
529 static int input_file_stack_tick; /* Incremented when the status changes. */
531 /* Current nesting level of input sources.
532 `instack[indepth]' is the level currently being read. */
533 static int indepth = -1;
534 #define CHECK_DEPTH(code) \
535 if (indepth >= (INPUT_STACK_MAX - 1)) \
537 error_with_line (line_for_error (instack[indepth].lineno), \
538 "macro or `#include' recursion too deep"); \
542 /* Current depth in #include directives that use <...>. */
543 static int system_include_depth = 0;
545 typedef struct file_buf FILE_BUF;
547 /* The output buffer. Its LENGTH field is the amount of room allocated
548 for the buffer, not the number of chars actually present. To get
549 that, subtract outbuf.buf from outbuf.bufp. */
551 #define OUTBUF_SIZE 10 /* initial size of output buffer */
552 static FILE_BUF outbuf;
554 /* Grow output buffer OBUF points at
555 so it can hold at least NEEDED more chars. */
557 #define check_expand(OBUF, NEEDED) \
558 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
559 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
561 struct file_name_list
563 struct file_name_list *next;
564 /* If the following is 1, it is a C-language system include
566 int c_system_include_path;
567 /* Mapping of file names for this directory. */
568 struct file_name_map *name_map;
569 /* Non-zero if name_map is valid. */
571 /* The include directory status. */
573 /* The include prefix: "" denotes the working directory,
574 otherwise fname must end in '/'.
575 The actual size is dynamically allocated. */
579 /* #include "file" looks in source file dir, then stack. */
580 /* #include <file> just looks in the stack. */
581 /* -I directories are added to the end, then the defaults are added. */
583 static struct default_include {
584 char *fname; /* The name of the directory. */
585 int cplusplus; /* Only look here if we're compiling C++. */
586 int cxx_aware; /* Includes in this directory don't need to
587 be wrapped in extern "C" when compiling
589 } include_defaults_array[]
590 #ifdef INCLUDE_DEFAULTS
594 /* Pick up GNU C++ specific include files. */
595 { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
596 { OLD_GPLUSPLUS_INCLUDE_DIR, 1, 1 },
598 /* This is the dir for fixincludes. Put it just before
599 the files that we fix. */
600 { GCC_INCLUDE_DIR, 0, 0 },
601 /* For cross-compilation, this dir name is generated
602 automatically in Makefile.in. */
603 { CROSS_INCLUDE_DIR, 0, 0 },
604 #ifdef TOOL_INCLUDE_DIR
605 /* This is another place that the target system's headers might be. */
606 { TOOL_INCLUDE_DIR, 0, 0 },
608 #else /* not CROSS_COMPILE */
609 #ifdef LOCAL_INCLUDE_DIR
610 /* This should be /usr/local/include and should come before
611 the fixincludes-fixed header files. */
612 { LOCAL_INCLUDE_DIR, 0, 1 },
614 #ifdef TOOL_INCLUDE_DIR
615 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
616 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
617 { TOOL_INCLUDE_DIR, 0, 0 },
619 /* This is the dir for fixincludes. Put it just before
620 the files that we fix. */
621 { GCC_INCLUDE_DIR, 0, 0 },
622 /* Some systems have an extra dir of include files. */
623 #ifdef SYSTEM_INCLUDE_DIR
624 { SYSTEM_INCLUDE_DIR, 0, 0 },
626 { STANDARD_INCLUDE_DIR, 0, 0 },
627 #endif /* not CROSS_COMPILE */
630 #endif /* no INCLUDE_DEFAULTS */
632 /* The code looks at the defaults through this pointer, rather than through
633 the constant structure above. This pointer gets changed if an environment
634 variable specifies other defaults. */
635 static struct default_include *include_defaults = include_defaults_array;
637 static struct file_name_list *include = 0; /* First dir to search */
638 /* First dir to search for <file> */
639 /* This is the first element to use for #include <...>.
640 If it is 0, use the entire chain for such includes. */
641 static struct file_name_list *first_bracket_include = 0;
642 /* This is the first element in the chain that corresponds to
643 a directory of system header files. */
644 static struct file_name_list *first_system_include = 0;
645 static struct file_name_list *last_include = 0; /* Last in chain */
647 /* Chain of include directories to put at the end of the other chain. */
648 static struct file_name_list *after_include = 0;
649 static struct file_name_list *last_after_include = 0; /* Last in chain */
651 /* Chain to put at the start of the system include files. */
652 static struct file_name_list *before_system = 0;
653 static struct file_name_list *last_before_system = 0; /* Last in chain */
655 /* Directory prefix that should replace `/usr' in the standard
656 include file directories. */
657 static char *include_prefix;
659 /* Maintain and search list of included files. */
661 struct include_file {
662 struct include_file *next; /* for include_hashtab */
663 struct include_file *next_ino; /* for include_ino_hashtab */
665 /* If the following is the empty string, it means #pragma once
666 was seen in this include file, or #import was applied to the file.
667 Otherwise, if it is nonzero, it is a macro name.
668 Don't include the file again if that macro is defined. */
669 U_CHAR *control_macro;
670 /* Nonzero if the dependency on this include file has been output. */
675 /* Hash tables of files already included with #include or #import.
676 include_hashtab is by full name; include_ino_hashtab is by inode number. */
678 #define INCLUDE_HASHSIZE 61
679 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
680 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
682 /* Global list of strings read in from precompiled files. This list
683 is kept in the order the strings are read in, with new strings being
684 added at the end through stringlist_tailp. We use this list to output
685 the strings at the end of the run.
687 static STRINGDEF *stringlist;
688 static STRINGDEF **stringlist_tailp = &stringlist;
691 /* Structure returned by create_definition */
692 typedef struct macrodef MACRODEF;
695 struct definition *defn;
700 enum sharp_token_type {
701 NO_SHARP_TOKEN = 0, /* token not present */
703 SHARP_TOKEN = '#', /* token spelled with # only */
704 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
706 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
707 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
710 /* Structure allocated for every #define. For a simple replacement
713 nargs = -1, the `pattern' list is null, and the expansion is just
714 the replacement text. Nargs = 0 means a functionlike macro with no args,
716 #define getchar() getc (stdin) .
717 When there are args, the expansion is the replacement text with the
718 args squashed out, and the reflist is a list describing how to
719 build the output from the input: e.g., "3 chars, then the 1st arg,
720 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
721 The chars here come from the expansion. Whatever is left of the
722 expansion after the last arg-occurrence is copied after that arg.
723 Note that the reflist can be arbitrarily long---
724 its length depends on the number of times the arguments appear in
725 the replacement text, not how many args there are. Example:
726 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
728 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
729 where (x, y) means (nchars, argno). */
731 typedef struct definition DEFINITION;
734 int length; /* length of expansion string */
735 int predefined; /* True if the macro was builtin or */
736 /* came from the command line */
738 int line; /* Line number of definition */
739 char *file; /* File of definition */
740 char rest_args; /* Nonzero if last arg. absorbs the rest */
742 struct reflist *next;
744 enum sharp_token_type stringify; /* set if a # operator before arg */
745 enum sharp_token_type raw_before; /* set if a ## operator before arg */
746 enum sharp_token_type raw_after; /* set if a ## operator after arg */
748 char rest_args; /* Nonzero if this arg. absorbs the rest */
749 int nchars; /* Number of literal chars to copy before
750 this arg occurrence. */
751 int argno; /* Number of arg to substitute (origin-0) */
754 /* Names of macro args, concatenated in reverse order
755 with comma-space between them.
756 The only use of this is that we warn on redefinition
757 if this differs between the old and new definitions. */
762 /* different kinds of things that can appear in the value field
763 of a hash node. Actually, this may be useless now. */
771 * special extension string that can be added to the last macro argument to
772 * allow it to absorb the "rest" of the arguments when expanded. Ex:
773 * #define wow(a, b...) process (b, a, b)
774 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
775 * { wow (one, two); } -> { process (two, one, two); }
776 * if this "rest_arg" is used with the concat token '##' and if it is not
777 * supplied then the token attached to with ## will not be outputted. Ex:
778 * #define wow (a, b...) process (b ## , a, ## b)
779 * { wow (1, 2); } -> { process (2, 1, 2); }
780 * { wow (one); } -> { process (one); {
782 static char rest_extension[] = "...";
783 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
785 /* The structure of a node in the hash table. The hash table
786 has entries for all tokens defined by #define directives (type T_MACRO),
787 plus some special tokens like __LINE__ (these each have their own
788 type, and the appropriate code is run when that type of node is seen.
789 It does not contain control words like "#define", which are recognized
790 by a separate piece of code. */
792 /* different flavors of hash nodes --- also used in keyword table */
794 T_DEFINE = 1, /* the `#define' keyword */
795 T_INCLUDE, /* the `#include' keyword */
796 T_INCLUDE_NEXT, /* the `#include_next' keyword */
797 T_IMPORT, /* the `#import' keyword */
798 T_IFDEF, /* the `#ifdef' keyword */
799 T_IFNDEF, /* the `#ifndef' keyword */
800 T_IF, /* the `#if' keyword */
801 T_ELSE, /* `#else' */
802 T_PRAGMA, /* `#pragma' */
803 T_ELIF, /* `#elif' */
804 T_UNDEF, /* `#undef' */
805 T_LINE, /* `#line' */
806 T_ERROR, /* `#error' */
807 T_WARNING, /* `#warning' */
808 T_ENDIF, /* `#endif' */
809 T_SCCS, /* `#sccs', used on system V. */
810 T_IDENT, /* `#ident', used on system V. */
811 T_ASSERT, /* `#assert', taken from system V. */
812 T_UNASSERT, /* `#unassert', taken from system V. */
813 T_SPECLINE, /* special symbol `__LINE__' */
814 T_DATE, /* `__DATE__' */
815 T_FILE, /* `__FILE__' */
816 T_BASE_FILE, /* `__BASE_FILE__' */
817 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
818 T_VERSION, /* `__VERSION__' */
819 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
820 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
821 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
822 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
823 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
824 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
825 T_TIME, /* `__TIME__' */
826 T_CONST, /* Constant value, used by `__STDC__' */
827 T_MACRO, /* macro defined by `#define' */
828 T_DISABLED, /* macro temporarily turned off for rescan */
829 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
830 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
831 T_UNUSED /* Used for something not defined. */
835 struct hashnode *next; /* double links for easy deletion */
836 struct hashnode *prev;
837 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
838 chain is kept, in case the node is the head
839 of the chain and gets deleted. */
840 enum node_type type; /* type of special token */
841 int length; /* length of token, for quick comparison */
842 U_CHAR *name; /* the actual name */
843 union hashval value; /* pointer to expansion, or whatever */
846 typedef struct hashnode HASHNODE;
848 /* Some definitions for the hash table. The hash function MUST be
849 computed as shown in hashf () below. That is because the rescan
850 loop computes the hash value `on the fly' for most tokens,
851 in order to avoid the overhead of a lot of procedure calls to
852 the hashf () function. Hashf () only exists for the sake of
853 politeness, for use when speed isn't so important. */
855 #define HASHSIZE 1403
856 static HASHNODE *hashtab[HASHSIZE];
857 #define HASHSTEP(old, c) ((old << 2) + c)
858 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
860 /* Symbols to predefine. */
862 #ifdef CPP_PREDEFINES
863 static char *predefs = CPP_PREDEFINES;
865 static char *predefs = "";
868 /* We let tm.h override the types used here, to handle trivial differences
869 such as the choice of unsigned int or long unsigned int for size_t.
870 When machines start needing nontrivial differences in the size type,
871 it would be best to do something here to figure out automatically
872 from other information what type to use. */
874 /* The string value for __SIZE_TYPE__. */
877 #define SIZE_TYPE "long unsigned int"
880 /* The string value for __PTRDIFF_TYPE__. */
883 #define PTRDIFF_TYPE "long int"
886 /* The string value for __WCHAR_TYPE__. */
889 #define WCHAR_TYPE "int"
891 char * wchar_type = WCHAR_TYPE;
894 /* The string value for __USER_LABEL_PREFIX__ */
896 #ifndef USER_LABEL_PREFIX
897 #define USER_LABEL_PREFIX ""
900 /* The string value for __REGISTER_PREFIX__ */
902 #ifndef REGISTER_PREFIX
903 #define REGISTER_PREFIX ""
906 /* The string value for __IMMEDIATE_PREFIX__ */
908 #ifndef IMMEDIATE_PREFIX
909 #define IMMEDIATE_PREFIX ""
912 /* In the definition of a #assert name, this structure forms
913 a list of the individual values asserted.
914 Each value is itself a list of "tokens".
915 These are strings that are compared by name. */
917 struct tokenlist_list {
918 struct tokenlist_list *next;
919 struct arglist *tokens;
922 struct assertion_hashnode {
923 struct assertion_hashnode *next; /* double links for easy deletion */
924 struct assertion_hashnode *prev;
925 /* also, a back pointer to this node's hash
926 chain is kept, in case the node is the head
927 of the chain and gets deleted. */
928 struct assertion_hashnode **bucket_hdr;
929 int length; /* length of token, for quick comparison */
930 U_CHAR *name; /* the actual name */
931 /* List of token-sequences. */
932 struct tokenlist_list *value;
935 typedef struct assertion_hashnode ASSERTION_HASHNODE;
937 /* Some definitions for the hash table. The hash function MUST be
938 computed as shown in hashf below. That is because the rescan
939 loop computes the hash value `on the fly' for most tokens,
940 in order to avoid the overhead of a lot of procedure calls to
941 the hashf function. hashf only exists for the sake of
942 politeness, for use when speed isn't so important. */
944 #define ASSERTION_HASHSIZE 37
945 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
947 /* Nonzero means inhibit macroexpansion of what seem to be
948 assertion tests, in rescan. For #if. */
949 static int assertions_flag;
951 /* `struct directive' defines one #-directive, including how to handle it. */
953 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
956 int length; /* Length of name */
957 int (*func) DO_PROTO; /* Function to handle directive */
958 char *name; /* Name of directive */
959 enum node_type type; /* Code which describes which directive. */
960 char angle_brackets; /* Nonzero => <...> is special. */
961 char traditional_comments; /* Nonzero: keep comments if -traditional. */
962 char pass_thru; /* Copy directive to output:
963 if 1, copy if dumping definitions;
964 if 2, always copy, after preprocessing. */
967 /* These functions are declared to return int instead of void since they
968 are going to be placed in the table and some old compilers have trouble with
969 pointers to functions returning void. */
971 static int do_assert DO_PROTO;
972 static int do_define DO_PROTO;
973 static int do_elif DO_PROTO;
974 static int do_else DO_PROTO;
975 static int do_endif DO_PROTO;
976 static int do_error DO_PROTO;
977 static int do_ident DO_PROTO;
978 static int do_if DO_PROTO;
979 static int do_include DO_PROTO;
980 static int do_line DO_PROTO;
981 static int do_pragma DO_PROTO;
982 #ifdef SCCS_DIRECTIVE
983 static int do_sccs DO_PROTO;
985 static int do_unassert DO_PROTO;
986 static int do_undef DO_PROTO;
987 static int do_warning DO_PROTO;
988 static int do_xifdef DO_PROTO;
990 /* Here is the actual list of #-directives, most-often-used first. */
992 static struct directive directive_table[] = {
993 { 6, do_define, "define", T_DEFINE, 0, 1, 1},
994 { 2, do_if, "if", T_IF},
995 { 5, do_xifdef, "ifdef", T_IFDEF},
996 { 6, do_xifdef, "ifndef", T_IFNDEF},
997 { 5, do_endif, "endif", T_ENDIF},
998 { 4, do_else, "else", T_ELSE},
999 { 4, do_elif, "elif", T_ELIF},
1000 { 4, do_line, "line", T_LINE},
1001 { 7, do_include, "include", T_INCLUDE, 1},
1002 { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
1003 { 6, do_include, "import", T_IMPORT, 1},
1004 { 5, do_undef, "undef", T_UNDEF},
1005 { 5, do_error, "error", T_ERROR},
1006 { 7, do_warning, "warning", T_WARNING},
1007 #ifdef SCCS_DIRECTIVE
1008 { 4, do_sccs, "sccs", T_SCCS},
1010 { 6, do_pragma, "pragma", T_PRAGMA, 0, 0, 2},
1011 { 5, do_ident, "ident", T_IDENT},
1012 { 6, do_assert, "assert", T_ASSERT},
1013 { 8, do_unassert, "unassert", T_UNASSERT},
1014 { -1, 0, "", T_UNUSED},
1017 /* When a directive handler is called,
1018 this points to the # (or the : of the %:) that started the directive. */
1019 U_CHAR *directive_start;
1021 /* table to tell if char can be part of a C identifier. */
1022 U_CHAR is_idchar[256];
1023 /* table to tell if char can be first char of a c identifier. */
1024 U_CHAR is_idstart[256];
1025 /* table to tell if c is horizontal space. */
1026 static U_CHAR is_hor_space[256];
1027 /* table to tell if c is horizontal or vertical space. */
1028 U_CHAR is_space[256];
1029 /* names of some characters */
1030 static char *char_name[256];
1032 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
1033 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
1035 static int errors = 0; /* Error counter for exit code */
1037 /* Name of output file, for error messages. */
1038 static char *out_fname;
1041 /* Stack of conditionals currently in progress
1042 (including both successful and failing conditionals). */
1045 struct if_stack *next; /* for chaining to the next stack frame */
1046 char *fname; /* copied from input when frame is made */
1047 int lineno; /* similarly */
1048 int if_succeeded; /* true if a leg of this if-group
1049 has been passed through rescan */
1050 U_CHAR *control_macro; /* For #ifndef at start of file,
1051 this is the macro name tested. */
1052 enum node_type type; /* type of last directive seen in this group */
1054 typedef struct if_stack IF_STACK_FRAME;
1055 static IF_STACK_FRAME *if_stack = NULL;
1057 /* Buffer of -M output. */
1058 static char *deps_buffer;
1060 /* Number of bytes allocated in above. */
1061 static int deps_allocated_size;
1063 /* Number of bytes used. */
1064 static int deps_size;
1066 /* Number of bytes since the last newline. */
1067 static int deps_column;
1069 /* Nonzero means -I- has been seen,
1070 so don't look for #include "foo" the source-file directory. */
1071 static int ignore_srcdir;
1073 static int safe_read PROTO((int, char *, int));
1074 static void safe_write PROTO((int, char *, int));
1076 int main PROTO((int, char **));
1078 static void path_include PROTO((char *));
1080 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
1082 static void trigraph_pcp PROTO((FILE_BUF *));
1084 static void newline_fix PROTO((U_CHAR *));
1085 static void name_newline_fix PROTO((U_CHAR *));
1087 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
1089 static void rescan PROTO((FILE_BUF *, int));
1091 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
1093 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
1095 static struct tm *timestamp PROTO((void));
1096 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
1098 static int is_system_include PROTO((char *));
1099 static char *base_name PROTO((char *));
1100 static int absolute_filename PROTO((char *));
1101 static size_t simplify_filename PROTO((char *));
1103 static char *read_filename_string PROTO((int, FILE *));
1104 static struct file_name_map *read_name_map PROTO((char *));
1105 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
1106 static char *remap_include_file PROTO((char *, struct file_name_list *));
1107 static int lookup_ino_include PROTO((struct include_file *));
1109 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
1110 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
1112 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
1113 static int check_preconditions PROTO((char *));
1114 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
1115 static void pcstring_used PROTO((HASHNODE *));
1116 static void write_output PROTO((void));
1117 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
1119 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
1121 static int check_macro_name PROTO((U_CHAR *, char *));
1122 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
1123 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
1125 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
1127 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
1128 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
1130 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
1131 static void free_token_list PROTO((struct arglist *));
1133 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
1134 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
1135 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
1137 static void do_once PROTO((void));
1139 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
1140 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
1141 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1142 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1144 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1145 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1146 static char *quote_string PROTO((char *, char *));
1147 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1149 /* Last arg to output_line_directive. */
1150 enum file_change_code {same_file, enter_file, leave_file};
1151 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1153 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1156 static char *macarg PROTO((struct argdata *, int));
1158 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, int *, int *, int *, int));
1160 static int discard_comments PROTO((U_CHAR *, int, int));
1162 static int change_newlines PROTO((U_CHAR *, int));
1164 char *my_strerror PROTO((int));
1165 void error PRINTF_PROTO_1((char *, ...));
1166 static void verror PROTO((char *, va_list));
1167 static void error_from_errno PROTO((char *));
1168 void warning PRINTF_PROTO_1((char *, ...));
1169 static void vwarning PROTO((char *, va_list));
1170 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1171 static void verror_with_line PROTO((int, char *, va_list));
1172 static void vwarning_with_line PROTO((int, char *, va_list));
1173 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1174 void pedwarn PRINTF_PROTO_1((char *, ...));
1175 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1176 static void pedwarn_with_file_and_line PRINTF_PROTO_3((char *, int, char *, ...));
1178 static void print_containing_files PROTO((void));
1180 static int line_for_error PROTO((int));
1181 static int grow_outbuf PROTO((FILE_BUF *, int));
1183 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1184 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1185 static void delete_macro PROTO((HASHNODE *));
1186 static int hashf PROTO((U_CHAR *, int, int));
1188 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1189 static void dump_all_macros PROTO((void));
1190 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1191 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1193 static void initialize_char_syntax PROTO((void));
1194 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1196 static void make_definition PROTO((char *, FILE_BUF *));
1197 static void make_undef PROTO((char *, FILE_BUF *));
1199 static void make_assertion PROTO((char *, char *));
1201 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *));
1202 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1204 static void deps_output PROTO((char *, int));
1206 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1207 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1208 static void perror_with_name PROTO((char *));
1209 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1210 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1212 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1213 GENERIC_PTR xmalloc PROTO((size_t));
1214 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1215 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1216 static char *savestring PROTO((char *));
1218 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1219 retrying if necessary. Return a negative value if an error occurs,
1220 otherwise return the actual number of bytes read,
1221 which must be LEN unless end-of-file was reached. */
1224 safe_read (desc, ptr, len)
1231 int nchars = read (desc, ptr, left);
1248 /* Write LEN bytes at PTR to descriptor DESC,
1249 retrying if necessary, and treating any real error as fatal. */
1252 safe_write (desc, ptr, len)
1258 int written = write (desc, ptr, len);
1265 pfatal_with_name (out_fname);
1282 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1283 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1284 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1285 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1286 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1288 /* Record the option used with each element of pend_assertions.
1289 This is preparation for supporting more than one option for making
1291 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1292 int inhibit_predefs = 0;
1293 int no_standard_includes = 0;
1294 int no_standard_cplusplus_includes = 0;
1295 int missing_newline = 0;
1297 /* Non-0 means don't output the preprocessed program. */
1298 int inhibit_output = 0;
1299 /* Non-0 means -v, so print the full set of include dirs. */
1302 /* File name which deps are being written to.
1303 This is 0 if deps are being written to stdout. */
1304 char *deps_file = 0;
1305 /* Fopen file mode to open deps_file with. */
1306 char *deps_mode = "a";
1307 /* Stream on which to print the dependency information. */
1308 FILE *deps_stream = 0;
1309 /* Target-name to write with the dependency information. */
1310 char *deps_target = 0;
1313 /* Get rid of any avoidable limit on stack size. */
1317 /* Set the stack limit huge so that alloca (particularly stringtab
1318 in dbxread.c) does not fail. */
1319 getrlimit (RLIMIT_STACK, &rlim);
1320 rlim.rlim_cur = rlim.rlim_max;
1321 setrlimit (RLIMIT_STACK, &rlim);
1323 #endif /* RLIMIT_STACK defined */
1326 signal (SIGPIPE, pipe_closed);
1329 progname = base_name (argv[0]);
1333 /* Remove extension from PROGNAME. */
1335 char *s = progname = savestring (progname);
1337 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1338 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1339 && (p[1] == 'e' || p[1] == 'E')
1340 && (p[2] == 'x' || p[2] == 'X')
1341 && (p[3] == 'e' || p[3] == 'E')
1350 /* Initialize is_idchar. */
1351 initialize_char_syntax ();
1353 no_line_directives = 0;
1355 dump_macros = dump_none;
1358 cplusplus_comments = 1;
1360 bzero ((char *) pend_files, argc * sizeof (char *));
1361 bzero ((char *) pend_defs, argc * sizeof (char *));
1362 bzero ((char *) pend_undefs, argc * sizeof (char *));
1363 bzero ((char *) pend_assertions, argc * sizeof (char *));
1364 bzero ((char *) pend_includes, argc * sizeof (char *));
1366 /* Process switches and find input file name. */
1368 for (i = 1; i < argc; i++) {
1369 if (argv[i][0] != '-') {
1370 if (out_fname != NULL)
1371 fatal ("Usage: %s [switches] input output", argv[0]);
1372 else if (in_fname != NULL)
1373 out_fname = argv[i];
1377 switch (argv[i][1]) {
1380 if (!strcmp (argv[i], "-include")) {
1382 fatal ("Filename missing after `-include' option");
1384 simplify_filename (pend_includes[i] = argv[++i]);
1386 if (!strcmp (argv[i], "-imacros")) {
1388 fatal ("Filename missing after `-imacros' option");
1390 simplify_filename (pend_files[i] = argv[++i]);
1392 if (!strcmp (argv[i], "-iprefix")) {
1394 fatal ("Filename missing after `-iprefix' option");
1396 include_prefix = argv[++i];
1398 if (!strcmp (argv[i], "-ifoutput")) {
1399 output_conditionals = 1;
1401 if (!strcmp (argv[i], "-isystem")) {
1402 struct file_name_list *dirtmp;
1404 if (! (dirtmp = new_include_prefix (NULL_PTR, "", argv[++i])))
1406 dirtmp->c_system_include_path = 1;
1408 if (before_system == 0)
1409 before_system = dirtmp;
1411 last_before_system->next = dirtmp;
1412 last_before_system = dirtmp; /* Tail follows the last one */
1414 /* Add directory to end of path for includes,
1415 with the default prefix at the front of its name. */
1416 if (!strcmp (argv[i], "-iwithprefix")) {
1417 struct file_name_list *dirtmp;
1420 if (include_prefix != 0)
1421 prefix = include_prefix;
1423 prefix = savestring (GCC_INCLUDE_DIR);
1424 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1425 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1426 prefix[strlen (prefix) - 7] = 0;
1429 if (! (dirtmp = new_include_prefix (NULL_PTR, prefix, argv[++i])))
1432 if (after_include == 0)
1433 after_include = dirtmp;
1435 last_after_include->next = dirtmp;
1436 last_after_include = dirtmp; /* Tail follows the last one */
1438 /* Add directory to main path for includes,
1439 with the default prefix at the front of its name. */
1440 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1441 struct file_name_list *dirtmp;
1444 if (include_prefix != 0)
1445 prefix = include_prefix;
1447 prefix = savestring (GCC_INCLUDE_DIR);
1448 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1449 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1450 prefix[strlen (prefix) - 7] = 0;
1453 dirtmp = new_include_prefix (NULL_PTR, prefix, argv[++i]);
1454 append_include_chain (dirtmp, dirtmp);
1456 /* Add directory to end of path for includes. */
1457 if (!strcmp (argv[i], "-idirafter")) {
1458 struct file_name_list *dirtmp;
1460 if (! (dirtmp = new_include_prefix (NULL_PTR, "", argv[++i])))
1463 if (after_include == 0)
1464 after_include = dirtmp;
1466 last_after_include->next = dirtmp;
1467 last_after_include = dirtmp; /* Tail follows the last one */
1472 if (out_fname != NULL)
1473 fatal ("Output filename specified twice");
1475 fatal ("Filename missing after -o option");
1476 out_fname = argv[++i];
1477 if (!strcmp (out_fname, "-"))
1482 if (!strcmp (argv[i], "-pedantic"))
1484 else if (!strcmp (argv[i], "-pedantic-errors")) {
1486 pedantic_errors = 1;
1487 } else if (!strcmp (argv[i], "-pcp")) {
1490 fatal ("Filename missing after -pcp option");
1491 pcp_fname = argv[++i];
1493 ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1494 ? fopen (pcp_fname, "w")
1496 if (pcp_outfile == 0)
1497 pfatal_with_name (pcp_fname);
1503 if (!strcmp (argv[i], "-traditional")) {
1505 cplusplus_comments = 0;
1506 } else if (!strcmp (argv[i], "-trigraphs")) {
1512 if (! strcmp (argv[i], "-lang-c"))
1513 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1514 if (! strcmp (argv[i], "-lang-c89"))
1515 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1516 if (! strcmp (argv[i], "-lang-c++"))
1517 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1518 if (! strcmp (argv[i], "-lang-objc"))
1519 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1520 if (! strcmp (argv[i], "-lang-objc++"))
1521 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1522 if (! strcmp (argv[i], "-lang-asm"))
1524 if (! strcmp (argv[i], "-lint"))
1529 cplusplus = 1, cplusplus_comments = 1;
1533 inhibit_warnings = 1;
1537 if (!strcmp (argv[i], "-Wtrigraphs"))
1539 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1541 else if (!strcmp (argv[i], "-Wcomment"))
1543 else if (!strcmp (argv[i], "-Wno-comment"))
1545 else if (!strcmp (argv[i], "-Wcomments"))
1547 else if (!strcmp (argv[i], "-Wno-comments"))
1549 else if (!strcmp (argv[i], "-Wtraditional"))
1551 else if (!strcmp (argv[i], "-Wno-traditional"))
1553 else if (!strcmp (argv[i], "-Wundef"))
1555 else if (!strcmp (argv[i], "-Wno-undef"))
1557 else if (!strcmp (argv[i], "-Wimport"))
1559 else if (!strcmp (argv[i], "-Wno-import"))
1561 else if (!strcmp (argv[i], "-Werror"))
1562 warnings_are_errors = 1;
1563 else if (!strcmp (argv[i], "-Wno-error"))
1564 warnings_are_errors = 0;
1565 else if (!strcmp (argv[i], "-Wall"))
1573 /* The style of the choices here is a bit mixed.
1574 The chosen scheme is a hybrid of keeping all options in one string
1575 and specifying each option in a separate argument:
1576 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1577 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1578 -M[M][G][D file]. This is awkward to handle in specs, and is not
1580 /* ??? -MG must be specified in addition to one of -M or -MM.
1581 This can be relaxed in the future without breaking anything.
1582 The converse isn't true. */
1584 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1585 if (!strcmp (argv[i], "-MG"))
1587 print_deps_missing_files = 1;
1590 if (!strcmp (argv[i], "-M"))
1592 else if (!strcmp (argv[i], "-MM"))
1594 else if (!strcmp (argv[i], "-MD"))
1596 else if (!strcmp (argv[i], "-MMD"))
1598 /* For -MD and -MMD options, write deps on file named by next arg. */
1599 if (!strcmp (argv[i], "-MD")
1600 || !strcmp (argv[i], "-MMD")) {
1602 fatal ("Filename missing after %s option", argv[i]);
1604 deps_file = argv[i];
1607 /* For -M and -MM, write deps on standard output
1608 and suppress the usual output. */
1609 deps_stream = stdout;
1616 char *p = argv[i] + 2;
1618 while ((c = *p++)) {
1619 /* Arg to -d specifies what parts of macros to dump */
1622 dump_macros = dump_only;
1626 dump_macros = dump_names;
1629 dump_macros = dump_definitions;
1637 if (argv[i][2] == '3')
1642 fprintf (stderr, "GNU CPP version %s", version_string);
1643 #ifdef TARGET_VERSION
1646 fprintf (stderr, "\n");
1651 print_include_names = 1;
1655 if (argv[i][2] != 0)
1656 pend_defs[i] = argv[i] + 2;
1657 else if (i + 1 == argc)
1658 fatal ("Macro name missing after -D option");
1660 i++, pend_defs[i] = argv[i];
1667 if (argv[i][2] != 0)
1669 else if (i + 1 == argc)
1670 fatal ("Assertion missing after -A option");
1674 if (!strcmp (p, "-")) {
1675 /* -A- eliminates all predefined macros and assertions.
1676 Let's include also any that were specified earlier
1677 on the command line. That way we can get rid of any
1678 that were passed automatically in from GCC. */
1680 inhibit_predefs = 1;
1681 for (j = 0; j < i; j++)
1682 pend_defs[j] = pend_assertions[j] = 0;
1684 pend_assertions[i] = p;
1685 pend_assertion_options[i] = "-A";
1690 case 'U': /* JF #undef something */
1691 if (argv[i][2] != 0)
1692 pend_undefs[i] = argv[i] + 2;
1693 else if (i + 1 == argc)
1694 fatal ("Macro name missing after -U option");
1696 pend_undefs[i] = argv[i+1], i++;
1700 put_out_comments = 1;
1703 case 'E': /* -E comes from cc -E; ignore it. */
1707 no_line_directives = 1;
1710 case '$': /* Don't include $ in identifiers. */
1711 is_idchar['$'] = is_idstart['$'] = 0;
1714 case 'I': /* Add directory to path for includes. */
1716 struct file_name_list *dirtmp;
1718 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1720 /* Don't use any preceding -I directories for #include <...>. */
1721 first_bracket_include = 0;
1724 dirtmp = new_include_prefix (last_include, "",
1725 argv[i][2] ? argv[i] + 2 : argv[++i]);
1726 append_include_chain (dirtmp, dirtmp);
1732 if (!strcmp (argv[i], "-nostdinc"))
1733 /* -nostdinc causes no default include directories.
1734 You must specify all include-file directories with -I. */
1735 no_standard_includes = 1;
1736 else if (!strcmp (argv[i], "-nostdinc++"))
1737 /* -nostdinc++ causes no default C++-specific include directories. */
1738 no_standard_cplusplus_includes = 1;
1739 else if (!strcmp (argv[i], "-noprecomp"))
1744 /* Sun compiler passes undocumented switch "-undef".
1745 Let's assume it means to inhibit the predefined symbols. */
1746 inhibit_predefs = 1;
1749 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1750 if (in_fname == NULL) {
1753 } else if (out_fname == NULL) {
1756 } /* else fall through into error */
1759 fatal ("Invalid option `%s'", argv[i]);
1764 /* Add dirs from CPATH after dirs from -I. */
1765 /* There seems to be confusion about what CPATH should do,
1766 so for the moment it is not documented. */
1767 /* Some people say that CPATH should replace the standard include dirs,
1768 but that seems pointless: it comes before them, so it overrides them
1770 cp = getenv ("CPATH");
1771 if (cp && ! no_standard_includes)
1774 /* Initialize output buffer */
1776 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1777 outbuf.bufp = outbuf.buf;
1778 outbuf.length = OUTBUF_SIZE;
1780 /* Do partial setup of input buffer for the sake of generating
1781 early #line directives (when -g is in effect). */
1783 fp = &instack[++indepth];
1784 if (in_fname == NULL)
1786 fp->nominal_fname = fp->fname = in_fname;
1789 /* In C++, wchar_t is a distinct basic type, and we can expect
1790 __wchar_t to be defined by cc1plus. */
1792 wchar_type = "__wchar_t";
1794 /* Install __LINE__, etc. Must follow initialize_char_syntax
1795 and option processing. */
1796 initialize_builtins (fp, &outbuf);
1798 /* Do standard #defines and assertions
1799 that identify system and machine type. */
1801 if (!inhibit_predefs) {
1802 char *p = (char *) alloca (strlen (predefs) + 1);
1803 strcpy (p, predefs);
1806 while (*p == ' ' || *p == '\t')
1808 /* Handle -D options. */
1809 if (p[0] == '-' && p[1] == 'D') {
1811 while (*p && *p != ' ' && *p != '\t')
1816 output_line_directive (fp, &outbuf, 0, same_file);
1817 make_definition (q, &outbuf);
1818 while (*p == ' ' || *p == '\t')
1820 } else if (p[0] == '-' && p[1] == 'A') {
1821 /* Handle -A options (assertions). */
1830 past_name = assertion;
1831 /* Locate end of name. */
1832 while (*past_name && *past_name != ' '
1833 && *past_name != '\t' && *past_name != '(')
1835 /* Locate `(' at start of value. */
1837 while (*value && (*value == ' ' || *value == '\t'))
1839 if (*value++ != '(')
1841 while (*value && (*value == ' ' || *value == '\t'))
1844 /* Locate end of value. */
1845 while (*past_value && *past_value != ' '
1846 && *past_value != '\t' && *past_value != ')')
1848 termination = past_value;
1849 while (*termination && (*termination == ' ' || *termination == '\t'))
1851 if (*termination++ != ')')
1853 if (*termination && *termination != ' ' && *termination != '\t')
1855 /* Temporarily null-terminate the value. */
1856 save_char = *termination;
1857 *termination = '\0';
1858 /* Install the assertion. */
1859 make_assertion ("-A", assertion);
1860 *termination = (char) save_char;
1862 while (*p == ' ' || *p == '\t')
1870 /* Now handle the command line options. */
1872 /* Do -U's, -D's and -A's in the order they were seen. */
1873 for (i = 1; i < argc; i++) {
1874 if (pend_undefs[i]) {
1876 output_line_directive (fp, &outbuf, 0, same_file);
1877 make_undef (pend_undefs[i], &outbuf);
1881 output_line_directive (fp, &outbuf, 0, same_file);
1882 make_definition (pend_defs[i], &outbuf);
1884 if (pend_assertions[i])
1885 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1888 done_initializing = 1;
1890 { /* Read the appropriate environment variable and if it exists
1891 replace include_defaults with the listed path. */
1893 switch ((objc << 1) + cplusplus)
1896 epath = getenv ("C_INCLUDE_PATH");
1899 epath = getenv ("CPLUS_INCLUDE_PATH");
1902 epath = getenv ("OBJC_INCLUDE_PATH");
1905 epath = getenv ("OBJCPLUS_INCLUDE_PATH");
1908 /* If the environment var for this language is set,
1909 add to the default list of include directories. */
1912 char *startp, *endp;
1914 for (num_dirs = 1, startp = epath; *startp; startp++)
1915 if (*startp == PATH_SEPARATOR)
1918 = (struct default_include *) xmalloc ((num_dirs
1919 * sizeof (struct default_include))
1920 + sizeof (include_defaults_array));
1921 startp = endp = epath;
1925 if (c == PATH_SEPARATOR || !c) {
1927 include_defaults[num_dirs].fname
1928 = startp == endp ? "." : savestring (startp);
1930 include_defaults[num_dirs].cplusplus = cplusplus;
1931 include_defaults[num_dirs].cxx_aware = 1;
1938 /* Put the usual defaults back in at the end. */
1939 bcopy ((char *) include_defaults_array,
1940 (char *) &include_defaults[num_dirs],
1941 sizeof (include_defaults_array));
1945 append_include_chain (before_system, last_before_system);
1946 first_system_include = before_system;
1948 /* Unless -fnostdinc,
1949 tack on the standard include file dirs to the specified list */
1950 if (!no_standard_includes) {
1951 struct default_include *p = include_defaults;
1952 char *specd_prefix = include_prefix;
1953 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1954 int default_len = 0;
1955 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1956 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1957 default_len = strlen (default_prefix) - 7;
1958 default_prefix[default_len] = 0;
1960 /* Search "translated" versions of GNU directories.
1961 These have /usr/local/lib/gcc... replaced by specd_prefix. */
1962 if (specd_prefix != 0 && default_len != 0)
1963 for (p = include_defaults; p->fname; p++) {
1964 /* Some standard dirs are only for C++. */
1965 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1966 /* Does this dir start with the prefix? */
1967 if (!strncmp (p->fname, default_prefix, default_len)) {
1968 /* Yes; change prefix and add to search list. */
1969 struct file_name_list *new
1970 = new_include_prefix (NULL_PTR, specd_prefix,
1971 p->fname + default_len);
1973 new->c_system_include_path = !p->cxx_aware;
1974 append_include_chain (new, new);
1975 if (first_system_include == 0)
1976 first_system_include = new;
1981 /* Search ordinary names for GNU include directories. */
1982 for (p = include_defaults; p->fname; p++) {
1983 /* Some standard dirs are only for C++. */
1984 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1985 struct file_name_list *new
1986 = new_include_prefix (NULL_PTR, "", p->fname);
1988 new->c_system_include_path = !p->cxx_aware;
1989 append_include_chain (new, new);
1990 if (first_system_include == 0)
1991 first_system_include = new;
1997 /* Tack the after_include chain at the end of the include chain. */
1998 append_include_chain (after_include, last_after_include);
1999 if (first_system_include == 0)
2000 first_system_include = after_include;
2002 /* With -v, print the list of dirs to search. */
2004 struct file_name_list *p;
2005 fprintf (stderr, "#include \"...\" search starts here:\n");
2006 for (p = include; p; p = p->next) {
2007 if (p == first_bracket_include)
2008 fprintf (stderr, "#include <...> search starts here:\n");
2010 fprintf (stderr, " .\n");
2011 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
2012 fprintf (stderr, " %s\n", p->fname);
2014 /* Omit trailing '/'. */
2015 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
2017 fprintf (stderr, "End of search list.\n");
2020 /* -MG doesn't select the form of output and must be specified with one of
2021 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2022 inhibit compilation. */
2023 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2024 fatal ("-MG must be specified with one of -M or -MM");
2026 /* Either of two environment variables can specify output of deps.
2027 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2028 where OUTPUT_FILE is the file to write deps info to
2029 and DEPS_TARGET is the target to mention in the deps. */
2032 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2033 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2034 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2039 spec = getenv ("SUNPRO_DEPENDENCIES");
2046 /* Find the space before the DEPS_TARGET, if there is one. */
2047 /* This should use index. (mrs) */
2048 while (*s != 0 && *s != ' ') s++;
2050 deps_target = s + 1;
2051 output_file = xmalloc (s - spec + 1);
2052 bcopy (spec, output_file, s - spec);
2053 output_file[s - spec] = 0;
2060 deps_file = output_file;
2064 /* For -M, print the expected object file name
2065 as the target of this Make-rule. */
2067 deps_allocated_size = 200;
2068 deps_buffer = xmalloc (deps_allocated_size);
2074 deps_output (deps_target, ':');
2075 } else if (*in_fname == 0) {
2076 deps_output ("-", ':');
2081 q = base_name (in_fname);
2083 /* Copy remainder to mungable area. */
2084 p = (char *) alloca (strlen(q) + 8);
2087 /* Output P, but remove known suffixes. */
2091 && p[len - 2] == '.'
2092 && index("cCsSm", p[len - 1]))
2095 && p[len - 3] == '.'
2096 && p[len - 2] == 'c'
2097 && p[len - 1] == 'c')
2100 && p[len - 4] == '.'
2101 && p[len - 3] == 'c'
2102 && p[len - 2] == 'x'
2103 && p[len - 1] == 'x')
2106 && p[len - 4] == '.'
2107 && p[len - 3] == 'c'
2108 && p[len - 2] == 'p'
2109 && p[len - 1] == 'p')
2112 /* Supply our own suffix. */
2119 deps_output (p, ':');
2120 deps_output (in_fname, ' ');
2124 /* Scan the -imacros files before the main input.
2125 Much like #including them, but with no_output set
2126 so that only their macro definitions matter. */
2128 no_output++; no_record_file++;
2129 for (i = 1; i < argc; i++)
2130 if (pend_files[i]) {
2131 struct include_file *inc;
2132 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2134 perror_with_name (pend_files[i]);
2135 return FATAL_EXIT_CODE;
2137 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2139 no_output--; no_record_file--;
2141 /* Copy the entire contents of the main input file into
2142 the stacked input buffer previously allocated for it. */
2144 /* JF check for stdin */
2145 if (in_fname == NULL || *in_fname == 0) {
2148 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2151 if (fstat (f, &st) != 0)
2152 pfatal_with_name (in_fname);
2153 fp->nominal_fname = fp->fname = in_fname;
2155 fp->system_header_p = 0;
2156 /* JF all this is mine about reading pipes and ttys */
2157 if (! S_ISREG (st.st_mode)) {
2158 /* Read input from a file that is not a normal disk file.
2159 We cannot preallocate a buffer with the correct size,
2160 so we must read in the file a piece at the time and make it bigger. */
2165 if (S_ISDIR (st.st_mode))
2166 fatal ("Input file `%s' is a directory", in_fname);
2170 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2172 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2173 if (cnt < 0) goto perror; /* error! */
2175 if (size != bsize) break; /* End of file */
2177 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2181 /* Read a file whose size we can determine in advance.
2182 For the sake of VMS, st.st_size is just an upper bound. */
2183 fp->buf = (U_CHAR *) xmalloc (st.st_size + 2);
2184 fp->length = safe_read (f, (char *) fp->buf, st.st_size);
2185 if (fp->length < 0) goto perror;
2188 fp->if_stack = if_stack;
2190 /* Make sure data ends with a newline. And put a null after it. */
2192 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2193 /* Backslash-newline at end is not good enough. */
2194 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2195 fp->buf[fp->length++] = '\n';
2196 missing_newline = 1;
2198 fp->buf[fp->length] = '\0';
2200 /* Unless inhibited, convert trigraphs in the input. */
2205 /* Now that we know the input file is valid, open the output. */
2207 if (!out_fname || !strcmp (out_fname, ""))
2208 out_fname = "stdout";
2209 else if (! freopen (out_fname, "w", stdout))
2210 pfatal_with_name (out_fname);
2212 output_line_directive (fp, &outbuf, 0, same_file);
2214 /* Scan the -include files before the main input. */
2217 for (i = 1; i < argc; i++)
2218 if (pend_includes[i]) {
2219 struct include_file *inc;
2220 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2222 perror_with_name (pend_includes[i]);
2223 return FATAL_EXIT_CODE;
2225 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2229 /* Scan the input, processing macros and directives. */
2231 rescan (&outbuf, 0);
2233 if (missing_newline)
2236 if (pedantic && missing_newline)
2237 pedwarn ("file does not end in newline");
2239 /* Now we have processed the entire input
2240 Write whichever kind of output has been requested. */
2242 if (dump_macros == dump_only)
2244 else if (! inhibit_output) {
2249 /* Don't actually write the deps file if compilation has failed. */
2251 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2252 pfatal_with_name (deps_file);
2253 fputs (deps_buffer, deps_stream);
2254 putc ('\n', deps_stream);
2256 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2257 fatal ("I/O error on output");
2262 if (pcp_outfile && pcp_outfile != stdout
2263 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2264 fatal ("I/O error on `-pcp' output");
2266 if (ferror (stdout) || fclose (stdout) != 0)
2267 fatal ("I/O error on output");
2270 exit (FATAL_EXIT_CODE);
2271 exit (SUCCESS_EXIT_CODE);
2274 pfatal_with_name (in_fname);
2278 /* Given a colon-separated list of file names PATH,
2279 add all the names to the search path for include files. */
2293 struct file_name_list *dirtmp;
2295 /* Find the end of this name. */
2296 while ((c = *q++) != PATH_SEPARATOR && c)
2300 dirtmp = new_include_prefix (last_include, "", p == q ? "." : p);
2302 append_include_chain (dirtmp, dirtmp);
2304 /* Advance past this name. */
2311 /* Return the address of the first character in S that equals C.
2312 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2313 Return 0 if there is no such character. Assume that C itself is not '\0'.
2314 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2315 but unfortunately memchr isn't autoconfigured yet. */
2323 char *p = (char *) s;
2325 char *q = index (p, c);
2327 return (U_CHAR *) q;
2329 size_t l = strlen (p);
2339 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2340 before main CCCP processing. Name `pcp' is also in honor of the
2341 drugs the trigraph designers must have been on.
2343 Using an extra pass through the buffer takes a little extra time,
2344 but is infinitely less hairy than trying to handle trigraphs inside
2345 strings, etc. everywhere, and also makes sure that trigraphs are
2346 only translated in the top level of processing. */
2352 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2355 fptr = bptr = sptr = buf->buf;
2356 lptr = fptr + buf->length;
2357 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2394 len = sptr - fptr - 2;
2396 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2397 C, this will be memmove (). */
2398 if (bptr != fptr && len > 0)
2399 bcopy ((char *) fptr, (char *) bptr, len);
2405 len = buf->length - (fptr - buf->buf);
2406 if (bptr != fptr && len > 0)
2407 bcopy ((char *) fptr, (char *) bptr, len);
2408 buf->length -= fptr - bptr;
2409 buf->buf[buf->length] = '\0';
2410 if (warn_trigraphs && fptr != bptr)
2411 warning_with_line (0, "%lu trigraph(s) encountered",
2412 (unsigned long) (fptr - bptr) / 2);
2415 /* Move all backslash-newline pairs out of embarrassing places.
2416 Exchange all such pairs following BP
2417 with any potentially-embarrassing characters that follow them.
2418 Potentially-embarrassing characters are / and *
2419 (because a backslash-newline inside a comment delimiter
2420 would cause it not to be recognized). */
2426 register U_CHAR *p = bp;
2428 /* First count the backslash-newline pairs here. */
2430 while (p[0] == '\\' && p[1] == '\n')
2433 /* What follows the backslash-newlines is not embarrassing. */
2435 if (*p != '/' && *p != '*')
2438 /* Copy all potentially embarrassing characters
2439 that follow the backslash-newline pairs
2440 down to where the pairs originally started. */
2442 while (*p == '*' || *p == '/')
2445 /* Now write the same number of pairs after the embarrassing chars. */
2452 /* Like newline_fix but for use within a directive-name.
2453 Move any backslash-newlines up past any following symbol constituents. */
2456 name_newline_fix (bp)
2459 register U_CHAR *p = bp;
2461 /* First count the backslash-newline pairs here. */
2462 while (p[0] == '\\' && p[1] == '\n')
2465 /* What follows the backslash-newlines is not embarrassing. */
2470 /* Copy all potentially embarrassing characters
2471 that follow the backslash-newline pairs
2472 down to where the pairs originally started. */
2474 while (is_idchar[*p])
2477 /* Now write the same number of pairs after the embarrassing chars. */
2484 /* Look for lint commands in comments.
2486 When we come in here, ibp points into a comment. Limit is as one expects.
2487 scan within the comment -- it should start, after lwsp, with a lint command.
2488 If so that command is returned as a (constant) string.
2490 Upon return, any arg will be pointed to with argstart and will be
2491 arglen long. Note that we don't parse that arg since it will just
2492 be printed out again. */
2495 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2496 register U_CHAR *ibp;
2497 register U_CHAR *limit;
2498 U_CHAR **argstart; /* point to command arg */
2499 int *arglen, *cmdlen; /* how long they are */
2501 HOST_WIDE_INT linsize;
2502 register U_CHAR *numptr; /* temp for arg parsing */
2506 SKIP_WHITE_SPACE (ibp);
2508 if (ibp >= limit) return NULL;
2510 linsize = limit - ibp;
2512 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2513 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2515 return "NOTREACHED";
2517 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2521 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2523 return "LINTLIBRARY";
2525 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2527 ibp += 7; linsize -= 7;
2528 if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2530 /* OK, read a number */
2531 for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2533 *arglen = numptr - *argstart;
2540 * The main loop of the program.
2542 * Read characters from the input stack, transferring them to the
2545 * Macros are expanded and push levels on the input stack.
2546 * At the end of such a level it is popped off and we keep reading.
2547 * At the end of any other kind of level, we return.
2548 * #-directives are handled, except within macros.
2550 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2551 * and insert them when appropriate. This is set while scanning macro
2552 * arguments before substitution. It is zero when scanning for final output.
2553 * There are three types of Newline markers:
2554 * * Newline - follows a macro name that was not expanded
2555 * because it appeared inside an expansion of the same macro.
2556 * This marker prevents future expansion of that identifier.
2557 * When the input is rescanned into the final output, these are deleted.
2558 * These are also deleted by ## concatenation.
2559 * * Newline Space (or Newline and any other whitespace character)
2560 * stands for a place that tokens must be separated or whitespace
2561 * is otherwise desirable, but where the ANSI standard specifies there
2562 * is no whitespace. This marker turns into a Space (or whichever other
2563 * whitespace char appears in the marker) in the final output,
2564 * but it turns into nothing in an argument that is stringified with #.
2565 * Such stringified arguments are the only place where the ANSI standard
2566 * specifies with precision that whitespace may not appear.
2568 * During this function, IP->bufp is kept cached in IBP for speed of access.
2569 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2570 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2571 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2572 * explicitly, and before RECACHE, since RECACHE uses OBP.
2576 rescan (op, output_marks)
2580 /* Character being scanned in main loop. */
2583 /* Length of pending accumulated identifier. */
2584 register int ident_length = 0;
2586 /* Hash code of pending accumulated identifier. */
2587 register int hash = 0;
2589 /* Current input level (&instack[indepth]). */
2592 /* Pointer for scanning input. */
2593 register U_CHAR *ibp;
2595 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2596 register U_CHAR *limit;
2598 /* Pointer for storing output. */
2599 register U_CHAR *obp;
2601 /* REDO_CHAR is nonzero if we are processing an identifier
2602 after backing up over the terminating character.
2603 Sometimes we process an identifier without backing up over
2604 the terminating character, if the terminating character
2605 is not special. Backing up is done so that the terminating character
2606 will be dispatched on again once the identifier is dealt with. */
2609 /* 1 if within an identifier inside of which a concatenation
2610 marker (Newline -) has been seen. */
2611 int concatenated = 0;
2613 /* While scanning a comment or a string constant,
2614 this records the line it started on, for error messages. */
2617 /* Record position of last `real' newline. */
2618 U_CHAR *beg_of_line;
2620 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2623 do { ip->macro->type = T_MACRO; \
2624 if (ip->free_ptr) free (ip->free_ptr); \
2625 --indepth; } while (0)
2627 /* Reload `rescan's local variables that describe the current
2628 level of the input stack. */
2631 do { ip = &instack[indepth]; \
2633 limit = ip->buf + ip->length; \
2635 check_expand (op, limit - ibp); \
2637 obp = op->bufp; } while (0)
2639 if (no_output && instack[indepth].fname != 0)
2640 skip_if_group (&instack[indepth], 1, NULL);
2647 /* Our caller must always put a null after the end of
2648 the input at each input stack level. */
2658 if (*ibp == '\n' && !ip->macro) {
2659 /* At the top level, always merge lines ending with backslash-newline,
2660 even in middle of identifier. But do not merge lines in a macro,
2661 since backslash might be followed by a newline-space marker. */
2664 --obp; /* remove backslash from obuf */
2667 /* If ANSI, backslash is just another character outside a string. */
2670 /* Otherwise, backslash suppresses specialness of following char,
2671 so copy it here to prevent the switch from seeing it.
2672 But first get any pending identifier processed. */
2673 if (ident_length > 0)
2680 if (ident_length || ip->macro || traditional)
2682 while (*ibp == '\\' && ibp[1] == '\n') {
2688 /* Treat this %: digraph as if it were #. */
2692 if (assertions_flag) {
2695 /* Copy #foo (bar lose) without macro expansion. */
2696 obp[-1] = '#'; /* In case it was '%'. */
2697 SKIP_WHITE_SPACE (ibp);
2698 while (is_idchar[*ibp])
2700 SKIP_WHITE_SPACE (ibp);
2703 skip_paren_group (ip);
2704 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2705 obp += ip->bufp - ibp;
2711 /* If this is expanding a macro definition, don't recognize
2712 preprocessing directives. */
2715 /* If this is expand_into_temp_buffer,
2716 don't recognize them either. Warn about them
2717 only after an actual newline at this level,
2718 not at the beginning of the input level. */
2720 if (ip->buf != beg_of_line)
2721 warning ("preprocessing directive not recognized within macro arg");
2728 /* # keyword: a # must be first nonblank char on the line */
2729 if (beg_of_line == 0)
2734 /* Scan from start of line, skipping whitespace, comments
2735 and backslash-newlines, and see if we reach this #.
2736 If not, this # is not special. */
2738 /* If -traditional, require # to be at beginning of line. */
2741 if (is_hor_space[*bp])
2743 else if (*bp == '\\' && bp[1] == '\n')
2745 else if (*bp == '/' && bp[1] == '*') {
2747 while (!(*bp == '*' && bp[1] == '/'))
2751 /* There is no point in trying to deal with C++ // comments here,
2752 because if there is one, then this # must be part of the
2753 comment and we would never reach here. */
2759 while (bp[1] == '\\' && bp[2] == '\n')
2763 /* %: appears at start of line; skip past the ':' too. */
2772 /* This # can start a directive. */
2774 --obp; /* Don't copy the '#' */
2778 if (! handle_directive (ip, op)) {
2782 /* Not a known directive: treat it as ordinary text.
2783 IP, OP, IBP, etc. have not been changed. */
2784 if (no_output && instack[indepth].fname) {
2785 /* If not generating expanded output,
2786 what we do with ordinary text is skip it.
2787 Discard everything until next # directive. */
2788 skip_if_group (&instack[indepth], 1, 0);
2793 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2794 /* Don't expand an identifier that could be a macro directive.
2795 (Section 3.8.3 of the ANSI C standard) */
2796 SKIP_WHITE_SPACE (ibp);
2797 if (is_idstart[*ibp])
2800 while (is_idchar[*ibp])
2808 /* A # directive has been successfully processed. */
2809 /* If not generating expanded output, ignore everything until
2810 next # directive. */
2811 if (no_output && instack[indepth].fname)
2812 skip_if_group (&instack[indepth], 1, 0);
2818 case '\"': /* skip quoted string */
2820 /* A single quoted string is treated like a double -- some
2821 programs (e.g., troff) are perverse this way */
2823 /* Handle any pending identifier;
2824 but the L in L'...' or L"..." is not an identifier. */
2826 && ! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2829 start_line = ip->lineno;
2831 /* Skip ahead to a matching quote. */
2835 if (ip->macro != 0) {
2836 /* try harder: this string crosses a macro expansion boundary.
2837 This can happen naturally if -traditional.
2838 Otherwise, only -D can make a macro with an unmatched quote. */
2844 error_with_line (line_for_error (start_line),
2845 "unterminated string or character constant");
2846 error_with_line (multiline_string_line,
2847 "possible real start of unterminated constant");
2848 multiline_string_line = 0;
2857 /* Traditionally, end of line ends a string constant with no error.
2858 So exit the loop and record the new line. */
2864 error_with_line (line_for_error (start_line),
2865 "unterminated character constant");
2868 if (multiline_string_line == 0) {
2870 pedwarn_with_line (line_for_error (start_line),
2871 "string constant runs past end of line");
2872 multiline_string_line = ip->lineno - 1;
2880 /* Backslash newline is replaced by nothing at all,
2881 but keep the line counts correct. */
2886 /* ANSI stupidly requires that in \\ the second \
2887 is *not* prevented from combining with a newline. */
2888 while (*ibp == '\\' && ibp[1] == '\n') {
2907 if (*ibp == '\\' && ibp[1] == '\n')
2911 && !(cplusplus_comments && *ibp == '/'))
2919 /* C++ style comment... */
2920 start_line = ip->lineno;
2922 /* Comments are equivalent to spaces. */
2923 if (! put_out_comments)
2927 U_CHAR *before_bp = ibp;
2929 while (++ibp < limit) {
2931 if (ibp[-1] != '\\') {
2932 if (put_out_comments) {
2933 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2934 obp += ibp - before_bp;
2939 warning ("multiline `//' comment");
2941 /* Copy the newline into the output buffer, in order to
2942 avoid the pain of a #line every time a multiline comment
2944 if (!put_out_comments)
2953 /* Ordinary C comment. Skip it, optionally copying it to output. */
2955 start_line = ip->lineno;
2957 ++ibp; /* Skip the star. */
2959 /* If this cpp is for lint, we peek inside the comments: */
2963 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2965 if (lintcmd != NULL) {
2967 check_expand (op, cmdlen + arglen + 14);
2969 /* I believe it is always safe to emit this newline: */
2971 bcopy ("#pragma lint ", (char *) obp, 13);
2973 bcopy (lintcmd, (char *) obp, cmdlen);
2978 bcopy (argbp, (char *) obp, arglen);
2982 /* OK, now bring us back to the state we were in before we entered
2983 this branch. We need #line because the #pragma's newline always
2984 messes up the line count. */
2986 output_line_directive (ip, op, 0, same_file);
2987 check_expand (op, limit - ibp + 2);
2993 /* Comments are equivalent to spaces.
2994 Note that we already output the slash; we might not want it.
2995 For -traditional, a comment is equivalent to nothing. */
2996 if (! put_out_comments) {
3006 U_CHAR *before_bp = ibp;
3011 if (ibp[-2] == '/' && warn_comments)
3012 warning ("`/*' within comment");
3013 if (*ibp == '\\' && ibp[1] == '\n')
3021 /* Copy the newline into the output buffer, in order to
3022 avoid the pain of a #line every time a multiline comment
3024 if (!put_out_comments)
3031 error_with_line (line_for_error (start_line),
3032 "unterminated comment");
3041 if (put_out_comments) {
3042 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3043 obp += ibp - before_bp;
3049 if (! is_idchar['$'])
3052 pedwarn ("`$' in identifier");
3055 case '0': case '1': case '2': case '3': case '4':
3056 case '5': case '6': case '7': case '8': case '9':
3057 /* If digit is not part of identifier, it starts a number,
3058 which means that following letters are not an identifier.
3059 "0x5" does not refer to an identifier "x5".
3060 So copy all alphanumerics that follow without accumulating
3061 as an identifier. Periods also, for sake of "3.e7". */
3063 if (ident_length == 0) {
3065 while (ibp[0] == '\\' && ibp[1] == '\n') {
3070 if (!is_idchar[c] && c != '.') {
3075 /* A sign can be part of a preprocessing number
3076 if it follows an `e' or `p'. */
3077 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3078 while (ibp[0] == '\\' && ibp[1] == '\n') {
3082 if (*ibp == '+' || *ibp == '-') {
3084 /* But traditional C does not let the token go past the sign,
3085 and C89 does not allow `p'. */
3086 if (traditional || (c89 && (c == 'p' || c == 'P')))
3096 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3097 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3098 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3099 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3101 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3102 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3103 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3104 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3108 /* Compute step of hash function, to avoid a proc call on every token */
3109 hash = HASHSTEP (hash, c);
3113 if (ip->fname == 0 && *ibp == '-') {
3114 /* Newline - inhibits expansion of preceding token.
3115 If expanding a macro arg, we keep the newline -.
3116 In final output, it is deleted.
3117 We recognize Newline - in macro bodies and macro args. */
3118 if (! concatenated) {
3123 if (!output_marks) {
3126 /* If expanding a macro arg, keep the newline -. */
3132 /* If reprocessing a macro expansion, newline is a special marker. */
3133 else if (ip->macro != 0) {
3134 /* Newline White is a "funny space" to separate tokens that are
3135 supposed to be separate but without space between.
3136 Here White means any whitespace character.
3137 Newline - marks a recursive macro use that is not
3138 supposed to be expandable. */
3140 if (is_space[*ibp]) {
3141 /* Newline Space does not prevent expansion of preceding token
3142 so expand the preceding token and then come back. */
3143 if (ident_length > 0)
3146 /* If generating final output, newline space makes a space. */
3147 if (!output_marks) {
3149 /* And Newline Newline makes a newline, so count it. */
3150 if (obp[-1] == '\n')
3153 /* If expanding a macro arg, keep the newline space.
3154 If the arg gets stringified, newline space makes nothing. */
3157 } else abort (); /* Newline followed by something random? */
3161 /* If there is a pending identifier, handle it and come back here. */
3162 if (ident_length > 0)
3167 /* Update the line counts and output a #line if necessary. */
3170 if (ip->lineno != op->lineno) {
3172 output_line_directive (ip, op, 1, same_file);
3173 check_expand (op, limit - ibp);
3178 /* Come here either after (1) a null character that is part of the input
3179 or (2) at the end of the input, because there is a null there. */
3182 /* Our input really contains a null character. */
3186 /* At end of a macro-expansion level, pop it and read next level. */
3187 if (ip->macro != 0) {
3190 /* If traditional, and we have an identifier that ends here,
3191 process it now, so we get the right error for recursion. */
3192 if (traditional && ident_length
3193 && ! is_idchar[*instack[indepth - 1].bufp]) {
3202 /* If we don't have a pending identifier,
3203 return at end of input. */
3204 if (ident_length == 0) {
3212 /* If we do have a pending identifier, just consider this null
3213 a special character and arrange to dispatch on it again.
3214 The second time, IDENT_LENGTH will be zero so we will return. */
3220 /* Handle the case of a character such as /, ', " or null
3221 seen following an identifier. Back over it so that
3222 after the identifier is processed the special char
3223 will be dispatched on again. */
3233 if (ident_length > 0) {
3234 register HASHNODE *hp;
3236 /* We have just seen an identifier end. If it's a macro, expand it.
3238 IDENT_LENGTH is the length of the identifier
3239 and HASH is its hash code.
3241 The identifier has already been copied to the output,
3242 so if it is a macro we must remove it.
3244 If REDO_CHAR is 0, the char that terminated the identifier
3245 has been skipped in the output and the input.
3246 OBP-IDENT_LENGTH-1 points to the identifier.
3247 If the identifier is a macro, we must back over the terminator.
3249 If REDO_CHAR is 1, the terminating char has already been
3250 backed over. OBP-IDENT_LENGTH points to the identifier. */
3252 if (!pcp_outfile || pcp_inside_if) {
3253 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3256 if (hp->length == ident_length) {
3257 int obufp_before_macroname;
3258 int op_lineno_before_macroname;
3259 register int i = ident_length;
3260 register U_CHAR *p = hp->name;
3261 register U_CHAR *q = obp - i;
3267 do { /* All this to avoid a strncmp () */
3272 /* We found a use of a macro name.
3273 see if the context shows it is a macro call. */
3275 /* Back up over terminating character if not already done. */
3281 /* Save this as a displacement from the beginning of the output
3282 buffer. We can not save this as a position in the output
3283 buffer, because it may get realloc'ed by RECACHE. */
3284 obufp_before_macroname = (obp - op->buf) - ident_length;
3285 op_lineno_before_macroname = op->lineno;
3287 if (hp->type == T_PCSTRING) {
3288 pcstring_used (hp); /* Mark the definition of this key
3289 as needed, ensuring that it
3291 break; /* Exit loop, since the key cannot have a
3292 definition any longer. */
3295 /* Record whether the macro is disabled. */
3296 disabled = hp->type == T_DISABLED;
3298 /* This looks like a macro ref, but if the macro was disabled,
3299 just copy its name and put in a marker if requested. */
3303 /* This error check caught useful cases such as
3304 #define foo(x,y) bar (x (y,0), y)
3307 error ("recursive use of macro `%s'", hp->name);
3311 check_expand (op, limit - ibp + 2);
3318 /* If macro wants an arglist, verify that a '(' follows.
3319 first skip all whitespace, copying it to the output
3320 after the macro name. Then, if there is no '(',
3321 decide this is not a macro call and leave things that way. */
3322 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3323 && hp->value.defn->nargs >= 0)
3325 U_CHAR *old_ibp = ibp;
3326 U_CHAR *old_obp = obp;
3327 int old_iln = ip->lineno;
3328 int old_oln = op->lineno;
3331 /* Scan forward over whitespace, copying it to the output. */
3332 if (ibp == limit && ip->macro != 0) {
3337 old_iln = ip->lineno;
3338 old_oln = op->lineno;
3340 /* A comment: copy it unchanged or discard it. */
3341 else if (*ibp == '/' && ibp[1] == '*') {
3342 if (put_out_comments) {
3345 } else if (! traditional) {
3349 while (ibp + 1 != limit
3350 && !(ibp[0] == '*' && ibp[1] == '/')) {
3351 /* We need not worry about newline-marks,
3352 since they are never found in comments. */
3354 /* Newline in a file. Count it. */
3358 if (put_out_comments)
3364 if (put_out_comments) {
3369 else if (is_space[*ibp]) {
3371 if (ibp[-1] == '\n') {
3372 if (ip->macro == 0) {
3373 /* Newline in a file. Count it. */
3376 } else if (!output_marks) {
3377 /* A newline mark, and we don't want marks
3378 in the output. If it is newline-hyphen,
3379 discard it entirely. Otherwise, it is
3380 newline-whitechar, so keep the whitechar. */
3390 /* A newline mark; copy both chars to the output. */
3398 /* It isn't a macro call.
3399 Put back the space that we just skipped. */
3402 ip->lineno = old_iln;
3403 op->lineno = old_oln;
3404 /* Exit the for loop. */
3409 /* This is now known to be a macro call.
3410 Discard the macro name from the output,
3411 along with any following whitespace just copied,
3412 but preserve newlines if not outputting marks since this
3413 is more likely to do the right thing with line numbers. */
3414 obp = op->buf + obufp_before_macroname;
3416 op->lineno = op_lineno_before_macroname;
3418 int newlines = op->lineno - op_lineno_before_macroname;
3419 while (0 < newlines--)
3423 /* Prevent accidental token-pasting with a character
3424 before the macro call. */
3425 if (!traditional && obp != op->buf) {
3427 case '!': case '%': case '&': case '*':
3428 case '+': case '-': case '.': case '/':
3429 case ':': case '<': case '=': case '>':
3431 /* If we are expanding a macro arg, make a newline marker
3432 to separate the tokens. If we are making real output,
3433 a plain space will do. */
3440 /* Expand the macro, reading arguments as needed,
3441 and push the expansion on the input stack. */
3444 macroexpand (hp, op);
3446 /* Reexamine input stack, since macroexpand has pushed
3447 a new level on it. */
3454 } /* End hash-table-search loop */
3456 ident_length = hash = 0; /* Stop collecting identifier */
3459 } /* End if (ident_length > 0) */
3461 } /* End per-char loop */
3463 /* Come here to return -- but first give an error message
3464 if there was an unterminated successful conditional. */
3466 if (if_stack != ip->if_stack)
3470 switch (if_stack->type)
3491 error_with_line (line_for_error (if_stack->lineno),
3492 "unterminated `#%s' conditional", str);
3494 if_stack = ip->if_stack;
3498 * Rescan a string into a temporary buffer and return the result
3499 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3501 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3502 * and insert such markers when appropriate. See `rescan' for details.
3503 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3504 * before substitution; it is 0 for other uses.
3507 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3508 U_CHAR *buf, *limit;
3509 int output_marks, assertions;
3511 register FILE_BUF *ip;
3513 int length = limit - buf;
3515 int odepth = indepth;
3516 int save_assertions_flag = assertions_flag;
3518 assertions_flag = assertions;
3523 /* Set up the input on the input stack. */
3525 buf1 = (U_CHAR *) alloca (length + 1);
3527 register U_CHAR *p1 = buf;
3528 register U_CHAR *p2 = buf1;
3535 /* Set up to receive the output. */
3537 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3538 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3543 CHECK_DEPTH ({return obuf;});
3547 ip = &instack[indepth];
3549 ip->nominal_fname = 0;
3551 ip->system_header_p = 0;
3554 ip->length = length;
3555 ip->buf = ip->bufp = buf1;
3556 ip->if_stack = if_stack;
3558 ip->lineno = obuf.lineno = 1;
3560 /* Scan the input, create the output. */
3561 rescan (&obuf, output_marks);
3563 /* Pop input stack to original state. */
3566 if (indepth != odepth)
3569 /* Record the output. */
3570 obuf.length = obuf.bufp - obuf.buf;
3572 assertions_flag = save_assertions_flag;
3577 * Process a # directive. Expects IP->bufp to point after the '#', as in
3578 * `#define foo bar'. Passes to the directive handler
3579 * (do_define, do_include, etc.): the addresses of the 1st and
3580 * last chars of the directive (starting immediately after the #
3581 * keyword), plus op and the keyword table pointer. If the directive
3582 * contains comments it is copied into a temporary buffer sans comments
3583 * and the temporary buffer is passed to the directive handler instead.
3584 * Likewise for backslash-newlines.
3586 * Returns nonzero if this was a known # directive.
3587 * Otherwise, returns zero, without advancing the input pointer.
3591 handle_directive (ip, op)
3594 register U_CHAR *bp, *cp;
3595 register struct directive *kt;
3596 register int ident_length;
3599 /* Nonzero means we must copy the entire directive
3600 to get rid of comments or backslash-newlines. */
3601 int copy_directive = 0;
3603 U_CHAR *ident, *after_ident;
3607 /* Record where the directive started. do_xifdef needs this. */
3608 directive_start = bp - 1;
3610 /* Skip whitespace and \-newline. */
3612 if (is_hor_space[*bp]) {
3613 if (*bp != ' ' && *bp != '\t' && pedantic)
3614 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3616 } else if (*bp == '/' && (bp[1] == '*'
3617 || (cplusplus_comments && bp[1] == '/'))) {
3619 skip_to_end_of_comment (ip, &ip->lineno, 0);
3621 } else if (*bp == '\\' && bp[1] == '\n') {
3622 bp += 2; ip->lineno++;
3626 /* Now find end of directive name.
3627 If we encounter a backslash-newline, exchange it with any following
3628 symbol-constituents so that we end up with a contiguous name. */
3635 if (*cp == '\\' && cp[1] == '\n')
3636 name_newline_fix (cp);
3642 ident_length = cp - bp;
3646 /* A line of just `#' becomes blank. */
3648 if (ident_length == 0 && *after_ident == '\n') {
3649 ip->bufp = after_ident;
3653 if (ident_length == 0 || !is_idstart[*ident]) {
3655 while (is_idchar[*p]) {
3656 if (*p < '0' || *p > '9')
3660 /* Handle # followed by a line number. */
3661 if (p != ident && !is_idchar[*p]) {
3662 static struct directive line_directive_table[] = {
3663 { 4, do_line, "line", T_LINE},
3666 pedwarn ("`#' followed by integer");
3667 after_ident = ident;
3668 kt = line_directive_table;
3672 /* Avoid error for `###' and similar cases unless -pedantic. */
3674 while (*p == '#' || is_hor_space[*p]) p++;
3676 if (pedantic && !lang_asm)
3677 warning ("invalid preprocessing directive");
3683 error ("invalid preprocessing directive name");
3689 * Decode the keyword and call the appropriate expansion
3690 * routine, after moving the input pointer up to the next line.
3692 for (kt = directive_table; kt->length > 0; kt++) {
3693 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3694 register U_CHAR *buf;
3695 register U_CHAR *limit;
3698 int *already_output;
3700 /* Nonzero means do not delete comments within the directive.
3701 #define needs this when -traditional. */
3706 limit = ip->buf + ip->length;
3709 keep_comments = traditional && kt->traditional_comments;
3710 /* #import is defined only in Objective C, or when on the NeXT. */
3711 if (kt->type == T_IMPORT
3712 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3715 /* Find the end of this directive (first newline not backslashed
3716 and not in a string or comment).
3717 Set COPY_DIRECTIVE if the directive must be copied
3718 (it contains a backslash-newline or a comment). */
3720 buf = bp = after_ident;
3721 while (bp < limit) {
3722 register U_CHAR c = *bp++;
3730 } else if (traditional)
3737 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3738 /* Don't bother calling the directive if we already got an error
3739 message due to unterminated string. Skip everything and pretend
3740 we called the directive. */
3743 /* Traditional preprocessing permits unterminated strings. */
3752 /* <...> is special for #include. */
3754 if (!kt->angle_brackets)
3756 while (bp < limit && *bp != '>' && *bp != '\n') {
3757 if (*bp == '\\' && bp[1] == '\n') {
3767 if (*bp == '\\' && bp[1] == '\n')
3770 || (cplusplus_comments && *bp == '/')) {
3771 U_CHAR *obp = bp - 1;
3773 skip_to_end_of_comment (ip, &ip->lineno, 0);
3775 /* No need to copy the directive because of a comment at the end;
3776 just don't include the comment in the directive. */
3777 if (!put_out_comments) {
3779 for (p = bp; *p == ' ' || *p == '\t'; p++)
3786 /* Don't remove the comments if -traditional. */
3787 if (! keep_comments)
3796 pedwarn ("%s in preprocessing directive", char_name[c]);
3800 --bp; /* Point to the newline */
3808 resume_p = ip->bufp;
3809 /* BP is the end of the directive.
3810 RESUME_P is the next interesting data after the directive.
3811 A comment may come between. */
3813 /* If a directive should be copied through, and -E was given,
3814 pass it through before removing comments. */
3815 if (!no_output && put_out_comments
3816 && (dump_macros != dump_definitions) < kt->pass_thru) {
3819 /* Output directive name. */
3820 check_expand (op, kt->length + 2);
3821 /* Make sure # is at the start of a line */
3822 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3827 bcopy (kt->name, op->bufp, kt->length);
3828 op->bufp += kt->length;
3830 /* Output arguments. */
3832 check_expand (op, len);
3833 bcopy (buf, (char *) op->bufp, len);
3835 /* Take account of any (escaped) newlines just output. */
3837 if (buf[len] == '\n')
3840 already_output = &junk;
3841 } /* Don't we need a newline or #line? */
3843 if (copy_directive) {
3844 register U_CHAR *xp = buf;
3845 /* Need to copy entire directive into temp buffer before dispatching */
3847 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3851 /* Copy to the new buffer, deleting comments
3852 and backslash-newlines (and whitespace surrounding the latter). */
3855 register U_CHAR c = *xp++;
3860 abort (); /* A bare newline should never part of the line. */
3863 /* <...> is special for #include. */
3865 if (!kt->angle_brackets)
3867 while (xp < bp && c != '>') {
3869 if (c == '\\' && xp < bp && *xp == '\n')
3880 if (cp != buf && is_hor_space[cp[-1]]) {
3881 while (cp - 1 != buf && is_hor_space[cp[-2]])
3883 SKIP_WHITE_SPACE (xp);
3884 } else if (is_hor_space[*xp]) {
3886 SKIP_WHITE_SPACE (xp);
3888 } else if (traditional && xp < bp) {
3896 register U_CHAR *bp1
3897 = skip_quoted_string (xp - 1, bp, ip->lineno,
3898 NULL_PTR, NULL_PTR, NULL_PTR);
3912 || (cplusplus_comments && *xp == '/')) {
3914 /* If we already copied the directive through,
3915 already_output != 0 prevents outputting comment now. */
3916 skip_to_end_of_comment (ip, already_output, 0);
3918 while (xp != ip->bufp)
3920 /* Delete or replace the slash. */
3921 else if (traditional)
3930 /* Null-terminate the copy. */
3936 ip->bufp = resume_p;
3938 /* Some directives should be written out for cc1 to process,
3939 just as if they were not defined. And sometimes we're copying
3940 definitions through. */
3942 if (!no_output && already_output == 0
3943 && (dump_macros < dump_names) < kt->pass_thru) {
3946 /* Output directive name. */
3947 check_expand (op, kt->length + 1);
3949 bcopy (kt->name, (char *) op->bufp, kt->length);
3950 op->bufp += kt->length;
3952 if ((dump_macros != dump_definitions) < kt->pass_thru) {
3953 /* Output arguments. */
3955 check_expand (op, len);
3956 bcopy (buf, (char *) op->bufp, len);
3958 } else if (kt->type == T_DEFINE && dump_macros == dump_names) {
3961 SKIP_WHITE_SPACE (xp);
3963 while (is_idchar[*xp]) xp++;
3965 check_expand (op, len + 1);
3967 bcopy (yp, op->bufp, len);
3970 } /* Don't we need a newline or #line? */
3972 /* Call the appropriate directive handler. buf now points to
3973 either the appropriate place in the input buffer, or to
3974 the temp buffer if it was necessary to make one. cp
3975 points to the first char after the contents of the (possibly
3976 copied) directive, in either case. */
3977 (*kt->func) (buf, cp, op, kt);
3978 check_expand (op, ip->length - (ip->bufp - ip->buf));
3984 /* It is deliberate that we don't warn about undefined directives.
3985 That is the responsibility of cc1. */
3992 static struct tm *timebuf;
3994 time_t t = time ((time_t *) 0);
3995 timebuf = localtime (&t);
4000 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4001 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4005 * expand things like __FILE__. Place the expansion into the output
4006 * buffer *without* rescanning.
4010 special_symbol (hp, op)
4017 FILE_BUF *ip = NULL;
4020 int paren = 0; /* For special `defined' keyword */
4022 if (pcp_outfile && pcp_inside_if
4023 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4024 error ("Predefined macro `%s' used inside `#if' during precompilation",
4027 for (i = indepth; i >= 0; i--)
4028 if (instack[i].fname != NULL) {
4033 error ("cccp error: not in any file?!");
4034 return; /* the show must go on */
4042 if (hp->type == T_FILE)
4043 string = ip->nominal_fname;
4045 string = instack[0].nominal_fname;
4049 buf = (char *) alloca (3 + 4 * strlen (string));
4050 quote_string (buf, string);
4058 case T_INCLUDE_LEVEL:
4060 for (i = indepth; i >= 0; i--)
4061 if (instack[i].fname != NULL)
4064 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4065 sprintf (buf, "%d", true_indepth - 1);
4069 buf = (char *) alloca (3 + strlen (version_string));
4070 sprintf (buf, "\"%s\"", version_string);
4073 #ifndef NO_BUILTIN_SIZE_TYPE
4079 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4080 case T_PTRDIFF_TYPE:
4089 case T_USER_LABEL_PREFIX_TYPE:
4090 buf = USER_LABEL_PREFIX;
4093 case T_REGISTER_PREFIX_TYPE:
4094 buf = REGISTER_PREFIX;
4097 case T_IMMEDIATE_PREFIX_TYPE:
4098 buf = IMMEDIATE_PREFIX;
4102 buf = hp->value.cpval;
4103 if (pcp_inside_if && pcp_outfile)
4104 /* Output a precondition for this macro use */
4105 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4109 buf = (char *) alloca (10);
4110 sprintf (buf, "%d", ip->lineno);
4115 buf = (char *) alloca (20);
4116 timebuf = timestamp ();
4117 if (hp->type == T_DATE)
4118 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4119 timebuf->tm_mday, timebuf->tm_year + 1900);
4121 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4125 case T_SPEC_DEFINED:
4126 buf = " 0 "; /* Assume symbol is not defined */
4127 ip = &instack[indepth];
4128 SKIP_WHITE_SPACE (ip->bufp);
4129 if (*ip->bufp == '(') {
4131 ip->bufp++; /* Skip over the paren */
4132 SKIP_WHITE_SPACE (ip->bufp);
4135 if (!is_idstart[*ip->bufp])
4137 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4139 if ((hp = lookup (ip->bufp, -1, -1))) {
4140 if (pcp_outfile && pcp_inside_if
4141 && (hp->type == T_CONST
4142 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4143 /* Output a precondition for this macro use. */
4144 fprintf (pcp_outfile, "#define %s\n", hp->name);
4148 if (pcp_outfile && pcp_inside_if) {
4149 /* Output a precondition for this macro use */
4150 U_CHAR *cp = ip->bufp;
4151 fprintf (pcp_outfile, "#undef ");
4152 while (is_idchar[*cp]) /* Ick! */
4153 fputc (*cp++, pcp_outfile);
4154 putc ('\n', pcp_outfile);
4156 while (is_idchar[*ip->bufp])
4158 SKIP_WHITE_SPACE (ip->bufp);
4160 if (*ip->bufp != ')')
4168 error ("`defined' without an identifier");
4172 error ("cccp error: invalid special hash type"); /* time for gdb */
4176 check_expand (op, len);
4177 bcopy (buf, (char *) op->bufp, len);
4184 /* Routines to handle #directives */
4186 /* Handle #include and #import.
4187 This function expects to see "fname" or <fname> on the input. */
4190 do_include (buf, limit, op, keyword)
4191 U_CHAR *buf, *limit;
4193 struct directive *keyword;
4195 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4196 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4197 static int import_warning = 0;
4198 char *fname; /* Dynamically allocated fname buffer */
4201 char *fbeg, *fend; /* Beginning and end of fname */
4204 struct file_name_list *search_start = include; /* Chain of dirs to search */
4205 struct file_name_list *dsp; /* First in chain, if #include "..." */
4206 struct file_name_list *searchptr = 0;
4209 int f = -3; /* file number */
4210 struct include_file *inc = 0;
4212 int retried = 0; /* Have already tried macro
4213 expanding the include line*/
4214 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4216 int vaxc_include = 0; /* 1 for token without punctuation */
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>' !");
4332 /* If -I-, start with the first -I dir after the -I-. */
4333 search_start = first_bracket_include;
4341 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4344 /* Expand buffer and then remove any newline markers.
4345 We can't just tell expand_to_temp_buffer to omit the markers,
4346 since it would put extra spaces in include file names. */
4349 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4351 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4353 while (src != trybuf.bufp) {
4354 switch ((*limit++ = *src++)) {
4363 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4364 NULL_PTR, NULL_PTR, NULL_PTR);
4378 /* For #include_next, skip in the search path
4379 past the dir in which the containing file was found. */
4382 for (fp = &instack[indepth]; fp >= instack; fp--)
4383 if (fp->fname != NULL) {
4384 /* fp->dir is null if the containing file was specified
4385 with an absolute file name. In that case, don't skip anything. */
4387 search_start = fp->dir->next;
4393 flen = simplify_filename (fbeg);
4397 error ("empty file name in `#%s'", keyword->name);
4401 /* Allocate this permanently, because it gets stored in the definitions
4403 fname = xmalloc (max_include_len + flen + 1);
4404 /* + 1 above for terminating null. */
4406 system_include_depth += angle_brackets;
4408 /* If specified file name is absolute, just open it. */
4410 if (absolute_filename (fbeg)) {
4411 strcpy (fname, fbeg);
4412 f = open_include_file (fname, NULL_PTR, importing, &inc);
4416 struct bypass_dir *next;
4418 struct file_name_list *searchptr;
4419 } **bypass_slot = 0;
4421 /* Search directory path, trying to open the file.
4422 Copy each filename tried into FNAME. */
4424 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4426 if (searchptr == first_bracket_include) {
4427 /* Go to bypass directory if we know we've seen this file before. */
4428 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4429 struct bypass_dir *p;
4430 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4432 for (p = *bypass_slot; p; p = p->next)
4433 if (!strcmp (fbeg, p->fname)) {
4434 searchptr = p->searchptr;
4440 strcpy (fname, searchptr->fname);
4441 strcat (fname, fbeg);
4443 /* Change this 1/2 Unix 1/2 VMS file specification into a
4444 full VMS file specification */
4445 if (searchptr->fname[0]) {
4446 /* Fix up the filename */
4447 hack_vms_include_specification (fname, vaxc_include);
4449 /* This is a normal VMS filespec, so use it unchanged. */
4450 strcpy (fname, fbeg);
4451 /* if it's '#include filename', add the missing .h */
4452 if (vaxc_include && index(fname,'.')==NULL) {
4453 strcat (fname, ".h");
4457 f = open_include_file (fname, searchptr, importing, &inc);
4459 if (bypass_slot && searchptr != first_bracket_include) {
4460 /* This is the first time we found this include file,
4461 and we found it after first_bracket_include.
4462 Record its location so that we can bypass to here next time. */
4463 struct bypass_dir *p
4464 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4465 p->next = *bypass_slot;
4466 p->fname = fname + strlen (searchptr->fname);
4467 p->searchptr = searchptr;
4473 /* Our VMS hacks can produce invalid filespecs, so don't worry
4474 about errors other than EACCES. */
4475 if (errno == EACCES)
4478 if (errno != ENOENT && errno != ENOTDIR)
4488 /* The file was already included. */
4490 /* If generating dependencies and -MG was specified, we assume missing
4491 files are leaf files, living in the same directory as the source file
4492 or other similar place; these missing files may be generated from
4493 other files and may not exist yet (eg: y.tab.h). */
4494 } else if (print_deps_missing_files
4495 && (system_include_depth != 0) < print_deps)
4497 /* If it was requested as a system header file,
4498 then assume it belongs in the first place to look for such. */
4502 char *p = (char *) alloca (strlen (search_start->fname)
4503 + strlen (fbeg) + 1);
4504 strcpy (p, search_start->fname);
4506 deps_output (p, ' ');
4511 /* Otherwise, omit the directory, as if the file existed
4512 in the directory with the source. */
4513 deps_output (fbeg, ' ');
4516 /* If -M was specified, and this header file won't be added to the
4517 dependency list, then don't count this as an error, because we can
4518 still produce correct output. Otherwise, we can't produce correct
4519 output, because there may be dependencies we need inside the missing
4520 file, and we don't know what directory this missing file exists in. */
4521 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4522 warning ("No include path in which to find %s", fbeg);
4524 error_from_errno (fbeg);
4526 error ("No include path in which to find %s", fbeg);
4530 /* Actually process the file. */
4532 pcftry = (char *) alloca (strlen (fname) + 30);
4539 sprintf (pcftry, "%s%d", fname, pcfnum++);
4541 pcf = open (pcftry, O_RDONLY, 0666);
4546 if (fstat (pcf, &s) != 0)
4547 pfatal_with_name (pcftry);
4548 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4549 || inc->st.st_dev != s.st_dev)
4551 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4552 /* Don't need it any more. */
4557 /* Don't need it at all. */
4562 } while (pcf != -1 && !pcfbuf);
4565 /* Actually process the file */
4567 pcfname = xmalloc (strlen (pcftry) + 1);
4568 strcpy (pcfname, pcftry);
4569 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4570 (U_CHAR *) fname, op);
4573 finclude (f, inc, op, is_system_include (fname), searchptr);
4576 system_include_depth -= angle_brackets;
4581 /* Return nonzero if the given FILENAME is an absolute pathname which
4582 designates a file within one of the known "system" include file
4583 directories. We assume here that if the given FILENAME looks like
4584 it is the name of a file which resides either directly in a "system"
4585 include file directory, or within any subdirectory thereof, then the
4586 given file must be a "system" include file. This function tells us
4587 if we should suppress pedantic errors/warnings for the given FILENAME.
4589 The value is 2 if the file is a C-language system header file
4590 for which C++ should (on most systems) assume `extern "C"'. */
4593 is_system_include (filename)
4594 register char *filename;
4596 struct file_name_list *searchptr;
4598 for (searchptr = first_system_include; searchptr;
4599 searchptr = searchptr->next)
4600 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4601 return searchptr->c_system_include_path + 1;
4605 /* Yield the non-directory suffix of a file name. */
4613 #if defined (__MSDOS__) || defined (_WIN32)
4614 if (isalpha (s[0]) && s[1] == ':') s += 2;
4617 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4618 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4619 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4623 if ((p = rindex (s, '/'))) s = p + 1;
4624 #ifdef DIR_SEPARATOR
4625 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4630 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4633 absolute_filename (filename)
4636 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4637 if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4639 #if defined (__CYGWIN32__)
4640 /* At present, any path that begins with a drive spec is absolute. */
4641 if (isalpha (filename[0]) && filename[1] == ':') return 1;
4643 if (filename[0] == '/') return 1;
4644 #ifdef DIR_SEPARATOR
4645 if (filename[0] == DIR_SEPARATOR) return 1;
4650 /* Remove unnecessary characters from FILENAME in place,
4651 to avoid unnecessary filename aliasing.
4652 Return the length of the resulting string.
4654 Do only the simplifications allowed by Posix.
4655 It is OK to miss simplifications on non-Posix hosts,
4656 since this merely leads to suboptimial results. */
4659 simplify_filename (filename)
4662 register char *from = filename;
4663 register char *to = filename;
4666 /* Remove redundant initial /s. */
4669 if (*++from == '/') {
4670 if (*++from == '/') {
4671 /* 3 or more initial /s are equivalent to 1 /. */
4672 while (*++from == '/')
4675 /* On some hosts // differs from /; Posix allows this. */
4676 static int slashslash_vs_slash;
4677 if (slashslash_vs_slash == 0) {
4679 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4680 && INO_T_EQ (s1.st_ino, s2.st_ino)
4681 && s1.st_dev == s2.st_dev)
4684 if (slashslash_vs_slash < 0)
4692 if (from[0] == '.' && from[1] == '/')
4695 /* Copy this component and trailing /, if any. */
4696 while ((*to++ = *from++) != '/') {
4698 /* Trim . component at end of nonempty name. */
4699 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4701 /* Trim unnecessary trailing /s. */
4702 while (to0 < --to && to[-1] == '/')
4706 return to - filename;
4711 /* Skip /s after a /. */
4712 while (*from == '/')
4717 /* The file_name_map structure holds a mapping of file names for a
4718 particular directory. This mapping is read from the file named
4719 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4720 map filenames on a file system with severe filename restrictions,
4721 such as DOS. The format of the file name map file is just a series
4722 of lines with two tokens on each line. The first token is the name
4723 to map, and the second token is the actual name to use. */
4725 struct file_name_map
4727 struct file_name_map *map_next;
4732 #define FILE_NAME_MAP_FILE "header.gcc"
4734 /* Read a space delimited string of unlimited length from a stdio
4738 read_filename_string (ch, f)
4746 set = alloc = xmalloc (len + 1);
4750 while ((ch = getc (f)) != EOF && ! is_space[ch])
4752 if (set - alloc == len)
4755 alloc = xrealloc (alloc, len + 1);
4756 set = alloc + len / 2;
4766 /* Read the file name map file for DIRNAME.
4767 If DIRNAME is empty, read the map file for the working directory;
4768 otherwise DIRNAME must end in '/'. */
4770 static struct file_name_map *
4771 read_name_map (dirname)
4774 /* This structure holds a linked list of file name maps, one per
4776 struct file_name_map_list
4778 struct file_name_map_list *map_list_next;
4779 char *map_list_name;
4780 struct file_name_map *map_list_map;
4782 static struct file_name_map_list *map_list;
4783 register struct file_name_map_list *map_list_ptr;
4788 for (map_list_ptr = map_list; map_list_ptr;
4789 map_list_ptr = map_list_ptr->map_list_next)
4790 if (! strcmp (map_list_ptr->map_list_name, dirname))
4791 return map_list_ptr->map_list_map;
4793 map_list_ptr = ((struct file_name_map_list *)
4794 xmalloc (sizeof (struct file_name_map_list)));
4795 map_list_ptr->map_list_name = savestring (dirname);
4796 map_list_ptr->map_list_map = NULL;
4798 dirlen = strlen (dirname);
4799 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4800 strcpy (name, dirname);
4801 strcat (name, FILE_NAME_MAP_FILE);
4802 f = fopen (name, "r");
4804 map_list_ptr->map_list_map = NULL;
4809 while ((ch = getc (f)) != EOF)
4812 struct file_name_map *ptr;
4817 from = read_filename_string (ch, f);
4818 while ((ch = getc (f)) != EOF && is_hor_space[ch])
4820 to = read_filename_string (ch, f);
4822 simplify_filename (from);
4823 tolen = simplify_filename (to);
4825 ptr = ((struct file_name_map *)
4826 xmalloc (sizeof (struct file_name_map)));
4827 ptr->map_from = from;
4829 /* Make the real filename absolute. */
4830 if (absolute_filename (to))
4834 ptr->map_to = xmalloc (dirlen + tolen + 1);
4835 strcpy (ptr->map_to, dirname);
4836 strcat (ptr->map_to, to);
4840 ptr->map_next = map_list_ptr->map_list_map;
4841 map_list_ptr->map_list_map = ptr;
4843 while ((ch = getc (f)) != '\n')
4850 map_list_ptr->map_list_next = map_list;
4851 map_list = map_list_ptr;
4853 return map_list_ptr->map_list_map;
4856 /* Try to open include file FILENAME. SEARCHPTR is the directory
4857 being tried from the include file search path.
4858 IMPORTING is "" if we are importing, null otherwise.
4859 Return -2 if found, either a matching name or a matching inode.
4860 Otherwise, open the file and return a file descriptor if successful
4861 or -1 if unsuccessful.
4862 Unless unsuccessful, put a descriptor of the included file into *PINC.
4863 This function maps filenames on file systems based on information read by
4867 open_include_file (filename, searchptr, importing, pinc)
4869 struct file_name_list *searchptr;
4871 struct include_file **pinc;
4873 char *fname = remap_include_file (filename, searchptr);
4876 /* Look up FNAME in include_hashtab. */
4877 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4880 struct include_file *inc, *head = *phead;
4881 for (inc = head; inc; inc = inc->next)
4882 if (!strcmp (fname, inc->fname))
4886 || ! inc->control_macro
4887 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4889 fd = open (fname, O_RDONLY, 0);
4895 /* FNAME was not in include_hashtab; insert a new entry. */
4896 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4899 inc->control_macro = 0;
4900 inc->deps_output = 0;
4901 if (fstat (fd, &inc->st) != 0)
4902 pfatal_with_name (fname);
4905 /* Look for another file with the same inode and device. */
4906 if (lookup_ino_include (inc)
4907 && inc->control_macro
4908 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4914 /* For -M, add this file to the dependencies. */
4915 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
4916 inc->deps_output = 1;
4917 deps_output (fname, ' ');
4920 /* Handle -H option. */
4921 if (print_include_names)
4922 fprintf (stderr, "%*s%s\n", indepth, "", fname);
4926 inc->control_macro = importing;
4932 /* Return the remapped name of the the include file FILENAME.
4933 SEARCHPTR is the directory being tried from the include file path. */
4936 remap_include_file (filename, searchptr)
4938 struct file_name_list *searchptr;
4940 register struct file_name_map *map;
4941 register char *from;
4945 if (! searchptr->got_name_map)
4947 searchptr->name_map = read_name_map (searchptr->fname);
4948 searchptr->got_name_map = 1;
4951 /* Check the mapping for the directory we are using. */
4952 from = filename + strlen (searchptr->fname);
4953 for (map = searchptr->name_map; map; map = map->map_next)
4954 if (! strcmp (map->map_from, from))
4958 from = base_name (filename);
4960 if (from != filename || !searchptr)
4962 /* Try to find a mapping file for the particular directory we are
4963 looking in. Thus #include <sys/types.h> will look up sys/types.h
4964 in /usr/include/header.gcc and look up types.h in
4965 /usr/include/sys/header.gcc. */
4967 char *dir = (char *) alloca (from - filename + 1);
4968 bcopy (filename, dir, from - filename);
4969 dir[from - filename] = '\0';
4971 for (map = read_name_map (dir); map; map = map->map_next)
4972 if (! strcmp (map->map_from, from))
4979 /* Insert INC into the include file table, hashed by device and inode number.
4980 If a file with different name but same dev+ino was already in the table,
4981 return 1 and set INC's control macro to the already-known macro. */
4984 lookup_ino_include (inc)
4985 struct include_file *inc;
4987 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
4988 % INCLUDE_HASHSIZE);
4989 struct include_file *i = include_ino_hashtab[hash];
4991 include_ino_hashtab[hash] = inc;
4993 for (; i; i = i->next_ino)
4994 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
4995 && inc->st.st_dev == i->st.st_dev) {
4996 inc->control_macro = i->control_macro;
5003 /* Process file descriptor F, which corresponds to include file INC,
5005 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5006 "system" include directories (as decided by the `is_system_include'
5008 DIRPTR is the link in the dir path through which this file was found,
5009 or 0 if the file name was absolute. */
5012 finclude (f, inc, op, system_header_p, dirptr)
5014 struct include_file *inc;
5016 int system_header_p;
5017 struct file_name_list *dirptr;
5019 char *fname = inc->fname;
5021 FILE_BUF *fp; /* For input stack frame */
5022 int missing_newline = 0;
5024 CHECK_DEPTH (return;);
5026 fp = &instack[indepth + 1];
5027 bzero ((char *) fp, sizeof (FILE_BUF));
5028 fp->nominal_fname = fp->fname = fname;
5032 fp->if_stack = if_stack;
5033 fp->system_header_p = system_header_p;
5036 if (S_ISREG (inc->st.st_mode)) {
5037 fp->buf = (U_CHAR *) xmalloc (inc->st.st_size + 2);
5040 /* Read the file contents, knowing that inc->st.st_size is an upper bound
5041 on the number of bytes we can read. */
5042 fp->length = safe_read (f, (char *) fp->buf, inc->st.st_size);
5043 if (fp->length < 0) goto nope;
5045 else if (S_ISDIR (inc->st.st_mode)) {
5046 error ("directory `%s' specified in #include", fname);
5050 /* Cannot count its file size before reading.
5051 First read the entire file into heap and
5052 copy them into buffer on stack. */
5057 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5060 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5062 goto nope; /* error! */
5064 if (st_size != bsize)
5065 break; /* End of file */
5067 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5070 fp->length = st_size;
5073 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5074 /* Backslash-newline at end is not good enough. */
5075 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5076 fp->buf[fp->length++] = '\n';
5077 missing_newline = 1;
5079 fp->buf[fp->length] = '\0';
5081 /* Close descriptor now, so nesting does not use lots of descriptors. */
5084 /* Must do this before calling trigraph_pcp, so that the correct file name
5085 will be printed in warning messages. */
5088 input_file_stack_tick++;
5093 output_line_directive (fp, op, 0, enter_file);
5096 if (missing_newline)
5099 if (pedantic && missing_newline)
5100 pedwarn ("file does not end in newline");
5103 input_file_stack_tick++;
5104 output_line_directive (&instack[indepth], op, 0, leave_file);
5110 perror_with_name (fname);
5115 /* Record that inclusion of the include file INC
5116 should be controlled by the macro named MACRO_NAME.
5117 This means that trying to include the file again
5118 will do something if that macro is defined. */
5121 record_control_macro (inc, macro_name)
5122 struct include_file *inc;
5125 if (!inc->control_macro || inc->control_macro[0])
5126 inc->control_macro = macro_name;
5129 /* Load the specified precompiled header into core, and verify its
5130 preconditions. PCF indicates the file descriptor to read, which must
5131 be a regular file. *ST is its file status.
5132 FNAME indicates the file name of the original header.
5133 *LIMIT will be set to an address one past the end of the file.
5134 If the preconditions of the file are not satisfied, the buffer is
5135 freed and we return 0. If the preconditions are satisfied, return
5136 the address of the buffer following the preconditions. The buffer, in
5137 this case, should never be freed because various pieces of it will
5138 be referred to until all precompiled strings are output at the end of
5142 check_precompiled (pcf, st, fname, limit)
5155 if (S_ISREG (st->st_mode))
5157 buf = xmalloc (st->st_size + 2);
5158 length = safe_read (pcf, buf, st->st_size);
5165 if (length > 0 && buf[length-1] != '\n')
5166 buf[length++] = '\n';
5169 *limit = buf + length;
5171 /* File is in core. Check the preconditions. */
5172 if (!check_preconditions (buf))
5174 for (cp = buf; *cp; cp++)
5177 fprintf (stderr, "Using preinclude %s\n", fname);
5183 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5189 /* PREC (null terminated) points to the preconditions of a
5190 precompiled header. These are a series of #define and #undef
5191 lines which must match the current contents of the hash
5195 check_preconditions (prec)
5202 lineend = index (prec, '\n');
5204 if (*prec++ != '#') {
5205 error ("Bad format encountered while reading precompiled file");
5208 if (!strncmp (prec, "define", 6)) {
5212 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5217 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5218 || (hp->type != T_MACRO && hp->type != T_CONST)
5219 || (hp->type == T_MACRO
5220 && !compare_defs (mdef.defn, hp->value.defn)
5221 && (mdef.defn->length != 2
5222 || mdef.defn->expansion[0] != '\n'
5223 || mdef.defn->expansion[1] != ' ')))
5225 } else if (!strncmp (prec, "undef", 5)) {
5230 while (is_hor_space[(U_CHAR) *prec])
5233 while (is_idchar[(U_CHAR) *prec])
5237 if (lookup ((U_CHAR *) name, len, -1))
5240 error ("Bad format encountered while reading precompiled file");
5245 /* They all passed successfully */
5249 /* Process the main body of a precompiled file. BUF points to the
5250 string section of the file, following the preconditions. LIMIT is one
5251 character past the end. NAME is the name of the file being read
5252 in. OP is the main output buffer. */
5255 pcfinclude (buf, limit, name, op)
5256 U_CHAR *buf, *limit, *name;
5263 /* First in the file comes 4 bytes indicating the number of strings, */
5264 /* in network byte order. (MSB first). */
5266 nstrings = (nstrings << 8) | *cp++;
5267 nstrings = (nstrings << 8) | *cp++;
5268 nstrings = (nstrings << 8) | *cp++;
5270 /* Looping over each string... */
5271 while (nstrings--) {
5272 U_CHAR *string_start;
5273 U_CHAR *endofthiskey;
5277 /* Each string starts with a STRINGDEF structure (str), followed */
5278 /* by the text of the string (string_start) */
5280 /* First skip to a longword boundary */
5281 /* ??? Why a 4-byte boundary? On all machines? */
5282 /* NOTE: This works correctly even if HOST_WIDE_INT
5283 is narrower than a pointer.
5284 Do not try risky measures here to get another type to use!
5285 Do not include stddef.h--it will fail! */
5286 if ((HOST_WIDE_INT) cp & 3)
5287 cp += 4 - ((HOST_WIDE_INT) cp & 3);
5289 /* Now get the string. */
5290 str = (STRINGDEF *) (GENERIC_PTR) cp;
5291 string_start = cp += sizeof (STRINGDEF);
5293 for (; *cp; cp++) /* skip the string */
5296 /* We need to macro expand the string here to ensure that the
5297 proper definition environment is in place. If it were only
5298 expanded when we find out it is needed, macros necessary for
5299 its proper expansion might have had their definitions changed. */
5300 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5301 /* Lineno is already set in the precompiled file */
5302 str->contents = tmpbuf.buf;
5303 str->len = tmpbuf.length;
5305 str->filename = name;
5306 str->output_mark = outbuf.bufp - outbuf.buf;
5309 *stringlist_tailp = str;
5310 stringlist_tailp = &str->chain;
5312 /* Next comes a fourbyte number indicating the number of keys
5315 nkeys = (nkeys << 8) | *cp++;
5316 nkeys = (nkeys << 8) | *cp++;
5317 nkeys = (nkeys << 8) | *cp++;
5319 /* If this number is -1, then the string is mandatory. */
5323 /* Otherwise, for each key, */
5324 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5325 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5328 /* It starts with a KEYDEF structure */
5329 cp += sizeof (KEYDEF);
5331 /* Find the end of the key. At the end of this for loop we
5332 advance CP to the start of the next key using this variable. */
5333 endofthiskey = cp + strlen ((char *) cp);
5336 /* Expand the key, and enter it into the hash table. */
5337 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5338 tmpbuf.bufp = tmpbuf.buf;
5340 while (is_hor_space[*tmpbuf.bufp])
5342 if (!is_idstart[*tmpbuf.bufp]
5343 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5348 hp = lookup (tmpbuf.bufp, -1, -1);
5351 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5353 else if (hp->type == T_PCSTRING) {
5354 kp->chain = hp->value.keydef;
5355 hp->value.keydef = kp;
5361 /* This output_line_directive serves to switch us back to the current
5362 input file in case some of these strings get output (which will
5363 result in line directives for the header file being output). */
5364 output_line_directive (&instack[indepth], op, 0, enter_file);
5367 /* Called from rescan when it hits a key for strings. Mark them all
5368 used and clean up. */
5376 for (kp = hp->value.keydef; kp; kp = kp->chain)
5377 kp->str->writeflag = 1;
5381 /* Write the output, interspersing precompiled strings in their
5382 appropriate places. */
5387 STRINGDEF *next_string;
5388 U_CHAR *cur_buf_loc;
5389 int line_directive_len = 80;
5390 char *line_directive = xmalloc (line_directive_len);
5393 /* In each run through the loop, either cur_buf_loc ==
5394 next_string_loc, in which case we print a series of strings, or
5395 it is less than next_string_loc, in which case we write some of
5397 cur_buf_loc = outbuf.buf;
5398 next_string = stringlist;
5400 while (cur_buf_loc < outbuf.bufp || next_string) {
5402 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5403 if (next_string->writeflag) {
5404 len = 4 * strlen ((char *) next_string->filename) + 32;
5405 while (len > line_directive_len)
5406 line_directive = xrealloc (line_directive,
5407 line_directive_len *= 2);
5408 sprintf (line_directive, "\n# %d ", next_string->lineno);
5409 strcpy (quote_string (line_directive + strlen (line_directive),
5410 (char *) next_string->filename),
5412 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5413 safe_write (fileno (stdout),
5414 (char *) next_string->contents, next_string->len);
5416 next_string = next_string->chain;
5420 ? (next_string->output_mark
5421 - (cur_buf_loc - outbuf.buf))
5422 : outbuf.bufp - cur_buf_loc);
5424 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5428 free (line_directive);
5431 /* Pass a directive through to the output file.
5432 BUF points to the contents of the directive, as a contiguous string.
5433 LIMIT points to the first character past the end of the directive.
5434 KEYWORD is the keyword-table entry for the directive. */
5437 pass_thru_directive (buf, limit, op, keyword)
5438 U_CHAR *buf, *limit;
5440 struct directive *keyword;
5442 register unsigned keyword_length = keyword->length;
5444 check_expand (op, 1 + keyword_length + (limit - buf));
5446 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5447 op->bufp += keyword_length;
5448 if (limit != buf && buf[0] != ' ')
5450 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5451 op->bufp += (limit - buf);
5454 /* Count the line we have just made in the output,
5455 to get in sync properly. */
5460 /* The arglist structure is built by do_define to tell
5461 collect_definition where the argument names begin. That
5462 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5463 would contain pointers to the strings x, y, and z.
5464 Collect_definition would then build a DEFINITION node,
5465 with reflist nodes pointing to the places x, y, and z had
5466 appeared. So the arglist is just convenience data passed
5467 between these two routines. It is not kept around after
5468 the current #define has been processed and entered into the
5472 struct arglist *next;
5479 /* Create a DEFINITION node from a #define directive. Arguments are
5480 as for do_define. */
5483 create_definition (buf, limit, op)
5484 U_CHAR *buf, *limit;
5487 U_CHAR *bp; /* temp ptr into input buffer */
5488 U_CHAR *symname; /* remember where symbol name starts */
5489 int sym_length; /* and how long it is */
5490 int line = instack[indepth].lineno;
5491 char *file = instack[indepth].nominal_fname;
5495 int arglengths = 0; /* Accumulate lengths of arg names
5496 plus number of args. */
5501 while (is_hor_space[*bp])
5504 symname = bp; /* remember where it starts */
5505 sym_length = check_macro_name (bp, "macro");
5508 /* Lossage will occur if identifiers or control keywords are broken
5509 across lines using backslash. This is not the right place to take
5513 struct arglist *arg_ptrs = NULL;
5516 bp++; /* skip '(' */
5517 SKIP_WHITE_SPACE (bp);
5519 /* Loop over macro argument names. */
5520 while (*bp != ')') {
5521 struct arglist *temp;
5523 temp = (struct arglist *) alloca (sizeof (struct arglist));
5525 temp->next = arg_ptrs;
5526 temp->argno = argno++;
5527 temp->rest_args = 0;
5531 pedwarn ("another parameter follows `%s'",
5534 if (!is_idstart[*bp])
5535 pedwarn ("invalid character in macro parameter name");
5537 /* Find the end of the arg name. */
5538 while (is_idchar[*bp]) {
5540 /* do we have a "special" rest-args extension here? */
5541 if (limit - bp > REST_EXTENSION_LENGTH &&
5542 bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5544 temp->rest_args = 1;
5548 temp->length = bp - temp->name;
5550 bp += REST_EXTENSION_LENGTH;
5551 arglengths += temp->length + 2;
5552 SKIP_WHITE_SPACE (bp);
5553 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5554 error ("badly punctuated parameter list in `#define'");
5559 SKIP_WHITE_SPACE (bp);
5560 /* A comma at this point can only be followed by an identifier. */
5561 if (!is_idstart[*bp]) {
5562 error ("badly punctuated parameter list in `#define'");
5567 error ("unterminated parameter list in `#define'");
5571 struct arglist *otemp;
5573 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5574 if (temp->length == otemp->length &&
5575 bcmp (temp->name, otemp->name, temp->length) == 0) {
5576 error ("duplicate argument name `%.*s' in `#define'",
5577 temp->length, temp->name);
5583 ++bp; /* skip paren */
5584 SKIP_WHITE_SPACE (bp);
5585 /* now everything from bp before limit is the definition. */
5586 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5587 defn->rest_args = rest_args;
5589 /* Now set defn->args.argnames to the result of concatenating
5590 the argument names in reverse order
5591 with comma-space between them. */
5592 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5594 struct arglist *temp;
5596 for (temp = arg_ptrs; temp; temp = temp->next) {
5597 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5599 if (temp->next != 0) {
5600 defn->args.argnames[i++] = ',';
5601 defn->args.argnames[i++] = ' ';
5604 defn->args.argnames[i] = 0;
5607 /* Simple expansion or empty definition. */
5611 if (is_hor_space[*bp]) {
5613 SKIP_WHITE_SPACE (bp);
5614 } else if (sym_length) {
5616 case '!': case '"': case '#': case '%': case '&': case '\'':
5617 case ')': case '*': case '+': case ',': case '-': case '.':
5618 case '/': case ':': case ';': case '<': case '=': case '>':
5619 case '?': case '[': case '\\': case ']': case '^': case '{':
5620 case '|': case '}': case '~':
5621 warning ("missing white space after `#define %.*s'",
5622 sym_length, symname);
5626 pedwarn ("missing white space after `#define %.*s'",
5627 sym_length, symname);
5632 /* Now everything from bp before limit is the definition. */
5633 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5634 defn->args.argnames = (U_CHAR *) "";
5640 /* OP is null if this is a predefinition */
5641 defn->predefined = !op;
5643 mdef.symnam = symname;
5644 mdef.symlen = sym_length;
5653 /* Process a #define directive.
5654 BUF points to the contents of the #define directive, as a contiguous string.
5655 LIMIT points to the first character past the end of the definition.
5656 KEYWORD is the keyword-table entry for #define. */
5659 do_define (buf, limit, op, keyword)
5660 U_CHAR *buf, *limit;
5662 struct directive *keyword;
5667 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5668 if (pcp_outfile && op)
5669 pass_thru_directive (buf, limit, op, keyword);
5671 mdef = create_definition (buf, limit, op);
5675 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5679 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5681 /* Redefining a precompiled key is ok. */
5682 if (hp->type == T_PCSTRING)
5684 /* Redefining a macro is ok if the definitions are the same. */
5685 else if (hp->type == T_MACRO)
5686 ok = ! compare_defs (mdef.defn, hp->value.defn);
5687 /* Redefining a constant is ok with -D. */
5688 else if (hp->type == T_CONST)
5689 ok = ! done_initializing;
5690 /* Print the warning if it's not ok. */
5692 /* If we are passing through #define and #undef directives, do
5693 that for this re-definition now. */
5694 if (debug_output && op)
5695 pass_thru_directive (buf, limit, op, keyword);
5697 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5698 if (hp->type == T_MACRO)
5699 pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5700 "this is the location of the previous definition");
5702 /* Replace the old definition. */
5704 hp->value.defn = mdef.defn;
5706 /* If we are passing through #define and #undef directives, do
5707 that for this new definition now. */
5708 if (debug_output && op)
5709 pass_thru_directive (buf, limit, op, keyword);
5710 install (mdef.symnam, mdef.symlen, T_MACRO,
5711 (char *) mdef.defn, hashcode);
5722 /* Check a purported macro name SYMNAME, and yield its length.
5723 USAGE is the kind of name this is intended for. */
5726 check_macro_name (symname, usage)
5733 for (p = symname; is_idchar[*p]; p++)
5735 sym_length = p - symname;
5737 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5738 error ("invalid %s name", usage);
5739 else if (!is_idstart[*symname]
5740 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5741 error ("invalid %s name `%.*s'", usage, sym_length, symname);
5745 /* Return zero if two DEFINITIONs are isomorphic. */
5748 compare_defs (d1, d2)
5749 DEFINITION *d1, *d2;
5751 register struct reflist *a1, *a2;
5752 register U_CHAR *p1 = d1->expansion;
5753 register U_CHAR *p2 = d2->expansion;
5756 if (d1->nargs != d2->nargs)
5758 if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5760 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5761 a1 = a1->next, a2 = a2->next) {
5762 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5763 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5764 || a1->argno != a2->argno
5765 || a1->stringify != a2->stringify
5766 || a1->raw_before != a2->raw_before
5767 || a1->raw_after != a2->raw_after)
5775 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5776 p2, d2->length - (p2 - d2->expansion), 1))
5781 /* Return 1 if two parts of two macro definitions are effectively different.
5782 One of the parts starts at BEG1 and has LEN1 chars;
5783 the other has LEN2 chars at BEG2.
5784 Any sequence of whitespace matches any other sequence of whitespace.
5785 FIRST means these parts are the first of a macro definition;
5786 so ignore leading whitespace entirely.
5787 LAST means these parts are the last of a macro definition;
5788 so ignore trailing whitespace entirely. */
5791 comp_def_part (first, beg1, len1, beg2, len2, last)
5793 U_CHAR *beg1, *beg2;
5797 register U_CHAR *end1 = beg1 + len1;
5798 register U_CHAR *end2 = beg2 + len2;
5800 while (beg1 != end1 && is_space[*beg1]) beg1++;
5801 while (beg2 != end2 && is_space[*beg2]) beg2++;
5804 while (beg1 != end1 && is_space[end1[-1]]) end1--;
5805 while (beg2 != end2 && is_space[end2[-1]]) end2--;
5807 while (beg1 != end1 && beg2 != end2) {
5808 if (is_space[*beg1] && is_space[*beg2]) {
5809 while (beg1 != end1 && is_space[*beg1]) beg1++;
5810 while (beg2 != end2 && is_space[*beg2]) beg2++;
5811 } else if (*beg1 == *beg2) {
5815 return (beg1 != end1) || (beg2 != end2);
5818 /* Read a replacement list for a macro with parameters.
5819 Build the DEFINITION structure.
5820 Reads characters of text starting at BUF until END.
5821 ARGLIST specifies the formal parameters to look for
5822 in the text of the definition; NARGS is the number of args
5823 in that list, or -1 for a macro name that wants no argument list.
5824 MACRONAME is the macro name itself (so we can avoid recursive expansion)
5825 and NAMELEN is its length in characters.
5827 Note that comments, backslash-newlines, and leading white space
5828 have already been deleted from the argument. */
5830 /* If there is no trailing whitespace, a Newline Space is added at the end
5831 to prevent concatenation that would be contrary to the standard. */
5834 collect_expansion (buf, end, nargs, arglist)
5837 struct arglist *arglist;
5840 register U_CHAR *p, *limit, *lastp, *exp_p;
5841 struct reflist *endpat = NULL;
5842 /* Pointer to first nonspace after last ## seen. */
5844 /* Pointer to first nonspace after last single-# seen. */
5845 U_CHAR *stringify = 0;
5846 /* How those tokens were spelled. */
5847 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5848 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5850 int expected_delimiter = '\0';
5852 /* Scan thru the replacement list, ignoring comments and quoted
5853 strings, picking up on the macro calls. It does a linear search
5854 thru the arg list on every potential symbol. Profiling might say
5855 that something smarter should happen. */
5860 /* Find the beginning of the trailing whitespace. */
5863 while (p < limit && is_space[limit[-1]]) limit--;
5865 /* Allocate space for the text in the macro definition.
5866 Each input char may or may not need 1 byte,
5867 so this is an upper bound.
5868 The extra 3 are for invented trailing newline-marker and final null. */
5869 maxsize = (sizeof (DEFINITION)
5871 defn = (DEFINITION *) xcalloc (1, maxsize);
5873 defn->nargs = nargs;
5874 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5879 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5880 error ("`##' at start of macro definition");
5881 p += p[0] == '#' ? 2 : 4;
5884 /* Process the main body of the definition. */
5886 int skipped_arg = 0;
5887 register U_CHAR c = *p++;
5895 if (expected_delimiter != '\0') {
5896 if (c == expected_delimiter)
5897 expected_delimiter = '\0';
5899 expected_delimiter = c;
5903 if (p < limit && expected_delimiter) {
5904 /* In a string, backslash goes through
5905 and makes next char ordinary. */
5911 if (!expected_delimiter && *p == ':') {
5912 /* %: is not a digraph if preceded by an odd number of '<'s. */
5914 while (buf < p0 && p0[-1] == '<')
5917 /* Treat %:%: as ## and %: as #. */
5918 if (p[1] == '%' && p[2] == ':') {
5920 goto sharp_sharp_token;
5931 /* # is ordinary inside a string. */
5932 if (expected_delimiter)
5936 /* ##: concatenate preceding and following tokens. */
5937 /* Take out the first #, discard preceding whitespace. */
5939 while (exp_p > lastp && is_hor_space[exp_p[-1]])
5941 /* Skip the second #. */
5943 concat_sharp_token_type = c;
5944 if (is_hor_space[*p]) {
5945 concat_sharp_token_type = c + 1;
5947 SKIP_WHITE_SPACE (p);
5951 error ("`##' at end of macro definition");
5952 } else if (nargs >= 0) {
5953 /* Single #: stringify following argument ref.
5954 Don't leave the # in the expansion. */
5957 stringify_sharp_token_type = c;
5958 if (is_hor_space[*p]) {
5959 stringify_sharp_token_type = c + 1;
5961 SKIP_WHITE_SPACE (p);
5963 if (! is_idstart[*p] || nargs == 0
5964 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
5965 error ("`#' operator is not followed by a macro argument name");
5972 /* In -traditional mode, recognize arguments inside strings and
5973 and character constants, and ignore special properties of #.
5974 Arguments inside strings are considered "stringified", but no
5975 extra quote marks are supplied. */
5979 if (expected_delimiter != '\0') {
5980 if (c == expected_delimiter)
5981 expected_delimiter = '\0';
5983 expected_delimiter = c;
5987 /* Backslash quotes delimiters and itself, but not macro args. */
5988 if (expected_delimiter != 0 && p < limit
5989 && (*p == expected_delimiter || *p == '\\')) {
5996 if (expected_delimiter != '\0') /* No comments inside strings. */
5999 /* If we find a comment that wasn't removed by handle_directive,
6000 this must be -traditional. So replace the comment with
6003 while (++p < limit) {
6004 if (p[0] == '*' && p[1] == '/') {
6010 /* Mark this as a concatenation-point, as if it had been ##. */
6018 /* Handle the start of a symbol. */
6019 if (is_idchar[c] && nargs > 0) {
6020 U_CHAR *id_beg = p - 1;
6024 while (p != limit && is_idchar[*p]) p++;
6025 id_len = p - id_beg;
6028 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6029 register struct arglist *arg;
6031 for (arg = arglist; arg != NULL; arg = arg->next) {
6032 struct reflist *tpat;
6034 if (arg->name[0] == c
6035 && arg->length == id_len
6036 && bcmp (arg->name, id_beg, id_len) == 0) {
6037 enum sharp_token_type tpat_stringify;
6038 if (expected_delimiter) {
6039 if (warn_stringify) {
6041 warning ("macro argument `%.*s' is stringified.",
6044 warning ("macro arg `%.*s' would be stringified with -traditional.",
6048 /* If ANSI, don't actually substitute inside a string. */
6051 tpat_stringify = SHARP_TOKEN;
6054 = (stringify == id_beg
6055 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6057 /* make a pat node for this arg and append it to the end of
6059 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6062 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6063 tpat->raw_after = NO_SHARP_TOKEN;
6064 tpat->rest_args = arg->rest_args;
6065 tpat->stringify = tpat_stringify;
6068 defn->pattern = tpat;
6070 endpat->next = tpat;
6073 tpat->argno = arg->argno;
6074 tpat->nchars = exp_p - lastp;
6076 register U_CHAR *p1 = p;
6077 SKIP_WHITE_SPACE (p1);
6080 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6081 tpat->raw_after = p1[0] + (p != p1);
6083 lastp = exp_p; /* place to start copying from next time */
6090 /* If this was not a macro arg, copy it into the expansion. */
6091 if (! skipped_arg) {
6092 register U_CHAR *lim1 = p;
6096 if (stringify == id_beg)
6097 error ("`#' operator should be followed by a macro argument name");
6102 if (!traditional && expected_delimiter == 0) {
6103 /* If ANSI, put in a newline-space marker to prevent token pasting.
6104 But not if "inside a string" (which in ANSI mode happens only for
6112 defn->length = exp_p - defn->expansion;
6114 /* Crash now if we overrun the allocated size. */
6115 if (defn->length + 1 > maxsize)
6119 /* This isn't worth the time it takes. */
6120 /* give back excess storage */
6121 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6128 do_assert (buf, limit, op, keyword)
6129 U_CHAR *buf, *limit;
6131 struct directive *keyword;
6133 U_CHAR *bp; /* temp ptr into input buffer */
6134 U_CHAR *symname; /* remember where symbol name starts */
6135 int sym_length; /* and how long it is */
6136 struct arglist *tokens = NULL;
6138 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6139 pedwarn ("ANSI C does not allow `#assert'");
6143 while (is_hor_space[*bp])
6146 symname = bp; /* remember where it starts */
6147 sym_length = check_macro_name (bp, "assertion");
6149 /* #define doesn't do this, but we should. */
6150 SKIP_WHITE_SPACE (bp);
6152 /* Lossage will occur if identifiers or control tokens are broken
6153 across lines using backslash. This is not the right place to take
6157 error ("missing token-sequence in `#assert'");
6164 bp++; /* skip '(' */
6165 SKIP_WHITE_SPACE (bp);
6167 tokens = read_token_list (&bp, limit, &error_flag);
6171 error ("empty token-sequence in `#assert'");
6175 ++bp; /* skip paren */
6176 SKIP_WHITE_SPACE (bp);
6179 /* If this name isn't already an assertion name, make it one.
6180 Error if it was already in use in some other way. */
6183 ASSERTION_HASHNODE *hp;
6184 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6185 struct tokenlist_list *value
6186 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6188 hp = assertion_lookup (symname, sym_length, hashcode);
6190 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6191 error ("`defined' redefined as assertion");
6192 hp = assertion_install (symname, sym_length, hashcode);
6195 /* Add the spec'd token-sequence to the list of such. */
6196 value->tokens = tokens;
6197 value->next = hp->value;
6205 do_unassert (buf, limit, op, keyword)
6206 U_CHAR *buf, *limit;
6208 struct directive *keyword;
6210 U_CHAR *bp; /* temp ptr into input buffer */
6211 U_CHAR *symname; /* remember where symbol name starts */
6212 int sym_length; /* and how long it is */
6214 struct arglist *tokens = NULL;
6215 int tokens_specified = 0;
6217 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6218 pedwarn ("ANSI C does not allow `#unassert'");
6222 while (is_hor_space[*bp])
6225 symname = bp; /* remember where it starts */
6226 sym_length = check_macro_name (bp, "assertion");
6228 /* #define doesn't do this, but we should. */
6229 SKIP_WHITE_SPACE (bp);
6231 /* Lossage will occur if identifiers or control tokens are broken
6232 across lines using backslash. This is not the right place to take
6238 bp++; /* skip '(' */
6239 SKIP_WHITE_SPACE (bp);
6241 tokens = read_token_list (&bp, limit, &error_flag);
6245 error ("empty token list in `#unassert'");
6249 tokens_specified = 1;
6251 ++bp; /* skip paren */
6252 SKIP_WHITE_SPACE (bp);
6256 ASSERTION_HASHNODE *hp;
6257 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6258 struct tokenlist_list *tail, *prev;
6260 hp = assertion_lookup (symname, sym_length, hashcode);
6264 /* If no token list was specified, then eliminate this assertion
6266 if (! tokens_specified) {
6267 struct tokenlist_list *next;
6268 for (tail = hp->value; tail; tail = next) {
6270 free_token_list (tail->tokens);
6273 delete_assertion (hp);
6275 /* If a list of tokens was given, then delete any matching list. */
6280 struct tokenlist_list *next = tail->next;
6281 if (compare_token_lists (tail->tokens, tokens)) {
6285 hp->value = tail->next;
6286 free_token_list (tail->tokens);
6299 /* Test whether there is an assertion named NAME
6300 and optionally whether it has an asserted token list TOKENS.
6301 NAME is not null terminated; its length is SYM_LENGTH.
6302 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6305 check_assertion (name, sym_length, tokens_specified, tokens)
6308 int tokens_specified;
6309 struct arglist *tokens;
6311 ASSERTION_HASHNODE *hp;
6312 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6314 if (pedantic && !instack[indepth].system_header_p)
6315 pedwarn ("ANSI C does not allow testing assertions");
6317 hp = assertion_lookup (name, sym_length, hashcode);
6319 /* It is not an assertion; just return false. */
6322 /* If no token list was specified, then value is 1. */
6323 if (! tokens_specified)
6327 struct tokenlist_list *tail;
6331 /* If a list of tokens was given,
6332 then succeed if the assertion records a matching list. */
6335 if (compare_token_lists (tail->tokens, tokens))
6340 /* Fail if the assertion has no matching list. */
6345 /* Compare two lists of tokens for equality including order of tokens. */
6348 compare_token_lists (l1, l2)
6349 struct arglist *l1, *l2;
6352 if (l1->length != l2->length)
6354 if (bcmp (l1->name, l2->name, l1->length))
6360 /* Succeed if both lists end at the same time. */
6364 /* Read a space-separated list of tokens ending in a close parenthesis.
6365 Return a list of strings, in the order they were written.
6366 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6367 Parse the text starting at *BPP, and update *BPP.
6368 Don't parse beyond LIMIT. */
6370 static struct arglist *
6371 read_token_list (bpp, limit, error_flag)
6376 struct arglist *token_ptrs = 0;
6382 /* Loop over the assertion value tokens. */
6384 struct arglist *temp;
6388 /* Find the end of the token. */
6392 } else if (*bp == ')') {
6397 } else if (*bp == '"' || *bp == '\'')
6398 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6400 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6401 && *bp != '"' && *bp != '\'' && bp != limit)
6404 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6405 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6406 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6407 temp->name[bp - beg] = 0;
6408 temp->next = token_ptrs;
6410 temp->length = bp - beg;
6412 SKIP_WHITE_SPACE (bp);
6415 error ("unterminated token sequence in `#assert' or `#unassert'");
6422 /* We accumulated the names in reverse order.
6423 Now reverse them to get the proper order. */
6425 register struct arglist *prev = 0, *this, *next;
6426 for (this = token_ptrs; this; this = next) {
6436 free_token_list (tokens)
6437 struct arglist *tokens;
6440 struct arglist *next = tokens->next;
6441 free (tokens->name);
6447 /* Install a name in the assertion hash table.
6449 If LEN is >= 0, it is the length of the name.
6450 Otherwise, compute the length by scanning the entire name.
6452 If HASH is >= 0, it is the precomputed hash code.
6453 Otherwise, compute the hash code. */
6455 static ASSERTION_HASHNODE *
6456 assertion_install (name, len, hash)
6461 register ASSERTION_HASHNODE *hp;
6462 register int i, bucket;
6463 register U_CHAR *p, *q;
6465 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6466 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6468 hp->bucket_hdr = &assertion_hashtab[bucket];
6469 hp->next = assertion_hashtab[bucket];
6470 assertion_hashtab[bucket] = hp;
6472 if (hp->next != NULL)
6473 hp->next->prev = hp;
6476 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6479 for (i = 0; i < len; i++)
6485 /* Find the most recent hash node for name name (ending with first
6486 non-identifier char) installed by install
6488 If LEN is >= 0, it is the length of the name.
6489 Otherwise, compute the length by scanning the entire name.
6491 If HASH is >= 0, it is the precomputed hash code.
6492 Otherwise, compute the hash code. */
6494 static ASSERTION_HASHNODE *
6495 assertion_lookup (name, len, hash)
6500 register ASSERTION_HASHNODE *bucket;
6502 bucket = assertion_hashtab[hash];
6504 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6506 bucket = bucket->next;
6512 delete_assertion (hp)
6513 ASSERTION_HASHNODE *hp;
6516 if (hp->prev != NULL)
6517 hp->prev->next = hp->next;
6518 if (hp->next != NULL)
6519 hp->next->prev = hp->prev;
6521 /* Make sure that the bucket chain header that the deleted guy was
6522 on points to the right thing afterwards. */
6523 if (hp == *hp->bucket_hdr)
6524 *hp->bucket_hdr = hp->next;
6530 * interpret #line directive. Remembers previously seen fnames
6531 * in its very own hash table.
6533 #define FNAME_HASHSIZE 37
6536 do_line (buf, limit, op, keyword)
6537 U_CHAR *buf, *limit;
6539 struct directive *keyword;
6541 register U_CHAR *bp;
6542 FILE_BUF *ip = &instack[indepth];
6545 enum file_change_code file_change = same_file;
6547 /* Expand any macros. */
6548 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6550 /* Point to macroexpanded line, which is null-terminated now. */
6552 SKIP_WHITE_SPACE (bp);
6554 if (!isdigit (*bp)) {
6555 error ("invalid format `#line' directive");
6559 /* The Newline at the end of this line remains to be processed.
6560 To put the next line at the specified line number,
6561 we must store a line number now that is one less. */
6562 new_lineno = atoi ((char *) bp) - 1;
6564 /* NEW_LINENO is one less than the actual line number here. */
6565 if (pedantic && new_lineno < 0)
6566 pedwarn ("line number out of range in `#line' directive");
6568 /* skip over the line number. */
6569 while (isdigit (*bp))
6572 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6573 if (*bp && !is_space[*bp]) {
6574 error ("invalid format `#line' directive");
6579 SKIP_WHITE_SPACE (bp);
6582 static HASHNODE *fname_table[FNAME_HASHSIZE];
6583 HASHNODE *hp, **hash_bucket;
6589 /* Turn the file name, which is a character string literal,
6590 into a null-terminated string. Do this in place. */
6593 switch ((*p++ = *bp++)) {
6595 error ("invalid format `#line' directive");
6600 char *bpc = (char *) bp;
6601 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6602 bp = (U_CHAR *) bpc;
6615 fname_length = p - fname;
6617 SKIP_WHITE_SPACE (bp);
6620 pedwarn ("garbage at end of `#line' directive");
6622 file_change = enter_file;
6623 else if (*bp == '2')
6624 file_change = leave_file;
6625 else if (*bp == '3')
6626 ip->system_header_p = 1;
6627 else if (*bp == '4')
6628 ip->system_header_p = 2;
6630 error ("invalid format `#line' directive");
6635 SKIP_WHITE_SPACE (bp);
6637 ip->system_header_p = 1;
6639 SKIP_WHITE_SPACE (bp);
6642 ip->system_header_p = 2;
6644 SKIP_WHITE_SPACE (bp);
6647 error ("invalid format `#line' directive");
6653 &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6654 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6655 if (hp->length == fname_length &&
6656 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6657 ip->nominal_fname = hp->value.cpval;
6661 /* Didn't find it; cons up a new one. */
6662 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6663 hp->next = *hash_bucket;
6666 hp->length = fname_length;
6667 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6668 bcopy (fname, hp->value.cpval, fname_length);
6671 error ("invalid format `#line' directive");
6675 ip->lineno = new_lineno;
6676 output_line_directive (ip, op, 0, file_change);
6677 check_expand (op, ip->length - (ip->bufp - ip->buf));
6681 /* Remove the definition of a symbol from the symbol table.
6682 according to un*x /lib/cpp, it is not an error to undef
6683 something that has no definitions, so it isn't one here either. */
6686 do_undef (buf, limit, op, keyword)
6687 U_CHAR *buf, *limit;
6689 struct directive *keyword;
6693 U_CHAR *orig_buf = buf;
6695 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
6696 if (pcp_outfile && op)
6697 pass_thru_directive (buf, limit, op, keyword);
6699 SKIP_WHITE_SPACE (buf);
6700 sym_length = check_macro_name (buf, "macro");
6702 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6703 /* If we are generating additional info for debugging (with -g) we
6704 need to pass through all effective #undef directives. */
6705 if (debug_output && op)
6706 pass_thru_directive (orig_buf, limit, op, keyword);
6707 if (hp->type != T_MACRO)
6708 warning ("undefining `%s'", hp->name);
6714 SKIP_WHITE_SPACE (buf);
6716 pedwarn ("garbage after `#undef' directive");
6721 /* Report an error detected by the program we are processing.
6722 Use the text of the line in the error message.
6723 (We use error because it prints the filename & line#.) */
6726 do_error (buf, limit, op, keyword)
6727 U_CHAR *buf, *limit;
6729 struct directive *keyword;
6731 int length = limit - buf;
6732 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6733 bcopy ((char *) buf, (char *) copy, length);
6735 SKIP_WHITE_SPACE (copy);
6736 error ("#error %s", copy);
6740 /* Report a warning detected by the program we are processing.
6741 Use the text of the line in the warning message, then continue.
6742 (We use error because it prints the filename & line#.) */
6745 do_warning (buf, limit, op, keyword)
6746 U_CHAR *buf, *limit;
6748 struct directive *keyword;
6750 int length = limit - buf;
6751 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6752 bcopy ((char *) buf, (char *) copy, length);
6754 SKIP_WHITE_SPACE (copy);
6755 warning ("#warning %s", copy);
6759 /* Remember the name of the current file being read from so that we can
6760 avoid ever including it again. */
6767 for (i = indepth; i >= 0; i--)
6768 if (instack[i].inc) {
6769 record_control_macro (instack[i].inc, (U_CHAR *) "");
6774 /* #ident has already been copied to the output file, so just ignore it. */
6777 do_ident (buf, limit, op, keyword)
6778 U_CHAR *buf, *limit;
6780 struct directive *keyword;
6785 /* Allow #ident in system headers, since that's not user's fault. */
6786 if (pedantic && !instack[indepth].system_header_p)
6787 pedwarn ("ANSI C does not allow `#ident'");
6789 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6790 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6791 bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6792 limit = buf + (trybuf.bufp - trybuf.buf);
6793 len = (limit - buf);
6796 /* Output directive name. */
6797 check_expand (op, 7);
6798 bcopy ("#ident ", (char *) op->bufp, 7);
6801 /* Output the expanded argument line. */
6802 check_expand (op, len);
6803 bcopy ((char *) buf, (char *) op->bufp, len);
6809 /* #pragma and its argument line have already been copied to the output file.
6810 Just check for some recognized pragmas that need validation here. */
6813 do_pragma (buf, limit, op, keyword)
6814 U_CHAR *buf, *limit;
6816 struct directive *keyword;
6818 SKIP_WHITE_SPACE (buf);
6819 if (!strncmp ((char *) buf, "once", 4)) {
6820 /* Allow #pragma once in system headers, since that's not the user's
6822 if (!instack[indepth].system_header_p)
6823 warning ("`#pragma once' is obsolete");
6827 if (!strncmp ((char *) buf, "implementation", 14)) {
6828 /* Be quiet about `#pragma implementation' for a file only if it hasn't
6829 been included yet. */
6832 U_CHAR *p = buf + 14, *fname;
6833 SKIP_WHITE_SPACE (p);
6834 if (*p == '\n' || *p != '\"')
6838 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6841 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6842 struct include_file *inc;
6843 for (inc = include_hashtab[h]; inc; inc = inc->next) {
6844 if (!strcmp (base_name (inc->fname), (char *) fname)) {
6845 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6855 /* This was a fun hack, but #pragma seems to start to be useful.
6856 By failing to recognize it, we pass it through unchanged to cc1. */
6858 /* The behavior of the #pragma directive is implementation defined.
6859 this implementation defines it as follows. */
6865 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6868 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6870 execl ("/usr/games/hack", "#pragma", 0);
6871 execl ("/usr/games/rogue", "#pragma", 0);
6872 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6873 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6875 fatal ("You are in a maze of twisty compiler features, all different");
6879 #ifdef SCCS_DIRECTIVE
6881 /* Just ignore #sccs, on systems where we define it at all. */
6884 do_sccs (buf, limit, op, keyword)
6885 U_CHAR *buf, *limit;
6887 struct directive *keyword;
6890 pedwarn ("ANSI C does not allow `#sccs'");
6894 #endif /* defined (SCCS_DIRECTIVE) */
6896 /* Handle #if directive by
6897 1) inserting special `defined' keyword into the hash table
6898 that gets turned into 0 or 1 by special_symbol (thus,
6899 if the luser has a symbol called `defined' already, it won't
6900 work inside the #if directive)
6901 2) rescan the input into a temporary output buffer
6902 3) pass the output buffer to the yacc parser and collect a value
6903 4) clean up the mess left from steps 1 and 2.
6904 5) call conditional_skip to skip til the next #endif (etc.),
6905 or not, depending on the value from step 3. */
6908 do_if (buf, limit, op, keyword)
6909 U_CHAR *buf, *limit;
6911 struct directive *keyword;
6913 HOST_WIDE_INT value;
6914 FILE_BUF *ip = &instack[indepth];
6916 value = eval_if_expression (buf, limit - buf);
6917 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6921 /* Handle a #elif directive by not changing if_stack either.
6922 see the comment above do_else. */
6925 do_elif (buf, limit, op, keyword)
6926 U_CHAR *buf, *limit;
6928 struct directive *keyword;
6930 HOST_WIDE_INT value;
6931 FILE_BUF *ip = &instack[indepth];
6933 if (if_stack == instack[indepth].if_stack) {
6934 error ("`#elif' not within a conditional");
6937 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6938 error ("`#elif' after `#else'");
6939 fprintf (stderr, " (matches line %d", if_stack->lineno);
6940 if (if_stack->fname != NULL && ip->fname != NULL &&
6941 strcmp (if_stack->fname, ip->nominal_fname) != 0)
6942 fprintf (stderr, ", file %s", if_stack->fname);
6943 fprintf (stderr, ")\n");
6945 if_stack->type = T_ELIF;
6948 if (if_stack->if_succeeded)
6949 skip_if_group (ip, 0, op);
6951 value = eval_if_expression (buf, limit - buf);
6953 skip_if_group (ip, 0, op);
6955 ++if_stack->if_succeeded; /* continue processing input */
6956 output_line_directive (ip, op, 1, same_file);
6962 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
6963 result as a C expression and return the value as an int. */
6965 static HOST_WIDE_INT
6966 eval_if_expression (buf, length)
6971 HASHNODE *save_defined;
6972 HOST_WIDE_INT value;
6974 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6977 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6979 delete_macro (save_defined); /* clean up special symbol */
6981 temp_obuf.buf[temp_obuf.length] = '\n';
6982 value = parse_c_expression ((char *) temp_obuf.buf);
6984 free (temp_obuf.buf);
6989 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
6990 or don't skip to the #endif/#else/#elif depending on what directive
6991 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 (! traditional) {
7049 if (isdigit (buf[0]))
7050 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7051 else if (end != limit)
7052 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7055 hp = lookup (buf, end-buf, -1);
7058 /* Output a precondition for this macro. */
7060 (hp->type == T_CONST
7061 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7062 fprintf (pcp_outfile, "#define %s\n", hp->name);
7065 fprintf (pcp_outfile, "#undef ");
7066 while (is_idchar[*cp]) /* Ick! */
7067 fputc (*cp++, pcp_outfile);
7068 putc ('\n', pcp_outfile);
7072 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7073 if (start_of_file && !skip) {
7074 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7075 bcopy ((char *) buf, (char *) control_macro, end - buf);
7076 control_macro[end - buf] = 0;
7080 conditional_skip (ip, skip, T_IF, control_macro, op);
7084 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7085 If this is a #ifndef starting at the beginning of a file,
7086 CONTROL_MACRO is the macro name tested by the #ifndef.
7087 Otherwise, CONTROL_MACRO is 0. */
7090 conditional_skip (ip, skip, type, control_macro, op)
7093 enum node_type type;
7094 U_CHAR *control_macro;
7097 IF_STACK_FRAME *temp;
7099 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7100 temp->fname = ip->nominal_fname;
7101 temp->lineno = ip->lineno;
7102 temp->next = if_stack;
7103 temp->control_macro = control_macro;
7106 if_stack->type = type;
7109 skip_if_group (ip, 0, op);
7112 ++if_stack->if_succeeded;
7113 output_line_directive (ip, &outbuf, 1, same_file);
7117 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7118 Leaves input ptr at the sharp sign found.
7119 If ANY is nonzero, return at next directive of any sort. */
7122 skip_if_group (ip, any, op)
7127 register U_CHAR *bp = ip->bufp, *cp;
7128 register U_CHAR *endb = ip->buf + ip->length;
7129 struct directive *kt;
7130 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7131 U_CHAR *beg_of_line = bp;
7132 register int ident_length;
7133 U_CHAR *ident, *after_ident;
7134 /* Save info about where the group starts. */
7135 U_CHAR *beg_of_group = bp;
7136 int beg_lineno = ip->lineno;
7138 if (output_conditionals && op != 0) {
7139 char *ptr = "#failed\n";
7140 int len = strlen (ptr);
7142 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7147 check_expand (op, len);
7148 bcopy (ptr, (char *) op->bufp, len);
7151 output_line_directive (ip, op, 1, 0);
7156 case '/': /* possible comment */
7157 if (*bp == '\\' && bp[1] == '\n')
7160 || (cplusplus_comments && *bp == '/')) {
7162 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7167 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7168 NULL_PTR, NULL_PTR);
7171 /* Char after backslash loses its special meaning. */
7174 ++ip->lineno; /* But do update the line-count. */
7183 if (beg_of_line == 0 || traditional)
7186 while (bp[0] == '\\' && bp[1] == '\n')
7192 /* # keyword: a # must be first nonblank char on the line */
7193 if (beg_of_line == 0)
7197 /* Scan from start of line, skipping whitespace, comments
7198 and backslash-newlines, and see if we reach this #.
7199 If not, this # is not special. */
7201 /* If -traditional, require # to be at beginning of line. */
7204 if (is_hor_space[*bp])
7206 else if (*bp == '\\' && bp[1] == '\n')
7208 else if (*bp == '/' && bp[1] == '*') {
7210 while (!(*bp == '*' && bp[1] == '/'))
7214 /* There is no point in trying to deal with C++ // comments here,
7215 because if there is one, then this # must be part of the
7216 comment and we would never reach here. */
7220 if (bp != ip->bufp) {
7221 bp = ip->bufp + 1; /* Reset bp to after the #. */
7225 bp = ip->bufp + 1; /* Point after the '#' */
7226 if (ip->bufp[0] == '%') {
7227 /* Skip past the ':' again. */
7228 while (*bp == '\\') {
7235 /* Skip whitespace and \-newline. */
7237 if (is_hor_space[*bp])
7239 else if (*bp == '\\' && bp[1] == '\n')
7241 else if (*bp == '/') {
7243 for (bp += 2; ; bp++) {
7246 else if (*bp == '*') {
7247 if (bp[-1] == '/' && warn_comments)
7248 warning ("`/*' within comment");
7254 } else if (bp[1] == '/' && cplusplus_comments) {
7255 for (bp += 2; ; bp++) {
7260 warning ("multiline `//' comment");
7272 /* Now find end of directive name.
7273 If we encounter a backslash-newline, exchange it with any following
7274 symbol-constituents so that we end up with a contiguous name. */
7280 if (*bp == '\\' && bp[1] == '\n')
7281 name_newline_fix (bp);
7287 ident_length = bp - cp;
7291 /* A line of just `#' becomes blank. */
7293 if (ident_length == 0 && *after_ident == '\n') {
7297 if (ident_length == 0 || !is_idstart[*ident]) {
7299 while (is_idchar[*p]) {
7300 if (*p < '0' || *p > '9')
7304 /* Handle # followed by a line number. */
7305 if (p != ident && !is_idchar[*p]) {
7307 pedwarn ("`#' followed by integer");
7311 /* Avoid error for `###' and similar cases unless -pedantic. */
7313 while (*p == '#' || is_hor_space[*p]) p++;
7315 if (pedantic && !lang_asm)
7316 pedwarn ("invalid preprocessing directive");
7321 if (!lang_asm && pedantic)
7322 pedwarn ("invalid preprocessing directive name");
7326 for (kt = directive_table; kt->length >= 0; kt++) {
7327 IF_STACK_FRAME *temp;
7328 if (ident_length == kt->length
7329 && bcmp (cp, kt->name, kt->length) == 0) {
7330 /* If we are asked to return on next directive, do so now. */
7338 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7339 temp->next = if_stack;
7341 temp->lineno = ip->lineno;
7342 temp->fname = ip->nominal_fname;
7343 temp->type = kt->type;
7347 if (pedantic && if_stack != save_if_stack)
7348 validate_else (bp, endb);
7350 if (if_stack == instack[indepth].if_stack) {
7351 error ("`#%s' not within a conditional", kt->name);
7354 else if (if_stack == save_if_stack)
7355 goto done; /* found what we came for */
7357 if (kt->type != T_ENDIF) {
7358 if (if_stack->type == T_ELSE)
7359 error ("`#else' or `#elif' after `#else'");
7360 if_stack->type = kt->type;
7365 if_stack = if_stack->next;
7375 /* Don't let erroneous code go by. */
7376 if (kt->length < 0 && !lang_asm && pedantic)
7377 pedwarn ("invalid preprocessing directive name");
7382 /* after this returns, rescan will exit because ip->bufp
7383 now points to the end of the buffer.
7384 rescan is responsible for the error message also. */
7387 if (output_conditionals && op != 0) {
7388 char *ptr = "#endfailed\n";
7389 int len = strlen (ptr);
7391 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7396 check_expand (op, beg_of_line - beg_of_group);
7397 bcopy ((char *) beg_of_group, (char *) op->bufp,
7398 beg_of_line - beg_of_group);
7399 op->bufp += beg_of_line - beg_of_group;
7400 op->lineno += ip->lineno - beg_lineno;
7401 check_expand (op, len);
7402 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. */
7414 do_else (buf, limit, op, keyword)
7415 U_CHAR *buf, *limit;
7417 struct directive *keyword;
7419 FILE_BUF *ip = &instack[indepth];
7422 SKIP_WHITE_SPACE (buf);
7424 pedwarn ("text following `#else' violates ANSI standard");
7427 if (if_stack == instack[indepth].if_stack) {
7428 error ("`#else' not within a conditional");
7431 /* #ifndef can't have its special treatment for containing the whole file
7432 if it has a #else clause. */
7433 if_stack->control_macro = 0;
7435 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7436 error ("`#else' after `#else'");
7437 fprintf (stderr, " (matches line %d", if_stack->lineno);
7438 if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7439 fprintf (stderr, ", file %s", if_stack->fname);
7440 fprintf (stderr, ")\n");
7442 if_stack->type = T_ELSE;
7445 if (if_stack->if_succeeded)
7446 skip_if_group (ip, 0, op);
7448 ++if_stack->if_succeeded; /* continue processing input */
7449 output_line_directive (ip, op, 1, same_file);
7454 /* Unstack after #endif directive. */
7457 do_endif (buf, limit, op, keyword)
7458 U_CHAR *buf, *limit;
7460 struct directive *keyword;
7463 SKIP_WHITE_SPACE (buf);
7465 pedwarn ("text following `#endif' violates ANSI standard");
7468 if (if_stack == instack[indepth].if_stack)
7469 error ("unbalanced `#endif'");
7471 IF_STACK_FRAME *temp = if_stack;
7472 if_stack = if_stack->next;
7473 if (temp->control_macro != 0) {
7474 /* This #endif matched a #ifndef at the start of the file.
7475 See if it is at the end of the file. */
7476 FILE_BUF *ip = &instack[indepth];
7477 U_CHAR *p = ip->bufp;
7478 U_CHAR *ep = ip->buf + ip->length;
7484 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7485 /* Skip this comment. */
7487 U_CHAR *save_bufp = ip->bufp;
7489 p = skip_to_end_of_comment (ip, &junk, 1);
7490 ip->bufp = save_bufp;
7495 /* If we get here, this #endif ends a #ifndef
7496 that contains all of the file (aside from whitespace).
7497 Arrange not to include the file again
7498 if the macro that was tested is defined.
7500 Do not do this for the top-level file in a -include or any
7501 file in a -imacros. */
7503 && ! (indepth == 1 && no_record_file)
7504 && ! (no_record_file && no_output))
7505 record_control_macro (ip->inc, temp->control_macro);
7509 output_line_directive (&instack[indepth], op, 1, same_file);
7514 /* When an #else or #endif is found while skipping failed conditional,
7515 if -pedantic was specified, this is called to warn about text after
7516 the directive name. P points to the first char after the directive
7520 validate_else (p, limit)
7522 register U_CHAR *limit;
7524 /* Advance P over whitespace and comments. */
7526 while (*p == '\\' && p[1] == '\n')
7528 if (is_hor_space[*p])
7530 else if (*p == '/') {
7531 while (p[1] == '\\' && p[2] == '\n')
7534 /* Don't bother warning about unterminated comments
7535 since that will happen later. Just be sure to exit. */
7536 for (p += 2; ; p++) {
7540 while (p[1] == '\\' && p[2] == '\n')
7549 else if (cplusplus_comments && p[1] == '/')
7555 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7558 /* Skip a comment, assuming the input ptr immediately follows the
7559 initial slash-star. Bump *LINE_COUNTER for each newline.
7560 (The canonical line counter is &ip->lineno.)
7561 Don't use this routine (or the next one) if bumping the line
7562 counter is not sufficient to deal with newlines in the string.
7564 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7565 This feature is useful when processing a comment that is going to
7566 be processed or was processed at another point in the preprocessor,
7567 to avoid a duplicate warning. Likewise for unterminated comment
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++) {
7593 if (!nowarn && warn_comments)
7594 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");
7646 /* Skip over a quoted string. BP points to the opening quote.
7647 Returns a pointer after the closing quote. Don't go past LIMIT.
7648 START_LINE is the line number of the starting point (but it need
7649 not be valid if the starting point is inside a macro expansion).
7651 The input stack state is not changed.
7653 If COUNT_NEWLINES is nonzero, it points to an int to increment
7654 for each newline passed.
7656 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7657 if we pass a backslash-newline.
7659 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
7662 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7663 register U_CHAR *bp;
7664 register U_CHAR *limit;
7666 int *count_newlines;
7667 int *backslash_newlines_p;
7670 register U_CHAR c, match;
7675 error_with_line (line_for_error (start_line),
7676 "unterminated string or character constant");
7677 error_with_line (multiline_string_line,
7678 "possible real start of unterminated constant");
7679 multiline_string_line = 0;
7686 while (*bp == '\\' && bp[1] == '\n') {
7687 if (backslash_newlines_p)
7688 *backslash_newlines_p = 1;
7693 if (*bp == '\n' && count_newlines) {
7694 if (backslash_newlines_p)
7695 *backslash_newlines_p = 1;
7699 } else if (c == '\n') {
7701 /* Unterminated strings and character constants are 'valid'. */
7702 bp--; /* Don't consume the newline. */
7707 if (match == '\'') {
7708 error_with_line (line_for_error (start_line),
7709 "unterminated string or character constant");
7715 /* If not traditional, then allow newlines inside strings. */
7718 if (multiline_string_line == 0) {
7720 pedwarn_with_line (line_for_error (start_line),
7721 "string constant runs past end of line");
7722 multiline_string_line = start_line;
7724 } else if (c == match)
7730 /* Place into DST a quoted string representing the string SRC.
7731 Return the address of DST's terminating null. */
7734 quote_string (dst, src)
7741 switch ((c = *src++))
7748 sprintf (dst, "\\%03o", c);
7766 /* Skip across a group of balanced parens, starting from IP->bufp.
7767 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
7769 This does not handle newlines, because it's used for the arg of #if,
7770 where there aren't any newlines. Also, backslash-newline can't appear. */
7773 skip_paren_group (ip)
7774 register FILE_BUF *ip;
7776 U_CHAR *limit = ip->buf + ip->length;
7777 U_CHAR *p = ip->bufp;
7779 int lines_dummy = 0;
7781 while (p != limit) {
7791 return ip->bufp = p;
7797 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7805 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7807 return ip->bufp = p;
7817 /* Write out a #line directive, for instance, after an #include file.
7818 If CONDITIONAL is nonzero, we can omit the #line if it would
7819 appear to be a no-op, and we can output a few newlines instead
7820 if we want to increase the line number by a small amount.
7821 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
7824 output_line_directive (ip, op, conditional, file_change)
7827 enum file_change_code file_change;
7830 char *line_directive_buf, *line_end;
7832 if (no_line_directives
7833 || ip->fname == NULL
7835 op->lineno = ip->lineno;
7840 if (ip->lineno == op->lineno)
7843 /* If the inherited line number is a little too small,
7844 output some newlines instead of a #line directive. */
7845 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7846 check_expand (op, 10);
7847 while (ip->lineno > op->lineno) {
7855 /* Output a positive line number if possible. */
7856 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7857 && *ip->bufp == '\n') {
7862 line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7863 sprintf (line_directive_buf, "# %d ", ip->lineno);
7864 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7866 if (file_change != same_file) {
7868 *line_end++ = file_change == enter_file ? '1' : '2';
7870 /* Tell cc1 if following text comes from a system header file. */
7871 if (ip->system_header_p) {
7875 #ifndef NO_IMPLICIT_EXTERN_C
7876 /* Tell cc1plus if following text should be treated as C. */
7877 if (ip->system_header_p == 2 && cplusplus) {
7883 len = line_end - line_directive_buf;
7884 check_expand (op, len + 1);
7885 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7887 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7889 op->lineno = ip->lineno;
7892 /* This structure represents one parsed argument in a macro call.
7893 `raw' points to the argument text as written (`raw_length' is its length).
7894 `expanded' points to the argument's macro-expansion
7895 (its length is `expand_length').
7896 `stringified_length' is the length the argument would have
7898 `use_count' is the number of times this macro arg is substituted
7899 into the macro. If the actual use count exceeds 10,
7900 the value stored is 10.
7901 `free1' and `free2', if nonzero, point to blocks to be freed
7902 when the macro argument data is no longer needed. */
7905 U_CHAR *raw, *expanded;
7906 int raw_length, expand_length;
7907 int stringified_length;
7908 U_CHAR *free1, *free2;
7913 /* Expand a macro call.
7914 HP points to the symbol that is the macro being called.
7915 Put the result of expansion onto the input stack
7916 so that subsequent input by our caller will use it.
7918 If macro wants arguments, caller has already verified that
7919 an argument list follows; arguments come from the input stack. */
7922 macroexpand (hp, op)
7927 DEFINITION *defn = hp->value.defn;
7928 register U_CHAR *xbuf;
7930 int start_line = instack[indepth].lineno;
7931 int rest_args, rest_zero;
7933 CHECK_DEPTH (return;);
7935 /* it might not actually be a macro. */
7936 if (hp->type != T_MACRO) {
7937 special_symbol (hp, op);
7941 /* This macro is being used inside a #if, which means it must be */
7942 /* recorded as a precondition. */
7943 if (pcp_inside_if && pcp_outfile && defn->predefined)
7944 dump_single_macro (hp, pcp_outfile);
7946 nargs = defn->nargs;
7950 struct argdata *args;
7951 char *parse_error = 0;
7953 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7955 for (i = 0; i < nargs; i++) {
7956 args[i].raw = (U_CHAR *) "";
7957 args[i].expanded = 0;
7958 args[i].raw_length = args[i].expand_length
7959 = args[i].stringified_length = 0;
7960 args[i].free1 = args[i].free2 = 0;
7961 args[i].use_count = 0;
7964 /* Parse all the macro args that are supplied. I counts them.
7965 The first NARGS args are stored in ARGS.
7966 The rest are discarded.
7967 If rest_args is set then we assume macarg absorbed the rest of the args.
7972 /* Discard the open-parenthesis or comma before the next arg. */
7973 ++instack[indepth].bufp;
7976 if (i < nargs || (nargs == 0 && i == 0)) {
7977 /* If we are working on last arg which absorbs rest of args... */
7978 if (i == nargs - 1 && defn->rest_args)
7980 parse_error = macarg (&args[i], rest_args);
7983 parse_error = macarg (NULL_PTR, 0);
7985 error_with_line (line_for_error (start_line), parse_error);
7989 } while (*instack[indepth].bufp != ')');
7991 /* If we got one arg but it was just whitespace, call that 0 args. */
7993 register U_CHAR *bp = args[0].raw;
7994 register U_CHAR *lim = bp + args[0].raw_length;
7995 /* cpp.texi says for foo ( ) we provide one argument.
7996 However, if foo wants just 0 arguments, treat this as 0. */
7998 while (bp != lim && is_space[*bp]) bp++;
8003 /* Don't output an error message if we have already output one for
8004 a parse error above. */
8006 if (nargs == 0 && i > 0) {
8008 error ("arguments given to macro `%s'", hp->name);
8009 } else if (i < nargs) {
8010 /* traditional C allows foo() if foo wants one argument. */
8011 if (nargs == 1 && i == 0 && traditional)
8013 /* the rest args token is allowed to absorb 0 tokens */
8014 else if (i == nargs - 1 && defn->rest_args)
8016 else if (parse_error)
8019 error ("macro `%s' used without args", hp->name);
8021 error ("macro `%s' used with just one arg", hp->name);
8023 error ("macro `%s' used with only %d args", hp->name, i);
8024 } else if (i > nargs) {
8026 error ("macro `%s' used with too many (%d) args", hp->name, i);
8029 /* Swallow the closeparen. */
8030 ++instack[indepth].bufp;
8032 /* If macro wants zero args, we parsed the arglist for checking only.
8033 Read directly from the macro definition. */
8035 xbuf = defn->expansion;
8036 xbuf_len = defn->length;
8038 register U_CHAR *exp = defn->expansion;
8039 register int offset; /* offset in expansion,
8040 copied a piece at a time */
8041 register int totlen; /* total amount of exp buffer filled so far */
8043 register struct reflist *ap, *last_ap;
8045 /* Macro really takes args. Compute the expansion of this call. */
8047 /* Compute length in characters of the macro's expansion.
8048 Also count number of times each arg is used. */
8049 xbuf_len = defn->length;
8050 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8052 xbuf_len += args[ap->argno].stringified_length;
8053 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8054 /* Add 4 for two newline-space markers to prevent
8055 token concatenation. */
8056 xbuf_len += args[ap->argno].raw_length + 4;
8058 /* We have an ordinary (expanded) occurrence of the arg.
8059 So compute its expansion, if we have not already. */
8060 if (args[ap->argno].expanded == 0) {
8062 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8063 args[ap->argno].raw + args[ap->argno].raw_length,
8066 args[ap->argno].expanded = obuf.buf;
8067 args[ap->argno].expand_length = obuf.length;
8068 args[ap->argno].free2 = obuf.buf;
8071 /* Add 4 for two newline-space markers to prevent
8072 token concatenation. */
8073 xbuf_len += args[ap->argno].expand_length + 4;
8075 if (args[ap->argno].use_count < 10)
8076 args[ap->argno].use_count++;
8079 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8081 /* Generate in XBUF the complete expansion
8082 with arguments substituted in.
8083 TOTLEN is the total size generated so far.
8084 OFFSET is the index in the definition
8085 of where we are copying from. */
8086 offset = totlen = 0;
8087 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8088 last_ap = ap, ap = ap->next) {
8089 register struct argdata *arg = &args[ap->argno];
8090 int count_before = totlen;
8092 /* Add chars to XBUF. */
8093 for (i = 0; i < ap->nchars; i++, offset++)
8094 xbuf[totlen++] = exp[offset];
8096 /* If followed by an empty rest arg with concatenation,
8097 delete the last run of nonwhite chars. */
8098 if (rest_zero && totlen > count_before
8099 && ((ap->rest_args && ap->raw_before != 0)
8100 || (last_ap != NULL && last_ap->rest_args
8101 && last_ap->raw_after != 0))) {
8102 /* Delete final whitespace. */
8103 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8107 /* Delete the nonwhites before them. */
8108 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8113 if (ap->stringify != 0) {
8114 int arglen = arg->raw_length;
8120 && (c = arg->raw[i], is_space[c]))
8123 && (c = arg->raw[arglen - 1], is_space[c]))
8126 xbuf[totlen++] = '\"'; /* insert beginning quote */
8127 for (; i < arglen; i++) {
8130 /* Special markers Newline Space
8131 generate nothing for a stringified argument. */
8132 if (c == '\n' && arg->raw[i+1] != '\n') {
8137 /* Internal sequences of whitespace are replaced by one space
8138 except within an string or char token. */
8140 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8142 /* Note that Newline Space does occur within whitespace
8143 sequences; consider it part of the sequence. */
8144 if (c == '\n' && is_space[arg->raw[i+1]])
8146 else if (c != '\n' && is_space[c])
8163 } else if (c == '\"' || c == '\'')
8167 /* Escape these chars */
8168 if (c == '\"' || (in_string && c == '\\'))
8169 xbuf[totlen++] = '\\';
8173 sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8178 xbuf[totlen++] = '\"'; /* insert ending quote */
8179 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8180 U_CHAR *p1 = arg->raw;
8181 U_CHAR *l1 = p1 + arg->raw_length;
8182 if (ap->raw_before != 0) {
8183 while (p1 != l1 && is_space[*p1]) p1++;
8184 while (p1 != l1 && is_idchar[*p1])
8185 xbuf[totlen++] = *p1++;
8186 /* Delete any no-reexpansion marker that follows
8187 an identifier at the beginning of the argument
8188 if the argument is concatenated with what precedes it. */
8189 if (p1[0] == '\n' && p1[1] == '-')
8191 } else if (!traditional) {
8192 /* Ordinary expanded use of the argument.
8193 Put in newline-space markers to prevent token pasting. */
8194 xbuf[totlen++] = '\n';
8195 xbuf[totlen++] = ' ';
8197 if (ap->raw_after != 0) {
8198 /* Arg is concatenated after: delete trailing whitespace,
8199 whitespace markers, and no-reexpansion markers. */
8201 if (is_space[l1[-1]]) l1--;
8202 else if (l1[-1] == '-') {
8203 U_CHAR *p2 = l1 - 1;
8204 /* If a `-' is preceded by an odd number of newlines then it
8205 and the last newline are a no-reexpansion marker. */
8206 while (p2 != p1 && p2[-1] == '\n') p2--;
8207 if ((l1 - 1 - p2) & 1) {
8216 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8218 if (!traditional && ap->raw_after == 0) {
8219 /* Ordinary expanded use of the argument.
8220 Put in newline-space markers to prevent token pasting. */
8221 xbuf[totlen++] = '\n';
8222 xbuf[totlen++] = ' ';
8225 /* Ordinary expanded use of the argument.
8226 Put in newline-space markers to prevent token pasting. */
8228 xbuf[totlen++] = '\n';
8229 xbuf[totlen++] = ' ';
8231 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8232 arg->expand_length);
8233 totlen += arg->expand_length;
8235 xbuf[totlen++] = '\n';
8236 xbuf[totlen++] = ' ';
8238 /* If a macro argument with newlines is used multiple times,
8239 then only expand the newlines once. This avoids creating output
8240 lines which don't correspond to any input line, which confuses
8242 if (arg->use_count > 1 && arg->newlines > 0) {
8243 /* Don't bother doing change_newlines for subsequent
8247 = change_newlines (arg->expanded, arg->expand_length);
8251 if (totlen > xbuf_len)
8255 /* If there is anything left of the definition after handling
8256 the arg list, copy that in too. */
8258 for (i = offset; i < defn->length; i++) {
8259 /* if we've reached the end of the macro */
8262 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8263 && last_ap->raw_after != 0))
8264 xbuf[totlen++] = exp[i];
8270 for (i = 0; i < nargs; i++) {
8271 if (args[i].free1 != 0)
8272 free (args[i].free1);
8273 if (args[i].free2 != 0)
8274 free (args[i].free2);
8278 xbuf = defn->expansion;
8279 xbuf_len = defn->length;
8282 /* Now put the expansion on the input stack
8283 so our caller will commence reading from it. */
8285 register FILE_BUF *ip2;
8287 ip2 = &instack[++indepth];
8290 ip2->nominal_fname = 0;
8292 /* This may not be exactly correct, but will give much better error
8293 messages for nested macro calls than using a line number of zero. */
8294 ip2->lineno = start_line;
8296 ip2->length = xbuf_len;
8298 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8300 ip2->if_stack = if_stack;
8301 ip2->system_header_p = 0;
8303 /* Recursive macro use sometimes works traditionally.
8304 #define foo(x,y) bar (x (y,0), y)
8308 hp->type = T_DISABLED;
8312 /* Parse a macro argument and store the info on it into *ARGPTR.
8313 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8314 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);
8501 } else if (bp[1] == '/' && cplusplus_comments) {
8503 for (bp += 2; bp < limit; bp++) {
8509 warning ("multiline `//' comment");
8518 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8523 while (*bp == '\\' && bp[1] == '\n') {
8526 } else if (*bp == '\n') {
8535 /* if we've returned to lowest level and we aren't absorbing all args */
8536 if ((*depthptr) == 0 && rest_args == 0)
8546 /* Discard comments and duplicate newlines
8547 in the string of length LENGTH at START,
8548 except inside of string constants.
8549 The string is copied into itself with its beginning staying fixed.
8551 NEWLINES is the number of newlines that must be duplicated.
8552 We assume that that much extra space is available past the end
8556 discard_comments (start, length, newlines)
8561 register U_CHAR *ibp;
8562 register U_CHAR *obp;
8563 register U_CHAR *limit;
8566 /* If we have newlines to duplicate, copy everything
8567 that many characters up. Then, in the second part,
8568 we will have room to insert the newlines
8570 NEWLINES may actually be too large, because it counts
8571 newlines in string constants, and we don't duplicate those.
8572 But that does no harm. */
8574 ibp = start + length;
8575 obp = ibp + newlines;
8577 while (limit != ibp)
8581 ibp = start + newlines;
8582 limit = start + length + newlines;
8585 while (ibp < limit) {
8586 *obp++ = c = *ibp++;
8589 /* Duplicate the newline. */
8601 if (*ibp == '\\' && ibp[1] == '\n')
8603 /* Delete any comment. */
8604 if (cplusplus_comments && ibp[0] == '/') {
8605 /* Comments are equivalent to spaces. */
8608 while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8612 if (ibp[0] != '*' || ibp + 1 >= limit)
8614 /* Comments are equivalent to spaces.
8615 For -traditional, a comment is equivalent to nothing. */
8621 while (ibp + 1 < limit) {
8623 && ibp[1] == '\\' && ibp[2] == '\n')
8624 newline_fix (ibp + 1);
8625 if (ibp[0] == '*' && ibp[1] == '/')
8634 /* Notice and skip strings, so that we don't
8635 think that comments start inside them,
8636 and so we don't duplicate newlines in them. */
8639 while (ibp < limit) {
8640 *obp++ = c = *ibp++;
8643 if (c == '\n' && quotec == '\'')
8645 if (c == '\\' && ibp < limit) {
8646 while (*ibp == '\\' && ibp[1] == '\n')
8659 /* Turn newlines to spaces in the string of length LENGTH at START,
8660 except inside of string constants.
8661 The string is copied into itself with its beginning staying fixed. */
8664 change_newlines (start, length)
8668 register U_CHAR *ibp;
8669 register U_CHAR *obp;
8670 register U_CHAR *limit;
8674 limit = start + length;
8677 while (ibp < limit) {
8678 *obp++ = c = *ibp++;
8681 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8682 string. Skip past the newline and its duplicate.
8683 Put a space in the output. */
8694 /* Notice and skip strings, so that we don't delete newlines in them. */
8697 while (ibp < limit) {
8698 *obp++ = c = *ibp++;
8701 if (c == '\n' && quotec == '\'')
8712 /* my_strerror - return the descriptive text associated with an
8716 my_strerror (errnum)
8722 #ifndef HAVE_STRERROR
8723 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8725 result = strerror (errnum);
8728 /* VAXCRTL's strerror() takes an optional second argument, which only
8729 matters when the first argument is EVMSERR. However, it's simplest
8730 just to pass it unconditionally. `vaxc$errno' is declared in
8731 <errno.h>, and maintained by the library in parallel with `errno'.
8732 We assume that caller's `errnum' either matches the last setting of
8733 `errno' by the library or else does not have the value `EVMSERR'. */
8735 result = strerror (errnum, vaxc$errno);
8739 result = "undocumented I/O error";
8744 /* error - print error message and increment count of errors. */
8747 error (PRINTF_ALIST (msg))
8752 VA_START (args, msg);
8763 FILE_BUF *ip = NULL;
8765 print_containing_files ();
8767 for (i = indepth; i >= 0; i--)
8768 if (instack[i].fname != NULL) {
8774 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8775 vfprintf (stderr, msg, args);
8776 fprintf (stderr, "\n");
8780 /* Error including a message from `errno'. */
8783 error_from_errno (name)
8787 FILE_BUF *ip = NULL;
8789 print_containing_files ();
8791 for (i = indepth; i >= 0; i--)
8792 if (instack[i].fname != NULL) {
8798 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8800 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8805 /* Print error message but don't count it. */
8808 warning (PRINTF_ALIST (msg))
8813 VA_START (args, msg);
8814 vwarning (msg, args);
8819 vwarning (msg, args)
8824 FILE_BUF *ip = NULL;
8826 if (inhibit_warnings)
8829 if (warnings_are_errors)
8832 print_containing_files ();
8834 for (i = indepth; i >= 0; i--)
8835 if (instack[i].fname != NULL) {
8841 fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8842 fprintf (stderr, "warning: ");
8843 vfprintf (stderr, msg, args);
8844 fprintf (stderr, "\n");
8848 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8849 error_with_line (int line, PRINTF_ALIST (msg))
8851 error_with_line (line, PRINTF_ALIST (msg))
8858 VA_START (args, msg);
8859 verror_with_line (line, msg, args);
8864 verror_with_line (line, msg, args)
8870 FILE_BUF *ip = NULL;
8872 print_containing_files ();
8874 for (i = indepth; i >= 0; i--)
8875 if (instack[i].fname != NULL) {
8881 fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8882 vfprintf (stderr, msg, args);
8883 fprintf (stderr, "\n");
8888 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8889 warning_with_line (int line, PRINTF_ALIST (msg))
8891 warning_with_line (line, PRINTF_ALIST (msg))
8898 VA_START (args, msg);
8899 vwarning_with_line (line, msg, args);
8904 vwarning_with_line (line, msg, args)
8910 FILE_BUF *ip = NULL;
8912 if (inhibit_warnings)
8915 if (warnings_are_errors)
8918 print_containing_files ();
8920 for (i = indepth; i >= 0; i--)
8921 if (instack[i].fname != NULL) {
8927 fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8928 fprintf (stderr, "warning: ");
8929 vfprintf (stderr, msg, args);
8930 fprintf (stderr, "\n");
8933 /* Print an error message and maybe count it. */
8936 pedwarn (PRINTF_ALIST (msg))
8941 VA_START (args, msg);
8942 if (pedantic_errors)
8945 vwarning (msg, args);
8950 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8951 pedwarn_with_line (int line, PRINTF_ALIST (msg))
8953 pedwarn_with_line (line, PRINTF_ALIST (msg))
8960 VA_START (args, msg);
8961 if (pedantic_errors)
8962 verror_with_line (line, msg, args);
8964 vwarning_with_line (line, msg, args);
8968 /* Report a warning (or an error if pedantic_errors)
8969 giving specified file name and line number, not current. */
8972 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8973 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
8975 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
8983 if (!pedantic_errors && inhibit_warnings)
8986 fprintf (stderr, "%s:%d: ", file, line);
8987 if (pedantic_errors)
8989 if (!pedantic_errors)
8990 fprintf (stderr, "warning: ");
8991 VA_START (args, msg);
8992 vfprintf (stderr, msg, args);
8994 fprintf (stderr, "\n");
8997 /* Print the file names and line numbers of the #include
8998 directives which led to the current file. */
9001 print_containing_files ()
9003 FILE_BUF *ip = NULL;
9007 /* If stack of files hasn't changed since we last printed
9008 this info, don't repeat it. */
9009 if (last_error_tick == input_file_stack_tick)
9012 for (i = indepth; i >= 0; i--)
9013 if (instack[i].fname != NULL) {
9018 /* Give up if we don't find a source file. */
9022 /* Find the other, outer source files. */
9023 for (i--; i >= 0; i--)
9024 if (instack[i].fname != NULL) {
9028 fprintf (stderr, "In file included");
9030 fprintf (stderr, ",\n ");
9033 fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9036 fprintf (stderr, ":\n");
9038 /* Record we have printed the status as of this time. */
9039 last_error_tick = input_file_stack_tick;
9042 /* Return the line at which an error occurred.
9043 The error is not necessarily associated with the current spot
9044 in the input stack, so LINE says where. LINE will have been
9045 copied from ip->lineno for the current input level.
9046 If the current level is for a file, we return LINE.
9047 But if the current level is not for a file, LINE is meaningless.
9048 In that case, we return the lineno of the innermost file. */
9051 line_for_error (line)
9057 for (i = indepth; i >= 0; ) {
9058 if (instack[i].fname != 0)
9063 line1 = instack[i].lineno;
9071 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9073 * As things stand, nothing is ever placed in the output buffer to be
9074 * removed again except when it's KNOWN to be part of an identifier,
9075 * so flushing and moving down everything left, instead of expanding,
9079 /* You might think void was cleaner for the return type,
9080 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.
9127 install (name, len, type, value, hash)
9130 enum node_type type;
9134 register HASHNODE *hp;
9135 register int i, bucket;
9136 register U_CHAR *p, *q;
9140 while (is_idchar[*p])
9146 hash = hashf (name, len, HASHSIZE);
9148 i = sizeof (HASHNODE) + len + 1;
9149 hp = (HASHNODE *) xmalloc (i);
9151 hp->bucket_hdr = &hashtab[bucket];
9152 hp->next = hashtab[bucket];
9153 hashtab[bucket] = hp;
9155 if (hp->next != NULL)
9156 hp->next->prev = hp;
9159 hp->value.cpval = value;
9160 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9163 for (i = 0; i < len; i++)
9170 * find the most recent hash node for name name (ending with first
9171 * non-identifier char) installed by install
9173 * If LEN is >= 0, it is the length of the name.
9174 * Otherwise, compute the length by scanning the entire name.
9176 * If HASH is >= 0, it is the precomputed hash code.
9177 * Otherwise, compute the hash code.
9181 lookup (name, len, hash)
9186 register U_CHAR *bp;
9187 register HASHNODE *bucket;
9190 for (bp = name; is_idchar[*bp]; bp++) ;
9195 hash = hashf (name, len, HASHSIZE);
9197 bucket = hashtab[hash];
9199 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9201 bucket = bucket->next;
9207 * Delete a hash node. Some weirdness to free junk from macros.
9208 * More such weirdness will have to be added if you define more hash
9209 * types that need it.
9212 /* Note that the DEFINITION of a macro is removed from the hash table
9213 but its storage is not freed. This would be a storage leak
9214 except that it is not reasonable to keep undefining and redefining
9215 large numbers of macros many times.
9216 In any case, this is necessary, because a macro can be #undef'd
9217 in the middle of reading the arguments to a call to it.
9218 If #undef freed the DEFINITION, that would crash. */
9225 if (hp->prev != NULL)
9226 hp->prev->next = hp->next;
9227 if (hp->next != NULL)
9228 hp->next->prev = hp->prev;
9230 /* Make sure that the bucket chain header that the deleted guy was
9231 on points to the right thing afterwards. */
9232 if (hp == *hp->bucket_hdr)
9233 *hp->bucket_hdr = hp->next;
9236 if (hp->type == T_MACRO) {
9237 DEFINITION *d = hp->value.defn;
9238 struct reflist *ap, *nextap;
9240 for (ap = d->pattern; ap != NULL; ap = nextap) {
9251 * return hash function on name. must be compatible with the one
9252 * computed a step at a time, elsewhere
9256 hashf (name, len, hashsize)
9257 register U_CHAR *name;
9264 r = HASHSTEP (r, *name++);
9266 return MAKE_POS (r) % hashsize;
9270 /* Dump the definition of a single macro HP to OF. */
9273 dump_single_macro (hp, of)
9274 register HASHNODE *hp;
9277 register DEFINITION *defn = hp->value.defn;
9283 /* Print the definition of the macro HP. */
9285 fprintf (of, "#define %s", hp->name);
9287 if (defn->nargs >= 0) {
9291 for (i = 0; i < defn->nargs; i++) {
9292 dump_arg_n (defn, i, of);
9293 if (i + 1 < defn->nargs)
9303 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9304 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9305 offset += ap->nchars;
9307 if (ap->nchars != 0)
9309 if (ap->stringify) {
9310 switch (ap->stringify) {
9311 case SHARP_TOKEN: fprintf (of, "#"); break;
9312 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9313 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9314 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9318 if (ap->raw_before != 0) {
9320 switch (ap->raw_before) {
9321 case WHITE_SHARP_TOKEN:
9322 case WHITE_PERCENT_COLON_TOKEN:
9329 switch (ap->raw_before) {
9330 case SHARP_TOKEN: fprintf (of, "##"); break;
9331 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9332 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9333 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9340 dump_arg_n (defn, ap->argno, of);
9341 if (!traditional && ap->raw_after != 0) {
9342 switch (ap->raw_after) {
9343 case SHARP_TOKEN: fprintf (of, "##"); break;
9344 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9345 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9346 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9352 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9356 /* Dump all macro definitions as #defines to stdout. */
9363 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9364 register HASHNODE *hp;
9366 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9367 if (hp->type == T_MACRO)
9368 dump_single_macro (hp, stdout);
9373 /* Output to OF a substring of a macro definition.
9374 BASE is the beginning of the definition.
9375 Output characters START thru LENGTH.
9376 Unless traditional, discard newlines outside of strings, thus
9377 converting funny-space markers to ordinary spaces. */
9380 dump_defn_1 (base, start, length, of)
9386 U_CHAR *p = base + start;
9387 U_CHAR *limit = base + start + length;
9390 fwrite (p, sizeof (*p), length, of);
9393 if (*p == '\"' || *p =='\'') {
9394 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9395 NULL_PTR, NULL_PTR);
9396 fwrite (p, sizeof (*p), p1 - p, of);
9407 /* Print the name of argument number ARGNUM of macro definition DEFN
9409 Recall that DEFN->args.argnames contains all the arg names
9410 concatenated in reverse order with comma-space in between. */
9413 dump_arg_n (defn, argnum, of)
9418 register U_CHAR *p = defn->args.argnames;
9419 while (argnum + 1 < defn->nargs) {
9420 p = (U_CHAR *) index ((char *) p, ' ') + 1;
9424 while (*p && *p != ',') {
9430 /* Initialize syntactic classifications of characters. */
9433 initialize_char_syntax ()
9438 * Set up is_idchar and is_idstart tables. These should be
9439 * faster than saying (is_alpha (c) || c == '_'), etc.
9440 * Set up these things before calling any routines tthat
9443 for (i = 'a'; i <= 'z'; i++) {
9444 is_idchar[i - 'a' + 'A'] = 1;
9446 is_idstart[i - 'a' + 'A'] = 1;
9449 for (i = '0'; i <= '9'; i++)
9452 is_idstart['_'] = 1;
9454 is_idstart['$'] = 1;
9456 /* horizontal space table */
9457 is_hor_space[' '] = 1;
9458 is_hor_space['\t'] = 1;
9459 is_hor_space['\v'] = 1;
9460 is_hor_space['\f'] = 1;
9461 is_hor_space['\r'] = 1;
9470 char_name['\v'] = "vertical tab";
9471 char_name['\f'] = "formfeed";
9472 char_name['\r'] = "carriage return";
9475 /* Initialize the built-in macros. */
9478 initialize_builtins (inp, outp)
9482 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9483 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9484 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9485 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9486 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9487 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9488 #ifndef NO_BUILTIN_SIZE_TYPE
9489 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9491 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9492 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9494 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9495 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9497 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9499 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9501 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9503 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9504 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9507 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9508 /* This is supplied using a -D by the compiler driver
9509 so that it is present only when truly compiling with GNU C. */
9510 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
9511 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9515 char directive[2048];
9516 U_CHAR *udirective = (U_CHAR *) directive;
9517 register struct directive *dp = &directive_table[0];
9518 struct tm *timebuf = timestamp ();
9520 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9521 instack[0].nominal_fname);
9522 output_line_directive (inp, outp, 0, same_file);
9523 pass_thru_directive (udirective, &udirective[strlen (directive)],
9526 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9527 output_line_directive (inp, outp, 0, same_file);
9528 pass_thru_directive (udirective, &udirective[strlen (directive)],
9531 #ifndef NO_BUILTIN_SIZE_TYPE
9532 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9533 output_line_directive (inp, outp, 0, same_file);
9534 pass_thru_directive (udirective, &udirective[strlen (directive)],
9538 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9539 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9540 output_line_directive (inp, outp, 0, same_file);
9541 pass_thru_directive (udirective, &udirective[strlen (directive)],
9545 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9546 output_line_directive (inp, outp, 0, same_file);
9547 pass_thru_directive (udirective, &udirective[strlen (directive)],
9550 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9551 monthnames[timebuf->tm_mon],
9552 timebuf->tm_mday, timebuf->tm_year + 1900);
9553 output_line_directive (inp, outp, 0, same_file);
9554 pass_thru_directive (udirective, &udirective[strlen (directive)],
9557 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9558 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9559 output_line_directive (inp, outp, 0, same_file);
9560 pass_thru_directive (udirective, &udirective[strlen (directive)],
9565 sprintf (directive, " __STDC__ 1");
9566 output_line_directive (inp, outp, 0, same_file);
9567 pass_thru_directive (udirective, &udirective[strlen (directive)],
9572 sprintf (directive, " __OBJC__ 1");
9573 output_line_directive (inp, outp, 0, same_file);
9574 pass_thru_directive (udirective, &udirective[strlen (directive)],
9581 * process a given definition string, for initialization
9582 * If STR is just an identifier, define it with value 1.
9583 * If STR has anything after the identifier, then it should
9584 * be identifier=definition.
9588 make_definition (str, op)
9593 struct directive *kt;
9596 p = buf = (U_CHAR *) str;
9597 if (!is_idstart[*p]) {
9598 error ("malformed option `-D %s'", str);
9601 while (is_idchar[*++p])
9604 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9607 p = (U_CHAR *) str; /* Error */
9610 buf = (U_CHAR *) alloca (p - buf + 4);
9611 strcpy ((char *)buf, str);
9612 strcat ((char *)buf, " 1");
9613 } else if (*p != '=') {
9614 error ("malformed option `-D %s'", str);
9618 /* Copy the entire option so we can modify it. */
9619 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9620 strncpy ((char *) buf, str, p - (U_CHAR *) str);
9621 /* Change the = to a space. */
9622 buf[p - (U_CHAR *) str] = ' ';
9623 /* Scan for any backslash-newline and remove it. */
9625 q = &buf[p - (U_CHAR *) str];
9627 if (*p == '\"' || *p == '\'') {
9628 int unterminated = 0;
9629 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9630 NULL_PTR, NULL_PTR, &unterminated);
9634 if (*p == '\\' && p[1] == '\n')
9638 } else if (*p == '\\' && p[1] == '\n')
9640 /* Change newline chars into newline-markers. */
9641 else if (*p == '\n')
9653 ip = &instack[++indepth];
9654 ip->nominal_fname = ip->fname = "*Initialization*";
9656 ip->buf = ip->bufp = buf;
9657 ip->length = strlen ((char *) buf);
9661 ip->if_stack = if_stack;
9662 ip->system_header_p = 0;
9664 for (kt = directive_table; kt->type != T_DEFINE; kt++)
9667 /* Pass NULL instead of OP, since this is a "predefined" macro. */
9668 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9672 /* JF, this does the work for the -U option */
9675 make_undef (str, op)
9680 struct directive *kt;
9682 ip = &instack[++indepth];
9683 ip->nominal_fname = ip->fname = "*undef*";
9685 ip->buf = ip->bufp = (U_CHAR *) str;
9686 ip->length = strlen (str);
9690 ip->if_stack = if_stack;
9691 ip->system_header_p = 0;
9693 for (kt = directive_table; kt->type != T_UNDEF; kt++)
9696 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9700 /* Process the string STR as if it appeared as the body of a #assert.
9701 OPTION is the option name for which STR was the argument. */
9704 make_assertion (option, str)
9709 struct directive *kt;
9710 U_CHAR *buf, *p, *q;
9712 /* Copy the entire option so we can modify it. */
9713 buf = (U_CHAR *) alloca (strlen (str) + 1);
9714 strcpy ((char *) buf, str);
9715 /* Scan for any backslash-newline and remove it. */
9718 if (*p == '\\' && p[1] == '\n')
9726 if (!is_idstart[*p]) {
9727 error ("malformed option `%s %s'", option, str);
9730 while (is_idchar[*++p])
9732 SKIP_WHITE_SPACE (p);
9733 if (! (*p == 0 || *p == '(')) {
9734 error ("malformed option `%s %s'", option, str);
9738 ip = &instack[++indepth];
9739 ip->nominal_fname = ip->fname = "*Initialization*";
9741 ip->buf = ip->bufp = buf;
9742 ip->length = strlen ((char *) buf);
9746 ip->if_stack = if_stack;
9747 ip->system_header_p = 0;
9749 for (kt = directive_table; kt->type != T_ASSERT; kt++)
9752 /* Pass NULL as output ptr to do_define since we KNOW it never does
9754 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9758 /* The previous include prefix, if any, is PREV_FILE_NAME.
9759 Allocate a new include prefix whose name is the
9760 simplified concatenation of PREFIX and NAME,
9761 with a trailing / added if needed.
9762 But return 0 if the include prefix should be ignored,
9763 e.g. because it is a duplicate of PREV_FILE_NAME. */
9765 static struct file_name_list *
9766 new_include_prefix (prev_file_name, prefix, name)
9767 struct file_name_list *prev_file_name;
9772 fatal ("Directory name missing after command line option");
9775 /* Ignore the empty string. */
9778 struct file_name_list *dir
9779 = ((struct file_name_list *)
9780 xmalloc (sizeof (struct file_name_list)
9781 + strlen (prefix) + strlen (name) + 1 /* for trailing / */));
9783 strcpy (dir->fname, prefix);
9784 strcat (dir->fname, name);
9785 len = simplify_filename (dir->fname);
9787 /* Convert directory name to a prefix. */
9788 if (dir->fname[len - 1] != '/') {
9789 if (len == 1 && dir->fname[len - 1] == '.')
9792 dir->fname[len++] = '/';
9793 dir->fname[len] = 0;
9796 /* Ignore a directory whose name matches the previous one. */
9797 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9798 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9799 if (!first_bracket_include)
9800 first_bracket_include = prev_file_name;
9806 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
9808 /* Ignore a nonexistent directory. */
9809 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9810 if (errno != ENOENT && errno != ENOTDIR)
9811 error_from_errno (dir->fname);
9816 /* Ignore a directory whose identity matches the previous one. */
9818 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9819 && prev_file_name->st.st_dev == dir->st.st_dev) {
9820 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
9821 if (!first_bracket_include)
9822 first_bracket_include = prev_file_name;
9829 dir->c_system_include_path = 0;
9830 dir->got_name_map = 0;
9836 /* Append a chain of `struct file_name_list's
9837 to the end of the main include chain.
9838 FIRST is the beginning of the chain to append, and LAST is the end. */
9841 append_include_chain (first, last)
9842 struct file_name_list *first, *last;
9844 struct file_name_list *dir;
9846 if (!first || !last)
9852 last_include->next = first;
9854 if (first_bracket_include == 0)
9855 first_bracket_include = first;
9857 for (dir = first; ; dir = dir->next) {
9858 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9859 if (len > max_include_len)
9860 max_include_len = len;
9866 last_include = last;
9869 /* Add output to `deps_buffer' for the -M switch.
9870 STRING points to the text to be output.
9871 SPACER is ':' for targets, ' ' for dependencies. */
9874 deps_output (string, spacer)
9878 int size = strlen (string);
9883 #ifndef MAX_OUTPUT_COLUMNS
9884 #define MAX_OUTPUT_COLUMNS 72
9886 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9887 && 1 < deps_column) {
9888 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9895 if (deps_size + size + 8 > deps_allocated_size) {
9896 deps_allocated_size = (deps_size + size + 50) * 2;
9897 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9899 if (spacer == ' ') {
9900 deps_buffer[deps_size++] = ' ';
9903 bcopy (string, &deps_buffer[deps_size], size);
9905 deps_column += size;
9906 if (spacer == ':') {
9907 deps_buffer[deps_size++] = ':';
9910 deps_buffer[deps_size] = 0;
9914 fatal (PRINTF_ALIST (msg))
9919 fprintf (stderr, "%s: ", progname);
9920 VA_START (args, msg);
9921 vfprintf (stderr, msg, args);
9923 fprintf (stderr, "\n");
9924 exit (FATAL_EXIT_CODE);
9927 /* More 'friendly' abort that prints the line and file.
9928 config.h can #define abort fancy_abort if you like that sort of thing. */
9933 fatal ("Internal gcc abort.");
9937 perror_with_name (name)
9940 fprintf (stderr, "%s: ", progname);
9941 fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9946 pfatal_with_name (name)
9949 perror_with_name (name);
9953 exit (FATAL_EXIT_CODE);
9957 /* Handler for SIGPIPE. */
9961 /* If this is missing, some compilers complain. */
9964 fatal ("output pipe has been closed");
9970 fatal ("Memory exhausted.");
9978 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
9985 xrealloc (old, size)
9989 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
9996 xcalloc (number, size)
9997 size_t number, size;
9999 register size_t total = number * size;
10000 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10003 bzero (ptr, total);
10011 size_t size = strlen (input);
10012 char *output = xmalloc (size + 1);
10013 strcpy (output, input);
10019 /* Under VMS we need to fix up the "include" specification filename so
10020 that everything following the 1st slash is changed into its correct
10021 VMS file specification. */
10024 hack_vms_include_specification (fname, vaxc_include)
10028 register char *cp, *cp1, *cp2;
10029 int f, check_filename_before_returning;
10032 check_filename_before_returning = 0;
10034 cp = base_name (fname);
10037 * Check if we have a vax-c style '#include filename'
10038 * and add the missing .h
10040 if (vaxc_include && !index (cp,'.'))
10043 cp2 = Local; /* initialize */
10045 /* We are trying to do a number of things here. First of all, we are
10046 trying to hammer the filenames into a standard format, such that later
10047 processing can handle them.
10049 If the file name contains something like [dir.], then it recognizes this
10050 as a root, and strips the ".]". Later processing will add whatever is
10051 needed to get things working properly.
10053 If no device is specified, then the first directory name is taken to be
10054 a device name (or a rooted logical). */
10056 /* See if we found that 1st slash */
10057 if (cp == 0) return; /* Nothing to do!!! */
10058 if (*cp != '/') return; /* Nothing to do!!! */
10059 /* Point to the UNIX filename part (which needs to be fixed!) */
10061 /* If the directory spec is not rooted, we can just copy
10062 the UNIX filename part and we are done */
10063 if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10064 if (cp[-2] != '.') {
10066 * The VMS part ends in a `]', and the preceding character is not a `.'.
10067 * We strip the `]', and then splice the two parts of the name in the
10068 * usual way. Given the default locations for include files in cccp.c,
10069 * we will only use this code if the user specifies alternate locations
10070 * with the /include (-I) switch on the command line. */
10071 cp -= 1; /* Strip "]" */
10072 cp1--; /* backspace */
10075 * The VMS part has a ".]" at the end, and this will not do. Later
10076 * processing will add a second directory spec, and this would be a syntax
10077 * error. Thus we strip the ".]", and thus merge the directory specs.
10078 * We also backspace cp1, so that it points to a '/'. This inhibits the
10079 * generation of the 000000 root directory spec (which does not belong here
10082 cp -= 2; /* Strip ".]" */
10083 cp1--; }; /* backspace */
10086 /* We drop in here if there is no VMS style directory specification yet.
10087 * If there is no device specification either, we make the first dir a
10088 * device and try that. If we do not do this, then we will be essentially
10089 * searching the users default directory (as if they did a #include "asdf.h").
10091 * Then all we need to do is to push a '[' into the output string. Later
10092 * processing will fill this in, and close the bracket.
10094 if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec. take first dir */
10095 *cp2++ = '['; /* Open the directory specification */
10098 /* at this point we assume that we have the device spec, and (at least
10099 the opening "[" for a directory specification. We may have directories
10100 specified already */
10102 /* If there are no other slashes then the filename will be
10103 in the "root" directory. Otherwise, we need to add
10104 directory specifications. */
10105 if (index (cp1, '/') == 0) {
10106 /* Just add "000000]" as the directory string */
10107 strcpy (cp2, "000000]");
10108 cp2 += strlen (cp2);
10109 check_filename_before_returning = 1; /* we might need to fool with this later */
10111 /* As long as there are still subdirectories to add, do them. */
10112 while (index (cp1, '/') != 0) {
10113 /* If this token is "." we can ignore it */
10114 if ((cp1[0] == '.') && (cp1[1] == '/')) {
10118 /* Add a subdirectory spec. Do not duplicate "." */
10119 if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10121 /* If this is ".." then the spec becomes "-" */
10122 if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10123 /* Add "-" and skip the ".." */
10128 /* Copy the subdirectory */
10129 while (*cp1 != '/') *cp2++= *cp1++;
10130 cp1++; /* Skip the "/" */
10132 /* Close the directory specification */
10133 if (cp2[-1] == '.') /* no trailing periods */
10137 /* Now add the filename */
10138 while (*cp1) *cp2++ = *cp1++;
10140 /* Now append it to the original VMS spec. */
10141 strcpy (cp, Local);
10143 /* If we put a [000000] in the filename, try to open it first. If this fails,
10144 remove the [000000], and return that name. This provides flexibility
10145 to the user in that they can use both rooted and non-rooted logical names
10146 to point to the location of the file. */
10148 if (check_filename_before_returning) {
10149 f = open (fname, O_RDONLY, 0666);
10151 /* The file name is OK as it is, so return it as is. */
10155 /* The filename did not work. Try to remove the [000000] from the name,
10157 cp = index (fname, '[');
10158 cp2 = index (fname, ']') + 1;
10159 strcpy (cp, cp2); /* this gets rid of it */
10167 /* These are the read/write replacement routines for
10168 VAX-11 "C". They make read/write behave enough
10169 like their UNIX counterparts that CCCP will work */
10172 read (fd, buf, size)
10177 #undef read /* Get back the REAL read routine */
10179 register int total = 0;
10181 /* Read until the buffer is exhausted */
10183 /* Limit each read to 32KB */
10184 i = (size > (32*1024)) ? (32*1024) : size;
10185 i = read (fd, buf, i);
10187 if (i == 0) return (total);
10190 /* Account for this read */
10199 write (fd, buf, size)
10204 #undef write /* Get back the REAL write routine */
10208 /* Limit individual writes to 32Kb */
10211 j = (i > (32*1024)) ? (32*1024) : i;
10212 if (write (fd, buf, j) < 0) return (-1);
10213 /* Account for the data written */
10220 /* The following wrapper functions supply additional arguments to the VMS
10221 I/O routines to optimize performance with file handling. The arguments
10223 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10224 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10225 "fop=tef"- Truncate unused portions of file when closing file.
10226 "shr=nil"- Disallow file sharing while file is open. */
10229 freopen (fname, type, oldfile)
10234 #undef freopen /* Get back the REAL fopen routine */
10235 if (strcmp (type, "w") == 0)
10236 return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10237 return freopen (fname, type, oldfile, "mbc=16");
10241 fopen (fname, type)
10245 #undef fopen /* Get back the REAL fopen routine */
10246 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10247 fixed arguments, which matches ANSI's specification but not VAXCRTL's
10248 pre-ANSI implementation. This hack circumvents the mismatch problem. */
10249 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10252 return (*vmslib_fopen) (fname, type, "mbc=32",
10253 "deq=64", "fop=tef", "shr=nil");
10255 return (*vmslib_fopen) (fname, type, "mbc=32");
10259 open (fname, flags, prot)
10264 #undef open /* Get back the REAL open routine */
10265 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10268 /* more VMS hackery */
10272 extern unsigned long sys$parse(), sys$search();
10274 /* Work around another library bug. If a file is located via a searchlist,
10275 and if the device it's on is not the same device as the one specified
10276 in the first element of that searchlist, then both stat() and fstat()
10277 will fail to return info about it. `errno' will be set to EVMSERR, and
10278 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10279 We can get around this by fully parsing the filename and then passing
10280 that absolute name to stat().
10282 Without this fix, we can end up failing to find header files, which is
10283 bad enough, but then compounding the problem by reporting the reason for
10284 failure as "normal successful completion." */
10286 #undef fstat /* get back to library version */
10289 VMS_fstat (fd, statbuf)
10291 struct stat *statbuf;
10293 int result = fstat (fd, statbuf);
10298 char nambuf[NAM$C_MAXRSS+1];
10300 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10301 result = VMS_stat (nambuf, statbuf);
10302 /* No fclose(fp) here; that would close(fd) as well. */
10309 VMS_stat (name, statbuf)
10311 struct stat *statbuf;
10313 int result = stat (name, statbuf);
10319 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for sys$parse */
10320 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for sys$search */
10323 fab.fab$l_fna = (char *) name;
10324 fab.fab$b_fns = (unsigned char) strlen (name);
10325 fab.fab$l_nam = (void *) &nam;
10327 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
10328 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
10329 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10330 if (sys$parse (&fab) & 1)
10332 if (sys$search (&fab) & 1)
10334 res_nam[nam.nam$b_rsl] = '\0';
10335 result = stat (res_nam, statbuf);
10337 /* Clean up searchlist context cached by the system. */
10338 nam.nam$b_nop = NAM$M_SYNCHK;
10339 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
10340 (void) sys$parse (&fab);