cpplib.c 49.2 KB
Newer Older
1
/* CPP Library. (Directive handling.)
Jeff Law committed
2
   Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3
   1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4
   Contributed by Per Bothner, 1994-95.
5
   Based on CCCP program by Paul Rubin, June 1986
Per Bothner committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19
   Adapted to ANSI C, Richard Stallman, Jan 1987

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Jeff Law committed
20
Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
Per Bothner committed
21

Jeff Law committed
22
#include "config.h"
23
#include "system.h"
Per Bothner committed
24

Jeff Law committed
25 26
#include "cpplib.h"
#include "cpphash.h"
27
#include "obstack.h"
Per Bothner committed
28

Neil Booth committed
29 30 31 32 33 34 35 36
/* Chained list of answers to an assertion.  */
struct answer
{
  struct answer *next;
  unsigned int count;
  cpp_token first[1];
};

37 38 39 40 41
/* Stack of conditionals currently in progress
   (including both successful and failing conditionals).  */
struct if_stack
{
  struct if_stack *next;
42
  unsigned int line;		/* Line where condition started.  */
Neil Booth committed
43
  const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
44 45 46
  bool skip_elses;		/* Can future #else / #elif be skipped?  */
  bool was_skipping;		/* If were skipping on entry.  */
  int type;			/* Most recent conditional, for diagnostics.  */
47 48
};

49 50 51 52 53
/* Contains a registered pragma or pragma namespace.  */
typedef void (*pragma_cb) PARAMS ((cpp_reader *));
struct pragma_entry
{
  struct pragma_entry *next;
54
  const cpp_hashnode *pragma;	/* Name and length.  */
55 56 57 58 59 60 61
  int is_nspace;
  union {
    pragma_cb handler;
    struct pragma_entry *space;
  } u;
};

Neil Booth committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
/* Values for the origin field of struct directive.  KANDR directives
   come from traditional (K&R) C.  STDC89 directives come from the
   1989 C standard.  EXTENSION directives are extensions.  */
#define KANDR		0
#define STDC89		1
#define EXTENSION	2

/* Values for the flags field of struct directive.  COND indicates a
   conditional; IF_COND an opening conditional.  INCL means to treat
   "..." and <...> as q-char and h-char sequences respectively.  IN_I
   means this directive should be handled even if -fpreprocessed is in
   effect (these are the directives with callback hooks).  */
#define COND		(1 << 0)
#define IF_COND		(1 << 1)
#define INCL		(1 << 2)
#define IN_I		(1 << 3)

/* Defines one #-directive, including how to handle it.  */
typedef void (*directive_handler) PARAMS ((cpp_reader *));
typedef struct directive directive;
struct directive
{
  directive_handler handler;	/* Function to handle directive.  */
  const U_CHAR *name;		/* Name of directive.  */
  unsigned short length;	/* Length of name.  */
  unsigned char origin;		/* Origin of directive.  */
  unsigned char flags;	        /* Flags describing this directive.  */
};

91 92
/* Forward declarations.  */

Neil Booth committed
93 94
static void skip_rest_of_line	PARAMS ((cpp_reader *));
static void check_eol		PARAMS ((cpp_reader *));
95 96
static void start_directive	PARAMS ((cpp_reader *));
static void end_directive	PARAMS ((cpp_reader *, int));
97 98
static void directive_diagnostics
	PARAMS ((cpp_reader *, const directive *, int));
Neil Booth committed
99
static void run_directive	PARAMS ((cpp_reader *, int,
100
					 const char *, size_t));
101 102
static const cpp_token *glue_header_name PARAMS ((cpp_reader *));
static const cpp_token *parse_include PARAMS ((cpp_reader *));
Zack Weinberg committed
103 104
static void push_conditional	PARAMS ((cpp_reader *, int, int,
					 const cpp_hashnode *));
105
static unsigned int read_flag	PARAMS ((cpp_reader *, unsigned int));
106
static int  strtoul_for_line	PARAMS ((const U_CHAR *, unsigned int,
Zack Weinberg committed
107
					 unsigned long *));
108
static void do_diagnostic	PARAMS ((cpp_reader *, enum error_type, int));
109
static cpp_hashnode *lex_macro_node	PARAMS ((cpp_reader *));
110
static void do_include_common	PARAMS ((cpp_reader *, enum include_type));
111
static struct pragma_entry *lookup_pragma_entry
112
  PARAMS ((struct pragma_entry *, const cpp_hashnode *pragma));
113
static struct pragma_entry *insert_pragma_entry
114 115
  PARAMS ((cpp_reader *, struct pragma_entry **, const cpp_hashnode *,
	   pragma_cb));
Neil Booth committed
116 117 118 119
static void do_pragma_once	PARAMS ((cpp_reader *));
static void do_pragma_poison	PARAMS ((cpp_reader *));
static void do_pragma_system_header	PARAMS ((cpp_reader *));
static void do_pragma_dependency	PARAMS ((cpp_reader *));
120 121
static const cpp_token *get_token_no_padding PARAMS ((cpp_reader *));
static const cpp_token *get__Pragma_string PARAMS ((cpp_reader *));
122
static void destringize_and_run PARAMS ((cpp_reader *, const cpp_string *));
Neil Booth committed
123 124 125 126 127
static int parse_answer PARAMS ((cpp_reader *, struct answer **, int));
static cpp_hashnode *parse_assertion PARAMS ((cpp_reader *, struct answer **,
					      int));
static struct answer ** find_answer PARAMS ((cpp_hashnode *,
					     const struct answer *));
128
static void handle_assertion	PARAMS ((cpp_reader *, const char *, int));
129

130 131 132 133
/* This is the table of directive handlers.  It is ordered by
   frequency of occurrence; the numbers at the end are directive
   counts from all the source code I have lying around (egcs and libc
   CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
Neil Booth committed
134 135 136 137
   pcmcia-cs-3.0.9).  This is no longer important as directive lookup
   is now O(1).  All extensions other than #warning and #include_next
   are deprecated.  The name is where the extension appears to have
   come from.  */
138

Neil Booth committed
139 140 141 142 143 144 145 146 147 148
#define DIRECTIVE_TABLE							\
D(define,	T_DEFINE = 0,	KANDR,     IN_I)	   /* 270554 */ \
D(include,	T_INCLUDE,	KANDR,     INCL)	   /*  52262 */ \
D(endif,	T_ENDIF,	KANDR,     COND)	   /*  45855 */ \
D(ifdef,	T_IFDEF,	KANDR,     COND | IF_COND) /*  22000 */ \
D(if,		T_IF,		KANDR,     COND | IF_COND) /*  18162 */ \
D(else,		T_ELSE,		KANDR,     COND)	   /*   9863 */ \
D(ifndef,	T_IFNDEF,	KANDR,     COND | IF_COND) /*   9675 */ \
D(undef,	T_UNDEF,	KANDR,     IN_I)	   /*   4837 */ \
D(line,		T_LINE,		KANDR,     IN_I)	   /*   2465 */ \
149
D(elif,		T_ELIF,		STDC89,    COND)	   /*    610 */ \
Neil Booth committed
150 151 152 153 154 155 156 157 158
D(error,	T_ERROR,	STDC89,    0)		   /*    475 */ \
D(pragma,	T_PRAGMA,	STDC89,    IN_I)	   /*    195 */ \
D(warning,	T_WARNING,	EXTENSION, 0)		   /*     22 */ \
D(include_next,	T_INCLUDE_NEXT,	EXTENSION, INCL)	   /*     19 */ \
D(ident,	T_IDENT,	EXTENSION, IN_I)	   /*     11 */ \
D(import,	T_IMPORT,	EXTENSION, INCL)	   /* 0 ObjC */	\
D(assert,	T_ASSERT,	EXTENSION, 0)		   /* 0 SVR4 */	\
D(unassert,	T_UNASSERT,	EXTENSION, 0)		   /* 0 SVR4 */	\
SCCS_ENTRY						   /* 0 SVR4? */
159

160 161
/* #sccs is not always recognized.  */
#ifdef SCCS_DIRECTIVE
Zack Weinberg committed
162
# define SCCS_ENTRY D(sccs, T_SCCS, EXTENSION, 0)
163 164 165 166
#else
# define SCCS_ENTRY /* nothing */
#endif

167 168 169 170 171 172 173
/* Use the table to generate a series of prototypes, an enum for the
   directive names, and an array of directive handlers.  */

/* The directive-processing functions are declared to return int
   instead of void, because some old compilers have trouble with
   pointers to functions returning void.  */

174
/* Don't invoke CONCAT2 with any whitespace or K&R cc will fail.  */
Zack Weinberg committed
175
#define D(name, t, o, f) static void CONCAT2(do_,name) PARAMS ((cpp_reader *));
176 177 178
DIRECTIVE_TABLE
#undef D

Zack Weinberg committed
179
#define D(n, tag, o, f) tag,
180 181 182 183
enum
{
  DIRECTIVE_TABLE
  N_DIRECTIVES
Per Bothner committed
184
};
185 186
#undef D

