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