OSDN Git Service

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