187
/* Don't invoke CONCAT2 with any whitespace or K&R cc will fail.  */
Zack Weinberg committed
188
#define D(name, t, origin, flags) \
189
{ CONCAT2(do_,name), (const U_CHAR *) STRINGX(name), \
Zack Weinberg committed
190
  sizeof STRINGX(name) - 1, origin, flags },
Neil Booth committed
191
static const directive dtable[] =
192 193 194 195 196
{
DIRECTIVE_TABLE
};
#undef D
#undef DIRECTIVE_TABLE
Per Bothner committed
197

198
#define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
199

Neil Booth committed
200 201 202
/* Skip any remaining tokens in a directive.  */
static void
skip_rest_of_line (pfile)
Zack Weinberg committed
203
     cpp_reader *pfile;
Zack Weinberg committed
204
{
Neil Booth committed
205 206 207 208
  /* Discard all stacked contexts.  */
  while (pfile->context != &pfile->base_context)
    _cpp_pop_context (pfile);

209
  /* Sweep up all tokens remaining on the line.  */
210 211 212
  if (! SEEN_EOL ())
    while (_cpp_lex_token (pfile)->type != CPP_EOF)
      ;
Neil Booth committed
213
}
Zack Weinberg committed
214

Neil Booth committed
215 216 217 218 219
/* Ensure there are no stray tokens at the end of a directive.  */
static void
check_eol (pfile)
     cpp_reader *pfile;
{
220 221 222
  if (! SEEN_EOL () && _cpp_lex_token (pfile)->type != CPP_EOF)
    cpp_pedwarn (pfile, "extra tokens at end of #%s directive",
		 pfile->directive->name);
Neil Booth committed
223 224
}

225 226 227
/* Called when entering a directive, _Pragma or command-line directive.  */
static void
start_directive (pfile)
Neil Booth committed
228 229
     cpp_reader *pfile;
{
230 231 232 233
  /* Setup in-directive state.  */
  pfile->state.in_directive = 1;
  pfile->state.save_comments = 0;

Neil Booth committed
234
  /* Some handlers need the position of the # for diagnostics.  */
235
  pfile->directive_line = pfile->line;
236 237 238 239 240 241 242 243 244 245
}

/* Called when leaving a directive, _Pragma or command-line directive.  */
static void
end_directive (pfile, skip_line)
     cpp_reader *pfile;
     int skip_line;
{
  /* We don't skip for an assembler #.  */
  if (skip_line)
246 247
    {
      skip_rest_of_line (pfile);
248 249 250 251 252
      if (!pfile->keep_tokens)
	{
	  pfile->cur_run = &pfile->base_run;
	  pfile->cur_token = pfile->base_run.base;
	}
253
    }
254 255 256 257 258

  /* Restore state.  */
  pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
  pfile->state.in_directive = 0;
  pfile->state.angled_headers = 0;
259
  pfile->state.line_extension = 0;
260 261 262
  pfile->directive = 0;
}

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
/* Output diagnostics for a directive DIR.  INDENTED is non-zero if
   the '#' was indented.  */
static void
directive_diagnostics (pfile, dir, indented)
     cpp_reader *pfile;
     const directive *dir;
     int indented;
{
  if (pfile->state.line_extension)
    {
      if (CPP_PEDANTIC (pfile)
	  && ! pfile->state.skipping)
	cpp_pedwarn (pfile, "style of line directive is a GCC extension");
    }
  else
    {
Kazu Hirata committed
279
      /* Issue -pedantic warnings for extensions.  */
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
      if (CPP_PEDANTIC (pfile)
	  && ! pfile->state.skipping
	  && dir->origin == EXTENSION)
	cpp_pedwarn (pfile, "#%s is a GCC extension", dir->name);

      /* Traditionally, a directive is ignored unless its # is in
	 column 1.  Therefore in code intended to work with K+R
	 compilers, directives added by C89 must have their #
	 indented, and directives present in traditional C must not.
	 This is true even of directives in skipped conditional
	 blocks.  */
      if (CPP_WTRADITIONAL (pfile))
	{
	  if (dir == &dtable[T_ELIF])
	    cpp_warning (pfile, "suggest not using #elif in traditional C");
	  else if (indented && dir->origin == KANDR)
	    cpp_warning (pfile,
			 "traditional C ignores #%s with the # indented",
			 dir->name);
	  else if (!indented && dir->origin != KANDR)
	    cpp_warning (pfile,
		 "suggest hiding #%s from traditional C with an indented #",
			 dir->name);
	}
    }
}

/* Check if we have a known directive.  INDENTED is non-zero if the
   '#' of the directive was indented.  This function is in this file
   to save unnecessarily exporting dtable etc. to cpplex.c.  Returns
   non-zero if the line of tokens has been handled, zero if we should
   continue processing the line.  */
312 313 314 315 316 317
int
_cpp_handle_directive (pfile, indented)
     cpp_reader *pfile;
     int indented;
{
  const directive *dir = 0;
318
  const cpp_token *dname;
319 320 321
  int skip = 1;

  start_directive (pfile);
322
  dname = _cpp_lex_token (pfile);
323

324
  if (dname->type == CPP_NAME)
325
    {
326 327
      if (dname->val.node->directive_index)
	dir = &dtable[dname->val.node->directive_index - 1];
328
    }
329 330
  /* We do not recognise the # followed by a number extension in
     assembler code.  */
331
  else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
332
    {
333 334
      dir = &dtable[T_LINE];
      pfile->state.line_extension = 1;
Neil Booth committed
335
    }
336

Neil Booth committed
337 338
  if (dir)
    {
339 340 341 342 343 344 345 346 347 348 349 350 351
      /* If we have a directive that is not an opening conditional,
	 invalidate any control macro.  */
      if (! (dir->flags & IF_COND))
	pfile->mi_valid = false;

      /* Kluge alert.  In order to be sure that code like this

	 #define HASH #
	 HASH define foo bar

	 does not cause '#define foo bar' to get executed when
	 compiled with -save-temps, we recognize directives in
	 -fpreprocessed mode only if the # is in column 1.  cppmacro.c
352
	 puts a space in front of any '#' at the start of a macro.  */
353 354
      if (CPP_OPTION (pfile, preprocessed)
	  && (indented || !(dir->flags & IN_I)))
355
	{
356 357
	  skip = 0;
	  dir = 0;
358 359
	}
      else
Neil Booth committed
360
	{
361 362 363 364 365 366 367 368 369
	  /* In failed conditional groups, all non-conditional
	     directives are ignored.  Before doing that, whether
	     skipping or not, we should lex angle-bracketed headers
	     correctly, and maybe output some diagnostics.  */
	  pfile->state.angled_headers = dir->flags & INCL;
	  if (! CPP_OPTION (pfile, preprocessed))
	    directive_diagnostics (pfile, dir, indented);
	  if (pfile->state.skipping && !(dir->flags & COND))
	    dir = 0;
Neil Booth committed
370 371
	}
    }
372
  else if (dname->type == CPP_EOF)
373 374
    ;	/* CPP_EOF is the "null directive".  */
  else
Neil Booth committed
375 376 377 378 379
    {
      /* An unknown directive.  Don't complain about it in assembly
	 source: we don't know where the comments are, and # may
	 introduce assembler pseudo-ops.  Don't complain about invalid
	 directives in skipped conditional groups (6.10 p4).  */
380
      if (CPP_OPTION (pfile, lang) == CLK_ASM)
381 382
	skip = 0;
      else if (!pfile->state.skipping)
Neil Booth committed
383
	cpp_error (pfile, "invalid preprocessing directive #%s",
384
		   cpp_token_as_text (pfile, dname));
385 386
    }

387 388 389 390 391 392 393 394 395
  if (dir)
    {
      pfile->directive = dir;
      (*pfile->directive->handler) (pfile);
    }
  else if (skip == 0)
    _cpp_backup_tokens (pfile, 1);

  end_directive (pfile, skip);
396
  return skip;
Zack Weinberg committed
397
}
Per Bothner committed
398

Neil Booth committed
399 400 401
/* Directive handler wrapper used by the command line option
   processor.  */
static void
402
run_directive (pfile, dir_no, buf, count)
Per Bothner committed
403
     cpp_reader *pfile;
Neil Booth committed
404 405 406
     int dir_no;
     const char *buf;
     size_t count;
407
{
408 409
  cpp_push_buffer (pfile, (const U_CHAR *) buf, count,
		   /* from_stage3 */ true, 1);
410
  start_directive (pfile);
411 412
  /* We don't want a leading # to be interpreted as a directive.  */
  pfile->buffer->saved_flags = 0;
413 414
  pfile->directive = &dtable[dir_no];
  (void) (*pfile->directive->handler) (pfile);
415
  end_directive (pfile, 1);
416
  _cpp_pop_buffer (pfile);
Neil Booth committed
417 418 419 420
}

/* Checks for validity the macro name in #define, #undef, #ifdef and
   #ifndef directives.  */
