OSDN Git Service

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