OSDN Git Service

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