OSDN Git Service

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