OSDN Git Service

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