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