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