Zack Weinberg committed
421
static cpp_hashnode *
Neil Booth committed
422
lex_macro_node (pfile)
Zack Weinberg committed
423 424
     cpp_reader *pfile;
{
425
  cpp_hashnode *node;
426
  const cpp_token *token = _cpp_lex_token (pfile);
427

428
  /* The token immediately after #define must be an identifier.  That
429 430 431 432 433
     identifier may not be "defined", per C99 6.10.8p4.
     In C++, it may not be any of the "named operators" either,
     per C++98 [lex.digraph], [lex.key].
     Finally, the identifier may not have been poisoned.  (In that case
     the lexer has issued the error message for us.)  */
434

435
  if (token->type != CPP_NAME)
Per Bothner committed
436
    {
437
      if (token->type == CPP_EOF)
Neil Booth committed
438 439
	cpp_error (pfile, "no macro name given in #%s directive",
		   pfile->directive->name);
440
      else if (token->flags & NAMED_OP)
Neil Booth committed
441
	cpp_error (pfile,
442
	   "\"%s\" cannot be used as a macro name as it is an operator in C++",
443
		   NODE_NAME (token->val.node));
444
      else
Neil Booth committed
445
	cpp_error (pfile, "macro names must be identifiers");
446 447

      return 0;
448
    }
449

450
  node = token->val.node;
451 452 453 454
  if (node->flags & NODE_POISONED)
    return 0;

  if (node == pfile->spec_nodes.n_defined)
455
    {
456 457 458
      cpp_error (pfile, "\"%s\" cannot be used as a macro name",
		 NODE_NAME (node));
      return 0;
459 460
    }

461
  return node;
Per Bothner committed
462 463
}

Neil Booth committed
464
/* Process a #define directive.  Most work is done in cppmacro.c.  */
Zack Weinberg committed
465
static void
466
do_define (pfile)
Per Bothner committed
467 468
     cpp_reader *pfile;
{
Neil Booth committed
469
  cpp_hashnode *node = lex_macro_node (pfile);
470

Neil Booth committed
471 472 473 474
  if (node)
    {
      if (_cpp_create_definition (pfile, node))
	if (pfile->cb.define)
475
	  (*pfile->cb.define) (pfile, pfile->directive_line, node);
Neil Booth committed
476
    }
Zack Weinberg committed
477 478
}

479
/* Handle #undef.  Mark the identifier NT_VOID in the hash table.  */
Zack Weinberg committed
480
static void
Zack Weinberg committed
481 482 483
do_undef (pfile)
     cpp_reader *pfile;
{
Neil Booth committed
484
  cpp_hashnode *node = lex_macro_node (pfile);  
485

Zack Weinberg committed
486 487
  /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified identifier
     is not currently defined as a macro name.  */
Neil Booth committed
488
  if (node && node->type == NT_MACRO)
489
    {
490
      if (pfile->cb.undef)
491
	(*pfile->cb.undef) (pfile, pfile->directive_line, node);
492

493
      if (node->flags & NODE_WARN)
494
	cpp_warning (pfile, "undefining \"%s\"", NODE_NAME (node));
495

Zack Weinberg committed
496
      _cpp_free_definition (node);
497
    }
Neil Booth committed
498
  check_eol (pfile);
Per Bothner committed
499 500
}

Neil Booth committed
501 502
/* Helper routine used by parse_include.  Reinterpret the current line
   as an h-char-sequence (< ... >); we are looking at the first token
503 504 505
   after the <.  Returns the header as a token, or NULL on failure.  */
static const cpp_token *
glue_header_name (pfile)
Neil Booth committed
506 507
     cpp_reader *pfile;
{
508 509
  cpp_token *header = NULL;
  const cpp_token *token;
510 511
  unsigned char *dest;
  size_t len;
Neil Booth committed
512 513 514 515

  /* To avoid lexed tokens overwriting our glued name, we can only
     allocate from the string pool once we've lexed everything.  */

516
  dest = BUFF_FRONT (pfile->u_buff);
Neil Booth committed
517 518
  for (;;)
    {
519
      token = cpp_get_token (pfile);
Neil Booth committed
520

521
      if (token->type == CPP_GREATER || token->type == CPP_EOF)
Neil Booth committed
522 523
	break;

524 525 526
      /* + 1 for terminating NUL.  */
      len = cpp_token_len (token) + 1;
      if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
Neil Booth committed
527
	{
528
	  size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
529
	  _cpp_extend_buff (pfile, &pfile->u_buff, len);
530
	  dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
Neil Booth committed
531 532
	}

533
      if (token->flags & PREV_WHITE)
534
	*dest++ = ' ';
Neil Booth committed
535

536
      dest = cpp_spell_token (pfile, token, dest);
Neil Booth committed
537 538
    }

539
  if (token->type == CPP_EOF)
Neil Booth committed
540 541 542
    cpp_error (pfile, "missing terminating > character");
  else
    {
543
      header = _cpp_temp_token (pfile);
Neil Booth committed
544
      header->type = CPP_HEADER_NAME;
545 546 547 548 549
      header->flags = 0;
      header->val.str.len = dest - BUFF_FRONT (pfile->u_buff);
      header->val.str.text = BUFF_FRONT (pfile->u_buff);
      *dest++ = '\0';
      BUFF_FRONT (pfile->u_buff) = dest;
Neil Booth committed
550
    }
Zack Weinberg committed
551

552
  return header;
Neil Booth committed
553
}
Per Bothner committed
554

555 556 557 558
/* Returns the header string of #include, #include_next, #import and
   #pragma dependency.  Returns NULL on error.  */
static const cpp_token *
parse_include (pfile)
Per Bothner committed
559 560
     cpp_reader *pfile;
{
Neil Booth committed
561
  const unsigned char *dir;
562
  const cpp_token *header;
Per Bothner committed
563

564
  if (pfile->directive == &dtable[T_PRAGMA])
Neil Booth committed
565 566 567 568 569
    dir = U"pragma dependency";
  else
    dir = pfile->directive->name;

  /* Allow macro expansion.  */
570
  header = cpp_get_token (pfile);
Neil Booth committed
571
  if (header->type != CPP_STRING && header->type != CPP_HEADER_NAME)
Per Bothner committed
572
    {
Neil Booth committed
573
      if (header->type != CPP_LESS)
Zack Weinberg committed
574 575
	{
	  cpp_error (pfile, "#%s expects \"FILENAME\" or <FILENAME>", dir);
576
	  return NULL;
Zack Weinberg committed
577
	}
578 579 580 581

      header = glue_header_name (pfile);
      if (header == NULL)
	return header;
Per Bothner committed
582
    }
Neil Booth committed
583 584

  if (header->val.str.len == 0)
Per Bothner committed
585
    {
Zack Weinberg committed
586
      cpp_error (pfile, "empty file name in #%s", dir);
587
      return NULL;
Per Bothner committed
588 589
    }

590
  return header;
591
}
592

593
/* Handle #include, #include_next and #import.  */
Zack Weinberg committed
594
static void
595
do_include_common (pfile, type)
596
     cpp_reader *pfile;
597
     enum include_type type;
598
{
599
  const cpp_token *header;
Per Bothner committed
600

601 602 603 604 605 606 607 608 609 610 611 612 613 614
  /* For #include_next, if this is the primary source file, warn and
     use the normal search logic.  */
  if (type == IT_INCLUDE_NEXT && ! pfile->buffer->prev)
    {
      cpp_warning (pfile, "#include_next in primary source file");
      type = IT_INCLUDE;
    }
  else if (type == IT_IMPORT && CPP_OPTION (pfile, warn_import))
    {
      CPP_OPTION (pfile, warn_import) = 0;
      cpp_warning (pfile,
	   "#import is obsolete, use an #ifndef wrapper in the header file");
    }

615 616
  header = parse_include (pfile);
  if (header)
617 618
    {
      /* Prevent #include recursion.  */
619
      if (pfile->line_maps.depth >= CPP_STACK_MAX)
620 621 622
	cpp_fatal (pfile, "#include nested too deeply");
      else
	{
623 624
	  check_eol (pfile);
	  /* Get out of macro context, if we are.  */
625
	  skip_rest_of_line (pfile);
626
	  if (pfile->cb.include)
627
	    (*pfile->cb.include) (pfile, pfile->directive_line,
628
				  pfile->directive->name, header);
629

630
	  _cpp_execute_include (pfile, header, type);
631 632
	}
    }
633
}
634

Zack Weinberg committed
635
static void
636
do_include (pfile)
637 638
     cpp_reader *pfile;
{
639 640
  do_include_common (pfile, IT_INCLUDE);
}
641

642 643 644 645 646
static void
do_import (pfile)
     cpp_reader *pfile;
{
  do_include_common (pfile, IT_IMPORT);
647
}
Per Bothner committed
648

Zack Weinberg committed
649
static void
650 651 652
do_include_next (pfile)
     cpp_reader *pfile;
{
653
  do_include_common (pfile, IT_INCLUDE_NEXT);
Per Bothner committed
654 655
}

