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