OSDN Git Service

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