OSDN Git Service

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