OSDN Git Service

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