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