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