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