OSDN Git Service

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