2014-12-14 Janus Weil <janus@gcc.gnu.org>
[official-gcc.git] / libcpp / directives.c
blobc9be4122511bc0db2a67ac820c75bbaa0707c22f
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2014 Free Software Foundation, Inc.
3 Contributed by Per Bothner, 1994-95.
4 Based on CCCP program by Paul Rubin, June 1986
5 Adapted to ANSI C, Richard Stallman, Jan 1987
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "cpplib.h"
24 #include "internal.h"
25 #include "mkdeps.h"
26 #include "obstack.h"
28 /* Stack of conditionals currently in progress
29 (including both successful and failing conditionals). */
30 struct if_stack
32 struct if_stack *next;
33 source_location line; /* Line where condition started. */
34 const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
35 bool skip_elses; /* Can future #else / #elif be skipped? */
36 bool was_skipping; /* If were skipping on entry. */
37 int type; /* Most recent conditional for diagnostics. */
40 /* Contains a registered pragma or pragma namespace. */
41 typedef void (*pragma_cb) (cpp_reader *);
42 struct pragma_entry
44 struct pragma_entry *next;
45 const cpp_hashnode *pragma; /* Name and length. */
46 bool is_nspace;
47 bool is_internal;
48 bool is_deferred;
49 bool allow_expansion;
50 union {
51 pragma_cb handler;
52 struct pragma_entry *space;
53 unsigned int ident;
54 } u;
57 /* Values for the origin field of struct directive. KANDR directives
58 come from traditional (K&R) C. STDC89 directives come from the
59 1989 C standard. EXTENSION directives are extensions. */
60 #define KANDR 0
61 #define STDC89 1
62 #define EXTENSION 2
64 /* Values for the flags field of struct directive. COND indicates a
65 conditional; IF_COND an opening conditional. INCL means to treat
66 "..." and <...> as q-char and h-char sequences respectively. IN_I
67 means this directive should be handled even if -fpreprocessed is in
68 effect (these are the directives with callback hooks).
70 EXPAND is set on directives that are always macro-expanded. */
71 #define COND (1 << 0)
72 #define IF_COND (1 << 1)
73 #define INCL (1 << 2)
74 #define IN_I (1 << 3)
75 #define EXPAND (1 << 4)
76 #define DEPRECATED (1 << 5)
78 /* Defines one #-directive, including how to handle it. */
79 typedef void (*directive_handler) (cpp_reader *);
80 typedef struct directive directive;
81 struct directive
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. */
90 /* Forward declarations. */
92 static void skip_rest_of_line (cpp_reader *);
93 static void check_eol (cpp_reader *, bool);
94 static void start_directive (cpp_reader *);
95 static void prepare_directive_trad (cpp_reader *);
96 static void end_directive (cpp_reader *, int);
97 static void directive_diagnostics (cpp_reader *, const directive *, int);
98 static void run_directive (cpp_reader *, int, const char *, size_t);
99 static char *glue_header_name (cpp_reader *);
100 static const char *parse_include (cpp_reader *, int *, const cpp_token ***,
101 source_location *);
102 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
103 static unsigned int read_flag (cpp_reader *, unsigned int);
104 static bool strtolinenum (const uchar *, size_t, linenum_type *, bool *);
105 static void do_diagnostic (cpp_reader *, int, int, int);
106 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
107 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
108 static void do_include_common (cpp_reader *, enum include_type);
109 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
110 const cpp_hashnode *);
111 static int count_registered_pragmas (struct pragma_entry *);
112 static char ** save_registered_pragmas (struct pragma_entry *, char **);
113 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
114 char **);
115 static void do_pragma_once (cpp_reader *);
116 static void do_pragma_poison (cpp_reader *);
117 static void do_pragma_system_header (cpp_reader *);
118 static void do_pragma_dependency (cpp_reader *);
119 static void do_pragma_warning_or_error (cpp_reader *, bool error);
120 static void do_pragma_warning (cpp_reader *);
121 static void do_pragma_error (cpp_reader *);
122 static void do_linemarker (cpp_reader *);
123 static const cpp_token *get_token_no_padding (cpp_reader *);
124 static const cpp_token *get__Pragma_string (cpp_reader *);
125 static void destringize_and_run (cpp_reader *, const cpp_string *);
126 static int parse_answer (cpp_reader *, struct answer **, int, source_location);
127 static cpp_hashnode *parse_assertion (cpp_reader *, struct answer **, int);
128 static struct answer ** find_answer (cpp_hashnode *, const struct answer *);
129 static void handle_assertion (cpp_reader *, const char *, int);
130 static void do_pragma_push_macro (cpp_reader *);
131 static void do_pragma_pop_macro (cpp_reader *);
132 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
134 /* This is the table of directive handlers. It is ordered by
135 frequency of occurrence; the numbers at the end are directive
136 counts from all the source code I have lying around (egcs and libc
137 CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
138 pcmcia-cs-3.0.9). This is no longer important as directive lookup
139 is now O(1). All extensions other than #warning, #include_next,
140 and #import are deprecated. The name is where the extension
141 appears to have come from. */
143 #define DIRECTIVE_TABLE \
144 D(define, T_DEFINE = 0, KANDR, IN_I) /* 270554 */ \
145 D(include, T_INCLUDE, KANDR, INCL | EXPAND) /* 52262 */ \
146 D(endif, T_ENDIF, KANDR, COND) /* 45855 */ \
147 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) /* 22000 */ \
148 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) /* 18162 */ \
149 D(else, T_ELSE, KANDR, COND) /* 9863 */ \
150 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) /* 9675 */ \
151 D(undef, T_UNDEF, KANDR, IN_I) /* 4837 */ \
152 D(line, T_LINE, KANDR, EXPAND) /* 2465 */ \
153 D(elif, T_ELIF, STDC89, COND | EXPAND) /* 610 */ \
154 D(error, T_ERROR, STDC89, 0) /* 475 */ \
155 D(pragma, T_PRAGMA, STDC89, IN_I) /* 195 */ \
156 D(warning, T_WARNING, EXTENSION, 0) /* 22 */ \
157 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) /* 19 */ \
158 D(ident, T_IDENT, EXTENSION, IN_I) /* 11 */ \
159 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* 0 ObjC */ \
160 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
161 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
162 D(sccs, T_SCCS, EXTENSION, IN_I) /* 0 SVR4? */
164 /* #sccs is synonymous with #ident. */
165 #define do_sccs do_ident
167 /* Use the table to generate a series of prototypes, an enum for the
168 directive names, and an array of directive handlers. */
170 #define D(name, t, o, f) static void do_##name (cpp_reader *);
171 DIRECTIVE_TABLE
172 #undef D
174 #define D(n, tag, o, f) tag,
175 enum
177 DIRECTIVE_TABLE
178 N_DIRECTIVES
180 #undef D
182 #define D(name, t, origin, flags) \
183 { do_##name, (const uchar *) #name, \
184 sizeof #name - 1, origin, flags },
185 static const directive dtable[] =
187 DIRECTIVE_TABLE
189 #undef D
190 #undef DIRECTIVE_TABLE
192 /* Wrapper struct directive for linemarkers.
193 The origin is more or less true - the original K+R cpp
194 did use this notation in its preprocessed output. */
195 static const directive linemarker_dir =
197 do_linemarker, UC"#", 1, KANDR, IN_I
200 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
202 /* Skip any remaining tokens in a directive. */
203 static void
204 skip_rest_of_line (cpp_reader *pfile)
206 /* Discard all stacked contexts. */
207 while (pfile->context->prev)
208 _cpp_pop_context (pfile);
210 /* Sweep up all tokens remaining on the line. */
211 if (! SEEN_EOL ())
212 while (_cpp_lex_token (pfile)->type != CPP_EOF)
216 /* Helper function for check_oel. */
218 static void
219 check_eol_1 (cpp_reader *pfile, bool expand, int reason)
221 if (! SEEN_EOL () && (expand
222 ? cpp_get_token (pfile)
223 : _cpp_lex_token (pfile))->type != CPP_EOF)
224 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
225 pfile->directive->name);
228 /* Variant of check_eol used for Wendif-labels warnings. */
230 static void
231 check_eol_endif_labels (cpp_reader *pfile)
233 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
236 /* Ensure there are no stray tokens at the end of a directive. If
237 EXPAND is true, tokens macro-expanding to nothing are allowed. */
239 static void
240 check_eol (cpp_reader *pfile, bool expand)
242 check_eol_1 (pfile, expand, CPP_W_NONE);
245 /* Ensure there are no stray tokens other than comments at the end of
246 a directive, and gather the comments. */
247 static const cpp_token **
248 check_eol_return_comments (cpp_reader *pfile)
250 size_t c;
251 size_t capacity = 8;
252 const cpp_token **buf;
254 buf = XNEWVEC (const cpp_token *, capacity);
255 c = 0;
256 if (! SEEN_EOL ())
258 while (1)
260 const cpp_token *tok;
262 tok = _cpp_lex_token (pfile);
263 if (tok->type == CPP_EOF)
264 break;
265 if (tok->type != CPP_COMMENT)
266 cpp_error (pfile, CPP_DL_PEDWARN,
267 "extra tokens at end of #%s directive",
268 pfile->directive->name);
269 else
271 if (c + 1 >= capacity)
273 capacity *= 2;
274 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
276 buf[c] = tok;
277 ++c;
281 buf[c] = NULL;
282 return buf;
285 /* Called when entering a directive, _Pragma or command-line directive. */
286 static void
287 start_directive (cpp_reader *pfile)
289 /* Setup in-directive state. */
290 pfile->state.in_directive = 1;
291 pfile->state.save_comments = 0;
292 pfile->directive_result.type = CPP_PADDING;
294 /* Some handlers need the position of the # for diagnostics. */
295 pfile->directive_line = pfile->line_table->highest_line;
298 /* Called when leaving a directive, _Pragma or command-line directive. */
299 static void
300 end_directive (cpp_reader *pfile, int skip_line)
302 if (CPP_OPTION (pfile, traditional))
304 /* Revert change of prepare_directive_trad. */
305 if (!pfile->state.in_deferred_pragma)
306 pfile->state.prevent_expansion--;
308 if (pfile->directive != &dtable[T_DEFINE])
309 _cpp_remove_overlay (pfile);
311 else if (pfile->state.in_deferred_pragma)
313 /* We don't skip for an assembler #. */
314 else if (skip_line)
316 skip_rest_of_line (pfile);
317 if (!pfile->keep_tokens)
319 pfile->cur_run = &pfile->base_run;
320 pfile->cur_token = pfile->base_run.base;
324 /* Restore state. */
325 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
326 pfile->state.in_directive = 0;
327 pfile->state.in_expression = 0;
328 pfile->state.angled_headers = 0;
329 pfile->directive = 0;
332 /* Prepare to handle the directive in pfile->directive. */
333 static void
334 prepare_directive_trad (cpp_reader *pfile)
336 if (pfile->directive != &dtable[T_DEFINE])
338 bool no_expand = (pfile->directive
339 && ! (pfile->directive->flags & EXPAND));
340 bool was_skipping = pfile->state.skipping;
342 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
343 || pfile->directive == &dtable[T_ELIF]);
344 if (pfile->state.in_expression)
345 pfile->state.skipping = false;
347 if (no_expand)
348 pfile->state.prevent_expansion++;
349 _cpp_scan_out_logical_line (pfile, NULL);
350 if (no_expand)
351 pfile->state.prevent_expansion--;
353 pfile->state.skipping = was_skipping;
354 _cpp_overlay_buffer (pfile, pfile->out.base,
355 pfile->out.cur - pfile->out.base);
358 /* Stop ISO C from expanding anything. */
359 pfile->state.prevent_expansion++;
362 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
363 the '#' was indented. */
364 static void
365 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
367 /* Issue -pedantic or deprecated warnings for extensions. We let
368 -pedantic take precedence if both are applicable. */
369 if (! pfile->state.skipping)
371 if (dir->origin == EXTENSION
372 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
373 && CPP_PEDANTIC (pfile))
374 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
375 else if (((dir->flags & DEPRECATED) != 0
376 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
377 && CPP_OPTION (pfile, cpp_warn_deprecated))
378 cpp_warning (pfile, CPP_W_DEPRECATED,
379 "#%s is a deprecated GCC extension", dir->name);
382 /* Traditionally, a directive is ignored unless its # is in
383 column 1. Therefore in code intended to work with K+R
384 compilers, directives added by C89 must have their #
385 indented, and directives present in traditional C must not.
386 This is true even of directives in skipped conditional
387 blocks. #elif cannot be used at all. */
388 if (CPP_WTRADITIONAL (pfile))
390 if (dir == &dtable[T_ELIF])
391 cpp_warning (pfile, CPP_W_TRADITIONAL,
392 "suggest not using #elif in traditional C");
393 else if (indented && dir->origin == KANDR)
394 cpp_warning (pfile, CPP_W_TRADITIONAL,
395 "traditional C ignores #%s with the # indented",
396 dir->name);
397 else if (!indented && dir->origin != KANDR)
398 cpp_warning (pfile, CPP_W_TRADITIONAL,
399 "suggest hiding #%s from traditional C with an indented #",
400 dir->name);
404 /* Check if we have a known directive. INDENTED is nonzero if the
405 '#' of the directive was indented. This function is in this file
406 to save unnecessarily exporting dtable etc. to lex.c. Returns
407 nonzero if the line of tokens has been handled, zero if we should
408 continue processing the line. */
410 _cpp_handle_directive (cpp_reader *pfile, int indented)
412 const directive *dir = 0;
413 const cpp_token *dname;
414 bool was_parsing_args = pfile->state.parsing_args;
415 bool was_discarding_output = pfile->state.discarding_output;
416 int skip = 1;
418 if (was_discarding_output)
419 pfile->state.prevent_expansion = 0;
421 if (was_parsing_args)
423 if (CPP_OPTION (pfile, cpp_pedantic))
424 cpp_error (pfile, CPP_DL_PEDWARN,
425 "embedding a directive within macro arguments is not portable");
426 pfile->state.parsing_args = 0;
427 pfile->state.prevent_expansion = 0;
429 start_directive (pfile);
430 dname = _cpp_lex_token (pfile);
432 if (dname->type == CPP_NAME)
434 if (dname->val.node.node->is_directive)
435 dir = &dtable[dname->val.node.node->directive_index];
437 /* We do not recognize the # followed by a number extension in
438 assembler code. */
439 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
441 dir = &linemarker_dir;
442 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
443 && ! pfile->state.skipping)
444 cpp_error (pfile, CPP_DL_PEDWARN,
445 "style of line directive is a GCC extension");
448 if (dir)
450 /* If we have a directive that is not an opening conditional,
451 invalidate any control macro. */
452 if (! (dir->flags & IF_COND))
453 pfile->mi_valid = false;
455 /* Kluge alert. In order to be sure that code like this
457 #define HASH #
458 HASH define foo bar
460 does not cause '#define foo bar' to get executed when
461 compiled with -save-temps, we recognize directives in
462 -fpreprocessed mode only if the # is in column 1. macro.c
463 puts a space in front of any '#' at the start of a macro.
465 We exclude the -fdirectives-only case because macro expansion
466 has not been performed yet, and block comments can cause spaces
467 to precede the directive. */
468 if (CPP_OPTION (pfile, preprocessed)
469 && !CPP_OPTION (pfile, directives_only)
470 && (indented || !(dir->flags & IN_I)))
472 skip = 0;
473 dir = 0;
475 else
477 /* In failed conditional groups, all non-conditional
478 directives are ignored. Before doing that, whether
479 skipping or not, we should lex angle-bracketed headers
480 correctly, and maybe output some diagnostics. */
481 pfile->state.angled_headers = dir->flags & INCL;
482 pfile->state.directive_wants_padding = dir->flags & INCL;
483 if (! CPP_OPTION (pfile, preprocessed))
484 directive_diagnostics (pfile, dir, indented);
485 if (pfile->state.skipping && !(dir->flags & COND))
486 dir = 0;
489 else if (dname->type == CPP_EOF)
490 ; /* CPP_EOF is the "null directive". */
491 else
493 /* An unknown directive. Don't complain about it in assembly
494 source: we don't know where the comments are, and # may
495 introduce assembler pseudo-ops. Don't complain about invalid
496 directives in skipped conditional groups (6.10 p4). */
497 if (CPP_OPTION (pfile, lang) == CLK_ASM)
498 skip = 0;
499 else if (!pfile->state.skipping)
500 cpp_error (pfile, CPP_DL_ERROR, "invalid preprocessing directive #%s",
501 cpp_token_as_text (pfile, dname));
504 pfile->directive = dir;
505 if (CPP_OPTION (pfile, traditional))
506 prepare_directive_trad (pfile);
508 if (dir)
509 pfile->directive->handler (pfile);
510 else if (skip == 0)
511 _cpp_backup_tokens (pfile, 1);
513 end_directive (pfile, skip);
514 if (was_parsing_args && !pfile->state.in_deferred_pragma)
516 /* Restore state when within macro args. */
517 pfile->state.parsing_args = 2;
518 pfile->state.prevent_expansion = 1;
520 if (was_discarding_output)
521 pfile->state.prevent_expansion = 1;
522 return skip;
525 /* Directive handler wrapper used by the command line option
526 processor. BUF is \n terminated. */
527 static void
528 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
530 cpp_push_buffer (pfile, (const uchar *) buf, count,
531 /* from_stage3 */ true);
532 start_directive (pfile);
534 /* This is a short-term fix to prevent a leading '#' being
535 interpreted as a directive. */
536 _cpp_clean_line (pfile);
538 pfile->directive = &dtable[dir_no];
539 if (CPP_OPTION (pfile, traditional))
540 prepare_directive_trad (pfile);
541 pfile->directive->handler (pfile);
542 end_directive (pfile, 1);
543 _cpp_pop_buffer (pfile);
546 /* Checks for validity the macro name in #define, #undef, #ifdef and
547 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
548 processing a #define or #undefine directive, and false
549 otherwise. */
550 static cpp_hashnode *
551 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
553 const cpp_token *token = _cpp_lex_token (pfile);
555 /* The token immediately after #define must be an identifier. That
556 identifier may not be "defined", per C99 6.10.8p4.
557 In C++, it may not be any of the "named operators" either,
558 per C++98 [lex.digraph], [lex.key].
559 Finally, the identifier may not have been poisoned. (In that case
560 the lexer has issued the error message for us.) */
562 if (token->type == CPP_NAME)
564 cpp_hashnode *node = token->val.node.node;
566 if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
567 cpp_error (pfile, CPP_DL_ERROR,
568 "\"defined\" cannot be used as a macro name");
569 else if (is_def_or_undef
570 && (node == pfile->spec_nodes.n__has_include__
571 || node == pfile->spec_nodes.n__has_include_next__))
572 cpp_error (pfile, CPP_DL_ERROR,
573 "\"__has_include__\" cannot be used as a macro name");
574 else if (is_def_or_undef
575 && node == pfile->spec_nodes.n__has_attribute__)
576 cpp_error (pfile, CPP_DL_ERROR,
577 "\"__has_attribute__\" cannot be used as a macro name");
578 else if (! (node->flags & NODE_POISONED))
579 return node;
581 else if (token->flags & NAMED_OP)
582 cpp_error (pfile, CPP_DL_ERROR,
583 "\"%s\" cannot be used as a macro name as it is an operator in C++",
584 NODE_NAME (token->val.node.node));
585 else if (token->type == CPP_EOF)
586 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
587 pfile->directive->name);
588 else
589 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
591 return NULL;
594 /* Process a #define directive. Most work is done in macro.c. */
595 static void
596 do_define (cpp_reader *pfile)
598 cpp_hashnode *node = lex_macro_node (pfile, true);
600 if (node)
602 /* If we have been requested to expand comments into macros,
603 then re-enable saving of comments. */
604 pfile->state.save_comments =
605 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
607 if (pfile->cb.before_define)
608 pfile->cb.before_define (pfile);
610 if (_cpp_create_definition (pfile, node))
611 if (pfile->cb.define)
612 pfile->cb.define (pfile, pfile->directive_line, node);
614 node->flags &= ~NODE_USED;
618 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
619 static void
620 do_undef (cpp_reader *pfile)
622 cpp_hashnode *node = lex_macro_node (pfile, true);
624 if (node)
626 if (pfile->cb.before_define)
627 pfile->cb.before_define (pfile);
629 if (pfile->cb.undef)
630 pfile->cb.undef (pfile, pfile->directive_line, node);
632 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
633 identifier is not currently defined as a macro name. */
634 if (node->type == NT_MACRO)
636 if (node->flags & NODE_WARN)
637 cpp_error (pfile, CPP_DL_WARNING,
638 "undefining \"%s\"", NODE_NAME (node));
639 else if ((node->flags & NODE_BUILTIN)
640 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
641 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
642 pfile->directive_line, 0,
643 "undefining \"%s\"", NODE_NAME (node));
645 if (CPP_OPTION (pfile, warn_unused_macros))
646 _cpp_warn_if_unused_macro (pfile, node, NULL);
648 _cpp_free_definition (node);
652 check_eol (pfile, false);
655 /* Undefine a single macro/assertion/whatever. */
657 static int
658 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
659 void *data_p ATTRIBUTE_UNUSED)
661 /* Body of _cpp_free_definition inlined here for speed.
662 Macros and assertions no longer have anything to free. */
663 h->type = NT_VOID;
664 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
665 return 1;
668 /* Undefine all macros and assertions. */
670 void
671 cpp_undef_all (cpp_reader *pfile)
673 cpp_forall_identifiers (pfile, undefine_macros, NULL);
677 /* Helper routine used by parse_include. Reinterpret the current line
678 as an h-char-sequence (< ... >); we are looking at the first token
679 after the <. Returns a malloced filename. */
680 static char *
681 glue_header_name (cpp_reader *pfile)
683 const cpp_token *token;
684 char *buffer;
685 size_t len, total_len = 0, capacity = 1024;
687 /* To avoid lexed tokens overwriting our glued name, we can only
688 allocate from the string pool once we've lexed everything. */
689 buffer = XNEWVEC (char, capacity);
690 for (;;)
692 token = get_token_no_padding (pfile);
694 if (token->type == CPP_GREATER)
695 break;
696 if (token->type == CPP_EOF)
698 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
699 break;
702 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
703 if (total_len + len > capacity)
705 capacity = (capacity + len) * 2;
706 buffer = XRESIZEVEC (char, buffer, capacity);
709 if (token->flags & PREV_WHITE)
710 buffer[total_len++] = ' ';
712 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
713 true)
714 - (uchar *) buffer);
717 buffer[total_len] = '\0';
718 return buffer;
721 /* Returns the file name of #include, #include_next, #import and
722 #pragma dependency. The string is malloced and the caller should
723 free it. Returns NULL on error. LOCATION is the source location
724 of the file name. */
726 static const char *
727 parse_include (cpp_reader *pfile, int *pangle_brackets,
728 const cpp_token ***buf, source_location *location)
730 char *fname;
731 const cpp_token *header;
733 /* Allow macro expansion. */
734 header = get_token_no_padding (pfile);
735 *location = header->src_loc;
736 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
737 || header->type == CPP_HEADER_NAME)
739 fname = XNEWVEC (char, header->val.str.len - 1);
740 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
741 fname[header->val.str.len - 2] = '\0';
742 *pangle_brackets = header->type == CPP_HEADER_NAME;
744 else if (header->type == CPP_LESS)
746 fname = glue_header_name (pfile);
747 *pangle_brackets = 1;
749 else
751 const unsigned char *dir;
753 if (pfile->directive == &dtable[T_PRAGMA])
754 dir = UC"pragma dependency";
755 else
756 dir = pfile->directive->name;
757 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
758 dir);
760 return NULL;
763 if (pfile->directive == &dtable[T_PRAGMA])
765 /* This pragma allows extra tokens after the file name. */
767 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
768 check_eol (pfile, true);
769 else
771 /* If we are not discarding comments, then gather them while
772 doing the eol check. */
773 *buf = check_eol_return_comments (pfile);
776 return fname;
779 /* Handle #include, #include_next and #import. */
780 static void
781 do_include_common (cpp_reader *pfile, enum include_type type)
783 const char *fname;
784 int angle_brackets;
785 const cpp_token **buf = NULL;
786 source_location location;
788 /* Re-enable saving of comments if requested, so that the include
789 callback can dump comments which follow #include. */
790 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
792 fname = parse_include (pfile, &angle_brackets, &buf, &location);
793 if (!fname)
795 if (buf)
796 XDELETEVEC (buf);
797 return;
800 if (!*fname)
802 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
803 "empty filename in #%s",
804 pfile->directive->name);
805 XDELETEVEC (fname);
806 if (buf)
807 XDELETEVEC (buf);
808 return;
811 /* Prevent #include recursion. */
812 if (pfile->line_table->depth >= CPP_STACK_MAX)
813 cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
814 else
816 /* Get out of macro context, if we are. */
817 skip_rest_of_line (pfile);
819 if (pfile->cb.include)
820 pfile->cb.include (pfile, pfile->directive_line,
821 pfile->directive->name, fname, angle_brackets,
822 buf);
824 _cpp_stack_include (pfile, fname, angle_brackets, type);
827 XDELETEVEC (fname);
828 if (buf)
829 XDELETEVEC (buf);
832 static void
833 do_include (cpp_reader *pfile)
835 do_include_common (pfile, IT_INCLUDE);
838 static void
839 do_import (cpp_reader *pfile)
841 do_include_common (pfile, IT_IMPORT);
844 static void
845 do_include_next (cpp_reader *pfile)
847 enum include_type type = IT_INCLUDE_NEXT;
849 /* If this is the primary source file, warn and use the normal
850 search logic. */
851 if (cpp_in_primary_file (pfile))
853 cpp_error (pfile, CPP_DL_WARNING,
854 "#include_next in primary source file");
855 type = IT_INCLUDE;
857 do_include_common (pfile, type);
860 /* Subroutine of do_linemarker. Read possible flags after file name.
861 LAST is the last flag seen; 0 if this is the first flag. Return the
862 flag if it is valid, 0 at the end of the directive. Otherwise
863 complain. */
864 static unsigned int
865 read_flag (cpp_reader *pfile, unsigned int last)
867 const cpp_token *token = _cpp_lex_token (pfile);
869 if (token->type == CPP_NUMBER && token->val.str.len == 1)
871 unsigned int flag = token->val.str.text[0] - '0';
873 if (flag > last && flag <= 4
874 && (flag != 4 || last == 3)
875 && (flag != 2 || last == 0))
876 return flag;
879 if (token->type != CPP_EOF)
880 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
881 cpp_token_as_text (pfile, token));
882 return 0;
885 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
886 of length LEN, to binary; store it in NUMP, and return false if the
887 number was well-formed, true if not. WRAPPED is set to true if the
888 number did not fit into 'unsigned long'. */
889 static bool
890 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
892 linenum_type reg = 0;
893 linenum_type reg_prev = 0;
895 uchar c;
896 *wrapped = false;
897 while (len--)
899 c = *str++;
900 if (!ISDIGIT (c))
901 return true;
902 reg *= 10;
903 reg += c - '0';
904 if (reg < reg_prev)
905 *wrapped = true;
906 reg_prev = reg;
908 *nump = reg;
909 return false;
912 /* Interpret #line command.
913 Note that the filename string (if any) is a true string constant
914 (escapes are interpreted), unlike in #line. */
915 static void
916 do_line (cpp_reader *pfile)
918 const struct line_maps *line_table = pfile->line_table;
919 const struct line_map *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
921 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
922 sysp right now. */
924 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
925 const cpp_token *token;
926 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
927 linenum_type new_lineno;
929 /* C99 raised the minimum limit on #line numbers. */
930 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
931 bool wrapped;
933 /* #line commands expand macros. */
934 token = cpp_get_token (pfile);
935 if (token->type != CPP_NUMBER
936 || strtolinenum (token->val.str.text, token->val.str.len,
937 &new_lineno, &wrapped))
939 if (token->type == CPP_EOF)
940 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
941 else
942 cpp_error (pfile, CPP_DL_ERROR,
943 "\"%s\" after #line is not a positive integer",
944 cpp_token_as_text (pfile, token));
945 return;
948 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
949 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
950 else if (wrapped)
951 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
953 token = cpp_get_token (pfile);
954 if (token->type == CPP_STRING)
956 cpp_string s = { 0, 0 };
957 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
958 &s, CPP_STRING))
959 new_file = (const char *)s.text;
960 check_eol (pfile, true);
962 else if (token->type != CPP_EOF)
964 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
965 cpp_token_as_text (pfile, token));
966 return;
969 skip_rest_of_line (pfile);
970 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
971 map_sysp);
974 /* Interpret the # 44 "file" [flags] notation, which has slightly
975 different syntax and semantics from #line: Flags are allowed,
976 and we never complain about the line number being too big. */
977 static void
978 do_linemarker (cpp_reader *pfile)
980 const struct line_maps *line_table = pfile->line_table;
981 const struct line_map *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
982 const cpp_token *token;
983 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
984 linenum_type new_lineno;
985 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
986 enum lc_reason reason = LC_RENAME_VERBATIM;
987 int flag;
988 bool wrapped;
990 /* Back up so we can get the number again. Putting this in
991 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
992 some circumstances, which can segfault. */
993 _cpp_backup_tokens (pfile, 1);
995 /* #line commands expand macros. */
996 token = cpp_get_token (pfile);
997 if (token->type != CPP_NUMBER
998 || strtolinenum (token->val.str.text, token->val.str.len,
999 &new_lineno, &wrapped))
1001 /* Unlike #line, there does not seem to be a way to get an EOF
1002 here. So, it should be safe to always spell the token. */
1003 cpp_error (pfile, CPP_DL_ERROR,
1004 "\"%s\" after # is not a positive integer",
1005 cpp_token_as_text (pfile, token));
1006 return;
1009 token = cpp_get_token (pfile);
1010 if (token->type == CPP_STRING)
1012 cpp_string s = { 0, 0 };
1013 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1014 1, &s, CPP_STRING))
1015 new_file = (const char *)s.text;
1017 new_sysp = 0;
1018 flag = read_flag (pfile, 0);
1019 if (flag == 1)
1021 reason = LC_ENTER;
1022 /* Fake an include for cpp_included (). */
1023 _cpp_fake_include (pfile, new_file);
1024 flag = read_flag (pfile, flag);
1026 else if (flag == 2)
1028 reason = LC_LEAVE;
1029 flag = read_flag (pfile, flag);
1031 if (flag == 3)
1033 new_sysp = 1;
1034 flag = read_flag (pfile, flag);
1035 if (flag == 4)
1036 new_sysp = 2;
1038 pfile->buffer->sysp = new_sysp;
1040 check_eol (pfile, false);
1042 else if (token->type != CPP_EOF)
1044 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1045 cpp_token_as_text (pfile, token));
1046 return;
1049 skip_rest_of_line (pfile);
1051 /* Compensate for the increment in linemap_add that occurs in
1052 _cpp_do_file_change. We're currently at the start of the line
1053 *following* the #line directive. A separate source_location for this
1054 location makes no sense (until we do the LC_LEAVE), and
1055 complicates LAST_SOURCE_LINE_LOCATION. */
1056 pfile->line_table->highest_location--;
1058 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1061 /* Arrange the file_change callback. pfile->line has changed to
1062 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
1063 header, 2 for a system header that needs to be extern "C" protected,
1064 and zero otherwise. */
1065 void
1066 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1067 const char *to_file, linenum_type file_line,
1068 unsigned int sysp)
1070 const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1071 to_file, file_line);
1072 if (map != NULL)
1073 linemap_line_start (pfile->line_table,
1074 ORDINARY_MAP_STARTING_LINE_NUMBER (map),
1075 127);
1077 if (pfile->cb.file_change)
1078 pfile->cb.file_change (pfile, map);
1081 /* Report a warning or error detected by the program we are
1082 processing. Use the directive's tokens in the error message. */
1083 static void
1084 do_diagnostic (cpp_reader *pfile, int code, int reason, int print_dir)
1086 const unsigned char *dir_name;
1087 unsigned char *line;
1088 source_location src_loc = pfile->cur_token[-1].src_loc;
1090 if (print_dir)
1091 dir_name = pfile->directive->name;
1092 else
1093 dir_name = NULL;
1094 pfile->state.prevent_expansion++;
1095 line = cpp_output_line_to_string (pfile, dir_name);
1096 pfile->state.prevent_expansion--;
1098 if (code == CPP_DL_WARNING_SYSHDR && reason)
1099 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1100 else if (code == CPP_DL_WARNING && reason)
1101 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1102 else
1103 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1104 free (line);
1107 static void
1108 do_error (cpp_reader *pfile)
1110 do_diagnostic (pfile, CPP_DL_ERROR, 0, 1);
1113 static void
1114 do_warning (cpp_reader *pfile)
1116 /* We want #warning diagnostics to be emitted in system headers too. */
1117 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1120 /* Report program identification. */
1121 static void
1122 do_ident (cpp_reader *pfile)
1124 const cpp_token *str = cpp_get_token (pfile);
1126 if (str->type != CPP_STRING)
1127 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1128 pfile->directive->name);
1129 else if (pfile->cb.ident)
1130 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1132 check_eol (pfile, false);
1135 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1136 matching entry, or NULL if none is found. The returned entry could
1137 be the start of a namespace chain, or a pragma. */
1138 static struct pragma_entry *
1139 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1141 while (chain && chain->pragma != pragma)
1142 chain = chain->next;
1144 return chain;
1147 /* Create and insert a blank pragma entry at the beginning of a
1148 singly-linked CHAIN. */
1149 static struct pragma_entry *
1150 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1152 struct pragma_entry *new_entry;
1154 new_entry = (struct pragma_entry *)
1155 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1157 memset (new_entry, 0, sizeof (struct pragma_entry));
1158 new_entry->next = *chain;
1160 *chain = new_entry;
1161 return new_entry;
1164 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1165 goes in the global namespace. */
1166 static struct pragma_entry *
1167 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1168 bool allow_name_expansion)
1170 struct pragma_entry **chain = &pfile->pragmas;
1171 struct pragma_entry *entry;
1172 const cpp_hashnode *node;
1174 if (space)
1176 node = cpp_lookup (pfile, UC space, strlen (space));
1177 entry = lookup_pragma_entry (*chain, node);
1178 if (!entry)
1180 entry = new_pragma_entry (pfile, chain);
1181 entry->pragma = node;
1182 entry->is_nspace = true;
1183 entry->allow_expansion = allow_name_expansion;
1185 else if (!entry->is_nspace)
1186 goto clash;
1187 else if (entry->allow_expansion != allow_name_expansion)
1189 cpp_error (pfile, CPP_DL_ICE,
1190 "registering pragmas in namespace \"%s\" with mismatched "
1191 "name expansion", space);
1192 return NULL;
1194 chain = &entry->u.space;
1196 else if (allow_name_expansion)
1198 cpp_error (pfile, CPP_DL_ICE,
1199 "registering pragma \"%s\" with name expansion "
1200 "and no namespace", name);
1201 return NULL;
1204 /* Check for duplicates. */
1205 node = cpp_lookup (pfile, UC name, strlen (name));
1206 entry = lookup_pragma_entry (*chain, node);
1207 if (entry == NULL)
1209 entry = new_pragma_entry (pfile, chain);
1210 entry->pragma = node;
1211 return entry;
1214 if (entry->is_nspace)
1215 clash:
1216 cpp_error (pfile, CPP_DL_ICE,
1217 "registering \"%s\" as both a pragma and a pragma namespace",
1218 NODE_NAME (node));
1219 else if (space)
1220 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1221 space, name);
1222 else
1223 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1225 return NULL;
1228 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1229 static void
1230 register_pragma_internal (cpp_reader *pfile, const char *space,
1231 const char *name, pragma_cb handler)
1233 struct pragma_entry *entry;
1235 entry = register_pragma_1 (pfile, space, name, false);
1236 entry->is_internal = true;
1237 entry->u.handler = handler;
1240 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1241 goes in the global namespace. HANDLER is the handler it will call,
1242 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1243 expansion while parsing pragma NAME. This function is exported
1244 from libcpp. */
1245 void
1246 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1247 pragma_cb handler, bool allow_expansion)
1249 struct pragma_entry *entry;
1251 if (!handler)
1253 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1254 return;
1257 entry = register_pragma_1 (pfile, space, name, false);
1258 if (entry)
1260 entry->allow_expansion = allow_expansion;
1261 entry->u.handler = handler;
1265 /* Similarly, but create mark the pragma for deferred processing.
1266 When found, a CPP_PRAGMA token will be insertted into the stream
1267 with IDENT in the token->u.pragma slot. */
1268 void
1269 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1270 const char *name, unsigned int ident,
1271 bool allow_expansion, bool allow_name_expansion)
1273 struct pragma_entry *entry;
1275 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1276 if (entry)
1278 entry->is_deferred = true;
1279 entry->allow_expansion = allow_expansion;
1280 entry->u.ident = ident;
1284 /* Register the pragmas the preprocessor itself handles. */
1285 void
1286 _cpp_init_internal_pragmas (cpp_reader *pfile)
1288 /* Pragmas in the global namespace. */
1289 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1290 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1291 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1293 /* New GCC-specific pragmas should be put in the GCC namespace. */
1294 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1295 register_pragma_internal (pfile, "GCC", "system_header",
1296 do_pragma_system_header);
1297 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1298 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1299 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1302 /* Return the number of registered pragmas in PE. */
1304 static int
1305 count_registered_pragmas (struct pragma_entry *pe)
1307 int ct = 0;
1308 for (; pe != NULL; pe = pe->next)
1310 if (pe->is_nspace)
1311 ct += count_registered_pragmas (pe->u.space);
1312 ct++;
1314 return ct;
1317 /* Save into SD the names of the registered pragmas referenced by PE,
1318 and return a pointer to the next free space in SD. */
1320 static char **
1321 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1323 for (; pe != NULL; pe = pe->next)
1325 if (pe->is_nspace)
1326 sd = save_registered_pragmas (pe->u.space, sd);
1327 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1328 HT_LEN (&pe->pragma->ident),
1329 HT_LEN (&pe->pragma->ident) + 1);
1331 return sd;
1334 /* Return a newly-allocated array which saves the names of the
1335 registered pragmas. */
1337 char **
1338 _cpp_save_pragma_names (cpp_reader *pfile)
1340 int ct = count_registered_pragmas (pfile->pragmas);
1341 char **result = XNEWVEC (char *, ct);
1342 (void) save_registered_pragmas (pfile->pragmas, result);
1343 return result;
1346 /* Restore from SD the names of the registered pragmas referenced by PE,
1347 and return a pointer to the next unused name in SD. */
1349 static char **
1350 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1351 char **sd)
1353 for (; pe != NULL; pe = pe->next)
1355 if (pe->is_nspace)
1356 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1357 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1358 free (*sd);
1359 sd++;
1361 return sd;
1364 /* Restore the names of the registered pragmas from SAVED. */
1366 void
1367 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1369 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1370 free (saved);
1373 /* Pragmata handling. We handle some, and pass the rest on to the
1374 front end. C99 defines three pragmas and says that no macro
1375 expansion is to be performed on them; whether or not macro
1376 expansion happens for other pragmas is implementation defined.
1377 This implementation allows for a mix of both, since GCC did not
1378 traditionally macro expand its (few) pragmas, whereas OpenMP
1379 specifies that macro expansion should happen. */
1380 static void
1381 do_pragma (cpp_reader *pfile)
1383 const struct pragma_entry *p = NULL;
1384 const cpp_token *token, *pragma_token;
1385 source_location pragma_token_virt_loc = 0;
1386 cpp_token ns_token;
1387 unsigned int count = 1;
1389 pfile->state.prevent_expansion++;
1391 pragma_token = token = cpp_get_token_with_location (pfile,
1392 &pragma_token_virt_loc);
1393 ns_token = *token;
1394 if (token->type == CPP_NAME)
1396 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1397 if (p && p->is_nspace)
1399 bool allow_name_expansion = p->allow_expansion;
1400 if (allow_name_expansion)
1401 pfile->state.prevent_expansion--;
1403 token = cpp_get_token (pfile);
1404 if (token->type == CPP_NAME)
1405 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1406 else
1407 p = NULL;
1408 if (allow_name_expansion)
1409 pfile->state.prevent_expansion++;
1410 count = 2;
1414 if (p)
1416 if (p->is_deferred)
1418 pfile->directive_result.src_loc = pragma_token_virt_loc;
1419 pfile->directive_result.type = CPP_PRAGMA;
1420 pfile->directive_result.flags = pragma_token->flags;
1421 pfile->directive_result.val.pragma = p->u.ident;
1422 pfile->state.in_deferred_pragma = true;
1423 pfile->state.pragma_allow_expansion = p->allow_expansion;
1424 if (!p->allow_expansion)
1425 pfile->state.prevent_expansion++;
1427 else
1429 /* Since the handler below doesn't get the line number, that
1430 it might need for diagnostics, make sure it has the right
1431 numbers in place. */
1432 if (pfile->cb.line_change)
1433 (*pfile->cb.line_change) (pfile, pragma_token, false);
1434 if (p->allow_expansion)
1435 pfile->state.prevent_expansion--;
1436 (*p->u.handler) (pfile);
1437 if (p->allow_expansion)
1438 pfile->state.prevent_expansion++;
1441 else if (pfile->cb.def_pragma)
1443 if (count == 1 || pfile->context->prev == NULL)
1444 _cpp_backup_tokens (pfile, count);
1445 else
1447 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1448 won't allow backing 2 tokens. */
1449 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1450 reads both tokens, we could perhaps free it, but if it doesn't,
1451 we don't know the exact lifespan. */
1452 cpp_token *toks = XNEWVEC (cpp_token, 2);
1453 toks[0] = ns_token;
1454 toks[0].flags |= NO_EXPAND;
1455 toks[1] = *token;
1456 toks[1].flags |= NO_EXPAND;
1457 _cpp_push_token_context (pfile, NULL, toks, 2);
1459 pfile->cb.def_pragma (pfile, pfile->directive_line);
1462 pfile->state.prevent_expansion--;
1465 /* Handle #pragma once. */
1466 static void
1467 do_pragma_once (cpp_reader *pfile)
1469 if (cpp_in_primary_file (pfile))
1470 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1472 check_eol (pfile, false);
1473 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1476 /* Handle #pragma push_macro(STRING). */
1477 static void
1478 do_pragma_push_macro (cpp_reader *pfile)
1480 cpp_hashnode *node;
1481 size_t defnlen;
1482 const uchar *defn = NULL;
1483 char *macroname, *dest;
1484 const char *limit, *src;
1485 const cpp_token *txt;
1486 struct def_pragma_macro *c;
1488 txt = get__Pragma_string (pfile);
1489 if (!txt)
1491 source_location src_loc = pfile->cur_token[-1].src_loc;
1492 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1493 "invalid #pragma push_macro directive");
1494 check_eol (pfile, false);
1495 skip_rest_of_line (pfile);
1496 return;
1498 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1499 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1500 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1501 while (src < limit)
1503 /* We know there is a character following the backslash. */
1504 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1505 src++;
1506 *dest++ = *src++;
1508 *dest = 0;
1509 check_eol (pfile, false);
1510 skip_rest_of_line (pfile);
1511 c = XNEW (struct def_pragma_macro);
1512 memset (c, 0, sizeof (struct def_pragma_macro));
1513 c->name = XNEWVAR (char, strlen (macroname) + 1);
1514 strcpy (c->name, macroname);
1515 c->next = pfile->pushed_macros;
1516 node = _cpp_lex_identifier (pfile, c->name);
1517 if (node->type == NT_VOID)
1518 c->is_undef = 1;
1519 else
1521 defn = cpp_macro_definition (pfile, node);
1522 defnlen = ustrlen (defn);
1523 c->definition = XNEWVEC (uchar, defnlen + 2);
1524 c->definition[defnlen] = '\n';
1525 c->definition[defnlen + 1] = 0;
1526 c->line = node->value.macro->line;
1527 c->syshdr = node->value.macro->syshdr;
1528 c->used = node->value.macro->used;
1529 memcpy (c->definition, defn, defnlen);
1532 pfile->pushed_macros = c;
1535 /* Handle #pragma pop_macro(STRING). */
1536 static void
1537 do_pragma_pop_macro (cpp_reader *pfile)
1539 char *macroname, *dest;
1540 const char *limit, *src;
1541 const cpp_token *txt;
1542 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1543 txt = get__Pragma_string (pfile);
1544 if (!txt)
1546 source_location src_loc = pfile->cur_token[-1].src_loc;
1547 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1548 "invalid #pragma pop_macro directive");
1549 check_eol (pfile, false);
1550 skip_rest_of_line (pfile);
1551 return;
1553 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1554 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1555 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1556 while (src < limit)
1558 /* We know there is a character following the backslash. */
1559 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1560 src++;
1561 *dest++ = *src++;
1563 *dest = 0;
1564 check_eol (pfile, false);
1565 skip_rest_of_line (pfile);
1567 while (c != NULL)
1569 if (!strcmp (c->name, macroname))
1571 if (!l)
1572 pfile->pushed_macros = c->next;
1573 else
1574 l->next = c->next;
1575 cpp_pop_definition (pfile, c);
1576 free (c->definition);
1577 free (c->name);
1578 free (c);
1579 break;
1581 l = c;
1582 c = c->next;
1586 /* Handle #pragma GCC poison, to poison one or more identifiers so
1587 that the lexer produces a hard error for each subsequent usage. */
1588 static void
1589 do_pragma_poison (cpp_reader *pfile)
1591 const cpp_token *tok;
1592 cpp_hashnode *hp;
1594 pfile->state.poisoned_ok = 1;
1595 for (;;)
1597 tok = _cpp_lex_token (pfile);
1598 if (tok->type == CPP_EOF)
1599 break;
1600 if (tok->type != CPP_NAME)
1602 cpp_error (pfile, CPP_DL_ERROR,
1603 "invalid #pragma GCC poison directive");
1604 break;
1607 hp = tok->val.node.node;
1608 if (hp->flags & NODE_POISONED)
1609 continue;
1611 if (hp->type == NT_MACRO)
1612 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1613 NODE_NAME (hp));
1614 _cpp_free_definition (hp);
1615 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1617 pfile->state.poisoned_ok = 0;
1620 /* Mark the current header as a system header. This will suppress
1621 some categories of warnings (notably those from -pedantic). It is
1622 intended for use in system libraries that cannot be implemented in
1623 conforming C, but cannot be certain that their headers appear in a
1624 system include directory. To prevent abuse, it is rejected in the
1625 primary source file. */
1626 static void
1627 do_pragma_system_header (cpp_reader *pfile)
1629 if (cpp_in_primary_file (pfile))
1630 cpp_error (pfile, CPP_DL_WARNING,
1631 "#pragma system_header ignored outside include file");
1632 else
1634 check_eol (pfile, false);
1635 skip_rest_of_line (pfile);
1636 cpp_make_system_header (pfile, 1, 0);
1640 /* Check the modified date of the current include file against a specified
1641 file. Issue a diagnostic, if the specified file is newer. We use this to
1642 determine if a fixed header should be refixed. */
1643 static void
1644 do_pragma_dependency (cpp_reader *pfile)
1646 const char *fname;
1647 int angle_brackets, ordering;
1648 source_location location;
1650 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1651 if (!fname)
1652 return;
1654 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1655 if (ordering < 0)
1656 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1657 else if (ordering > 0)
1659 cpp_error (pfile, CPP_DL_WARNING,
1660 "current file is older than %s", fname);
1661 if (cpp_get_token (pfile)->type != CPP_EOF)
1663 _cpp_backup_tokens (pfile, 1);
1664 do_diagnostic (pfile, CPP_DL_WARNING, 0, 0);
1668 free ((void *) fname);
1671 /* Issue a diagnostic with the message taken from the pragma. If
1672 ERROR is true, the diagnostic is a warning, otherwise, it is an
1673 error. */
1674 static void
1675 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1677 const cpp_token *tok = _cpp_lex_token (pfile);
1678 cpp_string str;
1679 if (tok->type != CPP_STRING
1680 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1681 CPP_STRING)
1682 || str.len == 0)
1684 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1685 error ? "error" : "warning");
1686 return;
1688 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1689 "%s", str.text);
1690 free ((void *)str.text);
1693 /* Issue a warning diagnostic. */
1694 static void
1695 do_pragma_warning (cpp_reader *pfile)
1697 do_pragma_warning_or_error (pfile, false);
1700 /* Issue an error diagnostic. */
1701 static void
1702 do_pragma_error (cpp_reader *pfile)
1704 do_pragma_warning_or_error (pfile, true);
1707 /* Get a token but skip padding. */
1708 static const cpp_token *
1709 get_token_no_padding (cpp_reader *pfile)
1711 for (;;)
1713 const cpp_token *result = cpp_get_token (pfile);
1714 if (result->type != CPP_PADDING)
1715 return result;
1719 /* Check syntax is "(string-literal)". Returns the string on success,
1720 or NULL on failure. */
1721 static const cpp_token *
1722 get__Pragma_string (cpp_reader *pfile)
1724 const cpp_token *string;
1725 const cpp_token *paren;
1727 paren = get_token_no_padding (pfile);
1728 if (paren->type == CPP_EOF)
1729 _cpp_backup_tokens (pfile, 1);
1730 if (paren->type != CPP_OPEN_PAREN)
1731 return NULL;
1733 string = get_token_no_padding (pfile);
1734 if (string->type == CPP_EOF)
1735 _cpp_backup_tokens (pfile, 1);
1736 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1737 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1738 && string->type != CPP_UTF8STRING)
1739 return NULL;
1741 paren = get_token_no_padding (pfile);
1742 if (paren->type == CPP_EOF)
1743 _cpp_backup_tokens (pfile, 1);
1744 if (paren->type != CPP_CLOSE_PAREN)
1745 return NULL;
1747 return string;
1750 /* Destringize IN into a temporary buffer, by removing the first \ of
1751 \" and \\ sequences, and process the result as a #pragma directive. */
1752 static void
1753 destringize_and_run (cpp_reader *pfile, const cpp_string *in)
1755 const unsigned char *src, *limit;
1756 char *dest, *result;
1757 cpp_context *saved_context;
1758 cpp_token *saved_cur_token;
1759 tokenrun *saved_cur_run;
1760 cpp_token *toks;
1761 int count;
1762 const struct directive *save_directive;
1764 dest = result = (char *) alloca (in->len - 1);
1765 src = in->text + 1 + (in->text[0] == 'L');
1766 limit = in->text + in->len - 1;
1767 while (src < limit)
1769 /* We know there is a character following the backslash. */
1770 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1771 src++;
1772 *dest++ = *src++;
1774 *dest = '\n';
1776 /* Ugh; an awful kludge. We are really not set up to be lexing
1777 tokens when in the middle of a macro expansion. Use a new
1778 context to force cpp_get_token to lex, and so skip_rest_of_line
1779 doesn't go beyond the end of the text. Also, remember the
1780 current lexing position so we can return to it later.
1782 Something like line-at-a-time lexing should remove the need for
1783 this. */
1784 saved_context = pfile->context;
1785 saved_cur_token = pfile->cur_token;
1786 saved_cur_run = pfile->cur_run;
1788 pfile->context = XCNEW (cpp_context);
1790 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1791 until we've read all of the tokens that we want. */
1792 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1793 /* from_stage3 */ true);
1794 /* ??? Antique Disgusting Hack. What does this do? */
1795 if (pfile->buffer->prev)
1796 pfile->buffer->file = pfile->buffer->prev->file;
1798 start_directive (pfile);
1799 _cpp_clean_line (pfile);
1800 save_directive = pfile->directive;
1801 pfile->directive = &dtable[T_PRAGMA];
1802 do_pragma (pfile);
1803 end_directive (pfile, 1);
1804 pfile->directive = save_directive;
1806 /* We always insert at least one token, the directive result. It'll
1807 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1808 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1810 /* If we're not handling the pragma internally, read all of the tokens from
1811 the string buffer now, while the string buffer is still installed. */
1812 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1813 to me what the true lifespan of the tokens are. It would appear that
1814 the lifespan is the entire parse of the main input stream, in which case
1815 this may not be wrong. */
1816 if (pfile->directive_result.type == CPP_PRAGMA)
1818 int maxcount;
1820 count = 1;
1821 maxcount = 50;
1822 toks = XNEWVEC (cpp_token, maxcount);
1823 toks[0] = pfile->directive_result;
1827 if (count == maxcount)
1829 maxcount = maxcount * 3 / 2;
1830 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1832 toks[count] = *cpp_get_token (pfile);
1833 /* Macros have been already expanded by cpp_get_token
1834 if the pragma allowed expansion. */
1835 toks[count++].flags |= NO_EXPAND;
1837 while (toks[count-1].type != CPP_PRAGMA_EOL);
1839 else
1841 count = 1;
1842 toks = XNEW (cpp_token);
1843 toks[0] = pfile->directive_result;
1845 /* If we handled the entire pragma internally, make sure we get the
1846 line number correct for the next token. */
1847 if (pfile->cb.line_change)
1848 pfile->cb.line_change (pfile, pfile->cur_token, false);
1851 /* Finish inlining run_directive. */
1852 pfile->buffer->file = NULL;
1853 _cpp_pop_buffer (pfile);
1855 /* Reset the old macro state before ... */
1856 XDELETE (pfile->context);
1857 pfile->context = saved_context;
1858 pfile->cur_token = saved_cur_token;
1859 pfile->cur_run = saved_cur_run;
1861 /* ... inserting the new tokens we collected. */
1862 _cpp_push_token_context (pfile, NULL, toks, count);
1865 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1867 _cpp_do__Pragma (cpp_reader *pfile)
1869 const cpp_token *string = get__Pragma_string (pfile);
1870 pfile->directive_result.type = CPP_PADDING;
1872 if (string)
1874 destringize_and_run (pfile, &string->val.str);
1875 return 1;
1877 cpp_error (pfile, CPP_DL_ERROR,
1878 "_Pragma takes a parenthesized string literal");
1879 return 0;
1882 /* Handle #ifdef. */
1883 static void
1884 do_ifdef (cpp_reader *pfile)
1886 int skip = 1;
1888 if (! pfile->state.skipping)
1890 cpp_hashnode *node = lex_macro_node (pfile, false);
1892 if (node)
1894 /* Do not treat conditional macros as being defined. This is due to
1895 the powerpc and spu ports using conditional macros for 'vector',
1896 'bool', and 'pixel' to act as conditional keywords. This messes
1897 up tests like #ifndef bool. */
1898 skip = (node->type != NT_MACRO
1899 || ((node->flags & NODE_CONDITIONAL) != 0));
1900 _cpp_mark_macro_used (node);
1901 if (!(node->flags & NODE_USED))
1903 node->flags |= NODE_USED;
1904 if (node->type == NT_MACRO)
1906 if ((node->flags & NODE_BUILTIN)
1907 && pfile->cb.user_builtin_macro)
1908 pfile->cb.user_builtin_macro (pfile, node);
1909 if (pfile->cb.used_define)
1910 pfile->cb.used_define (pfile, pfile->directive_line, node);
1912 else
1914 if (pfile->cb.used_undef)
1915 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1918 if (pfile->cb.used)
1919 pfile->cb.used (pfile, pfile->directive_line, node);
1920 check_eol (pfile, false);
1924 push_conditional (pfile, skip, T_IFDEF, 0);
1927 /* Handle #ifndef. */
1928 static void
1929 do_ifndef (cpp_reader *pfile)
1931 int skip = 1;
1932 cpp_hashnode *node = 0;
1934 if (! pfile->state.skipping)
1936 node = lex_macro_node (pfile, false);
1938 if (node)
1940 /* Do not treat conditional macros as being defined. This is due to
1941 the powerpc and spu ports using conditional macros for 'vector',
1942 'bool', and 'pixel' to act as conditional keywords. This messes
1943 up tests like #ifndef bool. */
1944 skip = (node->type == NT_MACRO
1945 && ((node->flags & NODE_CONDITIONAL) == 0));
1946 _cpp_mark_macro_used (node);
1947 if (!(node->flags & NODE_USED))
1949 node->flags |= NODE_USED;
1950 if (node->type == NT_MACRO)
1952 if ((node->flags & NODE_BUILTIN)
1953 && pfile->cb.user_builtin_macro)
1954 pfile->cb.user_builtin_macro (pfile, node);
1955 if (pfile->cb.used_define)
1956 pfile->cb.used_define (pfile, pfile->directive_line, node);
1958 else
1960 if (pfile->cb.used_undef)
1961 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1964 if (pfile->cb.used)
1965 pfile->cb.used (pfile, pfile->directive_line, node);
1966 check_eol (pfile, false);
1970 push_conditional (pfile, skip, T_IFNDEF, node);
1973 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1974 pfile->mi_ind_cmacro so we can handle multiple-include
1975 optimizations. If macro expansion occurs in the expression, we
1976 cannot treat it as a controlling conditional, since the expansion
1977 could change in the future. That is handled by cpp_get_token. */
1978 static void
1979 do_if (cpp_reader *pfile)
1981 int skip = 1;
1983 if (! pfile->state.skipping)
1984 skip = _cpp_parse_expr (pfile, true) == false;
1986 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1989 /* Flip skipping state if appropriate and continue without changing
1990 if_stack; this is so that the error message for missing #endif's
1991 etc. will point to the original #if. */
1992 static void
1993 do_else (cpp_reader *pfile)
1995 cpp_buffer *buffer = pfile->buffer;
1996 struct if_stack *ifs = buffer->if_stack;
1998 if (ifs == NULL)
1999 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2000 else
2002 if (ifs->type == T_ELSE)
2004 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2005 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2006 "the conditional began here");
2008 ifs->type = T_ELSE;
2010 /* Skip any future (erroneous) #elses or #elifs. */
2011 pfile->state.skipping = ifs->skip_elses;
2012 ifs->skip_elses = true;
2014 /* Invalidate any controlling macro. */
2015 ifs->mi_cmacro = 0;
2017 /* Only check EOL if was not originally skipping. */
2018 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2019 check_eol_endif_labels (pfile);
2023 /* Handle a #elif directive by not changing if_stack either. See the
2024 comment above do_else. */
2025 static void
2026 do_elif (cpp_reader *pfile)
2028 cpp_buffer *buffer = pfile->buffer;
2029 struct if_stack *ifs = buffer->if_stack;
2031 if (ifs == NULL)
2032 cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2033 else
2035 if (ifs->type == T_ELSE)
2037 cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2038 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2039 "the conditional began here");
2041 ifs->type = T_ELIF;
2043 if (! ifs->was_skipping)
2045 bool value;
2046 /* The standard mandates that the expression be parsed even
2047 if we are skipping elses at this point -- the lexical
2048 restrictions on #elif only apply to skipped groups, but
2049 this group is not being skipped. Temporarily set
2050 skipping to false to get lexer warnings. */
2051 pfile->state.skipping = 0;
2052 value = _cpp_parse_expr (pfile, false);
2053 if (ifs->skip_elses)
2054 pfile->state.skipping = 1;
2055 else
2057 pfile->state.skipping = ! value;
2058 ifs->skip_elses = value;
2062 /* Invalidate any controlling macro. */
2063 ifs->mi_cmacro = 0;
2067 /* #endif pops the if stack and resets pfile->state.skipping. */
2068 static void
2069 do_endif (cpp_reader *pfile)
2071 cpp_buffer *buffer = pfile->buffer;
2072 struct if_stack *ifs = buffer->if_stack;
2074 if (ifs == NULL)
2075 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2076 else
2078 /* Only check EOL if was not originally skipping. */
2079 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2080 check_eol_endif_labels (pfile);
2082 /* If potential control macro, we go back outside again. */
2083 if (ifs->next == 0 && ifs->mi_cmacro)
2085 pfile->mi_valid = true;
2086 pfile->mi_cmacro = ifs->mi_cmacro;
2089 buffer->if_stack = ifs->next;
2090 pfile->state.skipping = ifs->was_skipping;
2091 obstack_free (&pfile->buffer_ob, ifs);
2095 /* Push an if_stack entry for a preprocessor conditional, and set
2096 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2097 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2098 we need to check here that we are at the top of the file. */
2099 static void
2100 push_conditional (cpp_reader *pfile, int skip, int type,
2101 const cpp_hashnode *cmacro)
2103 struct if_stack *ifs;
2104 cpp_buffer *buffer = pfile->buffer;
2106 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2107 ifs->line = pfile->directive_line;
2108 ifs->next = buffer->if_stack;
2109 ifs->skip_elses = pfile->state.skipping || !skip;
2110 ifs->was_skipping = pfile->state.skipping;
2111 ifs->type = type;
2112 /* This condition is effectively a test for top-of-file. */
2113 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2114 ifs->mi_cmacro = cmacro;
2115 else
2116 ifs->mi_cmacro = 0;
2118 pfile->state.skipping = skip;
2119 buffer->if_stack = ifs;
2122 /* Read the tokens of the answer into the macro pool, in a directive
2123 of type TYPE. Only commit the memory if we intend it as permanent
2124 storage, i.e. the #assert case. Returns 0 on success, and sets
2125 ANSWERP to point to the answer. PRED_LOC is the location of the
2126 predicate. */
2127 static int
2128 parse_answer (cpp_reader *pfile, struct answer **answerp, int type,
2129 source_location pred_loc)
2131 const cpp_token *paren;
2132 struct answer *answer;
2133 unsigned int acount;
2135 /* In a conditional, it is legal to not have an open paren. We
2136 should save the following token in this case. */
2137 paren = cpp_get_token (pfile);
2139 /* If not a paren, see if we're OK. */
2140 if (paren->type != CPP_OPEN_PAREN)
2142 /* In a conditional no answer is a test for any answer. It
2143 could be followed by any token. */
2144 if (type == T_IF)
2146 _cpp_backup_tokens (pfile, 1);
2147 return 0;
2150 /* #unassert with no answer is valid - it removes all answers. */
2151 if (type == T_UNASSERT && paren->type == CPP_EOF)
2152 return 0;
2154 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2155 "missing '(' after predicate");
2156 return 1;
2159 for (acount = 0;; acount++)
2161 size_t room_needed;
2162 const cpp_token *token = cpp_get_token (pfile);
2163 cpp_token *dest;
2165 if (token->type == CPP_CLOSE_PAREN)
2166 break;
2168 if (token->type == CPP_EOF)
2170 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2171 return 1;
2174 /* struct answer includes the space for one token. */
2175 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
2177 if (BUFF_ROOM (pfile->a_buff) < room_needed)
2178 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
2180 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
2181 *dest = *token;
2183 /* Drop whitespace at start, for answer equivalence purposes. */
2184 if (acount == 0)
2185 dest->flags &= ~PREV_WHITE;
2188 if (acount == 0)
2190 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2191 return 1;
2194 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
2195 answer->count = acount;
2196 answer->next = NULL;
2197 *answerp = answer;
2199 return 0;
2202 /* Parses an assertion directive of type TYPE, returning a pointer to
2203 the hash node of the predicate, or 0 on error. If an answer was
2204 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
2205 static cpp_hashnode *
2206 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
2208 cpp_hashnode *result = 0;
2209 const cpp_token *predicate;
2211 /* We don't expand predicates or answers. */
2212 pfile->state.prevent_expansion++;
2214 *answerp = 0;
2215 predicate = cpp_get_token (pfile);
2216 if (predicate->type == CPP_EOF)
2217 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2218 else if (predicate->type != CPP_NAME)
2219 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2220 "predicate must be an identifier");
2221 else if (parse_answer (pfile, answerp, type, predicate->src_loc) == 0)
2223 unsigned int len = NODE_LEN (predicate->val.node.node);
2224 unsigned char *sym = (unsigned char *) alloca (len + 1);
2226 /* Prefix '#' to get it out of macro namespace. */
2227 sym[0] = '#';
2228 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2229 result = cpp_lookup (pfile, sym, len + 1);
2232 pfile->state.prevent_expansion--;
2233 return result;
2236 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2237 or a pointer to NULL if the answer is not in the chain. */
2238 static struct answer **
2239 find_answer (cpp_hashnode *node, const struct answer *candidate)
2241 unsigned int i;
2242 struct answer **result;
2244 for (result = &node->value.answers; *result; result = &(*result)->next)
2246 struct answer *answer = *result;
2248 if (answer->count == candidate->count)
2250 for (i = 0; i < answer->count; i++)
2251 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
2252 break;
2254 if (i == answer->count)
2255 break;
2259 return result;
2262 /* Test an assertion within a preprocessor conditional. Returns
2263 nonzero on failure, zero on success. On success, the result of
2264 the test is written into VALUE, otherwise the value 0. */
2266 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2268 struct answer *answer;
2269 cpp_hashnode *node;
2271 node = parse_assertion (pfile, &answer, T_IF);
2273 /* For recovery, an erroneous assertion expression is handled as a
2274 failing assertion. */
2275 *value = 0;
2277 if (node)
2278 *value = (node->type == NT_ASSERTION &&
2279 (answer == 0 || *find_answer (node, answer) != 0));
2280 else if (pfile->cur_token[-1].type == CPP_EOF)
2281 _cpp_backup_tokens (pfile, 1);
2283 /* We don't commit the memory for the answer - it's temporary only. */
2284 return node == 0;
2287 /* Handle #assert. */
2288 static void
2289 do_assert (cpp_reader *pfile)
2291 struct answer *new_answer;
2292 cpp_hashnode *node;
2294 node = parse_assertion (pfile, &new_answer, T_ASSERT);
2295 if (node)
2297 size_t answer_size;
2299 /* Place the new answer in the answer list. First check there
2300 is not a duplicate. */
2301 new_answer->next = 0;
2302 if (node->type == NT_ASSERTION)
2304 if (*find_answer (node, new_answer))
2306 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2307 NODE_NAME (node) + 1);
2308 return;
2310 new_answer->next = node->value.answers;
2313 answer_size = sizeof (struct answer) + ((new_answer->count - 1)
2314 * sizeof (cpp_token));
2315 /* Commit or allocate storage for the object. */
2316 if (pfile->hash_table->alloc_subobject)
2318 struct answer *temp_answer = new_answer;
2319 new_answer = (struct answer *) pfile->hash_table->alloc_subobject
2320 (answer_size);
2321 memcpy (new_answer, temp_answer, answer_size);
2323 else
2324 BUFF_FRONT (pfile->a_buff) += answer_size;
2326 node->type = NT_ASSERTION;
2327 node->value.answers = new_answer;
2328 check_eol (pfile, false);
2332 /* Handle #unassert. */
2333 static void
2334 do_unassert (cpp_reader *pfile)
2336 cpp_hashnode *node;
2337 struct answer *answer;
2339 node = parse_assertion (pfile, &answer, T_UNASSERT);
2340 /* It isn't an error to #unassert something that isn't asserted. */
2341 if (node && node->type == NT_ASSERTION)
2343 if (answer)
2345 struct answer **p = find_answer (node, answer), *temp;
2347 /* Remove the answer from the list. */
2348 temp = *p;
2349 if (temp)
2350 *p = temp->next;
2352 /* Did we free the last answer? */
2353 if (node->value.answers == 0)
2354 node->type = NT_VOID;
2356 check_eol (pfile, false);
2358 else
2359 _cpp_free_definition (node);
2362 /* We don't commit the memory for the answer - it's temporary only. */
2365 /* These are for -D, -U, -A. */
2367 /* Process the string STR as if it appeared as the body of a #define.
2368 If STR is just an identifier, define it with value 1.
2369 If STR has anything after the identifier, then it should
2370 be identifier=definition. */
2371 void
2372 cpp_define (cpp_reader *pfile, const char *str)
2374 char *buf;
2375 const char *p;
2376 size_t count;
2378 /* Copy the entire option so we can modify it.
2379 Change the first "=" in the string to a space. If there is none,
2380 tack " 1" on the end. */
2382 count = strlen (str);
2383 buf = (char *) alloca (count + 3);
2384 memcpy (buf, str, count);
2386 p = strchr (str, '=');
2387 if (p)
2388 buf[p - str] = ' ';
2389 else
2391 buf[count++] = ' ';
2392 buf[count++] = '1';
2394 buf[count] = '\n';
2396 run_directive (pfile, T_DEFINE, buf, count);
2400 /* Use to build macros to be run through cpp_define() as
2401 described above.
2402 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2404 void
2405 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2407 char *ptr;
2409 va_list ap;
2410 va_start (ap, fmt);
2411 ptr = xvasprintf (fmt, ap);
2412 va_end (ap);
2414 cpp_define (pfile, ptr);
2415 free (ptr);
2419 /* Slight variant of the above for use by initialize_builtins. */
2420 void
2421 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2423 size_t len = strlen (str);
2424 char *buf = (char *) alloca (len + 1);
2425 memcpy (buf, str, len);
2426 buf[len] = '\n';
2427 run_directive (pfile, T_DEFINE, buf, len);
2430 /* Process MACRO as if it appeared as the body of an #undef. */
2431 void
2432 cpp_undef (cpp_reader *pfile, const char *macro)
2434 size_t len = strlen (macro);
2435 char *buf = (char *) alloca (len + 1);
2436 memcpy (buf, macro, len);
2437 buf[len] = '\n';
2438 run_directive (pfile, T_UNDEF, buf, len);
2441 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2442 or first element is zero, then the macro should be undefined. */
2443 static void
2444 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2446 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2447 if (node == NULL)
2448 return;
2450 if (pfile->cb.before_define)
2451 pfile->cb.before_define (pfile);
2453 if (node->type == NT_MACRO)
2455 if (pfile->cb.undef)
2456 pfile->cb.undef (pfile, pfile->directive_line, node);
2457 if (CPP_OPTION (pfile, warn_unused_macros))
2458 _cpp_warn_if_unused_macro (pfile, node, NULL);
2460 if (node->type != NT_VOID)
2461 _cpp_free_definition (node);
2463 if (c->is_undef)
2464 return;
2466 size_t namelen;
2467 const uchar *dn;
2468 cpp_hashnode *h = NULL;
2469 cpp_buffer *nbuf;
2471 namelen = ustrcspn (c->definition, "( \n");
2472 h = cpp_lookup (pfile, c->definition, namelen);
2473 dn = c->definition + namelen;
2475 h->type = NT_VOID;
2476 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
2477 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2478 if (nbuf != NULL)
2480 _cpp_clean_line (pfile);
2481 nbuf->sysp = 1;
2482 if (!_cpp_create_definition (pfile, h))
2483 abort ();
2484 _cpp_pop_buffer (pfile);
2486 else
2487 abort ();
2488 h->value.macro->line = c->line;
2489 h->value.macro->syshdr = c->syshdr;
2490 h->value.macro->used = c->used;
2494 /* Process the string STR as if it appeared as the body of a #assert. */
2495 void
2496 cpp_assert (cpp_reader *pfile, const char *str)
2498 handle_assertion (pfile, str, T_ASSERT);
2501 /* Process STR as if it appeared as the body of an #unassert. */
2502 void
2503 cpp_unassert (cpp_reader *pfile, const char *str)
2505 handle_assertion (pfile, str, T_UNASSERT);
2508 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2509 static void
2510 handle_assertion (cpp_reader *pfile, const char *str, int type)
2512 size_t count = strlen (str);
2513 const char *p = strchr (str, '=');
2515 /* Copy the entire option so we can modify it. Change the first
2516 "=" in the string to a '(', and tack a ')' on the end. */
2517 char *buf = (char *) alloca (count + 2);
2519 memcpy (buf, str, count);
2520 if (p)
2522 buf[p - str] = '(';
2523 buf[count++] = ')';
2525 buf[count] = '\n';
2526 str = buf;
2528 run_directive (pfile, type, str, count);
2531 /* The options structure. */
2532 cpp_options *
2533 cpp_get_options (cpp_reader *pfile)
2535 return &pfile->opts;
2538 /* The callbacks structure. */
2539 cpp_callbacks *
2540 cpp_get_callbacks (cpp_reader *pfile)
2542 return &pfile->cb;
2545 /* Copy the given callbacks structure to our own. */
2546 void
2547 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2549 pfile->cb = *cb;
2552 /* The dependencies structure. (Creates one if it hasn't already been.) */
2553 struct deps *
2554 cpp_get_deps (cpp_reader *pfile)
2556 if (!pfile->deps)
2557 pfile->deps = deps_init ();
2558 return pfile->deps;
2561 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2562 doesn't fail. It does not generate a file change call back; that
2563 is the responsibility of the caller. */
2564 cpp_buffer *
2565 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2566 int from_stage3)
2568 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2570 /* Clears, amongst other things, if_stack and mi_cmacro. */
2571 memset (new_buffer, 0, sizeof (cpp_buffer));
2573 new_buffer->next_line = new_buffer->buf = buffer;
2574 new_buffer->rlimit = buffer + len;
2575 new_buffer->from_stage3 = from_stage3;
2576 new_buffer->prev = pfile->buffer;
2577 new_buffer->need_line = true;
2579 pfile->buffer = new_buffer;
2581 return new_buffer;
2584 /* Pops a single buffer, with a file change call-back if appropriate.
2585 Then pushes the next -include file, if any remain. */
2586 void
2587 _cpp_pop_buffer (cpp_reader *pfile)
2589 cpp_buffer *buffer = pfile->buffer;
2590 struct _cpp_file *inc = buffer->file;
2591 struct if_stack *ifs;
2592 const unsigned char *to_free;
2594 /* Walk back up the conditional stack till we reach its level at
2595 entry to this file, issuing error messages. */
2596 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2597 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2598 "unterminated #%s", dtable[ifs->type].name);
2600 /* In case of a missing #endif. */
2601 pfile->state.skipping = 0;
2603 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2604 pfile->buffer = buffer->prev;
2606 to_free = buffer->to_free;
2607 free (buffer->notes);
2609 /* Free the buffer object now; we may want to push a new buffer
2610 in _cpp_push_next_include_file. */
2611 obstack_free (&pfile->buffer_ob, buffer);
2613 if (inc)
2615 _cpp_pop_file_buffer (pfile, inc, to_free);
2617 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2621 /* Enter all recognized directives in the hash table. */
2622 void
2623 _cpp_init_directives (cpp_reader *pfile)
2625 unsigned int i;
2626 cpp_hashnode *node;
2628 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2630 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2631 node->is_directive = 1;
2632 node->directive_index = i;
2636 /* Extract header file from a bracket include. Parsing starts after '<'.
2637 The string is malloced and must be freed by the caller. */
2638 char *
2639 _cpp_bracket_include(cpp_reader *pfile)
2641 return glue_header_name (pfile);