OSDN Git Service

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