OSDN Git Service

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