OSDN Git Service

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