OSDN Git Service

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