OSDN Git Service

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