OSDN Git Service

1a38f01c2fb65fc769bcb23f05decda2089afeef
[pf3gnuchains/gcc-fork.git] / gcc / cpplib.c
1 /* CPP Library. (Directive handling.)
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4    Contributed by Per Bothner, 1994-95.
5    Based on CCCP program by Paul Rubin, June 1986
6    Adapted to ANSI C, Richard Stallman, Jan 1987
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24
25 #include "cpplib.h"
26 #include "cpphash.h"
27 #include "obstack.h"
28
29 /* Chained list of answers to an assertion.  */
30 struct answer
31 {
32   struct answer *next;
33   unsigned int count;
34   cpp_token first[1];
35 };
36
37 /* Stack of conditionals currently in progress
38    (including both successful and failing conditionals).  */
39 struct if_stack
40 {
41   struct if_stack *next;
42   unsigned int line;            /* Line where condition started.  */
43   const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
44   bool skip_elses;              /* Can future #else / #elif be skipped?  */
45   bool was_skipping;            /* If were skipping on entry.  */
46   int type;                     /* Most recent conditional, for diagnostics.  */
47 };
48
49 /* Contains a registered pragma or pragma namespace.  */
50 typedef void (*pragma_cb) PARAMS ((cpp_reader *));
51 struct pragma_entry
52 {
53   struct pragma_entry *next;
54   const cpp_hashnode *pragma;   /* Name and length.  */
55   int is_nspace;
56   union {
57     pragma_cb handler;
58     struct pragma_entry *space;
59   } u;
60 };
61
62 /* Values for the origin field of struct directive.  KANDR directives
63    come from traditional (K&R) C.  STDC89 directives come from the
64    1989 C standard.  EXTENSION directives are extensions.  */
65 #define KANDR           0
66 #define STDC89          1
67 #define EXTENSION       2
68
69 /* Values for the flags field of struct directive.  COND indicates a
70    conditional; IF_COND an opening conditional.  INCL means to treat
71    "..." and <...> as q-char and h-char sequences respectively.  IN_I
72    means this directive should be handled even if -fpreprocessed is in
73    effect (these are the directives with callback hooks).  */
74 #define COND            (1 << 0)
75 #define IF_COND         (1 << 1)
76 #define INCL            (1 << 2)
77 #define IN_I            (1 << 3)
78
79 /* Defines one #-directive, including how to handle it.  */
80 typedef void (*directive_handler) PARAMS ((cpp_reader *));
81 typedef struct directive directive;
82 struct directive
83 {
84   directive_handler handler;    /* Function to handle directive.  */
85   const U_CHAR *name;           /* Name of directive.  */
86   unsigned short length;        /* Length of name.  */
87   unsigned char origin;         /* Origin of directive.  */
88   unsigned char flags;          /* Flags describing this directive.  */
89 };
90
91 /* Forward declarations.  */
92
93 static void skip_rest_of_line   PARAMS ((cpp_reader *));
94 static void check_eol           PARAMS ((cpp_reader *));
95 static void start_directive     PARAMS ((cpp_reader *));
96 static void end_directive       PARAMS ((cpp_reader *, int));
97 static void directive_diagnostics
98         PARAMS ((cpp_reader *, const directive *, int));
99 static void run_directive       PARAMS ((cpp_reader *, int,
100                                          const char *, size_t));
101 static const cpp_token *glue_header_name PARAMS ((cpp_reader *));
102 static const cpp_token *parse_include PARAMS ((cpp_reader *));
103 static void push_conditional    PARAMS ((cpp_reader *, int, int,
104                                          const cpp_hashnode *));
105 static unsigned int read_flag   PARAMS ((cpp_reader *, unsigned int));
106 static int  strtoul_for_line    PARAMS ((const U_CHAR *, unsigned int,
107                                          unsigned long *));
108 static void do_diagnostic       PARAMS ((cpp_reader *, enum error_type, int));
109 static cpp_hashnode *lex_macro_node     PARAMS ((cpp_reader *));
110 static void do_include_common   PARAMS ((cpp_reader *, enum include_type));
111 static struct pragma_entry *lookup_pragma_entry
112   PARAMS ((struct pragma_entry *, const cpp_hashnode *pragma));
113 static struct pragma_entry *insert_pragma_entry
114   PARAMS ((cpp_reader *, struct pragma_entry **, const cpp_hashnode *,
115            pragma_cb));
116 static void do_pragma_once      PARAMS ((cpp_reader *));
117 static void do_pragma_poison    PARAMS ((cpp_reader *));
118 static void do_pragma_system_header     PARAMS ((cpp_reader *));
119 static void do_pragma_dependency        PARAMS ((cpp_reader *));
120 static const cpp_token *get_token_no_padding PARAMS ((cpp_reader *));
121 static const cpp_token *get__Pragma_string PARAMS ((cpp_reader *));
122 static void destringize_and_run PARAMS ((cpp_reader *, const cpp_string *));
123 static int parse_answer PARAMS ((cpp_reader *, struct answer **, int));
124 static cpp_hashnode *parse_assertion PARAMS ((cpp_reader *, struct answer **,
125                                               int));
126 static struct answer ** find_answer PARAMS ((cpp_hashnode *,
127                                              const struct answer *));
128 static void handle_assertion    PARAMS ((cpp_reader *, const char *, int));
129
130 /* This is the table of directive handlers.  It is ordered by
131    frequency of occurrence; the numbers at the end are directive
132    counts from all the source code I have lying around (egcs and libc
133    CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
134    pcmcia-cs-3.0.9).  This is no longer important as directive lookup
135    is now O(1).  All extensions other than #warning and #include_next
136    are deprecated.  The name is where the extension appears to have
137    come from.  */
138
139 #define DIRECTIVE_TABLE                                                 \
140 D(define,       T_DEFINE = 0,   KANDR,     IN_I)           /* 270554 */ \
141 D(include,      T_INCLUDE,      KANDR,     INCL)           /*  52262 */ \
142 D(endif,        T_ENDIF,        KANDR,     COND)           /*  45855 */ \
143 D(ifdef,        T_IFDEF,        KANDR,     COND | IF_COND) /*  22000 */ \
144 D(if,           T_IF,           KANDR,     COND | IF_COND) /*  18162 */ \
145 D(else,         T_ELSE,         KANDR,     COND)           /*   9863 */ \
146 D(ifndef,       T_IFNDEF,       KANDR,     COND | IF_COND) /*   9675 */ \
147 D(undef,        T_UNDEF,        KANDR,     IN_I)           /*   4837 */ \
148 D(line,         T_LINE,         KANDR,     IN_I)           /*   2465 */ \
149 D(elif,         T_ELIF,         STDC89,    COND)           /*    610 */ \
150 D(error,        T_ERROR,        STDC89,    0)              /*    475 */ \
151 D(pragma,       T_PRAGMA,       STDC89,    IN_I)           /*    195 */ \
152 D(warning,      T_WARNING,      EXTENSION, 0)              /*     22 */ \
153 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL)           /*     19 */ \
154 D(ident,        T_IDENT,        EXTENSION, IN_I)           /*     11 */ \
155 D(import,       T_IMPORT,       EXTENSION, INCL)           /* 0 ObjC */ \
156 D(assert,       T_ASSERT,       EXTENSION, 0)              /* 0 SVR4 */ \
157 D(unassert,     T_UNASSERT,     EXTENSION, 0)              /* 0 SVR4 */ \
158 SCCS_ENTRY                                                 /* 0 SVR4? */
159
160 /* #sccs is not always recognized.  */
161 #ifdef SCCS_DIRECTIVE
162 # define SCCS_ENTRY D(sccs, T_SCCS, EXTENSION, 0)
163 #else
164 # define SCCS_ENTRY /* nothing */
165 #endif
166
167 /* Use the table to generate a series of prototypes, an enum for the
168    directive names, and an array of directive handlers.  */
169
170 /* The directive-processing functions are declared to return int
171    instead of void, because some old compilers have trouble with
172    pointers to functions returning void.  */
173
174 /* Don't invoke CONCAT2 with any whitespace or K&R cc will fail.  */
175 #define D(name, t, o, f) static void CONCAT2(do_,name) PARAMS ((cpp_reader *));
176 DIRECTIVE_TABLE
177 #undef D
178
179 #define D(n, tag, o, f) tag,
180 enum
181 {
182   DIRECTIVE_TABLE
183   N_DIRECTIVES
184 };
185 #undef D
186
187 /* Don't invoke CONCAT2 with any whitespace or K&R cc will fail.  */
188 #define D(name, t, origin, flags) \
189 { CONCAT2(do_,name), (const U_CHAR *) STRINGX(name), \
190   sizeof STRINGX(name) - 1, origin, flags },
191 static const directive dtable[] =
192 {
193 DIRECTIVE_TABLE
194 };
195 #undef D
196 #undef DIRECTIVE_TABLE
197
198 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
199
200 /* Skip any remaining tokens in a directive.  */
201 static void
202 skip_rest_of_line (pfile)
203      cpp_reader *pfile;
204 {
205   /* Discard all stacked contexts.  */
206   while (pfile->context != &pfile->base_context)
207     _cpp_pop_context (pfile);
208
209   /* Sweep up all tokens remaining on the line.  */
210   if (! SEEN_EOL ())
211     while (_cpp_lex_token (pfile)->type != CPP_EOF)
212       ;
213 }
214
215 /* Ensure there are no stray tokens at the end of a directive.  */
216 static void
217 check_eol (pfile)
218      cpp_reader *pfile;
219 {
220   if (! SEEN_EOL () && _cpp_lex_token (pfile)->type != CPP_EOF)
221     cpp_pedwarn (pfile, "extra tokens at end of #%s directive",
222                  pfile->directive->name);
223 }
224
225 /* Called when entering a directive, _Pragma or command-line directive.  */
226 static void
227 start_directive (pfile)
228      cpp_reader *pfile;
229 {
230   /* Setup in-directive state.  */
231   pfile->state.in_directive = 1;
232   pfile->state.save_comments = 0;
233
234   /* Some handlers need the position of the # for diagnostics.  */
235   pfile->directive_line = pfile->line;
236 }
237
238 /* Called when leaving a directive, _Pragma or command-line directive.  */
239 static void
240 end_directive (pfile, skip_line)
241      cpp_reader *pfile;
242      int skip_line;
243 {
244   /* We don't skip for an assembler #.  */
245   if (skip_line)
246     {
247       skip_rest_of_line (pfile);
248       if (!pfile->keep_tokens)
249         {
250           pfile->cur_run = &pfile->base_run;
251           pfile->cur_token = pfile->base_run.base;
252         }
253     }
254
255   /* Restore state.  */
256   pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
257   pfile->state.in_directive = 0;
258   pfile->state.angled_headers = 0;
259   pfile->state.line_extension = 0;
260   pfile->directive = 0;
261 }
262
263 /* Output diagnostics for a directive DIR.  INDENTED is non-zero if
264    the '#' was indented.  */
265 static void
266 directive_diagnostics (pfile, dir, indented)
267      cpp_reader *pfile;
268      const directive *dir;
269      int indented;
270 {
271   if (pfile->state.line_extension)
272     {
273       if (CPP_PEDANTIC (pfile)
274           && ! pfile->state.skipping)
275         cpp_pedwarn (pfile, "style of line directive is a GCC extension");
276     }
277   else
278     {
279       /* Issue -pedantic warnings for extensions.  */
280       if (CPP_PEDANTIC (pfile)
281           && ! pfile->state.skipping
282           && dir->origin == EXTENSION)
283         cpp_pedwarn (pfile, "#%s is a GCC extension", dir->name);
284
285       /* Traditionally, a directive is ignored unless its # is in
286          column 1.  Therefore in code intended to work with K+R
287          compilers, directives added by C89 must have their #
288          indented, and directives present in traditional C must not.
289          This is true even of directives in skipped conditional
290          blocks.  */
291       if (CPP_WTRADITIONAL (pfile))
292         {
293           if (dir == &dtable[T_ELIF])
294             cpp_warning (pfile, "suggest not using #elif in traditional C");
295           else if (indented && dir->origin == KANDR)
296             cpp_warning (pfile,
297                          "traditional C ignores #%s with the # indented",
298                          dir->name);
299           else if (!indented && dir->origin != KANDR)
300             cpp_warning (pfile,
301                  "suggest hiding #%s from traditional C with an indented #",
302                          dir->name);
303         }
304     }
305 }
306
307 /* Check if we have a known directive.  INDENTED is non-zero if the
308    '#' of the directive was indented.  This function is in this file
309    to save unnecessarily exporting dtable etc. to cpplex.c.  Returns
310    non-zero if the line of tokens has been handled, zero if we should
311    continue processing the line.  */
312 int
313 _cpp_handle_directive (pfile, indented)
314      cpp_reader *pfile;
315      int indented;
316 {
317   const directive *dir = 0;
318   const cpp_token *dname;
319   int skip = 1;
320
321   start_directive (pfile);
322   dname = _cpp_lex_token (pfile);
323
324   if (dname->type == CPP_NAME)
325     {
326       if (dname->val.node->directive_index)
327         dir = &dtable[dname->val.node->directive_index - 1];
328     }
329   /* We do not recognise the # followed by a number extension in
330      assembler code.  */
331   else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
332     {
333       dir = &dtable[T_LINE];
334       pfile->state.line_extension = 1;
335     }
336
337   if (dir)
338     {
339       /* If we have a directive that is not an opening conditional,
340          invalidate any control macro.  */
341       if (! (dir->flags & IF_COND))
342         pfile->mi_valid = false;
343
344       /* Kluge alert.  In order to be sure that code like this
345
346          #define HASH #
347          HASH define foo bar
348
349          does not cause '#define foo bar' to get executed when
350          compiled with -save-temps, we recognize directives in
351          -fpreprocessed mode only if the # is in column 1.  cppmacro.c
352          puts a space in front of any '#' at the start of a macro.  */
353       if (CPP_OPTION (pfile, preprocessed)
354           && (indented || !(dir->flags & IN_I)))
355         {
356           skip = 0;
357           dir = 0;
358         }
359       else
360         {
361           /* In failed conditional groups, all non-conditional
362              directives are ignored.  Before doing that, whether
363              skipping or not, we should lex angle-bracketed headers
364              correctly, and maybe output some diagnostics.  */
365           pfile->state.angled_headers = dir->flags & INCL;
366           if (! CPP_OPTION (pfile, preprocessed))
367             directive_diagnostics (pfile, dir, indented);
368           if (pfile->state.skipping && !(dir->flags & COND))
369             dir = 0;
370         }
371     }
372   else if (dname->type == CPP_EOF)
373     ;   /* CPP_EOF is the "null directive".  */
374   else
375     {
376       /* An unknown directive.  Don't complain about it in assembly
377          source: we don't know where the comments are, and # may
378          introduce assembler pseudo-ops.  Don't complain about invalid
379          directives in skipped conditional groups (6.10 p4).  */
380       if (CPP_OPTION (pfile, lang) == CLK_ASM)
381         skip = 0;
382       else if (!pfile->state.skipping)
383         cpp_error (pfile, "invalid preprocessing directive #%s",
384                    cpp_token_as_text (pfile, dname));
385     }
386
387   if (dir)
388     {
389       pfile->directive = dir;
390       (*pfile->directive->handler) (pfile);
391     }
392   else if (skip == 0)
393     _cpp_backup_tokens (pfile, 1);
394
395   end_directive (pfile, skip);
396   return skip;
397 }
398
399 /* Directive handler wrapper used by the command line option
400    processor.  */
401 static void
402 run_directive (pfile, dir_no, buf, count)
403      cpp_reader *pfile;
404      int dir_no;
405      const char *buf;
406      size_t count;
407 {
408   cpp_push_buffer (pfile, (const U_CHAR *) buf, count,
409                    /* from_stage3 */ true, 1);
410   start_directive (pfile);
411   /* We don't want a leading # to be interpreted as a directive.  */
412   pfile->buffer->saved_flags = 0;
413   pfile->directive = &dtable[dir_no];
414   (void) (*pfile->directive->handler) (pfile);
415   end_directive (pfile, 1);
416   _cpp_pop_buffer (pfile);
417 }
418
419 /* Checks for validity the macro name in #define, #undef, #ifdef and
420    #ifndef directives.  */
421 static cpp_hashnode *
422 lex_macro_node (pfile)
423      cpp_reader *pfile;
424 {
425   cpp_hashnode *node;
426   const cpp_token *token = _cpp_lex_token (pfile);
427
428   /* The token immediately after #define must be an identifier.  That
429      identifier may not be "defined", per C99 6.10.8p4.
430      In C++, it may not be any of the "named operators" either,
431      per C++98 [lex.digraph], [lex.key].
432      Finally, the identifier may not have been poisoned.  (In that case
433      the lexer has issued the error message for us.)  */
434
435   if (token->type != CPP_NAME)
436     {
437       if (token->type == CPP_EOF)
438         cpp_error (pfile, "no macro name given in #%s directive",
439                    pfile->directive->name);
440       else if (token->flags & NAMED_OP)
441         cpp_error (pfile,
442            "\"%s\" cannot be used as a macro name as it is an operator in C++",
443                    NODE_NAME (token->val.node));
444       else
445         cpp_error (pfile, "macro names must be identifiers");
446
447       return 0;
448     }
449
450   node = token->val.node;
451   if (node->flags & NODE_POISONED)
452     return 0;
453
454   if (node == pfile->spec_nodes.n_defined)
455     {
456       cpp_error (pfile, "\"%s\" cannot be used as a macro name",
457                  NODE_NAME (node));
458       return 0;
459     }
460
461   return node;
462 }
463
464 /* Process a #define directive.  Most work is done in cppmacro.c.  */
465 static void
466 do_define (pfile)
467      cpp_reader *pfile;
468 {
469   cpp_hashnode *node = lex_macro_node (pfile);
470
471   if (node)
472     {
473       if (_cpp_create_definition (pfile, node))
474         if (pfile->cb.define)
475           (*pfile->cb.define) (pfile, pfile->directive_line, node);
476     }
477 }
478
479 /* Handle #undef.  Mark the identifier NT_VOID in the hash table.  */
480 static void
481 do_undef (pfile)
482      cpp_reader *pfile;
483 {
484   cpp_hashnode *node = lex_macro_node (pfile);  
485
486   /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified identifier
487      is not currently defined as a macro name.  */
488   if (node && node->type == NT_MACRO)
489     {
490       if (pfile->cb.undef)
491         (*pfile->cb.undef) (pfile, pfile->directive_line, node);
492
493       if (node->flags & NODE_WARN)
494         cpp_warning (pfile, "undefining \"%s\"", NODE_NAME (node));
495
496       _cpp_free_definition (node);
497     }
498   check_eol (pfile);
499 }
500
501 /* Helper routine used by parse_include.  Reinterpret the current line
502    as an h-char-sequence (< ... >); we are looking at the first token
503    after the <.  Returns the header as a token, or NULL on failure.  */
504 static const cpp_token *
505 glue_header_name (pfile)
506      cpp_reader *pfile;
507 {
508   cpp_token *header = NULL;
509   const cpp_token *token;
510   unsigned char *buffer;
511   size_t len, total_len = 0, capacity = 1024;
512
513   /* To avoid lexed tokens overwriting our glued name, we can only
514      allocate from the string pool once we've lexed everything.  */
515   buffer = (unsigned char *) xmalloc (capacity);
516   for (;;)
517     {
518       token = cpp_get_token (pfile);
519
520       if (token->type == CPP_GREATER || token->type == CPP_EOF)
521         break;
522
523       len = cpp_token_len (token);
524       if (total_len + len > capacity)
525         {
526           capacity = (capacity + len) * 2;
527           buffer = (unsigned char *) xrealloc (buffer, capacity);
528         }
529
530       if (token->flags & PREV_WHITE)
531         buffer[total_len++] = ' ';
532
533       total_len = cpp_spell_token (pfile, token, &buffer[total_len]) - buffer;
534     }
535
536   if (token->type == CPP_EOF)
537     cpp_error (pfile, "missing terminating > character");
538   else
539     {
540       unsigned char *token_mem = _cpp_unaligned_alloc (pfile, total_len + 1);
541       memcpy (token_mem, buffer, total_len);
542       token_mem[total_len] = '\0';
543
544       header = _cpp_temp_token (pfile);
545       header->type = CPP_HEADER_NAME;
546       header->flags = 0;
547       header->val.str.len = total_len;
548       header->val.str.text = token_mem;
549     }
550
551   free ((PTR) buffer);
552   return header;
553 }
554
555 /* Returns the header string of #include, #include_next, #import and
556    #pragma dependency.  Returns NULL on error.  */
557 static const cpp_token *
558 parse_include (pfile)
559      cpp_reader *pfile;
560 {
561   const unsigned char *dir;
562   const cpp_token *header;
563
564   if (pfile->directive == &dtable[T_PRAGMA])
565     dir = U"pragma dependency";
566   else
567     dir = pfile->directive->name;
568
569   /* Allow macro expansion.  */
570   header = cpp_get_token (pfile);
571   if (header->type != CPP_STRING && header->type != CPP_HEADER_NAME)
572     {
573       if (header->type != CPP_LESS)
574         {
575           cpp_error (pfile, "#%s expects \"FILENAME\" or <FILENAME>", dir);
576           return NULL;
577         }
578
579       header = glue_header_name (pfile);
580       if (header == NULL)
581         return header;
582     }
583
584   if (header->val.str.len == 0)
585     {
586       cpp_error (pfile, "empty file name in #%s", dir);
587       return NULL;
588     }
589
590   return header;
591 }
592
593 /* Handle #include, #include_next and #import.  */
594 static void
595 do_include_common (pfile, type)
596      cpp_reader *pfile;
597      enum include_type type;
598 {
599   const cpp_token *header;
600
601   /* For #include_next, if this is the primary source file, warn and
602      use the normal search logic.  */
603   if (type == IT_INCLUDE_NEXT && ! pfile->buffer->prev)
604     {
605       cpp_warning (pfile, "#include_next in primary source file");
606       type = IT_INCLUDE;
607     }
608   else if (type == IT_IMPORT && CPP_OPTION (pfile, warn_import))
609     {
610       CPP_OPTION (pfile, warn_import) = 0;
611       cpp_warning (pfile,
612            "#import is obsolete, use an #ifndef wrapper in the header file");
613     }
614
615   header = parse_include (pfile);
616   if (header)
617     {
618       /* Prevent #include recursion.  */
619       if (pfile->line_maps.depth >= CPP_STACK_MAX)
620         cpp_fatal (pfile, "#include nested too deeply");
621       else
622         {
623           check_eol (pfile);
624           /* Get out of macro context, if we are.  */
625           skip_rest_of_line (pfile);
626           if (pfile->cb.include)
627             (*pfile->cb.include) (pfile, pfile->directive_line,
628                                   pfile->directive->name, header);
629
630           _cpp_execute_include (pfile, header, type);
631         }
632     }
633 }
634
635 static void
636 do_include (pfile)
637      cpp_reader *pfile;
638 {
639   do_include_common (pfile, IT_INCLUDE);
640 }
641
642 static void
643 do_import (pfile)
644      cpp_reader *pfile;
645 {
646   do_include_common (pfile, IT_IMPORT);
647 }
648
649 static void
650 do_include_next (pfile)
651      cpp_reader *pfile;
652 {
653   do_include_common (pfile, IT_INCLUDE_NEXT);
654 }
655
656 /* Subroutine of do_line.  Read possible flags after file name.  LAST
657    is the last flag seen; 0 if this is the first flag. Return the flag
658    if it is valid, 0 at the end of the directive. Otherwise complain.  */
659 static unsigned int
660 read_flag (pfile, last)
661      cpp_reader *pfile;
662      unsigned int last;
663 {
664   const cpp_token *token = _cpp_lex_token (pfile);
665
666   if (token->type == CPP_NUMBER && token->val.str.len == 1)
667     {
668       unsigned int flag = token->val.str.text[0] - '0';
669
670       if (flag > last && flag <= 4
671           && (flag != 4 || last == 3)
672           && (flag != 2 || last == 0))
673         return flag;
674     }
675
676   if (token->type != CPP_EOF)
677     cpp_error (pfile, "invalid flag \"%s\" in line directive",
678                cpp_token_as_text (pfile, token));
679   return 0;
680 }
681
682 /* Another subroutine of do_line.  Convert a number in STR, of length
683    LEN, to binary; store it in NUMP, and return 0 if the number was
684    well-formed, 1 if not.  Temporary, hopefully.  */
685 static int
686 strtoul_for_line (str, len, nump)
687      const U_CHAR *str;
688      unsigned int len;
689      unsigned long *nump;
690 {
691   unsigned long reg = 0;
692   U_CHAR c;
693   while (len--)
694     {
695       c = *str++;
696       if (!ISDIGIT (c))
697         return 1;
698       reg *= 10;
699       reg += c - '0';
700     }
701   *nump = reg;
702   return 0;
703 }
704
705 /* Interpret #line command.
706    Note that the filename string (if any) is treated as if it were an
707    include filename.  That means no escape handling.  */
708 static void
709 do_line (pfile)
710      cpp_reader *pfile;
711 {
712   const cpp_token *token;
713   const char *new_file = pfile->map->to_file;
714   unsigned long new_lineno;
715   unsigned int cap, new_sysp = pfile->map->sysp;
716   enum lc_reason reason = LC_RENAME;
717
718   /* C99 raised the minimum limit on #line numbers.  */
719   cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
720
721   /* Putting this in _cpp_handle_directive risks two calls to
722      _cpp_backup_tokens in some circumstances, which can segfault.  */
723   if (pfile->state.line_extension)
724     _cpp_backup_tokens (pfile, 1);
725
726   /* #line commands expand macros.  */
727   token = cpp_get_token (pfile);
728   if (token->type != CPP_NUMBER
729       || strtoul_for_line (token->val.str.text, token->val.str.len,
730                            &new_lineno))
731     {
732       cpp_error (pfile, "\"%s\" after #line is not a positive integer",
733                  cpp_token_as_text (pfile, token));
734       return;
735     }      
736
737   if (CPP_PEDANTIC (pfile) && ! pfile->state.line_extension
738       && (new_lineno == 0 || new_lineno > cap))
739     cpp_pedwarn (pfile, "line number out of range");
740
741   token = cpp_get_token (pfile);
742   if (token->type == CPP_STRING)
743     {
744       new_file = (const char *) token->val.str.text;
745
746       /* Only accept flags for the # 55 form.  */
747       if (pfile->state.line_extension)
748         {
749           int flag;
750
751           new_sysp = 0;
752           flag = read_flag (pfile, 0);
753           if (flag == 1)
754             {
755               reason = LC_ENTER;
756               /* Fake an include for cpp_included ().  */
757               _cpp_fake_include (pfile, new_file);
758               flag = read_flag (pfile, flag);
759             }
760           else if (flag == 2)
761             {
762               reason = LC_LEAVE;
763               flag = read_flag (pfile, flag);
764             }
765           if (flag == 3)
766             {
767               new_sysp = 1;
768               flag = read_flag (pfile, flag);
769               if (flag == 4)
770                 new_sysp = 2;
771             }
772         }
773       check_eol (pfile);
774     }
775   else if (token->type != CPP_EOF)
776     {
777       cpp_error (pfile, "\"%s\" is not a valid filename",
778                  cpp_token_as_text (pfile, token));
779       return;
780     }
781
782   skip_rest_of_line (pfile);
783   _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
784 }
785
786 /* Arrange the file_change callback.  pfile->line has changed to
787    FILE_LINE of TO_FILE, for reason REASON.  SYSP is 1 for a system
788    header, 2 for a system header that needs to be extern "C" protected,
789    and zero otherwise.  */
790 void
791 _cpp_do_file_change (pfile, reason, to_file, file_line, sysp)
792      cpp_reader *pfile;
793      enum lc_reason reason;
794      const char *to_file;
795      unsigned int file_line;
796      unsigned int sysp;
797 {
798   pfile->map = add_line_map (&pfile->line_maps, reason, sysp,
799                              pfile->line, to_file, file_line);
800
801   if (pfile->cb.file_change)
802     (*pfile->cb.file_change) (pfile, pfile->map);
803 }
804
805 /* Report a warning or error detected by the program we are
806    processing.  Use the directive's tokens in the error message.  */
807 static void
808 do_diagnostic (pfile, code, print_dir)
809      cpp_reader *pfile;
810      enum error_type code;
811      int print_dir;
812 {
813   if (_cpp_begin_message (pfile, code, 0, 0))
814     {
815       if (print_dir)
816         fprintf (stderr, "#%s ", pfile->directive->name);
817       pfile->state.prevent_expansion++;
818       cpp_output_line (pfile, stderr);
819       pfile->state.prevent_expansion--;
820     }
821 }
822
823 static void
824 do_error (pfile)
825      cpp_reader *pfile;
826 {
827   do_diagnostic (pfile, ERROR, 1);
828 }
829
830 static void
831 do_warning (pfile)
832      cpp_reader *pfile;
833 {
834   /* We want #warning diagnostics to be emitted in system headers too.  */
835   do_diagnostic (pfile, WARNING_SYSHDR, 1);
836 }
837
838 /* Report program identification.  */
839 static void
840 do_ident (pfile)
841      cpp_reader *pfile;
842 {
843   const cpp_token *str = cpp_get_token (pfile);
844
845   if (str->type != CPP_STRING)
846     cpp_error (pfile, "invalid #ident directive");
847   else if (pfile->cb.ident)
848     (*pfile->cb.ident) (pfile, pfile->directive_line, &str->val.str);
849
850   check_eol (pfile);
851 }
852
853 /* Lookup a PRAGMA name in a singly-linked CHAIN.  Returns the
854    matching entry, or NULL if none is found.  The returned entry could
855    be the start of a namespace chain, or a pragma.  */
856 static struct pragma_entry *
857 lookup_pragma_entry (chain, pragma)
858      struct pragma_entry *chain;
859      const cpp_hashnode *pragma;
860 {
861   while (chain && chain->pragma != pragma)
862     chain = chain->next;
863
864   return chain;
865 }
866
867 /* Create and insert a pragma entry for NAME at the beginning of a
868    singly-linked CHAIN.  If handler is NULL, it is a namespace,
869    otherwise it is a pragma and its handler.  */
870 static struct pragma_entry *
871 insert_pragma_entry (pfile, chain, pragma, handler)
872      cpp_reader *pfile;
873      struct pragma_entry **chain;
874      const cpp_hashnode *pragma;
875      pragma_cb handler;
876 {
877   struct pragma_entry *new;
878
879   new = (struct pragma_entry *)
880     _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
881   new->pragma = pragma;
882   if (handler)
883     {
884       new->is_nspace = 0;
885       new->u.handler = handler;
886     }
887   else
888     {
889       new->is_nspace = 1;
890       new->u.space = NULL;
891     }
892
893   new->next = *chain;
894   *chain = new;
895   return new;
896 }
897
898 /* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
899    goes in the global namespace.  HANDLER is the handler it will call,
900    which must be non-NULL.  */
901 void
902 cpp_register_pragma (pfile, space, name, handler)
903      cpp_reader *pfile;
904      const char *space;
905      const char *name;
906      pragma_cb handler;
907 {
908   struct pragma_entry **chain = &pfile->pragmas;
909   struct pragma_entry *entry;
910   const cpp_hashnode *node;
911
912   if (!handler)
913     abort ();
914
915   if (space)
916     {
917       node = cpp_lookup (pfile, U space, strlen (space));
918       entry = lookup_pragma_entry (*chain, node);
919       if (!entry)
920         entry = insert_pragma_entry (pfile, chain, node, NULL);
921       else if (!entry->is_nspace)
922         goto clash;
923       chain = &entry->u.space;
924     }
925
926   /* Check for duplicates.  */
927   node = cpp_lookup (pfile, U name, strlen (name));
928   entry = lookup_pragma_entry (*chain, node);
929   if (entry)
930     {
931       if (entry->is_nspace)
932         clash:
933         cpp_ice (pfile,
934                  "registering \"%s\" as both a pragma and a pragma namespace",
935                  NODE_NAME (node));
936       else if (space)
937         cpp_ice (pfile, "#pragma %s %s is already registered", space, name);
938       else
939         cpp_ice (pfile, "#pragma %s is already registered", name);
940     }
941   else
942     insert_pragma_entry (pfile, chain, node, handler);
943 }
944
945 /* Register the pragmas the preprocessor itself handles.  */
946 void
947 _cpp_init_internal_pragmas (pfile)
948      cpp_reader *pfile;
949 {
950   /* Pragmas in the global namespace.  */
951   cpp_register_pragma (pfile, 0, "poison", do_pragma_poison);
952   cpp_register_pragma (pfile, 0, "once", do_pragma_once);
953
954   /* New GCC-specific pragmas should be put in the GCC namespace.  */
955   cpp_register_pragma (pfile, "GCC", "poison", do_pragma_poison);
956   cpp_register_pragma (pfile, "GCC", "system_header", do_pragma_system_header);
957   cpp_register_pragma (pfile, "GCC", "dependency", do_pragma_dependency);
958 }
959
960 /* Pragmata handling.  We handle some, and pass the rest on to the
961    front end.  C99 defines three pragmas and says that no macro
962    expansion is to be performed on them; whether or not macro
963    expansion happens for other pragmas is implementation defined.
964    This implementation never macro-expands the text after #pragma.  */
965 static void
966 do_pragma (pfile)
967      cpp_reader *pfile;
968 {
969   const struct pragma_entry *p = NULL;
970   const cpp_token *token;
971   unsigned int count = 1;
972
973   pfile->state.prevent_expansion++;
974
975   token = cpp_get_token (pfile);
976   if (token->type == CPP_NAME)
977     {
978       p = lookup_pragma_entry (pfile->pragmas, token->val.node);
979       if (p && p->is_nspace)
980         {
981           count = 2;
982           token = cpp_get_token (pfile);
983           if (token->type == CPP_NAME)
984             p = lookup_pragma_entry (p->u.space, token->val.node);
985           else
986             p = NULL;
987         }
988     }
989
990   /* FIXME.  This is an awful kludge to get the front ends to update
991      their notion of line number for diagnostic purposes.  The line
992      number should be passed to the handler and they should do it
993      themselves.  Stand-alone CPP must ignore us, otherwise it will
994      prefix the directive with spaces, hence the 1.  Ugh.  */
995   if (pfile->cb.line_change)
996     (*pfile->cb.line_change)(pfile, token, 1);
997
998   if (p)
999     (*p->u.handler) (pfile);
1000   else if (pfile->cb.def_pragma)
1001     {
1002       _cpp_backup_tokens (pfile, count);
1003       (*pfile->cb.def_pragma) (pfile, pfile->directive_line);
1004     }
1005
1006   pfile->state.prevent_expansion--;
1007 }
1008
1009 /* Handle #pragma once.  */
1010 static void
1011 do_pragma_once (pfile)
1012      cpp_reader *pfile;
1013 {
1014   cpp_warning (pfile, "#pragma once is obsolete");
1015  
1016   if (pfile->buffer->prev == NULL)
1017     cpp_warning (pfile, "#pragma once in main file");
1018   else
1019     _cpp_never_reread (pfile->buffer->inc);
1020
1021   check_eol (pfile);
1022 }
1023
1024 /* Handle #pragma poison, to poison one or more identifiers so that
1025    the lexer produces a hard error for each subsequent usage.  */
1026 static void
1027 do_pragma_poison (pfile)
1028      cpp_reader *pfile;
1029 {
1030   const cpp_token *tok;
1031   cpp_hashnode *hp;
1032
1033   pfile->state.poisoned_ok = 1;
1034   for (;;)
1035     {
1036       tok = _cpp_lex_token (pfile);
1037       if (tok->type == CPP_EOF)
1038         break;
1039       if (tok->type != CPP_NAME)
1040         {
1041           cpp_error (pfile, "invalid #pragma GCC poison directive");
1042           break;
1043         }
1044
1045       hp = tok->val.node;
1046       if (hp->flags & NODE_POISONED)
1047         continue;
1048
1049       if (hp->type == NT_MACRO)
1050         cpp_warning (pfile, "poisoning existing macro \"%s\"", NODE_NAME (hp));
1051       _cpp_free_definition (hp);
1052       hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1053     }
1054   pfile->state.poisoned_ok = 0;
1055 }
1056
1057 /* Mark the current header as a system header.  This will suppress
1058    some categories of warnings (notably those from -pedantic).  It is
1059    intended for use in system libraries that cannot be implemented in
1060    conforming C, but cannot be certain that their headers appear in a
1061    system include directory.  To prevent abuse, it is rejected in the
1062    primary source file.  */
1063 static void
1064 do_pragma_system_header (pfile)
1065      cpp_reader *pfile;
1066 {
1067   cpp_buffer *buffer = pfile->buffer;
1068
1069   if (buffer->prev == 0)
1070     cpp_warning (pfile, "#pragma system_header ignored outside include file");
1071   else
1072     {
1073       check_eol (pfile);
1074       skip_rest_of_line (pfile);
1075       cpp_make_system_header (pfile, 1, 0);
1076     }
1077 }
1078
1079 /* Check the modified date of the current include file against a specified
1080    file. Issue a diagnostic, if the specified file is newer. We use this to
1081    determine if a fixed header should be refixed.  */
1082 static void
1083 do_pragma_dependency (pfile)
1084      cpp_reader *pfile;
1085 {
1086   const cpp_token *header;
1087   int ordering;
1088  
1089   header = parse_include (pfile);
1090   if (!header)
1091     return;
1092
1093   ordering = _cpp_compare_file_date (pfile, header);
1094   if (ordering < 0)
1095     cpp_warning (pfile, "cannot find source %s",
1096                  cpp_token_as_text (pfile, header));
1097   else if (ordering > 0)
1098     {
1099       cpp_warning (pfile, "current file is older than %s",
1100                    cpp_token_as_text (pfile, header));
1101       if (cpp_get_token (pfile)->type != CPP_EOF)
1102         {
1103           _cpp_backup_tokens (pfile, 1);
1104           do_diagnostic (pfile, WARNING, 0);
1105         }
1106     }
1107 }
1108
1109 /* Get a token but skip padding.  */
1110 static const cpp_token *
1111 get_token_no_padding (pfile)
1112      cpp_reader *pfile;
1113 {
1114   for (;;)
1115     {
1116       const cpp_token *result = cpp_get_token (pfile);
1117       if (result->type != CPP_PADDING)
1118         return result;
1119     }
1120 }
1121
1122 /* Check syntax is "(string-literal)".  Returns the string on success,
1123    or NULL on failure.  */
1124 static const cpp_token *
1125 get__Pragma_string (pfile)
1126      cpp_reader *pfile;
1127 {
1128   const cpp_token *string;
1129
1130   if (get_token_no_padding (pfile)->type != CPP_OPEN_PAREN)
1131     return NULL;
1132
1133   string = get_token_no_padding (pfile);
1134   if (string->type != CPP_STRING && string->type != CPP_WSTRING)
1135     return NULL;
1136
1137   if (get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
1138     return NULL;
1139
1140   return string;
1141 }
1142
1143 /* Destringize IN into a temporary buffer, by removing the first \ of
1144    \" and \\ sequences, and process the result as a #pragma directive.  */
1145 static void
1146 destringize_and_run (pfile, in)
1147      cpp_reader *pfile;
1148      const cpp_string *in;
1149 {
1150   const unsigned char *src, *limit;
1151   char *dest, *result;
1152
1153   dest = result = alloca (in->len + 1);
1154   for (src = in->text, limit = src + in->len; src < limit;)
1155     {
1156       /* We know there is a character following the backslash.  */
1157       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1158         src++;
1159       *dest++ = *src++;
1160     }
1161   *dest = '\0';
1162
1163   run_directive (pfile, T_PRAGMA, result, dest - result);
1164 }
1165
1166 /* Handle the _Pragma operator.  */
1167 void
1168 _cpp_do__Pragma (pfile)
1169      cpp_reader *pfile;
1170 {
1171   const cpp_token *string = get__Pragma_string (pfile);
1172
1173   if (!string)
1174     cpp_error (pfile, "_Pragma takes a parenthesized string literal");
1175   else
1176     {
1177       /* Ideally, we'd like
1178                         token1 _Pragma ("foo") token2
1179          to be output as
1180                         token1
1181                         # 7 "file.c"
1182                         #pragma foo
1183                         # 7 "file.c"
1184                                                token2
1185          Getting these correct line markers is a little tricky.  */
1186
1187       unsigned int orig_line = pfile->line;
1188       destringize_and_run (pfile, &string->val.str);
1189       pfile->line = orig_line;
1190       pfile->buffer->saved_flags = BOL;
1191     }
1192 }
1193
1194 /* Just ignore #sccs, on systems where we define it at all.  */
1195 #ifdef SCCS_DIRECTIVE
1196 static void
1197 do_sccs (pfile)
1198      cpp_reader *pfile ATTRIBUTE_UNUSED;
1199 {
1200 }
1201 #endif
1202
1203 /* Handle #ifdef.  */
1204 static void
1205 do_ifdef (pfile)
1206      cpp_reader *pfile;
1207 {
1208   int skip = 1;
1209
1210   if (! pfile->state.skipping)
1211     {
1212       const cpp_hashnode *node = lex_macro_node (pfile);
1213
1214       if (node)
1215         skip = node->type != NT_MACRO;
1216
1217       if (node)
1218         check_eol (pfile);
1219     }
1220
1221   push_conditional (pfile, skip, T_IFDEF, 0);
1222 }
1223
1224 /* Handle #ifndef.  */
1225 static void
1226 do_ifndef (pfile)
1227      cpp_reader *pfile;
1228 {
1229   int skip = 1;
1230   const cpp_hashnode *node = 0;
1231
1232   if (! pfile->state.skipping)
1233     {
1234       node = lex_macro_node (pfile);
1235       if (node)
1236         skip = node->type == NT_MACRO;
1237
1238       if (node)
1239         check_eol (pfile);
1240     }
1241
1242   push_conditional (pfile, skip, T_IFNDEF, node);
1243 }
1244
1245 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1246    pfile->mi_ind_cmacro so we can handle multiple-include
1247    optimisations.  If macro expansion occurs in the expression, we
1248    cannot treat it as a controlling conditional, since the expansion
1249    could change in the future.  That is handled by cpp_get_token.  */
1250 static void
1251 do_if (pfile)
1252      cpp_reader *pfile;
1253 {
1254   int skip = 1;
1255
1256   if (! pfile->state.skipping)
1257     skip = _cpp_parse_expr (pfile) == 0;
1258
1259   push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1260 }
1261
1262 /* Flip skipping state if appropriate and continue without changing
1263    if_stack; this is so that the error message for missing #endif's
1264    etc. will point to the original #if.  */
1265 static void
1266 do_else (pfile)
1267      cpp_reader *pfile;
1268 {
1269   cpp_buffer *buffer = pfile->buffer;
1270   struct if_stack *ifs = buffer->if_stack;
1271
1272   if (ifs == NULL)
1273     cpp_error (pfile, "#else without #if");
1274   else
1275     {
1276       if (ifs->type == T_ELSE)
1277         {
1278           cpp_error (pfile, "#else after #else");
1279           cpp_error_with_line (pfile, ifs->line, 0,
1280                                "the conditional began here");
1281         }
1282       ifs->type = T_ELSE;
1283
1284       /* Skip any future (erroneous) #elses or #elifs.  */
1285       pfile->state.skipping = ifs->skip_elses;
1286       ifs->skip_elses = true;
1287
1288       /* Invalidate any controlling macro.  */
1289       ifs->mi_cmacro = 0;
1290
1291       /* Only check EOL if was not originally skipping.  */
1292       if (!ifs->was_skipping)
1293         check_eol (pfile);
1294     }
1295 }
1296
1297 /* Handle a #elif directive by not changing if_stack either.  See the
1298    comment above do_else.  */
1299 static void
1300 do_elif (pfile)
1301      cpp_reader *pfile;
1302 {
1303   cpp_buffer *buffer = pfile->buffer;
1304   struct if_stack *ifs = buffer->if_stack;
1305
1306   if (ifs == NULL)
1307     cpp_error (pfile, "#elif without #if");
1308   else
1309     {
1310       if (ifs->type == T_ELSE)
1311         {
1312           cpp_error (pfile, "#elif after #else");
1313           cpp_error_with_line (pfile, ifs->line, 0,
1314                                "the conditional began here");
1315         }
1316       ifs->type = T_ELIF;
1317
1318       /* Only evaluate this if we aren't skipping elses.  During
1319          evaluation, set skipping to false to get lexer warnings.  */
1320       if (ifs->skip_elses)
1321         pfile->state.skipping = 1;
1322       else
1323         {
1324           pfile->state.skipping = 0;
1325           pfile->state.skipping = ! _cpp_parse_expr (pfile);
1326           ifs->skip_elses = ! pfile->state.skipping;
1327         }
1328
1329       /* Invalidate any controlling macro.  */
1330       ifs->mi_cmacro = 0;
1331     }
1332 }
1333
1334 /* #endif pops the if stack and resets pfile->state.skipping.  */
1335 static void
1336 do_endif (pfile)
1337      cpp_reader *pfile;
1338 {
1339   cpp_buffer *buffer = pfile->buffer;
1340   struct if_stack *ifs = buffer->if_stack;
1341
1342   if (ifs == NULL)
1343     cpp_error (pfile, "#endif without #if");
1344   else
1345     {
1346       /* Only check EOL if was not originally skipping.  */
1347       if (!ifs->was_skipping)
1348         check_eol (pfile);
1349
1350       /* If potential control macro, we go back outside again.  */
1351       if (ifs->next == 0 && ifs->mi_cmacro)
1352         {
1353           pfile->mi_valid = true;
1354           pfile->mi_cmacro = ifs->mi_cmacro;
1355         }
1356
1357       buffer->if_stack = ifs->next;
1358       pfile->state.skipping = ifs->was_skipping;
1359       obstack_free (&pfile->buffer_ob, ifs);
1360     }
1361 }
1362
1363 /* Push an if_stack entry for a preprocessor conditional, and set
1364    pfile->state.skipping to SKIP.  If TYPE indicates the conditional
1365    is #if or #ifndef, CMACRO is a potentially controlling macro, and
1366    we need to check here that we are at the top of the file.  */
1367 static void
1368 push_conditional (pfile, skip, type, cmacro)
1369      cpp_reader *pfile;
1370      int skip;
1371      int type;
1372      const cpp_hashnode *cmacro;
1373 {
1374   struct if_stack *ifs;
1375   cpp_buffer *buffer = pfile->buffer;
1376
1377   ifs = xobnew (&pfile->buffer_ob, struct if_stack);
1378   ifs->line = pfile->directive_line;
1379   ifs->next = buffer->if_stack;
1380   ifs->skip_elses = pfile->state.skipping || !skip;
1381   ifs->was_skipping = pfile->state.skipping;
1382   ifs->type = type;
1383   /* This condition is effectively a test for top-of-file.  */
1384   if (pfile->mi_valid && pfile->mi_cmacro == 0)
1385     ifs->mi_cmacro = cmacro;
1386   else
1387     ifs->mi_cmacro = 0;
1388
1389   pfile->state.skipping = skip;
1390   buffer->if_stack = ifs;
1391 }
1392
1393 /* Read the tokens of the answer into the macro pool, in a directive
1394    of type TYPE.  Only commit the memory if we intend it as permanent
1395    storage, i.e. the #assert case.  Returns 0 on success, and sets
1396    ANSWERP to point to the answer.  */
1397 static int
1398 parse_answer (pfile, answerp, type)
1399      cpp_reader *pfile;
1400      struct answer **answerp;
1401      int type;
1402 {
1403   const cpp_token *paren;
1404   struct answer *answer;
1405   unsigned int acount;
1406
1407   /* In a conditional, it is legal to not have an open paren.  We
1408      should save the following token in this case.  */
1409   paren = cpp_get_token (pfile);
1410
1411   /* If not a paren, see if we're OK.  */
1412   if (paren->type != CPP_OPEN_PAREN)
1413     {
1414       /* In a conditional no answer is a test for any answer.  It
1415          could be followed by any token.  */
1416       if (type == T_IF)
1417         {
1418           _cpp_backup_tokens (pfile, 1);
1419           return 0;
1420         }
1421
1422       /* #unassert with no answer is valid - it removes all answers.  */
1423       if (type == T_UNASSERT && paren->type == CPP_EOF)
1424         return 0;
1425
1426       cpp_error (pfile, "missing '(' after predicate");
1427       return 1;
1428     }
1429
1430   for (acount = 0;; acount++)
1431     {
1432       size_t room_needed;
1433       const cpp_token *token = cpp_get_token (pfile);
1434       cpp_token *dest;
1435
1436       if (token->type == CPP_CLOSE_PAREN)
1437         break;
1438
1439       if (token->type == CPP_EOF)
1440         {
1441           cpp_error (pfile, "missing ')' to complete answer");
1442           return 1;
1443         }
1444
1445       /* struct answer includes the space for one token.  */
1446       room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
1447
1448       if (BUFF_ROOM (pfile->a_buff) < room_needed)
1449         _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
1450
1451       dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
1452       *dest = *token;
1453
1454       /* Drop whitespace at start, for answer equivalence purposes.  */
1455       if (acount == 0)
1456         dest->flags &= ~PREV_WHITE;
1457     }
1458
1459   if (acount == 0)
1460     {
1461       cpp_error (pfile, "predicate's answer is empty");
1462       return 1;
1463     }
1464
1465   answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
1466   answer->count = acount;
1467   answer->next = NULL;
1468   *answerp = answer;
1469
1470   return 0;
1471 }
1472
1473 /* Parses an assertion directive of type TYPE, returning a pointer to
1474    the hash node of the predicate, or 0 on error.  If an answer was
1475    supplied, it is placed in ANSWERP, otherwise it is set to 0.  */
1476 static cpp_hashnode *
1477 parse_assertion (pfile, answerp, type)
1478      cpp_reader *pfile;
1479      struct answer **answerp;
1480      int type;
1481 {
1482   cpp_hashnode *result = 0;
1483   const cpp_token *predicate;
1484
1485   /* We don't expand predicates or answers.  */
1486   pfile->state.prevent_expansion++;
1487
1488   *answerp = 0;
1489   predicate = cpp_get_token (pfile);
1490   if (predicate->type == CPP_EOF)
1491     cpp_error (pfile, "assertion without predicate");
1492   else if (predicate->type != CPP_NAME)
1493     cpp_error (pfile, "predicate must be an identifier");
1494   else if (parse_answer (pfile, answerp, type) == 0)
1495     {
1496       unsigned int len = NODE_LEN (predicate->val.node);
1497       unsigned char *sym = alloca (len + 1);
1498
1499       /* Prefix '#' to get it out of macro namespace.  */
1500       sym[0] = '#';
1501       memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
1502       result = cpp_lookup (pfile, sym, len + 1);
1503     }
1504
1505   pfile->state.prevent_expansion--;
1506   return result;
1507 }
1508
1509 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
1510    or a pointer to NULL if the answer is not in the chain.  */
1511 static struct answer **
1512 find_answer (node, candidate)
1513      cpp_hashnode *node;
1514      const struct answer *candidate;
1515 {
1516   unsigned int i;
1517   struct answer **result;
1518
1519   for (result = &node->value.answers; *result; result = &(*result)->next)
1520     {
1521       struct answer *answer = *result;
1522
1523       if (answer->count == candidate->count)
1524         {
1525           for (i = 0; i < answer->count; i++)
1526             if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
1527               break;
1528
1529           if (i == answer->count)
1530             break;
1531         }
1532     }
1533
1534   return result;
1535 }
1536
1537 /* Test an assertion within a preprocessor conditional.  Returns
1538    non-zero on failure, zero on success.  On success, the result of
1539    the test is written into VALUE.  */
1540 int
1541 _cpp_test_assertion (pfile, value)
1542      cpp_reader *pfile;
1543      int *value;
1544 {
1545   struct answer *answer;
1546   cpp_hashnode *node;
1547
1548   node = parse_assertion (pfile, &answer, T_IF);
1549   if (node)
1550     *value = (node->type == NT_ASSERTION &&
1551               (answer == 0 || *find_answer (node, answer) != 0));
1552
1553   /* We don't commit the memory for the answer - it's temporary only.  */
1554   return node == 0;
1555 }
1556
1557 /* Handle #assert.  */
1558 static void
1559 do_assert (pfile)
1560      cpp_reader *pfile;
1561 {
1562   struct answer *new_answer;
1563   cpp_hashnode *node;
1564   
1565   node = parse_assertion (pfile, &new_answer, T_ASSERT);
1566   if (node)
1567     {
1568       /* Place the new answer in the answer list.  First check there
1569          is not a duplicate.  */
1570       new_answer->next = 0;
1571       if (node->type == NT_ASSERTION)
1572         {
1573           if (*find_answer (node, new_answer))
1574             {
1575               cpp_warning (pfile, "\"%s\" re-asserted", NODE_NAME (node) + 1);
1576               return;
1577             }
1578           new_answer->next = node->value.answers;
1579         }
1580
1581       node->type = NT_ASSERTION;
1582       node->value.answers = new_answer;
1583       BUFF_FRONT (pfile->a_buff) += (sizeof (struct answer)
1584                                      + (new_answer->count - 1)
1585                                      * sizeof (cpp_token));
1586       check_eol (pfile);
1587     }
1588 }
1589
1590 /* Handle #unassert.  */
1591 static void
1592 do_unassert (pfile)
1593      cpp_reader *pfile;
1594 {
1595   cpp_hashnode *node;
1596   struct answer *answer;
1597   
1598   node = parse_assertion (pfile, &answer, T_UNASSERT);
1599   /* It isn't an error to #unassert something that isn't asserted.  */
1600   if (node && node->type == NT_ASSERTION)
1601     {
1602       if (answer)
1603         {
1604           struct answer **p = find_answer (node, answer), *temp;
1605
1606           /* Remove the answer from the list.  */
1607           temp = *p;
1608           if (temp)
1609             *p = temp->next;
1610
1611           /* Did we free the last answer?  */
1612           if (node->value.answers == 0)
1613             node->type = NT_VOID;
1614
1615           check_eol (pfile);
1616         }
1617       else
1618         _cpp_free_definition (node);
1619     }
1620
1621   /* We don't commit the memory for the answer - it's temporary only.  */
1622 }
1623
1624 /* These are for -D, -U, -A.  */
1625
1626 /* Process the string STR as if it appeared as the body of a #define.
1627    If STR is just an identifier, define it with value 1.
1628    If STR has anything after the identifier, then it should
1629    be identifier=definition.  */
1630 void
1631 cpp_define (pfile, str)
1632      cpp_reader *pfile;
1633      const char *str;
1634 {
1635   char *buf, *p;
1636   size_t count;
1637
1638   /* Copy the entire option so we can modify it. 
1639      Change the first "=" in the string to a space.  If there is none,
1640      tack " 1" on the end.  */
1641
1642   count = strlen (str);
1643   buf = (char *) alloca (count + 3);
1644   memcpy (buf, str, count);
1645
1646   p = strchr (str, '=');
1647   if (p)
1648     buf[p - str] = ' ';
1649   else
1650     {
1651       buf[count++] = ' ';
1652       buf[count++] = '1';
1653     }
1654   buf[count] = '\0';
1655
1656   run_directive (pfile, T_DEFINE, buf, count);
1657 }
1658
1659 /* Slight variant of the above for use by initialize_builtins.  */
1660 void
1661 _cpp_define_builtin (pfile, str)
1662      cpp_reader *pfile;
1663      const char *str;
1664 {
1665   run_directive (pfile, T_DEFINE, str, strlen (str));
1666 }
1667
1668 /* Process MACRO as if it appeared as the body of an #undef.  */
1669 void
1670 cpp_undef (pfile, macro)
1671      cpp_reader *pfile;
1672      const char *macro;
1673 {
1674   run_directive (pfile, T_UNDEF, macro, strlen (macro));
1675 }
1676
1677 /* Process the string STR as if it appeared as the body of a #assert.  */
1678 void
1679 cpp_assert (pfile, str)
1680      cpp_reader *pfile;
1681      const char *str;
1682 {
1683   handle_assertion (pfile, str, T_ASSERT);
1684 }
1685
1686 /* Process STR as if it appeared as the body of an #unassert.  */
1687 void
1688 cpp_unassert (pfile, str)
1689      cpp_reader *pfile;
1690      const char *str;
1691 {
1692   handle_assertion (pfile, str, T_UNASSERT);
1693 }  
1694
1695 /* Common code for cpp_assert (-A) and cpp_unassert (-A-).  */
1696 static void
1697 handle_assertion (pfile, str, type)
1698      cpp_reader *pfile;
1699      const char *str;
1700      int type;
1701 {
1702   size_t count = strlen (str);
1703   const char *p = strchr (str, '=');
1704
1705   if (p)
1706     {
1707       /* Copy the entire option so we can modify it.  Change the first
1708          "=" in the string to a '(', and tack a ')' on the end.  */
1709       char *buf = (char *) alloca (count + 2);
1710
1711       memcpy (buf, str, count);
1712       buf[p - str] = '(';
1713       buf[count++] = ')';
1714       buf[count] = '\0';
1715       str = buf;
1716     }
1717
1718   run_directive (pfile, type, str, count);
1719 }
1720
1721 /* The number of errors for a given reader.  */
1722 unsigned int
1723 cpp_errors (pfile)
1724      cpp_reader *pfile;
1725 {
1726   return pfile->errors;
1727 }
1728
1729 /* The options structure.  */
1730 cpp_options *
1731 cpp_get_options (pfile)
1732      cpp_reader *pfile;
1733 {
1734   return &pfile->opts;
1735 }
1736
1737 /* The callbacks structure.  */
1738 cpp_callbacks *
1739 cpp_get_callbacks (pfile)
1740      cpp_reader *pfile;
1741 {
1742   return &pfile->cb;
1743 }
1744
1745 /* The line map set.  */
1746 const struct line_maps *
1747 cpp_get_line_maps (pfile)
1748      cpp_reader *pfile;
1749 {
1750   return &pfile->line_maps;
1751 }
1752
1753 /* Copy the given callbacks structure to our own.  */
1754 void
1755 cpp_set_callbacks (pfile, cb)
1756      cpp_reader *pfile;
1757      cpp_callbacks *cb;
1758 {
1759   pfile->cb = *cb;
1760 }
1761
1762 /* Push a new buffer on the buffer stack.  Returns the new buffer; it
1763    doesn't fail.  It does not generate a file change call back; that
1764    is the responsibility of the caller.  */
1765 cpp_buffer *
1766 cpp_push_buffer (pfile, buffer, len, from_stage3, return_at_eof)
1767      cpp_reader *pfile;
1768      const U_CHAR *buffer;
1769      size_t len;
1770      int from_stage3;
1771      int return_at_eof;
1772 {
1773   cpp_buffer *new = xobnew (&pfile->buffer_ob, cpp_buffer);
1774
1775   /* Clears, amongst other things, if_stack and mi_cmacro.  */
1776   memset (new, 0, sizeof (cpp_buffer));
1777
1778   new->line_base = new->buf = new->cur = buffer;
1779   new->rlimit = buffer + len;
1780   new->from_stage3 = from_stage3;
1781   new->prev = pfile->buffer;
1782   new->return_at_eof = return_at_eof;
1783   new->saved_flags = BOL;
1784
1785   pfile->buffer = new;
1786
1787   return new;
1788 }
1789
1790 /* If called from do_line, pops a single buffer.  Otherwise pops all
1791    buffers until a real file is reached.  Generates appropriate
1792    call-backs.  */
1793 void
1794 _cpp_pop_buffer (pfile)
1795      cpp_reader *pfile;
1796 {
1797   cpp_buffer *buffer = pfile->buffer;
1798   struct if_stack *ifs;
1799   bool pushed = false;
1800
1801   /* Walk back up the conditional stack till we reach its level at
1802      entry to this file, issuing error messages.  */
1803   for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
1804     cpp_error_with_line (pfile, ifs->line, 0,
1805                          "unterminated #%s", dtable[ifs->type].name);
1806
1807   /* In case of a missing #endif.  */
1808   pfile->state.skipping = 0;
1809
1810   /* Update the reader's buffer before _cpp_do_file_change.  */
1811   pfile->buffer = buffer->prev;
1812
1813   if (buffer->inc)
1814     pushed = _cpp_pop_file_buffer (pfile, buffer->inc);
1815
1816   if (!pushed)
1817     obstack_free (&pfile->buffer_ob, buffer);
1818 }
1819
1820 /* Enter all recognised directives in the hash table.  */
1821 void
1822 _cpp_init_directives (pfile)
1823      cpp_reader *pfile;
1824 {
1825   unsigned int i;
1826   cpp_hashnode *node;
1827
1828   for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
1829     {
1830       node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
1831       node->directive_index = i + 1;
1832     }
1833 }