OSDN Git Service

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