OSDN Git Service

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