656 657 658
/* Subroutine of do_line.  Read possible flags after file name.  LAST
   is the last flag seen; 0 if this is the first flag. Return the flag
   if it is valid, 0 at the end of the directive. Otherwise complain.  */
659
static unsigned int
660
read_flag (pfile, last)
661
     cpp_reader *pfile;
662
     unsigned int last;
663
{
664
  const cpp_token *token = _cpp_lex_token (pfile);
665

666
  if (token->type == CPP_NUMBER && token->val.str.len == 1)
667
    {
668
      unsigned int flag = token->val.str.text[0] - '0';
669 670 671 672 673

      if (flag > last && flag <= 4
	  && (flag != 4 || last == 3)
	  && (flag != 2 || last == 0))
	return flag;
674
    }
Neil Booth committed
675

676
  if (token->type != CPP_EOF)
677
    cpp_error (pfile, "invalid flag \"%s\" in line directive",
678
	       cpp_token_as_text (pfile, token));
Neil Booth committed
679
  return 0;
680 681
}

Zack Weinberg committed
682 683
/* Another subroutine of do_line.  Convert a number in STR, of length
   LEN, to binary; store it in NUMP, and return 0 if the number was
684
   well-formed, 1 if not.  Temporary, hopefully.  */
Zack Weinberg committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
static int
strtoul_for_line (str, len, nump)
     const U_CHAR *str;
     unsigned int len;
     unsigned long *nump;
{
  unsigned long reg = 0;
  U_CHAR c;
  while (len--)
    {
      c = *str++;
      if (!ISDIGIT (c))
	return 1;
      reg *= 10;
      reg += c - '0';
    }
  *nump = reg;
  return 0;
}

705 706 707
/* Interpret #line command.
   Note that the filename string (if any) is treated as if it were an
   include filename.  That means no escape handling.  */
Zack Weinberg committed
708
static void
709
do_line (pfile)
Per Bothner committed
710 711
     cpp_reader *pfile;
{
712
  const cpp_token *token;
713 714 715 716
  const char *new_file = pfile->map->to_file;
  unsigned long new_lineno;
  unsigned int cap, new_sysp = pfile->map->sysp;
  enum lc_reason reason = LC_RENAME;
Neil Booth committed
717

718 719 720
  /* C99 raised the minimum limit on #line numbers.  */
  cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;

721 722 723 724 725
  /* Putting this in _cpp_handle_directive risks two calls to
     _cpp_backup_tokens in some circumstances, which can segfault.  */
  if (pfile->state.line_extension)
    _cpp_backup_tokens (pfile, 1);

Neil Booth committed
726
  /* #line commands expand macros.  */
727 728 729 730
  token = cpp_get_token (pfile);
  if (token->type != CPP_NUMBER
      || strtoul_for_line (token->val.str.text, token->val.str.len,
			   &new_lineno))
Per Bothner committed
731
    {
Neil Booth committed
732
      cpp_error (pfile, "\"%s\" after #line is not a positive integer",
733
		 cpp_token_as_text (pfile, token));
734
      return;
735
    }      
Per Bothner committed
736

Neil Booth committed
737 738
  if (CPP_PEDANTIC (pfile) && ! pfile->state.line_extension
      && (new_lineno == 0 || new_lineno > cap))
Zack Weinberg committed
739
    cpp_pedwarn (pfile, "line number out of range");
Per Bothner committed
740

741 742
  token = cpp_get_token (pfile);
  if (token->type == CPP_STRING)
743
    {
744
      new_file = (const char *) token->val.str.text;
745

746
      /* Only accept flags for the # 55 form.  */
747
      if (pfile->state.line_extension)
Neil Booth committed
748
	{
Neil Booth committed
749
	  int flag;
750

751
	  new_sysp = 0;
Neil Booth committed
752
	  flag = read_flag (pfile, 0);
753
	  if (flag == 1)
Neil Booth committed
754
	    {
Neil Booth committed
755
	      reason = LC_ENTER;
756
	      /* Fake an include for cpp_included ().  */
757
	      _cpp_fake_include (pfile, new_file);
758
	      flag = read_flag (pfile, flag);
Neil Booth committed
759
	    }
760
	  else if (flag == 2)
Neil Booth committed
761
	    {
Neil Booth committed
762
	      reason = LC_LEAVE;
763
	      flag = read_flag (pfile, flag);
Neil Booth committed
764
	    }
765
	  if (flag == 3)
Neil Booth committed
766
	    {
767
	      new_sysp = 1;
768 769
	      flag = read_flag (pfile, flag);
	      if (flag == 4)
770
		new_sysp = 2;
771
	    }
Neil Booth committed
772
	}
773
      check_eol (pfile);
Zack Weinberg committed
774
    }
775
  else if (token->type != CPP_EOF)
776 777
    {
      cpp_error (pfile, "\"%s\" is not a valid filename",
778
		 cpp_token_as_text (pfile, token));
779 780
      return;
    }
Per Bothner committed
781

782
  skip_rest_of_line (pfile);
783
  _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
784 785
}

786
/* Arrange the file_change callback.  pfile->line has changed to
Neil Booth committed
787
   FILE_LINE of TO_FILE, for reason REASON.  SYSP is 1 for a system
788
   header, 2 for a system header that needs to be extern "C" protected,
Neil Booth committed
789
   and zero otherwise.  */
790
void
Neil Booth committed
791
_cpp_do_file_change (pfile, reason, to_file, file_line, sysp)
792
     cpp_reader *pfile;
Neil Booth committed
793
     enum lc_reason reason;
Neil Booth committed
794
     const char *to_file;
795
     unsigned int file_line;
Neil Booth committed
796
     unsigned int sysp;
797
{
Neil Booth committed
798 799
  pfile->map = add_line_map (&pfile->line_maps, reason, sysp,
			     pfile->line, to_file, file_line);
Neil Booth committed
800

801
  if (pfile->cb.file_change)
Neil Booth committed
802
    (*pfile->cb.file_change) (pfile, pfile->map);
Per Bothner committed
803
}
804

805 806
/* Report a warning or error detected by the program we are
   processing.  Use the directive's tokens in the error message.  */
Zack Weinberg committed
807
static void
808
do_diagnostic (pfile, code, print_dir)
Per Bothner committed
809
     cpp_reader *pfile;
810
     enum error_type code;
811
     int print_dir;
Per Bothner committed
812
{
813
  if (_cpp_begin_message (pfile, code, 0, 0))
814
    {
815 816
      if (print_dir)
	fprintf (stderr, "#%s ", pfile->directive->name);
Neil Booth committed
817 818 819
      pfile->state.prevent_expansion++;
      cpp_output_line (pfile, stderr);
      pfile->state.prevent_expansion--;
820
    }
Per Bothner committed
821 822
}

823 824 825 826
static void
do_error (pfile)
     cpp_reader *pfile;
{
827
  do_diagnostic (pfile, ERROR, 1);
828
}
Per Bothner committed
829

Zack Weinberg committed
830
static void
831
do_warning (pfile)
Per Bothner committed
832 833
     cpp_reader *pfile;
{
834 835
  /* We want #warning diagnostics to be emitted in system headers too.  */
  do_diagnostic (pfile, WARNING_SYSHDR, 1);
Per Bothner committed
836 837
}

838
/* Report program identification.  */
Zack Weinberg committed
839
static void
840
do_ident (pfile)
Per Bothner committed
841 842
     cpp_reader *pfile;
{
843
  const cpp_token *str = cpp_get_token (pfile);
844

845 846
  if (str->type != CPP_STRING)
    cpp_error (pfile, "invalid #ident directive");
Neil Booth committed
847
  else if (pfile->cb.ident)
848
    (*pfile->cb.ident) (pfile, pfile->directive_line, &str->val.str);
849

Neil Booth committed
850
  check_eol (pfile);
Per Bothner committed
851 852
}

853 854 855 856 857 858
/* Lookup a PRAGMA name in a singly-linked CHAIN.  Returns the
   matching entry, or NULL if none is found.  The returned entry could
   be the start of a namespace chain, or a pragma.  */
static struct pragma_entry *
lookup_pragma_entry (chain, pragma)
     struct pragma_entry *chain;
859
     const cpp_hashnode *pragma;
860
{
861 862
  while (chain && chain->pragma != pragma)
    chain = chain->next;
863 864 865 866 867 868 869 870

  return chain;
}

/* Create and insert a pragma entry for NAME at the beginning of a
   singly-linked CHAIN.  If handler is NULL, it is a namespace,
   otherwise it is a pragma and its handler.  */
static struct pragma_entry *
871
insert_pragma_entry (pfile, chain, pragma, handler)
872
     cpp_reader *pfile;
873
     struct pragma_entry **chain;
874
     const cpp_hashnode *pragma;
Neil Booth committed
875
     pragma_cb handler;
