OSDN Git Service

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