OSDN Git Service

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