OSDN Git Service

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