OSDN Git Service

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