876
{
877
  struct pragma_entry *new;
878

879
  new = (struct pragma_entry *)
880
    _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
881
  new->pragma = pragma;
882 883 884 885 886 887 888 889 890 891
  if (handler)
    {
      new->is_nspace = 0;
      new->u.handler = handler;
    }
  else
    {
      new->is_nspace = 1;
      new->u.space = NULL;
    }
892

893 894 895
  new->next = *chain;
  *chain = new;
  return new;
896
}
897

898 899 900
/* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
   goes in the global namespace.  HANDLER is the handler it will call,
   which must be non-NULL.  */
901
void
902
cpp_register_pragma (pfile, space, name, handler)
903
     cpp_reader *pfile;
904
     const char *space;
905 906
     const char *name;
     pragma_cb handler;
907
{
908 909
  struct pragma_entry **chain = &pfile->pragmas;
  struct pragma_entry *entry;
910
  const cpp_hashnode *node;
911 912 913

  if (!handler)
    abort ();
914

915
  if (space)
916
    {
917 918
      node = cpp_lookup (pfile, U space, strlen (space));
      entry = lookup_pragma_entry (*chain, node);
919
      if (!entry)
920
	entry = insert_pragma_entry (pfile, chain, node, NULL);
921 922 923
      else if (!entry->is_nspace)
	goto clash;
      chain = &entry->u.space;
924 925
    }

926
  /* Check for duplicates.  */
927 928
  node = cpp_lookup (pfile, U name, strlen (name));
  entry = lookup_pragma_entry (*chain, node);
929 930 931 932 933 934
  if (entry)
    {
      if (entry->is_nspace)
	clash:
	cpp_ice (pfile,
		 "registering \"%s\" as both a pragma and a pragma namespace",
935
		 NODE_NAME (node));
936 937 938 939 940 941
      else if (space)
	cpp_ice (pfile, "#pragma %s %s is already registered", space, name);
      else
	cpp_ice (pfile, "#pragma %s is already registered", name);
    }
  else
942
    insert_pragma_entry (pfile, chain, node, handler);
943
}
944 945

/* Register the pragmas the preprocessor itself handles.  */
946 947 948 949
void
_cpp_init_internal_pragmas (pfile)
     cpp_reader *pfile;
{
950
  /* Pragmas in the global namespace.  */
951 952 953
  cpp_register_pragma (pfile, 0, "poison", do_pragma_poison);
  cpp_register_pragma (pfile, 0, "once", do_pragma_once);

954
  /* New GCC-specific pragmas should be put in the GCC namespace.  */
955 956 957
  cpp_register_pragma (pfile, "GCC", "poison", do_pragma_poison);
  cpp_register_pragma (pfile, "GCC", "system_header", do_pragma_system_header);
  cpp_register_pragma (pfile, "GCC", "dependency", do_pragma_dependency);
958
}
Per Bothner committed
959

960 961 962 963 964
/* Pragmata handling.  We handle some, and pass the rest on to the
   front end.  C99 defines three pragmas and says that no macro
   expansion is to be performed on them; whether or not macro
   expansion happens for other pragmas is implementation defined.
   This implementation never macro-expands the text after #pragma.  */
Zack Weinberg committed
965
static void
966
do_pragma (pfile)
Per Bothner committed
967 968
     cpp_reader *pfile;
{
969
  const struct pragma_entry *p = NULL;
970
  const cpp_token *token;
971
  unsigned int count = 1;
Zack Weinberg committed
972

Neil Booth committed
973
  pfile->state.prevent_expansion++;
974

975 976
  token = cpp_get_token (pfile);
  if (token->type == CPP_NAME)
977
    {
978
      p = lookup_pragma_entry (pfile->pragmas, token->val.node);
979
      if (p && p->is_nspace)
980
	{
981 982 983
	  count = 2;
	  token = cpp_get_token (pfile);
	  if (token->type == CPP_NAME)
984
	    p = lookup_pragma_entry (p->u.space, token->val.node);
985 986
	  else
	    p = NULL;
987 988
	}
    }
Zack Weinberg committed
989

990 991 992 993 994 995
  /* FIXME.  This is an awful kludge to get the front ends to update
     their notion of line number for diagnostic purposes.  The line
     number should be passed to the handler and they should do it
     themselves.  Stand-alone CPP must ignore us, otherwise it will
     prefix the directive with spaces, hence the 1.  Ugh.  */
  if (pfile->cb.line_change)
996
    (*pfile->cb.line_change)(pfile, token, 1);
997

998 999
  if (p)
    (*p->u.handler) (pfile);
Neil Booth committed
1000
  else if (pfile->cb.def_pragma)
1001 1002 1003 1004
    {
      _cpp_backup_tokens (pfile, count);
      (*pfile->cb.def_pragma) (pfile, pfile->directive_line);
    }
1005

1006
  pfile->state.prevent_expansion--;
1007 1008
}

1009
/* Handle #pragma once.  */
1010
static void
1011 1012 1013
do_pragma_once (pfile)
     cpp_reader *pfile;
{
1014 1015
  cpp_warning (pfile, "#pragma once is obsolete");
 
1016
  if (pfile->buffer->prev == NULL)
Neil Booth committed
1017
    cpp_warning (pfile, "#pragma once in main file");
1018
  else
1019
    _cpp_never_reread (pfile->buffer->inc);
Neil Booth committed
1020 1021

  check_eol (pfile);
1022
}
1023

1024 1025
/* Handle #pragma poison, to poison one or more identifiers so that
   the lexer produces a hard error for each subsequent usage.  */
1026
static void
1027 1028 1029
do_pragma_poison (pfile)
     cpp_reader *pfile;
{
1030
  const cpp_token *tok;
1031
  cpp_hashnode *hp;
1032

Neil Booth committed
1033
  pfile->state.poisoned_ok = 1;
1034 1035
  for (;;)
    {
1036 1037
      tok = _cpp_lex_token (pfile);
      if (tok->type == CPP_EOF)
1038
	break;
1039
      if (tok->type != CPP_NAME)
1040
	{
Neil Booth committed
1041 1042
	  cpp_error (pfile, "invalid #pragma GCC poison directive");
	  break;
1043 1044
	}

1045
      hp = tok->val.node;
Neil Booth committed
1046 1047 1048 1049
      if (hp->flags & NODE_POISONED)
	continue;

      if (hp->type == NT_MACRO)
1050
	cpp_warning (pfile, "poisoning existing macro \"%s\"", NODE_NAME (hp));
Neil Booth committed
1051 1052
      _cpp_free_definition (hp);
      hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1053
    }
Neil Booth committed
1054
  pfile->state.poisoned_ok = 0;
Per Bothner committed
1055
}
1056 1057 1058 1059 1060 1061 1062

/* Mark the current header as a system header.  This will suppress
   some categories of warnings (notably those from -pedantic).  It is
   intended for use in system libraries that cannot be implemented in
   conforming C, but cannot be certain that their headers appear in a
   system include directory.  To prevent abuse, it is rejected in the
   primary source file.  */
1063
static void
1064 1065 1066
do_pragma_system_header (pfile)
     cpp_reader *pfile;
{
1067 1068 1069 1070
  cpp_buffer *buffer = pfile->buffer;

  if (buffer->prev == 0)
    cpp_warning (pfile, "#pragma system_header ignored outside include file");
1071
  else
Neil Booth committed
1072 1073
    {
      check_eol (pfile);
1074
      skip_rest_of_line (pfile);
Neil Booth committed
1075 1076
      cpp_make_system_header (pfile, 1, 0);
    }
1077
}
1078 1079 1080 1081

/* Check the modified date of the current include file against a specified
   file. Issue a diagnostic, if the specified file is newer. We use this to
   determine if a fixed header should be refixed.  */
1082
static void
1083 1084 1085
do_pragma_dependency (pfile)
     cpp_reader *pfile;
{
1086
  const cpp_token *header;
Neil Booth committed
1087
  int ordering;
Zack Weinberg committed
1088
 
1089 1090
  header = parse_include (pfile);
  if (!header)
1091
    return;
Zack Weinberg committed
1092

1093
  ordering = _cpp_compare_file_date (pfile, header);
1094
  if (ordering < 0)
Neil Booth committed
1095
    cpp_warning (pfile, "cannot find source %s",
1096
		 cpp_token_as_text (pfile, header));
1097 1098
  else if (ordering > 0)
    {
Neil Booth committed
1099
      cpp_warning (pfile, "current file is older than %s",
1100 1101
		   cpp_token_as_text (pfile, header));
      if (cpp_get_token (pfile)->type != CPP_EOF)
1102 1103 1104 1105
	{
	  _cpp_backup_tokens (pfile, 1);
	  do_diagnostic (pfile, WARNING, 0);
	}
1106 1107 1108
    }
}

1109 1110 1111
/* Get a token but skip padding.  */
static const cpp_token *
get_token_no_padding (pfile)
1112 1113
     cpp_reader *pfile;
{
1114 1115 1116 1117 1118 1119 1120
  for (;;)
    {
      const cpp_token *result = cpp_get_token (pfile);
      if (result->type != CPP_PADDING)
	return result;
    }
}
1121

