OSDN Git Service

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