OSDN Git Service

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