OSDN Git Service

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