OSDN Git Service

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