OSDN Git Service

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