OSDN Git Service

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