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