OSDN Git Service

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