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