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