Be more careful when including <time.h> and <sys/file.h> in system.h.
[platform/upstream/gcc.git] / gcc / cccp.c
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
5
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
9 later version.
10
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.
15
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. */
20
21 #include "config.h"
22 #if defined (__STDC__) && defined (HAVE_VPRINTF)
23 # include <stdarg.h>
24 # define PRINTF_ALIST(msg) char *msg, ...
25 # define PRINTF_DCL(msg)
26 # define PRINTF_PROTO(ARGS, m, n) PROTO (ARGS) __attribute__ ((format (__printf__, m, n)))
27 #else
28 # include <varargs.h>
29 # define PRINTF_ALIST(msg) msg, va_alist
30 # define PRINTF_DCL(msg) char *msg; va_dcl
31 # define PRINTF_PROTO(ARGS, m, n) () __attribute__ ((format (__printf__, m, n)))
32 # define vfprintf(file, msg, args) \
33     { \
34       char *a0 = va_arg(args, char *); \
35       char *a1 = va_arg(args, char *); \
36       char *a2 = va_arg(args, char *); \
37       char *a3 = va_arg(args, char *); \
38       fprintf (file, msg, a0, a1, a2, a3); \
39     }
40 #endif
41
42 #define PRINTF_PROTO_1(ARGS) PRINTF_PROTO(ARGS, 1, 2)
43 #define PRINTF_PROTO_2(ARGS) PRINTF_PROTO(ARGS, 2, 3)
44 #define PRINTF_PROTO_3(ARGS) PRINTF_PROTO(ARGS, 3, 4)
45 #define PRINTF_PROTO_4(ARGS) PRINTF_PROTO(ARGS, 4, 5)
46
47 #include "system.h"
48 #include <sys/stat.h>
49 #include <signal.h>
50
51 #ifdef HAVE_SYS_RESOURCE_H
52 # include <sys/resource.h>
53 #endif
54
55 typedef unsigned char U_CHAR;
56
57 #include "gansidecl.h"
58 #include "pcp.h"
59
60 #ifndef GET_ENVIRONMENT
61 #define GET_ENVIRONMENT(ENV_VALUE,ENV_NAME) ENV_VALUE = getenv (ENV_NAME)
62 #endif
63
64 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
65 # define __attribute__(x)
66 #endif
67
68 #ifndef STANDARD_INCLUDE_DIR
69 # define STANDARD_INCLUDE_DIR "/usr/include"
70 #endif
71
72 /* By default, colon separates directories in a path.  */
73 #ifndef PATH_SEPARATOR
74 # define PATH_SEPARATOR ':'
75 #endif
76
77 /* By default, the suffix for object files is ".o".  */
78 #ifdef OBJECT_SUFFIX
79 # define HAVE_OBJECT_SUFFIX
80 #else
81 # define OBJECT_SUFFIX ".o"
82 #endif
83
84 /* VMS-specific definitions */
85 #ifdef VMS
86 #include <descrip.h>
87 #include <ssdef.h>
88 #include <syidef.h>
89 #define open(fname,mode,prot)   VMS_open (fname,mode,prot)
90 #define fopen(fname,mode)       VMS_fopen (fname,mode)
91 #define freopen(fname,mode,ofile) VMS_freopen (fname,mode,ofile)
92 #define fstat(fd,stbuf)         VMS_fstat (fd,stbuf)
93 static int VMS_fstat (), VMS_stat ();
94 static int VMS_open ();
95 static FILE *VMS_fopen ();
96 static FILE *VMS_freopen ();
97 static void hack_vms_include_specification ();
98 #define INO_T_EQ(a, b) (!bcmp((char *) &(a), (char *) &(b), sizeof (a)))
99 #define INO_T_HASH(a) 0
100 #define INCLUDE_LEN_FUDGE 12    /* leave room for VMS syntax conversion */
101 #endif /* VMS */
102
103 /* Windows does not natively support inodes, and neither does MSDOS.  */
104 #if (defined (_WIN32) && ! defined (CYGWIN32)) || defined (__MSDOS__)
105 #define INO_T_EQ(a, b) 0
106 #endif
107
108 #undef MIN
109 #undef MAX
110 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
111 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
112
113 /* Find the largest host integer type and set its size and type.
114    Watch out: on some crazy hosts `long' is shorter than `int'.  */
115
116 #ifndef HOST_WIDE_INT
117 # if HAVE_INTTYPES_H
118 #  include <inttypes.h>
119 #  define HOST_WIDE_INT intmax_t
120 # else
121 #  if (HOST_BITS_PER_LONG <= HOST_BITS_PER_INT && HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_INT)
122 #   define HOST_WIDE_INT int
123 #  else
124 #  if (HOST_BITS_PER_LONGLONG <= HOST_BITS_PER_LONG || ! (defined LONG_LONG_MAX || defined LLONG_MAX))
125 #   define HOST_WIDE_INT long
126 #  else
127 #   define HOST_WIDE_INT long long
128 #  endif
129 #  endif
130 # endif
131 #endif
132
133 #ifndef S_ISREG
134 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
135 #endif
136
137 #ifndef S_ISDIR
138 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
139 #endif
140
141 #ifndef INO_T_EQ
142 #define INO_T_EQ(a, b) ((a) == (b))
143 #endif
144
145 #ifndef INO_T_HASH
146 #define INO_T_HASH(a) (a)
147 #endif
148
149 #ifndef INCLUDE_LEN_FUDGE
150 #define INCLUDE_LEN_FUDGE 0
151 #endif
152
153 /* External declarations.  */
154
155 extern char *version_string;
156 extern char *update_path PROTO((char *, char *));
157 #ifndef VMS
158 #ifndef HAVE_STRERROR
159 extern int sys_nerr;
160 extern char *sys_errlist[];
161 #else   /* HAVE_STRERROR */
162 char *strerror ();
163 #endif
164 #else   /* VMS */
165 char *strerror (int,...);
166 #endif
167 HOST_WIDE_INT parse_escape PROTO((char **, HOST_WIDE_INT));
168 HOST_WIDE_INT parse_c_expression PROTO((char *, int));
169 \f
170 /* Name under which this program was invoked.  */
171
172 static char *progname;
173
174 /* Nonzero means use extra default include directories for C++.  */
175
176 static int cplusplus;
177
178 /* Nonzero means handle cplusplus style comments */
179
180 static int cplusplus_comments;
181
182 /* Nonzero means handle #import, for objective C.  */
183
184 static int objc;
185
186 /* Nonzero means this is an assembly file, and allow
187    unknown directives, which could be comments.  */
188
189 static int lang_asm;
190
191 /* Current maximum length of directory names in the search path
192    for include files.  (Altered as we get more of them.)  */
193
194 static int max_include_len;
195
196 /* Nonzero means turn NOTREACHED into #pragma NOTREACHED etc */
197
198 static int for_lint = 0;
199
200 /* Nonzero means copy comments into the output file.  */
201
202 static int put_out_comments = 0;
203
204 /* Nonzero means don't process the ANSI trigraph sequences.  */
205
206 static int no_trigraphs = 0;
207
208 /* Nonzero means print the names of included files rather than
209    the preprocessed output.  1 means just the #include "...",
210    2 means #include <...> as well.  */
211
212 static int print_deps = 0;
213
214 /* Nonzero if missing .h files in -M output are assumed to be generated
215    files and not errors.  */
216
217 static int print_deps_missing_files = 0;
218
219 /* Nonzero means print names of header files (-H).  */
220
221 static int print_include_names = 0;
222
223 /* Nonzero means don't output line number information.  */
224
225 static int no_line_directives;
226
227 /* Nonzero means output the text in failing conditionals,
228    inside #failed ... #endfailed.  */
229
230 static int output_conditionals;
231
232 /* dump_only means inhibit output of the preprocessed text
233              and instead output the definitions of all user-defined
234              macros in a form suitable for use as input to cccp.
235    dump_names means pass #define and the macro name through to output.
236    dump_definitions means pass the whole definition (plus #define) through
237 */
238
239 static enum {dump_none, dump_only, dump_names, dump_definitions}
240      dump_macros = dump_none;
241
242 /* Nonzero means pass all #define and #undef directives which we actually
243    process through to the output stream.  This feature is used primarily
244    to allow cc1 to record the #defines and #undefs for the sake of
245    debuggers which understand about preprocessor macros, but it may
246    also be useful with -E to figure out how symbols are defined, and
247    where they are defined.  */
248 static int debug_output = 0;
249
250 /* Nonzero means pass #include lines through to the output,
251    even if they are ifdefed out.  */
252 static int dump_includes;
253
254 /* Nonzero indicates special processing used by the pcp program.  The
255    special effects of this mode are: 
256      
257      Inhibit all macro expansion, except those inside #if directives.
258
259      Process #define directives normally, and output their contents 
260      to the output file.
261
262      Output preconditions to pcp_outfile indicating all the relevant
263      preconditions for use of this file in a later cpp run.
264 */
265 static FILE *pcp_outfile;
266
267 /* Nonzero means we are inside an IF during a -pcp run.  In this mode
268    macro expansion is done, and preconditions are output for all macro
269    uses requiring them.  */
270 static int pcp_inside_if;
271
272 /* Nonzero means never to include precompiled files.
273    This is 1 since there's no way now to make precompiled files,
274    so it's not worth testing for them.  */
275 static int no_precomp = 1;
276
277 /* Nonzero means give all the error messages the ANSI standard requires.  */
278
279 int pedantic;
280
281 /* Nonzero means try to make failure to fit ANSI C an error.  */
282
283 static int pedantic_errors;
284
285 /* Nonzero means don't print warning messages.  -w.  */
286
287 static int inhibit_warnings = 0;
288
289 /* Nonzero means warn if slash-star appears in a slash-star comment,
290    or if newline-backslash appears in a slash-slash comment.  */
291
292 static int warn_comments;
293
294 /* Nonzero means warn if a macro argument is (or would be)
295    stringified with -traditional.  */
296
297 static int warn_stringify;
298
299 /* Nonzero means warn if there are any trigraphs.  */
300
301 static int warn_trigraphs;
302
303 /* Nonzero means warn if undefined identifiers are evaluated in an #if.  */
304
305 static int warn_undef;
306
307 /* Nonzero means warn if #import is used.  */
308
309 static int warn_import = 1;
310
311 /* Nonzero means turn warnings into errors.  */
312
313 static int warnings_are_errors;
314
315 /* Nonzero means try to imitate old fashioned non-ANSI preprocessor.  */
316
317 int traditional;
318
319 /* Nonzero for the 1989 C Standard, including corrigenda and amendments.  */
320
321 int c89;
322
323 /* Nonzero causes output not to be done,
324    but directives such as #define that have side effects
325    are still obeyed.  */
326
327 static int no_output;
328
329 /* Nonzero means we should look for header.gcc files that remap file names.  */
330 static int remap;
331
332 /* Nonzero means this file was included with a -imacros or -include
333    command line and should not be recorded as an include file.  */
334
335 static int no_record_file;
336
337 /* Nonzero means that we have finished processing the command line options.
338    This flag is used to decide whether or not to issue certain errors
339    and/or warnings.  */
340
341 static int done_initializing = 0;
342
343 /* Line where a newline was first seen in a string constant.  */
344
345 static int multiline_string_line = 0;
346 \f
347 /* I/O buffer structure.
348    The `fname' field is nonzero for source files and #include files
349    and for the dummy text used for -D and -U.
350    It is zero for rescanning results of macro expansion
351    and for expanding macro arguments.  */
352 #define INPUT_STACK_MAX 400
353 static struct file_buf {
354   char *fname;
355   /* Filename specified with #line directive.  */
356   char *nominal_fname;
357   /* The length of nominal_fname, which may contain embedded NULs.  */
358   size_t nominal_fname_len;
359   /* Include file description.  */
360   struct include_file *inc;
361   /* Record where in the search path this file was found.
362      For #include_next.  */
363   struct file_name_list *dir;
364   int lineno;
365   int length;
366   U_CHAR *buf;
367   U_CHAR *bufp;
368   /* Macro that this level is the expansion of.
369      Included so that we can reenable the macro
370      at the end of this level.  */
371   struct hashnode *macro;
372   /* Value of if_stack at start of this file.
373      Used to prohibit unmatched #endif (etc) in an include file.  */
374   struct if_stack *if_stack;
375   /* Object to be freed at end of input at this level.  */
376   U_CHAR *free_ptr;
377   /* True if this is a system header file; see is_system_include.  */
378   char system_header_p;
379 } instack[INPUT_STACK_MAX];
380
381 static int last_error_tick;        /* Incremented each time we print it.  */
382 static int input_file_stack_tick;  /* Incremented when the status changes.  */
383
384 /* Current nesting level of input sources.
385    `instack[indepth]' is the level currently being read.  */
386 static int indepth = -1;
387 #define CHECK_DEPTH(code) \
388   if (indepth >= (INPUT_STACK_MAX - 1))                                 \
389     {                                                                   \
390       error_with_line (line_for_error (instack[indepth].lineno),        \
391                        "macro or `#include' recursion too deep");       \
392       code;                                                             \
393     }
394
395 /* Current depth in #include directives that use <...>.  */
396 static int system_include_depth = 0;
397
398 typedef struct file_buf FILE_BUF;
399
400 /* The output buffer.  Its LENGTH field is the amount of room allocated
401    for the buffer, not the number of chars actually present.  To get
402    that, subtract outbuf.buf from outbuf.bufp.  */
403
404 #define OUTBUF_SIZE 10  /* initial size of output buffer */
405 static FILE_BUF outbuf;
406
407 /* Grow output buffer OBUF points at
408    so it can hold at least NEEDED more chars.  */
409
410 #define check_expand(OBUF, NEEDED)  \
411   (((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED))   \
412    ? grow_outbuf ((OBUF), (NEEDED)) : 0)
413
414 struct file_name_list
415   {
416     struct file_name_list *next;
417     /* If the following is 1, it is a C-language system include
418        directory.  */
419     int c_system_include_path;
420     /* Mapping of file names for this directory.  */
421     struct file_name_map *name_map;
422     /* Non-zero if name_map is valid.  */
423     int got_name_map;
424     /* The include directory status.  */
425     struct stat st;
426     /* The include prefix: "" denotes the working directory,
427        otherwise fname must end in '/'.
428        The actual size is dynamically allocated.  */
429     char fname[1];
430   };
431
432 /* #include "file" looks in source file dir, then stack.  */
433 /* #include <file> just looks in the stack.  */
434 /* -I directories are added to the end, then the defaults are added.  */
435 /* The */
436 static struct default_include {
437   char *fname;                  /* The name of the directory.  */
438   char *component;              /* The component containing the directory */
439   int cplusplus;                /* Only look here if we're compiling C++.  */
440   int cxx_aware;                /* Includes in this directory don't need to
441                                    be wrapped in extern "C" when compiling
442                                    C++.  */
443 } include_defaults_array[]
444 #ifdef INCLUDE_DEFAULTS
445   = INCLUDE_DEFAULTS;
446 #else
447   = {
448     /* Pick up GNU C++ specific include files.  */
449     { GPLUSPLUS_INCLUDE_DIR, "G++", 1, 1 },
450     { OLD_GPLUSPLUS_INCLUDE_DIR, 0, 1, 1 },
451 #ifdef CROSS_COMPILE
452     /* This is the dir for fixincludes.  Put it just before
453        the files that we fix.  */
454     { GCC_INCLUDE_DIR, "GCC", 0, 0 },
455     /* For cross-compilation, this dir name is generated
456        automatically in Makefile.in.  */
457     { CROSS_INCLUDE_DIR, "GCC", 0, 0 },
458 #ifdef TOOL_INCLUDE_DIR
459     /* This is another place that the target system's headers might be.  */
460     { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
461 #endif
462 #else /* not CROSS_COMPILE */
463 #ifdef LOCAL_INCLUDE_DIR
464     /* This should be /usr/local/include and should come before
465        the fixincludes-fixed header files.  */
466     { LOCAL_INCLUDE_DIR, 0, 0, 1 },
467 #endif
468 #ifdef TOOL_INCLUDE_DIR
469     /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
470        Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h.  */
471     { TOOL_INCLUDE_DIR, "BINUTILS", 0, 0 },
472 #endif
473     /* This is the dir for fixincludes.  Put it just before
474        the files that we fix.  */
475     { GCC_INCLUDE_DIR, "GCC", 0, 0 },
476     /* Some systems have an extra dir of include files.  */
477 #ifdef SYSTEM_INCLUDE_DIR
478     { SYSTEM_INCLUDE_DIR, 0, 0, 0 },
479 #endif
480 #ifndef STANDARD_INCLUDE_COMPONENT
481 #define STANDARD_INCLUDE_COMPONENT 0
482 #endif
483     { STANDARD_INCLUDE_DIR, STANDARD_INCLUDE_COMPONENT, 0, 0 },
484 #endif /* not CROSS_COMPILE */
485     { 0, 0, 0, 0 }
486     };
487 #endif /* no INCLUDE_DEFAULTS */
488
489 /* The code looks at the defaults through this pointer, rather than through
490    the constant structure above.  This pointer gets changed if an environment
491    variable specifies other defaults.  */
492 static struct default_include *include_defaults = include_defaults_array;
493
494 static struct file_name_list *include = 0;      /* First dir to search */
495         /* First dir to search for <file> */
496 /* This is the first element to use for #include <...>.
497    If it is 0, use the entire chain for such includes.  */
498 static struct file_name_list *first_bracket_include = 0;
499 /* This is the first element in the chain that corresponds to
500    a directory of system header files.  */
501 static struct file_name_list *first_system_include = 0;
502 static struct file_name_list *last_include = 0; /* Last in chain */
503
504 /* Chain of include directories to put at the end of the other chain.  */
505 static struct file_name_list *after_include = 0;
506 static struct file_name_list *last_after_include = 0;   /* Last in chain */
507
508 /* Chain to put at the start of the system include files.  */
509 static struct file_name_list *before_system = 0;
510 static struct file_name_list *last_before_system = 0;   /* Last in chain */
511
512 /* Directory prefix that should replace `/usr' in the standard
513    include file directories.  */
514 static char *include_prefix;
515
516 /* Maintain and search list of included files.  */
517
518 struct include_file {
519   struct include_file *next; /* for include_hashtab */
520   struct include_file *next_ino; /* for include_ino_hashtab */
521   char *fname;
522   /* If the following is the empty string, it means #pragma once
523      was seen in this include file, or #import was applied to the file.
524      Otherwise, if it is nonzero, it is a macro name.
525      Don't include the file again if that macro is defined.  */
526   U_CHAR *control_macro;
527   /* Nonzero if the dependency on this include file has been output.  */
528   int deps_output;
529   struct stat st;
530 };
531
532 /* Hash tables of files already included with #include or #import.
533    include_hashtab is by full name; include_ino_hashtab is by inode number.  */
534
535 #define INCLUDE_HASHSIZE 61
536 static struct include_file *include_hashtab[INCLUDE_HASHSIZE];
537 static struct include_file *include_ino_hashtab[INCLUDE_HASHSIZE];
538
539 /* Global list of strings read in from precompiled files.  This list
540    is kept in the order the strings are read in, with new strings being
541    added at the end through stringlist_tailp.  We use this list to output
542    the strings at the end of the run. 
543 */
544 static STRINGDEF *stringlist;
545 static STRINGDEF **stringlist_tailp = &stringlist;
546
547
548 /* Structure returned by create_definition */
549 typedef struct macrodef MACRODEF;
550 struct macrodef
551 {
552   struct definition *defn;
553   U_CHAR *symnam;
554   int symlen;
555 };
556 \f
557 enum sharp_token_type {
558   NO_SHARP_TOKEN = 0,           /* token not present */
559
560   SHARP_TOKEN = '#',            /* token spelled with # only */
561   WHITE_SHARP_TOKEN,            /* token spelled with # and white space */
562
563   PERCENT_COLON_TOKEN = '%',    /* token spelled with %: only */
564   WHITE_PERCENT_COLON_TOKEN     /* token spelled with %: and white space */
565 };
566
567 /* Structure allocated for every #define.  For a simple replacement
568    such as
569         #define foo bar ,
570    nargs = -1, the `pattern' list is null, and the expansion is just
571    the replacement text.  Nargs = 0 means a functionlike macro with no args,
572    e.g.,
573        #define getchar() getc (stdin) .
574    When there are args, the expansion is the replacement text with the
575    args squashed out, and the reflist is a list describing how to
576    build the output from the input: e.g., "3 chars, then the 1st arg,
577    then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
578    The chars here come from the expansion.  Whatever is left of the
579    expansion after the last arg-occurrence is copied after that arg.
580    Note that the reflist can be arbitrarily long---
581    its length depends on the number of times the arguments appear in
582    the replacement text, not how many args there are.  Example:
583    #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
584    pattern list
585      { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
586    where (x, y) means (nchars, argno).  */
587
588 typedef struct definition DEFINITION;
589 struct definition {
590   int nargs;
591   int length;                   /* length of expansion string */
592   int predefined;               /* True if the macro was builtin or */
593                                 /* came from the command line */
594   U_CHAR *expansion;
595   int line;                     /* Line number of definition */
596   char *file;                   /* File of definition */
597   size_t file_len;              /* Length of file (which can contain NULs) */
598   char rest_args;               /* Nonzero if last arg. absorbs the rest */
599   struct reflist {
600     struct reflist *next;
601
602     enum sharp_token_type stringify;    /* set if a # operator before arg */
603     enum sharp_token_type raw_before;   /* set if a ## operator before arg */
604     enum sharp_token_type raw_after;    /* set if a ## operator after arg */
605
606     char rest_args;             /* Nonzero if this arg. absorbs the rest */
607     int nchars;                 /* Number of literal chars to copy before
608                                    this arg occurrence.  */
609     int argno;                  /* Number of arg to substitute (origin-0) */
610   } *pattern;
611   union {
612     /* Names of macro args, concatenated in reverse order
613        with comma-space between them.
614        The only use of this is that we warn on redefinition
615        if this differs between the old and new definitions.  */
616     U_CHAR *argnames;
617   } args;
618 };
619
620 /* different kinds of things that can appear in the value field
621    of a hash node.  Actually, this may be useless now.  */
622 union hashval {
623   char *cpval;
624   DEFINITION *defn;
625   KEYDEF *keydef;
626 };
627
628 /*
629  * special extension string that can be added to the last macro argument to 
630  * allow it to absorb the "rest" of the arguments when expanded.  Ex:
631  *              #define wow(a, b...)            process (b, a, b)
632  *              { wow (1, 2, 3); }      ->      { process (2, 3, 1, 2, 3); }
633  *              { wow (one, two); }     ->      { process (two, one, two); }
634  * if this "rest_arg" is used with the concat token '##' and if it is not
635  * supplied then the token attached to with ## will not be outputted.  Ex:
636  *              #define wow (a, b...)           process (b ## , a, ## b)
637  *              { wow (1, 2); }         ->      { process (2, 1, 2); }
638  *              { wow (one); }          ->      { process (one); {
639  */
640 static char rest_extension[] = "...";
641 #define REST_EXTENSION_LENGTH   (sizeof (rest_extension) - 1)
642
643 /* The structure of a node in the hash table.  The hash table
644    has entries for all tokens defined by #define directives (type T_MACRO),
645    plus some special tokens like __LINE__ (these each have their own
646    type, and the appropriate code is run when that type of node is seen.
647    It does not contain control words like "#define", which are recognized
648    by a separate piece of code.  */
649
650 /* different flavors of hash nodes --- also used in keyword table */
651 enum node_type {
652  T_DEFINE = 1,  /* the `#define' keyword */
653  T_INCLUDE,     /* the `#include' keyword */
654  T_INCLUDE_NEXT, /* the `#include_next' keyword */
655  T_IMPORT,      /* the `#import' keyword */
656  T_IFDEF,       /* the `#ifdef' keyword */
657  T_IFNDEF,      /* the `#ifndef' keyword */
658  T_IF,          /* the `#if' keyword */
659  T_ELSE,        /* `#else' */
660  T_PRAGMA,      /* `#pragma' */
661  T_ELIF,        /* `#elif' */
662  T_UNDEF,       /* `#undef' */
663  T_LINE,        /* `#line' */
664  T_ERROR,       /* `#error' */
665  T_WARNING,     /* `#warning' */
666  T_ENDIF,       /* `#endif' */
667  T_SCCS,        /* `#sccs', used on system V.  */
668  T_IDENT,       /* `#ident', used on system V.  */
669  T_ASSERT,      /* `#assert', taken from system V.  */
670  T_UNASSERT,    /* `#unassert', taken from system V.  */
671  T_SPECLINE,    /* special symbol `__LINE__' */
672  T_DATE,        /* `__DATE__' */
673  T_FILE,        /* `__FILE__' */
674  T_BASE_FILE,   /* `__BASE_FILE__' */
675  T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
676  T_VERSION,     /* `__VERSION__' */
677  T_SIZE_TYPE,   /* `__SIZE_TYPE__' */
678  T_PTRDIFF_TYPE,   /* `__PTRDIFF_TYPE__' */
679  T_WCHAR_TYPE,   /* `__WCHAR_TYPE__' */
680  T_USER_LABEL_PREFIX_TYPE, /* `__USER_LABEL_PREFIX__' */
681  T_REGISTER_PREFIX_TYPE,   /* `__REGISTER_PREFIX__' */
682  T_IMMEDIATE_PREFIX_TYPE,  /* `__IMMEDIATE_PREFIX__' */
683  T_TIME,        /* `__TIME__' */
684  T_CONST,       /* Constant value, used by `__STDC__' */
685  T_MACRO,       /* macro defined by `#define' */
686  T_DISABLED,    /* macro temporarily turned off for rescan */
687  T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
688  T_PCSTRING,    /* precompiled string (hashval is KEYDEF *) */
689  T_UNUSED       /* Used for something not defined.  */
690  };
691
692 struct hashnode {
693   struct hashnode *next;        /* double links for easy deletion */
694   struct hashnode *prev;
695   struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
696                                    chain is kept, in case the node is the head
697                                    of the chain and gets deleted.  */
698   enum node_type type;          /* type of special token */
699   int length;                   /* length of token, for quick comparison */
700   U_CHAR *name;                 /* the actual name */
701   union hashval value;          /* pointer to expansion, or whatever */
702 };
703
704 typedef struct hashnode HASHNODE;
705
706 /* Some definitions for the hash table.  The hash function MUST be
707    computed as shown in hashf () below.  That is because the rescan
708    loop computes the hash value `on the fly' for most tokens,
709    in order to avoid the overhead of a lot of procedure calls to
710    the hashf () function.  Hashf () only exists for the sake of
711    politeness, for use when speed isn't so important.  */
712
713 #define HASHSIZE 1403
714 static HASHNODE *hashtab[HASHSIZE];
715 #define HASHSTEP(old, c) ((old << 2) + c)
716 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
717
718 /* Symbols to predefine.  */
719
720 #ifdef CPP_PREDEFINES
721 static char *predefs = CPP_PREDEFINES;
722 #else
723 static char *predefs = "";
724 #endif
725 \f
726 /* We let tm.h override the types used here, to handle trivial differences
727    such as the choice of unsigned int or long unsigned int for size_t.
728    When machines start needing nontrivial differences in the size type,
729    it would be best to do something here to figure out automatically
730    from other information what type to use.  */
731
732 /* The string value for __SIZE_TYPE__.  */
733
734 #ifndef SIZE_TYPE
735 #define SIZE_TYPE "long unsigned int"
736 #endif
737
738 /* The string value for __PTRDIFF_TYPE__.  */
739
740 #ifndef PTRDIFF_TYPE
741 #define PTRDIFF_TYPE "long int"
742 #endif
743
744 /* The string value for __WCHAR_TYPE__.  */
745
746 #ifndef WCHAR_TYPE
747 #define WCHAR_TYPE "int"
748 #endif
749 char * wchar_type = WCHAR_TYPE;
750 #undef WCHAR_TYPE
751
752 /* The string value for __USER_LABEL_PREFIX__ */
753
754 #ifndef USER_LABEL_PREFIX
755 #define USER_LABEL_PREFIX ""
756 #endif
757
758 /* The string value for __REGISTER_PREFIX__ */
759
760 #ifndef REGISTER_PREFIX
761 #define REGISTER_PREFIX ""
762 #endif
763
764 /* The string value for __IMMEDIATE_PREFIX__ */
765
766 #ifndef IMMEDIATE_PREFIX
767 #define IMMEDIATE_PREFIX ""
768 #endif
769 \f
770 /* In the definition of a #assert name, this structure forms
771    a list of the individual values asserted.
772    Each value is itself a list of "tokens".
773    These are strings that are compared by name.  */
774
775 struct tokenlist_list {
776   struct tokenlist_list *next;
777   struct arglist *tokens;
778 };
779
780 struct assertion_hashnode {
781   struct assertion_hashnode *next;      /* double links for easy deletion */
782   struct assertion_hashnode *prev;
783   /* also, a back pointer to this node's hash
784      chain is kept, in case the node is the head
785      of the chain and gets deleted.  */
786   struct assertion_hashnode **bucket_hdr;
787   int length;                   /* length of token, for quick comparison */
788   U_CHAR *name;                 /* the actual name */
789   /* List of token-sequences.  */
790   struct tokenlist_list *value;
791 };
792
793 typedef struct assertion_hashnode ASSERTION_HASHNODE;
794
795 /* Some definitions for the hash table.  The hash function MUST be
796    computed as shown in hashf below.  That is because the rescan
797    loop computes the hash value `on the fly' for most tokens,
798    in order to avoid the overhead of a lot of procedure calls to
799    the hashf function.  hashf only exists for the sake of
800    politeness, for use when speed isn't so important.  */
801
802 #define ASSERTION_HASHSIZE 37
803 static ASSERTION_HASHNODE *assertion_hashtab[ASSERTION_HASHSIZE];
804
805 /* Nonzero means inhibit macroexpansion of what seem to be
806    assertion tests, in rescan.  For #if.  */
807 static int assertions_flag;
808 \f
809 /* `struct directive' defines one #-directive, including how to handle it.  */
810
811 #define DO_PROTO PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *))
812
813 struct directive {
814   int length;                   /* Length of name */
815   int (*func) DO_PROTO; /* Function to handle directive */
816   char *name;                   /* Name of directive */
817   enum node_type type;          /* Code which describes which directive.  */
818 };
819
820 #define IS_INCLUDE_DIRECTIVE_TYPE(t) \
821 ((int) T_INCLUDE <= (int) (t) && (int) (t) <= (int) T_IMPORT)
822
823 /* These functions are declared to return int instead of void since they
824    are going to be placed in the table and some old compilers have trouble with
825    pointers to functions returning void.  */
826
827 static int do_assert DO_PROTO;
828 static int do_define DO_PROTO;
829 static int do_elif DO_PROTO;
830 static int do_else DO_PROTO;
831 static int do_endif DO_PROTO;
832 static int do_error DO_PROTO;
833 static int do_ident DO_PROTO;
834 static int do_if DO_PROTO;
835 static int do_include DO_PROTO;
836 static int do_line DO_PROTO;
837 static int do_pragma DO_PROTO;
838 #ifdef SCCS_DIRECTIVE
839 static int do_sccs DO_PROTO;
840 #endif
841 static int do_unassert DO_PROTO;
842 static int do_undef DO_PROTO;
843 static int do_warning DO_PROTO;
844 static int do_xifdef DO_PROTO;
845
846 /* Here is the actual list of #-directives, most-often-used first.  */
847
848 static struct directive directive_table[] = {
849   {  6, do_define, "define", T_DEFINE},
850   {  2, do_if, "if", T_IF},
851   {  5, do_xifdef, "ifdef", T_IFDEF},
852   {  6, do_xifdef, "ifndef", T_IFNDEF},
853   {  5, do_endif, "endif", T_ENDIF},
854   {  4, do_else, "else", T_ELSE},
855   {  4, do_elif, "elif", T_ELIF},
856   {  4, do_line, "line", T_LINE},
857   {  7, do_include, "include", T_INCLUDE},
858   { 12, do_include, "include_next", T_INCLUDE_NEXT},
859   {  6, do_include, "import", T_IMPORT},
860   {  5, do_undef, "undef", T_UNDEF},
861   {  5, do_error, "error", T_ERROR},
862   {  7, do_warning, "warning", T_WARNING},
863 #ifdef SCCS_DIRECTIVE
864   {  4, do_sccs, "sccs", T_SCCS},
865 #endif
866   {  6, do_pragma, "pragma", T_PRAGMA},
867   {  5, do_ident, "ident", T_IDENT},
868   {  6, do_assert, "assert", T_ASSERT},
869   {  8, do_unassert, "unassert", T_UNASSERT},
870   {  -1, 0, "", T_UNUSED},
871 };
872
873 /* When a directive handler is called,
874    this points to the # (or the : of the %:) that started the directive.  */
875 U_CHAR *directive_start;
876
877 /* table to tell if char can be part of a C identifier.  */
878 U_CHAR is_idchar[256];
879 /* table to tell if char can be first char of a c identifier.  */
880 U_CHAR is_idstart[256];
881 /* table to tell if c is horizontal space.  */
882 static U_CHAR is_hor_space[256];
883 /* table to tell if c is horizontal or vertical space.  */
884 U_CHAR is_space[256];
885 /* names of some characters */
886 static char *char_name[256];
887
888 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
889 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
890   
891 static int errors = 0;                  /* Error counter for exit code */
892
893 /* Name of output file, for error messages.  */
894 static char *out_fname;
895
896
897 /* Stack of conditionals currently in progress
898    (including both successful and failing conditionals).  */
899
900 struct if_stack {
901   struct if_stack *next;        /* for chaining to the next stack frame */
902   char *fname;          /* copied from input when frame is made */
903   size_t fname_len;             /* similarly */
904   int lineno;                   /* similarly */
905   int if_succeeded;             /* true if a leg of this if-group
906                                     has been passed through rescan */
907   U_CHAR *control_macro;        /* For #ifndef at start of file,
908                                    this is the macro name tested.  */
909   enum node_type type;          /* type of last directive seen in this group */
910 };
911 typedef struct if_stack IF_STACK_FRAME;
912 static IF_STACK_FRAME *if_stack = NULL;
913
914 /* Buffer of -M output.  */
915 static char *deps_buffer;
916
917 /* Number of bytes allocated in above.  */
918 static int deps_allocated_size;
919
920 /* Number of bytes used.  */
921 static int deps_size;
922
923 /* Number of bytes since the last newline.  */
924 static int deps_column;
925
926 /* Nonzero means -I- has been seen,
927    so don't look for #include "foo" the source-file directory.  */
928 static int ignore_srcdir;
929 \f
930 static int safe_read PROTO((int, char *, int));
931 static void safe_write PROTO((int, char *, int));
932 static void eprint_string PROTO((char *, size_t));
933
934 int main PROTO((int, char **));
935
936 static void path_include PROTO((char *));
937
938 static U_CHAR *index0 PROTO((U_CHAR *, int, size_t));
939
940 static void trigraph_pcp PROTO((FILE_BUF *));
941
942 static void newline_fix PROTO((U_CHAR *));
943 static void name_newline_fix PROTO((U_CHAR *));
944
945 static char *get_lintcmd PROTO((U_CHAR *, U_CHAR *, U_CHAR **, int *, int *));
946
947 static void rescan PROTO((FILE_BUF *, int));
948
949 static FILE_BUF expand_to_temp_buffer PROTO((U_CHAR *, U_CHAR *, int, int));
950
951 static int handle_directive PROTO((FILE_BUF *, FILE_BUF *));
952
953 static struct tm *timestamp PROTO((void));
954 static void special_symbol PROTO((HASHNODE *, FILE_BUF *));
955
956 static int is_system_include PROTO((char *));
957 static char *base_name PROTO((char *));
958 static int absolute_filename PROTO((char *));
959 static size_t simplify_filename PROTO((char *));
960
961 static char *read_filename_string PROTO((int, FILE *));
962 static struct file_name_map *read_name_map PROTO((char *));
963 static int open_include_file PROTO((char *, struct file_name_list *, U_CHAR *, struct include_file **));
964 static char *remap_include_file PROTO((char *, struct file_name_list *));
965 static int lookup_ino_include PROTO((struct include_file *));
966
967 static void finclude PROTO((int, struct include_file *, FILE_BUF *, int, struct file_name_list *));
968 static void record_control_macro PROTO((struct include_file *, U_CHAR *));
969
970 static char *check_precompiled PROTO((int, struct stat *, char *, char **));
971 static int check_preconditions PROTO((char *));
972 static void pcfinclude PROTO((U_CHAR *, U_CHAR *, U_CHAR *, FILE_BUF *));
973 static void pcstring_used PROTO((HASHNODE *));
974 static void write_output PROTO((void));
975 static void pass_thru_directive PROTO((U_CHAR *, U_CHAR *, FILE_BUF *, struct directive *));
976
977 static MACRODEF create_definition PROTO((U_CHAR *, U_CHAR *, FILE_BUF *));
978
979 static int check_macro_name PROTO((U_CHAR *, char *));
980 static int compare_defs PROTO((DEFINITION *, DEFINITION *));
981 static int comp_def_part PROTO((int, U_CHAR *, int, U_CHAR *, int, int));
982
983 static DEFINITION *collect_expansion  PROTO((U_CHAR *, U_CHAR *, int, struct arglist *));
984
985 int check_assertion PROTO((U_CHAR *, int, int, struct arglist *));
986 static int compare_token_lists PROTO((struct arglist *, struct arglist *));
987
988 static struct arglist *read_token_list PROTO((U_CHAR **, U_CHAR *, int *));
989 static void free_token_list PROTO((struct arglist *));
990
991 static ASSERTION_HASHNODE *assertion_install PROTO((U_CHAR *, int, int));
992 static ASSERTION_HASHNODE *assertion_lookup PROTO((U_CHAR *, int, int));
993 static void delete_assertion PROTO((ASSERTION_HASHNODE *));
994
995 static void do_once PROTO((void));
996
997 static HOST_WIDE_INT eval_if_expression PROTO((U_CHAR *, int));
998 static void conditional_skip PROTO((FILE_BUF *, int, enum node_type, U_CHAR *, FILE_BUF *));
999 static void skip_if_group PROTO((FILE_BUF *, int, FILE_BUF *));
1000 static void validate_else PROTO((U_CHAR *, U_CHAR *));
1001
1002 static U_CHAR *skip_to_end_of_comment PROTO((FILE_BUF *, int *, int));
1003 static U_CHAR *skip_quoted_string PROTO((U_CHAR *, U_CHAR *, int, int *, int *, int *));
1004 static char *quote_string PROTO((char *, char *, size_t));
1005 static U_CHAR *skip_paren_group PROTO((FILE_BUF *));
1006
1007 /* Last arg to output_line_directive.  */
1008 enum file_change_code {same_file, enter_file, leave_file};
1009 static void output_line_directive PROTO((FILE_BUF *, FILE_BUF *, int, enum file_change_code));
1010
1011 static void macroexpand PROTO((HASHNODE *, FILE_BUF *));
1012
1013 struct argdata;
1014 static char *macarg PROTO((struct argdata *, int));
1015
1016 static U_CHAR *macarg1 PROTO((U_CHAR *, U_CHAR *, struct hashnode *, int *, int *, int *, int));
1017
1018 static int discard_comments PROTO((U_CHAR *, int, int));
1019
1020 static int change_newlines PROTO((U_CHAR *, int));
1021
1022 char *my_strerror PROTO((int));
1023 void error PRINTF_PROTO_1((char *, ...));
1024 static void verror PROTO((char *, va_list));
1025 static void error_from_errno PROTO((char *));
1026 void warning PRINTF_PROTO_1((char *, ...));
1027 static void vwarning PROTO((char *, va_list));
1028 static void error_with_line PRINTF_PROTO_2((int, char *, ...));
1029 static void verror_with_line PROTO((int, char *, va_list));
1030 static void vwarning_with_line PROTO((int, char *, va_list));
1031 static void warning_with_line PRINTF_PROTO_2((int, char *, ...));
1032 void pedwarn PRINTF_PROTO_1((char *, ...));
1033 void pedwarn_with_line PRINTF_PROTO_2((int, char *, ...));
1034 static void pedwarn_with_file_and_line PRINTF_PROTO_4((char *, size_t, int, char *, ...));
1035
1036 static void print_containing_files PROTO((void));
1037
1038 static int line_for_error PROTO((int));
1039 static int grow_outbuf PROTO((FILE_BUF *, int));
1040
1041 static HASHNODE *install PROTO((U_CHAR *, int, enum node_type, char *, int));
1042 HASHNODE *lookup PROTO((U_CHAR *, int, int));
1043 static void delete_macro PROTO((HASHNODE *));
1044 static int hashf PROTO((U_CHAR *, int, int));
1045
1046 static void dump_single_macro PROTO((HASHNODE *, FILE *));
1047 static void dump_all_macros PROTO((void));
1048 static void dump_defn_1 PROTO((U_CHAR *, int, int, FILE *));
1049 static void dump_arg_n PROTO((DEFINITION *, int, FILE *));
1050
1051 static void initialize_char_syntax PROTO((void));
1052 static void initialize_builtins PROTO((FILE_BUF *, FILE_BUF *));
1053
1054 static void make_definition PROTO((char *, FILE_BUF *));
1055 static void make_undef PROTO((char *, FILE_BUF *));
1056
1057 static void make_assertion PROTO((char *, char *));
1058
1059 static struct file_name_list *new_include_prefix PROTO((struct file_name_list *, char *, char *, char *));
1060 static void append_include_chain PROTO((struct file_name_list *, struct file_name_list *));
1061
1062 static int quote_string_for_make PROTO((char *, char *));
1063 static void deps_output PROTO((char *, int));
1064
1065 static void fatal PRINTF_PROTO_1((char *, ...)) __attribute__ ((noreturn));
1066 void fancy_abort PROTO((void)) __attribute__ ((noreturn));
1067 static void perror_with_name PROTO((char *));
1068 static void pfatal_with_name PROTO((char *)) __attribute__ ((noreturn));
1069 static void pipe_closed PROTO((int)) __attribute__ ((noreturn));
1070
1071 static void memory_full PROTO((void)) __attribute__ ((noreturn));
1072 GENERIC_PTR xmalloc PROTO((size_t));
1073 static GENERIC_PTR xrealloc PROTO((GENERIC_PTR, size_t));
1074 static GENERIC_PTR xcalloc PROTO((size_t, size_t));
1075 static char *savestring PROTO((char *));
1076 \f
1077 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
1078    retrying if necessary.  If MAX_READ_LEN is defined, read at most
1079    that bytes at a time.  Return a negative value if an error occurs,
1080    otherwise return the actual number of bytes read,
1081    which must be LEN unless end-of-file was reached.  */
1082
1083 static int
1084 safe_read (desc, ptr, len)
1085      int desc;
1086      char *ptr;
1087      int len;
1088 {
1089   int left, rcount, nchars;
1090
1091   left = len;
1092   while (left > 0) {
1093     rcount = left;
1094 #ifdef MAX_READ_LEN
1095     if (rcount > MAX_READ_LEN)
1096       rcount = MAX_READ_LEN;
1097 #endif
1098     nchars = read (desc, ptr, rcount);
1099     if (nchars < 0)
1100       {
1101 #ifdef EINTR
1102         if (errno == EINTR)
1103           continue;
1104 #endif
1105         return nchars;
1106       }
1107     if (nchars == 0)
1108       break;
1109     ptr += nchars;
1110     left -= nchars;
1111   }
1112   return len - left;
1113 }
1114
1115 /* Write LEN bytes at PTR to descriptor DESC,
1116    retrying if necessary, and treating any real error as fatal.
1117    If MAX_WRITE_LEN is defined, write at most that many bytes at a time.  */
1118
1119 static void
1120 safe_write (desc, ptr, len)
1121      int desc;
1122      char *ptr;
1123      int len;
1124 {
1125   int wcount, written;
1126
1127   while (len > 0) {
1128     wcount = len;
1129 #ifdef MAX_WRITE_LEN
1130     if (wcount > MAX_WRITE_LEN)
1131       wcount = MAX_WRITE_LEN;
1132 #endif
1133     written = write (desc, ptr, wcount);
1134     if (written < 0)
1135       {
1136 #ifdef EINTR
1137         if (errno == EINTR)
1138           continue;
1139 #endif
1140         pfatal_with_name (out_fname);
1141       }
1142     ptr += written;
1143     len -= written;
1144   }
1145 }
1146
1147 /* Print a string to stderr, with extra handling in case it contains
1148    embedded NUL characters.  Any present are written as is.
1149
1150    Using fwrite for this purpose produces undesireable results on VMS
1151    when stderr happens to be a record oriented file, such as a batch log
1152    file, rather than a stream oriented one.  */
1153
1154 static void
1155 eprint_string (string, length)
1156      char *string;
1157      size_t length;
1158 {
1159   size_t segment_length;
1160
1161   do {
1162     fprintf(stderr, "%s", string);
1163     length -= (segment_length = strlen(string));
1164     if (length > 0)
1165       {
1166         fputc('\0', stderr);
1167         length -= 1;
1168         /* Advance past the portion which has already been printed.  */
1169         string += segment_length + 1;
1170       }
1171   } while (length > 0);
1172 }
1173
1174 \f
1175 int
1176 main (argc, argv)
1177      int argc;
1178      char **argv;
1179 {
1180   struct stat st;
1181   char *in_fname;
1182   char *cp;
1183   int f, i;
1184   FILE_BUF *fp;
1185   char **pend_files = (char **) xmalloc (argc * sizeof (char *));
1186   char **pend_defs = (char **) xmalloc (argc * sizeof (char *));
1187   char **pend_undefs = (char **) xmalloc (argc * sizeof (char *));
1188   char **pend_assertions = (char **) xmalloc (argc * sizeof (char *));
1189   char **pend_includes = (char **) xmalloc (argc * sizeof (char *));
1190
1191   /* Record the option used with each element of pend_assertions.
1192      This is preparation for supporting more than one option for making
1193      an assertion.  */
1194   char **pend_assertion_options = (char **) xmalloc (argc * sizeof (char *));
1195   int inhibit_predefs = 0;
1196   int no_standard_includes = 0;
1197   int no_standard_cplusplus_includes = 0;
1198   int missing_newline = 0;
1199
1200   /* Non-0 means don't output the preprocessed program.  */
1201   int inhibit_output = 0;
1202   /* Non-0 means -v, so print the full set of include dirs.  */
1203   int verbose = 0;
1204
1205   /* File name which deps are being written to.
1206      This is 0 if deps are being written to stdout.  */
1207   char *deps_file = 0;
1208   /* Fopen file mode to open deps_file with.  */
1209   char *deps_mode = "a";
1210   /* Stream on which to print the dependency information.  */
1211   FILE *deps_stream = 0;
1212   /* Target-name to write with the dependency information.  */
1213   char *deps_target = 0;
1214
1215 #if defined (RLIMIT_STACK) && defined (HAVE_GETRLIMIT) && defined (HAVE_SETRLIMIT)
1216   /* Get rid of any avoidable limit on stack size.  */
1217   {
1218     struct rlimit rlim;
1219
1220     /* Set the stack limit huge so that alloca (particularly stringtab
1221        in dbxread.c) does not fail.  */
1222     getrlimit (RLIMIT_STACK, &rlim);
1223     rlim.rlim_cur = rlim.rlim_max;
1224     setrlimit (RLIMIT_STACK, &rlim);
1225   }
1226 #endif
1227
1228 #ifdef SIGPIPE
1229   signal (SIGPIPE, pipe_closed);
1230 #endif
1231
1232   progname = base_name (argv[0]);
1233
1234 #ifdef VMS
1235   {
1236     /* Remove extension from PROGNAME.  */
1237     char *p;
1238     char *s = progname = savestring (progname);
1239
1240     if ((p = rindex (s, ';')) != 0) *p = '\0';  /* strip version number */
1241     if ((p = rindex (s, '.')) != 0              /* strip type iff ".exe" */
1242         && (p[1] == 'e' || p[1] == 'E')
1243         && (p[2] == 'x' || p[2] == 'X')
1244         && (p[3] == 'e' || p[3] == 'E')
1245         && !p[4])
1246       *p = '\0';
1247   }
1248 #endif
1249
1250   in_fname = NULL;
1251   out_fname = NULL;
1252
1253   /* Initialize is_idchar.  */
1254   initialize_char_syntax ();
1255
1256   no_line_directives = 0;
1257   no_trigraphs = 1;
1258   dump_macros = dump_none;
1259   no_output = 0;
1260   cplusplus = 0;
1261   cplusplus_comments = 1;
1262
1263   bzero ((char *) pend_files, argc * sizeof (char *));
1264   bzero ((char *) pend_defs, argc * sizeof (char *));
1265   bzero ((char *) pend_undefs, argc * sizeof (char *));
1266   bzero ((char *) pend_assertions, argc * sizeof (char *));
1267   bzero ((char *) pend_includes, argc * sizeof (char *));
1268
1269   /* Process switches and find input file name.  */
1270
1271   for (i = 1; i < argc; i++) {
1272     if (argv[i][0] != '-') {
1273       if (out_fname != NULL)
1274         fatal ("Usage: %s [switches] input output", argv[0]);
1275       else if (in_fname != NULL)
1276         out_fname = argv[i];
1277       else
1278         in_fname = argv[i];
1279     } else {
1280       switch (argv[i][1]) {
1281
1282       case 'i':
1283         if (!strcmp (argv[i], "-include")) {
1284           int temp = i;
1285
1286           if (i + 1 == argc)
1287             fatal ("Filename missing after `-include' option");
1288           else
1289             simplify_filename (pend_includes[temp] = argv[++i]);
1290         }
1291         if (!strcmp (argv[i], "-imacros")) {
1292           int temp = i;
1293
1294           if (i + 1 == argc)
1295             fatal ("Filename missing after `-imacros' option");
1296           else
1297             simplify_filename (pend_files[temp] = argv[++i]);
1298         }
1299         if (!strcmp (argv[i], "-iprefix")) {
1300           if (i + 1 == argc)
1301             fatal ("Filename missing after `-iprefix' option");
1302           else
1303             include_prefix = argv[++i];
1304         }
1305         if (!strcmp (argv[i], "-ifoutput")) {
1306           output_conditionals = 1;
1307         }
1308         if (!strcmp (argv[i], "-isystem")) {
1309           struct file_name_list *dirtmp;
1310
1311           if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1312                                               "", argv[++i])))
1313             break;
1314           dirtmp->c_system_include_path = 1;
1315
1316           if (before_system == 0)
1317             before_system = dirtmp;
1318           else
1319             last_before_system->next = dirtmp;
1320           last_before_system = dirtmp; /* Tail follows the last one */
1321         }
1322         /* Add directory to end of path for includes,
1323            with the default prefix at the front of its name.  */
1324         if (!strcmp (argv[i], "-iwithprefix")) {
1325           struct file_name_list *dirtmp;
1326           char *prefix;
1327
1328           if (include_prefix != 0)
1329             prefix = include_prefix;
1330           else {
1331             prefix = savestring (GCC_INCLUDE_DIR);
1332             /* Remove the `include' from /usr/local/lib/gcc.../include.  */
1333             if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1334               prefix[strlen (prefix) - 7] = 0;
1335           }
1336
1337           if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1338                                               prefix, argv[++i])))
1339             break;
1340
1341           if (after_include == 0)
1342             after_include = dirtmp;
1343           else
1344             last_after_include->next = dirtmp;
1345           last_after_include = dirtmp; /* Tail follows the last one */
1346         }
1347         /* Add directory to main path for includes,
1348            with the default prefix at the front of its name.  */
1349         if (!strcmp (argv[i], "-iwithprefixbefore")) {
1350           struct file_name_list *dirtmp;
1351           char *prefix;
1352
1353           if (include_prefix != 0)
1354             prefix = include_prefix;
1355           else {
1356             prefix = savestring (GCC_INCLUDE_DIR);
1357             /* Remove the `include' from /usr/local/lib/gcc.../include.  */
1358             if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
1359               prefix[strlen (prefix) - 7] = 0;
1360           }
1361
1362           dirtmp = new_include_prefix (NULL_PTR, NULL_PTR, prefix, argv[++i]);
1363           append_include_chain (dirtmp, dirtmp);
1364         }
1365         /* Add directory to end of path for includes.  */
1366         if (!strcmp (argv[i], "-idirafter")) {
1367           struct file_name_list *dirtmp;
1368
1369           if (! (dirtmp = new_include_prefix (NULL_PTR, NULL_PTR,
1370                                               "", argv[++i])))
1371             break;
1372
1373           if (after_include == 0)
1374             after_include = dirtmp;
1375           else
1376             last_after_include->next = dirtmp;
1377           last_after_include = dirtmp; /* Tail follows the last one */
1378         }
1379         break;
1380
1381       case 'o':
1382         if (out_fname != NULL)
1383           fatal ("Output filename specified twice");
1384         if (i + 1 == argc)
1385           fatal ("Filename missing after -o option");
1386         out_fname = argv[++i];
1387         if (!strcmp (out_fname, "-"))
1388           out_fname = "";
1389         break;
1390
1391       case 'p':
1392         if (!strcmp (argv[i], "-pedantic"))
1393           pedantic = 1;
1394         else if (!strcmp (argv[i], "-pedantic-errors")) {
1395           pedantic = 1;
1396           pedantic_errors = 1;
1397         } else if (!strcmp (argv[i], "-pcp")) {
1398           char *pcp_fname;
1399           if (i + 1 == argc)
1400             fatal ("Filename missing after -pcp option");
1401           pcp_fname = argv[++i];
1402           pcp_outfile
1403             = ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
1404                ? fopen (pcp_fname, "w")
1405                : stdout);
1406           if (pcp_outfile == 0)
1407             pfatal_with_name (pcp_fname);
1408           no_precomp = 1;
1409         }
1410         break;
1411
1412       case 't':
1413         if (!strcmp (argv[i], "-traditional")) {
1414           traditional = 1;
1415           cplusplus_comments = 0;
1416         } else if (!strcmp (argv[i], "-trigraphs")) {
1417           no_trigraphs = 0;
1418         }
1419         break;
1420
1421       case 'l':
1422         if (! strcmp (argv[i], "-lang-c"))
1423           cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 0;
1424         if (! strcmp (argv[i], "-lang-c89"))
1425           cplusplus = 0, cplusplus_comments = 0, c89 = 1, objc = 0;
1426         if (! strcmp (argv[i], "-lang-c++"))
1427           cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 0;
1428         if (! strcmp (argv[i], "-lang-objc"))
1429           cplusplus = 0, cplusplus_comments = 1, c89 = 0, objc = 1;
1430         if (! strcmp (argv[i], "-lang-objc++"))
1431           cplusplus = 1, cplusplus_comments = 1, c89 = 0, objc = 1;
1432         if (! strcmp (argv[i], "-lang-asm"))
1433           lang_asm = 1;
1434         if (! strcmp (argv[i], "-lint"))
1435           for_lint = 1;
1436         break;
1437
1438       case '+':
1439         cplusplus = 1, cplusplus_comments = 1;
1440         break;
1441
1442       case 'w':
1443         inhibit_warnings = 1;
1444         break;
1445
1446       case 'W':
1447         if (!strcmp (argv[i], "-Wtrigraphs"))
1448           warn_trigraphs = 1;
1449         else if (!strcmp (argv[i], "-Wno-trigraphs"))
1450           warn_trigraphs = 0;
1451         else if (!strcmp (argv[i], "-Wcomment"))
1452           warn_comments = 1;
1453         else if (!strcmp (argv[i], "-Wno-comment"))
1454           warn_comments = 0;
1455         else if (!strcmp (argv[i], "-Wcomments"))
1456           warn_comments = 1;
1457         else if (!strcmp (argv[i], "-Wno-comments"))
1458           warn_comments = 0;
1459         else if (!strcmp (argv[i], "-Wtraditional"))
1460           warn_stringify = 1;
1461         else if (!strcmp (argv[i], "-Wno-traditional"))
1462           warn_stringify = 0;
1463         else if (!strcmp (argv[i], "-Wundef"))
1464           warn_undef = 1;
1465         else if (!strcmp (argv[i], "-Wno-undef"))
1466           warn_undef = 0;
1467         else if (!strcmp (argv[i], "-Wimport"))
1468           warn_import = 1;
1469         else if (!strcmp (argv[i], "-Wno-import"))
1470           warn_import = 0;
1471         else if (!strcmp (argv[i], "-Werror"))
1472           warnings_are_errors = 1;
1473         else if (!strcmp (argv[i], "-Wno-error"))
1474           warnings_are_errors = 0;
1475         else if (!strcmp (argv[i], "-Wall"))
1476           {
1477             warn_trigraphs = 1;
1478             warn_comments = 1;
1479           }
1480         break;
1481
1482       case 'M':
1483         /* The style of the choices here is a bit mixed.
1484            The chosen scheme is a hybrid of keeping all options in one string
1485            and specifying each option in a separate argument:
1486            -M|-MM|-MD file|-MMD file [-MG].  An alternative is:
1487            -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
1488            -M[M][G][D file].  This is awkward to handle in specs, and is not
1489            as extensible.  */
1490         /* ??? -MG must be specified in addition to one of -M or -MM.
1491            This can be relaxed in the future without breaking anything.
1492            The converse isn't true.  */
1493
1494         /* -MG isn't valid with -MD or -MMD.  This is checked for later.  */
1495         if (!strcmp (argv[i], "-MG"))
1496           {
1497             print_deps_missing_files = 1;
1498             break;
1499           }
1500         if (!strcmp (argv[i], "-M"))
1501           print_deps = 2;
1502         else if (!strcmp (argv[i], "-MM"))
1503           print_deps = 1;
1504         else if (!strcmp (argv[i], "-MD"))
1505           print_deps = 2;
1506         else if (!strcmp (argv[i], "-MMD"))
1507           print_deps = 1;
1508         /* For -MD and -MMD options, write deps on file named by next arg.  */
1509         if (!strcmp (argv[i], "-MD")
1510             || !strcmp (argv[i], "-MMD")) {
1511           if (i + 1 == argc)
1512             fatal ("Filename missing after %s option", argv[i]);
1513           i++;
1514           deps_file = argv[i];
1515           deps_mode = "w";
1516         } else {
1517           /* For -M and -MM, write deps on standard output
1518              and suppress the usual output.  */
1519           deps_stream = stdout;
1520           inhibit_output = 1;
1521         }         
1522         break;
1523
1524       case 'd':
1525         {
1526           char *p = argv[i] + 2;
1527           char c;
1528           while ((c = *p++)) {
1529             /* Arg to -d specifies what parts of macros to dump */
1530             switch (c) {
1531             case 'M':
1532               dump_macros = dump_only;
1533               no_output = 1;
1534               break;
1535             case 'N':
1536               dump_macros = dump_names;
1537               break;
1538             case 'D':
1539               dump_macros = dump_definitions;
1540               break;
1541             case 'I':
1542               dump_includes = 1;
1543               break;
1544             }
1545           }
1546         }
1547         break;
1548
1549       case 'g':
1550         if (argv[i][2] == '3')
1551           debug_output = 1;
1552         break;
1553
1554       case 'v':
1555         fprintf (stderr, "GNU CPP version %s", version_string);
1556 #ifdef TARGET_VERSION
1557         TARGET_VERSION;
1558 #endif
1559         fprintf (stderr, "\n");
1560         verbose = 1;
1561         break;
1562
1563       case 'H':
1564         print_include_names = 1;
1565         break;
1566
1567       case 'D':
1568         if (argv[i][2] != 0)
1569           pend_defs[i] = argv[i] + 2;
1570         else if (i + 1 == argc)
1571           fatal ("Macro name missing after -D option");
1572         else
1573           i++, pend_defs[i] = argv[i];
1574         break;
1575
1576       case 'A':
1577         {
1578           char *p;
1579
1580           if (argv[i][2] != 0)
1581             p = argv[i] + 2;
1582           else if (i + 1 == argc)
1583             fatal ("Assertion missing after -A option");
1584           else
1585             p = argv[++i];
1586
1587           if (!strcmp (p, "-")) {
1588             /* -A- eliminates all predefined macros and assertions.
1589                Let's include also any that were specified earlier
1590                on the command line.  That way we can get rid of any
1591                that were passed automatically in from GCC.  */
1592             int j;
1593             inhibit_predefs = 1;
1594             for (j = 0; j < i; j++)
1595               pend_defs[j] = pend_assertions[j] = 0;
1596           } else {
1597             pend_assertions[i] = p;
1598             pend_assertion_options[i] = "-A";
1599           }
1600         }
1601         break;
1602
1603       case 'U':         /* JF #undef something */
1604         if (argv[i][2] != 0)
1605           pend_undefs[i] = argv[i] + 2;
1606         else if (i + 1 == argc)
1607           fatal ("Macro name missing after -U option");
1608         else
1609           pend_undefs[i] = argv[i+1], i++;
1610         break;
1611
1612       case 'C':
1613         put_out_comments = 1;
1614         break;
1615
1616       case 'E':                 /* -E comes from cc -E; ignore it.  */
1617         break;
1618
1619       case 'P':
1620         no_line_directives = 1;
1621         break;
1622
1623       case '$':                 /* Don't include $ in identifiers.  */
1624         is_idchar['$'] = is_idstart['$'] = 0;
1625         break;
1626
1627       case 'I':                 /* Add directory to path for includes.  */
1628         {
1629           struct file_name_list *dirtmp;
1630
1631           if (! ignore_srcdir && !strcmp (argv[i] + 2, "-")) {
1632             ignore_srcdir = 1;
1633             /* Don't use any preceding -I directories for #include <...>.  */
1634             first_bracket_include = 0;
1635           }
1636           else {
1637             dirtmp = new_include_prefix (last_include, NULL_PTR, "",
1638                                          argv[i][2] ? argv[i] + 2 : argv[++i]);
1639             append_include_chain (dirtmp, dirtmp);
1640           }
1641         }
1642         break;
1643
1644       case 'n':
1645         if (!strcmp (argv[i], "-nostdinc"))
1646           /* -nostdinc causes no default include directories.
1647              You must specify all include-file directories with -I.  */
1648           no_standard_includes = 1;
1649         else if (!strcmp (argv[i], "-nostdinc++"))
1650           /* -nostdinc++ causes no default C++-specific include directories. */
1651           no_standard_cplusplus_includes = 1;
1652         else if (!strcmp (argv[i], "-noprecomp"))
1653           no_precomp = 1;
1654         break;
1655
1656       case 'r':
1657         if (!strcmp (argv[i], "-remap"))
1658           remap = 1;
1659         break;
1660
1661       case 'u':
1662         /* Sun compiler passes undocumented switch "-undef".
1663            Let's assume it means to inhibit the predefined symbols.  */
1664         inhibit_predefs = 1;
1665         break;
1666
1667       case '\0': /* JF handle '-' as file name meaning stdin or stdout */
1668         if (in_fname == NULL) {
1669           in_fname = "";
1670           break;
1671         } else if (out_fname == NULL) {
1672           out_fname = "";
1673           break;
1674         }       /* else fall through into error */
1675
1676       default:
1677         fatal ("Invalid option `%s'", argv[i]);
1678       }
1679     }
1680   }
1681
1682   /* Add dirs from CPATH after dirs from -I.  */
1683   /* There seems to be confusion about what CPATH should do,
1684      so for the moment it is not documented.  */
1685   /* Some people say that CPATH should replace the standard include dirs,
1686      but that seems pointless: it comes before them, so it overrides them
1687      anyway.  */
1688   GET_ENVIRONMENT (cp, "CPATH");
1689   if (cp && ! no_standard_includes)
1690     path_include (cp);
1691
1692   /* Initialize output buffer */
1693
1694   outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
1695   outbuf.bufp = outbuf.buf;
1696   outbuf.length = OUTBUF_SIZE;
1697
1698   /* Do partial setup of input buffer for the sake of generating
1699      early #line directives (when -g is in effect).  */
1700
1701   fp = &instack[++indepth];
1702   if (in_fname == NULL)
1703     in_fname = "";
1704   fp->nominal_fname = fp->fname = in_fname;
1705   fp->nominal_fname_len = strlen (in_fname);
1706   fp->lineno = 0;
1707
1708   /* In C++, wchar_t is a distinct basic type, and we can expect
1709      __wchar_t to be defined by cc1plus.  */
1710   if (cplusplus)
1711     wchar_type = "__wchar_t";
1712
1713   /* Install __LINE__, etc.  Must follow initialize_char_syntax
1714      and option processing.  */
1715   initialize_builtins (fp, &outbuf);
1716
1717   /* Do standard #defines and assertions
1718      that identify system and machine type.  */
1719
1720   if (!inhibit_predefs) {
1721     char *p = (char *) alloca (strlen (predefs) + 1);
1722
1723 #ifdef VMS
1724     struct dsc$descriptor_s lcl_name;
1725     struct item_list {
1726       unsigned short length;  /* input length */
1727       unsigned short code;    /* item code */   
1728       unsigned long dptr;     /* data ptr */
1729       unsigned long lptr;     /* output length ptr */
1730     };
1731
1732     unsigned long syi_length;
1733     char syi_data[16];
1734
1735     struct item_list items[] = {
1736       { 16, SYI$_VERSION, 0, 0 },
1737       { 0, 0, 0, 0 }
1738     };
1739
1740     items[0].dptr = (unsigned long)syi_data;
1741     items[0].lptr = (unsigned long)(&syi_length);
1742
1743     if (SYS$GETSYIW (0, 0, 0, items, NULL, NULL, NULL, NULL) == SS$_NORMAL)
1744       {
1745         unsigned long vms_version_value;
1746         char *vers;
1747
1748         vers = syi_data;
1749         vms_version_value = 0;
1750
1751         if (*vers == 'V')
1752           vers++;
1753         if (isdigit (*vers))
1754           {
1755             vms_version_value = (*vers - '0') * 10000000;
1756           }
1757         vers++;
1758         if (*vers == '.')
1759           {
1760             vers++;
1761             if (isdigit (*vers))
1762               {
1763                 vms_version_value += (*vers - '0') * 100000;
1764               }
1765           }
1766
1767         if (vms_version_value > 0)
1768           {
1769             char versbuf[32];
1770
1771             sprintf (versbuf, "__VMS_VER=%08ld", vms_version_value);
1772             if (debug_output)
1773               output_line_directive (fp, &outbuf, 0, same_file);
1774             make_definition (versbuf, &outbuf);
1775           }
1776       }
1777 #endif
1778
1779     strcpy (p, predefs);
1780     while (*p) {
1781       char *q;
1782       while (*p == ' ' || *p == '\t')
1783         p++;
1784       /* Handle -D options.  */ 
1785       if (p[0] == '-' && p[1] == 'D') {
1786         q = &p[2];
1787         while (*p && *p != ' ' && *p != '\t')
1788           p++;
1789         if (*p != 0)
1790           *p++= 0;
1791         if (debug_output)
1792           output_line_directive (fp, &outbuf, 0, same_file);
1793         make_definition (q, &outbuf);
1794         while (*p == ' ' || *p == '\t')
1795           p++;
1796       } else if (p[0] == '-' && p[1] == 'A') {
1797         /* Handle -A options (assertions).  */ 
1798         char *assertion;
1799         char *past_name;
1800         char *value;
1801         char *past_value;
1802         char *termination;
1803         int save_char;
1804
1805         assertion = &p[2];
1806         past_name = assertion;
1807         /* Locate end of name.  */
1808         while (*past_name && *past_name != ' '
1809                && *past_name != '\t' && *past_name != '(')
1810           past_name++;
1811         /* Locate `(' at start of value.  */
1812         value = past_name;
1813         while (*value && (*value == ' ' || *value == '\t'))
1814           value++;
1815         if (*value++ != '(')
1816           abort ();
1817         while (*value && (*value == ' ' || *value == '\t'))
1818           value++;
1819         past_value = value;
1820         /* Locate end of value.  */
1821         while (*past_value && *past_value != ' '
1822                && *past_value != '\t' && *past_value != ')')
1823           past_value++;
1824         termination = past_value;
1825         while (*termination && (*termination == ' ' || *termination == '\t'))
1826           termination++;
1827         if (*termination++ != ')')
1828           abort ();
1829         if (*termination && *termination != ' ' && *termination != '\t')
1830           abort ();
1831         /* Temporarily null-terminate the value.  */
1832         save_char = *termination;
1833         *termination = '\0';
1834         /* Install the assertion.  */
1835         make_assertion ("-A", assertion);
1836         *termination = (char) save_char;
1837         p = termination;
1838         while (*p == ' ' || *p == '\t')
1839           p++;
1840       } else {
1841         abort ();
1842       }
1843     }
1844   }
1845
1846   /* Now handle the command line options.  */
1847
1848   /* Do -U's, -D's and -A's in the order they were seen.  */
1849   for (i = 1; i < argc; i++) {
1850     if (pend_undefs[i]) {
1851       if (debug_output)
1852         output_line_directive (fp, &outbuf, 0, same_file);
1853       make_undef (pend_undefs[i], &outbuf);
1854     }
1855     if (pend_defs[i]) {
1856       if (debug_output)
1857         output_line_directive (fp, &outbuf, 0, same_file);
1858       make_definition (pend_defs[i], &outbuf);
1859     }
1860     if (pend_assertions[i])
1861       make_assertion (pend_assertion_options[i], pend_assertions[i]);
1862   }
1863
1864   done_initializing = 1;
1865
1866   { /* Read the appropriate environment variable and if it exists
1867        replace include_defaults with the listed path.  */
1868     char *epath = 0;
1869     switch ((objc << 1) + cplusplus)
1870       {
1871       case 0:
1872         GET_ENVIRONMENT (epath, "C_INCLUDE_PATH");
1873         break;
1874       case 1:
1875         GET_ENVIRONMENT (epath, "CPLUS_INCLUDE_PATH");
1876         break;
1877       case 2:
1878         GET_ENVIRONMENT (epath, "OBJC_INCLUDE_PATH");
1879         break;
1880       case 3:
1881         GET_ENVIRONMENT (epath, "OBJCPLUS_INCLUDE_PATH");
1882         break;
1883       }
1884     /* If the environment var for this language is set,
1885        add to the default list of include directories.  */
1886     if (epath) {
1887       int num_dirs;
1888       char *startp, *endp;
1889
1890       for (num_dirs = 1, startp = epath; *startp; startp++)
1891         if (*startp == PATH_SEPARATOR)
1892           num_dirs++;
1893       include_defaults
1894         = (struct default_include *) xmalloc ((num_dirs
1895                                                * sizeof (struct default_include))
1896                                               + sizeof (include_defaults_array));
1897       startp = endp = epath;
1898       num_dirs = 0;
1899       while (1) {
1900         char c = *endp++;
1901         if (c == PATH_SEPARATOR || !c) {
1902           endp[-1] = 0;
1903           include_defaults[num_dirs].fname
1904             = startp == endp ? "." : savestring (startp);
1905           endp[-1] = c;
1906           include_defaults[num_dirs].component = 0;
1907           include_defaults[num_dirs].cplusplus = cplusplus;
1908           include_defaults[num_dirs].cxx_aware = 1;
1909           num_dirs++;
1910           if (!c)
1911             break;
1912           startp = endp;
1913         }
1914       }
1915       /* Put the usual defaults back in at the end.  */
1916       bcopy ((char *) include_defaults_array,
1917              (char *) &include_defaults[num_dirs],
1918              sizeof (include_defaults_array));
1919     }
1920   }
1921
1922   append_include_chain (before_system, last_before_system);
1923   first_system_include = before_system;
1924
1925   /* Unless -fnostdinc,
1926      tack on the standard include file dirs to the specified list */
1927   if (!no_standard_includes) {
1928     struct default_include *p = include_defaults;
1929     char *specd_prefix = include_prefix;
1930     char *default_prefix = savestring (GCC_INCLUDE_DIR);
1931     int default_len = 0;
1932     /* Remove the `include' from /usr/local/lib/gcc.../include.  */
1933     if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
1934       default_len = strlen (default_prefix) - 7;
1935       default_prefix[default_len] = 0;
1936     }
1937     /* Search "translated" versions of GNU directories.
1938        These have /usr/local/lib/gcc... replaced by specd_prefix.  */
1939     if (specd_prefix != 0 && default_len != 0)
1940       for (p = include_defaults; p->fname; p++) {
1941         /* Some standard dirs are only for C++.  */
1942         if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1943           /* Does this dir start with the prefix?  */
1944           if (!strncmp (p->fname, default_prefix, default_len)) {
1945             /* Yes; change prefix and add to search list.  */
1946             struct file_name_list *new
1947               = new_include_prefix (NULL_PTR, NULL_PTR, specd_prefix,
1948                                     p->fname + default_len);
1949             if (new) {
1950               new->c_system_include_path = !p->cxx_aware;
1951               append_include_chain (new, new);
1952               if (first_system_include == 0)
1953                 first_system_include = new;
1954             }
1955           }
1956         }
1957       }
1958     /* Search ordinary names for GNU include directories.  */
1959     for (p = include_defaults; p->fname; p++) {
1960       /* Some standard dirs are only for C++.  */
1961       if (!p->cplusplus || (cplusplus && !no_standard_cplusplus_includes)) {
1962         struct file_name_list *new
1963           = new_include_prefix (NULL_PTR, p->component, "", p->fname);
1964         if (new) {
1965           new->c_system_include_path = !p->cxx_aware;
1966           append_include_chain (new, new);
1967           if (first_system_include == 0)
1968             first_system_include = new;
1969         }
1970       }
1971     }
1972   }
1973
1974   /* Tack the after_include chain at the end of the include chain.  */
1975   append_include_chain (after_include, last_after_include);
1976   if (first_system_include == 0)
1977     first_system_include = after_include;
1978
1979   /* With -v, print the list of dirs to search.  */
1980   if (verbose) {
1981     struct file_name_list *p;
1982     fprintf (stderr, "#include \"...\" search starts here:\n");
1983     for (p = include; p; p = p->next) {
1984       if (p == first_bracket_include)
1985         fprintf (stderr, "#include <...> search starts here:\n");
1986       if (!p->fname[0])
1987         fprintf (stderr, " .\n");
1988       else if (!strcmp (p->fname, "/") || !strcmp (p->fname, "//"))
1989         fprintf (stderr, " %s\n", p->fname);
1990       else
1991         /* Omit trailing '/'.  */
1992         fprintf (stderr, " %.*s\n", (int) strlen (p->fname) - 1, p->fname);
1993     }
1994     fprintf (stderr, "End of search list.\n");
1995   }
1996
1997   /* -MG doesn't select the form of output and must be specified with one of
1998      -M or -MM.  -MG doesn't make sense with -MD or -MMD since they don't
1999      inhibit compilation.  */
2000   if (print_deps_missing_files && (print_deps == 0 || !inhibit_output))
2001     fatal ("-MG must be specified with one of -M or -MM");
2002
2003   /* Either of two environment variables can specify output of deps.
2004      Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
2005      where OUTPUT_FILE is the file to write deps info to
2006      and DEPS_TARGET is the target to mention in the deps.  */
2007
2008   if (print_deps == 0
2009       && (getenv ("SUNPRO_DEPENDENCIES") != 0
2010           || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
2011     char *spec = getenv ("DEPENDENCIES_OUTPUT");
2012     char *s;
2013     char *output_file;
2014
2015     if (spec == 0) {
2016       spec = getenv ("SUNPRO_DEPENDENCIES");
2017       print_deps = 2;
2018     }
2019     else
2020       print_deps = 1;
2021
2022     s = spec;
2023     /* Find the space before the DEPS_TARGET, if there is one.  */
2024     /* This should use index.  (mrs) */
2025     while (*s != 0 && *s != ' ') s++;
2026     if (*s != 0) {
2027       deps_target = s + 1;
2028       output_file = xmalloc (s - spec + 1);
2029       bcopy (spec, output_file, s - spec);
2030       output_file[s - spec] = 0;
2031     }
2032     else {
2033       deps_target = 0;
2034       output_file = spec;
2035     }
2036       
2037     deps_file = output_file;
2038     deps_mode = "a";
2039   }
2040
2041   /* For -M, print the expected object file name
2042      as the target of this Make-rule.  */
2043   if (print_deps) {
2044     deps_allocated_size = 200;
2045     deps_buffer = xmalloc (deps_allocated_size);
2046     deps_buffer[0] = 0;
2047     deps_size = 0;
2048     deps_column = 0;
2049
2050     if (deps_target) {
2051       deps_output (deps_target, ':');
2052     } else if (*in_fname == 0) {
2053       deps_output ("-", ':');
2054     } else {
2055       char *p, *q;
2056       int len;
2057
2058       q = base_name (in_fname);
2059
2060       /* Copy remainder to mungable area.  */
2061       p = (char *) alloca (strlen(q) + 8);
2062       strcpy (p, q);
2063
2064       /* Output P, but remove known suffixes.  */
2065       len = strlen (p);
2066       q = p + len;
2067       if (len >= 2
2068           && p[len - 2] == '.'
2069           && index("cCsSm", p[len - 1]))
2070         q = p + (len - 2);
2071       else if (len >= 3
2072                && p[len - 3] == '.'
2073                && p[len - 2] == 'c'
2074                && p[len - 1] == 'c')
2075         q = p + (len - 3);
2076       else if (len >= 4
2077                && p[len - 4] == '.'
2078                && p[len - 3] == 'c'
2079                && p[len - 2] == 'x'
2080                && p[len - 1] == 'x')
2081         q = p + (len - 4);
2082       else if (len >= 4
2083                && p[len - 4] == '.'
2084                && p[len - 3] == 'c'
2085                && p[len - 2] == 'p'
2086                && p[len - 1] == 'p')
2087         q = p + (len - 4);
2088
2089       /* Supply our own suffix.  */
2090       strcpy (q, OBJECT_SUFFIX);
2091
2092       deps_output (p, ':');
2093       deps_output (in_fname, ' ');
2094     }
2095   }
2096
2097   /* Scan the -imacros files before the main input.
2098      Much like #including them, but with no_output set
2099      so that only their macro definitions matter.  */
2100
2101   no_output++; no_record_file++;
2102   for (i = 1; i < argc; i++)
2103     if (pend_files[i]) {
2104       struct include_file *inc;
2105       int fd = open_include_file (pend_files[i], NULL_PTR, NULL_PTR, &inc);
2106       if (fd < 0) {
2107         perror_with_name (pend_files[i]);
2108         return FATAL_EXIT_CODE;
2109       }
2110       finclude (fd, inc, &outbuf, 0, NULL_PTR);
2111     }
2112   no_output--; no_record_file--;
2113
2114   /* Copy the entire contents of the main input file into
2115      the stacked input buffer previously allocated for it.  */
2116
2117   /* JF check for stdin */
2118   if (in_fname == NULL || *in_fname == 0) {
2119     in_fname = "";
2120     f = 0;
2121   } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
2122     goto perror;
2123
2124   if (fstat (f, &st) != 0)
2125     pfatal_with_name (in_fname);
2126   fp->nominal_fname = fp->fname = in_fname;
2127   fp->nominal_fname_len = strlen (in_fname);
2128   fp->lineno = 1;
2129   fp->system_header_p = 0;
2130   /* JF all this is mine about reading pipes and ttys */
2131   if (! S_ISREG (st.st_mode)) {
2132     /* Read input from a file that is not a normal disk file.
2133        We cannot preallocate a buffer with the correct size,
2134        so we must read in the file a piece at the time and make it bigger.  */
2135     int size;
2136     int bsize;
2137     int cnt;
2138
2139     if (S_ISDIR (st.st_mode))
2140       fatal ("Input file `%s' is a directory", in_fname);
2141
2142     bsize = 2000;
2143     size = 0;
2144     fp->buf = (U_CHAR *) xmalloc (bsize + 2);
2145     for (;;) {
2146       cnt = safe_read (f, (char *) fp->buf + size, bsize - size);
2147       if (cnt < 0) goto perror; /* error! */
2148       size += cnt;
2149       if (size != bsize) break; /* End of file */
2150       bsize *= 2;
2151       fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
2152     }
2153     fp->length = size;
2154   } else {
2155     /* Read a file whose size we can determine in advance.
2156        For the sake of VMS, st.st_size is just an upper bound.  */
2157     size_t s = (size_t) st.st_size;
2158     if (s != st.st_size || s + 2 < s)
2159       memory_full ();
2160     fp->buf = (U_CHAR *) xmalloc (s + 2);
2161     fp->length = safe_read (f, (char *) fp->buf, s);
2162     if (fp->length < 0) goto perror;
2163   }
2164   fp->bufp = fp->buf;
2165   fp->if_stack = if_stack;
2166
2167   /* Make sure data ends with a newline.  And put a null after it.  */
2168
2169   if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
2170       /* Backslash-newline at end is not good enough.  */
2171       || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
2172     fp->buf[fp->length++] = '\n';
2173     missing_newline = 1;
2174   }
2175   fp->buf[fp->length] = '\0';
2176
2177   /* Unless inhibited, convert trigraphs in the input.  */
2178
2179   if (!no_trigraphs)
2180     trigraph_pcp (fp);
2181
2182   /* Now that we know the input file is valid, open the output.  */
2183
2184   if (!out_fname || !strcmp (out_fname, ""))
2185     out_fname = "stdout";
2186   else if (! freopen (out_fname, "w", stdout))
2187     pfatal_with_name (out_fname);
2188
2189   output_line_directive (fp, &outbuf, 0, same_file);
2190
2191   /* Scan the -include files before the main input.  */
2192
2193   no_record_file++;
2194   for (i = 1; i < argc; i++)
2195     if (pend_includes[i]) {
2196       struct include_file *inc;
2197       int fd = open_include_file (pend_includes[i], NULL_PTR, NULL_PTR, &inc);
2198       if (fd < 0) {
2199         perror_with_name (pend_includes[i]);
2200         return FATAL_EXIT_CODE;
2201       }
2202       finclude (fd, inc, &outbuf, 0, NULL_PTR);
2203     }
2204   no_record_file--;
2205
2206   /* Scan the input, processing macros and directives.  */
2207
2208   rescan (&outbuf, 0);
2209
2210   if (missing_newline)
2211     fp->lineno--;
2212
2213   if (pedantic && missing_newline)
2214     pedwarn ("file does not end in newline");
2215
2216   /* Now we have processed the entire input
2217      Write whichever kind of output has been requested.  */
2218
2219   if (dump_macros == dump_only)
2220     dump_all_macros ();
2221   else if (! inhibit_output) {
2222     write_output ();
2223   }
2224
2225   if (print_deps) {
2226     /* Don't actually write the deps file if compilation has failed.  */
2227     if (errors == 0) {
2228       if (deps_file && ! (deps_stream = fopen (deps_file, deps_mode)))
2229         pfatal_with_name (deps_file);
2230       fputs (deps_buffer, deps_stream);
2231       putc ('\n', deps_stream);
2232       if (deps_file) {
2233         if (ferror (deps_stream) || fclose (deps_stream) != 0)
2234           fatal ("I/O error on output");
2235       }
2236     }
2237   }
2238
2239   if (pcp_outfile && pcp_outfile != stdout
2240       && (ferror (pcp_outfile) || fclose (pcp_outfile) != 0))
2241     fatal ("I/O error on `-pcp' output");
2242
2243   if (ferror (stdout) || fclose (stdout) != 0)
2244     fatal ("I/O error on output");
2245
2246   if (errors)
2247     exit (FATAL_EXIT_CODE);
2248   exit (SUCCESS_EXIT_CODE);
2249
2250  perror:
2251   pfatal_with_name (in_fname);
2252   return 0;
2253 }
2254 \f
2255 /* Given a colon-separated list of file names PATH,
2256    add all the names to the search path for include files.  */
2257
2258 static void
2259 path_include (path)
2260      char *path;
2261 {
2262   char *p;
2263
2264   p = path;
2265
2266   if (*p)
2267     while (1) {
2268       char *q = p;
2269       char c;
2270       struct file_name_list *dirtmp;
2271
2272       /* Find the end of this name.  */
2273       while ((c = *q++) != PATH_SEPARATOR && c)
2274         continue;
2275
2276       q[-1] = 0;
2277       dirtmp = new_include_prefix (last_include, NULL_PTR,
2278                                    "", p == q ? "." : p);
2279       q[-1] = c;
2280       append_include_chain (dirtmp, dirtmp);
2281
2282       /* Advance past this name.  */
2283       p = q;
2284       if (! c)
2285         break;
2286     }
2287 }
2288 \f
2289 /* Return the address of the first character in S that equals C.
2290    S is an array of length N, possibly containing '\0's, and followed by '\0'.
2291    Return 0 if there is no such character.  Assume that C itself is not '\0'.
2292    If we knew we could use memchr, we could just invoke memchr (S, C, N),
2293    but unfortunately memchr isn't autoconfigured yet.  */
2294
2295 static U_CHAR *
2296 index0 (s, c, n)
2297      U_CHAR *s;
2298      int c;
2299      size_t n;
2300 {
2301   char *p = (char *) s;
2302   for (;;) {
2303     char *q = index (p, c);
2304     if (q)
2305       return (U_CHAR *) q;
2306     else {
2307       size_t l = strlen (p);
2308       if (l == n)
2309         return 0;
2310       l++;
2311       p += l;
2312       n -= l;
2313     }
2314   }
2315 }
2316 \f
2317 /* Pre-C-Preprocessor to translate ANSI trigraph idiocy in BUF
2318    before main CCCP processing.  Name `pcp' is also in honor of the
2319    drugs the trigraph designers must have been on.
2320
2321    Using an extra pass through the buffer takes a little extra time,
2322    but is infinitely less hairy than trying to handle trigraphs inside
2323    strings, etc. everywhere, and also makes sure that trigraphs are
2324    only translated in the top level of processing.  */
2325
2326 static void
2327 trigraph_pcp (buf)
2328      FILE_BUF *buf;
2329 {
2330   register U_CHAR c, *fptr, *bptr, *sptr, *lptr;
2331   int len;
2332
2333   fptr = bptr = sptr = buf->buf;
2334   lptr = fptr + buf->length;
2335   while ((sptr = index0 (sptr, '?', (size_t) (lptr - sptr))) != NULL) {
2336     if (*++sptr != '?')
2337       continue;
2338     switch (*++sptr) {
2339       case '=':
2340       c = '#';
2341       break;
2342     case '(':
2343       c = '[';
2344       break;
2345     case '/':
2346       c = '\\';
2347       break;
2348     case ')':
2349       c = ']';
2350       break;
2351     case '\'':
2352       c = '^';
2353       break;
2354     case '<':
2355       c = '{';
2356       break;
2357     case '!':
2358       c = '|';
2359       break;
2360     case '>':
2361       c = '}';
2362       break;
2363     case '-':
2364       c  = '~';
2365       break;
2366     case '?':
2367       sptr--;
2368       continue;
2369     default:
2370       continue;
2371     }
2372     len = sptr - fptr - 2;
2373
2374     /* BSD doc says bcopy () works right for overlapping strings.  In ANSI
2375        C, this will be memmove ().  */
2376     if (bptr != fptr && len > 0)
2377       bcopy ((char *) fptr, (char *) bptr, len);
2378
2379     bptr += len;
2380     *bptr++ = c;
2381     fptr = ++sptr;
2382   }
2383   len = buf->length - (fptr - buf->buf);
2384   if (bptr != fptr && len > 0)
2385     bcopy ((char *) fptr, (char *) bptr, len);
2386   buf->length -= fptr - bptr;
2387   buf->buf[buf->length] = '\0';
2388   if (warn_trigraphs && fptr != bptr)
2389     warning_with_line (0, "%lu trigraph(s) encountered",
2390                        (unsigned long) (fptr - bptr) / 2);
2391 }
2392 \f
2393 /* Move all backslash-newline pairs out of embarrassing places.
2394    Exchange all such pairs following BP
2395    with any potentially-embarrassing characters that follow them.
2396    Potentially-embarrassing characters are / and *
2397    (because a backslash-newline inside a comment delimiter
2398    would cause it not to be recognized).  */
2399
2400 static void
2401 newline_fix (bp)
2402      U_CHAR *bp;
2403 {
2404   register U_CHAR *p = bp;
2405
2406   /* First count the backslash-newline pairs here.  */
2407
2408   while (p[0] == '\\' && p[1] == '\n')
2409     p += 2;
2410
2411   /* What follows the backslash-newlines is not embarrassing.  */
2412
2413   if (*p != '/' && *p != '*')
2414     return;
2415
2416   /* Copy all potentially embarrassing characters
2417      that follow the backslash-newline pairs
2418      down to where the pairs originally started.  */
2419
2420   while (*p == '*' || *p == '/')
2421     *bp++ = *p++;
2422
2423   /* Now write the same number of pairs after the embarrassing chars.  */
2424   while (bp < p) {
2425     *bp++ = '\\';
2426     *bp++ = '\n';
2427   }
2428 }
2429
2430 /* Like newline_fix but for use within a directive-name.
2431    Move any backslash-newlines up past any following symbol constituents.  */
2432
2433 static void
2434 name_newline_fix (bp)
2435      U_CHAR *bp;
2436 {
2437   register U_CHAR *p = bp;
2438
2439   /* First count the backslash-newline pairs here.  */
2440   while (p[0] == '\\' && p[1] == '\n')
2441     p += 2;
2442
2443   /* What follows the backslash-newlines is not embarrassing.  */
2444
2445   if (!is_idchar[*p])
2446     return;
2447
2448   /* Copy all potentially embarrassing characters
2449      that follow the backslash-newline pairs
2450      down to where the pairs originally started.  */
2451
2452   while (is_idchar[*p])
2453     *bp++ = *p++;
2454
2455   /* Now write the same number of pairs after the embarrassing chars.  */
2456   while (bp < p) {
2457     *bp++ = '\\';
2458     *bp++ = '\n';
2459   }
2460 }
2461 \f
2462 /* Look for lint commands in comments.
2463
2464    When we come in here, ibp points into a comment.  Limit is as one expects.
2465    scan within the comment -- it should start, after lwsp, with a lint command.
2466    If so that command is returned as a (constant) string.
2467
2468    Upon return, any arg will be pointed to with argstart and will be
2469    arglen long.  Note that we don't parse that arg since it will just
2470    be printed out again.  */
2471
2472 static char *
2473 get_lintcmd (ibp, limit, argstart, arglen, cmdlen)
2474      register U_CHAR *ibp;
2475      register U_CHAR *limit;
2476      U_CHAR **argstart;         /* point to command arg */
2477      int *arglen, *cmdlen;      /* how long they are */
2478 {
2479   HOST_WIDE_INT linsize;
2480   register U_CHAR *numptr;      /* temp for arg parsing */
2481
2482   *arglen = 0;
2483
2484   SKIP_WHITE_SPACE (ibp);
2485
2486   if (ibp >= limit) return NULL;
2487
2488   linsize = limit - ibp;
2489   
2490   /* Oh, I wish C had lexical functions... hell, I'll just open-code the set */
2491   if ((linsize >= 10) && !bcmp (ibp, "NOTREACHED", 10)) {
2492     *cmdlen = 10;
2493     return "NOTREACHED";
2494   }
2495   if ((linsize >= 8) && !bcmp (ibp, "ARGSUSED", 8)) {
2496     *cmdlen = 8;
2497     return "ARGSUSED";
2498   }
2499   if ((linsize >= 11) && !bcmp (ibp, "LINTLIBRARY", 11)) {
2500     *cmdlen = 11;
2501     return "LINTLIBRARY";
2502   }
2503   if ((linsize >= 7) && !bcmp (ibp, "VARARGS", 7)) {
2504     *cmdlen = 7;
2505     ibp += 7; linsize -= 7;
2506     if ((linsize == 0) || ! isdigit (*ibp)) return "VARARGS";
2507
2508     /* OK, read a number */
2509     for (numptr = *argstart = ibp; (numptr < limit) && isdigit (*numptr);
2510          numptr++);
2511     *arglen = numptr - *argstart;
2512     return "VARARGS";
2513   }
2514   return NULL;
2515 }
2516 \f
2517 /*
2518  * The main loop of the program.
2519  *
2520  * Read characters from the input stack, transferring them to the
2521  * output buffer OP.
2522  *
2523  * Macros are expanded and push levels on the input stack.
2524  * At the end of such a level it is popped off and we keep reading.
2525  * At the end of any other kind of level, we return.
2526  * #-directives are handled, except within macros.
2527  *
2528  * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
2529  * and insert them when appropriate.  This is set while scanning macro
2530  * arguments before substitution.  It is zero when scanning for final output.
2531  *   There are three types of Newline markers:
2532  *   * Newline -  follows a macro name that was not expanded
2533  *     because it appeared inside an expansion of the same macro.
2534  *     This marker prevents future expansion of that identifier.
2535  *     When the input is rescanned into the final output, these are deleted.
2536  *     These are also deleted by ## concatenation.
2537  *   * Newline Space (or Newline and any other whitespace character)
2538  *     stands for a place that tokens must be separated or whitespace
2539  *     is otherwise desirable, but where the ANSI standard specifies there
2540  *     is no whitespace.  This marker turns into a Space (or whichever other
2541  *     whitespace char appears in the marker) in the final output,
2542  *     but it turns into nothing in an argument that is stringified with #.
2543  *     Such stringified arguments are the only place where the ANSI standard
2544  *     specifies with precision that whitespace may not appear.
2545  *
2546  * During this function, IP->bufp is kept cached in IBP for speed of access.
2547  * Likewise, OP->bufp is kept in OBP.  Before calling a subroutine
2548  * IBP, IP and OBP must be copied back to memory.  IP and IBP are
2549  * copied back with the RECACHE macro.  OBP must be copied back from OP->bufp
2550  * explicitly, and before RECACHE, since RECACHE uses OBP.
2551  */
2552
2553 static void
2554 rescan (op, output_marks)
2555      FILE_BUF *op;
2556      int output_marks;
2557 {
2558   /* Character being scanned in main loop.  */
2559   register U_CHAR c;
2560
2561   /* Length of pending accumulated identifier.  */
2562   register int ident_length = 0;
2563
2564   /* Hash code of pending accumulated identifier.  */
2565   register int hash = 0;
2566
2567   /* Current input level (&instack[indepth]).  */
2568   FILE_BUF *ip;
2569
2570   /* Pointer for scanning input.  */
2571   register U_CHAR *ibp;
2572
2573   /* Pointer to end of input.  End of scan is controlled by LIMIT.  */
2574   register U_CHAR *limit;
2575
2576   /* Pointer for storing output.  */
2577   register U_CHAR *obp;
2578
2579   /* REDO_CHAR is nonzero if we are processing an identifier
2580      after backing up over the terminating character.
2581      Sometimes we process an identifier without backing up over
2582      the terminating character, if the terminating character
2583      is not special.  Backing up is done so that the terminating character
2584      will be dispatched on again once the identifier is dealt with.  */
2585   int redo_char = 0;
2586
2587   /* 1 if within an identifier inside of which a concatenation
2588      marker (Newline -) has been seen.  */
2589   int concatenated = 0;
2590
2591   /* While scanning a comment or a string constant,
2592      this records the line it started on, for error messages.  */
2593   int start_line;
2594
2595   /* Record position of last `real' newline.  */
2596   U_CHAR *beg_of_line;
2597
2598 /* Pop the innermost input stack level, assuming it is a macro expansion.  */
2599
2600 #define POPMACRO \
2601 do { ip->macro->type = T_MACRO;         \
2602      if (ip->free_ptr) free (ip->free_ptr);     \
2603      --indepth; } while (0)
2604
2605 /* Reload `rescan's local variables that describe the current
2606    level of the input stack.  */
2607
2608 #define RECACHE  \
2609 do { ip = &instack[indepth];            \
2610      ibp = ip->bufp;                    \
2611      limit = ip->buf + ip->length;      \
2612      op->bufp = obp;                    \
2613      check_expand (op, limit - ibp);    \
2614      beg_of_line = 0;                   \
2615      obp = op->bufp; } while (0)
2616
2617   if (no_output && instack[indepth].fname != 0)
2618     skip_if_group (&instack[indepth], 1, NULL);
2619
2620   obp = op->bufp;
2621   RECACHE;
2622
2623   beg_of_line = ibp;
2624
2625   /* Our caller must always put a null after the end of
2626      the input at each input stack level.  */
2627   if (*limit != 0)
2628     abort ();
2629
2630   while (1) {
2631     c = *ibp++;
2632     *obp++ = c;
2633
2634     switch (c) {
2635     case '\\':
2636       if (*ibp == '\n' && !ip->macro) {
2637         /* At the top level, always merge lines ending with backslash-newline,
2638            even in middle of identifier.  But do not merge lines in a macro,
2639            since backslash might be followed by a newline-space marker.  */
2640         ++ibp;
2641         ++ip->lineno;
2642         --obp;          /* remove backslash from obuf */
2643         break;
2644       }
2645       /* If ANSI, backslash is just another character outside a string.  */
2646       if (!traditional)
2647         goto randomchar;
2648       /* Otherwise, backslash suppresses specialness of following char,
2649          so copy it here to prevent the switch from seeing it.
2650          But first get any pending identifier processed.  */
2651       if (ident_length > 0)
2652         goto specialchar;
2653       if (ibp < limit)
2654         *obp++ = *ibp++;
2655       break;
2656
2657     case '%':
2658       if (ident_length || ip->macro || traditional)
2659         goto randomchar;
2660       while (*ibp == '\\' && ibp[1] == '\n') {
2661         ibp += 2;
2662         ++ip->lineno;
2663       }
2664       if (*ibp != ':')
2665         break;
2666       /* Treat this %: digraph as if it were #.  */
2667       /* Fall through.  */
2668
2669     case '#':
2670       if (assertions_flag) {
2671         if (ident_length)
2672           goto specialchar;
2673         /* Copy #foo (bar lose) without macro expansion.  */
2674         obp[-1] = '#';  /* In case it was '%'.  */
2675         SKIP_WHITE_SPACE (ibp);
2676         while (is_idchar[*ibp])
2677           *obp++ = *ibp++;
2678         SKIP_WHITE_SPACE (ibp);
2679         if (*ibp == '(') {
2680           ip->bufp = ibp;
2681           skip_paren_group (ip);
2682           bcopy ((char *) ibp, (char *) obp, ip->bufp - ibp);
2683           obp += ip->bufp - ibp;
2684           ibp = ip->bufp;
2685         }
2686         break;
2687       }
2688
2689       /* If this is expanding a macro definition, don't recognize
2690          preprocessing directives.  */
2691       if (ip->macro != 0)
2692         goto randomchar;
2693       /* If this is expand_into_temp_buffer,
2694          don't recognize them either.  Warn about them
2695          only after an actual newline at this level,
2696          not at the beginning of the input level.  */
2697       if (! ip->fname) {
2698         if (ip->buf != beg_of_line)
2699           warning ("preprocessing directive not recognized within macro arg");
2700         goto randomchar;
2701       }
2702       if (ident_length)
2703         goto specialchar;
2704
2705       
2706       /* # keyword: a # must be first nonblank char on the line */
2707       if (beg_of_line == 0)
2708         goto randomchar;
2709       {
2710         U_CHAR *bp;
2711
2712         /* Scan from start of line, skipping whitespace, comments
2713            and backslash-newlines, and see if we reach this #.
2714            If not, this # is not special.  */
2715         bp = beg_of_line;
2716         /* If -traditional, require # to be at beginning of line.  */
2717         if (!traditional) {
2718           while (1) {
2719             if (is_hor_space[*bp])
2720               bp++;
2721             else if (*bp == '\\' && bp[1] == '\n')
2722               bp += 2;
2723             else if (*bp == '/' && bp[1] == '*') {
2724               bp += 2;
2725               while (!(*bp == '*' && bp[1] == '/'))
2726                 bp++;
2727               bp += 2;
2728             }
2729             /* There is no point in trying to deal with C++ // comments here,
2730                because if there is one, then this # must be part of the
2731                comment and we would never reach here.  */
2732             else break;
2733           }
2734           if (c == '%') {
2735             if (bp[0] != '%')
2736               break;
2737             while (bp[1] == '\\' && bp[2] == '\n')
2738               bp += 2;
2739             if (bp + 1 != ibp)
2740               break;
2741             /* %: appears at start of line; skip past the ':' too.  */
2742             bp++;
2743             ibp++;
2744           }
2745         }
2746         if (bp + 1 != ibp)
2747           goto randomchar;
2748       }
2749
2750       /* This # can start a directive.  */
2751
2752       --obp;            /* Don't copy the '#' */
2753
2754       ip->bufp = ibp;
2755       op->bufp = obp;
2756       if (! handle_directive (ip, op)) {
2757 #ifdef USE_C_ALLOCA
2758         alloca (0);
2759 #endif
2760         /* Not a known directive: treat it as ordinary text.
2761            IP, OP, IBP, etc. have not been changed.  */
2762         if (no_output && instack[indepth].fname) {
2763           /* If not generating expanded output,
2764              what we do with ordinary text is skip it.
2765              Discard everything until next # directive.  */
2766           skip_if_group (&instack[indepth], 1, 0);
2767           RECACHE;
2768           beg_of_line = ibp;
2769           break;
2770         }
2771         *obp++ = '#';   /* Copy # (even if it was originally %:).  */
2772         /* Don't expand an identifier that could be a macro directive.
2773            (Section 3.8.3 of the ANSI C standard)                       */
2774         SKIP_WHITE_SPACE (ibp);
2775         if (is_idstart[*ibp])
2776           {
2777             *obp++ = *ibp++;
2778             while (is_idchar[*ibp])
2779               *obp++ = *ibp++;
2780           }
2781         goto randomchar;
2782       }
2783 #ifdef USE_C_ALLOCA
2784       alloca (0);
2785 #endif
2786       /* A # directive has been successfully processed.  */
2787       /* If not generating expanded output, ignore everything until
2788          next # directive.  */
2789       if (no_output && instack[indepth].fname)
2790         skip_if_group (&instack[indepth], 1, 0);
2791       obp = op->bufp;
2792       RECACHE;
2793       beg_of_line = ibp;
2794       break;
2795
2796     case '\"':                  /* skip quoted string */
2797     case '\'':
2798       /* A single quoted string is treated like a double -- some
2799          programs (e.g., troff) are perverse this way */
2800
2801       /* Handle any pending identifier;
2802          but the L in L'...' or L"..." is not an identifier.  */
2803       if (ident_length) {
2804         if (! (ident_length == 1 && hash == HASHSTEP (0, 'L')))
2805           goto specialchar;
2806         ident_length = hash = 0;
2807       }
2808
2809       start_line = ip->lineno;
2810
2811       /* Skip ahead to a matching quote.  */
2812
2813       while (1) {
2814         if (ibp >= limit) {
2815           if (ip->macro != 0) {
2816             /* try harder: this string crosses a macro expansion boundary.
2817                This can happen naturally if -traditional.
2818                Otherwise, only -D can make a macro with an unmatched quote.  */
2819             POPMACRO;
2820             RECACHE;
2821             continue;
2822           }
2823           if (!traditional) {
2824             error_with_line (line_for_error (start_line),
2825                              "unterminated string or character constant");
2826             if (multiline_string_line) {
2827               error_with_line (multiline_string_line,
2828                                "possible real start of unterminated constant");
2829               multiline_string_line = 0;
2830             }
2831           }
2832           break;
2833         }
2834         *obp++ = *ibp;
2835         switch (*ibp++) {
2836         case '\n':
2837           ++ip->lineno;
2838           ++op->lineno;
2839           /* Traditionally, end of line ends a string constant with no error.
2840              So exit the loop and record the new line.  */
2841           if (traditional) {
2842             beg_of_line = ibp;
2843             goto while2end;
2844           }
2845           if (c == '\'') {
2846             error_with_line (line_for_error (start_line),
2847                              "unterminated character constant");
2848             goto while2end;
2849           }
2850           if (multiline_string_line == 0) {
2851             if (pedantic)
2852               pedwarn_with_line (line_for_error (start_line),
2853                                  "string constant runs past end of line");
2854             multiline_string_line = ip->lineno - 1;
2855           }
2856           break;
2857
2858         case '\\':
2859           if (*ibp == '\n') {
2860             /* Backslash newline is replaced by nothing at all, but
2861                keep the line counts correct.  But if we are reading
2862                from a macro, keep the backslash newline, since backslash
2863                newlines have already been processed.  */
2864             if (ip->macro)
2865               *obp++ = '\n';
2866             else
2867               --obp;
2868             ++ibp;
2869             ++ip->lineno;
2870           } else {
2871             /* ANSI stupidly requires that in \\ the second \
2872                is *not* prevented from combining with a newline.  */
2873             if (!ip->macro) {
2874               while (*ibp == '\\' && ibp[1] == '\n') {
2875                 ibp += 2;
2876                 ++ip->lineno;
2877               }
2878             }
2879             *obp++ = *ibp++;
2880           }
2881           break;
2882
2883         case '\"':
2884         case '\'':
2885           if (ibp[-1] == c)
2886             goto while2end;
2887           break;
2888         }
2889       }
2890     while2end:
2891       break;
2892
2893     case '/':
2894       if (ip->macro != 0)
2895         goto randomchar;
2896       if (*ibp == '\\' && ibp[1] == '\n')
2897         newline_fix (ibp);
2898       if (*ibp != '*'
2899           && !(cplusplus_comments && *ibp == '/'))
2900         goto randomchar;
2901       if (ident_length)
2902         goto specialchar;
2903
2904       if (*ibp == '/') {
2905         /* C++ style comment...  */
2906         start_line = ip->lineno;
2907
2908         /* Comments are equivalent to spaces.  */
2909         if (! put_out_comments)
2910           obp[-1] = ' ';
2911
2912         {
2913           U_CHAR *before_bp = ibp;
2914
2915           while (++ibp < limit) {
2916             if (*ibp == '\n') {
2917               if (ibp[-1] != '\\') {
2918                 if (put_out_comments) {
2919                   bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
2920                   obp += ibp - before_bp;
2921                 }
2922                 break;
2923               }
2924               if (warn_comments)
2925                 warning ("multiline `//' comment");
2926               ++ip->lineno;
2927               /* Copy the newline into the output buffer, in order to
2928                  avoid the pain of a #line every time a multiline comment
2929                  is seen.  */
2930               if (!put_out_comments)
2931                 *obp++ = '\n';
2932               ++op->lineno;
2933             }
2934           }
2935           break;
2936         }
2937       }
2938
2939       /* Ordinary C comment.  Skip it, optionally copying it to output.  */
2940
2941       start_line = ip->lineno;
2942
2943       ++ibp;                    /* Skip the star.  */
2944
2945       /* If this cpp is for lint, we peek inside the comments: */
2946       if (for_lint) {
2947         U_CHAR *argbp;
2948         int cmdlen, arglen;
2949         char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
2950
2951         if (lintcmd != NULL) {
2952           op->bufp = obp;
2953           check_expand (op, cmdlen + arglen + 14);
2954           obp = op->bufp;
2955           /* I believe it is always safe to emit this newline: */
2956           obp[-1] = '\n';
2957           bcopy ("#pragma lint ", (char *) obp, 13);
2958           obp += 13;
2959           bcopy (lintcmd, (char *) obp, cmdlen);
2960           obp += cmdlen;
2961
2962           if (arglen != 0) {
2963             *(obp++) = ' ';
2964             bcopy (argbp, (char *) obp, arglen);
2965             obp += arglen;
2966           }
2967
2968           /* OK, now bring us back to the state we were in before we entered
2969              this branch.  We need #line because the #pragma's newline always
2970              messes up the line count.  */
2971           op->bufp = obp;
2972           output_line_directive (ip, op, 0, same_file);
2973           check_expand (op, limit - ibp + 2);
2974           obp = op->bufp;
2975           *(obp++) = '/';
2976         }
2977       }
2978
2979       /* Comments are equivalent to spaces.
2980          Note that we already output the slash; we might not want it.
2981          For -traditional, a comment is equivalent to nothing.  */
2982       if (! put_out_comments) {
2983         if (traditional)
2984           obp--;
2985         else
2986           obp[-1] = ' ';
2987       }
2988       else
2989         *obp++ = '*';
2990
2991       {
2992         U_CHAR *before_bp = ibp;
2993
2994         for (;;) {
2995           switch (*ibp++) {
2996           case '*':
2997             if (ibp[-2] == '/' && warn_comments)
2998               warning ("`/*' within comment");
2999             if (*ibp == '\\' && ibp[1] == '\n')
3000               newline_fix (ibp);
3001             if (*ibp == '/')
3002               goto comment_end;
3003             break;
3004
3005           case '\n':
3006             ++ip->lineno;
3007             /* Copy the newline into the output buffer, in order to
3008                avoid the pain of a #line every time a multiline comment
3009                is seen.  */
3010             if (!put_out_comments)
3011               *obp++ = '\n';
3012             ++op->lineno;
3013             break;
3014
3015           case 0:
3016             if (limit < ibp) {
3017               error_with_line (line_for_error (start_line),
3018                                "unterminated comment");
3019               goto limit_reached;
3020             }
3021             break;
3022           }
3023         }
3024       comment_end:
3025
3026         ibp++;
3027         if (put_out_comments) {
3028           bcopy ((char *) before_bp, (char *) obp, ibp - before_bp);
3029           obp += ibp - before_bp;
3030         }
3031       }
3032       break;
3033
3034     case '$':
3035       if (! is_idchar['$'])
3036         goto randomchar;
3037       if (pedantic)
3038         pedwarn ("`$' in identifier");
3039       goto letter;
3040
3041     case '0': case '1': case '2': case '3': case '4':
3042     case '5': case '6': case '7': case '8': case '9':
3043       /* If digit is not part of identifier, it starts a number,
3044          which means that following letters are not an identifier.
3045          "0x5" does not refer to an identifier "x5".
3046          So copy all alphanumerics that follow without accumulating
3047          as an identifier.  Periods also, for sake of "3.e7".  */
3048
3049       if (ident_length == 0) {
3050         for (;;) {
3051           if (!ip->macro) {
3052             while (ibp[0] == '\\' && ibp[1] == '\n') {
3053               ++ip->lineno;
3054               ibp += 2;
3055             }
3056           }
3057           c = *ibp++;
3058           if (!is_idchar[c] && c != '.') {
3059             --ibp;
3060             break;
3061           }
3062           *obp++ = c;
3063           /* A sign can be part of a preprocessing number
3064              if it follows an `e' or `p'.  */
3065           if (c == 'e' || c == 'E' || c == 'p' || c == 'P') {
3066             if (!ip->macro) {
3067               while (ibp[0] == '\\' && ibp[1] == '\n') {
3068                 ++ip->lineno;
3069                 ibp += 2;
3070               }
3071             }
3072             if (*ibp == '+' || *ibp == '-') {
3073               *obp++ = *ibp++;
3074               /* But traditional C does not let the token go past the sign,
3075                  and C89 does not allow `p'.  */
3076               if (traditional || (c89 && (c == 'p' || c == 'P')))
3077                 break;
3078             }
3079           }
3080         }
3081         break;
3082       }
3083       /* fall through */
3084
3085     case '_':
3086     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3087     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
3088     case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
3089     case 's': case 't': case 'u': case 'v': case 'w': case 'x':
3090     case 'y': case 'z':
3091     case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3092     case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
3093     case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
3094     case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
3095     case 'Y': case 'Z':
3096     letter:
3097       ident_length++;
3098       /* Compute step of hash function, to avoid a proc call on every token */
3099       hash = HASHSTEP (hash, c);
3100       break;
3101
3102     case '\n':
3103       if (ip->fname == 0 && *ibp == '-') {
3104         /* Newline - inhibits expansion of preceding token.
3105            If expanding a macro arg, we keep the newline -.
3106            In final output, it is deleted.
3107            We recognize Newline - in macro bodies and macro args.  */
3108         if (! concatenated) {
3109           ident_length = 0;
3110           hash = 0;
3111         }
3112         ibp++;
3113         if (!output_marks) {
3114           obp--;
3115         } else {
3116           /* If expanding a macro arg, keep the newline -.  */
3117           *obp++ = '-';
3118         }
3119         break;
3120       }
3121
3122       /* If reprocessing a macro expansion, newline is a special marker.  */
3123       else if (ip->macro != 0) {
3124         /* Newline White is a "funny space" to separate tokens that are
3125            supposed to be separate but without space between.
3126            Here White means any whitespace character.
3127            Newline - marks a recursive macro use that is not
3128            supposed to be expandable.  */
3129
3130         if (is_space[*ibp]) {
3131           /* Newline Space does not prevent expansion of preceding token
3132              so expand the preceding token and then come back.  */
3133           if (ident_length > 0)
3134             goto specialchar;
3135
3136           /* If generating final output, newline space makes a space.  */
3137           if (!output_marks) {
3138             obp[-1] = *ibp++;
3139             /* And Newline Newline makes a newline, so count it.  */
3140             if (obp[-1] == '\n')
3141               op->lineno++;
3142           } else {
3143             /* If expanding a macro arg, keep the newline space.
3144                If the arg gets stringified, newline space makes nothing.  */
3145             *obp++ = *ibp++;
3146           }
3147         } else abort ();        /* Newline followed by something random?  */
3148         break;
3149       }
3150
3151       /* If there is a pending identifier, handle it and come back here.  */
3152       if (ident_length > 0)
3153         goto specialchar;
3154
3155       beg_of_line = ibp;
3156
3157       /* Update the line counts and output a #line if necessary.  */
3158       ++ip->lineno;
3159       ++op->lineno;
3160       if (ip->lineno != op->lineno) {
3161         op->bufp = obp;
3162         output_line_directive (ip, op, 1, same_file);
3163         check_expand (op, limit - ibp);
3164         obp = op->bufp;
3165       }
3166       break;
3167
3168       /* Come here either after (1) a null character that is part of the input
3169          or (2) at the end of the input, because there is a null there.  */
3170     case 0:
3171       if (ibp <= limit)
3172         /* Our input really contains a null character.  */
3173         goto randomchar;
3174
3175     limit_reached:
3176       /* At end of a macro-expansion level, pop it and read next level.  */
3177       if (ip->macro != 0) {
3178         obp--;
3179         ibp--;
3180         /* If traditional, and we have an identifier that ends here,
3181            process it now, so we get the right error for recursion.  */
3182         if (traditional && ident_length
3183             && ! is_idchar[*instack[indepth - 1].bufp]) {
3184           redo_char = 1;
3185           goto randomchar;
3186         }
3187         POPMACRO;
3188         RECACHE;
3189         break;
3190       }
3191
3192       /* If we don't have a pending identifier,
3193          return at end of input.  */
3194       if (ident_length == 0) {
3195         obp--;
3196         ibp--;
3197         op->bufp = obp;
3198         ip->bufp = ibp;
3199         goto ending;
3200       }
3201
3202       /* If we do have a pending identifier, just consider this null
3203          a special character and arrange to dispatch on it again.
3204          The second time, IDENT_LENGTH will be zero so we will return.  */
3205
3206       /* Fall through */
3207
3208 specialchar:
3209
3210       /* Handle the case of a character such as /, ', " or null
3211          seen following an identifier.  Back over it so that
3212          after the identifier is processed the special char
3213          will be dispatched on again.  */
3214
3215       ibp--;
3216       obp--;
3217       redo_char = 1;
3218
3219     default:
3220
3221 randomchar:
3222
3223       if (ident_length > 0) {
3224         register HASHNODE *hp;
3225
3226         /* We have just seen an identifier end.  If it's a macro, expand it.
3227
3228            IDENT_LENGTH is the length of the identifier
3229            and HASH is its hash code.
3230
3231            The identifier has already been copied to the output,
3232            so if it is a macro we must remove it.
3233
3234            If REDO_CHAR is 0, the char that terminated the identifier
3235            has been skipped in the output and the input.
3236            OBP-IDENT_LENGTH-1 points to the identifier.
3237            If the identifier is a macro, we must back over the terminator.
3238
3239            If REDO_CHAR is 1, the terminating char has already been
3240            backed over.  OBP-IDENT_LENGTH points to the identifier.  */
3241
3242         if (!pcp_outfile || pcp_inside_if) {
3243           for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
3244                hp = hp->next) {
3245             
3246             if (hp->length == ident_length) {
3247               int obufp_before_macroname;
3248               int op_lineno_before_macroname;
3249               register int i = ident_length;
3250               register U_CHAR *p = hp->name;
3251               register U_CHAR *q = obp - i;
3252               int disabled;
3253               
3254               if (! redo_char)
3255                 q--;
3256               
3257               do {              /* All this to avoid a strncmp () */
3258                 if (*p++ != *q++)
3259                   goto hashcollision;
3260               } while (--i);
3261               
3262               /* We found a use of a macro name.
3263                  see if the context shows it is a macro call.  */
3264               
3265               /* Back up over terminating character if not already done.  */
3266               if (! redo_char) {
3267                 ibp--;
3268                 obp--;
3269               }
3270               
3271               /* Save this as a displacement from the beginning of the output
3272                  buffer.  We can not save this as a position in the output
3273                  buffer, because it may get realloc'ed by RECACHE.  */
3274               obufp_before_macroname = (obp - op->buf) - ident_length;
3275               op_lineno_before_macroname = op->lineno;
3276               
3277               if (hp->type == T_PCSTRING) {
3278                 pcstring_used (hp); /* Mark the definition of this key
3279                                        as needed, ensuring that it
3280                                        will be output.  */
3281                 break;          /* Exit loop, since the key cannot have a
3282                                    definition any longer.  */
3283               }
3284
3285               /* Record whether the macro is disabled.  */
3286               disabled = hp->type == T_DISABLED;
3287               
3288               /* This looks like a macro ref, but if the macro was disabled,
3289                  just copy its name and put in a marker if requested.  */
3290               
3291               if (disabled) {
3292 #if 0
3293                 /* This error check caught useful cases such as
3294                    #define foo(x,y) bar (x (y,0), y)
3295                    foo (foo, baz)  */
3296                 if (traditional)
3297                   error ("recursive use of macro `%s'", hp->name);
3298 #endif
3299                 
3300                 if (output_marks) {
3301                   check_expand (op, limit - ibp + 2);
3302                   *obp++ = '\n';
3303                   *obp++ = '-';
3304                 }
3305                 break;
3306               }
3307               
3308               /* If macro wants an arglist, verify that a '(' follows.
3309                  first skip all whitespace, copying it to the output
3310                  after the macro name.  Then, if there is no '(',
3311                  decide this is not a macro call and leave things that way.  */
3312               if ((hp->type == T_MACRO || hp->type == T_DISABLED)
3313                   && hp->value.defn->nargs >= 0)
3314                 {
3315                   U_CHAR *old_ibp = ibp;
3316                   U_CHAR *old_obp = obp;
3317                   int old_iln = ip->lineno;
3318                   int old_oln = op->lineno;
3319                   
3320                   while (1) {
3321                     /* Scan forward over whitespace, copying it to the output.  */
3322                     if (ibp == limit && ip->macro != 0) {
3323                       POPMACRO;
3324                       RECACHE;
3325                       old_ibp = ibp;
3326                       old_obp = obp;
3327                       old_iln = ip->lineno;
3328                       old_oln = op->lineno;
3329                     }
3330                     else if (is_space[*ibp]) {
3331                       *obp++ = *ibp++;
3332                       if (ibp[-1] == '\n') {
3333                         if (ip->macro == 0) {
3334                           /* Newline in a file.  Count it.  */
3335                           ++ip->lineno;
3336                           ++op->lineno;
3337                         } else if (!output_marks) {
3338                           /* A newline mark, and we don't want marks
3339                              in the output.  If it is newline-hyphen,
3340                              discard it entirely.  Otherwise, it is
3341                              newline-whitechar, so keep the whitechar.  */
3342                           obp--;
3343                           if (*ibp == '-')
3344                             ibp++;
3345                           else {
3346                             if (*ibp == '\n')
3347                               ++op->lineno;
3348                             *obp++ = *ibp++;
3349                           }
3350                         } else {
3351                           /* A newline mark; copy both chars to the output.  */
3352                           *obp++ = *ibp++;
3353                         }
3354                       }
3355                     }
3356                     else if (ip->macro)
3357                       break;
3358                     else if (*ibp == '/') {
3359                       /* If a comment, copy it unchanged or discard it.  */
3360                       if (ibp[1] == '\\' && ibp[2] == '\n')
3361                         newline_fix (ibp + 1);
3362                       if (ibp[1] == '*') {
3363                         if (put_out_comments) {
3364                           *obp++ = '/';
3365                           *obp++ = '*';
3366                         } else if (! traditional) {
3367                           *obp++ = ' ';
3368                         }
3369                         for (ibp += 2; ibp < limit; ibp++) {
3370                           /* We need not worry about newline-marks,
3371                              since they are never found in comments.  */
3372                           if (ibp[0] == '*') {
3373                             if (ibp[1] == '\\' && ibp[2] == '\n')
3374                               newline_fix (ibp + 1);
3375                             if (ibp[1] == '/') {
3376                               ibp += 2;
3377                               if (put_out_comments) {
3378                                 *obp++ = '*';
3379                                 *obp++ = '/';
3380                               }
3381                               break;
3382                             }
3383                           }
3384                           if (*ibp == '\n') {
3385                             /* Newline in a file.  Count it.  */
3386                             ++ip->lineno;
3387                             ++op->lineno;
3388                           }
3389                           if (put_out_comments)
3390                             *obp++ = *ibp;
3391                         }
3392                       } else if (ibp[1] == '/' && cplusplus_comments) {
3393                         if (put_out_comments) {
3394                           *obp++ = '/';
3395                           *obp++ = '/';
3396                         } else if (! traditional) {
3397                           *obp++ = ' ';
3398                         }
3399                         for (ibp += 2; *ibp != '\n' || ibp[-1] == '\\'; ibp++)
3400                           if (put_out_comments)
3401                             *obp++ = *ibp;
3402                       } else
3403                         break;
3404                     }
3405                     else if (ibp[0] == '\\' && ibp[1] == '\n') {
3406                       ibp += 2;
3407                       ++ip->lineno;
3408                     }
3409                     else break;
3410                   }
3411                   if (*ibp != '(') {
3412                     /* It isn't a macro call.
3413                        Put back the space that we just skipped.  */
3414                     ibp = old_ibp;
3415                     obp = old_obp;
3416                     ip->lineno = old_iln;
3417                     op->lineno = old_oln;
3418                     /* Exit the for loop.  */
3419                     break;
3420                   }
3421                 }
3422               
3423               /* This is now known to be a macro call.
3424                  Discard the macro name from the output,
3425                  along with any following whitespace just copied,
3426                  but preserve newlines if not outputting marks since this
3427                  is more likely to do the right thing with line numbers.  */
3428               obp = op->buf + obufp_before_macroname;
3429               if (output_marks)
3430                 op->lineno = op_lineno_before_macroname;
3431               else {
3432                 int newlines = op->lineno - op_lineno_before_macroname;
3433                 while (0 < newlines--)
3434                   *obp++ = '\n';
3435               }
3436
3437               /* Prevent accidental token-pasting with a character
3438                  before the macro call.  */
3439               if (!traditional && obp != op->buf) {
3440                 switch (obp[-1]) {
3441                 case '!':  case '%':  case '&':  case '*':
3442                 case '+':  case '-':  case '.':  case '/':
3443                 case ':':  case '<':  case '=':  case '>':
3444                 case '^':  case '|':
3445                   /* If we are expanding a macro arg, make a newline marker
3446                      to separate the tokens.  If we are making real output,
3447                      a plain space will do.  */
3448                   if (output_marks)
3449                     *obp++ = '\n';
3450                   *obp++ = ' ';
3451                 }
3452               }
3453
3454               /* Expand the macro, reading arguments as needed,
3455                  and push the expansion on the input stack.  */
3456               ip->bufp = ibp;
3457               op->bufp = obp;
3458               macroexpand (hp, op);
3459               
3460               /* Reexamine input stack, since macroexpand has pushed
3461                  a new level on it.  */
3462               obp = op->bufp;
3463               RECACHE;
3464               break;
3465             }
3466 hashcollision:
3467             ;
3468           }                     /* End hash-table-search loop */
3469         }
3470         ident_length = hash = 0; /* Stop collecting identifier */
3471         redo_char = 0;
3472         concatenated = 0;
3473       }                         /* End if (ident_length > 0) */
3474     }                           /* End switch */
3475   }                             /* End per-char loop */
3476
3477   /* Come here to return -- but first give an error message
3478      if there was an unterminated successful conditional.  */
3479  ending:
3480   if (if_stack != ip->if_stack)
3481     {
3482       char *str;
3483
3484       switch (if_stack->type)
3485         {
3486         case T_IF:
3487           str = "if";
3488           break;
3489         case T_IFDEF:
3490           str = "ifdef";
3491           break;
3492         case T_IFNDEF:
3493           str = "ifndef";
3494           break;
3495         case T_ELSE:
3496           str = "else";
3497           break;
3498         case T_ELIF:
3499           str = "elif";
3500           break;
3501         default:
3502           abort ();
3503         }
3504
3505       error_with_line (line_for_error (if_stack->lineno),
3506                        "unterminated `#%s' conditional", str);
3507   }
3508   if_stack = ip->if_stack;
3509 }
3510 \f
3511 /*
3512  * Rescan a string into a temporary buffer and return the result
3513  * as a FILE_BUF.  Note this function returns a struct, not a pointer.
3514  *
3515  * OUTPUT_MARKS nonzero means keep Newline markers found in the input
3516  * and insert such markers when appropriate.  See `rescan' for details.
3517  * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
3518  * before substitution; it is 0 for other uses.
3519  */
3520 static FILE_BUF
3521 expand_to_temp_buffer (buf, limit, output_marks, assertions)
3522      U_CHAR *buf, *limit;
3523      int output_marks, assertions;
3524 {
3525   register FILE_BUF *ip;
3526   FILE_BUF obuf;
3527   int length = limit - buf;
3528   U_CHAR *buf1;
3529   int odepth = indepth;
3530   int save_assertions_flag = assertions_flag;
3531
3532   assertions_flag = assertions;
3533
3534   if (length < 0)
3535     abort ();
3536
3537   /* Set up the input on the input stack.  */
3538
3539   buf1 = (U_CHAR *) alloca (length + 1);
3540   {
3541     register U_CHAR *p1 = buf;
3542     register U_CHAR *p2 = buf1;
3543
3544     while (p1 != limit)
3545       *p2++ = *p1++;
3546   }
3547   buf1[length] = 0;
3548
3549   /* Set up to receive the output.  */
3550
3551   obuf.length = length * 2 + 100; /* Usually enough.  Why be stingy?  */
3552   obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
3553   obuf.nominal_fname = 0;
3554   obuf.inc = 0;
3555   obuf.dir = 0;
3556   obuf.fname = 0;
3557   obuf.macro = 0;
3558   obuf.if_stack = 0;
3559   obuf.free_ptr = 0;
3560   obuf.system_header_p = 0;
3561
3562   CHECK_DEPTH ({return obuf;});
3563
3564   ++indepth;
3565
3566   ip = &instack[indepth];
3567   ip->fname = 0;
3568   ip->nominal_fname = 0;
3569   ip->nominal_fname_len = 0;
3570   ip->inc = 0;
3571   ip->system_header_p = 0;
3572   ip->macro = 0;
3573   ip->free_ptr = 0;
3574   ip->length = length;
3575   ip->buf = ip->bufp = buf1;
3576   ip->if_stack = if_stack;
3577
3578   ip->lineno = obuf.lineno = 1;
3579
3580   /* Scan the input, create the output.  */
3581   rescan (&obuf, output_marks);
3582
3583   /* Pop input stack to original state.  */
3584   --indepth;
3585
3586   if (indepth != odepth)
3587     abort ();
3588
3589   /* Record the output.  */
3590   obuf.length = obuf.bufp - obuf.buf;
3591
3592   assertions_flag = save_assertions_flag;
3593   return obuf;
3594 }
3595 \f
3596 /*
3597  * Process a # directive.  Expects IP->bufp to point after the '#', as in
3598  * `#define foo bar'.  Passes to the directive handler
3599  * (do_define, do_include, etc.): the addresses of the 1st and
3600  * last chars of the directive (starting immediately after the #
3601  * keyword), plus op and the keyword table pointer.  If the directive
3602  * contains comments it is copied into a temporary buffer sans comments
3603  * and the temporary buffer is passed to the directive handler instead.
3604  * Likewise for backslash-newlines.
3605  *
3606  * Returns nonzero if this was a known # directive.
3607  * Otherwise, returns zero, without advancing the input pointer.
3608  */
3609
3610 static int
3611 handle_directive (ip, op)
3612      FILE_BUF *ip, *op;
3613 {
3614   register U_CHAR *bp, *cp;
3615   register struct directive *kt;
3616   register int ident_length;
3617   U_CHAR *resume_p;
3618
3619   /* Nonzero means we must copy the entire directive
3620      to get rid of comments or backslash-newlines.  */
3621   int copy_directive = 0;
3622
3623   U_CHAR *ident, *after_ident;
3624
3625   bp = ip->bufp;
3626
3627   /* Record where the directive started.  do_xifdef needs this.  */
3628   directive_start = bp - 1;
3629
3630   /* Skip whitespace and \-newline.  */
3631   while (1) {
3632     if (is_hor_space[*bp]) {
3633       if (*bp != ' ' && *bp != '\t' && pedantic)
3634         pedwarn ("%s in preprocessing directive", char_name[*bp]);
3635       bp++;
3636     } else if (*bp == '/') {
3637       if (bp[1] == '\\' && bp[2] == '\n')
3638         newline_fix (bp + 1);
3639       if (! (bp[1] == '*' || (cplusplus_comments && bp[1] == '/')))
3640         break;
3641       ip->bufp = bp + 2;
3642       skip_to_end_of_comment (ip, &ip->lineno, 0);
3643       bp = ip->bufp;
3644     } else if (*bp == '\\' && bp[1] == '\n') {
3645       bp += 2; ip->lineno++;
3646     } else break;
3647   }
3648
3649   /* Now find end of directive name.
3650      If we encounter a backslash-newline, exchange it with any following
3651      symbol-constituents so that we end up with a contiguous name.  */
3652
3653   cp = bp;
3654   while (1) {
3655     if (is_idchar[*cp])
3656       cp++;
3657     else {
3658       if (*cp == '\\' && cp[1] == '\n')
3659         name_newline_fix (cp);
3660       if (is_idchar[*cp])
3661         cp++;
3662       else break;
3663     }
3664   }
3665   ident_length = cp - bp;
3666   ident = bp;
3667   after_ident = cp;
3668
3669   /* A line of just `#' becomes blank.  */
3670
3671   if (ident_length == 0 && *after_ident == '\n') {
3672     ip->bufp = after_ident;
3673     return 1;
3674   }
3675
3676   if (ident_length == 0 || !is_idstart[*ident]) {
3677     U_CHAR *p = ident;
3678     while (is_idchar[*p]) {
3679       if (*p < '0' || *p > '9')
3680         break;
3681       p++;
3682     }
3683     /* Handle # followed by a line number.  */
3684     if (p != ident && !is_idchar[*p]) {
3685       static struct directive line_directive_table[] = {
3686         {  4, do_line, "line", T_LINE},
3687       };
3688       if (pedantic)
3689         pedwarn ("`#' followed by integer");
3690       after_ident = ident;
3691       kt = line_directive_table;
3692       goto old_linenum;
3693     }
3694
3695     /* Avoid error for `###' and similar cases unless -pedantic.  */
3696     if (p == ident) {
3697       while (*p == '#' || is_hor_space[*p]) p++;
3698       if (*p == '\n') {
3699         if (pedantic && !lang_asm)
3700           warning ("invalid preprocessing directive");
3701         return 0;
3702       }
3703     }
3704
3705     if (!lang_asm)
3706       error ("invalid preprocessing directive name");
3707
3708     return 0;
3709   }
3710
3711   /*
3712    * Decode the keyword and call the appropriate expansion
3713    * routine, after moving the input pointer up to the next line.
3714    */
3715   for (kt = directive_table; kt->length > 0; kt++) {
3716     if (kt->length == ident_length && !bcmp (kt->name, ident, ident_length)) {
3717       register U_CHAR *buf;
3718       register U_CHAR *limit;
3719       int unterminated;
3720       int junk;
3721       int *already_output;
3722
3723       /* Nonzero means do not delete comments within the directive.
3724          #define needs this when -traditional.  */
3725       int keep_comments;
3726
3727     old_linenum:
3728
3729       limit = ip->buf + ip->length;
3730       unterminated = 0;
3731       already_output = 0;
3732       keep_comments = traditional && kt->type == T_DEFINE;
3733       /* #import is defined only in Objective C, or when on the NeXT.  */
3734       if (kt->type == T_IMPORT
3735           && !(objc || lookup ((U_CHAR *) "__NeXT__", -1, -1)))
3736         break;
3737
3738       /* Find the end of this directive (first newline not backslashed
3739          and not in a string or comment).
3740          Set COPY_DIRECTIVE if the directive must be copied
3741          (it contains a backslash-newline or a comment).  */
3742
3743       buf = bp = after_ident;
3744       while (bp < limit) {
3745         register U_CHAR c = *bp++;
3746         switch (c) {
3747         case '\\':
3748           if (bp < limit) {
3749             if (*bp == '\n') {
3750               ip->lineno++;
3751               copy_directive = 1;
3752               bp++;
3753             } else if (traditional)
3754               bp++;
3755           }
3756           break;
3757
3758         case '"':
3759           /* "..." is special for #include.  */
3760           if (IS_INCLUDE_DIRECTIVE_TYPE (kt->type)) {
3761             while (bp < limit && *bp != '\n') {
3762               if (*bp == '"') {
3763                 bp++;
3764                 break;
3765               }
3766               if (*bp == '\\' && bp[1] == '\n') {
3767                 ip->lineno++;
3768                 copy_directive = 1;
3769                 bp++;
3770               }
3771               bp++;
3772             }
3773             break;
3774           }
3775           /* Fall through.  */
3776         case '\'':
3777           bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_directive, &unterminated);
3778           /* Don't bother calling the directive if we already got an error
3779              message due to unterminated string.  Skip everything and pretend
3780              we called the directive.  */
3781           if (unterminated) {
3782             if (traditional) {
3783               /* Traditional preprocessing permits unterminated strings.  */
3784               ip->bufp = bp;
3785               goto endloop1;
3786             }
3787             ip->bufp = bp;
3788             return 1;
3789           }
3790           break;
3791
3792           /* <...> is special for #include.  */
3793         case '<':
3794           if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3795             break;
3796           while (bp < limit && *bp != '>' && *bp != '\n') {
3797             if (*bp == '\\' && bp[1] == '\n') {
3798               ip->lineno++;
3799               copy_directive = 1;
3800               bp++;
3801             }
3802             bp++;
3803           }
3804           break;
3805
3806         case '/':
3807           if (*bp == '\\' && bp[1] == '\n')
3808             newline_fix (bp);
3809           if (*bp == '*'
3810               || (cplusplus_comments && *bp == '/')) {
3811             U_CHAR *obp = bp - 1;
3812             ip->bufp = bp + 1;
3813             skip_to_end_of_comment (ip, &ip->lineno, 0);
3814             bp = ip->bufp;
3815             /* No need to copy the directive because of a comment at the end;
3816                just don't include the comment in the directive.  */
3817             if (!put_out_comments) {
3818               U_CHAR *p;
3819               for (p = bp;  *p == ' ' || *p == '\t';  p++)
3820                 continue;
3821               if (*p == '\n') {
3822                 bp = obp;
3823                 goto endloop1;
3824               }
3825             }
3826             /* Don't remove the comments if -traditional.  */
3827             if (! keep_comments)
3828               copy_directive++;
3829           }
3830           break;
3831
3832         case '\f':
3833         case '\r':
3834         case '\v':
3835           if (pedantic)
3836             pedwarn ("%s in preprocessing directive", char_name[c]);
3837           break;
3838
3839         case '\n':
3840           --bp;         /* Point to the newline */
3841           ip->bufp = bp;
3842           goto endloop1;
3843         }
3844       }
3845       ip->bufp = bp;
3846
3847     endloop1:
3848       resume_p = ip->bufp;
3849       /* BP is the end of the directive.
3850          RESUME_P is the next interesting data after the directive.
3851          A comment may come between.  */
3852
3853       /* If a directive should be copied through, and -C was given,
3854          pass it through before removing comments.  */
3855       if (!no_output && put_out_comments
3856           && (kt->type == T_DEFINE ? dump_macros == dump_definitions
3857               : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3858               : kt->type == T_PRAGMA)) {
3859         int len;
3860
3861         /* Output directive name.  */
3862         check_expand (op, kt->length + 2);
3863         /* Make sure # is at the start of a line */
3864         if (op->bufp > op->buf && op->bufp[-1] != '\n') {
3865           op->lineno++;
3866           *op->bufp++ = '\n';
3867         }
3868         *op->bufp++ = '#';
3869         bcopy (kt->name, op->bufp, kt->length);
3870         op->bufp += kt->length;
3871
3872         /* Output arguments.  */
3873         len = (bp - buf);
3874         check_expand (op, len);
3875         bcopy (buf, (char *) op->bufp, len);
3876         op->bufp += len;
3877         /* Take account of any (escaped) newlines just output.  */
3878         while (--len >= 0)
3879           if (buf[len] == '\n')
3880             op->lineno++;
3881
3882         already_output = &junk;
3883       }                         /* Don't we need a newline or #line? */
3884
3885       if (copy_directive) {
3886         register U_CHAR *xp = buf;
3887         /* Need to copy entire directive into temp buffer before dispatching */
3888
3889         cp = (U_CHAR *) alloca (bp - buf + 5); /* room for directive plus
3890                                                   some slop */
3891         buf = cp;
3892
3893         /* Copy to the new buffer, deleting comments
3894            and backslash-newlines (and whitespace surrounding the latter).  */
3895
3896         while (xp < bp) {
3897           register U_CHAR c = *xp++;
3898           *cp++ = c;
3899
3900           switch (c) {
3901           case '\n':
3902             abort ();  /* A bare newline should never part of the line.  */
3903             break;
3904
3905             /* <...> is special for #include.  */
3906           case '<':
3907             if (! IS_INCLUDE_DIRECTIVE_TYPE (kt->type))
3908               break;
3909             while (xp < bp && c != '>') {
3910               c = *xp++;
3911               if (c == '\\' && xp < bp && *xp == '\n')
3912                 xp++;
3913               else
3914                 *cp++ = c;
3915             }
3916             break;
3917
3918           case '\\':
3919             if (*xp == '\n') {
3920               xp++;
3921               cp--;
3922               if (cp != buf && is_hor_space[cp[-1]]) {
3923                 while (cp - 1 != buf && is_hor_space[cp[-2]])
3924                   cp--;
3925                 SKIP_WHITE_SPACE (xp);
3926               } else if (is_hor_space[*xp]) {
3927                 *cp++ = *xp++;
3928                 SKIP_WHITE_SPACE (xp);
3929               }
3930             } else if (traditional && xp < bp) {
3931               *cp++ = *xp++;
3932             }
3933             break;
3934
3935           case '\'':
3936           case '\"':
3937             {
3938               register U_CHAR *bp1
3939                 = skip_quoted_string (xp - 1, bp, ip->lineno,
3940                                       NULL_PTR, NULL_PTR, NULL_PTR);
3941               while (xp != bp1)
3942                 *cp++ = *xp++;
3943             }
3944             break;
3945
3946           case '/':
3947             if (*xp == '*'
3948                 || (cplusplus_comments && *xp == '/')) {
3949               ip->bufp = xp + 1;
3950               /* If we already copied the directive through,
3951                  already_output != 0 prevents outputting comment now.  */
3952               skip_to_end_of_comment (ip, already_output, 0);
3953               if (keep_comments)
3954                 while (xp != ip->bufp)
3955                   *cp++ = *xp++;
3956               /* Delete or replace the slash.  */
3957               else if (traditional)
3958                 cp--;
3959               else
3960                 cp[-1] = ' ';
3961               xp = ip->bufp;
3962             }
3963           }
3964         }
3965
3966         /* Null-terminate the copy.  */
3967
3968         *cp = 0;
3969       } else
3970         cp = bp;
3971
3972       ip->bufp = resume_p;
3973
3974       /* Some directives should be written out for cc1 to process,
3975          just as if they were not defined.  And sometimes we're copying
3976          directives through.  */
3977
3978       if (!no_output && already_output == 0
3979           && (kt->type == T_DEFINE ? (int) dump_names <= (int) dump_macros
3980               : IS_INCLUDE_DIRECTIVE_TYPE (kt->type) ? dump_includes
3981               : kt->type == T_PRAGMA)) {
3982         int len;
3983
3984         /* Output directive name.  */
3985         check_expand (op, kt->length + 1);
3986         *op->bufp++ = '#';
3987         bcopy (kt->name, (char *) op->bufp, kt->length);
3988         op->bufp += kt->length;
3989
3990         if (kt->type == T_DEFINE && dump_macros == dump_names) {
3991           /* Output `#define name' only.  */
3992           U_CHAR *xp = buf;
3993           U_CHAR *yp;
3994           SKIP_WHITE_SPACE (xp);
3995           yp = xp;
3996           while (is_idchar[*xp]) xp++;
3997           len = (xp - yp);
3998           check_expand (op, len + 1);
3999           *op->bufp++ = ' ';
4000           bcopy (yp, (char *) op->bufp, len);
4001         } else {
4002           /* Output entire directive.  */
4003           len = (cp - buf);
4004           check_expand (op, len);
4005           bcopy (buf, (char *) op->bufp, len);
4006         }
4007         op->bufp += len;
4008       }                         /* Don't we need a newline or #line? */
4009
4010       /* Call the appropriate directive handler.  buf now points to
4011          either the appropriate place in the input buffer, or to
4012          the temp buffer if it was necessary to make one.  cp
4013          points to the first char after the contents of the (possibly
4014          copied) directive, in either case.  */
4015       (*kt->func) (buf, cp, op, kt);
4016       check_expand (op, ip->length - (ip->bufp - ip->buf));
4017
4018       return 1;
4019     }
4020   }
4021
4022   /* It is deliberate that we don't warn about undefined directives.
4023      That is the responsibility of cc1.  */
4024   return 0;
4025 }
4026 \f
4027 static struct tm *
4028 timestamp ()
4029 {
4030   static struct tm *timebuf;
4031   if (!timebuf) {
4032     time_t t = time ((time_t *) 0);
4033     timebuf = localtime (&t);
4034   }
4035   return timebuf;
4036 }
4037
4038 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
4039                              "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
4040                             };
4041
4042 /*
4043  * expand things like __FILE__.  Place the expansion into the output
4044  * buffer *without* rescanning.
4045  */
4046
4047 static void
4048 special_symbol (hp, op)
4049      HASHNODE *hp;
4050      FILE_BUF *op;
4051 {
4052   char *buf;
4053   int i, len;
4054   int true_indepth;
4055   FILE_BUF *ip = NULL;
4056   struct tm *timebuf;
4057
4058   int paren = 0;                /* For special `defined' keyword */
4059
4060   if (pcp_outfile && pcp_inside_if
4061       && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
4062     error ("Predefined macro `%s' used inside `#if' during precompilation",
4063            hp->name);
4064     
4065   for (i = indepth; i >= 0; i--)
4066     if (instack[i].fname != NULL) {
4067       ip = &instack[i];
4068       break;
4069     }
4070   if (ip == NULL) {
4071     error ("cccp error: not in any file?!");
4072     return;                     /* the show must go on */
4073   }
4074
4075   switch (hp->type) {
4076   case T_FILE:
4077   case T_BASE_FILE:
4078     {
4079       FILE_BUF *p = hp->type == T_FILE ? ip : &instack[0];
4080       char *string = p->nominal_fname;
4081
4082       if (string)
4083         {
4084           size_t string_len = p->nominal_fname_len;
4085           buf = (char *) alloca (3 + 4 * string_len);
4086           quote_string (buf, string, string_len);
4087         }
4088       else
4089         buf = "\"\"";
4090
4091       break;
4092     }
4093
4094   case T_INCLUDE_LEVEL:
4095     true_indepth = 0;
4096     for (i = indepth; i >= 0; i--)
4097       if (instack[i].fname != NULL)
4098         true_indepth++;
4099
4100     buf = (char *) alloca (8);  /* Eight bytes ought to be more than enough */
4101     sprintf (buf, "%d", true_indepth - 1);
4102     break;
4103
4104   case T_VERSION:
4105     buf = (char *) alloca (3 + strlen (version_string));
4106     sprintf (buf, "\"%s\"", version_string);
4107     break;
4108
4109 #ifndef NO_BUILTIN_SIZE_TYPE
4110   case T_SIZE_TYPE:
4111     buf = SIZE_TYPE;
4112     break;
4113 #endif
4114
4115 #ifndef NO_BUILTIN_PTRDIFF_TYPE
4116   case T_PTRDIFF_TYPE:
4117     buf = PTRDIFF_TYPE;
4118     break;
4119 #endif
4120
4121   case T_WCHAR_TYPE:
4122     buf = wchar_type;
4123     break;
4124
4125   case T_USER_LABEL_PREFIX_TYPE:
4126     buf = USER_LABEL_PREFIX;
4127     break;
4128
4129   case T_REGISTER_PREFIX_TYPE:
4130     buf = REGISTER_PREFIX;
4131     break;
4132
4133   case T_IMMEDIATE_PREFIX_TYPE:
4134     buf = IMMEDIATE_PREFIX;
4135     break;
4136
4137   case T_CONST:
4138     buf = hp->value.cpval;
4139 #ifdef STDC_0_IN_SYSTEM_HEADERS
4140     if (ip->system_header_p
4141         && hp->length == 8 && bcmp (hp->name, "__STDC__", 8) == 0
4142         && !lookup ((U_CHAR *) "__STRICT_ANSI__", -1, -1))
4143       buf = "0";
4144 #endif
4145     if (pcp_inside_if && pcp_outfile)
4146       /* Output a precondition for this macro use */
4147       fprintf (pcp_outfile, "#define %s %s\n", hp->name, buf);
4148     break;
4149
4150   case T_SPECLINE:
4151     buf = (char *) alloca (10);
4152     sprintf (buf, "%d", ip->lineno);
4153     break;
4154
4155   case T_DATE:
4156   case T_TIME:
4157     buf = (char *) alloca (20);
4158     timebuf = timestamp ();
4159     if (hp->type == T_DATE)
4160       sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
4161               timebuf->tm_mday, timebuf->tm_year + 1900);
4162     else
4163       sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
4164               timebuf->tm_sec);
4165     break;
4166
4167   case T_SPEC_DEFINED:
4168     buf = " 0 ";                /* Assume symbol is not defined */
4169     ip = &instack[indepth];
4170     SKIP_WHITE_SPACE (ip->bufp);
4171     if (*ip->bufp == '(') {
4172       paren++;
4173       ip->bufp++;                       /* Skip over the paren */
4174       SKIP_WHITE_SPACE (ip->bufp);
4175     }
4176
4177     if (!is_idstart[*ip->bufp])
4178       goto oops;
4179     if (ip->bufp[0] == 'L' && (ip->bufp[1] == '\'' || ip->bufp[1] == '"'))
4180       goto oops;
4181     if ((hp = lookup (ip->bufp, -1, -1))) {
4182       if (pcp_outfile && pcp_inside_if
4183           && (hp->type == T_CONST
4184               || (hp->type == T_MACRO && hp->value.defn->predefined)))
4185         /* Output a precondition for this macro use.  */
4186         fprintf (pcp_outfile, "#define %s\n", hp->name);
4187       buf = " 1 ";
4188     }
4189     else
4190       if (pcp_outfile && pcp_inside_if) {
4191         /* Output a precondition for this macro use */
4192         U_CHAR *cp = ip->bufp;
4193         fprintf (pcp_outfile, "#undef ");
4194         while (is_idchar[*cp]) /* Ick! */
4195           fputc (*cp++, pcp_outfile);
4196         putc ('\n', pcp_outfile);
4197       }
4198     while (is_idchar[*ip->bufp])
4199       ++ip->bufp;
4200     SKIP_WHITE_SPACE (ip->bufp);
4201     if (paren) {
4202       if (*ip->bufp != ')')
4203         goto oops;
4204       ++ip->bufp;
4205     }
4206     break;
4207
4208 oops:
4209
4210     error ("`defined' without an identifier");
4211     break;
4212
4213   default:
4214     error ("cccp error: invalid special hash type"); /* time for gdb */
4215     abort ();
4216   }
4217   len = strlen (buf);
4218   check_expand (op, len);
4219   bcopy (buf, (char *) op->bufp, len);
4220   op->bufp += len;
4221
4222   return;
4223 }
4224
4225 \f
4226 /* Routines to handle #directives */
4227
4228 /* Handle #include and #import.
4229    This function expects to see "fname" or <fname> on the input.  */
4230
4231 static int
4232 do_include (buf, limit, op, keyword)
4233      U_CHAR *buf, *limit;
4234      FILE_BUF *op;
4235      struct directive *keyword;
4236 {
4237   U_CHAR *importing = keyword->type == T_IMPORT ? (U_CHAR *) "" : (U_CHAR *) 0;
4238   int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
4239   static int import_warning = 0;
4240   char *fname;          /* Dynamically allocated fname buffer */
4241   char *pcftry;
4242   char *pcfname;
4243   char *fbeg, *fend;            /* Beginning and end of fname */
4244   U_CHAR *fin;
4245
4246   struct file_name_list *search_start = include; /* Chain of dirs to search */
4247   struct file_name_list *dsp;   /* First in chain, if #include "..." */
4248   struct file_name_list *searchptr = 0;
4249   size_t flen;
4250
4251   int f = -3;                   /* file number */
4252   struct include_file *inc = 0;
4253
4254   int retried = 0;              /* Have already tried macro
4255                                    expanding the include line*/
4256   int angle_brackets = 0;       /* 0 for "...", 1 for <...> */
4257 #ifdef VMS
4258   int vaxc_include = 0;         /* 1 for token without punctuation */
4259 #endif
4260   int pcf = -1;
4261   char *pcfbuf;
4262   char *pcfbuflimit;
4263   int pcfnum;
4264
4265   if (pedantic && !instack[indepth].system_header_p)
4266     {
4267       if (importing)
4268         pedwarn ("ANSI C does not allow `#import'");
4269       if (skip_dirs)
4270         pedwarn ("ANSI C does not allow `#include_next'");
4271     }
4272
4273   if (importing && warn_import && !inhibit_warnings
4274       && !instack[indepth].system_header_p && !import_warning) {
4275     import_warning = 1;
4276     warning ("using `#import' is not recommended");
4277     fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
4278     fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
4279     fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
4280     fprintf (stderr, "  #ifndef _FOO_H_INCLUDED\n");
4281     fprintf (stderr, "  #define _FOO_H_INCLUDED\n");
4282     fprintf (stderr, "  ... <real contents of file> ...\n");
4283     fprintf (stderr, "  #endif /* Not _FOO_H_INCLUDED */\n\n");
4284     fprintf (stderr, "Then users can use `#include' any number of times.\n");
4285     fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
4286     fprintf (stderr, "when it is equipped with such a conditional.\n");
4287   }
4288
4289 get_filename:
4290
4291   fin = buf;
4292   SKIP_WHITE_SPACE (fin);
4293   /* Discard trailing whitespace so we can easily see
4294      if we have parsed all the significant chars we were given.  */
4295   while (limit != fin && is_hor_space[limit[-1]]) limit--;
4296   fbeg = fend = (char *) alloca (limit - fin);
4297
4298   switch (*fin++) {
4299   case '\"':
4300     {
4301       FILE_BUF *fp;
4302       /* Copy the operand text, concatenating the strings.  */
4303       {
4304         for (;;) {
4305           for (;;) {
4306             if (fin == limit)
4307               goto invalid_include_file_name;
4308             *fend = *fin++;
4309             if (*fend == '"')
4310               break;
4311             fend++;
4312           }
4313           if (fin == limit)
4314             break;
4315           /* If not at the end, there had better be another string.  */
4316           /* Skip just horiz space, and don't go past limit.  */
4317           while (fin != limit && is_hor_space[*fin]) fin++;
4318           if (fin != limit && *fin == '\"')
4319             fin++;
4320           else
4321             goto fail;
4322         }
4323       }
4324
4325       /* We have "filename".  Figure out directory this source
4326          file is coming from and put it on the front of the list.  */
4327
4328       /* If -I- was specified, don't search current dir, only spec'd ones.  */
4329       if (ignore_srcdir) break;
4330
4331       for (fp = &instack[indepth]; fp >= instack; fp--)
4332         {
4333           int n;
4334           char *nam;
4335
4336           if ((nam = fp->nominal_fname) != NULL) {
4337             /* Found a named file.  Figure out dir of the file,
4338                and put it in front of the search list.  */
4339             dsp = ((struct file_name_list *)
4340                    alloca (sizeof (struct file_name_list)
4341                            + fp->nominal_fname_len));
4342             strcpy (dsp->fname, nam);
4343             simplify_filename (dsp->fname);
4344             nam = base_name (dsp->fname);
4345             *nam = 0;
4346             /* But for efficiency's sake, do not insert the dir
4347                if it matches the search list's first dir.  */
4348             dsp->next = search_start;
4349             if (!search_start || strcmp (dsp->fname, search_start->fname)) {
4350               search_start = dsp;
4351               n = nam - dsp->fname;
4352               if (n + INCLUDE_LEN_FUDGE > max_include_len)
4353                 max_include_len = n + INCLUDE_LEN_FUDGE;
4354             }
4355             dsp[0].got_name_map = 0;
4356             break;
4357           }
4358         }
4359       break;
4360     }
4361
4362   case '<':
4363     while (fin != limit && *fin != '>')
4364       *fend++ = *fin++;
4365     if (*fin == '>' && fin + 1 == limit) {
4366       angle_brackets = 1;
4367       /* If -I-, start with the first -I dir after the -I-.  */
4368       search_start = first_bracket_include;
4369       break;
4370     }
4371     goto fail;
4372
4373   default:
4374 #ifdef VMS
4375     /*
4376      * Support '#include xyz' like VAX-C to allow for easy use of all the
4377      * decwindow include files. It defaults to '#include <xyz.h>' (so the
4378      * code from case '<' is repeated here) and generates a warning.
4379      * (Note: macro expansion of `xyz' takes precedence.)
4380      */
4381     if (retried && isalpha(*(U_CHAR *) (--fbeg))) {
4382       while (fin != limit && (!isspace(*fin)))
4383         *fend++ = *fin++;
4384       warning ("VAX-C-style include specification found, use '#include <filename.h>' !");
4385       vaxc_include = 1;
4386       if (fin == limit) {
4387         angle_brackets = 1;
4388         /* If -I-, start with the first -I dir after the -I-.  */
4389         search_start = first_bracket_include;
4390         break;
4391       }
4392     }
4393 #endif
4394
4395   fail:
4396     if (! retried) {
4397       /* Expand buffer and then remove any newline markers.
4398          We can't just tell expand_to_temp_buffer to omit the markers,
4399          since it would put extra spaces in include file names.  */
4400       FILE_BUF trybuf;
4401       U_CHAR *src;
4402       int errors_before_expansion = errors;
4403       trybuf = expand_to_temp_buffer (buf, limit, 1, 0);
4404       if (errors != errors_before_expansion) {
4405         free (trybuf.buf);
4406         goto invalid_include_file_name;
4407       }
4408       src = trybuf.buf;
4409       buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
4410       limit = buf;
4411       while (src != trybuf.bufp) {
4412         switch ((*limit++ = *src++)) {
4413           case '\n':
4414             limit--;
4415             src++;
4416             break;
4417
4418           case '\'':
4419           case '\"':
4420             {
4421               U_CHAR *src1 = skip_quoted_string (src - 1, trybuf.bufp, 0,
4422                                                  NULL_PTR, NULL_PTR, NULL_PTR);
4423               while (src != src1)
4424                 *limit++ = *src++;
4425             }
4426             break;
4427         }
4428       }
4429       *limit = 0;
4430       free (trybuf.buf);
4431       retried = 1;
4432       goto get_filename;
4433     }
4434
4435   invalid_include_file_name:
4436     error ("`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
4437     return 0;
4438   }
4439
4440   /* For #include_next, skip in the search path
4441      past the dir in which the containing file was found.  */
4442   if (skip_dirs) {
4443     FILE_BUF *fp;
4444     for (fp = &instack[indepth]; fp >= instack; fp--)
4445       if (fp->fname != NULL) {
4446         /* fp->dir is null if the containing file was specified
4447            with an absolute file name.  In that case, don't skip anything.  */
4448         if (fp->dir)
4449           search_start = fp->dir->next;
4450         break;
4451       }
4452   }
4453
4454   *fend = 0;
4455   flen = simplify_filename (fbeg);
4456
4457   if (flen == 0)
4458     {
4459       error ("empty file name in `#%s'", keyword->name);
4460       return 0;
4461     }
4462
4463   /* Allocate this permanently, because it gets stored in the definitions
4464      of macros.  */
4465   fname = xmalloc (max_include_len + flen + 1);
4466   /* + 1 above for terminating null.  */
4467
4468   system_include_depth += angle_brackets;
4469
4470   /* If specified file name is absolute, just open it.  */
4471
4472   if (absolute_filename (fbeg)) {
4473     strcpy (fname, fbeg);
4474     f = open_include_file (fname, NULL_PTR, importing, &inc);
4475   } else {
4476
4477     struct bypass_dir {
4478       struct bypass_dir *next;
4479       char *fname;
4480       struct file_name_list *searchptr;
4481     } **bypass_slot = 0;
4482
4483     /* Search directory path, trying to open the file.
4484        Copy each filename tried into FNAME.  */
4485
4486     for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
4487
4488       if (searchptr == first_bracket_include) {
4489         /* Go to bypass directory if we know we've seen this file before.  */
4490         static struct bypass_dir *bypass_hashtab[INCLUDE_HASHSIZE];
4491         struct bypass_dir *p;
4492         bypass_slot = &bypass_hashtab[hashf ((U_CHAR *) fbeg, flen,
4493                                              INCLUDE_HASHSIZE)];
4494         for (p = *bypass_slot; p; p = p->next)
4495           if (!strcmp (fbeg, p->fname)) {
4496             searchptr = p->searchptr;
4497             bypass_slot = 0;
4498             break;
4499           }
4500       }
4501
4502       strcpy (fname, searchptr->fname);
4503       strcat (fname, fbeg);
4504 #ifdef VMS
4505       /* Change this 1/2 Unix 1/2 VMS file specification into a
4506          full VMS file specification */
4507       if (searchptr->fname[0]) {
4508         /* Fix up the filename */
4509         hack_vms_include_specification (fname, vaxc_include);
4510       } else {
4511         /* This is a normal VMS filespec, so use it unchanged.  */
4512         strcpy (fname, fbeg);
4513         /* if it's '#include filename', add the missing .h */
4514         if (vaxc_include && index(fname,'.')==NULL) {
4515           strcat (fname, ".h");
4516         }
4517       }
4518 #endif /* VMS */
4519       f = open_include_file (fname, searchptr, importing, &inc);
4520       if (f != -1) {
4521         if (bypass_slot && searchptr != first_bracket_include) {
4522           /* This is the first time we found this include file,
4523              and we found it after first_bracket_include.
4524              Record its location so that we can bypass to here next time.  */
4525           struct bypass_dir *p
4526             = (struct bypass_dir *) xmalloc (sizeof (struct bypass_dir));
4527           p->next = *bypass_slot;
4528           p->fname = fname + strlen (searchptr->fname);
4529           p->searchptr = searchptr;
4530           *bypass_slot = p;
4531         }
4532         break;
4533       }
4534 #ifdef VMS
4535       /* Our VMS hacks can produce invalid filespecs, so don't worry
4536          about errors other than EACCES.  */
4537       if (errno == EACCES)
4538         break;
4539 #else
4540       if (errno != ENOENT && errno != ENOTDIR)
4541         break;
4542 #endif
4543     }
4544   }
4545
4546
4547   if (f < 0) {
4548
4549     if (f == -2) {
4550       /* The file was already included.  */
4551
4552     /* If generating dependencies and -MG was specified, we assume missing
4553        files are leaf files, living in the same directory as the source file
4554        or other similar place; these missing files may be generated from
4555        other files and may not exist yet (eg: y.tab.h).  */
4556     } else if (print_deps_missing_files
4557                && (system_include_depth != 0) < print_deps)
4558       {
4559         /* If it was requested as a system header file,
4560            then assume it belongs in the first place to look for such.  */
4561         if (angle_brackets)
4562           {
4563             if (search_start) {
4564               char *p = (char *) alloca (strlen (search_start->fname)
4565                                          + strlen (fbeg) + 1);
4566               strcpy (p, search_start->fname);
4567               strcat (p, fbeg);
4568               deps_output (p, ' ');
4569             }
4570           }
4571         else
4572           {
4573             /* Otherwise, omit the directory, as if the file existed
4574                in the directory with the source.  */
4575             deps_output (fbeg, ' ');
4576           }
4577       }
4578     /* If -M was specified, and this header file won't be added to the
4579        dependency list, then don't count this as an error, because we can
4580        still produce correct output.  Otherwise, we can't produce correct
4581        output, because there may be dependencies we need inside the missing
4582        file, and we don't know what directory this missing file exists in.  */
4583     else if (0 < print_deps  &&  print_deps <= (system_include_depth != 0))
4584       warning ("No include path in which to find %s", fbeg);
4585     else if (f != -3)
4586       error_from_errno (fbeg);
4587     else
4588       error ("No include path in which to find %s", fbeg);
4589
4590   } else {
4591
4592     /* Actually process the file.  */
4593
4594     pcftry = (char *) alloca (strlen (fname) + 30);
4595     pcfbuf = 0;
4596     pcfnum = 0;
4597
4598     if (!no_precomp)
4599       {
4600         do {
4601           sprintf (pcftry, "%s%d", fname, pcfnum++);
4602
4603           pcf = open (pcftry, O_RDONLY, 0666);
4604           if (pcf != -1)
4605             {
4606               struct stat s;
4607
4608               if (fstat (pcf, &s) != 0)
4609                 pfatal_with_name (pcftry);
4610               if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4611                   || inc->st.st_dev != s.st_dev)
4612                 {
4613                   pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4614                   /* Don't need it any more.  */
4615                   close (pcf);
4616                 }
4617               else
4618                 {
4619                   /* Don't need it at all.  */
4620                   close (pcf);
4621                   break;
4622                 }
4623             }
4624         } while (pcf != -1 && !pcfbuf);
4625       }
4626     
4627     /* Actually process the file */
4628     if (pcfbuf) {
4629       pcfname = xmalloc (strlen (pcftry) + 1);
4630       strcpy (pcfname, pcftry);
4631       pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4632                   (U_CHAR *) fname, op);
4633     }
4634     else
4635       finclude (f, inc, op, is_system_include (fname), searchptr);
4636   }
4637
4638   system_include_depth -= angle_brackets;
4639
4640   return 0;
4641 }
4642
4643 /* Return nonzero if the given FILENAME is an absolute pathname which
4644    designates a file within one of the known "system" include file
4645    directories.  We assume here that if the given FILENAME looks like
4646    it is the name of a file which resides either directly in a "system"
4647    include file directory, or within any subdirectory thereof, then the
4648    given file must be a "system" include file.  This function tells us
4649    if we should suppress pedantic errors/warnings for the given FILENAME.
4650
4651    The value is 2 if the file is a C-language system header file
4652    for which C++ should (on most systems) assume `extern "C"'.  */
4653
4654 static int
4655 is_system_include (filename)
4656     register char *filename;
4657 {
4658   struct file_name_list *searchptr;
4659
4660   for (searchptr = first_system_include; searchptr;
4661        searchptr = searchptr->next)
4662     if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4663       return searchptr->c_system_include_path + 1;
4664   return 0;
4665 }
4666 \f
4667 /* Yield the non-directory suffix of a file name.  */
4668
4669 static char *
4670 base_name (fname)
4671      char *fname;
4672 {
4673   char *s = fname;
4674   char *p;
4675 #if defined (__MSDOS__) || defined (_WIN32)
4676   if (isalpha (s[0]) && s[1] == ':') s += 2;
4677 #endif
4678 #ifdef VMS
4679   if ((p = rindex (s, ':'))) s = p + 1; /* Skip device.  */
4680   if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory.  */
4681   if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir.  */
4682   if (s != fname)
4683     return s;
4684 #endif
4685   if ((p = rindex (s, '/'))) s = p + 1;
4686 #ifdef DIR_SEPARATOR
4687   if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4688 #endif
4689   return s;
4690 }
4691
4692 /* Yield nonzero if FILENAME is absolute (i.e. not relative).  */
4693
4694 static int
4695 absolute_filename (filename)
4696      char *filename;
4697 {
4698 #if defined (__MSDOS__) || (defined (_WIN32) && !defined (__CYGWIN32__))
4699   if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4700 #endif
4701 #if defined (__CYGWIN32__)
4702   /* At present, any path that begins with a drive spec is absolute.  */
4703   if (isalpha (filename[0]) && filename[1] == ':') return 1;
4704 #endif
4705   if (filename[0] == '/') return 1;
4706 #ifdef DIR_SEPARATOR
4707   if (filename[0] == DIR_SEPARATOR) return 1;
4708 #endif
4709   return 0;
4710 }
4711
4712 /* Remove unnecessary characters from FILENAME in place,
4713    to avoid unnecessary filename aliasing.
4714    Return the length of the resulting string.
4715
4716    Do only the simplifications allowed by Posix.
4717    It is OK to miss simplifications on non-Posix hosts,
4718    since this merely leads to suboptimal results.  */
4719
4720 static size_t
4721 simplify_filename (filename)
4722      char *filename;
4723 {
4724   register char *from = filename;
4725   register char *to = filename;
4726   char *to0;
4727
4728   /* Remove redundant initial /s.  */
4729   if (*from == '/') {
4730     *to++ = '/';
4731     if (*++from == '/') {
4732       if (*++from == '/') {
4733         /* 3 or more initial /s are equivalent to 1 /.  */
4734         while (*++from == '/')
4735           continue;
4736       } else {
4737         /* On some hosts // differs from /; Posix allows this.  */
4738         static int slashslash_vs_slash;
4739         if (slashslash_vs_slash == 0) {
4740           struct stat s1, s2;
4741           slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4742                                   && INO_T_EQ (s1.st_ino, s2.st_ino)
4743                                   && s1.st_dev == s2.st_dev)
4744                                  ? 1 : -1);
4745         }
4746         if (slashslash_vs_slash < 0)
4747           *to++ = '/';
4748       }
4749     }
4750   }
4751   to0 = to;
4752
4753   for (;;) {
4754     if (from[0] == '.' && from[1] == '/')
4755       from += 2;
4756     else {
4757       /* Copy this component and trailing /, if any.  */
4758       while ((*to++ = *from++) != '/') {
4759         if (!to[-1]) {
4760           /* Trim . component at end of nonempty name.  */
4761           to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4762
4763           /* Trim unnecessary trailing /s.  */
4764           while (to0 < --to && to[-1] == '/')
4765             continue;
4766
4767           *to = 0;
4768           return to - filename;
4769         }
4770       }
4771     }
4772
4773     /* Skip /s after a /.  */
4774     while (*from == '/')
4775       from++;
4776   }
4777 }
4778 \f
4779 /* The file_name_map structure holds a mapping of file names for a
4780    particular directory.  This mapping is read from the file named
4781    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
4782    map filenames on a file system with severe filename restrictions,
4783    such as DOS.  The format of the file name map file is just a series
4784    of lines with two tokens on each line.  The first token is the name
4785    to map, and the second token is the actual name to use.  */
4786
4787 struct file_name_map
4788 {
4789   struct file_name_map *map_next;
4790   char *map_from;
4791   char *map_to;
4792 };
4793
4794 #define FILE_NAME_MAP_FILE "header.gcc"
4795
4796 /* Read a space delimited string of unlimited length from a stdio
4797    file.  */
4798
4799 static char *
4800 read_filename_string (ch, f)
4801      int ch;
4802      FILE *f;
4803 {
4804   char *alloc, *set;
4805   int len;
4806
4807   len = 20;
4808   set = alloc = xmalloc (len + 1);
4809   if (! is_space[ch])
4810     {
4811       *set++ = ch;
4812       while ((ch = getc (f)) != EOF && ! is_space[ch])
4813         {
4814           if (set - alloc == len)
4815             {
4816               len *= 2;
4817               alloc = xrealloc (alloc, len + 1);
4818               set = alloc + len / 2;
4819             }
4820           *set++ = ch;
4821         }
4822     }
4823   *set = '\0';
4824   ungetc (ch, f);
4825   return alloc;
4826 }
4827
4828 /* Read the file name map file for DIRNAME.
4829    If DIRNAME is empty, read the map file for the working directory;
4830    otherwise DIRNAME must end in '/'.  */
4831
4832 static struct file_name_map *
4833 read_name_map (dirname)
4834      char *dirname;
4835 {
4836   /* This structure holds a linked list of file name maps, one per
4837      directory.  */
4838   struct file_name_map_list
4839     {
4840       struct file_name_map_list *map_list_next;
4841       char *map_list_name;
4842       struct file_name_map *map_list_map;
4843     };
4844   static struct file_name_map_list *map_list;
4845   register struct file_name_map_list *map_list_ptr;
4846   char *name;
4847   FILE *f;
4848   size_t dirlen;
4849
4850   for (map_list_ptr = map_list; map_list_ptr;
4851        map_list_ptr = map_list_ptr->map_list_next)
4852     if (! strcmp (map_list_ptr->map_list_name, dirname))
4853       return map_list_ptr->map_list_map;
4854
4855   map_list_ptr = ((struct file_name_map_list *)
4856                   xmalloc (sizeof (struct file_name_map_list)));
4857   map_list_ptr->map_list_name = savestring (dirname);
4858   map_list_ptr->map_list_map = NULL;
4859
4860   dirlen = strlen (dirname);
4861   name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4862   strcpy (name, dirname);
4863   strcat (name, FILE_NAME_MAP_FILE);
4864   f = fopen (name, "r");
4865   if (!f)
4866     map_list_ptr->map_list_map = NULL;
4867   else
4868     {
4869       int ch;
4870
4871       while ((ch = getc (f)) != EOF)
4872         {
4873           char *from, *to;
4874           struct file_name_map *ptr;
4875           size_t tolen;
4876
4877           if (is_space[ch])
4878             continue;
4879           from = read_filename_string (ch, f);
4880           while ((ch = getc (f)) != EOF && is_hor_space[ch])
4881             ;
4882           to = read_filename_string (ch, f);
4883
4884           simplify_filename (from);
4885           tolen = simplify_filename (to);
4886
4887           ptr = ((struct file_name_map *)
4888                  xmalloc (sizeof (struct file_name_map)));
4889           ptr->map_from = from;
4890
4891           /* Make the real filename absolute.  */
4892           if (absolute_filename (to))
4893             ptr->map_to = to;
4894           else
4895             {
4896               ptr->map_to = xmalloc (dirlen + tolen + 1);
4897               strcpy (ptr->map_to, dirname);
4898               strcat (ptr->map_to, to);
4899               free (to);
4900             }         
4901
4902           ptr->map_next = map_list_ptr->map_list_map;
4903           map_list_ptr->map_list_map = ptr;
4904
4905           while ((ch = getc (f)) != '\n')
4906             if (ch == EOF)
4907               break;
4908         }
4909       fclose (f);
4910     }
4911   
4912   map_list_ptr->map_list_next = map_list;
4913   map_list = map_list_ptr;
4914
4915   return map_list_ptr->map_list_map;
4916 }  
4917
4918 /* Try to open include file FILENAME.  SEARCHPTR is the directory
4919    being tried from the include file search path.
4920    IMPORTING is "" if we are importing, null otherwise.
4921    Return -2 if found, either a matching name or a matching inode.
4922    Otherwise, open the file and return a file descriptor if successful
4923    or -1 if unsuccessful.
4924    Unless unsuccessful, put a descriptor of the included file into *PINC.
4925    This function maps filenames on file systems based on information read by
4926    read_name_map.  */
4927
4928 static int
4929 open_include_file (filename, searchptr, importing, pinc)
4930      char *filename;
4931      struct file_name_list *searchptr;
4932      U_CHAR *importing;
4933      struct include_file **pinc;
4934 {
4935   char *fname = remap ? remap_include_file (filename, searchptr) : filename;
4936   int fd = -2;
4937
4938   /* Look up FNAME in include_hashtab.  */
4939   struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4940                                                         strlen (fname),
4941                                                         INCLUDE_HASHSIZE)];
4942   struct include_file *inc, *head = *phead;
4943   for (inc = head; inc; inc = inc->next)
4944     if (!strcmp (fname, inc->fname))
4945       break;
4946
4947   if (!inc
4948       || ! inc->control_macro
4949       || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4950
4951     fd = open (fname, O_RDONLY, 0);
4952
4953     if (fd < 0)
4954       return fd;
4955
4956     if (!inc) {
4957       /* FNAME was not in include_hashtab; insert a new entry.  */
4958       inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4959       inc->next = head;
4960       inc->fname = fname;
4961       inc->control_macro = 0;
4962       inc->deps_output = 0;
4963       if (fstat (fd, &inc->st) != 0)
4964         pfatal_with_name (fname);
4965       *phead = inc;
4966
4967       /* Look for another file with the same inode and device.  */
4968       if (lookup_ino_include (inc)
4969           && inc->control_macro
4970           && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4971         close (fd);
4972         fd = -2;
4973       }
4974     }
4975
4976     /* For -M, add this file to the dependencies.  */
4977     if (! inc->deps_output  &&  (system_include_depth != 0) < print_deps) {
4978       inc->deps_output = 1;
4979       deps_output (fname, ' ');
4980     }   
4981
4982     /* Handle -H option.  */
4983     if (print_include_names)
4984       fprintf (stderr, "%*s%s\n", indepth, "", fname);
4985   }
4986
4987   if (importing)
4988     inc->control_macro = importing;
4989
4990   *pinc = inc;
4991   return fd;
4992 }
4993
4994 /* Return the remapped name of the the include file FILENAME.
4995    SEARCHPTR is the directory being tried from the include file path.  */
4996
4997 static char *
4998 remap_include_file (filename, searchptr)
4999      char *filename;
5000      struct file_name_list *searchptr;
5001 {
5002   register struct file_name_map *map;
5003   register char *from;
5004
5005   if (searchptr)
5006     {
5007       if (! searchptr->got_name_map)
5008         {
5009           searchptr->name_map = read_name_map (searchptr->fname);
5010           searchptr->got_name_map = 1;
5011         }
5012
5013       /* Check the mapping for the directory we are using.  */
5014       from = filename + strlen (searchptr->fname);
5015       for (map = searchptr->name_map; map; map = map->map_next)
5016         if (! strcmp (map->map_from, from))
5017           return map->map_to;
5018     }
5019
5020   from = base_name (filename);
5021
5022   if (from != filename || !searchptr)
5023     {
5024       /* Try to find a mapping file for the particular directory we are
5025          looking in.  Thus #include <sys/types.h> will look up sys/types.h
5026          in /usr/include/header.gcc and look up types.h in
5027          /usr/include/sys/header.gcc.  */
5028
5029       char *dir = (char *) alloca (from - filename + 1);
5030       bcopy (filename, dir, from - filename);
5031       dir[from - filename] = '\0';
5032
5033       for (map = read_name_map (dir); map; map = map->map_next)
5034         if (! strcmp (map->map_from, from))
5035           return map->map_to;
5036     }
5037
5038   return filename;
5039 }
5040
5041 /* Insert INC into the include file table, hashed by device and inode number.
5042    If a file with different name but same dev+ino was already in the table,
5043    return 1 and set INC's control macro to the already-known macro.  */
5044
5045 static int
5046 lookup_ino_include (inc)
5047      struct include_file *inc;
5048 {
5049   int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
5050               % INCLUDE_HASHSIZE);
5051   struct include_file *i = include_ino_hashtab[hash];
5052   inc->next_ino = i;
5053   include_ino_hashtab[hash] = inc;
5054
5055   for (; i; i = i->next_ino)
5056     if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
5057         && inc->st.st_dev == i->st.st_dev) {
5058       inc->control_macro = i->control_macro;
5059       return 1;
5060     }
5061
5062   return 0;
5063 }
5064 \f
5065 /* Process file descriptor F, which corresponds to include file INC,
5066    with output to OP.
5067    SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5068    "system" include directories (as decided by the `is_system_include'
5069    function above).
5070    DIRPTR is the link in the dir path through which this file was found,
5071    or 0 if the file name was absolute.  */
5072
5073 static void
5074 finclude (f, inc, op, system_header_p, dirptr)
5075      int f;
5076      struct include_file *inc;
5077      FILE_BUF *op;
5078      int system_header_p;
5079      struct file_name_list *dirptr;
5080 {
5081   char *fname = inc->fname;
5082   int i;
5083   FILE_BUF *fp;                 /* For input stack frame */
5084   int missing_newline = 0;
5085
5086   CHECK_DEPTH (return;);
5087
5088   fp = &instack[indepth + 1];
5089   bzero ((char *) fp, sizeof (FILE_BUF));
5090   fp->nominal_fname = fp->fname = fname;
5091   fp->nominal_fname_len = strlen (fname);
5092   fp->inc = inc;
5093   fp->length = 0;
5094   fp->lineno = 1;
5095   fp->if_stack = if_stack;
5096   fp->system_header_p = system_header_p;
5097   fp->dir = dirptr;
5098
5099   if (S_ISREG (inc->st.st_mode)) {
5100     size_t s = (size_t) inc->st.st_size;
5101     if (s != inc->st.st_size || s + 2 < s)
5102       memory_full ();
5103     fp->buf = (U_CHAR *) xmalloc (s + 2);
5104     fp->bufp = fp->buf;
5105
5106     /* Read the file contents, knowing that s is an upper bound
5107        on the number of bytes we can read.  */
5108     fp->length = safe_read (f, (char *) fp->buf, s);
5109     if (fp->length < 0) goto nope;
5110   }
5111   else if (S_ISDIR (inc->st.st_mode)) {
5112     error ("directory `%s' specified in #include", fname);
5113     close (f);
5114     return;
5115   } else {
5116     /* Cannot count its file size before reading.
5117        First read the entire file into heap and
5118        copy them into buffer on stack.  */
5119
5120     int bsize = 2000;
5121     int st_size = 0;
5122
5123     fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5124
5125     for (;;) {
5126       i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5127       if (i < 0)
5128         goto nope;      /* error! */
5129       st_size += i;
5130       if (st_size != bsize)
5131         break;  /* End of file */
5132       bsize *= 2;
5133       fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5134     }
5135     fp->bufp = fp->buf;
5136     fp->length = st_size;
5137   }
5138
5139   if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5140       /* Backslash-newline at end is not good enough.  */
5141       || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5142     fp->buf[fp->length++] = '\n';
5143     missing_newline = 1;
5144   }
5145   fp->buf[fp->length] = '\0';
5146
5147   /* Close descriptor now, so nesting does not use lots of descriptors.  */
5148   close (f);
5149
5150   /* Must do this before calling trigraph_pcp, so that the correct file name
5151      will be printed in warning messages.  */
5152
5153   indepth++;
5154   input_file_stack_tick++;
5155
5156   if (!no_trigraphs)
5157     trigraph_pcp (fp);
5158
5159   output_line_directive (fp, op, 0, enter_file);
5160   rescan (op, 0);
5161
5162   if (missing_newline)
5163     fp->lineno--;
5164
5165   if (pedantic && missing_newline)
5166     pedwarn ("file does not end in newline");
5167
5168   indepth--;
5169   input_file_stack_tick++;
5170   output_line_directive (&instack[indepth], op, 0, leave_file);
5171   free (fp->buf);
5172   return;
5173
5174  nope:
5175
5176   perror_with_name (fname);
5177   close (f);
5178   free (fp->buf);
5179 }
5180
5181 /* Record that inclusion of the include file INC
5182    should be controlled by the macro named MACRO_NAME.
5183    This means that trying to include the file again
5184    will do something if that macro is defined.  */
5185
5186 static void
5187 record_control_macro (inc, macro_name)
5188      struct include_file *inc;
5189      U_CHAR *macro_name;
5190 {
5191   if (!inc->control_macro || inc->control_macro[0])
5192     inc->control_macro = macro_name;
5193 }
5194 \f
5195 /* Load the specified precompiled header into core, and verify its
5196    preconditions.  PCF indicates the file descriptor to read, which must
5197    be a regular file.  *ST is its file status.
5198    FNAME indicates the file name of the original header.
5199    *LIMIT will be set to an address one past the end of the file.
5200    If the preconditions of the file are not satisfied, the buffer is 
5201    freed and we return 0.  If the preconditions are satisfied, return
5202    the address of the buffer following the preconditions.  The buffer, in
5203    this case, should never be freed because various pieces of it will
5204    be referred to until all precompiled strings are output at the end of
5205    the run.  */
5206
5207 static char *
5208 check_precompiled (pcf, st, fname, limit)
5209      int pcf;
5210      struct stat *st;
5211      char *fname;
5212      char **limit;
5213 {
5214   int length = 0;
5215   char *buf;
5216   char *cp;
5217
5218   if (pcp_outfile)
5219     return 0;
5220
5221   if (S_ISREG (st->st_mode))
5222     {
5223       size_t s = (size_t) st->st_size;
5224       if (s != st->st_size || s + 2 < s)
5225         memory_full ();
5226       buf = xmalloc (s + 2);
5227       length = safe_read (pcf, buf, s);
5228       if (length < 0)
5229         goto nope;
5230     }
5231   else
5232     abort ();
5233     
5234   if (length > 0 && buf[length-1] != '\n')
5235     buf[length++] = '\n';
5236   buf[length] = '\0';
5237   
5238   *limit = buf + length;
5239
5240   /* File is in core.  Check the preconditions.  */
5241   if (!check_preconditions (buf))
5242     goto nope;
5243   for (cp = buf; *cp; cp++)
5244     ;
5245 #ifdef DEBUG_PCP
5246   fprintf (stderr, "Using preinclude %s\n", fname);
5247 #endif
5248   return cp + 1;
5249
5250  nope:
5251 #ifdef DEBUG_PCP
5252   fprintf (stderr, "Cannot use preinclude %s\n", fname);
5253 #endif
5254   free (buf);
5255   return 0;
5256 }
5257
5258 /* PREC (null terminated) points to the preconditions of a
5259    precompiled header.  These are a series of #define and #undef
5260    lines which must match the current contents of the hash
5261    table.  */
5262
5263 static int 
5264 check_preconditions (prec)
5265      char *prec;
5266 {
5267   MACRODEF mdef;
5268   char *lineend;
5269   
5270   while (*prec) {
5271     lineend = index (prec, '\n');
5272     
5273     if (*prec++ != '#') {
5274       error ("Bad format encountered while reading precompiled file");
5275       return 0;
5276     }
5277     if (!strncmp (prec, "define", 6)) {
5278       HASHNODE *hp;
5279       
5280       prec += 6;
5281       mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5282
5283       if (mdef.defn == 0)
5284         abort ();
5285       
5286       if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5287           || (hp->type != T_MACRO && hp->type != T_CONST)
5288           || (hp->type == T_MACRO
5289               && !compare_defs (mdef.defn, hp->value.defn)
5290               && (mdef.defn->length != 2
5291                   || mdef.defn->expansion[0] != '\n'
5292                   || mdef.defn->expansion[1] != ' ')))
5293         return 0;
5294     } else if (!strncmp (prec, "undef", 5)) {
5295       char *name;
5296       int len;
5297       
5298       prec += 5;
5299       while (is_hor_space[(U_CHAR) *prec])
5300         prec++;
5301       name = prec;
5302       while (is_idchar[(U_CHAR) *prec])
5303         prec++;
5304       len = prec - name;
5305       
5306       if (lookup ((U_CHAR *) name, len, -1))
5307         return 0;
5308     } else {
5309       error ("Bad format encountered while reading precompiled file");
5310       return 0;
5311     }
5312     prec = lineend + 1;
5313   }
5314   /* They all passed successfully */
5315   return 1;
5316 }
5317
5318 /* Process the main body of a precompiled file.  BUF points to the
5319    string section of the file, following the preconditions.  LIMIT is one
5320    character past the end.  NAME is the name of the file being read
5321    in.  OP is the main output buffer.  */
5322
5323 static void
5324 pcfinclude (buf, limit, name, op)
5325      U_CHAR *buf, *limit, *name;
5326      FILE_BUF *op;
5327 {
5328   FILE_BUF tmpbuf;
5329   int nstrings;
5330   U_CHAR *cp = buf;
5331
5332   /* First in the file comes 4 bytes indicating the number of strings, */
5333   /* in network byte order. (MSB first).  */
5334   nstrings = *cp++;
5335   nstrings = (nstrings << 8) | *cp++;
5336   nstrings = (nstrings << 8) | *cp++;
5337   nstrings = (nstrings << 8) | *cp++;
5338   
5339   /* Looping over each string...  */
5340   while (nstrings--) {
5341     U_CHAR *string_start;
5342     U_CHAR *endofthiskey;
5343     STRINGDEF *str;
5344     int nkeys;
5345     
5346     /* Each string starts with a STRINGDEF structure (str), followed */
5347     /* by the text of the string (string_start) */
5348
5349     /* First skip to a longword boundary */
5350     /* ??? Why a 4-byte boundary?  On all machines? */
5351     /* NOTE: This works correctly even if size_t
5352        is narrower than a pointer.
5353        Do not try risky measures here to get another type to use!
5354        Do not include stddef.h--it will fail!  */
5355     if ((size_t) cp & 3)
5356       cp += 4 - ((size_t) cp & 3);
5357     
5358     /* Now get the string.  */
5359     str = (STRINGDEF *) (GENERIC_PTR) cp;
5360     string_start = cp += sizeof (STRINGDEF);
5361     
5362     for (; *cp; cp++)           /* skip the string */
5363       ;
5364     
5365     /* We need to macro expand the string here to ensure that the
5366        proper definition environment is in place.  If it were only
5367        expanded when we find out it is needed, macros necessary for
5368        its proper expansion might have had their definitions changed.  */
5369     tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5370     /* Lineno is already set in the precompiled file */
5371     str->contents = tmpbuf.buf;
5372     str->len = tmpbuf.length;
5373     str->writeflag = 0;
5374     str->filename = name;
5375     str->output_mark = outbuf.bufp - outbuf.buf;
5376     
5377     str->chain = 0;
5378     *stringlist_tailp = str;
5379     stringlist_tailp = &str->chain;
5380     
5381     /* Next comes a fourbyte number indicating the number of keys
5382        for this string.  */
5383     nkeys = *cp++;
5384     nkeys = (nkeys << 8) | *cp++;
5385     nkeys = (nkeys << 8) | *cp++;
5386     nkeys = (nkeys << 8) | *cp++;
5387
5388     /* If this number is -1, then the string is mandatory.  */
5389     if (nkeys == -1)
5390       str->writeflag = 1;
5391     else
5392       /* Otherwise, for each key, */
5393       for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5394         KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5395         HASHNODE *hp;
5396         
5397         /* It starts with a KEYDEF structure */
5398         cp += sizeof (KEYDEF);
5399         
5400         /* Find the end of the key.  At the end of this for loop we
5401            advance CP to the start of the next key using this variable.  */
5402         endofthiskey = cp + strlen ((char *) cp);
5403         kp->str = str;
5404         
5405         /* Expand the key, and enter it into the hash table.  */
5406         tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5407         tmpbuf.bufp = tmpbuf.buf;
5408         
5409         while (is_hor_space[*tmpbuf.bufp])
5410           tmpbuf.bufp++;
5411         if (!is_idstart[*tmpbuf.bufp]
5412             || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5413           str->writeflag = 1;
5414           continue;
5415         }
5416             
5417         hp = lookup (tmpbuf.bufp, -1, -1);
5418         if (hp == NULL) {
5419           kp->chain = 0;
5420           install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5421         }
5422         else if (hp->type == T_PCSTRING) {
5423           kp->chain = hp->value.keydef;
5424           hp->value.keydef = kp;
5425         }
5426         else
5427           str->writeflag = 1;
5428       }
5429   }
5430   /* This output_line_directive serves to switch us back to the current
5431      input file in case some of these strings get output (which will 
5432      result in line directives for the header file being output).   */
5433   output_line_directive (&instack[indepth], op, 0, enter_file);
5434 }
5435
5436 /* Called from rescan when it hits a key for strings.  Mark them all
5437    used and clean up.  */
5438
5439 static void
5440 pcstring_used (hp)
5441      HASHNODE *hp;
5442 {
5443   KEYDEF *kp;
5444   
5445   for (kp = hp->value.keydef; kp; kp = kp->chain)
5446     kp->str->writeflag = 1;
5447   delete_macro (hp);
5448 }
5449
5450 /* Write the output, interspersing precompiled strings in their
5451    appropriate places.  */
5452
5453 static void
5454 write_output ()
5455 {
5456   STRINGDEF *next_string;
5457   U_CHAR *cur_buf_loc;
5458   int line_directive_len = 80;
5459   char *line_directive = xmalloc (line_directive_len);
5460   int len;
5461
5462   /* In each run through the loop, either cur_buf_loc ==
5463      next_string_loc, in which case we print a series of strings, or
5464      it is less than next_string_loc, in which case we write some of
5465      the buffer.  */
5466   cur_buf_loc = outbuf.buf; 
5467   next_string = stringlist;
5468   
5469   while (cur_buf_loc < outbuf.bufp || next_string) {
5470     if (next_string
5471         && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5472       if (next_string->writeflag) {
5473         len = 4 * strlen ((char *) next_string->filename) + 32;
5474         while (len > line_directive_len)
5475           line_directive = xrealloc (line_directive, 
5476                                      line_directive_len *= 2);
5477         sprintf (line_directive, "\n# %d ", next_string->lineno);
5478         strcpy (quote_string (line_directive + strlen (line_directive),
5479                               (char *) next_string->filename,
5480                               strlen ((char *) next_string->filename)),
5481                 "\n");
5482         safe_write (fileno (stdout), line_directive, strlen (line_directive));
5483         safe_write (fileno (stdout),
5484                     (char *) next_string->contents, next_string->len);
5485       }       
5486       next_string = next_string->chain;
5487     }
5488     else {
5489       len = (next_string
5490              ? (next_string->output_mark 
5491                 - (cur_buf_loc - outbuf.buf))
5492              : outbuf.bufp - cur_buf_loc);
5493       
5494       safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5495       cur_buf_loc += len;
5496     }
5497   }
5498   free (line_directive);
5499 }
5500
5501 /* Pass a directive through to the output file.
5502    BUF points to the contents of the directive, as a contiguous string.
5503    LIMIT points to the first character past the end of the directive.
5504    KEYWORD is the keyword-table entry for the directive.  */
5505
5506 static void
5507 pass_thru_directive (buf, limit, op, keyword)
5508      U_CHAR *buf, *limit;
5509      FILE_BUF *op;
5510      struct directive *keyword;
5511 {
5512   register unsigned keyword_length = keyword->length;
5513
5514   check_expand (op, 1 + keyword_length + (limit - buf));
5515   *op->bufp++ = '#';
5516   bcopy (keyword->name, (char *) op->bufp, keyword_length);
5517   op->bufp += keyword_length;
5518   if (limit != buf && buf[0] != ' ')
5519     *op->bufp++ = ' ';
5520   bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5521   op->bufp += (limit - buf);
5522 #if 0
5523   *op->bufp++ = '\n';
5524   /* Count the line we have just made in the output,
5525      to get in sync properly.  */
5526   op->lineno++;
5527 #endif
5528 }
5529 \f
5530 /* The arglist structure is built by do_define to tell
5531    collect_definition where the argument names begin.  That
5532    is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5533    would contain pointers to the strings x, y, and z.
5534    Collect_definition would then build a DEFINITION node,
5535    with reflist nodes pointing to the places x, y, and z had
5536    appeared.  So the arglist is just convenience data passed
5537    between these two routines.  It is not kept around after
5538    the current #define has been processed and entered into the
5539    hash table.  */
5540
5541 struct arglist {
5542   struct arglist *next;
5543   U_CHAR *name;
5544   int length;
5545   int argno;
5546   char rest_args;
5547 };
5548
5549 /* Create a DEFINITION node from a #define directive.  Arguments are 
5550    as for do_define.  */
5551
5552 static MACRODEF
5553 create_definition (buf, limit, op)
5554      U_CHAR *buf, *limit;
5555      FILE_BUF *op;
5556 {
5557   U_CHAR *bp;                   /* temp ptr into input buffer */
5558   U_CHAR *symname;              /* remember where symbol name starts */
5559   int sym_length;               /* and how long it is */
5560   int line = instack[indepth].lineno;
5561   char *file = instack[indepth].nominal_fname;
5562   size_t file_len = instack[indepth].nominal_fname_len;
5563   int rest_args = 0;
5564
5565   DEFINITION *defn;
5566   int arglengths = 0;           /* Accumulate lengths of arg names
5567                                    plus number of args.  */
5568   MACRODEF mdef;
5569
5570   bp = buf;
5571
5572   while (is_hor_space[*bp])
5573     bp++;
5574
5575   symname = bp;                 /* remember where it starts */
5576   sym_length = check_macro_name (bp, "macro");
5577   bp += sym_length;
5578
5579   /* Lossage will occur if identifiers or control keywords are broken
5580      across lines using backslash.  This is not the right place to take
5581      care of that.  */
5582
5583   if (*bp == '(') {
5584     struct arglist *arg_ptrs = NULL;
5585     int argno = 0;
5586
5587     bp++;                       /* skip '(' */
5588     SKIP_WHITE_SPACE (bp);
5589
5590     /* Loop over macro argument names.  */
5591     while (*bp != ')') {
5592       struct arglist *temp;
5593
5594       temp = (struct arglist *) alloca (sizeof (struct arglist));
5595       temp->name = bp;
5596       temp->next = arg_ptrs;
5597       temp->argno = argno++;
5598       temp->rest_args = 0;
5599       arg_ptrs = temp;
5600
5601       if (rest_args)
5602         pedwarn ("another parameter follows `%s'",
5603                  rest_extension);
5604
5605       if (!is_idstart[*bp])
5606         pedwarn ("invalid character in macro parameter name");
5607       
5608       /* Find the end of the arg name.  */
5609       while (is_idchar[*bp]) {
5610         bp++;
5611         /* do we have a "special" rest-args extension here? */
5612         if (limit - bp > REST_EXTENSION_LENGTH
5613             && bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5614           if (pedantic && !instack[indepth].system_header_p)
5615             pedwarn ("ANSI C does not allow macro with variable arguments");
5616           rest_args = 1;
5617           temp->rest_args = 1;
5618           break;
5619         }
5620       }
5621       temp->length = bp - temp->name;
5622       if (rest_args == 1)
5623         bp += REST_EXTENSION_LENGTH;
5624       arglengths += temp->length + 2;
5625       SKIP_WHITE_SPACE (bp);
5626       if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5627         error ("badly punctuated parameter list in `#define'");
5628         goto nope;
5629       }
5630       if (*bp == ',') {
5631         bp++;
5632         SKIP_WHITE_SPACE (bp);
5633         /* A comma at this point can only be followed by an identifier.  */
5634         if (!is_idstart[*bp]) {
5635           error ("badly punctuated parameter list in `#define'");
5636           goto nope;
5637         }
5638       }
5639       if (bp >= limit) {
5640         error ("unterminated parameter list in `#define'");
5641         goto nope;
5642       }
5643       {
5644         struct arglist *otemp;
5645
5646         for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5647           if (temp->length == otemp->length
5648               && bcmp (temp->name, otemp->name, temp->length) == 0) {
5649               error ("duplicate argument name `%.*s' in `#define'",
5650                      temp->length, temp->name);
5651               goto nope;
5652           }
5653       }
5654     }
5655
5656     ++bp;                       /* skip paren */
5657     SKIP_WHITE_SPACE (bp);
5658     /* now everything from bp before limit is the definition.  */
5659     defn = collect_expansion (bp, limit, argno, arg_ptrs);
5660     defn->rest_args = rest_args;
5661
5662     /* Now set defn->args.argnames to the result of concatenating
5663        the argument names in reverse order
5664        with comma-space between them.  */
5665     defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5666     {
5667       struct arglist *temp;
5668       int i = 0;
5669       for (temp = arg_ptrs; temp; temp = temp->next) {
5670         bcopy (temp->name, &defn->args.argnames[i], temp->length);
5671         i += temp->length;
5672         if (temp->next != 0) {
5673           defn->args.argnames[i++] = ',';
5674           defn->args.argnames[i++] = ' ';
5675         }
5676       }
5677       defn->args.argnames[i] = 0;
5678     }
5679   } else {
5680     /* Simple expansion or empty definition.  */
5681
5682     if (bp < limit)
5683       {
5684         if (is_hor_space[*bp]) {
5685           bp++;
5686           SKIP_WHITE_SPACE (bp);
5687         } else if (sym_length) {
5688           switch (*bp) {
5689             case '!':  case '"':  case '#':  case '%':  case '&':  case '\'':
5690             case ')':  case '*':  case '+':  case ',':  case '-':  case '.':
5691             case '/':  case ':':  case ';':  case '<':  case '=':  case '>':
5692             case '?':  case '[':  case '\\': case ']':  case '^':  case '{':
5693             case '|':  case '}':  case '~':
5694               warning ("missing white space after `#define %.*s'",
5695                        sym_length, symname);
5696               break;
5697
5698             default:
5699               pedwarn ("missing white space after `#define %.*s'",
5700                        sym_length, symname);
5701               break;
5702           }
5703         }
5704       }
5705     /* Now everything from bp before limit is the definition.  */
5706     defn = collect_expansion (bp, limit, -1, NULL_PTR);
5707     defn->args.argnames = (U_CHAR *) "";
5708   }
5709
5710   defn->line = line;
5711   defn->file = file;
5712   defn->file_len = file_len;
5713
5714   /* OP is null if this is a predefinition */
5715   defn->predefined = !op;
5716   mdef.defn = defn;
5717   mdef.symnam = symname;
5718   mdef.symlen = sym_length;
5719
5720   return mdef;
5721
5722  nope:
5723   mdef.defn = 0;
5724   return mdef;
5725 }
5726  
5727 /* Process a #define directive.
5728 BUF points to the contents of the #define directive, as a contiguous string.
5729 LIMIT points to the first character past the end of the definition.
5730 KEYWORD is the keyword-table entry for #define.  */
5731
5732 static int
5733 do_define (buf, limit, op, keyword)
5734      U_CHAR *buf, *limit;
5735      FILE_BUF *op;
5736      struct directive *keyword;
5737 {
5738   int hashcode;
5739   MACRODEF mdef;
5740
5741   /* If this is a precompiler run (with -pcp) pass thru #define directives.  */
5742   if (pcp_outfile && op)
5743     pass_thru_directive (buf, limit, op, keyword);
5744
5745   mdef = create_definition (buf, limit, op);
5746   if (mdef.defn == 0)
5747     goto nope;
5748
5749   hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5750
5751   {
5752     HASHNODE *hp;
5753     if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5754       int ok = 0;
5755       /* Redefining a precompiled key is ok.  */
5756       if (hp->type == T_PCSTRING)
5757         ok = 1;
5758       /* Redefining a macro is ok if the definitions are the same.  */
5759       else if (hp->type == T_MACRO)
5760         ok = ! compare_defs (mdef.defn, hp->value.defn);
5761       /* Redefining a constant is ok with -D.  */
5762       else if (hp->type == T_CONST)
5763         ok = ! done_initializing;
5764       /* Print the warning if it's not ok.  */
5765       if (!ok) {
5766         /* If we are passing through #define and #undef directives, do
5767            that for this re-definition now.  */
5768         if (debug_output && op)
5769           pass_thru_directive (buf, limit, op, keyword);
5770
5771         pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5772         if (hp->type == T_MACRO)
5773           pedwarn_with_file_and_line (hp->value.defn->file,
5774                                       hp->value.defn->file_len,
5775                                       hp->value.defn->line,
5776                                       "this is the location of the previous definition");
5777       }
5778       /* Replace the old definition.  */
5779       hp->type = T_MACRO;
5780       hp->value.defn = mdef.defn;
5781     } else {
5782       /* If we are passing through #define and #undef directives, do
5783          that for this new definition now.  */
5784       if (debug_output && op)
5785         pass_thru_directive (buf, limit, op, keyword);
5786       install (mdef.symnam, mdef.symlen, T_MACRO,
5787                (char *) mdef.defn, hashcode);
5788     }
5789   }
5790
5791   return 0;
5792
5793 nope:
5794
5795   return 1;
5796 }
5797 \f
5798 /* Check a purported macro name SYMNAME, and yield its length.
5799    USAGE is the kind of name this is intended for.  */
5800
5801 static int
5802 check_macro_name (symname, usage)
5803      U_CHAR *symname;
5804      char *usage;
5805 {
5806   U_CHAR *p;
5807   int sym_length;
5808
5809   for (p = symname; is_idchar[*p]; p++)
5810     ;
5811   sym_length = p - symname;
5812   if (sym_length == 0
5813       || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
5814     error ("invalid %s name", usage);
5815   else if (!is_idstart[*symname]
5816            || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5817     error ("invalid %s name `%.*s'", usage, sym_length, symname);
5818   return sym_length;
5819 }
5820
5821 /* Return zero if two DEFINITIONs are isomorphic.  */
5822      
5823 static int
5824 compare_defs (d1, d2)
5825      DEFINITION *d1, *d2;
5826 {
5827   register struct reflist *a1, *a2;
5828   register U_CHAR *p1 = d1->expansion;
5829   register U_CHAR *p2 = d2->expansion;
5830   int first = 1;
5831
5832   if (d1->nargs != d2->nargs)
5833     return 1;
5834   if (pedantic
5835       && strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5836     return 1;
5837   for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5838        a1 = a1->next, a2 = a2->next) {
5839     if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5840           || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5841         || a1->argno != a2->argno
5842         || a1->stringify != a2->stringify
5843         || a1->raw_before != a2->raw_before
5844         || a1->raw_after != a2->raw_after)
5845       return 1;
5846     first = 0;
5847     p1 += a1->nchars;
5848     p2 += a2->nchars;
5849   }
5850   if (a1 != a2)
5851     return 1;
5852   if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5853                      p2, d2->length - (p2 - d2->expansion), 1))
5854     return 1;
5855   return 0;
5856 }
5857
5858 /* Return 1 if two parts of two macro definitions are effectively different.
5859    One of the parts starts at BEG1 and has LEN1 chars;
5860    the other has LEN2 chars at BEG2.
5861    Any sequence of whitespace matches any other sequence of whitespace.
5862    FIRST means these parts are the first of a macro definition;
5863     so ignore leading whitespace entirely.
5864    LAST means these parts are the last of a macro definition;
5865     so ignore trailing whitespace entirely.  */
5866
5867 static int
5868 comp_def_part (first, beg1, len1, beg2, len2, last)
5869      int first;
5870      U_CHAR *beg1, *beg2;
5871      int len1, len2;
5872      int last;
5873 {
5874   register U_CHAR *end1 = beg1 + len1;
5875   register U_CHAR *end2 = beg2 + len2;
5876   if (first) {
5877     while (beg1 != end1 && is_space[*beg1]) beg1++;
5878     while (beg2 != end2 && is_space[*beg2]) beg2++;
5879   }
5880   if (last) {
5881     while (beg1 != end1 && is_space[end1[-1]]) end1--;
5882     while (beg2 != end2 && is_space[end2[-1]]) end2--;
5883   }
5884   while (beg1 != end1 && beg2 != end2) {
5885     if (is_space[*beg1] && is_space[*beg2]) {
5886       while (beg1 != end1 && is_space[*beg1]) beg1++;
5887       while (beg2 != end2 && is_space[*beg2]) beg2++;
5888     } else if (*beg1 == *beg2) {
5889       beg1++; beg2++;
5890     } else break;
5891   }
5892   return (beg1 != end1) || (beg2 != end2);
5893 }
5894 \f
5895 /* Read a replacement list for a macro with parameters.
5896    Build the DEFINITION structure.
5897    Reads characters of text starting at BUF until END.
5898    ARGLIST specifies the formal parameters to look for
5899    in the text of the definition; NARGS is the number of args
5900    in that list, or -1 for a macro name that wants no argument list.
5901    MACRONAME is the macro name itself (so we can avoid recursive expansion)
5902    and NAMELEN is its length in characters.
5903    
5904 Note that comments, backslash-newlines, and leading white space
5905 have already been deleted from the argument.  */
5906
5907 /* If there is no trailing whitespace, a Newline Space is added at the end
5908    to prevent concatenation that would be contrary to the standard.  */
5909
5910 static DEFINITION *
5911 collect_expansion (buf, end, nargs, arglist)
5912      U_CHAR *buf, *end;
5913      int nargs;
5914      struct arglist *arglist;
5915 {
5916   DEFINITION *defn;
5917   register U_CHAR *p, *limit, *lastp, *exp_p;
5918   struct reflist *endpat = NULL;
5919   /* Pointer to first nonspace after last ## seen.  */
5920   U_CHAR *concat = 0;
5921   /* Pointer to first nonspace after last single-# seen.  */
5922   U_CHAR *stringify = 0;
5923   /* How those tokens were spelled.  */
5924   enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5925   enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5926   int maxsize;
5927   int expected_delimiter = '\0';
5928
5929   /* Scan thru the replacement list, ignoring comments and quoted
5930      strings, picking up on the macro calls.  It does a linear search
5931      thru the arg list on every potential symbol.  Profiling might say
5932      that something smarter should happen.  */
5933
5934   if (end < buf)
5935     abort ();
5936
5937   /* Find the beginning of the trailing whitespace.  */
5938   limit = end;
5939   p = buf;
5940   while (p < limit && is_space[limit[-1]]) limit--;
5941
5942   /* Allocate space for the text in the macro definition.
5943      Each input char may or may not need 1 byte,
5944      so this is an upper bound.
5945      The extra 3 are for invented trailing newline-marker and final null.  */
5946   maxsize = (sizeof (DEFINITION)
5947              + (limit - p) + 3);
5948   defn = (DEFINITION *) xcalloc (1, maxsize);
5949
5950   defn->nargs = nargs;
5951   exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5952   lastp = exp_p;
5953
5954   if (p[0] == '#'
5955       ? p[1] == '#'
5956       : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5957     error ("`##' at start of macro definition");
5958     p += p[0] == '#' ? 2 : 4;
5959   }
5960
5961   /* Process the main body of the definition.  */
5962   while (p < limit) {
5963     int skipped_arg = 0;
5964     register U_CHAR c = *p++;
5965
5966     *exp_p++ = c;
5967
5968     if (!traditional) {
5969       switch (c) {
5970       case '\'':
5971       case '\"':
5972         if (expected_delimiter != '\0') {
5973           if (c == expected_delimiter)
5974             expected_delimiter = '\0';
5975         } else
5976           expected_delimiter = c;
5977         break;
5978
5979       case '\\':
5980         if (p < limit && expected_delimiter) {
5981           /* In a string, backslash goes through
5982              and makes next char ordinary.  */
5983           *exp_p++ = *p++;
5984         }
5985         break;
5986
5987       case '%':
5988         if (!expected_delimiter && *p == ':') {
5989           /* %: is not a digraph if preceded by an odd number of '<'s.  */
5990           U_CHAR *p0 = p - 1;
5991           while (buf < p0 && p0[-1] == '<')
5992             p0--;
5993           if ((p - p0) & 1) {
5994             /* Treat %:%: as ## and %: as #.  */
5995             if (p[1] == '%' && p[2] == ':') {
5996               p += 2;
5997               goto sharp_sharp_token;
5998             }
5999             if (nargs >= 0) {
6000               p++;
6001               goto sharp_token;
6002             }
6003           }
6004         }
6005         break;
6006
6007       case '#':
6008         /* # is ordinary inside a string.  */
6009         if (expected_delimiter)
6010           break;
6011         if (*p == '#') {
6012         sharp_sharp_token:
6013           /* ##: concatenate preceding and following tokens.  */
6014           /* Take out the first #, discard preceding whitespace.  */
6015           exp_p--;
6016           while (exp_p > lastp && is_hor_space[exp_p[-1]])
6017             --exp_p;
6018           /* Skip the second #.  */
6019           p++;
6020           concat_sharp_token_type = c;
6021           if (is_hor_space[*p]) {
6022             concat_sharp_token_type = c + 1;
6023             p++;
6024             SKIP_WHITE_SPACE (p);
6025           }
6026           concat = p;
6027           if (p == limit)
6028             error ("`##' at end of macro definition");
6029         } else if (nargs >= 0) {
6030           /* Single #: stringify following argument ref.
6031              Don't leave the # in the expansion.  */
6032         sharp_token:
6033           exp_p--;
6034           stringify_sharp_token_type = c;
6035           if (is_hor_space[*p]) {
6036             stringify_sharp_token_type = c + 1;
6037             p++;
6038             SKIP_WHITE_SPACE (p);
6039           }
6040           if (! is_idstart[*p] || nargs == 0
6041               || (*p == 'L' && (p[1] == '\'' || p[1] == '"')))
6042             error ("`#' operator is not followed by a macro argument name");
6043           else
6044             stringify = p;
6045         }
6046         break;
6047       }
6048     } else {
6049       /* In -traditional mode, recognize arguments inside strings and
6050          and character constants, and ignore special properties of #.
6051          Arguments inside strings are considered "stringified", but no
6052          extra quote marks are supplied.  */
6053       switch (c) {
6054       case '\'':
6055       case '\"':
6056         if (expected_delimiter != '\0') {
6057           if (c == expected_delimiter)
6058             expected_delimiter = '\0';
6059         } else
6060           expected_delimiter = c;
6061         break;
6062
6063       case '\\':
6064         /* Backslash quotes delimiters and itself, but not macro args.  */
6065         if (expected_delimiter != 0 && p < limit
6066             && (*p == expected_delimiter || *p == '\\')) {
6067           *exp_p++ = *p++;
6068           continue;
6069         }
6070         break;
6071
6072       case '/':
6073         if (expected_delimiter != '\0') /* No comments inside strings.  */
6074           break;
6075         if (*p == '*') {
6076           /* If we find a comment that wasn't removed by handle_directive,
6077              this must be -traditional.  So replace the comment with
6078              nothing at all.  */
6079           exp_p--;
6080           while (++p < limit) {
6081             if (p[0] == '*' && p[1] == '/') {
6082               p += 2;
6083               break;
6084             }
6085           }
6086 #if 0
6087           /* Mark this as a concatenation-point, as if it had been ##.  */
6088           concat = p;
6089 #endif
6090         }
6091         break;
6092       }
6093     }
6094
6095     /* Handle the start of a symbol.  */
6096     if (is_idchar[c] && nargs > 0) {
6097       U_CHAR *id_beg = p - 1;
6098       int id_len;
6099
6100       --exp_p;
6101       while (p != limit && is_idchar[*p]) p++;
6102       id_len = p - id_beg;
6103
6104       if (is_idstart[c]
6105           && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
6106         register struct arglist *arg;
6107
6108         for (arg = arglist; arg != NULL; arg = arg->next) {
6109           struct reflist *tpat;
6110
6111           if (arg->name[0] == c
6112               && arg->length == id_len
6113               && bcmp (arg->name, id_beg, id_len) == 0) {
6114             enum sharp_token_type tpat_stringify;
6115             if (expected_delimiter) {
6116               if (warn_stringify) {
6117                 if (traditional) {
6118                   warning ("macro argument `%.*s' is stringified.",
6119                            id_len, arg->name);
6120                 } else {
6121                   warning ("macro arg `%.*s' would be stringified with -traditional.",
6122                            id_len, arg->name);
6123                 }
6124               }
6125               /* If ANSI, don't actually substitute inside a string.  */
6126               if (!traditional)
6127                 break;
6128               tpat_stringify = SHARP_TOKEN;
6129             } else {
6130               tpat_stringify
6131                 = (stringify == id_beg
6132                    ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6133             }
6134             /* make a pat node for this arg and append it to the end of
6135                the pat list */
6136             tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6137             tpat->next = NULL;
6138             tpat->raw_before
6139               = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6140             tpat->raw_after = NO_SHARP_TOKEN;
6141             tpat->rest_args = arg->rest_args;
6142             tpat->stringify = tpat_stringify;
6143
6144             if (endpat == NULL)
6145               defn->pattern = tpat;
6146             else
6147               endpat->next = tpat;
6148             endpat = tpat;
6149
6150             tpat->argno = arg->argno;
6151             tpat->nchars = exp_p - lastp;
6152             {
6153               register U_CHAR *p1 = p;
6154               SKIP_WHITE_SPACE (p1);
6155               if (p1[0]=='#'
6156                   ? p1[1]=='#'
6157                   : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6158                 tpat->raw_after = p1[0] + (p != p1);
6159             }
6160             lastp = exp_p;      /* place to start copying from next time */
6161             skipped_arg = 1;
6162             break;
6163           }
6164         }
6165       }
6166
6167       /* If this was not a macro arg, copy it into the expansion.  */
6168       if (! skipped_arg) {
6169         register U_CHAR *lim1 = p;
6170         p = id_beg;
6171         while (p != lim1)
6172           *exp_p++ = *p++;
6173         if (stringify == id_beg)
6174           error ("`#' operator should be followed by a macro argument name");
6175       }
6176     }
6177   }
6178
6179   if (!traditional && expected_delimiter == 0) {
6180     /* If ANSI, put in a newline-space marker to prevent token pasting.
6181        But not if "inside a string" (which in ANSI mode happens only for
6182        -D option).  */
6183     *exp_p++ = '\n';
6184     *exp_p++ = ' ';
6185   }
6186
6187   *exp_p = '\0';
6188
6189   defn->length = exp_p - defn->expansion;
6190
6191   /* Crash now if we overrun the allocated size.  */
6192   if (defn->length + 1 > maxsize)
6193     abort ();
6194
6195 #if 0
6196 /* This isn't worth the time it takes.  */
6197   /* give back excess storage */
6198   defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6199 #endif
6200
6201   return defn;
6202 }
6203 \f
6204 static int
6205 do_assert (buf, limit, op, keyword)
6206      U_CHAR *buf, *limit;
6207      FILE_BUF *op;
6208      struct directive *keyword;
6209 {
6210   U_CHAR *bp;                   /* temp ptr into input buffer */
6211   U_CHAR *symname;              /* remember where symbol name starts */
6212   int sym_length;               /* and how long it is */
6213   struct arglist *tokens = NULL;
6214
6215   if (pedantic && done_initializing && !instack[indepth].system_header_p)
6216     pedwarn ("ANSI C does not allow `#assert'");
6217
6218   bp = buf;
6219
6220   while (is_hor_space[*bp])
6221     bp++;
6222
6223   symname = bp;                 /* remember where it starts */
6224   sym_length = check_macro_name (bp, "assertion");
6225   bp += sym_length;
6226   /* #define doesn't do this, but we should.  */
6227   SKIP_WHITE_SPACE (bp);
6228
6229   /* Lossage will occur if identifiers or control tokens are broken
6230      across lines using backslash.  This is not the right place to take
6231      care of that.  */
6232
6233   if (*bp != '(') {
6234     error ("missing token-sequence in `#assert'");
6235     return 1;
6236   }
6237
6238   {
6239     int error_flag = 0;
6240
6241     bp++;                       /* skip '(' */
6242     SKIP_WHITE_SPACE (bp);
6243
6244     tokens = read_token_list (&bp, limit, &error_flag);
6245     if (error_flag)
6246       return 1;
6247     if (tokens == 0) {
6248       error ("empty token-sequence in `#assert'");
6249       return 1;
6250     }
6251
6252     ++bp;                       /* skip paren */
6253     SKIP_WHITE_SPACE (bp);
6254   }
6255
6256   /* If this name isn't already an assertion name, make it one.
6257      Error if it was already in use in some other way.  */
6258
6259   {
6260     ASSERTION_HASHNODE *hp;
6261     int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6262     struct tokenlist_list *value
6263       = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6264
6265     hp = assertion_lookup (symname, sym_length, hashcode);
6266     if (hp == NULL) {
6267       if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6268         error ("`defined' redefined as assertion");
6269       hp = assertion_install (symname, sym_length, hashcode);
6270     }
6271
6272     /* Add the spec'd token-sequence to the list of such.  */
6273     value->tokens = tokens;
6274     value->next = hp->value;
6275     hp->value = value;
6276   }
6277
6278   return 0;
6279 }
6280 \f
6281 static int
6282 do_unassert (buf, limit, op, keyword)
6283      U_CHAR *buf, *limit;
6284      FILE_BUF *op;
6285      struct directive *keyword;
6286 {
6287   U_CHAR *bp;                   /* temp ptr into input buffer */
6288   U_CHAR *symname;              /* remember where symbol name starts */
6289   int sym_length;               /* and how long it is */
6290
6291   struct arglist *tokens = NULL;
6292   int tokens_specified = 0;
6293
6294   if (pedantic && done_initializing && !instack[indepth].system_header_p)
6295     pedwarn ("ANSI C does not allow `#unassert'");
6296
6297   bp = buf;
6298
6299   while (is_hor_space[*bp])
6300     bp++;
6301
6302   symname = bp;                 /* remember where it starts */
6303   sym_length = check_macro_name (bp, "assertion");
6304   bp += sym_length;
6305   /* #define doesn't do this, but we should.  */
6306   SKIP_WHITE_SPACE (bp);
6307
6308   /* Lossage will occur if identifiers or control tokens are broken
6309      across lines using backslash.  This is not the right place to take
6310      care of that.  */
6311
6312   if (*bp == '(') {
6313     int error_flag = 0;
6314
6315     bp++;                       /* skip '(' */
6316     SKIP_WHITE_SPACE (bp);
6317
6318     tokens = read_token_list (&bp, limit, &error_flag);
6319     if (error_flag)
6320       return 1;
6321     if (tokens == 0) {
6322       error ("empty token list in `#unassert'");
6323       return 1;
6324     }
6325
6326     tokens_specified = 1;
6327
6328     ++bp;                       /* skip paren */
6329     SKIP_WHITE_SPACE (bp);
6330   }
6331
6332   {
6333     ASSERTION_HASHNODE *hp;
6334     int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6335     struct tokenlist_list *tail, *prev;
6336
6337     hp = assertion_lookup (symname, sym_length, hashcode);
6338     if (hp == NULL)
6339       return 1;
6340
6341     /* If no token list was specified, then eliminate this assertion
6342        entirely.  */
6343     if (! tokens_specified) {
6344       struct tokenlist_list *next;
6345       for (tail = hp->value; tail; tail = next) {
6346         next = tail->next;
6347         free_token_list (tail->tokens);
6348         free (tail);
6349       }
6350       delete_assertion (hp);
6351     } else {
6352       /* If a list of tokens was given, then delete any matching list.  */
6353
6354       tail = hp->value;
6355       prev = 0;
6356       while (tail) {
6357         struct tokenlist_list *next = tail->next;
6358         if (compare_token_lists (tail->tokens, tokens)) {
6359           if (prev)
6360             prev->next = next;
6361           else
6362             hp->value = tail->next;
6363           free_token_list (tail->tokens);
6364           free (tail);
6365         } else {
6366           prev = tail;
6367         }
6368         tail = next;
6369       }
6370     }
6371   }
6372
6373   return 0;
6374 }
6375 \f
6376 /* Test whether there is an assertion named NAME
6377    and optionally whether it has an asserted token list TOKENS.
6378    NAME is not null terminated; its length is SYM_LENGTH.
6379    If TOKENS_SPECIFIED is 0, then don't check for any token list.  */
6380
6381 int
6382 check_assertion (name, sym_length, tokens_specified, tokens)
6383      U_CHAR *name;
6384      int sym_length;
6385      int tokens_specified;
6386      struct arglist *tokens;
6387 {
6388   ASSERTION_HASHNODE *hp;
6389   int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6390
6391   if (pedantic && !instack[indepth].system_header_p)
6392     pedwarn ("ANSI C does not allow testing assertions");
6393
6394   hp = assertion_lookup (name, sym_length, hashcode);
6395   if (hp == NULL)
6396     /* It is not an assertion; just return false.  */
6397     return 0;
6398
6399   /* If no token list was specified, then value is 1.  */
6400   if (! tokens_specified)
6401     return 1;
6402
6403   {
6404     struct tokenlist_list *tail;
6405
6406     tail = hp->value;
6407
6408     /* If a list of tokens was given,
6409        then succeed if the assertion records a matching list.  */
6410
6411     while (tail) {
6412       if (compare_token_lists (tail->tokens, tokens))
6413         return 1;
6414       tail = tail->next;
6415     }
6416
6417     /* Fail if the assertion has no matching list.  */
6418     return 0;
6419   }
6420 }
6421
6422 /* Compare two lists of tokens for equality including order of tokens.  */
6423
6424 static int
6425 compare_token_lists (l1, l2)
6426      struct arglist *l1, *l2;
6427 {
6428   while (l1 && l2) {
6429     if (l1->length != l2->length)
6430       return 0;
6431     if (bcmp (l1->name, l2->name, l1->length))
6432       return 0;
6433     l1 = l1->next;
6434     l2 = l2->next;
6435   }
6436
6437   /* Succeed if both lists end at the same time.  */
6438   return l1 == l2;
6439 }
6440 \f
6441 /* Read a space-separated list of tokens ending in a close parenthesis.
6442    Return a list of strings, in the order they were written.
6443    (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6444    Parse the text starting at *BPP, and update *BPP.
6445    Don't parse beyond LIMIT.  */
6446
6447 static struct arglist *
6448 read_token_list (bpp, limit, error_flag)
6449      U_CHAR **bpp;
6450      U_CHAR *limit;
6451      int *error_flag;
6452 {
6453   struct arglist *token_ptrs = 0;
6454   U_CHAR *bp = *bpp;
6455   int depth = 1;
6456
6457   *error_flag = 0;
6458
6459   /* Loop over the assertion value tokens.  */
6460   while (depth > 0) {
6461     struct arglist *temp;
6462     int eofp = 0;
6463     U_CHAR *beg = bp;
6464
6465     /* Find the end of the token.  */
6466     if (*bp == '(') {
6467       bp++;
6468       depth++;
6469     } else if (*bp == ')') {
6470       depth--;
6471       if (depth == 0)
6472         break;
6473       bp++;
6474     } else if (*bp == '"' || *bp == '\'')
6475       bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6476     else
6477       while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6478              && *bp != '"' && *bp != '\'' && bp != limit)
6479         bp++;
6480
6481     temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6482     temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6483     bcopy ((char *) beg, (char *) temp->name, bp - beg);
6484     temp->name[bp - beg] = 0;
6485     temp->next = token_ptrs;
6486     token_ptrs = temp;
6487     temp->length = bp - beg;
6488
6489     SKIP_WHITE_SPACE (bp);
6490
6491     if (bp >= limit) {
6492       error ("unterminated token sequence in `#assert' or `#unassert'");
6493       *error_flag = -1;
6494       return 0;
6495     }
6496   }
6497   *bpp = bp;
6498
6499   /* We accumulated the names in reverse order.
6500      Now reverse them to get the proper order.  */
6501   {
6502     register struct arglist *prev = 0, *this, *next;
6503     for (this = token_ptrs; this; this = next) {
6504       next = this->next;
6505       this->next = prev;
6506       prev = this;
6507     }
6508     return prev;
6509   }
6510 }
6511
6512 static void
6513 free_token_list (tokens)
6514      struct arglist *tokens;
6515 {
6516   while (tokens) {
6517     struct arglist *next = tokens->next;
6518     free (tokens->name);
6519     free (tokens);
6520     tokens = next;
6521   }
6522 }
6523 \f
6524 /* Install a name in the assertion hash table.
6525
6526    If LEN is >= 0, it is the length of the name.
6527    Otherwise, compute the length by scanning the entire name.
6528
6529    If HASH is >= 0, it is the precomputed hash code.
6530    Otherwise, compute the hash code.  */
6531
6532 static ASSERTION_HASHNODE *
6533 assertion_install (name, len, hash)
6534      U_CHAR *name;
6535      int len;
6536      int hash;
6537 {
6538   register ASSERTION_HASHNODE *hp;
6539   register int i, bucket;
6540   register U_CHAR *p, *q;
6541
6542   i = sizeof (ASSERTION_HASHNODE) + len + 1;
6543   hp = (ASSERTION_HASHNODE *) xmalloc (i);
6544   bucket = hash;
6545   hp->bucket_hdr = &assertion_hashtab[bucket];
6546   hp->next = assertion_hashtab[bucket];
6547   assertion_hashtab[bucket] = hp;
6548   hp->prev = NULL;
6549   if (hp->next != NULL)
6550     hp->next->prev = hp;
6551   hp->length = len;
6552   hp->value = 0;
6553   hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6554   p = hp->name;
6555   q = name;
6556   for (i = 0; i < len; i++)
6557     *p++ = *q++;
6558   hp->name[len] = 0;
6559   return hp;
6560 }
6561
6562 /* Find the most recent hash node for name name (ending with first
6563    non-identifier char) installed by install
6564
6565    If LEN is >= 0, it is the length of the name.
6566    Otherwise, compute the length by scanning the entire name.
6567
6568    If HASH is >= 0, it is the precomputed hash code.
6569    Otherwise, compute the hash code.  */
6570
6571 static ASSERTION_HASHNODE *
6572 assertion_lookup (name, len, hash)
6573      U_CHAR *name;
6574      int len;
6575      int hash;
6576 {
6577   register ASSERTION_HASHNODE *bucket;
6578
6579   bucket = assertion_hashtab[hash];
6580   while (bucket) {
6581     if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6582       return bucket;
6583     bucket = bucket->next;
6584   }
6585   return NULL;
6586 }
6587
6588 static void
6589 delete_assertion (hp)
6590      ASSERTION_HASHNODE *hp;
6591 {
6592
6593   if (hp->prev != NULL)
6594     hp->prev->next = hp->next;
6595   if (hp->next != NULL)
6596     hp->next->prev = hp->prev;
6597
6598   /* Make sure that the bucket chain header that the deleted guy was
6599      on points to the right thing afterwards.  */
6600   if (hp == *hp->bucket_hdr)
6601     *hp->bucket_hdr = hp->next;
6602
6603   free (hp);
6604 }
6605 \f
6606 /*
6607  * interpret #line directive.  Remembers previously seen fnames
6608  * in its very own hash table.
6609  */
6610 #define FNAME_HASHSIZE 37
6611
6612 static int
6613 do_line (buf, limit, op, keyword)
6614      U_CHAR *buf, *limit;
6615      FILE_BUF *op;
6616      struct directive *keyword;
6617 {
6618   register U_CHAR *bp;
6619   FILE_BUF *ip = &instack[indepth];
6620   FILE_BUF tem;
6621   int new_lineno;
6622   enum file_change_code file_change = same_file;
6623
6624   /* Expand any macros.  */
6625   tem = expand_to_temp_buffer (buf, limit, 0, 0);
6626
6627   /* Point to macroexpanded line, which is null-terminated now.  */
6628   bp = tem.buf;
6629   SKIP_WHITE_SPACE (bp);
6630
6631   if (!isdigit (*bp)) {
6632     error ("invalid format `#line' directive");
6633     return 0;
6634   }
6635
6636   /* The Newline at the end of this line remains to be processed.
6637      To put the next line at the specified line number,
6638      we must store a line number now that is one less.  */
6639   new_lineno = atoi ((char *) bp) - 1;
6640
6641   /* NEW_LINENO is one less than the actual line number here.  */
6642   if (pedantic && new_lineno < 0)
6643     pedwarn ("line number out of range in `#line' directive");
6644
6645   /* skip over the line number.  */
6646   while (isdigit (*bp))
6647     bp++;
6648
6649 #if 0 /* #line 10"foo.c" is supposed to be allowed.  */
6650   if (*bp && !is_space[*bp]) {
6651     error ("invalid format `#line' directive");
6652     return;
6653   }
6654 #endif
6655
6656   SKIP_WHITE_SPACE (bp);
6657
6658   if (*bp == '\"') {
6659     static HASHNODE *fname_table[FNAME_HASHSIZE];
6660     HASHNODE *hp, **hash_bucket;
6661     U_CHAR *fname, *p;
6662     int fname_length;
6663
6664     fname = ++bp;
6665
6666     /* Turn the file name, which is a character string literal,
6667        into a null-terminated string.  Do this in place.  */
6668     p = bp;
6669     for (;;)
6670       switch ((*p++ = *bp++)) {
6671       case '\0':
6672         error ("invalid format `#line' directive");
6673         return 0;
6674
6675       case '\\':
6676         {
6677           char *bpc = (char *) bp;
6678           HOST_WIDE_INT c = parse_escape (&bpc, (HOST_WIDE_INT) (U_CHAR) (-1));
6679           bp = (U_CHAR *) bpc;
6680           if (c < 0)
6681             p--;
6682           else
6683             p[-1] = c;
6684         }
6685         break;
6686
6687       case '\"':
6688         *--p = 0;
6689         goto fname_done;
6690       }
6691   fname_done:
6692     fname_length = p - fname;
6693
6694     SKIP_WHITE_SPACE (bp);
6695     if (*bp) {
6696       if (pedantic)
6697         pedwarn ("garbage at end of `#line' directive");
6698       if (*bp == '1')
6699         file_change = enter_file;
6700       else if (*bp == '2')
6701         file_change = leave_file;
6702       else if (*bp == '3')
6703         ip->system_header_p = 1;
6704       else if (*bp == '4')
6705         ip->system_header_p = 2;
6706       else {
6707         error ("invalid format `#line' directive");
6708         return 0;
6709       }
6710
6711       bp++;
6712       SKIP_WHITE_SPACE (bp);
6713       if (*bp == '3') {
6714         ip->system_header_p = 1;
6715         bp++;
6716         SKIP_WHITE_SPACE (bp);
6717       }
6718       if (*bp == '4') {
6719         ip->system_header_p = 2;
6720         bp++;
6721         SKIP_WHITE_SPACE (bp);
6722       }
6723       if (*bp) {
6724         error ("invalid format `#line' directive");
6725         return 0;
6726       }
6727     }
6728
6729     hash_bucket = &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6730     for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6731       if (hp->length == fname_length &&
6732           bcmp (hp->value.cpval, fname, fname_length) == 0) {
6733         ip->nominal_fname = hp->value.cpval;
6734         ip->nominal_fname_len = fname_length;
6735         break;
6736       }
6737     if (hp == 0) {
6738       /* Didn't find it; cons up a new one.  */
6739       hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6740       hp->next = *hash_bucket;
6741       *hash_bucket = hp;
6742
6743       ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6744       ip->nominal_fname_len = hp->length = fname_length;
6745       bcopy (fname, hp->value.cpval, fname_length + 1);
6746     }
6747   } else if (*bp) {
6748     error ("invalid format `#line' directive");
6749     return 0;
6750   }
6751
6752   ip->lineno = new_lineno;
6753   output_line_directive (ip, op, 0, file_change);
6754   check_expand (op, ip->length - (ip->bufp - ip->buf));
6755   return 0;
6756 }
6757
6758 /* Remove the definition of a symbol from the symbol table.
6759    according to un*x /lib/cpp, it is not an error to undef
6760    something that has no definitions, so it isn't one here either.  */
6761
6762 static int
6763 do_undef (buf, limit, op, keyword)
6764      U_CHAR *buf, *limit;
6765      FILE_BUF *op;
6766      struct directive *keyword;
6767 {
6768   int sym_length;
6769   HASHNODE *hp;
6770   U_CHAR *orig_buf = buf;
6771
6772   /* If this is a precompiler run (with -pcp) pass thru #undef directives.  */
6773   if (pcp_outfile && op)
6774     pass_thru_directive (buf, limit, op, keyword);
6775
6776   SKIP_WHITE_SPACE (buf);
6777   sym_length = check_macro_name (buf, "macro");
6778
6779   while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6780     /* If we are generating additional info for debugging (with -g) we
6781        need to pass through all effective #undef directives.  */
6782     if (debug_output && op)
6783       pass_thru_directive (orig_buf, limit, op, keyword);
6784     if (hp->type != T_MACRO)
6785       warning ("undefining `%s'", hp->name);
6786     delete_macro (hp);
6787   }
6788
6789   if (pedantic) {
6790     buf += sym_length;
6791     SKIP_WHITE_SPACE (buf);
6792     if (buf != limit)
6793       pedwarn ("garbage after `#undef' directive");
6794   }
6795   return 0;
6796 }
6797 \f
6798 /* Report an error detected by the program we are processing.
6799    Use the text of the line in the error message.
6800    (We use error because it prints the filename & line#.)  */
6801
6802 static int
6803 do_error (buf, limit, op, keyword)
6804      U_CHAR *buf, *limit;
6805      FILE_BUF *op;
6806      struct directive *keyword;
6807 {
6808   int length = limit - buf;
6809   U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6810   bcopy ((char *) buf, (char *) copy, length);
6811   copy[length] = 0;
6812   SKIP_WHITE_SPACE (copy);
6813   error ("#error %s", copy);
6814   return 0;
6815 }
6816
6817 /* Report a warning detected by the program we are processing.
6818    Use the text of the line in the warning message, then continue.
6819    (We use error because it prints the filename & line#.)  */
6820
6821 static int
6822 do_warning (buf, limit, op, keyword)
6823      U_CHAR *buf, *limit;
6824      FILE_BUF *op;
6825      struct directive *keyword;
6826 {
6827   int length = limit - buf;
6828   U_CHAR *copy = (U_CHAR *) alloca (length + 1);
6829   bcopy ((char *) buf, (char *) copy, length);
6830   copy[length] = 0;
6831   SKIP_WHITE_SPACE (copy);
6832
6833   if (pedantic && !instack[indepth].system_header_p)
6834     pedwarn ("ANSI C does not allow `#warning'");
6835
6836   /* Use `pedwarn' not `warning', because #warning isn't in the C Standard;
6837      if -pedantic-errors is given, #warning should cause an error.  */
6838   pedwarn ("#warning %s", copy);
6839   return 0;
6840 }
6841
6842 /* Remember the name of the current file being read from so that we can
6843    avoid ever including it again.  */
6844
6845 static void
6846 do_once ()
6847 {
6848   int i;
6849
6850   for (i = indepth; i >= 0; i--)
6851     if (instack[i].inc) {
6852       record_control_macro (instack[i].inc, (U_CHAR *) "");
6853       break;
6854     }
6855 }
6856
6857 /* Report program identification.  */
6858
6859 static int
6860 do_ident (buf, limit, op, keyword)
6861      U_CHAR *buf, *limit;
6862      FILE_BUF *op;
6863      struct directive *keyword;
6864 {
6865   FILE_BUF trybuf;
6866   int len;
6867
6868   /* Allow #ident in system headers, since that's not user's fault.  */
6869   if (pedantic && !instack[indepth].system_header_p)
6870     pedwarn ("ANSI C does not allow `#ident'");
6871
6872   trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6873   buf = trybuf.buf;
6874   len = trybuf.bufp - buf;
6875
6876   /* Output expanded directive.  */
6877   check_expand (op, 7 + len);
6878   bcopy ("#ident ", (char *) op->bufp, 7);
6879   op->bufp += 7;
6880   bcopy ((char *) buf, (char *) op->bufp, len);
6881   op->bufp += len;
6882
6883   free (buf);
6884   return 0;
6885 }
6886
6887 /* #pragma and its argument line have already been copied to the output file.
6888    Just check for some recognized pragmas that need validation here.  */
6889
6890 static int
6891 do_pragma (buf, limit, op, keyword)
6892      U_CHAR *buf, *limit;
6893      FILE_BUF *op;
6894      struct directive *keyword;
6895 {
6896   SKIP_WHITE_SPACE (buf);
6897   if (!strncmp ((char *) buf, "once", 4)) {
6898     /* Allow #pragma once in system headers, since that's not the user's
6899        fault.  */
6900     if (!instack[indepth].system_header_p)
6901       warning ("`#pragma once' is obsolete");
6902     do_once ();
6903   }
6904
6905   if (!strncmp ((char *) buf, "implementation", 14)) {
6906     /* Be quiet about `#pragma implementation' for a file only if it hasn't
6907        been included yet.  */
6908
6909     int h;
6910     U_CHAR *p = buf + 14, *fname;
6911     SKIP_WHITE_SPACE (p);
6912     if (*p != '\"')
6913       return 0;
6914
6915     fname = p + 1;
6916     if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6917       *p = '\0';
6918     
6919     for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6920       struct include_file *inc;
6921       for (inc = include_hashtab[h]; inc; inc = inc->next) {
6922         if (!strcmp (base_name (inc->fname), (char *) fname)) {
6923           warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6924           return 0;
6925         }
6926       }
6927     }
6928   }
6929   return 0;
6930 }
6931
6932 #if 0
6933 /* This was a fun hack, but #pragma seems to start to be useful.
6934    By failing to recognize it, we pass it through unchanged to cc1.  */
6935
6936 /* The behavior of the #pragma directive is implementation defined.
6937    this implementation defines it as follows.  */
6938
6939 static int
6940 do_pragma ()
6941 {
6942   close (0);
6943   if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6944     goto nope;
6945   close (1);
6946   if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6947     goto nope;
6948   execl ("/usr/games/hack", "#pragma", 0);
6949   execl ("/usr/games/rogue", "#pragma", 0);
6950   execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6951   execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6952 nope:
6953   fatal ("You are in a maze of twisty compiler features, all different");
6954 }
6955 #endif
6956
6957 #ifdef SCCS_DIRECTIVE
6958
6959 /* Just ignore #sccs, on systems where we define it at all.  */
6960
6961 static int
6962 do_sccs (buf, limit, op, keyword)
6963      U_CHAR *buf, *limit;
6964      FILE_BUF *op;
6965      struct directive *keyword;
6966 {
6967   if (pedantic)
6968     pedwarn ("ANSI C does not allow `#sccs'");
6969   return 0;
6970 }
6971
6972 #endif /* defined (SCCS_DIRECTIVE) */
6973 \f
6974 /* Handle #if directive by
6975      1) inserting special `defined' keyword into the hash table
6976         that gets turned into 0 or 1 by special_symbol (thus,
6977         if the luser has a symbol called `defined' already, it won't
6978         work inside the #if directive)
6979      2) rescan the input into a temporary output buffer
6980      3) pass the output buffer to the yacc parser and collect a value
6981      4) clean up the mess left from steps 1 and 2.
6982      5) call conditional_skip to skip til the next #endif (etc.),
6983         or not, depending on the value from step 3.  */
6984
6985 static int
6986 do_if (buf, limit, op, keyword)
6987      U_CHAR *buf, *limit;
6988      FILE_BUF *op;
6989      struct directive *keyword;
6990 {
6991   HOST_WIDE_INT value;
6992   FILE_BUF *ip = &instack[indepth];
6993
6994   value = eval_if_expression (buf, limit - buf);
6995   conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6996   return 0;
6997 }
6998
6999 /* Handle a #elif directive by not changing  if_stack  either.
7000    see the comment above do_else.  */
7001
7002 static int
7003 do_elif (buf, limit, op, keyword)
7004      U_CHAR *buf, *limit;
7005      FILE_BUF *op;
7006      struct directive *keyword;
7007 {
7008   HOST_WIDE_INT value;
7009   FILE_BUF *ip = &instack[indepth];
7010
7011   if (if_stack == instack[indepth].if_stack) {
7012     error ("`#elif' not within a conditional");
7013     return 0;
7014   } else {
7015     if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7016       error ("`#elif' after `#else'");
7017       fprintf (stderr, " (matches line %d", if_stack->lineno);
7018       if (! (if_stack->fname_len == ip->nominal_fname_len
7019              && !bcmp (if_stack->fname, ip->nominal_fname,
7020                        if_stack->fname_len))) {
7021         fprintf (stderr, ", file ");
7022         eprint_string (if_stack->fname, if_stack->fname_len);
7023       }
7024       fprintf (stderr, ")\n");
7025     }
7026     if_stack->type = T_ELIF;
7027   }
7028
7029   if (if_stack->if_succeeded)
7030     skip_if_group (ip, 0, op);
7031   else {
7032     value = eval_if_expression (buf, limit - buf);
7033     if (value == 0)
7034       skip_if_group (ip, 0, op);
7035     else {
7036       ++if_stack->if_succeeded; /* continue processing input */
7037       output_line_directive (ip, op, 1, same_file);
7038     }
7039   }
7040   return 0;
7041 }
7042
7043 /* Evaluate a #if expression in BUF, of length LENGTH, then parse the
7044    result as a C expression and return the value as an int.  */
7045
7046 static HOST_WIDE_INT
7047 eval_if_expression (buf, length)
7048      U_CHAR *buf;
7049      int length;
7050 {
7051   FILE_BUF temp_obuf;
7052   HASHNODE *save_defined;
7053   HOST_WIDE_INT value;
7054
7055   save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
7056                           NULL_PTR, -1);
7057   pcp_inside_if = 1;
7058   temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
7059   pcp_inside_if = 0;
7060   delete_macro (save_defined);  /* clean up special symbol */
7061
7062   temp_obuf.buf[temp_obuf.length] = '\n';
7063   value = parse_c_expression ((char *) temp_obuf.buf,
7064                               warn_undef && !instack[indepth].system_header_p);
7065
7066   free (temp_obuf.buf);
7067
7068   return value;
7069 }
7070
7071 /* routine to handle ifdef/ifndef.  Try to look up the symbol, then do
7072    or don't skip to the #endif/#else/#elif depending on what directive
7073    is actually being processed.  */
7074
7075 static int
7076 do_xifdef (buf, limit, op, keyword)
7077      U_CHAR *buf, *limit;
7078      FILE_BUF *op;
7079      struct directive *keyword;
7080 {
7081   int skip;
7082   FILE_BUF *ip = &instack[indepth];
7083   U_CHAR *end; 
7084   int start_of_file = 0;
7085   U_CHAR *control_macro = 0;
7086
7087   /* Detect a #ifndef at start of file (not counting comments).  */
7088   if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7089     U_CHAR *p = ip->buf;
7090     while (p != directive_start) {
7091       U_CHAR c = *p++;
7092       if (is_space[c])
7093         ;
7094       /* Make no special provision for backslash-newline here; this is
7095          slower if backslash-newlines are present, but it's correct,
7096          and it's not worth it to tune for the rare backslash-newline.  */
7097       else if (c == '/'
7098                && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7099         /* Skip this comment.  */
7100         int junk = 0;
7101         U_CHAR *save_bufp = ip->bufp;
7102         ip->bufp = p + 1;
7103         p = skip_to_end_of_comment (ip, &junk, 1);
7104         ip->bufp = save_bufp;
7105       } else {
7106         goto fail;
7107       }
7108     }
7109     /* If we get here, this conditional is the beginning of the file.  */
7110     start_of_file = 1;
7111   fail: ;
7112   }
7113
7114   /* Discard leading and trailing whitespace.  */
7115   SKIP_WHITE_SPACE (buf);
7116   while (limit != buf && is_hor_space[limit[-1]]) limit--;
7117
7118   /* Find the end of the identifier at the beginning.  */
7119   for (end = buf; is_idchar[*end]; end++);
7120
7121   if (end == buf) {
7122     skip = (keyword->type == T_IFDEF);
7123     if (! traditional)
7124       pedwarn (end == limit ? "`#%s' with no argument"
7125                : "`#%s' argument starts with punctuation",
7126                keyword->name);
7127   } else {
7128     HASHNODE *hp;
7129
7130     if (! traditional) {
7131       if (isdigit (buf[0]))
7132         pedwarn ("`#%s' argument starts with a digit", keyword->name);
7133       else if (end != limit)
7134         pedwarn ("garbage at end of `#%s' argument", keyword->name);
7135     }
7136
7137     hp = lookup (buf, end-buf, -1);
7138
7139     if (pcp_outfile) {
7140       /* Output a precondition for this macro.  */
7141       if (hp
7142           && (hp->type == T_CONST
7143               || (hp->type == T_MACRO && hp->value.defn->predefined)))
7144         fprintf (pcp_outfile, "#define %s\n", hp->name);
7145       else {
7146         U_CHAR *cp = buf;
7147         fprintf (pcp_outfile, "#undef ");
7148         while (is_idchar[*cp]) /* Ick! */
7149           fputc (*cp++, pcp_outfile);
7150         putc ('\n', pcp_outfile);
7151       }
7152     }
7153
7154     skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7155     if (start_of_file && !skip) {
7156       control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7157       bcopy ((char *) buf, (char *) control_macro, end - buf);
7158       control_macro[end - buf] = 0;
7159     }
7160   }
7161   
7162   conditional_skip (ip, skip, T_IF, control_macro, op);
7163   return 0;
7164 }
7165
7166 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7167    If this is a #ifndef starting at the beginning of a file,
7168    CONTROL_MACRO is the macro name tested by the #ifndef.
7169    Otherwise, CONTROL_MACRO is 0.  */
7170
7171 static void
7172 conditional_skip (ip, skip, type, control_macro, op)
7173      FILE_BUF *ip;
7174      int skip;
7175      enum node_type type;
7176      U_CHAR *control_macro;
7177      FILE_BUF *op;
7178 {
7179   IF_STACK_FRAME *temp;
7180
7181   temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7182   temp->fname = ip->nominal_fname;
7183   temp->fname_len = ip->nominal_fname_len;
7184   temp->lineno = ip->lineno;
7185   temp->next = if_stack;
7186   temp->control_macro = control_macro;
7187   if_stack = temp;
7188
7189   if_stack->type = type;
7190
7191   if (skip != 0) {
7192     skip_if_group (ip, 0, op);
7193     return;
7194   } else {
7195     ++if_stack->if_succeeded;
7196     output_line_directive (ip, &outbuf, 1, same_file);
7197   }
7198 }
7199
7200 /* Skip to #endif, #else, or #elif.  adjust line numbers, etc.
7201    Leaves input ptr at the sharp sign found.
7202    If ANY is nonzero, return at next directive of any sort.  */
7203      
7204 static void
7205 skip_if_group (ip, any, op)
7206      FILE_BUF *ip;
7207      int any;
7208      FILE_BUF *op;
7209 {
7210   register U_CHAR *bp = ip->bufp, *cp;
7211   register U_CHAR *endb = ip->buf + ip->length;
7212   struct directive *kt;
7213   IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7214   U_CHAR *beg_of_line = bp;
7215   register int ident_length;
7216   U_CHAR *ident, *after_ident;
7217   /* Save info about where the group starts.  */
7218   U_CHAR *beg_of_group = bp;
7219   int beg_lineno = ip->lineno;
7220   int skipping_include_directive = 0;
7221
7222   if (output_conditionals && op != 0) {
7223     char *ptr = "#failed\n";
7224     int len = strlen (ptr);
7225
7226     if (op->bufp > op->buf && op->bufp[-1] != '\n')
7227       {
7228         *op->bufp++ = '\n';
7229         op->lineno++;
7230       }
7231     check_expand (op, len);
7232     bcopy (ptr, (char *) op->bufp, len);
7233     op->bufp += len;
7234     op->lineno++;
7235     output_line_directive (ip, op, 1, 0);
7236   }
7237
7238   while (bp < endb) {
7239     switch (*bp++) {
7240     case '/':                   /* possible comment */
7241       if (*bp == '\\' && bp[1] == '\n')
7242         newline_fix (bp);
7243       if (*bp == '*'
7244           || (cplusplus_comments && *bp == '/')) {
7245         ip->bufp = ++bp;
7246         bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7247       }
7248       break;
7249     case '<':
7250       if (skipping_include_directive) {
7251         while (bp < endb && *bp != '>' && *bp != '\n') {
7252           if (*bp == '\\' && bp[1] == '\n') {
7253             ip->lineno++;
7254             bp++;
7255           }
7256           bp++;
7257         }
7258       }
7259       break;
7260     case '\"':
7261       if (skipping_include_directive) {
7262         while (bp < endb && *bp != '\n') {
7263           if (*bp == '"') {
7264             bp++;
7265             break;
7266           }
7267           if (*bp == '\\' && bp[1] == '\n') {
7268             ip->lineno++;
7269             bp++;
7270           }
7271           bp++;
7272         }
7273         break;
7274       }
7275       /* Fall through.  */
7276     case '\'':
7277       bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7278                                NULL_PTR, NULL_PTR);
7279       break;
7280     case '\\':
7281       /* Char after backslash loses its special meaning in some cases.  */
7282       if (*bp == '\n') {
7283         ++ip->lineno;
7284         bp++;
7285       } else if (traditional && bp < endb)
7286         bp++;
7287       break;
7288     case '\n':
7289       ++ip->lineno;
7290       beg_of_line = bp;
7291       skipping_include_directive = 0;
7292       break;
7293     case '%':
7294       if (beg_of_line == 0 || traditional)
7295         break;
7296       ip->bufp = bp - 1;
7297       while (bp[0] == '\\' && bp[1] == '\n')
7298         bp += 2;
7299       if (*bp == ':')
7300         goto sharp_token;
7301       break;
7302     case '#':
7303       /* # keyword: a # must be first nonblank char on the line */
7304       if (beg_of_line == 0)
7305         break;
7306       ip->bufp = bp - 1;
7307     sharp_token:
7308       /* Scan from start of line, skipping whitespace, comments
7309          and backslash-newlines, and see if we reach this #.
7310          If not, this # is not special.  */
7311       bp = beg_of_line;
7312       /* If -traditional, require # to be at beginning of line.  */
7313       if (!traditional) {
7314         while (1) {
7315           if (is_hor_space[*bp])
7316             bp++;
7317           else if (*bp == '\\' && bp[1] == '\n')
7318             bp += 2;
7319           else if (*bp == '/' && bp[1] == '*') {
7320             bp += 2;
7321             while (!(*bp == '*' && bp[1] == '/'))
7322               bp++;
7323             bp += 2;
7324           }
7325           /* There is no point in trying to deal with C++ // comments here,
7326              because if there is one, then this # must be part of the
7327              comment and we would never reach here.  */
7328           else break;
7329         }
7330       }
7331       if (bp != ip->bufp) {
7332         bp = ip->bufp + 1;      /* Reset bp to after the #.  */
7333         break;
7334       }
7335
7336       bp = ip->bufp + 1;        /* Point after the '#' */
7337       if (ip->bufp[0] == '%') {
7338         /* Skip past the ':' again.  */
7339         while (*bp == '\\') {
7340           ip->lineno++;
7341           bp += 2;
7342         }
7343         bp++;
7344       }
7345
7346       /* Skip whitespace and \-newline.  */
7347       while (1) {
7348         if (is_hor_space[*bp])
7349           bp++;
7350         else if (*bp == '\\' && bp[1] == '\n')
7351           bp += 2;
7352         else if (*bp == '/') {
7353           if (bp[1] == '\\' && bp[2] == '\n')
7354             newline_fix (bp + 1);
7355           if (bp[1] == '*') {
7356             for (bp += 2; ; bp++) {
7357               if (*bp == '\n')
7358                 ip->lineno++;
7359               else if (*bp == '*') {
7360                 if (bp[-1] == '/' && warn_comments)
7361                   warning ("`/*' within comment");
7362                 if (bp[1] == '\\' && bp[2] == '\n')
7363                   newline_fix (bp + 1);
7364                 if (bp[1] == '/')
7365                   break;
7366               }
7367             }
7368             bp += 2;
7369           } else if (bp[1] == '/' && cplusplus_comments) {
7370             for (bp += 2; ; bp++) {
7371               if (*bp == '\n') {
7372                 if (bp[-1] != '\\')
7373                   break;
7374                 if (warn_comments)
7375                   warning ("multiline `//' comment");
7376                 ip->lineno++;
7377               }
7378             }
7379           } else
7380             break;
7381         } else
7382           break;
7383       }
7384
7385       cp = bp;
7386
7387       /* Now find end of directive name.
7388          If we encounter a backslash-newline, exchange it with any following
7389          symbol-constituents so that we end up with a contiguous name.  */
7390
7391       while (1) {
7392         if (is_idchar[*bp])
7393           bp++;
7394         else {
7395           if (*bp == '\\' && bp[1] == '\n')
7396             name_newline_fix (bp);
7397           if (is_idchar[*bp])
7398             bp++;
7399           else break;
7400         }
7401       }
7402       ident_length = bp - cp;
7403       ident = cp;
7404       after_ident = bp;
7405
7406       /* A line of just `#' becomes blank.  */
7407
7408       if (ident_length == 0 && *after_ident == '\n') {
7409         continue;
7410       }
7411
7412       if (ident_length == 0 || !is_idstart[*ident]) {
7413         U_CHAR *p = ident;
7414         while (is_idchar[*p]) {
7415           if (*p < '0' || *p > '9')
7416             break;
7417           p++;
7418         }
7419         /* Handle # followed by a line number.  */
7420         if (p != ident && !is_idchar[*p]) {
7421           if (pedantic)
7422             pedwarn ("`#' followed by integer");
7423           continue;
7424         }
7425
7426         /* Avoid error for `###' and similar cases unless -pedantic.  */
7427         if (p == ident) {
7428           while (*p == '#' || is_hor_space[*p]) p++;
7429           if (*p == '\n') {
7430             if (pedantic && !lang_asm)
7431               pedwarn ("invalid preprocessing directive");
7432             continue;
7433           }
7434         }
7435
7436         if (!lang_asm && pedantic)
7437           pedwarn ("invalid preprocessing directive name");
7438         continue;
7439       }
7440
7441       for (kt = directive_table; kt->length >= 0; kt++) {
7442         IF_STACK_FRAME *temp;
7443         if (ident_length == kt->length
7444             && bcmp (cp, kt->name, kt->length) == 0) {
7445           /* If we are asked to return on next directive, do so now.  */
7446           if (any)
7447             goto done;
7448
7449           switch (kt->type) {
7450           case T_IF:
7451           case T_IFDEF:
7452           case T_IFNDEF:
7453             temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7454             temp->next = if_stack;
7455             if_stack = temp;
7456             temp->lineno = ip->lineno;
7457             temp->fname = ip->nominal_fname;
7458             temp->fname_len = ip->nominal_fname_len;
7459             temp->type = kt->type;
7460             break;
7461           case T_ELSE:
7462           case T_ENDIF:
7463             if (pedantic && if_stack != save_if_stack)
7464               validate_else (bp, endb);
7465           case T_ELIF:
7466             if (if_stack == instack[indepth].if_stack) {
7467               error ("`#%s' not within a conditional", kt->name);
7468               break;
7469             }
7470             else if (if_stack == save_if_stack)
7471               goto done;                /* found what we came for */
7472
7473             if (kt->type != T_ENDIF) {
7474               if (if_stack->type == T_ELSE)
7475                 error ("`#else' or `#elif' after `#else'");
7476               if_stack->type = kt->type;
7477               break;
7478             }
7479
7480             temp = if_stack;
7481             if_stack = if_stack->next;
7482             free (temp);
7483             break;
7484
7485           case T_INCLUDE:
7486           case T_INCLUDE_NEXT:
7487           case T_IMPORT:
7488             skipping_include_directive = 1;
7489             break;
7490
7491           default:
7492             break;
7493           }
7494           break;
7495         }
7496       }
7497       /* Don't let erroneous code go by.  */
7498       if (kt->length < 0 && !lang_asm && pedantic)
7499         pedwarn ("invalid preprocessing directive name");
7500     }
7501   }
7502
7503   ip->bufp = bp;
7504   /* after this returns, rescan will exit because ip->bufp
7505      now points to the end of the buffer.
7506      rescan is responsible for the error message also.  */
7507
7508  done:
7509   if (output_conditionals && op != 0) {
7510     char *ptr = "#endfailed\n";
7511     int len = strlen (ptr);
7512
7513     if (op->bufp > op->buf && op->bufp[-1] != '\n')
7514       {
7515         *op->bufp++ = '\n';
7516         op->lineno++;
7517       }
7518     check_expand (op, beg_of_line - beg_of_group);
7519     bcopy ((char *) beg_of_group, (char *) op->bufp,
7520            beg_of_line - beg_of_group);
7521     op->bufp += beg_of_line - beg_of_group;
7522     op->lineno += ip->lineno - beg_lineno;
7523     check_expand (op, len);
7524     bcopy (ptr, (char *) op->bufp, len);
7525     op->bufp += len;
7526     op->lineno++;
7527   }
7528 }
7529
7530 /* Handle a #else directive.  Do this by just continuing processing
7531    without changing  if_stack ;  this is so that the error message
7532    for missing #endif's etc. will point to the original #if.  It
7533    is possible that something different would be better.  */
7534
7535 static int
7536 do_else (buf, limit, op, keyword)
7537      U_CHAR *buf, *limit;
7538      FILE_BUF *op;
7539      struct directive *keyword;
7540 {
7541   FILE_BUF *ip = &instack[indepth];
7542
7543   if (pedantic) {
7544     SKIP_WHITE_SPACE (buf);
7545     if (buf != limit)
7546       pedwarn ("text following `#else' violates ANSI standard");
7547   }
7548
7549   if (if_stack == instack[indepth].if_stack) {
7550     error ("`#else' not within a conditional");
7551     return 0;
7552   } else {
7553     /* #ifndef can't have its special treatment for containing the whole file
7554        if it has a #else clause.  */
7555     if_stack->control_macro = 0;
7556
7557     if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7558       error ("`#else' after `#else'");
7559       fprintf (stderr, " (matches line %d", if_stack->lineno);
7560       if (! (if_stack->fname_len == ip->nominal_fname_len
7561              && !bcmp (if_stack->fname, ip->nominal_fname,
7562                        if_stack->fname_len))) {
7563         fprintf (stderr, ", file ");
7564         eprint_string (if_stack->fname, if_stack->fname_len);
7565       }
7566       fprintf (stderr, ")\n");
7567     }
7568     if_stack->type = T_ELSE;
7569   }
7570
7571   if (if_stack->if_succeeded)
7572     skip_if_group (ip, 0, op);
7573   else {
7574     ++if_stack->if_succeeded;   /* continue processing input */
7575     output_line_directive (ip, op, 1, same_file);
7576   }
7577   return 0;
7578 }
7579
7580 /* Unstack after #endif directive.  */
7581
7582 static int
7583 do_endif (buf, limit, op, keyword)
7584      U_CHAR *buf, *limit;
7585      FILE_BUF *op;
7586      struct directive *keyword;
7587 {
7588   if (pedantic) {
7589     SKIP_WHITE_SPACE (buf);
7590     if (buf != limit)
7591       pedwarn ("text following `#endif' violates ANSI standard");
7592   }
7593
7594   if (if_stack == instack[indepth].if_stack)
7595     error ("unbalanced `#endif'");
7596   else {
7597     IF_STACK_FRAME *temp = if_stack;
7598     if_stack = if_stack->next;
7599     if (temp->control_macro != 0) {
7600       /* This #endif matched a #ifndef at the start of the file.
7601          See if it is at the end of the file.  */
7602       FILE_BUF *ip = &instack[indepth];
7603       U_CHAR *p = ip->bufp;
7604       U_CHAR *ep = ip->buf + ip->length;
7605
7606       while (p != ep) {
7607         U_CHAR c = *p++;
7608         if (!is_space[c]) {
7609           if (c == '/'
7610               && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7611             /* Skip this comment.  */
7612             int junk = 0;
7613             U_CHAR *save_bufp = ip->bufp;
7614             ip->bufp = p + 1;
7615             p = skip_to_end_of_comment (ip, &junk, 1);
7616             ip->bufp = save_bufp;
7617           } else
7618             goto fail;
7619         }
7620       }
7621       /* If we get here, this #endif ends a #ifndef
7622          that contains all of the file (aside from whitespace).
7623          Arrange not to include the file again
7624          if the macro that was tested is defined.
7625
7626          Do not do this for the top-level file in a -include or any
7627          file in a -imacros.  */
7628       if (indepth != 0
7629           && ! (indepth == 1 && no_record_file)
7630           && ! (no_record_file && no_output))
7631         record_control_macro (ip->inc, temp->control_macro);
7632     fail: ;
7633     }
7634     free (temp);
7635     output_line_directive (&instack[indepth], op, 1, same_file);
7636   }
7637   return 0;
7638 }
7639
7640 /* When an #else or #endif is found while skipping failed conditional,
7641    if -pedantic was specified, this is called to warn about text after
7642    the directive name.  P points to the first char after the directive
7643    name.  */
7644
7645 static void
7646 validate_else (p, limit)
7647      register U_CHAR *p;
7648      register U_CHAR *limit;
7649 {
7650   /* Advance P over whitespace and comments.  */
7651   while (1) {
7652     while (*p == '\\' && p[1] == '\n')
7653       p += 2;
7654     if (is_hor_space[*p])
7655       p++;
7656     else if (*p == '/') {
7657       while (p[1] == '\\' && p[2] == '\n')
7658         p += 2;
7659       if (p[1] == '*') {
7660         /* Don't bother warning about unterminated comments
7661            since that will happen later.  Just be sure to exit.  */
7662         for (p += 2; ; p++) {
7663           if (p == limit)
7664             return;
7665           if (*p == '*') {
7666             while (p[1] == '\\' && p[2] == '\n')
7667               p += 2;
7668             if (p[1] == '/') {
7669               p += 2;
7670               break;
7671             }
7672           }
7673         }
7674       }
7675       else if (cplusplus_comments && p[1] == '/')
7676         return;
7677       else break;
7678     } else break;
7679   }
7680   if (*p != '\n')
7681     pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7682 }
7683 \f
7684 /* Skip a comment, assuming the input ptr immediately follows the
7685    initial slash-star.  Bump *LINE_COUNTER for each newline.
7686    (The canonical line counter is &ip->lineno.)
7687    Don't use this routine (or the next one) if bumping the line
7688    counter is not sufficient to deal with newlines in the string.
7689
7690    If NOWARN is nonzero, don't warn about slash-star inside a comment.
7691    This feature is useful when processing a comment that is going to
7692    be processed or was processed at another point in the preprocessor,
7693    to avoid a duplicate warning.  Likewise for unterminated comment
7694    errors.  */
7695
7696 static U_CHAR *
7697 skip_to_end_of_comment (ip, line_counter, nowarn)
7698      register FILE_BUF *ip;
7699      int *line_counter;         /* place to remember newlines, or NULL */
7700      int nowarn;
7701 {
7702   register U_CHAR *limit = ip->buf + ip->length;
7703   register U_CHAR *bp = ip->bufp;
7704   FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7705   int start_line = line_counter ? *line_counter : 0;
7706
7707         /* JF this line_counter stuff is a crock to make sure the
7708            comment is only put out once, no matter how many times
7709            the comment is skipped.  It almost works */
7710   if (op) {
7711     *op->bufp++ = '/';
7712     *op->bufp++ = bp[-1];
7713   }
7714   if (cplusplus_comments && bp[-1] == '/') {
7715     for (; bp < limit; bp++) {
7716       if (*bp == '\n') {
7717         if (bp[-1] != '\\')
7718           break;
7719         if (!nowarn && warn_comments)
7720           warning ("multiline `//' comment");
7721         if (line_counter)
7722           ++*line_counter;
7723         if (op)
7724           ++op->lineno;
7725       }
7726       if (op)
7727         *op->bufp++ = *bp;
7728     }
7729     ip->bufp = bp;
7730     return bp;
7731   }
7732   while (bp < limit) {
7733     if (op)
7734       *op->bufp++ = *bp;
7735     switch (*bp++) {
7736     case '\n':
7737       /* If this is the end of the file, we have an unterminated comment.
7738          Don't swallow the newline.  We are guaranteed that there will be a
7739          trailing newline and various pieces assume it's there.  */
7740       if (bp == limit)
7741         {
7742           --bp;
7743           --limit;
7744           break;
7745         }
7746       if (line_counter != NULL)
7747         ++*line_counter;
7748       if (op)
7749         ++op->lineno;
7750       break;
7751     case '*':
7752       if (bp[-2] == '/' && !nowarn && warn_comments)
7753         warning ("`/*' within comment");
7754       if (*bp == '\\' && bp[1] == '\n')
7755         newline_fix (bp);
7756       if (*bp == '/') {
7757         if (op)
7758           *op->bufp++ = '/';
7759         ip->bufp = ++bp;
7760         return bp;
7761       }
7762       break;
7763     }
7764   }
7765
7766   if (!nowarn)
7767     error_with_line (line_for_error (start_line), "unterminated comment");
7768   ip->bufp = bp;
7769   return bp;
7770 }
7771
7772 /* Skip over a quoted string.  BP points to the opening quote.
7773    Returns a pointer after the closing quote.  Don't go past LIMIT.
7774    START_LINE is the line number of the starting point (but it need
7775    not be valid if the starting point is inside a macro expansion).
7776
7777    The input stack state is not changed.
7778
7779    If COUNT_NEWLINES is nonzero, it points to an int to increment
7780    for each newline passed.
7781
7782    If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7783    if we pass a backslash-newline.
7784
7785    If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.  */
7786
7787 static U_CHAR *
7788 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7789      register U_CHAR *bp;
7790      register U_CHAR *limit;
7791      int start_line;
7792      int *count_newlines;
7793      int *backslash_newlines_p;
7794      int *eofp;
7795 {
7796   register U_CHAR c, match;
7797
7798   match = *bp++;
7799   while (1) {
7800     if (bp >= limit) {
7801       error_with_line (line_for_error (start_line),
7802                        "unterminated string or character constant");
7803       error_with_line (multiline_string_line,
7804                        "possible real start of unterminated constant");
7805       multiline_string_line = 0;
7806       if (eofp)
7807         *eofp = 1;
7808       break;
7809     }
7810     c = *bp++;
7811     if (c == '\\') {
7812       while (*bp == '\\' && bp[1] == '\n') {
7813         if (backslash_newlines_p)
7814           *backslash_newlines_p = 1;
7815         if (count_newlines)
7816           ++*count_newlines;
7817         bp += 2;
7818       }
7819       if (*bp == '\n') {
7820         if (backslash_newlines_p)
7821           *backslash_newlines_p = 1;
7822         if (count_newlines)
7823           ++*count_newlines;
7824       }
7825       bp++;
7826     } else if (c == '\n') {
7827       if (traditional) {
7828         /* Unterminated strings and character constants are 'valid'.  */
7829         bp--;   /* Don't consume the newline.  */
7830         if (eofp)
7831           *eofp = 1;
7832         break;
7833       }
7834       if (match == '\'') {
7835         error_with_line (line_for_error (start_line),
7836                          "unterminated string or character constant");
7837         bp--;
7838         if (eofp)
7839           *eofp = 1;
7840         break;
7841       }
7842       /* If not traditional, then allow newlines inside strings.  */
7843       if (count_newlines)
7844         ++*count_newlines;
7845       if (multiline_string_line == 0) {
7846         if (pedantic)
7847           pedwarn_with_line (line_for_error (start_line),
7848                              "string constant runs past end of line");
7849         multiline_string_line = start_line;
7850       }
7851     } else if (c == match)
7852       break;
7853   }
7854   return bp;
7855 }
7856
7857 /* Place into DST a quoted string representing the string SRC.
7858    SRCLEN is the length of SRC; SRC may contain null bytes.
7859    Return the address of DST's terminating null.  */
7860
7861 static char *
7862 quote_string (dst, src, srclen)
7863      char *dst, *src;
7864      size_t srclen;
7865 {
7866   U_CHAR c;
7867   char *srclim = src + srclen;
7868
7869   *dst++ = '\"';
7870   while (src != srclim)
7871     switch ((c = *src++))
7872       {
7873       default:
7874         if (isprint (c))
7875           *dst++ = c;
7876         else
7877           {
7878             sprintf (dst, "\\%03o", c);
7879             dst += 4;
7880           }
7881         break;
7882
7883       case '\"':
7884       case '\\':
7885         *dst++ = '\\';
7886         *dst++ = c;
7887         break;
7888       }
7889       
7890   *dst++ = '\"';
7891   *dst = '\0';
7892   return dst;
7893 }
7894
7895 /* Skip across a group of balanced parens, starting from IP->bufp.
7896    IP->bufp is updated.  Use this with IP->bufp pointing at an open-paren.
7897
7898    This does not handle newlines, because it's used for the arg of #if,
7899    where there aren't any newlines.  Also, backslash-newline can't appear.  */
7900
7901 static U_CHAR *
7902 skip_paren_group (ip)
7903      register FILE_BUF *ip;
7904 {
7905   U_CHAR *limit = ip->buf + ip->length;
7906   U_CHAR *p = ip->bufp;
7907   int depth = 0;
7908   int lines_dummy = 0;
7909
7910   while (p != limit) {
7911     int c = *p++;
7912     switch (c) {
7913     case '(':
7914       depth++;
7915       break;
7916
7917     case ')':
7918       depth--;
7919       if (depth == 0)
7920         return ip->bufp = p;
7921       break;
7922
7923     case '/':
7924       if (*p == '*') {
7925         ip->bufp = p;
7926         p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7927         p = ip->bufp;
7928       }
7929
7930     case '"':
7931     case '\'':
7932       {
7933         int eofp = 0;
7934         p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7935         if (eofp)
7936           return ip->bufp = p;
7937       }
7938       break;
7939     }
7940   }
7941
7942   ip->bufp = p;
7943   return p;
7944 }
7945 \f
7946 /* Write out a #line directive, for instance, after an #include file.
7947    If CONDITIONAL is nonzero, we can omit the #line if it would
7948    appear to be a no-op, and we can output a few newlines instead
7949    if we want to increase the line number by a small amount.
7950    FILE_CHANGE says whether we are entering a file, leaving, or neither.  */
7951
7952 static void
7953 output_line_directive (ip, op, conditional, file_change)
7954      FILE_BUF *ip, *op;
7955      int conditional;
7956      enum file_change_code file_change;
7957 {
7958   int len;
7959   char *line_directive_buf, *line_end;
7960
7961   if (no_line_directives
7962       || ip->fname == NULL
7963       || no_output) {
7964     op->lineno = ip->lineno;
7965     return;
7966   }
7967
7968   if (conditional) {
7969     if (ip->lineno == op->lineno)
7970       return;
7971
7972     /* If the inherited line number is a little too small,
7973        output some newlines instead of a #line directive.  */
7974     if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7975       check_expand (op, 10);
7976       while (ip->lineno > op->lineno) {
7977         *op->bufp++ = '\n';
7978         op->lineno++;
7979       }
7980       return;
7981     }
7982   }
7983
7984   /* Output a positive line number if possible.  */
7985   while (ip->lineno <= 0 && ip->bufp - ip->buf < ip->length
7986          && *ip->bufp == '\n') {
7987     ip->lineno++;
7988     ip->bufp++;
7989   }
7990
7991   line_directive_buf = (char *) alloca (4 * ip->nominal_fname_len + 100);
7992   sprintf (line_directive_buf, "# %d ", ip->lineno);
7993   line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7994                            ip->nominal_fname, ip->nominal_fname_len);
7995   if (file_change != same_file) {
7996     *line_end++ = ' ';
7997     *line_end++ = file_change == enter_file ? '1' : '2';
7998   }
7999   /* Tell cc1 if following text comes from a system header file.  */
8000   if (ip->system_header_p) {
8001     *line_end++ = ' ';
8002     *line_end++ = '3';
8003   }
8004 #ifndef NO_IMPLICIT_EXTERN_C
8005   /* Tell cc1plus if following text should be treated as C.  */
8006   if (ip->system_header_p == 2 && cplusplus) {
8007     *line_end++ = ' ';
8008     *line_end++ = '4';
8009   }
8010 #endif
8011   *line_end++ = '\n';
8012   len = line_end - line_directive_buf;
8013   check_expand (op, len + 1);
8014   if (op->bufp > op->buf && op->bufp[-1] != '\n')
8015     *op->bufp++ = '\n';
8016   bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
8017   op->bufp += len;
8018   op->lineno = ip->lineno;
8019 }
8020 \f
8021 /* This structure represents one parsed argument in a macro call.
8022    `raw' points to the argument text as written (`raw_length' is its length).
8023    `expanded' points to the argument's macro-expansion
8024    (its length is `expand_length').
8025    `stringified_length' is the length the argument would have
8026    if stringified.
8027    `use_count' is the number of times this macro arg is substituted
8028    into the macro.  If the actual use count exceeds 10, 
8029    the value stored is 10.
8030    `free1' and `free2', if nonzero, point to blocks to be freed
8031    when the macro argument data is no longer needed.  */
8032
8033 struct argdata {
8034   U_CHAR *raw, *expanded;
8035   int raw_length, expand_length;
8036   int stringified_length;
8037   U_CHAR *free1, *free2;
8038   char newlines;
8039   char use_count;
8040 };
8041
8042 /* Expand a macro call.
8043    HP points to the symbol that is the macro being called.
8044    Put the result of expansion onto the input stack
8045    so that subsequent input by our caller will use it.
8046
8047    If macro wants arguments, caller has already verified that
8048    an argument list follows; arguments come from the input stack.  */
8049
8050 static void
8051 macroexpand (hp, op)
8052      HASHNODE *hp;
8053      FILE_BUF *op;
8054 {
8055   int nargs;
8056   DEFINITION *defn = hp->value.defn;
8057   register U_CHAR *xbuf;
8058   int xbuf_len;
8059   int start_line = instack[indepth].lineno;
8060   int rest_args, rest_zero;
8061
8062   CHECK_DEPTH (return;);
8063
8064   /* it might not actually be a macro.  */
8065   if (hp->type != T_MACRO) {
8066     special_symbol (hp, op);
8067     return;
8068   }
8069
8070   /* This macro is being used inside a #if, which means it must be */
8071   /* recorded as a precondition.  */
8072   if (pcp_inside_if && pcp_outfile && defn->predefined)
8073     dump_single_macro (hp, pcp_outfile);
8074   
8075   nargs = defn->nargs;
8076
8077   if (nargs >= 0) {
8078     register int i;
8079     struct argdata *args;
8080     char *parse_error = 0;
8081
8082     args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
8083
8084     for (i = 0; i < nargs; i++) {
8085       args[i].raw = (U_CHAR *) "";
8086       args[i].expanded = 0;
8087       args[i].raw_length = args[i].expand_length
8088         = args[i].stringified_length = 0;
8089       args[i].free1 = args[i].free2 = 0;
8090       args[i].use_count = 0;
8091     }
8092
8093     /* Parse all the macro args that are supplied.  I counts them.
8094        The first NARGS args are stored in ARGS.
8095        The rest are discarded.
8096        If rest_args is set then we assume macarg absorbed the rest of the args.
8097        */
8098     i = 0;
8099     rest_args = 0;
8100     do {
8101       /* Discard the open-parenthesis or comma before the next arg.  */
8102       ++instack[indepth].bufp;
8103       if (rest_args)
8104         continue;
8105       if (i < nargs || (nargs == 0 && i == 0)) {
8106         /* If we are working on last arg which absorbs rest of args...  */
8107         if (i == nargs - 1 && defn->rest_args)
8108           rest_args = 1;
8109         parse_error = macarg (&args[i], rest_args);
8110       }
8111       else
8112         parse_error = macarg (NULL_PTR, 0);
8113       if (parse_error) {
8114         error_with_line (line_for_error (start_line), parse_error);
8115         break;
8116       }
8117       i++;
8118     } while (*instack[indepth].bufp != ')');
8119
8120     /* If we got one arg but it was just whitespace, call that 0 args.  */
8121     if (i == 1) {
8122       register U_CHAR *bp = args[0].raw;
8123       register U_CHAR *lim = bp + args[0].raw_length;
8124       /* cpp.texi says for foo ( ) we provide one argument.
8125          However, if foo wants just 0 arguments, treat this as 0.  */
8126       if (nargs == 0)
8127         while (bp != lim && is_space[*bp]) bp++;
8128       if (bp == lim)
8129         i = 0;
8130     }
8131
8132     /* Don't output an error message if we have already output one for
8133        a parse error above.  */
8134     rest_zero = 0;
8135     if (nargs == 0 && i > 0) {
8136       if (! parse_error)
8137         error ("arguments given to macro `%s'", hp->name);
8138     } else if (i < nargs) {
8139       /* traditional C allows foo() if foo wants one argument.  */
8140       if (nargs == 1 && i == 0 && traditional)
8141         ;
8142       /* the rest args token is allowed to absorb 0 tokens */
8143       else if (i == nargs - 1 && defn->rest_args)
8144         rest_zero = 1;
8145       else if (parse_error)
8146         ;
8147       else if (i == 0)
8148         error ("macro `%s' used without args", hp->name);
8149       else if (i == 1)
8150         error ("macro `%s' used with just one arg", hp->name);
8151       else
8152         error ("macro `%s' used with only %d args", hp->name, i);
8153     } else if (i > nargs) {
8154       if (! parse_error)
8155         error ("macro `%s' used with too many (%d) args", hp->name, i);
8156     }
8157
8158     /* Swallow the closeparen.  */
8159     ++instack[indepth].bufp;
8160
8161     /* If macro wants zero args, we parsed the arglist for checking only.
8162        Read directly from the macro definition.  */
8163     if (nargs == 0) {
8164       xbuf = defn->expansion;
8165       xbuf_len = defn->length;
8166     } else {
8167       register U_CHAR *exp = defn->expansion;
8168       register int offset;      /* offset in expansion,
8169                                    copied a piece at a time */
8170       register int totlen;      /* total amount of exp buffer filled so far */
8171
8172       register struct reflist *ap, *last_ap;
8173
8174       /* Macro really takes args.  Compute the expansion of this call.  */
8175
8176       /* Compute length in characters of the macro's expansion.
8177          Also count number of times each arg is used.  */
8178       xbuf_len = defn->length;
8179       for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8180         if (ap->stringify)
8181           xbuf_len += args[ap->argno].stringified_length;
8182         else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8183           /* Add 4 for two newline-space markers to prevent
8184              token concatenation.  */
8185           xbuf_len += args[ap->argno].raw_length + 4;
8186         else {
8187           /* We have an ordinary (expanded) occurrence of the arg.
8188              So compute its expansion, if we have not already.  */
8189           if (args[ap->argno].expanded == 0) {
8190             FILE_BUF obuf;
8191             obuf = expand_to_temp_buffer (args[ap->argno].raw,
8192                                           args[ap->argno].raw + args[ap->argno].raw_length,
8193                                           1, 0);
8194
8195             args[ap->argno].expanded = obuf.buf;
8196             args[ap->argno].expand_length = obuf.length;
8197             args[ap->argno].free2 = obuf.buf;
8198           }
8199
8200           /* Add 4 for two newline-space markers to prevent
8201              token concatenation.  */
8202           xbuf_len += args[ap->argno].expand_length + 4;
8203         }
8204         if (args[ap->argno].use_count < 10)
8205           args[ap->argno].use_count++;
8206       }
8207
8208       xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8209
8210       /* Generate in XBUF the complete expansion
8211          with arguments substituted in.
8212          TOTLEN is the total size generated so far.
8213          OFFSET is the index in the definition
8214          of where we are copying from.  */
8215       offset = totlen = 0;
8216       for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8217            last_ap = ap, ap = ap->next) {
8218         register struct argdata *arg = &args[ap->argno];
8219         int count_before = totlen;
8220
8221         /* Add chars to XBUF.  */
8222         for (i = 0; i < ap->nchars; i++, offset++)
8223           xbuf[totlen++] = exp[offset];
8224
8225         /* If followed by an empty rest arg with concatenation,
8226            delete the last run of nonwhite chars.  */
8227         if (rest_zero && totlen > count_before
8228             && ((ap->rest_args && ap->raw_before != 0)
8229                 || (last_ap != NULL && last_ap->rest_args
8230                     && last_ap->raw_after != 0))) {
8231           /* Delete final whitespace.  */
8232           while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8233             totlen--;
8234           }
8235
8236           /* Delete the nonwhites before them.  */
8237           while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8238             totlen--;
8239           }
8240         }
8241
8242         if (ap->stringify != 0) {
8243           int arglen = arg->raw_length;
8244           int escaped = 0;
8245           int in_string = 0;
8246           int c;
8247           i = 0;
8248           while (i < arglen
8249                  && (c = arg->raw[i], is_space[c]))
8250             i++;
8251           while (i < arglen
8252                  && (c = arg->raw[arglen - 1], is_space[c]))
8253             arglen--;
8254           if (!traditional)
8255             xbuf[totlen++] = '\"'; /* insert beginning quote */
8256           for (; i < arglen; i++) {
8257             c = arg->raw[i];
8258
8259             if (! in_string) {
8260               /* Special markers Newline Space
8261                  generate nothing for a stringified argument.  */
8262               if (c == '\n' && arg->raw[i+1] != '\n') {
8263                 i++;
8264                 continue;
8265               }
8266
8267               /* Internal sequences of whitespace are replaced by one space
8268                  except within an string or char token.  */
8269               if (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c]) {
8270                 while (1) {
8271                   /* Note that Newline Space does occur within whitespace
8272                      sequences; consider it part of the sequence.  */
8273                   if (c == '\n' && is_space[arg->raw[i+1]])
8274                     i += 2;
8275                   else if (c != '\n' && is_space[c])
8276                     i++;
8277                   else break;
8278                   c = arg->raw[i];
8279                 }
8280                 i--;
8281                 c = ' ';
8282               }
8283             }
8284
8285             if (escaped)
8286               escaped = 0;
8287             else {
8288               if (c == '\\')
8289                 escaped = 1;
8290               if (in_string) {
8291                 if (c == in_string)
8292                   in_string = 0;
8293               } else if (c == '\"' || c == '\'')
8294                 in_string = c;
8295             }
8296
8297             /* Escape these chars */
8298             if (c == '\"' || (in_string && c == '\\'))
8299               xbuf[totlen++] = '\\';
8300             /* We used to output e.g. \008 for control characters here,
8301                but this doesn't conform to the C Standard.
8302                Just output the characters as-is.  */
8303             xbuf[totlen++] = c;
8304           }
8305           if (!traditional)
8306             xbuf[totlen++] = '\"'; /* insert ending quote */
8307         } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8308           U_CHAR *p1 = arg->raw;
8309           U_CHAR *l1 = p1 + arg->raw_length;
8310           if (ap->raw_before != 0) {
8311             while (p1 != l1 && is_space[*p1]) p1++;
8312             while (p1 != l1 && is_idchar[*p1])
8313               xbuf[totlen++] = *p1++;
8314             /* Delete any no-reexpansion marker that follows
8315                an identifier at the beginning of the argument
8316                if the argument is concatenated with what precedes it.  */
8317             if (p1[0] == '\n' && p1[1] == '-')
8318               p1 += 2;
8319           } else if (!traditional) {
8320           /* Ordinary expanded use of the argument.
8321              Put in newline-space markers to prevent token pasting.  */
8322             xbuf[totlen++] = '\n';
8323             xbuf[totlen++] = ' ';
8324           }
8325           if (ap->raw_after != 0) {
8326             /* Arg is concatenated after: delete trailing whitespace,
8327                whitespace markers, and no-reexpansion markers.  */
8328             while (p1 != l1) {
8329               if (is_space[l1[-1]]) l1--;
8330               else if (l1[-1] == '-') {
8331                 U_CHAR *p2 = l1 - 1;
8332                 /* If a `-' is preceded by an odd number of newlines then it
8333                    and the last newline are a no-reexpansion marker.  */
8334                 while (p2 != p1 && p2[-1] == '\n') p2--;
8335                 if ((l1 - 1 - p2) & 1) {
8336                   l1 -= 2;
8337                 }
8338                 else break;
8339               }
8340               else break;
8341             }
8342           }
8343
8344           bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8345           totlen += l1 - p1;
8346           if (!traditional && ap->raw_after == 0) {
8347             /* Ordinary expanded use of the argument.
8348                Put in newline-space markers to prevent token pasting.  */
8349             xbuf[totlen++] = '\n';
8350             xbuf[totlen++] = ' ';
8351           }
8352         } else {
8353           /* Ordinary expanded use of the argument.
8354              Put in newline-space markers to prevent token pasting.  */
8355           if (!traditional) {
8356             xbuf[totlen++] = '\n';
8357             xbuf[totlen++] = ' ';
8358           }
8359           bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8360                  arg->expand_length);
8361           totlen += arg->expand_length;
8362           if (!traditional) {
8363             xbuf[totlen++] = '\n';
8364             xbuf[totlen++] = ' ';
8365           }
8366           /* If a macro argument with newlines is used multiple times,
8367              then only expand the newlines once.  This avoids creating output
8368              lines which don't correspond to any input line, which confuses
8369              gdb and gcov.  */
8370           if (arg->use_count > 1 && arg->newlines > 0) {
8371             /* Don't bother doing change_newlines for subsequent
8372                uses of arg.  */
8373             arg->use_count = 1;
8374             arg->expand_length
8375               = change_newlines (arg->expanded, arg->expand_length);
8376           }
8377         }
8378
8379         if (totlen > xbuf_len)
8380           abort ();
8381       }
8382
8383       /* If there is anything left of the definition after handling
8384          the arg list, copy that in too.  */
8385
8386       for (i = offset; i < defn->length; i++) {
8387         /* if we've reached the end of the macro */
8388         if (exp[i] == ')')
8389           rest_zero = 0;
8390         if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8391                && last_ap->raw_after != 0))
8392           xbuf[totlen++] = exp[i];
8393       }
8394
8395       xbuf[totlen] = 0;
8396       xbuf_len = totlen;
8397
8398       for (i = 0; i < nargs; i++) {
8399         if (args[i].free1 != 0)
8400           free (args[i].free1);
8401         if (args[i].free2 != 0)
8402           free (args[i].free2);
8403       }
8404     }
8405   } else {
8406     xbuf = defn->expansion;
8407     xbuf_len = defn->length;
8408   }
8409
8410   /* Now put the expansion on the input stack
8411      so our caller will commence reading from it.  */
8412   {
8413     register FILE_BUF *ip2;
8414
8415     ip2 = &instack[++indepth];
8416
8417     ip2->fname = 0;
8418     ip2->nominal_fname = 0;
8419     ip2->nominal_fname_len = 0;
8420     ip2->inc = 0;
8421     /* This may not be exactly correct, but will give much better error
8422        messages for nested macro calls than using a line number of zero.  */
8423     ip2->lineno = start_line;
8424     ip2->buf = xbuf;
8425     ip2->length = xbuf_len;
8426     ip2->bufp = xbuf;
8427     ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8428     ip2->macro = hp;
8429     ip2->if_stack = if_stack;
8430     ip2->system_header_p = 0;
8431
8432     /* Recursive macro use sometimes works traditionally.
8433        #define foo(x,y) bar (x (y,0), y)
8434        foo (foo, baz)  */
8435
8436     if (!traditional)
8437       hp->type = T_DISABLED;
8438   }
8439 }
8440 \f
8441 /* Parse a macro argument and store the info on it into *ARGPTR.
8442    REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8443    Return nonzero to indicate a syntax error.  */
8444
8445 static char *
8446 macarg (argptr, rest_args)
8447      register struct argdata *argptr;
8448      int rest_args;
8449 {
8450   FILE_BUF *ip = &instack[indepth];
8451   int paren = 0;
8452   int newlines = 0;
8453   int comments = 0;
8454   char *result = 0;
8455
8456   /* Try to parse as much of the argument as exists at this
8457      input stack level.  */
8458   U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro,
8459                         &paren, &newlines, &comments, rest_args);
8460
8461   /* If we find the end of the argument at this level,
8462      set up *ARGPTR to point at it in the input stack.  */
8463   if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8464       && bp != ip->buf + ip->length) {
8465     if (argptr != 0) {
8466       argptr->raw = ip->bufp;
8467       argptr->raw_length = bp - ip->bufp;
8468       argptr->newlines = newlines;
8469     }
8470     ip->bufp = bp;
8471   } else {
8472     /* This input stack level ends before the macro argument does.
8473        We must pop levels and keep parsing.
8474        Therefore, we must allocate a temporary buffer and copy
8475        the macro argument into it.  */
8476     int bufsize = bp - ip->bufp;
8477     int extra = newlines;
8478     U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8479     int final_start = 0;
8480
8481     bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8482     ip->bufp = bp;
8483     ip->lineno += newlines;
8484
8485     while (bp == ip->buf + ip->length) {
8486       if (instack[indepth].macro == 0) {
8487         result = "unterminated macro call";
8488         break;
8489       }
8490       ip->macro->type = T_MACRO;
8491       if (ip->free_ptr)
8492         free (ip->free_ptr);
8493       ip = &instack[--indepth];
8494       newlines = 0;
8495       comments = 0;
8496       bp = macarg1 (ip->bufp, ip->buf + ip->length, ip->macro, &paren,
8497                     &newlines, &comments, rest_args);
8498       final_start = bufsize;
8499       bufsize += bp - ip->bufp;
8500       extra += newlines;
8501       buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8502       bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8503              bp - ip->bufp);
8504       ip->bufp = bp;
8505       ip->lineno += newlines;
8506     }
8507
8508     /* Now, if arg is actually wanted, record its raw form,
8509        discarding comments and duplicating newlines in whatever
8510        part of it did not come from a macro expansion.
8511        EXTRA space has been preallocated for duplicating the newlines.
8512        FINAL_START is the index of the start of that part.  */
8513     if (argptr != 0) {
8514       argptr->raw = buffer;
8515       argptr->raw_length = bufsize;
8516       argptr->free1 = buffer;
8517       argptr->newlines = newlines;
8518       if ((newlines || comments) && ip->fname != 0)
8519         argptr->raw_length
8520           = final_start +
8521             discard_comments (argptr->raw + final_start,
8522                               argptr->raw_length - final_start,
8523                               newlines);
8524       argptr->raw[argptr->raw_length] = 0;
8525       if (argptr->raw_length > bufsize + extra)
8526         abort ();
8527     }
8528   }
8529
8530   /* If we are not discarding this argument,
8531      macroexpand it and compute its length as stringified.
8532      All this info goes into *ARGPTR.  */
8533
8534   if (argptr != 0) {
8535     register U_CHAR *buf, *lim;
8536     register int totlen;
8537
8538     buf = argptr->raw;
8539     lim = buf + argptr->raw_length;
8540
8541     while (buf != lim && is_space[*buf])
8542       buf++;
8543     while (buf != lim && is_space[lim[-1]])
8544       lim--;
8545     totlen = traditional ? 0 : 2;       /* Count opening and closing quote.  */
8546     while (buf != lim) {
8547       register U_CHAR c = *buf++;
8548       totlen++;
8549       /* Internal sequences of whitespace are replaced by one space
8550          in most cases, but not always.  So count all the whitespace
8551          in case we need to keep it all.  */
8552 #if 0
8553       if (is_space[c])
8554         SKIP_ALL_WHITE_SPACE (buf);
8555       else
8556 #endif
8557       if (c == '\"' || c == '\\') /* escape these chars */
8558         totlen++;
8559     }
8560     argptr->stringified_length = totlen;
8561   }
8562   return result;
8563 }
8564 \f
8565 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8566    taken from the expansion of MACRO,
8567    counting parens in *DEPTHPTR,
8568    and return if reach LIMIT
8569    or before a `)' that would make *DEPTHPTR negative
8570    or before a comma when *DEPTHPTR is zero.
8571    Single and double quotes are matched and termination
8572    is inhibited within them.  Comments also inhibit it.
8573    Value returned is pointer to stopping place.
8574
8575    Increment *NEWLINES each time a newline is passed.
8576    REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8577    Set *COMMENTS to 1 if a comment is seen.  */
8578
8579 static U_CHAR *
8580 macarg1 (start, limit, macro, depthptr, newlines, comments, rest_args)
8581      U_CHAR *start;
8582      register U_CHAR *limit;
8583      struct hashnode *macro;
8584      int *depthptr, *newlines, *comments;
8585      int rest_args;
8586 {
8587   register U_CHAR *bp = start;
8588
8589   while (bp < limit) {
8590     switch (*bp) {
8591     case '(':
8592       (*depthptr)++;
8593       break;
8594     case ')':
8595       if (--(*depthptr) < 0)
8596         return bp;
8597       break;
8598     case '\\':
8599       /* Traditionally, backslash makes following char not special.  */
8600       if (traditional && bp + 1 < limit && bp[1] != '\n')
8601         bp++;
8602       break;
8603     case '\n':
8604       ++*newlines;
8605       break;
8606     case '/':
8607       if (macro)
8608         break;
8609       if (bp[1] == '\\' && bp[2] == '\n')
8610         newline_fix (bp + 1);
8611       if (bp[1] == '*') {
8612         *comments = 1;
8613         for (bp += 2; bp < limit; bp++) {
8614           if (*bp == '\n')
8615             ++*newlines;
8616           else if (*bp == '*') {
8617             if (bp[-1] == '/' && warn_comments)
8618               warning ("`/*' within comment");
8619             if (bp[1] == '\\' && bp[2] == '\n')
8620               newline_fix (bp + 1);
8621             if (bp[1] == '/') {
8622               bp++;
8623               break;
8624             }
8625           }
8626         }
8627       } else if (bp[1] == '/' && cplusplus_comments) {
8628         *comments = 1;
8629         for (bp += 2; bp < limit; bp++) {
8630           if (*bp == '\n') {
8631             ++*newlines;
8632             if (bp[-1] != '\\')
8633               break;
8634             if (warn_comments)
8635               warning ("multiline `//' comment");
8636           }
8637         }
8638       }
8639       break;
8640     case '\'':
8641     case '\"':
8642       {
8643         int quotec;
8644         for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8645           if (*bp == '\\') {
8646             bp++;
8647             if (*bp == '\n')
8648               ++*newlines;
8649             if (!macro) {
8650               while (*bp == '\\' && bp[1] == '\n') {
8651                 bp += 2;
8652                 ++*newlines;
8653               }
8654             }
8655           } else if (*bp == '\n') {
8656             ++*newlines;
8657             if (quotec == '\'')
8658               break;
8659           }
8660         }
8661       }
8662       break;
8663     case ',':
8664       /* if we've returned to lowest level and we aren't absorbing all args */
8665       if ((*depthptr) == 0 && rest_args == 0)
8666         return bp;
8667       break;
8668     }
8669     bp++;
8670   }
8671
8672   return bp;
8673 }
8674 \f
8675 /* Discard comments and duplicate newlines
8676    in the string of length LENGTH at START,
8677    except inside of string constants.
8678    The string is copied into itself with its beginning staying fixed.  
8679
8680    NEWLINES is the number of newlines that must be duplicated.
8681    We assume that that much extra space is available past the end
8682    of the string.  */
8683
8684 static int
8685 discard_comments (start, length, newlines)
8686      U_CHAR *start;
8687      int length;
8688      int newlines;
8689 {
8690   register U_CHAR *ibp;
8691   register U_CHAR *obp;
8692   register U_CHAR *limit;
8693   register int c;
8694
8695   /* If we have newlines to duplicate, copy everything
8696      that many characters up.  Then, in the second part,
8697      we will have room to insert the newlines
8698      while copying down.
8699      NEWLINES may actually be too large, because it counts
8700      newlines in string constants, and we don't duplicate those.
8701      But that does no harm.  */
8702   if (newlines > 0) {
8703     ibp = start + length;
8704     obp = ibp + newlines;
8705     limit = start;
8706     while (limit != ibp)
8707       *--obp = *--ibp;
8708   }
8709
8710   ibp = start + newlines;
8711   limit = start + length + newlines;
8712   obp = start;
8713
8714   while (ibp < limit) {
8715     *obp++ = c = *ibp++;
8716     switch (c) {
8717     case '\n':
8718       /* Duplicate the newline.  */
8719       *obp++ = '\n';
8720       break;
8721
8722     case '\\':
8723       if (*ibp == '\n') {
8724         obp--;
8725         ibp++;
8726       }
8727       break;
8728
8729     case '/':
8730       if (*ibp == '\\' && ibp[1] == '\n')
8731         newline_fix (ibp);
8732       /* Delete any comment.  */
8733       if (cplusplus_comments && ibp[0] == '/') {
8734         /* Comments are equivalent to spaces.  */
8735         obp[-1] = ' ';
8736         ibp++;
8737         while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8738           ibp++;
8739         break;
8740       }
8741       if (ibp[0] != '*' || ibp + 1 >= limit)
8742         break;
8743       /* Comments are equivalent to spaces.
8744          For -traditional, a comment is equivalent to nothing.  */
8745       if (traditional)
8746         obp--;
8747       else
8748         obp[-1] = ' ';
8749       while (++ibp < limit) {
8750         if (ibp[0] == '*') {
8751           if (ibp[1] == '\\' && ibp[2] == '\n')
8752             newline_fix (ibp + 1);
8753           if (ibp[1] == '/') {
8754             ibp += 2;
8755             break;
8756           }
8757         }
8758       }
8759       break;
8760
8761     case '\'':
8762     case '\"':
8763       /* Notice and skip strings, so that we don't
8764          think that comments start inside them,
8765          and so we don't duplicate newlines in them.  */
8766       {
8767         int quotec = c;
8768         while (ibp < limit) {
8769           *obp++ = c = *ibp++;
8770           if (c == quotec)
8771             break;
8772           if (c == '\n' && quotec == '\'')
8773             break;
8774           if (c == '\\') {
8775             if (ibp < limit && *ibp == '\n') {
8776               ibp++;
8777               obp--;
8778             } else {
8779               while (*ibp == '\\' && ibp[1] == '\n')
8780                 ibp += 2;
8781               if (ibp < limit)
8782                 *obp++ = *ibp++;
8783             }
8784           }
8785         }
8786       }
8787       break;
8788     }
8789   }
8790
8791   return obp - start;
8792 }
8793 \f
8794 /* Turn newlines to spaces in the string of length LENGTH at START,
8795    except inside of string constants.
8796    The string is copied into itself with its beginning staying fixed.  */
8797
8798 static int
8799 change_newlines (start, length)
8800      U_CHAR *start;
8801      int length;
8802 {
8803   register U_CHAR *ibp;
8804   register U_CHAR *obp;
8805   register U_CHAR *limit;
8806   register int c;
8807
8808   ibp = start;
8809   limit = start + length;
8810   obp = start;
8811
8812   while (ibp < limit) {
8813     *obp++ = c = *ibp++;
8814     switch (c) {
8815     case '\n':
8816       /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8817          string.  Skip past the newline and its duplicate.
8818          Put a space in the output.  */
8819       if (*ibp == '\n')
8820         {
8821           ibp++;
8822           obp--;
8823           *obp++ = ' ';
8824         }
8825       break;
8826
8827     case '\'':
8828     case '\"':
8829       /* Notice and skip strings, so that we don't delete newlines in them.  */
8830       {
8831         int quotec = c;
8832         while (ibp < limit) {
8833           *obp++ = c = *ibp++;
8834           if (c == quotec && ibp[-2] != '\\')
8835             break;
8836           if (c == '\n' && quotec == '\'')
8837             break;
8838         }
8839       }
8840       break;
8841     }
8842   }
8843
8844   return obp - start;
8845 }
8846 \f
8847 /* my_strerror - return the descriptive text associated with an
8848    `errno' code.  */
8849
8850 char *
8851 my_strerror (errnum)
8852      int errnum;
8853 {
8854   char *result;
8855
8856 #ifndef VMS
8857 #ifndef HAVE_STRERROR
8858   result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8859 #else
8860   result = strerror (errnum);
8861 #endif
8862 #else   /* VMS */
8863   /* VAXCRTL's strerror() takes an optional second argument, which only
8864      matters when the first argument is EVMSERR.  However, it's simplest
8865      just to pass it unconditionally.  `vaxc$errno' is declared in
8866      <errno.h>, and maintained by the library in parallel with `errno'.
8867      We assume that caller's `errnum' either matches the last setting of
8868      `errno' by the library or else does not have the value `EVMSERR'.  */
8869
8870   result = strerror (errnum, vaxc$errno);
8871 #endif
8872
8873   if (!result)
8874     result = "undocumented I/O error";
8875
8876   return result;
8877 }
8878
8879 /* error - print error message and increment count of errors.  */
8880
8881 void
8882 error (PRINTF_ALIST (msg))
8883      PRINTF_DCL (msg)
8884 {
8885   va_list args;
8886
8887   VA_START (args, msg);
8888   verror (msg, args);
8889   va_end (args);
8890 }
8891
8892 static void
8893 verror (msg, args)
8894      char *msg;
8895      va_list args;
8896 {
8897   int i;
8898   FILE_BUF *ip = NULL;
8899
8900   print_containing_files ();
8901
8902   for (i = indepth; i >= 0; i--)
8903     if (instack[i].fname != NULL) {
8904       ip = &instack[i];
8905       break;
8906     }
8907
8908   if (ip != NULL) {
8909     eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8910     fprintf (stderr, ":%d: ", ip->lineno);
8911   }
8912   vfprintf (stderr, msg, args);
8913   fprintf (stderr, "\n");
8914   errors++;
8915 }
8916
8917 /* Error including a message from `errno'.  */
8918
8919 static void
8920 error_from_errno (name)
8921      char *name;
8922 {
8923   int e = errno;
8924   int i;
8925   FILE_BUF *ip = NULL;
8926
8927   print_containing_files ();
8928
8929   for (i = indepth; i >= 0; i--)
8930     if (instack[i].fname != NULL) {
8931       ip = &instack[i];
8932       break;
8933     }
8934
8935   if (ip != NULL) {
8936     eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8937     fprintf (stderr, ":%d: ", ip->lineno);
8938   }
8939
8940   fprintf (stderr, "%s: %s\n", name, my_strerror (e));
8941
8942   errors++;
8943 }
8944
8945 /* Print error message but don't count it.  */
8946
8947 void
8948 warning (PRINTF_ALIST (msg))
8949      PRINTF_DCL (msg)
8950 {
8951   va_list args;
8952
8953   VA_START (args, msg);
8954   vwarning (msg, args);
8955   va_end (args);
8956 }
8957
8958 static void
8959 vwarning (msg, args)
8960      char *msg;
8961      va_list args;
8962 {
8963   int i;
8964   FILE_BUF *ip = NULL;
8965
8966   if (inhibit_warnings)
8967     return;
8968
8969   if (warnings_are_errors)
8970     errors++;
8971
8972   print_containing_files ();
8973
8974   for (i = indepth; i >= 0; i--)
8975     if (instack[i].fname != NULL) {
8976       ip = &instack[i];
8977       break;
8978     }
8979
8980   if (ip != NULL) {
8981     eprint_string (ip->nominal_fname, ip->nominal_fname_len);
8982     fprintf (stderr, ":%d: ", ip->lineno);
8983   }
8984   fprintf (stderr, "warning: ");
8985   vfprintf (stderr, msg, args);
8986   fprintf (stderr, "\n");
8987 }
8988
8989 static void
8990 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8991 error_with_line (int line, PRINTF_ALIST (msg))
8992 #else
8993 error_with_line (line, PRINTF_ALIST (msg))
8994      int line;
8995      PRINTF_DCL (msg)
8996 #endif
8997 {
8998   va_list args;
8999
9000   VA_START (args, msg);
9001   verror_with_line (line, msg, args);
9002   va_end (args);
9003 }
9004
9005 static void
9006 verror_with_line (line, msg, args)
9007      int line;
9008      char *msg;
9009      va_list args;
9010 {
9011   int i;
9012   FILE_BUF *ip = NULL;
9013
9014   print_containing_files ();
9015
9016   for (i = indepth; i >= 0; i--)
9017     if (instack[i].fname != NULL) {
9018       ip = &instack[i];
9019       break;
9020     }
9021
9022   if (ip != NULL) {
9023     eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9024     fprintf (stderr, ":%d: ", line);
9025   }
9026   vfprintf (stderr, msg, args);
9027   fprintf (stderr, "\n");
9028   errors++;
9029 }
9030
9031 static void
9032 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9033 warning_with_line (int line, PRINTF_ALIST (msg))
9034 #else
9035 warning_with_line (line, PRINTF_ALIST (msg))
9036      int line;
9037      PRINTF_DCL (msg)
9038 #endif
9039 {
9040   va_list args;
9041
9042   VA_START (args, msg);
9043   vwarning_with_line (line, msg, args);
9044   va_end (args);
9045 }
9046
9047 static void
9048 vwarning_with_line (line, msg, args)
9049      int line;
9050      char *msg;
9051      va_list args;
9052 {
9053   int i;
9054   FILE_BUF *ip = NULL;
9055
9056   if (inhibit_warnings)
9057     return;
9058
9059   if (warnings_are_errors)
9060     errors++;
9061
9062   print_containing_files ();
9063
9064   for (i = indepth; i >= 0; i--)
9065     if (instack[i].fname != NULL) {
9066       ip = &instack[i];
9067       break;
9068     }
9069
9070   if (ip != NULL) {
9071     eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9072     fprintf (stderr, line ? ":%d: " : ": ", line);
9073   }
9074   fprintf (stderr, "warning: ");
9075   vfprintf (stderr, msg, args);
9076   fprintf (stderr, "\n");
9077 }
9078
9079 /* Print an error message and maybe count it.  */
9080
9081 void
9082 pedwarn (PRINTF_ALIST (msg))
9083      PRINTF_DCL (msg)
9084 {
9085   va_list args;
9086
9087   VA_START (args, msg);
9088   if (pedantic_errors)
9089     verror (msg, args);
9090   else
9091     vwarning (msg, args);
9092   va_end (args);
9093 }
9094
9095 void
9096 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9097 pedwarn_with_line (int line, PRINTF_ALIST (msg))
9098 #else
9099 pedwarn_with_line (line, PRINTF_ALIST (msg))
9100      int line;
9101      PRINTF_DCL (msg)
9102 #endif
9103 {
9104   va_list args;
9105
9106   VA_START (args, msg);
9107   if (pedantic_errors)
9108     verror_with_line (line, msg, args);
9109   else
9110     vwarning_with_line (line, msg, args);
9111   va_end (args);
9112 }
9113
9114 /* Report a warning (or an error if pedantic_errors)
9115    giving specified file name and line number, not current.  */
9116
9117 static void
9118 #if defined (__STDC__) && defined (HAVE_VPRINTF)
9119 pedwarn_with_file_and_line (char *file, size_t file_len, int line,
9120                             PRINTF_ALIST (msg))
9121 #else
9122 pedwarn_with_file_and_line (file, file_len, line, PRINTF_ALIST (msg))
9123      char *file;
9124      size_t file_len;
9125      int line;
9126      PRINTF_DCL (msg)
9127 #endif
9128 {
9129   va_list args;
9130
9131   if (!pedantic_errors && inhibit_warnings)
9132     return;
9133   if (file) {
9134     eprint_string (file, file_len);
9135     fprintf (stderr, ":%d: ", line);
9136   }
9137   if (pedantic_errors)
9138     errors++;
9139   if (!pedantic_errors)
9140     fprintf (stderr, "warning: ");
9141   VA_START (args, msg);
9142   vfprintf (stderr, msg, args);
9143   va_end (args);
9144   fprintf (stderr, "\n");
9145 }
9146 \f
9147 /* Print the file names and line numbers of the #include
9148    directives which led to the current file.  */
9149
9150 static void
9151 print_containing_files ()
9152 {
9153   FILE_BUF *ip = NULL;
9154   int i;
9155   int first = 1;
9156
9157   /* If stack of files hasn't changed since we last printed
9158      this info, don't repeat it.  */
9159   if (last_error_tick == input_file_stack_tick)
9160     return;
9161
9162   for (i = indepth; i >= 0; i--)
9163     if (instack[i].fname != NULL) {
9164       ip = &instack[i];
9165       break;
9166     }
9167
9168   /* Give up if we don't find a source file.  */
9169   if (ip == NULL)
9170     return;
9171
9172   /* Find the other, outer source files.  */
9173   for (i--; i >= 0; i--)
9174     if (instack[i].fname != NULL) {
9175       ip = &instack[i];
9176       if (first) {
9177         first = 0;
9178         fprintf (stderr, "In file included");
9179       } else {
9180         fprintf (stderr, ",\n                ");
9181       }
9182
9183       fprintf (stderr, " from ");
9184       eprint_string (ip->nominal_fname, ip->nominal_fname_len);
9185       fprintf (stderr, ":%d", ip->lineno);
9186     }
9187   if (! first)
9188     fprintf (stderr, ":\n");
9189
9190   /* Record we have printed the status as of this time.  */
9191   last_error_tick = input_file_stack_tick;
9192 }
9193 \f
9194 /* Return the line at which an error occurred.
9195    The error is not necessarily associated with the current spot
9196    in the input stack, so LINE says where.  LINE will have been
9197    copied from ip->lineno for the current input level.
9198    If the current level is for a file, we return LINE.
9199    But if the current level is not for a file, LINE is meaningless.
9200    In that case, we return the lineno of the innermost file.  */
9201
9202 static int
9203 line_for_error (line)
9204      int line;
9205 {
9206   int i;
9207   int line1 = line;
9208
9209   for (i = indepth; i >= 0; ) {
9210     if (instack[i].fname != 0)
9211       return line1;
9212     i--;
9213     if (i < 0)
9214       return 0;
9215     line1 = instack[i].lineno;
9216   }
9217   abort ();
9218   /*NOTREACHED*/
9219   return 0;
9220 }
9221
9222 /*
9223  * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9224  *
9225  * As things stand, nothing is ever placed in the output buffer to be
9226  * removed again except when it's KNOWN to be part of an identifier,
9227  * so flushing and moving down everything left, instead of expanding,
9228  * should work ok.
9229  */
9230
9231 /* You might think void was cleaner for the return type,
9232    but that would get type mismatch in check_expand in strict ANSI.  */
9233
9234 static int
9235 grow_outbuf (obuf, needed)
9236      register FILE_BUF *obuf;
9237      register int needed;
9238 {
9239   register U_CHAR *p;
9240   int minsize;
9241
9242   if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9243     return 0;
9244
9245   /* Make it at least twice as big as it is now.  */
9246   obuf->length *= 2;
9247   /* Make it have at least 150% of the free space we will need.  */
9248   minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9249   if (minsize > obuf->length)
9250     obuf->length = minsize;
9251
9252   if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9253     memory_full ();
9254
9255   obuf->bufp = p + (obuf->bufp - obuf->buf);
9256   obuf->buf = p;
9257
9258   return 0;
9259 }
9260 \f
9261 /* Symbol table for macro names and special symbols */
9262
9263 /*
9264  * install a name in the main hash table, even if it is already there.
9265  *   name stops with first non alphanumeric, except leading '#'.
9266  * caller must check against redefinition if that is desired.
9267  * delete_macro () removes things installed by install () in fifo order.
9268  * this is important because of the `defined' special symbol used
9269  * in #if, and also if pushdef/popdef directives are ever implemented.
9270  *
9271  * If LEN is >= 0, it is the length of the name.
9272  * Otherwise, compute the length by scanning the entire name.
9273  *
9274  * If HASH is >= 0, it is the precomputed hash code.
9275  * Otherwise, compute the hash code. 
9276  */
9277
9278 static HASHNODE *
9279 install (name, len, type, value, hash)
9280      U_CHAR *name;
9281      int len;
9282      enum node_type type;
9283      char *value;
9284      int hash;
9285 {
9286   register HASHNODE *hp;
9287   register int i, bucket;
9288   register U_CHAR *p, *q;
9289
9290   if (len < 0) {
9291     p = name;
9292     while (is_idchar[*p])
9293       p++;
9294     len = p - name;
9295   }
9296
9297   if (hash < 0)
9298     hash = hashf (name, len, HASHSIZE);
9299
9300   i = sizeof (HASHNODE) + len + 1;
9301   hp = (HASHNODE *) xmalloc (i);
9302   bucket = hash;
9303   hp->bucket_hdr = &hashtab[bucket];
9304   hp->next = hashtab[bucket];
9305   hashtab[bucket] = hp;
9306   hp->prev = NULL;
9307   if (hp->next != NULL)
9308     hp->next->prev = hp;
9309   hp->type = type;
9310   hp->length = len;
9311   hp->value.cpval = value;
9312   hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9313   p = hp->name;
9314   q = name;
9315   for (i = 0; i < len; i++)
9316     *p++ = *q++;
9317   hp->name[len] = 0;
9318   return hp;
9319 }
9320
9321 /*
9322  * find the most recent hash node for name name (ending with first
9323  * non-identifier char) installed by install
9324  *
9325  * If LEN is >= 0, it is the length of the name.
9326  * Otherwise, compute the length by scanning the entire name.
9327  *
9328  * If HASH is >= 0, it is the precomputed hash code.
9329  * Otherwise, compute the hash code.
9330  */
9331
9332 HASHNODE *
9333 lookup (name, len, hash)
9334      U_CHAR *name;
9335      int len;
9336      int hash;
9337 {
9338   register U_CHAR *bp;
9339   register HASHNODE *bucket;
9340
9341   if (len < 0) {
9342     for (bp = name; is_idchar[*bp]; bp++) ;
9343     len = bp - name;
9344   }
9345
9346   if (hash < 0)
9347     hash = hashf (name, len, HASHSIZE);
9348
9349   bucket = hashtab[hash];
9350   while (bucket) {
9351     if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9352       return bucket;
9353     bucket = bucket->next;
9354   }
9355   return NULL;
9356 }
9357
9358 /*
9359  * Delete a hash node.  Some weirdness to free junk from macros.
9360  * More such weirdness will have to be added if you define more hash
9361  * types that need it.
9362  */
9363
9364 /* Note that the DEFINITION of a macro is removed from the hash table
9365    but its storage is not freed.  This would be a storage leak
9366    except that it is not reasonable to keep undefining and redefining
9367    large numbers of macros many times.
9368    In any case, this is necessary, because a macro can be #undef'd
9369    in the middle of reading the arguments to a call to it.
9370    If #undef freed the DEFINITION, that would crash.  */
9371
9372 static void
9373 delete_macro (hp)
9374      HASHNODE *hp;
9375 {
9376
9377   if (hp->prev != NULL)
9378     hp->prev->next = hp->next;
9379   if (hp->next != NULL)
9380     hp->next->prev = hp->prev;
9381
9382   /* Make sure that the bucket chain header that the deleted guy was
9383      on points to the right thing afterwards.  */
9384   if (hp == *hp->bucket_hdr)
9385     *hp->bucket_hdr = hp->next;
9386
9387 #if 0
9388   if (hp->type == T_MACRO) {
9389     DEFINITION *d = hp->value.defn;
9390     struct reflist *ap, *nextap;
9391
9392     for (ap = d->pattern; ap != NULL; ap = nextap) {
9393       nextap = ap->next;
9394       free (ap);
9395     }
9396     free (d);
9397   }
9398 #endif
9399   free (hp);
9400 }
9401
9402 /*
9403  * return hash function on name.  must be compatible with the one
9404  * computed a step at a time, elsewhere
9405  */
9406
9407 static int
9408 hashf (name, len, hashsize)
9409      register U_CHAR *name;
9410      register int len;
9411      int hashsize;
9412 {
9413   register int r = 0;
9414
9415   while (len--)
9416     r = HASHSTEP (r, *name++);
9417
9418   return MAKE_POS (r) % hashsize;
9419 }
9420 \f
9421
9422 /* Dump the definition of a single macro HP to OF.  */
9423
9424 static void
9425 dump_single_macro (hp, of)
9426      register HASHNODE *hp;
9427      FILE *of;
9428 {
9429   register DEFINITION *defn = hp->value.defn;
9430   struct reflist *ap;
9431   int offset;
9432   int concat;
9433
9434
9435   /* Print the definition of the macro HP.  */
9436
9437   fprintf (of, "#define %s", hp->name);
9438
9439   if (defn->nargs >= 0) {
9440     int i;
9441
9442     fprintf (of, "(");
9443     for (i = 0; i < defn->nargs; i++) {
9444       dump_arg_n (defn, i, of);
9445       if (i + 1 < defn->nargs)
9446         fprintf (of, ", ");
9447     }
9448     fprintf (of, ")");
9449   }
9450
9451   fprintf (of, " ");
9452
9453   offset = 0;
9454   concat = 0;
9455   for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9456     dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9457     offset += ap->nchars;
9458     if (!traditional) {
9459       if (ap->nchars != 0)
9460         concat = 0;
9461       if (ap->stringify) {
9462         switch (ap->stringify) {
9463          case SHARP_TOKEN: fprintf (of, "#"); break;
9464          case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9465          case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9466          case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9467          default: abort ();
9468         }
9469       }
9470       if (ap->raw_before != 0) {
9471         if (concat) {
9472           switch (ap->raw_before) {
9473            case WHITE_SHARP_TOKEN:
9474            case WHITE_PERCENT_COLON_TOKEN:
9475             fprintf (of, " ");
9476             break;
9477            default:
9478             break;
9479           }
9480         } else {
9481           switch (ap->raw_before) {
9482            case SHARP_TOKEN: fprintf (of, "##"); break;
9483            case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9484            case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9485            case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9486            default: abort ();
9487           }
9488         }
9489       }
9490       concat = 0;
9491     }
9492     dump_arg_n (defn, ap->argno, of);
9493     if (!traditional && ap->raw_after != 0) {
9494       switch (ap->raw_after) {
9495        case SHARP_TOKEN: fprintf (of, "##"); break;
9496        case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9497        case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9498        case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9499        default: abort ();
9500       }
9501       concat = 1;
9502     }
9503   }
9504   dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9505   fprintf (of, "\n");
9506 }
9507
9508 /* Dump all macro definitions as #defines to stdout.  */
9509
9510 static void
9511 dump_all_macros ()
9512 {
9513   int bucket;
9514
9515   for (bucket = 0; bucket < HASHSIZE; bucket++) {
9516     register HASHNODE *hp;
9517
9518     for (hp = hashtab[bucket]; hp; hp= hp->next) {
9519       if (hp->type == T_MACRO)
9520         dump_single_macro (hp, stdout);
9521     }
9522   }
9523 }
9524
9525 /* Output to OF a substring of a macro definition.
9526    BASE is the beginning of the definition.
9527    Output characters START thru LENGTH.
9528    Unless traditional, discard newlines outside of strings, thus
9529    converting funny-space markers to ordinary spaces.  */
9530
9531 static void
9532 dump_defn_1 (base, start, length, of)
9533      U_CHAR *base;
9534      int start;
9535      int length;
9536      FILE *of;
9537 {
9538   U_CHAR *p = base + start;
9539   U_CHAR *limit = base + start + length;
9540
9541   if (traditional)
9542     fwrite (p, sizeof (*p), length, of);
9543   else {
9544     while (p < limit) {
9545       if (*p == '\"' || *p =='\'') {
9546         U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9547                                          NULL_PTR, NULL_PTR);
9548         fwrite (p, sizeof (*p), p1 - p, of);
9549         p = p1;
9550       } else {
9551         if (*p != '\n')
9552           putc (*p, of);
9553         p++;
9554       }
9555     }
9556   }
9557 }
9558
9559 /* Print the name of argument number ARGNUM of macro definition DEFN
9560    to OF.
9561    Recall that DEFN->args.argnames contains all the arg names
9562    concatenated in reverse order with comma-space in between.  */
9563
9564 static void
9565 dump_arg_n (defn, argnum, of)
9566      DEFINITION *defn;
9567      int argnum;
9568      FILE *of;
9569 {
9570   register U_CHAR *p = defn->args.argnames;
9571   while (argnum + 1 < defn->nargs) {
9572     p = (U_CHAR *) index ((char *) p, ' ') + 1;
9573     argnum++;
9574   }
9575
9576   while (*p && *p != ',') {
9577     putc (*p, of);
9578     p++;
9579   }
9580 }
9581 \f
9582 /* Initialize syntactic classifications of characters.  */
9583
9584 static void
9585 initialize_char_syntax ()
9586 {
9587   register int i;
9588
9589   /*
9590    * Set up is_idchar and is_idstart tables.  These should be
9591    * faster than saying (is_alpha (c) || c == '_'), etc.
9592    * Set up these things before calling any routines tthat
9593    * refer to them.
9594    */
9595   for (i = 'a'; i <= 'z'; i++) {
9596     is_idchar[i - 'a' + 'A'] = 1;
9597     is_idchar[i] = 1;
9598     is_idstart[i - 'a' + 'A'] = 1;
9599     is_idstart[i] = 1;
9600   }
9601   for (i = '0'; i <= '9'; i++)
9602     is_idchar[i] = 1;
9603   is_idchar['_'] = 1;
9604   is_idstart['_'] = 1;
9605   is_idchar['$'] = 1;
9606   is_idstart['$'] = 1;
9607
9608   /* horizontal space table */
9609   is_hor_space[' '] = 1;
9610   is_hor_space['\t'] = 1;
9611   is_hor_space['\v'] = 1;
9612   is_hor_space['\f'] = 1;
9613   is_hor_space['\r'] = 1;
9614
9615   is_space[' '] = 1;
9616   is_space['\t'] = 1;
9617   is_space['\v'] = 1;
9618   is_space['\f'] = 1;
9619   is_space['\n'] = 1;
9620   is_space['\r'] = 1;
9621
9622   char_name['\v'] = "vertical tab";
9623   char_name['\f'] = "formfeed";
9624   char_name['\r'] = "carriage return";
9625 }
9626
9627 /* Initialize the built-in macros.  */
9628
9629 static void
9630 initialize_builtins (inp, outp)
9631      FILE_BUF *inp;
9632      FILE_BUF *outp;
9633 {
9634   install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9635   install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9636   install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9637   install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9638   install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9639   install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9640 #ifndef NO_BUILTIN_SIZE_TYPE
9641   install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9642 #endif
9643 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9644   install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9645 #endif
9646   install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9647   install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9648            NULL_PTR, -1);
9649   install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9650            NULL_PTR, -1);
9651   install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9652            NULL_PTR, -1);
9653   install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9654   if (!traditional) {
9655     install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9656     install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9657   }
9658   if (objc)
9659     install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9660 /*  This is supplied using a -D by the compiler driver
9661     so that it is present only when truly compiling with GNU C.  */
9662 /*  install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1);  */
9663   install ((U_CHAR *) "__HAVE_BUILTIN_SETJMP__", -1, T_CONST, "1", -1);
9664
9665   if (debug_output)
9666     {
9667       char directive[2048];
9668       U_CHAR *udirective = (U_CHAR *) directive;
9669       register struct directive *dp = &directive_table[0];
9670       struct tm *timebuf = timestamp ();
9671
9672       sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9673                instack[0].nominal_fname);
9674       output_line_directive (inp, outp, 0, same_file);
9675       pass_thru_directive (udirective, &udirective[strlen (directive)],
9676                            outp, dp);
9677
9678       sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9679       output_line_directive (inp, outp, 0, same_file);
9680       pass_thru_directive (udirective, &udirective[strlen (directive)],
9681                            outp, dp);
9682
9683 #ifndef NO_BUILTIN_SIZE_TYPE
9684       sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9685       output_line_directive (inp, outp, 0, same_file);
9686       pass_thru_directive (udirective, &udirective[strlen (directive)],
9687                            outp, dp);
9688 #endif
9689
9690 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9691       sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_TYPE);
9692       output_line_directive (inp, outp, 0, same_file);
9693       pass_thru_directive (udirective, &udirective[strlen (directive)],
9694                            outp, dp);
9695 #endif
9696
9697       sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9698       output_line_directive (inp, outp, 0, same_file);
9699       pass_thru_directive (udirective, &udirective[strlen (directive)],
9700                            outp, dp);
9701
9702       sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9703                monthnames[timebuf->tm_mon],
9704                timebuf->tm_mday, timebuf->tm_year + 1900);
9705       output_line_directive (inp, outp, 0, same_file);
9706       pass_thru_directive (udirective, &udirective[strlen (directive)],
9707                            outp, dp);
9708
9709       sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9710                timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9711       output_line_directive (inp, outp, 0, same_file);
9712       pass_thru_directive (udirective, &udirective[strlen (directive)],
9713                            outp, dp);
9714
9715       if (!traditional)
9716         {
9717           sprintf (directive, " __STDC__ 1");
9718           output_line_directive (inp, outp, 0, same_file);
9719           pass_thru_directive (udirective, &udirective[strlen (directive)],
9720                                outp, dp);
9721         }
9722       if (objc)
9723         {
9724           sprintf (directive, " __OBJC__ 1");
9725           output_line_directive (inp, outp, 0, same_file);
9726           pass_thru_directive (udirective, &udirective[strlen (directive)],
9727                                outp, dp);
9728         }
9729     }
9730 }
9731 \f
9732 /*
9733  * process a given definition string, for initialization
9734  * If STR is just an identifier, define it with value 1.
9735  * If STR has anything after the identifier, then it should
9736  * be identifier=definition.
9737  */
9738
9739 static void
9740 make_definition (str, op)
9741      char *str;
9742      FILE_BUF *op;
9743 {
9744   FILE_BUF *ip;
9745   struct directive *kt;
9746   U_CHAR *buf, *p;
9747
9748   p = buf = (U_CHAR *) str;
9749   if (!is_idstart[*p]) {
9750     error ("malformed option `-D %s'", str);
9751     return;
9752   }
9753   while (is_idchar[*++p])
9754     ;
9755   if (*p == '(') {
9756     while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9757       ;
9758     if (*p++ != ')')
9759       p = (U_CHAR *) str;                       /* Error */
9760   }
9761   if (*p == 0) {
9762     buf = (U_CHAR *) alloca (p - buf + 4);
9763     strcpy ((char *)buf, str);
9764     strcat ((char *)buf, " 1");
9765   } else if (*p != '=') {
9766     error ("malformed option `-D %s'", str);
9767     return;
9768   } else {
9769     U_CHAR *q;
9770     /* Copy the entire option so we can modify it.  */
9771     buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9772     strncpy ((char *) buf, str, p - (U_CHAR *) str);
9773     /* Change the = to a space.  */
9774     buf[p - (U_CHAR *) str] = ' ';
9775     /* Scan for any backslash-newline and remove it.  */
9776     p++;
9777     q = &buf[p - (U_CHAR *) str];
9778     while (*p) {
9779       if (*p == '\"' || *p == '\'') {
9780         int unterminated = 0;
9781         U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9782                                          NULL_PTR, NULL_PTR, &unterminated);
9783         if (unterminated)
9784           return;
9785         while (p != p1)
9786           *q++ = *p++;
9787       } else if (*p == '\\' && p[1] == '\n')
9788         p += 2;
9789       /* Change newline chars into newline-markers.  */
9790       else if (*p == '\n')
9791         {
9792           *q++ = '\n';
9793           *q++ = '\n';
9794           p++;
9795         }
9796       else
9797         *q++ = *p++;
9798     }
9799     *q = 0;
9800   }
9801   
9802   ip = &instack[++indepth];
9803   ip->nominal_fname = ip->fname = "*Initialization*";
9804   ip->nominal_fname_len = strlen (ip->nominal_fname);
9805
9806   ip->buf = ip->bufp = buf;
9807   ip->length = strlen ((char *) buf);
9808   ip->lineno = 1;
9809   ip->macro = 0;
9810   ip->free_ptr = 0;
9811   ip->if_stack = if_stack;
9812   ip->system_header_p = 0;
9813
9814   for (kt = directive_table; kt->type != T_DEFINE; kt++)
9815     ;
9816
9817   /* Pass NULL instead of OP, since this is a "predefined" macro.  */
9818   do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9819   --indepth;
9820 }
9821
9822 /* JF, this does the work for the -U option */
9823
9824 static void
9825 make_undef (str, op)
9826      char *str;
9827      FILE_BUF *op;
9828 {
9829   FILE_BUF *ip;
9830   struct directive *kt;
9831
9832   ip = &instack[++indepth];
9833   ip->nominal_fname = ip->fname = "*undef*";
9834   ip->nominal_fname_len = strlen (ip->nominal_fname);
9835
9836   ip->buf = ip->bufp = (U_CHAR *) str;
9837   ip->length = strlen (str);
9838   ip->lineno = 1;
9839   ip->macro = 0;
9840   ip->free_ptr = 0;
9841   ip->if_stack = if_stack;
9842   ip->system_header_p = 0;
9843
9844   for (kt = directive_table; kt->type != T_UNDEF; kt++)
9845     ;
9846
9847   do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9848   --indepth;
9849 }
9850 \f
9851 /* Process the string STR as if it appeared as the body of a #assert.
9852    OPTION is the option name for which STR was the argument.  */
9853
9854 static void
9855 make_assertion (option, str)
9856      char *option;
9857      char *str;
9858 {
9859   FILE_BUF *ip;
9860   struct directive *kt;
9861   U_CHAR *buf, *p, *q;
9862
9863   /* Copy the entire option so we can modify it.  */
9864   buf = (U_CHAR *) alloca (strlen (str) + 1);
9865   strcpy ((char *) buf, str);
9866   /* Scan for any backslash-newline and remove it.  */
9867   p = q = buf;
9868   while (*p) {
9869     if (*p == '\\' && p[1] == '\n')
9870       p += 2;
9871     else
9872       *q++ = *p++;
9873   }
9874   *q = 0;
9875
9876   p = buf;
9877   if (!is_idstart[*p]) {
9878     error ("malformed option `%s %s'", option, str);
9879     return;
9880   }
9881   while (is_idchar[*++p])
9882     ;
9883   SKIP_WHITE_SPACE (p);
9884   if (! (*p == 0 || *p == '(')) {
9885     error ("malformed option `%s %s'", option, str);
9886     return;
9887   }
9888   
9889   ip = &instack[++indepth];
9890   ip->nominal_fname = ip->fname = "*Initialization*";
9891   ip->nominal_fname_len = strlen (ip->nominal_fname);
9892
9893   ip->buf = ip->bufp = buf;
9894   ip->length = strlen ((char *) buf);
9895   ip->lineno = 1;
9896   ip->macro = 0;
9897   ip->free_ptr = 0;
9898   ip->if_stack = if_stack;
9899   ip->system_header_p = 0;
9900
9901   for (kt = directive_table; kt->type != T_ASSERT; kt++)
9902     ;
9903
9904   /* Pass NULL as output ptr to do_define since we KNOW it never does
9905      any output....  */
9906   do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9907   --indepth;
9908 }
9909 \f
9910 #ifndef DIR_SEPARATOR
9911 #define DIR_SEPARATOR '/'
9912 #endif
9913
9914 /* The previous include prefix, if any, is PREV_FILE_NAME.
9915    Translate any pathnames with COMPONENT.
9916    Allocate a new include prefix whose name is the
9917    simplified concatenation of PREFIX and NAME,
9918    with a trailing / added if needed.
9919    But return 0 if the include prefix should be ignored,
9920    e.g. because it is a duplicate of PREV_FILE_NAME.  */
9921
9922 static struct file_name_list *
9923 new_include_prefix (prev_file_name, component, prefix, name)
9924      struct file_name_list *prev_file_name;
9925      char *component;
9926      char *prefix;
9927      char *name;
9928 {
9929   if (name == 0)
9930     fatal ("Directory name missing after command line option");
9931
9932   if (*name == 0)
9933     /* Ignore the empty string.  */
9934     return 0;
9935
9936   prefix = update_path (prefix, component);
9937   name = update_path (name, component);
9938
9939   {
9940     struct file_name_list *dir
9941       = ((struct file_name_list *)
9942          xmalloc (sizeof (struct file_name_list)
9943                   + strlen (prefix) + strlen (name) + 2));
9944     size_t len;
9945     strcpy (dir->fname, prefix);
9946     strcat (dir->fname, name);
9947     len = simplify_filename (dir->fname);
9948
9949     /* Convert directory name to a prefix.  */
9950     if (len && dir->fname[len - 1] != DIR_SEPARATOR) {
9951       if (len == 1 && dir->fname[len - 1] == '.')
9952         len = 0;
9953       else
9954         dir->fname[len++] = DIR_SEPARATOR;
9955       dir->fname[len] = 0;
9956     }
9957
9958     /* Ignore a directory whose name matches the previous one.  */
9959     if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9960       /* But treat `-Idir -I- -Idir' as `-I- -Idir'.  */
9961       if (!first_bracket_include)
9962         first_bracket_include = prev_file_name;
9963       free (dir);
9964       return 0;
9965     }
9966
9967 #ifndef VMS
9968     /* VMS can't stat dir prefixes, so skip these optimizations in VMS.  */
9969
9970     /* Add a trailing "." if there is a filename.  This increases the number
9971        of systems that can stat directories.  We remove it below.  */
9972     if (len != 0)
9973       {
9974         dir->fname[len] = '.';
9975         dir->fname[len + 1] = 0;
9976       }
9977
9978     /* Ignore a nonexistent directory.  */
9979     if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9980       if (errno != ENOENT && errno != ENOTDIR)
9981         error_from_errno (dir->fname);
9982       free (dir);
9983       return 0;
9984     }
9985
9986     if (len != 0)
9987       dir->fname[len] = 0;
9988
9989     /* Ignore a directory whose identity matches the previous one.  */
9990     if (prev_file_name
9991         && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9992         && prev_file_name->st.st_dev == dir->st.st_dev) {
9993       /* But treat `-Idir -I- -Idir' as `-I- -Idir'.  */
9994       if (!first_bracket_include)
9995         first_bracket_include = prev_file_name;
9996       free (dir);
9997       return 0;
9998     }
9999 #endif /* ! VMS */
10000
10001     dir->next = 0;
10002     dir->c_system_include_path = 0;
10003     dir->got_name_map = 0;
10004
10005     return dir;
10006   }
10007 }
10008
10009 /* Append a chain of `struct file_name_list's
10010    to the end of the main include chain.
10011    FIRST is the beginning of the chain to append, and LAST is the end.  */
10012
10013 static void
10014 append_include_chain (first, last)
10015      struct file_name_list *first, *last;
10016 {
10017   struct file_name_list *dir;
10018
10019   if (!first || !last)
10020     return;
10021
10022   if (include == 0)
10023     include = first;
10024   else
10025     last_include->next = first;
10026
10027   if (first_bracket_include == 0)
10028     first_bracket_include = first;
10029
10030   for (dir = first; ; dir = dir->next) {
10031     int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
10032     if (len > max_include_len)
10033       max_include_len = len;
10034     if (dir == last)
10035       break;
10036   }
10037
10038   last->next = NULL;
10039   last_include = last;
10040 }
10041 \f
10042 /* Place into DST a representation of the file named SRC that is suitable
10043    for `make'.  Do not null-terminate DST.  Return its length.  */
10044 static int
10045 quote_string_for_make (dst, src)
10046      char *dst;
10047      char *src;
10048 {
10049   char *p = src;
10050   int i = 0;
10051   for (;;)
10052     {
10053       char c = *p++;
10054       switch (c)
10055         {
10056         case '\0':
10057         case ' ':
10058         case '\t':
10059           {
10060             /* GNU make uses a weird quoting scheme for white space.
10061                A space or tab preceded by 2N+1 backslashes represents
10062                N backslashes followed by space; a space or tab
10063                preceded by 2N backslashes represents N backslashes at
10064                the end of a file name; and backslashes in other
10065                contexts should not be doubled.  */
10066             char *q;
10067             for (q = p - 1; src < q && q[-1] == '\\';  q--)
10068               {
10069                 if (dst)
10070                   dst[i] = '\\';
10071                 i++;
10072               }
10073           }
10074           if (!c)
10075             return i;
10076           if (dst)
10077             dst[i] = '\\';
10078           i++;
10079           goto ordinary_char;
10080           
10081         case '$':
10082           if (dst)
10083             dst[i] = c;
10084           i++;
10085           /* Fall through.  This can mishandle things like "$(" but
10086              there's no easy fix.  */
10087         default:
10088         ordinary_char:
10089           /* This can mishandle characters in the string "\0\n%*?[\\~";
10090              exactly which chars are mishandled depends on the `make' version.
10091              We know of no portable solution for this;
10092              even GNU make 3.76.1 doesn't solve the problem entirely.
10093              (Also, '\0' is mishandled due to our calling conventions.)  */
10094           if (dst)
10095             dst[i] = c;
10096           i++;
10097           break;
10098         }
10099     }
10100 }
10101
10102
10103 /* Add output to `deps_buffer' for the -M switch.
10104    STRING points to the text to be output.
10105    SPACER is ':' for targets, ' ' for dependencies.  */
10106
10107 static void
10108 deps_output (string, spacer)
10109      char *string;
10110      int spacer;
10111 {
10112   int size = quote_string_for_make ((char *) 0, string);
10113
10114   if (size == 0)
10115     return;
10116
10117 #ifndef MAX_OUTPUT_COLUMNS
10118 #define MAX_OUTPUT_COLUMNS 72
10119 #endif
10120   if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
10121       && 1 < deps_column) {
10122     bcopy (" \\\n ", &deps_buffer[deps_size], 4);
10123     deps_size += 4;
10124     deps_column = 1;
10125     if (spacer == ' ')
10126       spacer = 0;
10127   }
10128
10129   if (deps_size + 2 * size + 8 > deps_allocated_size) {
10130     deps_allocated_size = (deps_size + 2 * size + 50) * 2;
10131     deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
10132   }
10133   if (spacer == ' ') {
10134     deps_buffer[deps_size++] = ' ';
10135     deps_column++;
10136   }
10137   quote_string_for_make (&deps_buffer[deps_size], string);
10138   deps_size += size;
10139   deps_column += size;
10140   if (spacer == ':') {
10141     deps_buffer[deps_size++] = ':';
10142     deps_column++;
10143   }
10144   deps_buffer[deps_size] = 0;
10145 }
10146 \f
10147 static void
10148 fatal (PRINTF_ALIST (msg))
10149      PRINTF_DCL (msg)
10150 {
10151   va_list args;
10152
10153   fprintf (stderr, "%s: ", progname);
10154   VA_START (args, msg);
10155   vfprintf (stderr, msg, args);
10156   va_end (args);
10157   fprintf (stderr, "\n");
10158   exit (FATAL_EXIT_CODE);
10159 }
10160
10161 /* More 'friendly' abort that prints the line and file.
10162    config.h can #define abort fancy_abort if you like that sort of thing.  */
10163
10164 void
10165 fancy_abort ()
10166 {
10167   fatal ("Internal gcc abort.");
10168 }
10169
10170 static void
10171 perror_with_name (name)
10172      char *name;
10173 {
10174   fprintf (stderr, "%s: %s: %s\n", progname, name, my_strerror (errno));
10175   errors++;
10176 }
10177
10178 static void
10179 pfatal_with_name (name)
10180      char *name;
10181 {
10182   perror_with_name (name);
10183 #ifdef VMS
10184   exit (vaxc$errno);
10185 #else
10186   exit (FATAL_EXIT_CODE);
10187 #endif
10188 }
10189
10190 /* Handler for SIGPIPE.  */
10191
10192 static void
10193 pipe_closed (signo)
10194      /* If this is missing, some compilers complain.  */
10195      int signo;
10196 {
10197   fatal ("output pipe has been closed");
10198 }
10199 \f
10200 static void
10201 memory_full ()
10202 {
10203   fatal ("Memory exhausted.");
10204 }
10205
10206
10207 GENERIC_PTR
10208 xmalloc (size)
10209      size_t size;
10210 {
10211   register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
10212   if (!ptr)
10213     memory_full ();
10214   return ptr;
10215 }
10216
10217 static GENERIC_PTR
10218 xrealloc (old, size)
10219      GENERIC_PTR old;
10220      size_t size;
10221 {
10222   register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
10223   if (!ptr)
10224     memory_full ();
10225   return ptr;
10226 }
10227
10228 static GENERIC_PTR
10229 xcalloc (number, size)
10230      size_t number, size;
10231 {
10232   register size_t total = number * size;
10233   register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
10234   if (!ptr)
10235     memory_full ();
10236   bzero (ptr, total);
10237   return ptr;
10238 }
10239
10240 static char *
10241 savestring (input)
10242      char *input;
10243 {
10244   size_t size = strlen (input);
10245   char *output = xmalloc (size + 1);
10246   strcpy (output, input);
10247   return output;
10248 }
10249 \f
10250 #ifdef VMS
10251
10252 /* Under VMS we need to fix up the "include" specification filename so
10253    that everything following the 1st slash is changed into its correct
10254    VMS file specification.  */
10255
10256 static void
10257 hack_vms_include_specification (fname, vaxc_include)
10258      char *fname;
10259      int vaxc_include;
10260 {
10261   register char *cp, *cp1, *cp2;
10262   int f, check_filename_before_returning;
10263   char Local[512];
10264
10265   check_filename_before_returning = 0;
10266
10267   cp = base_name (fname);
10268
10269   /*
10270    * Check if we have a vax-c style '#include filename'
10271    * and add the missing .h
10272    */
10273   if (vaxc_include && !index (cp,'.'))
10274     strcat (cp, ".h");
10275
10276   cp2 = Local;                  /* initialize */
10277
10278   /* We are trying to do a number of things here.  First of all, we are
10279      trying to hammer the filenames into a standard format, such that later
10280      processing can handle them.
10281      
10282      If the file name contains something like [dir.], then it recognizes this
10283      as a root, and strips the ".]".  Later processing will add whatever is
10284      needed to get things working properly.
10285      
10286      If no device is specified, then the first directory name is taken to be
10287      a device name (or a rooted logical).  */
10288
10289   /* See if we found that 1st slash */
10290   if (cp == 0) return;          /* Nothing to do!!! */
10291   if (*cp != '/') return;       /* Nothing to do!!! */
10292   /* Point to the UNIX filename part (which needs to be fixed!) */
10293   cp1 = cp+1;
10294   /* If the directory spec is not rooted, we can just copy
10295      the UNIX filename part and we are done */
10296   if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10297     if (cp[-2] != '.') {
10298       /*
10299        * The VMS part ends in a `]', and the preceding character is not a `.'.
10300        * We strip the `]', and then splice the two parts of the name in the
10301        * usual way.  Given the default locations for include files in cccp.c,
10302        * we will only use this code if the user specifies alternate locations
10303        * with the /include (-I) switch on the command line.  */
10304       cp -= 1;                  /* Strip "]" */
10305       cp1--;                    /* backspace */
10306     } else {
10307       /*
10308        * The VMS part has a ".]" at the end, and this will not do.  Later
10309        * processing will add a second directory spec, and this would be a syntax
10310        * error.  Thus we strip the ".]", and thus merge the directory specs.
10311        * We also backspace cp1, so that it points to a '/'.  This inhibits the
10312        * generation of the 000000 root directory spec (which does not belong here
10313        * in this case).
10314        */
10315       cp -= 2;                  /* Strip ".]" */
10316       cp1--; };                 /* backspace */
10317   } else {
10318
10319     /* We drop in here if there is no VMS style directory specification yet.
10320      * If there is no device specification either, we make the first dir a
10321      * device and try that.  If we do not do this, then we will be essentially
10322      * searching the users default directory (as if they did a #include "asdf.h").
10323      *
10324      * Then all we need to do is to push a '[' into the output string. Later
10325      * processing will fill this in, and close the bracket.
10326      */
10327     if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec.  take first dir */
10328     *cp2++ = '[';               /* Open the directory specification */
10329   }
10330
10331   /* at this point we assume that we have the device spec, and (at least
10332      the opening "[" for a directory specification.  We may have directories
10333      specified already */
10334
10335   /* If there are no other slashes then the filename will be
10336      in the "root" directory.  Otherwise, we need to add
10337      directory specifications.  */
10338   if (index (cp1, '/') == 0) {
10339     /* Just add "000000]" as the directory string */
10340     strcpy (cp2, "000000]");
10341     cp2 += strlen (cp2);
10342     check_filename_before_returning = 1; /* we might need to fool with this later */
10343   } else {
10344     /* As long as there are still subdirectories to add, do them.  */
10345     while (index (cp1, '/') != 0) {
10346       /* If this token is "." we can ignore it */
10347       if ((cp1[0] == '.') && (cp1[1] == '/')) {
10348         cp1 += 2;
10349         continue;
10350       }
10351       /* Add a subdirectory spec. Do not duplicate "." */
10352       if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10353         *cp2++ = '.';
10354       /* If this is ".." then the spec becomes "-" */
10355       if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10356         /* Add "-" and skip the ".." */
10357         *cp2++ = '-';
10358         cp1 += 3;
10359         continue;
10360       }
10361       /* Copy the subdirectory */
10362       while (*cp1 != '/') *cp2++= *cp1++;
10363       cp1++;                    /* Skip the "/" */
10364     }
10365     /* Close the directory specification */
10366     if (cp2[-1] == '.')         /* no trailing periods */
10367       cp2--;
10368     *cp2++ = ']';
10369   }
10370   /* Now add the filename */
10371   while (*cp1) *cp2++ = *cp1++;
10372   *cp2 = 0;
10373   /* Now append it to the original VMS spec.  */
10374   strcpy (cp, Local);
10375
10376   /* If we put a [000000] in the filename, try to open it first. If this fails,
10377      remove the [000000], and return that name.  This provides flexibility
10378      to the user in that they can use both rooted and non-rooted logical names
10379      to point to the location of the file.  */
10380
10381   if (check_filename_before_returning) {
10382     f = open (fname, O_RDONLY, 0666);
10383     if (f >= 0) {
10384       /* The file name is OK as it is, so return it as is.  */
10385       close (f);
10386       return;
10387     }
10388     /* The filename did not work.  Try to remove the [000000] from the name,
10389        and return it.  */
10390     cp = index (fname, '[');
10391     cp2 = index (fname, ']') + 1;
10392     strcpy (cp, cp2);           /* this gets rid of it */
10393   }
10394   return;
10395 }
10396 #endif  /* VMS */
10397 \f
10398 #ifdef  VMS
10399
10400 /* The following wrapper functions supply additional arguments to the VMS
10401    I/O routines to optimize performance with file handling.  The arguments
10402    are:
10403      "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10404      "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10405      "fop=tef"- Truncate unused portions of file when closing file.
10406      "shr=nil"- Disallow file sharing while file is open.  */
10407
10408 static FILE *
10409 VMS_freopen (fname, type, oldfile)
10410      char *fname;
10411      char *type;
10412      FILE *oldfile;
10413 {
10414 #undef freopen  /* Get back the real freopen routine.  */
10415   if (strcmp (type, "w") == 0)
10416     return freopen (fname, type, oldfile,
10417                          "mbc=16", "deq=64", "fop=tef", "shr=nil");
10418   return freopen (fname, type, oldfile, "mbc=16");
10419 }
10420
10421 static FILE *
10422 VMS_fopen (fname, type)
10423      char *fname;
10424      char *type;
10425 {
10426 #undef fopen    /* Get back the real fopen routine.  */
10427   /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10428      fixed arguments, which matches ANSI's specification but not VAXCRTL's
10429      pre-ANSI implementation.  This hack circumvents the mismatch problem.  */
10430   FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10431
10432   if (*type == 'w')
10433     return (*vmslib_fopen) (fname, type, "mbc=32",
10434                             "deq=64", "fop=tef", "shr=nil");
10435   else
10436     return (*vmslib_fopen) (fname, type, "mbc=32");
10437 }
10438
10439 static int 
10440 VMS_open (fname, flags, prot)
10441      char *fname;
10442      int flags;
10443      int prot;
10444 {
10445 #undef open     /* Get back the real open routine.  */
10446   return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10447 }
10448 \f
10449 /* more VMS hackery */
10450 #include <fab.h>
10451 #include <nam.h>
10452
10453 extern unsigned long SYS$PARSE(), SYS$SEARCH();
10454
10455 /* Work around another library bug.  If a file is located via a searchlist,
10456    and if the device it's on is not the same device as the one specified
10457    in the first element of that searchlist, then both stat() and fstat()
10458    will fail to return info about it.  `errno' will be set to EVMSERR, and
10459    `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10460    We can get around this by fully parsing the filename and then passing
10461    that absolute name to stat().
10462
10463    Without this fix, we can end up failing to find header files, which is
10464    bad enough, but then compounding the problem by reporting the reason for
10465    failure as "normal successful completion."  */
10466
10467 #undef fstat    /* Get back to the library version.  */
10468
10469 static int
10470 VMS_fstat (fd, statbuf)
10471      int fd;
10472      struct stat *statbuf;
10473 {
10474   int result = fstat (fd, statbuf);
10475
10476   if (result < 0)
10477     {
10478       FILE *fp;
10479       char nambuf[NAM$C_MAXRSS+1];
10480
10481       if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10482         result = VMS_stat (nambuf, statbuf);
10483       /* No fclose(fp) here; that would close(fd) as well.  */
10484     }
10485
10486   return result;
10487 }
10488
10489 static int
10490 VMS_stat (name, statbuf)
10491      const char *name;
10492      struct stat *statbuf;
10493 {
10494   int result = stat (name, statbuf);
10495
10496   if (result < 0)
10497     {
10498       struct FAB fab;
10499       struct NAM nam;
10500       char exp_nam[NAM$C_MAXRSS+1],  /* expanded name buffer for SYS$PARSE */
10501            res_nam[NAM$C_MAXRSS+1];  /* resultant name buffer for SYS$SEARCH */
10502
10503       fab = cc$rms_fab;
10504       fab.fab$l_fna = (char *) name;
10505       fab.fab$b_fns = (unsigned char) strlen (name);
10506       fab.fab$l_nam = (void *) &nam;
10507       nam = cc$rms_nam;
10508       nam.nam$l_esa = exp_nam,  nam.nam$b_ess = sizeof exp_nam - 1;
10509       nam.nam$l_rsa = res_nam,  nam.nam$b_rss = sizeof res_nam - 1;
10510       nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10511       if (SYS$PARSE (&fab) & 1)
10512         {
10513           if (SYS$SEARCH (&fab) & 1)
10514             {
10515               res_nam[nam.nam$b_rsl] = '\0';
10516               result = stat (res_nam, statbuf);
10517             }
10518           /* Clean up searchlist context cached by the system.  */
10519           nam.nam$b_nop = NAM$M_SYNCHK;
10520           fab.fab$l_fna = 0,  fab.fab$b_fns = 0;
10521           (void) SYS$PARSE (&fab);
10522         }
10523     }
10524
10525   return result;
10526 }
10527 #endif /* VMS */