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