1122 1123 1124 1125 1126 1127 1128
/* Check syntax is "(string-literal)".  Returns the string on success,
   or NULL on failure.  */
static const cpp_token *
get__Pragma_string (pfile)
     cpp_reader *pfile;
{
  const cpp_token *string;
1129

1130 1131 1132 1133
  if (get_token_no_padding (pfile)->type != CPP_OPEN_PAREN)
    return NULL;

  string = get_token_no_padding (pfile);
1134
  if (string->type != CPP_STRING && string->type != CPP_WSTRING)
1135 1136 1137 1138
    return NULL;

  if (get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
    return NULL;
1139

1140
  return string;
1141 1142
}

1143 1144 1145 1146 1147
/* Destringize IN into a temporary buffer, by removing the first \ of
   \" and \\ sequences, and process the result as a #pragma directive.  */
static void
destringize_and_run (pfile, in)
     cpp_reader *pfile;
1148 1149 1150
     const cpp_string *in;
{
  const unsigned char *src, *limit;
1151
  char *dest, *result;
1152

1153
  dest = result = alloca (in->len + 1);
1154 1155 1156 1157 1158 1159 1160
  for (src = in->text, limit = src + in->len; src < limit;)
    {
      /* We know there is a character following the backslash.  */
      if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
	src++;
      *dest++ = *src++;
    }
1161
  *dest = '\0';
1162

1163
  run_directive (pfile, T_PRAGMA, result, dest - result);
1164 1165
}

1166
/* Handle the _Pragma operator.  */
1167 1168 1169 1170
void
_cpp_do__Pragma (pfile)
     cpp_reader *pfile;
{
1171
  const cpp_token *string = get__Pragma_string (pfile);
1172

1173
  if (!string)
1174 1175
    cpp_error (pfile, "_Pragma takes a parenthesized string literal");
  else
1176
    {
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
      /* Ideally, we'd like
			token1 _Pragma ("foo") token2
	 to be output as
			token1
			# 7 "file.c"
			#pragma foo
			# 7 "file.c"
					       token2
	 Getting these correct line markers is a little tricky.  */

      unsigned int orig_line = pfile->line;
1188
      destringize_and_run (pfile, &string->val.str);
1189 1190
      pfile->line = orig_line;
      pfile->buffer->saved_flags = BOL;
1191 1192 1193
    }
}

Per Bothner committed
1194
/* Just ignore #sccs, on systems where we define it at all.  */
1195
#ifdef SCCS_DIRECTIVE
Zack Weinberg committed
1196
static void
1197
do_sccs (pfile)
Zack Weinberg committed
1198
     cpp_reader *pfile ATTRIBUTE_UNUSED;
Per Bothner committed
1199 1200
{
}
1201
#endif
1202

1203
/* Handle #ifdef.  */
Zack Weinberg committed
1204
static void
1205 1206 1207
do_ifdef (pfile)
     cpp_reader *pfile;
{
Neil Booth committed
1208
  int skip = 1;
Zack Weinberg committed
1209

1210
  if (! pfile->state.skipping)
Neil Booth committed
1211 1212
    {
      const cpp_hashnode *node = lex_macro_node (pfile);
Zack Weinberg committed
1213

Neil Booth committed
1214 1215
      if (node)
	skip = node->type != NT_MACRO;
1216 1217 1218

      if (node)
	check_eol (pfile);
Neil Booth committed
1219
    }
1220

Neil Booth committed
1221 1222
  push_conditional (pfile, skip, T_IFDEF, 0);
}
1223

1224
/* Handle #ifndef.  */
Zack Weinberg committed
1225
static void
1226 1227 1228
do_ifndef (pfile)
     cpp_reader *pfile;
{
Neil Booth committed
1229
  int skip = 1;
1230
  const cpp_hashnode *node = 0;
1231

1232
  if (! pfile->state.skipping)
1233
    {
Neil Booth committed
1234 1235 1236
      node = lex_macro_node (pfile);
      if (node)
	skip = node->type == NT_MACRO;
1237 1238 1239

      if (node)
	check_eol (pfile);
1240
    }
Zack Weinberg committed
1241

Neil Booth committed
1242
  push_conditional (pfile, skip, T_IFNDEF, node);
Per Bothner committed
1243 1244
}

1245 1246 1247 1248 1249
/* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
   pfile->mi_ind_cmacro so we can handle multiple-include
   optimisations.  If macro expansion occurs in the expression, we
   cannot treat it as a controlling conditional, since the expansion
   could change in the future.  That is handled by cpp_get_token.  */
Zack Weinberg committed
1250
static void
1251
do_if (pfile)
Per Bothner committed
1252 1253
     cpp_reader *pfile;
{
Neil Booth committed
1254
  int skip = 1;
Per Bothner committed
1255

1256
  if (! pfile->state.skipping)
1257
    skip = _cpp_parse_expr (pfile) == 0;
Neil Booth committed
1258

1259
  push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
Per Bothner committed
1260 1261
}

1262
/* Flip skipping state if appropriate and continue without changing
1263 1264
   if_stack; this is so that the error message for missing #endif's
   etc. will point to the original #if.  */
Zack Weinberg committed
1265
static void
1266 1267
do_else (pfile)
     cpp_reader *pfile;
1268
{
1269 1270
  cpp_buffer *buffer = pfile->buffer;
  struct if_stack *ifs = buffer->if_stack;
1271

1272
  if (ifs == NULL)
Neil Booth committed
1273 1274
    cpp_error (pfile, "#else without #if");
  else
1275
    {
Neil Booth committed
1276 1277 1278
      if (ifs->type == T_ELSE)
	{
	  cpp_error (pfile, "#else after #else");
1279
	  cpp_error_with_line (pfile, ifs->line, 0,
Neil Booth committed
1280 1281
			       "the conditional began here");
	}
1282 1283
      ifs->type = T_ELSE;

1284 1285 1286
      /* Skip any future (erroneous) #elses or #elifs.  */
      pfile->state.skipping = ifs->skip_elses;
      ifs->skip_elses = true;
Per Bothner committed
1287

Neil Booth committed
1288 1289 1290
      /* Invalidate any controlling macro.  */
      ifs->mi_cmacro = 0;

1291 1292 1293 1294
      /* Only check EOL if was not originally skipping.  */
      if (!ifs->was_skipping)
	check_eol (pfile);
    }
Per Bothner committed
1295 1296
}

1297
/* Handle a #elif directive by not changing if_stack either.  See the
Neil Booth committed
1298
   comment above do_else.  */
Zack Weinberg committed
1299
static void
1300
do_elif (pfile)
Per Bothner committed
1301 1302
     cpp_reader *pfile;
{
1303 1304
  cpp_buffer *buffer = pfile->buffer;
  struct if_stack *ifs = buffer->if_stack;
Per Bothner committed
1305

1306
  if (ifs == NULL)
1307 1308
    cpp_error (pfile, "#elif without #if");
  else
1309
    {
1310 1311 1312
      if (ifs->type == T_ELSE)
	{
	  cpp_error (pfile, "#elif after #else");
1313
	  cpp_error_with_line (pfile, ifs->line, 0,
1314 1315 1316
			       "the conditional began here");
	}
      ifs->type = T_ELIF;
Neil Booth committed
1317

1318 1319 1320 1321 1322
      /* Only evaluate this if we aren't skipping elses.  During
	 evaluation, set skipping to false to get lexer warnings.  */
      if (ifs->skip_elses)
	pfile->state.skipping = 1;
      else
1323
	{
1324 1325 1326
	  pfile->state.skipping = 0;
	  pfile->state.skipping = ! _cpp_parse_expr (pfile);
	  ifs->skip_elses = ! pfile->state.skipping;
1327
	}
1328 1329 1330

      /* Invalidate any controlling macro.  */
      ifs->mi_cmacro = 0;
1331
    }
Per Bothner committed
1332 1333
}

1334
/* #endif pops the if stack and resets pfile->state.skipping.  */
Zack Weinberg committed
1335
static void
1336
do_endif (pfile)
Per Bothner committed
1337 1338
     cpp_reader *pfile;
{
1339 1340
  cpp_buffer *buffer = pfile->buffer;
  struct if_stack *ifs = buffer->if_stack;
1341 1342 1343

  if (ifs == NULL)
    cpp_error (pfile, "#endif without #if");
Per Bothner committed
1344 1345
  else
    {
1346 1347 1348 1349
      /* Only check EOL if was not originally skipping.  */
      if (!ifs->was_skipping)
	check_eol (pfile);

Neil Booth committed
1350 1351 1352
      /* If potential control macro, we go back outside again.  */
      if (ifs->next == 0 && ifs->mi_cmacro)
	{
1353
	  pfile->mi_valid = true;
Neil Booth committed
1354 1355 1356
	  pfile->mi_cmacro = ifs->mi_cmacro;
	}

1357
      buffer->if_stack = ifs->next;
1358
      pfile->state.skipping = ifs->was_skipping;
1359
      obstack_free (&pfile->buffer_ob, ifs);
Per Bothner committed
1360
    }
Neil Booth committed
1361
}
Zack Weinberg committed
1362

1363 1364 1365 1366
/* Push an if_stack entry for a preprocessor conditional, and set
   pfile->state.skipping to SKIP.  If TYPE indicates the conditional
   is #if or #ifndef, CMACRO is a potentially controlling macro, and
   we need to check here that we are at the top of the file.  */
1367 1368 1369 1370 1371 1372 1373 1374
static void
push_conditional (pfile, skip, type, cmacro)
     cpp_reader *pfile;
     int skip;
     int type;
     const cpp_hashnode *cmacro;
{
  struct if_stack *ifs;
1375
  cpp_buffer *buffer = pfile->buffer;
1376

1377
  ifs = xobnew (&pfile->buffer_ob, struct if_stack);
1378
  ifs->line = pfile->directive_line;
1379
  ifs->next = buffer->if_stack;
1380 1381
  ifs->skip_elses = pfile->state.skipping || !skip;
  ifs->was_skipping = pfile->state.skipping;
1382
  ifs->type = type;
1383 1384
  /* This condition is effectively a test for top-of-file.  */
  if (pfile->mi_valid && pfile->mi_cmacro == 0)
Neil Booth committed
1385 1386 1387
    ifs->mi_cmacro = cmacro;
  else
    ifs->mi_cmacro = 0;
1388

1389
  pfile->state.skipping = skip;
1390
  buffer->if_stack = ifs;
1391
}
1392

1393 1394 1395 1396
/* Read the tokens of the answer into the macro pool, in a directive
   of type TYPE.  Only commit the memory if we intend it as permanent
   storage, i.e. the #assert case.  Returns 0 on success, and sets
   ANSWERP to point to the answer.  */
Neil Booth committed
1397 1398
static int
parse_answer (pfile, answerp, type)
Per Bothner committed
1399
     cpp_reader *pfile;
Zack Weinberg committed
1400
     struct answer **answerp;
Neil Booth committed
1401
     int type;
Per Bothner committed
1402
{
1403
  const cpp_token *paren;
Neil Booth committed
1404
  struct answer *answer;
1405
  unsigned int acount;
Neil Booth committed
1406 1407 1408

  /* In a conditional, it is legal to not have an open paren.  We
     should save the following token in this case.  */
1409
  paren = cpp_get_token (pfile);
Neil Booth committed
1410 1411

  /* If not a paren, see if we're OK.  */
1412
  if (paren->type != CPP_OPEN_PAREN)
Zack Weinberg committed
1413
    {
Neil Booth committed
1414 1415 1416
      /* In a conditional no answer is a test for any answer.  It
         could be followed by any token.  */
      if (type == T_IF)
1417 1418 1419 1420
	{
	  _cpp_backup_tokens (pfile, 1);
	  return 0;
	}
Neil Booth committed
1421 1422

      /* #unassert with no answer is valid - it removes all answers.  */
1423
      if (type == T_UNASSERT && paren->type == CPP_EOF)
Neil Booth committed
1424
	return 0;
1425

Zack Weinberg committed
1426
      cpp_error (pfile, "missing '(' after predicate");
Neil Booth committed
1427
      return 1;
Zack Weinberg committed
1428
    }
1429

1430
  for (acount = 0;; acount++)
Zack Weinberg committed
1431
    {
1432 1433 1434
      size_t room_needed;
      const cpp_token *token = cpp_get_token (pfile);
      cpp_token *dest;
Neil Booth committed
1435

Zack Weinberg committed
1436 1437
      if (token->type == CPP_CLOSE_PAREN)
	break;
1438

Neil Booth committed
1439
      if (token->type == CPP_EOF)
Zack Weinberg committed
1440
	{
Neil Booth committed
1441 1442
	  cpp_error (pfile, "missing ')' to complete answer");
	  return 1;
Zack Weinberg committed
1443
	}
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

      /* struct answer includes the space for one token.  */
      room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));

      if (BUFF_ROOM (pfile->a_buff) < room_needed)
	_cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));

      dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
      *dest = *token;

      /* Drop whitespace at start, for answer equivalence purposes.  */
      if (acount == 0)
	dest->flags &= ~PREV_WHITE;
