OSDN Git Service

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