1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 87, 89, 92-97, 1998 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. */
23 #define PRINTF_PROTO(ARGS, m, n) PVPROTO (ARGS) ATTRIBUTE_PRINTF(m, n)
25 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
26 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
27 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
28 #define PRINTF_PROTO_4(ARGS) PRINTF_PROTO(ARGS, 4, 5)
34 #ifdef HAVE_SYS_RESOURCE_H
35 # include <sys/resource.h>
38 typedef unsigned char U_CHAR;
42 #ifdef MULTIBYTE_CHARS
45 #endif /* MULTIBYTE_CHARS */
47 #ifndef GET_ENV_PATH_LIST
48 #define GET_ENV_PATH_LIST(VAR,NAME) do { (VAR) = getenv (NAME); } while (0)
51 #ifndef STANDARD_INCLUDE_DIR
52 # define STANDARD_INCLUDE_DIR "/usr/include"
55 /* By default, colon separates directories in a path. */
56 #ifndef PATH_SEPARATOR
57 # define PATH_SEPARATOR ':'
60 /* By default, the suffix for object files is ".o". */
62 # define HAVE_OBJECT_SUFFIX
64 # define OBJECT_SUFFIX ".o"
67 /* VMS-specific definitions */
72 #define open(fname,mode,prot) VMS_open (fname,mode,prot)
73 #define fopen(fname,mode) VMS_fopen (fname,mode)
74 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
75 #define fstat(fd,stbuf) VMS_fstat (fd,stbuf)
76 static int VMS_fstat (), VMS_stat ();
77 static int VMS_open ();
78 static FILE *VMS_fopen ();
79 static FILE *VMS_freopen ();
80 static int hack_vms_include_specification ();
81 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
82 #define INO_T_HASH(a) 0
83 #define INCLUDE_LEN_FUDGE 12 /* leave room for VMS syntax conversion */
86 /* Windows does not natively support inodes, and neither does MSDOS. */
87 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
88 #define INO_T_EQ(a, b) 0
93 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
94 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
96 /* Find the largest host integer type and set its size and type.
97 Watch out: on some crazy hosts `long' is shorter than `int'. */
101 # include <inttypes.h>
102 # define HOST_WIDE_INT intmax_t
104 # if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
105 # define HOST_WIDE_INT int
107 # if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
108 # define HOST_WIDE_INT long
110 # define HOST_WIDE_INT long long
117 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
121 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
125 #define INO_T_EQ(a, b) ((a) == (b))
129 #define INO_T_HASH(a) (a)
132 #ifndef INCLUDE_LEN_FUDGE
133 #define INCLUDE_LEN_FUDGE 0
136 /* External declarations. */
138 extern char *version_string;
139 extern char *update_path PROTO((char *, char *));
140 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
141 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
143 /* Name under which this program was invoked. */
145 static char *progname;
147 /* Nonzero means use extra default include directories for C++. */
149 static int cplusplus;
151 /* Nonzero means handle cplusplus style comments */
153 static int cplusplus_comments;
155 /* Nonzero means handle #import, for objective C. */
159 /* Nonzero means this is an assembly file, and allow
160 unknown directives, which could be comments. */
164 /* Current maximum length of directory names in the search path
165 for include files. (Altered as we get more of them.) */
167 static int max_include_len;
169 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
171 static int for_lint = 0;
173 /* Nonzero means copy comments into the output file. */
175 static int put_out_comments = 0;
177 /* Nonzero means don't process the ANSI trigraph sequences. */
179 static int no_trigraphs = 0;
181 /* Nonzero means print the names of included files rather than
182 the preprocessed output. 1 means just the #include "...",
183 2 means #include <...> as well. */
185 static int print_deps = 0;
187 /* Nonzero if missing .h files in -M output are assumed to be generated
188 files and not errors. */
190 static int print_deps_missing_files = 0;
192 /* Nonzero means print names of header files (-H). */
194 static int print_include_names = 0;
196 /* Nonzero means don't output line number information. */
198 static int no_line_directives;
200 /* Nonzero means output the text in failing conditionals,
201 inside #failed ... #endfailed. */
203 static int output_conditionals;
205 /* dump_only means inhibit output of the preprocessed text
206 and instead output the definitions of all user-defined
207 macros in a form suitable for use as input to cccp.
208 dump_names means pass #define and the macro name through to output.
209 dump_definitions means pass the whole definition (plus #define) through
212 static enum {dump_none, dump_only, dump_names, dump_definitions}
213 dump_macros = dump_none;
215 /* Nonzero means pass all #define and #undef directives which we actually
216 process through to the output stream. This feature is used primarily
217 to allow cc1 to record the #defines and #undefs for the sake of
218 debuggers which understand about preprocessor macros, but it may
219 also be useful with -E to figure out how symbols are defined, and
220 where they are defined. */
221 static int debug_output = 0;
223 /* Nonzero means pass #include lines through to the output,
224 even if they are ifdefed out. */
225 static int dump_includes;
227 /* Nonzero indicates special processing used by the pcp program. The
228 special effects of this mode are:
230 Inhibit all macro expansion, except those inside #if directives.
232 Process #define directives normally, and output their contents
235 Output preconditions to pcp_outfile indicating all the relevant
236 preconditions for use of this file in a later cpp run.
238 static FILE *pcp_outfile;
240 /* Nonzero means we are inside an IF during a -pcp run. In this mode
241 macro expansion is done, and preconditions are output for all macro
242 uses requiring them. */
243 static int pcp_inside_if;
245 /* Nonzero means never to include precompiled files.
246 This is 1 since there's no way now to make precompiled files,
247 so it's not worth testing for them. */
248 static int no_precomp = 1;
250 /* Nonzero means give all the error messages the ANSI standard requires. */
254 /* Nonzero means try to make failure to fit ANSI C an error. */
256 static int pedantic_errors;
258 /* Nonzero means don't print warning messages. -w. */
260 static int inhibit_warnings = 0;
262 /* Nonzero means warn if slash-star appears in a slash-star comment,
263 or if newline-backslash appears in a slash-slash comment. */
265 static int warn_comments;
267 /* Nonzero means warn if a macro argument is (or would be)
268 stringified with -traditional. */
270 static int warn_stringify;
272 /* Nonzero means warn if there are any trigraphs. */
274 static int warn_trigraphs;
276 /* Nonzero means warn if undefined identifiers are evaluated in an #if. */
278 static int warn_undef;
280 /* Nonzero means warn if #import is used. */
282 static int warn_import = 1;
284 /* Nonzero means turn warnings into errors. */
286 static int warnings_are_errors;
288 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor. */
292 /* Nonzero for the 1989 C Standard, including corrigenda and amendments. */
296 /* Nonzero causes output not to be done,
297 but directives such as #define that have side effects
300 static int no_output;
302 /* Nonzero means we should look for header.gcc files that remap file names. */
305 /* Nonzero means this file was included with a -imacros or -include
306 command line and should not be recorded as an include file. */
308 static int no_record_file;
310 /* Nonzero means that we have finished processing the command line options.
311 This flag is used to decide whether or not to issue certain errors
314 static int done_initializing = 0;
316 /* Line where a newline was first seen in a string constant. */
318 static int multiline_string_line = 0;
320 /* I/O buffer structure.
321 The `fname' field is nonzero for source files and #include files
322 and for the dummy text used for -D and -U.
323 It is zero for rescanning results of macro expansion
324 and for expanding macro arguments. */
325 #define INPUT_STACK_MAX 400
326 static struct file_buf {
328 /* Filename specified with #line directive. */
330 /* The length of nominal_fname, which may contain embedded NULs. */
331 size_t nominal_fname_len;
332 /* Include file description. */
333 struct include_file *inc;
334 /* Record where in the search path this file was found.
335 For #include_next. */
336 struct file_name_list *dir;
341 /* Macro that this level is the expansion of.
342 Included so that we can reenable the macro
343 at the end of this level. */
344 struct hashnode *macro;
345 /* Value of if_stack at start of this file.
346 Used to prohibit unmatched #endif (etc) in an include file. */
347 struct if_stack *if_stack;
348 /* Object to be freed at end of input at this level. */
350 /* True if this is a system header file; see is_system_include. */
351 char system_header_p;
352 } instack[INPUT_STACK_MAX];
354 static int last_error_tick; /* Incremented each time we print it. */
355 static int input_file_stack_tick; /* Incremented when the status changes. */
357 /* Current nesting level of input sources.
358 `instack[indepth]' is the level currently being read. */
359 static int indepth = -1;
360 #define CHECK_DEPTH(code) \
361 if (indepth >= (INPUT_STACK_MAX - 1)) \
363 error_with_line (line_for_error (instack[indepth].lineno), \
364 "macro or `#include' recursion too deep"); \
368 /* Current depth in #include directives that use <...>. */
369 static int system_include_depth = 0;
371 typedef struct file_buf FILE_BUF;
373 /* The output buffer. Its LENGTH field is the amount of room allocated
374 for the buffer, not the number of chars actually present. To get
375 that, subtract outbuf.buf from outbuf.bufp. */
377 #define OUTBUF_SIZE 10 /* initial size of output buffer */
378 static FILE_BUF outbuf;
380 /* Grow output buffer OBUF points at
381 so it can hold at least NEEDED more chars. */
383 #define check_expand(OBUF, NEEDED) \
384 (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
385 ? grow_outbuf ((OBUF), (NEEDED)) : 0)
387 struct file_name_list
389 struct file_name_list *next;
390 /* If the following is 1, it is a C-language system include
392 int c_system_include_path;
393 /* Mapping of file names for this directory. */
394 struct file_name_map *name_map;
395 /* Non-zero if name_map is valid. */
397 /* The include directory status. */
399 /* The include prefix: "" denotes the working directory,
400 otherwise fname must end in '/'.
401 The actual size is dynamically allocated. */
405 /* #include "file" looks in source file dir, then stack. */
406 /* #include <file> just looks in the stack. */
407 /* -I directories are added to the end, then the defaults are added. */
409 static struct default_include {
410 char *fname; /* The name of the directory. */
411 char *component; /* The component containing the directory */
412 int cplusplus; /* Only look here if we're compiling C++. */
413 int cxx_aware; /* Includes in this directory don't need to
414 be wrapped in extern "C" when compiling
416 } include_defaults_array[]
417 #ifdef INCLUDE_DEFAULTS
421 /* Pick up GNU C++ specific include files. */
422 { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
424 /* This is the dir for fixincludes. Put it just before
425 the files that we fix. */
426 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
427 /* For cross-compilation, this dir name is generated
428 automatically in Makefile.in. */
429 { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
430 #ifdef TOOL_INCLUDE_DIR
431 /* This is another place that the target system's headers might be. */
432 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
434 #else /* not CROSS_COMPILE */
435 #ifdef LOCAL_INCLUDE_DIR
436 /* This should be /usr/local/include and should come before
437 the fixincludes-fixed header files. */
438 { LOCAL_INCLUDE_DIR, 0, 0, 1 },
440 #ifdef TOOL_INCLUDE_DIR
441 /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
442 Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h. */
443 { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
445 /* This is the dir for fixincludes. Put it just before
446 the files that we fix. */
447 { GCC_INCLUDE_DIR, "GCC", 0, 0 },
448 /* Some systems have an extra dir of include files. */
449 #ifdef SYSTEM_INCLUDE_DIR
450 { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
452 #ifndef STANDARD_INCLUDE_COMPONENT
453 #define STANDARD_INCLUDE_COMPONENT 0
455 { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
456 #endif /* not CROSS_COMPILE */
459 #endif /* no INCLUDE_DEFAULTS */
461 /* The code looks at the defaults through this pointer, rather than through
462 the constant structure above. This pointer gets changed if an environment
463 variable specifies other defaults. */
464 static struct default_include *include_defaults = include_defaults_array;
466 static struct file_name_list *include = 0; /* First dir to search */
467 /* First dir to search for <file> */
468 /* This is the first element to use for #include <...>.
469 If it is 0, use the entire chain for such includes. */
470 static struct file_name_list *first_bracket_include = 0;
471 /* This is the first element in the chain that corresponds to
472 a directory of system header files. */
473 static struct file_name_list *first_system_include = 0;
474 static struct file_name_list *last_include = 0; /* Last in chain */
476 /* Chain of include directories to put at the end of the other chain. */
477 static struct file_name_list *after_include = 0;
478 static struct file_name_list *last_after_include = 0; /* Last in chain */
480 /* Chain to put at the start of the system include files. */
481 static struct file_name_list *before_system = 0;
482 static struct file_name_list *last_before_system = 0; /* Last in chain */
484 /* Directory prefix that should replace `/usr' in the standard
485 include file directories. */
486 static char *include_prefix;
488 /* Maintain and search list of included files. */
490 struct include_file {
491 struct include_file *next; /* for include_hashtab */
492 struct include_file *next_ino; /* for include_ino_hashtab */
494 /* If the following is the empty string, it means #pragma once
495 was seen in this include file, or #import was applied to the file.
496 Otherwise, if it is nonzero, it is a macro name.
497 Don't include the file again if that macro is defined. */
498 U_CHAR *control_macro;
499 /* Nonzero if the dependency on this include file has been output. */
504 /* Hash tables of files already included with #include or #import.
505 include_hashtab is by full name; include_ino_hashtab is by inode number. */
507 #define INCLUDE_HASHSIZE 61
508 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
509 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
511 /* Global list of strings read in from precompiled files. This list
512 is kept in the order the strings are read in, with new strings being
513 added at the end through stringlist_tailp. We use this list to output
514 the strings at the end of the run.
516 static STRINGDEF *stringlist;
517 static STRINGDEF **stringlist_tailp = &stringlist;
520 /* Structure returned by create_definition */
521 typedef struct macrodef MACRODEF;
524 struct definition *defn;
529 enum sharp_token_type {
530 NO_SHARP_TOKEN = 0, /* token not present */
532 SHARP_TOKEN = '#', /* token spelled with # only */
533 WHITE_SHARP_TOKEN, /* token spelled with # and white space */
535 PERCENT_COLON_TOKEN = '%', /* token spelled with %: only */
536 WHITE_PERCENT_COLON_TOKEN /* token spelled with %: and white space */
539 /* Structure allocated for every #define. For a simple replacement
542 nargs = -1, the `pattern' list is null, and the expansion is just
543 the replacement text. Nargs = 0 means a functionlike macro with no args,
545 #define getchar() getc (stdin) .
546 When there are args, the expansion is the replacement text with the
547 args squashed out, and the reflist is a list describing how to
548 build the output from the input: e.g., "3 chars, then the 1st arg,
549 then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
550 The chars here come from the expansion. Whatever is left of the
551 expansion after the last arg-occurrence is copied after that arg.
552 Note that the reflist can be arbitrarily long---
553 its length depends on the number of times the arguments appear in
554 the replacement text, not how many args there are. Example:
555 #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
557 { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
558 where (x, y) means (nchars, argno). */
560 typedef struct definition DEFINITION;
563 int length; /* length of expansion string */
564 int predefined; /* True if the macro was builtin or */
565 /* came from the command line */
567 int line; /* Line number of definition */
568 char *file; /* File of definition */
569 size_t file_len; /* Length of file (which can contain NULs) */
570 char rest_args; /* Nonzero if last arg. absorbs the rest */
572 struct reflist *next;
574 enum sharp_token_type stringify; /* set if a # operator before arg */
575 enum sharp_token_type raw_before; /* set if a ## operator before arg */
576 enum sharp_token_type raw_after; /* set if a ## operator after arg */
578 char rest_args; /* Nonzero if this arg. absorbs the rest */
579 int nchars; /* Number of literal chars to copy before
580 this arg occurrence. */
581 int argno; /* Number of arg to substitute (origin-0) */
584 /* Names of macro args, concatenated in reverse order
585 with comma-space between them.
586 The only use of this is that we warn on redefinition
587 if this differs between the old and new definitions. */
592 /* different kinds of things that can appear in the value field
593 of a hash node. Actually, this may be useless now. */
601 * special extension string that can be added to the last macro argument to
602 * allow it to absorb the "rest" of the arguments when expanded. Ex:
603 * #define wow(a, b...) process (b, a, b)
604 * { wow (1, 2, 3); } -> { process (2, 3, 1, 2, 3); }
605 * { wow (one, two); } -> { process (two, one, two); }
606 * if this "rest_arg" is used with the concat token '##' and if it is not
607 * supplied then the token attached to with ## will not be outputted. Ex:
608 * #define wow (a, b...) process (b ## , a, ## b)
609 * { wow (1, 2); } -> { process (2, 1, 2); }
610 * { wow (one); } -> { process (one); {
612 static char rest_extension[] = "...";
613 #define REST_EXTENSION_LENGTH (sizeof (rest_extension) - 1)
615 /* The structure of a node in the hash table. The hash table
616 has entries for all tokens defined by #define directives (type T_MACRO),
617 plus some special tokens like __LINE__ (these each have their own
618 type, and the appropriate code is run when that type of node is seen.
619 It does not contain control words like "#define", which are recognized
620 by a separate piece of code. */
622 /* different flavors of hash nodes --- also used in keyword table */
624 T_DEFINE = 1, /* the `#define' keyword */
625 T_INCLUDE, /* the `#include' keyword */
626 T_INCLUDE_NEXT, /* the `#include_next' keyword */
627 T_IMPORT, /* the `#import' keyword */
628 T_IFDEF, /* the `#ifdef' keyword */
629 T_IFNDEF, /* the `#ifndef' keyword */
630 T_IF, /* the `#if' keyword */
631 T_ELSE, /* `#else' */
632 T_PRAGMA, /* `#pragma' */
633 T_ELIF, /* `#elif' */
634 T_UNDEF, /* `#undef' */
635 T_LINE, /* `#line' */
636 T_ERROR, /* `#error' */
637 T_WARNING, /* `#warning' */
638 T_ENDIF, /* `#endif' */
639 T_SCCS, /* `#sccs', used on system V. */
640 T_IDENT, /* `#ident', used on system V. */
641 T_ASSERT, /* `#assert', taken from system V. */
642 T_UNASSERT, /* `#unassert', taken from system V. */
643 T_SPECLINE, /* special symbol `__LINE__' */
644 T_DATE, /* `__DATE__' */
645 T_FILE, /* `__FILE__' */
646 T_BASE_FILE, /* `__BASE_FILE__' */
647 T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
648 T_VERSION, /* `__VERSION__' */
649 T_SIZE_TYPE, /* `__SIZE_TYPE__' */
650 T_PTRDIFF_TYPE, /* `__PTRDIFF_TYPE__' */
651 T_WCHAR_TYPE, /* `__WCHAR_TYPE__' */
652 T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
653 T_REGISTER_PREFIX_TYPE, /* `__REGISTER_PREFIX__' */
654 T_IMMEDIATE_PREFIX_TYPE, /* `__IMMEDIATE_PREFIX__' */
655 T_TIME, /* `__TIME__' */
656 T_CONST, /* Constant value, used by `__STDC__' */
657 T_MACRO, /* macro defined by `#define' */
658 T_DISABLED, /* macro temporarily turned off for rescan */
659 T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
660 T_PCSTRING, /* precompiled string (hashval is KEYDEF *) */
661 T_UNUSED /* Used for something not defined. */
665 struct hashnode *next; /* double links for easy deletion */
666 struct hashnode *prev;
667 struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
668 chain is kept, in case the node is the head
669 of the chain and gets deleted. */
670 enum node_type type; /* type of special token */
671 int length; /* length of token, for quick comparison */
672 U_CHAR *name; /* the actual name */
673 union hashval value; /* pointer to expansion, or whatever */
676 typedef struct hashnode HASHNODE;
678 /* Some definitions for the hash table. The hash function MUST be
679 computed as shown in hashf () below. That is because the rescan
680 loop computes the hash value `on the fly' for most tokens,
681 in order to avoid the overhead of a lot of procedure calls to
682 the hashf () function. Hashf () only exists for the sake of
683 politeness, for use when speed isn't so important. */
685 #define HASHSIZE 1403
686 static HASHNODE *hashtab[HASHSIZE];
687 #define HASHSTEP(old, c) ((old << 2) + c)
688 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
690 /* Symbols to predefine. */
692 #ifdef CPP_PREDEFINES
693 static char *predefs = CPP_PREDEFINES;
695 static char *predefs = "";
698 /* We let tm.h override the types used here, to handle trivial differences
699 such as the choice of unsigned int or long unsigned int for size_t.
700 When machines start needing nontrivial differences in the size type,
701 it would be best to do something here to figure out automatically
702 from other information what type to use. */
704 /* The string value for __SIZE_TYPE__. */
707 #define SIZE_TYPE "long unsigned int"
710 /* The string value for __PTRDIFF_TYPE__. */
713 #define PTRDIFF_TYPE "long int"
716 /* The string value for __WCHAR_TYPE__. */
719 #define WCHAR_TYPE "int"
721 char * wchar_type = WCHAR_TYPE;
724 /* The string value for __USER_LABEL_PREFIX__ */
726 #ifndef USER_LABEL_PREFIX
727 #define USER_LABEL_PREFIX ""
729 char * user_label_prefix = USER_LABEL_PREFIX;
730 #undef USER_LABEL_PREFIX
732 /* The string value for __REGISTER_PREFIX__ */
734 #ifndef REGISTER_PREFIX
735 #define REGISTER_PREFIX ""
738 /* The string value for __IMMEDIATE_PREFIX__ */
740 #ifndef IMMEDIATE_PREFIX
741 #define IMMEDIATE_PREFIX ""
744 /* In the definition of a #assert name, this structure forms
745 a list of the individual values asserted.
746 Each value is itself a list of "tokens".
747 These are strings that are compared by name. */
749 struct tokenlist_list {
750 struct tokenlist_list *next;
751 struct arglist *tokens;
754 struct assertion_hashnode {
755 struct assertion_hashnode *next; /* double links for easy deletion */
756 struct assertion_hashnode *prev;
757 /* also, a back pointer to this node's hash
758 chain is kept, in case the node is the head
759 of the chain and gets deleted. */
760 struct assertion_hashnode **bucket_hdr;
761 int length; /* length of token, for quick comparison */
762 U_CHAR *name; /* the actual name */
763 /* List of token-sequences. */
764 struct tokenlist_list *value;
767 typedef struct assertion_hashnode ASSERTION_HASHNODE;
769 /* Some definitions for the hash table. The hash function MUST be
770 computed as shown in hashf below. That is because the rescan
771 loop computes the hash value `on the fly' for most tokens,
772 in order to avoid the overhead of a lot of procedure calls to
773 the hashf function. hashf only exists for the sake of
774 politeness, for use when speed isn't so important. */
776 #define ASSERTION_HASHSIZE 37
777 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
779 /* Nonzero means inhibit macroexpansion of what seem to be
780 assertion tests, in rescan. For #if. */
781 static int assertions_flag;
783 /* `struct directive' defines one #-directive, including how to handle it. */
785 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
788 int length; /* Length of name */
789 int (*func) DO_PROTO; /* Function to handle directive */
790 char *name; /* Name of directive */
791 enum node_type type; /* Code which describes which directive. */
794 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
795 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
797 /* These functions are declared to return int instead of void since they
798 are going to be placed in the table and some old compilers have trouble with
799 pointers to functions returning void. */
801 static int do_assert DO_PROTO;
802 static int do_define DO_PROTO;
803 static int do_elif DO_PROTO;
804 static int do_else DO_PROTO;
805 static int do_endif DO_PROTO;
806 static int do_error DO_PROTO;
807 static int do_ident DO_PROTO;
808 static int do_if DO_PROTO;
809 static int do_include DO_PROTO;
810 static int do_line DO_PROTO;
811 static int do_pragma DO_PROTO;
812 #ifdef SCCS_DIRECTIVE
813 static int do_sccs DO_PROTO;
815 static int do_unassert DO_PROTO;
816 static int do_undef DO_PROTO;
817 static int do_warning DO_PROTO;
818 static int do_xifdef DO_PROTO;
820 /* Here is the actual list of #-directives, most-often-used first. */
822 static struct directive directive_table[] = {
823 { 6, do_define, "define", T_DEFINE},
824 { 2, do_if, "if", T_IF},
825 { 5, do_xifdef, "ifdef", T_IFDEF},
826 { 6, do_xifdef, "ifndef", T_IFNDEF},
827 { 5, do_endif, "endif", T_ENDIF},
828 { 4, do_else, "else", T_ELSE},
829 { 4, do_elif, "elif", T_ELIF},
830 { 4, do_line, "line", T_LINE},
831 { 7, do_include, "include", T_INCLUDE},
832 { 12, do_include, "include_next", T_INCLUDE_NEXT},
833 { 6, do_include, "import", T_IMPORT},
834 { 5, do_undef, "undef", T_UNDEF},
835 { 5, do_error, "error", T_ERROR},
836 { 7, do_warning, "warning", T_WARNING},
837 #ifdef SCCS_DIRECTIVE
838 { 4, do_sccs, "sccs", T_SCCS},
840 { 6, do_pragma, "pragma", T_PRAGMA},
841 { 5, do_ident, "ident", T_IDENT},
842 { 6, do_assert, "assert", T_ASSERT},
843 { 8, do_unassert, "unassert", T_UNASSERT},
844 { -1, 0, "", T_UNUSED},
847 /* When a directive handler is called,
848 this points to the # (or the : of the %:) that started the directive. */
849 U_CHAR *directive_start;
851 /* table to tell if char can be part of a C identifier. */
852 U_CHAR is_idchar[256];
853 /* table to tell if char can be first char of a c identifier. */
854 U_CHAR is_idstart[256];
855 /* table to tell if c is horizontal space. */
856 static U_CHAR is_hor_space[256];
857 /* table to tell if c is horizontal or vertical space. */
858 U_CHAR is_space[256];
859 /* names of some characters */
860 static char *char_name[256];
862 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
863 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
865 static int errors = 0; /* Error counter for exit code */
867 /* Name of output file, for error messages. */
868 static char *out_fname;
871 /* Stack of conditionals currently in progress
872 (including both successful and failing conditionals). */
875 struct if_stack *next; /* for chaining to the next stack frame */
876 char *fname; /* copied from input when frame is made */
877 size_t fname_len; /* similarly */
878 int lineno; /* similarly */
879 int if_succeeded; /* true if a leg of this if-group
880 has been passed through rescan */
881 U_CHAR *control_macro; /* For #ifndef at start of file,
882 this is the macro name tested. */
883 enum node_type type; /* type of last directive seen in this group */
885 typedef struct if_stack IF_STACK_FRAME;
886 static IF_STACK_FRAME *if_stack = NULL;
888 /* Buffer of -M output. */
889 static char *deps_buffer;
891 /* Number of bytes allocated in above. */
892 static int deps_allocated_size;
894 /* Number of bytes used. */
895 static int deps_size;
897 /* Number of bytes since the last newline. */
898 static int deps_column;
900 /* Nonzero means -I- has been seen,
901 so don't look for #include "foo" the source-file directory. */
902 static int ignore_srcdir;
904 static int safe_read PROTO((int, char *, int));
905 static void safe_write PROTO((int, char *, int));
906 static void eprint_string PROTO((char *, size_t));
908 int main PROTO((int, char **));
910 static void path_include PROTO((char *));
912 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
914 static void trigraph_pcp PROTO((FILE_BUF *));
916 static void newline_fix PROTO((U_CHAR *));
917 static void name_newline_fix PROTO((U_CHAR *));
919 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
921 static void rescan PROTO((FILE_BUF *, int));
923 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
925 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
927 static struct tm *timestamp PROTO((void));
928 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
930 static int is_system_include PROTO((char *));
931 static char *base_name PROTO((char *));
932 static int absolute_filename PROTO((char *));
933 static size_t simplify_filename PROTO((char *));
935 static char *read_filename_string PROTO((int, FILE *));
936 static struct file_name_map *read_name_map PROTO((char *));
937 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
938 static char *remap_include_file PROTO((char *, struct file_name_list *));
939 static int lookup_ino_include PROTO((struct include_file *));
941 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
942 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
944 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
945 static int check_preconditions PROTO((char *));
946 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
947 static void pcstring_used PROTO((HASHNODE *));
948 static void write_output PROTO((void));
949 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
951 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
953 static int check_macro_name PROTO((U_CHAR *, char *));
954 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
955 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
957 static DEFINITION *collect_expansion PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
959 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
960 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
962 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
963 static void free_token_list PROTO((struct arglist *));
965 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
966 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
967 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
969 static void do_once PROTO((void));
971 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
972 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
973 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
974 static void validate_else PROTO((U_CHAR *, U_CHAR *));
976 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
977 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
978 static char *quote_string PROTO((char *, char *, size_t));
979 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
981 /* Last arg to output_line_directive. */
982 enum file_change_code {same_file, enter_file, leave_file};
983 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
985 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
988 static char *macarg PROTO((struct argdata *, int));
990 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
992 static int discard_comments PROTO((U_CHAR *, int, int));
994 static int change_newlines PROTO((U_CHAR *, int));
996 static char *my_strerror PROTO((int));
997 void error PRINTF_PROTO_1((char *, ...));
998 static void verror PROTO((char *, va_list));
999 static void error_from_errno PROTO((char *));
1000 void warning PRINTF_PROTO_1((char *, ...));
1001 static void vwarning PROTO((char *, va_list));
1002 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1003 static void verror_with_line PROTO((int, char *, va_list));
1004 static void vwarning_with_line PROTO((int, char *, va_list));
1005 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1006 void pedwarn PRINTF_PROTO_1((char *, ...));
1007 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1008 static void pedwarn_with_file_and_line PRINTF_PROTO_4((char *, size_t, int, char *, ...));
1010 static void print_containing_files PROTO((void));
1012 static int line_for_error PROTO((int));
1013 static int grow_outbuf PROTO((FILE_BUF *, int));
1015 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1016 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1017 static void delete_macro PROTO((HASHNODE *));
1018 static int hashf PROTO((U_CHAR *, int, int));
1020 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1021 static void dump_all_macros PROTO((void));
1022 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1023 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1025 static void initialize_char_syntax PROTO((void));
1026 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1028 static void make_definition PROTO((char *));
1029 static void make_undef PROTO((char *, FILE_BUF *));
1031 static void make_assertion PROTO((char *, char *));
1033 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1034 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1036 static int quote_string_for_make PROTO((char *, char *));
1037 static void deps_output PROTO((char *, int));
1039 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1040 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1041 static void perror_with_name PROTO((char *));
1042 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1043 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1045 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1046 GENERIC_PTR xmalloc PROTO((size_t));
1047 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1048 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1049 static char *savestring PROTO((char *));
1050 static void print_help PROTO((void));
1052 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1053 retrying if necessary. If MAX_READ_LEN is defined, read at most
1054 that bytes at a time. Return a negative value if an error occurs,
1055 otherwise return the actual number of bytes read,
1056 which must be LEN unless end-of-file was reached. */
1059 safe_read (desc, ptr, len)
1064 int left, rcount, nchars;
1070 if (rcount > MAX_READ_LEN)
1071 rcount = MAX_READ_LEN;
1073 nchars = read (desc, ptr, rcount);
1090 /* Write LEN bytes at PTR to descriptor DESC,
1091 retrying if necessary, and treating any real error as fatal.
1092 If MAX_WRITE_LEN is defined, write at most that many bytes at a time. */
1095 safe_write (desc, ptr, len)
1100 int wcount, written;
1104 #ifdef MAX_WRITE_LEN
1105 if (wcount > MAX_WRITE_LEN)
1106 wcount = MAX_WRITE_LEN;
1108 written = write (desc, ptr, wcount);
1115 pfatal_with_name (out_fname);
1122 /* Print a string to stderr, with extra handling in case it contains
1123 embedded NUL characters. Any present are written as is.
1125 Using fwrite for this purpose produces undesireable results on VMS
1126 when stderr happens to be a record oriented file, such as a batch log
1127 file, rather than a stream oriented one. */
1130 eprint_string (string, length)
1134 size_t segment_length;
1137 fprintf(stderr, "%s", string);
1138 length -= (segment_length = strlen(string));
1141 fputc('\0', stderr);
1143 /* Advance past the portion which has already been printed. */
1144 string += segment_length + 1;
1146 } while (length > 0);
1153 printf ("Usage: %s [switches] input output\n", progname);
1154 printf ("Switches:\n");
1155 printf (" -include <file> Include the contents of <file> before other files\n");
1156 printf (" -imacros <file> Accept definition of marcos in <file>\n");
1157 printf (" -iprefix <path> Specify <path> as a prefix for next two options\n");
1158 printf (" -iwithprefix <dir> Add <dir> to the end of the system include paths\n");
1159 printf (" -iwithprefixbefore <dir> Add <dir> to the end of the main include paths\n");
1160 printf (" -isystem <dir> Add <dir> to the start of the system include paths\n");
1161 printf (" -idirafter <dir> Add <dir> to the end of the system include paths\n");
1162 printf (" -I <dir> Add <dir> to the end of the main include paths\n");
1163 printf (" -nostdinc Do not search the system include directories\n");
1164 printf (" -nostdinc++ Do not search the system include directories for C++\n");
1165 printf (" -o <file> Put output into <file>\n");
1166 printf (" -pedantic Issue all warnings demanded by strict ANSI C\n");
1167 printf (" -traditional Follow K&R pre-processor behaviour\n");
1168 printf (" -trigraphs Support ANSI C trigraphs\n");
1169 printf (" -lang-c Assume that the input sources are in C\n");
1170 printf (" -lang-c89 Assume that the input sources are in C89\n");
1171 printf (" -lang-c++ Assume that the input sources are in C++\n");
1172 printf (" -lang-objc Assume that the input sources are in ObjectiveC\n");
1173 printf (" -lang-objc++ Assume that the input sources are in ObjectiveC++\n");
1174 printf (" -lang-asm Assume that the input sources are in assembler\n");
1175 printf (" -lang-chill Assume that the input sources are in Chill\n");
1176 printf (" -+ Allow parsing of C++ style features\n");
1177 printf (" -w Inhibit warning messages\n");
1178 printf (" -Wtrigraphs Warn if trigraphs are encountered\n");
1179 printf (" -Wno-trigraphs Do not warn about trigraphs\n");
1180 printf (" -Wcomment{s} Warn if one comment starts inside another\n");
1181 printf (" -Wno-comment{s} Do not warn about comments\n");
1182 printf (" -Wtraditional Warn if a macro argument is/would be turned into\n");
1183 printf (" a string if -tradtional is specified\n");
1184 printf (" -Wno-traditional Do not warn about stringification\n");
1185 printf (" -Wundef Warn if an undefined macro is used by #if\n");
1186 printf (" -Wno-undef Do not warn about testing udefined macros\n");
1187 printf (" -Wimport Warn about the use of the #import directive\n");
1188 printf (" -Wno-import Do not warn about the use of #import\n");
1189 printf (" -Werror Treat all warnings as errors\n");
1190 printf (" -Wno-error Do not treat warnings as errors\n");
1191 printf (" -Wall Enable all preprocessor warnings\n");
1192 printf (" -M Generate make dependencies\n");
1193 printf (" -MM As -M, but ignore system header files\n");
1194 printf (" -MD As -M, but put output in a .d file\n");
1195 printf (" -MMD As -MD, but ignore system header files\n");
1196 printf (" -MG Treat missing header file as generated files\n");
1197 printf (" -g Include #define and #undef directives in the output\n");
1198 printf (" -D<macro> Define a <macro> with string '1' as its value\n");
1199 printf (" -D<macro>=<val> Define a <macro> with <val> as its value\n");
1200 printf (" -A<question> (<answer>) Assert the <answer> to <question>\n");
1201 printf (" -U<macro> Undefine <macro> \n");
1202 printf (" -u or -undef Do not predefine any macros\n");
1203 printf (" -v Display the version number\n");
1204 printf (" -H Print the name of header files as they are used\n");
1205 printf (" -C Do not discard comments\n");
1206 printf (" -dM Display a list of macro definitions active at end\n");
1207 printf (" -dD Preserve macro definitions in output\n");
1208 printf (" -dN As -dD except that only the names are preserved\n");
1209 printf (" -dI Include #include directives in the output\n");
1210 printf (" -ifoutput Describe skipped code blocks in output \n");
1211 printf (" -P Do not generate #line directives\n");
1212 printf (" -$ Do not include '$' in identifiers\n");
1213 printf (" -remap Remap file names when including files.\n");
1214 printf (" -h or --help Display this information\n");
1227 char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1228 char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1229 char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1230 char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1231 char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1233 /* Record the option used with each element of pend_assertions.
1234 This is preparation for supporting more than one option for making
1236 char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1237 int inhibit_predefs = 0;
1238 int no_standard_includes = 0;
1239 int no_standard_cplusplus_includes = 0;
1240 int missing_newline = 0;
1242 /* Non-0 means don't output the preprocessed program. */
1243 int inhibit_output = 0;
1244 /* Non-0 means -v, so print the full set of include dirs. */
1247 /* File name which deps are being written to.
1248 This is 0 if deps are being written to stdout. */
1249 char *deps_file = 0;
1250 /* Fopen file mode to open deps_file with. */
1251 char *deps_mode = "a";
1252 /* Stream on which to print the dependency information. */
1253 FILE *deps_stream = 0;
1254 /* Target-name to write with the dependency information. */
1255 char *deps_target = 0;
1257 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1258 /* Get rid of any avoidable limit on stack size. */
1262 /* Set the stack limit huge so that alloca (particularly stringtab
1263 in dbxread.c) does not fail. */
1264 getrlimit (RLIMIT_STACK, &rlim);
1265 rlim.rlim_cur = rlim.rlim_max;
1266 setrlimit (RLIMIT_STACK, &rlim);
1271 signal (SIGPIPE, pipe_closed);
1274 progname = base_name (argv[0]);
1278 /* Remove extension from PROGNAME. */
1280 char *s = progname = savestring (progname);
1282 if ((p = rindex (s, ';')) != 0) *p = '\0'; /* strip version number */
1283 if ((p = rindex (s, '.')) != 0 /* strip type iff ".exe" */
1284 && (p[1] == 'e' || p[1] == 'E')
1285 && (p[2] == 'x' || p[2] == 'X')
1286 && (p[3] == 'e' || p[3] == 'E')
1295 /* Initialize is_idchar. */
1296 initialize_char_syntax ();
1298 no_line_directives = 0;
1300 dump_macros = dump_none;
1303 cplusplus_comments = 1;
1305 bzero ((char *) pend_files, argc * sizeof (char *));
1306 bzero ((char *) pend_defs, argc * sizeof (char *));
1307 bzero ((char *) pend_undefs, argc * sizeof (char *));
1308 bzero ((char *) pend_assertions, argc * sizeof (char *));
1309 bzero ((char *) pend_includes, argc * sizeof (char *));
1311 #ifdef MULTIBYTE_CHARS
1312 /* Change to the native locale for multibyte conversions. */
1313 setlocale (LC_CTYPE, "");
1314 literal_codeset = getenv ("LANG");
1317 /* Process switches and find input file name. */
1319 for (i = 1; i < argc; i++) {
1320 if (argv[i][0] != '-') {
1321 if (out_fname != NULL)
1324 fatal ("Too many arguments");
1326 else if (in_fname != NULL)
1327 out_fname = argv[i];
1331 switch (argv[i][1]) {
1334 if (!strcmp (argv[i], "-include")) {
1338 fatal ("Filename missing after `-include' option");
1340 simplify_filename (pend_includes[temp] = argv[++i]);
1342 if (!strcmp (argv[i], "-imacros")) {
1346 fatal ("Filename missing after `-imacros' option");
1348 simplify_filename (pend_files[temp] = argv[++i]);
1350 if (!strcmp (argv[i], "-iprefix")) {
1352 fatal ("Filename missing after `-iprefix' option");
1354 include_prefix = argv[++i];
1356 if (!strcmp (argv[i], "-ifoutput")) {
1357 output_conditionals = 1;
1359 if (!strcmp (argv[i], "-isystem")) {
1360 struct file_name_list *dirtmp;
1362 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1365 dirtmp->c_system_include_path = 1;
1367 if (before_system == 0)
1368 before_system = dirtmp;
1370 last_before_system->next = dirtmp;
1371 last_before_system = dirtmp; /* Tail follows the last one */
1373 /* Add directory to end of path for includes,
1374 with the default prefix at the front of its name. */
1375 if (!strcmp (argv[i], "-iwithprefix")) {
1376 struct file_name_list *dirtmp;
1379 if (include_prefix != 0)
1380 prefix = include_prefix;
1382 prefix = savestring (GCC_INCLUDE_DIR);
1383 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1384 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1385 prefix[strlen (prefix) - 7] = 0;
1388 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1389 prefix, argv[++i])))
1392 if (after_include == 0)
1393 after_include = dirtmp;
1395 last_after_include->next = dirtmp;
1396 last_after_include = dirtmp; /* Tail follows the last one */
1398 /* Add directory to main path for includes,
1399 with the default prefix at the front of its name. */
1400 if (!strcmp (argv[i], "-iwithprefixbefore")) {
1401 struct file_name_list *dirtmp;
1404 if (include_prefix != 0)
1405 prefix = include_prefix;
1407 prefix = savestring (GCC_INCLUDE_DIR);
1408 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1409 if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1410 prefix[strlen (prefix) - 7] = 0;
1413 dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1414 append_include_chain (dirtmp, dirtmp);
1416 /* Add directory to end of path for includes. */
1417 if (!strcmp (argv[i], "-idirafter")) {
1418 struct file_name_list *dirtmp;
1420 if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1424 if (after_include == 0)
1425 after_include = dirtmp;
1427 last_after_include->next = dirtmp;
1428 last_after_include = dirtmp; /* Tail follows the last one */
1433 if (out_fname != NULL)
1434 fatal ("Output filename specified twice");
1436 fatal ("Filename missing after -o option");
1437 out_fname = argv[++i];
1438 if (!strcmp (out_fname, "-"))
1443 if (!strcmp (argv[i], "-pedantic"))
1445 else if (!strcmp (argv[i], "-pedantic-errors")) {
1447 pedantic_errors = 1;
1448 } else if (!strcmp (argv[i], "-pcp")) {
1451 fatal ("Filename missing after -pcp option");
1452 pcp_fname = argv[++i];
1454 = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1455 ? fopen (pcp_fname, "w")
1457 if (pcp_outfile == 0)
1458 pfatal_with_name (pcp_fname);
1464 if (!strcmp (argv[i], "-traditional")) {
1466 cplusplus_comments = 0;
1467 } else if (!strcmp (argv[i], "-trigraphs")) {
1473 if (! strcmp (argv[i], "-lang-c"))
1474 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1475 if (! strcmp (argv[i], "-lang-c89"))
1476 cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1477 if (! strcmp (argv[i], "-lang-c++"))
1478 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1479 if (! strcmp (argv[i], "-lang-objc"))
1480 cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1481 if (! strcmp (argv[i], "-lang-objc++"))
1482 cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1483 if (! strcmp (argv[i], "-lang-asm"))
1485 if (! strcmp (argv[i], "-lint"))
1490 cplusplus = 1, cplusplus_comments = 1;
1494 inhibit_warnings = 1;
1498 if (!strcmp (argv[i], "-Wtrigraphs"))
1500 else if (!strcmp (argv[i], "-Wno-trigraphs"))
1502 else if (!strcmp (argv[i], "-Wcomment"))
1504 else if (!strcmp (argv[i], "-Wno-comment"))
1506 else if (!strcmp (argv[i], "-Wcomments"))
1508 else if (!strcmp (argv[i], "-Wno-comments"))
1510 else if (!strcmp (argv[i], "-Wtraditional"))
1512 else if (!strcmp (argv[i], "-Wno-traditional"))
1514 else if (!strcmp (argv[i], "-Wundef"))
1516 else if (!strcmp (argv[i], "-Wno-undef"))
1518 else if (!strcmp (argv[i], "-Wimport"))
1520 else if (!strcmp (argv[i], "-Wno-import"))
1522 else if (!strcmp (argv[i], "-Werror"))
1523 warnings_are_errors = 1;
1524 else if (!strcmp (argv[i], "-Wno-error"))
1525 warnings_are_errors = 0;
1526 else if (!strcmp (argv[i], "-Wall"))
1534 if (!strcmp (argv[i], "-fleading-underscore"))
1535 user_label_prefix = "_";
1536 else if (!strcmp (argv[i], "-fno-leading-underscore"))
1537 user_label_prefix = "";
1541 /* The style of the choices here is a bit mixed.
1542 The chosen scheme is a hybrid of keeping all options in one string
1543 and specifying each option in a separate argument:
1544 -M|-MM|-MD file|-MMD file [-MG]. An alternative is:
1545 -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1546 -M[M][G][D file]. This is awkward to handle in specs, and is not
1548 /* ??? -MG must be specified in addition to one of -M or -MM.
1549 This can be relaxed in the future without breaking anything.
1550 The converse isn't true. */
1552 /* -MG isn't valid with -MD or -MMD. This is checked for later. */
1553 if (!strcmp (argv[i], "-MG"))
1555 print_deps_missing_files = 1;
1558 if (!strcmp (argv[i], "-M"))
1560 else if (!strcmp (argv[i], "-MM"))
1562 else if (!strcmp (argv[i], "-MD"))
1564 else if (!strcmp (argv[i], "-MMD"))
1566 /* For -MD and -MMD options, write deps on file named by next arg. */
1567 if (!strcmp (argv[i], "-MD")
1568 || !strcmp (argv[i], "-MMD")) {
1570 fatal ("Filename missing after %s option", argv[i]);
1572 deps_file = argv[i];
1575 /* For -M and -MM, write deps on standard output
1576 and suppress the usual output. */
1577 deps_stream = stdout;
1584 char *p = argv[i] + 2;
1586 while ((c = *p++)) {
1587 /* Arg to -d specifies what parts of macros to dump */
1590 dump_macros = dump_only;
1594 dump_macros = dump_names;
1597 dump_macros = dump_definitions;
1608 if (argv[i][2] == '3')
1613 if (strcmp (argv[i], "--help") != 0)
1620 fprintf (stderr, "GNU CPP version %s", version_string);
1621 #ifdef TARGET_VERSION
1624 fprintf (stderr, "\n");
1629 print_include_names = 1;
1633 if (argv[i][2] != 0)
1634 pend_defs[i] = argv[i] + 2;
1635 else if (i + 1 == argc)
1636 fatal ("Macro name missing after -D option");
1638 i++, pend_defs[i] = argv[i];
1645 if (argv[i][2] != 0)
1647 else if (i + 1 == argc)
1648 fatal ("Assertion missing after -A option");
1652 if (!strcmp (p, "-")) {
1653 /* -A- eliminates all predefined macros and assertions.
1654 Let's include also any that were specified earlier
1655 on the command line. That way we can get rid of any
1656 that were passed automatically in from GCC. */
1658 inhibit_predefs = 1;
1659 for (j = 0; j < i; j++)
1660 pend_defs[j] = pend_assertions[j] = 0;
1662 pend_assertions[i] = p;
1663 pend_assertion_options[i] = "-A";
1668 case 'U': /* JF #undef something */
1669 if (argv[i][2] != 0)
1670 pend_undefs[i] = argv[i] + 2;
1671 else if (i + 1 == argc)
1672 fatal ("Macro name missing after -U option");
1674 pend_undefs[i] = argv[i+1], i++;
1678 put_out_comments = 1;
1681 case 'E': /* -E comes from cc -E; ignore it. */
1685 no_line_directives = 1;
1688 case '$': /* Don't include $ in identifiers. */
1689 is_idchar['$'] = is_idstart['$'] = 0;
1692 case 'I': /* Add directory to path for includes. */
1694 struct file_name_list *dirtmp;
1696 if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1698 /* Don't use any preceding -I directories for #include <...>. */
1699 first_bracket_include = 0;
1702 dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1703 argv[i][2] ? argv[i] + 2 : argv[++i]);
1704 append_include_chain (dirtmp, dirtmp);
1710 if (!strcmp (argv[i], "-nostdinc"))
1711 /* -nostdinc causes no default include directories.
1712 You must specify all include-file directories with -I. */
1713 no_standard_includes = 1;
1714 else if (!strcmp (argv[i], "-nostdinc++"))
1715 /* -nostdinc++ causes no default C++-specific include directories. */
1716 no_standard_cplusplus_includes = 1;
1717 else if (!strcmp (argv[i], "-noprecomp"))
1722 if (!strcmp (argv[i], "-remap"))
1727 /* Sun compiler passes undocumented switch "-undef".
1728 Let's assume it means to inhibit the predefined symbols. */
1729 inhibit_predefs = 1;
1732 case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1733 if (in_fname == NULL) {
1736 } else if (out_fname == NULL) {
1739 } /* else fall through into error */
1742 fatal ("Invalid option `%s'", argv[i]);
1747 /* Add dirs from CPATH after dirs from -I. */
1748 /* There seems to be confusion about what CPATH should do,
1749 so for the moment it is not documented. */
1750 /* Some people say that CPATH should replace the standard include dirs,
1751 but that seems pointless: it comes before them, so it overrides them
1753 GET_ENV_PATH_LIST (cp, "CPATH");
1754 if (cp && ! no_standard_includes)
1757 /* Initialize output buffer */
1759 outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1760 outbuf.bufp = outbuf.buf;
1761 outbuf.length = OUTBUF_SIZE;
1763 /* Do partial setup of input buffer for the sake of generating
1764 early #line directives (when -g is in effect). */
1766 fp = &instack[++indepth];
1767 if (in_fname == NULL)
1769 fp->nominal_fname = fp->fname = in_fname;
1770 fp->nominal_fname_len = strlen (in_fname);
1773 /* In C++, wchar_t is a distinct basic type, and we can expect
1774 __wchar_t to be defined by cc1plus. */
1776 wchar_type = "__wchar_t";
1778 /* Install __LINE__, etc. Must follow initialize_char_syntax
1779 and option processing. */
1780 initialize_builtins (fp, &outbuf);
1782 /* Do standard #defines and assertions
1783 that identify system and machine type. */
1785 if (!inhibit_predefs) {
1786 char *p = (char *) alloca (strlen (predefs) + 1);
1789 struct dsc$descriptor_s lcl_name;
1791 unsigned short length; /* input length */
1792 unsigned short code; /* item code */
1793 unsigned long dptr; /* data ptr */
1794 unsigned long lptr; /* output length ptr */
1797 unsigned long syi_length;
1800 struct item_list items[] = {
1801 { 16, SYI$_VERSION, 0, 0 },
1805 items[0].dptr = (unsigned long)syi_data;
1806 items[0].lptr = (unsigned long)(&syi_length);
1808 if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1810 unsigned long vms_version_value;
1814 vms_version_value = 0;
1818 if (ISDIGIT (*vers))
1820 vms_version_value = (*vers - '0') * 10000000;
1826 if (ISDIGIT (*vers))
1828 vms_version_value += (*vers - '0') * 100000;
1832 if (vms_version_value > 0)
1836 sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1838 output_line_directive (fp, &outbuf, 0, same_file);
1839 make_definition (versbuf);
1844 strcpy (p, predefs);
1847 while (*p == ' ' || *p == '\t')
1849 /* Handle -D options. */
1850 if (p[0] == '-' && p[1] == 'D') {
1852 while (*p && *p != ' ' && *p != '\t')
1857 output_line_directive (fp, &outbuf, 0, same_file);
1858 make_definition (q);
1859 while (*p == ' ' || *p == '\t')
1861 } else if (p[0] == '-' && p[1] == 'A') {
1862 /* Handle -A options (assertions). */
1871 past_name = assertion;
1872 /* Locate end of name. */
1873 while (*past_name && *past_name != ' '
1874 && *past_name != '\t' && *past_name != '(')
1876 /* Locate `(' at start of value. */
1878 while (*value && (*value == ' ' || *value == '\t'))
1880 if (*value++ != '(')
1882 while (*value && (*value == ' ' || *value == '\t'))
1885 /* Locate end of value. */
1886 while (*past_value && *past_value != ' '
1887 && *past_value != '\t' && *past_value != ')')
1889 termination = past_value;
1890 while (*termination && (*termination == ' ' || *termination == '\t'))
1892 if (*termination++ != ')')
1894 if (*termination && *termination != ' ' && *termination != '\t')
1896 /* Temporarily null-terminate the value. */
1897 save_char = *termination;
1898 *termination = '\0';
1899 /* Install the assertion. */
1900 make_assertion ("-A", assertion);
1901 *termination = (char) save_char;
1903 while (*p == ' ' || *p == '\t')
1911 /* Now handle the command line options. */
1913 /* Do -U's, -D's and -A's in the order they were seen. */
1914 for (i = 1; i < argc; i++) {
1915 if (pend_undefs[i]) {
1917 output_line_directive (fp, &outbuf, 0, same_file);
1918 make_undef (pend_undefs[i], &outbuf);
1922 output_line_directive (fp, &outbuf, 0, same_file);
1923 make_definition (pend_defs[i]);
1925 if (pend_assertions[i])
1926 make_assertion (pend_assertion_options[i], pend_assertions[i]);
1929 done_initializing = 1;
1931 { /* Read the appropriate environment variable and if it exists
1932 replace include_defaults with the listed path. */
1934 switch ((objc << 1) + cplusplus)
1937 GET_ENV_PATH_LIST (epath, "C_INCLUDE_PATH");
1940 GET_ENV_PATH_LIST (epath, "CPLUS_INCLUDE_PATH");
1943 GET_ENV_PATH_LIST (epath, "OBJC_INCLUDE_PATH");
1946 GET_ENV_PATH_LIST (epath, "OBJCPLUS_INCLUDE_PATH");
1949 /* If the environment var for this language is set,
1950 add to the default list of include directories. */
1953 char *startp, *endp;
1955 for (num_dirs = 1, startp = epath; *startp; startp++)
1956 if (*startp == PATH_SEPARATOR)
1959 = (struct default_include *) xmalloc ((num_dirs
1960 * sizeof (struct default_include))
1961 + sizeof (include_defaults_array));
1962 startp = endp = epath;
1966 if (c == PATH_SEPARATOR || !c) {
1968 include_defaults[num_dirs].fname
1969 = startp == endp ? "." : savestring (startp);
1971 include_defaults[num_dirs].component = 0;
1972 include_defaults[num_dirs].cplusplus = cplusplus;
1973 include_defaults[num_dirs].cxx_aware = 1;
1980 /* Put the usual defaults back in at the end. */
1981 bcopy ((char *) include_defaults_array,
1982 (char *) &include_defaults[num_dirs],
1983 sizeof (include_defaults_array));
1987 append_include_chain (before_system, last_before_system);
1988 first_system_include = before_system;
1990 /* Unless -fnostdinc,
1991 tack on the standard include file dirs to the specified list */
1992 if (!no_standard_includes) {
1993 struct default_include *p = include_defaults;
1994 char *specd_prefix = include_prefix;
1995 char *default_prefix = savestring (GCC_INCLUDE_DIR);
1996 int default_len = 0;
1997 /* Remove the `include' from /usr/local/lib/gcc.../include. */
1998 if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1999 default_len = strlen (default_prefix) - 7;
2000 default_prefix[default_len] = 0;
2002 /* Search "translated" versions of GNU directories.
2003 These have /usr/local/lib/gcc... replaced by specd_prefix. */
2004 if (specd_prefix != 0 && default_len != 0)
2005 for (p = include_defaults; p->fname; p++) {
2006 /* Some standard dirs are only for C++. */
2007 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2008 /* Does this dir start with the prefix? */
2009 if (!strncmp (p->fname, default_prefix, default_len)) {
2010 /* Yes; change prefix and add to search list. */
2011 struct file_name_list *new
2012 = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
2013 p->fname + default_len);
2015 new->c_system_include_path = !p->cxx_aware;
2016 append_include_chain (new, new);
2017 if (first_system_include == 0)
2018 first_system_include = new;
2023 /* Search ordinary names for GNU include directories. */
2024 for (p = include_defaults; p->fname; p++) {
2025 /* Some standard dirs are only for C++. */
2026 if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
2027 struct file_name_list *new
2028 = new_include_prefix (NULL_PTR, p->component, "", p->fname);
2030 new->c_system_include_path = !p->cxx_aware;
2031 append_include_chain (new, new);
2032 if (first_system_include == 0)
2033 first_system_include = new;
2039 /* Tack the after_include chain at the end of the include chain. */
2040 append_include_chain (after_include, last_after_include);
2041 if (first_system_include == 0)
2042 first_system_include = after_include;
2044 /* With -v, print the list of dirs to search. */
2046 struct file_name_list *p;
2047 fprintf (stderr, "#include \"...\" search starts here:\n");
2048 for (p = include; p; p = p->next) {
2049 if (p == first_bracket_include)
2050 fprintf (stderr, "#include <...> search starts here:\n");
2052 fprintf (stderr, " .\n");
2053 else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
2054 fprintf (stderr, " %s\n", p->fname);
2056 /* Omit trailing '/'. */
2057 fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
2059 fprintf (stderr, "End of search list.\n");
2062 /* -MG doesn't select the form of output and must be specified with one of
2063 -M or -MM. -MG doesn't make sense with -MD or -MMD since they don't
2064 inhibit compilation. */
2065 if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2066 fatal ("-MG must be specified with one of -M or -MM");
2068 /* Either of two environment variables can specify output of deps.
2069 Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2070 where OUTPUT_FILE is the file to write deps info to
2071 and DEPS_TARGET is the target to mention in the deps. */
2074 && (getenv ("SUNPRO_DEPENDENCIES") != 0
2075 || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2076 char *spec = getenv ("DEPENDENCIES_OUTPUT");
2081 spec = getenv ("SUNPRO_DEPENDENCIES");
2088 /* Find the space before the DEPS_TARGET, if there is one. */
2089 /* This should use index. (mrs) */
2090 while (*s != 0 && *s != ' ') s++;
2092 deps_target = s + 1;
2093 output_file = xmalloc (s - spec + 1);
2094 bcopy (spec, output_file, s - spec);
2095 output_file[s - spec] = 0;
2102 deps_file = output_file;
2106 /* For -M, print the expected object file name
2107 as the target of this Make-rule. */
2109 deps_allocated_size = 200;
2110 deps_buffer = xmalloc (deps_allocated_size);
2116 deps_output (deps_target, ':');
2117 } else if (*in_fname == 0) {
2118 deps_output ("-", ':');
2123 q = base_name (in_fname);
2125 /* Copy remainder to mungable area. */
2126 p = (char *) alloca (strlen(q) + 8);
2129 /* Output P, but remove known suffixes. */
2133 && p[len - 2] == '.'
2134 && index("cCsSm", p[len - 1]))
2137 && p[len - 3] == '.'
2138 && p[len - 2] == 'c'
2139 && p[len - 1] == 'c')
2142 && p[len - 4] == '.'
2143 && p[len - 3] == 'c'
2144 && p[len - 2] == 'x'
2145 && p[len - 1] == 'x')
2148 && p[len - 4] == '.'
2149 && p[len - 3] == 'c'
2150 && p[len - 2] == 'p'
2151 && p[len - 1] == 'p')
2154 /* Supply our own suffix. */
2155 strcpy (q, OBJECT_SUFFIX);
2157 deps_output (p, ':');
2158 deps_output (in_fname, ' ');
2162 /* Scan the -imacros files before the main input.
2163 Much like #including them, but with no_output set
2164 so that only their macro definitions matter. */
2166 no_output++; no_record_file++;
2167 for (i = 1; i < argc; i++)
2168 if (pend_files[i]) {
2169 struct include_file *inc;
2170 int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2172 perror_with_name (pend_files[i]);
2173 return FATAL_EXIT_CODE;
2175 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2177 no_output--; no_record_file--;
2179 /* Copy the entire contents of the main input file into
2180 the stacked input buffer previously allocated for it. */
2182 /* JF check for stdin */
2183 if (in_fname == NULL || *in_fname == 0) {
2186 } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2189 if (fstat (f, &st) != 0)
2190 pfatal_with_name (in_fname);
2191 fp->nominal_fname = fp->fname = in_fname;
2192 fp->nominal_fname_len = strlen (in_fname);
2194 fp->system_header_p = 0;
2195 /* JF all this is mine about reading pipes and ttys */
2196 if (! S_ISREG (st.st_mode)) {
2197 /* Read input from a file that is not a normal disk file.
2198 We cannot preallocate a buffer with the correct size,
2199 so we must read in the file a piece at the time and make it bigger. */
2204 if (S_ISDIR (st.st_mode))
2205 fatal ("Input file `%s' is a directory", in_fname);
2209 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2211 cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2212 if (cnt < 0) goto perror; /* error! */
2214 if (size != bsize) break; /* End of file */
2216 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2220 /* Read a file whose size we can determine in advance.
2221 For the sake of VMS, st.st_size is just an upper bound. */
2222 size_t s = (size_t) st.st_size;
2223 if (s != st.st_size || s + 2 < s)
2225 fp->buf = (U_CHAR *) xmalloc (s + 2);
2226 fp->length = safe_read (f, (char *) fp->buf, s);
2227 if (fp->length < 0) goto perror;
2230 fp->if_stack = if_stack;
2232 /* Make sure data ends with a newline. And put a null after it. */
2234 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2235 /* Backslash-newline at end is not good enough. */
2236 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2237 fp->buf[fp->length++] = '\n';
2238 missing_newline = 1;
2240 fp->buf[fp->length] = '\0';
2242 /* Unless inhibited, convert trigraphs in the input. */
2247 /* Now that we know the input file is valid, open the output. */
2249 if (!out_fname || !strcmp (out_fname, ""))
2250 out_fname = "stdout";
2251 else if (! freopen (out_fname, "w", stdout))
2252 pfatal_with_name (out_fname);
2254 output_line_directive (fp, &outbuf, 0, same_file);
2256 /* Scan the -include files before the main input. */
2259 for (i = 1; i < argc; i++)
2260 if (pend_includes[i]) {
2261 struct include_file *inc;
2262 int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2264 perror_with_name (pend_includes[i]);
2265 return FATAL_EXIT_CODE;
2267 finclude (fd, inc, &outbuf, 0, NULL_PTR);
2271 /* Scan the input, processing macros and directives. */
2273 rescan (&outbuf, 0);
2275 if (missing_newline)
2278 if (pedantic && missing_newline)
2279 pedwarn ("file does not end in newline");
2281 /* Now we have processed the entire input
2282 Write whichever kind of output has been requested. */
2284 if (dump_macros == dump_only)
2286 else if (! inhibit_output) {
2291 /* Don't actually write the deps file if compilation has failed. */
2293 if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2294 pfatal_with_name (deps_file);
2295 fputs (deps_buffer, deps_stream);
2296 putc ('\n', deps_stream);
2298 if (ferror (deps_stream) || fclose (deps_stream) != 0)
2299 fatal ("I/O error on output");
2304 if (pcp_outfile && pcp_outfile != stdout
2305 && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2306 fatal ("I/O error on `-pcp' output");
2308 if (ferror (stdout) || fclose (stdout) != 0)
2309 fatal ("I/O error on output");
2312 exit (FATAL_EXIT_CODE);
2313 exit (SUCCESS_EXIT_CODE);
2316 pfatal_with_name (in_fname);
2320 /* Given a colon-separated list of file names PATH,
2321 add all the names to the search path for include files. */
2335 struct file_name_list *dirtmp;
2337 /* Find the end of this name. */
2338 while ((c = *q++) != PATH_SEPARATOR && c)
2342 dirtmp = new_include_prefix (last_include, NULL_PTR,
2343 "", p == q ? "." : p);
2345 append_include_chain (dirtmp, dirtmp);
2347 /* Advance past this name. */
2354 /* Return the address of the first character in S that equals C.
2355 S is an array of length N, possibly containing '\0's, and followed by '\0'.
2356 Return 0 if there is no such character. Assume that C itself is not '\0'.
2357 If we knew we could use memchr, we could just invoke memchr (S, C, N),
2358 but unfortunately memchr isn't autoconfigured yet. */
2366 char *p = (char *) s;
2368 char *q = index (p, c);
2370 return (U_CHAR *) q;
2372 size_t l = strlen (p);
2382 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2383 before main CCCP processing. Name `pcp' is also in honor of the
2384 drugs the trigraph designers must have been on.
2386 Using an extra pass through the buffer takes a little extra time,
2387 but is infinitely less hairy than trying to handle trigraphs inside
2388 strings, etc. everywhere, and also makes sure that trigraphs are
2389 only translated in the top level of processing. */
2395 register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2398 fptr = bptr = sptr = buf->buf;
2399 lptr = fptr + buf->length;
2400 while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2437 len = sptr - fptr - 2;
2439 /* BSD doc says bcopy () works right for overlapping strings. In ANSI
2440 C, this will be memmove (). */
2441 if (bptr != fptr && len > 0)
2442 bcopy ((char *) fptr, (char *) bptr, len);
2448 len = buf->length - (fptr - buf->buf);
2449 if (bptr != fptr && len > 0)
2450 bcopy ((char *) fptr, (char *) bptr, len);
2451 buf->length -= fptr - bptr;
2452 buf->buf[buf->length] = '\0';
2453 if (warn_trigraphs && fptr != bptr)
2454 warning_with_line (0, "%lu trigraph(s) encountered",
2455 (unsigned long) (fptr - bptr) / 2);
2458 /* Move all backslash-newline pairs out of embarrassing places.
2459 Exchange all such pairs following BP
2460 with any potentially-embarrassing characters that follow them.
2461 Potentially-embarrassing characters are / and *
2462 (because a backslash-newline inside a comment delimiter
2463 would cause it not to be recognized). */
2469 register U_CHAR *p = bp;
2471 /* First count the backslash-newline pairs here. */
2473 while (p[0] == '\\' && p[1] == '\n')
2476 /* What follows the backslash-newlines is not embarrassing. */
2478 if (*p != '/' && *p != '*')
2481 /* Copy all potentially embarrassing characters
2482 that follow the backslash-newline pairs
2483 down to where the pairs originally started. */
2485 while (*p == '*' || *p == '/')
2488 /* Now write the same number of pairs after the embarrassing chars. */
2495 /* Like newline_fix but for use within a directive-name.
2496 Move any backslash-newlines up past any following symbol constituents. */
2499 name_newline_fix (bp)
2502 register U_CHAR *p = bp;
2504 /* First count the backslash-newline pairs here. */
2505 while (p[0] == '\\' && p[1] == '\n')
2508 /* What follows the backslash-newlines is not embarrassing. */
2513 /* Copy all potentially embarrassing characters
2514 that follow the backslash-newline pairs
2515 down to where the pairs originally started. */
2517 while (is_idchar[*p])
2520 /* Now write the same number of pairs after the embarrassing chars. */
2527 /* Look for lint commands in comments.
2529 When we come in here, ibp points into a comment. Limit is as one expects.
2530 scan within the comment -- it should start, after lwsp, with a lint command.
2531 If so that command is returned as a (constant) string.
2533 Upon return, any arg will be pointed to with argstart and will be
2534 arglen long. Note that we don't parse that arg since it will just
2535 be printed out again. */
2538 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2539 register U_CHAR *ibp;
2540 register U_CHAR *limit;
2541 U_CHAR **argstart; /* point to command arg */
2542 int *arglen, *cmdlen; /* how long they are */
2544 HOST_WIDE_INT linsize;
2545 register U_CHAR *numptr; /* temp for arg parsing */
2549 SKIP_WHITE_SPACE (ibp);
2551 if (ibp >= limit) return NULL;
2553 linsize = limit - ibp;
2555 /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2556 if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2558 return "NOTREACHED";
2560 if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2564 if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2566 return "LINTLIBRARY";
2568 if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2570 ibp += 7; linsize -= 7;
2571 if ((linsize == 0) || ! ISDIGIT (*ibp)) return "VARARGS";
2573 /* OK, read a number */
2574 for (numptr = *argstart = ibp; (numptr < limit) && ISDIGIT (*numptr);
2576 *arglen = numptr - *argstart;
2583 * The main loop of the program.
2585 * Read characters from the input stack, transferring them to the
2588 * Macros are expanded and push levels on the input stack.
2589 * At the end of such a level it is popped off and we keep reading.
2590 * At the end of any other kind of level, we return.
2591 * #-directives are handled, except within macros.
2593 * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2594 * and insert them when appropriate. This is set while scanning macro
2595 * arguments before substitution. It is zero when scanning for final output.
2596 * There are three types of Newline markers:
2597 * * Newline - follows a macro name that was not expanded
2598 * because it appeared inside an expansion of the same macro.
2599 * This marker prevents future expansion of that identifier.
2600 * When the input is rescanned into the final output, these are deleted.
2601 * These are also deleted by ## concatenation.
2602 * * Newline Space (or Newline and any other whitespace character)
2603 * stands for a place that tokens must be separated or whitespace
2604 * is otherwise desirable, but where the ANSI standard specifies there
2605 * is no whitespace. This marker turns into a Space (or whichever other
2606 * whitespace char appears in the marker) in the final output,
2607 * but it turns into nothing in an argument that is stringified with #.
2608 * Such stringified arguments are the only place where the ANSI standard
2609 * specifies with precision that whitespace may not appear.
2611 * During this function, IP->bufp is kept cached in IBP for speed of access.
2612 * Likewise, OP->bufp is kept in OBP. Before calling a subroutine
2613 * IBP, IP and OBP must be copied back to memory. IP and IBP are
2614 * copied back with the RECACHE macro. OBP must be copied back from OP->bufp
2615 * explicitly, and before RECACHE, since RECACHE uses OBP.
2619 rescan (op, output_marks)
2623 /* Character being scanned in main loop. */
2626 /* Length of pending accumulated identifier. */
2627 register int ident_length = 0;
2629 /* Hash code of pending accumulated identifier. */
2630 register int hash = 0;
2632 /* Current input level (&instack[indepth]). */
2635 /* Pointer for scanning input. */
2636 register U_CHAR *ibp;
2638 /* Pointer to end of input. End of scan is controlled by LIMIT. */
2639 register U_CHAR *limit;
2641 /* Pointer for storing output. */
2642 register U_CHAR *obp;
2644 /* REDO_CHAR is nonzero if we are processing an identifier
2645 after backing up over the terminating character.
2646 Sometimes we process an identifier without backing up over
2647 the terminating character, if the terminating character
2648 is not special. Backing up is done so that the terminating character
2649 will be dispatched on again once the identifier is dealt with. */
2652 /* 1 if within an identifier inside of which a concatenation
2653 marker (Newline -) has been seen. */
2654 int concatenated = 0;
2656 /* While scanning a comment or a string constant,
2657 this records the line it started on, for error messages. */
2660 /* Record position of last `real' newline. */
2661 U_CHAR *beg_of_line;
2663 /* Pop the innermost input stack level, assuming it is a macro expansion. */
2666 do { ip->macro->type = T_MACRO; \
2667 if (ip->free_ptr) free (ip->free_ptr); \
2668 --indepth; } while (0)
2670 /* Reload `rescan's local variables that describe the current
2671 level of the input stack. */
2674 do { ip = &instack[indepth]; \
2676 limit = ip->buf + ip->length; \
2678 check_expand (op, limit - ibp); \
2680 obp = op->bufp; } while (0)
2682 if (no_output && instack[indepth].fname != 0)
2683 skip_if_group (&instack[indepth], 1, NULL);
2690 /* Our caller must always put a null after the end of
2691 the input at each input stack level. */
2701 if (*ibp == '\n' && !ip->macro) {
2702 /* At the top level, always merge lines ending with backslash-newline,
2703 even in middle of identifier. But do not merge lines in a macro,
2704 since backslash might be followed by a newline-space marker. */
2707 --obp; /* remove backslash from obuf */
2710 /* If ANSI, backslash is just another character outside a string. */
2713 /* Otherwise, backslash suppresses specialness of following char,
2714 so copy it here to prevent the switch from seeing it.
2715 But first get any pending identifier processed. */
2716 if (ident_length > 0)
2723 if (ident_length || ip->macro || traditional)
2725 while (*ibp == '\\' && ibp[1] == '\n') {
2731 /* Treat this %: digraph as if it were #. */
2735 if (assertions_flag) {
2738 /* Copy #foo (bar lose) without macro expansion. */
2739 obp[-1] = '#'; /* In case it was '%'. */
2740 SKIP_WHITE_SPACE (ibp);
2741 while (is_idchar[*ibp])
2743 SKIP_WHITE_SPACE (ibp);
2746 skip_paren_group (ip);
2747 bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2748 obp += ip->bufp - ibp;
2754 /* If this is expanding a macro definition, don't recognize
2755 preprocessing directives. */
2758 /* If this is expand_into_temp_buffer,
2759 don't recognize them either. Warn about them
2760 only after an actual newline at this level,
2761 not at the beginning of the input level. */
2763 if (ip->buf != beg_of_line)
2764 warning ("preprocessing directive not recognized within macro arg");
2771 /* # keyword: a # must be first nonblank char on the line */
2772 if (beg_of_line == 0)
2777 /* Scan from start of line, skipping whitespace, comments
2778 and backslash-newlines, and see if we reach this #.
2779 If not, this # is not special. */
2781 /* If -traditional, require # to be at beginning of line. */
2784 if (is_hor_space[*bp])
2786 else if (*bp == '\\' && bp[1] == '\n')
2788 else if (*bp == '/' && bp[1] == '*') {
2802 #ifdef MULTIBYTE_CHARS
2804 length = local_mblen (bp, limit - bp);
2812 /* There is no point in trying to deal with C++ // comments here,
2813 because if there is one, then this # must be part of the
2814 comment and we would never reach here. */
2820 while (bp[1] == '\\' && bp[2] == '\n')
2824 /* %: appears at start of line; skip past the ':' too. */
2833 /* This # can start a directive. */
2835 --obp; /* Don't copy the '#' */
2839 if (! handle_directive (ip, op)) {
2843 /* Not a known directive: treat it as ordinary text.
2844 IP, OP, IBP, etc. have not been changed. */
2845 if (no_output && instack[indepth].fname) {
2846 /* If not generating expanded output,
2847 what we do with ordinary text is skip it.
2848 Discard everything until next # directive. */
2849 skip_if_group (&instack[indepth], 1, 0);
2854 *obp++ = '#'; /* Copy # (even if it was originally %:). */
2855 /* Don't expand an identifier that could be a macro directive.
2856 (Section 3.8.3 of the ANSI C standard) */
2857 SKIP_WHITE_SPACE (ibp);
2858 if (is_idstart[*ibp])
2861 while (is_idchar[*ibp])
2869 /* A # directive has been successfully processed. */
2870 /* If not generating expanded output, ignore everything until
2871 next # directive. */
2872 if (no_output && instack[indepth].fname)
2873 skip_if_group (&instack[indepth], 1, 0);
2879 case '\"': /* skip quoted string */
2881 /* A single quoted string is treated like a double -- some
2882 programs (e.g., troff) are perverse this way */
2884 /* Handle any pending identifier;
2885 but the L in L'...' or L"..." is not an identifier. */
2887 if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2889 ident_length = hash = 0;
2892 start_line = ip->lineno;
2894 /* Skip ahead to a matching quote. */
2898 if (ip->macro != 0) {
2899 /* try harder: this string crosses a macro expansion boundary.
2900 This can happen naturally if -traditional.
2901 Otherwise, only -D can make a macro with an unmatched quote. */
2907 error_with_line (line_for_error (start_line),
2908 "unterminated string or character constant");
2909 if (multiline_string_line) {
2910 error_with_line (multiline_string_line,
2911 "possible real start of unterminated constant");
2912 multiline_string_line = 0;
2922 /* Traditionally, end of line ends a string constant with no error.
2923 So exit the loop and record the new line. */
2929 error_with_line (line_for_error (start_line),
2930 "unterminated character constant");
2933 if (multiline_string_line == 0) {
2935 pedwarn_with_line (line_for_error (start_line),
2936 "string constant runs past end of line");
2937 multiline_string_line = ip->lineno - 1;
2943 /* Backslash newline is replaced by nothing at all, but
2944 keep the line counts correct. But if we are reading
2945 from a macro, keep the backslash newline, since backslash
2946 newlines have already been processed. */
2954 /* ANSI stupidly requires that in \\ the second \
2955 is *not* prevented from combining with a newline. */
2957 while (*ibp == '\\' && ibp[1] == '\n') {
2971 #ifdef MULTIBYTE_CHARS
2976 length = local_mblen (ibp, limit - ibp);
2980 bcopy (ibp, obp, length);
2997 if (*ibp == '\\' && ibp[1] == '\n')
3000 && !(cplusplus_comments && *ibp == '/'))
3006 /* C++ style comment... */
3007 start_line = ip->lineno;
3009 /* Comments are equivalent to spaces. */
3010 if (! put_out_comments)
3014 U_CHAR *before_bp = ibp;
3016 while (++ibp < limit) {
3019 if (put_out_comments) {
3020 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3021 obp += ibp - before_bp;
3027 if (ibp + 1 < limit && ibp[1] == '\n')
3030 warning ("multiline `//' comment");
3032 /* Copy the newline into the output buffer, in order to
3033 avoid the pain of a #line every time a multiline comment
3035 if (!put_out_comments)
3043 #ifdef MULTIBYTE_CHARS
3045 length = local_mblen (ibp, limit - ibp);
3047 ibp += (length - 1);
3055 /* Ordinary C comment. Skip it, optionally copying it to output. */
3057 start_line = ip->lineno;
3059 ++ibp; /* Skip the star. */
3061 /* If this cpp is for lint, we peek inside the comments: */
3065 char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
3067 if (lintcmd != NULL) {
3069 check_expand (op, cmdlen + arglen + 14);
3071 /* I believe it is always safe to emit this newline: */
3073 bcopy ("#pragma lint ", (char *) obp, 13);
3075 bcopy (lintcmd, (char *) obp, cmdlen);
3080 bcopy (argbp, (char *) obp, arglen);
3084 /* OK, now bring us back to the state we were in before we entered
3085 this branch. We need #line because the #pragma's newline always
3086 messes up the line count. */
3088 output_line_directive (ip, op, 0, same_file);
3089 check_expand (op, limit - ibp + 2);
3095 /* Comments are equivalent to spaces.
3096 Note that we already output the slash; we might not want it.
3097 For -traditional, a comment is equivalent to nothing. */
3098 if (! put_out_comments) {
3108 U_CHAR *before_bp = ibp;
3113 if (ibp[-2] == '/' && warn_comments)
3114 warning ("`/*' within comment");
3115 if (*ibp == '\\' && ibp[1] == '\n')
3123 /* Copy the newline into the output buffer, in order to
3124 avoid the pain of a #line every time a multiline comment
3126 if (!put_out_comments)
3133 error_with_line (line_for_error (start_line),
3134 "unterminated comment");
3138 #ifdef MULTIBYTE_CHARS
3142 length = local_mblen (ibp, limit - ibp);
3144 ibp += (length - 1);
3153 if (put_out_comments) {
3154 bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3155 obp += ibp - before_bp;
3161 if (! is_idchar['$'])
3164 pedwarn ("`$' in identifier");
3167 case '0': case '1': case '2': case '3': case '4':
3168 case '5': case '6': case '7': case '8': case '9':
3169 /* If digit is not part of identifier, it starts a number,
3170 which means that following letters are not an identifier.
3171 "0x5" does not refer to an identifier "x5".
3172 So copy all alphanumerics that follow without accumulating
3173 as an identifier. Periods also, for sake of "3.e7". */
3175 if (ident_length == 0) {
3178 while (ibp[0] == '\\' && ibp[1] == '\n') {
3184 if (!is_idchar[c] && c != '.') {
3189 /* A sign can be part of a preprocessing number
3190 if it follows an `e' or `p'. */
3191 if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3193 while (ibp[0] == '\\' && ibp[1] == '\n') {
3198 if (*ibp == '+' || *ibp == '-') {
3200 /* But traditional C does not let the token go past the sign,
3201 and C89 does not allow `p'. */
3202 if (traditional || (c89 && (c == 'p' || c == 'P')))
3212 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3213 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3214 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3215 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3217 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3218 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3219 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3220 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3224 /* Compute step of hash function, to avoid a proc call on every token */
3225 hash = HASHSTEP (hash, c);
3229 if (ip->fname == 0 && *ibp == '-') {
3230 /* Newline - inhibits expansion of preceding token.
3231 If expanding a macro arg, we keep the newline -.
3232 In final output, it is deleted.
3233 We recognize Newline - in macro bodies and macro args. */
3234 if (! concatenated) {
3239 if (!output_marks) {
3242 /* If expanding a macro arg, keep the newline -. */
3248 /* If reprocessing a macro expansion, newline is a special marker. */
3249 else if (ip->macro != 0) {
3250 /* Newline White is a "funny space" to separate tokens that are
3251 supposed to be separate but without space between.
3252 Here White means any whitespace character.
3253 Newline - marks a recursive macro use that is not
3254 supposed to be expandable. */
3256 if (is_space[*ibp]) {
3257 /* Newline Space does not prevent expansion of preceding token
3258 so expand the preceding token and then come back. */
3259 if (ident_length > 0)
3262 /* If generating final output, newline space makes a space. */
3263 if (!output_marks) {
3265 /* And Newline Newline makes a newline, so count it. */
3266 if (obp[-1] == '\n')
3269 /* If expanding a macro arg, keep the newline space.
3270 If the arg gets stringified, newline space makes nothing. */
3273 } else abort (); /* Newline followed by something random? */
3277 /* If there is a pending identifier, handle it and come back here. */
3278 if (ident_length > 0)
3283 /* Update the line counts and output a #line if necessary. */
3286 if (ip->lineno != op->lineno) {
3288 output_line_directive (ip, op, 1, same_file);
3289 check_expand (op, limit - ibp);
3294 /* Come here either after (1) a null character that is part of the input
3295 or (2) at the end of the input, because there is a null there. */
3298 /* Our input really contains a null character. */
3302 /* At end of a macro-expansion level, pop it and read next level. */
3303 if (ip->macro != 0) {
3306 /* If traditional, and we have an identifier that ends here,
3307 process it now, so we get the right error for recursion. */
3308 if (traditional && ident_length
3309 && ! is_idchar[*instack[indepth - 1].bufp]) {
3318 /* If we don't have a pending identifier,
3319 return at end of input. */
3320 if (ident_length == 0) {
3328 /* If we do have a pending identifier, just consider this null
3329 a special character and arrange to dispatch on it again.
3330 The second time, IDENT_LENGTH will be zero so we will return. */
3336 /* Handle the case of a character such as /, ', " or null
3337 seen following an identifier. Back over it so that
3338 after the identifier is processed the special char
3339 will be dispatched on again. */
3349 if (ident_length > 0) {
3350 register HASHNODE *hp;
3352 /* We have just seen an identifier end. If it's a macro, expand it.
3354 IDENT_LENGTH is the length of the identifier
3355 and HASH is its hash code.
3357 The identifier has already been copied to the output,
3358 so if it is a macro we must remove it.
3360 If REDO_CHAR is 0, the char that terminated the identifier
3361 has been skipped in the output and the input.
3362 OBP-IDENT_LENGTH-1 points to the identifier.
3363 If the identifier is a macro, we must back over the terminator.
3365 If REDO_CHAR is 1, the terminating char has already been
3366 backed over. OBP-IDENT_LENGTH points to the identifier. */
3368 if (!pcp_outfile || pcp_inside_if) {
3369 for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3372 if (hp->length == ident_length) {
3373 int obufp_before_macroname;
3374 int op_lineno_before_macroname;
3375 register int i = ident_length;
3376 register U_CHAR *p = hp->name;
3377 register U_CHAR *q = obp - i;
3383 do { /* All this to avoid a strncmp () */
3388 /* We found a use of a macro name.
3389 see if the context shows it is a macro call. */
3391 /* Back up over terminating character if not already done. */
3397 /* Save this as a displacement from the beginning of the output
3398 buffer. We can not save this as a position in the output
3399 buffer, because it may get realloc'ed by RECACHE. */
3400 obufp_before_macroname = (obp - op->buf) - ident_length;
3401 op_lineno_before_macroname = op->lineno;
3403 if (hp->type == T_PCSTRING) {
3404 pcstring_used (hp); /* Mark the definition of this key
3405 as needed, ensuring that it
3407 break; /* Exit loop, since the key cannot have a
3408 definition any longer. */
3411 /* Record whether the macro is disabled. */
3412 disabled = hp->type == T_DISABLED;
3414 /* This looks like a macro ref, but if the macro was disabled,
3415 just copy its name and put in a marker if requested. */
3419 /* This error check caught useful cases such as
3420 #define foo(x,y) bar (x (y,0), y)
3423 error ("recursive use of macro `%s'", hp->name);
3427 check_expand (op, limit - ibp + 2);
3434 /* If macro wants an arglist, verify that a '(' follows.
3435 first skip all whitespace, copying it to the output
3436 after the macro name. Then, if there is no '(',
3437 decide this is not a macro call and leave things that way. */
3438 if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3439 && hp->value.defn->nargs >= 0)
3441 U_CHAR *old_ibp = ibp;
3442 U_CHAR *old_obp = obp;
3443 int old_iln = ip->lineno;
3444 int old_oln = op->lineno;
3447 /* Scan forward over whitespace, copying it to the output. */
3448 if (ibp == limit && ip->macro != 0) {
3453 old_iln = ip->lineno;
3454 old_oln = op->lineno;
3456 else if (is_space[*ibp]) {
3458 if (ibp[-1] == '\n') {
3459 if (ip->macro == 0) {
3460 /* Newline in a file. Count it. */
3463 } else if (!output_marks) {
3464 /* A newline mark, and we don't want marks
3465 in the output. If it is newline-hyphen,
3466 discard it entirely. Otherwise, it is
3467 newline-whitechar, so keep the whitechar. */
3477 /* A newline mark; copy both chars to the output. */
3484 else if (*ibp == '/') {
3485 /* If a comment, copy it unchanged or discard it. */
3486 if (ibp[1] == '\\' && ibp[2] == '\n')
3487 newline_fix (ibp + 1);
3488 if (ibp[1] == '*') {
3489 if (put_out_comments) {
3492 } else if (! traditional) {
3495 for (ibp += 2; ibp < limit; ibp++) {
3496 /* We need not worry about newline-marks,
3497 since they are never found in comments. */
3498 if (ibp[0] == '*') {
3499 if (ibp[1] == '\\' && ibp[2] == '\n')
3500 newline_fix (ibp + 1);
3501 if (ibp[1] == '/') {
3503 if (put_out_comments) {
3510 else if (*ibp == '\n') {
3511 /* Newline in a file. Count it. */
3517 #ifdef MULTIBYTE_CHARS
3519 length = local_mblen (ibp, limit - ibp);
3522 if (put_out_comments)
3524 bcopy (ibp, obp, length - 1);
3527 ibp += (length - 1);
3531 if (put_out_comments)
3534 } else if (ibp[1] == '/' && cplusplus_comments) {
3535 if (put_out_comments) {
3538 } else if (! traditional) {
3541 for (ibp += 2; ; ibp++)
3545 if (*ibp == '\\' && ibp[1] == '\n')
3547 if (put_out_comments)
3552 #ifdef MULTIBYTE_CHARS
3554 length = local_mblen (ibp, limit - ibp);
3557 if (put_out_comments)
3559 bcopy (ibp, obp, length - 1);
3562 ibp += (length - 1);
3566 if (put_out_comments)
3572 else if (ibp[0] == '\\' && ibp[1] == '\n') {
3579 /* It isn't a macro call.
3580 Put back the space that we just skipped. */
3583 ip->lineno = old_iln;
3584 op->lineno = old_oln;
3585 /* Exit the for loop. */
3590 /* This is now known to be a macro call.
3591 Discard the macro name from the output,
3592 along with any following whitespace just copied,
3593 but preserve newlines if not outputting marks since this
3594 is more likely to do the right thing with line numbers. */
3595 obp = op->buf + obufp_before_macroname;
3597 op->lineno = op_lineno_before_macroname;
3599 int newlines = op->lineno - op_lineno_before_macroname;
3600 while (0 < newlines--)
3604 /* Prevent accidental token-pasting with a character
3605 before the macro call. */
3606 if (!traditional && obp != op->buf) {
3608 case '!': case '%': case '&': case '*':
3609 case '+': case '-': case '.': case '/':
3610 case ':': case '<': case '=': case '>':
3612 /* If we are expanding a macro arg, make a newline marker
3613 to separate the tokens. If we are making real output,
3614 a plain space will do. */
3621 /* Expand the macro, reading arguments as needed,
3622 and push the expansion on the input stack. */
3625 macroexpand (hp, op);
3627 /* Reexamine input stack, since macroexpand has pushed
3628 a new level on it. */
3635 } /* End hash-table-search loop */
3637 ident_length = hash = 0; /* Stop collecting identifier */
3640 } /* End if (ident_length > 0) */
3642 } /* End per-char loop */
3644 /* Come here to return -- but first give an error message
3645 if there was an unterminated successful conditional. */
3647 if (if_stack != ip->if_stack)
3651 switch (if_stack->type)
3672 error_with_line (line_for_error (if_stack->lineno),
3673 "unterminated `#%s' conditional", str);
3675 if_stack = ip->if_stack;
3679 * Rescan a string into a temporary buffer and return the result
3680 * as a FILE_BUF. Note this function returns a struct, not a pointer.
3682 * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3683 * and insert such markers when appropriate. See `rescan' for details.
3684 * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3685 * before substitution; it is 0 for other uses.
3688 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3689 U_CHAR *buf, *limit;
3690 int output_marks, assertions;
3692 register FILE_BUF *ip;
3694 int length = limit - buf;
3696 int odepth = indepth;
3697 int save_assertions_flag = assertions_flag;
3699 assertions_flag = assertions;
3704 /* Set up the input on the input stack. */
3706 buf1 = (U_CHAR *) alloca (length + 1);
3708 register U_CHAR *p1 = buf;
3709 register U_CHAR *p2 = buf1;
3716 /* Set up to receive the output. */
3718 obuf.length = length * 2 + 100; /* Usually enough. Why be stingy? */
3719 obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3720 obuf.nominal_fname = 0;
3727 obuf.system_header_p = 0;
3729 CHECK_DEPTH ({return obuf;});
3733 ip = &instack[indepth];
3735 ip->nominal_fname = 0;
3736 ip->nominal_fname_len = 0;
3738 ip->system_header_p = 0;
3741 ip->length = length;
3742 ip->buf = ip->bufp = buf1;
3743 ip->if_stack = if_stack;
3745 ip->lineno = obuf.lineno = 1;
3747 /* Scan the input, create the output. */
3748 rescan (&obuf, output_marks);
3750 /* Pop input stack to original state. */
3753 if (indepth != odepth)
3756 /* Record the output. */
3757 obuf.length = obuf.bufp - obuf.buf;
3759 assertions_flag = save_assertions_flag;
3764 * Process a # directive. Expects IP->bufp to point after the '#', as in
3765 * `#define foo bar'. Passes to the directive handler
3766 * (do_define, do_include, etc.): the addresses of the 1st and
3767 * last chars of the directive (starting immediately after the #
3768 * keyword), plus op and the keyword table pointer. If the directive
3769 * contains comments it is copied into a temporary buffer sans comments
3770 * and the temporary buffer is passed to the directive handler instead.
3771 * Likewise for backslash-newlines.
3773 * Returns nonzero if this was a known # directive.
3774 * Otherwise, returns zero, without advancing the input pointer.
3778 handle_directive (ip, op)
3781 register U_CHAR *bp, *cp;
3782 register struct directive *kt;
3783 register int ident_length;
3786 /* Nonzero means we must copy the entire directive
3787 to get rid of comments or backslash-newlines. */
3788 int copy_directive = 0;
3790 U_CHAR *ident, *after_ident;
3794 /* Record where the directive started. do_xifdef needs this. */
3795 directive_start = bp - 1;
3797 /* Skip whitespace and \-newline. */
3799 if (is_hor_space[*bp]) {
3800 if (*bp != ' ' && *bp != '\t' && pedantic)
3801 pedwarn ("%s in preprocessing directive", char_name[*bp]);
3803 } else if (*bp == '/') {
3804 if (bp[1] == '\\' && bp[2] == '\n')
3805 newline_fix (bp + 1);
3806 if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3809 skip_to_end_of_comment (ip, &ip->lineno, 0);
3811 } else if (*bp == '\\' && bp[1] == '\n') {
3812 bp += 2; ip->lineno++;
3816 /* Now find end of directive name.
3817 If we encounter a backslash-newline, exchange it with any following
3818 symbol-constituents so that we end up with a contiguous name. */
3825 if (*cp == '\\' && cp[1] == '\n')
3826 name_newline_fix (cp);
3832 ident_length = cp - bp;
3836 /* A line of just `#' becomes blank. */
3838 if (ident_length == 0 && *after_ident == '\n') {
3839 ip->bufp = after_ident;
3843 if (ident_length == 0 || !is_idstart[*ident]) {
3845 while (is_idchar[*p]) {
3846 if (*p < '0' || *p > '9')
3850 /* Handle # followed by a line number. */
3851 if (p != ident && !is_idchar[*p]) {
3852 static struct directive line_directive_table[] = {
3853 { 4, do_line, "line", T_LINE},
3856 pedwarn ("`#' followed by integer");
3857 after_ident = ident;
3858 kt = line_directive_table;
3862 /* Avoid error for `###' and similar cases unless -pedantic. */
3864 while (*p == '#' || is_hor_space[*p]) p++;
3866 if (pedantic && !lang_asm)
3867 warning ("invalid preprocessing directive");
3873 error ("invalid preprocessing directive name");
3879 * Decode the keyword and call the appropriate expansion
3880 * routine, after moving the input pointer up to the next line.
3882 for (kt = directive_table; kt->length > 0; kt++) {
3883 if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3884 register U_CHAR *buf;
3885 register U_CHAR *limit;
3888 int *already_output;
3890 /* Nonzero means do not delete comments within the directive.
3891 #define needs this when -traditional. */
3896 limit = ip->buf + ip->length;
3899 keep_comments = traditional && kt->type == T_DEFINE;
3900 /* #import is defined only in Objective C, or when on the NeXT. */
3901 if (kt->type == T_IMPORT
3902 && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3905 /* Find the end of this directive (first newline not backslashed
3906 and not in a string or comment).
3907 Set COPY_DIRECTIVE if the directive must be copied
3908 (it contains a backslash-newline or a comment). */
3910 buf = bp = after_ident;
3911 while (bp < limit) {
3912 register U_CHAR c = *bp++;
3920 } else if (traditional)
3926 /* "..." is special for #include. */
3927 if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3928 while (bp < limit && *bp != '\n') {
3933 if (*bp == '\\' && bp[1] == '\n') {
3944 bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, ©_directive, &unterminated);
3945 /* Don't bother calling the directive if we already got an error
3946 message due to unterminated string. Skip everything and pretend
3947 we called the directive. */
3950 /* Traditional preprocessing permits unterminated strings. */
3959 /* <...> is special for #include. */
3961 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3963 while (bp < limit && *bp != '>' && *bp != '\n') {
3964 if (*bp == '\\' && bp[1] == '\n') {
3974 if (*bp == '\\' && bp[1] == '\n')
3977 || (cplusplus_comments && *bp == '/')) {
3978 U_CHAR *obp = bp - 1;
3980 skip_to_end_of_comment (ip, &ip->lineno, 0);
3982 /* No need to copy the directive because of a comment at the end;
3983 just don't include the comment in the directive. */
3984 if (!put_out_comments) {
3986 for (p = bp; *p == ' ' || *p == '\t'; p++)
3993 /* Don't remove the comments if -traditional. */
3994 if (! keep_comments)
4003 pedwarn ("%s in preprocessing directive", char_name[c]);
4007 --bp; /* Point to the newline */
4015 resume_p = ip->bufp;
4016 /* BP is the end of the directive.
4017 RESUME_P is the next interesting data after the directive.
4018 A comment may come between. */
4020 /* If a directive should be copied through, and -C was given,
4021 pass it through before removing comments. */
4022 if (!no_output && put_out_comments
4023 && (kt->type == T_DEFINE ? dump_macros == dump_definitions
4024 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4025 : kt->type == T_PRAGMA)) {
4028 /* Output directive name. */
4029 check_expand (op, kt->length + 2);
4030 /* Make sure # is at the start of a line */
4031 if (op->bufp > op->buf && op->bufp[-1] != '\n') {
4036 bcopy (kt->name, op->bufp, kt->length);
4037 op->bufp += kt->length;
4039 /* Output arguments. */
4041 check_expand (op, len);
4042 bcopy (buf, (char *) op->bufp, len);
4044 /* Take account of any (escaped) newlines just output. */
4046 if (buf[len] == '\n')
4049 already_output = &junk;
4050 } /* Don't we need a newline or #line? */
4052 if (copy_directive) {
4053 register U_CHAR *xp = buf;
4054 /* Need to copy entire directive into temp buffer before dispatching */
4056 cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
4060 /* Copy to the new buffer, deleting comments
4061 and backslash-newlines (and whitespace surrounding the latter). */
4064 register U_CHAR c = *xp++;
4069 abort (); /* A bare newline should never part of the line. */
4072 /* <...> is special for #include. */
4074 if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
4076 while (xp < bp && c != '>') {
4078 if (c == '\\' && xp < bp && *xp == '\n')
4089 if (cp != buf && is_hor_space[cp[-1]]) {
4090 while (cp - 1 != buf && is_hor_space[cp[-2]])
4092 SKIP_WHITE_SPACE (xp);
4093 } else if (is_hor_space[*xp]) {
4095 SKIP_WHITE_SPACE (xp);
4097 } else if (traditional && xp < bp) {
4105 register U_CHAR *bp1
4106 = skip_quoted_string (xp - 1, bp, ip->lineno,
4107 NULL_PTR, NULL_PTR, NULL_PTR);
4115 || (cplusplus_comments && *xp == '/')) {
4117 /* If we already copied the directive through,
4118 already_output != 0 prevents outputting comment now. */
4119 skip_to_end_of_comment (ip, already_output, 0);
4121 while (xp != ip->bufp)
4123 /* Delete or replace the slash. */
4124 else if (traditional)
4133 /* Null-terminate the copy. */
4139 ip->bufp = resume_p;
4141 /* Some directives should be written out for cc1 to process,
4142 just as if they were not defined. And sometimes we're copying
4143 directives through. */
4145 if (!no_output && already_output == 0
4146 && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
4147 : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
4148 : kt->type == T_PRAGMA)) {
4151 /* Output directive name. */
4152 check_expand (op, kt->length + 1);
4154 bcopy (kt->name, (char *) op->bufp, kt->length);
4155 op->bufp += kt->length;
4157 if (kt->type == T_DEFINE && dump_macros == dump_names) {
4158 /* Output `#define name' only. */
4161 SKIP_WHITE_SPACE (xp);
4163 while (is_idchar[*xp]) xp++;
4165 check_expand (op, len + 1);
4167 bcopy (yp, (char *) op->bufp, len);
4169 /* Output entire directive. */
4171 check_expand (op, len);
4172 bcopy (buf, (char *) op->bufp, len);
4175 } /* Don't we need a newline or #line? */
4177 /* Call the appropriate directive handler. buf now points to
4178 either the appropriate place in the input buffer, or to
4179 the temp buffer if it was necessary to make one. cp
4180 points to the first char after the contents of the (possibly
4181 copied) directive, in either case. */
4182 (*kt->func) (buf, cp, op, kt);
4183 check_expand (op, ip->length - (ip->bufp - ip->buf));
4189 /* It is deliberate that we don't warn about undefined directives.
4190 That is the responsibility of cc1. */
4197 static struct tm *timebuf;
4199 time_t t = time ((time_t *) 0);
4200 timebuf = localtime (&t);
4205 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4206 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4210 * expand things like __FILE__. Place the expansion into the output
4211 * buffer *without* rescanning.
4215 special_symbol (hp, op)
4222 FILE_BUF *ip = NULL;
4225 int paren = 0; /* For special `defined' keyword */
4227 if (pcp_outfile && pcp_inside_if
4228 && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4229 error ("Predefined macro `%s' used inside `#if' during precompilation",
4232 for (i = indepth; i >= 0; i--)
4233 if (instack[i].fname != NULL) {
4238 error ("cccp error: not in any file?!");
4239 return; /* the show must go on */
4246 FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4247 char *string = p->nominal_fname;
4251 size_t string_len = p->nominal_fname_len;
4252 buf = (char *) alloca (3 + 4 * string_len);
4253 quote_string (buf, string, string_len);
4261 case T_INCLUDE_LEVEL:
4263 for (i = indepth; i >= 0; i--)
4264 if (instack[i].fname != NULL)
4267 buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
4268 sprintf (buf, "%d", true_indepth - 1);
4272 buf = (char *) alloca (3 + strlen (version_string));
4273 sprintf (buf, "\"%s\"", version_string);
4276 #ifndef NO_BUILTIN_SIZE_TYPE
4282 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4283 case T_PTRDIFF_TYPE:
4292 case T_USER_LABEL_PREFIX_TYPE:
4293 buf = user_label_prefix;
4296 case T_REGISTER_PREFIX_TYPE:
4297 buf = REGISTER_PREFIX;
4300 case T_IMMEDIATE_PREFIX_TYPE:
4301 buf = IMMEDIATE_PREFIX;
4305 buf = hp->value.cpval;
4306 #ifdef STDC_0_IN_SYSTEM_HEADERS
4307 if (ip->system_header_p
4308 && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4309 && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4312 if (pcp_inside_if && pcp_outfile)
4313 /* Output a precondition for this macro use */
4314 fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4318 buf = (char *) alloca (10);
4319 sprintf (buf, "%d", ip->lineno);
4324 buf = (char *) alloca (20);
4325 timebuf = timestamp ();
4326 if (hp->type == T_DATE)
4327 sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4328 timebuf->tm_mday, timebuf->tm_year + 1900);
4330 sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4334 case T_SPEC_DEFINED:
4335 buf = " 0 "; /* Assume symbol is not defined */
4336 ip = &instack[indepth];
4337 SKIP_WHITE_SPACE (ip->bufp);
4338 if (*ip->bufp == '(') {
4340 ip->bufp++; /* Skip over the paren */
4341 SKIP_WHITE_SPACE (ip->bufp);
4344 if (!is_idstart[*ip->bufp])
4346 if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4348 if ((hp = lookup (ip->bufp, -1, -1))) {
4349 if (pcp_outfile && pcp_inside_if
4350 && (hp->type == T_CONST
4351 || (hp->type == T_MACRO && hp->value.defn->predefined)))
4352 /* Output a precondition for this macro use. */
4353 fprintf (pcp_outfile, "#define %s\n", hp->name);
4357 if (pcp_outfile && pcp_inside_if) {
4358 /* Output a precondition for this macro use */
4359 U_CHAR *cp = ip->bufp;
4360 fprintf (pcp_outfile, "#undef ");
4361 while (is_idchar[*cp]) /* Ick! */
4362 fputc (*cp++, pcp_outfile);
4363 putc ('\n', pcp_outfile);
4365 while (is_idchar[*ip->bufp])
4367 SKIP_WHITE_SPACE (ip->bufp);
4369 if (*ip->bufp != ')')
4377 error ("`defined' without an identifier");
4381 error ("cccp error: invalid special hash type"); /* time for gdb */
4385 check_expand (op, len);
4386 bcopy (buf, (char *) op->bufp, len);
4393 /* Routines to handle #directives */
4395 /* Handle #include and #import.
4396 This function expects to see "fname" or <fname> on the input. */
4399 do_include (buf, limit, op, keyword)
4400 U_CHAR *buf, *limit;
4402 struct directive *keyword;
4404 U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4405 int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4406 static int import_warning = 0;
4407 char *fname; /* Dynamically allocated fname buffer */
4410 char *fbeg, *fend; /* Beginning and end of fname */
4413 struct file_name_list *search_start = include; /* Chain of dirs to search */
4414 struct file_name_list *dsp; /* First in chain, if #include "..." */
4415 struct file_name_list *searchptr = 0;
4418 int f = -3; /* file number */
4419 struct include_file *inc = 0;
4421 int retried = 0; /* Have already tried macro
4422 expanding the include line*/
4423 int angle_brackets = 0; /* 0 for "...", 1 for <...> */
4425 int vaxc_include = 0; /* 1 for token without punctuation */
4432 if (pedantic && !instack[indepth].system_header_p)
4435 pedwarn ("ANSI C does not allow `#import'");
4437 pedwarn ("ANSI C does not allow `#include_next'");
4440 if (importing && warn_import && !inhibit_warnings
4441 && !instack[indepth].system_header_p && !import_warning) {
4443 warning ("using `#import' is not recommended");
4444 fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4445 fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4446 fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4447 fprintf (stderr, " #ifndef _FOO_H_INCLUDED\n");
4448 fprintf (stderr, " #define _FOO_H_INCLUDED\n");
4449 fprintf (stderr, " ... <real contents of file> ...\n");
4450 fprintf (stderr, " #endif /* Not _FOO_H_INCLUDED */\n\n");
4451 fprintf (stderr, "Then users can use `#include' any number of times.\n");
4452 fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4453 fprintf (stderr, "when it is equipped with such a conditional.\n");
4459 SKIP_WHITE_SPACE (fin);
4460 /* Discard trailing whitespace so we can easily see
4461 if we have parsed all the significant chars we were given. */
4462 while (limit != fin && is_hor_space[limit[-1]]) limit--;
4463 fbeg = fend = (char *) alloca (limit - fin);
4469 /* Copy the operand text, concatenating the strings. */
4474 goto invalid_include_file_name;
4482 /* If not at the end, there had better be another string. */
4483 /* Skip just horiz space, and don't go past limit. */
4484 while (fin != limit && is_hor_space[*fin]) fin++;
4485 if (fin != limit && *fin == '\"')
4492 /* We have "filename". Figure out directory this source
4493 file is coming from and put it on the front of the list. */
4495 /* If -I- was specified, don't search current dir, only spec'd ones. */
4496 if (ignore_srcdir) break;
4498 for (fp = &instack[indepth]; fp >= instack; fp--)
4503 if ((nam = fp->nominal_fname) != NULL) {
4504 /* Found a named file. Figure out dir of the file,
4505 and put it in front of the search list. */
4506 dsp = ((struct file_name_list *)
4507 alloca (sizeof (struct file_name_list)
4508 + fp->nominal_fname_len));
4509 strcpy (dsp->fname, nam);
4510 simplify_filename (dsp->fname);
4511 nam = base_name (dsp->fname);
4514 /* for hack_vms_include_specification(), a local
4515 dir specification must start with "./" on VMS. */
4516 if (nam == dsp->fname)
4523 /* But for efficiency's sake, do not insert the dir
4524 if it matches the search list's first dir. */
4525 dsp->next = search_start;
4526 if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4528 n = nam - dsp->fname;
4529 if (n + INCLUDE_LEN_FUDGE > max_include_len)
4530 max_include_len = n + INCLUDE_LEN_FUDGE;
4532 dsp[0].got_name_map = 0;
4540 while (fin != limit && *fin != '>')
4542 if (*fin == '>' && fin + 1 == limit) {
4544 /* If -I-, start with the first -I dir after the -I-. */
4545 search_start = first_bracket_include;
4553 * Support '#include xyz' like VAX-C to allow for easy use of all the
4554 * decwindow include files. It defaults to '#include <xyz.h>' (so the
4555 * code from case '<' is repeated here) and generates a warning.
4556 * (Note: macro expansion of `xyz' takes precedence.)
4558 /* Note: The argument of ISALPHA() can be evaluated twice, so do
4559 the pre-decrement outside of the macro. */
4560 if (retried && (--fin, ISALPHA(*(U_CHAR *) (fin)))) {
4561 while (fin != limit && (!ISSPACE(*fin)))
4563 warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4567 /* If -I-, start with the first -I dir after the -I-. */
4568 search_start = first_bracket_include;
4576 /* Expand buffer and then remove any newline markers.
4577 We can't just tell expand_to_temp_buffer to omit the markers,
4578 since it would put extra spaces in include file names. */
4581 int errors_before_expansion = errors;
4582 trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4583 if (errors != errors_before_expansion) {
4585 goto invalid_include_file_name;
4588 buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4590 while (src != trybuf.bufp) {
4591 switch ((*limit++ = *src++)) {
4600 U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4601 NULL_PTR, NULL_PTR, NULL_PTR);
4614 invalid_include_file_name:
4615 error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4619 /* For #include_next, skip in the search path
4620 past the dir in which the containing file was found. */
4623 for (fp = &instack[indepth]; fp >= instack; fp--)
4624 if (fp->fname != NULL) {
4625 /* fp->dir is null if the containing file was specified
4626 with an absolute file name. In that case, don't skip anything. */
4628 search_start = fp->dir->next;
4634 flen = simplify_filename (fbeg);
4638 error ("empty file name in `#%s'", keyword->name);
4642 /* Allocate this permanently, because it gets stored in the definitions
4644 fname = xmalloc (max_include_len + flen + 1);
4645 /* + 1 above for terminating null. */
4647 system_include_depth += angle_brackets;
4649 /* If specified file name is absolute, just open it. */
4651 if (absolute_filename (fbeg)) {
4652 strcpy (fname, fbeg);
4653 f = open_include_file (fname, NULL_PTR, importing, &inc);
4657 struct bypass_dir *next;
4659 struct file_name_list *searchptr;
4660 } **bypass_slot = 0;
4662 /* Search directory path, trying to open the file.
4663 Copy each filename tried into FNAME. */
4665 for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4667 if (searchptr == first_bracket_include) {
4668 /* Go to bypass directory if we know we've seen this file before. */
4669 static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4670 struct bypass_dir *p;
4671 bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4673 for (p = *bypass_slot; p; p = p->next)
4674 if (!strcmp (fbeg, p->fname)) {
4675 searchptr = p->searchptr;
4682 /* Change this 1/2 Unix 1/2 VMS file specification into a
4683 full VMS file specification */
4684 if (searchptr->fname[0])
4686 strcpy (fname, searchptr->fname);
4687 if (fname[strlen (fname) - 1] == ':')
4690 slashp = strchr (fbeg, '/');
4692 /* start at root-dir of logical device if no path given. */
4694 strcat (fname, "[000000]");
4696 strcat (fname, fbeg);
4698 /* Fix up the filename */
4699 hack_vms_include_specification (fname, vaxc_include);
4703 /* This is a normal VMS filespec, so use it unchanged. */
4704 strcpy (fname, fbeg);
4705 /* if it's '#include filename', add the missing .h */
4706 if (vaxc_include && index(fname,'.')==NULL)
4707 strcat (fname, ".h");
4710 strcpy (fname, searchptr->fname);
4711 strcat (fname, fbeg);
4713 f = open_include_file (fname, searchptr, importing, &inc);
4715 if (bypass_slot && searchptr != first_bracket_include) {
4716 /* This is the first time we found this include file,
4717 and we found it after first_bracket_include.
4718 Record its location so that we can bypass to here next time. */
4719 struct bypass_dir *p
4720 = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4721 p->next = *bypass_slot;
4722 p->fname = fname + strlen (searchptr->fname);
4723 p->searchptr = searchptr;
4729 /* Our VMS hacks can produce invalid filespecs, so don't worry
4730 about errors other than EACCES. */
4731 if (errno == EACCES)
4734 if (errno != ENOENT && errno != ENOTDIR)
4744 /* The file was already included. */
4746 /* If generating dependencies and -MG was specified, we assume missing
4747 files are leaf files, living in the same directory as the source file
4748 or other similar place; these missing files may be generated from
4749 other files and may not exist yet (eg: y.tab.h). */
4750 } else if (print_deps_missing_files
4751 && (system_include_depth != 0) < print_deps)
4753 /* If it was requested as a system header file,
4754 then assume it belongs in the first place to look for such. */
4758 char *p = (char *) alloca (strlen (search_start->fname)
4759 + strlen (fbeg) + 1);
4760 strcpy (p, search_start->fname);
4762 deps_output (p, ' ');
4767 /* Otherwise, omit the directory, as if the file existed
4768 in the directory with the source. */
4769 deps_output (fbeg, ' ');
4772 /* If -M was specified, and this header file won't be added to the
4773 dependency list, then don't count this as an error, because we can
4774 still produce correct output. Otherwise, we can't produce correct
4775 output, because there may be dependencies we need inside the missing
4776 file, and we don't know what directory this missing file exists in. */
4777 else if (0 < print_deps && print_deps <= (system_include_depth != 0))
4778 warning ("No include path in which to find %s", fbeg);
4780 error_from_errno (fbeg);
4782 error ("No include path in which to find %s", fbeg);
4786 /* Actually process the file. */
4788 pcftry = (char *) alloca (strlen (fname) + 30);
4795 sprintf (pcftry, "%s%d", fname, pcfnum++);
4797 pcf = open (pcftry, O_RDONLY, 0666);
4802 if (fstat (pcf, &s) != 0)
4803 pfatal_with_name (pcftry);
4804 if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4805 || inc->st.st_dev != s.st_dev)
4807 pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4808 /* Don't need it any more. */
4813 /* Don't need it at all. */
4818 } while (pcf != -1 && !pcfbuf);
4821 /* Actually process the file */
4823 pcfname = xmalloc (strlen (pcftry) + 1);
4824 strcpy (pcfname, pcftry);
4825 pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) fname, op);
4828 finclude (f, inc, op, is_system_include (fname), searchptr);
4831 system_include_depth -= angle_brackets;
4836 /* Return nonzero if the given FILENAME is an absolute pathname which
4837 designates a file within one of the known "system" include file
4838 directories. We assume here that if the given FILENAME looks like
4839 it is the name of a file which resides either directly in a "system"
4840 include file directory, or within any subdirectory thereof, then the
4841 given file must be a "system" include file. This function tells us
4842 if we should suppress pedantic errors/warnings for the given FILENAME.
4844 The value is 2 if the file is a C-language system header file
4845 for which C++ should (on most systems) assume `extern "C"'. */
4848 is_system_include (filename)
4849 register char *filename;
4851 struct file_name_list *searchptr;
4853 for (searchptr = first_system_include; searchptr;
4854 searchptr = searchptr->next)
4855 if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4856 return searchptr->c_system_include_path + 1;
4860 /* Yield the non-directory suffix of a file name. */
4868 #if defined (__MSDOS__) || defined (_WIN32)
4869 if (ISALPHA (s[0]) && s[1] == ':') s += 2;
4872 if ((p = rindex (s, ':'))) s = p + 1; /* Skip device. */
4873 if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory. */
4874 if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir. */
4878 if ((p = rindex (s, '/'))) s = p + 1;
4879 #ifdef DIR_SEPARATOR
4880 if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4885 /* Yield nonzero if FILENAME is absolute (i.e. not relative). */
4888 absolute_filename (filename)
4891 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4892 if (ISALPHA (filename[0]) && filename[1] == ':') filename += 2;
4894 #if defined (__CYGWIN32__)
4895 /* At present, any path that begins with a drive spec is absolute. */
4896 if (ISALPHA (filename[0]) && filename[1] == ':') return 1;
4899 if (index (filename, ':') != 0) return 1;
4901 if (filename[0] == '/') return 1;
4902 #ifdef DIR_SEPARATOR
4903 if (filename[0] == DIR_SEPARATOR) return 1;
4908 /* Remove unnecessary characters from FILENAME in place,
4909 to avoid unnecessary filename aliasing.
4910 Return the length of the resulting string.
4912 Do only the simplifications allowed by Posix.
4913 It is OK to miss simplifications on non-Posix hosts,
4914 since this merely leads to suboptimal results. */
4917 simplify_filename (filename)
4920 register char *from = filename;
4921 register char *to = filename;
4924 /* Remove redundant initial /s. */
4927 if (*++from == '/') {
4928 if (*++from == '/') {
4929 /* 3 or more initial /s are equivalent to 1 /. */
4930 while (*++from == '/')
4933 /* On some hosts // differs from /; Posix allows this. */
4934 static int slashslash_vs_slash;
4935 if (slashslash_vs_slash == 0) {
4937 slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4938 && INO_T_EQ (s1.st_ino, s2.st_ino)
4939 && s1.st_dev == s2.st_dev)
4942 if (slashslash_vs_slash < 0)
4951 if (from[0] == '.' && from[1] == '/')
4956 /* Copy this component and trailing /, if any. */
4957 while ((*to++ = *from++) != '/') {
4959 /* Trim . component at end of nonempty name. */
4960 to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4962 /* Trim unnecessary trailing /s. */
4963 while (to0 < --to && to[-1] == '/')
4967 return to - filename;
4972 /* Skip /s after a /. */
4973 while (*from == '/')
4978 /* The file_name_map structure holds a mapping of file names for a
4979 particular directory. This mapping is read from the file named
4980 FILE_NAME_MAP_FILE in that directory. Such a file can be used to
4981 map filenames on a file system with severe filename restrictions,
4982 such as DOS. The format of the file name map file is just a series
4983 of lines with two tokens on each line. The first token is the name
4984 to map, and the second token is the actual name to use. */
4986 struct file_name_map
4988 struct file_name_map *map_next;
4993 #define FILE_NAME_MAP_FILE "header.gcc"
4995 /* Read a space delimited string of unlimited length from a stdio
4999 read_filename_string (ch, f)
5007 set = alloc = xmalloc (len + 1);
5011 while ((ch = getc (f)) != EOF && ! is_space[ch])
5013 if (set - alloc == len)
5016 alloc = xrealloc (alloc, len + 1);
5017 set = alloc + len / 2;
5027 /* Read the file name map file for DIRNAME.
5028 If DIRNAME is empty, read the map file for the working directory;
5029 otherwise DIRNAME must end in '/'. */
5031 static struct file_name_map *
5032 read_name_map (dirname)
5035 /* This structure holds a linked list of file name maps, one per
5037 struct file_name_map_list
5039 struct file_name_map_list *map_list_next;
5040 char *map_list_name;
5041 struct file_name_map *map_list_map;
5043 static struct file_name_map_list *map_list;
5044 register struct file_name_map_list *map_list_ptr;
5049 for (map_list_ptr = map_list; map_list_ptr;
5050 map_list_ptr = map_list_ptr->map_list_next)
5051 if (! strcmp (map_list_ptr->map_list_name, dirname))
5052 return map_list_ptr->map_list_map;
5054 map_list_ptr = ((struct file_name_map_list *)
5055 xmalloc (sizeof (struct file_name_map_list)));
5056 map_list_ptr->map_list_name = savestring (dirname);
5057 map_list_ptr->map_list_map = NULL;
5059 dirlen = strlen (dirname);
5060 name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
5061 strcpy (name, dirname);
5062 strcat (name, FILE_NAME_MAP_FILE);
5063 f = fopen (name, "r");
5065 map_list_ptr->map_list_map = NULL;
5070 while ((ch = getc (f)) != EOF)
5073 struct file_name_map *ptr;
5078 from = read_filename_string (ch, f);
5079 while ((ch = getc (f)) != EOF && is_hor_space[ch])
5081 to = read_filename_string (ch, f);
5083 simplify_filename (from);
5084 tolen = simplify_filename (to);
5086 ptr = ((struct file_name_map *)
5087 xmalloc (sizeof (struct file_name_map)));
5088 ptr->map_from = from;
5090 /* Make the real filename absolute. */
5091 if (absolute_filename (to))
5095 ptr->map_to = xmalloc (dirlen + tolen + 1);
5096 strcpy (ptr->map_to, dirname);
5097 strcat (ptr->map_to, to);
5101 ptr->map_next = map_list_ptr->map_list_map;
5102 map_list_ptr->map_list_map = ptr;
5104 while ((ch = getc (f)) != '\n')
5111 map_list_ptr->map_list_next = map_list;
5112 map_list = map_list_ptr;
5114 return map_list_ptr->map_list_map;
5117 /* Try to open include file FILENAME. SEARCHPTR is the directory
5118 being tried from the include file search path.
5119 IMPORTING is "" if we are importing, null otherwise.
5120 Return -2 if found, either a matching name or a matching inode.
5121 Otherwise, open the file and return a file descriptor if successful
5122 or -1 if unsuccessful.
5123 Unless unsuccessful, put a descriptor of the included file into *PINC.
5124 This function maps filenames on file systems based on information read by
5128 open_include_file (filename, searchptr, importing, pinc)
5130 struct file_name_list *searchptr;
5132 struct include_file **pinc;
5134 char *fname = remap ? remap_include_file (filename, searchptr) : filename;
5137 /* Look up FNAME in include_hashtab. */
5138 struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
5141 struct include_file *inc, *head = *phead;
5142 for (inc = head; inc; inc = inc->next)
5143 if (!strcmp (fname, inc->fname))
5147 || ! inc->control_macro
5148 || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
5150 fd = open (fname, O_RDONLY, 0);
5155 /* if #include <dir/file> fails, try again with hacked spec. */
5156 if (!hack_vms_include_specification (fname, 0))
5158 fd = open (fname, O_RDONLY, 0);
5165 /* FNAME was not in include_hashtab; insert a new entry. */
5166 inc = (struct include_file *) xmalloc (sizeof (struct include_file));
5169 inc->control_macro = 0;
5170 inc->deps_output = 0;
5171 if (fstat (fd, &inc->st) != 0)
5172 pfatal_with_name (fname);
5175 /* Look for another file with the same inode and device. */
5176 if (lookup_ino_include (inc)
5177 && inc->control_macro
5178 && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
5184 /* For -M, add this file to the dependencies. */
5185 if (! inc->deps_output && (system_include_depth != 0) < print_deps) {
5186 inc->deps_output = 1;
5187 deps_output (fname, ' ');
5190 /* Handle -H option. */
5191 if (print_include_names)
5192 fprintf (stderr, "%*s%s\n", indepth, "", fname);
5196 inc->control_macro = importing;
5202 /* Return the remapped name of the include file FILENAME.
5203 SEARCHPTR is the directory being tried from the include file path. */
5206 remap_include_file (filename, searchptr)
5208 struct file_name_list *searchptr;
5210 register struct file_name_map *map;
5211 register char *from;
5215 if (! searchptr->got_name_map)
5217 searchptr->name_map = read_name_map (searchptr->fname);
5218 searchptr->got_name_map = 1;
5221 /* Check the mapping for the directory we are using. */
5222 from = filename + strlen (searchptr->fname);
5223 for (map = searchptr->name_map; map; map = map->map_next)
5224 if (! strcmp (map->map_from, from))
5228 from = base_name (filename);
5230 if (from != filename || !searchptr)
5232 /* Try to find a mapping file for the particular directory we are
5233 looking in. Thus #include <sys/types.h> will look up sys/types.h
5234 in /usr/include/header.gcc and look up types.h in
5235 /usr/include/sys/header.gcc. */
5237 char *dir = (char *) alloca (from - filename + 1);
5238 bcopy (filename, dir, from - filename);
5239 dir[from - filename] = '\0';
5241 for (map = read_name_map (dir); map; map = map->map_next)
5242 if (! strcmp (map->map_from, from))
5249 /* Insert INC into the include file table, hashed by device and inode number.
5250 If a file with different name but same dev+ino was already in the table,
5251 return 1 and set INC's control macro to the already-known macro. */
5254 lookup_ino_include (inc)
5255 struct include_file *inc;
5257 int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5258 % INCLUDE_HASHSIZE);
5259 struct include_file *i = include_ino_hashtab[hash];
5261 include_ino_hashtab[hash] = inc;
5263 for (; i; i = i->next_ino)
5264 if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5265 && inc->st.st_dev == i->st.st_dev) {
5266 inc->control_macro = i->control_macro;
5273 /* Process file descriptor F, which corresponds to include file INC,
5275 SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5276 "system" include directories (as decided by the `is_system_include'
5278 DIRPTR is the link in the dir path through which this file was found,
5279 or 0 if the file name was absolute. */
5282 finclude (f, inc, op, system_header_p, dirptr)
5284 struct include_file *inc;
5286 int system_header_p;
5287 struct file_name_list *dirptr;
5289 char *fname = inc->fname;
5291 FILE_BUF *fp; /* For input stack frame */
5292 int missing_newline = 0;
5294 CHECK_DEPTH (return;);
5296 fp = &instack[indepth + 1];
5297 bzero ((char *) fp, sizeof (FILE_BUF));
5298 fp->nominal_fname = fp->fname = fname;
5299 fp->nominal_fname_len = strlen (fname);
5303 fp->if_stack = if_stack;
5304 fp->system_header_p = system_header_p;
5307 if (S_ISREG (inc->st.st_mode)) {
5308 size_t s = (size_t) inc->st.st_size;
5309 if (s != inc->st.st_size || s + 2 < s)
5311 fp->buf = (U_CHAR *) xmalloc (s + 2);
5314 /* Read the file contents, knowing that s is an upper bound
5315 on the number of bytes we can read. */
5316 fp->length = safe_read (f, (char *) fp->buf, s);
5317 if (fp->length < 0) goto nope;
5319 else if (S_ISDIR (inc->st.st_mode)) {
5320 error ("directory `%s' specified in #include", fname);
5324 /* Cannot count its file size before reading.
5325 First read the entire file into heap and
5326 copy them into buffer on stack. */
5331 fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5334 i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5336 goto nope; /* error! */
5338 if (st_size != bsize)
5339 break; /* End of file */
5341 fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5344 fp->length = st_size;
5347 if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5348 /* Backslash-newline at end is not good enough. */
5349 || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5350 fp->buf[fp->length++] = '\n';
5351 missing_newline = 1;
5353 fp->buf[fp->length] = '\0';
5355 /* Close descriptor now, so nesting does not use lots of descriptors. */
5358 /* Must do this before calling trigraph_pcp, so that the correct file name
5359 will be printed in warning messages. */
5362 input_file_stack_tick++;
5367 output_line_directive (fp, op, 0, enter_file);
5370 if (missing_newline)
5373 if (pedantic && missing_newline)
5374 pedwarn ("file does not end in newline");
5377 input_file_stack_tick++;
5378 output_line_directive (&instack[indepth], op, 0, leave_file);
5384 perror_with_name (fname);
5389 /* Record that inclusion of the include file INC
5390 should be controlled by the macro named MACRO_NAME.
5391 This means that trying to include the file again
5392 will do something if that macro is defined. */
5395 record_control_macro (inc, macro_name)
5396 struct include_file *inc;
5399 if (!inc->control_macro || inc->control_macro[0])
5400 inc->control_macro = macro_name;
5403 /* Load the specified precompiled header into core, and verify its
5404 preconditions. PCF indicates the file descriptor to read, which must
5405 be a regular file. *ST is its file status.
5406 FNAME indicates the file name of the original header.
5407 *LIMIT will be set to an address one past the end of the file.
5408 If the preconditions of the file are not satisfied, the buffer is
5409 freed and we return 0. If the preconditions are satisfied, return
5410 the address of the buffer following the preconditions. The buffer, in
5411 this case, should never be freed because various pieces of it will
5412 be referred to until all precompiled strings are output at the end of
5416 check_precompiled (pcf, st, fname, limit)
5419 char *fname ATTRIBUTE_UNUSED;
5429 if (S_ISREG (st->st_mode))
5431 size_t s = (size_t) st->st_size;
5432 if (s != st->st_size || s + 2 < s)
5434 buf = xmalloc (s + 2);
5435 length = safe_read (pcf, buf, s);
5442 if (length > 0 && buf[length-1] != '\n')
5443 buf[length++] = '\n';
5446 *limit = buf + length;
5448 /* File is in core. Check the preconditions. */
5449 if (!check_preconditions (buf))
5451 for (cp = buf; *cp; cp++)
5454 fprintf (stderr, "Using preinclude %s\n", fname);
5460 fprintf (stderr, "Cannot use preinclude %s\n", fname);
5466 /* PREC (null terminated) points to the preconditions of a
5467 precompiled header. These are a series of #define and #undef
5468 lines which must match the current contents of the hash
5472 check_preconditions (prec)
5479 lineend = index (prec, '\n');
5481 if (*prec++ != '#') {
5482 error ("Bad format encountered while reading precompiled file");
5485 if (!strncmp (prec, "define", 6)) {
5489 mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5494 if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5495 || (hp->type != T_MACRO && hp->type != T_CONST)
5496 || (hp->type == T_MACRO
5497 && !compare_defs (mdef.defn, hp->value.defn)
5498 && (mdef.defn->length != 2
5499 || mdef.defn->expansion[0] != '\n'
5500 || mdef.defn->expansion[1] != ' ')))
5502 } else if (!strncmp (prec, "undef", 5)) {
5507 while (is_hor_space[(U_CHAR) *prec])
5510 while (is_idchar[(U_CHAR) *prec])
5514 if (lookup ((U_CHAR *) name, len, -1))
5517 error ("Bad format encountered while reading precompiled file");
5522 /* They all passed successfully */
5526 /* Process the main body of a precompiled file. BUF points to the
5527 string section of the file, following the preconditions. LIMIT is one
5528 character past the end. NAME is the name of the file being read
5529 in. OP is the main output buffer. */
5532 pcfinclude (buf, name, op)
5540 /* First in the file comes 4 bytes indicating the number of strings, */
5541 /* in network byte order. (MSB first). */
5543 nstrings = (nstrings << 8) | *cp++;
5544 nstrings = (nstrings << 8) | *cp++;
5545 nstrings = (nstrings << 8) | *cp++;
5547 /* Looping over each string... */
5548 while (nstrings--) {
5549 U_CHAR *string_start;
5550 U_CHAR *endofthiskey;
5554 /* Each string starts with a STRINGDEF structure (str), followed */
5555 /* by the text of the string (string_start) */
5557 /* First skip to a longword boundary */
5558 /* ??? Why a 4-byte boundary? On all machines? */
5559 /* NOTE: This works correctly even if size_t
5560 is narrower than a pointer.
5561 Do not try risky measures here to get another type to use!
5562 Do not include stddef.h--it will fail! */
5563 if ((size_t) cp & 3)
5564 cp += 4 - ((size_t) cp & 3);
5566 /* Now get the string. */
5567 str = (STRINGDEF *) (GENERIC_PTR) cp;
5568 string_start = cp += sizeof (STRINGDEF);
5570 for (; *cp; cp++) /* skip the string */
5573 /* We need to macro expand the string here to ensure that the
5574 proper definition environment is in place. If it were only
5575 expanded when we find out it is needed, macros necessary for
5576 its proper expansion might have had their definitions changed. */
5577 tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5578 /* Lineno is already set in the precompiled file */
5579 str->contents = tmpbuf.buf;
5580 str->len = tmpbuf.length;
5582 str->filename = name;
5583 str->output_mark = outbuf.bufp - outbuf.buf;
5586 *stringlist_tailp = str;
5587 stringlist_tailp = &str->chain;
5589 /* Next comes a fourbyte number indicating the number of keys
5592 nkeys = (nkeys << 8) | *cp++;
5593 nkeys = (nkeys << 8) | *cp++;
5594 nkeys = (nkeys << 8) | *cp++;
5596 /* If this number is -1, then the string is mandatory. */
5600 /* Otherwise, for each key, */
5601 for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5602 KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5605 /* It starts with a KEYDEF structure */
5606 cp += sizeof (KEYDEF);
5608 /* Find the end of the key. At the end of this for loop we
5609 advance CP to the start of the next key using this variable. */
5610 endofthiskey = cp + strlen ((char *) cp);
5613 /* Expand the key, and enter it into the hash table. */
5614 tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5615 tmpbuf.bufp = tmpbuf.buf;
5617 while (is_hor_space[*tmpbuf.bufp])
5619 if (!is_idstart[*tmpbuf.bufp]
5620 || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5625 hp = lookup (tmpbuf.bufp, -1, -1);
5628 install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5630 else if (hp->type == T_PCSTRING) {
5631 kp->chain = hp->value.keydef;
5632 hp->value.keydef = kp;
5638 /* This output_line_directive serves to switch us back to the current
5639 input file in case some of these strings get output (which will
5640 result in line directives for the header file being output). */
5641 output_line_directive (&instack[indepth], op, 0, enter_file);
5644 /* Called from rescan when it hits a key for strings. Mark them all
5645 used and clean up. */
5653 for (kp = hp->value.keydef; kp; kp = kp->chain)
5654 kp->str->writeflag = 1;
5658 /* Write the output, interspersing precompiled strings in their
5659 appropriate places. */
5664 STRINGDEF *next_string;
5665 U_CHAR *cur_buf_loc;
5666 int line_directive_len = 80;
5667 char *line_directive = xmalloc (line_directive_len);
5670 /* In each run through the loop, either cur_buf_loc ==
5671 next_string_loc, in which case we print a series of strings, or
5672 it is less than next_string_loc, in which case we write some of
5674 cur_buf_loc = outbuf.buf;
5675 next_string = stringlist;
5677 while (cur_buf_loc < outbuf.bufp || next_string) {
5679 && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5680 if (next_string->writeflag) {
5681 len = 4 * strlen ((char *) next_string->filename) + 32;
5682 while (len > line_directive_len)
5683 line_directive = xrealloc (line_directive,
5684 line_directive_len *= 2);
5685 sprintf (line_directive, "\n# %d ", next_string->lineno);
5686 strcpy (quote_string (line_directive + strlen (line_directive),
5687 (char *) next_string->filename,
5688 strlen ((char *) next_string->filename)),
5690 safe_write (fileno (stdout), line_directive, strlen (line_directive));
5691 safe_write (fileno (stdout),
5692 (char *) next_string->contents, next_string->len);
5694 next_string = next_string->chain;
5698 ? (next_string->output_mark
5699 - (cur_buf_loc - outbuf.buf))
5700 : outbuf.bufp - cur_buf_loc);
5702 safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5706 free (line_directive);
5709 /* Pass a directive through to the output file.
5710 BUF points to the contents of the directive, as a contiguous string.
5711 LIMIT points to the first character past the end of the directive.
5712 KEYWORD is the keyword-table entry for the directive. */
5715 pass_thru_directive (buf, limit, op, keyword)
5716 U_CHAR *buf, *limit;
5718 struct directive *keyword;
5720 register unsigned keyword_length = keyword->length;
5722 check_expand (op, 1 + keyword_length + (limit - buf));
5724 bcopy (keyword->name, (char *) op->bufp, keyword_length);
5725 op->bufp += keyword_length;
5726 if (limit != buf && buf[0] != ' ')
5728 bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5729 op->bufp += (limit - buf);
5732 /* Count the line we have just made in the output,
5733 to get in sync properly. */
5738 /* The arglist structure is built by do_define to tell
5739 collect_definition where the argument names begin. That
5740 is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5741 would contain pointers to the strings x, y, and z.
5742 Collect_definition would then build a DEFINITION node,
5743 with reflist nodes pointing to the places x, y, and z had
5744 appeared. So the arglist is just convenience data passed
5745 between these two routines. It is not kept around after
5746 the current #define has been processed and entered into the
5750 struct arglist *next;
5757 /* Create a DEFINITION node from a #define directive. Arguments are
5758 as for do_define. */
5761 create_definition (buf, limit, op)
5762 U_CHAR *buf, *limit;
5765 U_CHAR *bp; /* temp ptr into input buffer */
5766 U_CHAR *symname; /* remember where symbol name starts */
5767 int sym_length; /* and how long it is */
5768 int line = instack[indepth].lineno;
5769 char *file = instack[indepth].nominal_fname;
5770 size_t file_len = instack[indepth].nominal_fname_len;
5774 int arglengths = 0; /* Accumulate lengths of arg names
5775 plus number of args. */
5780 while (is_hor_space[*bp])
5783 symname = bp; /* remember where it starts */
5784 sym_length = check_macro_name (bp, "macro");
5787 /* Lossage will occur if identifiers or control keywords are broken
5788 across lines using backslash. This is not the right place to take
5792 struct arglist *arg_ptrs = NULL;
5795 bp++; /* skip '(' */
5796 SKIP_WHITE_SPACE (bp);
5798 /* Loop over macro argument names. */
5799 while (*bp != ')') {
5800 struct arglist *temp;
5802 temp = (struct arglist *) alloca (sizeof (struct arglist));
5804 temp->next = arg_ptrs;
5805 temp->argno = argno++;
5806 temp->rest_args = 0;
5810 pedwarn ("another parameter follows `%s'",
5813 if (!is_idstart[*bp])
5814 pedwarn ("invalid character in macro parameter name");
5816 /* Find the end of the arg name. */
5817 while (is_idchar[*bp]) {
5819 /* do we have a "special" rest-args extension here? */
5820 if (limit - bp > (long) REST_EXTENSION_LENGTH
5821 && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5822 if (pedantic && !instack[indepth].system_header_p)
5823 pedwarn ("ANSI C does not allow macro with variable arguments");
5825 temp->rest_args = 1;
5829 temp->length = bp - temp->name;
5831 bp += REST_EXTENSION_LENGTH;
5832 arglengths += temp->length + 2;
5833 SKIP_WHITE_SPACE (bp);
5834 if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5835 error ("badly punctuated parameter list in `#define'");
5840 SKIP_WHITE_SPACE (bp);
5841 /* A comma at this point can only be followed by an identifier. */
5842 if (!is_idstart[*bp]) {
5843 error ("badly punctuated parameter list in `#define'");
5848 error ("unterminated parameter list in `#define'");
5852 struct arglist *otemp;
5854 for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5855 if (temp->length == otemp->length
5856 && bcmp (temp->name, otemp->name, temp->length) == 0) {
5857 error ("duplicate argument name `%.*s' in `#define'",
5858 temp->length, temp->name);
5864 ++bp; /* skip paren */
5865 SKIP_WHITE_SPACE (bp);
5866 /* now everything from bp before limit is the definition. */
5867 defn = collect_expansion (bp, limit, argno, arg_ptrs);
5868 defn->rest_args = rest_args;
5870 /* Now set defn->args.argnames to the result of concatenating
5871 the argument names in reverse order
5872 with comma-space between them. */
5873 defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5875 struct arglist *temp;
5877 for (temp = arg_ptrs; temp; temp = temp->next) {
5878 bcopy (temp->name, &defn->args.argnames[i], temp->length);
5880 if (temp->next != 0) {
5881 defn->args.argnames[i++] = ',';
5882 defn->args.argnames[i++] = ' ';
5885 defn->args.argnames[i] = 0;
5888 /* Simple expansion or empty definition. */
5892 if (is_hor_space[*bp]) {
5894 SKIP_WHITE_SPACE (bp);
5895 } else if (sym_length) {
5897 case '!': case '"': case '#': case '%': case '&': case '\'':
5898 case ')': case '*': case '+': case ',': case '-': case '.':
5899 case '/': case ':': case ';': case '<': case '=': case '>':
5900 case '?': case '[': case '\\': case ']': case '^': case '{':
5901 case '|': case '}': case '~':
5902 warning ("missing white space after `#define %.*s'",
5903 sym_length, symname);
5907 pedwarn ("missing white space after `#define %.*s'",
5908 sym_length, symname);
5913 /* Now everything from bp before limit is the definition. */
5914 defn = collect_expansion (bp, limit, -1, NULL_PTR);
5915 defn->args.argnames = (U_CHAR *) "";
5920 defn->file_len = file_len;
5922 /* OP is null if this is a predefinition */
5923 defn->predefined = !op;
5925 mdef.symnam = symname;
5926 mdef.symlen = sym_length;
5935 /* Process a #define directive.
5936 BUF points to the contents of the #define directive, as a contiguous string.
5937 LIMIT points to the first character past the end of the definition.
5938 KEYWORD is the keyword-table entry for #define. */
5941 do_define (buf, limit, op, keyword)
5942 U_CHAR *buf, *limit;
5944 struct directive *keyword;
5949 /* If this is a precompiler run (with -pcp) pass thru #define directives. */
5950 if (pcp_outfile && op)
5951 pass_thru_directive (buf, limit, op, keyword);
5953 mdef = create_definition (buf, limit, op);
5957 hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5961 if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5963 /* Redefining a precompiled key is ok. */
5964 if (hp->type == T_PCSTRING)
5966 /* Redefining a macro is ok if the definitions are the same. */
5967 else if (hp->type == T_MACRO)
5968 ok = ! compare_defs (mdef.defn, hp->value.defn);
5969 /* Redefining a constant is ok with -D. */
5970 else if (hp->type == T_CONST)
5971 ok = ! done_initializing;
5972 /* Print the warning if it's not ok. */
5974 /* If we are passing through #define and #undef directives, do
5975 that for this re-definition now. */
5976 if (debug_output && op)
5977 pass_thru_directive (buf, limit, op, keyword);
5979 pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5980 if (hp->type == T_MACRO)
5981 pedwarn_with_file_and_line (hp->value.defn->file,
5982 hp->value.defn->file_len,
5983 hp->value.defn->line,
5984 "this is the location of the previous definition");
5986 /* Replace the old definition. */
5988 hp->value.defn = mdef.defn;
5990 /* If we are passing through #define and #undef directives, do
5991 that for this new definition now. */
5992 if (debug_output && op)
5993 pass_thru_directive (buf, limit, op, keyword);
5994 install (mdef.symnam, mdef.symlen, T_MACRO,
5995 (char *) mdef.defn, hashcode);
6006 /* Check a purported macro name SYMNAME, and yield its length.
6007 USAGE is the kind of name this is intended for. */
6010 check_macro_name (symname, usage)
6017 for (p = symname; is_idchar[*p]; p++)
6019 sym_length = p - symname;
6021 || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
6022 error ("invalid %s name", usage);
6023 else if (!is_idstart[*symname]
6024 || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
6025 error ("invalid %s name `%.*s'", usage, sym_length, symname);
6029 /* Return zero if two DEFINITIONs are isomorphic. */
6032 compare_defs (d1, d2)
6033 DEFINITION *d1, *d2;
6035 register struct reflist *a1, *a2;
6036 register U_CHAR *p1 = d1->expansion;
6037 register U_CHAR *p2 = d2->expansion;
6040 if (d1->nargs != d2->nargs)
6043 && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
6045 for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
6046 a1 = a1->next, a2 = a2->next) {
6047 if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
6048 || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
6049 || a1->argno != a2->argno
6050 || a1->stringify != a2->stringify
6051 || a1->raw_before != a2->raw_before
6052 || a1->raw_after != a2->raw_after)
6060 if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
6061 p2, d2->length - (p2 - d2->expansion), 1))
6066 /* Return 1 if two parts of two macro definitions are effectively different.
6067 One of the parts starts at BEG1 and has LEN1 chars;
6068 the other has LEN2 chars at BEG2.
6069 Any sequence of whitespace matches any other sequence of whitespace.
6070 FIRST means these parts are the first of a macro definition;
6071 so ignore leading whitespace entirely.
6072 LAST means these parts are the last of a macro definition;
6073 so ignore trailing whitespace entirely. */
6076 comp_def_part (first, beg1, len1, beg2, len2, last)
6078 U_CHAR *beg1, *beg2;
6082 register U_CHAR *end1 = beg1 + len1;
6083 register U_CHAR *end2 = beg2 + len2;
6085 while (beg1 != end1 && is_space[*beg1]) beg1++;
6086 while (beg2 != end2 && is_space[*beg2]) beg2++;
6089 while (beg1 != end1 && is_space[end1[-1]]) end1--;
6090 while (beg2 != end2 && is_space[end2[-1]]) end2--;
6092 while (beg1 != end1 && beg2 != end2) {
6093 if (is_space[*beg1] && is_space[*beg2]) {
6094 while (beg1 != end1 && is_space[*beg1]) beg1++;
6095 while (beg2 != end2 && is_space[*beg2]) beg2++;
6096 } else if (*beg1 == *beg2) {
6100 return (beg1 != end1) || (beg2 != end2);
6103 /* Read a replacement list for a macro with parameters.
6104 Build the DEFINITION structure.
6105 Reads characters of text starting at BUF until END.
6106 ARGLIST specifies the formal parameters to look for
6107 in the text of the definition; NARGS is the number of args
6108 in that list, or -1 for a macro name that wants no argument list.
6109 MACRONAME is the macro name itself (so we can avoid recursive expansion)
6110 and NAMELEN is its length in characters.
6112 Note that comments, backslash-newlines, and leading white space
6113 have already been deleted from the argument. */
6115 /* If there is no trailing whitespace, a Newline Space is added at the end
6116 to prevent concatenation that would be contrary to the standard. */
6119 collect_expansion (buf, end, nargs, arglist)
6122 struct arglist *arglist;
6125 register U_CHAR *p, *limit, *lastp, *exp_p;
6126 struct reflist *endpat = NULL;
6127 /* Pointer to first nonspace after last ## seen. */
6129 /* Pointer to first nonspace after last single-# seen. */
6130 U_CHAR *stringify = 0;
6131 /* How those tokens were spelled. */
6132 enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
6133 enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
6135 int expected_delimiter = '\0';
6137 /* Scan thru the replacement list, ignoring comments and quoted
6138 strings, picking up on the macro calls. It does a linear search
6139 thru the arg list on every potential symbol. Profiling might say
6140 that something smarter should happen. */
6145 /* Find the beginning of the trailing whitespace. */
6148 while (p < limit && is_space[limit[-1]]) limit--;
6150 /* Allocate space for the text in the macro definition.
6151 Each input char may or may not need 1 byte,
6152 so this is an upper bound.
6153 The extra 3 are for invented trailing newline-marker and final null. */
6154 maxsize = (sizeof (DEFINITION)
6156 defn = (DEFINITION *) xcalloc (1, maxsize);
6158 defn->nargs = nargs;
6159 exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
6164 : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
6165 error ("`##' at start of macro definition");
6166 p += p[0] == '#' ? 2 : 4;
6169 /* Process the main body of the definition. */
6171 int skipped_arg = 0;
6172 register U_CHAR c = *p++;
6180 if (expected_delimiter != '\0') {
6181 if (c == expected_delimiter)
6182 expected_delimiter = '\0';
6184 expected_delimiter = c;
6188 if (p < limit && expected_delimiter) {
6189 /* In a string, backslash goes through
6190 and makes next char ordinary. */
6196 if (!expected_delimiter && *p == ':') {
6197 /* %: is not a digraph if preceded by an odd number of '<'s. */
6199 while (buf < p0 && p0[-1] == '<')
6202 /* Treat %:%: as ## and %: as #. */
6203 if (p[1] == '%' && p[2] == ':') {
6205 goto sharp_sharp_token;
6216 /* # is ordinary inside a string. */
6217 if (expected_delimiter)
6221 /* ##: concatenate preceding and following tokens. */
6222 /* Take out the first #, discard preceding whitespace. */
6224 while (exp_p > lastp && is_hor_space[exp_p[-1]])
6226 /* Skip the second #. */
6228 concat_sharp_token_type = c;
6229 if (is_hor_space[*p]) {
6230 concat_sharp_token_type = c + 1;
6232 SKIP_WHITE_SPACE (p);
6236 error ("`##' at end of macro definition");
6237 } else if (nargs >= 0) {
6238 /* Single #: stringify following argument ref.
6239 Don't leave the # in the expansion. */
6242 stringify_sharp_token_type = c;
6243 if (is_hor_space[*p]) {
6244 stringify_sharp_token_type = c + 1;
6246 SKIP_WHITE_SPACE (p);
6248 if (! is_idstart[*p] || nargs == 0
6249 || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6250 error ("`#' operator is not followed by a macro argument name");
6257 /* In -traditional mode, recognize arguments inside strings and
6258 character constants, and ignore special properties of #.
6259 Arguments inside strings are considered "stringified", but no
6260 extra quote marks are supplied. */
6264 if (expected_delimiter != '\0') {
6265 if (c == expected_delimiter)
6266 expected_delimiter = '\0';
6268 expected_delimiter = c;
6272 /* Backslash quotes delimiters and itself, but not macro args. */
6273 if (expected_delimiter != 0 && p < limit
6274 && (*p == expected_delimiter || *p == '\\')) {
6281 if (expected_delimiter != '\0') /* No comments inside strings. */
6284 /* If we find a comment that wasn't removed by handle_directive,
6285 this must be -traditional. So replace the comment with
6288 while (++p < limit) {
6289 if (p[0] == '*' && p[1] == '/') {
6295 /* Mark this as a concatenation-point, as if it had been ##. */
6303 #ifdef MULTIBYTE_CHARS
6304 /* Handle multibyte characters inside string and character literals. */
6305 if (expected_delimiter != '\0')
6309 length = local_mblen (p, limit - p);
6313 bcopy (p, exp_p, length);
6322 /* Handle the start of a symbol. */
6323 if (is_idchar[c] && nargs > 0) {
6324 U_CHAR *id_beg = p - 1;
6328 while (p != limit && is_idchar[*p]) p++;
6329 id_len = p - id_beg;
6332 && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6333 register struct arglist *arg;
6335 for (arg = arglist; arg != NULL; arg = arg->next) {
6336 struct reflist *tpat;
6338 if (arg->name[0] == c
6339 && arg->length == id_len
6340 && bcmp (arg->name, id_beg, id_len) == 0) {
6341 enum sharp_token_type tpat_stringify;
6342 if (expected_delimiter) {
6343 if (warn_stringify) {
6345 warning ("macro argument `%.*s' is stringified.",
6348 warning ("macro arg `%.*s' would be stringified with -traditional.",
6352 /* If ANSI, don't actually substitute inside a string. */
6355 tpat_stringify = SHARP_TOKEN;
6358 = (stringify == id_beg
6359 ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6361 /* make a pat node for this arg and append it to the end of
6363 tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6366 = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6367 tpat->raw_after = NO_SHARP_TOKEN;
6368 tpat->rest_args = arg->rest_args;
6369 tpat->stringify = tpat_stringify;
6372 defn->pattern = tpat;
6374 endpat->next = tpat;
6377 tpat->argno = arg->argno;
6378 tpat->nchars = exp_p - lastp;
6380 register U_CHAR *p1 = p;
6381 SKIP_WHITE_SPACE (p1);
6384 : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6385 tpat->raw_after = p1[0] + (p != p1);
6387 lastp = exp_p; /* place to start copying from next time */
6394 /* If this was not a macro arg, copy it into the expansion. */
6395 if (! skipped_arg) {
6396 register U_CHAR *lim1 = p;
6400 if (stringify == id_beg)
6401 error ("`#' operator should be followed by a macro argument name");
6406 if (!traditional && expected_delimiter == 0) {
6407 /* If ANSI, put in a newline-space marker to prevent token pasting.
6408 But not if "inside a string" (which in ANSI mode happens only for
6416 defn->length = exp_p - defn->expansion;
6418 /* Crash now if we overrun the allocated size. */
6419 if (defn->length + 1 > maxsize)
6423 /* This isn't worth the time it takes. */
6424 /* give back excess storage */
6425 defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6432 do_assert (buf, limit, op, keyword)
6433 U_CHAR *buf, *limit;
6434 FILE_BUF *op ATTRIBUTE_UNUSED;
6435 struct directive *keyword ATTRIBUTE_UNUSED;
6437 U_CHAR *bp; /* temp ptr into input buffer */
6438 U_CHAR *symname; /* remember where symbol name starts */
6439 int sym_length; /* and how long it is */
6440 struct arglist *tokens = NULL;
6442 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6443 pedwarn ("ANSI C does not allow `#assert'");
6447 while (is_hor_space[*bp])
6450 symname = bp; /* remember where it starts */
6451 sym_length = check_macro_name (bp, "assertion");
6453 /* #define doesn't do this, but we should. */
6454 SKIP_WHITE_SPACE (bp);
6456 /* Lossage will occur if identifiers or control tokens are broken
6457 across lines using backslash. This is not the right place to take
6461 error ("missing token-sequence in `#assert'");
6468 bp++; /* skip '(' */
6469 SKIP_WHITE_SPACE (bp);
6471 tokens = read_token_list (&bp, limit, &error_flag);
6475 error ("empty token-sequence in `#assert'");
6479 ++bp; /* skip paren */
6480 SKIP_WHITE_SPACE (bp);
6483 /* If this name isn't already an assertion name, make it one.
6484 Error if it was already in use in some other way. */
6487 ASSERTION_HASHNODE *hp;
6488 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6489 struct tokenlist_list *value
6490 = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6492 hp = assertion_lookup (symname, sym_length, hashcode);
6494 if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6495 error ("`defined' redefined as assertion");
6496 hp = assertion_install (symname, sym_length, hashcode);
6499 /* Add the spec'd token-sequence to the list of such. */
6500 value->tokens = tokens;
6501 value->next = hp->value;
6509 do_unassert (buf, limit, op, keyword)
6510 U_CHAR *buf, *limit;
6511 FILE_BUF *op ATTRIBUTE_UNUSED;
6512 struct directive *keyword ATTRIBUTE_UNUSED;
6514 U_CHAR *bp; /* temp ptr into input buffer */
6515 U_CHAR *symname; /* remember where symbol name starts */
6516 int sym_length; /* and how long it is */
6518 struct arglist *tokens = NULL;
6519 int tokens_specified = 0;
6521 if (pedantic && done_initializing && !instack[indepth].system_header_p)
6522 pedwarn ("ANSI C does not allow `#unassert'");
6526 while (is_hor_space[*bp])
6529 symname = bp; /* remember where it starts */
6530 sym_length = check_macro_name (bp, "assertion");
6532 /* #define doesn't do this, but we should. */
6533 SKIP_WHITE_SPACE (bp);
6535 /* Lossage will occur if identifiers or control tokens are broken
6536 across lines using backslash. This is not the right place to take
6542 bp++; /* skip '(' */
6543 SKIP_WHITE_SPACE (bp);
6545 tokens = read_token_list (&bp, limit, &error_flag);
6549 error ("empty token list in `#unassert'");
6553 tokens_specified = 1;
6555 ++bp; /* skip paren */
6556 SKIP_WHITE_SPACE (bp);
6560 ASSERTION_HASHNODE *hp;
6561 int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6562 struct tokenlist_list *tail, *prev;
6564 hp = assertion_lookup (symname, sym_length, hashcode);
6568 /* If no token list was specified, then eliminate this assertion
6570 if (! tokens_specified) {
6571 struct tokenlist_list *next;
6572 for (tail = hp->value; tail; tail = next) {
6574 free_token_list (tail->tokens);
6577 delete_assertion (hp);
6579 /* If a list of tokens was given, then delete any matching list. */
6584 struct tokenlist_list *next = tail->next;
6585 if (compare_token_lists (tail->tokens, tokens)) {
6589 hp->value = tail->next;
6590 free_token_list (tail->tokens);
6603 /* Test whether there is an assertion named NAME
6604 and optionally whether it has an asserted token list TOKENS.
6605 NAME is not null terminated; its length is SYM_LENGTH.
6606 If TOKENS_SPECIFIED is 0, then don't check for any token list. */
6609 check_assertion (name, sym_length, tokens_specified, tokens)
6612 int tokens_specified;
6613 struct arglist *tokens;
6615 ASSERTION_HASHNODE *hp;
6616 int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6618 if (pedantic && !instack[indepth].system_header_p)
6619 pedwarn ("ANSI C does not allow testing assertions");
6621 hp = assertion_lookup (name, sym_length, hashcode);
6623 /* It is not an assertion; just return false. */
6626 /* If no token list was specified, then value is 1. */
6627 if (! tokens_specified)
6631 struct tokenlist_list *tail;
6635 /* If a list of tokens was given,
6636 then succeed if the assertion records a matching list. */
6639 if (compare_token_lists (tail->tokens, tokens))
6644 /* Fail if the assertion has no matching list. */
6649 /* Compare two lists of tokens for equality including order of tokens. */
6652 compare_token_lists (l1, l2)
6653 struct arglist *l1, *l2;
6656 if (l1->length != l2->length)
6658 if (bcmp (l1->name, l2->name, l1->length))
6664 /* Succeed if both lists end at the same time. */
6668 /* Read a space-separated list of tokens ending in a close parenthesis.
6669 Return a list of strings, in the order they were written.
6670 (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6671 Parse the text starting at *BPP, and update *BPP.
6672 Don't parse beyond LIMIT. */
6674 static struct arglist *
6675 read_token_list (bpp, limit, error_flag)
6680 struct arglist *token_ptrs = 0;
6686 /* Loop over the assertion value tokens. */
6688 struct arglist *temp;
6692 /* Find the end of the token. */
6696 } else if (*bp == ')') {
6701 } else if (*bp == '"' || *bp == '\'')
6702 bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6704 while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6705 && *bp != '"' && *bp != '\'' && bp != limit)
6708 temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6709 temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6710 bcopy ((char *) beg, (char *) temp->name, bp - beg);
6711 temp->name[bp - beg] = 0;
6712 temp->next = token_ptrs;
6714 temp->length = bp - beg;
6716 SKIP_WHITE_SPACE (bp);
6719 error ("unterminated token sequence in `#assert' or `#unassert'");
6726 /* We accumulated the names in reverse order.
6727 Now reverse them to get the proper order. */
6729 register struct arglist *prev = 0, *this, *next;
6730 for (this = token_ptrs; this; this = next) {
6740 free_token_list (tokens)
6741 struct arglist *tokens;
6744 struct arglist *next = tokens->next;
6745 free (tokens->name);
6751 /* Install a name in the assertion hash table.
6753 If LEN is >= 0, it is the length of the name.
6754 Otherwise, compute the length by scanning the entire name.
6756 If HASH is >= 0, it is the precomputed hash code.
6757 Otherwise, compute the hash code. */
6759 static ASSERTION_HASHNODE *
6760 assertion_install (name, len, hash)
6765 register ASSERTION_HASHNODE *hp;
6766 register int i, bucket;
6767 register U_CHAR *p, *q;
6769 i = sizeof (ASSERTION_HASHNODE) + len + 1;
6770 hp = (ASSERTION_HASHNODE *) xmalloc (i);
6772 hp->bucket_hdr = &assertion_hashtab[bucket];
6773 hp->next = assertion_hashtab[bucket];
6774 assertion_hashtab[bucket] = hp;
6776 if (hp->next != NULL)
6777 hp->next->prev = hp;
6780 hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6783 for (i = 0; i < len; i++)
6789 /* Find the most recent hash node for name "name" (ending with first
6790 non-identifier char) installed by install
6792 If LEN is >= 0, it is the length of the name.
6793 Otherwise, compute the length by scanning the entire name.
6795 If HASH is >= 0, it is the precomputed hash code.
6796 Otherwise, compute the hash code. */
6798 static ASSERTION_HASHNODE *
6799 assertion_lookup (name, len, hash)
6804 register ASSERTION_HASHNODE *bucket;
6806 bucket = assertion_hashtab[hash];
6808 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6810 bucket = bucket->next;
6816 delete_assertion (hp)
6817 ASSERTION_HASHNODE *hp;
6820 if (hp->prev != NULL)
6821 hp->prev->next = hp->next;
6822 if (hp->next != NULL)
6823 hp->next->prev = hp->prev;
6825 /* Make sure that the bucket chain header that the deleted guy was
6826 on points to the right thing afterwards. */
6827 if (hp == *hp->bucket_hdr)
6828 *hp->bucket_hdr = hp->next;
6834 * interpret #line directive. Remembers previously seen fnames
6835 * in its very own hash table.
6837 #define FNAME_HASHSIZE 37
6840 do_line (buf, limit, op, keyword)
6841 U_CHAR *buf, *limit;
6843 struct directive *keyword ATTRIBUTE_UNUSED;
6845 register U_CHAR *bp;
6846 FILE_BUF *ip = &instack[indepth];
6849 enum file_change_code file_change = same_file;
6851 /* Expand any macros. */
6852 tem = expand_to_temp_buffer (buf, limit, 0, 0);
6854 /* Point to macroexpanded line, which is null-terminated now. */
6856 SKIP_WHITE_SPACE (bp);
6858 if (!ISDIGIT (*bp)) {
6859 error ("invalid format `#line' directive");
6863 /* The Newline at the end of this line remains to be processed.
6864 To put the next line at the specified line number,
6865 we must store a line number now that is one less. */
6866 new_lineno = atoi ((char *) bp) - 1;
6868 /* NEW_LINENO is one less than the actual line number here. */
6869 if (pedantic && new_lineno < 0)
6870 pedwarn ("line number out of range in `#line' directive");
6872 /* skip over the line number. */
6873 while (ISDIGIT (*bp))
6876 #if 0 /* #line 10"foo.c" is supposed to be allowed. */
6877 if (*bp && !is_space[*bp]) {
6878 error ("invalid format `#line' directive");
6883 SKIP_WHITE_SPACE (bp);
6886 static HASHNODE *fname_table[FNAME_HASHSIZE];
6887 HASHNODE *hp, **hash_bucket;
6893 /* Turn the file name, which is a character string literal,
6894 into a null-terminated string. Do this in place. */
6897 switch ((*p++ = *bp++)) {
6899 error ("invalid format `#line' directive");
6904 char *bpc = (char *) bp;
6905 HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6906 bp = (U_CHAR *) bpc;
6919 fname_length = p - fname;
6921 SKIP_WHITE_SPACE (bp);
6924 pedwarn ("garbage at end of `#line' directive");
6926 file_change = enter_file;
6927 else if (*bp == '2')
6928 file_change = leave_file;
6929 else if (*bp == '3')
6930 ip->system_header_p = 1;
6931 else if (*bp == '4')
6932 ip->system_header_p = 2;
6934 error ("invalid format `#line' directive");
6939 SKIP_WHITE_SPACE (bp);
6941 ip->system_header_p = 1;
6943 SKIP_WHITE_SPACE (bp);
6946 ip->system_header_p = 2;
6948 SKIP_WHITE_SPACE (bp);
6951 error ("invalid format `#line' directive");
6956 hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6957 for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6958 if (hp->length == fname_length &&
6959 bcmp (hp->value.cpval, fname, fname_length) == 0) {
6960 ip->nominal_fname = hp->value.cpval;
6961 ip->nominal_fname_len = fname_length;
6965 /* Didn't find it; cons up a new one. */
6966 hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6967 hp->next = *hash_bucket;
6970 ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6971 ip->nominal_fname_len = hp->length = fname_length;
6972 bcopy (fname, hp->value.cpval, fname_length + 1);
6975 error ("invalid format `#line' directive");
6979 ip->lineno = new_lineno;
6980 output_line_directive (ip, op, 0, file_change);
6981 check_expand (op, ip->length - (ip->bufp - ip->buf));
6985 /* Remove the definition of a symbol from the symbol table.
6986 according to un*x /lib/cpp, it is not an error to undef
6987 something that has no definitions, so it isn't one here either. */
6990 do_undef (buf, limit, op, keyword)
6991 U_CHAR *buf, *limit;
6993 struct directive *keyword;
6997 U_CHAR *orig_buf = buf;
6999 /* If this is a precompiler run (with -pcp) pass thru #undef directives. */
7000 if (pcp_outfile && op)
7001 pass_thru_directive (buf, limit, op, keyword);
7003 SKIP_WHITE_SPACE (buf);
7004 sym_length = check_macro_name (buf, "macro");
7006 while ((hp = lookup (buf, sym_length, -1)) != NULL) {
7007 /* If we are generating additional info for debugging (with -g) we
7008 need to pass through all effective #undef directives. */
7009 if (debug_output && op)
7010 pass_thru_directive (orig_buf, limit, op, keyword);
7011 if (hp->type != T_MACRO)
7012 warning ("undefining `%s'", hp->name);
7018 SKIP_WHITE_SPACE (buf);
7020 pedwarn ("garbage after `#undef' directive");
7025 /* Report an error detected by the program we are processing.
7026 Use the text of the line in the error message.
7027 (We use error because it prints the filename & line#.) */
7030 do_error (buf, limit, op, keyword)
7031 U_CHAR *buf, *limit;
7032 FILE_BUF *op ATTRIBUTE_UNUSED;
7033 struct directive *keyword ATTRIBUTE_UNUSED;
7035 int length = limit - buf;
7036 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7037 bcopy ((char *) buf, (char *) copy, length);
7039 SKIP_WHITE_SPACE (copy);
7040 error ("#error %s", copy);
7044 /* Report a warning detected by the program we are processing.
7045 Use the text of the line in the warning message, then continue.
7046 (We use error because it prints the filename & line#.) */
7049 do_warning (buf, limit, op, keyword)
7050 U_CHAR *buf, *limit;
7051 FILE_BUF *op ATTRIBUTE_UNUSED;
7052 struct directive *keyword ATTRIBUTE_UNUSED;
7054 int length = limit - buf;
7055 U_CHAR *copy = (U_CHAR *) alloca (length + 1);
7056 bcopy ((char *) buf, (char *) copy, length);
7058 SKIP_WHITE_SPACE (copy);
7060 if (pedantic && !instack[indepth].system_header_p)
7061 pedwarn ("ANSI C does not allow `#warning'");
7063 /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
7064 if -pedantic-errors is given, #warning should cause an error. */
7065 pedwarn ("#warning %s", copy);
7069 /* Remember the name of the current file being read from so that we can
7070 avoid ever including it again. */
7077 for (i = indepth; i >= 0; i--)
7078 if (instack[i].inc) {
7079 record_control_macro (instack[i].inc, (U_CHAR *) "");
7084 /* Report program identification. */
7087 do_ident (buf, limit, op, keyword)
7088 U_CHAR *buf, *limit;
7090 struct directive *keyword ATTRIBUTE_UNUSED;
7095 /* Allow #ident in system headers, since that's not user's fault. */
7096 if (pedantic && !instack[indepth].system_header_p)
7097 pedwarn ("ANSI C does not allow `#ident'");
7099 trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
7101 len = trybuf.bufp - buf;
7103 /* Output expanded directive. */
7104 check_expand (op, 7 + len);
7105 bcopy ("#ident ", (char *) op->bufp, 7);
7107 bcopy ((char *) buf, (char *) op->bufp, len);
7114 /* #pragma and its argument line have already been copied to the output file.
7115 Just check for some recognized pragmas that need validation here. */
7118 do_pragma (buf, limit, op, keyword)
7119 U_CHAR *buf, *limit ATTRIBUTE_UNUSED;
7120 FILE_BUF *op ATTRIBUTE_UNUSED;
7121 struct directive *keyword ATTRIBUTE_UNUSED;
7123 SKIP_WHITE_SPACE (buf);
7124 if (!strncmp ((char *) buf, "once", 4)) {
7125 /* Allow #pragma once in system headers, since that's not the user's
7127 if (!instack[indepth].system_header_p)
7128 warning ("`#pragma once' is obsolete");
7132 if (!strncmp ((char *) buf, "implementation", 14)) {
7133 /* Be quiet about `#pragma implementation' for a file only if it hasn't
7134 been included yet. */
7137 U_CHAR *p = buf + 14, *fname;
7138 SKIP_WHITE_SPACE (p);
7143 if ((p = (U_CHAR *) index ((char *) fname, '\"')))
7146 for (h = 0; h < INCLUDE_HASHSIZE; h++) {
7147 struct include_file *inc;
7148 for (inc = include_hashtab[h]; inc; inc = inc->next) {
7149 if (!strcmp (base_name (inc->fname), (char *) fname)) {
7150 warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
7160 /* This was a fun hack, but #pragma seems to start to be useful.
7161 By failing to recognize it, we pass it through unchanged to cc1. */
7163 /* The behavior of the #pragma directive is implementation defined.
7164 this implementation defines it as follows. */
7170 if (open ("/dev/tty", O_RDONLY, 0666) != 0)
7173 if (open ("/dev/tty", O_WRONLY, 0666) != 1)
7175 execl ("/usr/games/hack", "#pragma", 0);
7176 execl ("/usr/games/rogue", "#pragma", 0);
7177 execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
7178 execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
7180 fatal ("You are in a maze of twisty compiler features, all different");
7184 #ifdef SCCS_DIRECTIVE
7186 /* Just ignore #sccs, on systems where we define it at all. */
7189 do_sccs (buf, limit, op, keyword)
7190 U_CHAR *buf ATTRIBUTE_UNUSED, *limit ATTRIBUTE_UNUSED;
7191 FILE_BUF *op ATTRIBUTE_UNUSED;
7192 struct directive *keyword ATTRIBUTE_UNUSED;
7195 pedwarn ("ANSI C does not allow `#sccs'");
7199 #endif /* defined (SCCS_DIRECTIVE) */
7201 /* Handle #if directive by
7202 1) inserting special `defined' keyword into the hash table
7203 that gets turned into 0 or 1 by special_symbol (thus,
7204 if the luser has a symbol called `defined' already, it won't
7205 work inside the #if directive)
7206 2) rescan the input into a temporary output buffer
7207 3) pass the output buffer to the yacc parser and collect a value
7208 4) clean up the mess left from steps 1 and 2.
7209 5) call conditional_skip to skip til the next #endif (etc.),
7210 or not, depending on the value from step 3. */
7213 do_if (buf, limit, op, keyword)
7214 U_CHAR *buf, *limit;
7216 struct directive *keyword ATTRIBUTE_UNUSED;
7218 HOST_WIDE_INT value;
7219 FILE_BUF *ip = &instack[indepth];
7221 value = eval_if_expression (buf, limit - buf);
7222 conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
7226 /* Handle a #elif directive by not changing if_stack either.
7227 see the comment above do_else. */
7230 do_elif (buf, limit, op, keyword)
7231 U_CHAR *buf, *limit;
7233 struct directive *keyword ATTRIBUTE_UNUSED;
7235 HOST_WIDE_INT value;
7236 FILE_BUF *ip = &instack[indepth];
7238 if (if_stack == instack[indepth].if_stack) {
7239 error ("`#elif' not within a conditional");
7242 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7243 error ("`#elif' after `#else'");
7244 fprintf (stderr, " (matches line %d", if_stack->lineno);
7245 if (! (if_stack->fname_len == ip->nominal_fname_len
7246 && !bcmp (if_stack->fname, ip->nominal_fname,
7247 if_stack->fname_len))) {
7248 fprintf (stderr, ", file ");
7249 eprint_string (if_stack->fname, if_stack->fname_len);
7251 fprintf (stderr, ")\n");
7253 if_stack->type = T_ELIF;
7256 if (if_stack->if_succeeded)
7257 skip_if_group (ip, 0, op);
7259 value = eval_if_expression (buf, limit - buf);
7261 skip_if_group (ip, 0, op);
7263 ++if_stack->if_succeeded; /* continue processing input */
7264 output_line_directive (ip, op, 1, same_file);
7270 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7271 result as a C expression and return the value as an int. */
7273 static HOST_WIDE_INT
7274 eval_if_expression (buf, length)
7279 HASHNODE *save_defined;
7280 HOST_WIDE_INT value;
7282 save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7285 temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7287 delete_macro (save_defined); /* clean up special symbol */
7289 temp_obuf.buf[temp_obuf.length] = '\n';
7290 value = parse_c_expression ((char *) temp_obuf.buf,
7291 warn_undef && !instack[indepth].system_header_p);
7293 free (temp_obuf.buf);
7298 /* routine to handle ifdef/ifndef. Try to look up the symbol, then do
7299 or don't skip to the #endif/#else/#elif depending on what directive
7300 is actually being processed. */
7303 do_xifdef (buf, limit, op, keyword)
7304 U_CHAR *buf, *limit;
7306 struct directive *keyword;
7309 FILE_BUF *ip = &instack[indepth];
7311 int start_of_file = 0;
7312 U_CHAR *control_macro = 0;
7314 /* Detect a #ifndef at start of file (not counting comments). */
7315 if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7316 U_CHAR *p = ip->buf;
7317 while (p != directive_start) {
7321 /* Make no special provision for backslash-newline here; this is
7322 slower if backslash-newlines are present, but it's correct,
7323 and it's not worth it to tune for the rare backslash-newline. */
7325 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7326 /* Skip this comment. */
7328 U_CHAR *save_bufp = ip->bufp;
7330 p = skip_to_end_of_comment (ip, &junk, 1);
7331 ip->bufp = save_bufp;
7336 /* If we get here, this conditional is the beginning of the file. */
7341 /* Discard leading and trailing whitespace. */
7342 SKIP_WHITE_SPACE (buf);
7343 while (limit != buf && is_hor_space[limit[-1]]) limit--;
7345 /* Find the end of the identifier at the beginning. */
7346 for (end = buf; is_idchar[*end]; end++);
7349 skip = (keyword->type == T_IFDEF);
7351 pedwarn (end == limit ? "`#%s' with no argument"
7352 : "`#%s' argument starts with punctuation",
7357 if (! traditional) {
7358 if (ISDIGIT (buf[0]))
7359 pedwarn ("`#%s' argument starts with a digit", keyword->name);
7360 else if (end != limit)
7361 pedwarn ("garbage at end of `#%s' argument", keyword->name);
7364 hp = lookup (buf, end-buf, -1);
7367 /* Output a precondition for this macro. */
7369 && (hp->type == T_CONST
7370 || (hp->type == T_MACRO && hp->value.defn->predefined)))
7371 fprintf (pcp_outfile, "#define %s\n", hp->name);
7374 fprintf (pcp_outfile, "#undef ");
7375 while (is_idchar[*cp]) /* Ick! */
7376 fputc (*cp++, pcp_outfile);
7377 putc ('\n', pcp_outfile);
7381 skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7382 if (start_of_file && !skip) {
7383 control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7384 bcopy ((char *) buf, (char *) control_macro, end - buf);
7385 control_macro[end - buf] = 0;
7389 conditional_skip (ip, skip, T_IF, control_macro, op);
7393 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7394 If this is a #ifndef starting at the beginning of a file,
7395 CONTROL_MACRO is the macro name tested by the #ifndef.
7396 Otherwise, CONTROL_MACRO is 0. */
7399 conditional_skip (ip, skip, type, control_macro, op)
7402 enum node_type type;
7403 U_CHAR *control_macro;
7406 IF_STACK_FRAME *temp;
7408 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7409 temp->fname = ip->nominal_fname;
7410 temp->fname_len = ip->nominal_fname_len;
7411 temp->lineno = ip->lineno;
7412 temp->next = if_stack;
7413 temp->control_macro = control_macro;
7416 if_stack->type = type;
7419 skip_if_group (ip, 0, op);
7422 ++if_stack->if_succeeded;
7423 output_line_directive (ip, &outbuf, 1, same_file);
7427 /* Skip to #endif, #else, or #elif. adjust line numbers, etc.
7428 Leaves input ptr at the sharp sign found.
7429 If ANY is nonzero, return at next directive of any sort. */
7432 skip_if_group (ip, any, op)
7437 register U_CHAR *bp = ip->bufp, *cp;
7438 register U_CHAR *endb = ip->buf + ip->length;
7439 struct directive *kt;
7440 IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7441 U_CHAR *beg_of_line = bp;
7442 register int ident_length;
7443 U_CHAR *ident, *after_ident;
7444 /* Save info about where the group starts. */
7445 U_CHAR *beg_of_group = bp;
7446 int beg_lineno = ip->lineno;
7447 int skipping_include_directive = 0;
7449 if (output_conditionals && op != 0) {
7450 char *ptr = "#failed\n";
7451 int len = strlen (ptr);
7453 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7458 check_expand (op, len);
7459 bcopy (ptr, (char *) op->bufp, len);
7462 output_line_directive (ip, op, 1, 0);
7467 case '/': /* possible comment */
7468 if (*bp == '\\' && bp[1] == '\n')
7471 || (cplusplus_comments && *bp == '/')) {
7473 bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7477 if (skipping_include_directive) {
7478 while (bp < endb && *bp != '>' && *bp != '\n') {
7479 if (*bp == '\\' && bp[1] == '\n') {
7488 if (skipping_include_directive) {
7489 while (bp < endb && *bp != '\n') {
7494 if (*bp == '\\' && bp[1] == '\n') {
7504 bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7505 NULL_PTR, NULL_PTR);
7508 /* Char after backslash loses its special meaning in some cases. */
7512 } else if (traditional && bp < endb)
7518 skipping_include_directive = 0;
7521 if (beg_of_line == 0 || traditional)
7524 while (bp[0] == '\\' && bp[1] == '\n')
7530 /* # keyword: a # must be first nonblank char on the line */
7531 if (beg_of_line == 0)
7535 /* Scan from start of line, skipping whitespace, comments
7536 and backslash-newlines, and see if we reach this #.
7537 If not, this # is not special. */
7539 /* If -traditional, require # to be at beginning of line. */
7542 if (is_hor_space[*bp])
7544 else if (*bp == '\\' && bp[1] == '\n')
7546 else if (*bp == '/' && bp[1] == '*') {
7560 #ifdef MULTIBYTE_CHARS
7562 length = local_mblen (bp, endb - bp);
7570 /* There is no point in trying to deal with C++ // comments here,
7571 because if there is one, then this # must be part of the
7572 comment and we would never reach here. */
7576 if (bp != ip->bufp) {
7577 bp = ip->bufp + 1; /* Reset bp to after the #. */
7581 bp = ip->bufp + 1; /* Point after the '#' */
7582 if (ip->bufp[0] == '%') {
7583 /* Skip past the ':' again. */
7584 while (*bp == '\\') {
7591 /* Skip whitespace and \-newline. */
7593 if (is_hor_space[*bp])
7595 else if (*bp == '\\' && bp[1] == '\n')
7597 else if (*bp == '/') {
7598 if (bp[1] == '\\' && bp[2] == '\n')
7599 newline_fix (bp + 1);
7601 for (bp += 2; ; bp++) {
7604 else if (*bp == '*') {
7605 if (bp[-1] == '/' && warn_comments)
7606 warning ("`/*' within comment");
7607 if (bp[1] == '\\' && bp[2] == '\n')
7608 newline_fix (bp + 1);
7614 #ifdef MULTIBYTE_CHARS
7616 length = local_mblen (bp, endb - bp);
7623 } else if (bp[1] == '/' && cplusplus_comments) {
7624 for (bp += 2; ; bp++) {
7627 if (*bp == '\\' && bp[1] == '\n')
7630 warning ("multiline `//' comment");
7636 #ifdef MULTIBYTE_CHARS
7638 length = local_mblen (bp, endb - bp);
7652 /* Now find end of directive name.
7653 If we encounter a backslash-newline, exchange it with any following
7654 symbol-constituents so that we end up with a contiguous name. */
7660 if (*bp == '\\' && bp[1] == '\n')
7661 name_newline_fix (bp);
7667 ident_length = bp - cp;
7671 /* A line of just `#' becomes blank. */
7673 if (ident_length == 0 && *after_ident == '\n') {
7677 if (ident_length == 0 || !is_idstart[*ident]) {
7679 while (is_idchar[*p]) {
7680 if (*p < '0' || *p > '9')
7684 /* Handle # followed by a line number. */
7685 if (p != ident && !is_idchar[*p]) {
7687 pedwarn ("`#' followed by integer");
7691 /* Avoid error for `###' and similar cases unless -pedantic. */
7693 while (*p == '#' || is_hor_space[*p]) p++;
7695 if (pedantic && !lang_asm)
7696 pedwarn ("invalid preprocessing directive");
7701 if (!lang_asm && pedantic)
7702 pedwarn ("invalid preprocessing directive name");
7706 for (kt = directive_table; kt->length >= 0; kt++) {
7707 IF_STACK_FRAME *temp;
7708 if (ident_length == kt->length
7709 && bcmp (cp, kt->name, kt->length) == 0) {
7710 /* If we are asked to return on next directive, do so now. */
7718 temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7719 temp->next = if_stack;
7721 temp->lineno = ip->lineno;
7722 temp->fname = ip->nominal_fname;
7723 temp->fname_len = ip->nominal_fname_len;
7724 temp->type = kt->type;
7728 if (pedantic && if_stack != save_if_stack)
7729 validate_else (bp, endb);
7731 if (if_stack == instack[indepth].if_stack) {
7732 error ("`#%s' not within a conditional", kt->name);
7735 else if (if_stack == save_if_stack)
7736 goto done; /* found what we came for */
7738 if (kt->type != T_ENDIF) {
7739 if (if_stack->type == T_ELSE)
7740 error ("`#else' or `#elif' after `#else'");
7741 if_stack->type = kt->type;
7746 if_stack = if_stack->next;
7751 case T_INCLUDE_NEXT:
7753 skipping_include_directive = 1;
7762 /* Don't let erroneous code go by. */
7763 if (kt->length < 0 && !lang_asm && pedantic)
7764 pedwarn ("invalid preprocessing directive name");
7769 /* after this returns, rescan will exit because ip->bufp
7770 now points to the end of the buffer.
7771 rescan is responsible for the error message also. */
7774 if (output_conditionals && op != 0) {
7775 char *ptr = "#endfailed\n";
7776 int len = strlen (ptr);
7778 if (op->bufp > op->buf && op->bufp[-1] != '\n')
7783 check_expand (op, beg_of_line - beg_of_group);
7784 bcopy ((char *) beg_of_group, (char *) op->bufp,
7785 beg_of_line - beg_of_group);
7786 op->bufp += beg_of_line - beg_of_group;
7787 op->lineno += ip->lineno - beg_lineno;
7788 check_expand (op, len);
7789 bcopy (ptr, (char *) op->bufp, len);
7795 /* Handle a #else directive. Do this by just continuing processing
7796 without changing if_stack ; this is so that the error message
7797 for missing #endif's etc. will point to the original #if. It
7798 is possible that something different would be better. */
7801 do_else (buf, limit, op, keyword)
7802 U_CHAR *buf, *limit;
7804 struct directive *keyword ATTRIBUTE_UNUSED;
7806 FILE_BUF *ip = &instack[indepth];
7809 SKIP_WHITE_SPACE (buf);
7811 pedwarn ("text following `#else' violates ANSI standard");
7814 if (if_stack == instack[indepth].if_stack) {
7815 error ("`#else' not within a conditional");
7818 /* #ifndef can't have its special treatment for containing the whole file
7819 if it has a #else clause. */
7820 if_stack->control_macro = 0;
7822 if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7823 error ("`#else' after `#else'");
7824 fprintf (stderr, " (matches line %d", if_stack->lineno);
7825 if (! (if_stack->fname_len == ip->nominal_fname_len
7826 && !bcmp (if_stack->fname, ip->nominal_fname,
7827 if_stack->fname_len))) {
7828 fprintf (stderr, ", file ");
7829 eprint_string (if_stack->fname, if_stack->fname_len);
7831 fprintf (stderr, ")\n");
7833 if_stack->type = T_ELSE;
7836 if (if_stack->if_succeeded)
7837 skip_if_group (ip, 0, op);
7839 ++if_stack->if_succeeded; /* continue processing input */
7840 output_line_directive (ip, op, 1, same_file);
7845 /* Unstack after #endif directive. */
7848 do_endif (buf, limit, op, keyword)
7849 U_CHAR *buf, *limit;
7851 struct directive *keyword ATTRIBUTE_UNUSED;
7854 SKIP_WHITE_SPACE (buf);
7856 pedwarn ("text following `#endif' violates ANSI standard");
7859 if (if_stack == instack[indepth].if_stack)
7860 error ("unbalanced `#endif'");
7862 IF_STACK_FRAME *temp = if_stack;
7863 if_stack = if_stack->next;
7864 if (temp->control_macro != 0) {
7865 /* This #endif matched a #ifndef at the start of the file.
7866 See if it is at the end of the file. */
7867 FILE_BUF *ip = &instack[indepth];
7868 U_CHAR *p = ip->bufp;
7869 U_CHAR *ep = ip->buf + ip->length;
7875 && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7876 /* Skip this comment. */
7878 U_CHAR *save_bufp = ip->bufp;
7880 p = skip_to_end_of_comment (ip, &junk, 1);
7881 ip->bufp = save_bufp;
7886 /* If we get here, this #endif ends a #ifndef
7887 that contains all of the file (aside from whitespace).
7888 Arrange not to include the file again
7889 if the macro that was tested is defined.
7891 Do not do this for the top-level file in a -include or any
7892 file in a -imacros. */
7894 && ! (indepth == 1 && no_record_file)
7895 && ! (no_record_file && no_output))
7896 record_control_macro (ip->inc, temp->control_macro);
7900 output_line_directive (&instack[indepth], op, 1, same_file);
7905 /* When an #else or #endif is found while skipping failed conditional,
7906 if -pedantic was specified, this is called to warn about text after
7907 the directive name. P points to the first char after the directive
7911 validate_else (p, limit)
7913 register U_CHAR *limit;
7915 /* Advance P over whitespace and comments. */
7917 while (*p == '\\' && p[1] == '\n')
7919 if (is_hor_space[*p])
7921 else if (*p == '/') {
7922 while (p[1] == '\\' && p[2] == '\n')
7925 /* Don't bother warning about unterminated comments
7926 since that will happen later. Just be sure to exit. */
7927 for (p += 2; ; p++) {
7931 while (p[1] == '\\' && p[2] == '\n')
7940 #ifdef MULTIBYTE_CHARS
7942 length = local_mblen (p, limit - p);
7949 else if (cplusplus_comments && p[1] == '/')
7955 pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7958 /* Skip a comment, assuming the input ptr immediately follows the
7959 initial slash-star. Bump *LINE_COUNTER for each newline.
7960 (The canonical line counter is &ip->lineno.)
7961 Don't use this routine (or the next one) if bumping the line
7962 counter is not sufficient to deal with newlines in the string.
7964 If NOWARN is nonzero, don't warn about slash-star inside a comment.
7965 This feature is useful when processing a comment that is going to
7966 be processed or was processed at another point in the preprocessor,
7967 to avoid a duplicate warning. Likewise for unterminated comment
7971 skip_to_end_of_comment (ip, line_counter, nowarn)
7972 register FILE_BUF *ip;
7973 int *line_counter; /* place to remember newlines, or NULL */
7976 register U_CHAR *limit = ip->buf + ip->length;
7977 register U_CHAR *bp = ip->bufp;
7978 FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7979 int start_line = line_counter ? *line_counter : 0;
7981 /* JF this line_counter stuff is a crock to make sure the
7982 comment is only put out once, no matter how many times
7983 the comment is skipped. It almost works */
7986 *op->bufp++ = bp[-1];
7988 if (cplusplus_comments && bp[-1] == '/') {
7989 for (; bp < limit; bp++) {
7992 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
7994 if (!nowarn && warn_comments)
7995 warning ("multiline `//' comment");
8007 #ifdef MULTIBYTE_CHARS
8009 length = local_mblen (bp, limit - bp);
8014 bcopy (bp, op->bufp, length - 1);
8015 op->bufp += (length - 1);
8027 while (bp < limit) {
8032 /* If this is the end of the file, we have an unterminated comment.
8033 Don't swallow the newline. We are guaranteed that there will be a
8034 trailing newline and various pieces assume it's there. */
8041 if (line_counter != NULL)
8047 if (bp[-2] == '/' && !nowarn && warn_comments)
8048 warning ("`/*' within comment");
8049 if (*bp == '\\' && bp[1] == '\n')
8058 #ifdef MULTIBYTE_CHARS
8063 length = local_mblen (bp, limit - bp);
8069 bcopy (bp, op->bufp, length);
8079 error_with_line (line_for_error (start_line), "unterminated comment");
8084 /* Skip over a quoted string. BP points to the opening quote.
8085 Returns a pointer after the closing quote. Don't go past LIMIT.
8086 START_LINE is the line number of the starting point (but it need
8087 not be valid if the starting point is inside a macro expansion).
8089 The input stack state is not changed.
8091 If COUNT_NEWLINES is nonzero, it points to an int to increment
8092 for each newline passed.
8094 If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
8095 if we pass a backslash-newline.
8097 If EOFP is nonzero, set *EOFP to 1 if the string is unterminated. */
8100 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
8101 register U_CHAR *bp;
8102 register U_CHAR *limit;
8104 int *count_newlines;
8105 int *backslash_newlines_p;
8108 register U_CHAR c, match;
8113 error_with_line (line_for_error (start_line),
8114 "unterminated string or character constant");
8115 error_with_line (multiline_string_line,
8116 "possible real start of unterminated constant");
8117 multiline_string_line = 0;
8124 while (*bp == '\\' && bp[1] == '\n') {
8125 if (backslash_newlines_p)
8126 *backslash_newlines_p = 1;
8132 if (backslash_newlines_p)
8133 *backslash_newlines_p = 1;
8138 } else if (c == '\n') {
8140 /* Unterminated strings and character constants are 'valid'. */
8141 bp--; /* Don't consume the newline. */
8146 if (match == '\'') {
8147 error_with_line (line_for_error (start_line),
8148 "unterminated string or character constant");
8154 /* If not traditional, then allow newlines inside strings. */
8157 if (multiline_string_line == 0) {
8159 pedwarn_with_line (line_for_error (start_line),
8160 "string constant runs past end of line");
8161 multiline_string_line = start_line;
8163 } else if (c == match)
8165 #ifdef MULTIBYTE_CHARS
8169 length = local_mblen (bp, limit - bp);
8179 /* Place into DST a quoted string representing the string SRC.
8180 SRCLEN is the length of SRC; SRC may contain null bytes.
8181 Return the address of DST's terminating null. */
8184 quote_string (dst, src, srclen)
8189 char *srclim = src + srclen;
8192 while (src != srclim)
8193 switch ((c = *src++))
8200 sprintf (dst, "\\%03o", c);
8217 /* Skip across a group of balanced parens, starting from IP->bufp.
8218 IP->bufp is updated. Use this with IP->bufp pointing at an open-paren.
8220 This does not handle newlines, because it's used for the arg of #if,
8221 where there aren't any newlines. Also, backslash-newline can't appear. */
8224 skip_paren_group (ip)
8225 register FILE_BUF *ip;
8227 U_CHAR *limit = ip->buf + ip->length;
8228 U_CHAR *p = ip->bufp;
8230 int lines_dummy = 0;
8232 while (p != limit) {
8242 return ip->bufp = p;
8248 p = skip_to_end_of_comment (ip, &lines_dummy, 0);
8256 p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
8258 return ip->bufp = p;
8268 /* Write out a #line directive, for instance, after an #include file.
8269 If CONDITIONAL is nonzero, we can omit the #line if it would
8270 appear to be a no-op, and we can output a few newlines instead
8271 if we want to increase the line number by a small amount.
8272 FILE_CHANGE says whether we are entering a file, leaving, or neither. */
8275 output_line_directive (ip, op, conditional, file_change)
8278 enum file_change_code file_change;
8281 char *line_directive_buf, *line_end;
8283 if (no_line_directives
8284 || ip->fname == NULL
8286 op->lineno = ip->lineno;
8291 if (ip->lineno == op->lineno)
8294 /* If the inherited line number is a little too small,
8295 output some newlines instead of a #line directive. */
8296 if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
8297 check_expand (op, 10);
8298 while (ip->lineno > op->lineno) {
8306 /* Output a positive line number if possible. */
8307 while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
8308 && *ip->bufp == '\n') {
8313 line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
8314 sprintf (line_directive_buf, "# %d ", ip->lineno);
8315 line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
8316 ip->nominal_fname, ip->nominal_fname_len);
8317 if (file_change != same_file) {
8319 *line_end++ = file_change == enter_file ? '1' : '2';
8321 /* Tell cc1 if following text comes from a system header file. */
8322 if (ip->system_header_p) {
8326 #ifndef NO_IMPLICIT_EXTERN_C
8327 /* Tell cc1plus if following text should be treated as C. */
8328 if (ip->system_header_p == 2 && cplusplus) {
8334 len = line_end - line_directive_buf;
8335 check_expand (op, len + 1);
8336 if (op->bufp > op->buf && op->bufp[-1] != '\n')
8338 bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8340 op->lineno = ip->lineno;
8343 /* This structure represents one parsed argument in a macro call.
8344 `raw' points to the argument text as written (`raw_length' is its length).
8345 `expanded' points to the argument's macro-expansion
8346 (its length is `expand_length').
8347 `stringified_length' is the length the argument would have
8349 `use_count' is the number of times this macro arg is substituted
8350 into the macro. If the actual use count exceeds 10,
8351 the value stored is 10.
8352 `free1' and `free2', if nonzero, point to blocks to be freed
8353 when the macro argument data is no longer needed. */
8356 U_CHAR *raw, *expanded;
8357 int raw_length, expand_length;
8358 int stringified_length;
8359 U_CHAR *free1, *free2;
8364 /* Expand a macro call.
8365 HP points to the symbol that is the macro being called.
8366 Put the result of expansion onto the input stack
8367 so that subsequent input by our caller will use it.
8369 If macro wants arguments, caller has already verified that
8370 an argument list follows; arguments come from the input stack. */
8373 macroexpand (hp, op)
8378 DEFINITION *defn = hp->value.defn;
8379 register U_CHAR *xbuf;
8381 int start_line = instack[indepth].lineno;
8382 int rest_args, rest_zero;
8384 CHECK_DEPTH (return;);
8386 /* it might not actually be a macro. */
8387 if (hp->type != T_MACRO) {
8388 special_symbol (hp, op);
8392 /* This macro is being used inside a #if, which means it must be */
8393 /* recorded as a precondition. */
8394 if (pcp_inside_if && pcp_outfile && defn->predefined)
8395 dump_single_macro (hp, pcp_outfile);
8397 nargs = defn->nargs;
8401 struct argdata *args;
8402 char *parse_error = 0;
8404 args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8406 for (i = 0; i < nargs; i++) {
8407 args[i].raw = (U_CHAR *) "";
8408 args[i].expanded = 0;
8409 args[i].raw_length = args[i].expand_length
8410 = args[i].stringified_length = 0;
8411 args[i].free1 = args[i].free2 = 0;
8412 args[i].use_count = 0;
8415 /* Parse all the macro args that are supplied. I counts them.
8416 The first NARGS args are stored in ARGS.
8417 The rest are discarded.
8418 If rest_args is set then we assume macarg absorbed the rest of the args.
8423 /* Discard the open-parenthesis or comma before the next arg. */
8424 ++instack[indepth].bufp;
8427 if (i < nargs || (nargs == 0 && i == 0)) {
8428 /* If we are working on last arg which absorbs rest of args... */
8429 if (i == nargs - 1 && defn->rest_args)
8431 parse_error = macarg (&args[i], rest_args);
8434 parse_error = macarg (NULL_PTR, 0);
8436 error_with_line (line_for_error (start_line), parse_error);
8440 } while (*instack[indepth].bufp != ')');
8442 /* If we got one arg but it was just whitespace, call that 0 args. */
8444 register U_CHAR *bp = args[0].raw;
8445 register U_CHAR *lim = bp + args[0].raw_length;
8446 /* cpp.texi says for foo ( ) we provide one argument.
8447 However, if foo wants just 0 arguments, treat this as 0. */
8449 while (bp != lim && is_space[*bp]) bp++;
8454 /* Don't output an error message if we have already output one for
8455 a parse error above. */
8457 if (nargs == 0 && i > 0) {
8459 error ("arguments given to macro `%s'", hp->name);
8460 } else if (i < nargs) {
8461 /* traditional C allows foo() if foo wants one argument. */
8462 if (nargs == 1 && i == 0 && traditional)
8464 /* the rest args token is allowed to absorb 0 tokens */
8465 else if (i == nargs - 1 && defn->rest_args)
8467 else if (parse_error)
8470 error ("macro `%s' used without args", hp->name);
8472 error ("macro `%s' used with just one arg", hp->name);
8474 error ("macro `%s' used with only %d args", hp->name, i);
8475 } else if (i > nargs) {
8477 error ("macro `%s' used with too many (%d) args", hp->name, i);
8480 /* Swallow the closeparen. */
8481 ++instack[indepth].bufp;
8483 /* If macro wants zero args, we parsed the arglist for checking only.
8484 Read directly from the macro definition. */
8486 xbuf = defn->expansion;
8487 xbuf_len = defn->length;
8489 register U_CHAR *exp = defn->expansion;
8490 register int offset; /* offset in expansion,
8491 copied a piece at a time */
8492 register int totlen; /* total amount of exp buffer filled so far */
8494 register struct reflist *ap, *last_ap;
8496 /* Macro really takes args. Compute the expansion of this call. */
8498 /* Compute length in characters of the macro's expansion.
8499 Also count number of times each arg is used. */
8500 xbuf_len = defn->length;
8501 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8503 xbuf_len += args[ap->argno].stringified_length;
8504 else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8505 /* Add 4 for two newline-space markers to prevent
8506 token concatenation. */
8507 xbuf_len += args[ap->argno].raw_length + 4;
8509 /* We have an ordinary (expanded) occurrence of the arg.
8510 So compute its expansion, if we have not already. */
8511 if (args[ap->argno].expanded == 0) {
8513 obuf = expand_to_temp_buffer (args[ap->argno].raw,
8514 args[ap->argno].raw + args[ap->argno].raw_length,
8517 args[ap->argno].expanded = obuf.buf;
8518 args[ap->argno].expand_length = obuf.length;
8519 args[ap->argno].free2 = obuf.buf;
8522 /* Add 4 for two newline-space markers to prevent
8523 token concatenation. */
8524 xbuf_len += args[ap->argno].expand_length + 4;
8526 if (args[ap->argno].use_count < 10)
8527 args[ap->argno].use_count++;
8530 xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8532 /* Generate in XBUF the complete expansion
8533 with arguments substituted in.
8534 TOTLEN is the total size generated so far.
8535 OFFSET is the index in the definition
8536 of where we are copying from. */
8537 offset = totlen = 0;
8538 for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8539 last_ap = ap, ap = ap->next) {
8540 register struct argdata *arg = &args[ap->argno];
8541 int count_before = totlen;
8543 /* Add chars to XBUF. */
8544 for (i = 0; i < ap->nchars; i++, offset++)
8545 xbuf[totlen++] = exp[offset];
8547 /* If followed by an empty rest arg with concatenation,
8548 delete the last run of nonwhite chars. */
8549 if (rest_zero && totlen > count_before
8550 && ((ap->rest_args && ap->raw_before != 0)
8551 || (last_ap != NULL && last_ap->rest_args
8552 && last_ap->raw_after != 0))) {
8553 /* Delete final whitespace. */
8554 while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8558 /* Delete the nonwhites before them. */
8559 while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8564 if (ap->stringify != 0) {
8565 int arglen = arg->raw_length;
8571 && (c = arg->raw[i], is_space[c]))
8574 && (c = arg->raw[arglen - 1], is_space[c]))
8577 xbuf[totlen++] = '\"'; /* insert beginning quote */
8578 for (; i < arglen; i++) {
8582 /* Special markers Newline Space
8583 generate nothing for a stringified argument. */
8584 if (c == '\n' && arg->raw[i+1] != '\n') {
8589 /* Internal sequences of whitespace are replaced by one space
8590 except within an string or char token. */
8591 if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8593 /* Note that Newline Space does occur within whitespace
8594 sequences; consider it part of the sequence. */
8595 if (c == '\n' && is_space[arg->raw[i+1]])
8597 else if (c != '\n' && is_space[c])
8612 else if (in_string) {
8617 #ifdef MULTIBYTE_CHARS
8619 length = local_mblen (arg->raw + i, arglen - i);
8622 bcopy (arg->raw + i, xbuf + totlen, length);
8629 } else if (c == '\"' || c == '\'')
8633 /* Escape these chars */
8634 if (c == '\"' || (in_string && c == '\\'))
8635 xbuf[totlen++] = '\\';
8636 /* We used to output e.g. \008 for control characters here,
8637 but this doesn't conform to the C Standard.
8638 Just output the characters as-is. */
8642 xbuf[totlen++] = '\"'; /* insert ending quote */
8643 } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8644 U_CHAR *p1 = arg->raw;
8645 U_CHAR *l1 = p1 + arg->raw_length;
8646 if (ap->raw_before != 0) {
8647 while (p1 != l1 && is_space[*p1]) p1++;
8648 while (p1 != l1 && is_idchar[*p1])
8649 xbuf[totlen++] = *p1++;
8650 /* Delete any no-reexpansion marker that follows
8651 an identifier at the beginning of the argument
8652 if the argument is concatenated with what precedes it. */
8653 if (p1[0] == '\n' && p1[1] == '-')
8655 } else if (!traditional) {
8656 /* Ordinary expanded use of the argument.
8657 Put in newline-space markers to prevent token pasting. */
8658 xbuf[totlen++] = '\n';
8659 xbuf[totlen++] = ' ';
8661 if (ap->raw_after != 0) {
8662 /* Arg is concatenated after: delete trailing whitespace,
8663 whitespace markers, and no-reexpansion markers. */
8665 if (is_space[l1[-1]]) l1--;
8666 else if (l1[-1] == '-') {
8667 U_CHAR *p2 = l1 - 1;
8668 /* If a `-' is preceded by an odd number of newlines then it
8669 and the last newline are a no-reexpansion marker. */
8670 while (p2 != p1 && p2[-1] == '\n') p2--;
8671 if ((l1 - 1 - p2) & 1) {
8680 bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8682 if (!traditional && ap->raw_after == 0) {
8683 /* Ordinary expanded use of the argument.
8684 Put in newline-space markers to prevent token pasting. */
8685 xbuf[totlen++] = '\n';
8686 xbuf[totlen++] = ' ';
8689 /* Ordinary expanded use of the argument.
8690 Put in newline-space markers to prevent token pasting. */
8692 xbuf[totlen++] = '\n';
8693 xbuf[totlen++] = ' ';
8695 bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8696 arg->expand_length);
8697 totlen += arg->expand_length;
8699 xbuf[totlen++] = '\n';
8700 xbuf[totlen++] = ' ';
8702 /* If a macro argument with newlines is used multiple times,
8703 then only expand the newlines once. This avoids creating output
8704 lines which don't correspond to any input line, which confuses
8706 if (arg->use_count > 1 && arg->newlines > 0) {
8707 /* Don't bother doing change_newlines for subsequent
8711 = change_newlines (arg->expanded, arg->expand_length);
8715 if (totlen > xbuf_len)
8719 /* If there is anything left of the definition after handling
8720 the arg list, copy that in too. */
8722 for (i = offset; i < defn->length; i++) {
8723 /* if we've reached the end of the macro */
8726 if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8727 && last_ap->raw_after != 0))
8728 xbuf[totlen++] = exp[i];
8734 for (i = 0; i < nargs; i++) {
8735 if (args[i].free1 != 0)
8736 free (args[i].free1);
8737 if (args[i].free2 != 0)
8738 free (args[i].free2);
8742 xbuf = defn->expansion;
8743 xbuf_len = defn->length;
8746 /* Now put the expansion on the input stack
8747 so our caller will commence reading from it. */
8749 register FILE_BUF *ip2;
8751 ip2 = &instack[++indepth];
8754 ip2->nominal_fname = 0;
8755 ip2->nominal_fname_len = 0;
8757 /* This may not be exactly correct, but will give much better error
8758 messages for nested macro calls than using a line number of zero. */
8759 ip2->lineno = start_line;
8761 ip2->length = xbuf_len;
8763 ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8765 ip2->if_stack = if_stack;
8766 ip2->system_header_p = 0;
8768 /* Recursive macro use sometimes works traditionally.
8769 #define foo(x,y) bar (x (y,0), y)
8773 hp->type = T_DISABLED;
8777 /* Parse a macro argument and store the info on it into *ARGPTR.
8778 REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8779 Return nonzero to indicate a syntax error. */
8782 macarg (argptr, rest_args)
8783 register struct argdata *argptr;
8786 FILE_BUF *ip = &instack[indepth];
8792 /* Try to parse as much of the argument as exists at this
8793 input stack level. */
8794 U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8795 &paren, &newlines, &comments, rest_args);
8797 /* If we find the end of the argument at this level,
8798 set up *ARGPTR to point at it in the input stack. */
8799 if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8800 && bp != ip->buf + ip->length) {
8802 argptr->raw = ip->bufp;
8803 argptr->raw_length = bp - ip->bufp;
8804 argptr->newlines = newlines;
8808 /* This input stack level ends before the macro argument does.
8809 We must pop levels and keep parsing.
8810 Therefore, we must allocate a temporary buffer and copy
8811 the macro argument into it. */
8812 int bufsize = bp - ip->bufp;
8813 int extra = newlines;
8814 U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8815 int final_start = 0;
8817 bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8819 ip->lineno += newlines;
8821 while (bp == ip->buf + ip->length) {
8822 if (instack[indepth].macro == 0) {
8823 result = "unterminated macro call";
8826 ip->macro->type = T_MACRO;
8828 free (ip->free_ptr);
8829 ip = &instack[--indepth];
8832 bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8833 &newlines, &comments, rest_args);
8834 final_start = bufsize;
8835 bufsize += bp - ip->bufp;
8837 buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8838 bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8841 ip->lineno += newlines;
8844 /* Now, if arg is actually wanted, record its raw form,
8845 discarding comments and duplicating newlines in whatever
8846 part of it did not come from a macro expansion.
8847 EXTRA space has been preallocated for duplicating the newlines.
8848 FINAL_START is the index of the start of that part. */
8850 argptr->raw = buffer;
8851 argptr->raw_length = bufsize;
8852 argptr->free1 = buffer;
8853 argptr->newlines = newlines;
8854 if ((newlines || comments) && ip->fname != 0)
8857 discard_comments (argptr->raw + final_start,
8858 argptr->raw_length - final_start,
8860 argptr->raw[argptr->raw_length] = 0;
8861 if (argptr->raw_length > bufsize + extra)
8866 /* If we are not discarding this argument,
8867 macroexpand it and compute its length as stringified.
8868 All this info goes into *ARGPTR. */
8871 register U_CHAR *buf, *lim;
8872 register int totlen;
8875 lim = buf + argptr->raw_length;
8877 while (buf != lim && is_space[*buf])
8879 while (buf != lim && is_space[lim[-1]])
8881 totlen = traditional ? 0 : 2; /* Count opening and closing quote. */
8882 while (buf != lim) {
8883 register U_CHAR c = *buf++;
8885 /* Internal sequences of whitespace are replaced by one space
8886 in most cases, but not always. So count all the whitespace
8887 in case we need to keep it all. */
8890 SKIP_ALL_WHITE_SPACE (buf);
8893 if (c == '\"' || c == '\\') /* escape these chars */
8896 argptr->stringified_length = totlen;
8901 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8902 taken from the expansion of MACRO,
8903 counting parens in *DEPTHPTR,
8904 and return if reach LIMIT
8905 or before a `)' that would make *DEPTHPTR negative
8906 or before a comma when *DEPTHPTR is zero.
8907 Single and double quotes are matched and termination
8908 is inhibited within them. Comments also inhibit it.
8909 Value returned is pointer to stopping place.
8911 Increment *NEWLINES each time a newline is passed.
8912 REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8913 Set *COMMENTS to 1 if a comment is seen. */
8916 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8918 register U_CHAR *limit;
8919 struct hashnode *macro;
8920 int *depthptr, *newlines, *comments;
8923 register U_CHAR *bp = start;
8925 while (bp < limit) {
8931 if (--(*depthptr) < 0)
8935 /* Traditionally, backslash makes following char not special. */
8936 if (traditional && bp + 1 < limit && bp[1] != '\n')
8945 if (bp[1] == '\\' && bp[2] == '\n')
8946 newline_fix (bp + 1);
8949 for (bp += 2; bp < limit; bp++) {
8952 else if (*bp == '*') {
8953 if (bp[-1] == '/' && warn_comments)
8954 warning ("`/*' within comment");
8955 if (bp[1] == '\\' && bp[2] == '\n')
8956 newline_fix (bp + 1);
8964 #ifdef MULTIBYTE_CHARS
8966 length = local_mblen (bp, limit - bp);
8972 } else if (bp[1] == '/' && cplusplus_comments) {
8974 for (bp += 2; bp < limit; bp++) {
8979 if (*bp == '\\' && bp + 1 < limit && bp[1] == '\n')
8983 warning ("multiline `//' comment");
8988 #ifdef MULTIBYTE_CHARS
8990 length = local_mblen (bp, limit - bp);
9002 for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
9008 while (*bp == '\\' && bp[1] == '\n') {
9013 } else if (*bp == '\n') {
9020 #ifdef MULTIBYTE_CHARS
9022 length = local_mblen (bp, limit - bp);
9031 /* if we've returned to lowest level and we aren't absorbing all args */
9032 if ((*depthptr) == 0 && rest_args == 0)
9042 /* Discard comments and duplicate newlines
9043 in the string of length LENGTH at START,
9044 except inside of string constants.
9045 The string is copied into itself with its beginning staying fixed.
9047 NEWLINES is the number of newlines that must be duplicated.
9048 We assume that that much extra space is available past the end
9052 discard_comments (start, length, newlines)
9057 register U_CHAR *ibp;
9058 register U_CHAR *obp;
9059 register U_CHAR *limit;
9062 /* If we have newlines to duplicate, copy everything
9063 that many characters up. Then, in the second part,
9064 we will have room to insert the newlines
9066 NEWLINES may actually be too large, because it counts
9067 newlines in string constants, and we don't duplicate those.
9068 But that does no harm. */
9070 ibp = start + length;
9071 obp = ibp + newlines;
9073 while (limit != ibp)
9077 ibp = start + newlines;
9078 limit = start + length + newlines;
9081 while (ibp < limit) {
9082 *obp++ = c = *ibp++;
9085 /* Duplicate the newline. */
9097 if (*ibp == '\\' && ibp[1] == '\n')
9099 /* Delete any comment. */
9100 if (cplusplus_comments && ibp[0] == '/') {
9101 /* Comments are equivalent to spaces. */
9108 if (*ibp == '\\' && ibp + 1 < limit && ibp[1] == '\n')
9112 #ifdef MULTIBYTE_CHARS
9113 int length = local_mblen (ibp, limit - ibp);
9115 ibp += (length - 1);
9122 if (ibp[0] != '*' || ibp + 1 >= limit)
9124 /* Comments are equivalent to spaces.
9125 For -traditional, a comment is equivalent to nothing. */
9130 while (++ibp < limit) {
9131 if (ibp[0] == '*') {
9132 if (ibp[1] == '\\' && ibp[2] == '\n')
9133 newline_fix (ibp + 1);
9134 if (ibp[1] == '/') {
9141 #ifdef MULTIBYTE_CHARS
9142 int length = local_mblen (ibp, limit - ibp);
9144 ibp += (length - 1);
9152 /* Notice and skip strings, so that we don't
9153 think that comments start inside them,
9154 and so we don't duplicate newlines in them. */
9157 while (ibp < limit) {
9158 *obp++ = c = *ibp++;
9166 else if (c == '\\') {
9167 if (ibp < limit && *ibp == '\n') {
9171 while (*ibp == '\\' && ibp[1] == '\n')
9179 #ifdef MULTIBYTE_CHARS
9182 length = local_mblen (ibp, limit - ibp);
9186 bcopy (ibp, obp, length);
9203 /* Turn newlines to spaces in the string of length LENGTH at START,
9204 except inside of string constants.
9205 The string is copied into itself with its beginning staying fixed. */
9208 change_newlines (start, length)
9212 register U_CHAR *ibp;
9213 register U_CHAR *obp;
9214 register U_CHAR *limit;
9218 limit = start + length;
9221 while (ibp < limit) {
9222 *obp++ = c = *ibp++;
9225 /* If this is a NEWLINE NEWLINE, then this is a real newline in the
9226 string. Skip past the newline and its duplicate.
9227 Put a space in the output. */
9238 /* Notice and skip strings, so that we don't delete newlines in them. */
9241 while (ibp < limit) {
9242 *obp++ = c = *ibp++;
9245 else if (c == '\\' && ibp < limit && *ibp == '\n')
9254 #ifdef MULTIBYTE_CHARS
9257 length = local_mblen (ibp, limit - ibp);
9261 bcopy (ibp, obp, length);
9278 /* my_strerror - return the descriptive text associated with an
9282 my_strerror (errnum)
9288 #ifndef HAVE_STRERROR
9289 result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
9291 result = strerror (errnum);
9294 /* VAXCRTL's strerror() takes an optional second argument, which only
9295 matters when the first argument is EVMSERR. However, it's simplest
9296 just to pass it unconditionally. `vaxc$errno' is declared in
9297 <errno.h>, and maintained by the library in parallel with `errno'.
9298 We assume that caller's `errnum' either matches the last setting of
9299 `errno' by the library or else does not have the value `EVMSERR'. */
9301 result = strerror (errnum, vaxc$errno);
9305 result = "undocumented I/O error";
9310 /* error - print error message and increment count of errors. */
9313 error VPROTO ((char * msg, ...))
9315 #ifndef ANSI_PROTOTYPES
9320 VA_START (args, msg);
9322 #ifndef ANSI_PROTOTYPES
9323 msg = va_arg (args, char *);
9336 FILE_BUF *ip = NULL;
9338 print_containing_files ();
9340 for (i = indepth; i >= 0; i--)
9341 if (instack[i].fname != NULL) {
9347 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9348 fprintf (stderr, ":%d: ", ip->lineno);
9350 vfprintf (stderr, msg, args);
9351 fprintf (stderr, "\n");
9355 /* Error including a message from `errno'. */
9358 error_from_errno (name)
9363 FILE_BUF *ip = NULL;
9365 print_containing_files ();
9367 for (i = indepth; i >= 0; i--)
9368 if (instack[i].fname != NULL) {
9374 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9375 fprintf (stderr, ":%d: ", ip->lineno);
9378 fprintf (stderr, "%s: %s\n", name, my_strerror (e));
9383 /* Print error message but don't count it. */
9386 warning VPROTO ((char * msg, ...))
9388 #ifndef ANSI_PROTOTYPES
9393 VA_START (args, msg);
9395 #ifndef ANSI_PROTOTYPES
9396 msg = va_arg (args, char *);
9399 vwarning (msg, args);
9404 vwarning (msg, args)
9409 FILE_BUF *ip = NULL;
9411 if (inhibit_warnings)
9414 if (warnings_are_errors)
9417 print_containing_files ();
9419 for (i = indepth; i >= 0; i--)
9420 if (instack[i].fname != NULL) {
9426 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9427 fprintf (stderr, ":%d: ", ip->lineno);
9429 fprintf (stderr, "warning: ");
9430 vfprintf (stderr, msg, args);
9431 fprintf (stderr, "\n");
9435 error_with_line VPROTO ((int line, char * msg, ...))
9437 #ifndef ANSI_PROTOTYPES
9443 VA_START (args, msg);
9445 #ifndef ANSI_PROTOTYPES
9446 line = va_arg (args, int);
9447 msg = va_arg (args, char *);
9450 verror_with_line (line, msg, args);
9455 verror_with_line (line, msg, args)
9461 FILE_BUF *ip = NULL;
9463 print_containing_files ();
9465 for (i = indepth; i >= 0; i--)
9466 if (instack[i].fname != NULL) {
9472 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9473 fprintf (stderr, ":%d: ", line);
9475 vfprintf (stderr, msg, args);
9476 fprintf (stderr, "\n");
9481 warning_with_line VPROTO ((int line, char * msg, ...))
9483 #ifndef ANSI_PROTOTYPES
9489 VA_START (args, msg);
9491 #ifndef ANSI_PROTOTYPES
9492 line = va_arg (args, int);
9493 msg = va_arg (args, char *);
9496 vwarning_with_line (line, msg, args);
9501 vwarning_with_line (line, msg, args)
9507 FILE_BUF *ip = NULL;
9509 if (inhibit_warnings)
9512 if (warnings_are_errors)
9515 print_containing_files ();
9517 for (i = indepth; i >= 0; i--)
9518 if (instack[i].fname != NULL) {
9524 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9525 fprintf (stderr, line ? ":%d: " : ": ", line);
9527 fprintf (stderr, "warning: ");
9528 vfprintf (stderr, msg, args);
9529 fprintf (stderr, "\n");
9532 /* Print an error message and maybe count it. */
9535 pedwarn VPROTO ((char * msg, ...))
9537 #ifndef ANSI_PROTOTYPES
9542 VA_START (args, msg);
9544 #ifndef ANSI_PROTOTYPES
9545 msg = va_arg (args, char *);
9548 if (pedantic_errors)
9551 vwarning (msg, args);
9556 pedwarn_with_line VPROTO ((int line, char * msg, ...))
9558 #ifndef ANSI_PROTOTYPES
9564 VA_START (args, msg);
9566 #ifndef ANSI_PROTOTYPES
9567 line = va_arg (args, int);
9568 msg = va_arg (args, char *);
9571 if (pedantic_errors)
9572 verror_with_line (line, msg, args);
9574 vwarning_with_line (line, msg, args);
9578 /* Report a warning (or an error if pedantic_errors)
9579 giving specified file name and line number, not current. */
9582 pedwarn_with_file_and_line VPROTO ((char *file, size_t file_len, int line,
9585 #ifndef ANSI_PROTOTYPES
9593 if (!pedantic_errors && inhibit_warnings)
9596 VA_START (args, msg);
9598 #ifndef ANSI_PROTOTYPES
9599 file = va_arg (args, char *);
9600 file_len = va_arg (args, size_t);
9601 line = va_arg (args, int);
9602 msg = va_arg (args, char *);
9606 eprint_string (file, file_len);
9607 fprintf (stderr, ":%d: ", line);
9609 if (pedantic_errors)
9611 if (!pedantic_errors)
9612 fprintf (stderr, "warning: ");
9614 vfprintf (stderr, msg, args);
9616 fprintf (stderr, "\n");
9619 /* Print the file names and line numbers of the #include
9620 directives which led to the current file. */
9623 print_containing_files ()
9625 FILE_BUF *ip = NULL;
9629 /* If stack of files hasn't changed since we last printed
9630 this info, don't repeat it. */
9631 if (last_error_tick == input_file_stack_tick)
9634 for (i = indepth; i >= 0; i--)
9635 if (instack[i].fname != NULL) {
9640 /* Give up if we don't find a source file. */
9644 /* Find the other, outer source files. */
9645 for (i--; i >= 0; i--)
9646 if (instack[i].fname != NULL) {
9650 fprintf (stderr, "In file included");
9652 fprintf (stderr, ",\n ");
9655 fprintf (stderr, " from ");
9656 eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9657 fprintf (stderr, ":%d", ip->lineno);
9660 fprintf (stderr, ":\n");
9662 /* Record we have printed the status as of this time. */
9663 last_error_tick = input_file_stack_tick;
9666 /* Return the line at which an error occurred.
9667 The error is not necessarily associated with the current spot
9668 in the input stack, so LINE says where. LINE will have been
9669 copied from ip->lineno for the current input level.
9670 If the current level is for a file, we return LINE.
9671 But if the current level is not for a file, LINE is meaningless.
9672 In that case, we return the lineno of the innermost file. */
9675 line_for_error (line)
9681 for (i = indepth; i >= 0; ) {
9682 if (instack[i].fname != 0)
9687 line1 = instack[i].lineno;
9695 * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9697 * As things stand, nothing is ever placed in the output buffer to be
9698 * removed again except when it's KNOWN to be part of an identifier,
9699 * so flushing and moving down everything left, instead of expanding,
9703 /* You might think void was cleaner for the return type,
9704 but that would get type mismatch in check_expand in strict ANSI. */
9707 grow_outbuf (obuf, needed)
9708 register FILE_BUF *obuf;
9709 register int needed;
9714 if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9717 /* Make it at least twice as big as it is now. */
9719 /* Make it have at least 150% of the free space we will need. */
9720 minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9721 if (minsize > obuf->length)
9722 obuf->length = minsize;
9724 if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9727 obuf->bufp = p + (obuf->bufp - obuf->buf);
9733 /* Symbol table for macro names and special symbols */
9736 * install a name in the main hash table, even if it is already there.
9737 * name stops with first non alphanumeric, except leading '#'.
9738 * caller must check against redefinition if that is desired.
9739 * delete_macro () removes things installed by install () in fifo order.
9740 * this is important because of the `defined' special symbol used
9741 * in #if, and also if pushdef/popdef directives are ever implemented.
9743 * If LEN is >= 0, it is the length of the name.
9744 * Otherwise, compute the length by scanning the entire name.
9746 * If HASH is >= 0, it is the precomputed hash code.
9747 * Otherwise, compute the hash code.
9751 install (name, len, type, value, hash)
9754 enum node_type type;
9758 register HASHNODE *hp;
9759 register int i, bucket;
9760 register U_CHAR *p, *q;
9764 while (is_idchar[*p])
9770 hash = hashf (name, len, HASHSIZE);
9772 i = sizeof (HASHNODE) + len + 1;
9773 hp = (HASHNODE *) xmalloc (i);
9775 hp->bucket_hdr = &hashtab[bucket];
9776 hp->next = hashtab[bucket];
9777 hashtab[bucket] = hp;
9779 if (hp->next != NULL)
9780 hp->next->prev = hp;
9783 hp->value.cpval = value;
9784 hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9787 for (i = 0; i < len; i++)
9794 * find the most recent hash node for name "name" (ending with first
9795 * non-identifier char) installed by install
9797 * If LEN is >= 0, it is the length of the name.
9798 * Otherwise, compute the length by scanning the entire name.
9800 * If HASH is >= 0, it is the precomputed hash code.
9801 * Otherwise, compute the hash code.
9805 lookup (name, len, hash)
9810 register U_CHAR *bp;
9811 register HASHNODE *bucket;
9814 for (bp = name; is_idchar[*bp]; bp++) ;
9819 hash = hashf (name, len, HASHSIZE);
9821 bucket = hashtab[hash];
9823 if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9825 bucket = bucket->next;
9831 * Delete a hash node. Some weirdness to free junk from macros.
9832 * More such weirdness will have to be added if you define more hash
9833 * types that need it.
9836 /* Note that the DEFINITION of a macro is removed from the hash table
9837 but its storage is not freed. This would be a storage leak
9838 except that it is not reasonable to keep undefining and redefining
9839 large numbers of macros many times.
9840 In any case, this is necessary, because a macro can be #undef'd
9841 in the middle of reading the arguments to a call to it.
9842 If #undef freed the DEFINITION, that would crash. */
9849 if (hp->prev != NULL)
9850 hp->prev->next = hp->next;
9851 if (hp->next != NULL)
9852 hp->next->prev = hp->prev;
9854 /* Make sure that the bucket chain header that the deleted guy was
9855 on points to the right thing afterwards. */
9856 if (hp == *hp->bucket_hdr)
9857 *hp->bucket_hdr = hp->next;
9860 if (hp->type == T_MACRO) {
9861 DEFINITION *d = hp->value.defn;
9862 struct reflist *ap, *nextap;
9864 for (ap = d->pattern; ap != NULL; ap = nextap) {
9875 * return hash function on name. must be compatible with the one
9876 * computed a step at a time, elsewhere
9880 hashf (name, len, hashsize)
9881 register U_CHAR *name;
9888 r = HASHSTEP (r, *name++);
9890 return MAKE_POS (r) % hashsize;
9894 /* Dump the definition of a single macro HP to OF. */
9897 dump_single_macro (hp, of)
9898 register HASHNODE *hp;
9901 register DEFINITION *defn = hp->value.defn;
9907 /* Print the definition of the macro HP. */
9909 fprintf (of, "#define %s", hp->name);
9911 if (defn->nargs >= 0) {
9915 for (i = 0; i < defn->nargs; i++) {
9916 dump_arg_n (defn, i, of);
9917 if (i + 1 < defn->nargs)
9927 for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9928 dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9929 offset += ap->nchars;
9931 if (ap->nchars != 0)
9933 if (ap->stringify) {
9934 switch (ap->stringify) {
9935 case SHARP_TOKEN: fprintf (of, "#"); break;
9936 case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9937 case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9938 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9942 if (ap->raw_before != 0) {
9944 switch (ap->raw_before) {
9945 case WHITE_SHARP_TOKEN:
9946 case WHITE_PERCENT_COLON_TOKEN:
9953 switch (ap->raw_before) {
9954 case SHARP_TOKEN: fprintf (of, "##"); break;
9955 case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9956 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9957 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9964 dump_arg_n (defn, ap->argno, of);
9965 if (!traditional && ap->raw_after != 0) {
9966 switch (ap->raw_after) {
9967 case SHARP_TOKEN: fprintf (of, "##"); break;
9968 case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9969 case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9970 case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9976 dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9980 /* Dump all macro definitions as #defines to stdout. */
9987 for (bucket = 0; bucket < HASHSIZE; bucket++) {
9988 register HASHNODE *hp;
9990 for (hp = hashtab[bucket]; hp; hp= hp->next) {
9991 if (hp->type == T_MACRO)
9992 dump_single_macro (hp, stdout);
9997 /* Output to OF a substring of a macro definition.
9998 BASE is the beginning of the definition.
9999 Output characters START thru LENGTH.
10000 Unless traditional, discard newlines outside of strings, thus
10001 converting funny-space markers to ordinary spaces. */
10004 dump_defn_1 (base, start, length, of)
10010 U_CHAR *p = base + start;
10011 U_CHAR *limit = base + start + length;
10014 fwrite (p, sizeof (*p), length, of);
10016 while (p < limit) {
10017 if (*p == '\"' || *p =='\'') {
10018 U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
10019 NULL_PTR, NULL_PTR);
10020 fwrite (p, sizeof (*p), p1 - p, of);
10031 /* Print the name of argument number ARGNUM of macro definition DEFN
10033 Recall that DEFN->args.argnames contains all the arg names
10034 concatenated in reverse order with comma-space in between. */
10037 dump_arg_n (defn, argnum, of)
10042 register U_CHAR *p = defn->args.argnames;
10043 while (argnum + 1 < defn->nargs) {
10044 p = (U_CHAR *) index ((char *) p, ' ') + 1;
10048 while (*p && *p != ',') {
10054 /* Initialize syntactic classifications of characters. */
10057 initialize_char_syntax ()
10062 * Set up is_idchar and is_idstart tables. These should be
10063 * faster than saying (is_alpha (c) || c == '_'), etc.
10064 * Set up these things before calling any routines tthat
10067 for (i = 'a'; i <= 'z'; i++) {
10068 is_idchar[i - 'a' + 'A'] = 1;
10070 is_idstart[i - 'a' + 'A'] = 1;
10073 for (i = '0'; i <= '9'; i++)
10075 is_idchar['_'] = 1;
10076 is_idstart['_'] = 1;
10077 is_idchar['$'] = 1;
10078 is_idstart['$'] = 1;
10080 /* horizontal space table */
10081 is_hor_space[' '] = 1;
10082 is_hor_space['\t'] = 1;
10083 is_hor_space['\v'] = 1;
10084 is_hor_space['\f'] = 1;
10085 is_hor_space['\r'] = 1;
10088 is_space['\t'] = 1;
10089 is_space['\v'] = 1;
10090 is_space['\f'] = 1;
10091 is_space['\n'] = 1;
10092 is_space['\r'] = 1;
10094 char_name['\v'] = "vertical tab";
10095 char_name['\f'] = "formfeed";
10096 char_name['\r'] = "carriage return";
10099 /* Initialize the built-in macros. */
10102 initialize_builtins (inp, outp)
10106 install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
10107 install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
10108 install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
10109 install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
10110 install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
10111 install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
10112 #ifndef NO_BUILTIN_SIZE_TYPE
10113 install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
10115 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10116 install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
10118 install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
10119 install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
10121 install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
10123 install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
10125 install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
10126 if (!traditional) {
10127 install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
10128 install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
10131 install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
10132 /* This is supplied using a -D by the compiler driver
10133 so that it is present only when truly compiling with GNU C. */
10134 /* install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1); */
10135 install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
10139 char directive[2048];
10140 U_CHAR *udirective = (U_CHAR *) directive;
10141 register struct directive *dp = &directive_table[0];
10142 struct tm *timebuf = timestamp ();
10144 sprintf (directive, " __BASE_FILE__ \"%s\"\n",
10145 instack[0].nominal_fname);
10146 output_line_directive (inp, outp, 0, same_file);
10147 pass_thru_directive (udirective, &udirective[strlen (directive)],
10150 sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
10151 output_line_directive (inp, outp, 0, same_file);
10152 pass_thru_directive (udirective, &udirective[strlen (directive)],
10155 #ifndef NO_BUILTIN_SIZE_TYPE
10156 sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
10157 output_line_directive (inp, outp, 0, same_file);
10158 pass_thru_directive (udirective, &udirective[strlen (directive)],
10162 #ifndef NO_BUILTIN_PTRDIFF_TYPE
10163 sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
10164 output_line_directive (inp, outp, 0, same_file);
10165 pass_thru_directive (udirective, &udirective[strlen (directive)],
10169 sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
10170 output_line_directive (inp, outp, 0, same_file);
10171 pass_thru_directive (udirective, &udirective[strlen (directive)],
10174 sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
10175 monthnames[timebuf->tm_mon],
10176 timebuf->tm_mday, timebuf->tm_year + 1900);
10177 output_line_directive (inp, outp, 0, same_file);
10178 pass_thru_directive (udirective, &udirective[strlen (directive)],
10181 sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
10182 timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
10183 output_line_directive (inp, outp, 0, same_file);
10184 pass_thru_directive (udirective, &udirective[strlen (directive)],
10189 sprintf (directive, " __STDC__ 1");
10190 output_line_directive (inp, outp, 0, same_file);
10191 pass_thru_directive (udirective, &udirective[strlen (directive)],
10196 sprintf (directive, " __OBJC__ 1");
10197 output_line_directive (inp, outp, 0, same_file);
10198 pass_thru_directive (udirective, &udirective[strlen (directive)],
10205 * process a given definition string, for initialization
10206 * If STR is just an identifier, define it with value 1.
10207 * If STR has anything after the identifier, then it should
10208 * be identifier=definition.
10212 make_definition (str)
10216 struct directive *kt;
10219 p = buf = (U_CHAR *) str;
10220 if (!is_idstart[*p]) {
10221 error ("malformed option `-D %s'", str);
10224 while (is_idchar[*++p])
10227 while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
10230 p = (U_CHAR *) str; /* Error */
10233 buf = (U_CHAR *) alloca (p - buf + 4);
10234 strcpy ((char *)buf, str);
10235 strcat ((char *)buf, " 1");
10236 } else if (*p != '=') {
10237 error ("malformed option `-D %s'", str);
10241 /* Copy the entire option so we can modify it. */
10242 buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
10243 strncpy ((char *) buf, str, p - (U_CHAR *) str);
10244 /* Change the = to a space. */
10245 buf[p - (U_CHAR *) str] = ' ';
10246 /* Scan for any backslash-newline and remove it. */
10248 q = &buf[p - (U_CHAR *) str];
10250 if (*p == '\"' || *p == '\'') {
10251 int unterminated = 0;
10252 U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
10253 NULL_PTR, NULL_PTR, &unterminated);
10258 } else if (*p == '\\' && p[1] == '\n')
10260 /* Change newline chars into newline-markers. */
10261 else if (*p == '\n')
10273 ip = &instack[++indepth];
10274 ip->nominal_fname = ip->fname = "*Initialization*";
10275 ip->nominal_fname_len = strlen (ip->nominal_fname);
10277 ip->buf = ip->bufp = buf;
10278 ip->length = strlen ((char *) buf);
10282 ip->if_stack = if_stack;
10283 ip->system_header_p = 0;
10285 for (kt = directive_table; kt->type != T_DEFINE; kt++)
10288 /* Pass NULL instead of OP, since this is a "predefined" macro. */
10289 do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
10293 /* JF, this does the work for the -U option */
10296 make_undef (str, op)
10301 struct directive *kt;
10303 ip = &instack[++indepth];
10304 ip->nominal_fname = ip->fname = "*undef*";
10305 ip->nominal_fname_len = strlen (ip->nominal_fname);
10307 ip->buf = ip->bufp = (U_CHAR *) str;
10308 ip->length = strlen (str);
10312 ip->if_stack = if_stack;
10313 ip->system_header_p = 0;
10315 for (kt = directive_table; kt->type != T_UNDEF; kt++)
10318 do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
10322 /* Process the string STR as if it appeared as the body of a #assert.
10323 OPTION is the option name for which STR was the argument. */
10326 make_assertion (option, str)
10331 struct directive *kt;
10332 U_CHAR *buf, *p, *q;
10334 /* Copy the entire option so we can modify it. */
10335 buf = (U_CHAR *) alloca (strlen (str) + 1);
10336 strcpy ((char *) buf, str);
10337 /* Scan for any backslash-newline and remove it. */
10340 if (*p == '\\' && p[1] == '\n')
10348 if (!is_idstart[*p]) {
10349 error ("malformed option `%s %s'", option, str);
10352 while (is_idchar[*++p])
10354 SKIP_WHITE_SPACE (p);
10355 if (! (*p == 0 || *p == '(')) {
10356 error ("malformed option `%s %s'", option, str);
10360 ip = &instack[++indepth];
10361 ip->nominal_fname = ip->fname = "*Initialization*";
10362 ip->nominal_fname_len = strlen (ip->nominal_fname);
10364 ip->buf = ip->bufp = buf;
10365 ip->length = strlen ((char *) buf);
10369 ip->if_stack = if_stack;
10370 ip->system_header_p = 0;
10372 for (kt = directive_table; kt->type != T_ASSERT; kt++)
10375 /* Pass NULL as output ptr to do_define since we KNOW it never does
10377 do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
10381 #ifndef DIR_SEPARATOR
10382 #define DIR_SEPARATOR '/'
10385 /* The previous include prefix, if any, is PREV_FILE_NAME.
10386 Translate any pathnames with COMPONENT.
10387 Allocate a new include prefix whose name is the
10388 simplified concatenation of PREFIX and NAME,
10389 with a trailing / added if needed.
10390 But return 0 if the include prefix should be ignored,
10391 e.g. because it is a duplicate of PREV_FILE_NAME. */
10393 static struct file_name_list *
10394 new_include_prefix (prev_file_name, component, prefix, name)
10395 struct file_name_list *prev_file_name;
10401 fatal ("Directory name missing after command line option");
10404 /* Ignore the empty string. */
10407 prefix = update_path (prefix, component);
10408 name = update_path (name, component);
10411 struct file_name_list *dir
10412 = ((struct file_name_list *)
10413 xmalloc (sizeof (struct file_name_list)
10414 + strlen (prefix) + strlen (name) + 2));
10416 strcpy (dir->fname, prefix);
10417 strcat (dir->fname, name);
10418 len = simplify_filename (dir->fname);
10420 /* Convert directory name to a prefix. */
10421 if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
10422 if (len == 1 && dir->fname[len - 1] == '.')
10426 /* must be '/', hack_vms_include_specification triggers on it. */
10427 dir->fname[len++] = '/';
10429 dir->fname[len++] = DIR_SEPARATOR;
10431 dir->fname[len] = 0;
10434 /* Ignore a directory whose name matches the previous one. */
10435 if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
10436 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10437 if (!first_bracket_include)
10438 first_bracket_include = prev_file_name;
10444 /* VMS can't stat dir prefixes, so skip these optimizations in VMS. */
10446 /* Add a trailing "." if there is a filename. This increases the number
10447 of systems that can stat directories. We remove it below. */
10450 dir->fname[len] = '.';
10451 dir->fname[len + 1] = 0;
10454 /* Ignore a nonexistent directory. */
10455 if (stat (len ? dir->fname : ".", &dir->st) != 0) {
10456 if (errno != ENOENT && errno != ENOTDIR)
10457 error_from_errno (dir->fname);
10463 dir->fname[len] = 0;
10465 /* Ignore a directory whose identity matches the previous one. */
10467 && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
10468 && prev_file_name->st.st_dev == dir->st.st_dev) {
10469 /* But treat `-Idir -I- -Idir' as `-I- -Idir'. */
10470 if (!first_bracket_include)
10471 first_bracket_include = prev_file_name;
10478 dir->c_system_include_path = 0;
10479 dir->got_name_map = 0;
10485 /* Append a chain of `struct file_name_list's
10486 to the end of the main include chain.
10487 FIRST is the beginning of the chain to append, and LAST is the end. */
10490 append_include_chain (first, last)
10491 struct file_name_list *first, *last;
10493 struct file_name_list *dir;
10495 if (!first || !last)
10501 last_include->next = first;
10503 if (first_bracket_include == 0)
10504 first_bracket_include = first;
10506 for (dir = first; ; dir = dir->next) {
10507 int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10508 if (len > max_include_len)
10509 max_include_len = len;
10515 last_include = last;
10518 /* Place into DST a representation of the file named SRC that is suitable
10519 for `make'. Do not null-terminate DST. Return its length. */
10521 quote_string_for_make (dst, src)
10536 /* GNU make uses a weird quoting scheme for white space.
10537 A space or tab preceded by 2N+1 backslashes represents
10538 N backslashes followed by space; a space or tab
10539 preceded by 2N backslashes represents N backslashes at
10540 the end of a file name; and backslashes in other
10541 contexts should not be doubled. */
10543 for (q = p - 1; src < q && q[-1] == '\\'; q--)
10555 goto ordinary_char;
10561 /* Fall through. This can mishandle things like "$(" but
10562 there's no easy fix. */
10565 /* This can mishandle characters in the string "\0\n%*?[\\~";
10566 exactly which chars are mishandled depends on the `make' version.
10567 We know of no portable solution for this;
10568 even GNU make 3.76.1 doesn't solve the problem entirely.
10569 (Also, '\0' is mishandled due to our calling conventions.) */
10579 /* Add output to `deps_buffer' for the -M switch.
10580 STRING points to the text to be output.
10581 SPACER is ':' for targets, ' ' for dependencies. */
10584 deps_output (string, spacer)
10588 int size = quote_string_for_make ((char *) 0, string);
10593 #ifndef MAX_OUTPUT_COLUMNS
10594 #define MAX_OUTPUT_COLUMNS 72
10596 if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10597 && 1 < deps_column) {
10598 bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10605 if (deps_size + 2 * size + 8 > deps_allocated_size) {
10606 deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10607 deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10609 if (spacer == ' ') {
10610 deps_buffer[deps_size++] = ' ';
10613 quote_string_for_make (&deps_buffer[deps_size], string);
10615 deps_column += size;
10616 if (spacer == ':') {
10617 deps_buffer[deps_size++] = ':';
10620 deps_buffer[deps_size] = 0;
10624 fatal VPROTO ((char * msg, ...))
10626 #ifndef ANSI_PROTOTYPES
10631 fprintf (stderr, "%s: ", progname);
10632 VA_START (args, msg);
10634 #ifndef ANSI_PROTOTYPES
10635 msg = va_arg (args, char *);
10638 vfprintf (stderr, msg, args);
10640 fprintf (stderr, "\n");
10641 exit (FATAL_EXIT_CODE);
10644 /* More 'friendly' abort that prints the line and file.
10645 config.h can #define abort fancy_abort if you like that sort of thing. */
10650 fatal ("Internal gcc abort.");
10654 perror_with_name (name)
10657 fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10662 pfatal_with_name (name)
10665 perror_with_name (name);
10669 exit (FATAL_EXIT_CODE);
10673 /* Handler for SIGPIPE. */
10676 pipe_closed (signo)
10677 /* If this is missing, some compilers complain. */
10678 int signo ATTRIBUTE_UNUSED;
10680 fatal ("output pipe has been closed");
10686 fatal ("Memory exhausted.");
10694 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10701 xrealloc (old, size)
10705 register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10712 xcalloc (number, size)
10713 size_t number, size;
10715 register size_t total = number * size;
10716 register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10719 bzero (ptr, total);
10727 size_t size = strlen (input);
10728 char *output = xmalloc (size + 1);
10729 strcpy (output, input);
10735 /* Under VMS we need to fix up the "include" specification filename.
10737 Rules for possible conversions
10739 fullname tried paths
10742 ./dir/name [.dir]name
10744 /name [000000]name, name
10745 dir/name dir:[000000]name, dir:name, dir/name
10746 dir1/dir2/name dir1:[dir2]name, dir1:[000000.dir2]name
10747 path:/name path:[000000]name, path:name
10748 path:/dir/name path:[000000.dir]name, path:[dir]name
10749 path:dir/name path:[dir]name
10750 [path]:[dir]name [path.dir]name
10751 path/[dir]name [path.dir]name
10753 The path:/name input is constructed when expanding <> includes.
10755 return 1 if name was changed, 0 else. */
10758 hack_vms_include_specification (fullname, vaxc_include)
10762 register char *basename, *unixname, *local_ptr, *first_slash;
10763 int f, check_filename_before_returning, must_revert;
10766 check_filename_before_returning = 0;
10768 /* See if we can find a 1st slash. If not, there's no path information. */
10769 first_slash = index (fullname, '/');
10770 if (first_slash == 0)
10771 return 0; /* Nothing to do!!! */
10773 /* construct device spec if none given. */
10775 if (index (fullname, ':') == 0)
10778 /* If fullname has a slash, take it as device spec. */
10780 if (first_slash == fullname)
10782 first_slash = index (fullname+1, '/'); /* 2nd slash ? */
10784 *first_slash = ':'; /* make device spec */
10785 for (basename = fullname; *basename != 0; basename++)
10786 *basename = *(basename+1); /* remove leading slash */
10788 else if ((first_slash[-1] != '.') /* keep ':/', './' */
10789 && (first_slash[-1] != ':')
10790 && (first_slash[-1] != ']')) /* or a vms path */
10792 *first_slash = ':';
10794 else if ((first_slash[1] == '[') /* skip './' in './[dir' */
10795 && (first_slash[-1] == '.'))
10799 /* Get part after first ':' (basename[-1] == ':')
10800 or last '/' (basename[-1] == '/'). */
10802 basename = base_name (fullname);
10805 * Check if we have a vax-c style '#include filename'
10806 * and add the missing .h
10809 if (vaxc_include && !index (basename,'.'))
10810 strcat (basename, ".h");
10812 local_ptr = Local; /* initialize */
10814 /* We are trying to do a number of things here. First of all, we are
10815 trying to hammer the filenames into a standard format, such that later
10816 processing can handle them.
10818 If the file name contains something like [dir.], then it recognizes this
10819 as a root, and strips the ".]". Later processing will add whatever is
10820 needed to get things working properly.
10822 If no device is specified, then the first directory name is taken to be
10823 a device name (or a rooted logical). */
10825 /* Point to the UNIX filename part (which needs to be fixed!)
10826 but skip vms path information.
10827 [basename != fullname since first_slash != 0]. */
10829 if ((basename[-1] == ':') /* vms path spec. */
10830 || (basename[-1] == ']')
10831 || (basename[-1] == '>'))
10832 unixname = basename;
10834 unixname = fullname;
10836 if (*unixname == '/')
10839 /* If the directory spec is not rooted, we can just copy
10840 the UNIX filename part and we are done. */
10842 if (((basename - fullname) > 1)
10843 && ( (basename[-1] == ']')
10844 || (basename[-1] == '>')))
10846 if (basename[-2] != '.')
10849 /* The VMS part ends in a `]', and the preceding character is not a `.'.
10850 -> PATH]:/name (basename = '/name', unixname = 'name')
10851 We strip the `]', and then splice the two parts of the name in the
10852 usual way. Given the default locations for include files in cccp.c,
10853 we will only use this code if the user specifies alternate locations
10854 with the /include (-I) switch on the command line. */
10856 basename -= 1; /* Strip "]" */
10857 unixname--; /* backspace */
10862 /* The VMS part has a ".]" at the end, and this will not do. Later
10863 processing will add a second directory spec, and this would be a syntax
10864 error. Thus we strip the ".]", and thus merge the directory specs.
10865 We also backspace unixname, so that it points to a '/'. This inhibits the
10866 generation of the 000000 root directory spec (which does not belong here
10869 basename -= 2; /* Strip ".]" */
10870 unixname--; /* backspace */
10878 /* We drop in here if there is no VMS style directory specification yet.
10879 If there is no device specification either, we make the first dir a
10880 device and try that. If we do not do this, then we will be essentially
10881 searching the users default directory (as if they did a #include "asdf.h").
10883 Then all we need to do is to push a '[' into the output string. Later
10884 processing will fill this in, and close the bracket. */
10886 if ((unixname != fullname) /* vms path spec found. */
10887 && (basename[-1] != ':'))
10888 *local_ptr++ = ':'; /* dev not in spec. take first dir */
10890 *local_ptr++ = '['; /* Open the directory specification */
10893 if (unixname == fullname) /* no vms dir spec. */
10896 if ((first_slash != 0) /* unix dir spec. */
10897 && (*unixname != '/') /* not beginning with '/' */
10898 && (*unixname != '.')) /* or './' or '../' */
10899 *local_ptr++ = '.'; /* dir is local ! */
10902 /* at this point we assume that we have the device spec, and (at least
10903 the opening "[" for a directory specification. We may have directories
10906 If there are no other slashes then the filename will be
10907 in the "root" directory. Otherwise, we need to add
10908 directory specifications. */
10910 if (index (unixname, '/') == 0)
10912 /* if no directories specified yet and none are following. */
10913 if (local_ptr[-1] == '[')
10915 /* Just add "000000]" as the directory string */
10916 strcpy (local_ptr, "000000]");
10917 local_ptr += strlen (local_ptr);
10918 check_filename_before_returning = 1; /* we might need to fool with this later */
10924 /* As long as there are still subdirectories to add, do them. */
10925 while (index (unixname, '/') != 0)
10927 /* If this token is "." we can ignore it
10928 if it's not at the beginning of a path. */
10929 if ((unixname[0] == '.') && (unixname[1] == '/'))
10931 /* remove it at beginning of path. */
10932 if ( ((unixname == fullname) /* no device spec */
10933 && (fullname+2 != basename)) /* starts with ./ */
10935 || ((basename[-1] == ':') /* device spec */
10936 && (unixname-1 == basename))) /* and ./ afterwards */
10937 *local_ptr++ = '.'; /* make '[.' start of path. */
10942 /* Add a subdirectory spec. Do not duplicate "." */
10943 if ( local_ptr[-1] != '.'
10944 && local_ptr[-1] != '['
10945 && local_ptr[-1] != '<')
10946 *local_ptr++ = '.';
10948 /* If this is ".." then the spec becomes "-" */
10949 if ( (unixname[0] == '.')
10950 && (unixname[1] == '.')
10951 && (unixname[2] == '/'))
10953 /* Add "-" and skip the ".." */
10954 if ((local_ptr[-1] == '.')
10955 && (local_ptr[-2] == '['))
10956 local_ptr--; /* prevent [.- */
10957 *local_ptr++ = '-';
10962 /* Copy the subdirectory */
10963 while (*unixname != '/')
10964 *local_ptr++= *unixname++;
10966 unixname++; /* Skip the "/" */
10969 /* Close the directory specification */
10970 if (local_ptr[-1] == '.') /* no trailing periods */
10973 if (local_ptr[-1] == '[') /* no dir needed */
10976 *local_ptr++ = ']';
10979 /* Now add the filename. */
10982 *local_ptr++ = *unixname++;
10985 /* Now append it to the original VMS spec. */
10987 strcpy ((must_revert==1)?fullname:basename, Local);
10989 /* If we put a [000000] in the filename, try to open it first. If this fails,
10990 remove the [000000], and return that name. This provides flexibility
10991 to the user in that they can use both rooted and non-rooted logical names
10992 to point to the location of the file. */
10994 if (check_filename_before_returning)
10996 f = open (fullname, O_RDONLY, 0666);
10999 /* The file name is OK as it is, so return it as is. */
11004 /* The filename did not work. Try to remove the [000000] from the name,
11007 basename = index (fullname, '[');
11008 local_ptr = index (fullname, ']') + 1;
11009 strcpy (basename, local_ptr); /* this gets rid of it */
11019 /* The following wrapper functions supply additional arguments to the VMS
11020 I/O routines to optimize performance with file handling. The arguments
11022 "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
11023 "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
11024 "fop=tef"- Truncate unused portions of file when closing file.
11025 "shr=nil"- Disallow file sharing while file is open. */
11028 VMS_freopen (fname, type, oldfile)
11033 #undef freopen /* Get back the real freopen routine. */
11034 if (strcmp (type, "w") == 0)
11035 return freopen (fname, type, oldfile,
11036 "mbc=16", "deq=64", "fop=tef", "shr=nil");
11037 return freopen (fname, type, oldfile, "mbc=16");
11041 VMS_fopen (fname, type)
11045 #undef fopen /* Get back the real fopen routine. */
11046 /* The gcc-vms-1.42 distribution's header files prototype fopen with two
11047 fixed arguments, which matches ANSI's specification but not VAXCRTL's
11048 pre-ANSI implementation. This hack circumvents the mismatch problem. */
11049 FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
11052 return (*vmslib_fopen) (fname, type, "mbc=32",
11053 "deq=64", "fop=tef", "shr=nil");
11055 return (*vmslib_fopen) (fname, type, "mbc=32");
11059 VMS_open (fname, flags, prot)
11064 #undef open /* Get back the real open routine. */
11065 return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
11068 /* more VMS hackery */
11072 extern unsigned long SYS$PARSE(), SYS$SEARCH();
11074 /* Work around another library bug. If a file is located via a searchlist,
11075 and if the device it's on is not the same device as the one specified
11076 in the first element of that searchlist, then both stat() and fstat()
11077 will fail to return info about it. `errno' will be set to EVMSERR, and
11078 `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
11079 We can get around this by fully parsing the filename and then passing
11080 that absolute name to stat().
11082 Without this fix, we can end up failing to find header files, which is
11083 bad enough, but then compounding the problem by reporting the reason for
11084 failure as "normal successful completion." */
11086 #undef fstat /* Get back to the library version. */
11089 VMS_fstat (fd, statbuf)
11091 struct stat *statbuf;
11093 int result = fstat (fd, statbuf);
11098 char nambuf[NAM$C_MAXRSS+1];
11100 if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
11101 result = VMS_stat (nambuf, statbuf);
11102 /* No fclose(fp) here; that would close(fd) as well. */
11109 VMS_stat (name, statbuf)
11111 struct stat *statbuf;
11113 int result = stat (name, statbuf);
11119 char exp_nam[NAM$C_MAXRSS+1], /* expanded name buffer for SYS$PARSE */
11120 res_nam[NAM$C_MAXRSS+1]; /* resultant name buffer for SYS$SEARCH */
11123 fab.fab$l_fna = (char *) name;
11124 fab.fab$b_fns = (unsigned char) strlen (name);
11125 fab.fab$l_nam = (void *) &nam;
11127 nam.nam$l_esa = exp_nam, nam.nam$b_ess = sizeof exp_nam - 1;
11128 nam.nam$l_rsa = res_nam, nam.nam$b_rss = sizeof res_nam - 1;
11129 nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
11130 if (SYS$PARSE (&fab) & 1)
11132 if (SYS$SEARCH (&fab) & 1)
11134 res_nam[nam.nam$b_rsl] = '\0';
11135 result = stat (res_nam, statbuf);
11137 /* Clean up searchlist context cached by the system. */
11138 nam.nam$b_nop = NAM$M_SYNCHK;
11139 fab.fab$l_fna = 0, fab.fab$b_fns = 0;
11140 (void) SYS$PARSE (&fab);