OSDN Git Service

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