Zack Weinberg committed
1457
    }
1458

1459
  if (acount == 0)
1460
    {
Zack Weinberg committed
1461
      cpp_error (pfile, "predicate's answer is empty");
Neil Booth committed
1462
      return 1;
Per Bothner committed
1463
    }
Zack Weinberg committed
1464

1465 1466 1467
  answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
  answer->count = acount;
  answer->next = NULL;
Neil Booth committed
1468
  *answerp = answer;
Zack Weinberg committed
1469

Neil Booth committed
1470 1471
  return 0;
}
Zack Weinberg committed
1472

1473 1474 1475
/* Parses an assertion directive of type TYPE, returning a pointer to
   the hash node of the predicate, or 0 on error.  If an answer was
   supplied, it is placed in ANSWERP, otherwise it is set to 0.  */
Neil Booth committed
1476 1477 1478 1479 1480 1481 1482
static cpp_hashnode *
parse_assertion (pfile, answerp, type)
     cpp_reader *pfile;
     struct answer **answerp;
     int type;
{
  cpp_hashnode *result = 0;
1483
  const cpp_token *predicate;
Neil Booth committed
1484 1485 1486 1487 1488

  /* We don't expand predicates or answers.  */
  pfile->state.prevent_expansion++;

  *answerp = 0;
1489 1490
  predicate = cpp_get_token (pfile);
  if (predicate->type == CPP_EOF)
Neil Booth committed
1491
    cpp_error (pfile, "assertion without predicate");
1492
  else if (predicate->type != CPP_NAME)
Neil Booth committed
1493 1494 1495
    cpp_error (pfile, "predicate must be an identifier");
  else if (parse_answer (pfile, answerp, type) == 0)
    {
1496
      unsigned int len = NODE_LEN (predicate->val.node);
Neil Booth committed
1497
      unsigned char *sym = alloca (len + 1);
Zack Weinberg committed
1498

Neil Booth committed
1499 1500
      /* Prefix '#' to get it out of macro namespace.  */
      sym[0] = '#';
1501
      memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
Neil Booth committed
1502 1503
      result = cpp_lookup (pfile, sym, len + 1);
    }
1504

Neil Booth committed
1505 1506
  pfile->state.prevent_expansion--;
  return result;
Per Bothner committed
1507
}
1508

1509
/* Returns a pointer to the pointer to CANDIDATE in the answer chain,
Zack Weinberg committed
1510
   or a pointer to NULL if the answer is not in the chain.  */
Neil Booth committed
1511 1512
static struct answer **
find_answer (node, candidate)
Zack Weinberg committed
1513
     cpp_hashnode *node;
Neil Booth committed
1514
     const struct answer *candidate;
Per Bothner committed
1515
{
Neil Booth committed
1516
  unsigned int i;
Zack Weinberg committed
1517
  struct answer **result;
Per Bothner committed
1518

Zack Weinberg committed
1519
  for (result = &node->value.answers; *result; result = &(*result)->next)
Neil Booth committed
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    {
      struct answer *answer = *result;

      if (answer->count == candidate->count)
	{
	  for (i = 0; i < answer->count; i++)
	    if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
	      break;

	  if (i == answer->count)
	    break;
	}
    }
1533

Zack Weinberg committed
1534 1535
  return result;
}
1536

Neil Booth committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
/* Test an assertion within a preprocessor conditional.  Returns
   non-zero on failure, zero on success.  On success, the result of
   the test is written into VALUE.  */
int
_cpp_test_assertion (pfile, value)
     cpp_reader *pfile;
     int *value;
{
  struct answer *answer;
  cpp_hashnode *node;

  node = parse_assertion (pfile, &answer, T_IF);
  if (node)
    *value = (node->type == NT_ASSERTION &&
	      (answer == 0 || *find_answer (node, answer) != 0));

  /* We don't commit the memory for the answer - it's temporary only.  */
  return node == 0;
}

1557
/* Handle #assert.  */
Zack Weinberg committed
1558
static void
Zack Weinberg committed
1559 1560 1561 1562 1563 1564
do_assert (pfile)
     cpp_reader *pfile;
{
  struct answer *new_answer;
  cpp_hashnode *node;
  
Neil Booth committed
1565
  node = parse_assertion (pfile, &new_answer, T_ASSERT);
Zack Weinberg committed
1566
  if (node)
1567
    {
Neil Booth committed
1568 1569
      /* Place the new answer in the answer list.  First check there
         is not a duplicate.  */
Zack Weinberg committed
1570
      new_answer->next = 0;
Neil Booth committed
1571
      if (node->type == NT_ASSERTION)
Zack Weinberg committed
1572
	{
Neil Booth committed
1573 1574
	  if (*find_answer (node, new_answer))
	    {
1575
	      cpp_warning (pfile, "\"%s\" re-asserted", NODE_NAME (node) + 1);
Neil Booth committed
1576 1577
	      return;
	    }
Zack Weinberg committed
1578 1579
	  new_answer->next = node->value.answers;
	}
1580

Neil Booth committed
1581
      node->type = NT_ASSERTION;
Zack Weinberg committed
1582
      node->value.answers = new_answer;
1583 1584 1585 1586
      BUFF_FRONT (pfile->a_buff) += (sizeof (struct answer)
				     + (new_answer->count - 1)
				     * sizeof (cpp_token));
      check_eol (pfile);
1587
    }
Zack Weinberg committed
1588
}
1589

