OSDN Git Service

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