OSDN Git Service

8338f6d25c53d4c3b26fde1484c9469ece4b7506
[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       if (errno != ENOENT)
4472         break;
4473     }
4474   }
4475
4476
4477   if (f < 0) {
4478
4479     if (f == -2) {
4480       /* The file was already included.  */
4481
4482     /* If generating dependencies and -MG was specified, we assume missing
4483        files are leaf files, living in the same directory as the source file
4484        or other similar place; these missing files may be generated from
4485        other files and may not exist yet (eg: y.tab.h).  */
4486     } else if (print_deps_missing_files
4487                && (system_include_depth != 0) < print_deps)
4488       {
4489         /* If it was requested as a system header file,
4490            then assume it belongs in the first place to look for such.  */
4491         if (angle_brackets)
4492           {
4493             if (search_start) {
4494               char *p = (char *) alloca (strlen (search_start->fname)
4495                                          + strlen (fbeg) + 1);
4496               strcpy (p, search_start->fname);
4497               strcat (p, fbeg);
4498               deps_output (p, ' ');
4499             }
4500           }
4501         else
4502           {
4503             /* Otherwise, omit the directory, as if the file existed
4504                in the directory with the source.  */
4505             deps_output (fbeg, ' ');
4506           }
4507       }
4508     /* If -M was specified, and this header file won't be added to the
4509        dependency list, then don't count this as an error, because we can
4510        still produce correct output.  Otherwise, we can't produce correct
4511        output, because there may be dependencies we need inside the missing
4512        file, and we don't know what directory this missing file exists in.  */
4513     else if (0 < print_deps  &&  print_deps <= (system_include_depth != 0))
4514       warning ("No include path in which to find %s", fbeg);
4515     else if (f != -3)
4516       error_from_errno (fbeg);
4517     else
4518       error ("No include path in which to find %s", fbeg);
4519
4520   } else {
4521
4522     /* Actually process the file.  */
4523
4524     pcftry = (char *) alloca (strlen (fname) + 30);
4525     pcfbuf = 0;
4526     pcfnum = 0;
4527
4528     if (!no_precomp)
4529       {
4530         do {
4531           sprintf (pcftry, "%s%d", fname, pcfnum++);
4532
4533           pcf = open (pcftry, O_RDONLY, 0666);
4534           if (pcf != -1)
4535             {
4536               struct stat s;
4537
4538               if (fstat (pcf, &s) != 0)
4539                 pfatal_with_name (pcftry);
4540               if (! INO_T_EQ (inc->st.st_ino, s.st_ino)
4541                   || inc->st.st_dev != s.st_dev)
4542                 {
4543                   pcfbuf = check_precompiled (pcf, &s, fname, &pcfbuflimit);
4544                   /* Don't need it any more.  */
4545                   close (pcf);
4546                 }
4547               else
4548                 {
4549                   /* Don't need it at all.  */
4550                   close (pcf);
4551                   break;
4552                 }
4553             }
4554         } while (pcf != -1 && !pcfbuf);
4555       }
4556     
4557     /* Actually process the file */
4558     if (pcfbuf) {
4559       pcfname = xmalloc (strlen (pcftry) + 1);
4560       strcpy (pcfname, pcftry);
4561       pcfinclude ((U_CHAR *) pcfbuf, (U_CHAR *) pcfbuflimit,
4562                   (U_CHAR *) fname, op);
4563     }
4564     else
4565       finclude (f, inc, op, is_system_include (fname), searchptr);
4566   }
4567
4568   system_include_depth -= angle_brackets;
4569
4570   return 0;
4571 }
4572
4573 /* Return nonzero if the given FILENAME is an absolute pathname which
4574    designates a file within one of the known "system" include file
4575    directories.  We assume here that if the given FILENAME looks like
4576    it is the name of a file which resides either directly in a "system"
4577    include file directory, or within any subdirectory thereof, then the
4578    given file must be a "system" include file.  This function tells us
4579    if we should suppress pedantic errors/warnings for the given FILENAME.
4580
4581    The value is 2 if the file is a C-language system header file
4582    for which C++ should (on most systems) assume `extern "C"'.  */
4583
4584 static int
4585 is_system_include (filename)
4586     register char *filename;
4587 {
4588   struct file_name_list *searchptr;
4589
4590   for (searchptr = first_system_include; searchptr;
4591        searchptr = searchptr->next)
4592     if (! strncmp (searchptr->fname, filename, strlen (searchptr->fname)))
4593       return searchptr->c_system_include_path + 1;
4594   return 0;
4595 }
4596 \f
4597 /* Yield the non-directory suffix of a file name.  */
4598
4599 static char *
4600 base_name (fname)
4601      char *fname;
4602 {
4603   char *s = fname;
4604   char *p;
4605 #if defined (__MSDOS__) || defined (_WIN32)
4606   if (isalpha (s[0]) && s[1] == ':') s += 2;
4607 #endif
4608 #ifdef VMS
4609   if ((p = rindex (s, ':'))) s = p + 1; /* Skip device.  */
4610   if ((p = rindex (s, ']'))) s = p + 1; /* Skip directory.  */
4611   if ((p = rindex (s, '>'))) s = p + 1; /* Skip alternate (int'n'l) dir.  */
4612   if (s != fname)
4613     return s;
4614 #endif
4615   if ((p = rindex (s, '/'))) s = p + 1;
4616 #ifdef DIR_SEPARATOR
4617   if ((p = rindex (s, DIR_SEPARATOR))) s = p + 1;
4618 #endif
4619   return s;
4620 }
4621
4622 /* Yield nonzero if FILENAME is absolute (i.e. not relative).  */
4623 static int
4624 absolute_filename (filename)
4625      char *filename;
4626 {
4627 #if defined (__MSDOS__) || defined (_WIN32)
4628   if (isalpha (filename[0]) && filename[1] == ':') filename += 2;
4629 #endif
4630   if (filename[0] == '/') return 1;
4631 #ifdef DIR_SEPARATOR
4632   if (filename[0] == DIR_SEPARATOR) return 1;
4633 #endif
4634   return 0;
4635 }
4636
4637 /* Remove unnecessary characters from FILENAME in place,
4638    to avoid unnecessary filename aliasing.
4639    Return the length of the resulting string.
4640
4641    Do only the simplifications allowed by Posix.
4642    It is OK to miss simplifications on non-Posix hosts,
4643    since this merely leads to suboptimial results.  */
4644
4645 static size_t
4646 simplify_filename (filename)
4647      char *filename;
4648 {
4649   register char *from = filename;
4650   register char *to = filename;
4651   char *to0;
4652
4653   /* Remove redundant initial /s.  */
4654   if (*from == '/') {
4655     *to++ = '/';
4656     if (*++from == '/') {
4657       if (*++from == '/') {
4658         /* 3 or more initial /s are equivalent to 1 /.  */
4659         while (*++from == '/')
4660           continue;
4661       } else {
4662         /* On some hosts // differs from /; Posix allows this.  */
4663         static int slashslash_vs_slash;
4664         if (slashslash_vs_slash == 0) {
4665           struct stat s1, s2;
4666           slashslash_vs_slash = ((stat ("/", &s1) == 0 && stat ("//", &s2) == 0
4667                                   && INO_T_EQ (s1.st_ino, s2.st_ino)
4668                                   && s1.st_dev == s2.st_dev)
4669                                  ? 1 : -1);
4670         }
4671         if (slashslash_vs_slash < 0)
4672           *to++ = '/';
4673       }
4674     }
4675   }
4676   to0 = to;
4677
4678   for (;;) {
4679     if (from[0] == '.' && from[1] == '/')
4680       from += 2;
4681     else {
4682       /* Copy this component and trailing /, if any.  */
4683       while ((*to++ = *from++) != '/') {
4684         if (!to[-1]) {
4685           /* Trim . component at end of nonempty name.  */
4686           to -= filename <= to - 3 && to[-3] == '/' && to[-2] == '.';
4687
4688           /* Trim unnecessary trailing /s.  */
4689           while (to0 < --to && to[-1] == '/')
4690             continue;
4691
4692           *to = 0;
4693           return to - filename;
4694         }
4695       }
4696     }
4697
4698     /* Skip /s after a /.  */
4699     while (*from == '/')
4700       from++;
4701   }
4702 }
4703 \f
4704 /* The file_name_map structure holds a mapping of file names for a
4705    particular directory.  This mapping is read from the file named
4706    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
4707    map filenames on a file system with severe filename restrictions,
4708    such as DOS.  The format of the file name map file is just a series
4709    of lines with two tokens on each line.  The first token is the name
4710    to map, and the second token is the actual name to use.  */
4711
4712 struct file_name_map
4713 {
4714   struct file_name_map *map_next;
4715   char *map_from;
4716   char *map_to;
4717 };
4718
4719 #define FILE_NAME_MAP_FILE "header.gcc"
4720
4721 /* Read a space delimited string of unlimited length from a stdio
4722    file.  */
4723
4724 static char *
4725 read_filename_string (ch, f)
4726      int ch;
4727      FILE *f;
4728 {
4729   char *alloc, *set;
4730   int len;
4731
4732   len = 20;
4733   set = alloc = xmalloc (len + 1);
4734   if (! is_space[ch])
4735     {
4736       *set++ = ch;
4737       while ((ch = getc (f)) != EOF && ! is_space[ch])
4738         {
4739           if (set - alloc == len)
4740             {
4741               len *= 2;
4742               alloc = xrealloc (alloc, len + 1);
4743               set = alloc + len / 2;
4744             }
4745           *set++ = ch;
4746         }
4747     }
4748   *set = '\0';
4749   ungetc (ch, f);
4750   return alloc;
4751 }
4752
4753 /* Read the file name map file for DIRNAME.
4754    If DIRNAME is empty, read the map file for the working directory;
4755    otherwise DIRNAME must end in '/'.  */
4756
4757 static struct file_name_map *
4758 read_name_map (dirname)
4759      char *dirname;
4760 {
4761   /* This structure holds a linked list of file name maps, one per
4762      directory.  */
4763   struct file_name_map_list
4764     {
4765       struct file_name_map_list *map_list_next;
4766       char *map_list_name;
4767       struct file_name_map *map_list_map;
4768     };
4769   static struct file_name_map_list *map_list;
4770   register struct file_name_map_list *map_list_ptr;
4771   char *name;
4772   FILE *f;
4773   size_t dirlen;
4774
4775   for (map_list_ptr = map_list; map_list_ptr;
4776        map_list_ptr = map_list_ptr->map_list_next)
4777     if (! strcmp (map_list_ptr->map_list_name, dirname))
4778       return map_list_ptr->map_list_map;
4779
4780   map_list_ptr = ((struct file_name_map_list *)
4781                   xmalloc (sizeof (struct file_name_map_list)));
4782   map_list_ptr->map_list_name = savestring (dirname);
4783   map_list_ptr->map_list_map = NULL;
4784
4785   dirlen = strlen (dirname);
4786   name = (char *) alloca (dirlen + strlen (FILE_NAME_MAP_FILE) + 1);
4787   strcpy (name, dirname);
4788   strcat (name, FILE_NAME_MAP_FILE);
4789   f = fopen (name, "r");
4790   if (!f)
4791     map_list_ptr->map_list_map = NULL;
4792   else
4793     {
4794       int ch;
4795
4796       while ((ch = getc (f)) != EOF)
4797         {
4798           char *from, *to;
4799           struct file_name_map *ptr;
4800           size_t tolen;
4801
4802           if (is_space[ch])
4803             continue;
4804           from = read_filename_string (ch, f);
4805           while ((ch = getc (f)) != EOF && is_hor_space[ch])
4806             ;
4807           to = read_filename_string (ch, f);
4808
4809           simplify_filename (from);
4810           tolen = simplify_filename (to);
4811
4812           ptr = ((struct file_name_map *)
4813                  xmalloc (sizeof (struct file_name_map)));
4814           ptr->map_from = from;
4815
4816           /* Make the real filename absolute.  */
4817           if (absolute_filename (to))
4818             ptr->map_to = to;
4819           else
4820             {
4821               ptr->map_to = xmalloc (dirlen + tolen + 1);
4822               strcpy (ptr->map_to, dirname);
4823               strcat (ptr->map_to, to);
4824               free (to);
4825             }         
4826
4827           ptr->map_next = map_list_ptr->map_list_map;
4828           map_list_ptr->map_list_map = ptr;
4829
4830           while ((ch = getc (f)) != '\n')
4831             if (ch == EOF)
4832               break;
4833         }
4834       fclose (f);
4835     }
4836   
4837   map_list_ptr->map_list_next = map_list;
4838   map_list = map_list_ptr;
4839
4840   return map_list_ptr->map_list_map;
4841 }  
4842
4843 /* Try to open include file FILENAME.  SEARCHPTR is the directory
4844    being tried from the include file search path.
4845    IMPORTING is "" if we are importing, null otherwise.
4846    Return -2 if found, either a matching name or a matching inode.
4847    Otherwise, open the file and return a file descriptor if successful
4848    or -1 if unsuccessful.
4849    Unless unsuccessful, put a descriptor of the included file into *PINC.
4850    This function maps filenames on file systems based on information read by
4851    read_name_map.  */
4852
4853 static int
4854 open_include_file (filename, searchptr, importing, pinc)
4855      char *filename;
4856      struct file_name_list *searchptr;
4857      U_CHAR *importing;
4858      struct include_file **pinc;
4859 {
4860   char *fname = remap_include_file (filename, searchptr);
4861   int fd = -2;
4862
4863   /* Look up FNAME in include_hashtab.  */
4864   struct include_file **phead = &include_hashtab[hashf ((U_CHAR *) fname,
4865                                                         strlen (fname),
4866                                                         INCLUDE_HASHSIZE)];
4867   struct include_file *inc, *head = *phead;
4868   for (inc = head; inc; inc = inc->next)
4869     if (!strcmp (fname, inc->fname))
4870       break;
4871
4872   if (!inc
4873       || ! inc->control_macro
4874       || (inc->control_macro[0] && ! lookup (inc->control_macro, -1, -1))) {
4875
4876     fd = open (fname, O_RDONLY, 0);
4877
4878     if (fd < 0)
4879       return fd;
4880
4881     if (!inc) {
4882       /* FNAME was not in include_hashtab; insert a new entry.  */
4883       inc = (struct include_file *) xmalloc (sizeof (struct include_file));
4884       inc->next = head;
4885       inc->fname = fname;
4886       inc->control_macro = 0;
4887       inc->deps_output = 0;
4888       if (fstat (fd, &inc->st) != 0)
4889         pfatal_with_name (fname);
4890       *phead = inc;
4891
4892       /* Look for another file with the same inode and device.  */
4893       if (lookup_ino_include (inc)
4894           && inc->control_macro
4895           && (!inc->control_macro[0] || lookup (inc->control_macro, -1, -1))) {
4896         close (fd);
4897         fd = -2;
4898       }
4899     }
4900
4901     /* For -M, add this file to the dependencies.  */
4902     if (! inc->deps_output  &&  (system_include_depth != 0) < print_deps) {
4903       inc->deps_output = 1;
4904       deps_output (fname, ' ');
4905     }   
4906
4907     /* Handle -H option.  */
4908     if (print_include_names)
4909       fprintf (stderr, "%*s%s\n", indepth, "", fname);
4910   }
4911
4912   if (importing)
4913     inc->control_macro = importing;
4914
4915   *pinc = inc;
4916   return fd;
4917 }
4918
4919 /* Return the remapped name of the the include file FILENAME.
4920    SEARCHPTR is the directory being tried from the include file path.  */
4921
4922 static char *
4923 remap_include_file (filename, searchptr)
4924      char *filename;
4925      struct file_name_list *searchptr;
4926 {
4927   register struct file_name_map *map;
4928   register char *from;
4929
4930   if (searchptr)
4931     {
4932       if (! searchptr->got_name_map)
4933         {
4934           searchptr->name_map = read_name_map (searchptr->fname);
4935           searchptr->got_name_map = 1;
4936         }
4937
4938       /* Check the mapping for the directory we are using.  */
4939       from = filename + strlen (searchptr->fname);
4940       for (map = searchptr->name_map; map; map = map->map_next)
4941         if (! strcmp (map->map_from, from))
4942           return map->map_to;
4943     }
4944
4945   from = base_name (filename);
4946
4947   if (from != filename || !searchptr)
4948     {
4949       /* Try to find a mapping file for the particular directory we are
4950          looking in.  Thus #include <sys/types.h> will look up sys/types.h
4951          in /usr/include/header.gcc and look up types.h in
4952          /usr/include/sys/header.gcc.  */
4953
4954       char *dir = (char *) alloca (from - filename + 1);
4955       bcopy (filename, dir, from - filename);
4956       dir[from - filename] = '\0';
4957
4958       for (map = read_name_map (dir); map; map = map->map_next)
4959         if (! strcmp (map->map_from, from))
4960           return map->map_to;
4961     }
4962
4963   return filename;
4964 }
4965
4966 /* Insert INC into the include file table, hashed by device and inode number.
4967    If a file with different name but same dev+ino was already in the table,
4968    return 1 and set INC's control macro to the already-known macro.  */
4969
4970 static int
4971 lookup_ino_include (inc)
4972      struct include_file *inc;
4973 {
4974   int hash = ((unsigned) (inc->st.st_dev + INO_T_HASH (inc->st.st_ino))
4975               % INCLUDE_HASHSIZE);
4976   struct include_file *i = include_ino_hashtab[hash];
4977   inc->next_ino = i;
4978   include_ino_hashtab[hash] = inc;
4979
4980   for (; i; i = i->next_ino)
4981     if (INO_T_EQ (inc->st.st_ino, i->st.st_ino)
4982         && inc->st.st_dev == i->st.st_dev) {
4983       inc->control_macro = i->control_macro;
4984       return 1;
4985     }
4986
4987   return 0;
4988 }
4989 \f
4990 /* Process file descriptor F, which corresponds to include file INC,
4991    with output to OP.
4992    SYSTEM_HEADER_P is 1 if this file resides in any one of the known
4993    "system" include directories (as decided by the `is_system_include'
4994    function above).
4995    DIRPTR is the link in the dir path through which this file was found,
4996    or 0 if the file name was absolute.  */
4997
4998 static void
4999 finclude (f, inc, op, system_header_p, dirptr)
5000      int f;
5001      struct include_file *inc;
5002      FILE_BUF *op;
5003      int system_header_p;
5004      struct file_name_list *dirptr;
5005 {
5006   char *fname = inc->fname;
5007   int i;
5008   FILE_BUF *fp;                 /* For input stack frame */
5009   int missing_newline = 0;
5010
5011   CHECK_DEPTH (return;);
5012
5013   fp = &instack[indepth + 1];
5014   bzero ((char *) fp, sizeof (FILE_BUF));
5015   fp->nominal_fname = fp->fname = fname;
5016   fp->inc = inc;
5017   fp->length = 0;
5018   fp->lineno = 1;
5019   fp->if_stack = if_stack;
5020   fp->system_header_p = system_header_p;
5021   fp->dir = dirptr;
5022
5023   if (S_ISREG (inc->st.st_mode)) {
5024     fp->buf = (U_CHAR *) xmalloc (inc->st.st_size + 2);
5025     fp->bufp = fp->buf;
5026
5027     /* Read the file contents, knowing that inc->st.st_size is an upper bound
5028        on the number of bytes we can read.  */
5029     fp->length = safe_read (f, (char *) fp->buf, inc->st.st_size);
5030     if (fp->length < 0) goto nope;
5031   }
5032   else if (S_ISDIR (inc->st.st_mode)) {
5033     error ("directory `%s' specified in #include", fname);
5034     close (f);
5035     return;
5036   } else {
5037     /* Cannot count its file size before reading.
5038        First read the entire file into heap and
5039        copy them into buffer on stack. */
5040
5041     int bsize = 2000;
5042     int st_size = 0;
5043
5044     fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5045
5046     for (;;) {
5047       i = safe_read (f, (char *) fp->buf + st_size, bsize - st_size);
5048       if (i < 0)
5049         goto nope;      /* error! */
5050       st_size += i;
5051       if (st_size != bsize)
5052         break;  /* End of file */
5053       bsize *= 2;
5054       fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5055     }
5056     fp->bufp = fp->buf;
5057     fp->length = st_size;
5058   }
5059
5060   if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
5061       /* Backslash-newline at end is not good enough.  */
5062       || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
5063     fp->buf[fp->length++] = '\n';
5064     missing_newline = 1;
5065   }
5066   fp->buf[fp->length] = '\0';
5067
5068   /* Close descriptor now, so nesting does not use lots of descriptors.  */
5069   close (f);
5070
5071   /* Must do this before calling trigraph_pcp, so that the correct file name
5072      will be printed in warning messages.  */
5073
5074   indepth++;
5075   input_file_stack_tick++;
5076
5077   if (!no_trigraphs)
5078     trigraph_pcp (fp);
5079
5080   output_line_directive (fp, op, 0, enter_file);
5081   rescan (op, 0);
5082
5083   if (missing_newline)
5084     fp->lineno--;
5085
5086   if (pedantic && missing_newline)
5087     pedwarn ("file does not end in newline");
5088
5089   indepth--;
5090   input_file_stack_tick++;
5091   output_line_directive (&instack[indepth], op, 0, leave_file);
5092   free (fp->buf);
5093   return;
5094
5095  nope:
5096
5097   perror_with_name (fname);
5098   close (f);
5099   free (fp->buf);
5100 }
5101
5102 /* Record that inclusion of the include file INC
5103    should be controlled by the macro named MACRO_NAME.
5104    This means that trying to include the file again
5105    will do something if that macro is defined.  */
5106
5107 static void
5108 record_control_macro (inc, macro_name)
5109      struct include_file *inc;
5110      U_CHAR *macro_name;
5111 {
5112   if (!inc->control_macro || inc->control_macro[0])
5113     inc->control_macro = macro_name;
5114 }
5115 \f
5116 /* Load the specified precompiled header into core, and verify its
5117    preconditions.  PCF indicates the file descriptor to read, which must
5118    be a regular file.  *ST is its file status.
5119    FNAME indicates the file name of the original header.
5120    *LIMIT will be set to an address one past the end of the file.
5121    If the preconditions of the file are not satisfied, the buffer is 
5122    freed and we return 0.  If the preconditions are satisfied, return
5123    the address of the buffer following the preconditions.  The buffer, in
5124    this case, should never be freed because various pieces of it will
5125    be referred to until all precompiled strings are output at the end of
5126    the run.
5127 */
5128 static char *
5129 check_precompiled (pcf, st, fname, limit)
5130      int pcf;
5131      struct stat *st;
5132      char *fname;
5133      char **limit;
5134 {
5135   int length = 0;
5136   char *buf;
5137   char *cp;
5138
5139   if (pcp_outfile)
5140     return 0;
5141
5142   if (S_ISREG (st->st_mode))
5143     {
5144       buf = xmalloc (st->st_size + 2);
5145       length = safe_read (pcf, buf, st->st_size);
5146       if (length < 0)
5147         goto nope;
5148     }
5149   else
5150     abort ();
5151     
5152   if (length > 0 && buf[length-1] != '\n')
5153     buf[length++] = '\n';
5154   buf[length] = '\0';
5155   
5156   *limit = buf + length;
5157
5158   /* File is in core.  Check the preconditions. */
5159   if (!check_preconditions (buf))
5160     goto nope;
5161   for (cp = buf; *cp; cp++)
5162     ;
5163 #ifdef DEBUG_PCP
5164   fprintf (stderr, "Using preinclude %s\n", fname);
5165 #endif
5166   return cp + 1;
5167
5168  nope:
5169 #ifdef DEBUG_PCP
5170   fprintf (stderr, "Cannot use preinclude %s\n", fname);
5171 #endif
5172   free (buf);
5173   return 0;
5174 }
5175
5176 /* PREC (null terminated) points to the preconditions of a
5177    precompiled header.  These are a series of #define and #undef
5178    lines which must match the current contents of the hash
5179    table.  */
5180 static int 
5181 check_preconditions (prec)
5182      char *prec;
5183 {
5184   MACRODEF mdef;
5185   char *lineend;
5186   
5187   while (*prec) {
5188     lineend = index (prec, '\n');
5189     
5190     if (*prec++ != '#') {
5191       error ("Bad format encountered while reading precompiled file");
5192       return 0;
5193     }
5194     if (!strncmp (prec, "define", 6)) {
5195       HASHNODE *hp;
5196       
5197       prec += 6;
5198       mdef = create_definition ((U_CHAR *) prec, (U_CHAR *) lineend, NULL_PTR);
5199
5200       if (mdef.defn == 0)
5201         abort ();
5202       
5203       if ((hp = lookup (mdef.symnam, mdef.symlen, -1)) == NULL
5204           || (hp->type != T_MACRO && hp->type != T_CONST)
5205           || (hp->type == T_MACRO
5206               && !compare_defs (mdef.defn, hp->value.defn)
5207               && (mdef.defn->length != 2
5208                   || mdef.defn->expansion[0] != '\n'
5209                   || mdef.defn->expansion[1] != ' ')))
5210         return 0;
5211     } else if (!strncmp (prec, "undef", 5)) {
5212       char *name;
5213       int len;
5214       
5215       prec += 5;
5216       while (is_hor_space[(U_CHAR) *prec])
5217         prec++;
5218       name = prec;
5219       while (is_idchar[(U_CHAR) *prec])
5220         prec++;
5221       len = prec - name;
5222       
5223       if (lookup ((U_CHAR *) name, len, -1))
5224         return 0;
5225     } else {
5226       error ("Bad format encountered while reading precompiled file");
5227       return 0;
5228     }
5229     prec = lineend + 1;
5230   }
5231   /* They all passed successfully */
5232   return 1;
5233 }
5234
5235 /* Process the main body of a precompiled file.  BUF points to the
5236    string section of the file, following the preconditions.  LIMIT is one
5237    character past the end.  NAME is the name of the file being read
5238    in.  OP is the main output buffer */
5239 static void
5240 pcfinclude (buf, limit, name, op)
5241      U_CHAR *buf, *limit, *name;
5242      FILE_BUF *op;
5243 {
5244   FILE_BUF tmpbuf;
5245   int nstrings;
5246   U_CHAR *cp = buf;
5247
5248   /* First in the file comes 4 bytes indicating the number of strings, */
5249   /* in network byte order. (MSB first).  */
5250   nstrings = *cp++;
5251   nstrings = (nstrings << 8) | *cp++;
5252   nstrings = (nstrings << 8) | *cp++;
5253   nstrings = (nstrings << 8) | *cp++;
5254   
5255   /* Looping over each string... */
5256   while (nstrings--) {
5257     U_CHAR *string_start;
5258     U_CHAR *endofthiskey;
5259     STRINGDEF *str;
5260     int nkeys;
5261     
5262     /* Each string starts with a STRINGDEF structure (str), followed */
5263     /* by the text of the string (string_start) */
5264
5265     /* First skip to a longword boundary */
5266     /* ??? Why a 4-byte boundary?  On all machines? */
5267     /* NOTE: This works correctly even if HOST_WIDE_INT
5268        is narrower than a pointer.
5269        Do not try risky measures here to get another type to use!
5270        Do not include stddef.h--it will fail!  */
5271     if ((HOST_WIDE_INT) cp & 3)
5272       cp += 4 - ((HOST_WIDE_INT) cp & 3);
5273     
5274     /* Now get the string. */
5275     str = (STRINGDEF *) (GENERIC_PTR) cp;
5276     string_start = cp += sizeof (STRINGDEF);
5277     
5278     for (; *cp; cp++)           /* skip the string */
5279       ;
5280     
5281     /* We need to macro expand the string here to ensure that the
5282        proper definition environment is in place.  If it were only
5283        expanded when we find out it is needed, macros necessary for
5284        its proper expansion might have had their definitions changed. */
5285     tmpbuf = expand_to_temp_buffer (string_start, cp++, 0, 0);
5286     /* Lineno is already set in the precompiled file */
5287     str->contents = tmpbuf.buf;
5288     str->len = tmpbuf.length;
5289     str->writeflag = 0;
5290     str->filename = name;
5291     str->output_mark = outbuf.bufp - outbuf.buf;
5292     
5293     str->chain = 0;
5294     *stringlist_tailp = str;
5295     stringlist_tailp = &str->chain;
5296     
5297     /* Next comes a fourbyte number indicating the number of keys */
5298     /* for this string. */
5299     nkeys = *cp++;
5300     nkeys = (nkeys << 8) | *cp++;
5301     nkeys = (nkeys << 8) | *cp++;
5302     nkeys = (nkeys << 8) | *cp++;
5303
5304     /* If this number is -1, then the string is mandatory. */
5305     if (nkeys == -1)
5306       str->writeflag = 1;
5307     else
5308       /* Otherwise, for each key, */
5309       for (; nkeys--; free (tmpbuf.buf), cp = endofthiskey + 1) {
5310         KEYDEF *kp = (KEYDEF *) (GENERIC_PTR) cp;
5311         HASHNODE *hp;
5312         
5313         /* It starts with a KEYDEF structure */
5314         cp += sizeof (KEYDEF);
5315         
5316         /* Find the end of the key.  At the end of this for loop we
5317            advance CP to the start of the next key using this variable. */
5318         endofthiskey = cp + strlen ((char *) cp);
5319         kp->str = str;
5320         
5321         /* Expand the key, and enter it into the hash table. */
5322         tmpbuf = expand_to_temp_buffer (cp, endofthiskey, 0, 0);
5323         tmpbuf.bufp = tmpbuf.buf;
5324         
5325         while (is_hor_space[*tmpbuf.bufp])
5326           tmpbuf.bufp++;
5327         if (!is_idstart[*tmpbuf.bufp]
5328             || tmpbuf.bufp == tmpbuf.buf + tmpbuf.length) {
5329           str->writeflag = 1;
5330           continue;
5331         }
5332             
5333         hp = lookup (tmpbuf.bufp, -1, -1);
5334         if (hp == NULL) {
5335           kp->chain = 0;
5336           install (tmpbuf.bufp, -1, T_PCSTRING, (char *) kp, -1);
5337         }
5338         else if (hp->type == T_PCSTRING) {
5339           kp->chain = hp->value.keydef;
5340           hp->value.keydef = kp;
5341         }
5342         else
5343           str->writeflag = 1;
5344       }
5345   }
5346   /* This output_line_directive serves to switch us back to the current
5347      input file in case some of these strings get output (which will 
5348      result in line directives for the header file being output). */
5349   output_line_directive (&instack[indepth], op, 0, enter_file);
5350 }
5351
5352 /* Called from rescan when it hits a key for strings.  Mark them all */
5353  /* used and clean up. */
5354 static void
5355 pcstring_used (hp)
5356      HASHNODE *hp;
5357 {
5358   KEYDEF *kp;
5359   
5360   for (kp = hp->value.keydef; kp; kp = kp->chain)
5361     kp->str->writeflag = 1;
5362   delete_macro (hp);
5363 }
5364
5365 /* Write the output, interspersing precompiled strings in their */
5366  /* appropriate places. */
5367 static void
5368 write_output ()
5369 {
5370   STRINGDEF *next_string;
5371   U_CHAR *cur_buf_loc;
5372   int line_directive_len = 80;
5373   char *line_directive = xmalloc (line_directive_len);
5374   int len;
5375
5376   /* In each run through the loop, either cur_buf_loc == */
5377   /* next_string_loc, in which case we print a series of strings, or */
5378   /* it is less than next_string_loc, in which case we write some of */
5379   /* the buffer. */
5380   cur_buf_loc = outbuf.buf; 
5381   next_string = stringlist;
5382   
5383   while (cur_buf_loc < outbuf.bufp || next_string) {
5384     if (next_string
5385         && cur_buf_loc - outbuf.buf == next_string->output_mark) {
5386       if (next_string->writeflag) {
5387         len = 4 * strlen ((char *) next_string->filename) + 32;
5388         while (len > line_directive_len)
5389           line_directive = xrealloc (line_directive, 
5390                                      line_directive_len *= 2);
5391         sprintf (line_directive, "\n# %d ", next_string->lineno);
5392         strcpy (quote_string (line_directive + strlen (line_directive),
5393                               (char *) next_string->filename),
5394                 "\n");
5395         safe_write (fileno (stdout), line_directive, strlen (line_directive));
5396         safe_write (fileno (stdout),
5397                     (char *) next_string->contents, next_string->len);
5398       }       
5399       next_string = next_string->chain;
5400     }
5401     else {
5402       len = (next_string
5403              ? (next_string->output_mark 
5404                 - (cur_buf_loc - outbuf.buf))
5405              : outbuf.bufp - cur_buf_loc);
5406       
5407       safe_write (fileno (stdout), (char *) cur_buf_loc, len);
5408       cur_buf_loc += len;
5409     }
5410   }
5411   free (line_directive);
5412 }
5413
5414 /* Pass a directive through to the output file.
5415    BUF points to the contents of the directive, as a contiguous string.
5416    LIMIT points to the first character past the end of the directive.
5417    KEYWORD is the keyword-table entry for the directive.  */
5418
5419 static void
5420 pass_thru_directive (buf, limit, op, keyword)
5421      U_CHAR *buf, *limit;
5422      FILE_BUF *op;
5423      struct directive *keyword;
5424 {
5425   register unsigned keyword_length = keyword->length;
5426
5427   check_expand (op, 1 + keyword_length + (limit - buf));
5428   *op->bufp++ = '#';
5429   bcopy (keyword->name, (char *) op->bufp, keyword_length);
5430   op->bufp += keyword_length;
5431   if (limit != buf && buf[0] != ' ')
5432     *op->bufp++ = ' ';
5433   bcopy ((char *) buf, (char *) op->bufp, limit - buf);
5434   op->bufp += (limit - buf);
5435 #if 0
5436   *op->bufp++ = '\n';
5437   /* Count the line we have just made in the output,
5438      to get in sync properly.  */
5439   op->lineno++;
5440 #endif
5441 }
5442 \f
5443 /* The arglist structure is built by do_define to tell
5444    collect_definition where the argument names begin.  That
5445    is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
5446    would contain pointers to the strings x, y, and z.
5447    Collect_definition would then build a DEFINITION node,
5448    with reflist nodes pointing to the places x, y, and z had
5449    appeared.  So the arglist is just convenience data passed
5450    between these two routines.  It is not kept around after
5451    the current #define has been processed and entered into the
5452    hash table. */
5453
5454 struct arglist {
5455   struct arglist *next;
5456   U_CHAR *name;
5457   int length;
5458   int argno;
5459   char rest_args;
5460 };
5461
5462 /* Create a DEFINITION node from a #define directive.  Arguments are 
5463    as for do_define. */
5464 static MACRODEF
5465 create_definition (buf, limit, op)
5466      U_CHAR *buf, *limit;
5467      FILE_BUF *op;
5468 {
5469   U_CHAR *bp;                   /* temp ptr into input buffer */
5470   U_CHAR *symname;              /* remember where symbol name starts */
5471   int sym_length;               /* and how long it is */
5472   int line = instack[indepth].lineno;
5473   char *file = instack[indepth].nominal_fname;
5474   int rest_args = 0;
5475
5476   DEFINITION *defn;
5477   int arglengths = 0;           /* Accumulate lengths of arg names
5478                                    plus number of args.  */
5479   MACRODEF mdef;
5480
5481   bp = buf;
5482
5483   while (is_hor_space[*bp])
5484     bp++;
5485
5486   symname = bp;                 /* remember where it starts */
5487   sym_length = check_macro_name (bp, "macro");
5488   bp += sym_length;
5489
5490   /* Lossage will occur if identifiers or control keywords are broken
5491      across lines using backslash.  This is not the right place to take
5492      care of that. */
5493
5494   if (*bp == '(') {
5495     struct arglist *arg_ptrs = NULL;
5496     int argno = 0;
5497
5498     bp++;                       /* skip '(' */
5499     SKIP_WHITE_SPACE (bp);
5500
5501     /* Loop over macro argument names.  */
5502     while (*bp != ')') {
5503       struct arglist *temp;
5504
5505       temp = (struct arglist *) alloca (sizeof (struct arglist));
5506       temp->name = bp;
5507       temp->next = arg_ptrs;
5508       temp->argno = argno++;
5509       temp->rest_args = 0;
5510       arg_ptrs = temp;
5511
5512       if (rest_args)
5513         pedwarn ("another parameter follows `%s'",
5514                  rest_extension);
5515
5516       if (!is_idstart[*bp])
5517         pedwarn ("invalid character in macro parameter name");
5518       
5519       /* Find the end of the arg name.  */
5520       while (is_idchar[*bp]) {
5521         bp++;
5522         /* do we have a "special" rest-args extension here? */
5523         if (limit - bp > REST_EXTENSION_LENGTH &&
5524             bcmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
5525           rest_args = 1;
5526           temp->rest_args = 1;
5527           break;
5528         }
5529       }
5530       temp->length = bp - temp->name;
5531       if (rest_args == 1)
5532         bp += REST_EXTENSION_LENGTH;
5533       arglengths += temp->length + 2;
5534       SKIP_WHITE_SPACE (bp);
5535       if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
5536         error ("badly punctuated parameter list in `#define'");
5537         goto nope;
5538       }
5539       if (*bp == ',') {
5540         bp++;
5541         SKIP_WHITE_SPACE (bp);
5542         /* A comma at this point can only be followed by an identifier.  */
5543         if (!is_idstart[*bp]) {
5544           error ("badly punctuated parameter list in `#define'");
5545           goto nope;
5546         }
5547       }
5548       if (bp >= limit) {
5549         error ("unterminated parameter list in `#define'");
5550         goto nope;
5551       }
5552       {
5553         struct arglist *otemp;
5554
5555         for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
5556           if (temp->length == otemp->length &&
5557               bcmp (temp->name, otemp->name, temp->length) == 0) {
5558               error ("duplicate argument name `%.*s' in `#define'",
5559                      temp->length, temp->name);
5560               goto nope;
5561           }
5562       }
5563     }
5564
5565     ++bp;                       /* skip paren */
5566     SKIP_WHITE_SPACE (bp);
5567     /* now everything from bp before limit is the definition. */
5568     defn = collect_expansion (bp, limit, argno, arg_ptrs);
5569     defn->rest_args = rest_args;
5570
5571     /* Now set defn->args.argnames to the result of concatenating
5572        the argument names in reverse order
5573        with comma-space between them.  */
5574     defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
5575     {
5576       struct arglist *temp;
5577       int i = 0;
5578       for (temp = arg_ptrs; temp; temp = temp->next) {
5579         bcopy (temp->name, &defn->args.argnames[i], temp->length);
5580         i += temp->length;
5581         if (temp->next != 0) {
5582           defn->args.argnames[i++] = ',';
5583           defn->args.argnames[i++] = ' ';
5584         }
5585       }
5586       defn->args.argnames[i] = 0;
5587     }
5588   } else {
5589     /* Simple expansion or empty definition.  */
5590
5591     if (bp < limit)
5592       {
5593         if (is_hor_space[*bp]) {
5594           bp++;
5595           SKIP_WHITE_SPACE (bp);
5596         } else {
5597           switch (*bp) {
5598             case '!':  case '"':  case '#':  case '%':  case '&':  case '\'':
5599             case ')':  case '*':  case '+':  case ',':  case '-':  case '.':
5600             case '/':  case ':':  case ';':  case '<':  case '=':  case '>':
5601             case '?':  case '[':  case '\\': case ']':  case '^':  case '{':
5602             case '|':  case '}':  case '~':
5603               warning ("missing white space after `#define %.*s'",
5604                        sym_length, symname);
5605               break;
5606
5607             default:
5608               pedwarn ("missing white space after `#define %.*s'",
5609                        sym_length, symname);
5610               break;
5611           }
5612         }
5613       }
5614     /* Now everything from bp before limit is the definition. */
5615     defn = collect_expansion (bp, limit, -1, NULL_PTR);
5616     defn->args.argnames = (U_CHAR *) "";
5617   }
5618
5619   defn->line = line;
5620   defn->file = file;
5621
5622   /* OP is null if this is a predefinition */
5623   defn->predefined = !op;
5624   mdef.defn = defn;
5625   mdef.symnam = symname;
5626   mdef.symlen = sym_length;
5627
5628   return mdef;
5629
5630  nope:
5631   mdef.defn = 0;
5632   return mdef;
5633 }
5634  
5635 /* Process a #define directive.
5636 BUF points to the contents of the #define directive, as a contiguous string.
5637 LIMIT points to the first character past the end of the definition.
5638 KEYWORD is the keyword-table entry for #define.  */
5639
5640 static int
5641 do_define (buf, limit, op, keyword)
5642      U_CHAR *buf, *limit;
5643      FILE_BUF *op;
5644      struct directive *keyword;
5645 {
5646   int hashcode;
5647   MACRODEF mdef;
5648
5649   /* If this is a precompiler run (with -pcp) pass thru #define directives.  */
5650   if (pcp_outfile && op)
5651     pass_thru_directive (buf, limit, op, keyword);
5652
5653   mdef = create_definition (buf, limit, op);
5654   if (mdef.defn == 0)
5655     goto nope;
5656
5657   hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
5658
5659   {
5660     HASHNODE *hp;
5661     if ((hp = lookup (mdef.symnam, mdef.symlen, hashcode)) != NULL) {
5662       int ok = 0;
5663       /* Redefining a precompiled key is ok.  */
5664       if (hp->type == T_PCSTRING)
5665         ok = 1;
5666       /* Redefining a macro is ok if the definitions are the same.  */
5667       else if (hp->type == T_MACRO)
5668         ok = ! compare_defs (mdef.defn, hp->value.defn);
5669       /* Redefining a constant is ok with -D.  */
5670       else if (hp->type == T_CONST)
5671         ok = ! done_initializing;
5672       /* Print the warning if it's not ok.  */
5673       if (!ok) {
5674         /* If we are passing through #define and #undef directives, do
5675            that for this re-definition now.  */
5676         if (debug_output && op)
5677           pass_thru_directive (buf, limit, op, keyword);
5678
5679         pedwarn ("`%.*s' redefined", mdef.symlen, mdef.symnam);
5680         if (hp->type == T_MACRO)
5681           pedwarn_with_file_and_line (hp->value.defn->file, hp->value.defn->line,
5682                                       "this is the location of the previous definition");
5683       }
5684       /* Replace the old definition.  */
5685       hp->type = T_MACRO;
5686       hp->value.defn = mdef.defn;
5687     } else {
5688       /* If we are passing through #define and #undef directives, do
5689          that for this new definition now.  */
5690       if (debug_output && op)
5691         pass_thru_directive (buf, limit, op, keyword);
5692       install (mdef.symnam, mdef.symlen, T_MACRO,
5693                (char *) mdef.defn, hashcode);
5694     }
5695   }
5696
5697   return 0;
5698
5699 nope:
5700
5701   return 1;
5702 }
5703 \f
5704 /* Check a purported macro name SYMNAME, and yield its length.
5705    USAGE is the kind of name this is intended for.  */
5706
5707 static int
5708 check_macro_name (symname, usage)
5709      U_CHAR *symname;
5710      char *usage;
5711 {
5712   U_CHAR *p;
5713   int sym_length;
5714
5715   for (p = symname; is_idchar[*p]; p++)
5716     ;
5717   sym_length = p - symname;
5718   if (sym_length == 0)
5719     error ("invalid %s name", usage);
5720   else if (!is_idstart[*symname]
5721            || (sym_length == 7 && ! bcmp (symname, "defined", 7)))
5722     error ("invalid %s name `%.*s'", usage, sym_length, symname);
5723   return sym_length;
5724 }
5725
5726 /*
5727  * return zero if two DEFINITIONs are isomorphic
5728  */
5729 static int
5730 compare_defs (d1, d2)
5731      DEFINITION *d1, *d2;
5732 {
5733   register struct reflist *a1, *a2;
5734   register U_CHAR *p1 = d1->expansion;
5735   register U_CHAR *p2 = d2->expansion;
5736   int first = 1;
5737
5738   if (d1->nargs != d2->nargs)
5739     return 1;
5740   if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
5741     return 1;
5742   for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
5743        a1 = a1->next, a2 = a2->next) {
5744     if (!((a1->nchars == a2->nchars && ! bcmp (p1, p2, a1->nchars))
5745           || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
5746         || a1->argno != a2->argno
5747         || a1->stringify != a2->stringify
5748         || a1->raw_before != a2->raw_before
5749         || a1->raw_after != a2->raw_after)
5750       return 1;
5751     first = 0;
5752     p1 += a1->nchars;
5753     p2 += a2->nchars;
5754   }
5755   if (a1 != a2)
5756     return 1;
5757   if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
5758                      p2, d2->length - (p2 - d2->expansion), 1))
5759     return 1;
5760   return 0;
5761 }
5762
5763 /* Return 1 if two parts of two macro definitions are effectively different.
5764    One of the parts starts at BEG1 and has LEN1 chars;
5765    the other has LEN2 chars at BEG2.
5766    Any sequence of whitespace matches any other sequence of whitespace.
5767    FIRST means these parts are the first of a macro definition;
5768     so ignore leading whitespace entirely.
5769    LAST means these parts are the last of a macro definition;
5770     so ignore trailing whitespace entirely.  */
5771
5772 static int
5773 comp_def_part (first, beg1, len1, beg2, len2, last)
5774      int first;
5775      U_CHAR *beg1, *beg2;
5776      int len1, len2;
5777      int last;
5778 {
5779   register U_CHAR *end1 = beg1 + len1;
5780   register U_CHAR *end2 = beg2 + len2;
5781   if (first) {
5782     while (beg1 != end1 && is_space[*beg1]) beg1++;
5783     while (beg2 != end2 && is_space[*beg2]) beg2++;
5784   }
5785   if (last) {
5786     while (beg1 != end1 && is_space[end1[-1]]) end1--;
5787     while (beg2 != end2 && is_space[end2[-1]]) end2--;
5788   }
5789   while (beg1 != end1 && beg2 != end2) {
5790     if (is_space[*beg1] && is_space[*beg2]) {
5791       while (beg1 != end1 && is_space[*beg1]) beg1++;
5792       while (beg2 != end2 && is_space[*beg2]) beg2++;
5793     } else if (*beg1 == *beg2) {
5794       beg1++; beg2++;
5795     } else break;
5796   }
5797   return (beg1 != end1) || (beg2 != end2);
5798 }
5799 \f
5800 /* Read a replacement list for a macro with parameters.
5801    Build the DEFINITION structure.
5802    Reads characters of text starting at BUF until END.
5803    ARGLIST specifies the formal parameters to look for
5804    in the text of the definition; NARGS is the number of args
5805    in that list, or -1 for a macro name that wants no argument list.
5806    MACRONAME is the macro name itself (so we can avoid recursive expansion)
5807    and NAMELEN is its length in characters.
5808    
5809 Note that comments, backslash-newlines, and leading white space
5810 have already been deleted from the argument.  */
5811
5812 /* If there is no trailing whitespace, a Newline Space is added at the end
5813    to prevent concatenation that would be contrary to the standard.  */
5814
5815 static DEFINITION *
5816 collect_expansion (buf, end, nargs, arglist)
5817      U_CHAR *buf, *end;
5818      int nargs;
5819      struct arglist *arglist;
5820 {
5821   DEFINITION *defn;
5822   register U_CHAR *p, *limit, *lastp, *exp_p;
5823   struct reflist *endpat = NULL;
5824   /* Pointer to first nonspace after last ## seen.  */
5825   U_CHAR *concat = 0;
5826   /* Pointer to first nonspace after last single-# seen.  */
5827   U_CHAR *stringify = 0;
5828   /* How those tokens were spelled.  */
5829   enum sharp_token_type concat_sharp_token_type = NO_SHARP_TOKEN;
5830   enum sharp_token_type stringify_sharp_token_type = NO_SHARP_TOKEN;
5831   int maxsize;
5832   int expected_delimiter = '\0';
5833
5834   /* Scan thru the replacement list, ignoring comments and quoted
5835      strings, picking up on the macro calls.  It does a linear search
5836      thru the arg list on every potential symbol.  Profiling might say
5837      that something smarter should happen. */
5838
5839   if (end < buf)
5840     abort ();
5841
5842   /* Find the beginning of the trailing whitespace.  */
5843   limit = end;
5844   p = buf;
5845   while (p < limit && is_space[limit[-1]]) limit--;
5846
5847   /* Allocate space for the text in the macro definition.
5848      Each input char may or may not need 1 byte,
5849      so this is an upper bound.
5850      The extra 3 are for invented trailing newline-marker and final null.  */
5851   maxsize = (sizeof (DEFINITION)
5852              + (limit - p) + 3);
5853   defn = (DEFINITION *) xcalloc (1, maxsize);
5854
5855   defn->nargs = nargs;
5856   exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
5857   lastp = exp_p;
5858
5859   if (p[0] == '#'
5860       ? p[1] == '#'
5861       : p[0] == '%' && p[1] == ':' && p[2] == '%' && p[3] == ':') {
5862     error ("`##' at start of macro definition");
5863     p += p[0] == '#' ? 2 : 4;
5864   }
5865
5866   /* Process the main body of the definition.  */
5867   while (p < limit) {
5868     int skipped_arg = 0;
5869     register U_CHAR c = *p++;
5870
5871     *exp_p++ = c;
5872
5873     if (!traditional) {
5874       switch (c) {
5875       case '\'':
5876       case '\"':
5877         if (expected_delimiter != '\0') {
5878           if (c == expected_delimiter)
5879             expected_delimiter = '\0';
5880         } else
5881           expected_delimiter = c;
5882         break;
5883
5884       case '\\':
5885         if (p < limit && expected_delimiter) {
5886           /* In a string, backslash goes through
5887              and makes next char ordinary.  */
5888           *exp_p++ = *p++;
5889         }
5890         break;
5891
5892       case '%':
5893         if (!expected_delimiter && *p == ':') {
5894           /* %: is not a digraph if preceded by an odd number of '<'s.  */
5895           U_CHAR *p0 = p - 1;
5896           while (buf < p0 && p0[-1] == '<')
5897             p0--;
5898           if ((p - p0) & 1) {
5899             /* Treat %:%: as ## and %: as #.  */
5900             if (p[1] == '%' && p[2] == ':') {
5901               p += 2;
5902               goto sharp_sharp_token;
5903             }
5904             if (nargs >= 0) {
5905               p++;
5906               goto sharp_token;
5907             }
5908           }
5909         }
5910         break;
5911
5912       case '#':
5913         /* # is ordinary inside a string.  */
5914         if (expected_delimiter)
5915           break;
5916         if (*p == '#') {
5917         sharp_sharp_token:
5918           /* ##: concatenate preceding and following tokens.  */
5919           /* Take out the first #, discard preceding whitespace.  */
5920           exp_p--;
5921           while (exp_p > lastp && is_hor_space[exp_p[-1]])
5922             --exp_p;
5923           /* Skip the second #.  */
5924           p++;
5925           concat_sharp_token_type = c;
5926           if (is_hor_space[*p]) {
5927             concat_sharp_token_type = c + 1;
5928             p++;
5929             SKIP_WHITE_SPACE (p);
5930           }
5931           concat = p;
5932           if (p == limit)
5933             error ("`##' at end of macro definition");
5934         } else if (nargs >= 0) {
5935           /* Single #: stringify following argument ref.
5936              Don't leave the # in the expansion.  */
5937         sharp_token:
5938           exp_p--;
5939           stringify_sharp_token_type = c;
5940           if (is_hor_space[*p]) {
5941             stringify_sharp_token_type = c + 1;
5942             p++;
5943             SKIP_WHITE_SPACE (p);
5944           }
5945           if (! is_idstart[*p] || nargs == 0)
5946             error ("`#' operator is not followed by a macro argument name");
5947           else
5948             stringify = p;
5949         }
5950         break;
5951       }
5952     } else {
5953       /* In -traditional mode, recognize arguments inside strings and
5954          and character constants, and ignore special properties of #.
5955          Arguments inside strings are considered "stringified", but no
5956          extra quote marks are supplied.  */
5957       switch (c) {
5958       case '\'':
5959       case '\"':
5960         if (expected_delimiter != '\0') {
5961           if (c == expected_delimiter)
5962             expected_delimiter = '\0';
5963         } else
5964           expected_delimiter = c;
5965         break;
5966
5967       case '\\':
5968         /* Backslash quotes delimiters and itself, but not macro args.  */
5969         if (expected_delimiter != 0 && p < limit
5970             && (*p == expected_delimiter || *p == '\\')) {
5971           *exp_p++ = *p++;
5972           continue;
5973         }
5974         break;
5975
5976       case '/':
5977         if (expected_delimiter != '\0') /* No comments inside strings.  */
5978           break;
5979         if (*p == '*') {
5980           /* If we find a comment that wasn't removed by handle_directive,
5981              this must be -traditional.  So replace the comment with
5982              nothing at all.  */
5983           exp_p--;
5984           p += 1;
5985           while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
5986             p++;
5987 #if 0
5988           /* Mark this as a concatenation-point, as if it had been ##.  */
5989           concat = p;
5990 #endif
5991         }
5992         break;
5993       }
5994     }
5995
5996     /* Handle the start of a symbol.  */
5997     if (is_idchar[c] && nargs > 0) {
5998       U_CHAR *id_beg = p - 1;
5999       int id_len;
6000
6001       --exp_p;
6002       while (p != limit && is_idchar[*p]) p++;
6003       id_len = p - id_beg;
6004
6005       if (is_idstart[c]) {
6006         register struct arglist *arg;
6007
6008         for (arg = arglist; arg != NULL; arg = arg->next) {
6009           struct reflist *tpat;
6010
6011           if (arg->name[0] == c
6012               && arg->length == id_len
6013               && bcmp (arg->name, id_beg, id_len) == 0) {
6014             enum sharp_token_type tpat_stringify;
6015             if (expected_delimiter) {
6016               if (warn_stringify) {
6017                 if (traditional) {
6018                   warning ("macro argument `%.*s' is stringified.",
6019                            id_len, arg->name);
6020                 } else {
6021                   warning ("macro arg `%.*s' would be stringified with -traditional.",
6022                            id_len, arg->name);
6023                 }
6024               }
6025               /* If ANSI, don't actually substitute inside a string.  */
6026               if (!traditional)
6027                 break;
6028               tpat_stringify = SHARP_TOKEN;
6029             } else {
6030               tpat_stringify
6031                 = (stringify == id_beg
6032                    ? stringify_sharp_token_type : NO_SHARP_TOKEN);
6033             }
6034             /* make a pat node for this arg and append it to the end of
6035                the pat list */
6036             tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
6037             tpat->next = NULL;
6038             tpat->raw_before
6039               = concat == id_beg ? concat_sharp_token_type : NO_SHARP_TOKEN;
6040             tpat->raw_after = NO_SHARP_TOKEN;
6041             tpat->rest_args = arg->rest_args;
6042             tpat->stringify = tpat_stringify;
6043
6044             if (endpat == NULL)
6045               defn->pattern = tpat;
6046             else
6047               endpat->next = tpat;
6048             endpat = tpat;
6049
6050             tpat->argno = arg->argno;
6051             tpat->nchars = exp_p - lastp;
6052             {
6053               register U_CHAR *p1 = p;
6054               SKIP_WHITE_SPACE (p1);
6055               if (p1[0]=='#'
6056                   ? p1[1]=='#'
6057                   : p1[0]=='%' && p1[1]==':' && p1[2]=='%' && p1[3]==':')
6058                 tpat->raw_after = p1[0] + (p != p1);
6059             }
6060             lastp = exp_p;      /* place to start copying from next time */
6061             skipped_arg = 1;
6062             break;
6063           }
6064         }
6065       }
6066
6067       /* If this was not a macro arg, copy it into the expansion.  */
6068       if (! skipped_arg) {
6069         register U_CHAR *lim1 = p;
6070         p = id_beg;
6071         while (p != lim1)
6072           *exp_p++ = *p++;
6073         if (stringify == id_beg)
6074           error ("`#' operator should be followed by a macro argument name");
6075       }
6076     }
6077   }
6078
6079   if (!traditional && expected_delimiter == 0) {
6080     /* If ANSI, put in a newline-space marker to prevent token pasting.
6081        But not if "inside a string" (which in ANSI mode happens only for
6082        -D option).  */
6083     *exp_p++ = '\n';
6084     *exp_p++ = ' ';
6085   }
6086
6087   *exp_p = '\0';
6088
6089   defn->length = exp_p - defn->expansion;
6090
6091   /* Crash now if we overrun the allocated size.  */
6092   if (defn->length + 1 > maxsize)
6093     abort ();
6094
6095 #if 0
6096 /* This isn't worth the time it takes.  */
6097   /* give back excess storage */
6098   defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
6099 #endif
6100
6101   return defn;
6102 }
6103 \f
6104 static int
6105 do_assert (buf, limit, op, keyword)
6106      U_CHAR *buf, *limit;
6107      FILE_BUF *op;
6108      struct directive *keyword;
6109 {
6110   U_CHAR *bp;                   /* temp ptr into input buffer */
6111   U_CHAR *symname;              /* remember where symbol name starts */
6112   int sym_length;               /* and how long it is */
6113   struct arglist *tokens = NULL;
6114
6115   if (pedantic && done_initializing && !instack[indepth].system_header_p)
6116     pedwarn ("ANSI C does not allow `#assert'");
6117
6118   bp = buf;
6119
6120   while (is_hor_space[*bp])
6121     bp++;
6122
6123   symname = bp;                 /* remember where it starts */
6124   sym_length = check_macro_name (bp, "assertion");
6125   bp += sym_length;
6126   /* #define doesn't do this, but we should.  */
6127   SKIP_WHITE_SPACE (bp);
6128
6129   /* Lossage will occur if identifiers or control tokens are broken
6130      across lines using backslash.  This is not the right place to take
6131      care of that. */
6132
6133   if (*bp != '(') {
6134     error ("missing token-sequence in `#assert'");
6135     return 1;
6136   }
6137
6138   {
6139     int error_flag = 0;
6140
6141     bp++;                       /* skip '(' */
6142     SKIP_WHITE_SPACE (bp);
6143
6144     tokens = read_token_list (&bp, limit, &error_flag);
6145     if (error_flag)
6146       return 1;
6147     if (tokens == 0) {
6148       error ("empty token-sequence in `#assert'");
6149       return 1;
6150     }
6151
6152     ++bp;                       /* skip paren */
6153     SKIP_WHITE_SPACE (bp);
6154   }
6155
6156   /* If this name isn't already an assertion name, make it one.
6157      Error if it was already in use in some other way.  */
6158
6159   {
6160     ASSERTION_HASHNODE *hp;
6161     int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6162     struct tokenlist_list *value
6163       = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6164
6165     hp = assertion_lookup (symname, sym_length, hashcode);
6166     if (hp == NULL) {
6167       if (sym_length == 7 && ! bcmp (symname, "defined", 7))
6168         error ("`defined' redefined as assertion");
6169       hp = assertion_install (symname, sym_length, hashcode);
6170     }
6171
6172     /* Add the spec'd token-sequence to the list of such.  */
6173     value->tokens = tokens;
6174     value->next = hp->value;
6175     hp->value = value;
6176   }
6177
6178   return 0;
6179 }
6180 \f
6181 static int
6182 do_unassert (buf, limit, op, keyword)
6183      U_CHAR *buf, *limit;
6184      FILE_BUF *op;
6185      struct directive *keyword;
6186 {
6187   U_CHAR *bp;                   /* temp ptr into input buffer */
6188   U_CHAR *symname;              /* remember where symbol name starts */
6189   int sym_length;               /* and how long it is */
6190
6191   struct arglist *tokens = NULL;
6192   int tokens_specified = 0;
6193
6194   if (pedantic && done_initializing && !instack[indepth].system_header_p)
6195     pedwarn ("ANSI C does not allow `#unassert'");
6196
6197   bp = buf;
6198
6199   while (is_hor_space[*bp])
6200     bp++;
6201
6202   symname = bp;                 /* remember where it starts */
6203   sym_length = check_macro_name (bp, "assertion");
6204   bp += sym_length;
6205   /* #define doesn't do this, but we should.  */
6206   SKIP_WHITE_SPACE (bp);
6207
6208   /* Lossage will occur if identifiers or control tokens are broken
6209      across lines using backslash.  This is not the right place to take
6210      care of that. */
6211
6212   if (*bp == '(') {
6213     int error_flag = 0;
6214
6215     bp++;                       /* skip '(' */
6216     SKIP_WHITE_SPACE (bp);
6217
6218     tokens = read_token_list (&bp, limit, &error_flag);
6219     if (error_flag)
6220       return 1;
6221     if (tokens == 0) {
6222       error ("empty token list in `#unassert'");
6223       return 1;
6224     }
6225
6226     tokens_specified = 1;
6227
6228     ++bp;                       /* skip paren */
6229     SKIP_WHITE_SPACE (bp);
6230   }
6231
6232   {
6233     ASSERTION_HASHNODE *hp;
6234     int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6235     struct tokenlist_list *tail, *prev;
6236
6237     hp = assertion_lookup (symname, sym_length, hashcode);
6238     if (hp == NULL)
6239       return 1;
6240
6241     /* If no token list was specified, then eliminate this assertion
6242        entirely.  */
6243     if (! tokens_specified) {
6244       struct tokenlist_list *next;
6245       for (tail = hp->value; tail; tail = next) {
6246         next = tail->next;
6247         free_token_list (tail->tokens);
6248         free (tail);
6249       }
6250       delete_assertion (hp);
6251     } else {
6252       /* If a list of tokens was given, then delete any matching list.  */
6253
6254       tail = hp->value;
6255       prev = 0;
6256       while (tail) {
6257         struct tokenlist_list *next = tail->next;
6258         if (compare_token_lists (tail->tokens, tokens)) {
6259           if (prev)
6260             prev->next = next;
6261           else
6262             hp->value = tail->next;
6263           free_token_list (tail->tokens);
6264           free (tail);
6265         } else {
6266           prev = tail;
6267         }
6268         tail = next;
6269       }
6270     }
6271   }
6272
6273   return 0;
6274 }
6275 \f
6276 /* Test whether there is an assertion named NAME
6277    and optionally whether it has an asserted token list TOKENS.
6278    NAME is not null terminated; its length is SYM_LENGTH.
6279    If TOKENS_SPECIFIED is 0, then don't check for any token list.  */
6280
6281 int
6282 check_assertion (name, sym_length, tokens_specified, tokens)
6283      U_CHAR *name;
6284      int sym_length;
6285      int tokens_specified;
6286      struct arglist *tokens;
6287 {
6288   ASSERTION_HASHNODE *hp;
6289   int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
6290
6291   if (pedantic && !instack[indepth].system_header_p)
6292     pedwarn ("ANSI C does not allow testing assertions");
6293
6294   hp = assertion_lookup (name, sym_length, hashcode);
6295   if (hp == NULL)
6296     /* It is not an assertion; just return false.  */
6297     return 0;
6298
6299   /* If no token list was specified, then value is 1.  */
6300   if (! tokens_specified)
6301     return 1;
6302
6303   {
6304     struct tokenlist_list *tail;
6305
6306     tail = hp->value;
6307
6308     /* If a list of tokens was given,
6309        then succeed if the assertion records a matching list.  */
6310
6311     while (tail) {
6312       if (compare_token_lists (tail->tokens, tokens))
6313         return 1;
6314       tail = tail->next;
6315     }
6316
6317     /* Fail if the assertion has no matching list.  */
6318     return 0;
6319   }
6320 }
6321
6322 /* Compare two lists of tokens for equality including order of tokens.  */
6323
6324 static int
6325 compare_token_lists (l1, l2)
6326      struct arglist *l1, *l2;
6327 {
6328   while (l1 && l2) {
6329     if (l1->length != l2->length)
6330       return 0;
6331     if (bcmp (l1->name, l2->name, l1->length))
6332       return 0;
6333     l1 = l1->next;
6334     l2 = l2->next;
6335   }
6336
6337   /* Succeed if both lists end at the same time.  */
6338   return l1 == l2;
6339 }
6340 \f
6341 /* Read a space-separated list of tokens ending in a close parenthesis.
6342    Return a list of strings, in the order they were written.
6343    (In case of error, return 0 and store -1 in *ERROR_FLAG.)
6344    Parse the text starting at *BPP, and update *BPP.
6345    Don't parse beyond LIMIT.  */
6346
6347 static struct arglist *
6348 read_token_list (bpp, limit, error_flag)
6349      U_CHAR **bpp;
6350      U_CHAR *limit;
6351      int *error_flag;
6352 {
6353   struct arglist *token_ptrs = 0;
6354   U_CHAR *bp = *bpp;
6355   int depth = 1;
6356
6357   *error_flag = 0;
6358
6359   /* Loop over the assertion value tokens.  */
6360   while (depth > 0) {
6361     struct arglist *temp;
6362     int eofp = 0;
6363     U_CHAR *beg = bp;
6364
6365     /* Find the end of the token.  */
6366     if (*bp == '(') {
6367       bp++;
6368       depth++;
6369     } else if (*bp == ')') {
6370       depth--;
6371       if (depth == 0)
6372         break;
6373       bp++;
6374     } else if (*bp == '"' || *bp == '\'')
6375       bp = skip_quoted_string (bp, limit, 0, NULL_PTR, NULL_PTR, &eofp);
6376     else
6377       while (! is_hor_space[*bp] && *bp != '(' && *bp != ')'
6378              && *bp != '"' && *bp != '\'' && bp != limit)
6379         bp++;
6380
6381     temp = (struct arglist *) xmalloc (sizeof (struct arglist));
6382     temp->name = (U_CHAR *) xmalloc (bp - beg + 1);
6383     bcopy ((char *) beg, (char *) temp->name, bp - beg);
6384     temp->name[bp - beg] = 0;
6385     temp->next = token_ptrs;
6386     token_ptrs = temp;
6387     temp->length = bp - beg;
6388
6389     SKIP_WHITE_SPACE (bp);
6390
6391     if (bp >= limit) {
6392       error ("unterminated token sequence in `#assert' or `#unassert'");
6393       *error_flag = -1;
6394       return 0;
6395     }
6396   }
6397   *bpp = bp;
6398
6399   /* We accumulated the names in reverse order.
6400      Now reverse them to get the proper order.  */
6401   {
6402     register struct arglist *prev = 0, *this, *next;
6403     for (this = token_ptrs; this; this = next) {
6404       next = this->next;
6405       this->next = prev;
6406       prev = this;
6407     }
6408     return prev;
6409   }
6410 }
6411
6412 static void
6413 free_token_list (tokens)
6414      struct arglist *tokens;
6415 {
6416   while (tokens) {
6417     struct arglist *next = tokens->next;
6418     free (tokens->name);
6419     free (tokens);
6420     tokens = next;
6421   }
6422 }
6423 \f
6424 /*
6425  * Install a name in the assertion hash table.
6426  *
6427  * If LEN is >= 0, it is the length of the name.
6428  * Otherwise, compute the length by scanning the entire name.
6429  *
6430  * If HASH is >= 0, it is the precomputed hash code.
6431  * Otherwise, compute the hash code.
6432  */
6433 static ASSERTION_HASHNODE *
6434 assertion_install (name, len, hash)
6435      U_CHAR *name;
6436      int len;
6437      int hash;
6438 {
6439   register ASSERTION_HASHNODE *hp;
6440   register int i, bucket;
6441   register U_CHAR *p, *q;
6442
6443   i = sizeof (ASSERTION_HASHNODE) + len + 1;
6444   hp = (ASSERTION_HASHNODE *) xmalloc (i);
6445   bucket = hash;
6446   hp->bucket_hdr = &assertion_hashtab[bucket];
6447   hp->next = assertion_hashtab[bucket];
6448   assertion_hashtab[bucket] = hp;
6449   hp->prev = NULL;
6450   if (hp->next != NULL)
6451     hp->next->prev = hp;
6452   hp->length = len;
6453   hp->value = 0;
6454   hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
6455   p = hp->name;
6456   q = name;
6457   for (i = 0; i < len; i++)
6458     *p++ = *q++;
6459   hp->name[len] = 0;
6460   return hp;
6461 }
6462
6463 /*
6464  * find the most recent hash node for name name (ending with first
6465  * non-identifier char) installed by install
6466  *
6467  * If LEN is >= 0, it is the length of the name.
6468  * Otherwise, compute the length by scanning the entire name.
6469  *
6470  * If HASH is >= 0, it is the precomputed hash code.
6471  * Otherwise, compute the hash code.
6472  */
6473 static ASSERTION_HASHNODE *
6474 assertion_lookup (name, len, hash)
6475      U_CHAR *name;
6476      int len;
6477      int hash;
6478 {
6479   register ASSERTION_HASHNODE *bucket;
6480
6481   bucket = assertion_hashtab[hash];
6482   while (bucket) {
6483     if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
6484       return bucket;
6485     bucket = bucket->next;
6486   }
6487   return NULL;
6488 }
6489
6490 static void
6491 delete_assertion (hp)
6492      ASSERTION_HASHNODE *hp;
6493 {
6494
6495   if (hp->prev != NULL)
6496     hp->prev->next = hp->next;
6497   if (hp->next != NULL)
6498     hp->next->prev = hp->prev;
6499
6500   /* make sure that the bucket chain header that
6501      the deleted guy was on points to the right thing afterwards. */
6502   if (hp == *hp->bucket_hdr)
6503     *hp->bucket_hdr = hp->next;
6504
6505   free (hp);
6506 }
6507 \f
6508 /*
6509  * interpret #line directive.  Remembers previously seen fnames
6510  * in its very own hash table.
6511  */
6512 #define FNAME_HASHSIZE 37
6513
6514 static int
6515 do_line (buf, limit, op, keyword)
6516      U_CHAR *buf, *limit;
6517      FILE_BUF *op;
6518      struct directive *keyword;
6519 {
6520   register U_CHAR *bp;
6521   FILE_BUF *ip = &instack[indepth];
6522   FILE_BUF tem;
6523   int new_lineno;
6524   enum file_change_code file_change = same_file;
6525
6526   /* Expand any macros.  */
6527   tem = expand_to_temp_buffer (buf, limit, 0, 0);
6528
6529   /* Point to macroexpanded line, which is null-terminated now.  */
6530   bp = tem.buf;
6531   SKIP_WHITE_SPACE (bp);
6532
6533   if (!isdigit (*bp)) {
6534     error ("invalid format `#line' directive");
6535     return 0;
6536   }
6537
6538   /* The Newline at the end of this line remains to be processed.
6539      To put the next line at the specified line number,
6540      we must store a line number now that is one less.  */
6541   new_lineno = atoi ((char *) bp) - 1;
6542
6543   /* NEW_LINENO is one less than the actual line number here.  */
6544   if (pedantic && new_lineno < 0)
6545     pedwarn ("line number out of range in `#line' directive");
6546
6547   /* skip over the line number.  */
6548   while (isdigit (*bp))
6549     bp++;
6550
6551 #if 0 /* #line 10"foo.c" is supposed to be allowed.  */
6552   if (*bp && !is_space[*bp]) {
6553     error ("invalid format `#line' directive");
6554     return;
6555   }
6556 #endif
6557
6558   SKIP_WHITE_SPACE (bp);
6559
6560   if (*bp == '\"') {
6561     static HASHNODE *fname_table[FNAME_HASHSIZE];
6562     HASHNODE *hp, **hash_bucket;
6563     U_CHAR *fname, *p;
6564     int fname_length;
6565
6566     fname = ++bp;
6567
6568     /* Turn the file name, which is a character string literal,
6569        into a null-terminated string.  Do this in place.  */
6570     p = bp;
6571     for (;;)
6572       switch ((*p++ = *bp++)) {
6573       case '\0':
6574         error ("invalid format `#line' directive");
6575         return 0;
6576
6577       case '\\':
6578         {
6579           char *bpc = (char *) bp;
6580           int c = parse_escape (&bpc);
6581           bp = (U_CHAR *) bpc;
6582           if (c < 0)
6583             p--;
6584           else
6585             p[-1] = c;
6586         }
6587         break;
6588
6589       case '\"':
6590         p[-1] = 0;
6591         goto fname_done;
6592       }
6593   fname_done:
6594     fname_length = p - fname;
6595
6596     SKIP_WHITE_SPACE (bp);
6597     if (*bp) {
6598       if (pedantic)
6599         pedwarn ("garbage at end of `#line' directive");
6600       if (*bp == '1')
6601         file_change = enter_file;
6602       else if (*bp == '2')
6603         file_change = leave_file;
6604       else if (*bp == '3')
6605         ip->system_header_p = 1;
6606       else if (*bp == '4')
6607         ip->system_header_p = 2;
6608       else {
6609         error ("invalid format `#line' directive");
6610         return 0;
6611       }
6612
6613       bp++;
6614       SKIP_WHITE_SPACE (bp);
6615       if (*bp == '3') {
6616         ip->system_header_p = 1;
6617         bp++;
6618         SKIP_WHITE_SPACE (bp);
6619       }
6620       if (*bp == '4') {
6621         ip->system_header_p = 2;
6622         bp++;
6623         SKIP_WHITE_SPACE (bp);
6624       }
6625       if (*bp) {
6626         error ("invalid format `#line' directive");
6627         return 0;
6628       }
6629     }
6630
6631     hash_bucket =
6632       &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
6633     for (hp = *hash_bucket; hp != NULL; hp = hp->next)
6634       if (hp->length == fname_length &&
6635           bcmp (hp->value.cpval, fname, fname_length) == 0) {
6636         ip->nominal_fname = hp->value.cpval;
6637         break;
6638       }
6639     if (hp == 0) {
6640       /* Didn't find it; cons up a new one.  */
6641       hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
6642       hp->next = *hash_bucket;
6643       *hash_bucket = hp;
6644
6645       hp->length = fname_length;
6646       ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
6647       bcopy (fname, hp->value.cpval, fname_length);
6648     }
6649   } else if (*bp) {
6650     error ("invalid format `#line' directive");
6651     return 0;
6652   }
6653
6654   ip->lineno = new_lineno;
6655   output_line_directive (ip, op, 0, file_change);
6656   check_expand (op, ip->length - (ip->bufp - ip->buf));
6657   return 0;
6658 }
6659
6660 /*
6661  * remove the definition of a symbol from the symbol table.
6662  * according to un*x /lib/cpp, it is not an error to undef
6663  * something that has no definitions, so it isn't one here either.
6664  */
6665
6666 static int
6667 do_undef (buf, limit, op, keyword)
6668      U_CHAR *buf, *limit;
6669      FILE_BUF *op;
6670      struct directive *keyword;
6671 {
6672   int sym_length;
6673   HASHNODE *hp;
6674   U_CHAR *orig_buf = buf;
6675
6676   /* If this is a precompiler run (with -pcp) pass thru #undef directives.  */
6677   if (pcp_outfile && op)
6678     pass_thru_directive (buf, limit, op, keyword);
6679
6680   SKIP_WHITE_SPACE (buf);
6681   sym_length = check_macro_name (buf, "macro");
6682
6683   while ((hp = lookup (buf, sym_length, -1)) != NULL) {
6684     /* If we are generating additional info for debugging (with -g) we
6685        need to pass through all effective #undef directives.  */
6686     if (debug_output && op)
6687       pass_thru_directive (orig_buf, limit, op, keyword);
6688     if (hp->type != T_MACRO)
6689       warning ("undefining `%s'", hp->name);
6690     delete_macro (hp);
6691   }
6692
6693   if (pedantic) {
6694     buf += sym_length;
6695     SKIP_WHITE_SPACE (buf);
6696     if (buf != limit)
6697       pedwarn ("garbage after `#undef' directive");
6698   }
6699   return 0;
6700 }
6701 \f
6702 /*
6703  * Report an error detected by the program we are processing.
6704  * Use the text of the line in the error message.
6705  * (We use error because it prints the filename & line#.)
6706  */
6707
6708 static int
6709 do_error (buf, limit, op, keyword)
6710      U_CHAR *buf, *limit;
6711      FILE_BUF *op;
6712      struct directive *keyword;
6713 {
6714   int length = limit - buf;
6715   U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6716   bcopy ((char *) buf, (char *) copy, length);
6717   copy[length] = 0;
6718   SKIP_WHITE_SPACE (copy);
6719   error ("#error %s", copy);
6720   return 0;
6721 }
6722
6723 /*
6724  * Report a warning detected by the program we are processing.
6725  * Use the text of the line in the warning message, then continue.
6726  * (We use error because it prints the filename & line#.)
6727  */
6728
6729 static int
6730 do_warning (buf, limit, op, keyword)
6731      U_CHAR *buf, *limit;
6732      FILE_BUF *op;
6733      struct directive *keyword;
6734 {
6735   int length = limit - buf;
6736   U_CHAR *copy = (U_CHAR *) xmalloc (length + 1);
6737   bcopy ((char *) buf, (char *) copy, length);
6738   copy[length] = 0;
6739   SKIP_WHITE_SPACE (copy);
6740   warning ("#warning %s", copy);
6741   return 0;
6742 }
6743
6744 /* Remember the name of the current file being read from so that we can
6745    avoid ever including it again.  */
6746
6747 static void
6748 do_once ()
6749 {
6750   int i;
6751
6752   for (i = indepth; i >= 0; i--)
6753     if (instack[i].inc) {
6754       record_control_macro (instack[i].inc, (U_CHAR *) "");
6755       break;
6756     }
6757 }
6758
6759 /* #ident has already been copied to the output file, so just ignore it.  */
6760
6761 static int
6762 do_ident (buf, limit, op, keyword)
6763      U_CHAR *buf, *limit;
6764      FILE_BUF *op;
6765      struct directive *keyword;
6766 {
6767   FILE_BUF trybuf;
6768   int len;
6769
6770   /* Allow #ident in system headers, since that's not user's fault.  */
6771   if (pedantic && !instack[indepth].system_header_p)
6772     pedwarn ("ANSI C does not allow `#ident'");
6773
6774   trybuf = expand_to_temp_buffer (buf, limit, 0, 0);
6775   buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
6776   bcopy ((char *) trybuf.buf, (char *) buf, trybuf.bufp - trybuf.buf);
6777   limit = buf + (trybuf.bufp - trybuf.buf);
6778   len = (limit - buf);
6779   free (trybuf.buf);
6780
6781   /* Output directive name.  */
6782   check_expand (op, 7);
6783   bcopy ("#ident ", (char *) op->bufp, 7);
6784   op->bufp += 7;
6785
6786   /* Output the expanded argument line.  */
6787   check_expand (op, len);
6788   bcopy ((char *) buf, (char *) op->bufp, len);
6789   op->bufp += len;
6790
6791   return 0;
6792 }
6793
6794 /* #pragma and its argument line have already been copied to the output file.
6795    Just check for some recognized pragmas that need validation here.  */
6796
6797 static int
6798 do_pragma (buf, limit, op, keyword)
6799      U_CHAR *buf, *limit;
6800      FILE_BUF *op;
6801      struct directive *keyword;
6802 {
6803   SKIP_WHITE_SPACE (buf);
6804   if (!strncmp ((char *) buf, "once", 4)) {
6805     /* Allow #pragma once in system headers, since that's not the user's
6806        fault.  */
6807     if (!instack[indepth].system_header_p)
6808       warning ("`#pragma once' is obsolete");
6809     do_once ();
6810   }
6811
6812   if (!strncmp ((char *) buf, "implementation", 14)) {
6813     /* Be quiet about `#pragma implementation' for a file only if it hasn't
6814        been included yet.  */
6815
6816     int h;
6817     U_CHAR *p = buf + 14, *fname;
6818     SKIP_WHITE_SPACE (p);
6819     if (*p == '\n' || *p != '\"')
6820       return 0;
6821
6822     fname = p + 1;
6823     if ((p = (U_CHAR *) index ((char *) fname, '\"')))
6824       *p = '\0';
6825     
6826     for (h = 0; h < INCLUDE_HASHSIZE; h++) {
6827       struct include_file *inc;
6828       for (inc = include_hashtab[h]; inc; inc = inc->next) {
6829         if (!strcmp (base_name (inc->fname), (char *) fname)) {
6830           warning ("`#pragma implementation' for \"%s\" appears after its #include",fname);
6831           return 0;
6832         }
6833       }
6834     }
6835   }
6836   return 0;
6837 }
6838
6839 #if 0
6840 /* This was a fun hack, but #pragma seems to start to be useful.
6841    By failing to recognize it, we pass it through unchanged to cc1.  */
6842
6843 /*
6844  * the behavior of the #pragma directive is implementation defined.
6845  * this implementation defines it as follows.
6846  */
6847
6848 static int
6849 do_pragma ()
6850 {
6851   close (0);
6852   if (open ("/dev/tty", O_RDONLY, 0666) != 0)
6853     goto nope;
6854   close (1);
6855   if (open ("/dev/tty", O_WRONLY, 0666) != 1)
6856     goto nope;
6857   execl ("/usr/games/hack", "#pragma", 0);
6858   execl ("/usr/games/rogue", "#pragma", 0);
6859   execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
6860   execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
6861 nope:
6862   fatal ("You are in a maze of twisty compiler features, all different");
6863 }
6864 #endif
6865
6866 #ifdef SCCS_DIRECTIVE
6867
6868 /* Just ignore #sccs, on systems where we define it at all.  */
6869
6870 static int
6871 do_sccs (buf, limit, op, keyword)
6872      U_CHAR *buf, *limit;
6873      FILE_BUF *op;
6874      struct directive *keyword;
6875 {
6876   if (pedantic)
6877     pedwarn ("ANSI C does not allow `#sccs'");
6878   return 0;
6879 }
6880
6881 #endif /* defined (SCCS_DIRECTIVE) */
6882 \f
6883 /*
6884  * handle #if directive by
6885  *   1) inserting special `defined' keyword into the hash table
6886  *      that gets turned into 0 or 1 by special_symbol (thus,
6887  *      if the luser has a symbol called `defined' already, it won't
6888  *      work inside the #if directive)
6889  *   2) rescan the input into a temporary output buffer
6890  *   3) pass the output buffer to the yacc parser and collect a value
6891  *   4) clean up the mess left from steps 1 and 2.
6892  *   5) call conditional_skip to skip til the next #endif (etc.),
6893  *      or not, depending on the value from step 3.
6894  */
6895
6896 static int
6897 do_if (buf, limit, op, keyword)
6898      U_CHAR *buf, *limit;
6899      FILE_BUF *op;
6900      struct directive *keyword;
6901 {
6902   HOST_WIDE_INT value;
6903   FILE_BUF *ip = &instack[indepth];
6904
6905   value = eval_if_expression (buf, limit - buf);
6906   conditional_skip (ip, value == 0, T_IF, NULL_PTR, op);
6907   return 0;
6908 }
6909
6910 /*
6911  * handle a #elif directive by not changing  if_stack  either.
6912  * see the comment above do_else.
6913  */
6914
6915 static int
6916 do_elif (buf, limit, op, keyword)
6917      U_CHAR *buf, *limit;
6918      FILE_BUF *op;
6919      struct directive *keyword;
6920 {
6921   HOST_WIDE_INT value;
6922   FILE_BUF *ip = &instack[indepth];
6923
6924   if (if_stack == instack[indepth].if_stack) {
6925     error ("`#elif' not within a conditional");
6926     return 0;
6927   } else {
6928     if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
6929       error ("`#elif' after `#else'");
6930       fprintf (stderr, " (matches line %d", if_stack->lineno);
6931       if (if_stack->fname != NULL && ip->fname != NULL &&
6932           strcmp (if_stack->fname, ip->nominal_fname) != 0)
6933         fprintf (stderr, ", file %s", if_stack->fname);
6934       fprintf (stderr, ")\n");
6935     }
6936     if_stack->type = T_ELIF;
6937   }
6938
6939   if (if_stack->if_succeeded)
6940     skip_if_group (ip, 0, op);
6941   else {
6942     value = eval_if_expression (buf, limit - buf);
6943     if (value == 0)
6944       skip_if_group (ip, 0, op);
6945     else {
6946       ++if_stack->if_succeeded; /* continue processing input */
6947       output_line_directive (ip, op, 1, same_file);
6948     }
6949   }
6950   return 0;
6951 }
6952
6953 /*
6954  * evaluate a #if expression in BUF, of length LENGTH,
6955  * then parse the result as a C expression and return the value as an int.
6956  */
6957 static HOST_WIDE_INT
6958 eval_if_expression (buf, length)
6959      U_CHAR *buf;
6960      int length;
6961 {
6962   FILE_BUF temp_obuf;
6963   HASHNODE *save_defined;
6964   HOST_WIDE_INT value;
6965
6966   save_defined = install ((U_CHAR *) "defined", -1, T_SPEC_DEFINED,
6967                           NULL_PTR, -1);
6968   pcp_inside_if = 1;
6969   temp_obuf = expand_to_temp_buffer (buf, buf + length, 0, 1);
6970   pcp_inside_if = 0;
6971   delete_macro (save_defined);  /* clean up special symbol */
6972
6973   value = parse_c_expression ((char *) temp_obuf.buf);
6974
6975   free (temp_obuf.buf);
6976
6977   return value;
6978 }
6979
6980 /*
6981  * routine to handle ifdef/ifndef.  Try to look up the symbol,
6982  * then do or don't skip to the #endif/#else/#elif depending
6983  * on what directive is actually being processed.
6984  */
6985
6986 static int
6987 do_xifdef (buf, limit, op, keyword)
6988      U_CHAR *buf, *limit;
6989      FILE_BUF *op;
6990      struct directive *keyword;
6991 {
6992   int skip;
6993   FILE_BUF *ip = &instack[indepth];
6994   U_CHAR *end; 
6995   int start_of_file = 0;
6996   U_CHAR *control_macro = 0;
6997
6998   /* Detect a #ifndef at start of file (not counting comments).  */
6999   if (ip->fname != 0 && keyword->type == T_IFNDEF) {
7000     U_CHAR *p = ip->buf;
7001     while (p != directive_start) {
7002       U_CHAR c = *p++;
7003       if (is_space[c])
7004         ;
7005       /* Make no special provision for backslash-newline here; this is
7006          slower if backslash-newlines are present, but it's correct,
7007          and it's not worth it to tune for the rare backslash-newline.  */
7008       else if (c == '/'
7009                && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7010         /* Skip this comment.  */
7011         int junk = 0;
7012         U_CHAR *save_bufp = ip->bufp;
7013         ip->bufp = p + 1;
7014         p = skip_to_end_of_comment (ip, &junk, 1);
7015         ip->bufp = save_bufp;
7016       } else {
7017         goto fail;
7018       }
7019     }
7020     /* If we get here, this conditional is the beginning of the file.  */
7021     start_of_file = 1;
7022   fail: ;
7023   }
7024
7025   /* Discard leading and trailing whitespace.  */
7026   SKIP_WHITE_SPACE (buf);
7027   while (limit != buf && is_hor_space[limit[-1]]) limit--;
7028
7029   /* Find the end of the identifier at the beginning.  */
7030   for (end = buf; is_idchar[*end]; end++);
7031
7032   if (end == buf) {
7033     skip = (keyword->type == T_IFDEF);
7034     if (! traditional)
7035       pedwarn (end == limit ? "`#%s' with no argument"
7036                : "`#%s' argument starts with punctuation",
7037                keyword->name);
7038   } else {
7039     HASHNODE *hp;
7040
7041     if (pedantic && buf[0] >= '0' && buf[0] <= '9')
7042       pedwarn ("`#%s' argument starts with a digit", keyword->name);
7043     else if (end != limit && !traditional)
7044       pedwarn ("garbage at end of `#%s' argument", keyword->name);
7045
7046     hp = lookup (buf, end-buf, -1);
7047
7048     if (pcp_outfile) {
7049       /* Output a precondition for this macro.  */
7050       if (hp &&
7051           (hp->type == T_CONST
7052            || (hp->type == T_MACRO && hp->value.defn->predefined)))
7053         fprintf (pcp_outfile, "#define %s\n", hp->name);
7054       else {
7055         U_CHAR *cp = buf;
7056         fprintf (pcp_outfile, "#undef ");
7057         while (is_idchar[*cp]) /* Ick! */
7058           fputc (*cp++, pcp_outfile);
7059         putc ('\n', pcp_outfile);
7060       }
7061     }
7062
7063     skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
7064     if (start_of_file && !skip) {
7065       control_macro = (U_CHAR *) xmalloc (end - buf + 1);
7066       bcopy ((char *) buf, (char *) control_macro, end - buf);
7067       control_macro[end - buf] = 0;
7068     }
7069   }
7070   
7071   conditional_skip (ip, skip, T_IF, control_macro, op);
7072   return 0;
7073 }
7074
7075 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
7076    If this is a #ifndef starting at the beginning of a file,
7077    CONTROL_MACRO is the macro name tested by the #ifndef.
7078    Otherwise, CONTROL_MACRO is 0.  */
7079
7080 static void
7081 conditional_skip (ip, skip, type, control_macro, op)
7082      FILE_BUF *ip;
7083      int skip;
7084      enum node_type type;
7085      U_CHAR *control_macro;
7086      FILE_BUF *op;
7087 {
7088   IF_STACK_FRAME *temp;
7089
7090   temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7091   temp->fname = ip->nominal_fname;
7092   temp->lineno = ip->lineno;
7093   temp->next = if_stack;
7094   temp->control_macro = control_macro;
7095   if_stack = temp;
7096
7097   if_stack->type = type;
7098
7099   if (skip != 0) {
7100     skip_if_group (ip, 0, op);
7101     return;
7102   } else {
7103     ++if_stack->if_succeeded;
7104     output_line_directive (ip, &outbuf, 1, same_file);
7105   }
7106 }
7107
7108 /*
7109  * skip to #endif, #else, or #elif.  adjust line numbers, etc.
7110  * leaves input ptr at the sharp sign found.
7111  * If ANY is nonzero, return at next directive of any sort.
7112  */
7113 static void
7114 skip_if_group (ip, any, op)
7115      FILE_BUF *ip;
7116      int any;
7117      FILE_BUF *op;
7118 {
7119   register U_CHAR *bp = ip->bufp, *cp;
7120   register U_CHAR *endb = ip->buf + ip->length;
7121   struct directive *kt;
7122   IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
7123   U_CHAR *beg_of_line = bp;
7124   register int ident_length;
7125   U_CHAR *ident, *after_ident;
7126   /* Save info about where the group starts.  */
7127   U_CHAR *beg_of_group = bp;
7128   int beg_lineno = ip->lineno;
7129
7130   if (output_conditionals && op != 0) {
7131     char *ptr = "#failed\n";
7132     int len = strlen (ptr);
7133
7134     if (op->bufp > op->buf && op->bufp[-1] != '\n')
7135       {
7136         *op->bufp++ = '\n';
7137         op->lineno++;
7138       }
7139     check_expand (op, len);
7140     bcopy (ptr, (char *) op->bufp, len);
7141     op->bufp += len;
7142     op->lineno++;
7143     output_line_directive (ip, op, 1, 0);
7144   }
7145
7146   while (bp < endb) {
7147     switch (*bp++) {
7148     case '/':                   /* possible comment */
7149       if (*bp == '\\' && bp[1] == '\n')
7150         newline_fix (bp);
7151       if (*bp == '*'
7152           || (cplusplus_comments && *bp == '/')) {
7153         ip->bufp = ++bp;
7154         bp = skip_to_end_of_comment (ip, &ip->lineno, 0);
7155       }
7156       break;
7157     case '\"':
7158     case '\'':
7159       bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno,
7160                                NULL_PTR, NULL_PTR);
7161       break;
7162     case '\\':
7163       /* Char after backslash loses its special meaning.  */
7164       if (bp < endb) {
7165         if (*bp == '\n')
7166           ++ip->lineno;         /* But do update the line-count.  */
7167         bp++;
7168       }
7169       break;
7170     case '\n':
7171       ++ip->lineno;
7172       beg_of_line = bp;
7173       break;
7174     case '%':
7175       if (beg_of_line == 0 || traditional)
7176         break;
7177       ip->bufp = bp - 1;
7178       while (bp[0] == '\\' && bp[1] == '\n')
7179         bp += 2;
7180       if (*bp == ':')
7181         goto sharp_token;
7182       break;
7183     case '#':
7184       /* # keyword: a # must be first nonblank char on the line */
7185       if (beg_of_line == 0)
7186         break;
7187       ip->bufp = bp - 1;
7188     sharp_token:
7189       /* Scan from start of line, skipping whitespace, comments
7190          and backslash-newlines, and see if we reach this #.
7191          If not, this # is not special.  */
7192       bp = beg_of_line;
7193       /* If -traditional, require # to be at beginning of line.  */
7194       if (!traditional) {
7195         while (1) {
7196           if (is_hor_space[*bp])
7197             bp++;
7198           else if (*bp == '\\' && bp[1] == '\n')
7199             bp += 2;
7200           else if (*bp == '/' && bp[1] == '*') {
7201             bp += 2;
7202             while (!(*bp == '*' && bp[1] == '/'))
7203               bp++;
7204             bp += 2;
7205           }
7206           /* There is no point in trying to deal with C++ // comments here,
7207              because if there is one, then this # must be part of the
7208              comment and we would never reach here.  */
7209           else break;
7210         }
7211       }
7212       if (bp != ip->bufp) {
7213         bp = ip->bufp + 1;      /* Reset bp to after the #.  */
7214         break;
7215       }
7216
7217       bp = ip->bufp + 1;        /* Point after the '#' */
7218       if (ip->bufp[0] == '%') {
7219         /* Skip past the ':' again.  */
7220         while (*bp == '\\') {
7221           ip->lineno++;
7222           bp += 2;
7223         }
7224         bp++;
7225       }
7226
7227       /* Skip whitespace and \-newline.  */
7228       while (1) {
7229         if (is_hor_space[*bp])
7230           bp++;
7231         else if (*bp == '\\' && bp[1] == '\n')
7232           bp += 2;
7233         else if (*bp == '/') {
7234           if (bp[1] == '*') {
7235             for (bp += 2; ; bp++) {
7236               if (*bp == '\n')
7237                 ip->lineno++;
7238               else if (*bp == '*') {
7239                 if (bp[-1] == '/' && warn_comments)
7240                   warning ("`/*' within comment");
7241                 if (bp[1] == '/')
7242                   break;
7243               }
7244             }
7245             bp += 2;
7246           } else if (bp[1] == '/' && cplusplus_comments) {
7247             for (bp += 2; ; bp++) {
7248               if (*bp == '\n') {
7249                 if (bp[-1] != '\\')
7250                   break;
7251                 if (warn_comments)
7252                   warning ("multiline `//' comment");
7253                 ip->lineno++;
7254               }
7255             }
7256           } else
7257             break;
7258         } else
7259           break;
7260       }
7261
7262       cp = bp;
7263
7264       /* Now find end of directive name.
7265          If we encounter a backslash-newline, exchange it with any following
7266          symbol-constituents so that we end up with a contiguous name.  */
7267
7268       while (1) {
7269         if (is_idchar[*bp])
7270           bp++;
7271         else {
7272           if (*bp == '\\' && bp[1] == '\n')
7273             name_newline_fix (bp);
7274           if (is_idchar[*bp])
7275             bp++;
7276           else break;
7277         }
7278       }
7279       ident_length = bp - cp;
7280       ident = cp;
7281       after_ident = bp;
7282
7283       /* A line of just `#' becomes blank.  */
7284
7285       if (ident_length == 0 && *after_ident == '\n') {
7286         continue;
7287       }
7288
7289       if (ident_length == 0 || !is_idstart[*ident]) {
7290         U_CHAR *p = ident;
7291         while (is_idchar[*p]) {
7292           if (*p < '0' || *p > '9')
7293             break;
7294           p++;
7295         }
7296         /* Handle # followed by a line number.  */
7297         if (p != ident && !is_idchar[*p]) {
7298           if (pedantic)
7299             pedwarn ("`#' followed by integer");
7300           continue;
7301         }
7302
7303         /* Avoid error for `###' and similar cases unless -pedantic.  */
7304         if (p == ident) {
7305           while (*p == '#' || is_hor_space[*p]) p++;
7306           if (*p == '\n') {
7307             if (pedantic && !lang_asm)
7308               pedwarn ("invalid preprocessing directive");
7309             continue;
7310           }
7311         }
7312
7313         if (!lang_asm && pedantic)
7314           pedwarn ("invalid preprocessing directive name");
7315         continue;
7316       }
7317
7318       for (kt = directive_table; kt->length >= 0; kt++) {
7319         IF_STACK_FRAME *temp;
7320         if (ident_length == kt->length
7321             && bcmp (cp, kt->name, kt->length) == 0) {
7322           /* If we are asked to return on next directive, do so now.  */
7323           if (any)
7324             goto done;
7325
7326           switch (kt->type) {
7327           case T_IF:
7328           case T_IFDEF:
7329           case T_IFNDEF:
7330             temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
7331             temp->next = if_stack;
7332             if_stack = temp;
7333             temp->lineno = ip->lineno;
7334             temp->fname = ip->nominal_fname;
7335             temp->type = kt->type;
7336             break;
7337           case T_ELSE:
7338           case T_ENDIF:
7339             if (pedantic && if_stack != save_if_stack)
7340               validate_else (bp);
7341           case T_ELIF:
7342             if (if_stack == instack[indepth].if_stack) {
7343               error ("`#%s' not within a conditional", kt->name);
7344               break;
7345             }
7346             else if (if_stack == save_if_stack)
7347               goto done;                /* found what we came for */
7348
7349             if (kt->type != T_ENDIF) {
7350               if (if_stack->type == T_ELSE)
7351                 error ("`#else' or `#elif' after `#else'");
7352               if_stack->type = kt->type;
7353               break;
7354             }
7355
7356             temp = if_stack;
7357             if_stack = if_stack->next;
7358             free (temp);
7359             break;
7360
7361            default:
7362             break;
7363           }
7364           break;
7365         }
7366       }
7367       /* Don't let erroneous code go by.  */
7368       if (kt->length < 0 && !lang_asm && pedantic)
7369         pedwarn ("invalid preprocessing directive name");
7370     }
7371   }
7372
7373   ip->bufp = bp;
7374   /* after this returns, rescan will exit because ip->bufp
7375      now points to the end of the buffer.
7376      rescan is responsible for the error message also.  */
7377
7378  done:
7379   if (output_conditionals && op != 0) {
7380     char *ptr = "#endfailed\n";
7381     int len = strlen (ptr);
7382
7383     if (op->bufp > op->buf && op->bufp[-1] != '\n')
7384       {
7385         *op->bufp++ = '\n';
7386         op->lineno++;
7387       }
7388     check_expand (op, beg_of_line - beg_of_group);
7389     bcopy ((char *) beg_of_group, (char *) op->bufp,
7390            beg_of_line - beg_of_group);
7391     op->bufp += beg_of_line - beg_of_group;
7392     op->lineno += ip->lineno - beg_lineno;
7393     check_expand (op, len);
7394     bcopy (ptr, (char *) op->bufp, len);
7395     op->bufp += len;
7396     op->lineno++;
7397   }
7398 }
7399
7400 /*
7401  * handle a #else directive.  Do this by just continuing processing
7402  * without changing  if_stack ;  this is so that the error message
7403  * for missing #endif's etc. will point to the original #if.  It
7404  * is possible that something different would be better.
7405  */
7406
7407 static int
7408 do_else (buf, limit, op, keyword)
7409      U_CHAR *buf, *limit;
7410      FILE_BUF *op;
7411      struct directive *keyword;
7412 {
7413   FILE_BUF *ip = &instack[indepth];
7414
7415   if (pedantic) {
7416     SKIP_WHITE_SPACE (buf);
7417     if (buf != limit)
7418       pedwarn ("text following `#else' violates ANSI standard");
7419   }
7420
7421   if (if_stack == instack[indepth].if_stack) {
7422     error ("`#else' not within a conditional");
7423     return 0;
7424   } else {
7425     /* #ifndef can't have its special treatment for containing the whole file
7426        if it has a #else clause.  */
7427     if_stack->control_macro = 0;
7428
7429     if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
7430       error ("`#else' after `#else'");
7431       fprintf (stderr, " (matches line %d", if_stack->lineno);
7432       if (strcmp (if_stack->fname, ip->nominal_fname) != 0)
7433         fprintf (stderr, ", file %s", if_stack->fname);
7434       fprintf (stderr, ")\n");
7435     }
7436     if_stack->type = T_ELSE;
7437   }
7438
7439   if (if_stack->if_succeeded)
7440     skip_if_group (ip, 0, op);
7441   else {
7442     ++if_stack->if_succeeded;   /* continue processing input */
7443     output_line_directive (ip, op, 1, same_file);
7444   }
7445   return 0;
7446 }
7447
7448 /*
7449  * unstack after #endif directive
7450  */
7451
7452 static int
7453 do_endif (buf, limit, op, keyword)
7454      U_CHAR *buf, *limit;
7455      FILE_BUF *op;
7456      struct directive *keyword;
7457 {
7458   if (pedantic) {
7459     SKIP_WHITE_SPACE (buf);
7460     if (buf != limit)
7461       pedwarn ("text following `#endif' violates ANSI standard");
7462   }
7463
7464   if (if_stack == instack[indepth].if_stack)
7465     error ("unbalanced `#endif'");
7466   else {
7467     IF_STACK_FRAME *temp = if_stack;
7468     if_stack = if_stack->next;
7469     if (temp->control_macro != 0) {
7470       /* This #endif matched a #ifndef at the start of the file.
7471          See if it is at the end of the file.  */
7472       FILE_BUF *ip = &instack[indepth];
7473       U_CHAR *p = ip->bufp;
7474       U_CHAR *ep = ip->buf + ip->length;
7475
7476       while (p != ep) {
7477         U_CHAR c = *p++;
7478         if (!is_space[c]) {
7479           if (c == '/'
7480               && (*p == '*' || (cplusplus_comments && *p == '/'))) {
7481             /* Skip this comment.  */
7482             int junk = 0;
7483             U_CHAR *save_bufp = ip->bufp;
7484             ip->bufp = p + 1;
7485             p = skip_to_end_of_comment (ip, &junk, 1);
7486             ip->bufp = save_bufp;
7487           } else
7488             goto fail;
7489         }
7490       }
7491       /* If we get here, this #endif ends a #ifndef
7492          that contains all of the file (aside from whitespace).
7493          Arrange not to include the file again
7494          if the macro that was tested is defined.
7495
7496          Do not do this for the top-level file in a -include or any
7497          file in a -imacros.  */
7498       if (indepth != 0
7499           && ! (indepth == 1 && no_record_file)
7500           && ! (no_record_file && no_output))
7501         record_control_macro (ip->inc, temp->control_macro);
7502     fail: ;
7503     }
7504     free (temp);
7505     output_line_directive (&instack[indepth], op, 1, same_file);
7506   }
7507   return 0;
7508 }
7509
7510 /* When an #else or #endif is found while skipping failed conditional,
7511    if -pedantic was specified, this is called to warn about text after
7512    the directive name.  P points to the first char after the directive name.  */
7513
7514 static void
7515 validate_else (p)
7516      register U_CHAR *p;
7517 {
7518   /* Advance P over whitespace and comments.  */
7519   while (1) {
7520     if (*p == '\\' && p[1] == '\n')
7521       p += 2;
7522     if (is_hor_space[*p])
7523       p++;
7524     else if (*p == '/') {
7525       if (p[1] == '\\' && p[2] == '\n')
7526         newline_fix (p + 1);
7527       if (p[1] == '*') {
7528         p += 2;
7529         /* Don't bother warning about unterminated comments
7530            since that will happen later.  Just be sure to exit.  */
7531         while (*p) {
7532           if (p[1] == '\\' && p[2] == '\n')
7533             newline_fix (p + 1);
7534           if (*p == '*' && p[1] == '/') {
7535             p += 2;
7536             break;
7537           }
7538           p++;
7539         }
7540       }
7541       else if (cplusplus_comments && p[1] == '/') {
7542         p += 2;
7543         while (*p && (*p != '\n' || p[-1] == '\\'))
7544           p++;
7545       }
7546     } else break;
7547   }
7548   if (*p && *p != '\n')
7549     pedwarn ("text following `#else' or `#endif' violates ANSI standard");
7550 }
7551 \f
7552 /* Skip a comment, assuming the input ptr immediately follows the
7553    initial slash-star.  Bump *LINE_COUNTER for each newline.
7554    (The canonical line counter is &ip->lineno.)
7555    Don't use this routine (or the next one) if bumping the line
7556    counter is not sufficient to deal with newlines in the string.
7557
7558    If NOWARN is nonzero, don't warn about slash-star inside a comment.
7559    This feature is useful when processing a comment that is going to be
7560    processed or was processed at another point in the preprocessor,
7561    to avoid a duplicate warning.  Likewise for unterminated comment errors.  */
7562
7563 static U_CHAR *
7564 skip_to_end_of_comment (ip, line_counter, nowarn)
7565      register FILE_BUF *ip;
7566      int *line_counter;         /* place to remember newlines, or NULL */
7567      int nowarn;
7568 {
7569   register U_CHAR *limit = ip->buf + ip->length;
7570   register U_CHAR *bp = ip->bufp;
7571   FILE_BUF *op = put_out_comments && !line_counter ? &outbuf : (FILE_BUF *) 0;
7572   int start_line = line_counter ? *line_counter : 0;
7573
7574         /* JF this line_counter stuff is a crock to make sure the
7575            comment is only put out once, no matter how many times
7576            the comment is skipped.  It almost works */
7577   if (op) {
7578     *op->bufp++ = '/';
7579     *op->bufp++ = bp[-1];
7580   }
7581   if (cplusplus_comments && bp[-1] == '/') {
7582     for (; bp < limit; bp++) {
7583       if (op)
7584         *op->bufp++ = *bp;
7585       if (*bp == '\n') {
7586         if (bp[-1] != '\\')
7587           break;
7588         if (!nowarn && warn_comments)
7589           warning ("multiline `//' comment");
7590         if (line_counter)
7591           ++*line_counter;
7592         if (op)
7593           ++op->lineno;
7594       }
7595     }
7596     ip->bufp = bp;
7597     return bp;
7598   }
7599   while (bp < limit) {
7600     if (op)
7601       *op->bufp++ = *bp;
7602     switch (*bp++) {
7603     case '\n':
7604       /* If this is the end of the file, we have an unterminated comment.
7605          Don't swallow the newline.  We are guaranteed that there will be a
7606          trailing newline and various pieces assume it's there.  */
7607       if (bp == limit)
7608         {
7609           --bp;
7610           --limit;
7611           break;
7612         }
7613       if (line_counter != NULL)
7614         ++*line_counter;
7615       if (op)
7616         ++op->lineno;
7617       break;
7618     case '*':
7619       if (bp[-2] == '/' && !nowarn && warn_comments)
7620         warning ("`/*' within comment");
7621       if (*bp == '\\' && bp[1] == '\n')
7622         newline_fix (bp);
7623       if (*bp == '/') {
7624         if (op)
7625           *op->bufp++ = '/';
7626         ip->bufp = ++bp;
7627         return bp;
7628       }
7629       break;
7630     }
7631   }
7632
7633   if (!nowarn)
7634     error_with_line (line_for_error (start_line), "unterminated comment");
7635   ip->bufp = bp;
7636   return bp;
7637 }
7638
7639 /*
7640  * Skip over a quoted string.  BP points to the opening quote.
7641  * Returns a pointer after the closing quote.  Don't go past LIMIT.
7642  * START_LINE is the line number of the starting point (but it need
7643  * not be valid if the starting point is inside a macro expansion).
7644  *
7645  * The input stack state is not changed.
7646  *
7647  * If COUNT_NEWLINES is nonzero, it points to an int to increment
7648  * for each newline passed.
7649  *
7650  * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
7651  * if we pass a backslash-newline.
7652  *
7653  * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
7654  */
7655 static U_CHAR *
7656 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
7657      register U_CHAR *bp;
7658      register U_CHAR *limit;
7659      int start_line;
7660      int *count_newlines;
7661      int *backslash_newlines_p;
7662      int *eofp;
7663 {
7664   register U_CHAR c, match;
7665
7666   match = *bp++;
7667   while (1) {
7668     if (bp >= limit) {
7669       error_with_line (line_for_error (start_line),
7670                        "unterminated string or character constant");
7671       error_with_line (multiline_string_line,
7672                        "possible real start of unterminated constant");
7673       multiline_string_line = 0;
7674       if (eofp)
7675         *eofp = 1;
7676       break;
7677     }
7678     c = *bp++;
7679     if (c == '\\') {
7680       while (*bp == '\\' && bp[1] == '\n') {
7681         if (backslash_newlines_p)
7682           *backslash_newlines_p = 1;
7683         if (count_newlines)
7684           ++*count_newlines;
7685         bp += 2;
7686       }
7687       if (*bp == '\n' && count_newlines) {
7688         if (backslash_newlines_p)
7689           *backslash_newlines_p = 1;
7690         ++*count_newlines;
7691       }
7692       bp++;
7693     } else if (c == '\n') {
7694       if (traditional) {
7695         /* Unterminated strings and character constants are 'valid'.  */
7696         bp--;   /* Don't consume the newline. */
7697         if (eofp)
7698           *eofp = 1;
7699         break;
7700       }
7701       if (pedantic || match == '\'') {
7702         error_with_line (line_for_error (start_line),
7703                          "unterminated string or character constant");
7704         bp--;
7705         if (eofp)
7706           *eofp = 1;
7707         break;
7708       }
7709       /* If not traditional, then allow newlines inside strings.  */
7710       if (count_newlines)
7711         ++*count_newlines;
7712       if (multiline_string_line == 0)
7713         multiline_string_line = start_line;
7714     } else if (c == match)
7715       break;
7716   }
7717   return bp;
7718 }
7719
7720 /* Place into DST a quoted string representing the string SRC.
7721    Return the address of DST's terminating null.  */
7722 static char *
7723 quote_string (dst, src)
7724      char *dst, *src;
7725 {
7726   U_CHAR c;
7727
7728   *dst++ = '\"';
7729   for (;;)
7730     switch ((c = *src++))
7731       {
7732       default:
7733         if (isprint (c))
7734           *dst++ = c;
7735         else
7736           {
7737             sprintf (dst, "\\%03o", c);
7738             dst += 4;
7739           }
7740         break;
7741
7742       case '\"':
7743       case '\\':
7744         *dst++ = '\\';
7745         *dst++ = c;
7746         break;
7747       
7748       case '\0':
7749         *dst++ = '\"';
7750         *dst = '\0';
7751         return dst;
7752       }
7753 }
7754
7755 /* Skip across a group of balanced parens, starting from IP->bufp.
7756    IP->bufp is updated.  Use this with IP->bufp pointing at an open-paren.
7757
7758    This does not handle newlines, because it's used for the arg of #if,
7759    where there aren't any newlines.  Also, backslash-newline can't appear.  */
7760
7761 static U_CHAR *
7762 skip_paren_group (ip)
7763      register FILE_BUF *ip;
7764 {
7765   U_CHAR *limit = ip->buf + ip->length;
7766   U_CHAR *p = ip->bufp;
7767   int depth = 0;
7768   int lines_dummy = 0;
7769
7770   while (p != limit) {
7771     int c = *p++;
7772     switch (c) {
7773     case '(':
7774       depth++;
7775       break;
7776
7777     case ')':
7778       depth--;
7779       if (depth == 0)
7780         return ip->bufp = p;
7781       break;
7782
7783     case '/':
7784       if (*p == '*') {
7785         ip->bufp = p;
7786         p = skip_to_end_of_comment (ip, &lines_dummy, 0);
7787         p = ip->bufp;
7788       }
7789
7790     case '"':
7791     case '\'':
7792       {
7793         int eofp = 0;
7794         p = skip_quoted_string (p - 1, limit, 0, NULL_PTR, NULL_PTR, &eofp);
7795         if (eofp)
7796           return ip->bufp = p;
7797       }
7798       break;
7799     }
7800   }
7801
7802   ip->bufp = p;
7803   return p;
7804 }
7805 \f
7806 /*
7807  * write out a #line directive, for instance, after an #include file.
7808  * If CONDITIONAL is nonzero, we can omit the #line if it would
7809  * appear to be a no-op, and we can output a few newlines instead
7810  * if we want to increase the line number by a small amount.
7811  * FILE_CHANGE says whether we are entering a file, leaving, or neither.
7812  */
7813
7814 static void
7815 output_line_directive (ip, op, conditional, file_change)
7816      FILE_BUF *ip, *op;
7817      int conditional;
7818      enum file_change_code file_change;
7819 {
7820   int len;
7821   char *line_directive_buf, *line_end;
7822
7823   if (no_line_directives
7824       || ip->fname == NULL
7825       || no_output) {
7826     op->lineno = ip->lineno;
7827     return;
7828   }
7829
7830   if (conditional) {
7831     if (ip->lineno == op->lineno)
7832       return;
7833
7834     /* If the inherited line number is a little too small,
7835        output some newlines instead of a #line directive.  */
7836     if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
7837       check_expand (op, 10);
7838       while (ip->lineno > op->lineno) {
7839         *op->bufp++ = '\n';
7840         op->lineno++;
7841       }
7842       return;
7843     }
7844   }
7845
7846   /* Don't output a line number of 0 if we can help it.  */
7847   if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
7848       && *ip->bufp == '\n') {
7849     ip->lineno++;
7850     ip->bufp++;
7851   }
7852
7853   line_directive_buf = (char *) alloca (4 * strlen (ip->nominal_fname) + 100);
7854   sprintf (line_directive_buf, "# %d ", ip->lineno);
7855   line_end = quote_string (line_directive_buf + strlen (line_directive_buf),
7856                            ip->nominal_fname);
7857   if (file_change != same_file) {
7858     *line_end++ = ' ';
7859     *line_end++ = file_change == enter_file ? '1' : '2';
7860   }
7861   /* Tell cc1 if following text comes from a system header file.  */
7862   if (ip->system_header_p) {
7863     *line_end++ = ' ';
7864     *line_end++ = '3';
7865   }
7866 #ifndef NO_IMPLICIT_EXTERN_C
7867   /* Tell cc1plus if following text should be treated as C.  */
7868   if (ip->system_header_p == 2 && cplusplus) {
7869     *line_end++ = ' ';
7870     *line_end++ = '4';
7871   }
7872 #endif
7873   *line_end++ = '\n';
7874   len = line_end - line_directive_buf;
7875   check_expand (op, len + 1);
7876   if (op->bufp > op->buf && op->bufp[-1] != '\n')
7877     *op->bufp++ = '\n';
7878   bcopy ((char *) line_directive_buf, (char *) op->bufp, len);
7879   op->bufp += len;
7880   op->lineno = ip->lineno;
7881 }
7882 \f
7883 /* This structure represents one parsed argument in a macro call.
7884    `raw' points to the argument text as written (`raw_length' is its length).
7885    `expanded' points to the argument's macro-expansion
7886    (its length is `expand_length').
7887    `stringified_length' is the length the argument would have
7888    if stringified.
7889    `use_count' is the number of times this macro arg is substituted
7890    into the macro.  If the actual use count exceeds 10, 
7891    the value stored is 10.
7892    `free1' and `free2', if nonzero, point to blocks to be freed
7893    when the macro argument data is no longer needed.  */
7894
7895 struct argdata {
7896   U_CHAR *raw, *expanded;
7897   int raw_length, expand_length;
7898   int stringified_length;
7899   U_CHAR *free1, *free2;
7900   char newlines;
7901   char use_count;
7902 };
7903
7904 /* Expand a macro call.
7905    HP points to the symbol that is the macro being called.
7906    Put the result of expansion onto the input stack
7907    so that subsequent input by our caller will use it.
7908
7909    If macro wants arguments, caller has already verified that
7910    an argument list follows; arguments come from the input stack.  */
7911
7912 static void
7913 macroexpand (hp, op)
7914      HASHNODE *hp;
7915      FILE_BUF *op;
7916 {
7917   int nargs;
7918   DEFINITION *defn = hp->value.defn;
7919   register U_CHAR *xbuf;
7920   int xbuf_len;
7921   int start_line = instack[indepth].lineno;
7922   int rest_args, rest_zero;
7923
7924   CHECK_DEPTH (return;);
7925
7926   /* it might not actually be a macro.  */
7927   if (hp->type != T_MACRO) {
7928     special_symbol (hp, op);
7929     return;
7930   }
7931
7932   /* This macro is being used inside a #if, which means it must be */
7933   /* recorded as a precondition.  */
7934   if (pcp_inside_if && pcp_outfile && defn->predefined)
7935     dump_single_macro (hp, pcp_outfile);
7936   
7937   nargs = defn->nargs;
7938
7939   if (nargs >= 0) {
7940     register int i;
7941     struct argdata *args;
7942     char *parse_error = 0;
7943
7944     args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
7945
7946     for (i = 0; i < nargs; i++) {
7947       args[i].raw = (U_CHAR *) "";
7948       args[i].expanded = 0;
7949       args[i].raw_length = args[i].expand_length
7950         = args[i].stringified_length = 0;
7951       args[i].free1 = args[i].free2 = 0;
7952       args[i].use_count = 0;
7953     }
7954
7955     /* Parse all the macro args that are supplied.  I counts them.
7956        The first NARGS args are stored in ARGS.
7957        The rest are discarded.
7958        If rest_args is set then we assume macarg absorbed the rest of the args.
7959        */
7960     i = 0;
7961     rest_args = 0;
7962     do {
7963       /* Discard the open-parenthesis or comma before the next arg.  */
7964       ++instack[indepth].bufp;
7965       if (rest_args)
7966         continue;
7967       if (i < nargs || (nargs == 0 && i == 0)) {
7968         /* if we are working on last arg which absorbs rest of args... */
7969         if (i == nargs - 1 && defn->rest_args)
7970           rest_args = 1;
7971         parse_error = macarg (&args[i], rest_args);
7972       }
7973       else
7974         parse_error = macarg (NULL_PTR, 0);
7975       if (parse_error) {
7976         error_with_line (line_for_error (start_line), parse_error);
7977         break;
7978       }
7979       i++;
7980     } while (*instack[indepth].bufp != ')');
7981
7982     /* If we got one arg but it was just whitespace, call that 0 args.  */
7983     if (i == 1) {
7984       register U_CHAR *bp = args[0].raw;
7985       register U_CHAR *lim = bp + args[0].raw_length;
7986       /* cpp.texi says for foo ( ) we provide one argument.
7987          However, if foo wants just 0 arguments, treat this as 0.  */
7988       if (nargs == 0)
7989         while (bp != lim && is_space[*bp]) bp++;
7990       if (bp == lim)
7991         i = 0;
7992     }
7993
7994     /* Don't output an error message if we have already output one for
7995        a parse error above.  */
7996     rest_zero = 0;
7997     if (nargs == 0 && i > 0) {
7998       if (! parse_error)
7999         error ("arguments given to macro `%s'", hp->name);
8000     } else if (i < nargs) {
8001       /* traditional C allows foo() if foo wants one argument.  */
8002       if (nargs == 1 && i == 0 && traditional)
8003         ;
8004       /* the rest args token is allowed to absorb 0 tokens */
8005       else if (i == nargs - 1 && defn->rest_args)
8006         rest_zero = 1;
8007       else if (parse_error)
8008         ;
8009       else if (i == 0)
8010         error ("macro `%s' used without args", hp->name);
8011       else if (i == 1)
8012         error ("macro `%s' used with just one arg", hp->name);
8013       else
8014         error ("macro `%s' used with only %d args", hp->name, i);
8015     } else if (i > nargs) {
8016       if (! parse_error)
8017         error ("macro `%s' used with too many (%d) args", hp->name, i);
8018     }
8019
8020     /* Swallow the closeparen.  */
8021     ++instack[indepth].bufp;
8022
8023     /* If macro wants zero args, we parsed the arglist for checking only.
8024        Read directly from the macro definition.  */
8025     if (nargs == 0) {
8026       xbuf = defn->expansion;
8027       xbuf_len = defn->length;
8028     } else {
8029       register U_CHAR *exp = defn->expansion;
8030       register int offset;      /* offset in expansion,
8031                                    copied a piece at a time */
8032       register int totlen;      /* total amount of exp buffer filled so far */
8033
8034       register struct reflist *ap, *last_ap;
8035
8036       /* Macro really takes args.  Compute the expansion of this call.  */
8037
8038       /* Compute length in characters of the macro's expansion.
8039          Also count number of times each arg is used.  */
8040       xbuf_len = defn->length;
8041       for (ap = defn->pattern; ap != NULL; ap = ap->next) {
8042         if (ap->stringify)
8043           xbuf_len += args[ap->argno].stringified_length;
8044         else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional)
8045           /* Add 4 for two newline-space markers to prevent
8046              token concatenation.  */
8047           xbuf_len += args[ap->argno].raw_length + 4;
8048         else {
8049           /* We have an ordinary (expanded) occurrence of the arg.
8050              So compute its expansion, if we have not already.  */
8051           if (args[ap->argno].expanded == 0) {
8052             FILE_BUF obuf;
8053             obuf = expand_to_temp_buffer (args[ap->argno].raw,
8054                                           args[ap->argno].raw + args[ap->argno].raw_length,
8055                                           1, 0);
8056
8057             args[ap->argno].expanded = obuf.buf;
8058             args[ap->argno].expand_length = obuf.length;
8059             args[ap->argno].free2 = obuf.buf;
8060           }
8061
8062           /* Add 4 for two newline-space markers to prevent
8063              token concatenation.  */
8064           xbuf_len += args[ap->argno].expand_length + 4;
8065         }
8066         if (args[ap->argno].use_count < 10)
8067           args[ap->argno].use_count++;
8068       }
8069
8070       xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
8071
8072       /* Generate in XBUF the complete expansion
8073          with arguments substituted in.
8074          TOTLEN is the total size generated so far.
8075          OFFSET is the index in the definition
8076          of where we are copying from.  */
8077       offset = totlen = 0;
8078       for (last_ap = NULL, ap = defn->pattern; ap != NULL;
8079            last_ap = ap, ap = ap->next) {
8080         register struct argdata *arg = &args[ap->argno];
8081         int count_before = totlen;
8082
8083         /* Add chars to XBUF.  */
8084         for (i = 0; i < ap->nchars; i++, offset++)
8085           xbuf[totlen++] = exp[offset];
8086
8087         /* If followed by an empty rest arg with concatenation,
8088            delete the last run of nonwhite chars.  */
8089         if (rest_zero && totlen > count_before
8090             && ((ap->rest_args && ap->raw_before != 0)
8091                 || (last_ap != NULL && last_ap->rest_args
8092                     && last_ap->raw_after != 0))) {
8093           /* Delete final whitespace.  */
8094           while (totlen > count_before && is_space[xbuf[totlen - 1]]) {
8095             totlen--;
8096           }
8097
8098           /* Delete the nonwhites before them.  */
8099           while (totlen > count_before && ! is_space[xbuf[totlen - 1]]) {
8100             totlen--;
8101           }
8102         }
8103
8104         if (ap->stringify != 0) {
8105           int arglen = arg->raw_length;
8106           int escaped = 0;
8107           int in_string = 0;
8108           int c;
8109           i = 0;
8110           while (i < arglen
8111                  && (c = arg->raw[i], is_space[c]))
8112             i++;
8113           while (i < arglen
8114                  && (c = arg->raw[arglen - 1], is_space[c]))
8115             arglen--;
8116           if (!traditional)
8117             xbuf[totlen++] = '\"'; /* insert beginning quote */
8118           for (; i < arglen; i++) {
8119             c = arg->raw[i];
8120
8121             /* Special markers Newline Space
8122                generate nothing for a stringified argument.  */
8123             if (c == '\n' && arg->raw[i+1] != '\n') {
8124               i++;
8125               continue;
8126             }
8127
8128             /* Internal sequences of whitespace are replaced by one space
8129                except within an string or char token.  */
8130             if (! in_string
8131                 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space[c])) {
8132               while (1) {
8133                 /* Note that Newline Space does occur within whitespace
8134                    sequences; consider it part of the sequence.  */
8135                 if (c == '\n' && is_space[arg->raw[i+1]])
8136                   i += 2;
8137                 else if (c != '\n' && is_space[c])
8138                   i++;
8139                 else break;
8140                 c = arg->raw[i];
8141               }
8142               i--;
8143               c = ' ';
8144             }
8145
8146             if (escaped)
8147               escaped = 0;
8148             else {
8149               if (c == '\\')
8150                 escaped = 1;
8151               if (in_string) {
8152                 if (c == in_string)
8153                   in_string = 0;
8154               } else if (c == '\"' || c == '\'')
8155                 in_string = c;
8156             }
8157
8158             /* Escape these chars */
8159             if (c == '\"' || (in_string && c == '\\'))
8160               xbuf[totlen++] = '\\';
8161             if (isprint (c))
8162               xbuf[totlen++] = c;
8163             else {
8164               sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
8165               totlen += 4;
8166             }
8167           }
8168           if (!traditional)
8169             xbuf[totlen++] = '\"'; /* insert ending quote */
8170         } else if (ap->raw_before != 0 || ap->raw_after != 0 || traditional) {
8171           U_CHAR *p1 = arg->raw;
8172           U_CHAR *l1 = p1 + arg->raw_length;
8173           if (ap->raw_before != 0) {
8174             while (p1 != l1 && is_space[*p1]) p1++;
8175             while (p1 != l1 && is_idchar[*p1])
8176               xbuf[totlen++] = *p1++;
8177             /* Delete any no-reexpansion marker that follows
8178                an identifier at the beginning of the argument
8179                if the argument is concatenated with what precedes it.  */
8180             if (p1[0] == '\n' && p1[1] == '-')
8181               p1 += 2;
8182           } else if (!traditional) {
8183           /* Ordinary expanded use of the argument.
8184              Put in newline-space markers to prevent token pasting.  */
8185             xbuf[totlen++] = '\n';
8186             xbuf[totlen++] = ' ';
8187           }
8188           if (ap->raw_after != 0) {
8189             /* Arg is concatenated after: delete trailing whitespace,
8190                whitespace markers, and no-reexpansion markers.  */
8191             while (p1 != l1) {
8192               if (is_space[l1[-1]]) l1--;
8193               else if (l1[-1] == '-') {
8194                 U_CHAR *p2 = l1 - 1;
8195                 /* If a `-' is preceded by an odd number of newlines then it
8196                    and the last newline are a no-reexpansion marker.  */
8197                 while (p2 != p1 && p2[-1] == '\n') p2--;
8198                 if ((l1 - 1 - p2) & 1) {
8199                   l1 -= 2;
8200                 }
8201                 else break;
8202               }
8203               else break;
8204             }
8205           }
8206
8207           bcopy ((char *) p1, (char *) (xbuf + totlen), l1 - p1);
8208           totlen += l1 - p1;
8209           if (!traditional && ap->raw_after == 0) {
8210             /* Ordinary expanded use of the argument.
8211                Put in newline-space markers to prevent token pasting.  */
8212             xbuf[totlen++] = '\n';
8213             xbuf[totlen++] = ' ';
8214           }
8215         } else {
8216           /* Ordinary expanded use of the argument.
8217              Put in newline-space markers to prevent token pasting.  */
8218           if (!traditional) {
8219             xbuf[totlen++] = '\n';
8220             xbuf[totlen++] = ' ';
8221           }
8222           bcopy ((char *) arg->expanded, (char *) (xbuf + totlen),
8223                  arg->expand_length);
8224           totlen += arg->expand_length;
8225           if (!traditional) {
8226             xbuf[totlen++] = '\n';
8227             xbuf[totlen++] = ' ';
8228           }
8229           /* If a macro argument with newlines is used multiple times,
8230              then only expand the newlines once.  This avoids creating output
8231              lines which don't correspond to any input line, which confuses
8232              gdb and gcov.  */
8233           if (arg->use_count > 1 && arg->newlines > 0) {
8234             /* Don't bother doing change_newlines for subsequent
8235                uses of arg.  */
8236             arg->use_count = 1;
8237             arg->expand_length
8238               = change_newlines (arg->expanded, arg->expand_length);
8239           }
8240         }
8241
8242         if (totlen > xbuf_len)
8243           abort ();
8244       }
8245
8246       /* if there is anything left of the definition
8247          after handling the arg list, copy that in too. */
8248
8249       for (i = offset; i < defn->length; i++) {
8250         /* if we've reached the end of the macro */
8251         if (exp[i] == ')')
8252           rest_zero = 0;
8253         if (! (rest_zero && last_ap != NULL && last_ap->rest_args
8254                && last_ap->raw_after != 0))
8255           xbuf[totlen++] = exp[i];
8256       }
8257
8258       xbuf[totlen] = 0;
8259       xbuf_len = totlen;
8260
8261       for (i = 0; i < nargs; i++) {
8262         if (args[i].free1 != 0)
8263           free (args[i].free1);
8264         if (args[i].free2 != 0)
8265           free (args[i].free2);
8266       }
8267     }
8268   } else {
8269     xbuf = defn->expansion;
8270     xbuf_len = defn->length;
8271   }
8272
8273   /* Now put the expansion on the input stack
8274      so our caller will commence reading from it.  */
8275   {
8276     register FILE_BUF *ip2;
8277
8278     ip2 = &instack[++indepth];
8279
8280     ip2->fname = 0;
8281     ip2->nominal_fname = 0;
8282     ip2->inc = 0;
8283     /* This may not be exactly correct, but will give much better error
8284        messages for nested macro calls than using a line number of zero.  */
8285     ip2->lineno = start_line;
8286     ip2->buf = xbuf;
8287     ip2->length = xbuf_len;
8288     ip2->bufp = xbuf;
8289     ip2->free_ptr = (nargs > 0) ? xbuf : 0;
8290     ip2->macro = hp;
8291     ip2->if_stack = if_stack;
8292     ip2->system_header_p = 0;
8293
8294     /* Recursive macro use sometimes works traditionally.
8295        #define foo(x,y) bar (x (y,0), y)
8296        foo (foo, baz)  */
8297
8298     if (!traditional)
8299       hp->type = T_DISABLED;
8300   }
8301 }
8302 \f
8303 /*
8304  * Parse a macro argument and store the info on it into *ARGPTR.
8305  * REST_ARGS is passed to macarg1 to make it absorb the rest of the args.
8306  * Return nonzero to indicate a syntax error.
8307  */
8308
8309 static char *
8310 macarg (argptr, rest_args)
8311      register struct argdata *argptr;
8312      int rest_args;
8313 {
8314   FILE_BUF *ip = &instack[indepth];
8315   int paren = 0;
8316   int newlines = 0;
8317   int comments = 0;
8318   char *result = 0;
8319
8320   /* Try to parse as much of the argument as exists at this
8321      input stack level.  */
8322   U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
8323                         &paren, &newlines, &comments, rest_args);
8324
8325   /* If we find the end of the argument at this level,
8326      set up *ARGPTR to point at it in the input stack.  */
8327   if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
8328       && bp != ip->buf + ip->length) {
8329     if (argptr != 0) {
8330       argptr->raw = ip->bufp;
8331       argptr->raw_length = bp - ip->bufp;
8332       argptr->newlines = newlines;
8333     }
8334     ip->bufp = bp;
8335   } else {
8336     /* This input stack level ends before the macro argument does.
8337        We must pop levels and keep parsing.
8338        Therefore, we must allocate a temporary buffer and copy
8339        the macro argument into it.  */
8340     int bufsize = bp - ip->bufp;
8341     int extra = newlines;
8342     U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
8343     int final_start = 0;
8344
8345     bcopy ((char *) ip->bufp, (char *) buffer, bufsize);
8346     ip->bufp = bp;
8347     ip->lineno += newlines;
8348
8349     while (bp == ip->buf + ip->length) {
8350       if (instack[indepth].macro == 0) {
8351         result = "unterminated macro call";
8352         break;
8353       }
8354       ip->macro->type = T_MACRO;
8355       if (ip->free_ptr)
8356         free (ip->free_ptr);
8357       ip = &instack[--indepth];
8358       newlines = 0;
8359       comments = 0;
8360       bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
8361                     &newlines, &comments, rest_args);
8362       final_start = bufsize;
8363       bufsize += bp - ip->bufp;
8364       extra += newlines;
8365       buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
8366       bcopy ((char *) ip->bufp, (char *) (buffer + bufsize - (bp - ip->bufp)),
8367              bp - ip->bufp);
8368       ip->bufp = bp;
8369       ip->lineno += newlines;
8370     }
8371
8372     /* Now, if arg is actually wanted, record its raw form,
8373        discarding comments and duplicating newlines in whatever
8374        part of it did not come from a macro expansion.
8375        EXTRA space has been preallocated for duplicating the newlines.
8376        FINAL_START is the index of the start of that part.  */
8377     if (argptr != 0) {
8378       argptr->raw = buffer;
8379       argptr->raw_length = bufsize;
8380       argptr->free1 = buffer;
8381       argptr->newlines = newlines;
8382       if ((newlines || comments) && ip->fname != 0)
8383         argptr->raw_length
8384           = final_start +
8385             discard_comments (argptr->raw + final_start,
8386                               argptr->raw_length - final_start,
8387                               newlines);
8388       argptr->raw[argptr->raw_length] = 0;
8389       if (argptr->raw_length > bufsize + extra)
8390         abort ();
8391     }
8392   }
8393
8394   /* If we are not discarding this argument,
8395      macroexpand it and compute its length as stringified.
8396      All this info goes into *ARGPTR.  */
8397
8398   if (argptr != 0) {
8399     register U_CHAR *buf, *lim;
8400     register int totlen;
8401
8402     buf = argptr->raw;
8403     lim = buf + argptr->raw_length;
8404
8405     while (buf != lim && is_space[*buf])
8406       buf++;
8407     while (buf != lim && is_space[lim[-1]])
8408       lim--;
8409     totlen = traditional ? 0 : 2;       /* Count opening and closing quote.  */
8410     while (buf != lim) {
8411       register U_CHAR c = *buf++;
8412       totlen++;
8413       /* Internal sequences of whitespace are replaced by one space
8414          in most cases, but not always.  So count all the whitespace
8415          in case we need to keep it all.  */
8416 #if 0
8417       if (is_space[c])
8418         SKIP_ALL_WHITE_SPACE (buf);
8419       else
8420 #endif
8421       if (c == '\"' || c == '\\') /* escape these chars */
8422         totlen++;
8423       else if (!isprint (c))
8424         totlen += 3;
8425     }
8426     argptr->stringified_length = totlen;
8427   }
8428   return result;
8429 }
8430 \f
8431 /* Scan text from START (inclusive) up to LIMIT (exclusive),
8432    counting parens in *DEPTHPTR,
8433    and return if reach LIMIT
8434    or before a `)' that would make *DEPTHPTR negative
8435    or before a comma when *DEPTHPTR is zero.
8436    Single and double quotes are matched and termination
8437    is inhibited within them.  Comments also inhibit it.
8438    Value returned is pointer to stopping place.
8439
8440    Increment *NEWLINES each time a newline is passed.
8441    REST_ARGS notifies macarg1 that it should absorb the rest of the args.
8442    Set *COMMENTS to 1 if a comment is seen.  */
8443
8444 static U_CHAR *
8445 macarg1 (start, limit, depthptr, newlines, comments, rest_args)
8446      U_CHAR *start;
8447      register U_CHAR *limit;
8448      int *depthptr, *newlines, *comments;
8449      int rest_args;
8450 {
8451   register U_CHAR *bp = start;
8452
8453   while (bp < limit) {
8454     switch (*bp) {
8455     case '(':
8456       (*depthptr)++;
8457       break;
8458     case ')':
8459       if (--(*depthptr) < 0)
8460         return bp;
8461       break;
8462     case '\\':
8463       /* Traditionally, backslash makes following char not special.  */
8464       if (bp + 1 < limit && traditional)
8465         {
8466           bp++;
8467           /* But count source lines anyway.  */
8468           if (*bp == '\n')
8469             ++*newlines;
8470         }
8471       break;
8472     case '\n':
8473       ++*newlines;
8474       break;
8475     case '/':
8476       if (bp[1] == '\\' && bp[2] == '\n')
8477         newline_fix (bp + 1);
8478       if (bp[1] == '*') {
8479         *comments = 1;
8480         for (bp += 2; bp < limit; bp++) {
8481           if (*bp == '\n')
8482             ++*newlines;
8483           else if (*bp == '*') {
8484             if (bp[-1] == '/' && warn_comments)
8485               warning ("`/*' within comment");
8486             if (bp[1] == '\\' && bp[2] == '\n')
8487               newline_fix (bp + 1);
8488             if (bp[1] == '/')
8489               break;
8490           }
8491         }
8492       } else if (bp[1] == '/' && cplusplus_comments) {
8493         *comments = 1;
8494         for (bp += 2; bp < limit; bp++) {
8495           if (*bp == '\n') {
8496             ++*newlines;
8497             if (bp[-1] != '\\')
8498               break;
8499             if (warn_comments)
8500               warning ("multiline `//' comment");
8501           }
8502         }
8503       }
8504       break;
8505     case '\'':
8506     case '\"':
8507       {
8508         int quotec;
8509         for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
8510           if (*bp == '\\') {
8511             bp++;
8512             if (*bp == '\n')
8513               ++*newlines;
8514             while (*bp == '\\' && bp[1] == '\n') {
8515               bp += 2;
8516             }
8517           } else if (*bp == '\n') {
8518             ++*newlines;
8519             if (quotec == '\'')
8520               break;
8521           }
8522         }
8523       }
8524       break;
8525     case ',':
8526       /* if we've returned to lowest level and we aren't absorbing all args */
8527       if ((*depthptr) == 0 && rest_args == 0)
8528         return bp;
8529       break;
8530     }
8531     bp++;
8532   }
8533
8534   return bp;
8535 }
8536 \f
8537 /* Discard comments and duplicate newlines
8538    in the string of length LENGTH at START,
8539    except inside of string constants.
8540    The string is copied into itself with its beginning staying fixed.  
8541
8542    NEWLINES is the number of newlines that must be duplicated.
8543    We assume that that much extra space is available past the end
8544    of the string.  */
8545
8546 static int
8547 discard_comments (start, length, newlines)
8548      U_CHAR *start;
8549      int length;
8550      int newlines;
8551 {
8552   register U_CHAR *ibp;
8553   register U_CHAR *obp;
8554   register U_CHAR *limit;
8555   register int c;
8556
8557   /* If we have newlines to duplicate, copy everything
8558      that many characters up.  Then, in the second part,
8559      we will have room to insert the newlines
8560      while copying down.
8561      NEWLINES may actually be too large, because it counts
8562      newlines in string constants, and we don't duplicate those.
8563      But that does no harm.  */
8564   if (newlines > 0) {
8565     ibp = start + length;
8566     obp = ibp + newlines;
8567     limit = start;
8568     while (limit != ibp)
8569       *--obp = *--ibp;
8570   }
8571
8572   ibp = start + newlines;
8573   limit = start + length + newlines;
8574   obp = start;
8575
8576   while (ibp < limit) {
8577     *obp++ = c = *ibp++;
8578     switch (c) {
8579     case '\n':
8580       /* Duplicate the newline.  */
8581       *obp++ = '\n';
8582       break;
8583
8584     case '\\':
8585       if (*ibp == '\n') {
8586         obp--;
8587         ibp++;
8588       }
8589       break;
8590
8591     case '/':
8592       if (*ibp == '\\' && ibp[1] == '\n')
8593         newline_fix (ibp);
8594       /* Delete any comment.  */
8595       if (cplusplus_comments && ibp[0] == '/') {
8596         /* Comments are equivalent to spaces.  */
8597         obp[-1] = ' ';
8598         ibp++;
8599         while (ibp < limit && (*ibp != '\n' || ibp[-1] == '\\'))
8600           ibp++;
8601         break;
8602       }
8603       if (ibp[0] != '*' || ibp + 1 >= limit)
8604         break;
8605       /* Comments are equivalent to spaces.
8606          For -traditional, a comment is equivalent to nothing.  */
8607       if (traditional)
8608         obp--;
8609       else
8610         obp[-1] = ' ';
8611       ibp++;
8612       while (ibp + 1 < limit) {
8613         if (ibp[0] == '*'
8614             && ibp[1] == '\\' && ibp[2] == '\n')
8615           newline_fix (ibp + 1);
8616         if (ibp[0] == '*' && ibp[1] == '/')
8617           break;
8618         ibp++;
8619       }
8620       ibp += 2;
8621       break;
8622
8623     case '\'':
8624     case '\"':
8625       /* Notice and skip strings, so that we don't
8626          think that comments start inside them,
8627          and so we don't duplicate newlines in them.  */
8628       {
8629         int quotec = c;
8630         while (ibp < limit) {
8631           *obp++ = c = *ibp++;
8632           if (c == quotec)
8633             break;
8634           if (c == '\n' && quotec == '\'')
8635             break;
8636           if (c == '\\' && ibp < limit) {
8637             while (*ibp == '\\' && ibp[1] == '\n')
8638               ibp += 2;
8639             *obp++ = *ibp++;
8640           }
8641         }
8642       }
8643       break;
8644     }
8645   }
8646
8647   return obp - start;
8648 }
8649 \f
8650 /* Turn newlines to spaces in the string of length LENGTH at START,
8651    except inside of string constants.
8652    The string is copied into itself with its beginning staying fixed.  */
8653
8654 static int
8655 change_newlines (start, length)
8656      U_CHAR *start;
8657      int length;
8658 {
8659   register U_CHAR *ibp;
8660   register U_CHAR *obp;
8661   register U_CHAR *limit;
8662   register int c;
8663
8664   ibp = start;
8665   limit = start + length;
8666   obp = start;
8667
8668   while (ibp < limit) {
8669     *obp++ = c = *ibp++;
8670     switch (c) {
8671     case '\n':
8672       /* If this is a NEWLINE NEWLINE, then this is a real newline in the
8673          string.  Skip past the newline and its duplicate.
8674          Put a space in the output.  */
8675       if (*ibp == '\n')
8676         {
8677           ibp++;
8678           obp--;
8679           *obp++ = ' ';
8680         }
8681       break;
8682
8683     case '\'':
8684     case '\"':
8685       /* Notice and skip strings, so that we don't delete newlines in them.  */
8686       {
8687         int quotec = c;
8688         while (ibp < limit) {
8689           *obp++ = c = *ibp++;
8690           if (c == quotec)
8691             break;
8692           if (c == '\n' && quotec == '\'')
8693             break;
8694         }
8695       }
8696       break;
8697     }
8698   }
8699
8700   return obp - start;
8701 }
8702 \f
8703 /*
8704  * my_strerror - return the descriptive text associated with an `errno' code.
8705  */
8706
8707 char *
8708 my_strerror (errnum)
8709      int errnum;
8710 {
8711   char *result;
8712
8713 #ifndef VMS
8714 #ifndef HAVE_STRERROR
8715   result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
8716 #else
8717   result = strerror (errnum);
8718 #endif
8719 #else   /* VMS */
8720   /* VAXCRTL's strerror() takes an optional second argument, which only
8721      matters when the first argument is EVMSERR.  However, it's simplest
8722      just to pass it unconditionally.  `vaxc$errno' is declared in
8723      <errno.h>, and maintained by the library in parallel with `errno'.
8724      We assume that caller's `errnum' either matches the last setting of
8725      `errno' by the library or else does not have the value `EVMSERR'.  */
8726
8727   result = strerror (errnum, vaxc$errno);
8728 #endif
8729
8730   if (!result)
8731     result = "undocumented I/O error";
8732
8733   return result;
8734 }
8735
8736 /*
8737  * error - print error message and increment count of errors.
8738  */
8739
8740 void
8741 error (PRINTF_ALIST (msg))
8742      PRINTF_DCL (msg)
8743 {
8744   va_list args;
8745
8746   VA_START (args, msg);
8747   verror (msg, args);
8748   va_end (args);
8749 }
8750
8751 static void
8752 verror (msg, args)
8753      char *msg;
8754      va_list args;
8755 {
8756   int i;
8757   FILE_BUF *ip = NULL;
8758
8759   print_containing_files ();
8760
8761   for (i = indepth; i >= 0; i--)
8762     if (instack[i].fname != NULL) {
8763       ip = &instack[i];
8764       break;
8765     }
8766
8767   if (ip != NULL)
8768     fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8769   vfprintf (stderr, msg, args);
8770   fprintf (stderr, "\n");
8771   errors++;
8772 }
8773
8774 /* Error including a message from `errno'.  */
8775
8776 static void
8777 error_from_errno (name)
8778      char *name;
8779 {
8780   int i;
8781   FILE_BUF *ip = NULL;
8782
8783   print_containing_files ();
8784
8785   for (i = indepth; i >= 0; i--)
8786     if (instack[i].fname != NULL) {
8787       ip = &instack[i];
8788       break;
8789     }
8790
8791   if (ip != NULL)
8792     fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8793
8794   fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
8795
8796   errors++;
8797 }
8798
8799 /* Print error message but don't count it.  */
8800
8801 void
8802 warning (PRINTF_ALIST (msg))
8803      PRINTF_DCL (msg)
8804 {
8805   va_list args;
8806
8807   VA_START (args, msg);
8808   vwarning (msg, args);
8809   va_end (args);
8810 }
8811
8812 static void
8813 vwarning (msg, args)
8814      char *msg;
8815      va_list args;
8816 {
8817   int i;
8818   FILE_BUF *ip = NULL;
8819
8820   if (inhibit_warnings)
8821     return;
8822
8823   if (warnings_are_errors)
8824     errors++;
8825
8826   print_containing_files ();
8827
8828   for (i = indepth; i >= 0; i--)
8829     if (instack[i].fname != NULL) {
8830       ip = &instack[i];
8831       break;
8832     }
8833
8834   if (ip != NULL)
8835     fprintf (stderr, "%s:%d: ", ip->nominal_fname, ip->lineno);
8836   fprintf (stderr, "warning: ");
8837   vfprintf (stderr, msg, args);
8838   fprintf (stderr, "\n");
8839 }
8840
8841 static void
8842 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8843 error_with_line (int line, PRINTF_ALIST (msg))
8844 #else
8845 error_with_line (line, PRINTF_ALIST (msg))
8846      int line;
8847      PRINTF_DCL (msg)
8848 #endif
8849 {
8850   va_list args;
8851
8852   VA_START (args, msg);
8853   verror_with_line (line, msg, args);
8854   va_end (args);
8855 }
8856
8857 static void
8858 verror_with_line (line, msg, args)
8859      int line;
8860      char *msg;
8861      va_list args;
8862 {
8863   int i;
8864   FILE_BUF *ip = NULL;
8865
8866   print_containing_files ();
8867
8868   for (i = indepth; i >= 0; i--)
8869     if (instack[i].fname != NULL) {
8870       ip = &instack[i];
8871       break;
8872     }
8873
8874   if (ip != NULL)
8875     fprintf (stderr, "%s:%d: ", ip->nominal_fname, line);
8876   vfprintf (stderr, msg, args);
8877   fprintf (stderr, "\n");
8878   errors++;
8879 }
8880
8881 static void
8882 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8883 warning_with_line (int line, PRINTF_ALIST (msg))
8884 #else
8885 warning_with_line (line, PRINTF_ALIST (msg))
8886      int line;
8887      PRINTF_DCL (msg)
8888 #endif
8889 {
8890   va_list args;
8891
8892   VA_START (args, msg);
8893   vwarning_with_line (line, msg, args);
8894   va_end (args);
8895 }
8896
8897 static void
8898 vwarning_with_line (line, msg, args)
8899      int line;
8900      char *msg;
8901      va_list args;
8902 {
8903   int i;
8904   FILE_BUF *ip = NULL;
8905
8906   if (inhibit_warnings)
8907     return;
8908
8909   if (warnings_are_errors)
8910     errors++;
8911
8912   print_containing_files ();
8913
8914   for (i = indepth; i >= 0; i--)
8915     if (instack[i].fname != NULL) {
8916       ip = &instack[i];
8917       break;
8918     }
8919
8920   if (ip != NULL)
8921     fprintf (stderr, line ? "%s:%d: " : "%s: ", ip->nominal_fname, line);
8922   fprintf (stderr, "warning: ");
8923   vfprintf (stderr, msg, args);
8924   fprintf (stderr, "\n");
8925 }
8926
8927 /* print an error message and maybe count it.  */
8928
8929 void
8930 pedwarn (PRINTF_ALIST (msg))
8931      PRINTF_DCL (msg)
8932 {
8933   va_list args;
8934
8935   VA_START (args, msg);
8936   if (pedantic_errors)
8937     verror (msg, args);
8938   else
8939     vwarning (msg, args);
8940   va_end (args);
8941 }
8942
8943 void
8944 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8945 pedwarn_with_line (int line, PRINTF_ALIST (msg))
8946 #else
8947 pedwarn_with_line (line, PRINTF_ALIST (msg))
8948      int line;
8949      PRINTF_DCL (msg)
8950 #endif
8951 {
8952   va_list args;
8953
8954   VA_START (args, msg);
8955   if (pedantic_errors)
8956     verror_with_line (line, msg, args);
8957   else
8958     vwarning_with_line (line, msg, args);
8959   va_end (args);
8960 }
8961
8962 /* Report a warning (or an error if pedantic_errors)
8963    giving specified file name and line number, not current.  */
8964
8965 static void
8966 #if defined (__STDC__) && defined (HAVE_VPRINTF)
8967 pedwarn_with_file_and_line (char *file, int line, PRINTF_ALIST (msg))
8968 #else
8969 pedwarn_with_file_and_line (file, line, PRINTF_ALIST (msg))
8970      char *file;
8971      int line;
8972      PRINTF_DCL (msg)
8973 #endif
8974 {
8975   va_list args;
8976
8977   if (!pedantic_errors && inhibit_warnings)
8978     return;
8979   if (file != NULL)
8980     fprintf (stderr, "%s:%d: ", file, line);
8981   if (pedantic_errors)
8982     errors++;
8983   if (!pedantic_errors)
8984     fprintf (stderr, "warning: ");
8985   VA_START (args, msg);
8986   vfprintf (stderr, msg, args);
8987   va_end (args);
8988   fprintf (stderr, "\n");
8989 }
8990 \f
8991 /* Print the file names and line numbers of the #include
8992    directives which led to the current file.  */
8993
8994 static void
8995 print_containing_files ()
8996 {
8997   FILE_BUF *ip = NULL;
8998   int i;
8999   int first = 1;
9000
9001   /* If stack of files hasn't changed since we last printed
9002      this info, don't repeat it.  */
9003   if (last_error_tick == input_file_stack_tick)
9004     return;
9005
9006   for (i = indepth; i >= 0; i--)
9007     if (instack[i].fname != NULL) {
9008       ip = &instack[i];
9009       break;
9010     }
9011
9012   /* Give up if we don't find a source file.  */
9013   if (ip == NULL)
9014     return;
9015
9016   /* Find the other, outer source files.  */
9017   for (i--; i >= 0; i--)
9018     if (instack[i].fname != NULL) {
9019       ip = &instack[i];
9020       if (first) {
9021         first = 0;
9022         fprintf (stderr, "In file included");
9023       } else {
9024         fprintf (stderr, ",\n                ");
9025       }
9026
9027       fprintf (stderr, " from %s:%d", ip->nominal_fname, ip->lineno);
9028     }
9029   if (! first)
9030     fprintf (stderr, ":\n");
9031
9032   /* Record we have printed the status as of this time.  */
9033   last_error_tick = input_file_stack_tick;
9034 }
9035 \f
9036 /* Return the line at which an error occurred.
9037    The error is not necessarily associated with the current spot
9038    in the input stack, so LINE says where.  LINE will have been
9039    copied from ip->lineno for the current input level.
9040    If the current level is for a file, we return LINE.
9041    But if the current level is not for a file, LINE is meaningless.
9042    In that case, we return the lineno of the innermost file.  */
9043
9044 static int
9045 line_for_error (line)
9046      int line;
9047 {
9048   int i;
9049   int line1 = line;
9050
9051   for (i = indepth; i >= 0; ) {
9052     if (instack[i].fname != 0)
9053       return line1;
9054     i--;
9055     if (i < 0)
9056       return 0;
9057     line1 = instack[i].lineno;
9058   }
9059   abort ();
9060   /*NOTREACHED*/
9061   return 0;
9062 }
9063
9064 /*
9065  * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
9066  *
9067  * As things stand, nothing is ever placed in the output buffer to be
9068  * removed again except when it's KNOWN to be part of an identifier,
9069  * so flushing and moving down everything left, instead of expanding,
9070  * should work ok.
9071  */
9072
9073 /* You might think void was cleaner for the return type,
9074    but that would get type mismatch in check_expand in strict ANSI.  */
9075 static int
9076 grow_outbuf (obuf, needed)
9077      register FILE_BUF *obuf;
9078      register int needed;
9079 {
9080   register U_CHAR *p;
9081   int minsize;
9082
9083   if (obuf->length - (obuf->bufp - obuf->buf) > needed)
9084     return 0;
9085
9086   /* Make it at least twice as big as it is now.  */
9087   obuf->length *= 2;
9088   /* Make it have at least 150% of the free space we will need.  */
9089   minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
9090   if (minsize > obuf->length)
9091     obuf->length = minsize;
9092
9093   if ((p = (U_CHAR *) xrealloc (obuf->buf, obuf->length)) == NULL)
9094     memory_full ();
9095
9096   obuf->bufp = p + (obuf->bufp - obuf->buf);
9097   obuf->buf = p;
9098
9099   return 0;
9100 }
9101 \f
9102 /* Symbol table for macro names and special symbols */
9103
9104 /*
9105  * install a name in the main hash table, even if it is already there.
9106  *   name stops with first non alphanumeric, except leading '#'.
9107  * caller must check against redefinition if that is desired.
9108  * delete_macro () removes things installed by install () in fifo order.
9109  * this is important because of the `defined' special symbol used
9110  * in #if, and also if pushdef/popdef directives are ever implemented.
9111  *
9112  * If LEN is >= 0, it is the length of the name.
9113  * Otherwise, compute the length by scanning the entire name.
9114  *
9115  * If HASH is >= 0, it is the precomputed hash code.
9116  * Otherwise, compute the hash code.
9117  */
9118 static HASHNODE *
9119 install (name, len, type, value, hash)
9120      U_CHAR *name;
9121      int len;
9122      enum node_type type;
9123      char *value;
9124      int hash;
9125 {
9126   register HASHNODE *hp;
9127   register int i, bucket;
9128   register U_CHAR *p, *q;
9129
9130   if (len < 0) {
9131     p = name;
9132     while (is_idchar[*p])
9133       p++;
9134     len = p - name;
9135   }
9136
9137   if (hash < 0)
9138     hash = hashf (name, len, HASHSIZE);
9139
9140   i = sizeof (HASHNODE) + len + 1;
9141   hp = (HASHNODE *) xmalloc (i);
9142   bucket = hash;
9143   hp->bucket_hdr = &hashtab[bucket];
9144   hp->next = hashtab[bucket];
9145   hashtab[bucket] = hp;
9146   hp->prev = NULL;
9147   if (hp->next != NULL)
9148     hp->next->prev = hp;
9149   hp->type = type;
9150   hp->length = len;
9151   hp->value.cpval = value;
9152   hp->name = ((U_CHAR *) hp) + sizeof (HASHNODE);
9153   p = hp->name;
9154   q = name;
9155   for (i = 0; i < len; i++)
9156     *p++ = *q++;
9157   hp->name[len] = 0;
9158   return hp;
9159 }
9160
9161 /*
9162  * find the most recent hash node for name name (ending with first
9163  * non-identifier char) installed by install
9164  *
9165  * If LEN is >= 0, it is the length of the name.
9166  * Otherwise, compute the length by scanning the entire name.
9167  *
9168  * If HASH is >= 0, it is the precomputed hash code.
9169  * Otherwise, compute the hash code.
9170  */
9171 HASHNODE *
9172 lookup (name, len, hash)
9173      U_CHAR *name;
9174      int len;
9175      int hash;
9176 {
9177   register U_CHAR *bp;
9178   register HASHNODE *bucket;
9179
9180   if (len < 0) {
9181     for (bp = name; is_idchar[*bp]; bp++) ;
9182     len = bp - name;
9183   }
9184
9185   if (hash < 0)
9186     hash = hashf (name, len, HASHSIZE);
9187
9188   bucket = hashtab[hash];
9189   while (bucket) {
9190     if (bucket->length == len && bcmp (bucket->name, name, len) == 0)
9191       return bucket;
9192     bucket = bucket->next;
9193   }
9194   return NULL;
9195 }
9196
9197 /*
9198  * Delete a hash node.  Some weirdness to free junk from macros.
9199  * More such weirdness will have to be added if you define more hash
9200  * types that need it.
9201  */
9202
9203 /* Note that the DEFINITION of a macro is removed from the hash table
9204    but its storage is not freed.  This would be a storage leak
9205    except that it is not reasonable to keep undefining and redefining
9206    large numbers of macros many times.
9207    In any case, this is necessary, because a macro can be #undef'd
9208    in the middle of reading the arguments to a call to it.
9209    If #undef freed the DEFINITION, that would crash.  */
9210
9211 static void
9212 delete_macro (hp)
9213      HASHNODE *hp;
9214 {
9215
9216   if (hp->prev != NULL)
9217     hp->prev->next = hp->next;
9218   if (hp->next != NULL)
9219     hp->next->prev = hp->prev;
9220
9221   /* make sure that the bucket chain header that
9222      the deleted guy was on points to the right thing afterwards. */
9223   if (hp == *hp->bucket_hdr)
9224     *hp->bucket_hdr = hp->next;
9225
9226 #if 0
9227   if (hp->type == T_MACRO) {
9228     DEFINITION *d = hp->value.defn;
9229     struct reflist *ap, *nextap;
9230
9231     for (ap = d->pattern; ap != NULL; ap = nextap) {
9232       nextap = ap->next;
9233       free (ap);
9234     }
9235     free (d);
9236   }
9237 #endif
9238   free (hp);
9239 }
9240
9241 /*
9242  * return hash function on name.  must be compatible with the one
9243  * computed a step at a time, elsewhere
9244  */
9245 static int
9246 hashf (name, len, hashsize)
9247      register U_CHAR *name;
9248      register int len;
9249      int hashsize;
9250 {
9251   register int r = 0;
9252
9253   while (len--)
9254     r = HASHSTEP (r, *name++);
9255
9256   return MAKE_POS (r) % hashsize;
9257 }
9258 \f
9259
9260 /* Dump the definition of a single macro HP to OF.  */
9261 static void
9262 dump_single_macro (hp, of)
9263      register HASHNODE *hp;
9264      FILE *of;
9265 {
9266   register DEFINITION *defn = hp->value.defn;
9267   struct reflist *ap;
9268   int offset;
9269   int concat;
9270
9271
9272   /* Print the definition of the macro HP.  */
9273
9274   fprintf (of, "#define %s", hp->name);
9275
9276   if (defn->nargs >= 0) {
9277     int i;
9278
9279     fprintf (of, "(");
9280     for (i = 0; i < defn->nargs; i++) {
9281       dump_arg_n (defn, i, of);
9282       if (i + 1 < defn->nargs)
9283         fprintf (of, ", ");
9284     }
9285     fprintf (of, ")");
9286   }
9287
9288   fprintf (of, " ");
9289
9290   offset = 0;
9291   concat = 0;
9292   for (ap = defn->pattern; ap != NULL; ap = ap->next) {
9293     dump_defn_1 (defn->expansion, offset, ap->nchars, of);
9294     offset += ap->nchars;
9295     if (!traditional) {
9296       if (ap->nchars != 0)
9297         concat = 0;
9298       if (ap->stringify) {
9299         switch (ap->stringify) {
9300          case SHARP_TOKEN: fprintf (of, "#"); break;
9301          case WHITE_SHARP_TOKEN: fprintf (of, "# "); break;
9302          case PERCENT_COLON_TOKEN: fprintf (of, "%%:"); break;
9303          case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%: "); break;
9304          default: abort ();
9305         }
9306       }
9307       if (ap->raw_before != 0) {
9308         if (concat) {
9309           switch (ap->raw_before) {
9310            case WHITE_SHARP_TOKEN:
9311            case WHITE_PERCENT_COLON_TOKEN:
9312             fprintf (of, " ");
9313             break;
9314            default:
9315             break;
9316           }
9317         } else {
9318           switch (ap->raw_before) {
9319            case SHARP_TOKEN: fprintf (of, "##"); break;
9320            case WHITE_SHARP_TOKEN: fprintf (of, "## "); break;
9321            case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9322            case WHITE_PERCENT_COLON_TOKEN: fprintf (of, "%%:%%: "); break;
9323            default: abort ();
9324           }
9325         }
9326       }
9327       concat = 0;
9328     }
9329     dump_arg_n (defn, ap->argno, of);
9330     if (!traditional && ap->raw_after != 0) {
9331       switch (ap->raw_after) {
9332        case SHARP_TOKEN: fprintf (of, "##"); break;
9333        case WHITE_SHARP_TOKEN: fprintf (of, " ##"); break;
9334        case PERCENT_COLON_TOKEN: fprintf (of, "%%:%%:"); break;
9335        case WHITE_PERCENT_COLON_TOKEN: fprintf (of, " %%:%%:"); break;
9336        default: abort ();
9337       }
9338       concat = 1;
9339     }
9340   }
9341   dump_defn_1 (defn->expansion, offset, defn->length - offset, of);
9342   fprintf (of, "\n");
9343 }
9344
9345 /* Dump all macro definitions as #defines to stdout.  */
9346
9347 static void
9348 dump_all_macros ()
9349 {
9350   int bucket;
9351
9352   for (bucket = 0; bucket < HASHSIZE; bucket++) {
9353     register HASHNODE *hp;
9354
9355     for (hp = hashtab[bucket]; hp; hp= hp->next) {
9356       if (hp->type == T_MACRO)
9357         dump_single_macro (hp, stdout);
9358     }
9359   }
9360 }
9361
9362 /* Output to OF a substring of a macro definition.
9363    BASE is the beginning of the definition.
9364    Output characters START thru LENGTH.
9365    Unless traditional, discard newlines outside of strings, thus
9366    converting funny-space markers to ordinary spaces.  */
9367
9368 static void
9369 dump_defn_1 (base, start, length, of)
9370      U_CHAR *base;
9371      int start;
9372      int length;
9373      FILE *of;
9374 {
9375   U_CHAR *p = base + start;
9376   U_CHAR *limit = base + start + length;
9377
9378   if (traditional)
9379     fwrite (p, sizeof (*p), length, of);
9380   else {
9381     while (p < limit) {
9382       if (*p == '\"' || *p =='\'') {
9383         U_CHAR *p1 = skip_quoted_string (p, limit, 0, NULL_PTR,
9384                                          NULL_PTR, NULL_PTR);
9385         fwrite (p, sizeof (*p), p1 - p, of);
9386         p = p1;
9387       } else {
9388         if (*p != '\n')
9389           putc (*p, of);
9390         p++;
9391       }
9392     }
9393   }
9394 }
9395
9396 /* Print the name of argument number ARGNUM of macro definition DEFN
9397    to OF.
9398    Recall that DEFN->args.argnames contains all the arg names
9399    concatenated in reverse order with comma-space in between.  */
9400
9401 static void
9402 dump_arg_n (defn, argnum, of)
9403      DEFINITION *defn;
9404      int argnum;
9405      FILE *of;
9406 {
9407   register U_CHAR *p = defn->args.argnames;
9408   while (argnum + 1 < defn->nargs) {
9409     p = (U_CHAR *) index ((char *) p, ' ') + 1;
9410     argnum++;
9411   }
9412
9413   while (*p && *p != ',') {
9414     putc (*p, of);
9415     p++;
9416   }
9417 }
9418 \f
9419 /* Initialize syntactic classifications of characters.  */
9420
9421 static void
9422 initialize_char_syntax ()
9423 {
9424   register int i;
9425
9426   /*
9427    * Set up is_idchar and is_idstart tables.  These should be
9428    * faster than saying (is_alpha (c) || c == '_'), etc.
9429    * Set up these things before calling any routines tthat
9430    * refer to them.
9431    */
9432   for (i = 'a'; i <= 'z'; i++) {
9433     is_idchar[i - 'a' + 'A'] = 1;
9434     is_idchar[i] = 1;
9435     is_idstart[i - 'a' + 'A'] = 1;
9436     is_idstart[i] = 1;
9437   }
9438   for (i = '0'; i <= '9'; i++)
9439     is_idchar[i] = 1;
9440   is_idchar['_'] = 1;
9441   is_idstart['_'] = 1;
9442   is_idchar['$'] = dollars_in_ident;
9443   is_idstart['$'] = dollars_in_ident;
9444
9445   /* horizontal space table */
9446   is_hor_space[' '] = 1;
9447   is_hor_space['\t'] = 1;
9448   is_hor_space['\v'] = 1;
9449   is_hor_space['\f'] = 1;
9450   is_hor_space['\r'] = 1;
9451
9452   is_space[' '] = 1;
9453   is_space['\t'] = 1;
9454   is_space['\v'] = 1;
9455   is_space['\f'] = 1;
9456   is_space['\n'] = 1;
9457   is_space['\r'] = 1;
9458
9459   char_name['\v'] = "vertical tab";
9460   char_name['\f'] = "formfeed";
9461   char_name['\r'] = "carriage return";
9462 }
9463
9464 /* Initialize the built-in macros.  */
9465
9466 static void
9467 initialize_builtins (inp, outp)
9468      FILE_BUF *inp;
9469      FILE_BUF *outp;
9470 {
9471   install ((U_CHAR *) "__LINE__", -1, T_SPECLINE, NULL_PTR, -1);
9472   install ((U_CHAR *) "__DATE__", -1, T_DATE, NULL_PTR, -1);
9473   install ((U_CHAR *) "__FILE__", -1, T_FILE, NULL_PTR, -1);
9474   install ((U_CHAR *) "__BASE_FILE__", -1, T_BASE_FILE, NULL_PTR, -1);
9475   install ((U_CHAR *) "__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, NULL_PTR, -1);
9476   install ((U_CHAR *) "__VERSION__", -1, T_VERSION, NULL_PTR, -1);
9477 #ifndef NO_BUILTIN_SIZE_TYPE
9478   install ((U_CHAR *) "__SIZE_TYPE__", -1, T_SIZE_TYPE, NULL_PTR, -1);
9479 #endif
9480 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9481   install ((U_CHAR *) "__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, NULL_PTR, -1);
9482 #endif
9483   install ((U_CHAR *) "__WCHAR_TYPE__", -1, T_WCHAR_TYPE, NULL_PTR, -1);
9484   install ((U_CHAR *) "__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE,
9485            NULL_PTR, -1);
9486   install ((U_CHAR *) "__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE,
9487            NULL_PTR, -1);
9488   install ((U_CHAR *) "__IMMEDIATE_PREFIX__", -1, T_IMMEDIATE_PREFIX_TYPE,
9489            NULL_PTR, -1);
9490   install ((U_CHAR *) "__TIME__", -1, T_TIME, NULL_PTR, -1);
9491   if (!traditional) {
9492     install ((U_CHAR *) "__STDC__", -1, T_CONST, "1", -1);
9493     install ((U_CHAR *) "__STDC_VERSION__", -1, T_CONST, "199409L", -1);
9494   }
9495   if (objc)
9496     install ((U_CHAR *) "__OBJC__", -1, T_CONST, "1", -1);
9497 /*  This is supplied using a -D by the compiler driver
9498     so that it is present only when truly compiling with GNU C.  */
9499 /*  install ((U_CHAR *) "__GNUC__", -1, T_CONST, "2", -1);  */
9500
9501   if (debug_output)
9502     {
9503       char directive[2048];
9504       U_CHAR *udirective = (U_CHAR *) directive;
9505       register struct directive *dp = &directive_table[0];
9506       struct tm *timebuf = timestamp ();
9507
9508       sprintf (directive, " __BASE_FILE__ \"%s\"\n",
9509                instack[0].nominal_fname);
9510       output_line_directive (inp, outp, 0, same_file);
9511       pass_thru_directive (udirective, &udirective[strlen (directive)],
9512                            outp, dp);
9513
9514       sprintf (directive, " __VERSION__ \"%s\"\n", version_string);
9515       output_line_directive (inp, outp, 0, same_file);
9516       pass_thru_directive (udirective, &udirective[strlen (directive)],
9517                            outp, dp);
9518
9519 #ifndef NO_BUILTIN_SIZE_TYPE
9520       sprintf (directive, " __SIZE_TYPE__ %s\n", SIZE_TYPE);
9521       output_line_directive (inp, outp, 0, same_file);
9522       pass_thru_directive (udirective, &udirective[strlen (directive)],
9523                            outp, dp);
9524 #endif
9525
9526 #ifndef NO_BUILTIN_PTRDIFF_TYPE
9527       sprintf (directive, " __PTRDIFF_TYPE__ %s\n", PTRDIFF_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       sprintf (directive, " __WCHAR_TYPE__ %s\n", wchar_type);
9534       output_line_directive (inp, outp, 0, same_file);
9535       pass_thru_directive (udirective, &udirective[strlen (directive)],
9536                            outp, dp);
9537
9538       sprintf (directive, " __DATE__ \"%s %2d %4d\"\n",
9539                monthnames[timebuf->tm_mon],
9540                timebuf->tm_mday, timebuf->tm_year + 1900);
9541       output_line_directive (inp, outp, 0, same_file);
9542       pass_thru_directive (udirective, &udirective[strlen (directive)],
9543                            outp, dp);
9544
9545       sprintf (directive, " __TIME__ \"%02d:%02d:%02d\"\n",
9546                timebuf->tm_hour, timebuf->tm_min, timebuf->tm_sec);
9547       output_line_directive (inp, outp, 0, same_file);
9548       pass_thru_directive (udirective, &udirective[strlen (directive)],
9549                            outp, dp);
9550
9551       if (!traditional)
9552         {
9553           sprintf (directive, " __STDC__ 1");
9554           output_line_directive (inp, outp, 0, same_file);
9555           pass_thru_directive (udirective, &udirective[strlen (directive)],
9556                                outp, dp);
9557         }
9558       if (objc)
9559         {
9560           sprintf (directive, " __OBJC__ 1");
9561           output_line_directive (inp, outp, 0, same_file);
9562           pass_thru_directive (udirective, &udirective[strlen (directive)],
9563                                outp, dp);
9564         }
9565     }
9566 }
9567 \f
9568 /*
9569  * process a given definition string, for initialization
9570  * If STR is just an identifier, define it with value 1.
9571  * If STR has anything after the identifier, then it should
9572  * be identifier=definition.
9573  */
9574
9575 static void
9576 make_definition (str, op)
9577      char *str;
9578      FILE_BUF *op;
9579 {
9580   FILE_BUF *ip;
9581   struct directive *kt;
9582   U_CHAR *buf, *p;
9583
9584   p = buf = (U_CHAR *) str;
9585   if (!is_idstart[*p]) {
9586     error ("malformed option `-D %s'", str);
9587     return;
9588   }
9589   while (is_idchar[*++p])
9590     ;
9591   if (*p == '(') {
9592     while (is_idchar[*++p] || *p == ',' || is_hor_space[*p])
9593       ;
9594     if (*p++ != ')')
9595       p = (U_CHAR *) str;                       /* Error */
9596   }
9597   if (*p == 0) {
9598     buf = (U_CHAR *) alloca (p - buf + 4);
9599     strcpy ((char *)buf, str);
9600     strcat ((char *)buf, " 1");
9601   } else if (*p != '=') {
9602     error ("malformed option `-D %s'", str);
9603     return;
9604   } else {
9605     U_CHAR *q;
9606     /* Copy the entire option so we can modify it.  */
9607     buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
9608     strncpy ((char *) buf, str, p - (U_CHAR *) str);
9609     /* Change the = to a space.  */
9610     buf[p - (U_CHAR *) str] = ' ';
9611     /* Scan for any backslash-newline and remove it.  */
9612     p++;
9613     q = &buf[p - (U_CHAR *) str];
9614     while (*p) {
9615       if (*p == '\"' || *p == '\'') {
9616         int unterminated = 0;
9617         U_CHAR *p1 = skip_quoted_string (p, p + strlen ((char *) p), 0,
9618                                          NULL_PTR, NULL_PTR, &unterminated);
9619         if (unterminated)
9620           return;
9621         while (p != p1)
9622           if (*p == '\\' && p[1] == '\n')
9623             p += 2;
9624           else
9625             *q++ = *p++;
9626       } else if (*p == '\\' && p[1] == '\n')
9627         p += 2;
9628       /* Change newline chars into newline-markers.  */
9629       else if (*p == '\n')
9630         {
9631           *q++ = '\n';
9632           *q++ = '\n';
9633           p++;
9634         }
9635       else
9636         *q++ = *p++;
9637     }
9638     *q = 0;
9639   }
9640   
9641   ip = &instack[++indepth];
9642   ip->nominal_fname = ip->fname = "*Initialization*";
9643
9644   ip->buf = ip->bufp = buf;
9645   ip->length = strlen ((char *) buf);
9646   ip->lineno = 1;
9647   ip->macro = 0;
9648   ip->free_ptr = 0;
9649   ip->if_stack = if_stack;
9650   ip->system_header_p = 0;
9651
9652   for (kt = directive_table; kt->type != T_DEFINE; kt++)
9653     ;
9654
9655   /* Pass NULL instead of OP, since this is a "predefined" macro.  */
9656   do_define (buf, buf + strlen ((char *) buf), NULL_PTR, kt);
9657   --indepth;
9658 }
9659
9660 /* JF, this does the work for the -U option */
9661
9662 static void
9663 make_undef (str, op)
9664      char *str;
9665      FILE_BUF *op;
9666 {
9667   FILE_BUF *ip;
9668   struct directive *kt;
9669
9670   ip = &instack[++indepth];
9671   ip->nominal_fname = ip->fname = "*undef*";
9672
9673   ip->buf = ip->bufp = (U_CHAR *) str;
9674   ip->length = strlen (str);
9675   ip->lineno = 1;
9676   ip->macro = 0;
9677   ip->free_ptr = 0;
9678   ip->if_stack = if_stack;
9679   ip->system_header_p = 0;
9680
9681   for (kt = directive_table; kt->type != T_UNDEF; kt++)
9682     ;
9683
9684   do_undef ((U_CHAR *) str, (U_CHAR *) str + strlen (str), op, kt);
9685   --indepth;
9686 }
9687 \f
9688 /* Process the string STR as if it appeared as the body of a #assert.
9689    OPTION is the option name for which STR was the argument.  */
9690
9691 static void
9692 make_assertion (option, str)
9693      char *option;
9694      char *str;
9695 {
9696   FILE_BUF *ip;
9697   struct directive *kt;
9698   U_CHAR *buf, *p, *q;
9699
9700   /* Copy the entire option so we can modify it.  */
9701   buf = (U_CHAR *) alloca (strlen (str) + 1);
9702   strcpy ((char *) buf, str);
9703   /* Scan for any backslash-newline and remove it.  */
9704   p = q = buf;
9705   while (*p) {
9706     if (*p == '\\' && p[1] == '\n')
9707       p += 2;
9708     else
9709       *q++ = *p++;
9710   }
9711   *q = 0;
9712
9713   p = buf;
9714   if (!is_idstart[*p]) {
9715     error ("malformed option `%s %s'", option, str);
9716     return;
9717   }
9718   while (is_idchar[*++p])
9719     ;
9720   SKIP_WHITE_SPACE (p);
9721   if (! (*p == 0 || *p == '(')) {
9722     error ("malformed option `%s %s'", option, str);
9723     return;
9724   }
9725   
9726   ip = &instack[++indepth];
9727   ip->nominal_fname = ip->fname = "*Initialization*";
9728
9729   ip->buf = ip->bufp = buf;
9730   ip->length = strlen ((char *) buf);
9731   ip->lineno = 1;
9732   ip->macro = 0;
9733   ip->free_ptr = 0;
9734   ip->if_stack = if_stack;
9735   ip->system_header_p = 0;
9736
9737   for (kt = directive_table; kt->type != T_ASSERT; kt++)
9738     ;
9739
9740   /* pass NULL as output ptr to do_define since we KNOW it never
9741      does any output.... */
9742   do_assert (buf, buf + strlen ((char *) buf) , NULL_PTR, kt);
9743   --indepth;
9744 }
9745 \f
9746 /* The previous include prefix, if any, is PREV_FILE_NAME.
9747    Allocate a new include prefix whose name is the
9748    simplified concatenation of PREFIX and NAME,
9749    with a trailing / added if needed.
9750    But return 0 if the include prefix should be ignored,
9751    e.g. because it is a duplicate of PREV_FILE_NAME.  */
9752
9753 static struct file_name_list *
9754 new_include_prefix (prev_file_name, prefix, name)
9755      struct file_name_list *prev_file_name;
9756      char *prefix;
9757      char *name;
9758 {
9759   if (!name)
9760     fatal ("Directory name missing after command line option");
9761
9762   if (!*name)
9763     /* Ignore the empty string.  */
9764     return 0;
9765   else {
9766     struct file_name_list *dir
9767       = ((struct file_name_list *)
9768          xmalloc (sizeof (struct file_name_list)
9769                   + strlen (prefix) + strlen (name) + 1 /* for trailing / */));
9770     size_t len;
9771     strcpy (dir->fname, prefix);
9772     strcat (dir->fname, name);
9773     len = simplify_filename (dir->fname);
9774
9775     /* Convert directory name to a prefix.  */
9776     if (dir->fname[len - 1] != '/') {
9777       if (len == 1 && dir->fname[len - 1] == '.')
9778         len = 0;
9779       else
9780         dir->fname[len++] = '/';
9781       dir->fname[len] = 0;
9782     }
9783
9784     /* Ignore a directory whose name matches the previous one.  */
9785     if (prev_file_name && !strcmp (prev_file_name->fname, dir->fname)) {
9786       /* But treat `-Idir -I- -Idir' as `-I- -Idir'.  */
9787       if (!first_bracket_include)
9788         first_bracket_include = prev_file_name;
9789       free (dir);
9790       return 0;
9791     }
9792
9793     /* Ignore a nonexistent directory.  */
9794     if (stat (len ? dir->fname : ".", &dir->st) != 0) {
9795       if (errno != ENOENT)
9796         error_from_errno (dir->fname);
9797       free (dir);
9798       return 0;
9799     }
9800
9801     /* Ignore a directory whose identity matches the previous one.  */
9802     if (prev_file_name
9803         && INO_T_EQ (prev_file_name->st.st_ino, dir->st.st_ino)
9804         && prev_file_name->st.st_dev == dir->st.st_dev) {
9805       /* But treat `-Idir -I- -Idir' as `-I- -Idir'.  */
9806       if (!first_bracket_include)
9807         first_bracket_include = prev_file_name;
9808       free (dir);
9809       return 0;
9810     }
9811
9812     dir->next = 0;
9813     dir->c_system_include_path = 0;
9814     dir->got_name_map = 0;
9815
9816     return dir;
9817   }
9818 }
9819
9820 /* Append a chain of `struct file_name_list's
9821    to the end of the main include chain.
9822    FIRST is the beginning of the chain to append, and LAST is the end.  */
9823
9824 static void
9825 append_include_chain (first, last)
9826      struct file_name_list *first, *last;
9827 {
9828   struct file_name_list *dir;
9829
9830   if (!first || !last)
9831     return;
9832
9833   if (include == 0)
9834     include = first;
9835   else
9836     last_include->next = first;
9837
9838   if (first_bracket_include == 0)
9839     first_bracket_include = first;
9840
9841   for (dir = first; ; dir = dir->next) {
9842     int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
9843     if (len > max_include_len)
9844       max_include_len = len;
9845     if (dir == last)
9846       break;
9847   }
9848
9849   last->next = NULL;
9850   last_include = last;
9851 }
9852 \f
9853 /* Add output to `deps_buffer' for the -M switch.
9854    STRING points to the text to be output.
9855    SPACER is ':' for targets, ' ' for dependencies.  */
9856
9857 static void
9858 deps_output (string, spacer)
9859      char *string;
9860      int spacer;
9861 {
9862   int size = strlen (string);
9863
9864   if (size == 0)
9865     return;
9866
9867 #ifndef MAX_OUTPUT_COLUMNS
9868 #define MAX_OUTPUT_COLUMNS 72
9869 #endif
9870   if (MAX_OUTPUT_COLUMNS - 1 /*spacer*/ - 2 /*` \'*/ < deps_column + size
9871       && 1 < deps_column) {
9872     bcopy (" \\\n ", &deps_buffer[deps_size], 4);
9873     deps_size += 4;
9874     deps_column = 1;
9875     if (spacer == ' ')
9876       spacer = 0;
9877   }
9878
9879   if (deps_size + size + 8 > deps_allocated_size) {
9880     deps_allocated_size = (deps_size + size + 50) * 2;
9881     deps_buffer = xrealloc (deps_buffer, deps_allocated_size);
9882   }
9883   if (spacer == ' ') {
9884     deps_buffer[deps_size++] = ' ';
9885     deps_column++;
9886   }
9887   bcopy (string, &deps_buffer[deps_size], size);
9888   deps_size += size;
9889   deps_column += size;
9890   if (spacer == ':') {
9891     deps_buffer[deps_size++] = ':';
9892     deps_column++;
9893   }
9894   deps_buffer[deps_size] = 0;
9895 }
9896 \f
9897 static void
9898 fatal (PRINTF_ALIST (msg))
9899      PRINTF_DCL (msg)
9900 {
9901   va_list args;
9902
9903   fprintf (stderr, "%s: ", progname);
9904   VA_START (args, msg);
9905   vfprintf (stderr, msg, args);
9906   va_end (args);
9907   fprintf (stderr, "\n");
9908   exit (FATAL_EXIT_CODE);
9909 }
9910
9911 /* More 'friendly' abort that prints the line and file.
9912    config.h can #define abort fancy_abort if you like that sort of thing.  */
9913
9914 void
9915 fancy_abort ()
9916 {
9917   fatal ("Internal gcc abort.");
9918 }
9919
9920 static void
9921 perror_with_name (name)
9922      char *name;
9923 {
9924   fprintf (stderr, "%s: ", progname);
9925   fprintf (stderr, "%s: %s\n", name, my_strerror (errno));
9926   errors++;
9927 }
9928
9929 static void
9930 pfatal_with_name (name)
9931      char *name;
9932 {
9933   perror_with_name (name);
9934 #ifdef VMS
9935   exit (vaxc$errno);
9936 #else
9937   exit (FATAL_EXIT_CODE);
9938 #endif
9939 }
9940
9941 /* Handler for SIGPIPE.  */
9942
9943 static void
9944 pipe_closed (signo)
9945      /* If this is missing, some compilers complain.  */
9946      int signo;
9947 {
9948   fatal ("output pipe has been closed");
9949 }
9950 \f
9951 static void
9952 memory_full ()
9953 {
9954   fatal ("Memory exhausted.");
9955 }
9956
9957
9958 GENERIC_PTR
9959 xmalloc (size)
9960      size_t size;
9961 {
9962   register GENERIC_PTR ptr = (GENERIC_PTR) malloc (size);
9963   if (!ptr)
9964     memory_full ();
9965   return ptr;
9966 }
9967
9968 static GENERIC_PTR
9969 xrealloc (old, size)
9970      GENERIC_PTR old;
9971      size_t size;
9972 {
9973   register GENERIC_PTR ptr = (GENERIC_PTR) realloc (old, size);
9974   if (!ptr)
9975     memory_full ();
9976   return ptr;
9977 }
9978
9979 static GENERIC_PTR
9980 xcalloc (number, size)
9981      size_t number, size;
9982 {
9983   register size_t total = number * size;
9984   register GENERIC_PTR ptr = (GENERIC_PTR) malloc (total);
9985   if (!ptr)
9986     memory_full ();
9987   bzero (ptr, total);
9988   return ptr;
9989 }
9990
9991 static char *
9992 savestring (input)
9993      char *input;
9994 {
9995   size_t size = strlen (input);
9996   char *output = xmalloc (size + 1);
9997   strcpy (output, input);
9998   return output;
9999 }
10000 \f
10001 #ifdef VMS
10002
10003 /* Under VMS we need to fix up the "include" specification
10004    filename so that everything following the 1st slash is
10005    changed into its correct VMS file specification. */
10006
10007 static void
10008 hack_vms_include_specification (fname)
10009      char *fname;
10010 {
10011   register char *cp, *cp1, *cp2;
10012   int f, check_filename_before_returning;
10013   char Local[512];
10014
10015   check_filename_before_returning = 0;
10016
10017   cp = base_name (fname);
10018
10019   /*
10020    * Check if we have a vax-c style '#include filename'
10021    * and add the missing .h
10022    */
10023   if (!index (cp,'.'))
10024     strcat (cp, ".h");
10025
10026   cp2 = Local;                  /* initialize */
10027
10028   /* We are trying to do a number of things here.  First of all, we are
10029      trying to hammer the filenames into a standard format, such that later
10030      processing can handle them.
10031      
10032      If the file name contains something like [dir.], then it recognizes this
10033      as a root, and strips the ".]".  Later processing will add whatever is
10034      needed to get things working properly.
10035      
10036      If no device is specified, then the first directory name is taken to be
10037      a device name (or a rooted logical). */
10038
10039   /* See if we found that 1st slash */
10040   if (cp == 0) return;          /* Nothing to do!!! */
10041   if (*cp != '/') return;       /* Nothing to do!!! */
10042   /* Point to the UNIX filename part (which needs to be fixed!) */
10043   cp1 = cp+1;
10044   /* If the directory spec is not rooted, we can just copy
10045      the UNIX filename part and we are done */
10046   if (((cp - fname) > 1) && ((cp[-1] == ']') || (cp[-1] == '>'))) {
10047     if (cp[-2] != '.') {
10048       /*
10049        * The VMS part ends in a `]', and the preceding character is not a `.'.
10050        * We strip the `]', and then splice the two parts of the name in the
10051        * usual way.  Given the default locations for include files in cccp.c,
10052        * we will only use this code if the user specifies alternate locations
10053        * with the /include (-I) switch on the command line.  */
10054       cp -= 1;                  /* Strip "]" */
10055       cp1--;                    /* backspace */
10056     } else {
10057       /*
10058        * The VMS part has a ".]" at the end, and this will not do.  Later
10059        * processing will add a second directory spec, and this would be a syntax
10060        * error.  Thus we strip the ".]", and thus merge the directory specs.
10061        * We also backspace cp1, so that it points to a '/'.  This inhibits the
10062        * generation of the 000000 root directory spec (which does not belong here
10063        * in this case).
10064        */
10065       cp -= 2;                  /* Strip ".]" */
10066       cp1--; };                 /* backspace */
10067   } else {
10068
10069     /* We drop in here if there is no VMS style directory specification yet.
10070      * If there is no device specification either, we make the first dir a
10071      * device and try that.  If we do not do this, then we will be essentially
10072      * searching the users default directory (as if they did a #include "asdf.h").
10073      *
10074      * Then all we need to do is to push a '[' into the output string. Later
10075      * processing will fill this in, and close the bracket.
10076      */
10077     if (cp[-1] != ':') *cp2++ = ':'; /* dev not in spec.  take first dir */
10078     *cp2++ = '[';               /* Open the directory specification */
10079   }
10080
10081   /* at this point we assume that we have the device spec, and (at least
10082      the opening "[" for a directory specification.  We may have directories
10083      specified already */
10084
10085   /* If there are no other slashes then the filename will be
10086      in the "root" directory.  Otherwise, we need to add
10087      directory specifications. */
10088   if (index (cp1, '/') == 0) {
10089     /* Just add "000000]" as the directory string */
10090     strcpy (cp2, "000000]");
10091     cp2 += strlen (cp2);
10092     check_filename_before_returning = 1; /* we might need to fool with this later */
10093   } else {
10094     /* As long as there are still subdirectories to add, do them. */
10095     while (index (cp1, '/') != 0) {
10096       /* If this token is "." we can ignore it */
10097       if ((cp1[0] == '.') && (cp1[1] == '/')) {
10098         cp1 += 2;
10099         continue;
10100       }
10101       /* Add a subdirectory spec. Do not duplicate "." */
10102       if (cp2[-1] != '.' && cp2[-1] != '[' && cp2[-1] != '<')
10103         *cp2++ = '.';
10104       /* If this is ".." then the spec becomes "-" */
10105       if ((cp1[0] == '.') && (cp1[1] == '.') && (cp[2] == '/')) {
10106         /* Add "-" and skip the ".." */
10107         *cp2++ = '-';
10108         cp1 += 3;
10109         continue;
10110       }
10111       /* Copy the subdirectory */
10112       while (*cp1 != '/') *cp2++= *cp1++;
10113       cp1++;                    /* Skip the "/" */
10114     }
10115     /* Close the directory specification */
10116     if (cp2[-1] == '.')         /* no trailing periods */
10117       cp2--;
10118     *cp2++ = ']';
10119   }
10120   /* Now add the filename */
10121   while (*cp1) *cp2++ = *cp1++;
10122   *cp2 = 0;
10123   /* Now append it to the original VMS spec. */
10124   strcpy (cp, Local);
10125
10126   /* If we put a [000000] in the filename, try to open it first. If this fails,
10127      remove the [000000], and return that name.  This provides flexibility
10128      to the user in that they can use both rooted and non-rooted logical names
10129      to point to the location of the file.  */
10130
10131   if (check_filename_before_returning) {
10132     f = open (fname, O_RDONLY, 0666);
10133     if (f >= 0) {
10134       /* The file name is OK as it is, so return it as is.  */
10135       close (f);
10136       return;
10137     }
10138     /* The filename did not work.  Try to remove the [000000] from the name,
10139        and return it.  */
10140     cp = index (fname, '[');
10141     cp2 = index (fname, ']') + 1;
10142     strcpy (cp, cp2);           /* this gets rid of it */
10143   }
10144   return;
10145 }
10146 #endif  /* VMS */
10147 \f
10148 #ifdef  VMS
10149
10150 /* These are the read/write replacement routines for
10151    VAX-11 "C".  They make read/write behave enough
10152    like their UNIX counterparts that CCCP will work */
10153
10154 static int
10155 read (fd, buf, size)
10156      int fd;
10157      char *buf;
10158      int size;
10159 {
10160 #undef  read    /* Get back the REAL read routine */
10161   register int i;
10162   register int total = 0;
10163
10164   /* Read until the buffer is exhausted */
10165   while (size > 0) {
10166     /* Limit each read to 32KB */
10167     i = (size > (32*1024)) ? (32*1024) : size;
10168     i = read (fd, buf, i);
10169     if (i <= 0) {
10170       if (i == 0) return (total);
10171       return (i);
10172     }
10173     /* Account for this read */
10174     total += i;
10175     buf += i;
10176     size -= i;
10177   }
10178   return (total);
10179 }
10180
10181 static int
10182 write (fd, buf, size)
10183      int fd;
10184      char *buf;
10185      int size;
10186 {
10187 #undef  write   /* Get back the REAL write routine */
10188   int i;
10189   int j;
10190
10191   /* Limit individual writes to 32Kb */
10192   i = size;
10193   while (i > 0) {
10194     j = (i > (32*1024)) ? (32*1024) : i;
10195     if (write (fd, buf, j) < 0) return (-1);
10196     /* Account for the data written */
10197     buf += j;
10198     i -= j;
10199   }
10200   return (size);
10201 }
10202
10203 /* The following wrapper functions supply additional arguments to the VMS
10204    I/O routines to optimize performance with file handling.  The arguments
10205    are:
10206      "mbc=16" - Set multi-block count to 16 (use a 8192 byte buffer).
10207      "deq=64" - When extending the file, extend it in chunks of 32Kbytes.
10208      "fop=tef"- Truncate unused portions of file when closing file.
10209      "shr=nil"- Disallow file sharing while file is open.
10210  */
10211
10212 static FILE *
10213 freopen (fname, type, oldfile)
10214      char *fname;
10215      char *type;
10216      FILE *oldfile;
10217 {
10218 #undef  freopen /* Get back the REAL fopen routine */
10219   if (strcmp (type, "w") == 0)
10220     return freopen (fname, type, oldfile, "mbc=16", "deq=64", "fop=tef", "shr=nil");
10221   return freopen (fname, type, oldfile, "mbc=16");
10222 }
10223
10224 static FILE *
10225 fopen (fname, type)
10226      char *fname;
10227      char *type;
10228 {
10229 #undef fopen    /* Get back the REAL fopen routine */
10230   /* The gcc-vms-1.42 distribution's header files prototype fopen with two
10231      fixed arguments, which matches ANSI's specification but not VAXCRTL's
10232      pre-ANSI implementation.  This hack circumvents the mismatch problem.  */
10233   FILE *(*vmslib_fopen)() = (FILE *(*)()) fopen;
10234
10235   if (*type == 'w')
10236     return (*vmslib_fopen) (fname, type, "mbc=32",
10237                             "deq=64", "fop=tef", "shr=nil");
10238   else
10239     return (*vmslib_fopen) (fname, type, "mbc=32");
10240 }
10241
10242 static int 
10243 open (fname, flags, prot)
10244      char *fname;
10245      int flags;
10246      int prot;
10247 {
10248 #undef open     /* Get back the REAL open routine */
10249   return open (fname, flags, prot, "mbc=16", "deq=64", "fop=tef");
10250 }
10251 \f
10252 /* more VMS hackery */
10253 #include <fab.h>
10254 #include <nam.h>
10255
10256 extern unsigned long sys$parse(), sys$search();
10257
10258 /* Work around another library bug.  If a file is located via a searchlist,
10259    and if the device it's on is not the same device as the one specified
10260    in the first element of that searchlist, then both stat() and fstat()
10261    will fail to return info about it.  `errno' will be set to EVMSERR, and
10262    `vaxc$errno' will be set to SS$_NORMAL due yet another bug in stat()!
10263    We can get around this by fully parsing the filename and then passing
10264    that absolute name to stat().
10265
10266    Without this fix, we can end up failing to find header files, which is
10267    bad enough, but then compounding the problem by reporting the reason for
10268    failure as "normal successful completion."  */
10269
10270 #undef fstat    /* get back to library version */
10271
10272 static int
10273 VMS_fstat (fd, statbuf)
10274      int fd;
10275      struct stat *statbuf;
10276 {
10277   int result = fstat (fd, statbuf);
10278
10279   if (result < 0)
10280     {
10281       FILE *fp;
10282       char nambuf[NAM$C_MAXRSS+1];
10283
10284       if ((fp = fdopen (fd, "r")) != 0 && fgetname (fp, nambuf) != 0)
10285         result = VMS_stat (nambuf, statbuf);
10286       /* No fclose(fp) here; that would close(fd) as well.  */
10287     }
10288
10289   return result;
10290 }
10291
10292 static int
10293 VMS_stat (name, statbuf)
10294      const char *name;
10295      struct stat *statbuf;
10296 {
10297   int result = stat (name, statbuf);
10298
10299   if (result < 0)
10300     {
10301       struct FAB fab;
10302       struct NAM nam;
10303       char exp_nam[NAM$C_MAXRSS+1],  /* expanded name buffer for sys$parse */
10304            res_nam[NAM$C_MAXRSS+1];  /* resultant name buffer for sys$search */
10305
10306       fab = cc$rms_fab;
10307       fab.fab$l_fna = (char *) name;
10308       fab.fab$b_fns = (unsigned char) strlen (name);
10309       fab.fab$l_nam = (void *) &nam;
10310       nam = cc$rms_nam;
10311       nam.nam$l_esa = exp_nam,  nam.nam$b_ess = sizeof exp_nam - 1;
10312       nam.nam$l_rsa = res_nam,  nam.nam$b_rss = sizeof res_nam - 1;
10313       nam.nam$b_nop = NAM$M_PWD | NAM$M_NOCONCEAL;
10314       if (sys$parse (&fab) & 1)
10315         {
10316           if (sys$search (&fab) & 1)
10317             {
10318               res_nam[nam.nam$b_rsl] = '\0';
10319               result = stat (res_nam, statbuf);
10320             }
10321           /* Clean up searchlist context cached by the system.  */
10322           nam.nam$b_nop = NAM$M_SYNCHK;
10323           fab.fab$l_fna = 0,  fab.fab$b_fns = 0;
10324           (void) sys$parse (&fab);
10325         }
10326     }
10327
10328   return result;
10329 }
10330 #endif /* VMS */