OSDN Git Service

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