OSDN Git Service

PR preprocessor/6521
[pf3gnuchains/gcc-fork.git] / gcc / tradcpp.c
1 /* C Compatible Compiler Preprocessor (CCCP)
2 Copyright (C) 1986, 1987, 1989, 2000, 2001 Free Software Foundation, Inc.
3                     Written by Paul Rubin, June 1986
4                     Adapted to ANSI C, Richard Stallman, Jan 1987
5                     Dusted off, polished, and adapted for use as traditional
6                     preprocessor only, Zack Weinberg, Jul 2000
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "version.h"
25 #include "cppdefault.h"
26 #include "tradcpp.h"
27 #include "mkdeps.h"
28 #include "intl.h"
29
30 typedef unsigned char U_CHAR;
31
32 /* Name under which this program was invoked.  */
33
34 static const char *progname;
35
36 /* Current maximum length of directory names in the search path
37    for include files.  (Altered as we get more of them.)  */
38
39 size_t max_include_len;
40
41 /* Nonzero means copy comments into the output file.  */
42
43 int put_out_comments = 0;
44
45 /* mkdeps.h opaque structure that encapsulates dependency information.  */
46 struct deps *deps;
47
48 /* Nonzero means print the names of included files rather than
49    the preprocessed output.  1 means just the #include "...",
50    2 means #include <...> as well.  */
51
52 int print_deps = 0;
53
54 /* Nonzero means print dummy targets for each header file.  */
55
56 int print_deps_phony_targets = 0;
57
58 /* If true, fopen (deps_file, "a") else fopen (deps_file, "w").  */
59
60 int deps_append = 0;
61
62 /* File name which deps are being written to.  This is 0 if deps are
63    being written to stdout.  */
64
65 const char *deps_file = 0;
66
67 /* Nonzero if missing .h files in -M output are assumed to be
68    generated files and not errors.  */
69
70 int deps_missing_files = 0;
71        
72 /* Nonzero means don't output line number information.  */
73
74 int no_line_commands;
75
76 /* Nonzero means inhibit output of the preprocessed text
77    and instead output the definitions of all user-defined macros
78    in a form suitable for use as input to cccp.  */
79
80 int dump_macros;
81
82 /* Nonzero means don't print warning messages.  -w.  */
83
84 int inhibit_warnings = 0;
85
86 /* Non-0 means don't output the preprocessed program.  */
87 int inhibit_output = 0;
88
89 /* Nonzero means chars are signed.  */
90 #if DEFAULT_SIGNED_CHAR
91 int flag_signed_char = 1;
92 #else
93 int flag_signed_char = 0;
94 #endif
95
96 /* Nonzero means warn if slash-star appears in a comment.  */
97
98 int warn_comments;
99
100 /* Nonzero causes output not to be done,
101    but directives such as #define that have side effects
102    are still obeyed.  */
103
104 int no_output;
105
106 /* Value of __USER_LABEL_PREFIX__.  Target-dependent, also controlled
107    by -f(no-)leading-underscore.  */
108 static const char *user_label_prefix;
109
110 /* I/O buffer structure.
111    The `fname' field is nonzero for source files and #include files
112    and for the dummy text used for -D and -U.
113    It is zero for rescanning results of macro expansion
114    and for expanding macro arguments.  */
115 #define INPUT_STACK_MAX 200
116 struct file_name_list;
117 struct file_buf {
118   const char *fname;
119   int lineno;
120   int length;
121   U_CHAR *buf;
122   U_CHAR *bufp;
123   /* Macro that this level is the expansion of.
124      Included so that we can reenable the macro
125      at the end of this level.  */
126   struct hashnode *macro;
127   /* Value of if_stack at start of this file.
128      Used to prohibit unmatched #endif (etc) in an include file.  */
129   struct if_stack *if_stack;
130   /* Object to be freed at end of input at this level.  */
131   U_CHAR *free_ptr;
132   /* Position to start scanning for #include_next in this file.  */
133   struct file_name_list *next_header_dir;
134 } instack[INPUT_STACK_MAX];
135
136 typedef struct file_buf FILE_BUF;
137
138 /* Current nesting level of input sources.
139    `instack[indepth]' is the level currently being read.  */
140 int indepth = -1;
141 #define CHECK_DEPTH(code) \
142   if (indepth >= (INPUT_STACK_MAX - 1))                                 \
143     {                                                                   \
144       error_with_line (line_for_error (instack[indepth].lineno),        \
145                        "macro or #include recursion too deep");         \
146       code;                                                             \
147     }
148
149 /* Current depth in #include directives that use <...>.  */
150 int system_include_depth = 0;
151
152 /* The output buffer.  Its LENGTH field is the amount of room allocated
153    for the buffer, not the number of chars actually present.  To get
154    that, subtract outbuf.buf from outbuf.bufp. */
155
156 #define OUTBUF_SIZE 10  /* initial size of output buffer */
157 FILE_BUF outbuf;
158
159 /* Grow output buffer OBUF points at
160    so it can hold at least NEEDED more chars.  */
161
162 #define check_expand(OBUF, NEEDED) do { \
163   if ((OBUF)->length - ((OBUF)->bufp - (OBUF)->buf) <= (NEEDED)) \
164     grow_outbuf ((OBUF), (NEEDED)); \
165  } while (0)
166
167 struct file_name_list
168   {
169     struct file_name_list *next;
170     const char *fname;
171   };
172
173 struct file_name_list *include = 0;     /* First dir to search */
174         /* First dir to search for <file> */
175 struct file_name_list *first_bracket_include = 0;
176 struct file_name_list *last_include = 0;        /* Last in chain */
177
178 /* List of included files that contained #once.  */
179 struct file_name_list *dont_repeat_files = 0;
180
181 /* List of other included files.  */
182 struct file_name_list *all_include_files = 0;
183 \f
184 /* Structure allocated for every #define.  For a simple replacement
185    such as
186         #define foo bar ,
187    nargs = -1, the `pattern' list is null, and the expansion is just
188    the replacement text.  Nargs = 0 means a functionlike macro with no args,
189    e.g.,
190        #define getchar() getc (stdin) .
191    When there are args, the expansion is the replacement text with the
192    args squashed out, and the reflist is a list describing how to
193    build the output from the input: e.g., "3 chars, then the 1st arg,
194    then 9 chars, then the 3rd arg, then 0 chars, then the 2nd arg".
195    The chars here come from the expansion.  Whatever is left of the
196    expansion after the last arg-occurrence is copied after that arg.
197    Note that the reflist can be arbitrarily long---
198    its length depends on the number of times the arguments appear in
199    the replacement text, not how many args there are.  Example:
200    #define f(x) x+x+x+x+x+x+x would have replacement text "++++++" and
201    pattern list
202      { (0, 1), (1, 1), (1, 1), ..., (1, 1), NULL }
203    where (x, y) means (nchars, argno). */
204
205 typedef struct definition DEFINITION;
206 struct definition {
207   int nargs;
208   int length;                   /* length of expansion string */
209   U_CHAR *expansion;
210   struct reflist {
211     struct reflist *next;
212     char stringify;             /* nonzero if this arg was preceded by a
213                                    # operator. */
214     char raw_before;            /* Nonzero if a ## operator before arg. */
215     char raw_after;             /* Nonzero if a ## operator after arg. */
216     int nchars;                 /* Number of literal chars to copy before
217                                    this arg occurrence.  */
218     int argno;                  /* Number of arg to substitute (origin-0) */
219   } *pattern;
220   /* Names of macro args, concatenated in reverse order
221      with comma-space between them.
222      The only use of this is that we warn on redefinition
223      if this differs between the old and new definitions.  */
224   const U_CHAR *argnames;
225 };
226
227 /* Chained list of answers to an assertion.  */
228 struct answer
229 {
230   struct answer *next;
231   const unsigned char *answer;
232   size_t len;
233 };
234
235 /* different kinds of things that can appear in the value field
236    of a hash node.  Actually, this may be useless now. */
237 union hashval {
238   const char *cpval;
239   DEFINITION *defn;
240   struct answer *answers;
241 };
242
243 /* The structure of a node in the hash table.  The hash table
244    has entries for all tokens defined by #define commands (type T_MACRO),
245    plus some special tokens like __LINE__ (these each have their own
246    type, and the appropriate code is run when that type of node is seen.
247    It does not contain control words like "#define", which are recognized
248    by a separate piece of code. */
249
250 /* different flavors of hash nodes --- also used in keyword table */
251 enum node_type {
252  T_DEFINE = 1,  /* `#define' */
253  T_INCLUDE,     /* `#include' */
254  T_INCLUDE_NEXT,/* `#include_next' */
255  T_IFDEF,       /* `#ifdef' */
256  T_IFNDEF,      /* `#ifndef' */
257  T_IF,          /* `#if' */
258  T_ELSE,        /* `#else' */
259  T_ELIF,        /* `#elif' */
260  T_UNDEF,       /* `#undef' */
261  T_LINE,        /* `#line' */
262  T_ENDIF,       /* `#endif' */
263  T_ERROR,       /* `#error' */
264  T_WARNING,     /* `#warning' */
265  T_ASSERT,      /* `#assert' */
266  T_UNASSERT,    /* `#unassert' */
267  T_SPECLINE,    /* special symbol `__LINE__' */
268  T_DATE,        /* `__DATE__' */
269  T_FILE,        /* `__FILE__' */
270  T_BASE_FILE,   /* `__BASE_FILE__' */
271  T_INCLUDE_LEVEL, /* `__INCLUDE_LEVEL__' */
272  T_VERSION,     /* `__VERSION__' */
273  T_TIME,        /* `__TIME__' */
274  T_CONST,       /* Constant value, used by `__STDC__' */
275  T_MACRO,       /* macro defined by `#define' */
276  T_SPEC_DEFINED, /* special `defined' macro for use in #if statements */
277  T_UNUSED       /* Used for something not defined.  */
278 };
279
280 struct hashnode {
281   struct hashnode *next;        /* double links for easy deletion */
282   struct hashnode *prev;
283   struct hashnode **bucket_hdr; /* also, a back pointer to this node's hash
284                                    chain is kept, in case the node is the head
285                                    of the chain and gets deleted. */
286   enum node_type type;          /* type of special token */
287   int length;                   /* length of token, for quick comparison */
288   U_CHAR *name;                 /* the actual name */
289   union hashval value;          /* pointer to expansion, or whatever */
290 };
291
292 typedef struct hashnode HASHNODE;
293
294 static HASHNODE *parse_assertion PARAMS ((const unsigned char *,
295                                           const unsigned char *,
296                                           struct answer **, int));
297 static struct answer **find_answer PARAMS ((HASHNODE *,
298                                             const struct answer *));
299 static int parse_answer PARAMS ((const unsigned char *, const unsigned char *,
300                                  struct answer **, int));
301 static unsigned char *canonicalize_text PARAMS ((const unsigned char *,
302                                                  const unsigned char *,
303                                                  const unsigned char **));
304
305 /* Some definitions for the hash table.  The hash function MUST be
306    computed as shown in hashf () below.  That is because the rescan
307    loop computes the hash value `on the fly' for most tokens,
308    in order to avoid the overhead of a lot of procedure calls to
309    the hashf () function.  Hashf () only exists for the sake of
310    politeness, for use when speed isn't so important. */
311
312 #define HASHSIZE 1403
313 HASHNODE *hashtab[HASHSIZE];
314 #define HASHSTEP(old, c) ((old << 2) + c)
315 #define MAKE_POS(v) (v & 0x7fffffff) /* make number positive */
316
317 /* `struct directive' defines one #-directive, including how to handle it.  */
318
319 struct directive {
320   const int length;             /* Length of name */
321   void (*const func) PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
322                                 /* Function to handle directive */
323   const char *const name;       /* Name of directive */
324   const enum node_type type;    /* Code which describes which directive. */
325 };
326
327 /* Last arg to output_line_command.  */
328 enum file_change_code {same_file, enter_file, leave_file};
329
330 /* This structure represents one parsed argument in a macro call.
331    `raw' points to the argument text as written (`raw_length' is its length).
332    `expanded' points to the argument's macro-expansion
333    (its length is `expand_length').
334    `stringified_length' is the length the argument would have
335    if stringified.
336    `free1' and `free2', if nonzero, point to blocks to be freed
337    when the macro argument data is no longer needed.  */
338
339 struct argdata {
340   U_CHAR *raw, *expanded;
341   int raw_length, expand_length;
342   int stringified_length;
343   U_CHAR *free1, *free2;
344   char newlines;
345   char comments;
346 };
347
348 /* The arglist structure is built by do_define to tell
349    collect_definition where the argument names begin.  That
350    is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
351    would contain pointers to the strings x, y, and z.
352    Collect_definition would then build a DEFINITION node,
353    with reflist nodes pointing to the places x, y, and z had
354    appeared.  So the arglist is just convenience data passed
355    between these two routines.  It is not kept around after
356    the current #define has been processed and entered into the
357    hash table. */
358
359 struct arglist {
360   struct arglist *next;
361   U_CHAR *name;
362   int length;
363   int argno;
364 };
365
366 /* Function prototypes.  */
367
368 static void do_define   PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
369 static void do_error    PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
370 static void do_warning  PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
371 static void do_line     PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
372 static void do_include  PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
373 static void do_include_next     PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
374 static void do_undef    PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
375 static void do_if       PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
376 static void do_ifdef    PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
377 static void do_ifndef   PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
378 static void do_else     PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
379 static void do_elif     PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
380 static void do_endif    PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
381 static void do_assert   PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
382 static void do_unassert PARAMS ((U_CHAR *, U_CHAR *, FILE_BUF *));
383 static void do_xifdef   PARAMS ((U_CHAR *, U_CHAR *, enum node_type));
384
385 static struct hashnode *install PARAMS ((const U_CHAR *, int, enum node_type, int));
386 static int hashf                 PARAMS ((const U_CHAR *, int, int));
387 static int compare_defs  PARAMS ((DEFINITION *, DEFINITION *));
388 static int comp_def_part         PARAMS ((int, const U_CHAR *, int,
389                                           const U_CHAR *, int, int));
390 static void delete_macro         PARAMS ((HASHNODE *));
391
392 /* First arg to v_message.  */
393 enum msgtype { MT_WARNING = 0, MT_ERROR, MT_FATAL };
394 static void v_message            PARAMS ((enum msgtype mtype, int line,
395                                           const char *msgid, va_list ap))
396      ATTRIBUTE_PRINTF (3, 0);
397
398 static int line_for_error        PARAMS ((int));
399
400 /* We know perfectly well which file this is, so we don't need to
401    use __FILE__.  */
402 #undef abort
403 #if (GCC_VERSION >= 2007)
404 #define abort() fancy_abort(__LINE__, __FUNCTION__)
405 #else
406 #define abort() fancy_abort(__LINE__, 0);
407 #endif
408
409 static void macroexpand         PARAMS ((HASHNODE *, FILE_BUF *));
410 static void special_symbol      PARAMS ((HASHNODE *, FILE_BUF *));
411 static void dump_all_macros     PARAMS ((void));
412 static void dump_defn_1         PARAMS ((const U_CHAR *, int, int));
413 static void dump_arg_n          PARAMS ((DEFINITION *, int));
414 static void conditional_skip    PARAMS ((FILE_BUF *, int, enum node_type));
415 static void skip_if_group       PARAMS ((FILE_BUF *, int));
416 static void output_line_command PARAMS ((FILE_BUF *, FILE_BUF *,
417                                          int, enum file_change_code));
418
419 static int eval_if_expression   PARAMS ((const U_CHAR *, int));
420
421 static void output_deps         PARAMS ((void));
422 static void initialize_builtins PARAMS ((void));
423 static void run_directive       PARAMS ((const char *, size_t,
424                                          enum node_type));
425 static void make_definition     PARAMS ((const char *));
426 static void make_undef          PARAMS ((const char *));
427 static void make_assertion      PARAMS ((const char *));
428
429 static void grow_outbuf         PARAMS ((FILE_BUF *, int));
430 static int handle_directive     PARAMS ((FILE_BUF *, FILE_BUF *));
431 static void process_include     PARAMS ((struct file_name_list *,
432                                          const U_CHAR *, int, int, FILE_BUF *));
433 static void fixup_newlines      PARAMS ((FILE_BUF *));
434 static void finclude            PARAMS ((int, const char *,
435                                          struct file_name_list *, FILE_BUF *));
436 static void init_dependency_output PARAMS ((void));
437 static void rescan              PARAMS ((FILE_BUF *, int));
438 static void newline_fix         PARAMS ((U_CHAR *));
439 static void name_newline_fix    PARAMS ((U_CHAR *));
440 static U_CHAR *macarg1          PARAMS ((U_CHAR *, const U_CHAR *, int *,
441                                          int *, int *));
442 static const char *macarg       PARAMS ((struct argdata *));
443 static int discard_comments     PARAMS ((U_CHAR *, int, int));
444 static int file_size_and_mode   PARAMS ((int, int *, long *));
445
446 static U_CHAR *skip_to_end_of_comment PARAMS ((FILE_BUF *, int *));
447 static U_CHAR *skip_quoted_string     PARAMS ((const U_CHAR *, const U_CHAR *,
448                                                int, int *, int *, int *));
449
450 int main                PARAMS ((int, char **));
451
452 /* Convenience.  Write U"string" to get an unsigned string constant.  */
453 #define U (const unsigned char *)
454
455 /* Here is the actual list of #-directives, most-often-used first.  */
456
457 static const struct directive directive_table[] = {
458   {  6, do_define,  "define",  T_DEFINE  },
459   {  7, do_include, "include", T_INCLUDE },
460   {  5, do_endif,   "endif",   T_ENDIF   },
461   {  5, do_ifdef,   "ifdef",   T_IFDEF   },
462   {  2, do_if,      "if",      T_IF,     },
463   {  4, do_else,    "else",    T_ELSE    },
464   {  6, do_ifndef,  "ifndef",  T_IFNDEF  },
465   {  5, do_undef,   "undef",   T_UNDEF   },
466   {  4, do_line,    "line",    T_LINE    },
467   {  4, do_elif,    "elif",    T_ELIF    },
468   {  5, do_error,   "error",   T_ERROR   },
469   {  7, do_warning, "warning", T_WARNING },
470   { 12, do_include_next, "include_next", T_INCLUDE_NEXT },
471   {  6, do_assert,  "assert",  T_ASSERT  },
472   {  8, do_unassert,"unassert",T_UNASSERT},
473   {  -1, 0, "", T_UNUSED},
474 };
475
476 #define SKIP_WHITE_SPACE(p) do { while (is_nvspace(*p)) p++; } while (0)
477 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space(*p)) p++; } while (0)
478   
479 int errors = 0;                 /* Error counter for exit code */
480
481 static FILE_BUF expand_to_temp_buffer PARAMS ((const U_CHAR *, const U_CHAR *, int));
482 static DEFINITION *collect_expansion  PARAMS ((U_CHAR *, U_CHAR *, int,
483                                                struct arglist *));
484
485 /* Stack of conditionals currently in progress
486    (including both successful and failing conditionals).  */
487
488 struct if_stack {
489   struct if_stack *next;        /* for chaining to the next stack frame */
490   const char *fname;            /* copied from input when frame is made */
491   int lineno;                   /* similarly */
492   int if_succeeded;             /* true if a leg of this if-group
493                                     has been passed through rescan */
494   enum node_type type;          /* type of last directive seen in this group */
495 };
496 typedef struct if_stack IF_STACK_FRAME;
497 IF_STACK_FRAME *if_stack = NULL;
498
499 /* Nonzero means -I- has been seen,
500    so don't look for #include "foo" the source-file directory.  */
501 int ignore_srcdir;
502
503 /* Pending directives.  */
504 enum pending_dir_t {PD_NONE = 0, PD_DEFINE, PD_UNDEF, PD_ASSERTION, PD_FILE};
505
506 typedef struct pending_dir pending_dir;
507 struct pending_dir
508 {
509   const char *arg;
510   enum pending_dir_t type;
511 };
512
513 int
514 main (argc, argv)
515      int argc;
516      char **argv;
517 {
518   int st_mode;
519   long st_size;
520   const char *in_fname, *out_fname;
521   int f, i;
522   FILE_BUF *fp;
523   pending_dir *pend = (pending_dir *) xcalloc (argc, sizeof (pending_dir));
524   int no_standard_includes = 0;
525
526   hex_init ();
527
528 #ifdef RLIMIT_STACK
529   /* Get rid of any avoidable limit on stack size.  */
530   {
531     struct rlimit rlim;
532
533     /* Set the stack limit huge so that alloca (particularly stringtab
534      * in dbxread.c) does not fail. */
535     getrlimit (RLIMIT_STACK, &rlim);
536     rlim.rlim_cur = rlim.rlim_max;
537     setrlimit (RLIMIT_STACK, &rlim);
538   }
539 #endif /* RLIMIT_STACK defined */
540
541   progname = argv[0];
542
543   in_fname = NULL;
544   out_fname = NULL;
545
546   no_line_commands = 0;
547   dump_macros = 0;
548   no_output = 0;
549
550   max_include_len = cpp_GCC_INCLUDE_DIR_len + 7;  /* ??? */
551
552   gcc_init_libintl ();
553
554   /* It's simplest to just create this struct whether or not it will
555      be needed.  */
556   deps = deps_init ();
557
558   /* Process switches and find input file name.  */
559
560   for (i = 1; i < argc; i++) {
561     if (argv[i][0] != '-') {
562       if (out_fname != NULL)
563         fatal ("usage: %s [switches] input output", argv[0]);
564       else if (in_fname != NULL)
565         out_fname = argv[i];
566       else
567         in_fname = argv[i];
568     } else {
569       int c = argv[i][1];
570
571       switch (c) {
572       case 'E':
573       case '$':
574         break;  /* Ignore for compatibility with ISO/extended cpp.  */
575
576       case 'l':
577         if (!strcmp (argv[i], "-lang-c++")
578             || !strcmp (argv[i], "-lang-objc++"))
579           fatal ("-traditional is not supported in C++");
580         else if (!strcmp (argv[i], "-lang-c89"))
581           fatal ("-traditional and -ansi are mutually exclusive");
582         else if (!strcmp (argv[i], "-lang-objc"))
583           pend[i].type = PD_DEFINE, pend[i].arg = "__OBJC__";
584         else if (!strcmp (argv[i], "-lang-asm"))
585           pend[i].type = PD_DEFINE, pend[i].arg = "__ASSEMBLER__";
586         else if (!strcmp (argv[i], "-lang-fortran"))
587           pend[i].type = PD_DEFINE, pend[i].arg = "_LANGUAGE_FORTRAN";
588         /* All other possibilities ignored.  */
589         break;
590
591       case 'i':
592         if (!strcmp (argv[i], "-include"))
593           {
594             if (i + 1 == argc)
595               fatal ("filename missing after -i option");
596             else
597               pend[i].type = PD_FILE, pend[i].arg = argv[i + 1], i++;
598           }
599         else if (!strcmp (argv[i], "-iprefix"))
600           i++; /* Ignore for compatibility */
601         else if (!strcmp (argv[i], "-isystem")
602                  || !strcmp (argv[i], "-iwithprefix")
603                  || !strcmp (argv[i], "-iwithprefixbefore")
604                  || !strcmp (argv[i], "-idirafter"))
605           goto add_include;  /* best we can do */
606           
607         break;
608
609       case 'o':
610         if (out_fname != NULL)
611           fatal ("output filename specified twice");
612         if (i + 1 == argc)
613           fatal ("filename missing after -o option");
614         out_fname = argv[++i];
615         if (!strcmp (out_fname, "-"))
616           out_fname = "";
617         break;
618
619       case 'w':
620         inhibit_warnings = 1;
621         break;
622
623       case 'W':
624         if (!strcmp (argv[i], "-Wcomments"))
625           warn_comments = 1;
626         else if (!strcmp (argv[i], "-Wcomment"))
627           warn_comments = 1;
628         else if (!strcmp (argv[i], "-Wall")) {
629           warn_comments = 1;
630         }
631         break;
632
633       case 'f':
634         if (!strcmp (argv[i], "-fleading-underscore"))
635           user_label_prefix = "_";
636         else if (!strcmp (argv[i], "-fno-leading-underscore"))
637           user_label_prefix = "";
638         else if (!strcmp (argv[i], "-fsigned-char"))
639           flag_signed_char = 1;
640         else if (!strcmp (argv[i], "-funsigned-char"))
641           flag_signed_char = 0;
642         break;
643
644       case 'M':
645         {
646           char *p = NULL;
647
648           /* -MD and -MMD for tradcpp are deprecated and undocumented
649              (use -M or -MM with -MF instead), and probably should be
650              removed with the next major GCC version.  For the moment
651              we allow these for the benefit of Automake 1.4, which
652              uses these when dependency tracking is enabled.  Automake
653              1.5 will fix this.  */
654           if (!strncmp (argv[i], "-MD", 3)) {
655             p = argv[i] + 3;
656             print_deps = 2;
657           } else if (!strncmp (argv[i], "-MMD", 4)) {
658             p = argv[i] + 4;
659             print_deps = 1;
660           } else if (!strcmp (argv[i], "-M")) {
661             print_deps = 2;
662           } else if (!strcmp (argv[i], "-MM")) {
663             print_deps = 1;
664           } else if (!strcmp (argv[i], "-MG")) {
665             deps_missing_files = 1;
666           } else if (!strcmp (argv[i], "-MF")) {
667             p = argv[i] + 3;
668           } else if (!strcmp (argv[i], "-MP")) {
669             print_deps_phony_targets = 1;
670           } else if (!strcmp (argv[i], "-MQ") || !strcmp (argv[i], "-MT")) {
671             /* Add a target.  -MQ quotes for Make.  */
672             const char *tgt = argv[i] + 3;
673             int quoted = argv[i][2] == 'Q';
674
675             if (*tgt == '\0' && i + 1 == argc)
676               fatal ("target missing after %s option", argv[i]);
677             else
678               {
679                 if (*tgt == '\0')
680                   tgt = argv[++i];
681               
682                 deps_add_target (deps, tgt, quoted);
683               }
684           }
685
686           if (p) {
687             if (*p)
688               deps_file = p;
689             else if (i + 1 == argc)
690               fatal ("filename missing after %s option", argv[i]);
691             else
692               deps_file = argv[++i];
693           }
694         }
695         break;
696
697       case 'd':
698         dump_macros = 1;
699         no_output = 1;
700         break;
701
702       case 'v':
703         fprintf (stderr, "GNU traditional CPP version %s\n", version_string);
704         break;
705
706       case 'D':
707       case 'U':
708       case 'A':
709         {
710           char *p;
711
712           if (argv[i][2] != 0)
713             p = argv[i] + 2;
714           else if (i + 1 == argc)
715             fatal ("macro name missing after -%c option", c);
716           else
717             p = argv[++i];
718
719           if (c == 'D')
720             pend[i].type = PD_DEFINE;
721           else if (c == 'U')
722             pend[i].type = PD_UNDEF;
723           else
724             pend[i].type = PD_ASSERTION;
725           pend[i].arg = p;
726         }
727         break;
728
729       case 'C':
730         put_out_comments = 1;
731         break;
732
733       case 'p':
734         if (!strcmp (argv[i], "-pedantic"))
735           fatal ("-pedantic and -traditional are mutually exclusive");
736         break;
737
738       case 't':
739         if (!strcmp (argv[i], "-trigraphs"))
740           fatal ("-trigraphs and -traditional are mutually exclusive");
741         break;
742
743       case 'P':
744         no_line_commands = 1;
745         break;
746
747       case 'I':                 /* Add directory to path for includes.  */
748       add_include:
749         {
750           struct file_name_list *dirtmp;
751
752           if (! ignore_srcdir && !strcmp (argv[i] + 2, "-"))
753             ignore_srcdir = 1;
754           else {
755             dirtmp = (struct file_name_list *)
756               xmalloc (sizeof (struct file_name_list));
757             dirtmp->next = 0;           /* New one goes on the end */
758             if (include == 0)
759               include = dirtmp;
760             else
761               last_include->next = dirtmp;
762             last_include = dirtmp;      /* Tail follows the last one */
763             if (argv[i][1] == 'I' && argv[i][2] != 0)
764               dirtmp->fname = argv[i] + 2;
765             else if (i + 1 == argc)
766               fatal ("directory name missing after -I option");
767             else
768               dirtmp->fname = argv[++i];
769             if (strlen (dirtmp->fname) > max_include_len)
770               max_include_len = strlen (dirtmp->fname);
771             if (ignore_srcdir && first_bracket_include == 0)
772               first_bracket_include = dirtmp;
773             }
774         }
775         break;
776
777       case 'n':
778         /* -nostdinc causes no default include directories.
779            You must specify all include-file directories with -I.  */
780         no_standard_includes = 1;
781         break;
782
783       case 'q':
784         /* Accept -quiet silently.  */
785         break;
786
787       case '\0': /* JF handle '-' as file name meaning stdin or stdout */
788         if (in_fname == NULL) {
789           in_fname = "";
790           break;
791         } else if (out_fname == NULL) {
792           out_fname = "";
793           break;
794         }       /* else fall through into error */
795
796       default:
797         fatal ("invalid option `%s'", argv[i]);
798       }
799     }
800   }
801
802   init_dependency_output ();
803
804   /* After checking the environment variables, check if -M or -MM has
805      not been specified, but other -M options have.  */
806   if (print_deps == 0
807       && (deps_missing_files || deps_file || print_deps_phony_targets))
808     fatal ("you must additionally specify either -M or -MM");
809
810   if (user_label_prefix == 0)
811     user_label_prefix = USER_LABEL_PREFIX;
812
813   if (print_deps)
814     {
815       /* Set the default target (if there is none already), and
816          the dependency on the main file.  */
817       deps_add_default_target (deps, in_fname);
818
819       deps_add_dep (deps, in_fname);
820     }
821
822   /* Install __LINE__, etc.  Must follow option processing.  */
823   initialize_builtins ();
824
825   /* Do defines specified with -D and undefines specified with -U.  */
826   for (i = 1; i < argc; i++)
827     if (pend[i].type == PD_DEFINE)
828       make_definition (pend[i].arg);
829     else if (pend[i].type == PD_UNDEF)
830       make_undef (pend[i].arg);
831     else if (pend[i].type == PD_ASSERTION)
832       make_assertion (pend[i].arg);
833
834   /* Unless -fnostdinc,
835      tack on the standard include file dirs to the specified list */
836   if (!no_standard_includes) {
837     const struct default_include *di;
838     struct file_name_list *old_last_include = last_include;
839     struct file_name_list *dirtmp;
840     for (di = cpp_include_defaults; di->fname; di++) {
841       if (di->cplusplus)
842         continue;
843       dirtmp = (struct file_name_list *)
844         xmalloc (sizeof (struct file_name_list));
845       dirtmp->next = 0;         /* New one goes on the end */
846       if (include == 0)
847         include = dirtmp;
848       else
849         last_include->next = dirtmp;
850       last_include = dirtmp;    /* Tail follows the last one */
851       dirtmp->fname = di->fname;
852       if (strlen (dirtmp->fname) > max_include_len)
853         max_include_len = strlen (dirtmp->fname);
854     }
855
856     if (ignore_srcdir && first_bracket_include == 0)
857       first_bracket_include = old_last_include->next;
858   }
859
860   /* Initialize output buffer */
861
862   outbuf.buf = (U_CHAR *) xmalloc (OUTBUF_SIZE);
863   outbuf.bufp = outbuf.buf;
864   outbuf.length = OUTBUF_SIZE;
865
866   /* Scan the -i files before the main input.
867      Much like #including them, but with no_output set
868      so that only their macro definitions matter.  */
869
870   no_output++;
871   indepth++;
872   for (i = 1; i < argc; i++)
873     if (pend[i].type == PD_FILE)
874       {
875         int fd = open (pend[i].arg, O_RDONLY, 0666);
876         if (fd < 0)
877           {
878             perror_with_name (pend[i].arg);
879             return FATAL_EXIT_CODE;
880           }
881
882         /* For -M, add this file to the dependencies.  */
883         if (print_deps)
884           deps_add_dep (deps, pend[i].arg);
885
886         finclude (fd, pend[i].arg, 0, &outbuf);
887       }
888   indepth--;
889   no_output--;
890
891   /* Pending directives no longer needed.  */
892   free ((PTR) pend);
893
894   /* Create an input stack level for the main input file
895      and copy the entire contents of the file into it.  */
896
897   fp = &instack[++indepth];
898
899   /* JF check for stdin */
900   if (in_fname == NULL || *in_fname == 0) {
901     in_fname = "";
902     f = 0;
903   } else if ((f = open (in_fname, O_RDONLY, 0666)) < 0)
904     goto sys_error;
905
906   if (file_size_and_mode (f, &st_mode, &st_size))
907     goto sys_error;
908   fp->fname = in_fname;
909   fp->lineno = 1;
910   /* JF all this is mine about reading pipes and ttys */
911   if (!S_ISREG (st_mode)) {
912     /* Read input from a file that is not a normal disk file.
913        We cannot preallocate a buffer with the correct size,
914        so we must read in the file a piece at the time and make it bigger.  */
915     int size;
916     int bsize;
917     int cnt;
918     U_CHAR *bufp;
919
920     bsize = 2000;
921     size = 0;
922     fp->buf = (U_CHAR *) xmalloc (bsize + 2);
923     bufp = fp->buf;
924     for (;;) {
925       cnt = read (f, bufp, bsize - size);
926       if (cnt < 0) goto sys_error;      /* error! */
927       if (cnt == 0) break;              /* End of file */
928       size += cnt;
929       bufp += cnt;
930       if (bsize == size) {              /* Buffer is full! */
931         bsize *= 2;
932         fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
933         bufp = fp->buf + size;  /* May have moved */
934       }
935     }
936     fp->length = size;
937   } else {
938     /* Read a file whose size we can determine in advance.
939        For the sake of VMS, st_size is just an upper bound.  */
940     long i;
941     fp->length = 0;
942     fp->buf = (U_CHAR *) xmalloc (st_size + 2);
943
944     while (st_size > 0) {
945       i = read (f, fp->buf + fp->length, st_size);
946       if (i <= 0) {
947         if (i == 0) break;
948         goto sys_error;
949       }
950       fp->length += i;
951       st_size -= i;
952     }
953   }
954   fp->bufp = fp->buf;
955   fp->if_stack = if_stack;
956   fixup_newlines (fp);
957
958   /* Make sure data ends with a newline.  And put a null after it.  */
959
960   if (fp->length > 0 && fp->buf[fp->length-1] != '\n')
961     fp->buf[fp->length++] = '\n';
962   fp->buf[fp->length] = '\0';
963   
964   /* Now that we know the input file is valid, open the output.  */
965
966   if (!out_fname || !strcmp (out_fname, ""))
967     out_fname = "stdout";
968   else if (! freopen (out_fname, "w", stdout))
969     pfatal_with_name (out_fname);
970
971   output_line_command (fp, &outbuf, 0, same_file);
972
973   /* Scan the input, processing macros and directives.  */
974
975   rescan (&outbuf, 0);
976
977   /* Now we have processed the entire input
978      Write whichever kind of output has been requested.  */
979
980
981   if (dump_macros)
982     dump_all_macros ();
983   else if (! inhibit_output)
984     if (write (fileno (stdout), outbuf.buf, outbuf.bufp - outbuf.buf) < 0)
985       fatal ("I/O error on output");
986
987   /* Don't write the deps file if preprocessing has failed.  */
988   if (print_deps && errors == 0)
989     output_deps ();
990
991   /* Destruct the deps object.  */
992   deps_free (deps);
993
994   if (ferror (stdout))
995     fatal ("I/O error on output");
996
997   if (errors)
998     exit (FATAL_EXIT_CODE);
999   exit (SUCCESS_EXIT_CODE);
1000
1001  sys_error:
1002   pfatal_with_name (in_fname);
1003 }
1004
1005 /* Set up dependency-file output.  */
1006 static void
1007 init_dependency_output ()
1008 {
1009   char *spec, *s, *output_file;
1010
1011   /* Either of two environment variables can specify output of deps.
1012      Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
1013      where OUTPUT_FILE is the file to write deps info to
1014      and DEPS_TARGET is the target to mention in the deps.  */
1015
1016   if (print_deps == 0)
1017     {
1018       spec = getenv ("DEPENDENCIES_OUTPUT");
1019       if (spec)
1020         print_deps = 1;
1021       else
1022         {
1023           spec = getenv ("SUNPRO_DEPENDENCIES");
1024           if (spec)
1025             print_deps = 2;
1026           else
1027             return;
1028         }
1029
1030       /* Find the space before the DEPS_TARGET, if there is one.  */
1031       s = strchr (spec, ' ');
1032       if (s)
1033         {
1034           /* Let the caller perform MAKE quoting.  */
1035           deps_add_target (deps, s + 1, 0);
1036           output_file = (char *) xmalloc (s - spec + 1);
1037           memcpy (output_file, spec, s - spec);
1038           output_file[s - spec] = 0;
1039         }
1040       else
1041         output_file = spec;
1042
1043       /* Command line overrides environment variables.  */
1044       if (deps_file == 0)
1045         deps_file = output_file;
1046       deps_append = 1;
1047     }
1048
1049   /* If dependencies go to standard output, or -MG is used, we should
1050      suppress output.  The user may be requesting other stuff to
1051      stdout, with -dM, -v etc.  We let them shoot themselves in the
1052      foot.  */
1053   if (deps_file == 0 || deps_missing_files)
1054     inhibit_output = 1;
1055 }
1056
1057 /* Use mkdeps.c to output dependency information.  */
1058 static void
1059 output_deps ()
1060 {
1061   /* Stream on which to print the dependency information.  */
1062   FILE *deps_stream = 0;
1063   const char *const deps_mode = deps_append ? "a" : "w";
1064
1065   if (deps_file == 0)
1066     deps_stream = stdout;
1067   else
1068     {
1069       deps_stream = fopen (deps_file, deps_mode);
1070       if (deps_stream == 0)
1071         {
1072           error_from_errno (deps_file);
1073           return;
1074         }
1075     }
1076
1077   deps_write (deps, deps_stream, 72);
1078
1079   if (print_deps_phony_targets)
1080     deps_phony_targets (deps, deps_stream);
1081
1082   /* Don't close stdout.  */
1083   if (deps_file)
1084     {
1085       if (ferror (deps_stream) || fclose (deps_stream) != 0)
1086         fatal ("I/O error on output");
1087     }
1088 }
1089
1090 /* Move all backslash-newline pairs out of embarrassing places.
1091    Exchange all such pairs following BP
1092    with any potentially-embarrasing characters that follow them.
1093    Potentially-embarrassing characters are / and *
1094    (because a backslash-newline inside a comment delimiter
1095    would cause it not to be recognized).  */
1096 static void
1097 newline_fix (bp)
1098      U_CHAR *bp;
1099 {
1100   U_CHAR *p = bp;
1101   int count = 0;
1102
1103   /* First count the backslash-newline pairs here.  */
1104
1105   while (*p++ == '\\' && *p++ == '\n')
1106     count++;
1107
1108   p = bp + count * 2;
1109
1110   /* Exit if what follows the backslash-newlines is not embarrassing.  */
1111
1112   if (count == 0 || (*p != '/' && *p != '*'))
1113     return;
1114
1115   /* Copy all potentially embarrassing characters
1116      that follow the backslash-newline pairs
1117      down to where the pairs originally started.  */
1118
1119   while (*p == '*' || *p == '/')
1120     *bp++ = *p++;
1121
1122   /* Now write the same number of pairs after the embarrassing chars.  */
1123   while (count-- > 0) {
1124     *bp++ = '\\';
1125     *bp++ = '\n';
1126   }
1127 }
1128
1129 /* Like newline_fix but for use within a directive-name.
1130    Move any backslash-newlines up past any following symbol constituents.  */
1131 static void
1132 name_newline_fix (bp)
1133      U_CHAR *bp;
1134 {
1135   U_CHAR *p = bp;
1136   int count = 0;
1137
1138   /* First count the backslash-newline pairs here.  */
1139
1140   while (*p++ == '\\' && *p++ == '\n')
1141     count++;
1142
1143   p = bp + count * 2;
1144
1145   /* What follows the backslash-newlines is not embarrassing.  */
1146
1147   if (count == 0 || !is_idchar (*p))
1148     return;
1149
1150   /* Copy all potentially embarrassing characters
1151      that follow the backslash-newline pairs
1152      down to where the pairs originally started.  */
1153
1154   while (is_idchar (*p))
1155     *bp++ = *p++;
1156
1157   /* Now write the same number of pairs after the embarrassing chars.  */
1158   while (count-- > 0) {
1159     *bp++ = '\\';
1160     *bp++ = '\n';
1161   }
1162 }
1163 \f
1164 /*
1165  * The main loop of the program.
1166  *
1167  * Read characters from the input stack, transferring them to the
1168  * output buffer OP.
1169  *
1170  * Macros are expanded and push levels on the input stack.
1171  * At the end of such a level it is popped off and we keep reading.
1172  * At the end of any other kind of level, we return.
1173  * #-directives are handled, except within macros.
1174  *
1175  * If OUTPUT_MARKS is nonzero, keep Newline markers found in the input
1176  * and insert them when appropriate.  This is set while scanning macro
1177  * arguments before substitution.  It is zero when scanning for final output.
1178  *   There are three types of Newline markers:
1179  *   * Newline -  follows a macro name that was not expanded
1180  *     because it appeared inside an expansion of the same macro.
1181  *     This marker prevents future expansion of that identifier.
1182  *     When the input is rescanned into the final output, these are deleted.
1183  *     These are also deleted by ## concatenation.
1184  *   * Newline Space (or Newline and any other whitespace character)
1185  *     stands for a place that tokens must be separated or whitespace
1186  *     is otherwise desirable, but where the ANSI standard specifies there
1187  *     is no whitespace.  This marker turns into a Space (or whichever other
1188  *     whitespace char appears in the marker) in the final output,
1189  *     but it turns into nothing in an argument that is stringified with #.
1190  *     Such stringified arguments are the only place where the ANSI standard
1191  *     specifies with precision that whitespace may not appear.
1192  *
1193  * During this function, IP->bufp is kept cached in IBP for speed of access.
1194  * Likewise, OP->bufp is kept in OBP.  Before calling a subroutine
1195  * IBP, IP and OBP must be copied back to memory.  IP and IBP are
1196  * copied back with the RECACHE macro.  OBP must be copied back from OP->bufp
1197  * explicitly, and before RECACHE, since RECACHE uses OBP.
1198  */
1199
1200 static void
1201 rescan (op, output_marks)
1202      FILE_BUF *op;
1203      int output_marks;
1204 {
1205   /* Character being scanned in main loop.  */
1206   U_CHAR c;
1207
1208   /* Length of pending accumulated identifier.  */
1209   int ident_length = 0;
1210
1211   /* Hash code of pending accumulated identifier.  */
1212   int hash = 0;
1213
1214   /* Current input level (&instack[indepth]).  */
1215   FILE_BUF *ip;
1216
1217   /* Pointer for scanning input.  */
1218   U_CHAR *ibp;
1219
1220   /* Pointer to end of input.  End of scan is controlled by LIMIT.  */
1221   U_CHAR *limit;
1222
1223   /* Pointer for storing output.  */
1224   U_CHAR *obp;
1225
1226   /* REDO_CHAR is nonzero if we are processing an identifier
1227      after backing up over the terminating character.
1228      Sometimes we process an identifier without backing up over
1229      the terminating character, if the terminating character
1230      is not special.  Backing up is done so that the terminating character
1231      will be dispatched on again once the identifier is dealt with.  */
1232   int redo_char = 0;
1233
1234   /* 1 if within an identifier inside of which a concatenation
1235      marker (Newline -) has been seen.  */
1236   int concatenated = 0;
1237
1238   /* While scanning a comment or a string constant,
1239      this records the line it started on, for error messages.  */
1240   int start_line;
1241
1242   /* Record position of last `real' newline.  */
1243   U_CHAR *beg_of_line;
1244
1245   /* This has to be a global bacause of RECACHE.  */
1246   U_CHAR *obufp_before_macroname = NULL;
1247
1248 /* Pop the innermost input stack level, assuming it is a macro expansion.  */
1249
1250 #define POPMACRO \
1251 do { ip->macro->type = T_MACRO;         \
1252      if (ip->free_ptr) free (ip->free_ptr);     \
1253      --indepth; } while (0)
1254
1255 /* Reload `rescan's local variables that describe the current
1256    level of the input stack.  */
1257
1258 #define RECACHE  \
1259 do { ip = &instack[indepth];            \
1260      ibp = ip->bufp;                    \
1261      limit = ip->buf + ip->length;      \
1262      op->bufp = obp;                    \
1263      check_expand (op, limit - ibp);    \
1264      beg_of_line = 0;                   \
1265      obufp_before_macroname += op->bufp - obp;  \
1266      obp = op->bufp; } while (0)
1267
1268   if (no_output && instack[indepth].fname != 0)
1269     skip_if_group (&instack[indepth], 1);
1270
1271   obp = op->bufp;
1272   RECACHE;
1273   beg_of_line = ibp;
1274
1275   /* Our caller must always put a null after the end of
1276      the input at each input stack level.  */
1277   if (*limit != 0)
1278     abort ();
1279
1280   while (1) {
1281     c = *ibp++;
1282     *obp++ = c;
1283
1284     switch (c) {
1285     case '\\':
1286       if (ibp >= limit)
1287         break;
1288       if (*ibp == '\n') {
1289         /* Always merge lines ending with backslash-newline,
1290            even in middle of identifier.  */
1291         ++ibp;
1292         ++ip->lineno;
1293         --obp;          /* remove backslash from obuf */
1294         break;
1295       }
1296       /* Otherwise, backslash suppresses specialness of following char,
1297          so copy it here to prevent the switch from seeing it.
1298          But first get any pending identifier processed.  */
1299       if (ident_length > 0)
1300         goto specialchar;
1301       *obp++ = *ibp++;
1302       break;
1303
1304     case '#':
1305       /* If this is expanding a macro definition, don't recognize
1306          preprocessor directives.  */
1307       if (ip->macro != 0)
1308         goto randomchar;
1309       if (ident_length)
1310         goto specialchar;
1311
1312       /* # keyword: a # must be the first char on the line */
1313       if (beg_of_line == 0)
1314         goto randomchar;
1315       if (beg_of_line + 1 != ibp)
1316         goto randomchar;
1317
1318       /* This # can start a directive.  */
1319
1320       --obp;            /* Don't copy the '#' */
1321
1322       ip->bufp = ibp;
1323       op->bufp = obp;
1324       if (! handle_directive (ip, op)) {
1325 #ifdef USE_C_ALLOCA
1326         alloca (0);
1327 #endif
1328         /* Not a known directive: treat it as ordinary text.
1329            IP, OP, IBP, etc. have not been changed.  */
1330         if (no_output && instack[indepth].fname) {
1331           /* If not generating expanded output,
1332              what we do with ordinary text is skip it.
1333              Discard everything until next # directive.  */
1334           skip_if_group (&instack[indepth], 1);
1335           RECACHE;
1336           beg_of_line = ibp;
1337           break;
1338         }
1339         ++obp;          /* Copy the '#' after all */
1340         goto randomchar;
1341       }
1342 #ifdef USE_C_ALLOCA
1343       alloca (0);
1344 #endif
1345       /* A # directive has been successfully processed.  */
1346       /* If not generating expanded output, ignore everything until
1347          next # directive.  */
1348       if (no_output && instack[indepth].fname)
1349         skip_if_group (&instack[indepth], 1);
1350       obp = op->bufp;
1351       RECACHE;
1352       beg_of_line = ibp;
1353       break;
1354
1355     case '\"':                  /* skip quoted string */
1356     case '\'':
1357       /* A single quoted string is treated like a double -- some
1358          programs (e.g., troff) are perverse this way */
1359
1360       if (ident_length)
1361         goto specialchar;
1362
1363       start_line = ip->lineno;
1364
1365       /* Skip ahead to a matching quote.  */
1366
1367       while (1) {
1368         if (ibp >= limit) {
1369           if (ip->macro != 0) {
1370             /* try harder: this string crosses a macro expansion boundary */
1371             POPMACRO;
1372             RECACHE;
1373             continue;
1374           }
1375           break;
1376         }
1377         *obp++ = *ibp;
1378         switch (*ibp++) {
1379         case '\n':
1380           ++ip->lineno;
1381           ++op->lineno;
1382           /* Traditionally, end of line ends a string constant with no error.
1383              So exit the loop and record the new line.  */
1384           beg_of_line = ibp;
1385           goto while2end;
1386
1387         case '\\':
1388           if (ibp >= limit)
1389             break;
1390           if (*ibp == '\n') {
1391             /* Backslash newline is replaced by nothing at all,
1392                but keep the line counts correct.  */
1393             --obp;
1394             ++ibp;
1395             ++ip->lineno;
1396           } else {
1397             /* ANSI stupidly requires that in \\ the second \
1398                is *not* prevented from combining with a newline.  */
1399             while (*ibp == '\\' && ibp[1] == '\n') {
1400               ibp += 2;
1401               ++ip->lineno;
1402             }
1403             *obp++ = *ibp++;
1404           }
1405           break;
1406
1407         case '\"':
1408         case '\'':
1409           if (ibp[-1] == c)
1410             goto while2end;
1411           break;
1412         }
1413       }
1414     while2end:
1415       break;
1416
1417     case '/':
1418       if (*ibp == '\\' && ibp[1] == '\n')
1419         newline_fix (ibp);
1420       /* Don't look for comments inside a macro definition.  */
1421       if (ip->macro != 0)
1422         goto randomchar;
1423       /* A comment constitutes white space, so it can terminate an identifier.
1424          Process the identifier, if any.  */
1425       if (ident_length)
1426         goto specialchar;
1427
1428       if (*ibp != '*')
1429         goto randomchar;
1430
1431       /* We have a comment.  Skip it, optionally copying it to output.  */
1432
1433       start_line = ip->lineno;
1434
1435       ++ibp;                    /* Skip the star. */
1436
1437       /* In K+R C, a comment is equivalent to nothing.  Note that we
1438           already output the slash; we might not want it.  */
1439       if (! put_out_comments)
1440         obp--;
1441       else
1442         *obp++ = '*';
1443
1444       {
1445         U_CHAR *before_bp = ibp;
1446
1447         while (ibp < limit) {
1448           switch (*ibp++) {
1449           case '/':
1450             if (warn_comments && ibp < limit && *ibp == '*')
1451               warning("`/*' within comment");
1452             break;
1453           case '*':
1454             if (*ibp == '\\' && ibp[1] == '\n')
1455               newline_fix (ibp);
1456             if (ibp >= limit || *ibp == '/')
1457               goto comment_end;
1458             break;
1459           case '\n':
1460             ++ip->lineno;
1461             /* Copy the newline into the output buffer, in order to
1462                avoid the pain of a #line every time a multiline comment
1463                is seen.  */
1464             if (!put_out_comments)
1465               *obp++ = '\n';
1466             ++op->lineno;
1467           }
1468         }
1469       comment_end:
1470
1471         if (ibp >= limit)
1472           error_with_line (line_for_error (start_line),
1473                            "unterminated comment");
1474         else {
1475           ibp++;
1476           if (put_out_comments) {
1477             memcpy (obp, before_bp, ibp - before_bp);
1478             obp += ibp - before_bp;
1479           }
1480         }
1481       }
1482       break;
1483
1484     case '0': case '1': case '2': case '3': case '4':
1485     case '5': case '6': case '7': case '8': case '9':
1486       /* If digit is not part of identifier, it starts a number,
1487          which means that following letters are not an identifier.
1488          "0x5" does not refer to an identifier "x5".
1489          So copy all alphanumerics that follow without accumulating
1490          as an identifier.  Periods also, for sake of "3.e7".  */
1491
1492       if (ident_length == 0) {
1493         while (ibp < limit) {
1494           while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
1495             ++ip->lineno;
1496             ibp += 2;
1497           }
1498           c = *ibp++;
1499           if (! ISIDNUM (c) && c != '.') {
1500             --ibp;
1501             break;
1502           }
1503           *obp++ = c;
1504           /* A sign can be part of a preprocessing number
1505              if it follows an e.  */
1506           if (c == 'e' || c == 'E') {
1507             while (ibp < limit && ibp[0] == '\\' && ibp[1] == '\n') {
1508               ++ip->lineno;
1509               ibp += 2;
1510             }
1511             if (ibp < limit && (*ibp == '+' || *ibp == '-')) {
1512               *obp++ = *ibp++;
1513               /* Traditional C does not let the token go past the sign.  */
1514               break;
1515             }
1516           }
1517         }
1518         break;
1519       }
1520       /* fall through */
1521
1522     case '_':
1523     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1524     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1525     case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1526     case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1527     case 'y': case 'z':
1528     case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1529     case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1530     case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1531     case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1532     case 'Y': case 'Z':
1533       ident_length++;
1534       /* Compute step of hash function, to avoid a proc call on every token */
1535       hash = HASHSTEP (hash, c);
1536       break;
1537
1538     case '\n':
1539       /* If reprocessing a macro expansion, newline is a special marker.  */
1540       if (ip->macro != 0) {
1541         /* Newline White is a "funny space" to separate tokens that are
1542            supposed to be separate but without space between.
1543            Here White means any horizontal whitespace character.
1544            Newline - marks a recursive macro use that is not
1545            supposed to be expandable.  */
1546
1547         if (*ibp == '-') {
1548           /* Newline - inhibits expansion of preceding token.
1549              If expanding a macro arg, we keep the newline -.
1550              In final output, it is deleted.  */
1551           if (! concatenated) {
1552             ident_length = 0;
1553             hash = 0;
1554           }
1555           ibp++;
1556           if (!output_marks) {
1557             obp--;
1558           } else {
1559             /* If expanding a macro arg, keep the newline -.  */
1560             *obp++ = '-';
1561           }
1562         } else if (is_space (*ibp)) {
1563           /* Newline Space does not prevent expansion of preceding token
1564              so expand the preceding token and then come back.  */
1565           if (ident_length > 0)
1566             goto specialchar;
1567
1568           /* If generating final output, newline space makes a space.  */
1569           if (!output_marks) {
1570             obp[-1] = *ibp++;
1571             /* And Newline Newline makes a newline, so count it.  */
1572             if (obp[-1] == '\n')
1573               op->lineno++;
1574           } else {
1575             /* If expanding a macro arg, keep the newline space.
1576                If the arg gets stringified, newline space makes nothing.  */
1577             *obp++ = *ibp++;
1578           }
1579         } else abort ();        /* Newline followed by something random?  */
1580         break;
1581       }
1582
1583       /* If there is a pending identifier, handle it and come back here.  */
1584       if (ident_length > 0)
1585         goto specialchar;
1586
1587       beg_of_line = ibp;
1588
1589       /* Update the line counts and output a #line if necessary.  */
1590       ++ip->lineno;
1591       ++op->lineno;
1592       if (ip->lineno != op->lineno) {
1593         op->bufp = obp;
1594         output_line_command (ip, op, 1, same_file);
1595         check_expand (op, ip->length - (ip->bufp - ip->buf));
1596         obp = op->bufp;
1597       }
1598       break;
1599
1600       /* Come here either after (1) a null character that is part of the input
1601          or (2) at the end of the input, because there is a null there.  */
1602     case 0:
1603       if (ibp <= limit)
1604         /* Our input really contains a null character.  */
1605         goto randomchar;
1606
1607       /* At end of a macro-expansion level, pop it and read next level.  */
1608       if (ip->macro != 0) {
1609         obp--;
1610         ibp--;
1611         /* If we have an identifier that ends here, process it now, so
1612            we get the right error for recursion.  */
1613         if (ident_length && ! is_idchar (*instack[indepth - 1].bufp)) {
1614           redo_char = 1;
1615           goto randomchar;
1616         }
1617         POPMACRO;
1618         RECACHE;
1619         break;
1620       }
1621
1622       /* If we don't have a pending identifier,
1623          return at end of input.  */
1624       if (ident_length == 0) {
1625         obp--;
1626         ibp--;
1627         op->bufp = obp;
1628         ip->bufp = ibp;
1629         goto ending;
1630       }
1631
1632       /* If we do have a pending identifier, just consider this null
1633          a special character and arrange to dispatch on it again.
1634          The second time, IDENT_LENGTH will be zero so we will return.  */
1635
1636       /* Fall through */
1637
1638 specialchar:
1639
1640       /* Handle the case of a character such as /, ', " or null
1641          seen following an identifier.  Back over it so that
1642          after the identifier is processed the special char
1643          will be dispatched on again.  */
1644
1645       ibp--;
1646       obp--;
1647       redo_char = 1;
1648
1649     default:
1650
1651 randomchar:
1652
1653       if (ident_length > 0) {
1654         HASHNODE *hp;
1655
1656         /* We have just seen an identifier end.  If it's a macro, expand it.
1657
1658            IDENT_LENGTH is the length of the identifier
1659            and HASH is its hash code.
1660
1661            The identifier has already been copied to the output,
1662            so if it is a macro we must remove it.
1663
1664            If REDO_CHAR is 0, the char that terminated the identifier
1665            has been skipped in the output and the input.
1666            OBP-IDENT_LENGTH-1 points to the identifier.
1667            If the identifier is a macro, we must back over the terminator.
1668
1669            If REDO_CHAR is 1, the terminating char has already been
1670            backed over.  OBP-IDENT_LENGTH points to the identifier.  */
1671
1672         for (hp = hashtab[MAKE_POS (hash) % HASHSIZE]; hp != NULL;
1673              hp = hp->next) {
1674
1675           if (hp->length == ident_length) {
1676             /* obufp_before_macroname is used only in this block,
1677                but it has to be global because of RECACHE.  */
1678             int op_lineno_before_macroname;
1679             int i = ident_length;
1680             U_CHAR *p = hp->name;
1681             U_CHAR *q = obp - i;
1682
1683             if (! redo_char)
1684               q--;
1685
1686             do {                /* All this to avoid a strncmp () */
1687               if (*p++ != *q++)
1688                 goto hashcollision;
1689             } while (--i);
1690
1691             /* We found a use of a macro name.
1692                see if the context shows it is a macro call.  */
1693
1694             /* Back up over terminating character if not already done.  */
1695             if (! redo_char) {
1696               ibp--;
1697               obp--;
1698             }
1699
1700             obufp_before_macroname = obp - ident_length;
1701             op_lineno_before_macroname = op->lineno;
1702
1703             /* If macro wants an arglist, verify that a '(' follows.
1704                first skip all whitespace, copying it to the output
1705                after the macro name.  Then, if there is no '(',
1706                decide this is not a macro call and leave things that way.  */
1707             if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
1708               {
1709                 while (1) {
1710                   /* Scan forward over whitespace, copying it to the output.  */
1711                   if (ibp == limit && ip->macro != 0) {
1712                     POPMACRO;
1713                     RECACHE;
1714                   }
1715                   /* A comment: copy it unchanged or discard it.  */
1716                   else if (*ibp == '/' && ibp+1 != limit && ibp[1] == '*') {
1717                     if (put_out_comments) {
1718                       *obp++ = '/';
1719                       *obp++ = '*';
1720                     }
1721                     ibp += 2;
1722                     while (ibp + 1 != limit
1723                            && !(ibp[0] == '*' && ibp[1] == '/')) {
1724                       /* We need not worry about newline-marks,
1725                          since they are never found in comments.  */
1726                       if (*ibp == '\n') {
1727                         /* Newline in a file.  Count it.  */
1728                         ++ip->lineno;
1729                         ++op->lineno;
1730                       }
1731                       if (put_out_comments)
1732                         *obp++ = *ibp++;
1733                       else
1734                         ibp++;
1735                     }
1736                     ibp += 2;
1737                     if (put_out_comments) {
1738                       *obp++ = '*';
1739                       *obp++ = '/';
1740                     }
1741                   }
1742                   else if (is_space (*ibp)) {
1743                     *obp++ = *ibp++;
1744                     if (ibp[-1] == '\n') {
1745                       if (ip->macro == 0) {
1746                         /* Newline in a file.  Count it.  */
1747                         ++ip->lineno;
1748                         ++op->lineno;
1749                       } else if (!output_marks) {
1750                         /* A newline mark, and we don't want marks
1751                            in the output.  If it is newline-hyphen,
1752                            discard it entirely.  Otherwise, it is
1753                            newline-whitechar, so keep the whitechar.  */
1754                         obp--;
1755                         if (*ibp == '-')
1756                           ibp++;
1757                         else {
1758                           if (*ibp == '\n')
1759                             ++op->lineno;
1760                           *obp++ = *ibp++;
1761                         }
1762                       } else {
1763                         /* A newline mark; copy both chars to the output.  */
1764                         *obp++ = *ibp++;
1765                       }
1766                     }
1767                   }
1768                   else break;
1769                 }
1770                 if (*ibp != '(')
1771                   break;
1772               }
1773
1774             /* This is now known to be a macro call.
1775                Discard the macro name from the output,
1776                along with any following whitespace just copied.  */
1777             obp = obufp_before_macroname;
1778             op->lineno = op_lineno_before_macroname;
1779
1780             /* Expand the macro, reading arguments as needed,
1781                and push the expansion on the input stack.  */
1782             ip->bufp = ibp;
1783             op->bufp = obp;
1784             macroexpand (hp, op);
1785
1786             /* Reexamine input stack, since macroexpand has pushed
1787                a new level on it.  */
1788             obp = op->bufp;
1789             RECACHE;
1790             break;
1791           }
1792 hashcollision:
1793                ;
1794         }                       /* End hash-table-search loop */
1795         ident_length = hash = 0; /* Stop collecting identifier */
1796         redo_char = 0;
1797         concatenated = 0;
1798       }                         /* End if (ident_length > 0) */
1799     }                           /* End switch */
1800   }                             /* End per-char loop */
1801
1802   /* Come here to return -- but first give an error message
1803      if there was an unterminated successful conditional.  */
1804  ending:
1805   if (if_stack != ip->if_stack) {
1806     const char *str;
1807     switch (if_stack->type) {
1808     case T_IF:
1809       str = "if";
1810       break;
1811     case T_IFDEF:
1812       str = "ifdef";
1813       break;
1814     case T_IFNDEF:
1815       str = "ifndef";
1816       break;
1817     case T_ELSE:
1818       str = "else";
1819       break;
1820     case T_ELIF:
1821       str = "elif";
1822       break;
1823     default:
1824       abort ();
1825     }
1826     error_with_line (line_for_error (if_stack->lineno),
1827                      "unterminated #%s conditional", str);
1828   }
1829   if_stack = ip->if_stack;
1830 }
1831 \f
1832 /*
1833  * Rescan a string into a temporary buffer and return the result
1834  * as a FILE_BUF.  Note this function returns a struct, not a pointer.
1835  *
1836  * OUTPUT_MARKS nonzero means keep Newline markers found in the input
1837  * and insert such markers when appropriate.  See `rescan' for details.
1838  * OUTPUT_MARKS is 1 for macroexpanding a macro argument separately
1839  * before substitution; it is 0 for other uses.
1840  */
1841 static FILE_BUF
1842 expand_to_temp_buffer (buf, limit, output_marks)
1843      const U_CHAR *buf, *limit;
1844      int output_marks;
1845 {
1846   FILE_BUF *ip;
1847   FILE_BUF obuf;
1848   int length = limit - buf;
1849   U_CHAR *buf1;
1850   int odepth = indepth;
1851
1852   if (length < 0)
1853     abort ();
1854
1855   /* Set up the input on the input stack.  */
1856
1857   buf1 = (U_CHAR *) alloca (length + 1);
1858   {
1859     const U_CHAR *p1 = buf;
1860     U_CHAR *p2 = buf1;
1861
1862     while (p1 != limit)
1863       *p2++ = *p1++;
1864   }
1865   buf1[length] = 0;
1866
1867   /* Set up to receive the output.  */
1868
1869   obuf.length = length * 2 + 100; /* Usually enough.  Why be stingy?  */
1870   obuf.bufp = obuf.buf = (U_CHAR *) xmalloc (obuf.length);
1871   obuf.fname = 0;
1872   obuf.macro = 0;
1873   obuf.free_ptr = 0;
1874
1875   CHECK_DEPTH ({return obuf;});
1876
1877   ++indepth;
1878
1879   ip = &instack[indepth];
1880   ip->fname = 0;
1881   ip->macro = 0;
1882   ip->free_ptr = 0;
1883   ip->length = length;
1884   ip->buf = ip->bufp = buf1;
1885   ip->if_stack = if_stack;
1886
1887   ip->lineno = obuf.lineno = 1;
1888
1889   /* Scan the input, create the output.  */
1890
1891   rescan (&obuf, output_marks);
1892
1893   /* Pop input stack to original state.  */
1894   --indepth;
1895
1896   if (indepth != odepth)
1897     abort ();
1898
1899   /* Record the output.  */
1900   obuf.length = obuf.bufp - obuf.buf;
1901
1902   return obuf;
1903 }
1904 \f
1905 /*
1906  * Process a # directive.  Expects IP->bufp to point to the '#', as in
1907  * `#define foo bar'.  Passes to the command handler
1908  * (do_define, do_include, etc.): the addresses of the 1st and
1909  * last chars of the command (starting immediately after the #
1910  * keyword), plus op and the keyword table pointer.  If the command
1911  * contains comments it is copied into a temporary buffer sans comments
1912  * and the temporary buffer is passed to the command handler instead.
1913  * Likewise for backslash-newlines.
1914  *
1915  * Returns nonzero if this was a known # directive.
1916  * Otherwise, returns zero, without advancing the input pointer.
1917  */
1918
1919 static int
1920 handle_directive (ip, op)
1921      FILE_BUF *ip, *op;
1922 {
1923   U_CHAR *bp, *cp;
1924   const struct directive *kt;
1925   int ident_length;
1926   U_CHAR *resume_p;
1927
1928   /* Nonzero means we must copy the entire command
1929      to get rid of comments or backslash-newlines.  */
1930   int copy_command = 0;
1931
1932   U_CHAR *ident, *after_ident;
1933
1934   bp = ip->bufp;
1935   /* Skip whitespace and \-newline.  */
1936   while (1) {
1937     if (is_nvspace (*bp))
1938       bp++;
1939     else if (*bp == '/' && (newline_fix (bp + 1), bp[1]) == '*') {
1940       ip->bufp = bp;
1941       skip_to_end_of_comment (ip, &ip->lineno);
1942       bp = ip->bufp;
1943     } else if (*bp == '\\' && bp[1] == '\n') {
1944       bp += 2; ip->lineno++;
1945     } else break;
1946   }
1947
1948   /* Now find end of directive name.
1949      If we encounter a backslash-newline, exchange it with any following
1950      symbol-constituents so that we end up with a contiguous name.  */
1951
1952   cp = bp;
1953   while (1) {
1954     if (is_idchar (*cp))
1955       cp++;
1956     else {
1957       if (*cp == '\\' && cp[1] == '\n')
1958         name_newline_fix (cp);
1959       if (is_idchar (*cp))
1960         cp++;
1961       else break;
1962     }
1963   }
1964   ident_length = cp - bp;
1965   ident = bp;
1966   after_ident = cp;
1967
1968   /* A line of just `#' becomes blank.  */
1969
1970   if (ident_length == 0 && *after_ident == '\n') {
1971     ip->bufp = after_ident;
1972     return 1;
1973   }
1974
1975   /*
1976    * Decode the keyword and call the appropriate expansion
1977    * routine, after moving the input pointer up to the next line.
1978    */
1979   for (kt = directive_table; kt->length > 0; kt++) {
1980     if (kt->length == ident_length
1981         && !strncmp (kt->name, (const char *)ident, ident_length)) {
1982       U_CHAR *buf;
1983       U_CHAR *limit = ip->buf + ip->length;
1984       int unterminated = 0;
1985
1986       /* Nonzero means do not delete comments within the directive.
1987          #define needs this to detect traditional token paste.  */
1988       int keep_comments = kt->type == T_DEFINE;
1989
1990       /* Find the end of this command (first newline not backslashed
1991          and not in a string or comment).
1992          Set COPY_COMMAND if the command must be copied
1993          (it contains a backslash-newline or a comment).  */
1994
1995       buf = bp = after_ident;
1996       while (bp < limit) {
1997         U_CHAR c = *bp++;
1998         switch (c) {
1999         case '\\':
2000           if (bp < limit) {
2001             if (*bp == '\n') {
2002               ip->lineno++;
2003               copy_command = 1;
2004             }
2005             bp++;
2006           }
2007           break;
2008
2009         case '\'':
2010         case '\"':
2011           bp = skip_quoted_string (bp - 1, limit, ip->lineno, &ip->lineno, &copy_command, &unterminated);
2012           if (unterminated) {
2013             /* Traditional preprocessing permits unterminated strings.  */
2014             ip->bufp = bp;
2015             goto endloop1;
2016           }
2017           break;
2018
2019           /* <...> is special for #include.  */
2020         case '<':
2021           if (kt->type != T_INCLUDE)
2022             break;
2023           while (*bp && *bp != '>') bp++;
2024           break;
2025
2026         case '/':
2027           if (*bp == '\\' && bp[1] == '\n')
2028             newline_fix (bp);
2029           if (*bp == '*') {
2030             U_CHAR *obp = bp - 1;
2031             ip->bufp = bp + 1;
2032             skip_to_end_of_comment (ip, &ip->lineno);
2033             bp = ip->bufp;
2034             /* No need to copy the command because of a comment at the end;
2035                just don't include the comment in the directive.  */
2036             if (bp == limit || *bp == '\n') {
2037               bp = obp;
2038               goto endloop1;
2039             }
2040             /* Don't remove the comments if this is #define.  */
2041             if (! keep_comments)
2042               copy_command++;
2043           }
2044           break;
2045
2046         case '\n':
2047           --bp;         /* Point to the newline */
2048           ip->bufp = bp;
2049           goto endloop1;
2050         }
2051       }
2052       ip->bufp = bp;
2053
2054     endloop1:
2055       resume_p = ip->bufp;
2056       /* BP is the end of the directive.
2057          RESUME_P is the next interesting data after the directive.
2058          A comment may come between.  */
2059
2060       if (copy_command) {
2061         U_CHAR *xp = buf;
2062         /* Need to copy entire command into temp buffer before dispatching */
2063
2064         cp = (U_CHAR *) alloca (bp - buf + 5); /* room for cmd plus
2065                                                   some slop */
2066         buf = cp;
2067
2068         /* Copy to the new buffer, deleting comments
2069            and backslash-newlines (and whitespace surrounding the latter).  */
2070
2071         while (xp < bp) {
2072           U_CHAR c = *xp++;
2073           *cp++ = c;
2074
2075           switch (c) {
2076           case '\n':
2077             break;
2078
2079             /* <...> is special for #include.  */
2080           case '<':
2081             if (kt->type != T_INCLUDE)
2082               break;
2083             while (xp < bp && c != '>') {
2084               c = *xp++;
2085               if (c == '\\' && xp < bp && *xp == '\n')
2086                 xp++, ip->lineno++;
2087               else
2088                 *cp++ = c;
2089             }
2090             break;
2091
2092           case '\\':
2093             if (*xp == '\n') {
2094               xp++;
2095               cp--;
2096               if (cp != buf && is_space (cp[-1])) {
2097                 while (cp != buf && is_space(cp[-1])) cp--;
2098                 cp++;
2099                 SKIP_WHITE_SPACE (xp);
2100               } else if (is_nvspace (*xp)) {
2101                 *cp++ = *xp++;
2102                 SKIP_WHITE_SPACE (xp);
2103               }
2104             } else {
2105               *cp++ = *xp++;
2106             }
2107             break;
2108
2109           case '\'':
2110           case '\"':
2111             {
2112               const U_CHAR *bp1
2113                 = skip_quoted_string (xp - 1, limit, ip->lineno, 0, 0, 0);
2114               while (xp != bp1)
2115                 *cp++ = *xp++;
2116             }
2117             break;
2118
2119           case '/':
2120             if (*xp == '*') {
2121               ip->bufp = xp + 1;
2122               skip_to_end_of_comment (ip, 0);
2123               if (keep_comments)
2124                 while (xp != ip->bufp)
2125                   *cp++ = *xp++;
2126               /* Delete the slash.  */
2127               else
2128                 cp--;
2129               xp = ip->bufp;
2130             }
2131           }
2132         }
2133
2134         /* Null-terminate the copy.  */
2135
2136         *cp = 0;
2137       }
2138       else
2139         cp = bp;
2140
2141       ip->bufp = resume_p;
2142
2143       /* Call the appropriate command handler.  buf now points to
2144          either the appropriate place in the input buffer, or to
2145          the temp buffer if it was necessary to make one.  cp
2146          points to the first char after the contents of the (possibly
2147          copied) command, in either case. */
2148       (*kt->func) (buf, cp, op);
2149       check_expand (op, ip->length - (ip->bufp - ip->buf));
2150
2151       return 1;
2152     }
2153   }
2154
2155   return 0;
2156 }
2157 \f
2158 static const char *const
2159 monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2160                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2161
2162 /*
2163  * expand things like __FILE__.  Place the expansion into the output
2164  * buffer *without* rescanning.
2165  */
2166 static void
2167 special_symbol (hp, op)
2168      HASHNODE *hp;
2169      FILE_BUF *op;
2170 {
2171   const char *buf;
2172   time_t t;
2173   int i, len;
2174   int true_indepth;
2175   FILE_BUF *ip = NULL;
2176   static struct tm *timebuf = NULL;
2177
2178   int paren = 0;                /* For special `defined' keyword */
2179
2180   for (i = indepth; i >= 0; i--)
2181     if (instack[i].fname != NULL) {
2182       ip = &instack[i];
2183       break;
2184     }
2185   if (ip == NULL)
2186     fatal ("not in any file?!");
2187
2188   switch (hp->type) {
2189   case T_FILE:
2190   case T_BASE_FILE:
2191     {
2192       const char *string;
2193       if (hp->type == T_FILE)
2194         string = ip->fname;
2195       else
2196         string = instack[0].fname;
2197
2198       if (string)
2199         {
2200           char *tmp = (char *) alloca (3 + strlen (string));
2201           sprintf (tmp, "\"%s\"", string);
2202           buf = tmp;
2203         }
2204       else
2205         buf = "";
2206
2207       break;
2208     }
2209
2210   case T_INCLUDE_LEVEL:
2211     {
2212       char *tmp = (char *) alloca (8);  /* Eigth bytes ought to be more than enough */
2213       true_indepth = 0;
2214       for (i = indepth; i >= 0; i--)
2215         if (instack[i].fname != NULL)
2216           true_indepth++;
2217
2218     sprintf (tmp, "%d", true_indepth - 1);
2219     buf = tmp;
2220     break;
2221     }
2222
2223   case T_VERSION:
2224     {
2225       char *tmp = (char *) alloca (3 + strlen (version_string));
2226       sprintf (tmp, "\"%s\"", version_string);
2227       buf = tmp;
2228       break;
2229     }
2230
2231   case T_CONST:
2232     buf = hp->value.cpval;
2233     break;
2234
2235   case T_SPECLINE:
2236     {
2237       char *tmp = (char *) alloca (10);
2238       sprintf (tmp, "%d", ip->lineno);
2239       buf = tmp;
2240       break;
2241     }
2242
2243   case T_DATE:
2244   case T_TIME:
2245     {
2246       char *tmp = (char *) alloca (20);
2247
2248       if (timebuf == NULL) {
2249         t = time (0);
2250         timebuf = localtime (&t);
2251       }
2252       if (hp->type == T_DATE)
2253         sprintf (tmp, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2254                  timebuf->tm_mday, timebuf->tm_year + 1900);
2255       else
2256         sprintf (tmp, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2257                  timebuf->tm_sec);
2258       buf = tmp;
2259       break;
2260     }
2261
2262   case T_SPEC_DEFINED:
2263     buf = " 0 ";                        /* Assume symbol is not defined */
2264     ip = &instack[indepth];
2265     SKIP_WHITE_SPACE (ip->bufp);
2266     if (*ip->bufp == '(') {
2267       paren++;
2268       ip->bufp++;                       /* Skip over the paren */
2269       SKIP_WHITE_SPACE (ip->bufp);
2270     }
2271
2272     if (!is_idstart (*ip->bufp))
2273       goto oops;
2274     {
2275       HASHNODE *hp = lookup (ip->bufp, -1, -1);
2276
2277       if (hp && hp->type != T_UNUSED && hp->type != T_SPEC_DEFINED)
2278         buf = " 1 ";
2279     }
2280     while (is_idchar (*ip->bufp))
2281       ++ip->bufp;
2282     SKIP_WHITE_SPACE (ip->bufp);
2283     if (paren) {
2284       if (*ip->bufp != ')')
2285         goto oops;
2286       ++ip->bufp;
2287     }
2288     break;
2289
2290 oops:
2291
2292     error ("`defined' must be followed by ident or (ident)");
2293     break;
2294
2295   default:
2296     error ("cccp error: invalid special hash type"); /* time for gdb */
2297     abort ();
2298   }
2299   len = strlen (buf);
2300   check_expand (op, len);
2301   memcpy (op->bufp, buf, len);
2302   op->bufp += len;
2303 }
2304
2305 \f
2306 /* Routines to handle #directives */
2307
2308 /*
2309  * Process include file by reading it in and calling rescan.
2310  * Expects to see "fname" or <fname> on the input.
2311  */
2312 static void
2313 do_include (buf, limit, op)
2314      U_CHAR *buf, *limit;
2315      FILE_BUF *op;
2316 {
2317   U_CHAR *fbeg, *fend;          /* Beginning and end of fname */
2318
2319   struct file_name_list *stackp = include; /* Chain of dirs to search */
2320   struct file_name_list dsp[1]; /* First in chain, if #include "..." */
2321   int flen;
2322
2323   int retried = 0;              /* Have already tried macro
2324                                    expanding the include line*/
2325   FILE_BUF trybuf;              /* It got expanded into here */
2326   int system_header_p = 0;      /* 0 for "...", 1 for <...> */
2327
2328 get_filename:
2329
2330   fbeg = buf;
2331   SKIP_WHITE_SPACE (fbeg);
2332   /* Discard trailing whitespace so we can easily see
2333      if we have parsed all the significant chars we were given.  */
2334   while (limit != fbeg && is_nvspace (limit[-1])) limit--;
2335
2336   switch (*fbeg++) {
2337   case '\"':
2338     fend = fbeg;
2339     while (fend != limit && *fend != '\"')
2340       fend++;
2341     if (*fend == '\"' && fend + 1 == limit) {
2342       FILE_BUF *fp;
2343
2344       /* We have "filename".  Figure out directory this source
2345          file is coming from and put it on the front of the list. */
2346
2347       /* If -I- was specified, don't search current dir, only spec'd ones. */
2348       if (ignore_srcdir) break;
2349
2350       for (fp = &instack[indepth]; fp >= instack; fp--)
2351         {
2352           size_t n;
2353           const char *ep, *nam;
2354
2355           if ((nam = fp->fname) != NULL) {
2356             /* Found a named file.  Figure out dir of the file,
2357                and put it in front of the search list.  */
2358             dsp[0].next = stackp;
2359             stackp = dsp;
2360             ep = strrchr (nam, '/');
2361             if (ep != NULL) {
2362               char *f; 
2363               n = ep - nam;
2364               f = (char *) alloca (n + 1);
2365               strncpy (f, nam, n);
2366               f[n] = '\0';
2367               dsp[0].fname = f;
2368               if (n > max_include_len) max_include_len = n;
2369             } else {
2370               dsp[0].fname = 0; /* Current directory */
2371             }
2372             break;
2373           }
2374         }
2375       break;
2376     }
2377     goto fail;
2378
2379   case '<':
2380     fend = fbeg;
2381     while (fend != limit && *fend != '>') fend++;
2382     if (*fend == '>' && fend + 1 == limit) {
2383       system_header_p = 1;
2384       /* If -I-, start with the first -I dir after the -I-.  */
2385       if (first_bracket_include)
2386         stackp = first_bracket_include;
2387       break;
2388     }
2389     goto fail;
2390
2391   default:
2392   fail:
2393     if (retried) {
2394       error ("#include expects \"fname\" or <fname>");
2395       return;
2396     } else {
2397       trybuf = expand_to_temp_buffer (buf, limit, 0);
2398       buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
2399       memcpy (buf, trybuf.buf, trybuf.bufp - trybuf.buf);
2400       limit = buf + (trybuf.bufp - trybuf.buf);
2401       free (trybuf.buf);
2402       retried++;
2403       goto get_filename;
2404     }
2405   }
2406
2407   flen = fend - fbeg;
2408   process_include (stackp, fbeg, flen, system_header_p, op);
2409 }
2410
2411 static void
2412 do_include_next (buf, limit, op)
2413      U_CHAR *buf, *limit;
2414      FILE_BUF *op;
2415 {
2416   U_CHAR *fbeg, *fend;          /* Beginning and end of fname */
2417
2418   struct file_name_list *stackp; /* Chain of dirs to search */
2419   int flen;
2420
2421   int retried = 0;              /* Have already tried macro
2422                                    expanding the include line*/
2423   FILE_BUF trybuf;              /* It got expanded into here */
2424   int system_header_p = 0;      /* 0 for "...", 1 for <...> */
2425
2426   /* Treat as plain #include if we don't know where to start
2427      looking.  */
2428   stackp = instack[indepth].next_header_dir;
2429   if (stackp == 0)
2430     {
2431       do_include (buf, limit, op);
2432       return;
2433     }
2434
2435 get_filename:
2436
2437   fbeg = buf;
2438   SKIP_WHITE_SPACE (fbeg);
2439   /* Discard trailing whitespace so we can easily see
2440      if we have parsed all the significant chars we were given.  */
2441   while (limit != fbeg && is_nvspace (limit[-1])) limit--;
2442
2443   switch (*fbeg++) {
2444   case '\"':
2445     fend = fbeg;
2446     while (fend != limit && *fend != '\"')
2447       fend++;
2448     if (*fend == '\"' && fend + 1 == limit)
2449       break;
2450     goto fail;
2451
2452   case '<':
2453     fend = fbeg;
2454     while (fend != limit && *fend != '>') fend++;
2455     if (*fend == '>' && fend + 1 == limit) {
2456       system_header_p = 1;
2457       break;
2458     }
2459     goto fail;
2460
2461   default:
2462   fail:
2463     if (retried) {
2464       error ("#include expects \"fname\" or <fname>");
2465       return;
2466     } else {
2467       trybuf = expand_to_temp_buffer (buf, limit, 0);
2468       buf = (U_CHAR *) alloca (trybuf.bufp - trybuf.buf + 1);
2469       memcpy (buf, trybuf.buf, trybuf.bufp - trybuf.buf);
2470       limit = buf + (trybuf.bufp - trybuf.buf);
2471       free (trybuf.buf);
2472       retried++;
2473       goto get_filename;
2474     }
2475   }
2476
2477   flen = fend - fbeg;
2478   process_include (stackp, fbeg, flen, system_header_p, op);
2479 }
2480
2481 static void
2482 process_include (stackp, fbeg, flen, system_header_p, op)
2483      struct file_name_list *stackp;
2484      const U_CHAR *fbeg;
2485      int flen;
2486      int system_header_p;
2487      FILE_BUF *op;
2488 {
2489   char *fname;
2490   int f = -1;                   /* file number */
2491
2492   fname = (char *) alloca (max_include_len + flen + 2);
2493   /* + 2 above for slash and terminating null.  */
2494
2495   /* If specified file name is absolute, just open it.  */
2496
2497   if (IS_ABSOLUTE_PATHNAME (fbeg)) {
2498     strncpy (fname, (const char *)fbeg, flen);
2499     fname[flen] = 0;
2500     f = open (fname, O_RDONLY, 0666);
2501   } else {
2502     /* Search directory path, trying to open the file.
2503        Copy each filename tried into FNAME.  */
2504
2505     for (; stackp; stackp = stackp->next) {
2506       if (stackp->fname) {
2507         strcpy (fname, stackp->fname);
2508         strcat (fname, "/");
2509         fname[strlen (fname) + flen] = 0;
2510       } else {
2511         fname[0] = 0;
2512       }
2513       strncat (fname, (const char *)fbeg, flen);
2514       if ((f = open (fname, O_RDONLY, 0666)) >= 0)
2515         break;
2516     }
2517   }
2518
2519   if (f < 0) {
2520     strncpy (fname, (const char *)fbeg, flen);
2521     fname[flen] = 0;
2522     if (deps_missing_files
2523         && print_deps > (system_header_p || (system_include_depth > 0))) {
2524
2525       /* If requested as a system header, assume it belongs in
2526          the first system header directory. */
2527       if (first_bracket_include)
2528         stackp = first_bracket_include;
2529       else
2530         stackp = include;
2531
2532       if (!system_header_p || IS_ABSOLUTE_PATHNAME (fbeg) || !stackp->fname)
2533         deps_add_dep (deps, fname);
2534       else {
2535         char *p;
2536         int len = strlen(stackp->fname);
2537
2538         p = (char *) alloca (len + flen + 2);
2539         memcpy (p, stackp->fname, len);
2540         p[len++] = '/';
2541         memcpy (p + len, fbeg, flen);
2542         len += flen;
2543         p[len] = '\0';
2544         deps_add_dep (deps, p);
2545       }
2546     } else if (print_deps
2547                && print_deps <= (system_header_p
2548                                  || (system_include_depth > 0)))
2549       warning ("no include path in which to find %.*s", flen, fbeg);
2550     else
2551       error_from_errno (fname);
2552
2553   } else {
2554
2555     /* Check to see if this include file is a once-only include file.
2556        If so, give up.  */
2557
2558     struct file_name_list* ptr;
2559
2560     for (ptr = dont_repeat_files; ptr; ptr = ptr->next) {
2561       if (!strcmp (ptr->fname, fname)) {
2562         close (f);
2563         return;                         /* This file was once'd. */
2564       }
2565     }
2566
2567     for (ptr = all_include_files; ptr; ptr = ptr->next) {
2568       if (!strcmp (ptr->fname, fname))
2569         break;                          /* This file was included before. */
2570     }
2571
2572     if (ptr == 0) {
2573       /* This is the first time for this file.  */
2574       /* Add it to list of files included.  */
2575
2576       ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
2577       ptr->next = all_include_files;
2578       all_include_files = ptr;
2579       ptr->fname = xstrdup (fname);
2580
2581       /* For -M, add this file to the dependencies.  */
2582       if (print_deps > (system_header_p || (system_include_depth > 0)))
2583         deps_add_dep (deps, fname);
2584     }   
2585
2586     if (system_header_p)
2587       system_include_depth++;
2588
2589     /* Actually process the file.  */
2590     finclude (f, fname, stackp->next, op);
2591
2592     if (system_header_p)
2593       system_include_depth--;
2594
2595     close (f);
2596   }
2597 }
2598
2599 /* Replace all CR NL, NL CR and CR sequences with NL.  */
2600
2601 static void
2602 fixup_newlines (FILE_BUF *fp)
2603 {
2604   U_CHAR *p, *q, *end;
2605
2606   if (fp->length <= 0)
2607     return;
2608
2609   end = fp->buf + fp->length;
2610   *end = '\r';
2611   p = (U_CHAR *) strchr ((const char *) fp->buf, '\r');
2612   *end = '\0';
2613   if (p == end)
2614     return;
2615
2616   if (p > fp->buf && p[-1] == '\n')
2617     p--;
2618   q = p;
2619   while (p < end)
2620     switch (*p)
2621       {
2622       default:
2623         *q++ = *p++;
2624         break;
2625       case '\n':
2626       case '\r':
2627         p += 1 + (p[0] + p[1] == '\n' + '\r');
2628         *q++ = '\n';
2629         break;
2630       }
2631
2632   fp->length = q - fp->buf;
2633 }
2634
2635 /* Process the contents of include file FNAME, already open on descriptor F,
2636    with output to OP.  */
2637
2638 static void
2639 finclude (f, fname, nhd, op)
2640      int f;
2641      const char *fname;
2642      struct file_name_list *nhd;
2643      FILE_BUF *op;
2644 {
2645   int st_mode;
2646   long st_size;
2647   long i;
2648   FILE_BUF *fp;                 /* For input stack frame */
2649
2650   CHECK_DEPTH (return;);
2651
2652   if (file_size_and_mode (f, &st_mode, &st_size))
2653     goto nope;
2654
2655   fp = &instack[indepth + 1];
2656   memset (fp, 0, sizeof (FILE_BUF));
2657   fp->fname = fname;
2658   fp->length = 0;
2659   fp->lineno = 1;
2660   fp->if_stack = if_stack;
2661   fp->next_header_dir = nhd;
2662
2663   if (S_ISREG (st_mode)) {
2664     fp->buf = (U_CHAR *) xmalloc (st_size + 2);
2665     fp->bufp = fp->buf;
2666
2667     /* Read the file contents, knowing that st_size is an upper bound
2668        on the number of bytes we can read.  */
2669     while (st_size > 0) {
2670       i = read (f, fp->buf + fp->length, st_size);
2671       if (i <= 0) {
2672         if (i == 0) break;
2673         goto nope;
2674       }
2675       fp->length += i;
2676       st_size -= i;
2677     }
2678   }
2679   else {
2680     /* Cannot count its file size before reading.  */
2681
2682     U_CHAR *bufp;
2683     U_CHAR *basep;
2684     int bsize = 2000;
2685
2686     st_size = 0;
2687     basep = (U_CHAR *) xmalloc (bsize + 2);
2688     bufp = basep;
2689
2690     for (;;) {
2691       i = read (f, bufp, bsize - st_size);
2692       if (i < 0)
2693         goto nope;      /* error! */
2694       if (i == 0)
2695         break;  /* End of file */
2696       st_size += i;
2697       bufp += i;
2698       if (bsize == st_size) {   /* Buffer is full! */
2699           bsize *= 2;
2700           basep = (U_CHAR *) xrealloc (basep, bsize + 2);
2701           bufp = basep + st_size;       /* May have moved */
2702         }
2703     }
2704     fp->buf = basep;
2705     fp->bufp = fp->buf;
2706     fp->length = st_size;
2707   }
2708   close (f);
2709   fixup_newlines (fp);
2710
2711   /* Make sure data ends with a newline.  And put a null after it.  */
2712
2713   if (fp->length > 0 && fp->buf[fp->length-1] != '\n')
2714     fp->buf[fp->length++] = '\n';
2715   fp->buf[fp->length] = '\0';
2716
2717   indepth++;
2718   output_line_command (fp, op, 0, enter_file);
2719   rescan (op, 0);
2720   indepth--;
2721   instack[indepth].lineno++;
2722   instack[indepth].bufp++;      /* Skip the new line.  */
2723   output_line_command (&instack[indepth], op, 0, leave_file);
2724   free (fp->buf);
2725   return;
2726
2727 nope:
2728   perror_with_name (fname);
2729   close (f);
2730 }
2731 \f
2732
2733 /* Process a #define command.
2734 BUF points to the contents of the #define command, as a continguous string.
2735 LIMIT points to the first character past the end of the definition.
2736 KEYWORD is the keyword-table entry for #define.  */
2737
2738 static void
2739 do_define (buf, limit, op)
2740      U_CHAR *buf, *limit;
2741      FILE_BUF *op ATTRIBUTE_UNUSED;
2742 {
2743   U_CHAR *bp;                   /* temp ptr into input buffer */
2744   U_CHAR *symname;              /* remember where symbol name starts */
2745   int sym_length;               /* and how long it is */
2746
2747   DEFINITION *defn;
2748   int arglengths = 0;           /* Accumulate lengths of arg names
2749                                    plus number of args.  */
2750   int hashcode;
2751
2752   bp = buf;
2753
2754   while (is_nvspace (*bp))
2755     bp++;
2756
2757   symname = bp;                 /* remember where it starts */
2758   while (is_idchar (*bp) && bp < limit) {
2759     bp++;
2760   }
2761   sym_length = bp - symname;
2762   if (sym_length == 0)
2763     {
2764       error ("invalid macro name");
2765       return;
2766     }
2767   else if (!is_idstart (*symname)) {
2768     U_CHAR *msg;                        /* what pain... */
2769     msg = (U_CHAR *) alloca (sym_length + 1);
2770     memcpy (msg, symname, sym_length);
2771     msg[sym_length] = 0;
2772     error ("invalid macro name `%s'", msg);
2773     return;
2774   } else {
2775     if (! strncmp ((const char *)symname, "defined", 7) && sym_length == 7)
2776       {
2777         error ("\"defined\" cannot be used as a macro name");
2778         return;
2779       }
2780   }
2781
2782   /* lossage will occur if identifiers or control keywords are broken
2783      across lines using backslash.  This is not the right place to take
2784      care of that. */
2785
2786   if (*bp == '(') {
2787     struct arglist *arg_ptrs = NULL;
2788     int argno = 0;
2789
2790     bp++;                       /* skip '(' */
2791     SKIP_WHITE_SPACE (bp);
2792
2793     /* Loop over macro argument names.  */
2794     while (*bp != ')') {
2795       struct arglist *temp;
2796
2797       temp = (struct arglist *) alloca (sizeof (struct arglist));
2798       temp->name = bp;
2799       temp->next = arg_ptrs;
2800       temp->argno = argno++;
2801       arg_ptrs = temp;
2802
2803       if (!is_idstart (*bp))
2804         warning ("parameter name starts with a digit in #define");
2805
2806       /* Find the end of the arg name.  */
2807       while (is_idchar (*bp)) {
2808         bp++;
2809       }
2810       temp->length = bp - temp->name;
2811       arglengths += temp->length + 2;
2812       SKIP_WHITE_SPACE (bp);
2813       if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
2814         error ("badly punctuated parameter list in #define");
2815         return;
2816       }
2817       if (*bp == ',') {
2818         bp++;
2819         SKIP_WHITE_SPACE (bp);
2820       }
2821       if (bp >= limit) {
2822         error ("unterminated parameter list in #define");
2823         return;
2824       }
2825     }
2826
2827     ++bp;                                       /* skip paren */
2828     while (is_nvspace (*bp) && bp < limit)      /* and leading whitespace */
2829       ++bp;
2830     /* now everything from bp before limit is the definition. */
2831     defn = collect_expansion (bp, limit, argno, arg_ptrs);
2832
2833     /* Now set defn->argnames to the result of concatenating
2834        the argument names in reverse order
2835        with comma-space between them.  */
2836     {
2837       struct arglist *temp;
2838       int i = 0;
2839       U_CHAR *tmp = (U_CHAR *) xmalloc (arglengths + 1);
2840
2841       for (temp = arg_ptrs; temp; temp = temp->next) {
2842         memcpy (&tmp[i], temp->name, temp->length);
2843         i += temp->length;
2844         if (temp->next != 0) {
2845           tmp[i++] = ',';
2846           tmp[i++] = ' ';
2847         }
2848       }
2849       tmp[i] = 0;
2850       defn->argnames = tmp;
2851       
2852     }
2853   } else {
2854     /* simple expansion or empty definition; skip leading whitespace */
2855     while (is_nvspace (*bp) && bp < limit)
2856       ++bp;
2857     /* now everything from bp before limit is the definition. */
2858     defn = collect_expansion (bp, limit, -1, 0);
2859     defn->argnames = (const U_CHAR *) "";
2860   }
2861
2862   hashcode = hashf (symname, sym_length, HASHSIZE);
2863
2864   {
2865     HASHNODE *hp;
2866     if ((hp = lookup (symname, sym_length, hashcode)) == NULL)
2867       hp = install (symname, sym_length, T_MACRO, hashcode);
2868     else {
2869       if (hp->type != T_MACRO || compare_defs (defn, hp->value.defn))
2870         warning ("\"%.*s\" redefined", sym_length, symname);
2871
2872       /* Replace the old definition.  */
2873       hp->type = T_MACRO;
2874     }
2875
2876     hp->value.defn = defn;
2877   }
2878 }
2879
2880 /*
2881  * return zero if two DEFINITIONs are isomorphic
2882  */
2883 static int
2884 compare_defs (d1, d2)
2885      DEFINITION *d1, *d2;
2886 {
2887   struct reflist *a1, *a2;
2888   U_CHAR *p1 = d1->expansion;
2889   U_CHAR *p2 = d2->expansion;
2890   int first = 1;
2891
2892   if (d1->nargs != d2->nargs)
2893     return 1;
2894   if (strcmp ((const char *)d1->argnames, (const char *)d2->argnames))
2895     return 1;
2896   for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
2897        a1 = a1->next, a2 = a2->next) {
2898     if (!((a1->nchars == a2->nchars
2899            && ! strncmp ((const char *)p1, (const char *)p2, a1->nchars))
2900           || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
2901         || a1->argno != a2->argno
2902         || a1->stringify != a2->stringify
2903         || a1->raw_before != a2->raw_before
2904         || a1->raw_after != a2->raw_after)
2905       return 1;
2906     first = 0;
2907     p1 += a1->nchars;
2908     p2 += a2->nchars;
2909   }
2910   if (a1 != a2)
2911     return 1;
2912   if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
2913                      p2, d2->length - (p2 - d2->expansion), 1))
2914     return 1;
2915   return 0;
2916 }
2917
2918 /* Return 1 if two parts of two macro definitions are effectively different.
2919    One of the parts starts at BEG1 and has LEN1 chars;
2920    the other has LEN2 chars at BEG2.
2921    Any sequence of whitespace matches any other sequence of whitespace.
2922    FIRST means these parts are the first of a macro definition;
2923     so ignore leading whitespace entirely.
2924    LAST means these parts are the last of a macro definition;
2925     so ignore trailing whitespace entirely.  */
2926 static int
2927 comp_def_part (first, beg1, len1, beg2, len2, last)
2928      int first;
2929      const U_CHAR *beg1, *beg2;
2930      int len1, len2;
2931      int last;
2932 {
2933   const U_CHAR *end1 = beg1 + len1;
2934   const U_CHAR *end2 = beg2 + len2;
2935   if (first) {
2936     while (beg1 != end1 && is_space (*beg1)) beg1++;
2937     while (beg2 != end2 && is_space (*beg2)) beg2++;
2938   }
2939   if (last) {
2940     while (beg1 != end1 && is_space (end1[-1])) end1--;
2941     while (beg2 != end2 && is_space (end2[-1])) end2--;
2942   }
2943   while (beg1 != end1 && beg2 != end2) {
2944     if (is_space (*beg1) && is_space (*beg2)) {
2945       while (beg1 != end1 && is_space (*beg1)) beg1++;
2946       while (beg2 != end2 && is_space (*beg2)) beg2++;
2947     } else if (*beg1 == *beg2) {
2948       beg1++; beg2++;
2949     } else break;
2950   }
2951   return (beg1 != end1) || (beg2 != end2);
2952 }
2953
2954 /* Read a replacement list for a macro with parameters.
2955    Build the DEFINITION structure.
2956    Reads characters of text starting at BUF until LIMIT.
2957    ARGLIST specifies the formal parameters to look for
2958    in the text of the definition; NARGS is the number of args
2959    in that list, or -1 for a macro name that wants no argument list.
2960    MACRONAME is the macro name itself (so we can avoid recursive expansion)
2961    and NAMELEN is its length in characters.
2962    
2963 Note that comments and backslash-newlines have already been deleted
2964 from the argument.  */
2965
2966 /* Leading and trailing Space, Tab, etc. are converted to markers
2967    Newline Space, Newline Tab, etc.
2968    Newline Space makes a space in the final output
2969    but is discarded if stringified.  (Newline Tab is similar but
2970    makes a Tab instead.)
2971
2972    If there is no trailing whitespace, a Newline Space is added at the end
2973    to prevent concatenation that would be contrary to the standard.  */
2974
2975 static DEFINITION *
2976 collect_expansion (buf, end, nargs, arglist)
2977      U_CHAR *buf, *end;
2978      int nargs;
2979      struct arglist *arglist;
2980 {
2981   DEFINITION *defn;
2982   U_CHAR *p, *limit, *lastp, *exp_p;
2983   struct reflist *endpat = NULL;
2984   /* Pointer to first nonspace after last ## seen.  */
2985   U_CHAR *concat = 0;
2986   /* Pointer to first nonspace after last single-# seen.  */
2987   U_CHAR *stringify = 0;
2988   int maxsize;
2989   int expected_delimiter = '\0';
2990
2991   /* Scan thru the replacement list, ignoring comments and quoted
2992      strings, picking up on the macro calls.  It does a linear search
2993      thru the arg list on every potential symbol.  Profiling might say
2994      that something smarter should happen. */
2995
2996   if (end < buf)
2997     abort ();
2998
2999   /* Find the beginning of the trailing whitespace.  */
3000   /* Find end of leading whitespace.  */
3001   limit = end;
3002   p = buf;
3003   while (p < limit && is_space (limit[-1])) limit--;
3004   while (p < limit && is_space (*p)) p++;
3005
3006   /* Allocate space for the text in the macro definition.
3007      Leading and trailing whitespace chars need 2 bytes each.
3008      Each other input char may or may not need 1 byte,
3009      so this is an upper bound.
3010      The extra 2 are for invented trailing newline-marker and final null.  */
3011   maxsize = (sizeof (DEFINITION)
3012              + 2 * (end - limit) + 2 * (p - buf)
3013              + (limit - p) + 3);
3014   defn = (DEFINITION *) xcalloc (1, maxsize);
3015
3016   defn->nargs = nargs;
3017   exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
3018   lastp = exp_p;
3019
3020   p = buf;
3021
3022   /* Convert leading whitespace to Newline-markers.  */
3023   while (p < limit && is_space (*p)) {
3024     *exp_p++ = '\n';
3025     *exp_p++ = *p++;
3026   }
3027
3028   /* Process the main body of the definition.  */
3029   while (p < limit) {
3030     int skipped_arg = 0;
3031     U_CHAR c = *p++;
3032
3033     *exp_p++ = c;
3034
3035     /* In -traditional mode, recognize arguments inside strings and
3036        and character constants, and ignore special properties of #.
3037        Arguments inside strings are considered "stringified", but no
3038        extra quote marks are supplied.  */
3039     switch (c) {
3040     case '\'':
3041     case '\"':
3042       if (expected_delimiter != '\0') {
3043         if (c == expected_delimiter)
3044           expected_delimiter = '\0';
3045       } else
3046         expected_delimiter = c;
3047       break;
3048
3049     case '\\':
3050       /* Backslash quotes delimiters and itself, but not macro args.  */
3051       if (expected_delimiter != 0 && p < limit
3052           && (*p == expected_delimiter || *p == '\\')) {
3053         *exp_p++ = *p++;
3054         continue;
3055       }
3056       break;
3057
3058     case '/':
3059       if (expected_delimiter != '\0') /* No comments inside strings.  */
3060         break;
3061       if (*p == '*') {
3062         /* If we find a comment that wasn't removed by handle_directive,
3063            this must be -traditional.  So replace the comment with
3064            nothing at all.  */
3065         exp_p--;
3066         p += 1;
3067         while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
3068           p++;
3069       }
3070       break;
3071     }
3072
3073     if (is_idchar (c) && nargs > 0) {
3074       U_CHAR *id_beg = p - 1;
3075       int id_len;
3076
3077       --exp_p;
3078       while (p != limit && is_idchar (*p)) p++;
3079       id_len = p - id_beg;
3080
3081       if (is_idstart (c)) {
3082         struct arglist *arg;
3083
3084         for (arg = arglist; arg != NULL; arg = arg->next) {
3085           struct reflist *tpat;
3086
3087           if (arg->name[0] == c
3088               && arg->length == id_len
3089               && strncmp ((const char *)arg->name,
3090                           (const char *)id_beg, id_len) == 0) {
3091             /* make a pat node for this arg and append it to the end of
3092                the pat list */
3093             tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
3094             tpat->next = NULL;
3095             tpat->raw_before = concat == id_beg;
3096             tpat->raw_after = 0;
3097             tpat->stringify = expected_delimiter != '\0';
3098
3099             if (endpat == NULL)
3100               defn->pattern = tpat;
3101             else
3102               endpat->next = tpat;
3103             endpat = tpat;
3104
3105             tpat->argno = arg->argno;
3106             tpat->nchars = exp_p - lastp;
3107             {
3108               U_CHAR *p1 = p;
3109               SKIP_WHITE_SPACE (p1);
3110               if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
3111                 tpat->raw_after = 1;
3112             }
3113             lastp = exp_p;      /* place to start copying from next time */
3114             skipped_arg = 1;
3115             break;
3116           }
3117         }
3118       }
3119
3120       /* If this was not a macro arg, copy it into the expansion.  */
3121       if (! skipped_arg) {
3122         U_CHAR *lim1 = p;
3123         p = id_beg;
3124         while (p != lim1)
3125           *exp_p++ = *p++;
3126         if (stringify == id_beg)
3127           error ("# operator should be followed by a macro argument name");
3128       }
3129     }
3130   }
3131
3132   if (limit < end) {
3133     /* Convert trailing whitespace to Newline-markers.  */
3134     while (limit < end && is_space (*limit)) {
3135       *exp_p++ = '\n';
3136       *exp_p++ = *limit++;
3137     }
3138   }
3139   *exp_p = '\0';
3140
3141   defn->length = exp_p - defn->expansion;
3142
3143   /* Crash now if we overrun the allocated size.  */
3144   if (defn->length + 1 > maxsize)
3145     abort ();
3146
3147   return defn;
3148 }
3149 \f
3150 /*
3151  * interpret #line command.  Remembers previously seen fnames
3152  * in its very own hash table.
3153  */
3154 #define FNAME_HASHSIZE 37
3155 static void
3156 do_line (buf, limit, op)
3157      U_CHAR *buf, *limit;
3158      FILE_BUF *op;
3159 {
3160   U_CHAR *bp;
3161   FILE_BUF *ip = &instack[indepth];
3162   FILE_BUF tem;
3163   int new_lineno;
3164   enum file_change_code file_change = same_file;
3165
3166   /* Expand any macros.  */
3167   tem = expand_to_temp_buffer (buf, limit, 0);
3168
3169   /* Point to macroexpanded line, which is null-terminated now.  */
3170   bp = tem.buf;
3171   SKIP_WHITE_SPACE (bp);
3172
3173   if (!ISDIGIT (*bp)) {
3174     error ("invalid format #line command");
3175     return;
3176   }
3177
3178   /* The Newline at the end of this line remains to be processed.
3179      To put the next line at the specified line number,
3180      we must store a line number now that is one less.  */
3181   new_lineno = atoi ((const char *)bp);
3182
3183   /* skip over the line number.  */
3184   while (ISDIGIT (*bp))
3185     bp++;
3186
3187   SKIP_WHITE_SPACE (bp);
3188
3189   if (*bp == '\"') {
3190     static HASHNODE *fname_table[FNAME_HASHSIZE];
3191     HASHNODE *hp, **hash_bucket;
3192     U_CHAR *fname;
3193     int fname_length;
3194
3195     fname = ++bp;
3196
3197     while (*bp && *bp != '\"')
3198       bp++;
3199     if (*bp != '\"') {
3200       error ("invalid format #line command");
3201       return;
3202     }
3203
3204     fname_length = bp - fname;
3205
3206     bp++;
3207     SKIP_WHITE_SPACE (bp);
3208     if (*bp) {
3209       if (*bp == '1')
3210         file_change = enter_file;
3211       else if (*bp == '2')
3212         file_change = leave_file;
3213       else {
3214         error ("invalid format #line command");
3215         return;
3216       }
3217
3218       bp++;
3219       SKIP_WHITE_SPACE (bp);
3220       if (*bp) {
3221         error ("invalid format #line command");
3222         return;
3223       }
3224     }
3225
3226     hash_bucket =
3227       &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
3228     for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3229       if (hp->length == fname_length &&
3230           strncmp (hp->value.cpval, (const char *)fname, fname_length) == 0) {
3231         ip->fname = hp->value.cpval;
3232         break;
3233       }
3234     if (hp == 0) {
3235       char *q;
3236       /* Didn't find it; cons up a new one.  */
3237       hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
3238       hp->next = *hash_bucket;
3239       *hash_bucket = hp;
3240
3241       hp->length = fname_length;
3242       ip->fname = hp->value.cpval = q = ((char *) hp) + sizeof (HASHNODE);
3243       memcpy (q, fname, fname_length);
3244     }
3245   } else if (*bp) {
3246     error ("invalid format #line command");
3247     return;
3248   }
3249
3250   ip->lineno = new_lineno;
3251   output_line_command (ip, op, 0, file_change);
3252   ip->bufp++;                   /* Skip the new line.  */
3253   check_expand (op, ip->length - (ip->bufp - ip->buf));
3254 }
3255
3256 /*
3257  * remove all definitions of symbol from symbol table.
3258  * according to un*x /lib/cpp, it is not an error to undef
3259  * something that has no definitions, so it isn't one here either.
3260  */
3261 static void
3262 do_undef (buf, limit, op)
3263      U_CHAR *buf;
3264      U_CHAR *limit ATTRIBUTE_UNUSED;
3265      FILE_BUF *op ATTRIBUTE_UNUSED;
3266 {
3267   HASHNODE *hp;
3268
3269   SKIP_WHITE_SPACE (buf);
3270
3271   if (! strncmp ((const char *)buf, "defined", 7) && ! is_idchar (buf[7]))
3272     warning ("undefining `defined'");
3273
3274   while ((hp = lookup (buf, -1, -1)) != NULL) {
3275     if (hp->type != T_MACRO)
3276       warning ("undefining `%s'", hp->name);
3277     delete_macro (hp);
3278   }
3279 }
3280
3281 /* Read the tokens of the answer into the macro pool.  Only commit the
3282    memory if we intend it as permanent storage, i.e. the #assert case.
3283    Returns 0 on success.  */
3284
3285 static int
3286 parse_answer (buf, limit, answerp, type)
3287      const unsigned char *buf, *limit;
3288      struct answer **answerp;
3289      int type;
3290 {
3291   const unsigned char *start;
3292
3293   /* Skip leading whitespace.  */
3294   if (buf < limit && *buf == ' ')
3295     buf++;
3296
3297   /* Parentheses are optional here.  */
3298   if (buf == limit && type == T_UNASSERT)
3299     return 0;
3300
3301   if (buf == limit || *buf++ != '(')
3302     {
3303       if (type == T_IF)
3304         return 0;
3305
3306       error ("missing '(' after predicate");
3307       return 1;
3308     }
3309
3310   /* Drop whitespace at start.  */
3311   while (buf < limit && *buf == ' ')
3312     buf++;
3313
3314   start = buf;
3315   while (buf < limit && *buf != ')')
3316     buf++;
3317
3318   if (buf == limit)
3319     {
3320       error ("missing ')' to complete answer");
3321       return 1;
3322     }
3323
3324   if (buf == start)
3325     {
3326       error ("predicate's answer is empty");
3327       return 1;
3328     }
3329
3330   if ((type == T_ASSERT || type == T_UNASSERT) && buf + 1 != limit)
3331     {
3332       error ("extra text at end of directive");
3333       return 1;
3334     }
3335
3336   /* Lose trailing whitespace.  */
3337   if (buf[-1] == ' ')
3338     buf--;
3339
3340   *answerp = (struct answer *) xmalloc (sizeof (struct answer));
3341   (*answerp)->answer = start;
3342   (*answerp)->len = buf - start;
3343
3344   return 0;
3345 }
3346
3347 /* Parses an assertion, returning a pointer to the hash node of the
3348    predicate, or 0 on error.  If an answer was supplied, it is placed
3349    in ANSWERP, otherwise it is set to 0.  */
3350 static HASHNODE *
3351 parse_assertion (buf, limit, answerp, type)
3352      const unsigned char *buf, *limit;
3353      struct answer **answerp;
3354      int type;
3355 {
3356   HASHNODE *result = 0;
3357   const unsigned char *climit;
3358   unsigned char *bp, *symname = canonicalize_text (buf, limit, &climit);
3359   unsigned int len;
3360
3361   bp = symname;
3362   if (bp < climit && is_idstart (*bp))
3363     {
3364       do
3365         bp++;
3366       while (bp < climit && is_idchar (*bp));
3367     }
3368   len = bp - symname;
3369
3370   *answerp = 0;
3371   if (len == 0)
3372     {
3373       if (symname == climit)
3374         error ("assertion without predicate");
3375       else
3376         error ("predicate must be an identifier");
3377     }
3378   /* Unfortunately, because of the way we handle #if, we don't avoid
3379      macro expansion in answers.  This is not easy to fix.  */
3380   else if (parse_answer (bp, climit, answerp, type) == 0)
3381     {
3382       unsigned char *sym = alloca (len + 1);
3383       int hashcode;
3384       
3385       /* Prefix '#' to get it out of macro namespace.  */
3386       sym[0] = '#';
3387       memcpy (sym + 1, symname, len);
3388
3389       hashcode = hashf (sym, len + 1, HASHSIZE);
3390       result = lookup (sym, len + 1, hashcode);
3391       if (result == 0)
3392         result = install (sym, len + 1, T_UNUSED, hashcode);
3393     }
3394
3395   return result;
3396 }
3397
3398 /* Test an assertion within a preprocessor conditional.  Returns zero
3399    on error or failure, one on success.  */
3400 int
3401 test_assertion (pbuf)
3402      unsigned char **pbuf;      /* NUL-terminated.  */
3403 {
3404   unsigned char *buf = *pbuf;
3405   unsigned char *limit = buf + strlen ((char *) buf);
3406   struct answer *answer;
3407   HASHNODE *node;
3408   int result = 0;
3409
3410   node = parse_assertion (buf, limit, &answer, T_IF);
3411   if (node)
3412     {
3413       result = (node->type == T_ASSERT &&
3414                 (answer == 0 || *find_answer (node, answer) != 0));
3415
3416       /* Yuk.  We update pbuf to point after the assertion test.
3417          First, move past the identifier.  */
3418       if (is_space (*buf))
3419         buf++;
3420       while (is_idchar (*buf))
3421         buf++;
3422       /* If we have an answer, we need to move past the parentheses.  */
3423       if (answer)
3424         while (*buf++ != ')')
3425           ;
3426       *pbuf = buf;
3427     }
3428
3429   return result;
3430 }
3431
3432 /* Handle a #error directive.  */
3433 static void
3434 do_error (buf, limit, op)
3435      U_CHAR *buf;
3436      U_CHAR *limit;
3437      FILE_BUF *op ATTRIBUTE_UNUSED;
3438 {
3439   error ("#error%.*s", (int) (limit - buf), buf);
3440 }
3441
3442 /* Handle a #warning directive.  */
3443 static void
3444 do_warning (buf, limit, op)
3445      U_CHAR *buf;
3446      U_CHAR *limit;
3447      FILE_BUF *op ATTRIBUTE_UNUSED;
3448 {
3449   warning ("#warning%.*s", (int) (limit - buf), buf);
3450 }
3451
3452 /* Handle a #assert directive.  */
3453 static void
3454 do_assert (buf, limit, op)
3455      U_CHAR *buf;
3456      U_CHAR *limit;
3457      FILE_BUF *op ATTRIBUTE_UNUSED;
3458 {
3459   struct answer *new_answer;
3460   HASHNODE *node;
3461   
3462   node = parse_assertion (buf, limit, &new_answer, T_ASSERT);
3463   if (node)
3464     {
3465       /* Place the new answer in the answer list.  First check there
3466          is not a duplicate.  */
3467       new_answer->next = 0;
3468       if (node->type == T_ASSERT)
3469         {
3470           if (*find_answer (node, new_answer))
3471             {
3472               free (new_answer);
3473               warning ("\"%s\" re-asserted", node->name + 1);
3474               return;
3475             }
3476           new_answer->next = node->value.answers;
3477         }
3478       node->type = T_ASSERT;
3479       node->value.answers = new_answer;
3480     }
3481 }
3482
3483 /* Function body to be provided later.  */
3484 static void
3485 do_unassert (buf, limit, op)
3486      U_CHAR *buf;
3487      U_CHAR *limit;
3488      FILE_BUF *op ATTRIBUTE_UNUSED;
3489 {
3490   HASHNODE *node;
3491   struct answer *answer;
3492   
3493   node = parse_assertion (buf, limit, &answer, T_UNASSERT);
3494   /* It isn't an error to #unassert something that isn't asserted.  */
3495   if (node)
3496     {
3497       if (node->type == T_ASSERT)
3498         {
3499           if (answer)
3500             {
3501               struct answer **p = find_answer (node, answer), *temp;
3502
3503               /* Remove the answer from the list.  */
3504               temp = *p;
3505               if (temp)
3506                 *p = temp->next;
3507
3508               /* Did we free the last answer?  */
3509               if (node->value.answers == 0)
3510                 delete_macro (node);
3511             }
3512           else
3513             delete_macro (node);
3514         }
3515
3516       free (answer);
3517     }
3518 }
3519
3520 /* Returns a pointer to the pointer to the answer in the answer chain,
3521    or a pointer to NULL if the answer is not in the chain.  */
3522 static struct answer **
3523 find_answer (node, candidate)
3524      HASHNODE *node;
3525      const struct answer *candidate;
3526 {
3527   struct answer **result;
3528
3529   for (result = &node->value.answers; *result; result = &(*result)->next)
3530     {
3531       struct answer *answer = *result;
3532
3533       if (answer->len == candidate->len
3534           && !memcmp (answer->answer, candidate->answer, answer->len))
3535         break;
3536     }
3537
3538   return result;
3539 }
3540
3541 /* Return a malloced buffer with leading and trailing whitespace
3542    removed, and all instances of internal whitespace reduced to a
3543    single space.  */
3544 static unsigned char *
3545 canonicalize_text (buf, limit, climit)
3546      const unsigned char *buf, *limit, **climit;
3547 {
3548   unsigned int len = limit - buf;
3549   unsigned char *result = (unsigned char *) xmalloc (len), *dest;
3550
3551   for (dest = result; buf < limit;)
3552     {
3553       if (! is_space (*buf))
3554         *dest++ = *buf++;
3555       else
3556         {
3557           while (++buf < limit && is_space (*buf))
3558             ;
3559           if (dest != result && buf != limit)
3560             *dest++ = ' ';
3561         }
3562     }
3563
3564   *climit = dest;
3565   return result;
3566 }
3567
3568 /*
3569  * handle #if command by
3570  *   1) inserting special `defined' keyword into the hash table
3571  *      that gets turned into 0 or 1 by special_symbol (thus,
3572  *      if the luser has a symbol called `defined' already, it won't
3573  *      work inside the #if command)
3574  *   2) rescan the input into a temporary output buffer
3575  *   3) pass the output buffer to the yacc parser and collect a value
3576  *   4) clean up the mess left from steps 1 and 2.
3577  *   5) call conditional_skip to skip til the next #endif (etc.),
3578  *      or not, depending on the value from step 3.
3579  */
3580 static void
3581 do_if (buf, limit, op)
3582      U_CHAR *buf, *limit;
3583      FILE_BUF *op ATTRIBUTE_UNUSED;
3584 {
3585   int value;
3586   FILE_BUF *ip = &instack[indepth];
3587
3588   value = eval_if_expression (buf, limit - buf);
3589   conditional_skip (ip, value == 0, T_IF);
3590 }
3591
3592 /*
3593  * handle a #elif directive by not changing  if_stack  either.
3594  * see the comment above do_else.
3595  */
3596 static void
3597 do_elif (buf, limit, op)
3598      U_CHAR *buf, *limit;
3599      FILE_BUF *op;
3600 {
3601   int value;
3602   FILE_BUF *ip = &instack[indepth];
3603
3604   if (if_stack == instack[indepth].if_stack) {
3605     error ("#elif not within a conditional");
3606     return;
3607   } else {
3608     if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
3609       error ("#elif after #else");
3610       fprintf (stderr, " (matches line %d", if_stack->lineno);
3611       if (if_stack->fname != NULL && ip->fname != NULL &&
3612           strcmp (if_stack->fname, ip->fname) != 0)
3613         fprintf (stderr, ", file %s", if_stack->fname);
3614       fprintf (stderr, ")\n");
3615     }
3616     if_stack->type = T_ELIF;
3617   }
3618
3619   if (if_stack->if_succeeded)
3620     skip_if_group (ip, 0);
3621   else {
3622     value = eval_if_expression (buf, limit - buf);
3623     if (value == 0)
3624       skip_if_group (ip, 0);
3625     else {
3626       ++if_stack->if_succeeded; /* continue processing input */
3627       output_line_command (ip, op, 1, same_file);
3628     }
3629   }
3630 }
3631
3632 /*
3633  * evaluate a #if expression in BUF, of length LENGTH,
3634  * then parse the result as a C expression and return the value as an int.
3635  */
3636 static int
3637 eval_if_expression (buf, length)
3638      const U_CHAR *buf;
3639      int length;
3640 {
3641   FILE_BUF temp_obuf;
3642   HASHNODE *save_defined;
3643   int value;
3644
3645   save_defined = install (U"defined", -1, T_SPEC_DEFINED, -1);
3646   temp_obuf = expand_to_temp_buffer (buf, buf + length, 0);
3647   delete_macro (save_defined);  /* clean up special symbol */
3648
3649   value = parse_c_expression ((const char *)temp_obuf.buf);
3650
3651   free (temp_obuf.buf);
3652
3653   return value;
3654 }
3655
3656 /*
3657  * routine to handle ifdef/ifndef.  Try to look up the symbol,
3658  * then do or don't skip to the #endif/#else/#elif depending
3659  * on what directive is actually being processed.
3660  */
3661 static void
3662 do_xifdef (buf, limit, type)
3663      U_CHAR *buf, *limit;
3664      enum node_type type;     
3665 {
3666   int skip;
3667   FILE_BUF *ip = &instack[indepth];
3668   U_CHAR *end; 
3669
3670   /* Discard leading and trailing whitespace.  */
3671   SKIP_WHITE_SPACE (buf);
3672   while (limit != buf && is_nvspace (limit[-1])) limit--;
3673
3674   /* Find the end of the identifier at the beginning.  */
3675   for (end = buf; is_idchar (*end); end++);
3676
3677   if (end == buf)
3678     skip = (type == T_IFDEF);
3679   else
3680     skip = (lookup (buf, end-buf, -1) == NULL) ^ (type == T_IFNDEF);
3681
3682   conditional_skip (ip, skip, T_IF);
3683 }
3684
3685 static void
3686 do_ifdef (buf, limit, op)
3687      U_CHAR *buf, *limit;
3688      FILE_BUF *op ATTRIBUTE_UNUSED;
3689 {
3690   do_xifdef (buf, limit, T_IFDEF);
3691 }
3692
3693 static void
3694 do_ifndef (buf, limit, op)
3695      U_CHAR *buf, *limit;
3696      FILE_BUF *op ATTRIBUTE_UNUSED;
3697 {
3698   do_xifdef (buf, limit, T_IFNDEF);
3699 }
3700
3701 /*
3702  * push TYPE on stack; then, if SKIP is nonzero, skip ahead.
3703  */
3704 static void
3705 conditional_skip (ip, skip, type)
3706      FILE_BUF *ip;
3707      int skip;
3708      enum node_type type;
3709 {
3710   IF_STACK_FRAME *temp;
3711
3712   temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
3713   temp->fname = ip->fname;
3714   temp->lineno = ip->lineno;
3715   temp->next = if_stack;
3716   if_stack = temp;
3717
3718   if_stack->type = type;
3719
3720   if (skip != 0) {
3721     skip_if_group (ip, 0);
3722     return;
3723   } else {
3724     ++if_stack->if_succeeded;
3725     output_line_command (ip, &outbuf, 1, same_file);
3726   }
3727 }
3728
3729 /*
3730  * skip to #endif, #else, or #elif.  adjust line numbers, etc.
3731  * leaves input ptr at the sharp sign found.
3732  * If ANY is nonzero, return at next directive of any sort.
3733  */
3734 static void
3735 skip_if_group (ip, any)
3736      FILE_BUF *ip;
3737      int any;
3738 {
3739   U_CHAR *bp = ip->bufp, *cp;
3740   U_CHAR *endb = ip->buf + ip->length;
3741   const struct directive *kt;
3742   IF_STACK_FRAME *save_if_stack = if_stack; /* don't pop past here */
3743   U_CHAR *beg_of_line = bp;
3744
3745   while (bp < endb) {
3746     switch (*bp++) {
3747     case '/':                   /* possible comment */
3748       if (*bp == '\\' && bp[1] == '\n')
3749         newline_fix (bp);
3750       if (*bp == '*') {
3751         ip->bufp = ++bp;
3752         bp = skip_to_end_of_comment (ip, &ip->lineno);
3753       }
3754       break;
3755     case '\"':
3756     case '\'':
3757       bp = skip_quoted_string (bp - 1, endb, ip->lineno, &ip->lineno, 0, 0);
3758       break;
3759     case '\\':
3760       /* Char after backslash loses its special meaning.  */
3761       if (bp < endb) {
3762         if (*bp == '\n')
3763           ++ip->lineno;         /* But do update the line-count.  */
3764         bp++;
3765       }
3766       break;
3767     case '\n':
3768       ++ip->lineno;
3769       beg_of_line = bp;
3770       break;
3771     case '#':
3772       ip->bufp = bp - 1;
3773
3774       /* # keyword: a # must be first nonblank char on the line */
3775       if (beg_of_line == 0)
3776         break;
3777       /* Scan from start of line, skipping whitespace, comments
3778          and backslash-newlines, and see if we reach this #.
3779          If not, this # is not special.  */
3780       bp = beg_of_line;
3781       while (1) {
3782         if (is_nvspace (*bp))
3783           bp++;
3784         else if (*bp == '\\' && bp[1] == '\n')
3785           bp += 2;
3786         else if (*bp == '/' && bp[1] == '*') {
3787           bp += 2;
3788           while (!(*bp == '*' && bp[1] == '/')) {
3789             if (*bp == '\n')
3790               ip->lineno++;
3791             bp++;
3792           }
3793           bp += 2;
3794         }
3795         else break;
3796       }
3797       if (bp != ip->bufp) {
3798         bp = ip->bufp + 1;      /* Reset bp to after the #.  */
3799         break;
3800       }
3801
3802       bp = ip->bufp + 1;        /* Point after '#'.  */
3803
3804       /* Skip whitespace and \-newline.  */
3805       while (1) {
3806         if (is_nvspace (*bp))
3807           bp++;
3808         else if (*bp == '\\' && bp[1] == '\n')
3809           bp += 2;
3810         else if (*bp == '/' && bp[1] == '*') {
3811           bp += 2;
3812           while (!(*bp == '*' && bp[1] == '/'))
3813             bp++;
3814           bp += 2;
3815         }
3816         else break;
3817       }
3818
3819       cp = bp;
3820
3821       /* Now find end of directive name.
3822          If we encounter a backslash-newline, exchange it with any following
3823          symbol-constituents so that we end up with a contiguous name.  */
3824
3825       while (1) {
3826         if (is_idchar (*bp))
3827           bp++;
3828         else {
3829           if (*bp == '\\' && bp[1] == '\n')
3830             name_newline_fix (bp);
3831           if (is_idchar (*bp))
3832             bp++;
3833           else break;
3834         }
3835       }
3836
3837       for (kt = directive_table; kt->length >= 0; kt++) {
3838         IF_STACK_FRAME *temp;
3839         if (strncmp ((const char *)cp, kt->name, kt->length) == 0
3840             && !is_idchar (cp[kt->length])) {
3841
3842           /* If we are asked to return on next directive,
3843              do so now.  */
3844           if (any)
3845             return;
3846
3847           switch (kt->type) {
3848           case T_IF:
3849           case T_IFDEF:
3850           case T_IFNDEF:
3851             temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
3852             temp->next = if_stack;
3853             if_stack = temp;
3854             temp->lineno = ip->lineno;
3855             temp->fname = ip->fname;
3856             temp->type = kt->type;
3857             break;
3858           case T_ELSE:
3859           case T_ENDIF:
3860           case T_ELIF:
3861             if (if_stack == instack[indepth].if_stack) {
3862               error ("#%s not within a conditional", kt->name);
3863               break;
3864             }
3865             else if (if_stack == save_if_stack)
3866               return;           /* found what we came for */
3867
3868             if (kt->type != T_ENDIF) {
3869               if (if_stack->type == T_ELSE)
3870                 error ("#else or #elif after #else");
3871               if_stack->type = kt->type;
3872               break;
3873             }
3874
3875             temp = if_stack;
3876             if_stack = if_stack->next;
3877             free (temp);
3878             break;
3879
3880           default:
3881             /* Anything else is ignored.  */
3882             break;
3883           }
3884           break;
3885         }
3886       }
3887     }
3888   }
3889   ip->bufp = bp;
3890   /* after this returns, rescan will exit because ip->bufp
3891      now points to the end of the buffer.
3892      rescan is responsible for the error message also.  */
3893 }
3894
3895 /*
3896  * handle a #else directive.  Do this by just continuing processing
3897  * without changing  if_stack ;  this is so that the error message
3898  * for missing #endif's etc. will point to the original #if.  It
3899  * is possible that something different would be better.
3900  */
3901 static void
3902 do_else (buf, limit, op)
3903      U_CHAR *buf ATTRIBUTE_UNUSED;
3904      U_CHAR *limit ATTRIBUTE_UNUSED;
3905      FILE_BUF *op;
3906 {
3907   FILE_BUF *ip = &instack[indepth];
3908
3909   if (if_stack == instack[indepth].if_stack) {
3910     error ("#else not within a conditional");
3911     return;
3912   } else {
3913     if (if_stack->type != T_IF && if_stack->type != T_ELIF) {
3914       error ("#else after #else");
3915       fprintf (stderr, " (matches line %d", if_stack->lineno);
3916       if (strcmp (if_stack->fname, ip->fname) != 0)
3917         fprintf (stderr, ", file %s", if_stack->fname);
3918       fprintf (stderr, ")\n");
3919     }
3920     if_stack->type = T_ELSE;
3921   }
3922
3923   if (if_stack->if_succeeded)
3924     skip_if_group (ip, 0);
3925   else {
3926     ++if_stack->if_succeeded;   /* continue processing input */
3927     output_line_command (ip, op, 1, same_file);
3928   }
3929 }
3930
3931 /*
3932  * unstack after #endif command
3933  */
3934 static void
3935 do_endif (buf, limit, op)
3936      U_CHAR *buf ATTRIBUTE_UNUSED;
3937      U_CHAR *limit ATTRIBUTE_UNUSED;
3938      FILE_BUF *op;
3939 {
3940   if (if_stack == instack[indepth].if_stack)
3941     error ("unbalanced #endif");
3942   else {
3943     IF_STACK_FRAME *temp = if_stack;
3944     if_stack = if_stack->next;
3945     free (temp);
3946     output_line_command (&instack[indepth], op, 1, same_file);
3947   }
3948 }
3949
3950 /*
3951  * Skip a comment, assuming the input ptr immediately follows the
3952  * initial slash-star.  Bump line counter as necessary.
3953  * (The canonical line counter is &ip->lineno).
3954  * Don't use this routine (or the next one) if bumping the line
3955  * counter is not sufficient to deal with newlines in the string.
3956  */
3957 static U_CHAR *
3958 skip_to_end_of_comment (ip, line_counter)
3959      FILE_BUF *ip;
3960      int *line_counter;         /* place to remember newlines, or NULL */
3961 {
3962   U_CHAR *limit = ip->buf + ip->length;
3963   U_CHAR *bp = ip->bufp;
3964   FILE_BUF *op = &outbuf;       /* JF */
3965   int output = put_out_comments && !line_counter;
3966
3967         /* JF this line_counter stuff is a crock to make sure the
3968            comment is only put out once, no matter how many times
3969            the comment is skipped.  It almost works */
3970   if (output) {
3971     *op->bufp++ = '/';
3972     *op->bufp++ = '*';
3973   }
3974   while (bp < limit) {
3975     if (output)
3976       *op->bufp++ = *bp;
3977     switch (*bp++) {
3978     case '/':
3979       if (warn_comments && bp < limit && *bp == '*')
3980         warning("`/*' within comment");
3981       break;
3982     case '\n':
3983       if (line_counter != NULL)
3984         ++*line_counter;
3985       if (output)
3986         ++op->lineno;
3987       break;
3988     case '*':
3989       if (*bp == '\\' && bp[1] == '\n')
3990         newline_fix (bp);
3991       if (*bp == '/') {
3992         if (output)
3993           *op->bufp++ = '/';
3994         ip->bufp = ++bp;
3995         return bp;
3996       }
3997       break;
3998     }
3999   }
4000   ip->bufp = bp;
4001   return bp;
4002 }
4003
4004 /*
4005  * Skip over a quoted string.  BP points to the opening quote.
4006  * Returns a pointer after the closing quote.  Don't go past LIMIT.
4007  * START_LINE is the line number of the starting point (but it need
4008  * not be valid if the starting point is inside a macro expansion).
4009  *
4010  * The input stack state is not changed.
4011  *
4012  * If COUNT_NEWLINES is nonzero, it points to an int to increment
4013  * for each newline passed.
4014  *
4015  * If BACKSLASH_NEWLINES_P is nonzero, store 1 thru it
4016  * if we pass a backslash-newline.
4017  *
4018  * If EOFP is nonzero, set *EOFP to 1 if the string is unterminated.
4019  */
4020 static U_CHAR *
4021 skip_quoted_string (bp, limit, start_line, count_newlines, backslash_newlines_p, eofp)
4022      const U_CHAR *bp;
4023      const U_CHAR *limit;
4024      int start_line;
4025      int *count_newlines;
4026      int *backslash_newlines_p;
4027      int *eofp;
4028 {
4029   U_CHAR c, match;
4030
4031   match = *bp++;
4032   while (1) {
4033     if (bp >= limit) {
4034       error_with_line (line_for_error (start_line),
4035                        "unterminated string or character constant");
4036       if (eofp)
4037         *eofp = 1;
4038       break;
4039     }
4040     c = *bp++;
4041     if (c == '\\') {
4042       while (*bp == '\\' && bp[1] == '\n') {
4043         if (backslash_newlines_p)
4044           *backslash_newlines_p = 1;
4045         if (count_newlines)
4046           ++*count_newlines;
4047         bp += 2;
4048       }
4049       if (*bp == '\n' && count_newlines) {
4050         if (backslash_newlines_p)
4051           *backslash_newlines_p = 1;
4052         ++*count_newlines;
4053       }
4054       bp++;
4055     } else if (c == '\n') {
4056       /* Unterminated strings and character constants are 'legal'.  */
4057       bp--;     /* Don't consume the newline. */
4058       if (eofp)
4059         *eofp = 1;
4060       break;
4061     } else if (c == match)
4062       break;
4063   }
4064   return (U_CHAR *) bp;
4065 }
4066 \f
4067 /*
4068  * write out a #line command, for instance, after an #include file.
4069  * If CONDITIONAL is nonzero, we can omit the #line if it would
4070  * appear to be a no-op, and we can output a few newlines instead
4071  * if we want to increase the line number by a small amount.
4072  * FILE_CHANGE says whether we are entering a file, leaving, or neither.
4073  */
4074
4075 static void
4076 output_line_command (ip, op, conditional, file_change)
4077      FILE_BUF *ip, *op;
4078      int conditional;
4079      enum file_change_code file_change;
4080 {
4081   int len;
4082   char line_cmd_buf[500];
4083
4084   if (no_line_commands
4085       || ip->fname == NULL
4086       || no_output) {
4087     op->lineno = ip->lineno;
4088     return;
4089   }
4090
4091   if (conditional) {
4092     if (ip->lineno == op->lineno)
4093       return;
4094
4095     /* If the inherited line number is a little too small,
4096        output some newlines instead of a #line command.  */
4097     if (ip->lineno > op->lineno && ip->lineno < op->lineno + 8) {
4098       check_expand (op, 10);
4099       while (ip->lineno > op->lineno) {
4100         *op->bufp++ = '\n';
4101         op->lineno++;
4102       }
4103       return;
4104     }
4105   }
4106
4107   sprintf (line_cmd_buf, "# %d \"%s\"", ip->lineno, ip->fname);
4108   if (file_change != same_file)
4109     strcat (line_cmd_buf, file_change == enter_file ? " 1" : " 2");
4110   if (system_include_depth > 0)
4111     strcat (line_cmd_buf, " 3");
4112   len = strlen (line_cmd_buf);
4113   line_cmd_buf[len++] = '\n';
4114   check_expand (op, len + 1);
4115   if (op->bufp > op->buf && op->bufp[-1] != '\n')
4116     *op->bufp++ = '\n';
4117   memcpy (op->bufp, line_cmd_buf, len);
4118   op->bufp += len;
4119   op->lineno = ip->lineno;
4120 }
4121 \f
4122
4123 /* Expand a macro call.
4124    HP points to the symbol that is the macro being called.
4125    Put the result of expansion onto the input stack
4126    so that subsequent input by our caller will use it.
4127
4128    If macro wants arguments, caller has already verified that
4129    an argument list follows; arguments come from the input stack.  */
4130
4131 static void
4132 macroexpand (hp, op)
4133      HASHNODE *hp;
4134      FILE_BUF *op;
4135 {
4136   int nargs;
4137   DEFINITION *defn = hp->value.defn;
4138   U_CHAR *xbuf;
4139   int xbuf_len;
4140   int start_line = instack[indepth].lineno;
4141
4142   CHECK_DEPTH (return;);
4143
4144   /* it might not actually be a macro.  */
4145   if (hp->type != T_MACRO) {
4146     special_symbol (hp, op);
4147     return;
4148   }
4149
4150   nargs = defn->nargs;
4151
4152   if (nargs >= 0) {
4153     int i;
4154     struct argdata *args;
4155     const char *parse_error = 0;
4156
4157     args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
4158
4159     for (i = 0; i < nargs; i++) {
4160       args[i].raw = args[i].expanded = (U_CHAR *) "";
4161       args[i].raw_length = args[i].expand_length
4162         = args[i].stringified_length = 0;
4163       args[i].free1 = args[i].free2 = 0;
4164     }
4165
4166     /* Parse all the macro args that are supplied.  I counts them.
4167        The first NARGS args are stored in ARGS.
4168        The rest are discarded.  */
4169     i = 0;
4170     do {
4171       /* Discard the open-parenthesis or comma before the next arg.  */
4172       ++instack[indepth].bufp;
4173       parse_error
4174         = macarg ((i < nargs || (nargs == 0 && i == 0)) ? &args[i] : 0);
4175       if (parse_error)
4176         {
4177           error_with_line (line_for_error (start_line), "%s", parse_error);
4178           break;
4179         }
4180       i++;
4181     } while (*instack[indepth].bufp != ')');
4182
4183     /* If we got one arg but it was just whitespace, call that 0 args.  */
4184     if (i == 1) {
4185       const U_CHAR *bp = args[0].raw;
4186       const U_CHAR *lim = bp + args[0].raw_length;
4187       while (bp != lim && is_space (*bp)) bp++;
4188       if (bp == lim)
4189         i = 0;
4190     }
4191
4192     if (nargs == 0 && i > 0)
4193       error ("arguments given to macro `%s'", hp->name);
4194     else if (i < nargs) {
4195       /* traditional C allows foo() if foo wants one argument.  */
4196       if (nargs == 1 && i == 0)
4197         ;
4198       else if (i == 0)
4199         error ("no args to macro `%s'", hp->name);
4200       else if (i == 1)
4201         error ("only 1 arg to macro `%s'", hp->name);
4202       else
4203         error ("only %d args to macro `%s'", i, hp->name);
4204     } else if (i > nargs)
4205       error ("too many (%d) args to macro `%s'", i, hp->name);
4206
4207     /* Swallow the closeparen.  */
4208     ++instack[indepth].bufp;
4209
4210     /* If macro wants zero args, we parsed the arglist for checking only.
4211        Read directly from the macro definition.  */
4212     if (nargs == 0) {
4213       xbuf = defn->expansion;
4214       xbuf_len = defn->length;
4215     } else {
4216       U_CHAR *exp = defn->expansion;
4217       int offset;       /* offset in expansion,
4218                                    copied a piece at a time */
4219       int totlen;       /* total amount of exp buffer filled so far */
4220
4221       struct reflist *ap;
4222
4223       /* Macro really takes args.  Compute the expansion of this call.  */
4224
4225       /* Compute length in characters of the macro's expansion.  */
4226       xbuf_len = defn->length;
4227       for (ap = defn->pattern; ap != NULL; ap = ap->next) {
4228         if (ap->stringify)
4229           xbuf_len += args[ap->argno].stringified_length;
4230         else 
4231           xbuf_len += args[ap->argno].raw_length;
4232       }
4233
4234       xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
4235
4236       /* Generate in XBUF the complete expansion
4237          with arguments substituted in.
4238          TOTLEN is the total size generated so far.
4239          OFFSET is the index in the definition
4240          of where we are copying from.  */
4241       offset = totlen = 0;
4242       for (ap = defn->pattern; ap != NULL; ap = ap->next) {
4243         struct argdata *arg = &args[ap->argno];
4244
4245         for (i = 0; i < ap->nchars; i++)
4246           xbuf[totlen++] = exp[offset++];
4247
4248         if (ap->stringify != 0) {
4249           int arglen = arg->raw_length;
4250           int escaped = 0;
4251           int in_string = 0;
4252           int c;
4253           i = 0;
4254           while (i < arglen
4255                  && (c = arg->raw[i], is_space (c)))
4256             i++;
4257           while (i < arglen
4258                  && (c = arg->raw[arglen - 1], is_space (c)))
4259             arglen--;
4260           for (; i < arglen; i++) {
4261             c = arg->raw[i];
4262
4263             /* Special markers Newline Space
4264                generate nothing for a stringified argument.  */
4265             if (c == '\n' && arg->raw[i+1] != '\n') {
4266               i++;
4267               continue;
4268             }
4269
4270             /* Internal sequences of whitespace are replaced by one space
4271                except within an string or char token.  */
4272             if (! in_string
4273                 && (c == '\n' ? arg->raw[i+1] == '\n' : is_space (c))) {
4274               while (1) {
4275                 /* Note that Newline Space does occur within whitespace
4276                    sequences; consider it part of the sequence.  */
4277                 if (c == '\n' && is_space (arg->raw[i+1]))
4278                   i += 2;
4279                 else if (c != '\n' && is_space (c))
4280                   i++;
4281                 else break;
4282                 c = arg->raw[i];
4283               }
4284               i--;
4285               c = ' ';
4286             }
4287
4288             if (escaped)
4289               escaped = 0;
4290             else {
4291               if (c == '\\')
4292                 escaped = 1;
4293               if (in_string) {
4294                 if (c == in_string)
4295                   in_string = 0;
4296               } else if (c == '\"' || c == '\'')
4297                 in_string = c;
4298             }
4299
4300             /* Escape these chars */
4301             if (c == '\"' || (in_string && c == '\\'))
4302               xbuf[totlen++] = '\\';
4303             if (ISPRINT (c))
4304               xbuf[totlen++] = c;
4305             else {
4306               sprintf ((char *) &xbuf[totlen], "\\%03o", (unsigned int) c);
4307               totlen += 4;
4308             }
4309           }
4310         } else {
4311           const U_CHAR *p1 = arg->raw;
4312           const U_CHAR *l1 = p1 + arg->raw_length;
4313
4314           if (ap->raw_before) {
4315             while (p1 != l1 && is_space (*p1)) p1++;
4316             while (p1 != l1 && is_idchar (*p1))
4317               xbuf[totlen++] = *p1++;
4318             /* Delete any no-reexpansion marker that follows
4319                an identifier at the beginning of the argument
4320                if the argument is concatenated with what precedes it.  */
4321             if (p1[0] == '\n' && p1[1] == '-')
4322               p1 += 2;
4323           }
4324           if (ap->raw_after) {
4325             /* Arg is concatenated after: delete trailing whitespace,
4326                whitespace markers, and no-reexpansion markers.  */
4327             while (p1 != l1) {
4328               if (is_space (l1[-1])) l1--;
4329               else if (l1[-1] == '-') {
4330                 const U_CHAR *p2 = l1 - 1;
4331                 /* If a `-' is preceded by an odd number of newlines then it
4332                    and the last newline are a no-reexpansion marker.  */
4333                 while (p2 != p1 && p2[-1] == '\n') p2--;
4334                 if ((l1 - 1 - p2) & 1) {
4335                   l1 -= 2;
4336                 }
4337                 else break;
4338               }
4339               else break;
4340             }
4341           }
4342           memmove (xbuf + totlen, p1, l1 - p1);
4343           totlen += l1 - p1;
4344         }
4345
4346         if (totlen > xbuf_len)
4347           abort ();
4348       }
4349
4350       /* if there is anything left of the definition
4351          after handling the arg list, copy that in too. */
4352
4353       for (i = offset; i < defn->length; i++)
4354         xbuf[totlen++] = exp[i];
4355
4356       xbuf[totlen] = 0;
4357       xbuf_len = totlen;
4358
4359       for (i = 0; i < nargs; i++) {
4360         if (args[i].free1 != 0)
4361           free (args[i].free1);
4362         if (args[i].free2 != 0)
4363           free (args[i].free2);
4364       }
4365     }
4366   } else {
4367     xbuf = defn->expansion;
4368     xbuf_len = defn->length;
4369   }
4370
4371   /* Now put the expansion on the input stack
4372      so our caller will commence reading from it.  */
4373   {
4374     FILE_BUF *ip2;
4375
4376     ip2 = &instack[++indepth];
4377
4378     ip2->fname = 0;
4379     ip2->lineno = 0;
4380     ip2->buf = xbuf;
4381     ip2->length = xbuf_len;
4382     ip2->bufp = xbuf;
4383     ip2->free_ptr = (nargs > 0) ? xbuf : 0;
4384     ip2->macro = hp;
4385     ip2->if_stack = if_stack;
4386   }
4387 }
4388 \f
4389 /*
4390  * Parse a macro argument and store the info on it into *ARGPTR.
4391  * Return nonzero to indicate a syntax error.
4392  */
4393
4394 static const char *
4395 macarg (argptr)
4396      struct argdata *argptr;
4397 {
4398   FILE_BUF *ip = &instack[indepth];
4399   int paren = 0;
4400   int newlines = 0;
4401   int comments = 0;
4402
4403   /* Try to parse as much of the argument as exists at this
4404      input stack level.  */
4405   U_CHAR *bp = macarg1 (ip->bufp, ip->buf + ip->length,
4406                         &paren, &newlines, &comments);
4407
4408   /* If we find the end of the argument at this level,
4409      set up *ARGPTR to point at it in the input stack.  */
4410   if (!(ip->fname != 0 && (newlines != 0 || comments != 0))
4411       && bp != ip->buf + ip->length) {
4412     if (argptr != 0) {
4413       argptr->raw = ip->bufp;
4414       argptr->raw_length = bp - ip->bufp;
4415     }
4416     ip->bufp = bp;
4417   } else {
4418     /* This input stack level ends before the macro argument does.
4419        We must pop levels and keep parsing.
4420        Therefore, we must allocate a temporary buffer and copy
4421        the macro argument into it.  */
4422     int bufsize = bp - ip->bufp;
4423     int extra = newlines;
4424     U_CHAR *buffer = (U_CHAR *) xmalloc (bufsize + extra + 1);
4425     int final_start = 0;
4426
4427     memcpy (buffer, ip->bufp, bufsize);
4428     ip->bufp = bp;
4429     ip->lineno += newlines;
4430
4431     while (bp == ip->buf + ip->length) {
4432       if (instack[indepth].macro == 0) {
4433         free (buffer);
4434         return "unterminated macro call";
4435       }
4436       ip->macro->type = T_MACRO;
4437       if (ip->free_ptr)
4438         free (ip->free_ptr);
4439       ip = &instack[--indepth];
4440       newlines = 0;
4441       comments = 0;
4442       bp = macarg1 (ip->bufp, ip->buf + ip->length, &paren,
4443                     &newlines, &comments);
4444       final_start = bufsize;
4445       bufsize += bp - ip->bufp;
4446       extra += newlines;
4447       buffer = (U_CHAR *) xrealloc (buffer, bufsize + extra + 1);
4448       memcpy (buffer + bufsize - (bp - ip->bufp), ip->bufp, bp - ip->bufp);
4449       ip->bufp = bp;
4450       ip->lineno += newlines;
4451     }
4452
4453     /* Now, if arg is actually wanted, record its raw form,
4454        discarding comments and duplicating newlines in whatever
4455        part of it did not come from a macro expansion.
4456        EXTRA space has been preallocated for duplicating the newlines.
4457        FINAL_START is the index of the start of that part.  */
4458     if (argptr != 0) {
4459       argptr->raw = buffer;
4460       argptr->raw_length = bufsize;
4461       argptr->free1 = buffer;
4462       argptr->newlines = newlines;
4463       argptr->comments = comments;
4464       if ((newlines || comments) && ip->fname != 0)
4465         argptr->raw_length
4466           = final_start +
4467             discard_comments (argptr->raw + final_start,
4468                               argptr->raw_length - final_start,
4469                               newlines);
4470       argptr->raw[argptr->raw_length] = 0;
4471       if (argptr->raw_length > bufsize + extra)
4472         abort ();
4473     }
4474   }
4475
4476   /* If we are not discarding this argument,
4477      macroexpand it and compute its length as stringified.
4478      All this info goes into *ARGPTR.  */
4479
4480   if (argptr != 0) {
4481     FILE_BUF obuf;
4482     const U_CHAR *buf, *lim;
4483     int totlen;
4484
4485     obuf = expand_to_temp_buffer (argptr->raw,
4486                                   argptr->raw + argptr->raw_length,
4487                                   1);
4488
4489     argptr->expanded = obuf.buf;
4490     argptr->expand_length = obuf.length;
4491     argptr->free2 = obuf.buf;
4492
4493     buf = argptr->raw;
4494     lim = buf + argptr->raw_length;
4495
4496     totlen = 0;
4497     while (buf != lim) {
4498       U_CHAR c = *buf++;
4499       totlen++;
4500       /* Internal sequences of whitespace are replaced by one space
4501          in most cases, but not always.  So count all the whitespace
4502          in case we need to keep it all.  */
4503       if (c == '\"' || c == '\\') /* escape these chars */
4504         totlen++;
4505       else if (!ISPRINT (c))
4506         totlen += 3;
4507     }
4508     argptr->stringified_length = totlen;
4509   }
4510   return 0;
4511 }
4512
4513 /* Scan text from START (inclusive) up to LIMIT (exclusive),
4514    counting parens in *DEPTHPTR,
4515    and return if reach LIMIT
4516    or before a `)' that would make *DEPTHPTR negative
4517    or before a comma when *DEPTHPTR is zero.
4518    Single and double quotes are matched and termination
4519    is inhibited within them.  Comments also inhibit it.
4520    Value returned is pointer to stopping place.
4521
4522    Increment *NEWLINES each time a newline is passed.
4523    Set *COMMENTS to 1 if a comment is seen.  */
4524
4525 static U_CHAR *
4526 macarg1 (start, limit, depthptr, newlines, comments)
4527      U_CHAR *start;
4528      const U_CHAR *limit;
4529      int *depthptr, *newlines, *comments;
4530 {
4531   U_CHAR *bp = start;
4532
4533   while (bp < limit) {
4534     switch (*bp) {
4535     case '(':
4536       (*depthptr)++;
4537       break;
4538     case ')':
4539       if (--(*depthptr) < 0)
4540         return bp;
4541       break;
4542     case '\\':
4543       /* Traditionally, backslash makes following char not special.  */
4544       if (bp + 1 < limit)
4545         {
4546           bp++;
4547           /* But count source lines anyway.  */
4548           if (*bp == '\n')
4549             ++*newlines;
4550         }
4551       break;
4552     case '\n':
4553       ++*newlines;
4554       break;
4555     case '/':
4556       if (bp[1] == '\\' && bp[2] == '\n')
4557         newline_fix (bp + 1);
4558       if (bp[1] != '*' || bp + 1 >= limit)
4559         break;
4560       *comments = 1;
4561       bp += 2;
4562       while (bp + 1 < limit) {
4563         if (bp[0] == '*'
4564             && bp[1] == '\\' && bp[2] == '\n')
4565           newline_fix (bp + 1);
4566         if (bp[0] == '*' && bp[1] == '/')
4567           break;
4568         if (*bp == '\n') ++*newlines;
4569         bp++;
4570       }
4571       bp += 1;
4572       break;
4573     case '\'':
4574     case '\"':
4575       {
4576         int quotec;
4577         for (quotec = *bp++; bp + 1 < limit && *bp != quotec; bp++) {
4578           if (*bp == '\\') {
4579             bp++;
4580             if (*bp == '\n')
4581               ++*newlines;
4582             while (*bp == '\\' && bp[1] == '\n') {
4583               bp += 2;
4584             }
4585           } else if (*bp == '\n') {
4586             ++*newlines;
4587             if (quotec == '\'')
4588               break;
4589           }
4590         }
4591       }
4592       break;
4593     case ',':
4594       if ((*depthptr) == 0)
4595         return bp;
4596       break;
4597     }
4598     bp++;
4599   }
4600
4601   return bp;
4602 }
4603
4604 /* Discard comments and duplicate newlines
4605    in the string of length LENGTH at START,
4606    except inside of string constants.
4607    The string is copied into itself with its beginning staying fixed.  
4608
4609    NEWLINES is the number of newlines that must be duplicated.
4610    We assume that that much extra space is available past the end
4611    of the string.  */
4612
4613 static int
4614 discard_comments (start, length, newlines)
4615      U_CHAR *start;
4616      int length;
4617      int newlines;
4618 {
4619   U_CHAR *ibp;
4620   U_CHAR *obp;
4621   const U_CHAR *limit;
4622   int c;
4623
4624   /* If we have newlines to duplicate, copy everything
4625      that many characters up.  Then, in the second part,
4626      we will have room to insert the newlines
4627      while copying down.
4628      NEWLINES may actually be too large, because it counts
4629      newlines in string constants, and we don't duplicate those.
4630      But that does no harm.  */
4631   if (newlines > 0) {
4632     ibp = start + length;
4633     obp = ibp + newlines;
4634     limit = start;
4635     while (limit != ibp)
4636       *--obp = *--ibp;
4637   }
4638
4639   ibp = start + newlines;
4640   limit = start + length + newlines;
4641   obp = start;
4642
4643   while (ibp < limit) {
4644     *obp++ = c = *ibp++;
4645     switch (c) {
4646     case '\n':
4647       /* Duplicate the newline.  */
4648       *obp++ = '\n';
4649       break;
4650
4651     case '\\':
4652       if (*ibp == '\n') {
4653         obp--;
4654         ibp++;
4655       }
4656       break;
4657
4658     case '/':
4659       if (*ibp == '\\' && ibp[1] == '\n')
4660         newline_fix (ibp);
4661       /* Delete any comment.  */
4662       if (ibp[0] != '*' || ibp + 1 >= limit)
4663         break;
4664       obp--;
4665       ibp++;
4666       while (ibp + 1 < limit) {
4667         if (ibp[0] == '*'
4668             && ibp[1] == '\\' && ibp[2] == '\n')
4669           newline_fix (ibp + 1);
4670         if (ibp[0] == '*' && ibp[1] == '/')
4671           break;
4672         ibp++;
4673       }
4674       ibp += 2;
4675       break;
4676
4677     case '\'':
4678     case '\"':
4679       /* Notice and skip strings, so that we don't
4680          think that comments start inside them,
4681          and so we don't duplicate newlines in them.  */
4682       {
4683         int quotec = c;
4684         while (ibp < limit) {
4685           *obp++ = c = *ibp++;
4686           if (c == quotec)
4687             break;
4688           if (c == '\n' && quotec == '\'')
4689             break;
4690           if (c == '\\' && ibp < limit) {
4691             while (*ibp == '\\' && ibp[1] == '\n')
4692               ibp += 2;
4693             *obp++ = *ibp++;
4694           }
4695         }
4696       }
4697       break;
4698     }
4699   }
4700
4701   return obp - start;
4702 }
4703 \f
4704
4705 /* Core error handling routine.  */
4706 static void
4707 v_message (mtype, line, msgid, ap)
4708      enum msgtype mtype;
4709      int line;
4710      const char *msgid;
4711      va_list ap;
4712 {
4713   const char *fname = 0;
4714   int i;
4715
4716   if (mtype == MT_WARNING && inhibit_warnings)
4717     return;
4718
4719   for (i = indepth; i >= 0; i--)
4720     if (instack[i].fname != NULL) {
4721       if (line == 0)
4722         line = instack[i].lineno;
4723       fname = instack[i].fname;
4724       break;
4725     }
4726
4727   if (fname)
4728     fprintf (stderr, "%s:%d: ", fname, line);
4729   else
4730     fprintf (stderr, "%s: ", progname);
4731
4732   if (mtype == MT_WARNING)
4733     fputs (_("warning: "), stderr);
4734
4735   vfprintf (stderr, _(msgid), ap);
4736   putc ('\n', stderr);
4737
4738   if (mtype == MT_ERROR)
4739     errors++;
4740 }
4741
4742 /*
4743  * error - print error message and increment count of errors.
4744  */
4745 void
4746 error VPARAMS ((const char *msgid, ...))
4747 {
4748   VA_OPEN(ap, msgid);
4749   VA_FIXEDARG (ap, const char *, msgid);
4750
4751   v_message (MT_ERROR, 0, msgid, ap);
4752   VA_CLOSE (ap);
4753 }
4754
4755 void
4756 error_with_line VPARAMS ((int line, const char *msgid, ...))
4757 {
4758   VA_OPEN(ap, msgid);
4759   VA_FIXEDARG (ap, int, line);
4760   VA_FIXEDARG (ap, const char *, msgid);
4761
4762   v_message (MT_ERROR, line, msgid, ap);
4763   VA_CLOSE (ap);
4764 }
4765
4766 /* Error including a message from `errno'.  */
4767 void
4768 error_from_errno (name)
4769      const char *name;
4770 {
4771   error ("%s: %s", name, strerror (errno));
4772 }
4773
4774 /* Print error message but don't count it.  */
4775 void
4776 warning VPARAMS ((const char *msgid, ...))
4777 {
4778   VA_OPEN(ap, msgid);
4779   VA_FIXEDARG (ap, const char *, msgid);
4780
4781   v_message (MT_WARNING, 0, msgid, ap);
4782   VA_CLOSE (ap);
4783 }
4784
4785 void
4786 fatal VPARAMS ((const char *msgid, ...))
4787 {
4788   VA_OPEN(ap, msgid);
4789   VA_FIXEDARG (ap, const char *, msgid);
4790
4791   v_message (MT_FATAL, 0, msgid, ap);
4792   VA_CLOSE (ap);
4793   exit (FATAL_EXIT_CODE);
4794 }
4795
4796 /* More 'friendly' abort that prints the location at which we died.  */
4797 void
4798 fancy_abort (line, func)
4799      int line;
4800      const char *func;
4801 {
4802   fatal ("internal error in %s, at tradcpp.c:%d\n\
4803 Please submit a full bug report.\n\
4804 See %s for instructions.", func, line, GCCBUGURL);
4805 }
4806
4807 void
4808 perror_with_name (name)
4809      const char *name;
4810 {
4811   fprintf (stderr, "%s: %s: %s\n", progname, name, strerror (errno));
4812   errors++;
4813 }
4814
4815 void
4816 pfatal_with_name (name)
4817      const char *name;
4818 {
4819   perror_with_name (name);
4820   exit (FATAL_EXIT_CODE);
4821 }
4822
4823 /* Return the line at which an error occurred.
4824    The error is not necessarily associated with the current spot
4825    in the input stack, so LINE says where.  LINE will have been
4826    copied from ip->lineno for the current input level.
4827    If the current level is for a file, we return LINE.
4828    But if the current level is not for a file, LINE is meaningless.
4829    In that case, we return the lineno of the innermost file.  */
4830 static int
4831 line_for_error (line)
4832      int line;
4833 {
4834   int i;
4835   int line1 = line;
4836
4837   for (i = indepth; i >= 0; ) {
4838     if (instack[i].fname != 0)
4839       return line1;
4840     i--;
4841     if (i < 0)
4842       return 0;
4843     line1 = instack[i].lineno;
4844   }
4845   return 0;
4846 }
4847
4848 /*
4849  * If OBUF doesn't have NEEDED bytes after OPTR, make it bigger.
4850  *
4851  * As things stand, nothing is ever placed in the output buffer to be
4852  * removed again except when it's KNOWN to be part of an identifier,
4853  * so flushing and moving down everything left, instead of expanding,
4854  * should work ok.
4855  */
4856
4857 static void
4858 grow_outbuf (obuf, needed)
4859      FILE_BUF *obuf;
4860      int needed;
4861 {
4862   U_CHAR *p;
4863   int minsize;
4864
4865   if (obuf->length - (obuf->bufp - obuf->buf) > needed)
4866     return;
4867
4868   /* Make it at least twice as big as it is now.  */
4869   obuf->length *= 2;
4870   /* Make it have at least 150% of the free space we will need.  */
4871   minsize = (3 * needed) / 2 + (obuf->bufp - obuf->buf);
4872   if (minsize > obuf->length)
4873     obuf->length = minsize;
4874
4875   p = (U_CHAR *) xrealloc (obuf->buf, obuf->length);
4876   obuf->bufp = p + (obuf->bufp - obuf->buf);
4877   obuf->buf = p;
4878 }
4879 \f
4880 /* Symbol table for macro names and special symbols */
4881
4882 /*
4883  * install a name in the main hash table, even if it is already there.
4884  *   name stops with first non alphanumeric, except leading '#'.
4885  * caller must check against redefinition if that is desired.
4886  * delete_macro () removes things installed by install () in fifo order.
4887  * this is important because of the `defined' special symbol used
4888  * in #if, and also if pushdef/popdef directives are ever implemented.
4889  *
4890  * If LEN is >= 0, it is the length of the name.
4891  * Otherwise, compute the length by scanning the entire name.
4892  *
4893  * If HASH is >= 0, it is the precomputed hash code.
4894  * Otherwise, compute the hash code.
4895  *
4896  * caller must set the value, if any is desired.
4897  */
4898 static HASHNODE *
4899 install (name, len, type, hash)
4900      const U_CHAR *name;
4901      int len;
4902      enum node_type type;
4903      int hash;
4904         /* watch out here if sizeof (U_CHAR *) != sizeof (int) */
4905 {
4906   HASHNODE *hp;
4907   int bucket;
4908   const U_CHAR *p;
4909   U_CHAR *q;
4910
4911   if (len < 0) {
4912     p = name;
4913     while (is_idchar (*p))
4914       p++;
4915     len = p - name;
4916   }
4917
4918   if (hash < 0)
4919     hash = hashf (name, len, HASHSIZE);
4920
4921   hp = (HASHNODE *) xmalloc (sizeof (HASHNODE) + len + 1);
4922   bucket = hash;
4923   hp->bucket_hdr = &hashtab[bucket];
4924   hp->next = hashtab[bucket];
4925   hashtab[bucket] = hp;
4926   hp->prev = NULL;
4927   if (hp->next != NULL)
4928     hp->next->prev = hp;
4929   hp->type = type;
4930   hp->length = len;
4931   hp->name = q = ((U_CHAR *) hp) + sizeof (HASHNODE);
4932   memcpy (q, name, len);
4933   q[len] = 0;
4934   return hp;
4935 }
4936
4937 /*
4938  * find the most recent hash node for name name (ending with first
4939  * non-identifier char) installed by install
4940  *
4941  * If LEN is >= 0, it is the length of the name.
4942  * Otherwise, compute the length by scanning the entire name.
4943  *
4944  * If HASH is >= 0, it is the precomputed hash code.
4945  * Otherwise, compute the hash code.
4946  */
4947 HASHNODE *
4948 lookup (name, len, hash)
4949      const U_CHAR *name;
4950      int len;
4951      int hash;
4952 {
4953   const U_CHAR *bp;
4954   HASHNODE *bucket;
4955
4956   if (len < 0) {
4957     for (bp = name; is_idchar (*bp); bp++) ;
4958     len = bp - name;
4959   }
4960
4961   if (hash < 0)
4962     hash = hashf (name, len, HASHSIZE);
4963
4964   bucket = hashtab[hash];
4965   while (bucket) {
4966     if (bucket->length == len
4967         && strncmp ((const char *)bucket->name, (const char *)name, len) == 0)
4968       return bucket;
4969     bucket = bucket->next;
4970   }
4971   return NULL;
4972 }
4973
4974 /*
4975  * Delete a hash node.  Some weirdness to free junk from macros.
4976  * More such weirdness will have to be added if you define more hash
4977  * types that need it.
4978  */
4979
4980 /* Note that the DEFINITION of a macro is removed from the hash table
4981    but its storage is not freed.  This would be a storage leak
4982    except that it is not reasonable to keep undefining and redefining
4983    large numbers of macros many times.
4984    In any case, this is necessary, because a macro can be #undef'd
4985    in the middle of reading the arguments to a call to it.
4986    If #undef freed the DEFINITION, that would crash.  */
4987 static void
4988 delete_macro (hp)
4989      HASHNODE *hp;
4990 {
4991
4992   if (hp->prev != NULL)
4993     hp->prev->next = hp->next;
4994   if (hp->next != NULL)
4995     hp->next->prev = hp->prev;
4996
4997   /* make sure that the bucket chain header that
4998      the deleted guy was on points to the right thing afterwards. */
4999   if (hp == *hp->bucket_hdr)
5000     *hp->bucket_hdr = hp->next;
5001
5002   free (hp);
5003 }
5004
5005 /*
5006  * return hash function on name.  must be compatible with the one
5007  * computed a step at a time, elsewhere
5008  */
5009 static int
5010 hashf (name, len, hashsize)
5011      const U_CHAR *name;
5012      int len;
5013      int hashsize;
5014 {
5015   int r = 0;
5016
5017   while (len--)
5018     r = HASHSTEP (r, *name++);
5019
5020   return MAKE_POS (r) % hashsize;
5021 }
5022 \f
5023 /* Dump all macro definitions as #defines to stdout.  */
5024
5025 static void
5026 dump_all_macros ()
5027 {
5028   int bucket;
5029
5030   for (bucket = 0; bucket < HASHSIZE; bucket++) {
5031     HASHNODE *hp;
5032
5033     for (hp = hashtab[bucket]; hp; hp= hp->next) {
5034       if (hp->type == T_MACRO) {
5035         DEFINITION *defn = hp->value.defn;
5036         struct reflist *ap;
5037         int offset;
5038         int concat;
5039
5040
5041         /* Print the definition of the macro HP.  */
5042
5043         printf ("#define %s", hp->name);
5044         if (defn->nargs >= 0) {
5045           int i;
5046
5047           printf ("(");
5048           for (i = 0; i < defn->nargs; i++) {
5049             dump_arg_n (defn, i);
5050             if (i + 1 < defn->nargs)
5051               printf (", ");
5052           }
5053           printf (")");
5054         }
5055
5056         printf (" ");
5057
5058         offset = 0;
5059         concat = 0;
5060         for (ap = defn->pattern; ap != NULL; ap = ap->next) {
5061           dump_defn_1 (defn->expansion, offset, ap->nchars);
5062           if (ap->nchars != 0)
5063             concat = 0;
5064           offset += ap->nchars;
5065           if (ap->stringify)
5066             printf (" #");
5067           if (ap->raw_before && !concat)
5068             printf (" ## ");
5069           concat = 0;
5070           dump_arg_n (defn, ap->argno);
5071           if (ap->raw_after) {
5072             printf (" ## ");
5073             concat = 1;
5074           }
5075         }
5076         dump_defn_1 (defn->expansion, offset, defn->length - offset);
5077         printf ("\n");
5078       }
5079     }
5080   }
5081 }
5082
5083 /* Output to stdout a substring of a macro definition.
5084    BASE is the beginning of the definition.
5085    Output characters START thru LENGTH.
5086    Discard newlines outside of strings, thus
5087    converting funny-space markers to ordinary spaces.  */
5088 static void
5089 dump_defn_1 (base, start, length)
5090      const U_CHAR *base;
5091      int start;
5092      int length;
5093 {
5094   const U_CHAR *p = base + start;
5095   const U_CHAR *limit = base + start + length;
5096
5097   while (p < limit) {
5098     if (*p != '\n')
5099       putchar (*p);
5100     else if (*p == '\"' || *p =='\'') {
5101       const U_CHAR *p1 = skip_quoted_string (p, limit, 0, 0, 0, 0);
5102       fwrite (p, p1 - p, 1, stdout);
5103       p = p1 - 1;
5104     }
5105     p++;
5106   }
5107 }
5108
5109 /* Print the name of argument number ARGNUM of macro definition DEFN.
5110    Recall that DEFN->argnames contains all the arg names
5111    concatenated in reverse order with comma-space in between.  */
5112 static void
5113 dump_arg_n (defn, argnum)
5114      DEFINITION *defn;
5115      int argnum;
5116 {
5117   const U_CHAR *p = defn->argnames;
5118   while (argnum + 1 < defn->nargs) {
5119     p = (const U_CHAR *) strchr ((const char *)p, ' ') + 1;
5120     argnum++;
5121   }
5122
5123   while (*p && *p != ',') {
5124     putchar (*p);
5125     p++;
5126   }
5127 }
5128
5129 /* Initialize the built-in macros.  */
5130 #define DSC(x) U x, sizeof x - 1
5131 #define install_spec(name, type) \
5132  install(DSC(name), type, -1);
5133 #define install_value(name, val) \
5134  hp = install(DSC(name), T_CONST, -1); hp->value.cpval = val;
5135 static void
5136 initialize_builtins ()
5137 {
5138   HASHNODE *hp;
5139
5140   install_spec ("__BASE_FILE__",     T_BASE_FILE);
5141   install_spec ("__DATE__",          T_DATE);
5142   install_spec ("__FILE__",          T_FILE);
5143   install_spec ("__TIME__",          T_TIME);
5144   install_spec ("__VERSION__",       T_VERSION);
5145   install_spec ("__INCLUDE_LEVEL__", T_INCLUDE_LEVEL);
5146   install_spec ("__LINE__",          T_SPECLINE);
5147
5148 #ifndef NO_BUILTIN_SIZE_TYPE
5149   install_value ("__SIZE_TYPE__",         SIZE_TYPE);
5150 #endif
5151 #ifndef NO_BUILTIN_PTRDIFF_TYPE
5152   install_value ("__PTRDIFF_TYPE__",      PTRDIFF_TYPE);
5153 #endif
5154 #ifndef NO_BUILTIN_WCHAR_TYPE
5155   install_value ("__WCHAR_TYPE__",        WCHAR_TYPE);
5156 #endif
5157 #ifndef NO_BUILTIN_WINT_TYPE
5158   install_value ("__WINT_TYPE__",         WINT_TYPE);
5159 #endif
5160   install_value ("__REGISTER_PREFIX__",   REGISTER_PREFIX);
5161   install_value ("__USER_LABEL_PREFIX__", user_label_prefix);
5162
5163   if (flag_signed_char == 0)
5164     install_value ("__CHAR_UNSIGNED__", "1");
5165 }
5166 #undef DSC
5167 #undef install_spec
5168 #undef install_value
5169 \f
5170 /* Common handler of command line directives -U, -D and -A.  */
5171 static void
5172 run_directive (str, len, type)
5173      const char *str;
5174      size_t len;
5175      enum node_type type;
5176 {
5177   const struct directive *kt;
5178   FILE_BUF *ip = &instack[++indepth];
5179   ip->fname = "*command line*";
5180
5181   ip->buf = ip->bufp = (U_CHAR *) str;
5182   ip->length = len;
5183   ip->lineno = 1;
5184   ip->macro = 0;
5185   ip->free_ptr = 0;
5186   ip->if_stack = if_stack;
5187
5188   for (kt = directive_table; kt->type != type; kt++)
5189     ;
5190
5191   (*kt->func) ((U_CHAR *) str, (U_CHAR *) str + len, NULL);
5192   --indepth;
5193 }
5194
5195 /* Handle the -D option.  If STR is just an identifier, define it with
5196  * value 1.  If STR has anything after the identifier, then it should
5197  * be identifier-space-definition.  */
5198 static void
5199 make_definition (str)
5200      const char *str;
5201 {
5202   char *buf, *p;
5203   size_t count;
5204
5205   /* Copy the entire option so we can modify it. 
5206      Change the first "=" in the string to a space.  If there is none,
5207      tack " 1" on the end.  */
5208
5209   /* Length including the null.  */  
5210   count = strlen (str);
5211   buf = (char *) alloca (count + 2);
5212   memcpy (buf, str, count);
5213
5214   p = strchr (str, '=');
5215   if (p)
5216     buf[p - str] = ' ';
5217   else
5218     {
5219       buf[count++] = ' ';
5220       buf[count++] = '1';
5221     }
5222
5223   run_directive (buf, count, T_DEFINE);
5224 }
5225
5226 /* Handle the -U option.  */
5227 static void
5228 make_undef (str)
5229      const char *str;
5230 {
5231   run_directive (str, strlen (str), T_UNDEF);
5232 }
5233
5234 /* Handles the #assert (-A) and #unassert (-A-) command line options.  */
5235 static void
5236 make_assertion (str)
5237      const char *str;
5238 {
5239   enum node_type type = T_ASSERT;
5240   size_t count;
5241   const char *p;
5242
5243   if (*str == '-')
5244     {
5245       str++;
5246       type = T_UNASSERT;
5247     }
5248   
5249   count = strlen (str);
5250   p = strchr (str, '=');
5251   if (p)
5252     {
5253       /* Copy the entire option so we can modify it.  Change the first
5254          "=" in the string to a '(', and tack a ')' on the end.  */
5255       char *buf = (char *) alloca (count + 1);
5256
5257       memcpy (buf, str, count);
5258       buf[p - str] = '(';
5259       buf[count++] = ')';
5260       str = buf;
5261     }
5262
5263   run_directive (str, count, type);
5264 }
5265 \f
5266 /* Get the file-mode and data size of the file open on FD
5267    and store them in *MODE_POINTER and *SIZE_POINTER.  */
5268
5269 static int
5270 file_size_and_mode (fd, mode_pointer, size_pointer)
5271      int fd;
5272      int *mode_pointer;
5273      long *size_pointer;
5274 {
5275   struct stat sbuf;
5276
5277   if (fstat (fd, &sbuf) < 0) return -1;
5278   if (mode_pointer) *mode_pointer = sbuf.st_mode;
5279   if (size_pointer) *size_pointer = sbuf.st_size;
5280   return 0;
5281 }