gcc50/csu: Skip depends step to avoid possible race
[dragonfly.git] / contrib / gcc-4.4 / libcpp / directives.c
1 /* CPP Library. (Directive handling.)
2    Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005,
4    2007, 2008, 2009 Free Software Foundation, Inc.
5    Contributed by Per Bothner, 1994-95.
6    Based on CCCP program by Paul Rubin, June 1986
7    Adapted to ANSI C, Richard Stallman, Jan 1987
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 3, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "cpplib.h"
26 #include "internal.h"
27 #include "mkdeps.h"
28 #include "obstack.h"
29
30 /* Stack of conditionals currently in progress
31    (including both successful and failing conditionals).  */
32 struct if_stack
33 {
34   struct if_stack *next;
35   linenum_type line;            /* Line where condition started.  */
36   const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
37   bool skip_elses;              /* Can future #else / #elif be skipped?  */
38   bool was_skipping;            /* If were skipping on entry.  */
39   int type;                     /* Most recent conditional for diagnostics.  */
40 };
41
42 /* Contains a registered pragma or pragma namespace.  */
43 typedef void (*pragma_cb) (cpp_reader *);
44 struct pragma_entry
45 {
46   struct pragma_entry *next;
47   const cpp_hashnode *pragma;   /* Name and length.  */
48   bool is_nspace;
49   bool is_internal;
50   bool is_deferred;
51   bool allow_expansion;
52   union {
53     pragma_cb handler;
54     struct pragma_entry *space;
55     unsigned int ident;
56   } u;
57 };
58
59 /* Values for the origin field of struct directive.  KANDR directives
60    come from traditional (K&R) C.  STDC89 directives come from the
61    1989 C standard.  EXTENSION directives are extensions.  */
62 #define KANDR           0
63 #define STDC89          1
64 #define EXTENSION       2
65
66 /* Values for the flags field of struct directive.  COND indicates a
67    conditional; IF_COND an opening conditional.  INCL means to treat
68    "..." and <...> as q-char and h-char sequences respectively.  IN_I
69    means this directive should be handled even if -fpreprocessed is in
70    effect (these are the directives with callback hooks).
71
72    EXPAND is set on directives that are always macro-expanded.  */
73 #define COND            (1 << 0)
74 #define IF_COND         (1 << 1)
75 #define INCL            (1 << 2)
76 #define IN_I            (1 << 3)
77 #define EXPAND          (1 << 4)
78 #define DEPRECATED      (1 << 5)
79
80 /* Defines one #-directive, including how to handle it.  */
81 typedef void (*directive_handler) (cpp_reader *);
82 typedef struct directive directive;
83 struct directive
84 {
85   directive_handler handler;    /* Function to handle directive.  */
86   const uchar *name;            /* Name of directive.  */
87   unsigned short length;        /* Length of name.  */
88   unsigned char origin;         /* Origin of directive.  */
89   unsigned char flags;          /* Flags describing this directive.  */
90 };
91
92 /* Forward declarations.  */
93
94 static void skip_rest_of_line (cpp_reader *);
95 static void check_eol (cpp_reader *);
96 static void start_directive (cpp_reader *);
97 static void prepare_directive_trad (cpp_reader *);
98 static void end_directive (cpp_reader *, int);
99 static void directive_diagnostics (cpp_reader *, const directive *, int);
100 static void run_directive (cpp_reader *, int, const char *, size_t);
101 static char *glue_header_name (cpp_reader *);
102 static const char *parse_include (cpp_reader *, int *, const cpp_token ***);
103 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
104 static unsigned int read_flag (cpp_reader *, unsigned int);
105 static bool strtolinenum (const uchar *, size_t, linenum_type *, bool *);
106 static void do_diagnostic (cpp_reader *, int, int);
107 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
108 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
109 static void do_include_common (cpp_reader *, enum include_type);
110 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
111                                                  const cpp_hashnode *);
112 static int count_registered_pragmas (struct pragma_entry *);
113 static char ** save_registered_pragmas (struct pragma_entry *, char **);
114 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
115                                            char **);
116 static void do_pragma_once (cpp_reader *);
117 static void do_pragma_poison (cpp_reader *);
118 static void do_pragma_system_header (cpp_reader *);
119 static void do_pragma_dependency (cpp_reader *);
120 static void do_linemarker (cpp_reader *);
121 static const cpp_token *get_token_no_padding (cpp_reader *);
122 static const cpp_token *get__Pragma_string (cpp_reader *);
123 static void destringize_and_run (cpp_reader *, const cpp_string *);
124 static int parse_answer (cpp_reader *, struct answer **, int);
125 static cpp_hashnode *parse_assertion (cpp_reader *, struct answer **, int);
126 static struct answer ** find_answer (cpp_hashnode *, const struct answer *);
127 static void handle_assertion (cpp_reader *, const char *, int);
128 static void do_pragma_push_macro (cpp_reader *);
129 static void do_pragma_pop_macro (cpp_reader *);
130
131 /* This is the table of directive handlers.  It is ordered by
132    frequency of occurrence; the numbers at the end are directive
133    counts from all the source code I have lying around (egcs and libc
134    CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
135    pcmcia-cs-3.0.9).  This is no longer important as directive lookup
136    is now O(1).  All extensions other than #warning, #include_next,
137    and #import are deprecated.  The name is where the extension
138    appears to have come from.  */
139
140 #define DIRECTIVE_TABLE                                                 \
141 D(define,       T_DEFINE = 0,   KANDR,     IN_I)           /* 270554 */ \
142 D(include,      T_INCLUDE,      KANDR,     INCL | EXPAND)  /*  52262 */ \
143 D(endif,        T_ENDIF,        KANDR,     COND)           /*  45855 */ \
144 D(ifdef,        T_IFDEF,        KANDR,     COND | IF_COND) /*  22000 */ \
145 D(if,           T_IF,           KANDR, COND | IF_COND | EXPAND) /*  18162 */ \
146 D(else,         T_ELSE,         KANDR,     COND)           /*   9863 */ \
147 D(ifndef,       T_IFNDEF,       KANDR,     COND | IF_COND) /*   9675 */ \
148 D(undef,        T_UNDEF,        KANDR,     IN_I)           /*   4837 */ \
149 D(line,         T_LINE,         KANDR,     EXPAND)         /*   2465 */ \
150 D(elif,         T_ELIF,         STDC89,    COND | EXPAND)  /*    610 */ \
151 D(error,        T_ERROR,        STDC89,    0)              /*    475 */ \
152 D(pragma,       T_PRAGMA,       STDC89,    IN_I)           /*    195 */ \
153 D(warning,      T_WARNING,      EXTENSION, 0)              /*     22 */ \
154 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND)  /*     19 */ \
155 D(ident,        T_IDENT,        EXTENSION, IN_I | DEPRECATED) /*     11 */ \
156 D(import,       T_IMPORT,       EXTENSION, INCL | EXPAND)  /* 0 ObjC */ \
157 D(assert,       T_ASSERT,       EXTENSION, DEPRECATED)     /* 0 SVR4 */ \
158 D(unassert,     T_UNASSERT,     EXTENSION, DEPRECATED)     /* 0 SVR4 */ \
159 D(sccs,         T_SCCS,         EXTENSION, IN_I | DEPRECATED) /* 0 SVR4? */
160
161 /* #sccs is synonymous with #ident.  */
162 #define do_sccs do_ident
163
164 /* Use the table to generate a series of prototypes, an enum for the
165    directive names, and an array of directive handlers.  */
166
167 #define D(name, t, o, f) static void do_##name (cpp_reader *);
168 DIRECTIVE_TABLE
169 #undef D
170
171 #define D(n, tag, o, f) tag,
172 enum
173 {
174   DIRECTIVE_TABLE
175   N_DIRECTIVES
176 };
177 #undef D
178
179 #define D(name, t, origin, flags) \
180 { do_##name, (const uchar *) #name, \
181   sizeof #name - 1, origin, flags },
182 static const directive dtable[] =
183 {
184 DIRECTIVE_TABLE
185 };
186 #undef D
187 #undef DIRECTIVE_TABLE
188
189 /* Wrapper struct directive for linemarkers.
190    The origin is more or less true - the original K+R cpp
191    did use this notation in its preprocessed output.  */
192 static const directive linemarker_dir =
193 {
194   do_linemarker, UC"#", 1, KANDR, IN_I
195 };
196
197 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
198
199 /* Skip any remaining tokens in a directive.  */
200 static void
201 skip_rest_of_line (cpp_reader *pfile)
202 {
203   /* Discard all stacked contexts.  */
204   while (pfile->context->prev)
205     _cpp_pop_context (pfile);
206
207   /* Sweep up all tokens remaining on the line.  */
208   if (! SEEN_EOL ())
209     while (_cpp_lex_token (pfile)->type != CPP_EOF)
210       ;
211 }
212
213 /* Ensure there are no stray tokens at the end of a directive.  */
214 static void
215 check_eol (cpp_reader *pfile)
216 {
217   if (! SEEN_EOL () && _cpp_lex_token (pfile)->type != CPP_EOF)
218     cpp_error (pfile, CPP_DL_PEDWARN, "extra tokens at end of #%s directive",
219                pfile->directive->name);
220 }
221
222 /* Ensure there are no stray tokens other than comments at the end of
223    a directive, and gather the comments.  */
224 static const cpp_token **
225 check_eol_return_comments (cpp_reader *pfile)
226 {
227   size_t c;
228   size_t capacity = 8;
229   const cpp_token **buf;
230
231   buf = XNEWVEC (const cpp_token *, capacity);
232   c = 0;
233   if (! SEEN_EOL ())
234     {
235       while (1)
236         {
237           const cpp_token *tok;
238
239           tok = _cpp_lex_token (pfile);
240           if (tok->type == CPP_EOF)
241             break;
242           if (tok->type != CPP_COMMENT)
243             cpp_error (pfile, CPP_DL_PEDWARN,
244                        "extra tokens at end of #%s directive",
245                        pfile->directive->name);
246           else
247             {
248               if (c + 1 >= capacity)
249                 {
250                   capacity *= 2;
251                   buf = XRESIZEVEC (const cpp_token *, buf, capacity);
252                 }
253               buf[c] = tok;
254               ++c;
255             }
256         }
257     }
258   buf[c] = NULL;
259   return buf;
260 }
261
262 /* Called when entering a directive, _Pragma or command-line directive.  */
263 static void
264 start_directive (cpp_reader *pfile)
265 {
266   /* Setup in-directive state.  */
267   pfile->state.in_directive = 1;
268   pfile->state.save_comments = 0;
269   pfile->directive_result.type = CPP_PADDING;
270
271   /* Some handlers need the position of the # for diagnostics.  */
272   pfile->directive_line = pfile->line_table->highest_line;
273 }
274
275 /* Called when leaving a directive, _Pragma or command-line directive.  */
276 static void
277 end_directive (cpp_reader *pfile, int skip_line)
278 {
279   if (CPP_OPTION (pfile, traditional))
280     {
281       /* Revert change of prepare_directive_trad.  */
282       if (!pfile->state.in_deferred_pragma)
283         pfile->state.prevent_expansion--;
284
285       if (pfile->directive != &dtable[T_DEFINE])
286         _cpp_remove_overlay (pfile);
287     }
288   else if (pfile->state.in_deferred_pragma)
289     ;
290   /* We don't skip for an assembler #.  */
291   else if (skip_line)
292     {
293       skip_rest_of_line (pfile);
294       if (!pfile->keep_tokens)
295         {
296           pfile->cur_run = &pfile->base_run;
297           pfile->cur_token = pfile->base_run.base;
298         }
299     }
300
301   /* Restore state.  */
302   pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
303   pfile->state.in_directive = 0;
304   pfile->state.in_expression = 0;
305   pfile->state.angled_headers = 0;
306   pfile->directive = 0;
307 }
308
309 /* Prepare to handle the directive in pfile->directive.  */
310 static void
311 prepare_directive_trad (cpp_reader *pfile)
312 {
313   if (pfile->directive != &dtable[T_DEFINE])
314     {
315       bool no_expand = (pfile->directive
316                         && ! (pfile->directive->flags & EXPAND));
317       bool was_skipping = pfile->state.skipping;
318
319       pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
320                                     || pfile->directive == &dtable[T_ELIF]);
321       if (pfile->state.in_expression)
322         pfile->state.skipping = false;
323
324       if (no_expand)
325         pfile->state.prevent_expansion++;
326       _cpp_scan_out_logical_line (pfile, NULL);
327       if (no_expand)
328         pfile->state.prevent_expansion--;
329
330       pfile->state.skipping = was_skipping;
331       _cpp_overlay_buffer (pfile, pfile->out.base,
332                            pfile->out.cur - pfile->out.base);
333     }
334
335   /* Stop ISO C from expanding anything.  */
336   pfile->state.prevent_expansion++;
337 }
338
339 /* Output diagnostics for a directive DIR.  INDENTED is nonzero if
340    the '#' was indented.  */
341 static void
342 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
343 {
344   /* Issue -pedantic or deprecated warnings for extensions.  We let
345      -pedantic take precedence if both are applicable.  */
346   if (! pfile->state.skipping)
347     {
348       if (dir->origin == EXTENSION
349           && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
350           && CPP_PEDANTIC (pfile))
351         cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
352       else if (((dir->flags & DEPRECATED) != 0
353                 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
354                && CPP_OPTION (pfile, warn_deprecated))
355         cpp_error (pfile, CPP_DL_WARNING, "#%s is a deprecated GCC extension",
356                    dir->name);
357     }
358
359   /* Traditionally, a directive is ignored unless its # is in
360      column 1.  Therefore in code intended to work with K+R
361      compilers, directives added by C89 must have their #
362      indented, and directives present in traditional C must not.
363      This is true even of directives in skipped conditional
364      blocks.  #elif cannot be used at all.  */
365   if (CPP_WTRADITIONAL (pfile))
366     {
367       if (dir == &dtable[T_ELIF])
368         cpp_error (pfile, CPP_DL_WARNING,
369                    "suggest not using #elif in traditional C");
370       else if (indented && dir->origin == KANDR)
371         cpp_error (pfile, CPP_DL_WARNING,
372                    "traditional C ignores #%s with the # indented",
373                    dir->name);
374       else if (!indented && dir->origin != KANDR)
375         cpp_error (pfile, CPP_DL_WARNING,
376                    "suggest hiding #%s from traditional C with an indented #",
377                    dir->name);
378     }
379 }
380
381 /* Check if we have a known directive.  INDENTED is nonzero if the
382    '#' of the directive was indented.  This function is in this file
383    to save unnecessarily exporting dtable etc. to lex.c.  Returns
384    nonzero if the line of tokens has been handled, zero if we should
385    continue processing the line.  */
386 int
387 _cpp_handle_directive (cpp_reader *pfile, int indented)
388 {
389   const directive *dir = 0;
390   const cpp_token *dname;
391   bool was_parsing_args = pfile->state.parsing_args;
392   bool was_discarding_output = pfile->state.discarding_output;
393   int skip = 1;
394
395   if (was_discarding_output)
396     pfile->state.prevent_expansion = 0;
397
398   if (was_parsing_args)
399     {
400       if (CPP_OPTION (pfile, pedantic))
401         cpp_error (pfile, CPP_DL_PEDWARN,
402              "embedding a directive within macro arguments is not portable");
403       pfile->state.parsing_args = 0;
404       pfile->state.prevent_expansion = 0;
405     }
406   start_directive (pfile);
407   dname = _cpp_lex_token (pfile);
408
409   if (dname->type == CPP_NAME)
410     {
411       if (dname->val.node->is_directive)
412         dir = &dtable[dname->val.node->directive_index];
413     }
414   /* We do not recognize the # followed by a number extension in
415      assembler code.  */
416   else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
417     {
418       dir = &linemarker_dir;
419       if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
420           && ! pfile->state.skipping)
421         cpp_error (pfile, CPP_DL_PEDWARN,
422                    "style of line directive is a GCC extension");
423     }
424
425   if (dir)
426     {
427       /* If we have a directive that is not an opening conditional,
428          invalidate any control macro.  */
429       if (! (dir->flags & IF_COND))
430         pfile->mi_valid = false;
431
432       /* Kluge alert.  In order to be sure that code like this
433
434          #define HASH #
435          HASH define foo bar
436
437          does not cause '#define foo bar' to get executed when
438          compiled with -save-temps, we recognize directives in
439          -fpreprocessed mode only if the # is in column 1.  macro.c
440          puts a space in front of any '#' at the start of a macro.
441          
442          We exclude the -fdirectives-only case because macro expansion
443          has not been performed yet, and block comments can cause spaces
444          to preceed the directive.  */
445       if (CPP_OPTION (pfile, preprocessed)
446           && !CPP_OPTION (pfile, directives_only)
447           && (indented || !(dir->flags & IN_I)))
448         {
449           skip = 0;
450           dir = 0;
451         }
452       else
453         {
454           /* In failed conditional groups, all non-conditional
455              directives are ignored.  Before doing that, whether
456              skipping or not, we should lex angle-bracketed headers
457              correctly, and maybe output some diagnostics.  */
458           pfile->state.angled_headers = dir->flags & INCL;
459           pfile->state.directive_wants_padding = dir->flags & INCL;
460           if (! CPP_OPTION (pfile, preprocessed))
461             directive_diagnostics (pfile, dir, indented);
462           if (pfile->state.skipping && !(dir->flags & COND))
463             dir = 0;
464         }
465     }
466   else if (dname->type == CPP_EOF)
467     ;   /* CPP_EOF is the "null directive".  */
468   else
469     {
470       /* An unknown directive.  Don't complain about it in assembly
471          source: we don't know where the comments are, and # may
472          introduce assembler pseudo-ops.  Don't complain about invalid
473          directives in skipped conditional groups (6.10 p4).  */
474       if (CPP_OPTION (pfile, lang) == CLK_ASM)
475         skip = 0;
476       else if (!pfile->state.skipping)
477         cpp_error (pfile, CPP_DL_ERROR, "invalid preprocessing directive #%s",
478                    cpp_token_as_text (pfile, dname));
479     }
480
481   pfile->directive = dir;
482   if (CPP_OPTION (pfile, traditional))
483     prepare_directive_trad (pfile);
484
485   if (dir)
486     pfile->directive->handler (pfile);
487   else if (skip == 0)
488     _cpp_backup_tokens (pfile, 1);
489
490   end_directive (pfile, skip);
491   if (was_parsing_args && !pfile->state.in_deferred_pragma)
492     {
493       /* Restore state when within macro args.  */
494       pfile->state.parsing_args = 2;
495       pfile->state.prevent_expansion = 1;
496     }
497   if (was_discarding_output)
498     pfile->state.prevent_expansion = 1;
499   return skip;
500 }
501
502 /* Directive handler wrapper used by the command line option
503    processor.  BUF is \n terminated.  */
504 static void
505 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
506 {
507   cpp_push_buffer (pfile, (const uchar *) buf, count,
508                    /* from_stage3 */ true);
509   start_directive (pfile);
510
511   /* This is a short-term fix to prevent a leading '#' being
512      interpreted as a directive.  */
513   _cpp_clean_line (pfile);
514
515   pfile->directive = &dtable[dir_no];
516   if (CPP_OPTION (pfile, traditional))
517     prepare_directive_trad (pfile);
518   pfile->directive->handler (pfile);
519   end_directive (pfile, 1);
520   _cpp_pop_buffer (pfile);
521 }
522
523 /* Checks for validity the macro name in #define, #undef, #ifdef and
524    #ifndef directives.  IS_DEF_OR_UNDEF is true if this call is
525    processing a #define or #undefine directive, and false
526    otherwise.  */
527 static cpp_hashnode *
528 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
529 {
530   const cpp_token *token = _cpp_lex_token (pfile);
531
532   /* The token immediately after #define must be an identifier.  That
533      identifier may not be "defined", per C99 6.10.8p4.
534      In C++, it may not be any of the "named operators" either,
535      per C++98 [lex.digraph], [lex.key].
536      Finally, the identifier may not have been poisoned.  (In that case
537      the lexer has issued the error message for us.)  */
538
539   if (token->type == CPP_NAME)
540     {
541       cpp_hashnode *node = token->val.node;
542
543       if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
544         cpp_error (pfile, CPP_DL_ERROR,
545                    "\"defined\" cannot be used as a macro name");
546       else if (! (node->flags & NODE_POISONED))
547         return node;
548     }
549   else if (token->flags & NAMED_OP)
550     cpp_error (pfile, CPP_DL_ERROR,
551        "\"%s\" cannot be used as a macro name as it is an operator in C++",
552                NODE_NAME (token->val.node));
553   else if (token->type == CPP_EOF)
554     cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
555                pfile->directive->name);
556   else
557     cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
558
559   return NULL;
560 }
561
562 /* Process a #define directive.  Most work is done in macro.c.  */
563 static void
564 do_define (cpp_reader *pfile)
565 {
566   cpp_hashnode *node = lex_macro_node (pfile, true);
567
568   if (node)
569     {
570       /* If we have been requested to expand comments into macros,
571          then re-enable saving of comments.  */
572       pfile->state.save_comments =
573         ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
574
575       if (pfile->cb.before_define)
576         pfile->cb.before_define (pfile);
577
578       if (_cpp_create_definition (pfile, node))
579         if (pfile->cb.define)
580           pfile->cb.define (pfile, pfile->directive_line, node);
581
582       node->flags &= ~NODE_USED;
583     }
584 }
585
586 /* Handle #undef.  Mark the identifier NT_VOID in the hash table.  */
587 static void
588 do_undef (cpp_reader *pfile)
589 {
590   cpp_hashnode *node = lex_macro_node (pfile, true);
591
592   if (node)
593     {
594       if (pfile->cb.before_define)
595         pfile->cb.before_define (pfile);
596
597       if (pfile->cb.undef)
598         pfile->cb.undef (pfile, pfile->directive_line, node);
599
600       /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
601          identifier is not currently defined as a macro name.  */
602       if (node->type == NT_MACRO)
603         {
604           if (node->flags & NODE_WARN)
605             cpp_error (pfile, CPP_DL_WARNING,
606                        "undefining \"%s\"", NODE_NAME (node));
607
608           if (CPP_OPTION (pfile, warn_unused_macros))
609             _cpp_warn_if_unused_macro (pfile, node, NULL);
610
611           _cpp_free_definition (node);
612         }
613     }
614
615   check_eol (pfile);
616 }
617
618 /* Undefine a single macro/assertion/whatever.  */
619
620 static int
621 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
622                  void *data_p ATTRIBUTE_UNUSED)
623 {
624   /* Body of _cpp_free_definition inlined here for speed.
625      Macros and assertions no longer have anything to free.  */
626   h->type = NT_VOID;
627   h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
628   return 1;
629 }
630
631 /* Undefine all macros and assertions.  */
632
633 void
634 cpp_undef_all (cpp_reader *pfile)
635 {
636   cpp_forall_identifiers (pfile, undefine_macros, NULL);
637 }
638
639
640 /* Helper routine used by parse_include.  Reinterpret the current line
641    as an h-char-sequence (< ... >); we are looking at the first token
642    after the <.  Returns a malloced filename.  */
643 static char *
644 glue_header_name (cpp_reader *pfile)
645 {
646   const cpp_token *token;
647   char *buffer;
648   size_t len, total_len = 0, capacity = 1024;
649
650   /* To avoid lexed tokens overwriting our glued name, we can only
651      allocate from the string pool once we've lexed everything.  */
652   buffer = XNEWVEC (char, capacity);
653   for (;;)
654     {
655       token = get_token_no_padding (pfile);
656
657       if (token->type == CPP_GREATER)
658         break;
659       if (token->type == CPP_EOF)
660         {
661           cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
662           break;
663         }
664
665       len = cpp_token_len (token) + 2; /* Leading space, terminating \0.  */
666       if (total_len + len > capacity)
667         {
668           capacity = (capacity + len) * 2;
669           buffer = XRESIZEVEC (char, buffer, capacity);
670         }
671
672       if (token->flags & PREV_WHITE)
673         buffer[total_len++] = ' ';
674
675       total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
676                                     true)
677                    - (uchar *) buffer);
678     }
679
680   buffer[total_len] = '\0';
681   return buffer;
682 }
683
684 /* Returns the file name of #include, #include_next, #import and
685    #pragma dependency.  The string is malloced and the caller should
686    free it.  Returns NULL on error.  */
687 static const char *
688 parse_include (cpp_reader *pfile, int *pangle_brackets,
689                const cpp_token ***buf)
690 {
691   char *fname;
692   const cpp_token *header;
693
694   /* Allow macro expansion.  */
695   header = get_token_no_padding (pfile);
696   if (header->type == CPP_STRING || header->type == CPP_HEADER_NAME)
697     {
698       fname = XNEWVEC (char, header->val.str.len - 1);
699       memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
700       fname[header->val.str.len - 2] = '\0';
701       *pangle_brackets = header->type == CPP_HEADER_NAME;
702     }
703   else if (header->type == CPP_LESS)
704     {
705       fname = glue_header_name (pfile);
706       *pangle_brackets = 1;
707     }
708   else
709     {
710       const unsigned char *dir;
711
712       if (pfile->directive == &dtable[T_PRAGMA])
713         dir = UC"pragma dependency";
714       else
715         dir = pfile->directive->name;
716       cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
717                  dir);
718
719       return NULL;
720     }
721
722   if (pfile->directive == &dtable[T_PRAGMA])
723     {
724       /* This pragma allows extra tokens after the file name.  */
725     }
726   else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
727     check_eol (pfile);
728   else
729     {
730       /* If we are not discarding comments, then gather them while
731          doing the eol check.  */
732       *buf = check_eol_return_comments (pfile);
733     }
734
735   return fname;
736 }
737
738 /* Handle #include, #include_next and #import.  */
739 static void
740 do_include_common (cpp_reader *pfile, enum include_type type)
741 {
742   const char *fname;
743   int angle_brackets;
744   const cpp_token **buf = NULL;
745
746   /* Re-enable saving of comments if requested, so that the include
747      callback can dump comments which follow #include.  */
748   pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
749
750   fname = parse_include (pfile, &angle_brackets, &buf);
751   if (!fname)
752     {
753       if (buf)
754         XDELETEVEC (buf);
755       return;
756     }
757
758   if (!*fname)
759   {
760     cpp_error (pfile, CPP_DL_ERROR, "empty filename in #%s",
761                pfile->directive->name);
762     XDELETEVEC (fname);
763     if (buf)
764       XDELETEVEC (buf);
765     return;
766   }
767
768   /* Prevent #include recursion.  */
769   if (pfile->line_table->depth >= CPP_STACK_MAX)
770     cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
771   else
772     {
773       /* Get out of macro context, if we are.  */
774       skip_rest_of_line (pfile);
775
776       if (pfile->cb.include)
777         pfile->cb.include (pfile, pfile->directive_line,
778                            pfile->directive->name, fname, angle_brackets,
779                            buf);
780
781       _cpp_stack_include (pfile, fname, angle_brackets, type);
782     }
783
784   XDELETEVEC (fname);
785   if (buf)
786     XDELETEVEC (buf);
787 }
788
789 static void
790 do_include (cpp_reader *pfile)
791 {
792   do_include_common (pfile, IT_INCLUDE);
793 }
794
795 static void
796 do_import (cpp_reader *pfile)
797 {
798   do_include_common (pfile, IT_IMPORT);
799 }
800
801 static void
802 do_include_next (cpp_reader *pfile)
803 {
804   enum include_type type = IT_INCLUDE_NEXT;
805
806   /* If this is the primary source file, warn and use the normal
807      search logic.  */
808   if (cpp_in_primary_file (pfile))
809     {
810       cpp_error (pfile, CPP_DL_WARNING,
811                  "#include_next in primary source file");
812       type = IT_INCLUDE;
813     }
814   do_include_common (pfile, type);
815 }
816
817 /* Subroutine of do_linemarker.  Read possible flags after file name.
818    LAST is the last flag seen; 0 if this is the first flag. Return the
819    flag if it is valid, 0 at the end of the directive. Otherwise
820    complain.  */
821 static unsigned int
822 read_flag (cpp_reader *pfile, unsigned int last)
823 {
824   const cpp_token *token = _cpp_lex_token (pfile);
825
826   if (token->type == CPP_NUMBER && token->val.str.len == 1)
827     {
828       unsigned int flag = token->val.str.text[0] - '0';
829
830       if (flag > last && flag <= 4
831           && (flag != 4 || last == 3)
832           && (flag != 2 || last == 0))
833         return flag;
834     }
835
836   if (token->type != CPP_EOF)
837     cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
838                cpp_token_as_text (pfile, token));
839   return 0;
840 }
841
842 /* Subroutine of do_line and do_linemarker.  Convert a number in STR,
843    of length LEN, to binary; store it in NUMP, and return false if the
844    number was well-formed, true if not. WRAPPED is set to true if the
845    number did not fit into 'unsigned long'.  */
846 static bool
847 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
848 {
849   linenum_type reg = 0;
850   linenum_type reg_prev = 0;
851
852   uchar c;
853   *wrapped = false;
854   while (len--)
855     {
856       c = *str++;
857       if (!ISDIGIT (c))
858         return true;
859       reg *= 10;
860       reg += c - '0';
861       if (reg < reg_prev) 
862         *wrapped = true;
863       reg_prev = reg;
864     }
865   *nump = reg;
866   return false;
867 }
868
869 /* Interpret #line command.
870    Note that the filename string (if any) is a true string constant
871    (escapes are interpreted), unlike in #line.  */
872 static void
873 do_line (cpp_reader *pfile)
874 {
875   const struct line_maps *line_table = pfile->line_table;
876   const struct line_map *map = &line_table->maps[line_table->used - 1];
877
878   /* skip_rest_of_line() may cause line table to be realloc()ed so note down
879      sysp right now.  */
880
881   unsigned char map_sysp = map->sysp;
882   const cpp_token *token;
883   const char *new_file = map->to_file;
884   linenum_type new_lineno;
885
886   /* C99 raised the minimum limit on #line numbers.  */
887   linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
888   bool wrapped;
889
890   /* #line commands expand macros.  */
891   token = cpp_get_token (pfile);
892   if (token->type != CPP_NUMBER
893       || strtolinenum (token->val.str.text, token->val.str.len,
894                        &new_lineno, &wrapped))
895     {
896       if (token->type == CPP_EOF)
897         cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
898       else
899         cpp_error (pfile, CPP_DL_ERROR,
900                    "\"%s\" after #line is not a positive integer",
901                    cpp_token_as_text (pfile, token));
902       return;
903     }
904
905   if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
906     cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
907   else if (wrapped)
908     cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
909
910   token = cpp_get_token (pfile);
911   if (token->type == CPP_STRING)
912     {
913       cpp_string s = { 0, 0 };
914       if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
915                                             &s, false))
916         new_file = (const char *)s.text;
917       check_eol (pfile);
918     }
919   else if (token->type != CPP_EOF)
920     {
921       cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
922                  cpp_token_as_text (pfile, token));
923       return;
924     }
925
926   skip_rest_of_line (pfile);
927   _cpp_do_file_change (pfile, LC_RENAME, new_file, new_lineno,
928                        map_sysp);
929 }
930
931 /* Interpret the # 44 "file" [flags] notation, which has slightly
932    different syntax and semantics from #line:  Flags are allowed,
933    and we never complain about the line number being too big.  */
934 static void
935 do_linemarker (cpp_reader *pfile)
936 {
937   const struct line_maps *line_table = pfile->line_table;
938   const struct line_map *map = &line_table->maps[line_table->used - 1];
939   const cpp_token *token;
940   const char *new_file = map->to_file;
941   linenum_type new_lineno;
942   unsigned int new_sysp = map->sysp;
943   enum lc_reason reason = LC_RENAME;
944   int flag;
945   bool wrapped;
946
947   /* Back up so we can get the number again.  Putting this in
948      _cpp_handle_directive risks two calls to _cpp_backup_tokens in
949      some circumstances, which can segfault.  */
950   _cpp_backup_tokens (pfile, 1);
951
952   /* #line commands expand macros.  */
953   token = cpp_get_token (pfile);
954   if (token->type != CPP_NUMBER
955       || strtolinenum (token->val.str.text, token->val.str.len,
956                        &new_lineno, &wrapped))
957     {
958       /* Unlike #line, there does not seem to be a way to get an EOF
959          here.  So, it should be safe to always spell the token.  */
960       cpp_error (pfile, CPP_DL_ERROR,
961                  "\"%s\" after # is not a positive integer",
962                  cpp_token_as_text (pfile, token));
963       return;
964     }
965
966   token = cpp_get_token (pfile);
967   if (token->type == CPP_STRING)
968     {
969       cpp_string s = { 0, 0 };
970       if (cpp_interpret_string_notranslate (pfile, &token->val.str,
971                                             1, &s, false))
972         new_file = (const char *)s.text;
973
974       new_sysp = 0;
975       flag = read_flag (pfile, 0);
976       if (flag == 1)
977         {
978           reason = LC_ENTER;
979           /* Fake an include for cpp_included ().  */
980           _cpp_fake_include (pfile, new_file);
981           flag = read_flag (pfile, flag);
982         }
983       else if (flag == 2)
984         {
985           reason = LC_LEAVE;
986           flag = read_flag (pfile, flag);
987         }
988       if (flag == 3)
989         {
990           new_sysp = 1;
991           flag = read_flag (pfile, flag);
992           if (flag == 4)
993             new_sysp = 2;
994         }
995       pfile->buffer->sysp = new_sysp;
996
997       check_eol (pfile);
998     }
999   else if (token->type != CPP_EOF)
1000     {
1001       cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1002                  cpp_token_as_text (pfile, token));
1003       return;
1004     }
1005
1006   skip_rest_of_line (pfile);
1007   _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1008 }
1009
1010 /* Arrange the file_change callback.  pfile->line has changed to
1011    FILE_LINE of TO_FILE, for reason REASON.  SYSP is 1 for a system
1012    header, 2 for a system header that needs to be extern "C" protected,
1013    and zero otherwise.  */
1014 void
1015 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1016                      const char *to_file, linenum_type file_line,
1017                      unsigned int sysp)
1018 {
1019   const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1020                                             to_file, file_line);
1021   if (map != NULL)
1022     linemap_line_start (pfile->line_table, map->to_line, 127);
1023
1024   if (pfile->cb.file_change)
1025     pfile->cb.file_change (pfile, map);
1026 }
1027
1028 /* Report a warning or error detected by the program we are
1029    processing.  Use the directive's tokens in the error message.  */
1030 static void
1031 do_diagnostic (cpp_reader *pfile, int code, int print_dir)
1032 {
1033   const unsigned char *dir_name;
1034   unsigned char *line;
1035   source_location src_loc = pfile->cur_token[-1].src_loc;
1036
1037   if (print_dir)
1038     dir_name = pfile->directive->name;
1039   else
1040     dir_name = NULL;
1041   pfile->state.prevent_expansion++;
1042   line = cpp_output_line_to_string (pfile, dir_name);
1043   pfile->state.prevent_expansion--;
1044
1045   cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1046   free (line);
1047 }
1048
1049 static void
1050 do_error (cpp_reader *pfile)
1051 {
1052   do_diagnostic (pfile, CPP_DL_ERROR, 1);
1053 }
1054
1055 static void
1056 do_warning (cpp_reader *pfile)
1057 {
1058   /* We want #warning diagnostics to be emitted in system headers too.  */
1059   do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, 1);
1060 }
1061
1062 /* Report program identification.  */
1063 static void
1064 do_ident (cpp_reader *pfile)
1065 {
1066   const cpp_token *str = cpp_get_token (pfile);
1067
1068   if (str->type != CPP_STRING)
1069     cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1070                pfile->directive->name);
1071   else if (pfile->cb.ident)
1072     pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1073
1074   check_eol (pfile);
1075 }
1076
1077 /* Lookup a PRAGMA name in a singly-linked CHAIN.  Returns the
1078    matching entry, or NULL if none is found.  The returned entry could
1079    be the start of a namespace chain, or a pragma.  */
1080 static struct pragma_entry *
1081 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1082 {
1083   while (chain && chain->pragma != pragma)
1084     chain = chain->next;
1085
1086   return chain;
1087 }
1088
1089 /* Create and insert a blank pragma entry at the beginning of a
1090    singly-linked CHAIN.  */
1091 static struct pragma_entry *
1092 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1093 {
1094   struct pragma_entry *new_entry;
1095
1096   new_entry = (struct pragma_entry *)
1097     _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1098
1099   memset (new_entry, 0, sizeof (struct pragma_entry));
1100   new_entry->next = *chain;
1101
1102   *chain = new_entry;
1103   return new_entry;
1104 }
1105
1106 /* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
1107    goes in the global namespace.  */
1108 static struct pragma_entry *
1109 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1110                    bool allow_name_expansion)
1111 {
1112   struct pragma_entry **chain = &pfile->pragmas;
1113   struct pragma_entry *entry;
1114   const cpp_hashnode *node;
1115
1116   if (space)
1117     {
1118       node = cpp_lookup (pfile, UC space, strlen (space));
1119       entry = lookup_pragma_entry (*chain, node);
1120       if (!entry)
1121         {
1122           entry = new_pragma_entry (pfile, chain);
1123           entry->pragma = node;
1124           entry->is_nspace = true;
1125           entry->allow_expansion = allow_name_expansion;
1126         }
1127       else if (!entry->is_nspace)
1128         goto clash;
1129       else if (entry->allow_expansion != allow_name_expansion)
1130         {
1131           cpp_error (pfile, CPP_DL_ICE,
1132                      "registering pragmas in namespace \"%s\" with mismatched "
1133                      "name expansion", space);
1134           return NULL;
1135         }
1136       chain = &entry->u.space;
1137     }
1138   else if (allow_name_expansion)
1139     {
1140       cpp_error (pfile, CPP_DL_ICE,
1141                  "registering pragma \"%s\" with name expansion "
1142                  "and no namespace", name);
1143       return NULL;
1144     }
1145
1146   /* Check for duplicates.  */
1147   node = cpp_lookup (pfile, UC name, strlen (name));
1148   entry = lookup_pragma_entry (*chain, node);
1149   if (entry == NULL)
1150     {
1151       entry = new_pragma_entry (pfile, chain);
1152       entry->pragma = node;
1153       return entry;
1154     }
1155
1156   if (entry->is_nspace)
1157     clash:
1158     cpp_error (pfile, CPP_DL_ICE,
1159                "registering \"%s\" as both a pragma and a pragma namespace",
1160                NODE_NAME (node));
1161   else if (space)
1162     cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1163                space, name);
1164   else
1165     cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1166
1167   return NULL;
1168 }
1169
1170 /* Register a cpplib internal pragma SPACE NAME with HANDLER.  */
1171 static void
1172 register_pragma_internal (cpp_reader *pfile, const char *space,
1173                           const char *name, pragma_cb handler)
1174 {
1175   struct pragma_entry *entry;
1176
1177   entry = register_pragma_1 (pfile, space, name, false);
1178   entry->is_internal = true;
1179   entry->u.handler = handler;
1180 }
1181
1182 /* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
1183    goes in the global namespace.  HANDLER is the handler it will call,
1184    which must be non-NULL.  If ALLOW_EXPANSION is set, allow macro
1185    expansion while parsing pragma NAME.  This function is exported
1186    from libcpp. */
1187 void
1188 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1189                      pragma_cb handler, bool allow_expansion)
1190 {
1191   struct pragma_entry *entry;
1192
1193   if (!handler)
1194     {
1195       cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1196       return;
1197     }
1198
1199   entry = register_pragma_1 (pfile, space, name, false);
1200   if (entry)
1201     {
1202       entry->allow_expansion = allow_expansion;
1203       entry->u.handler = handler;
1204     }
1205 }
1206
1207 /* Similarly, but create mark the pragma for deferred processing.
1208    When found, a CPP_PRAGMA token will be insertted into the stream
1209    with IDENT in the token->u.pragma slot.  */
1210 void
1211 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1212                               const char *name, unsigned int ident,
1213                               bool allow_expansion, bool allow_name_expansion)
1214 {
1215   struct pragma_entry *entry;
1216
1217   entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1218   if (entry)
1219     {
1220       entry->is_deferred = true;
1221       entry->allow_expansion = allow_expansion;
1222       entry->u.ident = ident;
1223     }
1224 }  
1225
1226 /* Register the pragmas the preprocessor itself handles.  */
1227 void
1228 _cpp_init_internal_pragmas (cpp_reader *pfile)
1229 {
1230   /* Pragmas in the global namespace.  */
1231   register_pragma_internal (pfile, 0, "once", do_pragma_once);
1232   register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1233   register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1234
1235   /* New GCC-specific pragmas should be put in the GCC namespace.  */
1236   register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1237   register_pragma_internal (pfile, "GCC", "system_header",
1238                             do_pragma_system_header);
1239   register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1240 }
1241
1242 /* Return the number of registered pragmas in PE.  */
1243
1244 static int
1245 count_registered_pragmas (struct pragma_entry *pe)
1246 {
1247   int ct = 0;
1248   for (; pe != NULL; pe = pe->next)
1249     {
1250       if (pe->is_nspace)
1251         ct += count_registered_pragmas (pe->u.space);
1252       ct++;
1253     }
1254   return ct;
1255 }
1256
1257 /* Save into SD the names of the registered pragmas referenced by PE,
1258    and return a pointer to the next free space in SD.  */
1259
1260 static char **
1261 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1262 {
1263   for (; pe != NULL; pe = pe->next)
1264     {
1265       if (pe->is_nspace)
1266         sd = save_registered_pragmas (pe->u.space, sd);
1267       *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1268                                 HT_LEN (&pe->pragma->ident),
1269                                 HT_LEN (&pe->pragma->ident) + 1);
1270     }
1271   return sd;
1272 }
1273
1274 /* Return a newly-allocated array which saves the names of the
1275    registered pragmas.  */
1276
1277 char **
1278 _cpp_save_pragma_names (cpp_reader *pfile)
1279 {
1280   int ct = count_registered_pragmas (pfile->pragmas);
1281   char **result = XNEWVEC (char *, ct);
1282   (void) save_registered_pragmas (pfile->pragmas, result);
1283   return result;
1284 }
1285
1286 /* Restore from SD the names of the registered pragmas referenced by PE,
1287    and return a pointer to the next unused name in SD.  */
1288
1289 static char **
1290 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1291                             char **sd)
1292 {
1293   for (; pe != NULL; pe = pe->next)
1294     {
1295       if (pe->is_nspace)
1296         sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1297       pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1298       free (*sd);
1299       sd++;
1300     }
1301   return sd;
1302 }
1303
1304 /* Restore the names of the registered pragmas from SAVED.  */
1305
1306 void
1307 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1308 {
1309   (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1310   free (saved);
1311 }
1312
1313 /* Pragmata handling.  We handle some, and pass the rest on to the
1314    front end.  C99 defines three pragmas and says that no macro
1315    expansion is to be performed on them; whether or not macro
1316    expansion happens for other pragmas is implementation defined.
1317    This implementation allows for a mix of both, since GCC did not
1318    traditionally macro expand its (few) pragmas, whereas OpenMP
1319    specifies that macro expansion should happen.  */
1320 static void
1321 do_pragma (cpp_reader *pfile)
1322 {
1323   const struct pragma_entry *p = NULL;
1324   const cpp_token *token, *pragma_token = pfile->cur_token;
1325   cpp_token ns_token;
1326   unsigned int count = 1;
1327
1328   pfile->state.prevent_expansion++;
1329
1330   token = cpp_get_token (pfile);
1331   ns_token = *token;
1332   if (token->type == CPP_NAME)
1333     {
1334       p = lookup_pragma_entry (pfile->pragmas, token->val.node);
1335       if (p && p->is_nspace)
1336         {
1337           bool allow_name_expansion = p->allow_expansion;
1338           if (allow_name_expansion)
1339             pfile->state.prevent_expansion--;
1340           token = cpp_get_token (pfile);
1341           if (token->type == CPP_NAME)
1342             p = lookup_pragma_entry (p->u.space, token->val.node);
1343           else
1344             p = NULL;
1345           if (allow_name_expansion)
1346             pfile->state.prevent_expansion++;
1347           count = 2;
1348         }
1349     }
1350
1351   if (p)
1352     {
1353       if (p->is_deferred)
1354         {
1355           pfile->directive_result.src_loc = pragma_token->src_loc;
1356           pfile->directive_result.type = CPP_PRAGMA;
1357           pfile->directive_result.flags = pragma_token->flags;
1358           pfile->directive_result.val.pragma = p->u.ident;
1359           pfile->state.in_deferred_pragma = true;
1360           pfile->state.pragma_allow_expansion = p->allow_expansion;
1361           if (!p->allow_expansion)
1362             pfile->state.prevent_expansion++;
1363         }
1364       else
1365         {
1366           /* Since the handler below doesn't get the line number, that
1367              it might need for diagnostics, make sure it has the right
1368              numbers in place.  */
1369           if (pfile->cb.line_change)
1370             (*pfile->cb.line_change) (pfile, pragma_token, false);
1371           if (p->allow_expansion)
1372             pfile->state.prevent_expansion--;
1373           (*p->u.handler) (pfile);
1374           if (p->allow_expansion)
1375             pfile->state.prevent_expansion++;
1376         }
1377     }
1378   else if (pfile->cb.def_pragma)
1379     {
1380       if (count == 1 || pfile->context->prev == NULL)
1381         _cpp_backup_tokens (pfile, count);
1382       else
1383         {
1384           /* Invalid name comes from macro expansion, _cpp_backup_tokens
1385              won't allow backing 2 tokens.  */
1386           /* ??? The token buffer is leaked.  Perhaps if def_pragma hook
1387              reads both tokens, we could perhaps free it, but if it doesn't,
1388              we don't know the exact lifespan.  */
1389           cpp_token *toks = XNEWVEC (cpp_token, 2);
1390           toks[0] = ns_token;
1391           toks[0].flags |= NO_EXPAND;
1392           toks[1] = *token;
1393           toks[1].flags |= NO_EXPAND;
1394           _cpp_push_token_context (pfile, NULL, toks, 2);
1395         }
1396       pfile->cb.def_pragma (pfile, pfile->directive_line);
1397     }
1398
1399   pfile->state.prevent_expansion--;
1400 }
1401
1402 /* Handle #pragma once.  */
1403 static void
1404 do_pragma_once (cpp_reader *pfile)
1405 {
1406   if (cpp_in_primary_file (pfile))
1407     cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1408
1409   check_eol (pfile);
1410   _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1411 }
1412
1413 /* Handle #pragma push_macro(STRING).  */
1414 static void
1415 do_pragma_push_macro (cpp_reader *pfile)
1416 {
1417   char *macroname, *dest;
1418   const char *limit, *src;
1419   const cpp_token *txt;
1420   struct def_pragma_macro *c;
1421
1422   txt = get__Pragma_string (pfile);
1423   if (!txt)
1424     {
1425       source_location src_loc = pfile->cur_token[-1].src_loc;
1426       cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1427                  "invalid #pragma push_macro directive");
1428       check_eol (pfile);
1429       skip_rest_of_line (pfile);
1430       return;
1431     }
1432   dest = macroname = (char *) alloca (txt->val.str.len + 2);
1433   src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1434   limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1435   while (src < limit)
1436     {
1437       /* We know there is a character following the backslash.  */
1438       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1439         src++;
1440       *dest++ = *src++;
1441     }
1442   *dest = 0;
1443   check_eol (pfile);
1444   skip_rest_of_line (pfile);
1445   c = XNEW (struct def_pragma_macro);
1446   c->name = XNEWVAR (char, strlen (macroname) + 1);
1447   strcpy (c->name, macroname);
1448   c->next = pfile->pushed_macros;
1449   c->value = cpp_push_definition (pfile, c->name);
1450   pfile->pushed_macros = c;
1451 }
1452
1453 /* Handle #pragma pop_macro(STRING).  */
1454 static void
1455 do_pragma_pop_macro (cpp_reader *pfile)
1456 {
1457   char *macroname, *dest;
1458   const char *limit, *src;
1459   const cpp_token *txt;
1460   struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1461   txt = get__Pragma_string (pfile);
1462   if (!txt)
1463     {
1464       source_location src_loc = pfile->cur_token[-1].src_loc;
1465       cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1466                  "invalid #pragma pop_macro directive");
1467       check_eol (pfile);
1468       skip_rest_of_line (pfile);
1469       return;
1470     }
1471   dest = macroname = (char *) alloca (txt->val.str.len + 2);
1472   src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1473   limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1474   while (src < limit)
1475     {
1476       /* We know there is a character following the backslash.  */
1477       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1478         src++;
1479       *dest++ = *src++;
1480     }
1481   *dest = 0;
1482   check_eol (pfile);
1483   skip_rest_of_line (pfile);
1484
1485   while (c != NULL)
1486     {
1487       if (!strcmp (c->name, macroname))
1488         {
1489           if (!l)
1490             pfile->pushed_macros = c->next;
1491           else
1492             l->next = c->next;
1493           cpp_pop_definition (pfile, c->name, c->value);
1494           free (c->name);
1495           free (c);
1496           break;
1497         }
1498       l = c;
1499       c = c->next;
1500     }
1501 }
1502
1503 /* Handle #pragma GCC poison, to poison one or more identifiers so
1504    that the lexer produces a hard error for each subsequent usage.  */
1505 static void
1506 do_pragma_poison (cpp_reader *pfile)
1507 {
1508   const cpp_token *tok;
1509   cpp_hashnode *hp;
1510
1511   pfile->state.poisoned_ok = 1;
1512   for (;;)
1513     {
1514       tok = _cpp_lex_token (pfile);
1515       if (tok->type == CPP_EOF)
1516         break;
1517       if (tok->type != CPP_NAME)
1518         {
1519           cpp_error (pfile, CPP_DL_ERROR,
1520                      "invalid #pragma GCC poison directive");
1521           break;
1522         }
1523
1524       hp = tok->val.node;
1525       if (hp->flags & NODE_POISONED)
1526         continue;
1527
1528       if (hp->type == NT_MACRO)
1529         cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1530                    NODE_NAME (hp));
1531       _cpp_free_definition (hp);
1532       hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1533     }
1534   pfile->state.poisoned_ok = 0;
1535 }
1536
1537 /* Mark the current header as a system header.  This will suppress
1538    some categories of warnings (notably those from -pedantic).  It is
1539    intended for use in system libraries that cannot be implemented in
1540    conforming C, but cannot be certain that their headers appear in a
1541    system include directory.  To prevent abuse, it is rejected in the
1542    primary source file.  */
1543 static void
1544 do_pragma_system_header (cpp_reader *pfile)
1545 {
1546   if (cpp_in_primary_file (pfile))
1547     cpp_error (pfile, CPP_DL_WARNING,
1548                "#pragma system_header ignored outside include file");
1549   else
1550     {
1551       check_eol (pfile);
1552       skip_rest_of_line (pfile);
1553       cpp_make_system_header (pfile, 1, 0);
1554     }
1555 }
1556
1557 /* Check the modified date of the current include file against a specified
1558    file. Issue a diagnostic, if the specified file is newer. We use this to
1559    determine if a fixed header should be refixed.  */
1560 static void
1561 do_pragma_dependency (cpp_reader *pfile)
1562 {
1563   const char *fname;
1564   int angle_brackets, ordering;
1565
1566   fname = parse_include (pfile, &angle_brackets, NULL);
1567   if (!fname)
1568     return;
1569
1570   ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1571   if (ordering < 0)
1572     cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1573   else if (ordering > 0)
1574     {
1575       cpp_error (pfile, CPP_DL_WARNING,
1576                  "current file is older than %s", fname);
1577       if (cpp_get_token (pfile)->type != CPP_EOF)
1578         {
1579           _cpp_backup_tokens (pfile, 1);
1580           do_diagnostic (pfile, CPP_DL_WARNING, 0);
1581         }
1582     }
1583
1584   free ((void *) fname);
1585 }
1586
1587 /* Get a token but skip padding.  */
1588 static const cpp_token *
1589 get_token_no_padding (cpp_reader *pfile)
1590 {
1591   for (;;)
1592     {
1593       const cpp_token *result = cpp_get_token (pfile);
1594       if (result->type != CPP_PADDING)
1595         return result;
1596     }
1597 }
1598
1599 /* Check syntax is "(string-literal)".  Returns the string on success,
1600    or NULL on failure.  */
1601 static const cpp_token *
1602 get__Pragma_string (cpp_reader *pfile)
1603 {
1604   const cpp_token *string;
1605   const cpp_token *paren;
1606
1607   paren = get_token_no_padding (pfile);
1608   if (paren->type == CPP_EOF)
1609     _cpp_backup_tokens (pfile, 1);
1610   if (paren->type != CPP_OPEN_PAREN)
1611     return NULL;
1612
1613   string = get_token_no_padding (pfile);
1614   if (string->type == CPP_EOF)
1615     _cpp_backup_tokens (pfile, 1);
1616   if (string->type != CPP_STRING && string->type != CPP_WSTRING
1617       && string->type != CPP_STRING32 && string->type != CPP_STRING16)
1618     return NULL;
1619
1620   paren = get_token_no_padding (pfile);
1621   if (paren->type == CPP_EOF)
1622     _cpp_backup_tokens (pfile, 1);
1623   if (paren->type != CPP_CLOSE_PAREN)
1624     return NULL;
1625
1626   return string;
1627 }
1628
1629 /* Destringize IN into a temporary buffer, by removing the first \ of
1630    \" and \\ sequences, and process the result as a #pragma directive.  */
1631 static void
1632 destringize_and_run (cpp_reader *pfile, const cpp_string *in)
1633 {
1634   const unsigned char *src, *limit;
1635   char *dest, *result;
1636   cpp_context *saved_context;
1637   cpp_token *saved_cur_token;
1638   tokenrun *saved_cur_run;
1639   cpp_token *toks;
1640   int count;
1641   const struct directive *save_directive;
1642
1643   dest = result = (char *) alloca (in->len - 1);
1644   src = in->text + 1 + (in->text[0] == 'L');
1645   limit = in->text + in->len - 1;
1646   while (src < limit)
1647     {
1648       /* We know there is a character following the backslash.  */
1649       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1650         src++;
1651       *dest++ = *src++;
1652     }
1653   *dest = '\n';
1654
1655   /* Ugh; an awful kludge.  We are really not set up to be lexing
1656      tokens when in the middle of a macro expansion.  Use a new
1657      context to force cpp_get_token to lex, and so skip_rest_of_line
1658      doesn't go beyond the end of the text.  Also, remember the
1659      current lexing position so we can return to it later.
1660
1661      Something like line-at-a-time lexing should remove the need for
1662      this.  */
1663   saved_context = pfile->context;
1664   saved_cur_token = pfile->cur_token;
1665   saved_cur_run = pfile->cur_run;
1666
1667   pfile->context = XNEW (cpp_context);
1668   pfile->context->macro = 0;
1669   pfile->context->prev = 0;
1670   pfile->context->next = 0;
1671
1672   /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1673      until we've read all of the tokens that we want.  */
1674   cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1675                    /* from_stage3 */ true);
1676   /* ??? Antique Disgusting Hack.  What does this do?  */
1677   if (pfile->buffer->prev)
1678     pfile->buffer->file = pfile->buffer->prev->file;
1679
1680   start_directive (pfile);
1681   _cpp_clean_line (pfile);
1682   save_directive = pfile->directive;
1683   pfile->directive = &dtable[T_PRAGMA];
1684   do_pragma (pfile);
1685   end_directive (pfile, 1);
1686   pfile->directive = save_directive;
1687
1688   /* We always insert at least one token, the directive result.  It'll
1689      either be a CPP_PADDING or a CPP_PRAGMA.  In the later case, we 
1690      need to insert *all* of the tokens, including the CPP_PRAGMA_EOL.  */
1691
1692   /* If we're not handling the pragma internally, read all of the tokens from
1693      the string buffer now, while the string buffer is still installed.  */
1694   /* ??? Note that the token buffer allocated here is leaked.  It's not clear
1695      to me what the true lifespan of the tokens are.  It would appear that
1696      the lifespan is the entire parse of the main input stream, in which case
1697      this may not be wrong.  */
1698   if (pfile->directive_result.type == CPP_PRAGMA)
1699     {
1700       int maxcount;
1701
1702       count = 1;
1703       maxcount = 50;
1704       toks = XNEWVEC (cpp_token, maxcount);
1705       toks[0] = pfile->directive_result;
1706
1707       do
1708         {
1709           if (count == maxcount)
1710             {
1711               maxcount = maxcount * 3 / 2;
1712               toks = XRESIZEVEC (cpp_token, toks, maxcount);
1713             }
1714           toks[count] = *cpp_get_token (pfile);
1715           /* Macros have been already expanded by cpp_get_token
1716              if the pragma allowed expansion.  */
1717           toks[count++].flags |= NO_EXPAND;
1718         }
1719       while (toks[count-1].type != CPP_PRAGMA_EOL);
1720     }
1721   else
1722     {
1723       count = 1;
1724       toks = XNEW (cpp_token);
1725       toks[0] = pfile->directive_result;
1726
1727       /* If we handled the entire pragma internally, make sure we get the
1728          line number correct for the next token.  */
1729       if (pfile->cb.line_change)
1730         pfile->cb.line_change (pfile, pfile->cur_token, false);
1731     }
1732
1733   /* Finish inlining run_directive.  */
1734   pfile->buffer->file = NULL;
1735   _cpp_pop_buffer (pfile);
1736
1737   /* Reset the old macro state before ...  */
1738   XDELETE (pfile->context);
1739   pfile->context = saved_context;
1740   pfile->cur_token = saved_cur_token;
1741   pfile->cur_run = saved_cur_run;
1742
1743   /* ... inserting the new tokens we collected.  */
1744   _cpp_push_token_context (pfile, NULL, toks, count);
1745 }
1746
1747 /* Handle the _Pragma operator.  Return 0 on error, 1 if ok.  */
1748 int
1749 _cpp_do__Pragma (cpp_reader *pfile)
1750 {
1751   const cpp_token *string = get__Pragma_string (pfile);
1752   pfile->directive_result.type = CPP_PADDING;
1753
1754   if (string)
1755     {
1756       destringize_and_run (pfile, &string->val.str);
1757       return 1;
1758     }
1759   cpp_error (pfile, CPP_DL_ERROR,
1760              "_Pragma takes a parenthesized string literal");
1761   return 0;
1762 }
1763
1764 /* Handle #ifdef.  */
1765 static void
1766 do_ifdef (cpp_reader *pfile)
1767 {
1768   int skip = 1;
1769
1770   if (! pfile->state.skipping)
1771     {
1772       cpp_hashnode *node = lex_macro_node (pfile, false);
1773
1774       if (node)
1775         {
1776           skip = node->type != NT_MACRO;
1777           _cpp_mark_macro_used (node);
1778           if (!(node->flags & NODE_USED))
1779             {
1780               node->flags |= NODE_USED;
1781               if (node->type == NT_MACRO)
1782                 {
1783                   if (pfile->cb.used_define)
1784                     pfile->cb.used_define (pfile, pfile->directive_line, node);
1785                 }
1786               else
1787                 {
1788                   if (pfile->cb.used_undef)
1789                     pfile->cb.used_undef (pfile, pfile->directive_line, node);
1790                 }
1791             }
1792           check_eol (pfile);
1793         }
1794     }
1795
1796   push_conditional (pfile, skip, T_IFDEF, 0);
1797 }
1798
1799 /* Handle #ifndef.  */
1800 static void
1801 do_ifndef (cpp_reader *pfile)
1802 {
1803   int skip = 1;
1804   cpp_hashnode *node = 0;
1805
1806   if (! pfile->state.skipping)
1807     {
1808       node = lex_macro_node (pfile, false);
1809
1810       if (node)
1811         {
1812           skip = node->type == NT_MACRO;
1813           _cpp_mark_macro_used (node);
1814           if (!(node->flags & NODE_USED))
1815             {
1816               node->flags |= NODE_USED;
1817               if (node->type == NT_MACRO)
1818                 {
1819                   if (pfile->cb.used_define)
1820                     pfile->cb.used_define (pfile, pfile->directive_line, node);
1821                 }
1822               else
1823                 {
1824                   if (pfile->cb.used_undef)
1825                     pfile->cb.used_undef (pfile, pfile->directive_line, node);
1826                 }
1827             }
1828           check_eol (pfile);
1829         }
1830     }
1831
1832   push_conditional (pfile, skip, T_IFNDEF, node);
1833 }
1834
1835 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1836    pfile->mi_ind_cmacro so we can handle multiple-include
1837    optimizations.  If macro expansion occurs in the expression, we
1838    cannot treat it as a controlling conditional, since the expansion
1839    could change in the future.  That is handled by cpp_get_token.  */
1840 static void
1841 do_if (cpp_reader *pfile)
1842 {
1843   int skip = 1;
1844
1845   if (! pfile->state.skipping)
1846     skip = _cpp_parse_expr (pfile, true) == false;
1847
1848   push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1849 }
1850
1851 /* Flip skipping state if appropriate and continue without changing
1852    if_stack; this is so that the error message for missing #endif's
1853    etc. will point to the original #if.  */
1854 static void
1855 do_else (cpp_reader *pfile)
1856 {
1857   cpp_buffer *buffer = pfile->buffer;
1858   struct if_stack *ifs = buffer->if_stack;
1859
1860   if (ifs == NULL)
1861     cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
1862   else
1863     {
1864       if (ifs->type == T_ELSE)
1865         {
1866           cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
1867           cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
1868                                "the conditional began here");
1869         }
1870       ifs->type = T_ELSE;
1871
1872       /* Skip any future (erroneous) #elses or #elifs.  */
1873       pfile->state.skipping = ifs->skip_elses;
1874       ifs->skip_elses = true;
1875
1876       /* Invalidate any controlling macro.  */
1877       ifs->mi_cmacro = 0;
1878
1879       /* Only check EOL if was not originally skipping.  */
1880       if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1881         check_eol (pfile);
1882     }
1883 }
1884
1885 /* Handle a #elif directive by not changing if_stack either.  See the
1886    comment above do_else.  */
1887 static void
1888 do_elif (cpp_reader *pfile)
1889 {
1890   cpp_buffer *buffer = pfile->buffer;
1891   struct if_stack *ifs = buffer->if_stack;
1892
1893   if (ifs == NULL)
1894     cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
1895   else
1896     {
1897       if (ifs->type == T_ELSE)
1898         {
1899           cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
1900           cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
1901                                "the conditional began here");
1902         }
1903       ifs->type = T_ELIF;
1904
1905       if (! ifs->was_skipping)
1906         {
1907           bool value;
1908           /* The standard mandates that the expression be parsed even
1909              if we are skipping elses at this point -- the lexical
1910              restrictions on #elif only apply to skipped groups, but
1911              this group is not being skipped.  Temporarily set
1912              skipping to false to get lexer warnings.  */
1913           pfile->state.skipping = 0;
1914           value = _cpp_parse_expr (pfile, false);
1915           if (ifs->skip_elses)
1916             pfile->state.skipping = 1;
1917           else
1918             {
1919               pfile->state.skipping = ! value;
1920               ifs->skip_elses = value;
1921             }
1922         }
1923
1924       /* Invalidate any controlling macro.  */
1925       ifs->mi_cmacro = 0;
1926     }
1927 }
1928
1929 /* #endif pops the if stack and resets pfile->state.skipping.  */
1930 static void
1931 do_endif (cpp_reader *pfile)
1932 {
1933   cpp_buffer *buffer = pfile->buffer;
1934   struct if_stack *ifs = buffer->if_stack;
1935
1936   if (ifs == NULL)
1937     cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
1938   else
1939     {
1940       /* Only check EOL if was not originally skipping.  */
1941       if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1942         check_eol (pfile);
1943
1944       /* If potential control macro, we go back outside again.  */
1945       if (ifs->next == 0 && ifs->mi_cmacro)
1946         {
1947           pfile->mi_valid = true;
1948           pfile->mi_cmacro = ifs->mi_cmacro;
1949         }
1950
1951       buffer->if_stack = ifs->next;
1952       pfile->state.skipping = ifs->was_skipping;
1953       obstack_free (&pfile->buffer_ob, ifs);
1954     }
1955 }
1956
1957 /* Push an if_stack entry for a preprocessor conditional, and set
1958    pfile->state.skipping to SKIP.  If TYPE indicates the conditional
1959    is #if or #ifndef, CMACRO is a potentially controlling macro, and
1960    we need to check here that we are at the top of the file.  */
1961 static void
1962 push_conditional (cpp_reader *pfile, int skip, int type,
1963                   const cpp_hashnode *cmacro)
1964 {
1965   struct if_stack *ifs;
1966   cpp_buffer *buffer = pfile->buffer;
1967
1968   ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
1969   ifs->line = pfile->directive_line;
1970   ifs->next = buffer->if_stack;
1971   ifs->skip_elses = pfile->state.skipping || !skip;
1972   ifs->was_skipping = pfile->state.skipping;
1973   ifs->type = type;
1974   /* This condition is effectively a test for top-of-file.  */
1975   if (pfile->mi_valid && pfile->mi_cmacro == 0)
1976     ifs->mi_cmacro = cmacro;
1977   else
1978     ifs->mi_cmacro = 0;
1979
1980   pfile->state.skipping = skip;
1981   buffer->if_stack = ifs;
1982 }
1983
1984 /* Read the tokens of the answer into the macro pool, in a directive
1985    of type TYPE.  Only commit the memory if we intend it as permanent
1986    storage, i.e. the #assert case.  Returns 0 on success, and sets
1987    ANSWERP to point to the answer.  */
1988 static int
1989 parse_answer (cpp_reader *pfile, struct answer **answerp, int type)
1990 {
1991   const cpp_token *paren;
1992   struct answer *answer;
1993   unsigned int acount;
1994
1995   /* In a conditional, it is legal to not have an open paren.  We
1996      should save the following token in this case.  */
1997   paren = cpp_get_token (pfile);
1998
1999   /* If not a paren, see if we're OK.  */
2000   if (paren->type != CPP_OPEN_PAREN)
2001     {
2002       /* In a conditional no answer is a test for any answer.  It
2003          could be followed by any token.  */
2004       if (type == T_IF)
2005         {
2006           _cpp_backup_tokens (pfile, 1);
2007           return 0;
2008         }
2009
2010       /* #unassert with no answer is valid - it removes all answers.  */
2011       if (type == T_UNASSERT && paren->type == CPP_EOF)
2012         return 0;
2013
2014       cpp_error (pfile, CPP_DL_ERROR, "missing '(' after predicate");
2015       return 1;
2016     }
2017
2018   for (acount = 0;; acount++)
2019     {
2020       size_t room_needed;
2021       const cpp_token *token = cpp_get_token (pfile);
2022       cpp_token *dest;
2023
2024       if (token->type == CPP_CLOSE_PAREN)
2025         break;
2026
2027       if (token->type == CPP_EOF)
2028         {
2029           cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2030           return 1;
2031         }
2032
2033       /* struct answer includes the space for one token.  */
2034       room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
2035
2036       if (BUFF_ROOM (pfile->a_buff) < room_needed)
2037         _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
2038
2039       dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
2040       *dest = *token;
2041
2042       /* Drop whitespace at start, for answer equivalence purposes.  */
2043       if (acount == 0)
2044         dest->flags &= ~PREV_WHITE;
2045     }
2046
2047   if (acount == 0)
2048     {
2049       cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2050       return 1;
2051     }
2052
2053   answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
2054   answer->count = acount;
2055   answer->next = NULL;
2056   *answerp = answer;
2057
2058   return 0;
2059 }
2060
2061 /* Parses an assertion directive of type TYPE, returning a pointer to
2062    the hash node of the predicate, or 0 on error.  If an answer was
2063    supplied, it is placed in ANSWERP, otherwise it is set to 0.  */
2064 static cpp_hashnode *
2065 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
2066 {
2067   cpp_hashnode *result = 0;
2068   const cpp_token *predicate;
2069
2070   /* We don't expand predicates or answers.  */
2071   pfile->state.prevent_expansion++;
2072
2073   *answerp = 0;
2074   predicate = cpp_get_token (pfile);
2075   if (predicate->type == CPP_EOF)
2076     cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2077   else if (predicate->type != CPP_NAME)
2078     cpp_error (pfile, CPP_DL_ERROR, "predicate must be an identifier");
2079   else if (parse_answer (pfile, answerp, type) == 0)
2080     {
2081       unsigned int len = NODE_LEN (predicate->val.node);
2082       unsigned char *sym = (unsigned char *) alloca (len + 1);
2083
2084       /* Prefix '#' to get it out of macro namespace.  */
2085       sym[0] = '#';
2086       memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
2087       result = cpp_lookup (pfile, sym, len + 1);
2088     }
2089
2090   pfile->state.prevent_expansion--;
2091   return result;
2092 }
2093
2094 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2095    or a pointer to NULL if the answer is not in the chain.  */
2096 static struct answer **
2097 find_answer (cpp_hashnode *node, const struct answer *candidate)
2098 {
2099   unsigned int i;
2100   struct answer **result;
2101
2102   for (result = &node->value.answers; *result; result = &(*result)->next)
2103     {
2104       struct answer *answer = *result;
2105
2106       if (answer->count == candidate->count)
2107         {
2108           for (i = 0; i < answer->count; i++)
2109             if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
2110               break;
2111
2112           if (i == answer->count)
2113             break;
2114         }
2115     }
2116
2117   return result;
2118 }
2119
2120 /* Test an assertion within a preprocessor conditional.  Returns
2121    nonzero on failure, zero on success.  On success, the result of
2122    the test is written into VALUE, otherwise the value 0.  */
2123 int
2124 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2125 {
2126   struct answer *answer;
2127   cpp_hashnode *node;
2128
2129   node = parse_assertion (pfile, &answer, T_IF);
2130
2131   /* For recovery, an erroneous assertion expression is handled as a
2132      failing assertion.  */
2133   *value = 0;
2134
2135   if (node)
2136     *value = (node->type == NT_ASSERTION &&
2137               (answer == 0 || *find_answer (node, answer) != 0));
2138   else if (pfile->cur_token[-1].type == CPP_EOF)
2139     _cpp_backup_tokens (pfile, 1);
2140
2141   /* We don't commit the memory for the answer - it's temporary only.  */
2142   return node == 0;
2143 }
2144
2145 /* Handle #assert.  */
2146 static void
2147 do_assert (cpp_reader *pfile)
2148 {
2149   struct answer *new_answer;
2150   cpp_hashnode *node;
2151
2152   node = parse_assertion (pfile, &new_answer, T_ASSERT);
2153   if (node)
2154     {
2155       size_t answer_size;
2156
2157       /* Place the new answer in the answer list.  First check there
2158          is not a duplicate.  */
2159       new_answer->next = 0;
2160       if (node->type == NT_ASSERTION)
2161         {
2162           if (*find_answer (node, new_answer))
2163             {
2164               cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2165                          NODE_NAME (node) + 1);
2166               return;
2167             }
2168           new_answer->next = node->value.answers;
2169         }
2170
2171       answer_size = sizeof (struct answer) + ((new_answer->count - 1)
2172                                               * sizeof (cpp_token));
2173       /* Commit or allocate storage for the object.  */
2174       if (pfile->hash_table->alloc_subobject)
2175         {
2176           struct answer *temp_answer = new_answer;
2177           new_answer = (struct answer *) pfile->hash_table->alloc_subobject
2178             (answer_size);
2179           memcpy (new_answer, temp_answer, answer_size);
2180         }
2181       else
2182         BUFF_FRONT (pfile->a_buff) += answer_size;
2183
2184       node->type = NT_ASSERTION;
2185       node->value.answers = new_answer;
2186       check_eol (pfile);
2187     }
2188 }
2189
2190 /* Handle #unassert.  */
2191 static void
2192 do_unassert (cpp_reader *pfile)
2193 {
2194   cpp_hashnode *node;
2195   struct answer *answer;
2196
2197   node = parse_assertion (pfile, &answer, T_UNASSERT);
2198   /* It isn't an error to #unassert something that isn't asserted.  */
2199   if (node && node->type == NT_ASSERTION)
2200     {
2201       if (answer)
2202         {
2203           struct answer **p = find_answer (node, answer), *temp;
2204
2205           /* Remove the answer from the list.  */
2206           temp = *p;
2207           if (temp)
2208             *p = temp->next;
2209
2210           /* Did we free the last answer?  */
2211           if (node->value.answers == 0)
2212             node->type = NT_VOID;
2213
2214           check_eol (pfile);
2215         }
2216       else
2217         _cpp_free_definition (node);
2218     }
2219
2220   /* We don't commit the memory for the answer - it's temporary only.  */
2221 }
2222
2223 /* These are for -D, -U, -A.  */
2224
2225 /* Process the string STR as if it appeared as the body of a #define.
2226    If STR is just an identifier, define it with value 1.
2227    If STR has anything after the identifier, then it should
2228    be identifier=definition.  */
2229 void
2230 cpp_define (cpp_reader *pfile, const char *str)
2231 {
2232   char *buf, *p;
2233   size_t count;
2234
2235   /* Copy the entire option so we can modify it.
2236      Change the first "=" in the string to a space.  If there is none,
2237      tack " 1" on the end.  */
2238
2239   count = strlen (str);
2240   buf = (char *) alloca (count + 3);
2241   memcpy (buf, str, count);
2242
2243   p = strchr (str, '=');
2244   if (p)
2245     buf[p - str] = ' ';
2246   else
2247     {
2248       buf[count++] = ' ';
2249       buf[count++] = '1';
2250     }
2251   buf[count] = '\n';
2252
2253   run_directive (pfile, T_DEFINE, buf, count);
2254 }
2255
2256
2257 /* Use to build macros to be run through cpp_define() as
2258    described above.
2259    Example: cpp_define_formatted (pfile, "MACRO=%d", value);  */
2260
2261 void
2262 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2263 {
2264   char *ptr = NULL;
2265
2266   va_list ap;
2267   va_start (ap, fmt);
2268   vasprintf (&ptr, fmt, ap);
2269   va_end (ap);
2270
2271   cpp_define (pfile, ptr);
2272   free (ptr);
2273 }
2274
2275
2276 /* Slight variant of the above for use by initialize_builtins.  */
2277 void
2278 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2279 {
2280   size_t len = strlen (str);
2281   char *buf = (char *) alloca (len + 1);
2282   memcpy (buf, str, len);
2283   buf[len] = '\n';
2284   run_directive (pfile, T_DEFINE, buf, len);
2285 }
2286
2287 /* Process MACRO as if it appeared as the body of an #undef.  */
2288 void
2289 cpp_undef (cpp_reader *pfile, const char *macro)
2290 {
2291   size_t len = strlen (macro);
2292   char *buf = (char *) alloca (len + 1);
2293   memcpy (buf, macro, len);
2294   buf[len] = '\n';
2295   run_directive (pfile, T_UNDEF, buf, len);
2296 }
2297
2298 /* If STR is a defined macro, return its definition node, else return NULL.  */
2299 cpp_macro *
2300 cpp_push_definition (cpp_reader *pfile, const char *str)
2301 {
2302   cpp_hashnode *node = _cpp_lex_identifier (pfile, str);
2303   if (node && node->type == NT_MACRO)
2304     return node->value.macro;
2305   else
2306     return NULL;
2307 }
2308
2309 /* Replace a previous definition DFN of the macro STR.  If DFN is NULL,
2310    then the macro should be undefined.  */
2311 void
2312 cpp_pop_definition (cpp_reader *pfile, const char *str, cpp_macro *dfn)
2313 {
2314   cpp_hashnode *node = _cpp_lex_identifier (pfile, str);
2315   if (node == NULL)
2316     return;
2317
2318   if (pfile->cb.before_define)
2319     pfile->cb.before_define (pfile);
2320
2321   if (node->type == NT_MACRO)
2322     {
2323       if (pfile->cb.undef)
2324         pfile->cb.undef (pfile, pfile->directive_line, node);
2325       if (CPP_OPTION (pfile, warn_unused_macros))
2326         _cpp_warn_if_unused_macro (pfile, node, NULL);
2327     }
2328   if (node->type != NT_VOID)
2329     _cpp_free_definition (node);
2330
2331   if (dfn)
2332     {
2333       node->type = NT_MACRO;
2334       node->value.macro = dfn;
2335       if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_")))
2336         node->flags |= NODE_WARN;
2337
2338       if (pfile->cb.define)
2339         pfile->cb.define (pfile, pfile->directive_line, node);
2340     }
2341 }
2342
2343 /* Process the string STR as if it appeared as the body of a #assert.  */
2344 void
2345 cpp_assert (cpp_reader *pfile, const char *str)
2346 {
2347   handle_assertion (pfile, str, T_ASSERT);
2348 }
2349
2350 /* Process STR as if it appeared as the body of an #unassert.  */
2351 void
2352 cpp_unassert (cpp_reader *pfile, const char *str)
2353 {
2354   handle_assertion (pfile, str, T_UNASSERT);
2355 }
2356
2357 /* Common code for cpp_assert (-A) and cpp_unassert (-A-).  */
2358 static void
2359 handle_assertion (cpp_reader *pfile, const char *str, int type)
2360 {
2361   size_t count = strlen (str);
2362   const char *p = strchr (str, '=');
2363
2364   /* Copy the entire option so we can modify it.  Change the first
2365      "=" in the string to a '(', and tack a ')' on the end.  */
2366   char *buf = (char *) alloca (count + 2);
2367
2368   memcpy (buf, str, count);
2369   if (p)
2370     {
2371       buf[p - str] = '(';
2372       buf[count++] = ')';
2373     }
2374   buf[count] = '\n';
2375   str = buf;
2376
2377   run_directive (pfile, type, str, count);
2378 }
2379
2380 /* The number of errors for a given reader.  */
2381 unsigned int
2382 cpp_errors (cpp_reader *pfile)
2383 {
2384   return pfile->errors;
2385 }
2386
2387 /* The options structure.  */
2388 cpp_options *
2389 cpp_get_options (cpp_reader *pfile)
2390 {
2391   return &pfile->opts;
2392 }
2393
2394 /* The callbacks structure.  */
2395 cpp_callbacks *
2396 cpp_get_callbacks (cpp_reader *pfile)
2397 {
2398   return &pfile->cb;
2399 }
2400
2401 /* Copy the given callbacks structure to our own.  */
2402 void
2403 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2404 {
2405   pfile->cb = *cb;
2406 }
2407
2408 /* The dependencies structure.  (Creates one if it hasn't already been.)  */
2409 struct deps *
2410 cpp_get_deps (cpp_reader *pfile)
2411 {
2412   if (!pfile->deps)
2413     pfile->deps = deps_init ();
2414   return pfile->deps;
2415 }
2416
2417 /* Push a new buffer on the buffer stack.  Returns the new buffer; it
2418    doesn't fail.  It does not generate a file change call back; that
2419    is the responsibility of the caller.  */
2420 cpp_buffer *
2421 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2422                  int from_stage3)
2423 {
2424   cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2425
2426   /* Clears, amongst other things, if_stack and mi_cmacro.  */
2427   memset (new_buffer, 0, sizeof (cpp_buffer));
2428
2429   new_buffer->next_line = new_buffer->buf = buffer;
2430   new_buffer->rlimit = buffer + len;
2431   new_buffer->from_stage3 = from_stage3;
2432   new_buffer->prev = pfile->buffer;
2433   new_buffer->need_line = true;
2434
2435   pfile->buffer = new_buffer;
2436
2437   return new_buffer;
2438 }
2439
2440 /* Pops a single buffer, with a file change call-back if appropriate.
2441    Then pushes the next -include file, if any remain.  */
2442 void
2443 _cpp_pop_buffer (cpp_reader *pfile)
2444 {
2445   cpp_buffer *buffer = pfile->buffer;
2446   struct _cpp_file *inc = buffer->file;
2447   struct if_stack *ifs;
2448
2449   /* Walk back up the conditional stack till we reach its level at
2450      entry to this file, issuing error messages.  */
2451   for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2452     cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2453                          "unterminated #%s", dtable[ifs->type].name);
2454
2455   /* In case of a missing #endif.  */
2456   pfile->state.skipping = 0;
2457
2458   /* _cpp_do_file_change expects pfile->buffer to be the new one.  */
2459   pfile->buffer = buffer->prev;
2460
2461   free (buffer->notes);
2462
2463   /* Free the buffer object now; we may want to push a new buffer
2464      in _cpp_push_next_include_file.  */
2465   obstack_free (&pfile->buffer_ob, buffer);
2466
2467   if (inc)
2468     {
2469       _cpp_pop_file_buffer (pfile, inc);
2470
2471       _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2472     }
2473 }
2474
2475 /* Enter all recognized directives in the hash table.  */
2476 void
2477 _cpp_init_directives (cpp_reader *pfile)
2478 {
2479   unsigned int i;
2480   cpp_hashnode *node;
2481
2482   for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2483     {
2484       node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2485       node->is_directive = 1;
2486       node->directive_index = i;
2487     }
2488 }