1590
/* Handle #unassert.  */
Zack Weinberg committed
1591
static void
Zack Weinberg committed
1592 1593 1594 1595
do_unassert (pfile)
     cpp_reader *pfile;
{
  cpp_hashnode *node;
Neil Booth committed
1596
  struct answer *answer;
Zack Weinberg committed
1597
  
Neil Booth committed
1598 1599 1600
  node = parse_assertion (pfile, &answer, T_UNASSERT);
  /* It isn't an error to #unassert something that isn't asserted.  */
  if (node && node->type == NT_ASSERTION)
1601
    {
Neil Booth committed
1602
      if (answer)
1603
	{
Neil Booth committed
1604
	  struct answer **p = find_answer (node, answer), *temp;
Zack Weinberg committed
1605

Neil Booth committed
1606 1607 1608 1609
	  /* Remove the answer from the list.  */
	  temp = *p;
	  if (temp)
	    *p = temp->next;
1610

Neil Booth committed
1611 1612 1613
	  /* Did we free the last answer?  */
	  if (node->value.answers == 0)
	    node->type = NT_VOID;
1614 1615

	  check_eol (pfile);
Neil Booth committed
1616 1617 1618
	}
      else
	_cpp_free_definition (node);
Zack Weinberg committed
1619
    }
Neil Booth committed
1620 1621

  /* We don't commit the memory for the answer - it's temporary only.  */
Per Bothner committed
1622 1623
}

1624 1625 1626 1627 1628
/* These are for -D, -U, -A.  */

/* Process the string STR as if it appeared as the body of a #define.
   If STR is just an identifier, define it with value 1.
   If STR has anything after the identifier, then it should
1629
   be identifier=definition.  */
1630
void
1631
cpp_define (pfile, str)
1632
     cpp_reader *pfile;
1633
     const char *str;
1634
{
1635 1636 1637 1638 1639
  char *buf, *p;
  size_t count;

  /* Copy the entire option so we can modify it. 
     Change the first "=" in the string to a space.  If there is none,
1640 1641 1642
     tack " 1" on the end.  */

  count = strlen (str);
1643
  buf = (char *) alloca (count + 3);
1644 1645 1646
  memcpy (buf, str, count);

  p = strchr (str, '=');
1647
  if (p)
1648
    buf[p - str] = ' ';
1649 1650
  else
    {
1651 1652
      buf[count++] = ' ';
      buf[count++] = '1';
1653
    }
1654
  buf[count] = '\0';
1655

1656
  run_directive (pfile, T_DEFINE, buf, count);
1657 1658
}

1659
/* Slight variant of the above for use by initialize_builtins.  */
1660 1661 1662 1663 1664
void
_cpp_define_builtin (pfile, str)
     cpp_reader *pfile;
     const char *str;
{
1665
  run_directive (pfile, T_DEFINE, str, strlen (str));
1666
}
Mike Stump committed
1667

1668 1669 1670
/* Process MACRO as if it appeared as the body of an #undef.  */
void
cpp_undef (pfile, macro)
Per Bothner committed
1671
     cpp_reader *pfile;
1672
     const char *macro;
Per Bothner committed
1673
{
1674
  run_directive (pfile, T_UNDEF, macro, strlen (macro));
Per Bothner committed
1675 1676
}

1677
/* Process the string STR as if it appeared as the body of a #assert.  */
1678 1679 1680 1681 1682
void
cpp_assert (pfile, str)
     cpp_reader *pfile;
     const char *str;
{
1683
  handle_assertion (pfile, str, T_ASSERT);
1684
}
Per Bothner committed
1685

1686
/* Process STR as if it appeared as the body of an #unassert.  */
1687 1688
void
cpp_unassert (pfile, str)
Per Bothner committed
1689
     cpp_reader *pfile;
1690
     const char *str;
Per Bothner committed
1691
{
1692
  handle_assertion (pfile, str, T_UNASSERT);
1693
}  
1694

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
/* Common code for cpp_assert (-A) and cpp_unassert (-A-).  */
static void
handle_assertion (pfile, str, type)
     cpp_reader *pfile;
     const char *str;
     int type;
{
  size_t count = strlen (str);
  const char *p = strchr (str, '=');

  if (p)
    {
      /* Copy the entire option so we can modify it.  Change the first
	 "=" in the string to a '(', and tack a ')' on the end.  */
1709
      char *buf = (char *) alloca (count + 2);
1710 1711 1712 1713

      memcpy (buf, str, count);
      buf[p - str] = '(';
      buf[count++] = ')';
1714
      buf[count] = '\0';
1715 1716 1717
      str = buf;
    }

1718
  run_directive (pfile, type, str, count);
1719 1720
}

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
/* The number of errors for a given reader.  */
unsigned int
cpp_errors (pfile)
     cpp_reader *pfile;
{
  return pfile->errors;
}

/* The options structure.  */
cpp_options *
cpp_get_options (pfile)
     cpp_reader *pfile;
{
  return &pfile->opts;
}

/* The callbacks structure.  */
cpp_callbacks *
cpp_get_callbacks (pfile)
     cpp_reader *pfile;
{
  return &pfile->cb;
}

Neil Booth committed
1745
/* The line map set.  */
Neil Booth committed
1746
const struct line_maps *
Neil Booth committed
1747 1748 1749 1750 1751 1752
cpp_get_line_maps (pfile)
     cpp_reader *pfile;
{
  return &pfile->line_maps;
}

1753 1754 1755 1756 1757 1758 1759 1760 1761
/* Copy the given callbacks structure to our own.  */
void
cpp_set_callbacks (pfile, cb)
     cpp_reader *pfile;
     cpp_callbacks *cb;
{
  pfile->cb = *cb;
}

1762 1763 1764
/* Push a new buffer on the buffer stack.  Returns the new buffer; it
   doesn't fail.  It does not generate a file change call back; that
   is the responsibility of the caller.  */
1765
cpp_buffer *
1766
cpp_push_buffer (pfile, buffer, len, from_stage3, return_at_eof)
1767 1768
     cpp_reader *pfile;
     const U_CHAR *buffer;
1769
     size_t len;
1770
     int from_stage3;
1771
     int return_at_eof;
1772
{
1773
  cpp_buffer *new = xobnew (&pfile->buffer_ob, cpp_buffer);
Neil Booth committed
1774

1775 1776 1777 1778 1779
  /* Clears, amongst other things, if_stack and mi_cmacro.  */
  memset (new, 0, sizeof (cpp_buffer));

  new->line_base = new->buf = new->cur = buffer;
  new->rlimit = buffer + len;
1780
  new->from_stage3 = from_stage3;
1781
  new->prev = pfile->buffer;
1782
  new->return_at_eof = return_at_eof;
1783
  new->saved_flags = BOL;
1784

1785
  pfile->buffer = new;
1786

1787 1788 1789
  return new;
}

1790 1791 1792
/* If called from do_line, pops a single buffer.  Otherwise pops all
   buffers until a real file is reached.  Generates appropriate
   call-backs.  */
1793 1794
void
_cpp_pop_buffer (pfile)
1795 1796
     cpp_reader *pfile;
{
1797
  cpp_buffer *buffer = pfile->buffer;
1798
  struct if_stack *ifs;
1799
  bool pushed = false;
1800

1801 1802 1803
  /* Walk back up the conditional stack till we reach its level at
     entry to this file, issuing error messages.  */
  for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
1804
    cpp_error_with_line (pfile, ifs->line, 0,
1805
			 "unterminated #%s", dtable[ifs->type].name);
1806

1807
  /* In case of a missing #endif.  */
1808
  pfile->state.skipping = 0;
1809 1810 1811 1812 1813

  /* Update the reader's buffer before _cpp_do_file_change.  */
  pfile->buffer = buffer->prev;

  if (buffer->inc)
1814
    pushed = _cpp_pop_file_buffer (pfile, buffer->inc);
1815

1816 1817
  if (!pushed)
    obstack_free (&pfile->buffer_ob, buffer);
1818 1819
}

1820
/* Enter all recognised directives in the hash table.  */
1821
void
1822
_cpp_init_directives (pfile)
1823 1824
     cpp_reader *pfile;
{
1825
  unsigned int i;
Neil Booth committed
1826
  cpp_hashnode *node;
1827

1828
  for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
Neil Booth committed
1829
    {
1830 1831
      node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
      node->directive_index = i + 1;
Neil Booth committed
1832
    }
1833
}