OSDN Git Service

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