2016-03-02 Richard Biener <rguenther@suse.de>
[official-gcc.git] / libcpp / directives.c
blob63f54ef72307e8bd7d598fe7e830c635852dfe60
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2016 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 source_location);
127 static int parse_answer (cpp_reader *, struct answer **, int, source_location);
128 static cpp_hashnode *parse_assertion (cpp_reader *, struct answer **, int);
129 static struct answer ** find_answer (cpp_hashnode *, const struct answer *);
130 static void handle_assertion (cpp_reader *, const char *, int);
131 static void do_pragma_push_macro (cpp_reader *);
132 static void do_pragma_pop_macro (cpp_reader *);
133 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
135 /* This is the table of directive handlers. It is ordered by
136 frequency of occurrence; the numbers at the end are directive
137 counts from all the source code I have lying around (egcs and libc
138 CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
139 pcmcia-cs-3.0.9). This is no longer important as directive lookup
140 is now O(1). All extensions other than #warning, #include_next,
141 and #import are deprecated. The name is where the extension
142 appears to have come from. */
144 #define DIRECTIVE_TABLE \
145 D(define, T_DEFINE = 0, KANDR, IN_I) /* 270554 */ \
146 D(include, T_INCLUDE, KANDR, INCL | EXPAND) /* 52262 */ \
147 D(endif, T_ENDIF, KANDR, COND) /* 45855 */ \
148 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) /* 22000 */ \
149 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) /* 18162 */ \
150 D(else, T_ELSE, KANDR, COND) /* 9863 */ \
151 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) /* 9675 */ \
152 D(undef, T_UNDEF, KANDR, IN_I) /* 4837 */ \
153 D(line, T_LINE, KANDR, EXPAND) /* 2465 */ \
154 D(elif, T_ELIF, STDC89, COND | EXPAND) /* 610 */ \
155 D(error, T_ERROR, STDC89, 0) /* 475 */ \
156 D(pragma, T_PRAGMA, STDC89, IN_I) /* 195 */ \
157 D(warning, T_WARNING, EXTENSION, 0) /* 22 */ \
158 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) /* 19 */ \
159 D(ident, T_IDENT, EXTENSION, IN_I) /* 11 */ \
160 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* 0 ObjC */ \
161 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
162 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
163 D(sccs, T_SCCS, EXTENSION, IN_I) /* 0 SVR4? */
165 /* #sccs is synonymous with #ident. */
166 #define do_sccs do_ident
168 /* Use the table to generate a series of prototypes, an enum for the
169 directive names, and an array of directive handlers. */
171 #define D(name, t, o, f) static void do_##name (cpp_reader *);
172 DIRECTIVE_TABLE
173 #undef D
175 #define D(n, tag, o, f) tag,
176 enum
178 DIRECTIVE_TABLE
179 N_DIRECTIVES
181 #undef D
183 #define D(name, t, origin, flags) \
184 { do_##name, (const uchar *) #name, \
185 sizeof #name - 1, origin, flags },
186 static const directive dtable[] =
188 DIRECTIVE_TABLE
190 #undef D
191 #undef DIRECTIVE_TABLE
193 /* Wrapper struct directive for linemarkers.
194 The origin is more or less true - the original K+R cpp
195 did use this notation in its preprocessed output. */
196 static const directive linemarker_dir =
198 do_linemarker, UC"#", 1, KANDR, IN_I
201 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
203 /* Skip any remaining tokens in a directive. */
204 static void
205 skip_rest_of_line (cpp_reader *pfile)
207 /* Discard all stacked contexts. */
208 while (pfile->context->prev)
209 _cpp_pop_context (pfile);
211 /* Sweep up all tokens remaining on the line. */
212 if (! SEEN_EOL ())
213 while (_cpp_lex_token (pfile)->type != CPP_EOF)
217 /* Helper function for check_oel. */
219 static void
220 check_eol_1 (cpp_reader *pfile, bool expand, int reason)
222 if (! SEEN_EOL () && (expand
223 ? cpp_get_token (pfile)
224 : _cpp_lex_token (pfile))->type != CPP_EOF)
225 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
226 pfile->directive->name);
229 /* Variant of check_eol used for Wendif-labels warnings. */
231 static void
232 check_eol_endif_labels (cpp_reader *pfile)
234 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
237 /* Ensure there are no stray tokens at the end of a directive. If
238 EXPAND is true, tokens macro-expanding to nothing are allowed. */
240 static void
241 check_eol (cpp_reader *pfile, bool expand)
243 check_eol_1 (pfile, expand, CPP_W_NONE);
246 /* Ensure there are no stray tokens other than comments at the end of
247 a directive, and gather the comments. */
248 static const cpp_token **
249 check_eol_return_comments (cpp_reader *pfile)
251 size_t c;
252 size_t capacity = 8;
253 const cpp_token **buf;
255 buf = XNEWVEC (const cpp_token *, capacity);
256 c = 0;
257 if (! SEEN_EOL ())
259 while (1)
261 const cpp_token *tok;
263 tok = _cpp_lex_token (pfile);
264 if (tok->type == CPP_EOF)
265 break;
266 if (tok->type != CPP_COMMENT)
267 cpp_error (pfile, CPP_DL_PEDWARN,
268 "extra tokens at end of #%s directive",
269 pfile->directive->name);
270 else
272 if (c + 1 >= capacity)
274 capacity *= 2;
275 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
277 buf[c] = tok;
278 ++c;
282 buf[c] = NULL;
283 return buf;
286 /* Called when entering a directive, _Pragma or command-line directive. */
287 static void
288 start_directive (cpp_reader *pfile)
290 /* Setup in-directive state. */
291 pfile->state.in_directive = 1;
292 pfile->state.save_comments = 0;
293 pfile->directive_result.type = CPP_PADDING;
295 /* Some handlers need the position of the # for diagnostics. */
296 pfile->directive_line = pfile->line_table->highest_line;
299 /* Called when leaving a directive, _Pragma or command-line directive. */
300 static void
301 end_directive (cpp_reader *pfile, int skip_line)
303 if (CPP_OPTION (pfile, traditional))
305 /* Revert change of prepare_directive_trad. */
306 if (!pfile->state.in_deferred_pragma)
307 pfile->state.prevent_expansion--;
309 if (pfile->directive != &dtable[T_DEFINE])
310 _cpp_remove_overlay (pfile);
312 else if (pfile->state.in_deferred_pragma)
314 /* We don't skip for an assembler #. */
315 else if (skip_line)
317 skip_rest_of_line (pfile);
318 if (!pfile->keep_tokens)
320 pfile->cur_run = &pfile->base_run;
321 pfile->cur_token = pfile->base_run.base;
325 /* Restore state. */
326 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
327 pfile->state.in_directive = 0;
328 pfile->state.in_expression = 0;
329 pfile->state.angled_headers = 0;
330 pfile->directive = 0;
333 /* Prepare to handle the directive in pfile->directive. */
334 static void
335 prepare_directive_trad (cpp_reader *pfile)
337 if (pfile->directive != &dtable[T_DEFINE])
339 bool no_expand = (pfile->directive
340 && ! (pfile->directive->flags & EXPAND));
341 bool was_skipping = pfile->state.skipping;
343 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
344 || pfile->directive == &dtable[T_ELIF]);
345 if (pfile->state.in_expression)
346 pfile->state.skipping = false;
348 if (no_expand)
349 pfile->state.prevent_expansion++;
350 _cpp_scan_out_logical_line (pfile, NULL, false);
351 if (no_expand)
352 pfile->state.prevent_expansion--;
354 pfile->state.skipping = was_skipping;
355 _cpp_overlay_buffer (pfile, pfile->out.base,
356 pfile->out.cur - pfile->out.base);
359 /* Stop ISO C from expanding anything. */
360 pfile->state.prevent_expansion++;
363 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
364 the '#' was indented. */
365 static void
366 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
368 /* Issue -pedantic or deprecated warnings for extensions. We let
369 -pedantic take precedence if both are applicable. */
370 if (! pfile->state.skipping)
372 if (dir->origin == EXTENSION
373 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
374 && CPP_PEDANTIC (pfile))
375 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
376 else if (((dir->flags & DEPRECATED) != 0
377 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
378 && CPP_OPTION (pfile, cpp_warn_deprecated))
379 cpp_warning (pfile, CPP_W_DEPRECATED,
380 "#%s is a deprecated GCC extension", dir->name);
383 /* Traditionally, a directive is ignored unless its # is in
384 column 1. Therefore in code intended to work with K+R
385 compilers, directives added by C89 must have their #
386 indented, and directives present in traditional C must not.
387 This is true even of directives in skipped conditional
388 blocks. #elif cannot be used at all. */
389 if (CPP_WTRADITIONAL (pfile))
391 if (dir == &dtable[T_ELIF])
392 cpp_warning (pfile, CPP_W_TRADITIONAL,
393 "suggest not using #elif in traditional C");
394 else if (indented && dir->origin == KANDR)
395 cpp_warning (pfile, CPP_W_TRADITIONAL,
396 "traditional C ignores #%s with the # indented",
397 dir->name);
398 else if (!indented && dir->origin != KANDR)
399 cpp_warning (pfile, CPP_W_TRADITIONAL,
400 "suggest hiding #%s from traditional C with an indented #",
401 dir->name);
405 /* Check if we have a known directive. INDENTED is nonzero if the
406 '#' of the directive was indented. This function is in this file
407 to save unnecessarily exporting dtable etc. to lex.c. Returns
408 nonzero if the line of tokens has been handled, zero if we should
409 continue processing the line. */
411 _cpp_handle_directive (cpp_reader *pfile, int indented)
413 const directive *dir = 0;
414 const cpp_token *dname;
415 bool was_parsing_args = pfile->state.parsing_args;
416 bool was_discarding_output = pfile->state.discarding_output;
417 int skip = 1;
419 if (was_discarding_output)
420 pfile->state.prevent_expansion = 0;
422 if (was_parsing_args)
424 if (CPP_OPTION (pfile, cpp_pedantic))
425 cpp_error (pfile, CPP_DL_PEDWARN,
426 "embedding a directive within macro arguments is not portable");
427 pfile->state.parsing_args = 0;
428 pfile->state.prevent_expansion = 0;
430 start_directive (pfile);
431 dname = _cpp_lex_token (pfile);
433 if (dname->type == CPP_NAME)
435 if (dname->val.node.node->is_directive)
436 dir = &dtable[dname->val.node.node->directive_index];
438 /* We do not recognize the # followed by a number extension in
439 assembler code. */
440 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
442 dir = &linemarker_dir;
443 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
444 && ! pfile->state.skipping)
445 cpp_error (pfile, CPP_DL_PEDWARN,
446 "style of line directive is a GCC extension");
449 if (dir)
451 /* If we have a directive that is not an opening conditional,
452 invalidate any control macro. */
453 if (! (dir->flags & IF_COND))
454 pfile->mi_valid = false;
456 /* Kluge alert. In order to be sure that code like this
458 #define HASH #
459 HASH define foo bar
461 does not cause '#define foo bar' to get executed when
462 compiled with -save-temps, we recognize directives in
463 -fpreprocessed mode only if the # is in column 1. macro.c
464 puts a space in front of any '#' at the start of a macro.
466 We exclude the -fdirectives-only case because macro expansion
467 has not been performed yet, and block comments can cause spaces
468 to precede the directive. */
469 if (CPP_OPTION (pfile, preprocessed)
470 && !CPP_OPTION (pfile, directives_only)
471 && (indented || !(dir->flags & IN_I)))
473 skip = 0;
474 dir = 0;
476 else
478 /* In failed conditional groups, all non-conditional
479 directives are ignored. Before doing that, whether
480 skipping or not, we should lex angle-bracketed headers
481 correctly, and maybe output some diagnostics. */
482 pfile->state.angled_headers = dir->flags & INCL;
483 pfile->state.directive_wants_padding = dir->flags & INCL;
484 if (! CPP_OPTION (pfile, preprocessed))
485 directive_diagnostics (pfile, dir, indented);
486 if (pfile->state.skipping && !(dir->flags & COND))
487 dir = 0;
490 else if (dname->type == CPP_EOF)
491 ; /* CPP_EOF is the "null directive". */
492 else
494 /* An unknown directive. Don't complain about it in assembly
495 source: we don't know where the comments are, and # may
496 introduce assembler pseudo-ops. Don't complain about invalid
497 directives in skipped conditional groups (6.10 p4). */
498 if (CPP_OPTION (pfile, lang) == CLK_ASM)
499 skip = 0;
500 else if (!pfile->state.skipping)
501 cpp_error (pfile, CPP_DL_ERROR, "invalid preprocessing directive #%s",
502 cpp_token_as_text (pfile, dname));
505 pfile->directive = dir;
506 if (CPP_OPTION (pfile, traditional))
507 prepare_directive_trad (pfile);
509 if (dir)
510 pfile->directive->handler (pfile);
511 else if (skip == 0)
512 _cpp_backup_tokens (pfile, 1);
514 end_directive (pfile, skip);
515 if (was_parsing_args && !pfile->state.in_deferred_pragma)
517 /* Restore state when within macro args. */
518 pfile->state.parsing_args = 2;
519 pfile->state.prevent_expansion = 1;
521 if (was_discarding_output)
522 pfile->state.prevent_expansion = 1;
523 return skip;
526 /* Directive handler wrapper used by the command line option
527 processor. BUF is \n terminated. */
528 static void
529 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
531 cpp_push_buffer (pfile, (const uchar *) buf, count,
532 /* from_stage3 */ true);
533 start_directive (pfile);
535 /* This is a short-term fix to prevent a leading '#' being
536 interpreted as a directive. */
537 _cpp_clean_line (pfile);
539 pfile->directive = &dtable[dir_no];
540 if (CPP_OPTION (pfile, traditional))
541 prepare_directive_trad (pfile);
542 pfile->directive->handler (pfile);
543 end_directive (pfile, 1);
544 _cpp_pop_buffer (pfile);
547 /* Checks for validity the macro name in #define, #undef, #ifdef and
548 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
549 processing a #define or #undefine directive, and false
550 otherwise. */
551 static cpp_hashnode *
552 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
554 const cpp_token *token = _cpp_lex_token (pfile);
556 /* The token immediately after #define must be an identifier. That
557 identifier may not be "defined", per C99 6.10.8p4.
558 In C++, it may not be any of the "named operators" either,
559 per C++98 [lex.digraph], [lex.key].
560 Finally, the identifier may not have been poisoned. (In that case
561 the lexer has issued the error message for us.) */
563 if (token->type == CPP_NAME)
565 cpp_hashnode *node = token->val.node.node;
567 if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
568 cpp_error (pfile, CPP_DL_ERROR,
569 "\"defined\" cannot be used as a macro name");
570 else if (is_def_or_undef
571 && (node == pfile->spec_nodes.n__has_include__
572 || node == pfile->spec_nodes.n__has_include_next__))
573 cpp_error (pfile, CPP_DL_ERROR,
574 "\"__has_include__\" cannot be used as a macro name");
575 else if (! (node->flags & NODE_POISONED))
576 return node;
578 else if (token->flags & NAMED_OP)
579 cpp_error (pfile, CPP_DL_ERROR,
580 "\"%s\" cannot be used as a macro name as it is an operator in C++",
581 NODE_NAME (token->val.node.node));
582 else if (token->type == CPP_EOF)
583 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
584 pfile->directive->name);
585 else
586 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
588 return NULL;
591 /* Process a #define directive. Most work is done in macro.c. */
592 static void
593 do_define (cpp_reader *pfile)
595 cpp_hashnode *node = lex_macro_node (pfile, true);
597 if (node)
599 /* If we have been requested to expand comments into macros,
600 then re-enable saving of comments. */
601 pfile->state.save_comments =
602 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
604 if (pfile->cb.before_define)
605 pfile->cb.before_define (pfile);
607 if (_cpp_create_definition (pfile, node))
608 if (pfile->cb.define)
609 pfile->cb.define (pfile, pfile->directive_line, node);
611 node->flags &= ~NODE_USED;
615 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
616 static void
617 do_undef (cpp_reader *pfile)
619 cpp_hashnode *node = lex_macro_node (pfile, true);
621 if (node)
623 if (pfile->cb.before_define)
624 pfile->cb.before_define (pfile);
626 if (pfile->cb.undef)
627 pfile->cb.undef (pfile, pfile->directive_line, node);
629 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
630 identifier is not currently defined as a macro name. */
631 if (node->type == NT_MACRO)
633 if (node->flags & NODE_WARN)
634 cpp_error (pfile, CPP_DL_WARNING,
635 "undefining \"%s\"", NODE_NAME (node));
636 else if ((node->flags & NODE_BUILTIN)
637 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
638 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
639 pfile->directive_line, 0,
640 "undefining \"%s\"", NODE_NAME (node));
642 if (CPP_OPTION (pfile, warn_unused_macros))
643 _cpp_warn_if_unused_macro (pfile, node, NULL);
645 _cpp_free_definition (node);
649 check_eol (pfile, false);
652 /* Undefine a single macro/assertion/whatever. */
654 static int
655 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
656 void *data_p ATTRIBUTE_UNUSED)
658 /* Body of _cpp_free_definition inlined here for speed.
659 Macros and assertions no longer have anything to free. */
660 h->type = NT_VOID;
661 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
662 return 1;
665 /* Undefine all macros and assertions. */
667 void
668 cpp_undef_all (cpp_reader *pfile)
670 cpp_forall_identifiers (pfile, undefine_macros, NULL);
674 /* Helper routine used by parse_include. Reinterpret the current line
675 as an h-char-sequence (< ... >); we are looking at the first token
676 after the <. Returns a malloced filename. */
677 static char *
678 glue_header_name (cpp_reader *pfile)
680 const cpp_token *token;
681 char *buffer;
682 size_t len, total_len = 0, capacity = 1024;
684 /* To avoid lexed tokens overwriting our glued name, we can only
685 allocate from the string pool once we've lexed everything. */
686 buffer = XNEWVEC (char, capacity);
687 for (;;)
689 token = get_token_no_padding (pfile);
691 if (token->type == CPP_GREATER)
692 break;
693 if (token->type == CPP_EOF)
695 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
696 break;
699 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
700 if (total_len + len > capacity)
702 capacity = (capacity + len) * 2;
703 buffer = XRESIZEVEC (char, buffer, capacity);
706 if (token->flags & PREV_WHITE)
707 buffer[total_len++] = ' ';
709 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
710 true)
711 - (uchar *) buffer);
714 buffer[total_len] = '\0';
715 return buffer;
718 /* Returns the file name of #include, #include_next, #import and
719 #pragma dependency. The string is malloced and the caller should
720 free it. Returns NULL on error. LOCATION is the source location
721 of the file name. */
723 static const char *
724 parse_include (cpp_reader *pfile, int *pangle_brackets,
725 const cpp_token ***buf, source_location *location)
727 char *fname;
728 const cpp_token *header;
730 /* Allow macro expansion. */
731 header = get_token_no_padding (pfile);
732 *location = header->src_loc;
733 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
734 || header->type == CPP_HEADER_NAME)
736 fname = XNEWVEC (char, header->val.str.len - 1);
737 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
738 fname[header->val.str.len - 2] = '\0';
739 *pangle_brackets = header->type == CPP_HEADER_NAME;
741 else if (header->type == CPP_LESS)
743 fname = glue_header_name (pfile);
744 *pangle_brackets = 1;
746 else
748 const unsigned char *dir;
750 if (pfile->directive == &dtable[T_PRAGMA])
751 dir = UC"pragma dependency";
752 else
753 dir = pfile->directive->name;
754 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
755 dir);
757 return NULL;
760 if (pfile->directive == &dtable[T_PRAGMA])
762 /* This pragma allows extra tokens after the file name. */
764 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
765 check_eol (pfile, true);
766 else
768 /* If we are not discarding comments, then gather them while
769 doing the eol check. */
770 *buf = check_eol_return_comments (pfile);
773 return fname;
776 /* Handle #include, #include_next and #import. */
777 static void
778 do_include_common (cpp_reader *pfile, enum include_type type)
780 const char *fname;
781 int angle_brackets;
782 const cpp_token **buf = NULL;
783 source_location location;
785 /* Re-enable saving of comments if requested, so that the include
786 callback can dump comments which follow #include. */
787 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
789 fname = parse_include (pfile, &angle_brackets, &buf, &location);
790 if (!fname)
792 if (buf)
793 XDELETEVEC (buf);
794 return;
797 if (!*fname)
799 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
800 "empty filename in #%s",
801 pfile->directive->name);
802 XDELETEVEC (fname);
803 if (buf)
804 XDELETEVEC (buf);
805 return;
808 /* Prevent #include recursion. */
809 if (pfile->line_table->depth >= CPP_STACK_MAX)
810 cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
811 else
813 /* Get out of macro context, if we are. */
814 skip_rest_of_line (pfile);
816 if (pfile->cb.include)
817 pfile->cb.include (pfile, pfile->directive_line,
818 pfile->directive->name, fname, angle_brackets,
819 buf);
821 _cpp_stack_include (pfile, fname, angle_brackets, type);
824 XDELETEVEC (fname);
825 if (buf)
826 XDELETEVEC (buf);
829 static void
830 do_include (cpp_reader *pfile)
832 do_include_common (pfile, IT_INCLUDE);
835 static void
836 do_import (cpp_reader *pfile)
838 do_include_common (pfile, IT_IMPORT);
841 static void
842 do_include_next (cpp_reader *pfile)
844 enum include_type type = IT_INCLUDE_NEXT;
846 /* If this is the primary source file, warn and use the normal
847 search logic. */
848 if (cpp_in_primary_file (pfile))
850 cpp_error (pfile, CPP_DL_WARNING,
851 "#include_next in primary source file");
852 type = IT_INCLUDE;
854 do_include_common (pfile, type);
857 /* Subroutine of do_linemarker. Read possible flags after file name.
858 LAST is the last flag seen; 0 if this is the first flag. Return the
859 flag if it is valid, 0 at the end of the directive. Otherwise
860 complain. */
861 static unsigned int
862 read_flag (cpp_reader *pfile, unsigned int last)
864 const cpp_token *token = _cpp_lex_token (pfile);
866 if (token->type == CPP_NUMBER && token->val.str.len == 1)
868 unsigned int flag = token->val.str.text[0] - '0';
870 if (flag > last && flag <= 4
871 && (flag != 4 || last == 3)
872 && (flag != 2 || last == 0))
873 return flag;
876 if (token->type != CPP_EOF)
877 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
878 cpp_token_as_text (pfile, token));
879 return 0;
882 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
883 of length LEN, to binary; store it in NUMP, and return false if the
884 number was well-formed, true if not. WRAPPED is set to true if the
885 number did not fit into 'unsigned long'. */
886 static bool
887 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
889 linenum_type reg = 0;
890 linenum_type reg_prev = 0;
892 uchar c;
893 *wrapped = false;
894 while (len--)
896 c = *str++;
897 if (!ISDIGIT (c))
898 return true;
899 reg *= 10;
900 reg += c - '0';
901 if (reg < reg_prev)
902 *wrapped = true;
903 reg_prev = reg;
905 *nump = reg;
906 return false;
909 /* Interpret #line command.
910 Note that the filename string (if any) is a true string constant
911 (escapes are interpreted), unlike in #line. */
912 static void
913 do_line (cpp_reader *pfile)
915 struct line_maps *line_table = pfile->line_table;
916 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
918 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
919 sysp right now. */
921 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
922 const cpp_token *token;
923 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
924 linenum_type new_lineno;
926 /* C99 raised the minimum limit on #line numbers. */
927 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
928 bool wrapped;
930 /* #line commands expand macros. */
931 token = cpp_get_token (pfile);
932 if (token->type != CPP_NUMBER
933 || strtolinenum (token->val.str.text, token->val.str.len,
934 &new_lineno, &wrapped))
936 if (token->type == CPP_EOF)
937 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
938 else
939 cpp_error (pfile, CPP_DL_ERROR,
940 "\"%s\" after #line is not a positive integer",
941 cpp_token_as_text (pfile, token));
942 return;
945 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
946 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
947 else if (wrapped)
948 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
950 token = cpp_get_token (pfile);
951 if (token->type == CPP_STRING)
953 cpp_string s = { 0, 0 };
954 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
955 &s, CPP_STRING))
956 new_file = (const char *)s.text;
957 check_eol (pfile, true);
959 else if (token->type != CPP_EOF)
961 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
962 cpp_token_as_text (pfile, token));
963 return;
966 skip_rest_of_line (pfile);
967 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
968 map_sysp);
969 line_table->seen_line_directive = true;
972 /* Interpret the # 44 "file" [flags] notation, which has slightly
973 different syntax and semantics from #line: Flags are allowed,
974 and we never complain about the line number being too big. */
975 static void
976 do_linemarker (cpp_reader *pfile)
978 struct line_maps *line_table = pfile->line_table;
979 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
980 const cpp_token *token;
981 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
982 linenum_type new_lineno;
983 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
984 enum lc_reason reason = LC_RENAME_VERBATIM;
985 int flag;
986 bool wrapped;
988 /* Back up so we can get the number again. Putting this in
989 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
990 some circumstances, which can segfault. */
991 _cpp_backup_tokens (pfile, 1);
993 /* #line commands expand macros. */
994 token = cpp_get_token (pfile);
995 if (token->type != CPP_NUMBER
996 || strtolinenum (token->val.str.text, token->val.str.len,
997 &new_lineno, &wrapped))
999 /* Unlike #line, there does not seem to be a way to get an EOF
1000 here. So, it should be safe to always spell the token. */
1001 cpp_error (pfile, CPP_DL_ERROR,
1002 "\"%s\" after # is not a positive integer",
1003 cpp_token_as_text (pfile, token));
1004 return;
1007 token = cpp_get_token (pfile);
1008 if (token->type == CPP_STRING)
1010 cpp_string s = { 0, 0 };
1011 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1012 1, &s, CPP_STRING))
1013 new_file = (const char *)s.text;
1015 new_sysp = 0;
1016 flag = read_flag (pfile, 0);
1017 if (flag == 1)
1019 reason = LC_ENTER;
1020 /* Fake an include for cpp_included (). */
1021 _cpp_fake_include (pfile, new_file);
1022 flag = read_flag (pfile, flag);
1024 else if (flag == 2)
1026 reason = LC_LEAVE;
1027 flag = read_flag (pfile, flag);
1029 if (flag == 3)
1031 new_sysp = 1;
1032 flag = read_flag (pfile, flag);
1033 if (flag == 4)
1034 new_sysp = 2;
1036 pfile->buffer->sysp = new_sysp;
1038 check_eol (pfile, false);
1040 else if (token->type != CPP_EOF)
1042 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1043 cpp_token_as_text (pfile, token));
1044 return;
1047 skip_rest_of_line (pfile);
1049 /* Compensate for the increment in linemap_add that occurs in
1050 _cpp_do_file_change. We're currently at the start of the line
1051 *following* the #line directive. A separate source_location for this
1052 location makes no sense (until we do the LC_LEAVE), and
1053 complicates LAST_SOURCE_LINE_LOCATION. */
1054 pfile->line_table->highest_location--;
1056 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1057 line_table->seen_line_directive = true;
1060 /* Arrange the file_change callback. pfile->line has changed to
1061 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
1062 header, 2 for a system header that needs to be extern "C" protected,
1063 and zero otherwise. */
1064 void
1065 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1066 const char *to_file, linenum_type file_line,
1067 unsigned int sysp)
1069 linemap_assert (reason != LC_ENTER_MACRO);
1070 const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1071 to_file, file_line);
1072 const line_map_ordinary *ord_map = NULL;
1073 if (map != NULL)
1075 ord_map = linemap_check_ordinary (map);
1076 linemap_line_start (pfile->line_table,
1077 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1078 127);
1081 if (pfile->cb.file_change)
1082 pfile->cb.file_change (pfile, ord_map);
1085 /* Report a warning or error detected by the program we are
1086 processing. Use the directive's tokens in the error message. */
1087 static void
1088 do_diagnostic (cpp_reader *pfile, int code, int reason, int print_dir)
1090 const unsigned char *dir_name;
1091 unsigned char *line;
1092 source_location src_loc = pfile->cur_token[-1].src_loc;
1094 if (print_dir)
1095 dir_name = pfile->directive->name;
1096 else
1097 dir_name = NULL;
1098 pfile->state.prevent_expansion++;
1099 line = cpp_output_line_to_string (pfile, dir_name);
1100 pfile->state.prevent_expansion--;
1102 if (code == CPP_DL_WARNING_SYSHDR && reason)
1103 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1104 else if (code == CPP_DL_WARNING && reason)
1105 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1106 else
1107 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1108 free (line);
1111 static void
1112 do_error (cpp_reader *pfile)
1114 do_diagnostic (pfile, CPP_DL_ERROR, 0, 1);
1117 static void
1118 do_warning (cpp_reader *pfile)
1120 /* We want #warning diagnostics to be emitted in system headers too. */
1121 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1124 /* Report program identification. */
1125 static void
1126 do_ident (cpp_reader *pfile)
1128 const cpp_token *str = cpp_get_token (pfile);
1130 if (str->type != CPP_STRING)
1131 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1132 pfile->directive->name);
1133 else if (pfile->cb.ident)
1134 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1136 check_eol (pfile, false);
1139 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1140 matching entry, or NULL if none is found. The returned entry could
1141 be the start of a namespace chain, or a pragma. */
1142 static struct pragma_entry *
1143 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1145 while (chain && chain->pragma != pragma)
1146 chain = chain->next;
1148 return chain;
1151 /* Create and insert a blank pragma entry at the beginning of a
1152 singly-linked CHAIN. */
1153 static struct pragma_entry *
1154 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1156 struct pragma_entry *new_entry;
1158 new_entry = (struct pragma_entry *)
1159 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1161 memset (new_entry, 0, sizeof (struct pragma_entry));
1162 new_entry->next = *chain;
1164 *chain = new_entry;
1165 return new_entry;
1168 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1169 goes in the global namespace. */
1170 static struct pragma_entry *
1171 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1172 bool allow_name_expansion)
1174 struct pragma_entry **chain = &pfile->pragmas;
1175 struct pragma_entry *entry;
1176 const cpp_hashnode *node;
1178 if (space)
1180 node = cpp_lookup (pfile, UC space, strlen (space));
1181 entry = lookup_pragma_entry (*chain, node);
1182 if (!entry)
1184 entry = new_pragma_entry (pfile, chain);
1185 entry->pragma = node;
1186 entry->is_nspace = true;
1187 entry->allow_expansion = allow_name_expansion;
1189 else if (!entry->is_nspace)
1190 goto clash;
1191 else if (entry->allow_expansion != allow_name_expansion)
1193 cpp_error (pfile, CPP_DL_ICE,
1194 "registering pragmas in namespace \"%s\" with mismatched "
1195 "name expansion", space);
1196 return NULL;
1198 chain = &entry->u.space;
1200 else if (allow_name_expansion)
1202 cpp_error (pfile, CPP_DL_ICE,
1203 "registering pragma \"%s\" with name expansion "
1204 "and no namespace", name);
1205 return NULL;
1208 /* Check for duplicates. */
1209 node = cpp_lookup (pfile, UC name, strlen (name));
1210 entry = lookup_pragma_entry (*chain, node);
1211 if (entry == NULL)
1213 entry = new_pragma_entry (pfile, chain);
1214 entry->pragma = node;
1215 return entry;
1218 if (entry->is_nspace)
1219 clash:
1220 cpp_error (pfile, CPP_DL_ICE,
1221 "registering \"%s\" as both a pragma and a pragma namespace",
1222 NODE_NAME (node));
1223 else if (space)
1224 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1225 space, name);
1226 else
1227 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1229 return NULL;
1232 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1233 static void
1234 register_pragma_internal (cpp_reader *pfile, const char *space,
1235 const char *name, pragma_cb handler)
1237 struct pragma_entry *entry;
1239 entry = register_pragma_1 (pfile, space, name, false);
1240 entry->is_internal = true;
1241 entry->u.handler = handler;
1244 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1245 goes in the global namespace. HANDLER is the handler it will call,
1246 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1247 expansion while parsing pragma NAME. This function is exported
1248 from libcpp. */
1249 void
1250 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1251 pragma_cb handler, bool allow_expansion)
1253 struct pragma_entry *entry;
1255 if (!handler)
1257 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1258 return;
1261 entry = register_pragma_1 (pfile, space, name, false);
1262 if (entry)
1264 entry->allow_expansion = allow_expansion;
1265 entry->u.handler = handler;
1269 /* Similarly, but create mark the pragma for deferred processing.
1270 When found, a CPP_PRAGMA token will be insertted into the stream
1271 with IDENT in the token->u.pragma slot. */
1272 void
1273 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1274 const char *name, unsigned int ident,
1275 bool allow_expansion, bool allow_name_expansion)
1277 struct pragma_entry *entry;
1279 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1280 if (entry)
1282 entry->is_deferred = true;
1283 entry->allow_expansion = allow_expansion;
1284 entry->u.ident = ident;
1288 /* Register the pragmas the preprocessor itself handles. */
1289 void
1290 _cpp_init_internal_pragmas (cpp_reader *pfile)
1292 /* Pragmas in the global namespace. */
1293 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1294 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1295 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1297 /* New GCC-specific pragmas should be put in the GCC namespace. */
1298 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1299 register_pragma_internal (pfile, "GCC", "system_header",
1300 do_pragma_system_header);
1301 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1302 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1303 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1306 /* Return the number of registered pragmas in PE. */
1308 static int
1309 count_registered_pragmas (struct pragma_entry *pe)
1311 int ct = 0;
1312 for (; pe != NULL; pe = pe->next)
1314 if (pe->is_nspace)
1315 ct += count_registered_pragmas (pe->u.space);
1316 ct++;
1318 return ct;
1321 /* Save into SD the names of the registered pragmas referenced by PE,
1322 and return a pointer to the next free space in SD. */
1324 static char **
1325 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1327 for (; pe != NULL; pe = pe->next)
1329 if (pe->is_nspace)
1330 sd = save_registered_pragmas (pe->u.space, sd);
1331 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1332 HT_LEN (&pe->pragma->ident),
1333 HT_LEN (&pe->pragma->ident) + 1);
1335 return sd;
1338 /* Return a newly-allocated array which saves the names of the
1339 registered pragmas. */
1341 char **
1342 _cpp_save_pragma_names (cpp_reader *pfile)
1344 int ct = count_registered_pragmas (pfile->pragmas);
1345 char **result = XNEWVEC (char *, ct);
1346 (void) save_registered_pragmas (pfile->pragmas, result);
1347 return result;
1350 /* Restore from SD the names of the registered pragmas referenced by PE,
1351 and return a pointer to the next unused name in SD. */
1353 static char **
1354 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1355 char **sd)
1357 for (; pe != NULL; pe = pe->next)
1359 if (pe->is_nspace)
1360 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1361 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1362 free (*sd);
1363 sd++;
1365 return sd;
1368 /* Restore the names of the registered pragmas from SAVED. */
1370 void
1371 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1373 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1374 free (saved);
1377 /* Pragmata handling. We handle some, and pass the rest on to the
1378 front end. C99 defines three pragmas and says that no macro
1379 expansion is to be performed on them; whether or not macro
1380 expansion happens for other pragmas is implementation defined.
1381 This implementation allows for a mix of both, since GCC did not
1382 traditionally macro expand its (few) pragmas, whereas OpenMP
1383 specifies that macro expansion should happen. */
1384 static void
1385 do_pragma (cpp_reader *pfile)
1387 const struct pragma_entry *p = NULL;
1388 const cpp_token *token, *pragma_token;
1389 source_location pragma_token_virt_loc = 0;
1390 cpp_token ns_token;
1391 unsigned int count = 1;
1393 pfile->state.prevent_expansion++;
1395 pragma_token = token = cpp_get_token_with_location (pfile,
1396 &pragma_token_virt_loc);
1397 ns_token = *token;
1398 if (token->type == CPP_NAME)
1400 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1401 if (p && p->is_nspace)
1403 bool allow_name_expansion = p->allow_expansion;
1404 if (allow_name_expansion)
1405 pfile->state.prevent_expansion--;
1407 token = cpp_get_token (pfile);
1408 if (token->type == CPP_NAME)
1409 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1410 else
1411 p = NULL;
1412 if (allow_name_expansion)
1413 pfile->state.prevent_expansion++;
1414 count = 2;
1418 if (p)
1420 if (p->is_deferred)
1422 pfile->directive_result.src_loc = pragma_token_virt_loc;
1423 pfile->directive_result.type = CPP_PRAGMA;
1424 pfile->directive_result.flags = pragma_token->flags;
1425 pfile->directive_result.val.pragma = p->u.ident;
1426 pfile->state.in_deferred_pragma = true;
1427 pfile->state.pragma_allow_expansion = p->allow_expansion;
1428 if (!p->allow_expansion)
1429 pfile->state.prevent_expansion++;
1431 else
1433 /* Since the handler below doesn't get the line number, that
1434 it might need for diagnostics, make sure it has the right
1435 numbers in place. */
1436 if (pfile->cb.line_change)
1437 (*pfile->cb.line_change) (pfile, pragma_token, false);
1438 if (p->allow_expansion)
1439 pfile->state.prevent_expansion--;
1440 (*p->u.handler) (pfile);
1441 if (p->allow_expansion)
1442 pfile->state.prevent_expansion++;
1445 else if (pfile->cb.def_pragma)
1447 if (count == 1 || pfile->context->prev == NULL)
1448 _cpp_backup_tokens (pfile, count);
1449 else
1451 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1452 won't allow backing 2 tokens. */
1453 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1454 reads both tokens, we could perhaps free it, but if it doesn't,
1455 we don't know the exact lifespan. */
1456 cpp_token *toks = XNEWVEC (cpp_token, 2);
1457 toks[0] = ns_token;
1458 toks[0].flags |= NO_EXPAND;
1459 toks[1] = *token;
1460 toks[1].flags |= NO_EXPAND;
1461 _cpp_push_token_context (pfile, NULL, toks, 2);
1463 pfile->cb.def_pragma (pfile, pfile->directive_line);
1466 pfile->state.prevent_expansion--;
1469 /* Handle #pragma once. */
1470 static void
1471 do_pragma_once (cpp_reader *pfile)
1473 if (cpp_in_primary_file (pfile))
1474 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1476 check_eol (pfile, false);
1477 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1480 /* Handle #pragma push_macro(STRING). */
1481 static void
1482 do_pragma_push_macro (cpp_reader *pfile)
1484 cpp_hashnode *node;
1485 size_t defnlen;
1486 const uchar *defn = NULL;
1487 char *macroname, *dest;
1488 const char *limit, *src;
1489 const cpp_token *txt;
1490 struct def_pragma_macro *c;
1492 txt = get__Pragma_string (pfile);
1493 if (!txt)
1495 source_location src_loc = pfile->cur_token[-1].src_loc;
1496 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1497 "invalid #pragma push_macro directive");
1498 check_eol (pfile, false);
1499 skip_rest_of_line (pfile);
1500 return;
1502 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1503 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1504 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1505 while (src < limit)
1507 /* We know there is a character following the backslash. */
1508 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1509 src++;
1510 *dest++ = *src++;
1512 *dest = 0;
1513 check_eol (pfile, false);
1514 skip_rest_of_line (pfile);
1515 c = XNEW (struct def_pragma_macro);
1516 memset (c, 0, sizeof (struct def_pragma_macro));
1517 c->name = XNEWVAR (char, strlen (macroname) + 1);
1518 strcpy (c->name, macroname);
1519 c->next = pfile->pushed_macros;
1520 node = _cpp_lex_identifier (pfile, c->name);
1521 if (node->type == NT_VOID)
1522 c->is_undef = 1;
1523 else
1525 defn = cpp_macro_definition (pfile, node);
1526 defnlen = ustrlen (defn);
1527 c->definition = XNEWVEC (uchar, defnlen + 2);
1528 c->definition[defnlen] = '\n';
1529 c->definition[defnlen + 1] = 0;
1530 c->line = node->value.macro->line;
1531 c->syshdr = node->value.macro->syshdr;
1532 c->used = node->value.macro->used;
1533 memcpy (c->definition, defn, defnlen);
1536 pfile->pushed_macros = c;
1539 /* Handle #pragma pop_macro(STRING). */
1540 static void
1541 do_pragma_pop_macro (cpp_reader *pfile)
1543 char *macroname, *dest;
1544 const char *limit, *src;
1545 const cpp_token *txt;
1546 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1547 txt = get__Pragma_string (pfile);
1548 if (!txt)
1550 source_location src_loc = pfile->cur_token[-1].src_loc;
1551 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1552 "invalid #pragma pop_macro directive");
1553 check_eol (pfile, false);
1554 skip_rest_of_line (pfile);
1555 return;
1557 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1558 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1559 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1560 while (src < limit)
1562 /* We know there is a character following the backslash. */
1563 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1564 src++;
1565 *dest++ = *src++;
1567 *dest = 0;
1568 check_eol (pfile, false);
1569 skip_rest_of_line (pfile);
1571 while (c != NULL)
1573 if (!strcmp (c->name, macroname))
1575 if (!l)
1576 pfile->pushed_macros = c->next;
1577 else
1578 l->next = c->next;
1579 cpp_pop_definition (pfile, c);
1580 free (c->definition);
1581 free (c->name);
1582 free (c);
1583 break;
1585 l = c;
1586 c = c->next;
1590 /* Handle #pragma GCC poison, to poison one or more identifiers so
1591 that the lexer produces a hard error for each subsequent usage. */
1592 static void
1593 do_pragma_poison (cpp_reader *pfile)
1595 const cpp_token *tok;
1596 cpp_hashnode *hp;
1598 pfile->state.poisoned_ok = 1;
1599 for (;;)
1601 tok = _cpp_lex_token (pfile);
1602 if (tok->type == CPP_EOF)
1603 break;
1604 if (tok->type != CPP_NAME)
1606 cpp_error (pfile, CPP_DL_ERROR,
1607 "invalid #pragma GCC poison directive");
1608 break;
1611 hp = tok->val.node.node;
1612 if (hp->flags & NODE_POISONED)
1613 continue;
1615 if (hp->type == NT_MACRO)
1616 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1617 NODE_NAME (hp));
1618 _cpp_free_definition (hp);
1619 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1621 pfile->state.poisoned_ok = 0;
1624 /* Mark the current header as a system header. This will suppress
1625 some categories of warnings (notably those from -pedantic). It is
1626 intended for use in system libraries that cannot be implemented in
1627 conforming C, but cannot be certain that their headers appear in a
1628 system include directory. To prevent abuse, it is rejected in the
1629 primary source file. */
1630 static void
1631 do_pragma_system_header (cpp_reader *pfile)
1633 if (cpp_in_primary_file (pfile))
1634 cpp_error (pfile, CPP_DL_WARNING,
1635 "#pragma system_header ignored outside include file");
1636 else
1638 check_eol (pfile, false);
1639 skip_rest_of_line (pfile);
1640 cpp_make_system_header (pfile, 1, 0);
1644 /* Check the modified date of the current include file against a specified
1645 file. Issue a diagnostic, if the specified file is newer. We use this to
1646 determine if a fixed header should be refixed. */
1647 static void
1648 do_pragma_dependency (cpp_reader *pfile)
1650 const char *fname;
1651 int angle_brackets, ordering;
1652 source_location location;
1654 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1655 if (!fname)
1656 return;
1658 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1659 if (ordering < 0)
1660 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1661 else if (ordering > 0)
1663 cpp_error (pfile, CPP_DL_WARNING,
1664 "current file is older than %s", fname);
1665 if (cpp_get_token (pfile)->type != CPP_EOF)
1667 _cpp_backup_tokens (pfile, 1);
1668 do_diagnostic (pfile, CPP_DL_WARNING, 0, 0);
1672 free ((void *) fname);
1675 /* Issue a diagnostic with the message taken from the pragma. If
1676 ERROR is true, the diagnostic is a warning, otherwise, it is an
1677 error. */
1678 static void
1679 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1681 const cpp_token *tok = _cpp_lex_token (pfile);
1682 cpp_string str;
1683 if (tok->type != CPP_STRING
1684 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1685 CPP_STRING)
1686 || str.len == 0)
1688 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1689 error ? "error" : "warning");
1690 return;
1692 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1693 "%s", str.text);
1694 free ((void *)str.text);
1697 /* Issue a warning diagnostic. */
1698 static void
1699 do_pragma_warning (cpp_reader *pfile)
1701 do_pragma_warning_or_error (pfile, false);
1704 /* Issue an error diagnostic. */
1705 static void
1706 do_pragma_error (cpp_reader *pfile)
1708 do_pragma_warning_or_error (pfile, true);
1711 /* Get a token but skip padding. */
1712 static const cpp_token *
1713 get_token_no_padding (cpp_reader *pfile)
1715 for (;;)
1717 const cpp_token *result = cpp_get_token (pfile);
1718 if (result->type != CPP_PADDING)
1719 return result;
1723 /* Check syntax is "(string-literal)". Returns the string on success,
1724 or NULL on failure. */
1725 static const cpp_token *
1726 get__Pragma_string (cpp_reader *pfile)
1728 const cpp_token *string;
1729 const cpp_token *paren;
1731 paren = get_token_no_padding (pfile);
1732 if (paren->type == CPP_EOF)
1733 _cpp_backup_tokens (pfile, 1);
1734 if (paren->type != CPP_OPEN_PAREN)
1735 return NULL;
1737 string = get_token_no_padding (pfile);
1738 if (string->type == CPP_EOF)
1739 _cpp_backup_tokens (pfile, 1);
1740 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1741 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1742 && string->type != CPP_UTF8STRING)
1743 return NULL;
1745 paren = get_token_no_padding (pfile);
1746 if (paren->type == CPP_EOF)
1747 _cpp_backup_tokens (pfile, 1);
1748 if (paren->type != CPP_CLOSE_PAREN)
1749 return NULL;
1751 return string;
1754 /* Destringize IN into a temporary buffer, by removing the first \ of
1755 \" and \\ sequences, and process the result as a #pragma directive. */
1756 static void
1757 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1758 source_location expansion_loc)
1760 const unsigned char *src, *limit;
1761 char *dest, *result;
1762 cpp_context *saved_context;
1763 cpp_token *saved_cur_token;
1764 tokenrun *saved_cur_run;
1765 cpp_token *toks;
1766 int count;
1767 const struct directive *save_directive;
1769 dest = result = (char *) alloca (in->len - 1);
1770 src = in->text + 1 + (in->text[0] == 'L');
1771 limit = in->text + in->len - 1;
1772 while (src < limit)
1774 /* We know there is a character following the backslash. */
1775 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1776 src++;
1777 *dest++ = *src++;
1779 *dest = '\n';
1781 /* Ugh; an awful kludge. We are really not set up to be lexing
1782 tokens when in the middle of a macro expansion. Use a new
1783 context to force cpp_get_token to lex, and so skip_rest_of_line
1784 doesn't go beyond the end of the text. Also, remember the
1785 current lexing position so we can return to it later.
1787 Something like line-at-a-time lexing should remove the need for
1788 this. */
1789 saved_context = pfile->context;
1790 saved_cur_token = pfile->cur_token;
1791 saved_cur_run = pfile->cur_run;
1793 pfile->context = XCNEW (cpp_context);
1795 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1796 until we've read all of the tokens that we want. */
1797 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1798 /* from_stage3 */ true);
1799 /* ??? Antique Disgusting Hack. What does this do? */
1800 if (pfile->buffer->prev)
1801 pfile->buffer->file = pfile->buffer->prev->file;
1803 start_directive (pfile);
1804 _cpp_clean_line (pfile);
1805 save_directive = pfile->directive;
1806 pfile->directive = &dtable[T_PRAGMA];
1807 do_pragma (pfile);
1808 end_directive (pfile, 1);
1809 pfile->directive = save_directive;
1811 /* We always insert at least one token, the directive result. It'll
1812 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1813 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1815 /* If we're not handling the pragma internally, read all of the tokens from
1816 the string buffer now, while the string buffer is still installed. */
1817 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1818 to me what the true lifespan of the tokens are. It would appear that
1819 the lifespan is the entire parse of the main input stream, in which case
1820 this may not be wrong. */
1821 if (pfile->directive_result.type == CPP_PRAGMA)
1823 int maxcount;
1825 count = 1;
1826 maxcount = 50;
1827 toks = XNEWVEC (cpp_token, maxcount);
1828 toks[0] = pfile->directive_result;
1832 if (count == maxcount)
1834 maxcount = maxcount * 3 / 2;
1835 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1837 toks[count] = *cpp_get_token (pfile);
1838 /* _Pragma is a builtin, so we're not within a macro-map, and so
1839 the token locations are set to bogus ordinary locations
1840 near to, but after that of the "_Pragma".
1841 Paper over this by setting them equal to the location of the
1842 _Pragma itself (PR preprocessor/69126). */
1843 toks[count].src_loc = expansion_loc;
1844 /* Macros have been already expanded by cpp_get_token
1845 if the pragma allowed expansion. */
1846 toks[count++].flags |= NO_EXPAND;
1848 while (toks[count-1].type != CPP_PRAGMA_EOL);
1850 else
1852 count = 1;
1853 toks = XNEW (cpp_token);
1854 toks[0] = pfile->directive_result;
1856 /* If we handled the entire pragma internally, make sure we get the
1857 line number correct for the next token. */
1858 if (pfile->cb.line_change)
1859 pfile->cb.line_change (pfile, pfile->cur_token, false);
1862 /* Finish inlining run_directive. */
1863 pfile->buffer->file = NULL;
1864 _cpp_pop_buffer (pfile);
1866 /* Reset the old macro state before ... */
1867 XDELETE (pfile->context);
1868 pfile->context = saved_context;
1869 pfile->cur_token = saved_cur_token;
1870 pfile->cur_run = saved_cur_run;
1872 /* ... inserting the new tokens we collected. */
1873 _cpp_push_token_context (pfile, NULL, toks, count);
1876 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1878 _cpp_do__Pragma (cpp_reader *pfile, source_location expansion_loc)
1880 const cpp_token *string = get__Pragma_string (pfile);
1881 pfile->directive_result.type = CPP_PADDING;
1883 if (string)
1885 destringize_and_run (pfile, &string->val.str, expansion_loc);
1886 return 1;
1888 cpp_error (pfile, CPP_DL_ERROR,
1889 "_Pragma takes a parenthesized string literal");
1890 return 0;
1893 /* Handle #ifdef. */
1894 static void
1895 do_ifdef (cpp_reader *pfile)
1897 int skip = 1;
1899 if (! pfile->state.skipping)
1901 cpp_hashnode *node = lex_macro_node (pfile, false);
1903 if (node)
1905 /* Do not treat conditional macros as being defined. This is due to
1906 the powerpc and spu ports using conditional macros for 'vector',
1907 'bool', and 'pixel' to act as conditional keywords. This messes
1908 up tests like #ifndef bool. */
1909 skip = (node->type != NT_MACRO
1910 || ((node->flags & NODE_CONDITIONAL) != 0));
1911 _cpp_mark_macro_used (node);
1912 if (!(node->flags & NODE_USED))
1914 node->flags |= NODE_USED;
1915 if (node->type == NT_MACRO)
1917 if ((node->flags & NODE_BUILTIN)
1918 && pfile->cb.user_builtin_macro)
1919 pfile->cb.user_builtin_macro (pfile, node);
1920 if (pfile->cb.used_define)
1921 pfile->cb.used_define (pfile, pfile->directive_line, node);
1923 else
1925 if (pfile->cb.used_undef)
1926 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1929 if (pfile->cb.used)
1930 pfile->cb.used (pfile, pfile->directive_line, node);
1931 check_eol (pfile, false);
1935 push_conditional (pfile, skip, T_IFDEF, 0);
1938 /* Handle #ifndef. */
1939 static void
1940 do_ifndef (cpp_reader *pfile)
1942 int skip = 1;
1943 cpp_hashnode *node = 0;
1945 if (! pfile->state.skipping)
1947 node = lex_macro_node (pfile, false);
1949 if (node)
1951 /* Do not treat conditional macros as being defined. This is due to
1952 the powerpc and spu ports using conditional macros for 'vector',
1953 'bool', and 'pixel' to act as conditional keywords. This messes
1954 up tests like #ifndef bool. */
1955 skip = (node->type == NT_MACRO
1956 && ((node->flags & NODE_CONDITIONAL) == 0));
1957 _cpp_mark_macro_used (node);
1958 if (!(node->flags & NODE_USED))
1960 node->flags |= NODE_USED;
1961 if (node->type == NT_MACRO)
1963 if ((node->flags & NODE_BUILTIN)
1964 && pfile->cb.user_builtin_macro)
1965 pfile->cb.user_builtin_macro (pfile, node);
1966 if (pfile->cb.used_define)
1967 pfile->cb.used_define (pfile, pfile->directive_line, node);
1969 else
1971 if (pfile->cb.used_undef)
1972 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1975 if (pfile->cb.used)
1976 pfile->cb.used (pfile, pfile->directive_line, node);
1977 check_eol (pfile, false);
1981 push_conditional (pfile, skip, T_IFNDEF, node);
1984 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1985 pfile->mi_ind_cmacro so we can handle multiple-include
1986 optimizations. If macro expansion occurs in the expression, we
1987 cannot treat it as a controlling conditional, since the expansion
1988 could change in the future. That is handled by cpp_get_token. */
1989 static void
1990 do_if (cpp_reader *pfile)
1992 int skip = 1;
1994 if (! pfile->state.skipping)
1995 skip = _cpp_parse_expr (pfile, true) == false;
1997 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2000 /* Flip skipping state if appropriate and continue without changing
2001 if_stack; this is so that the error message for missing #endif's
2002 etc. will point to the original #if. */
2003 static void
2004 do_else (cpp_reader *pfile)
2006 cpp_buffer *buffer = pfile->buffer;
2007 struct if_stack *ifs = buffer->if_stack;
2009 if (ifs == NULL)
2010 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2011 else
2013 if (ifs->type == T_ELSE)
2015 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2016 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2017 "the conditional began here");
2019 ifs->type = T_ELSE;
2021 /* Skip any future (erroneous) #elses or #elifs. */
2022 pfile->state.skipping = ifs->skip_elses;
2023 ifs->skip_elses = true;
2025 /* Invalidate any controlling macro. */
2026 ifs->mi_cmacro = 0;
2028 /* Only check EOL if was not originally skipping. */
2029 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2030 check_eol_endif_labels (pfile);
2034 /* Handle a #elif directive by not changing if_stack either. See the
2035 comment above do_else. */
2036 static void
2037 do_elif (cpp_reader *pfile)
2039 cpp_buffer *buffer = pfile->buffer;
2040 struct if_stack *ifs = buffer->if_stack;
2042 if (ifs == NULL)
2043 cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2044 else
2046 if (ifs->type == T_ELSE)
2048 cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2049 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2050 "the conditional began here");
2052 ifs->type = T_ELIF;
2054 /* See DR#412: "Only the first group whose control condition
2055 evaluates to true (nonzero) is processed; any following groups
2056 are skipped and their controlling directives are processed as
2057 if they were in a group that is skipped." */
2058 if (ifs->skip_elses)
2059 pfile->state.skipping = 1;
2060 else
2062 pfile->state.skipping = ! _cpp_parse_expr (pfile, false);
2063 ifs->skip_elses = ! pfile->state.skipping;
2066 /* Invalidate any controlling macro. */
2067 ifs->mi_cmacro = 0;
2071 /* #endif pops the if stack and resets pfile->state.skipping. */
2072 static void
2073 do_endif (cpp_reader *pfile)
2075 cpp_buffer *buffer = pfile->buffer;
2076 struct if_stack *ifs = buffer->if_stack;
2078 if (ifs == NULL)
2079 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2080 else
2082 /* Only check EOL if was not originally skipping. */
2083 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2084 check_eol_endif_labels (pfile);
2086 /* If potential control macro, we go back outside again. */
2087 if (ifs->next == 0 && ifs->mi_cmacro)
2089 pfile->mi_valid = true;
2090 pfile->mi_cmacro = ifs->mi_cmacro;
2093 buffer->if_stack = ifs->next;
2094 pfile->state.skipping = ifs->was_skipping;
2095 obstack_free (&pfile->buffer_ob, ifs);
2099 /* Push an if_stack entry for a preprocessor conditional, and set
2100 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2101 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2102 we need to check here that we are at the top of the file. */
2103 static void
2104 push_conditional (cpp_reader *pfile, int skip, int type,
2105 const cpp_hashnode *cmacro)
2107 struct if_stack *ifs;
2108 cpp_buffer *buffer = pfile->buffer;
2110 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2111 ifs->line = pfile->directive_line;
2112 ifs->next = buffer->if_stack;
2113 ifs->skip_elses = pfile->state.skipping || !skip;
2114 ifs->was_skipping = pfile->state.skipping;
2115 ifs->type = type;
2116 /* This condition is effectively a test for top-of-file. */
2117 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2118 ifs->mi_cmacro = cmacro;
2119 else
2120 ifs->mi_cmacro = 0;
2122 pfile->state.skipping = skip;
2123 buffer->if_stack = ifs;
2126 /* Read the tokens of the answer into the macro pool, in a directive
2127 of type TYPE. Only commit the memory if we intend it as permanent
2128 storage, i.e. the #assert case. Returns 0 on success, and sets
2129 ANSWERP to point to the answer. PRED_LOC is the location of the
2130 predicate. */
2131 static int
2132 parse_answer (cpp_reader *pfile, struct answer **answerp, int type,
2133 source_location pred_loc)
2135 const cpp_token *paren;
2136 struct answer *answer;
2137 unsigned int acount;
2139 /* In a conditional, it is legal to not have an open paren. We
2140 should save the following token in this case. */
2141 paren = cpp_get_token (pfile);
2143 /* If not a paren, see if we're OK. */
2144 if (paren->type != CPP_OPEN_PAREN)
2146 /* In a conditional no answer is a test for any answer. It
2147 could be followed by any token. */
2148 if (type == T_IF)
2150 _cpp_backup_tokens (pfile, 1);
2151 return 0;
2154 /* #unassert with no answer is valid - it removes all answers. */
2155 if (type == T_UNASSERT && paren->type == CPP_EOF)
2156 return 0;
2158 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2159 "missing '(' after predicate");
2160 return 1;
2163 for (acount = 0;; acount++)
2165 size_t room_needed;
2166 const cpp_token *token = cpp_get_token (pfile);
2167 cpp_token *dest;
2169 if (token->type == CPP_CLOSE_PAREN)
2170 break;
2172 if (token->type == CPP_EOF)
2174 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2175 return 1;
2178 /* struct answer includes the space for one token. */
2179 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
2181 if (BUFF_ROOM (pfile->a_buff) < room_needed)
2182 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
2184 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
2185 *dest = *token;
2187 /* Drop whitespace at start, for answer equivalence purposes. */
2188 if (acount == 0)
2189 dest->flags &= ~PREV_WHITE;
2192 if (acount == 0)
2194 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2195 return 1;
2198 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
2199 answer->count = acount;
2200 answer->next = NULL;
2201 *answerp = answer;
2203 return 0;
2206 /* Parses an assertion directive of type TYPE, returning a pointer to
2207 the hash node of the predicate, or 0 on error. If an answer was
2208 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
2209 static cpp_hashnode *
2210 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
2212 cpp_hashnode *result = 0;
2213 const cpp_token *predicate;
2215 /* We don't expand predicates or answers. */
2216 pfile->state.prevent_expansion++;
2218 *answerp = 0;
2219 predicate = cpp_get_token (pfile);
2220 if (predicate->type == CPP_EOF)
2221 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2222 else if (predicate->type != CPP_NAME)
2223 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2224 "predicate must be an identifier");
2225 else if (parse_answer (pfile, answerp, type, predicate->src_loc) == 0)
2227 unsigned int len = NODE_LEN (predicate->val.node.node);
2228 unsigned char *sym = (unsigned char *) alloca (len + 1);
2230 /* Prefix '#' to get it out of macro namespace. */
2231 sym[0] = '#';
2232 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2233 result = cpp_lookup (pfile, sym, len + 1);
2236 pfile->state.prevent_expansion--;
2237 return result;
2240 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2241 or a pointer to NULL if the answer is not in the chain. */
2242 static struct answer **
2243 find_answer (cpp_hashnode *node, const struct answer *candidate)
2245 unsigned int i;
2246 struct answer **result;
2248 for (result = &node->value.answers; *result; result = &(*result)->next)
2250 struct answer *answer = *result;
2252 if (answer->count == candidate->count)
2254 for (i = 0; i < answer->count; i++)
2255 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
2256 break;
2258 if (i == answer->count)
2259 break;
2263 return result;
2266 /* Test an assertion within a preprocessor conditional. Returns
2267 nonzero on failure, zero on success. On success, the result of
2268 the test is written into VALUE, otherwise the value 0. */
2270 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2272 struct answer *answer;
2273 cpp_hashnode *node;
2275 node = parse_assertion (pfile, &answer, T_IF);
2277 /* For recovery, an erroneous assertion expression is handled as a
2278 failing assertion. */
2279 *value = 0;
2281 if (node)
2282 *value = (node->type == NT_ASSERTION &&
2283 (answer == 0 || *find_answer (node, answer) != 0));
2284 else if (pfile->cur_token[-1].type == CPP_EOF)
2285 _cpp_backup_tokens (pfile, 1);
2287 /* We don't commit the memory for the answer - it's temporary only. */
2288 return node == 0;
2291 /* Handle #assert. */
2292 static void
2293 do_assert (cpp_reader *pfile)
2295 struct answer *new_answer;
2296 cpp_hashnode *node;
2298 node = parse_assertion (pfile, &new_answer, T_ASSERT);
2299 if (node)
2301 size_t answer_size;
2303 /* Place the new answer in the answer list. First check there
2304 is not a duplicate. */
2305 new_answer->next = 0;
2306 if (node->type == NT_ASSERTION)
2308 if (*find_answer (node, new_answer))
2310 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2311 NODE_NAME (node) + 1);
2312 return;
2314 new_answer->next = node->value.answers;
2317 answer_size = sizeof (struct answer) + ((new_answer->count - 1)
2318 * sizeof (cpp_token));
2319 /* Commit or allocate storage for the object. */
2320 if (pfile->hash_table->alloc_subobject)
2322 struct answer *temp_answer = new_answer;
2323 new_answer = (struct answer *) pfile->hash_table->alloc_subobject
2324 (answer_size);
2325 memcpy (new_answer, temp_answer, answer_size);
2327 else
2328 BUFF_FRONT (pfile->a_buff) += answer_size;
2330 node->type = NT_ASSERTION;
2331 node->value.answers = new_answer;
2332 check_eol (pfile, false);
2336 /* Handle #unassert. */
2337 static void
2338 do_unassert (cpp_reader *pfile)
2340 cpp_hashnode *node;
2341 struct answer *answer;
2343 node = parse_assertion (pfile, &answer, T_UNASSERT);
2344 /* It isn't an error to #unassert something that isn't asserted. */
2345 if (node && node->type == NT_ASSERTION)
2347 if (answer)
2349 struct answer **p = find_answer (node, answer), *temp;
2351 /* Remove the answer from the list. */
2352 temp = *p;
2353 if (temp)
2354 *p = temp->next;
2356 /* Did we free the last answer? */
2357 if (node->value.answers == 0)
2358 node->type = NT_VOID;
2360 check_eol (pfile, false);
2362 else
2363 _cpp_free_definition (node);
2366 /* We don't commit the memory for the answer - it's temporary only. */
2369 /* These are for -D, -U, -A. */
2371 /* Process the string STR as if it appeared as the body of a #define.
2372 If STR is just an identifier, define it with value 1.
2373 If STR has anything after the identifier, then it should
2374 be identifier=definition. */
2375 void
2376 cpp_define (cpp_reader *pfile, const char *str)
2378 char *buf;
2379 const char *p;
2380 size_t count;
2382 /* Copy the entire option so we can modify it.
2383 Change the first "=" in the string to a space. If there is none,
2384 tack " 1" on the end. */
2386 count = strlen (str);
2387 buf = (char *) alloca (count + 3);
2388 memcpy (buf, str, count);
2390 p = strchr (str, '=');
2391 if (p)
2392 buf[p - str] = ' ';
2393 else
2395 buf[count++] = ' ';
2396 buf[count++] = '1';
2398 buf[count] = '\n';
2400 run_directive (pfile, T_DEFINE, buf, count);
2404 /* Use to build macros to be run through cpp_define() as
2405 described above.
2406 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2408 void
2409 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2411 char *ptr;
2413 va_list ap;
2414 va_start (ap, fmt);
2415 ptr = xvasprintf (fmt, ap);
2416 va_end (ap);
2418 cpp_define (pfile, ptr);
2419 free (ptr);
2423 /* Slight variant of the above for use by initialize_builtins. */
2424 void
2425 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2427 size_t len = strlen (str);
2428 char *buf = (char *) alloca (len + 1);
2429 memcpy (buf, str, len);
2430 buf[len] = '\n';
2431 run_directive (pfile, T_DEFINE, buf, len);
2434 /* Process MACRO as if it appeared as the body of an #undef. */
2435 void
2436 cpp_undef (cpp_reader *pfile, const char *macro)
2438 size_t len = strlen (macro);
2439 char *buf = (char *) alloca (len + 1);
2440 memcpy (buf, macro, len);
2441 buf[len] = '\n';
2442 run_directive (pfile, T_UNDEF, buf, len);
2445 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2446 or first element is zero, then the macro should be undefined. */
2447 static void
2448 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2450 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2451 if (node == NULL)
2452 return;
2454 if (pfile->cb.before_define)
2455 pfile->cb.before_define (pfile);
2457 if (node->type == NT_MACRO)
2459 if (pfile->cb.undef)
2460 pfile->cb.undef (pfile, pfile->directive_line, node);
2461 if (CPP_OPTION (pfile, warn_unused_macros))
2462 _cpp_warn_if_unused_macro (pfile, node, NULL);
2464 if (node->type != NT_VOID)
2465 _cpp_free_definition (node);
2467 if (c->is_undef)
2468 return;
2470 size_t namelen;
2471 const uchar *dn;
2472 cpp_hashnode *h = NULL;
2473 cpp_buffer *nbuf;
2475 namelen = ustrcspn (c->definition, "( \n");
2476 h = cpp_lookup (pfile, c->definition, namelen);
2477 dn = c->definition + namelen;
2479 h->type = NT_VOID;
2480 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
2481 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2482 if (nbuf != NULL)
2484 _cpp_clean_line (pfile);
2485 nbuf->sysp = 1;
2486 if (!_cpp_create_definition (pfile, h))
2487 abort ();
2488 _cpp_pop_buffer (pfile);
2490 else
2491 abort ();
2492 h->value.macro->line = c->line;
2493 h->value.macro->syshdr = c->syshdr;
2494 h->value.macro->used = c->used;
2498 /* Process the string STR as if it appeared as the body of a #assert. */
2499 void
2500 cpp_assert (cpp_reader *pfile, const char *str)
2502 handle_assertion (pfile, str, T_ASSERT);
2505 /* Process STR as if it appeared as the body of an #unassert. */
2506 void
2507 cpp_unassert (cpp_reader *pfile, const char *str)
2509 handle_assertion (pfile, str, T_UNASSERT);
2512 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2513 static void
2514 handle_assertion (cpp_reader *pfile, const char *str, int type)
2516 size_t count = strlen (str);
2517 const char *p = strchr (str, '=');
2519 /* Copy the entire option so we can modify it. Change the first
2520 "=" in the string to a '(', and tack a ')' on the end. */
2521 char *buf = (char *) alloca (count + 2);
2523 memcpy (buf, str, count);
2524 if (p)
2526 buf[p - str] = '(';
2527 buf[count++] = ')';
2529 buf[count] = '\n';
2530 str = buf;
2532 run_directive (pfile, type, str, count);
2535 /* The options structure. */
2536 cpp_options *
2537 cpp_get_options (cpp_reader *pfile)
2539 return &pfile->opts;
2542 /* The callbacks structure. */
2543 cpp_callbacks *
2544 cpp_get_callbacks (cpp_reader *pfile)
2546 return &pfile->cb;
2549 /* Copy the given callbacks structure to our own. */
2550 void
2551 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2553 pfile->cb = *cb;
2556 /* The dependencies structure. (Creates one if it hasn't already been.) */
2557 struct deps *
2558 cpp_get_deps (cpp_reader *pfile)
2560 if (!pfile->deps)
2561 pfile->deps = deps_init ();
2562 return pfile->deps;
2565 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2566 doesn't fail. It does not generate a file change call back; that
2567 is the responsibility of the caller. */
2568 cpp_buffer *
2569 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2570 int from_stage3)
2572 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2574 /* Clears, amongst other things, if_stack and mi_cmacro. */
2575 memset (new_buffer, 0, sizeof (cpp_buffer));
2577 new_buffer->next_line = new_buffer->buf = buffer;
2578 new_buffer->rlimit = buffer + len;
2579 new_buffer->from_stage3 = from_stage3;
2580 new_buffer->prev = pfile->buffer;
2581 new_buffer->need_line = true;
2583 pfile->buffer = new_buffer;
2585 return new_buffer;
2588 /* Pops a single buffer, with a file change call-back if appropriate.
2589 Then pushes the next -include file, if any remain. */
2590 void
2591 _cpp_pop_buffer (cpp_reader *pfile)
2593 cpp_buffer *buffer = pfile->buffer;
2594 struct _cpp_file *inc = buffer->file;
2595 struct if_stack *ifs;
2596 const unsigned char *to_free;
2598 /* Walk back up the conditional stack till we reach its level at
2599 entry to this file, issuing error messages. */
2600 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2601 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2602 "unterminated #%s", dtable[ifs->type].name);
2604 /* In case of a missing #endif. */
2605 pfile->state.skipping = 0;
2607 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2608 pfile->buffer = buffer->prev;
2610 to_free = buffer->to_free;
2611 free (buffer->notes);
2613 /* Free the buffer object now; we may want to push a new buffer
2614 in _cpp_push_next_include_file. */
2615 obstack_free (&pfile->buffer_ob, buffer);
2617 if (inc)
2619 _cpp_pop_file_buffer (pfile, inc, to_free);
2621 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2625 /* Enter all recognized directives in the hash table. */
2626 void
2627 _cpp_init_directives (cpp_reader *pfile)
2629 unsigned int i;
2630 cpp_hashnode *node;
2632 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2634 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2635 node->is_directive = 1;
2636 node->directive_index = i;
2640 /* Extract header file from a bracket include. Parsing starts after '<'.
2641 The string is malloced and must be freed by the caller. */
2642 char *
2643 _cpp_bracket_include(cpp_reader *pfile)
2645 return glue_header_name (pfile);