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