OSDN Git Service

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