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