OSDN Git Service

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