OSDN Git Service

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