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