OSDN Git Service

* libgcc2.c (__bb_exit_func): Support gcov style output.
[pf3gnuchains/gcc-fork.git] / gcc / cpplib.c
1 /* CPP Library.
2    Copyright (C) 1986, 87, 89, 92-6, 1997 Free Software Foundation, Inc.
3    Contributed by Per Bothner, 1994-95.
4    Based on CCCP program by Paul Rubin, June 1986
5    Adapted to ANSI C, Richard Stallman, Jan 1987
6
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20
21  In other words, you are welcome to use, share and improve this program.
22  You are forbidden to forbid anyone else to use, share and improve
23  what you give them.   Help stamp out software-hoarding!  */
24
25 #ifdef EMACS
26 #define NO_SHORTNAMES
27 #include "../src/config.h"
28 #ifdef open
29 #undef open
30 #undef read
31 #undef write
32 #endif /* open */
33 #endif /* EMACS */
34
35 /* The macro EMACS is defined when cpp is distributed as part of Emacs,
36    for the sake of machines with limited C compilers.  */
37 #ifndef EMACS
38 #include "config.h"
39 #endif /* not EMACS */
40
41 #ifndef STANDARD_INCLUDE_DIR
42 #define STANDARD_INCLUDE_DIR "/usr/include"
43 #endif
44
45 #if 0 /* We can't get ptrdiff_t, so I arranged not to need PTR_INT_TYPE.  */
46 #ifdef __STDC__
47 #define PTR_INT_TYPE ptrdiff_t
48 #else
49 #define PTR_INT_TYPE long
50 #endif
51 #endif /* 0 */
52
53 #include "cpplib.h"
54 #include "cpphash.h"
55
56 #ifndef STDC_VALUE
57 #define STDC_VALUE 1
58 #endif
59
60 /* By default, colon separates directories in a path.  */
61 #ifndef PATH_SEPARATOR
62 #define PATH_SEPARATOR ':'
63 #endif
64
65 #include <ctype.h>
66 #include <stdio.h>
67 #include <signal.h>
68 #ifdef __STDC__
69 #include <stdlib.h>
70 #endif
71
72 #ifndef VMS
73 #ifndef USG
74 #include <sys/time.h>           /* for __DATE__ and __TIME__ */
75 #include <sys/resource.h>
76 #else
77 #include <sys/times.h>
78 #include <time.h>
79 #include <fcntl.h>
80 #endif /* USG */
81 #endif /* not VMS */
82
83 /* This defines "errno" properly for VMS, and gives us EACCES.  */
84 #include <errno.h>
85
86 extern char *index ();
87 extern char *rindex ();
88
89 #ifndef O_RDONLY
90 #define O_RDONLY 0
91 #endif
92
93 #undef MIN
94 #undef MAX
95 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
96 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
97
98 /* Find the largest host integer type and set its size and type.  */
99
100 #ifndef HOST_BITS_PER_WIDE_INT
101
102 #if HOST_BITS_PER_LONG > HOST_BITS_PER_INT
103 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_LONG
104 #define HOST_WIDE_INT long
105 #else
106 #define HOST_BITS_PER_WIDE_INT HOST_BITS_PER_INT
107 #define HOST_WIDE_INT int
108 #endif
109
110 #endif
111
112 #ifndef S_ISREG
113 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
114 #endif
115
116 #ifndef S_ISDIR
117 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
118 #endif
119
120 /* Define a generic NULL if one hasn't already been defined.  */
121
122 #ifndef NULL
123 #define NULL 0
124 #endif
125
126 #ifndef GENERIC_PTR
127 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
128 #define GENERIC_PTR void *
129 #else
130 #define GENERIC_PTR char *
131 #endif
132 #endif
133
134 #ifndef NULL_PTR
135 #define NULL_PTR ((GENERIC_PTR) 0)
136 #endif
137
138 #ifndef INCLUDE_LEN_FUDGE
139 #define INCLUDE_LEN_FUDGE 0
140 #endif
141
142 /* Symbols to predefine.  */
143
144 #ifdef CPP_PREDEFINES
145 static char *predefs = CPP_PREDEFINES;
146 #else
147 static char *predefs = "";
148 #endif
149 \f
150 /* We let tm.h override the types used here, to handle trivial differences
151    such as the choice of unsigned int or long unsigned int for size_t.
152    When machines start needing nontrivial differences in the size type,
153    it would be best to do something here to figure out automatically
154    from other information what type to use.  */
155
156 /* The string value for __SIZE_TYPE__.  */
157
158 #ifndef SIZE_TYPE
159 #define SIZE_TYPE "long unsigned int"
160 #endif
161
162 /* The string value for __PTRDIFF_TYPE__.  */
163
164 #ifndef PTRDIFF_TYPE
165 #define PTRDIFF_TYPE "long int"
166 #endif
167
168 /* The string value for __WCHAR_TYPE__.  */
169
170 #ifndef WCHAR_TYPE
171 #define WCHAR_TYPE "int"
172 #endif
173 #define CPP_WCHAR_TYPE(PFILE) \
174         (CPP_OPTIONS (PFILE)->cplusplus ? "__wchar_t" : WCHAR_TYPE)
175
176 /* The string value for __USER_LABEL_PREFIX__ */
177
178 #ifndef USER_LABEL_PREFIX
179 #define USER_LABEL_PREFIX ""
180 #endif
181
182 /* The string value for __REGISTER_PREFIX__ */
183
184 #ifndef REGISTER_PREFIX
185 #define REGISTER_PREFIX ""
186 #endif
187 \f
188 /* In the definition of a #assert name, this structure forms
189    a list of the individual values asserted.
190    Each value is itself a list of "tokens".
191    These are strings that are compared by name.  */
192
193 struct tokenlist_list {
194   struct tokenlist_list *next;
195   struct arglist *tokens;
196 };
197
198 struct assertion_hashnode {
199   struct assertion_hashnode *next;      /* double links for easy deletion */
200   struct assertion_hashnode *prev;
201   /* also, a back pointer to this node's hash
202      chain is kept, in case the node is the head
203      of the chain and gets deleted.  */
204   struct assertion_hashnode **bucket_hdr;
205   int length;                   /* length of token, for quick comparison */
206   U_CHAR *name;                 /* the actual name */
207   /* List of token-sequences.  */
208   struct tokenlist_list *value;
209 };
210 \f
211 #define SKIP_WHITE_SPACE(p) do { while (is_hor_space[*p]) p++; } while (0)
212 #define SKIP_ALL_WHITE_SPACE(p) do { while (is_space[*p]) p++; } while (0)
213
214 #define PEEKN(N) (CPP_BUFFER (pfile)->rlimit - CPP_BUFFER (pfile)->cur >= (N) ? CPP_BUFFER (pfile)->cur[N] : EOF)
215 #define FORWARD(N) CPP_FORWARD (CPP_BUFFER (pfile), (N))
216 #define GETC() CPP_BUF_GET (CPP_BUFFER (pfile))
217 #define PEEKC() CPP_BUF_PEEK (CPP_BUFFER (pfile))
218 /* CPP_IS_MACRO_BUFFER is true if the buffer contains macro expansion.
219    (Note that it is false while we're expanding marco *arguments*.) */
220 #define CPP_IS_MACRO_BUFFER(PBUF) ((PBUF)->cleanup == macro_cleanup)
221
222 /* Move all backslash-newline pairs out of embarrassing places.
223    Exchange all such pairs following BP
224    with any potentially-embarrassing characters that follow them.
225    Potentially-embarrassing characters are / and *
226    (because a backslash-newline inside a comment delimiter
227    would cause it not to be recognized).  */
228
229 #define NEWLINE_FIX \
230   do {while (PEEKC() == '\\' && PEEKN(1) == '\n') FORWARD(2); } while(0)
231
232 /* Same, but assume we've already read the potential '\\' into C.  */
233 #define NEWLINE_FIX1(C) do { \
234     while ((C) == '\\' && PEEKC() == '\n') { FORWARD(1); (C) = GETC(); }\
235   } while(0)
236
237 struct cpp_pending {
238   struct cpp_pending *next;
239   char *cmd;
240   char *arg;
241 };
242
243 /* Forward declarations.  */
244
245 extern char *xmalloc ();
246
247 static void add_import ();
248 static void append_include_chain ();
249 static void make_undef ();
250 static void make_assertion ();
251 static void path_include ();
252 static void initialize_builtins ();
253 static void initialize_char_syntax ();
254 static void dump_arg_n ();
255 static void dump_defn_1 ();
256 extern void delete_macro ();
257 static void trigraph_pcp ();
258 static int finclude ();
259 static void validate_else ();
260 static int comp_def_part ();
261 #ifdef abort
262 extern void fancy_abort ();
263 #endif
264 static void pipe_closed ();
265 static void print_containing_files ();
266 static int lookup_import ();
267 static int redundant_include_p ();
268 static is_system_include ();
269 static struct file_name_map *read_name_map ();
270 static char *read_filename_string ();
271 static int open_include_file ();
272 static int check_preconditions ();
273 static void pcfinclude ();
274 static void pcstring_used ();
275 static int check_macro_name ();
276 static int compare_defs ();
277 static int compare_token_lists ();
278 static HOST_WIDE_INT eval_if_expression ();
279 static int change_newlines ();
280 extern int hashf ();
281 static int file_size_and_mode ();
282 static struct arglist *read_token_list ();
283 static void free_token_list ();
284 static int safe_read ();
285 static void push_macro_expansion PARAMS ((cpp_reader *,
286                                           U_CHAR *, int, HASHNODE *));
287 static struct cpp_pending *nreverse_pending PARAMS ((struct cpp_pending *));
288 extern char *xrealloc ();
289 static char *xcalloc ();
290 static char *savestring ();
291
292 static void conditional_skip ();
293 static void skip_if_group ();
294
295 /* Last arg to output_line_command.  */
296 enum file_change_code {same_file, enter_file, leave_file};
297
298 /* External declarations.  */
299
300 extern HOST_WIDE_INT cpp_parse_expr PARAMS ((cpp_reader *));
301
302 extern char *getenv ();
303 extern FILE *fdopen ();
304 extern char *version_string;
305 extern struct tm *localtime ();
306
307 /* These functions are declared to return int instead of void since they
308    are going to be placed in a table and some old compilers have trouble with
309    pointers to functions returning void.  */
310
311 static int do_define ();
312 static int do_line ();
313 static int do_include ();
314 static int do_undef ();
315 static int do_error ();
316 static int do_pragma ();
317 static int do_ident ();
318 static int do_if ();
319 static int do_xifdef ();
320 static int do_else ();
321 static int do_elif ();
322 static int do_endif ();
323 static int do_sccs ();
324 static int do_once ();
325 static int do_assert ();
326 static int do_unassert ();
327 static int do_warning ();
328 \f
329 struct file_name_list
330   {
331     struct file_name_list *next;
332     char *fname;
333     /* If the following is nonzero, it is a macro name.
334        Don't include the file again if that macro is defined.  */
335     U_CHAR *control_macro;
336     /* If the following is nonzero, it is a C-language system include
337        directory.  */
338     int c_system_include_path;
339     /* Mapping of file names for this directory.  */
340     struct file_name_map *name_map;
341     /* Non-zero if name_map is valid.  */
342     int got_name_map;
343   };
344
345 /* If a buffer's dir field is SELF_DIR_DUMMY, it means the file was found
346    via the same directory as the file that #included it.  */
347 #define SELF_DIR_DUMMY ((struct file_name_list *) (~0))
348
349 /* #include "file" looks in source file dir, then stack.  */
350 /* #include <file> just looks in the stack.  */
351 /* -I directories are added to the end, then the defaults are added.  */
352 /* The */
353 static struct default_include {
354   char *fname;                  /* The name of the directory.  */
355   int cplusplus;                /* Only look here if we're compiling C++.  */
356   int cxx_aware;                /* Includes in this directory don't need to
357                                    be wrapped in extern "C" when compiling
358                                    C++.  */
359 } include_defaults_array[]
360 #ifdef INCLUDE_DEFAULTS
361   = INCLUDE_DEFAULTS;
362 #else
363   = {
364     /* Pick up GNU C++ specific include files.  */
365     { GPLUSPLUS_INCLUDE_DIR, 1, 1 },
366     { OLD_GPLUSPLUS_INCLUDE_DIR, 1, 1 },
367 #ifdef CROSS_COMPILE
368     /* This is the dir for fixincludes.  Put it just before
369        the files that we fix.  */
370     { GCC_INCLUDE_DIR, 0, 0 },
371     /* For cross-compilation, this dir name is generated
372        automatically in Makefile.in.  */
373     { CROSS_INCLUDE_DIR, 0, 0 },
374 #ifdef TOOL_INCLUDE_DIR
375     /* This is another place that the target system's headers might be.  */
376     { TOOL_INCLUDE_DIR, 0, 1 },
377 #endif
378 #else /* not CROSS_COMPILE */
379 #ifdef LOCAL_INCLUDE_DIR
380     /* This should be /usr/local/include and should come before
381        the fixincludes-fixed header files.  */
382     { LOCAL_INCLUDE_DIR, 0, 1 },
383 #endif
384 #ifdef TOOL_INCLUDE_DIR
385     /* This is here ahead of GCC_INCLUDE_DIR because assert.h goes here.
386        Likewise, behind LOCAL_INCLUDE_DIR, where glibc puts its assert.h.  */
387     { TOOL_INCLUDE_DIR, 0, 1 },
388 #endif
389     /* This is the dir for fixincludes.  Put it just before
390        the files that we fix.  */
391     { GCC_INCLUDE_DIR, 0, 0 },
392     /* Some systems have an extra dir of include files.  */
393 #ifdef SYSTEM_INCLUDE_DIR
394     { SYSTEM_INCLUDE_DIR, 0, 0 },
395 #endif
396     { STANDARD_INCLUDE_DIR, 0, 0 },
397 #endif /* not CROSS_COMPILE */
398     { 0, 0, 0 }
399     };
400 #endif /* no INCLUDE_DEFAULTS */
401
402 /* `struct directive' defines one #-directive, including how to handle it.  */
403
404 struct directive {
405   int length;                   /* Length of name */
406   int (*func)();                /* Function to handle directive */
407   char *name;                   /* Name of directive */
408   enum node_type type;          /* Code which describes which directive.  */
409   char command_reads_line;      /* One if rest of line is read by func.  */
410   char traditional_comments;    /* Nonzero: keep comments if -traditional.  */
411   char pass_thru;               /* Copy preprocessed directive to output file.*/
412 };
413
414 /* Here is the actual list of #-directives, most-often-used first.
415    The initialize_builtins function assumes #define is the very first.  */
416
417 static struct directive directive_table[] = {
418   {  6, do_define, "define", T_DEFINE, 0, 1},
419   {  5, do_xifdef, "ifdef", T_IFDEF, 1},
420   {  6, do_xifdef, "ifndef", T_IFNDEF, 1},
421   {  7, do_include, "include", T_INCLUDE, 1},
422   { 12, do_include, "include_next", T_INCLUDE_NEXT, 1},
423   {  6, do_include, "import", T_IMPORT, 1},
424   {  5, do_endif, "endif", T_ENDIF, 1},
425   {  4, do_else, "else", T_ELSE, 1},
426   {  2, do_if, "if", T_IF, 1},
427   {  4, do_elif, "elif", T_ELIF, 1},
428   {  5, do_undef, "undef", T_UNDEF},
429   {  5, do_error, "error", T_ERROR},
430   {  7, do_warning, "warning", T_WARNING},
431   {  6, do_pragma, "pragma", T_PRAGMA, 0, 0, 1},
432   {  4, do_line, "line", T_LINE, 1},
433   {  5, do_ident, "ident", T_IDENT, 1, 0, 1},
434 #ifdef SCCS_DIRECTIVE
435   {  4, do_sccs, "sccs", T_SCCS},
436 #endif
437   {  6, do_assert, "assert", T_ASSERT, 1},
438   {  8, do_unassert, "unassert", T_UNASSERT, 1},
439   {  -1, 0, "", T_UNUSED},
440 };
441 \f
442 /* table to tell if char can be part of a C identifier.  */
443 U_CHAR is_idchar[256];
444 /* table to tell if char can be first char of a c identifier.  */
445 U_CHAR is_idstart[256];
446 /* table to tell if c is horizontal space.  */
447 U_CHAR is_hor_space[256];
448 /* table to tell if c is horizontal or vertical space.  */
449 static U_CHAR is_space[256];
450
451 /* Initialize syntactic classifications of characters.  */
452
453 static void
454 initialize_char_syntax (opts)
455      struct cpp_options *opts;
456 {
457   register int i;
458
459   /*
460    * Set up is_idchar and is_idstart tables.  These should be
461    * faster than saying (is_alpha (c) || c == '_'), etc.
462    * Set up these things before calling any routines tthat
463    * refer to them.
464    */
465   for (i = 'a'; i <= 'z'; i++) {
466     is_idchar[i - 'a' + 'A'] = 1;
467     is_idchar[i] = 1;
468     is_idstart[i - 'a' + 'A'] = 1;
469     is_idstart[i] = 1;
470   }
471   for (i = '0'; i <= '9'; i++)
472     is_idchar[i] = 1;
473   is_idchar['_'] = 1;
474   is_idstart['_'] = 1;
475   is_idchar['$'] = opts->dollars_in_ident;
476   is_idstart['$'] = opts->dollars_in_ident;
477
478   /* horizontal space table */
479   is_hor_space[' '] = 1;
480   is_hor_space['\t'] = 1;
481   is_hor_space['\v'] = 1;
482   is_hor_space['\f'] = 1;
483   is_hor_space['\r'] = 1;
484
485   is_space[' '] = 1;
486   is_space['\t'] = 1;
487   is_space['\v'] = 1;
488   is_space['\f'] = 1;
489   is_space['\n'] = 1;
490   is_space['\r'] = 1;
491 }
492
493
494 /* Place into PFILE a quoted string representing the string SRC.
495    Caller must reserve enough space in pfile->token_buffer.  */
496
497 static void
498 quote_string (pfile, src)
499      cpp_reader *pfile;
500      char *src;
501 {
502   U_CHAR c;
503
504   CPP_PUTC_Q (pfile, '\"');
505   for (;;)
506     switch ((c = *src++))
507       {
508       default:
509         if (isprint (c))
510           CPP_PUTC_Q (pfile, c);
511         else
512           {
513             sprintf (CPP_PWRITTEN (pfile), "\\%03o", c);
514             CPP_ADJUST_WRITTEN (pfile, 4);
515           }
516         break;
517
518       case '\"':
519       case '\\':
520         CPP_PUTC_Q (pfile, '\\');
521         CPP_PUTC_Q (pfile, c);
522         break;
523       
524       case '\0':
525         CPP_PUTC_Q (pfile, '\"');
526         CPP_NUL_TERMINATE_Q (pfile);
527         return;
528       }
529 }
530
531 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars.  */
532
533 void
534 cpp_grow_buffer (pfile, n)
535      cpp_reader *pfile;
536      long n;
537 {
538   long old_written = CPP_WRITTEN (pfile);
539   pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
540   pfile->token_buffer = (U_CHAR *)
541     xrealloc(pfile->token_buffer, pfile->token_buffer_size);
542   CPP_SET_WRITTEN (pfile, old_written);
543 }
544
545 \f
546 /*
547  * process a given definition string, for initialization
548  * If STR is just an identifier, define it with value 1.
549  * If STR has anything after the identifier, then it should
550  * be identifier=definition.
551  */
552
553 void
554 cpp_define (pfile, str)
555      cpp_reader *pfile;
556      U_CHAR *str;
557 {
558   U_CHAR *buf, *p;
559
560   buf = str;
561   p = str;
562   if (!is_idstart[*p])
563     {
564       cpp_error (pfile, "malformed option `-D %s'", str);
565       return;
566     }
567   while (is_idchar[*++p])
568     ;
569   if (*p == 0)
570     {
571       buf = (U_CHAR *) alloca (p - buf + 4);
572       strcpy ((char *)buf, str);
573       strcat ((char *)buf, " 1");
574     }
575   else if (*p != '=')
576     {
577       cpp_error (pfile, "malformed option `-D %s'", str);
578       return;
579     }
580   else
581     {
582       U_CHAR *q;
583       /* Copy the entire option so we can modify it.  */
584       buf = (U_CHAR *) alloca (2 * strlen (str) + 1);
585       strncpy (buf, str, p - str);
586       /* Change the = to a space.  */
587       buf[p - str] = ' ';
588       /* Scan for any backslash-newline and remove it.  */
589       p++;
590       q = &buf[p - str];
591       while (*p)
592         {
593       if (*p == '\\' && p[1] == '\n')
594         p += 2;
595       else
596         *q++ = *p++;
597     }
598     *q = 0;
599   }
600   
601   do_define (pfile, NULL, buf, buf + strlen (buf));
602 }
603 \f
604 /* Process the string STR as if it appeared as the body of a #assert.
605    OPTION is the option name for which STR was the argument.  */
606
607 static void
608 make_assertion (pfile, option, str)
609      cpp_reader *pfile;
610      char *option;
611      U_CHAR *str;
612 {
613   struct directive *kt;
614   U_CHAR *buf, *p, *q;
615
616   /* Copy the entire option so we can modify it.  */
617   buf = (U_CHAR *) alloca (strlen (str) + 1);
618   strcpy ((char *) buf, str);
619   /* Scan for any backslash-newline and remove it.  */
620   p = q = buf;
621   while (*p) {
622 #if 0
623     if (*p == '\\' && p[1] == '\n')
624       p += 2;
625     else
626 #endif
627       *q++ = *p++;
628   }
629   *q = 0;
630
631   p = buf;
632   if (!is_idstart[*p]) {
633     cpp_error (pfile, "malformed option `%s %s'", option, str);
634     return;
635   }
636   while (is_idchar[*++p])
637     ;
638   while (*p == ' ' || *p == '\t') p++;
639   if (! (*p == 0 || *p == '(')) {
640     cpp_error (pfile, "malformed option `%s %s'", option, str);
641     return;
642   }
643   
644   if (cpp_push_buffer (pfile, buf, strlen (buf)) != NULL)
645     {
646       do_assert (pfile, NULL, NULL, NULL);
647       cpp_pop_buffer (pfile);
648     }
649 }
650 \f
651 /* Append a chain of `struct file_name_list's
652    to the end of the main include chain.
653    FIRST is the beginning of the chain to append, and LAST is the end.  */
654
655 static void
656 append_include_chain (pfile, first, last)
657      cpp_reader *pfile;
658      struct file_name_list *first, *last;
659 {
660   struct cpp_options *opts = CPP_OPTIONS (pfile);
661   struct file_name_list *dir;
662
663   if (!first || !last)
664     return;
665
666   if (opts->include == 0)
667     opts->include = first;
668   else
669     opts->last_include->next = first;
670
671   if (opts->first_bracket_include == 0)
672     opts->first_bracket_include = first;
673
674   for (dir = first; ; dir = dir->next) {
675     int len = strlen (dir->fname) + INCLUDE_LEN_FUDGE;
676     if (len > pfile->max_include_len)
677       pfile->max_include_len = len;
678     if (dir == last)
679       break;
680   }
681
682   last->next = NULL;
683   opts->last_include = last;
684 }
685 \f
686 /* Add output to `deps_buffer' for the -M switch.
687    STRING points to the text to be output.
688    SPACER is ':' for targets, ' ' for dependencies, zero for text
689    to be inserted literally.  */
690
691 static void
692 deps_output (pfile, string, spacer)
693      cpp_reader *pfile;
694      char *string;
695      int spacer;
696 {
697   int size = strlen (string);
698
699   if (size == 0)
700     return;
701
702 #ifndef MAX_OUTPUT_COLUMNS
703 #define MAX_OUTPUT_COLUMNS 72
704 #endif
705   if (spacer
706       && pfile->deps_column > 0
707       && (pfile->deps_column + size) > MAX_OUTPUT_COLUMNS)
708     {
709       deps_output (pfile, " \\\n  ", 0);
710       pfile->deps_column = 0;
711     }
712
713   if (pfile->deps_size + size + 8 > pfile->deps_allocated_size)
714     {
715       pfile->deps_allocated_size = (pfile->deps_size + size + 50) * 2;
716       pfile->deps_buffer = (char *) xrealloc (pfile->deps_buffer,
717                                               pfile->deps_allocated_size);
718     }
719   if (spacer == ' ' && pfile->deps_column > 0)
720     pfile->deps_buffer[pfile->deps_size++] = ' ';
721   bcopy (string, &pfile->deps_buffer[pfile->deps_size], size);
722   pfile->deps_size += size;
723   pfile->deps_column += size;
724   if (spacer == ':')
725     pfile->deps_buffer[pfile->deps_size++] = ':';
726   pfile->deps_buffer[pfile->deps_size] = 0;
727 }
728 \f
729 /* Given a colon-separated list of file names PATH,
730    add all the names to the search path for include files.  */
731
732 static void
733 path_include (pfile, path)
734      cpp_reader *pfile;
735      char *path;
736 {
737   char *p;
738
739   p = path;
740
741   if (*p)
742     while (1) {
743       char *q = p;
744       char *name;
745       struct file_name_list *dirtmp;
746
747       /* Find the end of this name.  */
748       while (*q != 0 && *q != PATH_SEPARATOR) q++;
749       if (p == q) {
750         /* An empty name in the path stands for the current directory.  */
751         name = (char *) xmalloc (2);
752         name[0] = '.';
753         name[1] = 0;
754       } else {
755         /* Otherwise use the directory that is named.  */
756         name = (char *) xmalloc (q - p + 1);
757         bcopy (p, name, q - p);
758         name[q - p] = 0;
759       }
760
761       dirtmp = (struct file_name_list *)
762         xmalloc (sizeof (struct file_name_list));
763       dirtmp->next = 0;         /* New one goes on the end */
764       dirtmp->control_macro = 0;
765       dirtmp->c_system_include_path = 0;
766       dirtmp->fname = name;
767       dirtmp->got_name_map = 0;
768       append_include_chain (pfile, dirtmp, dirtmp);
769
770       /* Advance past this name.  */
771       p = q;
772       if (*p == 0)
773         break;
774       /* Skip the colon.  */
775       p++;
776     }
777 }
778 \f
779 void
780 cpp_options_init (opts)
781      cpp_options *opts;
782 {
783   bzero ((char *) opts, sizeof *opts);
784   opts->in_fname = NULL;
785   opts->out_fname = NULL;
786
787   /* Initialize is_idchar to allow $.  */
788   opts->dollars_in_ident = 1;
789   initialize_char_syntax (opts);
790
791   opts->no_line_commands = 0;
792   opts->no_trigraphs = 1;
793   opts->put_out_comments = 0;
794   opts->print_include_names = 0;
795   opts->dump_macros = dump_none;
796   opts->no_output = 0;
797   opts->cplusplus = 0;
798   opts->cplusplus_comments = 0;
799
800   opts->verbose = 0;
801   opts->objc = 0;
802   opts->lang_asm = 0;
803   opts->for_lint = 0;
804   opts->chill = 0;
805   opts->pedantic_errors = 0;
806   opts->inhibit_warnings = 0;
807   opts->warn_comments = 0;
808   opts->warn_import = 1;
809   opts->warnings_are_errors = 0;
810 }
811
812 enum cpp_token
813 null_underflow (pfile)
814      cpp_reader *pfile;
815 {
816   return CPP_EOF;
817 }
818
819 int
820 null_cleanup (pbuf, pfile)
821      cpp_buffer *pbuf;
822      cpp_reader *pfile;
823 {
824   return 0;
825 }
826
827 int
828 macro_cleanup (pbuf, pfile)
829      cpp_buffer *pbuf;
830      cpp_reader *pfile;
831 {
832   HASHNODE *macro = (HASHNODE *) pbuf->data;
833   if (macro->type == T_DISABLED)
834     macro->type = T_MACRO;
835   if (macro->type != T_MACRO || pbuf->buf != macro->value.defn->expansion)
836     free (pbuf->buf);
837   return 0;
838 }
839
840 int
841 file_cleanup (pbuf, pfile)
842      cpp_buffer *pbuf;
843      cpp_reader *pfile;
844 {
845   if (pbuf->buf)
846     {
847       free (pbuf->buf);
848       pbuf->buf = 0;
849     }
850   return 0;
851 }
852
853 /* Assuming we have read '/'.
854    If this is the start of a comment (followed by '*' or '/'),
855    skip to the end of the comment, and return ' '.
856    Return EOF if we reached the end of file before the end of the comment.
857    If not the start of a comment, return '/'.  */
858
859 static int
860 skip_comment (pfile, linep)
861      cpp_reader *pfile;
862      long *linep;
863 {
864   int c = 0;
865   while (PEEKC() == '\\' && PEEKN(1) == '\n')
866     {
867       if (linep)
868         (*linep)++;
869       FORWARD(2);
870     }
871   if (PEEKC() == '*')
872     {
873       FORWARD(1);
874       for (;;)
875         {
876           int prev_c = c;
877           c = GETC ();
878           if (c == EOF)
879             return EOF;
880           while (c == '\\' && PEEKC() == '\n')
881             {
882               if (linep)
883                 (*linep)++;
884               FORWARD(1), c = GETC();
885             }
886           if (prev_c == '*' && c == '/')
887             return ' ';
888           if (c == '\n' && linep)
889             (*linep)++;
890         }
891     }
892   else if (PEEKC() == '/' && CPP_OPTIONS (pfile)->cplusplus_comments)
893     {
894       FORWARD(1);
895       for (;;)
896         {
897           c = GETC ();
898           if (c == EOF)
899             return ' '; /* Allow // to be terminated by EOF.  */
900           while (c == '\\' && PEEKC() == '\n')
901             {
902               FORWARD(1);
903               c = GETC();
904               if (linep)
905                 (*linep)++;
906             }
907           if (c == '\n')
908             {
909               /* Don't consider final '\n' to be part of comment.  */
910               FORWARD(-1);
911               return ' ';
912             }
913         }
914     }
915   else
916     return '/';
917 }     
918
919 /* Skip whitespace \-newline and comments.  Does not macro-expand.  */
920
921 void
922 cpp_skip_hspace (pfile)
923      cpp_reader *pfile;
924 {
925   while (1)
926     {
927       int c = PEEKC();
928       if (c == EOF)
929         return; /* FIXME */
930       if (is_hor_space[c])
931         {
932           if ((c == '\f' || c == '\v') && CPP_PEDANTIC (pfile))
933             cpp_pedwarn (pfile, "%s in preprocessing directive",
934                          c == '\f' ? "formfeed" : "vertical tab");
935           FORWARD(1);
936         }
937       else if (c == '/')
938         {
939           FORWARD (1);
940           c = skip_comment (pfile, NULL);
941           if (c == '/')
942             FORWARD(-1);
943           if (c == EOF || c == '/')
944             return;
945         }
946       else if (c == '\\' && PEEKN(1) == '\n') {
947         FORWARD(2);
948       }
949       else if (c == '@' && CPP_BUFFER (pfile)->has_escapes
950                && is_hor_space[PEEKN(1)])
951         FORWARD(2);
952       else return;
953     }
954 }
955
956 /* Read the rest of the current line.
957    The line is appended to PFILE's output buffer.  */
958
959 static void
960 copy_rest_of_line (pfile)
961      cpp_reader *pfile;
962 {
963   struct cpp_options *opts = CPP_OPTIONS (pfile);
964   for (;;)
965     {
966       int c = GETC();
967       int nextc;
968       switch (c)
969         {
970         case EOF:
971           goto end_directive;
972         case '\\':
973           if (PEEKC() == '\n')
974             {
975               FORWARD (1);
976               continue;
977             }
978         case '\'':
979         case '\"':
980           goto scan_directive_token;
981           break;
982         case '/':
983           nextc = PEEKC();
984           if (nextc == '*' || (opts->cplusplus_comments && nextc == '*'))
985             goto scan_directive_token;
986           break;
987         case '\f':
988         case '\v':
989           if (CPP_PEDANTIC (pfile))
990             cpp_pedwarn (pfile, "%s in preprocessing directive",
991                          c == '\f' ? "formfeed" : "vertical tab");
992           break;
993
994         case '\n':
995           FORWARD(-1);
996           goto end_directive;
997         scan_directive_token:
998           FORWARD(-1);
999           cpp_get_token (pfile);
1000           continue;
1001         }
1002       CPP_PUTC (pfile, c);
1003     }
1004  end_directive: ;
1005   CPP_NUL_TERMINATE (pfile);
1006 }
1007
1008 void
1009 skip_rest_of_line (pfile)
1010      cpp_reader *pfile;
1011 {
1012   long old = CPP_WRITTEN (pfile);
1013   copy_rest_of_line (pfile);
1014   CPP_SET_WRITTEN (pfile, old);
1015 }
1016
1017 /* Handle a possible # directive.
1018    '#' has already been read.  */
1019
1020 int
1021 handle_directive (pfile)
1022      cpp_reader *pfile;
1023 { int c;
1024   register struct directive *kt;
1025   int ident_length;
1026   long after_ident;
1027   U_CHAR *ident, *line_end;
1028   long old_written = CPP_WRITTEN (pfile);
1029
1030   cpp_skip_hspace (pfile);
1031
1032   c = PEEKC ();
1033   if (c >= '0' && c <= '9')
1034     {
1035       /* Handle # followed by a line number.  */
1036       if (CPP_PEDANTIC (pfile))
1037         cpp_pedwarn (pfile, "`#' followed by integer");
1038       do_line (pfile, NULL);
1039       goto done_a_directive;
1040     }
1041
1042   /* Now find the directive name.  */
1043   CPP_PUTC (pfile, '#');
1044   parse_name (pfile, GETC());
1045   ident = pfile->token_buffer + old_written + 1;
1046   ident_length = CPP_PWRITTEN (pfile) - ident;
1047   if (ident_length == 0 && PEEKC() == '\n')
1048     {
1049       /* A line of just `#' becomes blank.  */
1050       goto done_a_directive;
1051     }
1052
1053 #if 0
1054   if (ident_length == 0 || !is_idstart[*ident]) {
1055     U_CHAR *p = ident;
1056     while (is_idchar[*p]) {
1057       if (*p < '0' || *p > '9')
1058         break;
1059       p++;
1060     }
1061     /* Avoid error for `###' and similar cases unless -pedantic.  */
1062     if (p == ident) {
1063       while (*p == '#' || is_hor_space[*p]) p++;
1064       if (*p == '\n') {
1065         if (pedantic && !lang_asm)
1066           cpp_warning (pfile, "invalid preprocessor directive");
1067         return 0;
1068       }
1069     }
1070
1071     if (!lang_asm)
1072       cpp_error (pfile, "invalid preprocessor directive name");
1073
1074     return 0;
1075   }
1076 #endif
1077   /*
1078    * Decode the keyword and call the appropriate expansion
1079    * routine, after moving the input pointer up to the next line.
1080    */
1081   for (kt = directive_table; ; kt++) {
1082     if (kt->length <= 0)
1083       goto not_a_directive;
1084     if (kt->length == ident_length && !strncmp (kt->name, ident, ident_length)) 
1085       break;
1086   }
1087
1088   if (kt->command_reads_line)
1089     after_ident = 0;
1090   else
1091     {
1092       /* Nonzero means do not delete comments within the directive.
1093          #define needs this when -traditional.  */
1094         int comments = CPP_TRADITIONAL (pfile) && kt->traditional_comments; 
1095         int save_put_out_comments = CPP_OPTIONS (pfile)->put_out_comments;
1096         CPP_OPTIONS (pfile)->put_out_comments = comments;
1097         after_ident = CPP_WRITTEN (pfile);
1098         copy_rest_of_line (pfile);
1099         CPP_OPTIONS (pfile)->put_out_comments = save_put_out_comments;
1100     }
1101
1102   /* For #pragma and #define, we may want to pass through the directive.
1103      Other directives may create output, but we don't want the directive
1104      itself out, so we pop it now.  For example #include may write a #line
1105      command (see comment in do_include), and conditionals may emit
1106      #failed ... #endfailed stuff.  But note that popping the buffer
1107      means the parameters to kt->func may point after pfile->limit
1108      so these parameters are invalid as soon as something gets appended
1109      to the token_buffer.  */
1110
1111   line_end = CPP_PWRITTEN (pfile);
1112   if (!kt->pass_thru && kt->type != T_DEFINE)
1113     CPP_SET_WRITTEN (pfile, old_written);
1114
1115   (*kt->func) (pfile, kt, pfile->token_buffer + after_ident, line_end);
1116   if (kt->pass_thru
1117       || (kt->type == T_DEFINE
1118           && CPP_OPTIONS (pfile)->dump_macros == dump_definitions))
1119     {
1120       /* Just leave the entire #define in the output stack.  */
1121     }
1122   else if (kt->type == T_DEFINE
1123            && CPP_OPTIONS (pfile)->dump_macros == dump_names)
1124     {
1125       U_CHAR *p = pfile->token_buffer + old_written + 7;  /* Skip "#define". */
1126       SKIP_WHITE_SPACE (p);
1127       while (is_idchar[*p]) p++;
1128       pfile->limit = p;
1129       CPP_PUTC (pfile, '\n');
1130     }
1131   else if (kt->type == T_DEFINE)
1132     CPP_SET_WRITTEN (pfile, old_written);
1133  done_a_directive:
1134   return 1;
1135
1136  not_a_directive:
1137   return 0;
1138 }
1139
1140 /* Pass a directive through to the output file.
1141    BUF points to the contents of the directive, as a contiguous string.
1142    LIMIT points to the first character past the end of the directive.
1143    KEYWORD is the keyword-table entry for the directive.  */
1144
1145 static void
1146 pass_thru_directive (buf, limit, pfile, keyword)
1147      U_CHAR *buf, *limit;
1148      cpp_reader *pfile;
1149      struct directive *keyword;
1150 {
1151   register unsigned keyword_length = keyword->length;
1152
1153   CPP_RESERVE (pfile, 1 + keyword_length + (limit - buf));
1154   CPP_PUTC_Q (pfile, '#');
1155   CPP_PUTS_Q (pfile, keyword->name, keyword_length);
1156   if (limit != buf && buf[0] != ' ')
1157     CPP_PUTC_Q (pfile, ' ');
1158   CPP_PUTS_Q (pfile, buf, limit - buf);
1159 #if 0
1160   CPP_PUTS_Q (pfile, '\n');
1161   /* Count the line we have just made in the output,
1162      to get in sync properly.  */
1163   pfile->lineno++;
1164 #endif
1165 }
1166 \f
1167 /* The arglist structure is built by do_define to tell
1168    collect_definition where the argument names begin.  That
1169    is, for a define like "#define f(x,y,z) foo+x-bar*y", the arglist
1170    would contain pointers to the strings x, y, and z.
1171    Collect_definition would then build a DEFINITION node,
1172    with reflist nodes pointing to the places x, y, and z had
1173    appeared.  So the arglist is just convenience data passed
1174    between these two routines.  It is not kept around after
1175    the current #define has been processed and entered into the
1176    hash table.  */
1177
1178 struct arglist {
1179   struct arglist *next;
1180   U_CHAR *name;
1181   int length;
1182   int argno;
1183   char rest_args;
1184 };
1185
1186 /* Read a replacement list for a macro with parameters.
1187    Build the DEFINITION structure.
1188    Reads characters of text starting at BUF until END.
1189    ARGLIST specifies the formal parameters to look for
1190    in the text of the definition; NARGS is the number of args
1191    in that list, or -1 for a macro name that wants no argument list.
1192    MACRONAME is the macro name itself (so we can avoid recursive expansion)
1193    and NAMELEN is its length in characters.
1194    
1195    Note that comments, backslash-newlines, and leading white space
1196    have already been deleted from the argument.  */
1197
1198 static DEFINITION *
1199 collect_expansion (pfile, buf, limit, nargs, arglist)
1200      cpp_reader *pfile;
1201      U_CHAR *buf, *limit;
1202      int nargs;
1203      struct arglist *arglist;
1204 {
1205   DEFINITION *defn;
1206   register U_CHAR *p, *lastp, *exp_p;
1207   struct reflist *endpat = NULL;
1208   /* Pointer to first nonspace after last ## seen.  */
1209   U_CHAR *concat = 0;
1210   /* Pointer to first nonspace after last single-# seen.  */
1211   U_CHAR *stringify = 0;
1212   int maxsize;
1213   int expected_delimiter = '\0';
1214
1215   /* Scan thru the replacement list, ignoring comments and quoted
1216      strings, picking up on the macro calls.  It does a linear search
1217      thru the arg list on every potential symbol.  Profiling might say
1218      that something smarter should happen.  */
1219
1220   if (limit < buf)
1221     abort ();
1222
1223   /* Find the beginning of the trailing whitespace.  */
1224   p = buf;
1225   while (p < limit && is_space[limit[-1]]) limit--;
1226
1227   /* Allocate space for the text in the macro definition.
1228      Leading and trailing whitespace chars need 2 bytes each.
1229      Each other input char may or may not need 1 byte,
1230      so this is an upper bound.  The extra 5 are for invented
1231      leading and trailing newline-marker and final null.  */
1232   maxsize = (sizeof (DEFINITION)
1233              + (limit - p) + 5);
1234   /* Occurrences of '@' get doubled, so allocate extra space for them.  */
1235   while (p < limit)
1236     if (*p++ == '@')
1237       maxsize++;
1238   defn = (DEFINITION *) xcalloc (1, maxsize);
1239
1240   defn->nargs = nargs;
1241   exp_p = defn->expansion = (U_CHAR *) defn + sizeof (DEFINITION);
1242   lastp = exp_p;
1243
1244   p = buf;
1245
1246   /* Add one initial space escape-marker to prevent accidental
1247      token-pasting (often removed by macroexpand).  */
1248   *exp_p++ = '@';
1249   *exp_p++ = ' ';
1250
1251   if (limit - p >= 2 && p[0] == '#' && p[1] == '#') {
1252     cpp_error (pfile, "`##' at start of macro definition");
1253     p += 2;
1254   }
1255
1256   /* Process the main body of the definition.  */
1257   while (p < limit) {
1258     int skipped_arg = 0;
1259     register U_CHAR c = *p++;
1260
1261     *exp_p++ = c;
1262
1263     if (!CPP_TRADITIONAL (pfile)) {
1264       switch (c) {
1265       case '\'':
1266       case '\"':
1267         if (expected_delimiter != '\0') {
1268           if (c == expected_delimiter)
1269             expected_delimiter = '\0';
1270         } else
1271           expected_delimiter = c;
1272         break;
1273
1274       case '\\':
1275         if (p < limit && expected_delimiter) {
1276           /* In a string, backslash goes through
1277              and makes next char ordinary.  */
1278           *exp_p++ = *p++;
1279         }
1280         break;
1281
1282       case '@':
1283         /* An '@' in a string or character constant stands for itself,
1284            and does not need to be escaped.  */
1285         if (!expected_delimiter)
1286           *exp_p++ = c;
1287         break;
1288
1289       case '#':
1290         /* # is ordinary inside a string.  */
1291         if (expected_delimiter)
1292           break;
1293         if (p < limit && *p == '#') {
1294           /* ##: concatenate preceding and following tokens.  */
1295           /* Take out the first #, discard preceding whitespace.  */
1296           exp_p--;
1297           while (exp_p > lastp && is_hor_space[exp_p[-1]])
1298             --exp_p;
1299           /* Skip the second #.  */
1300           p++;
1301           /* Discard following whitespace.  */
1302           SKIP_WHITE_SPACE (p);
1303           concat = p;
1304           if (p == limit)
1305             cpp_error (pfile, "`##' at end of macro definition");
1306         } else if (nargs >= 0) {
1307           /* Single #: stringify following argument ref.
1308              Don't leave the # in the expansion.  */
1309           exp_p--;
1310           SKIP_WHITE_SPACE (p);
1311           if (p == limit || ! is_idstart[*p]
1312               || (*p == 'L' && p + 1 < limit && (p[1] == '\'' || p[1] == '"')))
1313             cpp_error (pfile,
1314                      "`#' operator is not followed by a macro argument name");
1315           else
1316             stringify = p;
1317         }
1318         break;
1319       }
1320     } else {
1321       /* In -traditional mode, recognize arguments inside strings and
1322          and character constants, and ignore special properties of #.
1323          Arguments inside strings are considered "stringified", but no
1324          extra quote marks are supplied.  */
1325       switch (c) {
1326       case '\'':
1327       case '\"':
1328         if (expected_delimiter != '\0') {
1329           if (c == expected_delimiter)
1330             expected_delimiter = '\0';
1331         } else
1332           expected_delimiter = c;
1333         break;
1334
1335       case '\\':
1336         /* Backslash quotes delimiters and itself, but not macro args.  */
1337         if (expected_delimiter != 0 && p < limit
1338             && (*p == expected_delimiter || *p == '\\')) {
1339           *exp_p++ = *p++;
1340           continue;
1341         }
1342         break;
1343
1344       case '/':
1345         if (expected_delimiter != '\0') /* No comments inside strings.  */
1346           break;
1347         if (*p == '*') {
1348           /* If we find a comment that wasn't removed by handle_directive,
1349              this must be -traditional.  So replace the comment with
1350              nothing at all.  */
1351           exp_p--;
1352           p += 1;
1353           while (p < limit && !(p[-2] == '*' && p[-1] == '/'))
1354             p++;
1355 #if 0
1356           /* Mark this as a concatenation-point, as if it had been ##.  */
1357           concat = p;
1358 #endif
1359         }
1360         break;
1361       }
1362     }
1363
1364     /* Handle the start of a symbol.  */
1365     if (is_idchar[c] && nargs > 0) {
1366       U_CHAR *id_beg = p - 1;
1367       int id_len;
1368
1369       --exp_p;
1370       while (p != limit && is_idchar[*p]) p++;
1371       id_len = p - id_beg;
1372
1373       if (is_idstart[c]
1374           && ! (id_len == 1 && c == 'L' && (*p == '\'' || *p == '"'))) {
1375         register struct arglist *arg;
1376
1377         for (arg = arglist; arg != NULL; arg = arg->next) {
1378           struct reflist *tpat;
1379
1380           if (arg->name[0] == c
1381               && arg->length == id_len
1382               && strncmp (arg->name, id_beg, id_len) == 0) {
1383             if (expected_delimiter && CPP_OPTIONS (pfile)->warn_stringify) {
1384               if (CPP_TRADITIONAL (pfile)) {
1385                 cpp_warning (pfile, "macro argument `%.*s' is stringified.",
1386                              id_len, arg->name);
1387               } else {
1388                 cpp_warning (pfile,
1389                     "macro arg `%.*s' would be stringified with -traditional.",
1390                              id_len, arg->name);
1391               }
1392             }
1393             /* If ANSI, don't actually substitute inside a string.  */
1394             if (!CPP_TRADITIONAL (pfile) && expected_delimiter)
1395               break;
1396             /* make a pat node for this arg and append it to the end of
1397                the pat list */
1398             tpat = (struct reflist *) xmalloc (sizeof (struct reflist));
1399             tpat->next = NULL;
1400             tpat->raw_before = concat == id_beg;
1401             tpat->raw_after = 0;
1402             tpat->rest_args = arg->rest_args;
1403             tpat->stringify = (CPP_TRADITIONAL (pfile)
1404                                ? expected_delimiter != '\0'
1405                                : stringify == id_beg);
1406
1407             if (endpat == NULL)
1408               defn->pattern = tpat;
1409             else
1410               endpat->next = tpat;
1411             endpat = tpat;
1412
1413             tpat->argno = arg->argno;
1414             tpat->nchars = exp_p - lastp;
1415             {
1416               register U_CHAR *p1 = p;
1417               SKIP_WHITE_SPACE (p1);
1418               if (p1 + 2 <= limit && p1[0] == '#' && p1[1] == '#')
1419                 tpat->raw_after = 1;
1420             }
1421             lastp = exp_p;      /* place to start copying from next time */
1422             skipped_arg = 1;
1423             break;
1424           }
1425         }
1426       }
1427
1428       /* If this was not a macro arg, copy it into the expansion.  */
1429       if (! skipped_arg) {
1430         register U_CHAR *lim1 = p;
1431         p = id_beg;
1432         while (p != lim1)
1433           *exp_p++ = *p++;
1434         if (stringify == id_beg)
1435           cpp_error (pfile,
1436                    "`#' operator should be followed by a macro argument name");
1437       }
1438     }
1439   }
1440
1441   if (!CPP_TRADITIONAL (pfile) && expected_delimiter == 0)
1442     {
1443       /* If ANSI, put in a "@ " marker to prevent token pasting.
1444          But not if "inside a string" (which in ANSI mode
1445          happens only for -D option).  */
1446       *exp_p++ = '@';
1447       *exp_p++ = ' ';
1448     }
1449
1450   *exp_p = '\0';
1451
1452   defn->length = exp_p - defn->expansion;
1453
1454   /* Crash now if we overrun the allocated size.  */
1455   if (defn->length + 1 > maxsize)
1456     abort ();
1457
1458 #if 0
1459 /* This isn't worth the time it takes.  */
1460   /* give back excess storage */
1461   defn->expansion = (U_CHAR *) xrealloc (defn->expansion, defn->length + 1);
1462 #endif
1463
1464   return defn;
1465 }
1466
1467 /*
1468  * special extension string that can be added to the last macro argument to 
1469  * allow it to absorb the "rest" of the arguments when expanded.  Ex:
1470  *              #define wow(a, b...)            process (b, a, b)
1471  *              { wow (1, 2, 3); }      ->      { process (2, 3, 1, 2, 3); }
1472  *              { wow (one, two); }     ->      { process (two, one, two); }
1473  * if this "rest_arg" is used with the concat token '##' and if it is not
1474  * supplied then the token attached to with ## will not be outputted.  Ex:
1475  *              #define wow (a, b...)           process (b ## , a, ## b)
1476  *              { wow (1, 2); }         ->      { process (2, 1, 2); }
1477  *              { wow (one); }          ->      { process (one); {
1478  */
1479 static char rest_extension[] = "...";
1480 #define REST_EXTENSION_LENGTH   (sizeof (rest_extension) - 1)
1481
1482 /* Create a DEFINITION node from a #define directive.  Arguments are 
1483    as for do_define.  */
1484
1485 static MACRODEF
1486 create_definition (buf, limit, pfile, predefinition)
1487      U_CHAR *buf, *limit;
1488      cpp_reader *pfile;
1489      int predefinition;
1490 {
1491   U_CHAR *bp;                   /* temp ptr into input buffer */
1492   U_CHAR *symname;              /* remember where symbol name starts */
1493   int sym_length;               /* and how long it is */
1494   int rest_args = 0;
1495   long line, col;
1496   char *file = CPP_BUFFER (pfile) ? CPP_BUFFER (pfile)->nominal_fname : "";
1497   DEFINITION *defn;
1498   int arglengths = 0;           /* Accumulate lengths of arg names
1499                                    plus number of args.  */
1500   MACRODEF mdef;
1501   cpp_buf_line_and_col (CPP_BUFFER (pfile), &line, &col);
1502
1503   bp = buf;
1504
1505   while (is_hor_space[*bp])
1506     bp++;
1507
1508   symname = bp;                 /* remember where it starts */
1509
1510   sym_length = check_macro_name (pfile, bp, "macro");
1511   bp += sym_length;
1512
1513   /* Lossage will occur if identifiers or control keywords are broken
1514      across lines using backslash.  This is not the right place to take
1515      care of that.  */
1516
1517   if (*bp == '(') {
1518     struct arglist *arg_ptrs = NULL;
1519     int argno = 0;
1520
1521     bp++;                       /* skip '(' */
1522     SKIP_WHITE_SPACE (bp);
1523
1524     /* Loop over macro argument names.  */
1525     while (*bp != ')') {
1526       struct arglist *temp;
1527
1528       temp = (struct arglist *) alloca (sizeof (struct arglist));
1529       temp->name = bp;
1530       temp->next = arg_ptrs;
1531       temp->argno = argno++;
1532       temp->rest_args = 0;
1533       arg_ptrs = temp;
1534
1535       if (rest_args)
1536         cpp_pedwarn (pfile, "another parameter follows `%s'", rest_extension);
1537
1538       if (!is_idstart[*bp])
1539         cpp_pedwarn (pfile, "invalid character in macro parameter name");
1540       
1541       /* Find the end of the arg name.  */
1542       while (is_idchar[*bp]) {
1543         bp++;
1544         /* do we have a "special" rest-args extension here? */
1545         if (limit - bp > REST_EXTENSION_LENGTH &&
1546             strncmp (rest_extension, bp, REST_EXTENSION_LENGTH) == 0) {
1547           rest_args = 1;
1548           temp->rest_args = 1;
1549           break;
1550         }
1551       }
1552       temp->length = bp - temp->name;
1553       if (rest_args == 1)
1554         bp += REST_EXTENSION_LENGTH;
1555       arglengths += temp->length + 2;
1556       SKIP_WHITE_SPACE (bp);
1557       if (temp->length == 0 || (*bp != ',' && *bp != ')')) {
1558         cpp_error (pfile, "badly punctuated parameter list in `#define'");
1559         goto nope;
1560       }
1561       if (*bp == ',') {
1562         bp++;
1563         SKIP_WHITE_SPACE (bp);
1564       }
1565       if (bp >= limit) {
1566         cpp_error (pfile, "unterminated parameter list in `#define'");
1567         goto nope;
1568       }
1569       {
1570         struct arglist *otemp;
1571
1572         for (otemp = temp->next; otemp != NULL; otemp = otemp->next)
1573           if (temp->length == otemp->length &&
1574             strncmp (temp->name, otemp->name, temp->length) == 0) {
1575               U_CHAR *name;
1576
1577               name = (U_CHAR *) alloca (temp->length + 1);
1578               (void) strncpy (name, temp->name, temp->length);
1579               name[temp->length] = '\0';
1580               cpp_error (pfile,
1581                          "duplicate argument name `%s' in `#define'", name);
1582               goto nope;
1583           }
1584       }
1585     }
1586
1587     ++bp;                       /* skip paren */
1588     SKIP_WHITE_SPACE (bp);
1589     /* now everything from bp before limit is the definition.  */
1590     defn = collect_expansion (pfile, bp, limit, argno, arg_ptrs);
1591     defn->rest_args = rest_args;
1592
1593     /* Now set defn->args.argnames to the result of concatenating
1594        the argument names in reverse order
1595        with comma-space between them.  */
1596     defn->args.argnames = (U_CHAR *) xmalloc (arglengths + 1);
1597     {
1598       struct arglist *temp;
1599       int i = 0;
1600       for (temp = arg_ptrs; temp; temp = temp->next) {
1601         bcopy (temp->name, &defn->args.argnames[i], temp->length);
1602         i += temp->length;
1603         if (temp->next != 0) {
1604           defn->args.argnames[i++] = ',';
1605           defn->args.argnames[i++] = ' ';
1606         }
1607       }
1608       defn->args.argnames[i] = 0;
1609     }
1610   } else {
1611     /* Simple expansion or empty definition.  */
1612
1613     if (bp < limit)
1614       {
1615         if (is_hor_space[*bp]) {
1616           bp++;
1617           SKIP_WHITE_SPACE (bp);
1618         } else {
1619           switch (*bp) {
1620             case '!':  case '"':  case '#':  case '%':  case '&':  case '\'':
1621             case ')':  case '*':  case '+':  case ',':  case '-':  case '.':
1622             case '/':  case ':':  case ';':  case '<':  case '=':  case '>':
1623             case '?':  case '[':  case '\\': case ']':  case '^':  case '{':
1624             case '|':  case '}':  case '~':
1625               cpp_warning (pfile, "missing white space after `#define %.*s'",
1626                            sym_length, symname);
1627               break;
1628
1629             default:
1630               cpp_pedwarn (pfile, "missing white space after `#define %.*s'",
1631                            sym_length, symname);
1632               break;
1633           }
1634         }
1635       }
1636     /* now everything from bp before limit is the definition.  */
1637     defn = collect_expansion (pfile, bp, limit, -1, NULL_PTR);
1638     defn->args.argnames = (U_CHAR *) "";
1639   }
1640
1641   defn->line = line;
1642   defn->file = file;
1643
1644   /* OP is null if this is a predefinition */
1645   defn->predefined = predefinition;
1646   mdef.defn = defn;
1647   mdef.symnam = symname;
1648   mdef.symlen = sym_length;
1649
1650   return mdef;
1651
1652  nope:
1653   mdef.defn = 0;
1654   return mdef;
1655 }
1656
1657 /* Check a purported macro name SYMNAME, and yield its length.
1658    USAGE is the kind of name this is intended for.  */
1659
1660 static int
1661 check_macro_name (pfile, symname, usage)
1662      cpp_reader *pfile;
1663      U_CHAR *symname;
1664      char *usage;
1665 {
1666   U_CHAR *p;
1667   int sym_length;
1668
1669   for (p = symname; is_idchar[*p]; p++)
1670     ;
1671   sym_length = p - symname;
1672   if (sym_length == 0
1673       || (sym_length == 1 && *symname == 'L' && (*p == '\'' || *p == '"')))
1674     cpp_error (pfile, "invalid %s name", usage);
1675   else if (!is_idstart[*symname]) {
1676     U_CHAR *msg;                        /* what pain...  */
1677     msg = (U_CHAR *) alloca (sym_length + 1);
1678     bcopy (symname, msg, sym_length);
1679     msg[sym_length] = 0;
1680     cpp_error (pfile, "invalid %s name `%s'", usage, msg);
1681   } else {
1682     if (! strncmp (symname, "defined", 7) && sym_length == 7)
1683       cpp_error (pfile, "invalid %s name `defined'", usage);
1684   }
1685   return sym_length;
1686 }
1687
1688 /* Return zero if two DEFINITIONs are isomorphic.  */
1689
1690 static int
1691 compare_defs (d1, d2)
1692      DEFINITION *d1, *d2;
1693 {
1694   register struct reflist *a1, *a2;
1695   register U_CHAR *p1 = d1->expansion;
1696   register U_CHAR *p2 = d2->expansion;
1697   int first = 1;
1698
1699   if (d1->nargs != d2->nargs)
1700     return 1;
1701   if (strcmp ((char *)d1->args.argnames, (char *)d2->args.argnames))
1702     return 1;
1703   for (a1 = d1->pattern, a2 = d2->pattern; a1 && a2;
1704        a1 = a1->next, a2 = a2->next) {
1705     if (!((a1->nchars == a2->nchars && ! strncmp (p1, p2, a1->nchars))
1706           || ! comp_def_part (first, p1, a1->nchars, p2, a2->nchars, 0))
1707         || a1->argno != a2->argno
1708         || a1->stringify != a2->stringify
1709         || a1->raw_before != a2->raw_before
1710         || a1->raw_after != a2->raw_after)
1711       return 1;
1712     first = 0;
1713     p1 += a1->nchars;
1714     p2 += a2->nchars;
1715   }
1716   if (a1 != a2)
1717     return 1;
1718   if (comp_def_part (first, p1, d1->length - (p1 - d1->expansion),
1719                      p2, d2->length - (p2 - d2->expansion), 1))
1720     return 1;
1721   return 0;
1722 }
1723
1724 /* Return 1 if two parts of two macro definitions are effectively different.
1725    One of the parts starts at BEG1 and has LEN1 chars;
1726    the other has LEN2 chars at BEG2.
1727    Any sequence of whitespace matches any other sequence of whitespace.
1728    FIRST means these parts are the first of a macro definition;
1729     so ignore leading whitespace entirely.
1730    LAST means these parts are the last of a macro definition;
1731     so ignore trailing whitespace entirely.  */
1732
1733 static int
1734 comp_def_part (first, beg1, len1, beg2, len2, last)
1735      int first;
1736      U_CHAR *beg1, *beg2;
1737      int len1, len2;
1738      int last;
1739 {
1740   register U_CHAR *end1 = beg1 + len1;
1741   register U_CHAR *end2 = beg2 + len2;
1742   if (first) {
1743     while (beg1 != end1 && is_space[*beg1]) beg1++;
1744     while (beg2 != end2 && is_space[*beg2]) beg2++;
1745   }
1746   if (last) {
1747     while (beg1 != end1 && is_space[end1[-1]]) end1--;
1748     while (beg2 != end2 && is_space[end2[-1]]) end2--;
1749   }
1750   while (beg1 != end1 && beg2 != end2) {
1751     if (is_space[*beg1] && is_space[*beg2]) {
1752       while (beg1 != end1 && is_space[*beg1]) beg1++;
1753       while (beg2 != end2 && is_space[*beg2]) beg2++;
1754     } else if (*beg1 == *beg2) {
1755       beg1++; beg2++;
1756     } else break;
1757   }
1758   return (beg1 != end1) || (beg2 != end2);
1759 }
1760
1761 /* Process a #define command.
1762 BUF points to the contents of the #define command, as a contiguous string.
1763 LIMIT points to the first character past the end of the definition.
1764 KEYWORD is the keyword-table entry for #define,
1765 or NULL for a "predefined" macro.  */
1766
1767 static int
1768 do_define (pfile, keyword, buf, limit)
1769      cpp_reader *pfile;
1770      struct directive *keyword;
1771      U_CHAR *buf, *limit;
1772 {
1773   int hashcode;
1774   MACRODEF mdef;
1775   HASHNODE *hp;
1776
1777 #if 0
1778   /* If this is a precompiler run (with -pcp) pass thru #define commands.  */
1779   if (pcp_outfile && keyword)
1780     pass_thru_directive (buf, limit, pfile, keyword);
1781 #endif
1782
1783   mdef = create_definition (buf, limit, pfile, keyword == NULL);
1784   if (mdef.defn == 0)
1785     goto nope;
1786
1787   hashcode = hashf (mdef.symnam, mdef.symlen, HASHSIZE);
1788
1789   if ((hp = cpp_lookup (pfile, mdef.symnam, mdef.symlen, hashcode)) != NULL)
1790     {
1791       int ok = 0;
1792       /* Redefining a precompiled key is ok.  */
1793       if (hp->type == T_PCSTRING)
1794         ok = 1;
1795       /* Redefining a macro is ok if the definitions are the same.  */
1796       else if (hp->type == T_MACRO)
1797         ok = ! compare_defs (mdef.defn, hp->value.defn);
1798       /* Redefining a constant is ok with -D.  */
1799       else if (hp->type == T_CONST)
1800         ok = ! CPP_OPTIONS (pfile)->done_initializing;
1801       /* Print the warning if it's not ok.  */
1802       if (!ok)
1803         {
1804           U_CHAR *msg;          /* what pain...  */
1805
1806           /* If we are passing through #define and #undef directives, do
1807              that for this re-definition now.  */
1808           if (CPP_OPTIONS (pfile)->debug_output && keyword)
1809             pass_thru_directive (buf, limit, pfile, keyword);
1810
1811           msg = (U_CHAR *) alloca (mdef.symlen + 22);
1812           *msg = '`';
1813           bcopy (mdef.symnam, msg + 1, mdef.symlen);
1814           strcpy ((char *) (msg + mdef.symlen + 1), "' redefined");
1815           cpp_pedwarn (pfile, msg);
1816           if (hp->type == T_MACRO)
1817             cpp_pedwarn_with_file_and_line (pfile, hp->value.defn->file, hp->value.defn->line,
1818                                       "this is the location of the previous definition");
1819         }
1820       /* Replace the old definition.  */
1821       hp->type = T_MACRO;
1822       hp->value.defn = mdef.defn;
1823     }
1824   else
1825     {
1826       /* If we are passing through #define and #undef directives, do
1827          that for this new definition now.  */
1828       if (CPP_OPTIONS (pfile)->debug_output && keyword)
1829         pass_thru_directive (buf, limit, pfile, keyword);
1830       install (mdef.symnam, mdef.symlen, T_MACRO, 0,
1831                (char *) mdef.defn, hashcode);
1832     }
1833
1834   return 0;
1835
1836 nope:
1837
1838   return 1;
1839 }
1840
1841 /* This structure represents one parsed argument in a macro call.
1842    `raw' points to the argument text as written (`raw_length' is its length).
1843    `expanded' points to the argument's macro-expansion
1844    (its length is `expand_length').
1845    `stringified_length' is the length the argument would have
1846    if stringified.
1847    `use_count' is the number of times this macro arg is substituted
1848    into the macro.  If the actual use count exceeds 10, 
1849    the value stored is 10.  */
1850
1851 /* raw and expanded are relative to ARG_BASE */
1852 #define ARG_BASE ((pfile)->token_buffer)
1853
1854 struct argdata {
1855   /* Strings relative to pfile->token_buffer */
1856   long raw, expanded, stringified;
1857   int raw_length, expand_length;
1858   int stringified_length;
1859   char newlines;
1860   char use_count;
1861 };
1862
1863 /* Allocate a new cpp_buffer for PFILE, and push it on the input buffer stack.
1864    If BUFFER != NULL, then use the LENGTH characters in BUFFER
1865    as the new input buffer.
1866    Return the new buffer, or NULL on failure.  */
1867
1868 cpp_buffer *
1869 cpp_push_buffer (pfile, buffer, length)
1870      cpp_reader *pfile;
1871      U_CHAR *buffer;
1872      long length;
1873 {
1874   register cpp_buffer *buf = CPP_BUFFER (pfile);
1875   if (buf == pfile->buffer_stack)
1876     {
1877       cpp_fatal (pfile, "%s: macro or `#include' recursion too deep",
1878                  buf->fname);
1879       return NULL;
1880     }
1881   buf--;
1882   bzero ((char *) buf, sizeof (cpp_buffer));
1883   CPP_BUFFER (pfile) = buf;
1884   buf->if_stack = pfile->if_stack;
1885   buf->cleanup = null_cleanup;
1886   buf->underflow = null_underflow;
1887   buf->buf = buf->cur = buffer;
1888   buf->alimit = buf->rlimit = buffer + length;
1889   
1890   return buf;
1891 }
1892
1893 cpp_buffer *
1894 cpp_pop_buffer (pfile)
1895      cpp_reader *pfile;
1896 {
1897   cpp_buffer *buf = CPP_BUFFER (pfile);
1898   (*buf->cleanup) (buf, pfile);
1899   return ++CPP_BUFFER (pfile);
1900 }
1901
1902 /* Scan until CPP_BUFFER (PFILE) is exhausted into PFILE->token_buffer.
1903    Pop the buffer when done.  */
1904
1905 void
1906 cpp_scan_buffer (pfile)
1907      cpp_reader *pfile;
1908 {
1909   cpp_buffer *buffer = CPP_BUFFER (pfile);
1910   for (;;)
1911     {
1912       enum cpp_token token = cpp_get_token (pfile);
1913       if (token == CPP_EOF) /* Should not happen ...  */
1914         break;
1915       if (token == CPP_POP && CPP_BUFFER (pfile) == buffer)
1916         {
1917           cpp_pop_buffer (pfile);
1918           break;
1919         }
1920     }
1921 }
1922
1923 /*
1924  * Rescan a string (which may have escape marks) into pfile's buffer.
1925  * Place the result in pfile->token_buffer.
1926  *
1927  * The input is copied before it is scanned, so it is safe to pass
1928  * it something from the token_buffer that will get overwritten
1929  * (because it follows CPP_WRITTEN).  This is used by do_include.
1930  */
1931
1932 static void
1933 cpp_expand_to_buffer (pfile, buf, length)
1934      cpp_reader *pfile;
1935      U_CHAR *buf;
1936      int length;
1937 {
1938   register cpp_buffer *ip;
1939   cpp_buffer obuf;
1940   U_CHAR *limit = buf + length;
1941   U_CHAR *buf1;
1942 #if 0
1943   int odepth = indepth;
1944 #endif
1945
1946   if (length < 0)
1947     abort ();
1948
1949   /* Set up the input on the input stack.  */
1950
1951   buf1 = (U_CHAR *) alloca (length + 1);
1952   {
1953     register U_CHAR *p1 = buf;
1954     register U_CHAR *p2 = buf1;
1955
1956     while (p1 != limit)
1957       *p2++ = *p1++;
1958   }
1959   buf1[length] = 0;
1960
1961   ip = cpp_push_buffer (pfile, buf1, length);
1962   if (ip == NULL)
1963     return;
1964   ip->has_escapes = 1;
1965 #if 0
1966   ip->lineno = obuf.lineno = 1;
1967 #endif
1968
1969   /* Scan the input, create the output.  */
1970   cpp_scan_buffer (pfile);
1971
1972 #if 0
1973   if (indepth != odepth)
1974     abort ();
1975 #endif
1976
1977   CPP_NUL_TERMINATE (pfile);
1978 }
1979
1980 \f
1981 static void
1982 adjust_position (buf, limit, linep, colp)
1983      U_CHAR *buf;
1984      U_CHAR *limit;
1985      long *linep;
1986      long *colp;
1987 {
1988   while (buf < limit)
1989     {
1990       U_CHAR ch = *buf++;
1991       if (ch == '\n')
1992         (*linep)++, (*colp) = 1;
1993       else
1994         (*colp)++;
1995     }
1996 }
1997
1998 /* Move line_base forward, updating lineno and colno.  */
1999
2000 static void
2001 update_position (pbuf)
2002      register cpp_buffer *pbuf;
2003 {
2004   unsigned char *old_pos = pbuf->buf + pbuf->line_base;
2005   unsigned char *new_pos = pbuf->cur;
2006   register struct parse_marker *mark;
2007   for (mark = pbuf->marks;  mark != NULL; mark = mark->next)
2008     {
2009       if (pbuf->buf + mark->position < new_pos)
2010         new_pos = pbuf->buf + mark->position;
2011     }
2012   pbuf->line_base += new_pos - old_pos;
2013   adjust_position (old_pos, new_pos, &pbuf->lineno, &pbuf->colno);
2014 }
2015
2016 void
2017 cpp_buf_line_and_col (pbuf, linep, colp)
2018      register cpp_buffer *pbuf;
2019      long *linep, *colp;
2020 {
2021   long dummy;
2022   if (colp == NULL)
2023     colp = &dummy;
2024   if (pbuf)
2025     {
2026       *linep = pbuf->lineno;
2027       *colp = pbuf->colno;
2028       adjust_position (pbuf->buf + pbuf->line_base, pbuf->cur, linep, colp);
2029     }
2030   else
2031     {
2032       *linep = 0;
2033       *colp = 0;
2034     }
2035 }
2036
2037 /* Return the cpp_buffer that corresponds to a file (not a macro).  */
2038
2039 cpp_buffer *
2040 cpp_file_buffer (pfile)
2041      cpp_reader *pfile;
2042 {
2043   cpp_buffer *ip = CPP_BUFFER (pfile);
2044
2045   for ( ; ip != CPP_NULL_BUFFER (pfile); ip = CPP_PREV_BUFFER (ip))
2046     if (ip->fname != NULL)
2047       return ip;
2048   return NULL;
2049 }
2050
2051 static long
2052 count_newlines (buf, limit)
2053      register U_CHAR *buf;
2054      register U_CHAR *limit;
2055 {
2056   register long count = 0;
2057   while (buf < limit)
2058     {
2059       U_CHAR ch = *buf++;
2060       if (ch == '\n')
2061         count++;
2062     }
2063   return count;
2064 }
2065
2066 /*
2067  * write out a #line command, for instance, after an #include file.
2068  * If CONDITIONAL is nonzero, we can omit the #line if it would
2069  * appear to be a no-op, and we can output a few newlines instead
2070  * if we want to increase the line number by a small amount.
2071  * FILE_CHANGE says whether we are entering a file, leaving, or neither.
2072  */
2073
2074 static void
2075 output_line_command (pfile, conditional, file_change)
2076      cpp_reader *pfile;
2077      int conditional;
2078      enum file_change_code file_change;
2079 {
2080   int len;
2081   char *line_cmd_buf, *line_end;
2082   long line, col;
2083   cpp_buffer *ip = CPP_BUFFER (pfile);
2084
2085   if (ip->fname == NULL)
2086     return;
2087
2088   update_position (ip);
2089
2090   if (CPP_OPTIONS (pfile)->no_line_commands
2091       || CPP_OPTIONS (pfile)->no_output)
2092     return;
2093
2094   line = CPP_BUFFER (pfile)->lineno;
2095   col = CPP_BUFFER (pfile)->colno;
2096   adjust_position (CPP_LINE_BASE (ip), ip->cur, &line, &col);
2097
2098   if (CPP_OPTIONS (pfile)->no_line_commands)
2099     return;
2100
2101   if (conditional) {
2102     if (line == pfile->lineno)
2103       return;
2104
2105     /* If the inherited line number is a little too small,
2106        output some newlines instead of a #line command.  */
2107     if (line > pfile->lineno && line < pfile->lineno + 8) {
2108       CPP_RESERVE (pfile, 20);
2109       while (line > pfile->lineno) {
2110         CPP_PUTC_Q (pfile, '\n');
2111         pfile->lineno++;
2112       }
2113       return;
2114     }
2115   }
2116
2117 #if 0
2118   /* Don't output a line number of 0 if we can help it.  */
2119   if (ip->lineno == 0 && ip->bufp - ip->buf < ip->length
2120       && *ip->bufp == '\n') {
2121     ip->lineno++;
2122     ip->bufp++;
2123   }
2124 #endif
2125
2126   CPP_RESERVE (pfile, 4 * strlen (ip->nominal_fname) + 50);
2127   {
2128 #ifdef OUTPUT_LINE_COMMANDS
2129     static char sharp_line[] = "#line ";
2130 #else
2131     static char sharp_line[] = "# ";
2132 #endif
2133     CPP_PUTS_Q (pfile, sharp_line, sizeof(sharp_line)-1);
2134   }
2135
2136   sprintf (CPP_PWRITTEN (pfile), "%d ", line);
2137   CPP_ADJUST_WRITTEN (pfile, strlen (CPP_PWRITTEN (pfile)));
2138
2139   quote_string (pfile, ip->nominal_fname); 
2140   if (file_change != same_file) {
2141     CPP_PUTC_Q (pfile, ' ');
2142     CPP_PUTC_Q (pfile, file_change == enter_file ? '1' : '2');
2143   }
2144   /* Tell cc1 if following text comes from a system header file.  */
2145   if (ip->system_header_p) {
2146     CPP_PUTC_Q (pfile, ' ');
2147     CPP_PUTC_Q (pfile, '3');
2148   }
2149 #ifndef NO_IMPLICIT_EXTERN_C
2150   /* Tell cc1plus if following text should be treated as C.  */
2151   if (ip->system_header_p == 2 && CPP_OPTIONS (pfile)->cplusplus) {
2152     CPP_PUTC_Q (pfile, ' ');
2153     CPP_PUTC_Q (pfile, '4');
2154   }
2155 #endif
2156   CPP_PUTC_Q (pfile, '\n');
2157   pfile->lineno = line;
2158 }
2159 \f
2160 /*
2161  * Parse a macro argument and append the info on PFILE's token_buffer.
2162  * REST_ARGS means to absorb the rest of the args.
2163  * Return nonzero to indicate a syntax error.
2164  */
2165
2166 static enum cpp_token
2167 macarg (pfile, rest_args)
2168      cpp_reader *pfile;
2169      int rest_args;
2170 {
2171   int paren = 0;
2172   enum cpp_token token;
2173   long arg_start = CPP_WRITTEN (pfile);
2174   char save_put_out_comments = CPP_OPTIONS (pfile)->put_out_comments;
2175   CPP_OPTIONS (pfile)->put_out_comments = 0;
2176
2177   /* Try to parse as much of the argument as exists at this
2178      input stack level.  */
2179   pfile->no_macro_expand++;
2180   for (;;)
2181     {
2182       token = cpp_get_token (pfile);
2183       switch (token)
2184         {
2185         case CPP_EOF:
2186           goto done;
2187         case CPP_POP:
2188           /* If we've hit end of file, it's an error (reported by caller).
2189              Ditto if it's the end of cpp_expand_to_buffer text.
2190              If we've hit end of macro, just continue.  */
2191           if (! CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
2192             goto done;
2193           break;
2194         case CPP_LPAREN:
2195           paren++;
2196           break;
2197         case CPP_RPAREN:
2198           if (--paren < 0)
2199             goto found;
2200           break;
2201         case CPP_COMMA:
2202           /* if we've returned to lowest level and
2203              we aren't absorbing all args */
2204           if (paren == 0 && rest_args == 0)
2205             goto found;
2206           break;
2207         found:
2208           /* Remove ',' or ')' from argument buffer.  */
2209           CPP_ADJUST_WRITTEN (pfile, -1);
2210           goto done;
2211       default: ;
2212         }
2213     }
2214
2215  done:
2216   CPP_OPTIONS (pfile)->put_out_comments = save_put_out_comments;
2217   pfile->no_macro_expand--;
2218
2219   return token;
2220 }
2221 \f
2222 /* Turn newlines to spaces in the string of length LENGTH at START,
2223    except inside of string constants.
2224    The string is copied into itself with its beginning staying fixed.  */
2225
2226 static int
2227 change_newlines (start, length)
2228      U_CHAR *start;
2229      int length;
2230 {
2231   register U_CHAR *ibp;
2232   register U_CHAR *obp;
2233   register U_CHAR *limit;
2234   register int c;
2235
2236   ibp = start;
2237   limit = start + length;
2238   obp = start;
2239
2240   while (ibp < limit) {
2241     *obp++ = c = *ibp++;
2242     switch (c) {
2243
2244     case '\'':
2245     case '\"':
2246       /* Notice and skip strings, so that we don't delete newlines in them.  */
2247       {
2248         int quotec = c;
2249         while (ibp < limit) {
2250           *obp++ = c = *ibp++;
2251           if (c == quotec)
2252             break;
2253           if (c == '\n' && quotec == '\'')
2254             break;
2255         }
2256       }
2257       break;
2258     }
2259   }
2260
2261   return obp - start;
2262 }
2263
2264 \f
2265 static struct tm *
2266 timestamp (pfile)
2267      cpp_reader *pfile;
2268 {
2269   if (!pfile->timebuf) {
2270     time_t t = time ((time_t *) 0);
2271     pfile->timebuf = localtime (&t);
2272   }
2273   return pfile->timebuf;
2274 }
2275
2276 static char *monthnames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2277                              "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
2278                             };
2279
2280 /*
2281  * expand things like __FILE__.  Place the expansion into the output
2282  * buffer *without* rescanning.
2283  */
2284
2285 static void
2286 special_symbol (hp, pfile)
2287      HASHNODE *hp;
2288      cpp_reader *pfile;
2289 {
2290   char *buf;
2291   int i, len;
2292   int true_indepth;
2293   cpp_buffer *ip = NULL;
2294   struct tm *timebuf;
2295
2296   int paren = 0;                /* For special `defined' keyword */
2297
2298 #if 0
2299   if (pcp_outfile && pcp_inside_if
2300       && hp->type != T_SPEC_DEFINED && hp->type != T_CONST)
2301     cpp_error (pfile,
2302                "Predefined macro `%s' used inside `#if' during precompilation",
2303                hp->name);
2304 #endif
2305     
2306   for (ip = CPP_BUFFER (pfile); ; ip = CPP_PREV_BUFFER (ip))
2307     {
2308       if (ip == CPP_NULL_BUFFER (pfile))
2309         {
2310           cpp_error (pfile, "cccp error: not in any file?!");
2311           return;                       /* the show must go on */
2312         }
2313       if (ip->fname != NULL)
2314         break;
2315     }
2316
2317   switch (hp->type)
2318     {
2319     case T_FILE:
2320     case T_BASE_FILE:
2321       {
2322         char *string;
2323         if (hp->type == T_BASE_FILE)
2324           {
2325             while (CPP_PREV_BUFFER (ip) != CPP_NULL_BUFFER (pfile))
2326               ip = CPP_PREV_BUFFER (ip);
2327           }
2328         string = ip->nominal_fname;
2329
2330         if (!string)
2331           string = "";
2332         CPP_RESERVE (pfile, 3 + 4 * strlen (string));
2333         quote_string (pfile, string);
2334         return;
2335       }
2336
2337     case T_INCLUDE_LEVEL:
2338       true_indepth = 0;
2339       ip = CPP_BUFFER (pfile);
2340       for (;  ip != CPP_NULL_BUFFER (pfile); ip = CPP_PREV_BUFFER (ip))
2341         if (ip->fname != NULL)
2342           true_indepth++;
2343
2344       buf = (char *) alloca (8); /* Eight bytes ought to be more than enough */
2345       sprintf (buf, "%d", true_indepth - 1);
2346       break;
2347
2348   case T_VERSION:
2349       buf = (char *) alloca (3 + strlen (version_string));
2350       sprintf (buf, "\"%s\"", version_string);
2351       break;
2352
2353 #ifndef NO_BUILTIN_SIZE_TYPE
2354     case T_SIZE_TYPE:
2355       buf = SIZE_TYPE;
2356       break;
2357 #endif
2358
2359 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2360     case T_PTRDIFF_TYPE:
2361       buf = PTRDIFF_TYPE;
2362       break;
2363 #endif
2364
2365     case T_WCHAR_TYPE:
2366       buf = CPP_WCHAR_TYPE (pfile);
2367     break;
2368
2369     case T_USER_LABEL_PREFIX_TYPE:
2370       buf = USER_LABEL_PREFIX;
2371       break;
2372
2373     case T_REGISTER_PREFIX_TYPE:
2374       buf = REGISTER_PREFIX;
2375       break;
2376
2377   case T_CONST:
2378       buf = (char *) alloca (4 * sizeof (int));
2379       sprintf (buf, "%d", hp->value.ival);
2380 #if 0
2381       if (pcp_inside_if && pcp_outfile)
2382         /* Output a precondition for this macro use */
2383         fprintf (pcp_outfile, "#define %s %d\n", hp->name, hp->value.ival);
2384 #endif
2385       break;
2386
2387     case T_SPECLINE:
2388       {
2389         long line = ip->lineno;
2390         long col = ip->colno;
2391         adjust_position (CPP_LINE_BASE (ip), ip->cur, &line, &col);
2392
2393         buf = (char *) alloca (10);
2394         sprintf (buf, "%d", line);
2395       }
2396       break;
2397
2398     case T_DATE:
2399     case T_TIME:
2400       buf = (char *) alloca (20);
2401       timebuf = timestamp (pfile);
2402       if (hp->type == T_DATE)
2403         sprintf (buf, "\"%s %2d %4d\"", monthnames[timebuf->tm_mon],
2404                  timebuf->tm_mday, timebuf->tm_year + 1900);
2405       else
2406         sprintf (buf, "\"%02d:%02d:%02d\"", timebuf->tm_hour, timebuf->tm_min,
2407                  timebuf->tm_sec);
2408       break;
2409
2410     case T_SPEC_DEFINED:
2411       buf = " 0 ";              /* Assume symbol is not defined */
2412       ip = CPP_BUFFER (pfile);
2413       SKIP_WHITE_SPACE (ip->cur);
2414       if (*ip->cur == '(')
2415         {
2416           paren++;
2417           ip->cur++;                    /* Skip over the paren */
2418           SKIP_WHITE_SPACE (ip->cur);
2419         }
2420
2421       if (!is_idstart[*ip->cur])
2422         goto oops;
2423       if (ip->cur[0] == 'L' && (ip->cur[1] == '\'' || ip->cur[1] == '"'))
2424         goto oops;
2425       if (hp = cpp_lookup (pfile, ip->cur, -1, -1))
2426         {
2427 #if 0
2428           if (pcp_outfile && pcp_inside_if
2429               && (hp->type == T_CONST
2430                   || (hp->type == T_MACRO && hp->value.defn->predefined)))
2431             /* Output a precondition for this macro use.  */
2432             fprintf (pcp_outfile, "#define %s\n", hp->name);
2433 #endif
2434           buf = " 1 ";
2435         }
2436 #if 0
2437       else
2438         if (pcp_outfile && pcp_inside_if)
2439           {
2440             /* Output a precondition for this macro use */
2441             U_CHAR *cp = ip->bufp;
2442             fprintf (pcp_outfile, "#undef ");
2443             while (is_idchar[*cp]) /* Ick! */
2444               fputc (*cp++, pcp_outfile);
2445             putc ('\n', pcp_outfile);
2446           }
2447 #endif
2448       while (is_idchar[*ip->cur])
2449         ++ip->cur;
2450       SKIP_WHITE_SPACE (ip->cur);
2451       if (paren)
2452         {
2453           if (*ip->cur != ')')
2454             goto oops;
2455           ++ip->cur;
2456         }
2457       break;
2458
2459     oops:
2460
2461       cpp_error (pfile, "`defined' without an identifier");
2462       break;
2463
2464     default:
2465       cpp_error (pfile, "cccp error: invalid special hash type"); /* time for gdb */
2466       abort ();
2467     }
2468   len = strlen (buf);
2469   CPP_RESERVE (pfile, len + 1);
2470   CPP_PUTS_Q (pfile, buf, len);
2471   CPP_NUL_TERMINATE_Q (pfile);
2472
2473   return;
2474 }
2475
2476 /* Write out a #define command for the special named MACRO_NAME
2477    to PFILE's token_buffer.  */
2478
2479 static void
2480 dump_special_to_buffer (pfile, macro_name)
2481      cpp_reader *pfile;
2482      char *macro_name;
2483 {
2484   static char define_directive[] = "#define ";
2485   int macro_name_length = strlen (macro_name);
2486   output_line_command (pfile, 0, same_file);
2487   CPP_RESERVE (pfile, sizeof(define_directive) + macro_name_length);
2488   CPP_PUTS_Q (pfile, define_directive, sizeof(define_directive)-1);
2489   CPP_PUTS_Q (pfile, macro_name, macro_name_length);
2490   CPP_PUTC_Q (pfile, ' ');
2491   cpp_expand_to_buffer (pfile, macro_name, macro_name_length);
2492   CPP_PUTC (pfile, '\n');
2493 }
2494
2495 /* Initialize the built-in macros.  */
2496
2497 static void
2498 initialize_builtins (pfile)
2499      cpp_reader *pfile;
2500 {
2501   install ("__LINE__", -1, T_SPECLINE, 0, 0, -1);
2502   install ("__DATE__", -1, T_DATE, 0, 0, -1);
2503   install ("__FILE__", -1, T_FILE, 0, 0, -1);
2504   install ("__BASE_FILE__", -1, T_BASE_FILE, 0, 0, -1);
2505   install ("__INCLUDE_LEVEL__", -1, T_INCLUDE_LEVEL, 0, 0, -1);
2506   install ("__VERSION__", -1, T_VERSION, 0, 0, -1);
2507 #ifndef NO_BUILTIN_SIZE_TYPE
2508   install ("__SIZE_TYPE__", -1, T_SIZE_TYPE, 0, 0, -1);
2509 #endif
2510 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2511   install ("__PTRDIFF_TYPE__ ", -1, T_PTRDIFF_TYPE, 0, 0, -1);
2512 #endif
2513   install ("__WCHAR_TYPE__", -1, T_WCHAR_TYPE, 0, 0, -1);
2514   install ("__USER_LABEL_PREFIX__", -1, T_USER_LABEL_PREFIX_TYPE, 0, 0, -1);
2515   install ("__REGISTER_PREFIX__", -1, T_REGISTER_PREFIX_TYPE, 0, 0, -1);
2516   install ("__TIME__", -1, T_TIME, 0, 0, -1);
2517   if (!CPP_TRADITIONAL (pfile))
2518     install ("__STDC__", -1, T_CONST, STDC_VALUE, 0, -1);
2519   if (CPP_OPTIONS (pfile)->objc)
2520     install ("__OBJC__", -1, T_CONST, 1, 0, -1);
2521 /*  This is supplied using a -D by the compiler driver
2522     so that it is present only when truly compiling with GNU C.  */
2523 /*  install ("__GNUC__", -1, T_CONST, 2, 0, -1);  */
2524
2525   if (CPP_OPTIONS (pfile)->debug_output)
2526     {
2527       dump_special_to_buffer (pfile, "__BASE_FILE__");
2528       dump_special_to_buffer (pfile, "__VERSION__");
2529 #ifndef NO_BUILTIN_SIZE_TYPE
2530       dump_special_to_buffer (pfile, "__SIZE_TYPE__");
2531 #endif
2532 #ifndef NO_BUILTIN_PTRDIFF_TYPE
2533       dump_special_to_buffer (pfile, "__PTRDIFF_TYPE__");
2534 #endif
2535       dump_special_to_buffer (pfile, "__WCHAR_TYPE__");
2536       dump_special_to_buffer (pfile, "__DATE__");
2537       dump_special_to_buffer (pfile, "__TIME__");
2538       if (!CPP_TRADITIONAL (pfile))
2539         dump_special_to_buffer (pfile, "__STDC__");
2540       if (CPP_OPTIONS (pfile)->objc)
2541         dump_special_to_buffer (pfile, "__OBJC__");
2542     }
2543 }
2544 \f
2545 /* Return 1 iff a token ending in C1 followed directly by a token C2
2546    could cause mis-tokenization.  */
2547
2548 static int
2549 unsafe_chars (c1, c2)
2550      int c1, c2;
2551 {
2552   switch (c1)
2553     {
2554     case '+': case '-':
2555       if (c2 == c1 || c2 == '=')
2556         return 1;
2557       goto letter;
2558     case '.':
2559     case '0': case '1': case '2': case '3': case '4':
2560     case '5': case '6': case '7': case '8': case '9':
2561     case 'e': case 'E': case 'p': case 'P':
2562       if (c2 == '-' || c2 == '+')
2563         return 1; /* could extend a pre-processing number */
2564       goto letter;
2565     case 'L':
2566       if (c2 == '\'' || c2 == '\"')
2567         return 1;   /* Could turn into L"xxx" or L'xxx'.  */
2568       goto letter;
2569     letter:
2570     case '_':
2571     case 'a': case 'b': case 'c': case 'd':           case 'f':
2572     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2573     case 'm': case 'n': case 'o':           case 'q': case 'r':
2574     case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2575     case 'y': case 'z':
2576     case 'A': case 'B': case 'C': case 'D':           case 'F':
2577     case 'G': case 'H': case 'I': case 'J': case 'K':
2578     case 'M': case 'N': case 'O':           case 'Q': case 'R':
2579     case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2580     case 'Y': case 'Z':
2581       /* We're in the middle of either a name or a pre-processing number.  */
2582       return (is_idchar[c2] || c2 == '.');
2583     case '<': case '>': case '!': case '%': case '#': case ':':
2584     case '^': case '&': case '|': case '*': case '/': case '=':
2585       return (c2 == c1 || c2 == '=');
2586     }
2587   return 0;
2588 }
2589
2590 /* Expand a macro call.
2591    HP points to the symbol that is the macro being called.
2592    Put the result of expansion onto the input stack
2593    so that subsequent input by our caller will use it.
2594
2595    If macro wants arguments, caller has already verified that
2596    an argument list follows; arguments come from the input stack.  */
2597
2598 static void
2599 macroexpand (pfile, hp)
2600      cpp_reader *pfile;
2601      HASHNODE *hp;
2602 {
2603   int nargs;
2604   DEFINITION *defn = hp->value.defn;
2605   register U_CHAR *xbuf;
2606   long start_line, start_column;
2607   int xbuf_len;
2608   struct argdata *args;
2609   long old_written = CPP_WRITTEN (pfile);
2610 #if 0
2611   int start_line = instack[indepth].lineno;
2612 #endif
2613   int rest_args, rest_zero;
2614       register int i;
2615
2616 #if 0
2617   CHECK_DEPTH (return;);
2618 #endif
2619
2620 #if 0
2621   /* This macro is being used inside a #if, which means it must be */
2622   /* recorded as a precondition.  */
2623   if (pcp_inside_if && pcp_outfile && defn->predefined)
2624     dump_single_macro (hp, pcp_outfile);
2625 #endif
2626
2627   pfile->output_escapes++;
2628   cpp_buf_line_and_col (cpp_file_buffer (pfile), &start_line, &start_column);
2629
2630   nargs = defn->nargs;
2631
2632   if (nargs >= 0)
2633     {
2634       enum cpp_token token;
2635
2636       args = (struct argdata *) alloca ((nargs + 1) * sizeof (struct argdata));
2637
2638       for (i = 0; i < nargs; i++)
2639         {
2640           args[i].raw = args[i].expanded = 0;
2641           args[i].raw_length = 0; 
2642           args[i].expand_length = args[i].stringified_length = -1;
2643           args[i].use_count = 0;
2644         }
2645
2646       /* Parse all the macro args that are supplied.  I counts them.
2647          The first NARGS args are stored in ARGS.
2648          The rest are discarded.  If rest_args is set then we assume
2649          macarg absorbed the rest of the args.  */
2650       i = 0;
2651       rest_args = 0;
2652       rest_args = 0;
2653       FORWARD(1); /* Discard the open-parenthesis before the first arg.  */
2654       do
2655         {
2656           if (rest_args)
2657             continue;
2658           if (i < nargs || (nargs == 0 && i == 0))
2659             {
2660               /* if we are working on last arg which absorbs rest of args... */
2661               if (i == nargs - 1 && defn->rest_args)
2662                 rest_args = 1;
2663               args[i].raw = CPP_WRITTEN (pfile);
2664               token = macarg (pfile, rest_args);
2665               args[i].raw_length = CPP_WRITTEN (pfile) - args[i].raw;
2666               args[i].newlines = 0; /* FIXME */
2667             }
2668           else
2669             token = macarg (pfile, 0);
2670           if (token == CPP_EOF || token == CPP_POP)
2671             {
2672               cpp_error_with_line (pfile, start_line, start_column,
2673                                    "unterminated macro call");
2674               return;
2675             }
2676           i++;
2677         } while (token == CPP_COMMA);
2678
2679       /* If we got one arg but it was just whitespace, call that 0 args.  */
2680       if (i == 1)
2681         {
2682           register U_CHAR *bp = ARG_BASE + args[0].raw;
2683           register U_CHAR *lim = bp + args[0].raw_length;
2684           /* cpp.texi says for foo ( ) we provide one argument.
2685              However, if foo wants just 0 arguments, treat this as 0.  */
2686           if (nargs == 0)
2687             while (bp != lim && is_space[*bp]) bp++;
2688           if (bp == lim)
2689             i = 0;
2690         }
2691
2692       /* Don't output an error message if we have already output one for
2693          a parse error above.  */
2694       rest_zero = 0;
2695       if (nargs == 0 && i > 0)
2696         {
2697           cpp_error (pfile, "arguments given to macro `%s'", hp->name);
2698         }
2699       else if (i < nargs)
2700         {
2701           /* traditional C allows foo() if foo wants one argument.  */
2702           if (nargs == 1 && i == 0 && CPP_TRADITIONAL (pfile))
2703             ;
2704           /* the rest args token is allowed to absorb 0 tokens */
2705           else if (i == nargs - 1 && defn->rest_args)
2706             rest_zero = 1;
2707           else if (i == 0)
2708             cpp_error (pfile, "macro `%s' used without args", hp->name);
2709           else if (i == 1)
2710             cpp_error (pfile, "macro `%s' used with just one arg", hp->name);
2711           else
2712             cpp_error (pfile, "macro `%s' used with only %d args",
2713                        hp->name, i);
2714       }
2715       else if (i > nargs)
2716         {
2717           cpp_error (pfile,
2718                      "macro `%s' used with too many (%d) args", hp->name, i);
2719         }
2720     }
2721
2722   /* If macro wants zero args, we parsed the arglist for checking only.
2723      Read directly from the macro definition.  */
2724   if (nargs <= 0)
2725     {
2726       xbuf = defn->expansion;
2727       xbuf_len = defn->length;
2728     }
2729   else
2730     {
2731       register U_CHAR *exp = defn->expansion;
2732       register int offset;      /* offset in expansion,
2733                                    copied a piece at a time */
2734       register int totlen;      /* total amount of exp buffer filled so far */
2735
2736       register struct reflist *ap, *last_ap;
2737
2738       /* Macro really takes args.  Compute the expansion of this call.  */
2739
2740       /* Compute length in characters of the macro's expansion.
2741          Also count number of times each arg is used.  */
2742       xbuf_len = defn->length;
2743       for (ap = defn->pattern; ap != NULL; ap = ap->next)
2744         {
2745           if (ap->stringify)
2746             {
2747               register struct argdata *arg = &args[ap->argno];
2748               /* Stringify it it hasn't already been */
2749               if (arg->stringified_length < 0)
2750                 {
2751                   int arglen = arg->raw_length;
2752                   int escaped = 0;
2753                   int in_string = 0;
2754                   int c;
2755                   /* Initially need_space is -1.  Otherwise, 1 means the
2756                      previous character was a space, but we suppressed it;
2757                      0 means the previous character was a non-space.  */
2758                   int need_space = -1;
2759                   i = 0;
2760                   arg->stringified = CPP_WRITTEN (pfile);
2761                   if (!CPP_TRADITIONAL (pfile))
2762                     CPP_PUTC (pfile, '\"'); /* insert beginning quote */
2763                   for (; i < arglen; i++)
2764                     {
2765                       c = (ARG_BASE + arg->raw)[i];
2766
2767                       if (! in_string)
2768                         {
2769                           /* Internal sequences of whitespace are replaced by
2770                              one space except within an string or char token.*/
2771                           if (is_space[c])
2772                             {
2773                               if (CPP_WRITTEN (pfile) > arg->stringified
2774                                   && (CPP_PWRITTEN (pfile))[-1] == '@')
2775                                 {
2776                                   /* "@ " escape markers are removed */
2777                                   CPP_ADJUST_WRITTEN (pfile, -1);
2778                                   continue;
2779                                 }
2780                               if (need_space == 0)
2781                                 need_space = 1;
2782                               continue;
2783                             }
2784                           else if (need_space > 0)
2785                             CPP_PUTC (pfile, ' ');
2786                           need_space = 0;
2787                         }
2788
2789                       if (escaped)
2790                         escaped = 0;
2791                       else
2792                         {
2793                           if (c == '\\')
2794                             escaped = 1;
2795                           if (in_string)
2796                             {
2797                               if (c == in_string)
2798                                 in_string = 0;
2799                             }
2800                           else if (c == '\"' || c == '\'')
2801                             in_string = c;
2802                         }
2803
2804                       /* Escape these chars */
2805                       if (c == '\"' || (in_string && c == '\\'))
2806                         CPP_PUTC (pfile, '\\');
2807                       if (isprint (c))
2808                         CPP_PUTC (pfile, c);
2809                       else
2810                         {
2811                           CPP_RESERVE (pfile, 4);
2812                           sprintf (CPP_PWRITTEN (pfile), "\\%03o",
2813                                    (unsigned int) c);
2814                           CPP_ADJUST_WRITTEN (pfile, 4);
2815                         }
2816                     }
2817                   if (!CPP_TRADITIONAL (pfile))
2818                     CPP_PUTC (pfile, '\"'); /* insert ending quote */
2819                   arg->stringified_length
2820                     = CPP_WRITTEN (pfile) - arg->stringified;
2821                 }
2822               xbuf_len += args[ap->argno].stringified_length;
2823             }
2824           else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
2825             /* Add 4 for two newline-space markers to prevent
2826                token concatenation.  */
2827             xbuf_len += args[ap->argno].raw_length + 4;
2828           else
2829             {
2830               /* We have an ordinary (expanded) occurrence of the arg.
2831                  So compute its expansion, if we have not already.  */
2832               if (args[ap->argno].expand_length < 0)
2833                 {
2834                   args[ap->argno].expanded = CPP_WRITTEN (pfile);
2835                   cpp_expand_to_buffer (pfile,
2836                                         ARG_BASE + args[ap->argno].raw,
2837                                         args[ap->argno].raw_length);
2838
2839                   args[ap->argno].expand_length
2840                     = CPP_WRITTEN (pfile) - args[ap->argno].expanded;
2841                 }
2842
2843               /* Add 4 for two newline-space markers to prevent
2844                  token concatenation.  */
2845               xbuf_len += args[ap->argno].expand_length + 4;
2846             }
2847           if (args[ap->argno].use_count < 10)
2848             args[ap->argno].use_count++;
2849         }
2850
2851       xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
2852
2853       /* Generate in XBUF the complete expansion
2854          with arguments substituted in.
2855          TOTLEN is the total size generated so far.
2856          OFFSET is the index in the definition
2857          of where we are copying from.  */
2858       offset = totlen = 0;
2859       for (last_ap = NULL, ap = defn->pattern; ap != NULL;
2860            last_ap = ap, ap = ap->next)
2861         {
2862           register struct argdata *arg = &args[ap->argno];
2863           int count_before = totlen;
2864
2865           /* Add chars to XBUF.  */
2866           for (i = 0; i < ap->nchars; i++, offset++)
2867             xbuf[totlen++] = exp[offset];
2868
2869           /* If followed by an empty rest arg with concatenation,
2870              delete the last run of nonwhite chars.  */
2871           if (rest_zero && totlen > count_before
2872               && ((ap->rest_args && ap->raw_before)
2873                   || (last_ap != NULL && last_ap->rest_args
2874                       && last_ap->raw_after)))
2875             {
2876               /* Delete final whitespace.  */
2877               while (totlen > count_before && is_space[xbuf[totlen - 1]])
2878                 totlen--;
2879
2880               /* Delete the nonwhites before them.  */
2881               while (totlen > count_before && ! is_space[xbuf[totlen - 1]])
2882                 totlen--;
2883             }
2884
2885           if (ap->stringify != 0)
2886             {
2887               bcopy (ARG_BASE + arg->stringified,
2888                      xbuf + totlen, arg->stringified_length);
2889               totlen += arg->stringified_length;
2890             }
2891           else if (ap->raw_before || ap->raw_after || CPP_TRADITIONAL (pfile))
2892             {
2893               U_CHAR *p1 = ARG_BASE + arg->raw;
2894               U_CHAR *l1 = p1 + arg->raw_length;
2895               if (ap->raw_before)
2896                 {
2897                   while (p1 != l1 && is_space[*p1]) p1++;
2898                   while (p1 != l1 && is_idchar[*p1])
2899                     xbuf[totlen++] = *p1++;
2900                   /* Delete any no-reexpansion marker that follows
2901                      an identifier at the beginning of the argument
2902                      if the argument is concatenated with what precedes it.  */
2903                   if (p1[0] == '@' && p1[1] == '-')
2904                     p1 += 2;
2905                 }
2906               if (ap->raw_after)
2907                 {
2908                   /* Arg is concatenated after: delete trailing whitespace,
2909                      whitespace markers, and no-reexpansion markers.  */
2910                   while (p1 != l1)
2911                     {
2912                       if (is_space[l1[-1]]) l1--;
2913                       else if (l1[-1] == '-')
2914                         {
2915                           U_CHAR *p2 = l1 - 1;
2916                           /* If a `-' is preceded by an odd number of newlines then it
2917                              and the last newline are a no-reexpansion marker.  */
2918                           while (p2 != p1 && p2[-1] == '\n') p2--;
2919                           if ((l1 - 1 - p2) & 1) {
2920                             l1 -= 2;
2921                           }
2922                           else break;
2923                         }
2924                       else break;
2925                     }
2926                 }
2927
2928               bcopy (p1, xbuf + totlen, l1 - p1);
2929               totlen += l1 - p1;
2930             }
2931           else
2932             {
2933               U_CHAR *expanded = ARG_BASE + arg->expanded;
2934               if (!ap->raw_before && totlen > 0 && arg->expand_length
2935                   && !CPP_TRADITIONAL(pfile)
2936                   && unsafe_chars (xbuf[totlen-1], expanded[0]))
2937                 {
2938                   xbuf[totlen++] = '@';
2939                   xbuf[totlen++] = ' ';
2940                 }
2941
2942               bcopy (expanded, xbuf + totlen, arg->expand_length);
2943               totlen += arg->expand_length;
2944
2945               if (!ap->raw_after && totlen > 0 && offset < defn->length
2946                   && !CPP_TRADITIONAL(pfile)
2947                   && unsafe_chars (xbuf[totlen-1], exp[offset]))
2948                 {
2949                   xbuf[totlen++] = '@';
2950                   xbuf[totlen++] = ' ';
2951                 }
2952
2953               /* If a macro argument with newlines is used multiple times,
2954                  then only expand the newlines once.  This avoids creating
2955                  output lines which don't correspond to any input line,
2956                  which confuses gdb and gcov.  */
2957               if (arg->use_count > 1 && arg->newlines > 0)
2958                 {
2959                   /* Don't bother doing change_newlines for subsequent
2960                      uses of arg.  */
2961                   arg->use_count = 1;
2962                   arg->expand_length
2963                     = change_newlines (expanded, arg->expand_length);
2964                 }
2965             }
2966
2967           if (totlen > xbuf_len)
2968             abort ();
2969       }
2970
2971       /* if there is anything left of the definition
2972          after handling the arg list, copy that in too.  */
2973
2974       for (i = offset; i < defn->length; i++)
2975         {
2976           /* if we've reached the end of the macro */
2977           if (exp[i] == ')')
2978             rest_zero = 0;
2979           if (! (rest_zero && last_ap != NULL && last_ap->rest_args
2980                  && last_ap->raw_after))
2981             xbuf[totlen++] = exp[i];
2982         }
2983
2984       xbuf[totlen] = 0;
2985       xbuf_len = totlen;
2986
2987     }
2988
2989   pfile->output_escapes--;
2990
2991   /* Now put the expansion on the input stack
2992      so our caller will commence reading from it.  */
2993   push_macro_expansion (pfile, xbuf, xbuf_len, hp);
2994   CPP_BUFFER (pfile)->has_escapes = 1;
2995
2996   /* Pop the space we've used in the token_buffer for argument expansion.  */
2997   CPP_SET_WRITTEN (pfile, old_written);
2998     
2999   /* Recursive macro use sometimes works traditionally.
3000      #define foo(x,y) bar (x (y,0), y)
3001      foo (foo, baz)  */
3002   
3003   if (!CPP_TRADITIONAL (pfile))
3004     hp->type = T_DISABLED;
3005 }
3006
3007 static void
3008 push_macro_expansion (pfile, xbuf, xbuf_len, hp)
3009      cpp_reader *pfile;
3010      register U_CHAR *xbuf;
3011      int xbuf_len;
3012      HASHNODE *hp;
3013 {
3014   register cpp_buffer *mbuf = cpp_push_buffer (pfile, xbuf, xbuf_len);
3015   if (mbuf == NULL)
3016     return;
3017   mbuf->cleanup = macro_cleanup;
3018   mbuf->data = hp;
3019
3020   /* The first chars of the expansion should be a "@ " added by
3021      collect_expansion.  This is to prevent accidental token-pasting
3022      between the text preceding the macro invocation, and the macro
3023      expansion text.
3024
3025      We would like to avoid adding unneeded spaces (for the sake of
3026      tools that use cpp, such as imake).  In some common cases we can
3027      tell that it is safe to omit the space.
3028
3029      The character before the macro invocation cannot have been an
3030      idchar (or else it would have been pasted with the idchars of
3031      the macro name).  Therefore, if the first non-space character
3032      of the expansion is an idchar, we do not need the extra space
3033      to prevent token pasting.
3034
3035      Also, we don't need the extra space if the first char is '(',
3036      or some other (less common) characters.  */
3037
3038   if (xbuf[0] == '@' && xbuf[1] == ' '
3039       && (is_idchar[xbuf[2]] || xbuf[2] == '(' || xbuf[2] == '\''
3040           || xbuf[2] == '\"'))
3041     mbuf->cur += 2;
3042 }
3043 \f
3044 /* Like cpp_get_token, except that it does not read past end-of-line.
3045    Also, horizontal space is skipped, and macros are popped.  */
3046
3047 static enum cpp_token
3048 get_directive_token (pfile)
3049      cpp_reader *pfile;
3050 {
3051   for (;;)
3052     {
3053       long old_written = CPP_WRITTEN (pfile);
3054       enum cpp_token token;
3055       cpp_skip_hspace (pfile);
3056       if (PEEKC () == '\n')
3057           return CPP_VSPACE;
3058       token = cpp_get_token (pfile);
3059       switch (token)
3060       {
3061       case CPP_POP:
3062           if (! CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
3063               return token;
3064           /* ... else fall though ...  */
3065       case CPP_HSPACE:  case CPP_COMMENT:
3066           CPP_SET_WRITTEN (pfile, old_written);
3067           break;
3068       default:
3069           return token;
3070       }
3071     }
3072 }
3073 \f
3074 /* Handle #include and #import.
3075    This function expects to see "fname" or <fname> on the input.
3076
3077    The input is normally in part of the output_buffer following
3078    CPP_WRITTEN, and will get overwritten by output_line_command.
3079    I.e. in input file specification has been popped by handle_directive.
3080    This is safe.  */
3081
3082 static int
3083 do_include (pfile, keyword, unused1, unused2)
3084      cpp_reader *pfile;
3085      struct directive *keyword;
3086      U_CHAR *unused1, *unused2;
3087 {
3088   int importing = (keyword->type == T_IMPORT);
3089   int skip_dirs = (keyword->type == T_INCLUDE_NEXT);
3090   char *fname;          /* Dynamically allocated fname buffer */
3091   char *pcftry;
3092   char *pcfname;
3093   U_CHAR *fbeg, *fend;          /* Beginning and end of fname */
3094   enum cpp_token token;
3095
3096   /* Chain of dirs to search */
3097   struct file_name_list *search_start = CPP_OPTIONS (pfile)->include;
3098   struct file_name_list dsp[1]; /* First in chain, if #include "..." */
3099   struct file_name_list *searchptr = 0;
3100   long old_written = CPP_WRITTEN (pfile);
3101
3102   int flen;
3103
3104   int f;                        /* file number */
3105
3106   int retried = 0;              /* Have already tried macro
3107                                    expanding the include line */
3108   int angle_brackets = 0;       /* 0 for "...", 1 for <...> */
3109   int pcf = -1;
3110   char *pcfbuf;
3111   char *pcfbuflimit;
3112   int pcfnum;
3113   f= -1;                        /* JF we iz paranoid! */
3114
3115   if (importing && CPP_OPTIONS (pfile)->warn_import
3116       && !CPP_OPTIONS (pfile)->inhibit_warnings
3117       && !CPP_BUFFER (pfile)->system_header_p && !pfile->import_warning)
3118     {
3119       pfile->import_warning = 1;
3120       cpp_warning (pfile, "using `#import' is not recommended");
3121       fprintf (stderr, "The fact that a certain header file need not be processed more than once\n");
3122       fprintf (stderr, "should be indicated in the header file, not where it is used.\n");
3123       fprintf (stderr, "The best way to do this is with a conditional of this form:\n\n");
3124       fprintf (stderr, "  #ifndef _FOO_H_INCLUDED\n");
3125       fprintf (stderr, "  #define _FOO_H_INCLUDED\n");
3126       fprintf (stderr, "  ... <real contents of file> ...\n");
3127       fprintf (stderr, "  #endif /* Not _FOO_H_INCLUDED */\n\n");
3128       fprintf (stderr, "Then users can use `#include' any number of times.\n");
3129       fprintf (stderr, "GNU C automatically avoids processing the file more than once\n");
3130       fprintf (stderr, "when it is equipped with such a conditional.\n");
3131     }
3132
3133   pfile->parsing_include_directive++;
3134   token = get_directive_token (pfile);
3135   pfile->parsing_include_directive--;
3136
3137   if (token == CPP_STRING)
3138     {
3139       /* FIXME - check no trailing garbage */
3140       fbeg = pfile->token_buffer + old_written + 1;
3141       fend = CPP_PWRITTEN (pfile) - 1;
3142       if (fbeg[-1] == '<')
3143         {
3144           angle_brackets = 1;
3145           /* If -I-, start with the first -I dir after the -I-.  */
3146           if (CPP_OPTIONS (pfile)->first_bracket_include)
3147             search_start = CPP_OPTIONS (pfile)->first_bracket_include;
3148         }
3149       /* If -I- was specified, don't search current dir, only spec'd ones.  */
3150       else if (! CPP_OPTIONS (pfile)->ignore_srcdir)
3151         {
3152           cpp_buffer *fp = CPP_BUFFER (pfile);
3153           /* We have "filename".  Figure out directory this source
3154              file is coming from and put it on the front of the list.  */
3155
3156           for ( ; fp != CPP_NULL_BUFFER (pfile); fp = CPP_PREV_BUFFER (fp))
3157             {
3158               int n;
3159               char *ep,*nam;
3160
3161               if ((nam = fp->nominal_fname) != NULL)
3162                 {
3163                   /* Found a named file.  Figure out dir of the file,
3164                      and put it in front of the search list.  */
3165                   dsp[0].next = search_start;
3166                   search_start = dsp;
3167 #ifndef VMS
3168                   ep = rindex (nam, '/');
3169 #else                           /* VMS */
3170                   ep = rindex (nam, ']');
3171                   if (ep == NULL) ep = rindex (nam, '>');
3172                   if (ep == NULL) ep = rindex (nam, ':');
3173                   if (ep != NULL) ep++;
3174 #endif                          /* VMS */
3175                   if (ep != NULL)
3176                     {
3177                       n = ep - nam;
3178                       dsp[0].fname = (char *) alloca (n + 1);
3179                       strncpy (dsp[0].fname, nam, n);
3180                       dsp[0].fname[n] = '\0';
3181                       if (n + INCLUDE_LEN_FUDGE > pfile->max_include_len)
3182                         pfile->max_include_len = n + INCLUDE_LEN_FUDGE;
3183                     }
3184                   else
3185                     {
3186                       dsp[0].fname = 0; /* Current directory */
3187                     }
3188                   dsp[0].got_name_map = 0;
3189                   break;
3190                 }
3191             }
3192         }
3193     }
3194 #ifdef VMS
3195   else if (token == CPP_NAME)
3196     {
3197       /*
3198        * Support '#include xyz' like VAX-C to allow for easy use of all the
3199        * decwindow include files. It defaults to '#include <xyz.h>' (so the
3200        * code from case '<' is repeated here) and generates a warning.
3201        */
3202       cpp_warning (pfile,
3203                    "VAX-C-style include specification found, use '#include <filename.h>' !");
3204       angle_brackets = 1;
3205       /* If -I-, start with the first -I dir after the -I-.  */
3206       if (CPP_OPTIONS (pfile)->first_bracket_include)
3207         search_start = CPP_OPTIONS (pfile)->first_bracket_include;
3208       fbeg = pfile->token_buffer + old_written;
3209       fend = CPP_PWRITTEN (pfile);
3210     }
3211 #endif
3212   else
3213     {
3214       cpp_error (pfile,
3215                  "`#%s' expects \"FILENAME\" or <FILENAME>", keyword->name);
3216       CPP_SET_WRITTEN (pfile, old_written);
3217       skip_rest_of_line (pfile);
3218       return 0;
3219     }
3220
3221   *fend = 0;
3222
3223   token = get_directive_token (pfile);
3224   if (token != CPP_VSPACE)
3225     {
3226       cpp_error (pfile, "junk at end of `#include'");
3227       while (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP)
3228         token = get_directive_token (pfile);
3229     }
3230
3231   /* For #include_next, skip in the search path
3232      past the dir in which the containing file was found.  */
3233   if (skip_dirs)
3234     {
3235       cpp_buffer *fp = CPP_BUFFER (pfile);
3236       for (; fp != CPP_NULL_BUFFER (pfile); fp = CPP_PREV_BUFFER (fp))
3237         if (fp->fname != NULL)
3238           {
3239             /* fp->dir is null if the containing file was specified with
3240                an absolute file name.  In that case, don't skip anything.  */
3241             if (fp->dir == SELF_DIR_DUMMY)
3242               search_start = CPP_OPTIONS (pfile)->include;
3243             else if (fp->dir)
3244               search_start = fp->dir->next;
3245             break;
3246           }
3247     }
3248
3249   CPP_SET_WRITTEN (pfile, old_written);
3250
3251   flen = fend - fbeg;
3252
3253   if (flen == 0)
3254     {
3255       cpp_error (pfile, "empty file name in `#%s'", keyword->name);
3256       return 0;
3257     }
3258
3259   /* Allocate this permanently, because it gets stored in the definitions
3260      of macros.  */
3261   fname = (char *) xmalloc (pfile->max_include_len + flen + 4);
3262   /* + 2 above for slash and terminating null.  */
3263   /* + 2 added for '.h' on VMS (to support '#include filename') */
3264
3265   /* If specified file name is absolute, just open it.  */
3266
3267   if (*fbeg == '/') {
3268     strncpy (fname, fbeg, flen);
3269     fname[flen] = 0;
3270     if (redundant_include_p (pfile, fname))
3271       return 0;
3272     if (importing)
3273       f = lookup_import (pfile, fname, NULL_PTR);
3274     else
3275       f = open_include_file (pfile, fname, NULL_PTR);
3276     if (f == -2)
3277       return 0;         /* Already included this file */
3278   } else {
3279     /* Search directory path, trying to open the file.
3280        Copy each filename tried into FNAME.  */
3281
3282     for (searchptr = search_start; searchptr; searchptr = searchptr->next) {
3283       if (searchptr->fname) {
3284         /* The empty string in a search path is ignored.
3285            This makes it possible to turn off entirely
3286            a standard piece of the list.  */
3287         if (searchptr->fname[0] == 0)
3288           continue;
3289         strcpy (fname, searchptr->fname);
3290         strcat (fname, "/");
3291         fname[strlen (fname) + flen] = 0;
3292       } else {
3293         fname[0] = 0;
3294       }
3295       strncat (fname, fbeg, flen);
3296 #ifdef VMS
3297       /* Change this 1/2 Unix 1/2 VMS file specification into a
3298          full VMS file specification */
3299       if (searchptr->fname && (searchptr->fname[0] != 0)) {
3300         /* Fix up the filename */
3301         hack_vms_include_specification (fname);
3302       } else {
3303         /* This is a normal VMS filespec, so use it unchanged.  */
3304         strncpy (fname, fbeg, flen);
3305         fname[flen] = 0;
3306         /* if it's '#include filename', add the missing .h */
3307         if (index(fname,'.')==NULL) {
3308           strcat (fname, ".h");
3309         }
3310       }
3311 #endif /* VMS */
3312       /* ??? There are currently 3 separate mechanisms for avoiding processing
3313          of redundant include files: #import, #pragma once, and
3314          redundant_include_p.  It would be nice if they were unified.  */
3315       if (redundant_include_p (pfile, fname))
3316         return 0;
3317       if (importing)
3318         f = lookup_import (pfile, fname, searchptr);
3319       else
3320         f = open_include_file (pfile, fname, searchptr);
3321       if (f == -2)
3322         return 0;                       /* Already included this file */
3323 #ifdef EACCES
3324       else if (f == -1 && errno == EACCES)
3325         cpp_warning (pfile, "Header file %s exists, but is not readable",
3326                      fname);
3327 #endif
3328       if (f >= 0)
3329         break;
3330     }
3331   }
3332
3333   if (f < 0)
3334     {
3335       /* A file that was not found.  */
3336       strncpy (fname, fbeg, flen);
3337       fname[flen] = 0;
3338       /* If generating dependencies and -MG was specified, we assume missing
3339          files are leaf files, living in the same directory as the source file
3340          or other similar place; these missing files may be generated from
3341          other files and may not exist yet (eg: y.tab.h).  */
3342
3343       if (CPP_OPTIONS(pfile)->print_deps_missing_files
3344           && CPP_PRINT_DEPS (pfile)
3345           > (angle_brackets || (pfile->system_include_depth > 0)))
3346         {
3347           /* If it was requested as a system header file,
3348              then assume it belongs in the first place to look for such.  */
3349           if (angle_brackets)
3350             {
3351               for (searchptr = search_start; searchptr;
3352                    searchptr = searchptr->next)
3353                 {
3354                   if (searchptr->fname)
3355                     {
3356                       char *p;
3357
3358                       if (searchptr->fname[0] == 0)
3359                         continue;
3360                       p = (char *) alloca (strlen (searchptr->fname)
3361                                            + strlen (fname) + 2);
3362                       strcpy (p, searchptr->fname);
3363                       strcat (p, "/");
3364                       strcat (p, fname);
3365                       deps_output (pfile, p, ' ');
3366                       break;
3367                     }
3368                 }
3369             }
3370           else
3371             {
3372               /* Otherwise, omit the directory, as if the file existed
3373                  in the directory with the source.  */
3374               deps_output (pfile, fname, ' ');
3375             }
3376         }
3377       /* If -M was specified, and this header file won't be added to the
3378          dependency list, then don't count this as an error, because we can
3379          still produce correct output.  Otherwise, we can't produce correct
3380          output, because there may be dependencies we need inside the missing
3381          file, and we don't know what directory this missing file exists in.*/
3382       else if (CPP_PRINT_DEPS (pfile)
3383                && (CPP_PRINT_DEPS (pfile)
3384                    <= (angle_brackets || (pfile->system_include_depth > 0))))
3385         cpp_warning (pfile, "No include path in which to find %s", fname);
3386       else if (search_start)
3387         cpp_error_from_errno (pfile, fname);
3388       else
3389         cpp_error (pfile, "No include path in which to find %s", fname);
3390     }
3391   else {
3392     /* Check to see if this include file is a once-only include file.
3393        If so, give up.  */
3394
3395     struct file_name_list *ptr;
3396
3397     for (ptr = pfile->dont_repeat_files; ptr; ptr = ptr->next) {
3398       if (!strcmp (ptr->fname, fname)) {
3399         close (f);
3400         return 0;                               /* This file was once'd.  */
3401       }
3402     }
3403
3404     for (ptr = pfile->all_include_files; ptr; ptr = ptr->next) {
3405       if (!strcmp (ptr->fname, fname))
3406         break;                          /* This file was included before.  */
3407     }
3408
3409     if (ptr == 0) {
3410       /* This is the first time for this file.  */
3411       /* Add it to list of files included.  */
3412
3413       ptr = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3414       ptr->control_macro = 0;
3415       ptr->c_system_include_path = 0;
3416       ptr->next = pfile->all_include_files;
3417       pfile->all_include_files = ptr;
3418       ptr->fname = savestring (fname);
3419       ptr->got_name_map = 0;
3420
3421       /* For -M, add this file to the dependencies.  */
3422       if (CPP_PRINT_DEPS (pfile)
3423           > (angle_brackets || (pfile->system_include_depth > 0)))
3424         deps_output (pfile, fname, ' ');
3425     }   
3426
3427     /* Handle -H option.  */
3428     if (CPP_OPTIONS(pfile)->print_include_names)
3429       {
3430         cpp_buffer *buf = CPP_BUFFER (pfile);
3431         while ((buf = CPP_PREV_BUFFER (buf)) != CPP_NULL_BUFFER (pfile))
3432           putc ('.', stderr);
3433         fprintf (stderr, "%s\n", fname);
3434       }
3435
3436     if (angle_brackets)
3437       pfile->system_include_depth++;
3438
3439     /* Actually process the file.  */
3440
3441     /* Record file on "seen" list for #import.  */
3442     add_import (pfile, f, fname);
3443
3444     pcftry = (char *) alloca (strlen (fname) + 30);
3445     pcfbuf = 0;
3446     pcfnum = 0;
3447
3448 #if 0
3449     if (!no_precomp)
3450       {
3451         struct stat stat_f;
3452
3453         fstat (f, &stat_f);
3454
3455         do {
3456           sprintf (pcftry, "%s%d", fname, pcfnum++);
3457
3458           pcf = open (pcftry, O_RDONLY, 0666);
3459           if (pcf != -1)
3460             {
3461               struct stat s;
3462
3463               fstat (pcf, &s);
3464               if (bcmp ((char *) &stat_f.st_ino, (char *) &s.st_ino,
3465                         sizeof (s.st_ino))
3466                   || stat_f.st_dev != s.st_dev)
3467                 {
3468                   pcfbuf = check_precompiled (pcf, fname, &pcfbuflimit);
3469                   /* Don't need it any more.  */
3470                   close (pcf);
3471                 }
3472               else
3473                 {
3474                   /* Don't need it at all.  */
3475                   close (pcf);
3476                   break;
3477                 }
3478             }
3479         } while (pcf != -1 && !pcfbuf);
3480       }
3481 #endif
3482     
3483     /* Actually process the file */
3484     if (cpp_push_buffer (pfile, NULL, 0) == NULL)
3485       return 0;
3486     if (finclude (pfile, f, fname, is_system_include (pfile, fname),
3487                   searchptr != dsp ? searchptr : SELF_DIR_DUMMY))
3488       {
3489         output_line_command (pfile, 0, enter_file);
3490         pfile->only_seen_white = 2;
3491       }
3492
3493     if (angle_brackets)
3494       pfile->system_include_depth--;
3495   }
3496   return 0;
3497 }
3498
3499 /* Return nonzero if there is no need to include file NAME
3500    because it has already been included and it contains a conditional
3501    to make a repeated include do nothing.  */
3502
3503 static int
3504 redundant_include_p (pfile, name)
3505      cpp_reader *pfile;
3506      char *name;
3507 {
3508   struct file_name_list *l = pfile->all_include_files;
3509   for (; l; l = l->next)
3510     if (! strcmp (name, l->fname)
3511         && l->control_macro
3512         && cpp_lookup (pfile, l->control_macro, -1, -1))
3513       return 1;
3514   return 0;
3515 }
3516
3517 /* Return nonzero if the given FILENAME is an absolute pathname which
3518    designates a file within one of the known "system" include file
3519    directories.  We assume here that if the given FILENAME looks like
3520    it is the name of a file which resides either directly in a "system"
3521    include file directory, or within any subdirectory thereof, then the
3522    given file must be a "system" include file.  This function tells us
3523    if we should suppress pedantic errors/warnings for the given FILENAME.
3524
3525    The value is 2 if the file is a C-language system header file
3526    for which C++ should (on most systems) assume `extern "C"'.  */
3527
3528 static int
3529 is_system_include (pfile, filename)
3530      cpp_reader *pfile;
3531      register char *filename;
3532 {
3533   struct file_name_list *searchptr;
3534
3535   for (searchptr = CPP_OPTIONS (pfile)->first_system_include; searchptr;
3536        searchptr = searchptr->next)
3537     if (searchptr->fname) {
3538       register char *sys_dir = searchptr->fname;
3539       register unsigned length = strlen (sys_dir);
3540
3541       if (! strncmp (sys_dir, filename, length) && filename[length] == '/')
3542         {
3543           if (searchptr->c_system_include_path)
3544             return 2;
3545           else
3546             return 1;
3547         }
3548     }
3549   return 0;
3550 }
3551
3552 \f
3553 /*
3554  * Install a name in the assertion hash table.
3555  *
3556  * If LEN is >= 0, it is the length of the name.
3557  * Otherwise, compute the length by scanning the entire name.
3558  *
3559  * If HASH is >= 0, it is the precomputed hash code.
3560  * Otherwise, compute the hash code.
3561  */
3562
3563 static ASSERTION_HASHNODE *
3564 assertion_install (pfile, name, len, hash)
3565      cpp_reader *pfile;
3566      U_CHAR *name;
3567      int len;
3568      int hash;
3569 {
3570   register ASSERTION_HASHNODE *hp;
3571   register int i, bucket;
3572   register U_CHAR *p, *q;
3573
3574   i = sizeof (ASSERTION_HASHNODE) + len + 1;
3575   hp = (ASSERTION_HASHNODE *) xmalloc (i);
3576   bucket = hash;
3577   hp->bucket_hdr = &pfile->assertion_hashtab[bucket];
3578   hp->next = pfile->assertion_hashtab[bucket];
3579   pfile->assertion_hashtab[bucket] = hp;
3580   hp->prev = NULL;
3581   if (hp->next != NULL)
3582     hp->next->prev = hp;
3583   hp->length = len;
3584   hp->value = 0;
3585   hp->name = ((U_CHAR *) hp) + sizeof (ASSERTION_HASHNODE);
3586   p = hp->name;
3587   q = name;
3588   for (i = 0; i < len; i++)
3589     *p++ = *q++;
3590   hp->name[len] = 0;
3591   return hp;
3592 }
3593 /*
3594  * find the most recent hash node for name name (ending with first
3595  * non-identifier char) installed by install
3596  *
3597  * If LEN is >= 0, it is the length of the name.
3598  * Otherwise, compute the length by scanning the entire name.
3599  *
3600  * If HASH is >= 0, it is the precomputed hash code.
3601  * Otherwise, compute the hash code.
3602  */
3603
3604 static ASSERTION_HASHNODE *
3605 assertion_lookup (pfile, name, len, hash)
3606      cpp_reader *pfile;
3607      U_CHAR *name;
3608      int len;
3609      int hash;
3610 {
3611   register ASSERTION_HASHNODE *bucket;
3612
3613   bucket = pfile->assertion_hashtab[hash];
3614   while (bucket) {
3615     if (bucket->length == len && strncmp (bucket->name, name, len) == 0)
3616       return bucket;
3617     bucket = bucket->next;
3618   }
3619   return NULL;
3620 }
3621
3622 static void
3623 delete_assertion (hp)
3624      ASSERTION_HASHNODE *hp;
3625 {
3626   struct tokenlist_list *tail;
3627   if (hp->prev != NULL)
3628     hp->prev->next = hp->next;
3629   if (hp->next != NULL)
3630     hp->next->prev = hp->prev;
3631
3632   for (tail = hp->value; tail; )
3633     {
3634       struct tokenlist_list *next = tail->next;
3635       free_token_list (tail->tokens);
3636       free (tail);
3637       tail = next;
3638     }
3639
3640   /* Make sure that the bucket chain header that
3641      the deleted guy was on points to the right thing afterwards.  */
3642   if (hp == *hp->bucket_hdr)
3643     *hp->bucket_hdr = hp->next;
3644
3645   free (hp);
3646 }
3647 \f
3648 /* Convert a character string literal into a nul-terminated string.
3649    The input string is [IN ... LIMIT).
3650    The result is placed in RESULT.  RESULT can be the same as IN.
3651    The value returned in the end of the string written to RESULT,
3652    or NULL on error.  */
3653
3654 static U_CHAR *
3655 convert_string (pfile, result, in, limit, handle_escapes)
3656      cpp_reader *pfile;
3657      register U_CHAR *result, *in, *limit;
3658      int handle_escapes;
3659 {
3660   U_CHAR c;
3661   c = *in++;
3662   if (c != '\"')
3663     return NULL;
3664   while (in < limit)
3665     {
3666       U_CHAR c = *in++;
3667       switch (c)
3668         {
3669         case '\0':
3670           return NULL;
3671         case '\"':
3672           limit = in;
3673           break;
3674         case '\\':
3675           if (handle_escapes)
3676             {
3677               char *bpc = (char *) in;
3678               int i = (U_CHAR) cpp_parse_escape (pfile, &bpc);
3679               in = (U_CHAR *) bpc;
3680               if (i >= 0)
3681                 *result++ = (U_CHAR)c;
3682               break;
3683             }
3684           /* else fall through */
3685         default:
3686           *result++ = c;
3687         }
3688     }
3689   *result = 0;
3690   return result;
3691 }
3692
3693 /*
3694  * interpret #line command.  Remembers previously seen fnames
3695  * in its very own hash table.
3696  */
3697 #define FNAME_HASHSIZE 37
3698
3699 static int
3700 do_line (pfile, keyword)
3701      cpp_reader *pfile;
3702      struct directive *keyword;
3703 {
3704   cpp_buffer *ip = CPP_BUFFER (pfile);
3705   int new_lineno;
3706   long old_written = CPP_WRITTEN (pfile);
3707   enum file_change_code file_change = same_file;
3708   enum cpp_token token;
3709   int i;
3710
3711   token = get_directive_token (pfile);
3712
3713   if (token != CPP_NUMBER
3714       || !isdigit(pfile->token_buffer[old_written]))
3715     {
3716       cpp_error (pfile, "invalid format `#line' command");
3717       goto bad_line_directive;
3718     }
3719
3720   /* The Newline at the end of this line remains to be processed.
3721      To put the next line at the specified line number,
3722      we must store a line number now that is one less.  */
3723   new_lineno = atoi (pfile->token_buffer + old_written) - 1;
3724   CPP_SET_WRITTEN (pfile, old_written);
3725
3726   /* NEW_LINENO is one less than the actual line number here.  */
3727   if (CPP_PEDANTIC (pfile) && new_lineno < 0)
3728     cpp_pedwarn (pfile, "line number out of range in `#line' command");
3729
3730 #if 0 /* #line 10"foo.c" is supposed to be allowed.  */
3731   if (PEEKC() && !is_space[PEEKC()]) {
3732     cpp_error (pfile, "invalid format `#line' command");
3733     goto bad_line_directive;
3734   }
3735 #endif
3736
3737   token = get_directive_token (pfile);
3738
3739   if (token == CPP_STRING) {
3740     U_CHAR *fname = pfile->token_buffer + old_written;
3741     U_CHAR *end_name;
3742     static HASHNODE *fname_table[FNAME_HASHSIZE];
3743     HASHNODE *hp, **hash_bucket;
3744     U_CHAR *p;
3745     long num_start;
3746     int fname_length;
3747
3748     /* Turn the file name, which is a character string literal,
3749        into a null-terminated string.  Do this in place.  */
3750     end_name = convert_string (pfile, fname, fname, CPP_PWRITTEN (pfile), 1);
3751     if (end_name == NULL)
3752     {
3753         cpp_error (pfile, "invalid format `#line' command");
3754         goto bad_line_directive;
3755     }
3756
3757     fname_length = end_name - fname;
3758
3759     num_start = CPP_WRITTEN (pfile);
3760     token = get_directive_token (pfile);
3761     if (token != CPP_VSPACE && token != CPP_EOF && token != CPP_POP) {
3762       p = pfile->token_buffer + num_start;
3763       if (CPP_PEDANTIC (pfile))
3764         cpp_pedwarn (pfile, "garbage at end of `#line' command");
3765
3766       if (token != CPP_NUMBER || *p < '0' || *p > '4' || p[1] != '\0')
3767       {
3768         cpp_error (pfile, "invalid format `#line' command");
3769         goto bad_line_directive;
3770       }
3771       if (*p == '1')
3772         file_change = enter_file;
3773       else if (*p == 2)
3774         file_change = leave_file;
3775       else if (*p == 3)
3776         ip->system_header_p = 1;
3777       else /* if (*p == 4) */
3778         ip->system_header_p = 2;
3779
3780       CPP_SET_WRITTEN (pfile, num_start);
3781       token = get_directive_token (pfile);
3782       p = pfile->token_buffer + num_start;
3783       if (token == CPP_NUMBER && p[1] == '\0' && (*p == '3' || *p== '4')) {
3784         ip->system_header_p = *p == 3 ? 1 : 2;
3785         token = get_directive_token (pfile);
3786       }
3787       if (token != CPP_VSPACE) {
3788         cpp_error (pfile, "invalid format `#line' command");
3789         goto bad_line_directive;
3790       }
3791     }
3792
3793     hash_bucket =
3794       &fname_table[hashf (fname, fname_length, FNAME_HASHSIZE)];
3795     for (hp = *hash_bucket; hp != NULL; hp = hp->next)
3796       if (hp->length == fname_length &&
3797           strncmp (hp->value.cpval, fname, fname_length) == 0) {
3798         ip->nominal_fname = hp->value.cpval;
3799         break;
3800       }
3801     if (hp == 0) {
3802       /* Didn't find it; cons up a new one.  */
3803       hp = (HASHNODE *) xcalloc (1, sizeof (HASHNODE) + fname_length + 1);
3804       hp->next = *hash_bucket;
3805       *hash_bucket = hp;
3806
3807       hp->length = fname_length;
3808       ip->nominal_fname = hp->value.cpval = ((char *) hp) + sizeof (HASHNODE);
3809       bcopy (fname, hp->value.cpval, fname_length);
3810     }
3811   }
3812   else if (token != CPP_VSPACE && token != CPP_EOF) {
3813     cpp_error (pfile, "invalid format `#line' command");
3814     goto bad_line_directive;
3815   }
3816
3817   ip->lineno = new_lineno;
3818  bad_line_directive:
3819   skip_rest_of_line (pfile);
3820   CPP_SET_WRITTEN (pfile, old_written);
3821   output_line_command (pfile, 0, file_change);
3822   return 0;
3823 }
3824
3825 /*
3826  * remove the definition of a symbol from the symbol table.
3827  * according to un*x /lib/cpp, it is not an error to undef
3828  * something that has no definitions, so it isn't one here either.
3829  */
3830
3831 static int
3832 do_undef (pfile, keyword, buf, limit)
3833      cpp_reader *pfile;
3834      struct directive *keyword;
3835      U_CHAR *buf, *limit;
3836 {
3837   int sym_length;
3838   HASHNODE *hp;
3839   U_CHAR *orig_buf = buf;
3840
3841 #if 0
3842   /* If this is a precompiler run (with -pcp) pass thru #undef commands.  */
3843   if (pcp_outfile && keyword)
3844     pass_thru_directive (buf, limit, pfile, keyword);
3845 #endif
3846
3847   SKIP_WHITE_SPACE (buf);
3848   sym_length = check_macro_name (pfile, buf, "macro");
3849
3850   while ((hp = cpp_lookup (pfile, buf, sym_length, -1)) != NULL)
3851     {
3852       /* If we are generating additional info for debugging (with -g) we
3853          need to pass through all effective #undef commands.  */
3854       if (CPP_OPTIONS (pfile)->debug_output && keyword)
3855         pass_thru_directive (orig_buf, limit, pfile, keyword);
3856       if (hp->type != T_MACRO)
3857         cpp_warning (pfile, "undefining `%s'", hp->name);
3858       delete_macro (hp);
3859     }
3860
3861   if (CPP_PEDANTIC (pfile)) {
3862     buf += sym_length;
3863     SKIP_WHITE_SPACE (buf);
3864     if (buf != limit)
3865       cpp_pedwarn (pfile, "garbage after `#undef' directive");
3866   }
3867   return 0;
3868 }
3869 \f
3870 /*
3871  * Report an error detected by the program we are processing.
3872  * Use the text of the line in the error message.
3873  * (We use error because it prints the filename & line#.)
3874  */
3875
3876 static int
3877 do_error (pfile, keyword, buf, limit)
3878      cpp_reader *pfile;
3879      struct directive *keyword;
3880      U_CHAR *buf, *limit;
3881 {
3882   int length = limit - buf;
3883   U_CHAR *copy = (U_CHAR *) alloca (length + 1);
3884   bcopy (buf, copy, length);
3885   copy[length] = 0;
3886   SKIP_WHITE_SPACE (copy);
3887   cpp_error (pfile, "#error %s", copy);
3888   return 0;
3889 }
3890
3891 /*
3892  * Report a warning detected by the program we are processing.
3893  * Use the text of the line in the warning message, then continue.
3894  * (We use error because it prints the filename & line#.)
3895  */
3896
3897 static int
3898 do_warning (pfile, keyword, buf, limit)
3899      cpp_reader *pfile;
3900      struct directive *keyword;
3901      U_CHAR *buf, *limit;
3902 {
3903   int length = limit - buf;
3904   U_CHAR *copy = (U_CHAR *) alloca (length + 1);
3905   bcopy (buf, copy, length);
3906   copy[length] = 0;
3907   SKIP_WHITE_SPACE (copy);
3908   cpp_warning (pfile, "#warning %s", copy);
3909   return 0;
3910 }
3911
3912 /* Remember the name of the current file being read from so that we can
3913    avoid ever including it again.  */
3914
3915 static int
3916 do_once (pfile)
3917      cpp_reader *pfile;
3918 {
3919   cpp_buffer *ip = NULL;
3920   struct file_name_list *new;
3921
3922   for (ip = CPP_BUFFER (pfile); ; ip = CPP_PREV_BUFFER (ip))
3923     {
3924       if (ip == CPP_NULL_BUFFER (pfile))
3925         return 0;
3926       if (ip->fname != NULL)
3927         break;
3928     }
3929
3930     
3931   new = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
3932   new->next = pfile->dont_repeat_files;
3933   pfile->dont_repeat_files = new;
3934   new->fname = savestring (ip->fname);
3935   new->control_macro = 0;
3936   new->got_name_map = 0;
3937   new->c_system_include_path = 0;
3938
3939   return 0;
3940 }
3941
3942 /* #ident has already been copied to the output file, so just ignore it.  */
3943
3944 static int
3945 do_ident (pfile, keyword, buf, limit)
3946      cpp_reader *pfile;
3947      struct directive *keyword;
3948      U_CHAR *buf, *limit;
3949 {
3950 /*  long old_written = CPP_WRITTEN (pfile);*/
3951   int len;
3952
3953   /* Allow #ident in system headers, since that's not user's fault.  */
3954   if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
3955     cpp_pedwarn (pfile, "ANSI C does not allow `#ident'");
3956
3957   /* Leave rest of line to be read by later calls to cpp_get_token.  */
3958
3959   return 0;
3960 }
3961
3962 /* #pragma and its argument line have already been copied to the output file.
3963    Just check for some recognized pragmas that need validation here.  */
3964
3965 static int
3966 do_pragma (pfile, keyword, buf, limit)
3967      cpp_reader *pfile;
3968      struct directive *keyword;
3969      U_CHAR *buf, *limit;
3970 {
3971   while (*buf == ' ' || *buf == '\t')
3972     buf++;
3973   if (!strncmp (buf, "once", 4)) {
3974     /* Allow #pragma once in system headers, since that's not the user's
3975        fault.  */
3976     if (!CPP_BUFFER (pfile)->system_header_p)
3977       cpp_warning (pfile, "`#pragma once' is obsolete");
3978     do_once (pfile);
3979   }
3980
3981   if (!strncmp (buf, "implementation", 14)) {
3982     /* Be quiet about `#pragma implementation' for a file only if it hasn't
3983        been included yet.  */
3984     struct file_name_list *ptr;
3985     U_CHAR *p = buf + 14, *fname, *inc_fname;
3986     int fname_len;
3987     SKIP_WHITE_SPACE (p);
3988     if (*p == '\n' || *p != '\"')
3989       return 0;
3990
3991     fname = p + 1;
3992     p = (U_CHAR *) index (fname, '\"');
3993     fname_len = p != NULL ? p - fname : strlen (fname);
3994     
3995     for (ptr = pfile->all_include_files; ptr; ptr = ptr->next) {
3996       inc_fname = (U_CHAR *) rindex (ptr->fname, '/');
3997       inc_fname = inc_fname ? inc_fname + 1 : (U_CHAR *) ptr->fname;
3998       if (inc_fname && !strncmp (inc_fname, fname, fname_len))
3999         cpp_warning (pfile,
4000            "`#pragma implementation' for `%s' appears after file is included",
4001                      fname);
4002     }
4003   }
4004
4005   return 0;
4006 }
4007
4008 #if 0
4009 /* This was a fun hack, but #pragma seems to start to be useful.
4010    By failing to recognize it, we pass it through unchanged to cc1.  */
4011
4012 /*
4013  * the behavior of the #pragma directive is implementation defined.
4014  * this implementation defines it as follows.
4015  */
4016
4017 static int
4018 do_pragma ()
4019 {
4020   close (0);
4021   if (open ("/dev/tty", O_RDONLY, 0666) != 0)
4022     goto nope;
4023   close (1);
4024   if (open ("/dev/tty", O_WRONLY, 0666) != 1)
4025     goto nope;
4026   execl ("/usr/games/hack", "#pragma", 0);
4027   execl ("/usr/games/rogue", "#pragma", 0);
4028   execl ("/usr/new/emacs", "-f", "hanoi", "9", "-kill", 0);
4029   execl ("/usr/local/emacs", "-f", "hanoi", "9", "-kill", 0);
4030 nope:
4031   fatal ("You are in a maze of twisty compiler features, all different");
4032 }
4033 #endif
4034
4035 /* Just ignore #sccs, on systems where we define it at all.  */
4036
4037 static int
4038 do_sccs (pfile, keyword, buf, limit)
4039      cpp_reader *pfile;
4040      struct directive *keyword;
4041      U_CHAR *buf, *limit;
4042 {
4043   if (CPP_PEDANTIC (pfile))
4044     cpp_pedwarn (pfile, "ANSI C does not allow `#sccs'");
4045   return 0;
4046 }
4047 \f
4048 /*
4049  * handle #if command by
4050  *   1) inserting special `defined' keyword into the hash table
4051  *      that gets turned into 0 or 1 by special_symbol (thus,
4052  *      if the luser has a symbol called `defined' already, it won't
4053  *      work inside the #if command)
4054  *   2) rescan the input into a temporary output buffer
4055  *   3) pass the output buffer to the yacc parser and collect a value
4056  *   4) clean up the mess left from steps 1 and 2.
4057  *   5) call conditional_skip to skip til the next #endif (etc.),
4058  *      or not, depending on the value from step 3.
4059  */
4060
4061 static int
4062 do_if (pfile, keyword, buf, limit)
4063      cpp_reader *pfile;
4064      struct directive *keyword;
4065      U_CHAR *buf, *limit;
4066 {
4067   HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4068   conditional_skip (pfile, value == 0, T_IF, NULL_PTR);
4069   return 0;
4070 }
4071
4072 /*
4073  * handle a #elif directive by not changing  if_stack  either.
4074  * see the comment above do_else.
4075  */
4076
4077 static int
4078 do_elif (pfile, keyword, buf, limit)
4079      cpp_reader *pfile;
4080      struct directive *keyword;
4081      U_CHAR *buf, *limit;
4082 {
4083   if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack) {
4084     cpp_error (pfile, "`#elif' not within a conditional");
4085     return 0;
4086   } else {
4087     if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF) {
4088       cpp_error (pfile, "`#elif' after `#else'");
4089 #if 0
4090       fprintf (stderr, " (matches line %d", pfile->if_stack->lineno);
4091 #endif
4092       if (pfile->if_stack->fname != NULL && CPP_BUFFER (pfile)->fname != NULL
4093           && strcmp (pfile->if_stack->fname,
4094                      CPP_BUFFER (pfile)->nominal_fname) != 0)
4095         fprintf (stderr, ", file %s", pfile->if_stack->fname);
4096       fprintf (stderr, ")\n");
4097     }
4098     pfile->if_stack->type = T_ELIF;
4099   }
4100
4101   if (pfile->if_stack->if_succeeded)
4102     skip_if_group (pfile, 0);
4103   else {
4104     HOST_WIDE_INT value = eval_if_expression (pfile, buf, limit - buf);
4105     if (value == 0)
4106       skip_if_group (pfile, 0);
4107     else {
4108       ++pfile->if_stack->if_succeeded;  /* continue processing input */
4109       output_line_command (pfile, 1, same_file);
4110     }
4111   }
4112   return 0;
4113 }
4114
4115 /*
4116  * evaluate a #if expression in BUF, of length LENGTH,
4117  * then parse the result as a C expression and return the value as an int.
4118  */
4119
4120 static HOST_WIDE_INT
4121 eval_if_expression (pfile, buf, length)
4122      cpp_reader *pfile;
4123      U_CHAR *buf;
4124      int length;
4125 {
4126   HASHNODE *save_defined;
4127   HOST_WIDE_INT value;
4128   long old_written = CPP_WRITTEN (pfile);
4129
4130   save_defined = install ("defined", -1, T_SPEC_DEFINED, 0, 0, -1);
4131   pfile->pcp_inside_if = 1;
4132
4133   value = cpp_parse_expr (pfile);
4134   pfile->pcp_inside_if = 0;
4135   delete_macro (save_defined);  /* clean up special symbol */
4136
4137   CPP_SET_WRITTEN (pfile, old_written); /* Pop */
4138
4139   return value;
4140 }
4141
4142 /*
4143  * routine to handle ifdef/ifndef.  Try to look up the symbol,
4144  * then do or don't skip to the #endif/#else/#elif depending
4145  * on what directive is actually being processed.
4146  */
4147
4148 static int
4149 do_xifdef (pfile, keyword, unused1, unused2)
4150      cpp_reader *pfile;
4151      struct directive *keyword;
4152      U_CHAR *unused1, *unused2;
4153 {
4154   int skip;
4155   cpp_buffer *ip = CPP_BUFFER (pfile);
4156   U_CHAR *ident;
4157   int ident_length;
4158   enum cpp_token token;
4159   int start_of_file = 0;
4160   U_CHAR *control_macro = 0;
4161   int old_written = CPP_WRITTEN (pfile);
4162
4163   /* Detect a #ifndef at start of file (not counting comments).  */
4164   if (ip->fname != 0 && keyword->type == T_IFNDEF)
4165     start_of_file = pfile->only_seen_white == 2;
4166
4167   pfile->no_macro_expand++;
4168   token = get_directive_token (pfile);
4169   pfile->no_macro_expand--;
4170
4171   ident = pfile->token_buffer + old_written;
4172   ident_length = CPP_WRITTEN (pfile) - old_written;
4173   CPP_SET_WRITTEN (pfile, old_written); /* Pop */
4174
4175   if (token == CPP_VSPACE || token == CPP_POP || token == CPP_EOF)
4176     {
4177       skip = (keyword->type == T_IFDEF);
4178       if (! CPP_TRADITIONAL (pfile))
4179         cpp_pedwarn (pfile, "`#%s' with no argument", keyword->name);
4180     }
4181   else if (token == CPP_NAME)
4182     {
4183       HASHNODE *hp = cpp_lookup (pfile, ident, ident_length, -1);
4184       skip = (hp == NULL) ^ (keyword->type == T_IFNDEF);
4185       if (start_of_file && !skip)
4186         {
4187           control_macro = (U_CHAR *) xmalloc (ident_length + 1);
4188           bcopy (ident, control_macro, ident_length + 1);
4189         }
4190     }
4191   else
4192     {
4193       skip = (keyword->type == T_IFDEF);
4194       if (! CPP_TRADITIONAL (pfile))
4195         cpp_error (pfile, "`#%s' with invalid argument", keyword->name);
4196     }
4197
4198   if (!CPP_TRADITIONAL (pfile))
4199     { int c;
4200       cpp_skip_hspace (pfile);
4201       c = PEEKC ();
4202       if (c != EOF && c != '\n')
4203         cpp_pedwarn (pfile, "garbage at end of `#%s' argument", keyword->name);
4204     }
4205   skip_rest_of_line (pfile);
4206
4207 #if 0
4208     if (pcp_outfile) {
4209       /* Output a precondition for this macro.  */
4210       if (hp && hp->value.defn->predefined)
4211         fprintf (pcp_outfile, "#define %s\n", hp->name);
4212       else {
4213         U_CHAR *cp = buf;
4214         fprintf (pcp_outfile, "#undef ");
4215         while (is_idchar[*cp]) /* Ick! */
4216           fputc (*cp++, pcp_outfile);
4217         putc ('\n', pcp_outfile);
4218       }
4219 #endif
4220
4221   conditional_skip (pfile, skip, T_IF, control_macro);
4222   return 0;
4223 }
4224
4225 /* Push TYPE on stack; then, if SKIP is nonzero, skip ahead.
4226    If this is a #ifndef starting at the beginning of a file,
4227    CONTROL_MACRO is the macro name tested by the #ifndef.
4228    Otherwise, CONTROL_MACRO is 0.  */
4229
4230 static void
4231 conditional_skip (pfile, skip, type, control_macro)
4232      cpp_reader *pfile;
4233      int skip;
4234      enum node_type type;
4235      U_CHAR *control_macro;
4236 {
4237   IF_STACK_FRAME *temp;
4238
4239   temp = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
4240   temp->fname = CPP_BUFFER (pfile)->nominal_fname;
4241 #if 0
4242   temp->lineno = CPP_BUFFER (pfile)->lineno;
4243 #endif
4244   temp->next = pfile->if_stack;
4245   temp->control_macro = control_macro;
4246   pfile->if_stack = temp;
4247
4248   pfile->if_stack->type = type;
4249
4250   if (skip != 0) {
4251     skip_if_group (pfile, 0);
4252     return;
4253   } else {
4254     ++pfile->if_stack->if_succeeded;
4255     output_line_command (pfile, 1, same_file);
4256   }
4257 }
4258
4259 /*
4260  * skip to #endif, #else, or #elif.  adjust line numbers, etc.
4261  * leaves input ptr at the sharp sign found.
4262  * If ANY is nonzero, return at next directive of any sort.
4263  */
4264
4265 static void
4266 skip_if_group (pfile, any)
4267      cpp_reader *pfile;
4268      int any;
4269 {
4270   int c;
4271   int at_beg_of_line = 1;
4272   struct directive *kt;
4273   IF_STACK_FRAME *save_if_stack = pfile->if_stack; /* don't pop past here */
4274 #if 0
4275   U_CHAR *beg_of_line = bp;
4276 #endif
4277   register int ident_length;
4278   U_CHAR *ident, *after_ident;
4279   struct parse_marker line_start_mark;
4280
4281   parse_set_mark (&line_start_mark, pfile);
4282
4283   if (CPP_OPTIONS (pfile)->output_conditionals) {
4284     static char failed[] = "#failed\n";
4285     CPP_PUTS (pfile, failed, sizeof(failed)-1);
4286     pfile->lineno++;
4287     output_line_command (pfile, 1, same_file);
4288   }
4289
4290  beg_of_line:
4291   if (CPP_OPTIONS (pfile)->output_conditionals)
4292     {
4293       cpp_buffer *pbuf = CPP_BUFFER (pfile);
4294       U_CHAR *start_line = pbuf->buf + line_start_mark.position;
4295       CPP_PUTS (pfile, start_line, pbuf->cur - start_line);
4296     }
4297   parse_move_mark (&line_start_mark, pfile);
4298   if (!CPP_TRADITIONAL (pfile))
4299       cpp_skip_hspace (pfile);
4300   c  = GETC();
4301   if (c == '#')
4302     {
4303       int old_written = CPP_WRITTEN (pfile);
4304       cpp_skip_hspace (pfile);
4305
4306       parse_name (pfile, GETC());
4307       ident_length = CPP_WRITTEN (pfile) - old_written;
4308       ident = pfile->token_buffer + old_written;
4309       pfile->limit = ident;
4310 #if 0
4311       if (ident_length == 0)
4312         goto not_a_directive;
4313
4314       /* Handle # followed by a line number.  */
4315
4316       /* Avoid error for `###' and similar cases unless -pedantic.  */
4317 #endif
4318
4319       for (kt = directive_table; kt->length >= 0; kt++)
4320         {
4321           IF_STACK_FRAME *temp;
4322           if (ident_length == kt->length
4323               && strncmp (ident, kt->name, kt->length) == 0)
4324             {
4325               /* If we are asked to return on next directive, do so now.  */
4326               if (any)
4327                 goto done;
4328
4329               switch (kt->type)
4330                 {
4331                 case T_IF:
4332                 case T_IFDEF:
4333                 case T_IFNDEF:
4334                   temp
4335                     = (IF_STACK_FRAME *) xcalloc (1, sizeof (IF_STACK_FRAME));
4336                   temp->next = pfile->if_stack;
4337                   pfile->if_stack = temp;
4338 #if 0
4339                   temp->lineno = CPP_BUFFER(pfile)->lineno;
4340 #endif
4341                   temp->fname = CPP_BUFFER(pfile)->nominal_fname;
4342                   temp->type = kt->type;
4343                   break;
4344                 case T_ELSE:
4345                 case T_ENDIF:
4346                   if (CPP_PEDANTIC (pfile) && pfile->if_stack != save_if_stack)
4347                     validate_else (pfile,
4348                                    kt->type == T_ELSE ? "#else" : "#endif");
4349                 case T_ELIF:
4350                   if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack)
4351                     {
4352                       cpp_error (pfile,
4353                                  "`#%s' not within a conditional", kt->name);
4354                       break;
4355                     }
4356                   else if (pfile->if_stack == save_if_stack)
4357                     goto done;          /* found what we came for */
4358
4359                   if (kt->type != T_ENDIF)
4360                     {
4361                       if (pfile->if_stack->type == T_ELSE)
4362                         cpp_error (pfile, "`#else' or `#elif' after `#else'");
4363                       pfile->if_stack->type = kt->type;
4364                       break;
4365                     }
4366
4367                   temp = pfile->if_stack;
4368                   pfile->if_stack = temp->next;
4369                   free (temp);
4370                   break;
4371               default: ;
4372                 }
4373               break;
4374             }
4375           /* Don't let erroneous code go by.  */
4376           if (kt->length < 0 && !CPP_OPTIONS (pfile)->lang_asm
4377               && CPP_PEDANTIC (pfile))
4378             cpp_pedwarn (pfile, "invalid preprocessor directive name");
4379         }
4380       c = GETC ();
4381     }
4382   /* We're in the middle of a line.  Skip the rest of it.  */
4383   for (;;) {
4384     switch (c)
4385       {
4386         long old;
4387       case EOF:
4388         goto done;
4389       case '/':                 /* possible comment */
4390         c = skip_comment (pfile, NULL);
4391         if (c == EOF)
4392           goto done;
4393         break;
4394       case '\"':
4395       case '\'':
4396         FORWARD(-1);
4397         old = CPP_WRITTEN (pfile);
4398         cpp_get_token (pfile);
4399         CPP_SET_WRITTEN (pfile, old);
4400         break;
4401       case '\\':
4402         /* Char after backslash loses its special meaning.  */
4403         if (PEEKC() == '\n')
4404           FORWARD (1);
4405         break;
4406       case '\n':
4407         goto beg_of_line;
4408         break;
4409       }
4410     c = GETC ();
4411   }
4412  done:
4413   if (CPP_OPTIONS (pfile)->output_conditionals) {
4414     static char end_failed[] = "#endfailed\n";
4415     CPP_PUTS (pfile, end_failed, sizeof(end_failed)-1);
4416     pfile->lineno++;
4417   }
4418   pfile->only_seen_white = 1;
4419   parse_goto_mark (&line_start_mark, pfile);
4420   parse_clear_mark (&line_start_mark);
4421 }
4422
4423 /*
4424  * handle a #else directive.  Do this by just continuing processing
4425  * without changing  if_stack ;  this is so that the error message
4426  * for missing #endif's etc. will point to the original #if.  It
4427  * is possible that something different would be better.
4428  */
4429
4430 static int
4431 do_else (pfile, keyword, buf, limit)
4432      cpp_reader *pfile;
4433      struct directive *keyword;
4434      U_CHAR *buf, *limit;
4435 {
4436   cpp_buffer *ip = CPP_BUFFER (pfile);
4437
4438   if (CPP_PEDANTIC (pfile))
4439     validate_else (pfile, "#else");
4440   skip_rest_of_line (pfile);
4441
4442   if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack) {
4443     cpp_error (pfile, "`#else' not within a conditional");
4444     return 0;
4445   } else {
4446     /* #ifndef can't have its special treatment for containing the whole file
4447        if it has a #else clause.  */
4448     pfile->if_stack->control_macro = 0;
4449
4450     if (pfile->if_stack->type != T_IF && pfile->if_stack->type != T_ELIF) {
4451       cpp_error (pfile, "`#else' after `#else'");
4452       fprintf (stderr, " (matches line %d", pfile->if_stack->lineno);
4453       if (strcmp (pfile->if_stack->fname, ip->nominal_fname) != 0)
4454         fprintf (stderr, ", file %s", pfile->if_stack->fname);
4455       fprintf (stderr, ")\n");
4456     }
4457     pfile->if_stack->type = T_ELSE;
4458   }
4459
4460   if (pfile->if_stack->if_succeeded)
4461     skip_if_group (pfile, 0);
4462   else {
4463     ++pfile->if_stack->if_succeeded;    /* continue processing input */
4464     output_line_command (pfile, 1, same_file);
4465   }
4466   return 0;
4467 }
4468
4469 /*
4470  * unstack after #endif command
4471  */
4472
4473 static int
4474 do_endif (pfile, keyword, buf, limit)
4475      cpp_reader *pfile;
4476      struct directive *keyword;
4477      U_CHAR *buf, *limit;
4478 {
4479   if (CPP_PEDANTIC (pfile))
4480     validate_else (pfile, "#endif");
4481   skip_rest_of_line (pfile);
4482
4483   if (pfile->if_stack == CPP_BUFFER (pfile)->if_stack)
4484     cpp_error (pfile, "unbalanced `#endif'");
4485   else
4486     {
4487       IF_STACK_FRAME *temp = pfile->if_stack;
4488       pfile->if_stack = temp->next;
4489       if (temp->control_macro != 0)
4490         {
4491           /* This #endif matched a #ifndef at the start of the file.
4492              See if it is at the end of the file.  */
4493           struct parse_marker start_mark;
4494           int c;
4495
4496           parse_set_mark (&start_mark, pfile);
4497
4498           for (;;)
4499             {
4500               cpp_skip_hspace (pfile);
4501               c = GETC ();
4502               if (c != '\n')
4503                 break;
4504             }
4505           parse_goto_mark (&start_mark, pfile);
4506           parse_clear_mark (&start_mark);
4507
4508           if (c == EOF)
4509             {
4510               /* If we get here, this #endif ends a #ifndef
4511                  that contains all of the file (aside from whitespace).
4512                  Arrange not to include the file again
4513                  if the macro that was tested is defined.
4514
4515                  Do not do this for the top-level file in a -include or any
4516                  file in a -imacros.  */
4517 #if 0
4518 FIXME!
4519               if (indepth != 0
4520                   && ! (indepth == 1 && pfile->no_record_file)
4521                   && ! (pfile->no_record_file && no_output))
4522 #endif
4523                 {
4524                   struct file_name_list *ifile = pfile->all_include_files;
4525                   
4526                   for ( ; ifile != NULL; ifile = ifile->next)
4527                     {
4528                       if (!strcmp (ifile->fname, CPP_BUFFER (pfile)->fname))
4529                         {
4530                           ifile->control_macro = temp->control_macro;
4531                           break;
4532                         }
4533                     }
4534                 }
4535             }
4536         }
4537       free (temp);
4538       output_line_command (pfile, 1, same_file);
4539     }
4540   return 0;
4541 }
4542
4543 /* When an #else or #endif is found while skipping failed conditional,
4544    if -pedantic was specified, this is called to warn about text after
4545    the command name.  P points to the first char after the command name.  */
4546
4547 static void
4548 validate_else (pfile, directive)
4549      cpp_reader *pfile;
4550      char *directive;
4551 {
4552   int c;
4553   cpp_skip_hspace (pfile);
4554   c = PEEKC ();
4555   if (c != EOF && c != '\n')
4556     cpp_pedwarn (pfile,
4557                  "text following `%s' violates ANSI standard", directive);
4558 }
4559
4560 /* Get the next token, and add it to the text in pfile->token_buffer.
4561    Return the kind of token we got.  */
4562   
4563 enum cpp_token
4564 cpp_get_token (pfile)
4565      cpp_reader *pfile;
4566 {
4567   register int c, c2, c3;
4568   long old_written;
4569   long start_line, start_column;
4570   enum cpp_token token;
4571   struct cpp_options *opts = CPP_OPTIONS (pfile);
4572   CPP_BUFFER (pfile)->prev = CPP_BUFFER (pfile)->cur;
4573  get_next:
4574   c = GETC();
4575   if (c == EOF)
4576     {
4577     handle_eof:
4578       if (CPP_BUFFER (pfile)->seen_eof)
4579         {
4580           if (cpp_pop_buffer (pfile) != CPP_NULL_BUFFER (pfile))
4581             goto get_next;
4582           else
4583             return CPP_EOF;
4584         }
4585       else
4586         {
4587           cpp_buffer *next_buf
4588             = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
4589           CPP_BUFFER (pfile)->seen_eof = 1;
4590           if (CPP_BUFFER (pfile)->nominal_fname
4591               && next_buf != CPP_NULL_BUFFER (pfile))
4592             {
4593               /* We're about to return from an #include file.
4594                  Emit #line information now (as part of the CPP_POP) result.
4595                  But the #line refers to the file we will pop to.  */
4596               cpp_buffer *cur_buffer = CPP_BUFFER (pfile);
4597               CPP_BUFFER (pfile) = next_buf;
4598               pfile->input_stack_listing_current = 0;
4599               output_line_command (pfile, 0, leave_file);
4600               CPP_BUFFER (pfile) = cur_buffer;
4601             }
4602           return CPP_POP;
4603         }
4604     }
4605   else
4606     {
4607       switch (c)
4608         {
4609           long newlines;
4610           struct parse_marker start_mark;
4611         case '/':
4612           if (PEEKC () == '=')
4613             goto op2;
4614           if (opts->put_out_comments)
4615             parse_set_mark (&start_mark, pfile);
4616           newlines = 0;
4617           cpp_buf_line_and_col (cpp_file_buffer (pfile),
4618                                 &start_line, &start_column);
4619           c = skip_comment (pfile, &newlines);
4620           if (opts->put_out_comments && (c == '/' || c == EOF))
4621             parse_clear_mark (&start_mark);
4622           if (c == '/')
4623             goto randomchar;
4624           if (c == EOF)
4625             {
4626               cpp_error_with_line (pfile, start_line, start_column,
4627                                    "unterminated comment");
4628               goto handle_eof;
4629             }
4630           c = '/';  /* Initial letter of comment.  */
4631         return_comment:
4632           /* Comments are equivalent to spaces.
4633              For -traditional, a comment is equivalent to nothing.  */
4634           if (opts->put_out_comments)
4635             {
4636               cpp_buffer *pbuf = CPP_BUFFER (pfile);
4637               long dummy;
4638               U_CHAR *start = pbuf->buf + start_mark.position;
4639               int len = pbuf->cur - start;
4640               CPP_RESERVE(pfile, 1 + len);
4641               CPP_PUTC_Q (pfile, c);
4642               CPP_PUTS_Q (pfile, start, len);
4643               pfile->lineno += newlines;
4644               parse_clear_mark (&start_mark);
4645               return CPP_COMMENT;
4646             }
4647           else if (CPP_TRADITIONAL (pfile))
4648             {
4649               return CPP_COMMENT;
4650             }
4651           else
4652             {
4653 #if 0
4654               /* This may not work if cpp_get_token is called recursively,
4655                  since many places look for horizontal space.  */
4656               if (newlines)
4657                 {
4658                   /* Copy the newlines into the output buffer, in order to
4659                      avoid the pain of a #line every time a multiline comment
4660                      is seen.  */
4661                   CPP_RESERVE(pfile, newlines);
4662                   while (--newlines >= 0)
4663                     {
4664                       CPP_PUTC_Q (pfile, '\n');
4665                       pfile->lineno++;
4666                     }
4667                   return CPP_VSPACE;
4668                 }
4669 #endif
4670               CPP_RESERVE(pfile, 1);
4671               CPP_PUTC_Q (pfile, ' ');
4672               return CPP_HSPACE;
4673             }
4674 #if 0
4675           if (opts->for_lint) {
4676             U_CHAR *argbp;
4677             int cmdlen, arglen;
4678             char *lintcmd = get_lintcmd (ibp, limit, &argbp, &arglen, &cmdlen);
4679             
4680             if (lintcmd != NULL) {
4681               /* I believe it is always safe to emit this newline: */
4682               obp[-1] = '\n';
4683               bcopy ("#pragma lint ", (char *) obp, 13);
4684               obp += 13;
4685               bcopy (lintcmd, (char *) obp, cmdlen);
4686               obp += cmdlen;
4687
4688               if (arglen != 0) {
4689                 *(obp++) = ' ';
4690                 bcopy (argbp, (char *) obp, arglen);
4691                 obp += arglen;
4692               }
4693
4694               /* OK, now bring us back to the state we were in before we entered
4695                  this branch.  We need #line b/c the newline for the pragma
4696                  could fuck things up.  */
4697               output_line_command (pfile, 0, same_file);
4698               *(obp++) = ' ';   /* just in case, if comments are copied thru */
4699               *(obp++) = '/';
4700             }
4701           }
4702 #endif
4703
4704         case '#':
4705 #if 0
4706           /* If this is expanding a macro definition, don't recognize
4707              preprocessor directives.  */
4708           if (ip->macro != 0)
4709             goto randomchar;
4710           /* If this is expand_into_temp_buffer, recognize them
4711              only after an actual newline at this level,
4712              not at the beginning of the input level.  */
4713           if (ip->fname == 0 && beg_of_line == ip->buf)
4714             goto randomchar;
4715           if (ident_length)
4716             goto specialchar;
4717 #endif
4718
4719           if (!pfile->only_seen_white)
4720             goto randomchar;
4721           if (handle_directive (pfile))
4722             return CPP_DIRECTIVE;
4723           pfile->only_seen_white = 0;
4724           return CPP_OTHER;
4725
4726         case '\"':
4727         case '\'':
4728           /* A single quoted string is treated like a double -- some
4729              programs (e.g., troff) are perverse this way */
4730           cpp_buf_line_and_col (cpp_file_buffer (pfile),
4731                                 &start_line, &start_column);
4732           old_written = CPP_WRITTEN (pfile);
4733         string:
4734           CPP_PUTC (pfile, c);
4735           while (1)
4736             {
4737               int cc = GETC();
4738               if (cc == EOF)
4739                 {
4740                   if (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
4741                     {
4742                       /* try harder: this string crosses a macro expansion
4743                          boundary.  This can happen naturally if -traditional.
4744                          Otherwise, only -D can make a macro with an unmatched
4745                          quote.  */
4746                         cpp_buffer *next_buf
4747                             = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
4748                         (*CPP_BUFFER (pfile)->cleanup)
4749                             (CPP_BUFFER (pfile), pfile);
4750                         CPP_BUFFER (pfile) = next_buf;
4751                         continue;
4752                     }
4753                   if (!CPP_TRADITIONAL (pfile))
4754                     {
4755                       cpp_error_with_line (pfile, start_line, start_column,
4756                               "unterminated string or character constant");
4757                       if (pfile->multiline_string_line != start_line
4758                           && pfile->multiline_string_line != 0)
4759                         cpp_error_with_line (pfile,
4760                                              pfile->multiline_string_line, -1,
4761                                "possible real start of unterminated constant");
4762                       pfile->multiline_string_line = 0;
4763                     }
4764                   break;
4765                 }
4766               CPP_PUTC (pfile, cc);
4767               switch (cc)
4768                 {
4769                 case '\n':
4770                   /* Traditionally, end of line ends a string constant with
4771                  no error.  So exit the loop and record the new line.  */
4772                   if (CPP_TRADITIONAL (pfile))
4773                     goto while2end;
4774                   if (c == '\'')
4775                     {
4776                       cpp_error_with_line (pfile, start_line, start_column,
4777                                            "unterminated character constant");
4778                       goto while2end;
4779                     }
4780                   if (CPP_PEDANTIC (pfile)
4781                       && pfile->multiline_string_line == 0)
4782                     {
4783                       cpp_pedwarn_with_line (pfile, start_line, start_column,
4784                                "string constant runs past end of line");
4785                     }
4786                   if (pfile->multiline_string_line == 0)
4787                     pfile->multiline_string_line = start_line;
4788                   break;
4789                 
4790                 case '\\':
4791                   cc = GETC();
4792                   if (cc == '\n')
4793                     {
4794                       /* Backslash newline is replaced by nothing at all.  */
4795                       CPP_ADJUST_WRITTEN (pfile, -1);
4796                       pfile->lineno++;
4797                     }
4798                   else
4799                     {
4800                       /* ANSI stupidly requires that in \\ the second \
4801                          is *not* prevented from combining with a newline.  */
4802                       NEWLINE_FIX1(cc);
4803                       if (cc != EOF)
4804                         CPP_PUTC (pfile, cc);
4805                     }
4806                   break;
4807
4808                 case '\"':
4809                 case '\'':
4810                   if (cc == c)
4811                     goto while2end;
4812                   break;
4813                 }
4814             }
4815         while2end:
4816           pfile->lineno += count_newlines (pfile->token_buffer + old_written,
4817                                            CPP_PWRITTEN (pfile));
4818           pfile->only_seen_white = 0;
4819           return c == '\'' ? CPP_CHAR : CPP_STRING;
4820
4821         case '$':
4822           if (!opts->dollars_in_ident)
4823             goto randomchar;
4824           goto letter;
4825
4826         case ':':
4827           if (opts->cplusplus && PEEKC () == ':')
4828             goto op2;
4829           goto randomchar;
4830
4831         case '&':
4832         case '+':
4833         case '|':
4834           NEWLINE_FIX;
4835           c2 = PEEKC ();
4836           if (c2 == c || c2 == '=')
4837             goto op2;
4838           goto randomchar;
4839
4840         case '*':
4841         case '!':
4842         case '%':
4843         case '=':
4844         case '^':
4845           NEWLINE_FIX;
4846           if (PEEKC () == '=')
4847             goto op2;
4848           goto randomchar;
4849
4850         case '-':
4851           NEWLINE_FIX;
4852           c2 = PEEKC ();
4853           if (c2 == '-' && opts->chill)
4854             {
4855               /* Chill style comment */
4856               if (opts->put_out_comments)
4857                 parse_set_mark (&start_mark, pfile);
4858               FORWARD(1);  /* Skip second '-'.  */
4859               for (;;)
4860                 {
4861                   c = GETC ();
4862                   if (c == EOF)
4863                     break;
4864                   if (c == '\n')
4865                     {
4866                       /* Don't consider final '\n' to be part of comment.  */
4867                       FORWARD(-1);
4868                       break;
4869                     }
4870                 }
4871               c = '-';
4872               goto return_comment;
4873             }
4874           if (c2 == '-' || c2 == '=' || c2 == '>')
4875             goto op2;
4876           goto randomchar;
4877
4878         case '<':
4879           if (pfile->parsing_include_directive)
4880             {
4881               for (;;)
4882                 {
4883                   CPP_PUTC (pfile, c);
4884                   if (c == '>')
4885                     break;
4886                   c = GETC ();
4887                   NEWLINE_FIX1 (c);
4888                   if (c == '\n' || c == EOF)
4889                     {
4890                       cpp_error (pfile,
4891                                  "missing '>' in `#include <FILENAME>'");
4892                       break;
4893                     }
4894                 }
4895               return CPP_STRING;
4896             }
4897           /* else fall through */
4898         case '>':
4899           NEWLINE_FIX;
4900           c2 = PEEKC ();
4901           if (c2 == '=')
4902             goto op2;
4903           if (c2 != c)
4904             goto randomchar;
4905           FORWARD(1);
4906           CPP_RESERVE (pfile, 4);
4907           CPP_PUTC (pfile, c);
4908           CPP_PUTC (pfile, c2);
4909           NEWLINE_FIX;
4910           c3 = PEEKC ();
4911           if (c3 == '=')
4912             CPP_PUTC_Q (pfile, GETC ());
4913           CPP_NUL_TERMINATE_Q (pfile);
4914           pfile->only_seen_white = 0;
4915           return CPP_OTHER;
4916
4917         case '@':
4918           if (CPP_BUFFER (pfile)->has_escapes)
4919             {
4920               c = GETC ();
4921               if (c == '-')
4922                 {
4923                   if (pfile->output_escapes)
4924                     CPP_PUTS (pfile, "@-", 2);
4925                   parse_name (pfile, GETC ());
4926                   return CPP_NAME;
4927                 }
4928               else if (is_space [c])
4929                 {
4930                   CPP_RESERVE (pfile, 2);
4931                   if (pfile->output_escapes)
4932                     CPP_PUTC_Q (pfile, '@');
4933                   CPP_PUTC_Q (pfile, c);
4934                   return CPP_HSPACE;
4935                 }
4936             }
4937           if (pfile->output_escapes)
4938             {
4939               CPP_PUTS (pfile, "@@", 2);
4940               return CPP_OTHER;
4941             }
4942           goto randomchar;
4943
4944         case '.':
4945           NEWLINE_FIX;
4946           c2 = PEEKC ();
4947           if (isdigit(c2))
4948             {
4949               CPP_RESERVE(pfile, 2);
4950               CPP_PUTC_Q (pfile, '.');
4951               c = GETC ();
4952               goto number;
4953             }
4954           /* FIXME - misses the case "..\\\n." */
4955           if (c2 == '.' && PEEKN(1) == '.')
4956             {
4957               CPP_RESERVE(pfile, 4);
4958               CPP_PUTC_Q (pfile, '.');
4959               CPP_PUTC_Q (pfile, '.');
4960               CPP_PUTC_Q (pfile, '.');
4961               FORWARD (2);
4962               CPP_NUL_TERMINATE_Q (pfile);
4963               pfile->only_seen_white = 0;
4964               return CPP_3DOTS;
4965             }
4966           goto randomchar;
4967
4968         op2:
4969           token = CPP_OTHER;
4970           pfile->only_seen_white = 0;
4971         op2any:
4972           CPP_RESERVE(pfile, 3);
4973           CPP_PUTC_Q (pfile, c);
4974           CPP_PUTC_Q (pfile, GETC ());
4975           CPP_NUL_TERMINATE_Q (pfile);
4976           return token;
4977
4978         case 'L':
4979           NEWLINE_FIX;
4980           c2 = PEEKC ();
4981           if ((c2 == '\'' || c2 == '\"') && !CPP_TRADITIONAL (pfile))
4982             {
4983               CPP_PUTC (pfile, c);
4984               c = GETC ();
4985               goto string;
4986             }
4987           goto letter;
4988
4989         case '0': case '1': case '2': case '3': case '4':
4990         case '5': case '6': case '7': case '8': case '9':
4991         number:
4992           c2  = '.';
4993           for (;;)
4994             {
4995               CPP_RESERVE (pfile, 2);
4996               CPP_PUTC_Q (pfile, c);
4997               NEWLINE_FIX;
4998               c = PEEKC ();
4999               if (c == EOF)
5000                 break;
5001               if (!is_idchar[c] && c != '.'
5002                   && ((c2 != 'e' && c2 != 'E'
5003                        && ((c2 != 'p' && c2 != 'P') || CPP_C89 (pfile)))
5004                       || (c != '+' && c != '-')))
5005                 break;
5006               FORWARD(1);
5007               c2= c;
5008             }
5009           CPP_NUL_TERMINATE_Q (pfile);
5010           pfile->only_seen_white = 0;
5011           return CPP_NUMBER;
5012         case 'b': case 'c': case 'd': case 'h': case 'o':
5013         case 'B': case 'C': case 'D': case 'H': case 'O':
5014           if (opts->chill && PEEKC () == '\'')
5015             {
5016               pfile->only_seen_white = 0;
5017               CPP_RESERVE (pfile, 2);
5018               CPP_PUTC_Q (pfile, c);
5019               CPP_PUTC_Q (pfile, '\'');
5020               FORWARD(1);
5021               for (;;)
5022                 {
5023                   c = GETC();
5024                   if (c == EOF)
5025                     goto chill_number_eof;
5026                   if (!is_idchar[c])
5027                     {
5028                       if (c == '\\' && PEEKC() == '\n')
5029                         {
5030                           FORWARD(2);
5031                           continue;
5032                         }
5033                       break;
5034                     }
5035                   CPP_PUTC (pfile, c);
5036                 }
5037               if (c == '\'')
5038                 {
5039                   CPP_RESERVE (pfile, 2);
5040                   CPP_PUTC_Q (pfile, c);
5041                   CPP_NUL_TERMINATE_Q (pfile);
5042                   return CPP_STRING;
5043                 }
5044               else
5045                 {
5046                   FORWARD(-1);
5047                 chill_number_eof:
5048                   CPP_NUL_TERMINATE (pfile);
5049                   return CPP_NUMBER;
5050                 }
5051             }
5052           else
5053             goto letter;
5054         case '_':
5055         case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
5056         case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
5057         case 'r': case 's': case 't': case 'u': case 'v': case 'w':
5058         case 'x': case 'y': case 'z':
5059         case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
5060         case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
5061         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
5062         case 'Y': case 'Z':
5063         letter:
5064           {
5065             HASHNODE *hp;
5066             unsigned char *ident;
5067             int before_name_written = CPP_WRITTEN (pfile);
5068             int ident_len;
5069             parse_name (pfile, c);
5070             pfile->only_seen_white = 0;
5071             if (pfile->no_macro_expand)
5072               return CPP_NAME;
5073             ident = pfile->token_buffer + before_name_written;
5074             ident_len = CPP_PWRITTEN (pfile) - ident;
5075             hp = cpp_lookup (pfile, ident, ident_len, -1);
5076             if (!hp)
5077               return CPP_NAME;
5078             if (hp->type == T_DISABLED)
5079               {
5080                 if (pfile->output_escapes)
5081                   { /* Return "@-IDENT", followed by '\0'.  */
5082                     int i;
5083                     CPP_RESERVE (pfile, 3);
5084                     ident = pfile->token_buffer + before_name_written;
5085                     CPP_ADJUST_WRITTEN (pfile, 2);
5086                     for (i = ident_len; i >= 0; i--) ident[i+2] = ident[i];
5087                     ident[0] = '@';
5088                     ident[1] = '-';
5089                   }
5090                 return CPP_NAME;
5091               }
5092
5093             /* If macro wants an arglist, verify that a '(' follows.
5094                first skip all whitespace, copying it to the output
5095                after the macro name.  Then, if there is no '(',
5096                decide this is not a macro call and leave things that way.  */
5097             if (hp->type == T_MACRO && hp->value.defn->nargs >= 0)
5098             {
5099               struct parse_marker macro_mark;
5100               int is_macro_call;
5101               while (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
5102                 {
5103                   cpp_buffer *next_buf;
5104                   cpp_skip_hspace (pfile);
5105                   if (PEEKC () != EOF)
5106                     break;
5107                   next_buf = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
5108                   (*CPP_BUFFER (pfile)->cleanup) (CPP_BUFFER (pfile), pfile);
5109                   CPP_BUFFER (pfile) = next_buf;
5110                 }
5111               parse_set_mark (&macro_mark, pfile);
5112               for (;;)
5113                 {
5114                   cpp_skip_hspace (pfile);
5115                   c = PEEKC ();
5116                   is_macro_call = c == '(';
5117                   if (c != '\n')
5118                     break;
5119                   FORWARD (1);
5120                 }
5121               if (!is_macro_call)
5122                 parse_goto_mark (&macro_mark, pfile);
5123               parse_clear_mark (&macro_mark);
5124               if (!is_macro_call)
5125                 return CPP_NAME;
5126             }
5127             /* This is now known to be a macro call.  */
5128
5129             /* it might not actually be a macro.  */
5130             if (hp->type != T_MACRO) {
5131               int xbuf_len;  U_CHAR *xbuf;
5132               CPP_SET_WRITTEN (pfile, before_name_written);
5133               special_symbol (hp, pfile);
5134               xbuf_len = CPP_WRITTEN (pfile) - before_name_written;
5135               xbuf = (U_CHAR *) xmalloc (xbuf_len + 1);
5136               CPP_SET_WRITTEN (pfile, before_name_written);
5137               bcopy (CPP_PWRITTEN (pfile), xbuf, xbuf_len + 1);
5138               push_macro_expansion (pfile, xbuf, xbuf_len, hp);
5139             }
5140             else
5141               {
5142                 /* Expand the macro, reading arguments as needed,
5143                    and push the expansion on the input stack.  */
5144                 macroexpand (pfile, hp);
5145                 CPP_SET_WRITTEN (pfile, before_name_written);
5146               }
5147
5148             /* An extra "@ " is added to the end of a macro expansion
5149                to prevent accidental token pasting.  We prefer to avoid
5150                unneeded extra spaces (for the sake of cpp-using tools like
5151                imake).  Here we remove the space if it is safe to do so.  */
5152             if (pfile->buffer->rlimit - pfile->buffer->cur >= 3
5153                 && pfile->buffer->rlimit[-2] == '@'
5154                 && pfile->buffer->rlimit[-1] == ' ')
5155               {
5156                 int c1 = pfile->buffer->rlimit[-3];
5157                 int c2 = CPP_BUF_PEEK (CPP_PREV_BUFFER (CPP_BUFFER (pfile)));
5158                 if (c2 == EOF || ! unsafe_chars (c1, c2))
5159                   pfile->buffer->rlimit -= 2;
5160               }
5161           }
5162           goto get_next;
5163
5164         case ' ':  case '\t':  case '\v':  case '\r':
5165           for (;;)
5166             {
5167               CPP_PUTC (pfile, c);
5168               c = PEEKC ();
5169               if (c == EOF || !is_hor_space[c])
5170                 break;
5171               FORWARD(1);
5172             }
5173           return CPP_HSPACE;
5174
5175         case '\\':
5176           c2 = PEEKC ();
5177           if (c2 != '\n')
5178             goto randomchar;
5179           token = CPP_HSPACE;
5180           goto op2any;
5181
5182         case '\n':
5183           CPP_PUTC (pfile, c);
5184           if (pfile->only_seen_white == 0)
5185             pfile->only_seen_white = 1;
5186           pfile->lineno++;
5187           output_line_command (pfile, 1, same_file);
5188           return CPP_VSPACE;
5189
5190         case '(': token = CPP_LPAREN;    goto char1;
5191         case ')': token = CPP_RPAREN;    goto char1;
5192         case '{': token = CPP_LBRACE;    goto char1;
5193         case '}': token = CPP_RBRACE;    goto char1;
5194         case ',': token = CPP_COMMA;     goto char1;
5195         case ';': token = CPP_SEMICOLON; goto char1;
5196
5197         randomchar:
5198         default:
5199           token = CPP_OTHER;
5200         char1:
5201           pfile->only_seen_white = 0;
5202           CPP_PUTC (pfile, c);
5203           return token;
5204         }
5205     }
5206 }
5207
5208 /* Like cpp_get_token, but skip spaces and comments.  */
5209
5210 enum cpp_token
5211 cpp_get_non_space_token (pfile)
5212      cpp_reader *pfile;
5213 {
5214   int old_written = CPP_WRITTEN (pfile);
5215   for (;;)
5216     {
5217       enum cpp_token token = cpp_get_token (pfile);
5218       if (token != CPP_COMMENT && token != CPP_POP
5219           && token != CPP_HSPACE && token != CPP_VSPACE)
5220         return token;
5221       CPP_SET_WRITTEN (pfile, old_written);
5222     }
5223 }
5224
5225 /* Parse an identifier starting with C.  */
5226
5227 int
5228 parse_name (pfile, c)
5229      cpp_reader *pfile; int c;
5230 {
5231   for (;;)
5232   {
5233       if (! is_idchar[c])
5234       {
5235           if (c == '\\' && PEEKC() == '\n')
5236           {
5237               FORWARD(2);
5238               continue;
5239           }
5240           FORWARD (-1);
5241           break;
5242       }
5243
5244       if (c == '$' && CPP_PEDANTIC (pfile))
5245         cpp_pedwarn ("`$' in identifier");
5246
5247       CPP_RESERVE(pfile, 2); /* One more for final NUL.  */
5248       CPP_PUTC_Q (pfile, c);
5249       c = GETC();
5250       if (c == EOF)
5251         break;
5252   }
5253   CPP_NUL_TERMINATE_Q (pfile);
5254   return 1;
5255 }
5256
5257 \f
5258 /* Maintain and search list of included files, for #import.  */
5259
5260 /* Hash a file name for import_hash_table.  */
5261
5262 static int 
5263 import_hash (f)
5264      char *f;
5265 {
5266   int val = 0;
5267
5268   while (*f) val += *f++;
5269   return (val%IMPORT_HASH_SIZE);
5270 }
5271
5272 /* Search for file FILENAME in import_hash_table.
5273    Return -2 if found, either a matching name or a matching inode.
5274    Otherwise, open the file and return a file descriptor if successful
5275    or -1 if unsuccessful.  */
5276
5277 static int
5278 lookup_import (pfile, filename, searchptr)
5279      cpp_reader *pfile;
5280      char *filename;
5281      struct file_name_list *searchptr;
5282 {
5283   struct import_file *i;
5284   int h;
5285   int hashval;
5286   struct stat sb;
5287   int fd;
5288
5289   hashval = import_hash (filename);
5290
5291   /* Attempt to find file in list of already included files */
5292   i = pfile->import_hash_table[hashval];
5293
5294   while (i) {
5295     if (!strcmp (filename, i->name))
5296       return -2;                /* return found */
5297     i = i->next;
5298   }
5299   /* Open it and try a match on inode/dev */
5300   fd = open_include_file (pfile, filename, searchptr);
5301   if (fd < 0)
5302     return fd;
5303   fstat (fd, &sb);
5304   for (h = 0; h < IMPORT_HASH_SIZE; h++) {
5305     i = pfile->import_hash_table[h];
5306     while (i) {
5307       /* Compare the inode and the device.
5308          Supposedly on some systems the inode is not a scalar.  */
5309       if (!bcmp ((char *) &i->inode, (char *) &sb.st_ino, sizeof (sb.st_ino))
5310           && i->dev == sb.st_dev) {
5311         close (fd);
5312         return -2;              /* return found */
5313       }
5314       i = i->next;
5315     }
5316   }
5317   return fd;                    /* Not found, return open file */
5318 }
5319
5320 /* Add the file FNAME, open on descriptor FD, to import_hash_table.  */
5321
5322 static void
5323 add_import (pfile, fd, fname)
5324      cpp_reader *pfile;
5325      int fd;
5326      char *fname;
5327 {
5328   struct import_file *i;
5329   int hashval;
5330   struct stat sb;
5331
5332   hashval = import_hash (fname);
5333   fstat (fd, &sb);
5334   i = (struct import_file *)xmalloc (sizeof (struct import_file));
5335   i->name = (char *)xmalloc (strlen (fname)+1);
5336   strcpy (i->name, fname);
5337   bcopy ((char *) &sb.st_ino, (char *) &i->inode, sizeof (sb.st_ino));
5338   i->dev = sb.st_dev;
5339   i->next = pfile->import_hash_table[hashval];
5340   pfile->import_hash_table[hashval] = i;
5341 }
5342 \f
5343 /* The file_name_map structure holds a mapping of file names for a
5344    particular directory.  This mapping is read from the file named
5345    FILE_NAME_MAP_FILE in that directory.  Such a file can be used to
5346    map filenames on a file system with severe filename restrictions,
5347    such as DOS.  The format of the file name map file is just a series
5348    of lines with two tokens on each line.  The first token is the name
5349    to map, and the second token is the actual name to use.  */
5350
5351 struct file_name_map
5352 {
5353   struct file_name_map *map_next;
5354   char *map_from;
5355   char *map_to;
5356 };
5357
5358 #define FILE_NAME_MAP_FILE "header.gcc"
5359
5360 /* Read a space delimited string of unlimited length from a stdio
5361    file.  */
5362
5363 static char *
5364 read_filename_string (ch, f)
5365      int ch;
5366      FILE *f;
5367 {
5368   char *alloc, *set;
5369   int len;
5370
5371   len = 20;
5372   set = alloc = xmalloc (len + 1);
5373   if (! is_space[ch])
5374     {
5375       *set++ = ch;
5376       while ((ch = getc (f)) != EOF && ! is_space[ch])
5377         {
5378           if (set - alloc == len)
5379             {
5380               len *= 2;
5381               alloc = xrealloc (alloc, len + 1);
5382               set = alloc + len / 2;
5383             }
5384           *set++ = ch;
5385         }
5386     }
5387   *set = '\0';
5388   ungetc (ch, f);
5389   return alloc;
5390 }
5391
5392 /* This structure holds a linked list of file name maps, one per directory.  */
5393
5394 struct file_name_map_list
5395 {
5396   struct file_name_map_list *map_list_next;
5397   char *map_list_name;
5398   struct file_name_map *map_list_map;
5399 };
5400
5401 /* Read the file name map file for DIRNAME.  */
5402
5403 static struct file_name_map *
5404 read_name_map (pfile, dirname)
5405      cpp_reader *pfile;
5406      char *dirname;
5407 {
5408   register struct file_name_map_list *map_list_ptr;
5409   char *name;
5410   FILE *f;
5411
5412   for (map_list_ptr = CPP_OPTIONS (pfile)->map_list; map_list_ptr;
5413        map_list_ptr = map_list_ptr->map_list_next)
5414     if (! strcmp (map_list_ptr->map_list_name, dirname))
5415       return map_list_ptr->map_list_map;
5416
5417   map_list_ptr = ((struct file_name_map_list *)
5418                   xmalloc (sizeof (struct file_name_map_list)));
5419   map_list_ptr->map_list_name = savestring (dirname);
5420   map_list_ptr->map_list_map = NULL;
5421
5422   name = (char *) alloca (strlen (dirname) + strlen (FILE_NAME_MAP_FILE) + 2);
5423   strcpy (name, dirname);
5424   if (*dirname)
5425     strcat (name, "/");
5426   strcat (name, FILE_NAME_MAP_FILE);
5427   f = fopen (name, "r");
5428   if (!f)
5429     map_list_ptr->map_list_map = NULL;
5430   else
5431     {
5432       int ch;
5433       int dirlen = strlen (dirname);
5434
5435       while ((ch = getc (f)) != EOF)
5436         {
5437           char *from, *to;
5438           struct file_name_map *ptr;
5439
5440           if (is_space[ch])
5441             continue;
5442           from = read_filename_string (ch, f);
5443           while ((ch = getc (f)) != EOF && is_hor_space[ch])
5444             ;
5445           to = read_filename_string (ch, f);
5446
5447           ptr = ((struct file_name_map *)
5448                  xmalloc (sizeof (struct file_name_map)));
5449           ptr->map_from = from;
5450
5451           /* Make the real filename absolute.  */
5452           if (*to == '/')
5453             ptr->map_to = to;
5454           else
5455             {
5456               ptr->map_to = xmalloc (dirlen + strlen (to) + 2);
5457               strcpy (ptr->map_to, dirname);
5458               ptr->map_to[dirlen] = '/';
5459               strcpy (ptr->map_to + dirlen + 1, to);
5460               free (to);
5461             }         
5462
5463           ptr->map_next = map_list_ptr->map_list_map;
5464           map_list_ptr->map_list_map = ptr;
5465
5466           while ((ch = getc (f)) != '\n')
5467             if (ch == EOF)
5468               break;
5469         }
5470       fclose (f);
5471     }
5472   
5473   map_list_ptr->map_list_next = CPP_OPTIONS (pfile)->map_list;
5474   CPP_OPTIONS (pfile)->map_list = map_list_ptr;
5475
5476   return map_list_ptr->map_list_map;
5477 }  
5478
5479 /* Try to open include file FILENAME.  SEARCHPTR is the directory
5480    being tried from the include file search path.  This function maps
5481    filenames on file systems based on information read by
5482    read_name_map.  */
5483
5484 static int
5485 open_include_file (pfile, filename, searchptr)
5486      cpp_reader *pfile;
5487      char *filename;
5488      struct file_name_list *searchptr;
5489 {
5490   register struct file_name_map *map;
5491   register char *from;
5492   char *p, *dir;
5493
5494   if (searchptr && ! searchptr->got_name_map)
5495     {
5496       searchptr->name_map = read_name_map (pfile,
5497                                            searchptr->fname
5498                                            ? searchptr->fname : ".");
5499       searchptr->got_name_map = 1;
5500     }
5501
5502   /* First check the mapping for the directory we are using.  */
5503   if (searchptr && searchptr->name_map)
5504     {
5505       from = filename;
5506       if (searchptr->fname)
5507         from += strlen (searchptr->fname) + 1;
5508       for (map = searchptr->name_map; map; map = map->map_next)
5509         {
5510           if (! strcmp (map->map_from, from))
5511             {
5512               /* Found a match.  */
5513               return open (map->map_to, O_RDONLY, 0666);
5514             }
5515         }
5516     }
5517
5518   /* Try to find a mapping file for the particular directory we are
5519      looking in.  Thus #include <sys/types.h> will look up sys/types.h
5520      in /usr/include/header.gcc and look up types.h in
5521      /usr/include/sys/header.gcc.  */
5522   p = rindex (filename, '/');
5523   if (! p)
5524     p = filename;
5525   if (searchptr
5526       && searchptr->fname
5527       && strlen (searchptr->fname) == p - filename
5528       && ! strncmp (searchptr->fname, filename, p - filename))
5529     {
5530       /* FILENAME is in SEARCHPTR, which we've already checked.  */
5531       return open (filename, O_RDONLY, 0666);
5532     }
5533
5534   if (p == filename)
5535     {
5536       dir = ".";
5537       from = filename;
5538     }
5539   else
5540     {
5541       dir = (char *) alloca (p - filename + 1);
5542       bcopy (filename, dir, p - filename);
5543       dir[p - filename] = '\0';
5544       from = p + 1;
5545     }
5546   for (map = read_name_map (pfile, dir); map; map = map->map_next)
5547     if (! strcmp (map->map_from, from))
5548       return open (map->map_to, O_RDONLY, 0666);
5549
5550   return open (filename, O_RDONLY, 0666);
5551 }
5552
5553 /* Process the contents of include file FNAME, already open on descriptor F,
5554    with output to OP.
5555    SYSTEM_HEADER_P is 1 if this file resides in any one of the known
5556    "system" include directories (as decided by the `is_system_include'
5557    function above).
5558    DIRPTR is the link in the dir path through which this file was found,
5559    or 0 if the file name was absolute or via the current directory.
5560    Return 1 on success, 0 on failure.
5561
5562    The caller is responsible for the cpp_push_buffer.  */
5563
5564 static int
5565 finclude (pfile, f, fname, system_header_p, dirptr)
5566      cpp_reader *pfile;
5567      int f;
5568      char *fname;
5569      int system_header_p;
5570      struct file_name_list *dirptr;
5571 {
5572   int st_mode;
5573   long st_size;
5574   long i;
5575   int length;
5576   cpp_buffer *fp;                       /* For input stack frame */
5577   int missing_newline = 0;
5578
5579   if (file_size_and_mode (f, &st_mode, &st_size) < 0)
5580     {
5581       cpp_perror_with_name (pfile, fname);
5582       close (f);
5583       cpp_pop_buffer (pfile);
5584       return 0;
5585     }
5586
5587   fp = CPP_BUFFER (pfile);
5588   fp->nominal_fname = fp->fname = fname;
5589 #if 0
5590   fp->length = 0;
5591 #endif
5592   fp->dir = dirptr;
5593   fp->system_header_p = system_header_p;
5594   fp->lineno = 1;
5595   fp->colno = 1;
5596   fp->cleanup = file_cleanup;
5597
5598   if (S_ISREG (st_mode)) {
5599     fp->buf = (U_CHAR *) xmalloc (st_size + 2);
5600     fp->alimit = fp->buf + st_size + 2;
5601     fp->cur = fp->buf;
5602
5603     /* Read the file contents, knowing that st_size is an upper bound
5604        on the number of bytes we can read.  */
5605     length = safe_read (f, fp->buf, st_size);
5606     fp->rlimit = fp->buf + length;
5607     if (length < 0) goto nope;
5608   }
5609   else if (S_ISDIR (st_mode)) {
5610     cpp_error (pfile, "directory `%s' specified in #include", fname);
5611     close (f);
5612     return 0;
5613   } else {
5614     /* Cannot count its file size before reading.
5615        First read the entire file into heap and
5616        copy them into buffer on stack.  */
5617
5618     int bsize = 2000;
5619
5620     st_size = 0;
5621     fp->buf = (U_CHAR *) xmalloc (bsize + 2);
5622
5623     for (;;) {
5624       i = safe_read (f, fp->buf + st_size, bsize - st_size);
5625       if (i < 0)
5626         goto nope;      /* error! */
5627       st_size += i;
5628       if (st_size != bsize)
5629         break;  /* End of file */
5630       bsize *= 2;
5631       fp->buf = (U_CHAR *) xrealloc (fp->buf, bsize + 2);
5632     }
5633     fp->cur = fp->buf;
5634     length = st_size;
5635   }
5636
5637   if ((length > 0 && fp->buf[length - 1] != '\n')
5638       /* Backslash-newline at end is not good enough.  */
5639       || (length > 1 && fp->buf[length - 2] == '\\')) {
5640     fp->buf[length++] = '\n';
5641 #if 0
5642     missing_newline = 1;
5643 #endif
5644   }
5645   fp->buf[length] = '\0';
5646   fp->rlimit = fp->buf + length;
5647
5648   /* Close descriptor now, so nesting does not use lots of descriptors.  */
5649   close (f);
5650
5651   /* Must do this before calling trigraph_pcp, so that the correct file name
5652      will be printed in warning messages.  */
5653
5654   pfile->input_stack_listing_current = 0;
5655
5656 #if 0
5657   if (!no_trigraphs)
5658     trigraph_pcp (fp);
5659 #endif
5660
5661 #if 0
5662   rescan (op, 0);
5663
5664   if (missing_newline)
5665     fp->lineno--;
5666
5667   if (CPP_PEDANTIC (pfile) && missing_newline)
5668     pedwarn ("file does not end in newline");
5669
5670   indepth--;
5671   input_file_stack_tick++;
5672   free (fp->buf);
5673 #endif
5674   return 1;
5675
5676  nope:
5677
5678   cpp_perror_with_name (pfile, fname);
5679   close (f);
5680   free (fp->buf);
5681   return 1;
5682 }
5683
5684 /* This is called after options have been processed.
5685  * Check options for consistency, and setup for processing input
5686  * from the file named FNAME.  (Use standard input if FNAME==NULL.)
5687  * Return 1 on succes, 0 on failure.
5688  */
5689
5690 int
5691 cpp_start_read (pfile, fname)
5692      cpp_reader *pfile;
5693      char *fname;
5694 {
5695   struct cpp_options *opts = CPP_OPTIONS (pfile);
5696   struct cpp_pending *pend;
5697   char *p;
5698   int f;
5699   cpp_buffer *fp;
5700
5701   /* The code looks at the defaults through this pointer, rather than through
5702      the constant structure above.  This pointer gets changed if an environment
5703      variable specifies other defaults.  */
5704   struct default_include *include_defaults = include_defaults_array;
5705
5706   /* Add dirs from CPATH after dirs from -I.  */
5707   /* There seems to be confusion about what CPATH should do,
5708      so for the moment it is not documented.  */
5709   /* Some people say that CPATH should replace the standard include dirs,
5710      but that seems pointless: it comes before them, so it overrides them
5711      anyway.  */
5712   p = (char *) getenv ("CPATH");
5713   if (p != 0 && ! opts->no_standard_includes)
5714     path_include (pfile, p);
5715
5716   /* Now that dollars_in_ident is known, initialize is_idchar.  */
5717   initialize_char_syntax (opts);
5718
5719   /* Do partial setup of input buffer for the sake of generating
5720      early #line directives (when -g is in effect).  */
5721   fp = cpp_push_buffer (pfile, NULL, 0);
5722   if (!fp)
5723     return 0;
5724   if (opts->in_fname == NULL)
5725     opts->in_fname = "";
5726   fp->nominal_fname = fp->fname = opts->in_fname;
5727   fp->lineno = 0;
5728
5729   /* Install __LINE__, etc.  Must follow initialize_char_syntax
5730      and option processing.  */
5731   initialize_builtins (pfile);
5732
5733   /* Do standard #defines and assertions
5734      that identify system and machine type.  */
5735
5736   if (!opts->inhibit_predefs) {
5737     char *p = (char *) alloca (strlen (predefs) + 1);
5738     strcpy (p, predefs);
5739     while (*p) {
5740       char *q;
5741       while (*p == ' ' || *p == '\t')
5742         p++;
5743       /* Handle -D options.  */ 
5744       if (p[0] == '-' && p[1] == 'D') {
5745         q = &p[2];
5746         while (*p && *p != ' ' && *p != '\t')
5747           p++;
5748         if (*p != 0)
5749           *p++= 0;
5750         if (opts->debug_output)
5751           output_line_command (pfile, 0, same_file);
5752         cpp_define (pfile, q);
5753         while (*p == ' ' || *p == '\t')
5754           p++;
5755       } else if (p[0] == '-' && p[1] == 'A') {
5756         /* Handle -A options (assertions).  */ 
5757         char *assertion;
5758         char *past_name;
5759         char *value;
5760         char *past_value;
5761         char *termination;
5762         int save_char;
5763
5764         assertion = &p[2];
5765         past_name = assertion;
5766         /* Locate end of name.  */
5767         while (*past_name && *past_name != ' '
5768                && *past_name != '\t' && *past_name != '(')
5769           past_name++;
5770         /* Locate `(' at start of value.  */
5771         value = past_name;
5772         while (*value && (*value == ' ' || *value == '\t'))
5773           value++;
5774         if (*value++ != '(')
5775           abort ();
5776         while (*value && (*value == ' ' || *value == '\t'))
5777           value++;
5778         past_value = value;
5779         /* Locate end of value.  */
5780         while (*past_value && *past_value != ' '
5781                && *past_value != '\t' && *past_value != ')')
5782           past_value++;
5783         termination = past_value;
5784         while (*termination && (*termination == ' ' || *termination == '\t'))
5785           termination++;
5786         if (*termination++ != ')')
5787           abort ();
5788         if (*termination && *termination != ' ' && *termination != '\t')
5789           abort ();
5790         /* Temporarily null-terminate the value.  */
5791         save_char = *termination;
5792         *termination = '\0';
5793         /* Install the assertion.  */
5794         make_assertion (pfile, "-A", assertion);
5795         *termination = (char) save_char;
5796         p = termination;
5797         while (*p == ' ' || *p == '\t')
5798           p++;
5799       } else {
5800         abort ();
5801       }
5802     }
5803   }
5804
5805   /* Now handle the command line options.  */
5806
5807   /* Do -U's, -D's and -A's in the order they were seen.  */
5808   /* First reverse the list.  */
5809   opts->pending = nreverse_pending (opts->pending);
5810
5811   for (pend = opts->pending;  pend;  pend = pend->next)
5812     {
5813       if (pend->cmd != NULL && pend->cmd[0] == '-')
5814         {
5815           switch (pend->cmd[1])
5816             {
5817             case 'U':
5818               if (opts->debug_output)
5819                 output_line_command (pfile, 0, same_file);
5820               do_undef (pfile, NULL, pend->arg, pend->arg + strlen (pend->arg));
5821               break;
5822             case 'D':
5823               if (opts->debug_output)
5824                 output_line_command (pfile, 0, same_file);
5825               cpp_define (pfile, pend->arg);
5826               break;
5827             case 'A':
5828               make_assertion (pfile, "-A", pend->arg);
5829               break;
5830             }
5831         }
5832     }
5833
5834   opts->done_initializing = 1;
5835
5836   { /* Read the appropriate environment variable and if it exists
5837        replace include_defaults with the listed path.  */
5838     char *epath = 0;
5839     switch ((opts->objc << 1) + opts->cplusplus)
5840       {
5841       case 0:
5842         epath = getenv ("C_INCLUDE_PATH");
5843         break;
5844       case 1:
5845         epath = getenv ("CPLUS_INCLUDE_PATH");
5846         break;
5847       case 2:
5848         epath = getenv ("OBJC_INCLUDE_PATH");
5849         break;
5850       case 3:
5851         epath = getenv ("OBJCPLUS_INCLUDE_PATH");
5852         break;
5853       }
5854     /* If the environment var for this language is set,
5855        add to the default list of include directories.  */
5856     if (epath) {
5857       char *nstore = (char *) alloca (strlen (epath) + 2);
5858       int num_dirs;
5859       char *startp, *endp;
5860
5861       for (num_dirs = 1, startp = epath; *startp; startp++)
5862         if (*startp == PATH_SEPARATOR)
5863           num_dirs++;
5864       include_defaults
5865         = (struct default_include *) xmalloc ((num_dirs
5866                                                * sizeof (struct default_include))
5867                                               + sizeof (include_defaults_array));
5868       startp = endp = epath;
5869       num_dirs = 0;
5870       while (1) {
5871         /* Handle cases like c:/usr/lib:d:/gcc/lib */
5872         if ((*endp == PATH_SEPARATOR)
5873             || *endp == 0) {
5874           strncpy (nstore, startp, endp-startp);
5875           if (endp == startp)
5876             strcpy (nstore, ".");
5877           else
5878             nstore[endp-startp] = '\0';
5879
5880           include_defaults[num_dirs].fname = savestring (nstore);
5881           include_defaults[num_dirs].cplusplus = opts->cplusplus;
5882           include_defaults[num_dirs].cxx_aware = 1;
5883           num_dirs++;
5884           if (*endp == '\0')
5885             break;
5886           endp = startp = endp + 1;
5887         } else
5888           endp++;
5889       }
5890       /* Put the usual defaults back in at the end.  */
5891       bcopy ((char *) include_defaults_array,
5892              (char *) &include_defaults[num_dirs],
5893              sizeof (include_defaults_array));
5894     }
5895   }
5896
5897   append_include_chain (pfile, opts->before_system, opts->last_before_system);
5898   opts->first_system_include = opts->before_system;
5899
5900   /* Unless -fnostdinc,
5901      tack on the standard include file dirs to the specified list */
5902   if (!opts->no_standard_includes) {
5903     struct default_include *p = include_defaults;
5904     char *specd_prefix = opts->include_prefix;
5905     char *default_prefix = savestring (GCC_INCLUDE_DIR);
5906     int default_len = 0;
5907     /* Remove the `include' from /usr/local/lib/gcc.../include.  */
5908     if (!strcmp (default_prefix + strlen (default_prefix) - 8, "/include")) {
5909       default_len = strlen (default_prefix) - 7;
5910       default_prefix[default_len] = 0;
5911     }
5912     /* Search "translated" versions of GNU directories.
5913        These have /usr/local/lib/gcc... replaced by specd_prefix.  */
5914     if (specd_prefix != 0 && default_len != 0)
5915       for (p = include_defaults; p->fname; p++) {
5916         /* Some standard dirs are only for C++.  */
5917         if (!p->cplusplus
5918             || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
5919           /* Does this dir start with the prefix?  */
5920           if (!strncmp (p->fname, default_prefix, default_len)) {
5921             /* Yes; change prefix and add to search list.  */
5922             struct file_name_list *new
5923               = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5924             int this_len = strlen (specd_prefix) + strlen (p->fname) - default_len;
5925             char *str = (char *) xmalloc (this_len + 1);
5926             strcpy (str, specd_prefix);
5927             strcat (str, p->fname + default_len);
5928             new->fname = str;
5929             new->control_macro = 0;
5930             new->c_system_include_path = !p->cxx_aware;
5931             new->got_name_map = 0;
5932             append_include_chain (pfile, new, new);
5933             if (opts->first_system_include == 0)
5934               opts->first_system_include = new;
5935           }
5936         }
5937       }
5938     /* Search ordinary names for GNU include directories.  */
5939     for (p = include_defaults; p->fname; p++) {
5940       /* Some standard dirs are only for C++.  */
5941       if (!p->cplusplus
5942           || (opts->cplusplus && !opts->no_standard_cplusplus_includes)) {
5943         struct file_name_list *new
5944           = (struct file_name_list *) xmalloc (sizeof (struct file_name_list));
5945         new->control_macro = 0;
5946         new->c_system_include_path = !p->cxx_aware;
5947         new->fname = p->fname;
5948         new->got_name_map = 0;
5949         append_include_chain (pfile, new, new);
5950         if (opts->first_system_include == 0)
5951           opts->first_system_include = new;
5952       }
5953     }
5954   }
5955
5956   /* Tack the after_include chain at the end of the include chain.  */
5957   append_include_chain (pfile, opts->after_include, opts->last_after_include);
5958   if (opts->first_system_include == 0)
5959     opts->first_system_include = opts->after_include;
5960
5961   /* With -v, print the list of dirs to search.  */
5962   if (opts->verbose) {
5963     struct file_name_list *p;
5964     fprintf (stderr, "#include \"...\" search starts here:\n");
5965     for (p = opts->include; p; p = p->next) {
5966       if (p == opts->first_bracket_include)
5967         fprintf (stderr, "#include <...> search starts here:\n");
5968       fprintf (stderr, " %s\n", p->fname);
5969     }
5970     fprintf (stderr, "End of search list.\n");
5971   }
5972
5973   /* Scan the -imacros files before the main input.
5974      Much like #including them, but with no_output set
5975      so that only their macro definitions matter.  */
5976
5977   opts->no_output++; pfile->no_record_file++;
5978   for (pend = opts->pending;  pend;  pend = pend->next)
5979     {
5980       if (pend->cmd != NULL && strcmp (pend->cmd, "-imacros") == 0)
5981         {
5982           int fd = open (pend->arg, O_RDONLY, 0666);
5983           if (fd < 0)
5984             {
5985               cpp_perror_with_name (pfile, pend->arg);
5986               return 0;
5987             }
5988           if (!cpp_push_buffer (pfile, NULL, 0))
5989               return 0;
5990           finclude (pfile, fd, pend->arg, 0, NULL_PTR);
5991           cpp_scan_buffer (pfile);
5992         }
5993     }
5994   opts->no_output--; pfile->no_record_file--;
5995
5996   /* Copy the entire contents of the main input file into
5997      the stacked input buffer previously allocated for it.  */
5998   if (fname == NULL || *fname == 0) {
5999     fname = "";
6000     f = 0;
6001   } else if ((f = open (fname, O_RDONLY, 0666)) < 0)
6002     cpp_pfatal_with_name (pfile, fname);
6003
6004   /* -MG doesn't select the form of output and must be specified with one of
6005      -M or -MM.  -MG doesn't make sense with -MD or -MMD since they don't
6006      inhibit compilation.  */
6007   if (opts->print_deps_missing_files
6008       && (opts->print_deps == 0 || !opts->no_output))
6009     {
6010       cpp_fatal (pfile, "-MG must be specified with one of -M or -MM");
6011       return 0;
6012     }
6013
6014   /* Either of two environment variables can specify output of deps.
6015      Its value is either "OUTPUT_FILE" or "OUTPUT_FILE DEPS_TARGET",
6016      where OUTPUT_FILE is the file to write deps info to
6017      and DEPS_TARGET is the target to mention in the deps.  */
6018
6019   if (opts->print_deps == 0
6020       && (getenv ("SUNPRO_DEPENDENCIES") != 0
6021           || getenv ("DEPENDENCIES_OUTPUT") != 0)) {
6022     char *spec = getenv ("DEPENDENCIES_OUTPUT");
6023     char *s;
6024     char *output_file;
6025
6026     if (spec == 0)
6027       {
6028         spec = getenv ("SUNPRO_DEPENDENCIES");
6029         opts->print_deps = 2;
6030       }
6031     else
6032       opts->print_deps = 1;
6033
6034     s = spec;
6035     /* Find the space before the DEPS_TARGET, if there is one.  */
6036     /* This should use index.  (mrs) */
6037     while (*s != 0 && *s != ' ') s++;
6038     if (*s != 0)
6039       {
6040         opts->deps_target = s + 1;
6041         output_file = (char *) xmalloc (s - spec + 1);
6042         bcopy (spec, output_file, s - spec);
6043         output_file[s - spec] = 0;
6044       }
6045     else
6046       {
6047         opts->deps_target = 0;
6048         output_file = spec;
6049       }
6050
6051     opts->deps_file = output_file;
6052     opts->print_deps_append = 1;
6053   }
6054
6055   /* For -M, print the expected object file name
6056      as the target of this Make-rule.  */
6057   if (opts->print_deps)
6058     {
6059       pfile->deps_allocated_size = 200;
6060       pfile->deps_buffer = (char *) xmalloc (pfile->deps_allocated_size);
6061       pfile->deps_buffer[0] = 0;
6062       pfile->deps_size = 0;
6063       pfile->deps_column = 0;
6064
6065       if (opts->deps_target)
6066         deps_output (pfile, opts->deps_target, ':');
6067       else if (*opts->in_fname == 0)
6068         deps_output (pfile, "-", ':');
6069       else
6070         {
6071           char *p, *q;
6072           int len;
6073
6074           /* Discard all directory prefixes from filename.  */
6075           if ((q = rindex (opts->in_fname, '/')) != NULL
6076 #ifdef DIR_SEPARATOR
6077               && (q = rindex (opts->in_fname, DIR_SEPARATOR)) != NULL
6078 #endif
6079               )
6080             ++q;
6081           else
6082             q = opts->in_fname;
6083
6084           /* Copy remainder to mungable area.  */
6085           p = (char *) alloca (strlen(q) + 8);
6086           strcpy (p, q);
6087
6088           /* Output P, but remove known suffixes.  */
6089           len = strlen (p);
6090           q = p + len;
6091           if (len >= 2
6092               && p[len - 2] == '.'
6093               && index("cCsSm", p[len - 1]))
6094             q = p + (len - 2);
6095           else if (len >= 3
6096                    && p[len - 3] == '.'
6097                    && p[len - 2] == 'c'
6098                    && p[len - 1] == 'c')
6099             q = p + (len - 3);
6100           else if (len >= 4
6101                    && p[len - 4] == '.'
6102                    && p[len - 3] == 'c'
6103                    && p[len - 2] == 'x'
6104                    && p[len - 1] == 'x')
6105             q = p + (len - 4);
6106           else if (len >= 4
6107                    && p[len - 4] == '.'
6108                    && p[len - 3] == 'c'
6109                    && p[len - 2] == 'p'
6110                    && p[len - 1] == 'p')
6111             q = p + (len - 4);
6112
6113           /* Supply our own suffix.  */
6114 #ifndef VMS
6115           strcpy (q, ".o");
6116 #else
6117           strcpy (q, ".obj");
6118 #endif
6119
6120           deps_output (pfile, p, ':');
6121           deps_output (pfile, opts->in_fname, ' ');
6122         }
6123     }
6124
6125 #if 0
6126   /* Make sure data ends with a newline.  And put a null after it.  */
6127
6128   if ((fp->length > 0 && fp->buf[fp->length - 1] != '\n')
6129       /* Backslash-newline at end is not good enough.  */
6130       || (fp->length > 1 && fp->buf[fp->length - 2] == '\\')) {
6131     fp->buf[fp->length++] = '\n';
6132     missing_newline = 1;
6133   }
6134   fp->buf[fp->length] = '\0';
6135
6136   /* Unless inhibited, convert trigraphs in the input.  */
6137
6138   if (!no_trigraphs)
6139     trigraph_pcp (fp);
6140 #endif
6141
6142   /* Scan the -include files before the main input.
6143    We push these in reverse order, so that the first one is handled first.  */
6144
6145   pfile->no_record_file++;
6146   opts->pending = nreverse_pending (opts->pending);
6147   for (pend = opts->pending;  pend;  pend = pend->next)
6148     {
6149       if (pend->cmd != NULL && strcmp (pend->cmd, "-include") == 0)
6150         {
6151           int fd = open (pend->arg, O_RDONLY, 0666);
6152           if (fd < 0)
6153             {
6154               cpp_perror_with_name (pfile, pend->arg);
6155               return 0;
6156             }
6157           if (!cpp_push_buffer (pfile, NULL, 0))
6158             return 0;
6159           finclude (pfile, fd, pend->arg, 0, NULL_PTR);
6160         }
6161     }
6162   pfile->no_record_file--;
6163
6164   /* Free the pending list.  */
6165   for (pend = opts->pending;  pend; )
6166     {
6167       struct cpp_pending *next = pend->next;
6168       free (pend);
6169       pend = next;
6170     }
6171   opts->pending = NULL;
6172
6173 #if 0
6174   /* Scan the input, processing macros and directives.  */
6175
6176   rescan (&outbuf, 0);
6177
6178   if (missing_newline)
6179     fp->lineno--;
6180
6181   if (CPP_PEDANTIC (pfile) && missing_newline)
6182     pedwarn ("file does not end in newline");
6183
6184 #endif
6185   if (finclude (pfile, f, fname, 0, NULL_PTR))
6186     output_line_command (pfile, 0, same_file);
6187   return 1;
6188 }
6189
6190 void
6191 cpp_reader_init (pfile)
6192      cpp_reader *pfile;
6193 {
6194   bzero ((char *) pfile, sizeof (cpp_reader));
6195   pfile->get_token = cpp_get_token;
6196
6197   pfile->token_buffer_size = 200;
6198   pfile->token_buffer = (U_CHAR *) xmalloc (pfile->token_buffer_size);
6199   CPP_SET_WRITTEN (pfile, 0);
6200
6201   pfile->system_include_depth = 0;
6202   pfile->dont_repeat_files = 0;
6203   pfile->all_include_files = 0;
6204   pfile->max_include_len = 0;
6205   pfile->timebuf = NULL;
6206   pfile->only_seen_white = 1;
6207   pfile->buffer = CPP_NULL_BUFFER(pfile);
6208 }
6209
6210 static struct cpp_pending *
6211 nreverse_pending (list)
6212      struct cpp_pending *list;
6213      
6214 {
6215   register struct cpp_pending *prev = 0, *next, *pend;
6216   for (pend = list;  pend;  pend = next)
6217     {
6218       next = pend->next;
6219       pend->next = prev;
6220       prev = pend;
6221     }
6222   return prev;
6223 }
6224
6225 static void
6226 push_pending (pfile, cmd, arg)
6227      cpp_reader *pfile;
6228      char *cmd;
6229      char *arg;
6230 {
6231   struct cpp_pending *pend
6232     = (struct cpp_pending *) xmalloc (sizeof (struct cpp_pending));
6233   pend->cmd = cmd;
6234   pend->arg = arg;
6235   pend->next = CPP_OPTIONS (pfile)->pending;
6236   CPP_OPTIONS (pfile)->pending = pend;
6237 }
6238
6239 /* Handle command-line options in (argc, argv).
6240    Can be called multiple times, to handle multiple sets of options.
6241    Returns if an unrecognized option is seen.
6242    Returns number of handled arguments.  */
6243
6244 int
6245 cpp_handle_options (pfile, argc, argv)
6246      cpp_reader *pfile;
6247      int argc;
6248      char **argv;
6249 {
6250   int i;
6251   struct cpp_options *opts = CPP_OPTIONS (pfile);
6252   for (i = 0; i < argc; i++) {
6253     if (argv[i][0] != '-') {
6254       if (opts->out_fname != NULL)
6255         {
6256           cpp_fatal (pfile, "Usage: %s [switches] input output", argv[0]);
6257           return argc;
6258         }
6259       else if (opts->in_fname != NULL)
6260         opts->out_fname = argv[i];
6261       else
6262         opts->in_fname = argv[i];
6263     } else {
6264       switch (argv[i][1]) {
6265
6266       missing_filename:
6267         cpp_fatal (pfile, "Filename missing after `%s' option", argv[i]);
6268         return argc;
6269       missing_dirname:
6270         cpp_fatal (pfile, "Directory name missing after `%s' option", argv[i]);
6271         return argc;
6272
6273       case 'i':
6274         if (!strcmp (argv[i], "-include")
6275             || !strcmp (argv[i], "-imacros")) {
6276           if (i + 1 == argc)
6277             goto missing_filename;
6278           else
6279             push_pending (pfile, argv[i], argv[i+1]), i++;
6280         }
6281         if (!strcmp (argv[i], "-iprefix")) {
6282           if (i + 1 == argc)
6283             goto missing_filename;
6284           else
6285             opts->include_prefix = argv[++i];
6286         }
6287         if (!strcmp (argv[i], "-ifoutput")) {
6288           opts->output_conditionals = 1;
6289         }
6290         if (!strcmp (argv[i], "-isystem")) {
6291           struct file_name_list *dirtmp;
6292
6293           if (i + 1 == argc)
6294             goto missing_filename;
6295
6296           dirtmp = (struct file_name_list *)
6297             xmalloc (sizeof (struct file_name_list));
6298           dirtmp->next = 0;
6299           dirtmp->control_macro = 0;
6300           dirtmp->c_system_include_path = 1;
6301           dirtmp->fname = (char *) xmalloc (strlen (argv[i+1]) + 1);
6302           strcpy (dirtmp->fname, argv[++i]);
6303           dirtmp->got_name_map = 0;
6304
6305           if (opts->before_system == 0)
6306             opts->before_system = dirtmp;
6307           else
6308             opts->last_before_system->next = dirtmp;
6309           opts->last_before_system = dirtmp; /* Tail follows the last one */
6310         }
6311         /* Add directory to end of path for includes,
6312            with the default prefix at the front of its name.  */
6313         if (!strcmp (argv[i], "-iwithprefix")) {
6314           struct file_name_list *dirtmp;
6315           char *prefix;
6316
6317           if (opts->include_prefix != 0)
6318             prefix = opts->include_prefix;
6319           else {
6320             prefix = savestring (GCC_INCLUDE_DIR);
6321             /* Remove the `include' from /usr/local/lib/gcc.../include.  */
6322             if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
6323               prefix[strlen (prefix) - 7] = 0;
6324           }
6325
6326           dirtmp = (struct file_name_list *)
6327             xmalloc (sizeof (struct file_name_list));
6328           dirtmp->next = 0;     /* New one goes on the end */
6329           dirtmp->control_macro = 0;
6330           dirtmp->c_system_include_path = 0;
6331           if (i + 1 == argc)
6332             goto missing_dirname;
6333
6334           dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
6335                                             + strlen (prefix) + 1);
6336           strcpy (dirtmp->fname, prefix);
6337           strcat (dirtmp->fname, argv[++i]);
6338           dirtmp->got_name_map = 0;
6339
6340           if (opts->after_include == 0)
6341             opts->after_include = dirtmp;
6342           else
6343             opts->last_after_include->next = dirtmp;
6344           opts->last_after_include = dirtmp; /* Tail follows the last one */
6345         }
6346         /* Add directory to main path for includes,
6347            with the default prefix at the front of its name.  */
6348         if (!strcmp (argv[i], "-iwithprefixbefore")) {
6349           struct file_name_list *dirtmp;
6350           char *prefix;
6351
6352           if (opts->include_prefix != 0)
6353             prefix = opts->include_prefix;
6354           else {
6355             prefix = savestring (GCC_INCLUDE_DIR);
6356             /* Remove the `include' from /usr/local/lib/gcc.../include.  */
6357             if (!strcmp (prefix + strlen (prefix) - 8, "/include"))
6358               prefix[strlen (prefix) - 7] = 0;
6359           }
6360
6361           dirtmp = (struct file_name_list *)
6362             xmalloc (sizeof (struct file_name_list));
6363           dirtmp->next = 0;     /* New one goes on the end */
6364           dirtmp->control_macro = 0;
6365           dirtmp->c_system_include_path = 0;
6366           if (i + 1 == argc)
6367             goto missing_dirname;
6368
6369           dirtmp->fname = (char *) xmalloc (strlen (argv[i+1])
6370                                             + strlen (prefix) + 1);
6371           strcpy (dirtmp->fname, prefix);
6372           strcat (dirtmp->fname, argv[++i]);
6373           dirtmp->got_name_map = 0;
6374
6375           append_include_chain (pfile, dirtmp, dirtmp);
6376         }
6377         /* Add directory to end of path for includes.  */
6378         if (!strcmp (argv[i], "-idirafter")) {
6379           struct file_name_list *dirtmp;
6380
6381           dirtmp = (struct file_name_list *)
6382             xmalloc (sizeof (struct file_name_list));
6383           dirtmp->next = 0;     /* New one goes on the end */
6384           dirtmp->control_macro = 0;
6385           dirtmp->c_system_include_path = 0;
6386           if (i + 1 == argc)
6387             goto missing_dirname;
6388           else
6389             dirtmp->fname = argv[++i];
6390           dirtmp->got_name_map = 0;
6391
6392           if (opts->after_include == 0)
6393             opts->after_include = dirtmp;
6394           else
6395             opts->last_after_include->next = dirtmp;
6396           opts->last_after_include = dirtmp; /* Tail follows the last one */
6397         }
6398         break;
6399
6400       case 'o':
6401         if (opts->out_fname != NULL)
6402           {
6403             cpp_fatal (pfile, "Output filename specified twice");
6404             return argc;
6405           }
6406         if (i + 1 == argc)
6407           goto missing_filename;
6408         opts->out_fname = argv[++i];
6409         if (!strcmp (opts->out_fname, "-"))
6410           opts->out_fname = "";
6411         break;
6412
6413       case 'p':
6414         if (!strcmp (argv[i], "-pedantic"))
6415           CPP_PEDANTIC (pfile) = 1;
6416         else if (!strcmp (argv[i], "-pedantic-errors")) {
6417           CPP_PEDANTIC (pfile) = 1;
6418           opts->pedantic_errors = 1;
6419         }
6420 #if 0
6421         else if (!strcmp (argv[i], "-pcp")) {
6422           char *pcp_fname = argv[++i];
6423           pcp_outfile = 
6424             ((pcp_fname[0] != '-' || pcp_fname[1] != '\0')
6425              ? fopen (pcp_fname, "w")
6426              : fdopen (dup (fileno (stdout)), "w"));
6427           if (pcp_outfile == 0)
6428             cpp_pfatal_with_name (pfile, pcp_fname);
6429           no_precomp = 1;
6430         }
6431 #endif
6432         break;
6433
6434       case 't':
6435         if (!strcmp (argv[i], "-traditional")) {
6436           opts->traditional = 1;
6437         } else if (!strcmp (argv[i], "-trigraphs")) {
6438           if (!opts->chill)
6439             opts->no_trigraphs = 0;
6440         }
6441         break;
6442
6443       case 'l':
6444         if (! strcmp (argv[i], "-lang-c"))
6445           opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
6446           opts->objc = 0;
6447         if (! strcmp (argv[i], "-lang-c89"))
6448           opts->cplusplus = 0, opts->cplusplus_comments = 0, opts->c89 = 1,
6449           opts->objc = 0;
6450         if (! strcmp (argv[i], "-lang-c++"))
6451           opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
6452           opts->objc = 0;
6453         if (! strcmp (argv[i], "-lang-objc"))
6454           opts->cplusplus = 0, opts->cplusplus_comments = 1, opts->c89 = 0,
6455           opts->objc = 1;
6456         if (! strcmp (argv[i], "-lang-objc++"))
6457           opts->cplusplus = 1, opts->cplusplus_comments = 1, opts->c89 = 0,
6458           opts->objc = 1;
6459         if (! strcmp (argv[i], "-lang-asm"))
6460           opts->lang_asm = 1;
6461         if (! strcmp (argv[i], "-lint"))
6462           opts->for_lint = 1;
6463         if (! strcmp (argv[i], "-lang-chill"))
6464           opts->objc = 0, opts->cplusplus = 0, opts->chill = 1,
6465           opts->traditional = 1, opts->no_trigraphs = 1;
6466         break;
6467
6468       case '+':
6469         opts->cplusplus = 1, opts->cplusplus_comments = 1;
6470         break;
6471
6472       case 'w':
6473         opts->inhibit_warnings = 1;
6474         break;
6475
6476       case 'W':
6477         if (!strcmp (argv[i], "-Wtrigraphs"))
6478           opts->warn_trigraphs = 1;
6479         else if (!strcmp (argv[i], "-Wno-trigraphs"))
6480           opts->warn_trigraphs = 0;
6481         else if (!strcmp (argv[i], "-Wcomment"))
6482           opts->warn_comments = 1;
6483         else if (!strcmp (argv[i], "-Wno-comment"))
6484           opts->warn_comments = 0;
6485         else if (!strcmp (argv[i], "-Wcomments"))
6486           opts->warn_comments = 1;
6487         else if (!strcmp (argv[i], "-Wno-comments"))
6488           opts->warn_comments = 0;
6489         else if (!strcmp (argv[i], "-Wtraditional"))
6490           opts->warn_stringify = 1;
6491         else if (!strcmp (argv[i], "-Wno-traditional"))
6492           opts->warn_stringify = 0;
6493         else if (!strcmp (argv[i], "-Wimport"))
6494           opts->warn_import = 1;
6495         else if (!strcmp (argv[i], "-Wno-import"))
6496           opts->warn_import = 0;
6497         else if (!strcmp (argv[i], "-Werror"))
6498           opts->warnings_are_errors = 1;
6499         else if (!strcmp (argv[i], "-Wno-error"))
6500           opts->warnings_are_errors = 0;
6501         else if (!strcmp (argv[i], "-Wall"))
6502           {
6503             opts->warn_trigraphs = 1;
6504             opts->warn_comments = 1;
6505           }
6506         break;
6507
6508       case 'M':
6509         /* The style of the choices here is a bit mixed.
6510            The chosen scheme is a hybrid of keeping all options in one string
6511            and specifying each option in a separate argument:
6512            -M|-MM|-MD file|-MMD file [-MG].  An alternative is:
6513            -M|-MM|-MD file|-MMD file|-MG|-MMG; or more concisely:
6514            -M[M][G][D file].  This is awkward to handle in specs, and is not
6515            as extensible.  */
6516         /* ??? -MG must be specified in addition to one of -M or -MM.
6517            This can be relaxed in the future without breaking anything.
6518            The converse isn't true.  */
6519
6520         /* -MG isn't valid with -MD or -MMD.  This is checked for later.  */
6521         if (!strcmp (argv[i], "-MG"))
6522           {
6523             opts->print_deps_missing_files = 1;
6524             break;
6525           }
6526         if (!strcmp (argv[i], "-M"))
6527           opts->print_deps = 2;
6528         else if (!strcmp (argv[i], "-MM"))
6529           opts->print_deps = 1;
6530         else if (!strcmp (argv[i], "-MD"))
6531           opts->print_deps = 2;
6532         else if (!strcmp (argv[i], "-MMD"))
6533           opts->print_deps = 1;
6534         /* For -MD and -MMD options, write deps on file named by next arg.  */
6535         if (!strcmp (argv[i], "-MD") || !strcmp (argv[i], "-MMD"))
6536           {
6537             if (i+1 == argc)
6538               goto missing_filename;
6539             opts->deps_file = argv[++i];
6540           }
6541         else
6542           {
6543             /* For -M and -MM, write deps on standard output
6544                and suppress the usual output.  */
6545             opts->no_output = 1;
6546           }       
6547         break;
6548
6549       case 'd':
6550         {
6551           char *p = argv[i] + 2;
6552           char c;
6553           while ((c = *p++) != 0) {
6554             /* Arg to -d specifies what parts of macros to dump */
6555             switch (c) {
6556             case 'M':
6557               opts->dump_macros = dump_only;
6558               opts->no_output = 1;
6559               break;
6560             case 'N':
6561               opts->dump_macros = dump_names;
6562               break;
6563             case 'D':
6564               opts->dump_macros = dump_definitions;
6565               break;
6566             }
6567           }
6568         }
6569         break;
6570
6571       case 'g':
6572         if (argv[i][2] == '3')
6573           opts->debug_output = 1;
6574         break;
6575
6576       case 'v':
6577         fprintf (stderr, "GNU CPP version %s", version_string);
6578 #ifdef TARGET_VERSION
6579         TARGET_VERSION;
6580 #endif
6581         fprintf (stderr, "\n");
6582         opts->verbose = 1;
6583         break;
6584
6585       case 'H':
6586         opts->print_include_names = 1;
6587         break;
6588
6589       case 'D':
6590         if (argv[i][2] != 0)
6591           push_pending (pfile, "-D", argv[i] + 2);
6592         else if (i + 1 == argc)
6593           {
6594             cpp_fatal (pfile, "Macro name missing after -D option");
6595             return argc;
6596           }
6597         else
6598           i++, push_pending (pfile, "-D", argv[i]);
6599         break;
6600
6601       case 'A':
6602         {
6603           char *p;
6604
6605           if (argv[i][2] != 0)
6606             p = argv[i] + 2;
6607           else if (i + 1 == argc)
6608             {
6609               cpp_fatal (pfile, "Assertion missing after -A option");
6610               return argc;
6611             }
6612           else
6613             p = argv[++i];
6614
6615           if (!strcmp (p, "-")) {
6616             struct cpp_pending **ptr;
6617             /* -A- eliminates all predefined macros and assertions.
6618                Let's include also any that were specified earlier
6619                on the command line.  That way we can get rid of any
6620                that were passed automatically in from GCC.  */
6621             int j;
6622             opts->inhibit_predefs = 1;
6623             for (ptr = &opts->pending; *ptr != NULL; )
6624               {
6625                 struct cpp_pending *pend = *ptr;
6626                 if (pend->cmd && pend->cmd[0] == '-'
6627                     && (pend->cmd[1] == 'D' || pend->cmd[1] == 'A'))
6628                   {
6629                     *ptr = pend->next;
6630                     free (pend);
6631                   }
6632                 else
6633                   ptr = &pend->next;
6634               }
6635           } else {
6636             push_pending (pfile, "-A", p);
6637           }
6638         }
6639         break;
6640
6641       case 'U':         /* JF #undef something */
6642         if (argv[i][2] != 0)
6643           push_pending (pfile, "-U", argv[i] + 2);
6644         else if (i + 1 == argc)
6645           {
6646             cpp_fatal (pfile, "Macro name missing after -U option", NULL);
6647             return argc;
6648           }
6649         else
6650           push_pending (pfile, "-U", argv[i+1]), i++;
6651         break;
6652
6653       case 'C':
6654         opts->put_out_comments = 1;
6655         break;
6656
6657       case 'E':                 /* -E comes from cc -E; ignore it.  */
6658         break;
6659
6660       case 'P':
6661         opts->no_line_commands = 1;
6662         break;
6663
6664       case '$':                 /* Don't include $ in identifiers.  */
6665         opts->dollars_in_ident = 0;
6666         break;
6667
6668       case 'I':                 /* Add directory to path for includes.  */
6669         {
6670           struct file_name_list *dirtmp;
6671
6672           if (! CPP_OPTIONS(pfile)->ignore_srcdir
6673               && !strcmp (argv[i] + 2, "-")) {
6674             CPP_OPTIONS (pfile)->ignore_srcdir = 1;
6675             /* Don't use any preceding -I directories for #include <...>.  */
6676             CPP_OPTIONS (pfile)->first_bracket_include = 0;
6677           }
6678           else {
6679             dirtmp = (struct file_name_list *)
6680               xmalloc (sizeof (struct file_name_list));
6681             dirtmp->next = 0;           /* New one goes on the end */
6682             dirtmp->control_macro = 0;
6683             dirtmp->c_system_include_path = 0;
6684             if (argv[i][2] != 0)
6685               dirtmp->fname = argv[i] + 2;
6686             else if (i + 1 == argc)
6687               goto missing_dirname;
6688             else
6689               dirtmp->fname = argv[++i];
6690             dirtmp->got_name_map = 0;
6691             append_include_chain (pfile, dirtmp, dirtmp);
6692           }
6693         }
6694         break;
6695
6696       case 'n':
6697         if (!strcmp (argv[i], "-nostdinc"))
6698           /* -nostdinc causes no default include directories.
6699              You must specify all include-file directories with -I.  */
6700           opts->no_standard_includes = 1;
6701         else if (!strcmp (argv[i], "-nostdinc++"))
6702           /* -nostdinc++ causes no default C++-specific include directories. */
6703           opts->no_standard_cplusplus_includes = 1;
6704 #if 0
6705         else if (!strcmp (argv[i], "-noprecomp"))
6706           no_precomp = 1;
6707 #endif
6708         break;
6709
6710       case 'u':
6711         /* Sun compiler passes undocumented switch "-undef".
6712            Let's assume it means to inhibit the predefined symbols.  */
6713         opts->inhibit_predefs = 1;
6714         break;
6715
6716       case '\0': /* JF handle '-' as file name meaning stdin or stdout */
6717         if (opts->in_fname == NULL) {
6718           opts->in_fname = "";
6719           break;
6720         } else if (opts->out_fname == NULL) {
6721           opts->out_fname = "";
6722           break;
6723         }       /* else fall through into error */
6724
6725       default:
6726         return i;
6727       }
6728     }
6729   }
6730   return i;
6731 }
6732 \f
6733 void
6734 cpp_finish (pfile)
6735      cpp_reader *pfile;
6736 {
6737   struct cpp_options *opts = CPP_OPTIONS (pfile);
6738   
6739   if (opts->print_deps)
6740     {
6741       /* Stream on which to print the dependency information.  */
6742       FILE *deps_stream;
6743
6744       /* Don't actually write the deps file if compilation has failed.  */
6745       if (pfile->errors == 0)
6746         {
6747           char *deps_mode = opts->print_deps_append ? "a" : "w";
6748           if (opts->deps_file == 0)
6749             deps_stream = stdout;
6750           else if ((deps_stream = fopen (opts->deps_file, deps_mode)) == 0)
6751             cpp_pfatal_with_name (pfile, opts->deps_file);
6752           fputs (pfile->deps_buffer, deps_stream);
6753           putc ('\n', deps_stream);
6754           if (opts->deps_file)
6755             {
6756               if (ferror (deps_stream) || fclose (deps_stream) != 0)
6757                 cpp_fatal (pfile, "I/O error on output");
6758             }
6759         }
6760     }
6761 }
6762
6763 /* Free resources used by PFILE.
6764    This is the cpp_reader 'finalizer' or 'destructor' (in C++ terminology).  */
6765
6766 void
6767 cpp_cleanup (pfile)
6768      cpp_reader *pfile;
6769 {
6770   int i;
6771   while ( CPP_BUFFER (pfile) != CPP_NULL_BUFFER (pfile))
6772     cpp_pop_buffer (pfile);
6773
6774   if (pfile->token_buffer)
6775     {
6776       free (pfile->token_buffer);
6777       pfile->token_buffer = NULL;
6778     }
6779
6780   if (pfile->deps_buffer)
6781     {
6782       free (pfile->deps_buffer);
6783       pfile->deps_buffer = NULL;
6784       pfile->deps_allocated_size = 0;
6785     }
6786
6787   while (pfile->if_stack)
6788     {
6789       IF_STACK_FRAME *temp = pfile->if_stack;
6790       pfile->if_stack = temp->next;
6791       free (temp);
6792     }
6793
6794   while (pfile->dont_repeat_files)
6795     {
6796       struct file_name_list *temp = pfile->dont_repeat_files;
6797       pfile->dont_repeat_files = temp->next;
6798       free (temp->fname);
6799       free (temp);
6800     }
6801
6802   while (pfile->all_include_files)
6803     {
6804       struct file_name_list *temp = pfile->all_include_files;
6805       pfile->all_include_files = temp->next;
6806       free (temp->fname);
6807       free (temp);
6808     }
6809
6810   for (i = IMPORT_HASH_SIZE; --i >= 0; )
6811     {
6812       register struct import_file *imp = pfile->import_hash_table[i];
6813       while (imp)
6814         {
6815           struct import_file *next = imp->next;
6816           free (imp->name);
6817           free (imp);
6818           imp = next;
6819         }
6820       pfile->import_hash_table[i] = 0;
6821     }
6822
6823   for (i = ASSERTION_HASHSIZE; --i >= 0; )
6824     {
6825       while (pfile->assertion_hashtab[i])
6826         delete_assertion (pfile->assertion_hashtab[i]);
6827     }
6828
6829   cpp_hash_cleanup (pfile);
6830 }
6831 \f
6832 static int
6833 do_assert (pfile, keyword, buf, limit)
6834      cpp_reader *pfile;
6835      struct directive *keyword;
6836      U_CHAR *buf, *limit;
6837 {
6838   long symstart;                /* remember where symbol name starts */
6839   int c;
6840   int sym_length;               /* and how long it is */
6841   struct arglist *tokens = NULL;
6842
6843   if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->done_initializing
6844       && !CPP_BUFFER (pfile)->system_header_p)
6845     cpp_pedwarn (pfile, "ANSI C does not allow `#assert'");
6846
6847   cpp_skip_hspace (pfile);
6848   symstart = CPP_WRITTEN (pfile);       /* remember where it starts */
6849   parse_name (pfile, GETC());
6850   sym_length = check_macro_name (pfile, pfile->token_buffer + symstart,
6851                                  "assertion");
6852
6853   cpp_skip_hspace (pfile);
6854   if (PEEKC() != '(') {
6855     cpp_error (pfile, "missing token-sequence in `#assert'");
6856     goto error;
6857   }
6858
6859   {
6860     int error_flag = 0;
6861     tokens = read_token_list (pfile, &error_flag);
6862     if (error_flag)
6863       goto error;
6864     if (tokens == 0) {
6865       cpp_error (pfile, "empty token-sequence in `#assert'");
6866       goto error;
6867     }
6868   cpp_skip_hspace (pfile);
6869   c = PEEKC ();
6870   if (c != EOF && c != '\n')
6871       cpp_pedwarn (pfile, "junk at end of `#assert'");
6872   skip_rest_of_line (pfile);
6873   }
6874
6875   /* If this name isn't already an assertion name, make it one.
6876      Error if it was already in use in some other way.  */
6877
6878   {
6879     ASSERTION_HASHNODE *hp;
6880     U_CHAR *symname = pfile->token_buffer + symstart;
6881     int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6882     struct tokenlist_list *value
6883       = (struct tokenlist_list *) xmalloc (sizeof (struct tokenlist_list));
6884
6885     hp = assertion_lookup (pfile, symname, sym_length, hashcode);
6886     if (hp == NULL) {
6887       if (sym_length == 7 && ! strncmp (symname, "defined", sym_length))
6888         cpp_error (pfile, "`defined' redefined as assertion");
6889       hp = assertion_install (pfile, symname, sym_length, hashcode);
6890     }
6891
6892     /* Add the spec'd token-sequence to the list of such.  */
6893     value->tokens = tokens;
6894     value->next = hp->value;
6895     hp->value = value;
6896   }
6897   CPP_SET_WRITTEN (pfile, symstart); /* Pop */
6898   return 0;
6899  error:
6900   CPP_SET_WRITTEN (pfile, symstart); /* Pop */
6901   skip_rest_of_line (pfile);
6902   return 1;
6903 }
6904 \f
6905 static int
6906 do_unassert (pfile, keyword, buf, limit)
6907      cpp_reader *pfile;
6908      struct directive *keyword;
6909      U_CHAR *buf, *limit;
6910 {
6911   long symstart;                /* remember where symbol name starts */
6912   int sym_length;       /* and how long it is */
6913   int c;
6914
6915   struct arglist *tokens = NULL;
6916   int tokens_specified = 0;
6917
6918   if (CPP_PEDANTIC (pfile) && CPP_OPTIONS (pfile)->done_initializing
6919       && !CPP_BUFFER (pfile)->system_header_p)
6920     cpp_pedwarn (pfile, "ANSI C does not allow `#unassert'");
6921
6922   cpp_skip_hspace (pfile);
6923
6924   symstart = CPP_WRITTEN (pfile);       /* remember where it starts */
6925   parse_name (pfile, GETC());
6926   sym_length = check_macro_name (pfile, pfile->token_buffer + symstart,
6927                                  "assertion");
6928
6929   cpp_skip_hspace (pfile);
6930   if (PEEKC() == '(') {
6931     int error_flag = 0;
6932
6933     tokens = read_token_list (pfile, &error_flag);
6934     if (error_flag)
6935       goto error;
6936     if (tokens == 0) {
6937       cpp_error (pfile, "empty token list in `#unassert'");
6938       goto error;
6939     }
6940
6941     tokens_specified = 1;
6942   }
6943
6944   cpp_skip_hspace (pfile);
6945   c = PEEKC ();
6946   if (c != EOF && c != '\n')
6947       cpp_error (pfile, "junk at end of `#unassert'");
6948   skip_rest_of_line (pfile);
6949
6950   {
6951     ASSERTION_HASHNODE *hp;
6952     U_CHAR *symname = pfile->token_buffer + symstart;
6953     int hashcode = hashf (symname, sym_length, ASSERTION_HASHSIZE);
6954     struct tokenlist_list *tail, *prev;
6955
6956     hp = assertion_lookup (pfile, symname, sym_length, hashcode);
6957     if (hp == NULL)
6958       return 1;
6959
6960     /* If no token list was specified, then eliminate this assertion
6961        entirely.  */
6962     if (! tokens_specified)
6963       delete_assertion (hp);
6964     else {
6965       /* If a list of tokens was given, then delete any matching list.  */
6966
6967       tail = hp->value;
6968       prev = 0;
6969       while (tail) {
6970         struct tokenlist_list *next = tail->next;
6971         if (compare_token_lists (tail->tokens, tokens)) {
6972           if (prev)
6973             prev->next = next;
6974           else
6975             hp->value = tail->next;
6976           free_token_list (tail->tokens);
6977           free (tail);
6978         } else {
6979           prev = tail;
6980         }
6981         tail = next;
6982       }
6983     }
6984   }
6985
6986   CPP_SET_WRITTEN (pfile, symstart); /* Pop */
6987   return 0;
6988  error:
6989   CPP_SET_WRITTEN (pfile, symstart); /* Pop */
6990   skip_rest_of_line (pfile);
6991   return 1;
6992 }
6993 \f
6994 /* Test whether there is an assertion named NAME
6995    and optionally whether it has an asserted token list TOKENS.
6996    NAME is not null terminated; its length is SYM_LENGTH.
6997    If TOKENS_SPECIFIED is 0, then don't check for any token list.  */
6998
6999 int
7000 check_assertion (pfile, name, sym_length, tokens_specified, tokens)
7001      cpp_reader *pfile;
7002      U_CHAR *name;
7003      int sym_length;
7004      int tokens_specified;
7005      struct arglist *tokens;
7006 {
7007   ASSERTION_HASHNODE *hp;
7008   int hashcode = hashf (name, sym_length, ASSERTION_HASHSIZE);
7009
7010   if (CPP_PEDANTIC (pfile) && !CPP_BUFFER (pfile)->system_header_p)
7011     cpp_pedwarn (pfile, "ANSI C does not allow testing assertions");
7012
7013   hp = assertion_lookup (pfile, name, sym_length, hashcode);
7014   if (hp == NULL)
7015     /* It is not an assertion; just return false.  */
7016     return 0;
7017
7018   /* If no token list was specified, then value is 1.  */
7019   if (! tokens_specified)
7020     return 1;
7021
7022   {
7023     struct tokenlist_list *tail;
7024
7025     tail = hp->value;
7026
7027     /* If a list of tokens was given,
7028        then succeed if the assertion records a matching list.  */
7029
7030     while (tail) {
7031       if (compare_token_lists (tail->tokens, tokens))
7032         return 1;
7033       tail = tail->next;
7034     }
7035
7036     /* Fail if the assertion has no matching list.  */
7037     return 0;
7038   }
7039 }
7040
7041 /* Compare two lists of tokens for equality including order of tokens.  */
7042
7043 static int
7044 compare_token_lists (l1, l2)
7045      struct arglist *l1, *l2;
7046 {
7047   while (l1 && l2) {
7048     if (l1->length != l2->length)
7049       return 0;
7050     if (strncmp (l1->name, l2->name, l1->length))
7051       return 0;
7052     l1 = l1->next;
7053     l2 = l2->next;
7054   }
7055
7056   /* Succeed if both lists end at the same time.  */
7057   return l1 == l2;
7058 }
7059 \f
7060 struct arglist *
7061 reverse_token_list (tokens)
7062      struct arglist *tokens;
7063 {
7064   register struct arglist *prev = 0, *this, *next;
7065   for (this = tokens; this; this = next)
7066     {
7067       next = this->next;
7068       this->next = prev;
7069       prev = this;
7070     }
7071   return prev;
7072 }
7073
7074 /* Read a space-separated list of tokens ending in a close parenthesis.
7075    Return a list of strings, in the order they were written.
7076    (In case of error, return 0 and store -1 in *ERROR_FLAG.) */
7077
7078 static struct arglist *
7079 read_token_list (pfile, error_flag)
7080      cpp_reader *pfile;
7081      int *error_flag;
7082 {
7083   struct arglist *token_ptrs = 0;
7084   int depth = 1;
7085   int length;
7086
7087   *error_flag = 0;
7088   FORWARD (1);  /* Skip '(' */
7089
7090   /* Loop over the assertion value tokens.  */
7091   while (depth > 0)
7092     {
7093       struct arglist *temp;
7094       long name_written = CPP_WRITTEN (pfile);
7095       int eofp = 0;  int c;
7096
7097       cpp_skip_hspace (pfile);
7098
7099       c = GETC ();
7100           
7101       /* Find the end of the token.  */
7102       if (c == '(')
7103         {
7104           CPP_PUTC (pfile, c);
7105           depth++;
7106         }
7107       else if (c == ')')
7108         {
7109           depth--;
7110           if (depth == 0)
7111             break;
7112           CPP_PUTC (pfile, c);
7113         }
7114       else if (c == '"' || c == '\'')
7115         {
7116           FORWARD(-1);
7117           cpp_get_token (pfile);
7118         }
7119       else if (c == '\n')
7120         break;
7121       else
7122         {
7123           while (c != EOF && ! is_space[c] && c != '(' && c != ')'
7124                  && c != '"' && c != '\'')
7125             {
7126               CPP_PUTC (pfile, c);
7127               c = GETC();
7128             }
7129           if (c != EOF)  FORWARD(-1);
7130         }
7131
7132       length = CPP_WRITTEN (pfile) - name_written;
7133       temp = (struct arglist *)
7134           xmalloc (sizeof (struct arglist) + length + 1);
7135       temp->name = (U_CHAR *) (temp + 1);
7136       bcopy ((char *) (pfile->token_buffer + name_written),
7137              (char *) temp->name, length);
7138       temp->name[length] = 0;
7139       temp->next = token_ptrs;
7140       token_ptrs = temp;
7141       temp->length = length;
7142
7143       CPP_ADJUST_WRITTEN (pfile, -length); /* pop */
7144
7145       if (c == EOF || c == '\n')
7146         { /* FIXME */
7147           cpp_error (pfile,
7148                      "unterminated token sequence following  `#' operator");
7149           return 0;
7150         }
7151     }
7152
7153   /* We accumulated the names in reverse order.
7154      Now reverse them to get the proper order.  */
7155   return reverse_token_list (token_ptrs);
7156 }
7157
7158 static void
7159 free_token_list (tokens)
7160      struct arglist *tokens;
7161 {
7162   while (tokens) {
7163     struct arglist *next = tokens->next;
7164     free (tokens->name);
7165     free (tokens);
7166     tokens = next;
7167   }
7168 }
7169 \f
7170 /* Get the file-mode and data size of the file open on FD
7171    and store them in *MODE_POINTER and *SIZE_POINTER.  */
7172
7173 static int
7174 file_size_and_mode (fd, mode_pointer, size_pointer)
7175      int fd;
7176      int *mode_pointer;
7177      long int *size_pointer;
7178 {
7179   struct stat sbuf;
7180
7181   if (fstat (fd, &sbuf) < 0) return (-1);
7182   if (mode_pointer) *mode_pointer = sbuf.st_mode;
7183   if (size_pointer) *size_pointer = sbuf.st_size;
7184   return 0;
7185 }
7186
7187 /* Read LEN bytes at PTR from descriptor DESC, for file FILENAME,
7188    retrying if necessary.  Return a negative value if an error occurs,
7189    otherwise return the actual number of bytes read,
7190    which must be LEN unless end-of-file was reached.  */
7191
7192 static int
7193 safe_read (desc, ptr, len)
7194      int desc;
7195      char *ptr;
7196      int len;
7197 {
7198   int left = len;
7199   while (left > 0) {
7200     int nchars = read (desc, ptr, left);
7201     if (nchars < 0)
7202       {
7203 #ifdef EINTR
7204         if (errno == EINTR)
7205           continue;
7206 #endif
7207         return nchars;
7208       }
7209     if (nchars == 0)
7210       break;
7211     ptr += nchars;
7212     left -= nchars;
7213   }
7214   return len - left;
7215 }
7216
7217 static char *
7218 xcalloc (number, size)
7219      unsigned number, size;
7220 {
7221   register unsigned total = number * size;
7222   register char *ptr = (char *) xmalloc (total);
7223   bzero (ptr, total);
7224   return ptr;
7225 }
7226
7227 static char *
7228 savestring (input)
7229      char *input;
7230 {
7231   unsigned size = strlen (input);
7232   char *output = xmalloc (size + 1);
7233   strcpy (output, input);
7234   return output;
7235 }
7236 \f
7237 /* Initialize PMARK to remember the current position of PFILE.  */
7238
7239 void
7240 parse_set_mark (pmark, pfile)
7241      struct parse_marker *pmark;
7242      cpp_reader *pfile;
7243 {
7244   cpp_buffer *pbuf = CPP_BUFFER (pfile);
7245   pmark->next = pbuf->marks;
7246   pbuf->marks = pmark;
7247   pmark->buf = pbuf;
7248   pmark->position = pbuf->cur - pbuf->buf;
7249 }
7250
7251 /* Cleanup PMARK - we no longer need it.  */
7252
7253 void
7254 parse_clear_mark (pmark)
7255      struct parse_marker *pmark;
7256 {
7257   struct parse_marker **pp = &pmark->buf->marks;
7258   for (; ; pp = &(*pp)->next) {
7259     if (*pp == NULL) abort ();
7260     if (*pp == pmark) break;
7261   }
7262   *pp = pmark->next;
7263 }
7264
7265 /* Backup the current position of PFILE to that saved in PMARK.  */
7266
7267 void
7268 parse_goto_mark (pmark, pfile)
7269      struct parse_marker *pmark;
7270      cpp_reader *pfile;
7271 {
7272   cpp_buffer *pbuf = CPP_BUFFER (pfile);
7273   if (pbuf != pmark->buf)
7274     cpp_fatal (pfile, "internal error %s", "parse_goto_mark");
7275   pbuf->cur = pbuf->buf + pmark->position;
7276 }
7277
7278 /* Reset PMARK to point to the current position of PFILE.  (Same
7279    as parse_clear_mark (PMARK), parse_set_mark (PMARK, PFILE) but faster.  */
7280
7281 void
7282 parse_move_mark (pmark, pfile)
7283      struct parse_marker *pmark;
7284      cpp_reader *pfile;
7285 {
7286   cpp_buffer *pbuf = CPP_BUFFER (pfile);
7287   if (pbuf != pmark->buf)
7288     cpp_fatal (pfile, "internal error %s", "parse_move_mark");
7289   pmark->position = pbuf->cur - pbuf->buf;
7290 }
7291
7292 int
7293 cpp_read_check_assertion (pfile)
7294      cpp_reader *pfile;
7295 {
7296   int name_start = CPP_WRITTEN (pfile);
7297   int name_length, name_written;
7298   int result;
7299   FORWARD (1);  /* Skip '#' */
7300   cpp_skip_hspace (pfile);
7301   parse_name (pfile, GETC ());
7302   name_written = CPP_WRITTEN (pfile);
7303   name_length = name_written - name_start;
7304   cpp_skip_hspace (pfile);
7305   if (CPP_BUF_PEEK (CPP_BUFFER (pfile)) == '(')
7306     {
7307       int error_flag;
7308       struct arglist *token_ptrs = read_token_list (pfile, &error_flag);
7309       result = check_assertion (pfile,
7310                                 pfile->token_buffer + name_start, name_length,
7311                                 1, token_ptrs);
7312     }
7313   else
7314     result = check_assertion (pfile,
7315                               pfile->token_buffer + name_start, name_length,
7316                               0, NULL_PTR);
7317   CPP_ADJUST_WRITTEN (pfile, - name_length);  /* pop */
7318   return result;
7319 }
7320 \f
7321 void
7322 cpp_print_file_and_line (pfile)
7323      cpp_reader *pfile;
7324 {
7325   cpp_buffer *ip = cpp_file_buffer (pfile);
7326
7327   if (ip != NULL)
7328     {
7329       long line, col;
7330       cpp_buf_line_and_col (ip, &line, &col);
7331       cpp_file_line_for_message (pfile, ip->nominal_fname,
7332                                  line, pfile->show_column ? col : -1);
7333     }
7334 }
7335
7336 void
7337 cpp_error (pfile, msg, arg1, arg2, arg3)
7338      cpp_reader *pfile;
7339      char *msg;
7340      char *arg1, *arg2, *arg3;
7341 {
7342   cpp_print_containing_files (pfile);
7343   cpp_print_file_and_line (pfile);
7344   cpp_message (pfile, 1, msg, arg1, arg2, arg3);
7345 }
7346
7347 /* Print error message but don't count it.  */
7348
7349 void
7350 cpp_warning (pfile, msg, arg1, arg2, arg3)
7351      cpp_reader *pfile;
7352      char *msg;
7353      char *arg1, *arg2, *arg3;
7354 {
7355   if (CPP_OPTIONS (pfile)->inhibit_warnings)
7356     return;
7357
7358   if (CPP_OPTIONS (pfile)->warnings_are_errors)
7359     pfile->errors++;
7360
7361   cpp_print_containing_files (pfile);
7362   cpp_print_file_and_line (pfile);
7363   cpp_message (pfile, 0, msg, arg1, arg2, arg3);
7364 }
7365
7366 /* Print an error message and maybe count it.  */
7367
7368 void
7369 cpp_pedwarn (pfile, msg, arg1, arg2, arg3)
7370      cpp_reader *pfile;
7371      char *msg;
7372      char *arg1, *arg2, *arg3;
7373 {
7374   if (CPP_OPTIONS (pfile)->pedantic_errors)
7375     cpp_error (pfile, msg, arg1, arg2, arg3);
7376   else
7377     cpp_warning (pfile, msg, arg1, arg2, arg3);
7378 }
7379
7380 void
7381 cpp_error_with_line (pfile, line, column, msg, arg1, arg2, arg3)
7382      cpp_reader *pfile;
7383      int line, column;
7384      char *msg;
7385      char *arg1, *arg2, *arg3;
7386 {
7387   int i;
7388   cpp_buffer *ip = cpp_file_buffer (pfile);
7389
7390   cpp_print_containing_files (pfile);
7391
7392   if (ip != NULL)
7393     cpp_file_line_for_message (pfile, ip->nominal_fname, line, column);
7394
7395   cpp_message (pfile, 1, msg, arg1, arg2, arg3);
7396 }
7397
7398 static void
7399 cpp_warning_with_line (pfile, line, column, msg, arg1, arg2, arg3)
7400      cpp_reader *pfile;
7401      int line, column;
7402      char *msg;
7403      char *arg1, *arg2, *arg3;
7404 {
7405   int i;
7406   cpp_buffer *ip;
7407
7408   if (CPP_OPTIONS (pfile)->inhibit_warnings)
7409     return;
7410
7411   if (CPP_OPTIONS (pfile)->warnings_are_errors)
7412     pfile->errors++;
7413
7414   cpp_print_containing_files (pfile);
7415
7416   ip = cpp_file_buffer (pfile);
7417
7418   if (ip != NULL)
7419     cpp_file_line_for_message (pfile, ip->nominal_fname, line, column);
7420
7421   cpp_message (pfile, 0, msg, arg1, arg2, arg3);
7422 }
7423
7424 void
7425 cpp_pedwarn_with_line (pfile, line, column, msg, arg1, arg2, arg3)
7426      cpp_reader *pfile;
7427      int line;
7428      char *msg;
7429      char *arg1, *arg2, *arg3;
7430 {
7431   if (CPP_OPTIONS (pfile)->pedantic_errors)
7432     cpp_error_with_line (pfile, column, line, msg, arg1, arg2, arg3);
7433   else
7434     cpp_warning_with_line (pfile, line, column, msg, arg1, arg2, arg3);
7435 }
7436
7437 /* Report a warning (or an error if pedantic_errors)
7438    giving specified file name and line number, not current.  */
7439
7440 void
7441 cpp_pedwarn_with_file_and_line (pfile, file, line, msg, arg1, arg2, arg3)
7442      cpp_reader *pfile;
7443      char *file;
7444      int line;
7445      char *msg;
7446      char *arg1, *arg2, *arg3;
7447 {
7448   if (!CPP_OPTIONS (pfile)->pedantic_errors
7449       && CPP_OPTIONS (pfile)->inhibit_warnings)
7450     return;
7451   if (file != NULL)
7452     cpp_file_line_for_message (pfile, file, line, -1);
7453   cpp_message (pfile, CPP_OPTIONS (pfile)->pedantic_errors,
7454                msg, arg1, arg2, arg3);
7455 }
7456
7457 /* This defines "errno" properly for VMS, and gives us EACCES.  */
7458 #include <errno.h>
7459 #ifndef errno
7460 extern int errno;
7461 #endif
7462
7463 #ifndef VMS
7464 #ifndef HAVE_STRERROR
7465 extern int sys_nerr;
7466 #if defined(bsd4_4)
7467 extern const char *const sys_errlist[];
7468 #else
7469 extern char *sys_errlist[];
7470 #endif
7471 #else   /* HAVE_STRERROR */
7472 char *strerror ();
7473 #endif
7474 #else   /* VMS */
7475 char *strerror (int,...);
7476 #endif
7477
7478 /* my_strerror - return the descriptive text associated with an
7479    `errno' code.  */
7480
7481 char *
7482 my_strerror (errnum)
7483      int errnum;
7484 {
7485   char *result;
7486
7487 #ifndef VMS
7488 #ifndef HAVE_STRERROR
7489   result = (char *) ((errnum < sys_nerr) ? sys_errlist[errnum] : 0);
7490 #else
7491   result = strerror (errnum);
7492 #endif
7493 #else   /* VMS */
7494   /* VAXCRTL's strerror() takes an optional second argument, which only
7495      matters when the first argument is EVMSERR.  However, it's simplest
7496      just to pass it unconditionally.  `vaxc$errno' is declared in
7497      <errno.h>, and maintained by the library in parallel with `errno'.
7498      We assume that caller's `errnum' either matches the last setting of
7499      `errno' by the library or else does not have the value `EVMSERR'.  */
7500
7501   result = strerror (errnum, vaxc$errno);
7502 #endif
7503
7504   if (!result)
7505     result = "undocumented I/O error";
7506
7507   return result;
7508 }
7509
7510 /* Error including a message from `errno'.  */
7511
7512 void
7513 cpp_error_from_errno (pfile, name)
7514      cpp_reader *pfile;
7515      char *name;
7516 {
7517   int i;
7518   cpp_buffer *ip = cpp_file_buffer (pfile);
7519
7520   cpp_print_containing_files (pfile);
7521
7522   if (ip != NULL)
7523     cpp_file_line_for_message (pfile, ip->nominal_fname, ip->lineno, -1);
7524
7525   cpp_message (pfile, 1, "%s: %s", name, my_strerror (errno));
7526 }
7527
7528 void
7529 cpp_perror_with_name (pfile, name)
7530      cpp_reader *pfile;
7531      char *name;
7532 {
7533   cpp_message (pfile, 1, "%s: %s: %s", progname, name, my_strerror (errno));
7534 }
7535
7536 /* TODO:
7537  * No pre-compiled header file support.
7538  *
7539  * Possibly different enum token codes for each C/C++ token.
7540  *
7541  * Should clean up remaining directives to that do_XXX functions
7542  *   only take two arguments and all have command_reads_line.
7543  *
7544  * Find and cleanup remaining uses of static variables,
7545  *
7546  * Support for trigraphs.
7547  *
7548  * Support -dM flag (dump_all_macros).
7549  *
7550  * Support for_lint flag.
7551  */