OSDN Git Service

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