OSDN Git Service

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