compiler: set varargs correctly for type of method expression
[official-gcc.git] / libcpp / directives.c
blobf59718708e47c75afd7247cd8d6f18959398b03d
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2020 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 location_t 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 location_t *);
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 *, enum cpp_diagnostic_level code,
106 enum cpp_warning_reason reason, int);
107 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
108 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
109 static void do_include_common (cpp_reader *, enum include_type);
110 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
111 const cpp_hashnode *);
112 static int count_registered_pragmas (struct pragma_entry *);
113 static char ** save_registered_pragmas (struct pragma_entry *, char **);
114 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
115 char **);
116 static void do_pragma_once (cpp_reader *);
117 static void do_pragma_poison (cpp_reader *);
118 static void do_pragma_system_header (cpp_reader *);
119 static void do_pragma_dependency (cpp_reader *);
120 static void do_pragma_warning_or_error (cpp_reader *, bool error);
121 static void do_pragma_warning (cpp_reader *);
122 static void do_pragma_error (cpp_reader *);
123 static void do_linemarker (cpp_reader *);
124 static const cpp_token *get_token_no_padding (cpp_reader *);
125 static const cpp_token *get__Pragma_string (cpp_reader *);
126 static void destringize_and_run (cpp_reader *, const cpp_string *,
127 location_t);
128 static bool parse_answer (cpp_reader *, int, location_t, cpp_macro **);
129 static cpp_hashnode *parse_assertion (cpp_reader *, int, cpp_macro **);
130 static cpp_macro **find_answer (cpp_hashnode *, const cpp_macro *);
131 static void handle_assertion (cpp_reader *, const char *, int);
132 static void do_pragma_push_macro (cpp_reader *);
133 static void do_pragma_pop_macro (cpp_reader *);
134 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
136 /* This is the table of directive handlers. All extensions other than
137 #warning, #include_next, and #import are deprecated. The name is
138 where the extension appears to have come from. */
140 #define DIRECTIVE_TABLE \
141 D(define, T_DEFINE = 0, KANDR, IN_I) \
142 D(include, T_INCLUDE, KANDR, INCL | EXPAND) \
143 D(endif, T_ENDIF, KANDR, COND) \
144 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) \
145 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) \
146 D(else, T_ELSE, KANDR, COND) \
147 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) \
148 D(undef, T_UNDEF, KANDR, IN_I) \
149 D(line, T_LINE, KANDR, EXPAND) \
150 D(elif, T_ELIF, STDC89, COND | EXPAND) \
151 D(error, T_ERROR, STDC89, 0) \
152 D(pragma, T_PRAGMA, STDC89, IN_I) \
153 D(warning, T_WARNING, EXTENSION, 0) \
154 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) \
155 D(ident, T_IDENT, EXTENSION, IN_I) \
156 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* ObjC */ \
157 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* SVR4 */ \
158 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* SVR4 */ \
159 D(sccs, T_SCCS, EXTENSION, IN_I) /* SVR4? */
161 /* #sccs is synonymous with #ident. */
162 #define do_sccs do_ident
164 /* Use the table to generate a series of prototypes, an enum for the
165 directive names, and an array of directive handlers. */
167 #define D(name, t, o, f) static void do_##name (cpp_reader *);
168 DIRECTIVE_TABLE
169 #undef D
171 #define D(n, tag, o, f) tag,
172 enum
174 DIRECTIVE_TABLE
175 N_DIRECTIVES
177 #undef D
179 #define D(name, t, origin, flags) \
180 { do_##name, (const uchar *) #name, \
181 sizeof #name - 1, origin, flags },
182 static const directive dtable[] =
184 DIRECTIVE_TABLE
186 #undef D
188 /* A NULL-terminated array of directive names for use
189 when suggesting corrections for misspelled directives. */
190 #define D(name, t, origin, flags) #name,
191 static const char * const directive_names[] = {
192 DIRECTIVE_TABLE
193 NULL
195 #undef D
197 #undef DIRECTIVE_TABLE
199 /* Wrapper struct directive for linemarkers.
200 The origin is more or less true - the original K+R cpp
201 did use this notation in its preprocessed output. */
202 static const directive linemarker_dir =
204 do_linemarker, UC"#", 1, KANDR, IN_I
207 /* Skip any remaining tokens in a directive. */
208 static void
209 skip_rest_of_line (cpp_reader *pfile)
211 /* Discard all stacked contexts. */
212 while (pfile->context->prev)
213 _cpp_pop_context (pfile);
215 /* Sweep up all tokens remaining on the line. */
216 if (! SEEN_EOL ())
217 while (_cpp_lex_token (pfile)->type != CPP_EOF)
221 /* Helper function for check_oel. */
223 static void
224 check_eol_1 (cpp_reader *pfile, bool expand, enum cpp_warning_reason reason)
226 if (! SEEN_EOL () && (expand
227 ? cpp_get_token (pfile)
228 : _cpp_lex_token (pfile))->type != CPP_EOF)
229 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
230 pfile->directive->name);
233 /* Variant of check_eol used for Wendif-labels warnings. */
235 static void
236 check_eol_endif_labels (cpp_reader *pfile)
238 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
241 /* Ensure there are no stray tokens at the end of a directive. If
242 EXPAND is true, tokens macro-expanding to nothing are allowed. */
244 static void
245 check_eol (cpp_reader *pfile, bool expand)
247 check_eol_1 (pfile, expand, CPP_W_NONE);
250 /* Ensure there are no stray tokens other than comments at the end of
251 a directive, and gather the comments. */
252 static const cpp_token **
253 check_eol_return_comments (cpp_reader *pfile)
255 size_t c;
256 size_t capacity = 8;
257 const cpp_token **buf;
259 buf = XNEWVEC (const cpp_token *, capacity);
260 c = 0;
261 if (! SEEN_EOL ())
263 while (1)
265 const cpp_token *tok;
267 tok = _cpp_lex_token (pfile);
268 if (tok->type == CPP_EOF)
269 break;
270 if (tok->type != CPP_COMMENT)
271 cpp_error (pfile, CPP_DL_PEDWARN,
272 "extra tokens at end of #%s directive",
273 pfile->directive->name);
274 else
276 if (c + 1 >= capacity)
278 capacity *= 2;
279 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
281 buf[c] = tok;
282 ++c;
286 buf[c] = NULL;
287 return buf;
290 /* Called when entering a directive, _Pragma or command-line directive. */
291 static void
292 start_directive (cpp_reader *pfile)
294 /* Setup in-directive state. */
295 pfile->state.in_directive = 1;
296 pfile->state.save_comments = 0;
297 pfile->directive_result.type = CPP_PADDING;
299 /* Some handlers need the position of the # for diagnostics. */
300 pfile->directive_line = pfile->line_table->highest_line;
303 /* Called when leaving a directive, _Pragma or command-line directive. */
304 static void
305 end_directive (cpp_reader *pfile, int skip_line)
307 if (CPP_OPTION (pfile, traditional))
309 /* Revert change of prepare_directive_trad. */
310 if (!pfile->state.in_deferred_pragma)
311 pfile->state.prevent_expansion--;
313 if (pfile->directive != &dtable[T_DEFINE])
314 _cpp_remove_overlay (pfile);
316 else if (pfile->state.in_deferred_pragma)
318 /* We don't skip for an assembler #. */
319 else if (skip_line)
321 skip_rest_of_line (pfile);
322 if (!pfile->keep_tokens)
324 pfile->cur_run = &pfile->base_run;
325 pfile->cur_token = pfile->base_run.base;
329 /* Restore state. */
330 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
331 pfile->state.in_directive = 0;
332 pfile->state.in_expression = 0;
333 pfile->state.angled_headers = 0;
334 pfile->directive = 0;
337 /* Prepare to handle the directive in pfile->directive. */
338 static void
339 prepare_directive_trad (cpp_reader *pfile)
341 if (pfile->directive != &dtable[T_DEFINE])
343 bool no_expand = (pfile->directive
344 && ! (pfile->directive->flags & EXPAND));
345 bool was_skipping = pfile->state.skipping;
347 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
348 || pfile->directive == &dtable[T_ELIF]);
349 if (pfile->state.in_expression)
350 pfile->state.skipping = false;
352 if (no_expand)
353 pfile->state.prevent_expansion++;
354 _cpp_scan_out_logical_line (pfile, NULL, false);
355 if (no_expand)
356 pfile->state.prevent_expansion--;
358 pfile->state.skipping = was_skipping;
359 _cpp_overlay_buffer (pfile, pfile->out.base,
360 pfile->out.cur - pfile->out.base);
363 /* Stop ISO C from expanding anything. */
364 pfile->state.prevent_expansion++;
367 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
368 the '#' was indented. */
369 static void
370 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
372 /* Issue -pedantic or deprecated warnings for extensions. We let
373 -pedantic take precedence if both are applicable. */
374 if (! pfile->state.skipping)
376 if (dir->origin == EXTENSION
377 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
378 && CPP_PEDANTIC (pfile))
379 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
380 else if (((dir->flags & DEPRECATED) != 0
381 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
382 && CPP_OPTION (pfile, cpp_warn_deprecated))
383 cpp_warning (pfile, CPP_W_DEPRECATED,
384 "#%s is a deprecated GCC extension", dir->name);
387 /* Traditionally, a directive is ignored unless its # is in
388 column 1. Therefore in code intended to work with K+R
389 compilers, directives added by C89 must have their #
390 indented, and directives present in traditional C must not.
391 This is true even of directives in skipped conditional
392 blocks. #elif cannot be used at all. */
393 if (CPP_WTRADITIONAL (pfile))
395 if (dir == &dtable[T_ELIF])
396 cpp_warning (pfile, CPP_W_TRADITIONAL,
397 "suggest not using #elif in traditional C");
398 else if (indented && dir->origin == KANDR)
399 cpp_warning (pfile, CPP_W_TRADITIONAL,
400 "traditional C ignores #%s with the # indented",
401 dir->name);
402 else if (!indented && dir->origin != KANDR)
403 cpp_warning (pfile, CPP_W_TRADITIONAL,
404 "suggest hiding #%s from traditional C with an indented #",
405 dir->name);
409 /* Check if we have a known directive. INDENTED is true if the
410 '#' of the directive was indented. This function is in this file
411 to save unnecessarily exporting dtable etc. to lex.c. Returns
412 nonzero if the line of tokens has been handled, zero if we should
413 continue processing the line. */
415 _cpp_handle_directive (cpp_reader *pfile, bool indented)
417 const directive *dir = 0;
418 const cpp_token *dname;
419 bool was_parsing_args = pfile->state.parsing_args;
420 bool was_discarding_output = pfile->state.discarding_output;
421 int skip = 1;
423 if (was_discarding_output)
424 pfile->state.prevent_expansion = 0;
426 if (was_parsing_args)
428 if (CPP_OPTION (pfile, cpp_pedantic))
429 cpp_error (pfile, CPP_DL_PEDWARN,
430 "embedding a directive within macro arguments is not portable");
431 pfile->state.parsing_args = 0;
432 pfile->state.prevent_expansion = 0;
434 start_directive (pfile);
435 dname = _cpp_lex_token (pfile);
437 if (dname->type == CPP_NAME)
439 if (dname->val.node.node->is_directive)
440 dir = &dtable[dname->val.node.node->directive_index];
442 /* We do not recognize the # followed by a number extension in
443 assembler code. */
444 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
446 dir = &linemarker_dir;
447 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
448 && ! pfile->state.skipping)
449 cpp_error (pfile, CPP_DL_PEDWARN,
450 "style of line directive is a GCC extension");
453 if (dir)
455 /* If we have a directive that is not an opening conditional,
456 invalidate any control macro. */
457 if (! (dir->flags & IF_COND))
458 pfile->mi_valid = false;
460 /* Kluge alert. In order to be sure that code like this
462 #define HASH #
463 HASH define foo bar
465 does not cause '#define foo bar' to get executed when
466 compiled with -save-temps, we recognize directives in
467 -fpreprocessed mode only if the # is in column 1. macro.c
468 puts a space in front of any '#' at the start of a macro.
470 We exclude the -fdirectives-only case because macro expansion
471 has not been performed yet, and block comments can cause spaces
472 to precede the directive. */
473 if (CPP_OPTION (pfile, preprocessed)
474 && !CPP_OPTION (pfile, directives_only)
475 && (indented || !(dir->flags & IN_I)))
477 skip = 0;
478 dir = 0;
480 else
482 /* In failed conditional groups, all non-conditional
483 directives are ignored. Before doing that, whether
484 skipping or not, we should lex angle-bracketed headers
485 correctly, and maybe output some diagnostics. */
486 pfile->state.angled_headers = dir->flags & INCL;
487 pfile->state.directive_wants_padding = dir->flags & INCL;
488 if (! CPP_OPTION (pfile, preprocessed))
489 directive_diagnostics (pfile, dir, indented);
490 if (pfile->state.skipping && !(dir->flags & COND))
491 dir = 0;
494 else if (dname->type == CPP_EOF)
495 ; /* CPP_EOF is the "null directive". */
496 else
498 /* An unknown directive. Don't complain about it in assembly
499 source: we don't know where the comments are, and # may
500 introduce assembler pseudo-ops. Don't complain about invalid
501 directives in skipped conditional groups (6.10 p4). */
502 if (CPP_OPTION (pfile, lang) == CLK_ASM)
503 skip = 0;
504 else if (!pfile->state.skipping)
506 const char *unrecognized
507 = (const char *)cpp_token_as_text (pfile, dname);
508 const char *hint = NULL;
510 /* Call back into gcc to get a spelling suggestion. Ideally
511 we'd just use best_match from gcc/spellcheck.h (and filter
512 out the uncommon directives), but that requires moving it
513 to a support library. */
514 if (pfile->cb.get_suggestion)
515 hint = pfile->cb.get_suggestion (pfile, unrecognized,
516 directive_names);
518 if (hint)
520 rich_location richloc (pfile->line_table, dname->src_loc);
521 source_range misspelled_token_range
522 = get_range_from_loc (pfile->line_table, dname->src_loc);
523 richloc.add_fixit_replace (misspelled_token_range, hint);
524 cpp_error_at (pfile, CPP_DL_ERROR, &richloc,
525 "invalid preprocessing directive #%s;"
526 " did you mean #%s?",
527 unrecognized, hint);
529 else
530 cpp_error (pfile, CPP_DL_ERROR,
531 "invalid preprocessing directive #%s",
532 unrecognized);
536 pfile->directive = dir;
537 if (CPP_OPTION (pfile, traditional))
538 prepare_directive_trad (pfile);
540 if (dir)
541 pfile->directive->handler (pfile);
542 else if (skip == 0)
543 _cpp_backup_tokens (pfile, 1);
545 end_directive (pfile, skip);
546 if (was_parsing_args && !pfile->state.in_deferred_pragma)
548 /* Restore state when within macro args. */
549 pfile->state.parsing_args = 2;
550 pfile->state.prevent_expansion = 1;
552 if (was_discarding_output)
553 pfile->state.prevent_expansion = 1;
554 return skip;
557 /* Directive handler wrapper used by the command line option
558 processor. BUF is \n terminated. */
559 static void
560 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
562 cpp_push_buffer (pfile, (const uchar *) buf, count,
563 /* from_stage3 */ true);
564 start_directive (pfile);
566 /* This is a short-term fix to prevent a leading '#' being
567 interpreted as a directive. */
568 _cpp_clean_line (pfile);
570 pfile->directive = &dtable[dir_no];
571 if (CPP_OPTION (pfile, traditional))
572 prepare_directive_trad (pfile);
573 pfile->directive->handler (pfile);
574 end_directive (pfile, 1);
575 _cpp_pop_buffer (pfile);
578 /* Checks for validity the macro name in #define, #undef, #ifdef and
579 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
580 processing a #define or #undefine directive, and false
581 otherwise. */
582 static cpp_hashnode *
583 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
585 const cpp_token *token = _cpp_lex_token (pfile);
587 /* The token immediately after #define must be an identifier. That
588 identifier may not be "defined", per C99 6.10.8p4.
589 In C++, it may not be any of the "named operators" either,
590 per C++98 [lex.digraph], [lex.key].
591 Finally, the identifier may not have been poisoned. (In that case
592 the lexer has issued the error message for us.) */
594 if (token->type == CPP_NAME)
596 cpp_hashnode *node = token->val.node.node;
598 if (is_def_or_undef
599 && node == pfile->spec_nodes.n_defined)
600 cpp_error (pfile, CPP_DL_ERROR,
601 "\"%s\" cannot be used as a macro name",
602 NODE_NAME (node));
603 else if (! (node->flags & NODE_POISONED))
604 return node;
606 else if (token->flags & NAMED_OP)
607 cpp_error (pfile, CPP_DL_ERROR,
608 "\"%s\" cannot be used as a macro name as it is an operator in C++",
609 NODE_NAME (token->val.node.node));
610 else if (token->type == CPP_EOF)
611 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
612 pfile->directive->name);
613 else
614 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
616 return NULL;
619 /* Process a #define directive. Most work is done in macro.c. */
620 static void
621 do_define (cpp_reader *pfile)
623 cpp_hashnode *node = lex_macro_node (pfile, true);
625 if (node)
627 /* If we have been requested to expand comments into macros,
628 then re-enable saving of comments. */
629 pfile->state.save_comments =
630 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
632 if (pfile->cb.before_define)
633 pfile->cb.before_define (pfile);
635 if (_cpp_create_definition (pfile, node))
636 if (pfile->cb.define)
637 pfile->cb.define (pfile, pfile->directive_line, node);
639 node->flags &= ~NODE_USED;
643 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
644 static void
645 do_undef (cpp_reader *pfile)
647 cpp_hashnode *node = lex_macro_node (pfile, true);
649 if (node)
651 if (pfile->cb.before_define)
652 pfile->cb.before_define (pfile);
654 if (pfile->cb.undef)
655 pfile->cb.undef (pfile, pfile->directive_line, node);
657 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
658 identifier is not currently defined as a macro name. */
659 if (cpp_macro_p (node))
661 if (node->flags & NODE_WARN)
662 cpp_error (pfile, CPP_DL_WARNING,
663 "undefining \"%s\"", NODE_NAME (node));
664 else if (cpp_builtin_macro_p (node)
665 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
666 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
667 pfile->directive_line, 0,
668 "undefining \"%s\"", NODE_NAME (node));
670 if (CPP_OPTION (pfile, warn_unused_macros))
671 _cpp_warn_if_unused_macro (pfile, node, NULL);
673 _cpp_free_definition (node);
677 check_eol (pfile, false);
680 /* Undefine a single macro/assertion/whatever. */
682 static int
683 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
684 void *data_p ATTRIBUTE_UNUSED)
686 /* Body of _cpp_free_definition inlined here for speed.
687 Macros and assertions no longer have anything to free. */
688 h->type = NT_VOID;
689 h->value.answers = NULL;
690 h->flags &= ~(NODE_POISONED|NODE_DISABLED|NODE_USED);
691 return 1;
694 /* Undefine all macros and assertions. */
696 void
697 cpp_undef_all (cpp_reader *pfile)
699 cpp_forall_identifiers (pfile, undefine_macros, NULL);
703 /* Helper routine used by parse_include. Reinterpret the current line
704 as an h-char-sequence (< ... >); we are looking at the first token
705 after the <. Returns a malloced filename. */
706 static char *
707 glue_header_name (cpp_reader *pfile)
709 const cpp_token *token;
710 char *buffer;
711 size_t len, total_len = 0, capacity = 1024;
713 /* To avoid lexed tokens overwriting our glued name, we can only
714 allocate from the string pool once we've lexed everything. */
715 buffer = XNEWVEC (char, capacity);
716 for (;;)
718 token = get_token_no_padding (pfile);
720 if (token->type == CPP_GREATER)
721 break;
722 if (token->type == CPP_EOF)
724 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
725 break;
728 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
729 if (total_len + len > capacity)
731 capacity = (capacity + len) * 2;
732 buffer = XRESIZEVEC (char, buffer, capacity);
735 if (token->flags & PREV_WHITE)
736 buffer[total_len++] = ' ';
738 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
739 true)
740 - (uchar *) buffer);
743 buffer[total_len] = '\0';
744 return buffer;
747 /* Returns the file name of #include, #include_next, #import and
748 #pragma dependency. The string is malloced and the caller should
749 free it. Returns NULL on error. LOCATION is the source location
750 of the file name. */
752 static const char *
753 parse_include (cpp_reader *pfile, int *pangle_brackets,
754 const cpp_token ***buf, location_t *location)
756 char *fname;
757 const cpp_token *header;
759 /* Allow macro expansion. */
760 header = get_token_no_padding (pfile);
761 *location = header->src_loc;
762 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
763 || header->type == CPP_HEADER_NAME)
765 fname = XNEWVEC (char, header->val.str.len - 1);
766 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
767 fname[header->val.str.len - 2] = '\0';
768 *pangle_brackets = header->type == CPP_HEADER_NAME;
770 else if (header->type == CPP_LESS)
772 fname = glue_header_name (pfile);
773 *pangle_brackets = 1;
775 else
777 const unsigned char *dir;
779 if (pfile->directive == &dtable[T_PRAGMA])
780 dir = UC"pragma dependency";
781 else
782 dir = pfile->directive->name;
783 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
784 dir);
786 return NULL;
789 if (pfile->directive == &dtable[T_PRAGMA])
791 /* This pragma allows extra tokens after the file name. */
793 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
794 check_eol (pfile, true);
795 else
797 /* If we are not discarding comments, then gather them while
798 doing the eol check. */
799 *buf = check_eol_return_comments (pfile);
802 return fname;
805 /* Handle #include, #include_next and #import. */
806 static void
807 do_include_common (cpp_reader *pfile, enum include_type type)
809 const char *fname;
810 int angle_brackets;
811 const cpp_token **buf = NULL;
812 location_t location;
814 /* Re-enable saving of comments if requested, so that the include
815 callback can dump comments which follow #include. */
816 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
818 /* Tell the lexer this is an include directive -- we want it to
819 increment the line number even if this is the last line of a file. */
820 pfile->state.in_directive = 2;
822 fname = parse_include (pfile, &angle_brackets, &buf, &location);
823 if (!fname)
824 goto done;
826 if (!*fname)
828 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
829 "empty filename in #%s",
830 pfile->directive->name);
831 goto done;
834 /* Prevent #include recursion. */
835 if (pfile->line_table->depth >= CPP_OPTION (pfile, max_include_depth))
836 cpp_error (pfile,
837 CPP_DL_ERROR,
838 "#include nested depth %u exceeds maximum of %u"
839 " (use -fmax-include-depth=DEPTH to increase the maximum)",
840 pfile->line_table->depth,
841 CPP_OPTION (pfile, max_include_depth));
842 else
844 /* Get out of macro context, if we are. */
845 skip_rest_of_line (pfile);
847 if (pfile->cb.include)
848 pfile->cb.include (pfile, pfile->directive_line,
849 pfile->directive->name, fname, angle_brackets,
850 buf);
852 _cpp_stack_include (pfile, fname, angle_brackets, type, location);
855 done:
856 XDELETEVEC (fname);
857 if (buf)
858 XDELETEVEC (buf);
861 static void
862 do_include (cpp_reader *pfile)
864 do_include_common (pfile, IT_INCLUDE);
867 static void
868 do_import (cpp_reader *pfile)
870 do_include_common (pfile, IT_IMPORT);
873 static void
874 do_include_next (cpp_reader *pfile)
876 enum include_type type = IT_INCLUDE_NEXT;
878 /* If this is the primary source file, warn and use the normal
879 search logic. */
880 if (cpp_in_primary_file (pfile))
882 cpp_error (pfile, CPP_DL_WARNING,
883 "#include_next in primary source file");
884 type = IT_INCLUDE;
886 do_include_common (pfile, type);
889 /* Subroutine of do_linemarker. Read possible flags after file name.
890 LAST is the last flag seen; 0 if this is the first flag. Return the
891 flag if it is valid, 0 at the end of the directive. Otherwise
892 complain. */
893 static unsigned int
894 read_flag (cpp_reader *pfile, unsigned int last)
896 const cpp_token *token = _cpp_lex_token (pfile);
898 if (token->type == CPP_NUMBER && token->val.str.len == 1)
900 unsigned int flag = token->val.str.text[0] - '0';
902 if (flag > last && flag <= 4
903 && (flag != 4 || last == 3)
904 && (flag != 2 || last == 0))
905 return flag;
908 if (token->type != CPP_EOF)
909 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
910 cpp_token_as_text (pfile, token));
911 return 0;
914 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
915 of length LEN, to binary; store it in NUMP, and return false if the
916 number was well-formed, true if not. WRAPPED is set to true if the
917 number did not fit into 'unsigned long'. */
918 static bool
919 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
921 linenum_type reg = 0;
922 linenum_type reg_prev = 0;
924 uchar c;
925 *wrapped = false;
926 while (len--)
928 c = *str++;
929 if (!ISDIGIT (c))
930 return true;
931 reg *= 10;
932 reg += c - '0';
933 if (reg < reg_prev)
934 *wrapped = true;
935 reg_prev = reg;
937 *nump = reg;
938 return false;
941 /* Interpret #line command.
942 Note that the filename string (if any) is a true string constant
943 (escapes are interpreted). */
944 static void
945 do_line (cpp_reader *pfile)
947 class line_maps *line_table = pfile->line_table;
948 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
950 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
951 sysp right now. */
953 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
954 const cpp_token *token;
955 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
956 linenum_type new_lineno;
958 /* C99 raised the minimum limit on #line numbers. */
959 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
960 bool wrapped;
962 /* #line commands expand macros. */
963 token = cpp_get_token (pfile);
964 if (token->type != CPP_NUMBER
965 || strtolinenum (token->val.str.text, token->val.str.len,
966 &new_lineno, &wrapped))
968 if (token->type == CPP_EOF)
969 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
970 else
971 cpp_error (pfile, CPP_DL_ERROR,
972 "\"%s\" after #line is not a positive integer",
973 cpp_token_as_text (pfile, token));
974 return;
977 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
978 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
979 else if (wrapped)
980 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
982 token = cpp_get_token (pfile);
983 if (token->type == CPP_STRING)
985 cpp_string s = { 0, 0 };
986 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
987 &s, CPP_STRING))
988 new_file = (const char *)s.text;
989 check_eol (pfile, true);
991 else if (token->type != CPP_EOF)
993 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
994 cpp_token_as_text (pfile, token));
995 return;
998 skip_rest_of_line (pfile);
999 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1000 map_sysp);
1001 line_table->seen_line_directive = true;
1004 /* Interpret the # 44 "file" [flags] notation, which has slightly
1005 different syntax and semantics from #line: Flags are allowed,
1006 and we never complain about the line number being too big. */
1007 static void
1008 do_linemarker (cpp_reader *pfile)
1010 class line_maps *line_table = pfile->line_table;
1011 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1012 const cpp_token *token;
1013 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1014 linenum_type new_lineno;
1015 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1016 enum lc_reason reason = LC_RENAME_VERBATIM;
1017 int flag;
1018 bool wrapped;
1020 /* Back up so we can get the number again. Putting this in
1021 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1022 some circumstances, which can segfault. */
1023 _cpp_backup_tokens (pfile, 1);
1025 /* #line commands expand macros. */
1026 token = cpp_get_token (pfile);
1027 if (token->type != CPP_NUMBER
1028 || strtolinenum (token->val.str.text, token->val.str.len,
1029 &new_lineno, &wrapped))
1031 /* Unlike #line, there does not seem to be a way to get an EOF
1032 here. So, it should be safe to always spell the token. */
1033 cpp_error (pfile, CPP_DL_ERROR,
1034 "\"%s\" after # is not a positive integer",
1035 cpp_token_as_text (pfile, token));
1036 return;
1039 token = cpp_get_token (pfile);
1040 if (token->type == CPP_STRING)
1042 cpp_string s = { 0, 0 };
1043 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1044 1, &s, CPP_STRING))
1045 new_file = (const char *)s.text;
1047 new_sysp = 0;
1048 flag = read_flag (pfile, 0);
1049 if (flag == 1)
1051 reason = LC_ENTER;
1052 /* Fake an include for cpp_included (). */
1053 _cpp_fake_include (pfile, new_file);
1054 flag = read_flag (pfile, flag);
1056 else if (flag == 2)
1058 reason = LC_LEAVE;
1059 flag = read_flag (pfile, flag);
1061 if (flag == 3)
1063 new_sysp = 1;
1064 flag = read_flag (pfile, flag);
1065 if (flag == 4)
1066 new_sysp = 2;
1068 pfile->buffer->sysp = new_sysp;
1070 check_eol (pfile, false);
1072 else if (token->type != CPP_EOF)
1074 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1075 cpp_token_as_text (pfile, token));
1076 return;
1079 skip_rest_of_line (pfile);
1081 if (reason == LC_LEAVE)
1083 /* Reread map since cpp_get_token can invalidate it with a
1084 reallocation. */
1085 map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1086 const line_map_ordinary *from
1087 = linemap_included_from_linemap (line_table, map);
1089 if (!from)
1090 /* Not nested. */;
1091 else if (!new_file[0])
1092 /* Leaving to "" means fill in the popped-to name. */
1093 new_file = ORDINARY_MAP_FILE_NAME (from);
1094 else if (filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0)
1095 /* It's the wrong name, Grommit! */
1096 from = NULL;
1098 if (!from)
1100 cpp_warning (pfile, CPP_W_NONE,
1101 "file \"%s\" linemarker ignored due to "
1102 "incorrect nesting", new_file);
1103 return;
1107 /* Compensate for the increment in linemap_add that occurs in
1108 _cpp_do_file_change. We're currently at the start of the line
1109 *following* the #line directive. A separate location_t for this
1110 location makes no sense (until we do the LC_LEAVE), and
1111 complicates LAST_SOURCE_LINE_LOCATION. */
1112 pfile->line_table->highest_location--;
1114 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1115 line_table->seen_line_directive = true;
1118 /* Arrange the file_change callback. Changing to TO_FILE:TO_LINE for
1119 REASON. SYSP is 1 for a system header, 2 for a system header that
1120 needs to be extern "C" protected, and zero otherwise. */
1121 void
1122 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1123 const char *to_file, linenum_type to_line,
1124 unsigned int sysp)
1126 linemap_assert (reason != LC_ENTER_MACRO);
1128 const line_map_ordinary *ord_map = NULL;
1129 if (!to_line && reason == LC_RENAME_VERBATIM)
1131 /* A linemarker moving to line zero. If we're on the second
1132 line of the current map, and it also starts at zero, just
1133 rewind -- we're probably reading the builtins of a
1134 preprocessed source. */
1135 line_map_ordinary *last = LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table);
1136 if (!ORDINARY_MAP_STARTING_LINE_NUMBER (last)
1137 && SOURCE_LINE (last, pfile->line_table->highest_line) == 2)
1139 ord_map = last;
1140 pfile->line_table->highest_location
1141 = pfile->line_table->highest_line = MAP_START_LOCATION (last);
1145 if (!ord_map)
1146 if (const line_map *map = linemap_add (pfile->line_table, reason, sysp,
1147 to_file, to_line))
1149 ord_map = linemap_check_ordinary (map);
1150 linemap_line_start (pfile->line_table,
1151 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1152 127);
1155 if (pfile->cb.file_change)
1156 pfile->cb.file_change (pfile, ord_map);
1159 /* Report a warning or error detected by the program we are
1160 processing. Use the directive's tokens in the error message. */
1161 static void
1162 do_diagnostic (cpp_reader *pfile, enum cpp_diagnostic_level code,
1163 enum cpp_warning_reason reason, int print_dir)
1165 const unsigned char *dir_name;
1166 unsigned char *line;
1167 location_t src_loc = pfile->cur_token[-1].src_loc;
1169 if (print_dir)
1170 dir_name = pfile->directive->name;
1171 else
1172 dir_name = NULL;
1173 pfile->state.prevent_expansion++;
1174 line = cpp_output_line_to_string (pfile, dir_name);
1175 pfile->state.prevent_expansion--;
1177 if (code == CPP_DL_WARNING_SYSHDR && reason)
1178 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1179 else if (code == CPP_DL_WARNING && reason)
1180 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1181 else
1182 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1183 free (line);
1186 static void
1187 do_error (cpp_reader *pfile)
1189 do_diagnostic (pfile, CPP_DL_ERROR, CPP_W_NONE, 1);
1192 static void
1193 do_warning (cpp_reader *pfile)
1195 /* We want #warning diagnostics to be emitted in system headers too. */
1196 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1199 /* Report program identification. */
1200 static void
1201 do_ident (cpp_reader *pfile)
1203 const cpp_token *str = cpp_get_token (pfile);
1205 if (str->type != CPP_STRING)
1206 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1207 pfile->directive->name);
1208 else if (pfile->cb.ident)
1209 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1211 check_eol (pfile, false);
1214 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1215 matching entry, or NULL if none is found. The returned entry could
1216 be the start of a namespace chain, or a pragma. */
1217 static struct pragma_entry *
1218 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1220 while (chain && chain->pragma != pragma)
1221 chain = chain->next;
1223 return chain;
1226 /* Create and insert a blank pragma entry at the beginning of a
1227 singly-linked CHAIN. */
1228 static struct pragma_entry *
1229 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1231 struct pragma_entry *new_entry;
1233 new_entry = (struct pragma_entry *)
1234 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1236 memset (new_entry, 0, sizeof (struct pragma_entry));
1237 new_entry->next = *chain;
1239 *chain = new_entry;
1240 return new_entry;
1243 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1244 goes in the global namespace. */
1245 static struct pragma_entry *
1246 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1247 bool allow_name_expansion)
1249 struct pragma_entry **chain = &pfile->pragmas;
1250 struct pragma_entry *entry;
1251 const cpp_hashnode *node;
1253 if (space)
1255 node = cpp_lookup (pfile, UC space, strlen (space));
1256 entry = lookup_pragma_entry (*chain, node);
1257 if (!entry)
1259 entry = new_pragma_entry (pfile, chain);
1260 entry->pragma = node;
1261 entry->is_nspace = true;
1262 entry->allow_expansion = allow_name_expansion;
1264 else if (!entry->is_nspace)
1265 goto clash;
1266 else if (entry->allow_expansion != allow_name_expansion)
1268 cpp_error (pfile, CPP_DL_ICE,
1269 "registering pragmas in namespace \"%s\" with mismatched "
1270 "name expansion", space);
1271 return NULL;
1273 chain = &entry->u.space;
1275 else if (allow_name_expansion)
1277 cpp_error (pfile, CPP_DL_ICE,
1278 "registering pragma \"%s\" with name expansion "
1279 "and no namespace", name);
1280 return NULL;
1283 /* Check for duplicates. */
1284 node = cpp_lookup (pfile, UC name, strlen (name));
1285 entry = lookup_pragma_entry (*chain, node);
1286 if (entry == NULL)
1288 entry = new_pragma_entry (pfile, chain);
1289 entry->pragma = node;
1290 return entry;
1293 if (entry->is_nspace)
1294 clash:
1295 cpp_error (pfile, CPP_DL_ICE,
1296 "registering \"%s\" as both a pragma and a pragma namespace",
1297 NODE_NAME (node));
1298 else if (space)
1299 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1300 space, name);
1301 else
1302 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1304 return NULL;
1307 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1308 static void
1309 register_pragma_internal (cpp_reader *pfile, const char *space,
1310 const char *name, pragma_cb handler)
1312 struct pragma_entry *entry;
1314 entry = register_pragma_1 (pfile, space, name, false);
1315 entry->is_internal = true;
1316 entry->u.handler = handler;
1319 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1320 goes in the global namespace. HANDLER is the handler it will call,
1321 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1322 expansion while parsing pragma NAME. This function is exported
1323 from libcpp. */
1324 void
1325 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1326 pragma_cb handler, bool allow_expansion)
1328 struct pragma_entry *entry;
1330 if (!handler)
1332 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1333 return;
1336 entry = register_pragma_1 (pfile, space, name, false);
1337 if (entry)
1339 entry->allow_expansion = allow_expansion;
1340 entry->u.handler = handler;
1344 /* Similarly, but create mark the pragma for deferred processing.
1345 When found, a CPP_PRAGMA token will be insertted into the stream
1346 with IDENT in the token->u.pragma slot. */
1347 void
1348 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1349 const char *name, unsigned int ident,
1350 bool allow_expansion, bool allow_name_expansion)
1352 struct pragma_entry *entry;
1354 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1355 if (entry)
1357 entry->is_deferred = true;
1358 entry->allow_expansion = allow_expansion;
1359 entry->u.ident = ident;
1363 /* Register the pragmas the preprocessor itself handles. */
1364 void
1365 _cpp_init_internal_pragmas (cpp_reader *pfile)
1367 /* Pragmas in the global namespace. */
1368 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1369 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1370 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1372 /* New GCC-specific pragmas should be put in the GCC namespace. */
1373 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1374 register_pragma_internal (pfile, "GCC", "system_header",
1375 do_pragma_system_header);
1376 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1377 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1378 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1381 /* Return the number of registered pragmas in PE. */
1383 static int
1384 count_registered_pragmas (struct pragma_entry *pe)
1386 int ct = 0;
1387 for (; pe != NULL; pe = pe->next)
1389 if (pe->is_nspace)
1390 ct += count_registered_pragmas (pe->u.space);
1391 ct++;
1393 return ct;
1396 /* Save into SD the names of the registered pragmas referenced by PE,
1397 and return a pointer to the next free space in SD. */
1399 static char **
1400 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1402 for (; pe != NULL; pe = pe->next)
1404 if (pe->is_nspace)
1405 sd = save_registered_pragmas (pe->u.space, sd);
1406 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1407 HT_LEN (&pe->pragma->ident),
1408 HT_LEN (&pe->pragma->ident) + 1);
1410 return sd;
1413 /* Return a newly-allocated array which saves the names of the
1414 registered pragmas. */
1416 char **
1417 _cpp_save_pragma_names (cpp_reader *pfile)
1419 int ct = count_registered_pragmas (pfile->pragmas);
1420 char **result = XNEWVEC (char *, ct);
1421 (void) save_registered_pragmas (pfile->pragmas, result);
1422 return result;
1425 /* Restore from SD the names of the registered pragmas referenced by PE,
1426 and return a pointer to the next unused name in SD. */
1428 static char **
1429 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1430 char **sd)
1432 for (; pe != NULL; pe = pe->next)
1434 if (pe->is_nspace)
1435 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1436 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1437 free (*sd);
1438 sd++;
1440 return sd;
1443 /* Restore the names of the registered pragmas from SAVED. */
1445 void
1446 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1448 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1449 free (saved);
1452 /* Pragmata handling. We handle some, and pass the rest on to the
1453 front end. C99 defines three pragmas and says that no macro
1454 expansion is to be performed on them; whether or not macro
1455 expansion happens for other pragmas is implementation defined.
1456 This implementation allows for a mix of both, since GCC did not
1457 traditionally macro expand its (few) pragmas, whereas OpenMP
1458 specifies that macro expansion should happen. */
1459 static void
1460 do_pragma (cpp_reader *pfile)
1462 const struct pragma_entry *p = NULL;
1463 const cpp_token *token, *pragma_token;
1464 location_t pragma_token_virt_loc = 0;
1465 cpp_token ns_token;
1466 unsigned int count = 1;
1468 pfile->state.prevent_expansion++;
1470 pragma_token = token = cpp_get_token_with_location (pfile,
1471 &pragma_token_virt_loc);
1472 ns_token = *token;
1473 if (token->type == CPP_NAME)
1475 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1476 if (p && p->is_nspace)
1478 bool allow_name_expansion = p->allow_expansion;
1479 if (allow_name_expansion)
1480 pfile->state.prevent_expansion--;
1482 token = cpp_get_token (pfile);
1483 if (token->type == CPP_NAME)
1484 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1485 else
1486 p = NULL;
1487 if (allow_name_expansion)
1488 pfile->state.prevent_expansion++;
1489 count = 2;
1493 if (p)
1495 if (p->is_deferred)
1497 pfile->directive_result.src_loc = pragma_token_virt_loc;
1498 pfile->directive_result.type = CPP_PRAGMA;
1499 pfile->directive_result.flags = pragma_token->flags;
1500 pfile->directive_result.val.pragma = p->u.ident;
1501 pfile->state.in_deferred_pragma = true;
1502 pfile->state.pragma_allow_expansion = p->allow_expansion;
1503 if (!p->allow_expansion)
1504 pfile->state.prevent_expansion++;
1506 else
1508 /* Since the handler below doesn't get the line number, that
1509 it might need for diagnostics, make sure it has the right
1510 numbers in place. */
1511 if (pfile->cb.line_change)
1512 (*pfile->cb.line_change) (pfile, pragma_token, false);
1513 if (p->allow_expansion)
1514 pfile->state.prevent_expansion--;
1515 (*p->u.handler) (pfile);
1516 if (p->allow_expansion)
1517 pfile->state.prevent_expansion++;
1520 else if (pfile->cb.def_pragma)
1522 if (count == 1 || pfile->context->prev == NULL)
1523 _cpp_backup_tokens (pfile, count);
1524 else
1526 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1527 won't allow backing 2 tokens. */
1528 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1529 reads both tokens, we could perhaps free it, but if it doesn't,
1530 we don't know the exact lifespan. */
1531 cpp_token *toks = XNEWVEC (cpp_token, 2);
1532 toks[0] = ns_token;
1533 toks[0].flags |= NO_EXPAND;
1534 toks[1] = *token;
1535 toks[1].flags |= NO_EXPAND;
1536 _cpp_push_token_context (pfile, NULL, toks, 2);
1538 pfile->cb.def_pragma (pfile, pfile->directive_line);
1541 pfile->state.prevent_expansion--;
1544 /* Handle #pragma once. */
1545 static void
1546 do_pragma_once (cpp_reader *pfile)
1548 if (cpp_in_primary_file (pfile))
1549 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1551 check_eol (pfile, false);
1552 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1555 /* Handle #pragma push_macro(STRING). */
1556 static void
1557 do_pragma_push_macro (cpp_reader *pfile)
1559 cpp_hashnode *node;
1560 size_t defnlen;
1561 const uchar *defn = NULL;
1562 char *macroname, *dest;
1563 const char *limit, *src;
1564 const cpp_token *txt;
1565 struct def_pragma_macro *c;
1567 txt = get__Pragma_string (pfile);
1568 if (!txt)
1570 location_t src_loc = pfile->cur_token[-1].src_loc;
1571 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1572 "invalid #pragma push_macro directive");
1573 check_eol (pfile, false);
1574 skip_rest_of_line (pfile);
1575 return;
1577 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1578 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1579 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1580 while (src < limit)
1582 /* We know there is a character following the backslash. */
1583 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1584 src++;
1585 *dest++ = *src++;
1587 *dest = 0;
1588 check_eol (pfile, false);
1589 skip_rest_of_line (pfile);
1590 c = XNEW (struct def_pragma_macro);
1591 memset (c, 0, sizeof (struct def_pragma_macro));
1592 c->name = XNEWVAR (char, strlen (macroname) + 1);
1593 strcpy (c->name, macroname);
1594 c->next = pfile->pushed_macros;
1595 node = _cpp_lex_identifier (pfile, c->name);
1596 if (node->type == NT_VOID)
1597 c->is_undef = 1;
1598 else if (node->type == NT_BUILTIN_MACRO)
1599 c->is_builtin = 1;
1600 else
1602 defn = cpp_macro_definition (pfile, node);
1603 defnlen = ustrlen (defn);
1604 c->definition = XNEWVEC (uchar, defnlen + 2);
1605 c->definition[defnlen] = '\n';
1606 c->definition[defnlen + 1] = 0;
1607 c->line = node->value.macro->line;
1608 c->syshdr = node->value.macro->syshdr;
1609 c->used = node->value.macro->used;
1610 memcpy (c->definition, defn, defnlen);
1613 pfile->pushed_macros = c;
1616 /* Handle #pragma pop_macro(STRING). */
1617 static void
1618 do_pragma_pop_macro (cpp_reader *pfile)
1620 char *macroname, *dest;
1621 const char *limit, *src;
1622 const cpp_token *txt;
1623 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1624 txt = get__Pragma_string (pfile);
1625 if (!txt)
1627 location_t src_loc = pfile->cur_token[-1].src_loc;
1628 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1629 "invalid #pragma pop_macro directive");
1630 check_eol (pfile, false);
1631 skip_rest_of_line (pfile);
1632 return;
1634 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1635 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1636 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1637 while (src < limit)
1639 /* We know there is a character following the backslash. */
1640 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1641 src++;
1642 *dest++ = *src++;
1644 *dest = 0;
1645 check_eol (pfile, false);
1646 skip_rest_of_line (pfile);
1648 while (c != NULL)
1650 if (!strcmp (c->name, macroname))
1652 if (!l)
1653 pfile->pushed_macros = c->next;
1654 else
1655 l->next = c->next;
1656 cpp_pop_definition (pfile, c);
1657 free (c->definition);
1658 free (c->name);
1659 free (c);
1660 break;
1662 l = c;
1663 c = c->next;
1667 /* Handle #pragma GCC poison, to poison one or more identifiers so
1668 that the lexer produces a hard error for each subsequent usage. */
1669 static void
1670 do_pragma_poison (cpp_reader *pfile)
1672 const cpp_token *tok;
1673 cpp_hashnode *hp;
1675 pfile->state.poisoned_ok = 1;
1676 for (;;)
1678 tok = _cpp_lex_token (pfile);
1679 if (tok->type == CPP_EOF)
1680 break;
1681 if (tok->type != CPP_NAME)
1683 cpp_error (pfile, CPP_DL_ERROR,
1684 "invalid #pragma GCC poison directive");
1685 break;
1688 hp = tok->val.node.node;
1689 if (hp->flags & NODE_POISONED)
1690 continue;
1692 if (cpp_macro_p (hp))
1693 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1694 NODE_NAME (hp));
1695 _cpp_free_definition (hp);
1696 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1698 pfile->state.poisoned_ok = 0;
1701 /* Mark the current header as a system header. This will suppress
1702 some categories of warnings (notably those from -pedantic). It is
1703 intended for use in system libraries that cannot be implemented in
1704 conforming C, but cannot be certain that their headers appear in a
1705 system include directory. To prevent abuse, it is rejected in the
1706 primary source file. */
1707 static void
1708 do_pragma_system_header (cpp_reader *pfile)
1710 if (cpp_in_primary_file (pfile))
1711 cpp_error (pfile, CPP_DL_WARNING,
1712 "#pragma system_header ignored outside include file");
1713 else
1715 check_eol (pfile, false);
1716 skip_rest_of_line (pfile);
1717 cpp_make_system_header (pfile, 1, 0);
1721 /* Check the modified date of the current include file against a specified
1722 file. Issue a diagnostic, if the specified file is newer. We use this to
1723 determine if a fixed header should be refixed. */
1724 static void
1725 do_pragma_dependency (cpp_reader *pfile)
1727 const char *fname;
1728 int angle_brackets, ordering;
1729 location_t location;
1731 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1732 if (!fname)
1733 return;
1735 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1736 if (ordering < 0)
1737 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1738 else if (ordering > 0)
1740 cpp_error (pfile, CPP_DL_WARNING,
1741 "current file is older than %s", fname);
1742 if (cpp_get_token (pfile)->type != CPP_EOF)
1744 _cpp_backup_tokens (pfile, 1);
1745 do_diagnostic (pfile, CPP_DL_WARNING, CPP_W_NONE, 0);
1749 free ((void *) fname);
1752 /* Issue a diagnostic with the message taken from the pragma. If
1753 ERROR is true, the diagnostic is a warning, otherwise, it is an
1754 error. */
1755 static void
1756 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1758 const cpp_token *tok = _cpp_lex_token (pfile);
1759 cpp_string str;
1760 if (tok->type != CPP_STRING
1761 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1762 CPP_STRING)
1763 || str.len == 0)
1765 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1766 error ? "error" : "warning");
1767 return;
1769 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1770 "%s", str.text);
1771 free ((void *)str.text);
1774 /* Issue a warning diagnostic. */
1775 static void
1776 do_pragma_warning (cpp_reader *pfile)
1778 do_pragma_warning_or_error (pfile, false);
1781 /* Issue an error diagnostic. */
1782 static void
1783 do_pragma_error (cpp_reader *pfile)
1785 do_pragma_warning_or_error (pfile, true);
1788 /* Get a token but skip padding. */
1789 static const cpp_token *
1790 get_token_no_padding (cpp_reader *pfile)
1792 for (;;)
1794 const cpp_token *result = cpp_get_token (pfile);
1795 if (result->type != CPP_PADDING)
1796 return result;
1800 /* Check syntax is "(string-literal)". Returns the string on success,
1801 or NULL on failure. */
1802 static const cpp_token *
1803 get__Pragma_string (cpp_reader *pfile)
1805 const cpp_token *string;
1806 const cpp_token *paren;
1808 paren = get_token_no_padding (pfile);
1809 if (paren->type == CPP_EOF)
1810 _cpp_backup_tokens (pfile, 1);
1811 if (paren->type != CPP_OPEN_PAREN)
1812 return NULL;
1814 string = get_token_no_padding (pfile);
1815 if (string->type == CPP_EOF)
1816 _cpp_backup_tokens (pfile, 1);
1817 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1818 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1819 && string->type != CPP_UTF8STRING)
1820 return NULL;
1822 paren = get_token_no_padding (pfile);
1823 if (paren->type == CPP_EOF)
1824 _cpp_backup_tokens (pfile, 1);
1825 if (paren->type != CPP_CLOSE_PAREN)
1826 return NULL;
1828 return string;
1831 /* Destringize IN into a temporary buffer, by removing the first \ of
1832 \" and \\ sequences, and process the result as a #pragma directive. */
1833 static void
1834 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1835 location_t expansion_loc)
1837 const unsigned char *src, *limit;
1838 char *dest, *result;
1839 cpp_context *saved_context;
1840 cpp_token *saved_cur_token;
1841 tokenrun *saved_cur_run;
1842 cpp_token *toks;
1843 int count;
1844 const struct directive *save_directive;
1846 dest = result = (char *) alloca (in->len - 1);
1847 src = in->text + 1 + (in->text[0] == 'L');
1848 limit = in->text + in->len - 1;
1849 while (src < limit)
1851 /* We know there is a character following the backslash. */
1852 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1853 src++;
1854 *dest++ = *src++;
1856 *dest = '\n';
1858 /* Ugh; an awful kludge. We are really not set up to be lexing
1859 tokens when in the middle of a macro expansion. Use a new
1860 context to force cpp_get_token to lex, and so skip_rest_of_line
1861 doesn't go beyond the end of the text. Also, remember the
1862 current lexing position so we can return to it later.
1864 Something like line-at-a-time lexing should remove the need for
1865 this. */
1866 saved_context = pfile->context;
1867 saved_cur_token = pfile->cur_token;
1868 saved_cur_run = pfile->cur_run;
1870 pfile->context = XCNEW (cpp_context);
1872 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1873 until we've read all of the tokens that we want. */
1874 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1875 /* from_stage3 */ true);
1876 /* ??? Antique Disgusting Hack. What does this do? */
1877 if (pfile->buffer->prev)
1878 pfile->buffer->file = pfile->buffer->prev->file;
1880 start_directive (pfile);
1881 _cpp_clean_line (pfile);
1882 save_directive = pfile->directive;
1883 pfile->directive = &dtable[T_PRAGMA];
1884 do_pragma (pfile);
1885 end_directive (pfile, 1);
1886 pfile->directive = save_directive;
1888 /* We always insert at least one token, the directive result. It'll
1889 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1890 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1892 /* If we're not handling the pragma internally, read all of the tokens from
1893 the string buffer now, while the string buffer is still installed. */
1894 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1895 to me what the true lifespan of the tokens are. It would appear that
1896 the lifespan is the entire parse of the main input stream, in which case
1897 this may not be wrong. */
1898 if (pfile->directive_result.type == CPP_PRAGMA)
1900 int maxcount;
1902 count = 1;
1903 maxcount = 50;
1904 toks = XNEWVEC (cpp_token, maxcount);
1905 toks[0] = pfile->directive_result;
1909 if (count == maxcount)
1911 maxcount = maxcount * 3 / 2;
1912 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1914 toks[count] = *cpp_get_token (pfile);
1915 /* _Pragma is a builtin, so we're not within a macro-map, and so
1916 the token locations are set to bogus ordinary locations
1917 near to, but after that of the "_Pragma".
1918 Paper over this by setting them equal to the location of the
1919 _Pragma itself (PR preprocessor/69126). */
1920 toks[count].src_loc = expansion_loc;
1921 /* Macros have been already expanded by cpp_get_token
1922 if the pragma allowed expansion. */
1923 toks[count++].flags |= NO_EXPAND;
1925 while (toks[count-1].type != CPP_PRAGMA_EOL);
1927 else
1929 count = 1;
1930 toks = XNEW (cpp_token);
1931 toks[0] = pfile->directive_result;
1933 /* If we handled the entire pragma internally, make sure we get the
1934 line number correct for the next token. */
1935 if (pfile->cb.line_change)
1936 pfile->cb.line_change (pfile, pfile->cur_token, false);
1939 /* Finish inlining run_directive. */
1940 pfile->buffer->file = NULL;
1941 _cpp_pop_buffer (pfile);
1943 /* Reset the old macro state before ... */
1944 XDELETE (pfile->context);
1945 pfile->context = saved_context;
1946 pfile->cur_token = saved_cur_token;
1947 pfile->cur_run = saved_cur_run;
1949 /* ... inserting the new tokens we collected. */
1950 _cpp_push_token_context (pfile, NULL, toks, count);
1953 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1955 _cpp_do__Pragma (cpp_reader *pfile, location_t expansion_loc)
1957 const cpp_token *string = get__Pragma_string (pfile);
1958 pfile->directive_result.type = CPP_PADDING;
1960 if (string)
1962 destringize_and_run (pfile, &string->val.str, expansion_loc);
1963 return 1;
1965 cpp_error (pfile, CPP_DL_ERROR,
1966 "_Pragma takes a parenthesized string literal");
1967 return 0;
1970 /* Handle #ifdef. */
1971 static void
1972 do_ifdef (cpp_reader *pfile)
1974 int skip = 1;
1976 if (! pfile->state.skipping)
1978 cpp_hashnode *node = lex_macro_node (pfile, false);
1980 if (node)
1982 skip = !_cpp_defined_macro_p (node);
1983 _cpp_mark_macro_used (node);
1984 _cpp_maybe_notify_macro_use (pfile, node);
1985 if (pfile->cb.used)
1986 pfile->cb.used (pfile, pfile->directive_line, node);
1987 check_eol (pfile, false);
1991 push_conditional (pfile, skip, T_IFDEF, 0);
1994 /* Handle #ifndef. */
1995 static void
1996 do_ifndef (cpp_reader *pfile)
1998 int skip = 1;
1999 cpp_hashnode *node = 0;
2001 if (! pfile->state.skipping)
2003 node = lex_macro_node (pfile, false);
2005 if (node)
2007 /* Do not treat conditional macros as being defined. This is due to
2008 the powerpc port using conditional macros for 'vector', 'bool',
2009 and 'pixel' to act as conditional keywords. This messes up tests
2010 like #ifndef bool. */
2011 skip = _cpp_defined_macro_p (node);
2012 _cpp_mark_macro_used (node);
2013 _cpp_maybe_notify_macro_use (pfile, node);
2014 if (pfile->cb.used)
2015 pfile->cb.used (pfile, pfile->directive_line, node);
2016 check_eol (pfile, false);
2020 push_conditional (pfile, skip, T_IFNDEF, node);
2023 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2024 pfile->mi_ind_cmacro so we can handle multiple-include
2025 optimizations. If macro expansion occurs in the expression, we
2026 cannot treat it as a controlling conditional, since the expansion
2027 could change in the future. That is handled by cpp_get_token. */
2028 static void
2029 do_if (cpp_reader *pfile)
2031 int skip = 1;
2033 if (! pfile->state.skipping)
2034 skip = _cpp_parse_expr (pfile, true) == false;
2036 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2039 /* Flip skipping state if appropriate and continue without changing
2040 if_stack; this is so that the error message for missing #endif's
2041 etc. will point to the original #if. */
2042 static void
2043 do_else (cpp_reader *pfile)
2045 cpp_buffer *buffer = pfile->buffer;
2046 struct if_stack *ifs = buffer->if_stack;
2048 if (ifs == NULL)
2049 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2050 else
2052 if (ifs->type == T_ELSE)
2054 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2055 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2056 "the conditional began here");
2058 ifs->type = T_ELSE;
2060 /* Skip any future (erroneous) #elses or #elifs. */
2061 pfile->state.skipping = ifs->skip_elses;
2062 ifs->skip_elses = true;
2064 /* Invalidate any controlling macro. */
2065 ifs->mi_cmacro = 0;
2067 /* Only check EOL if was not originally skipping. */
2068 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2069 check_eol_endif_labels (pfile);
2073 /* Handle a #elif directive by not changing if_stack either. See the
2074 comment above do_else. */
2075 static void
2076 do_elif (cpp_reader *pfile)
2078 cpp_buffer *buffer = pfile->buffer;
2079 struct if_stack *ifs = buffer->if_stack;
2081 if (ifs == NULL)
2082 cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2083 else
2085 if (ifs->type == T_ELSE)
2087 cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2088 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2089 "the conditional began here");
2091 ifs->type = T_ELIF;
2093 /* See DR#412: "Only the first group whose control condition
2094 evaluates to true (nonzero) is processed; any following groups
2095 are skipped and their controlling directives are processed as
2096 if they were in a group that is skipped." */
2097 if (ifs->skip_elses)
2098 pfile->state.skipping = 1;
2099 else
2101 pfile->state.skipping = ! _cpp_parse_expr (pfile, false);
2102 ifs->skip_elses = ! pfile->state.skipping;
2105 /* Invalidate any controlling macro. */
2106 ifs->mi_cmacro = 0;
2110 /* #endif pops the if stack and resets pfile->state.skipping. */
2111 static void
2112 do_endif (cpp_reader *pfile)
2114 cpp_buffer *buffer = pfile->buffer;
2115 struct if_stack *ifs = buffer->if_stack;
2117 if (ifs == NULL)
2118 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2119 else
2121 /* Only check EOL if was not originally skipping. */
2122 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2123 check_eol_endif_labels (pfile);
2125 /* If potential control macro, we go back outside again. */
2126 if (ifs->next == 0 && ifs->mi_cmacro)
2128 pfile->mi_valid = true;
2129 pfile->mi_cmacro = ifs->mi_cmacro;
2132 buffer->if_stack = ifs->next;
2133 pfile->state.skipping = ifs->was_skipping;
2134 obstack_free (&pfile->buffer_ob, ifs);
2138 /* Push an if_stack entry for a preprocessor conditional, and set
2139 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2140 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2141 we need to check here that we are at the top of the file. */
2142 static void
2143 push_conditional (cpp_reader *pfile, int skip, int type,
2144 const cpp_hashnode *cmacro)
2146 struct if_stack *ifs;
2147 cpp_buffer *buffer = pfile->buffer;
2149 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2150 ifs->line = pfile->directive_line;
2151 ifs->next = buffer->if_stack;
2152 ifs->skip_elses = pfile->state.skipping || !skip;
2153 ifs->was_skipping = pfile->state.skipping;
2154 ifs->type = type;
2155 /* This condition is effectively a test for top-of-file. */
2156 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2157 ifs->mi_cmacro = cmacro;
2158 else
2159 ifs->mi_cmacro = 0;
2161 pfile->state.skipping = skip;
2162 buffer->if_stack = ifs;
2165 /* Read the tokens of the answer into the macro pool, in a directive
2166 of type TYPE. Only commit the memory if we intend it as permanent
2167 storage, i.e. the #assert case. Returns 0 on success, and sets
2168 ANSWERP to point to the answer. PRED_LOC is the location of the
2169 predicate. */
2170 static bool
2171 parse_answer (cpp_reader *pfile, int type, location_t pred_loc,
2172 cpp_macro **answer_ptr)
2174 /* In a conditional, it is legal to not have an open paren. We
2175 should save the following token in this case. */
2176 const cpp_token *paren = cpp_get_token (pfile);
2178 /* If not a paren, see if we're OK. */
2179 if (paren->type != CPP_OPEN_PAREN)
2181 /* In a conditional no answer is a test for any answer. It
2182 could be followed by any token. */
2183 if (type == T_IF)
2185 _cpp_backup_tokens (pfile, 1);
2186 return true;
2189 /* #unassert with no answer is valid - it removes all answers. */
2190 if (type == T_UNASSERT && paren->type == CPP_EOF)
2191 return true;
2193 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2194 "missing '(' after predicate");
2195 return false;
2198 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2199 _cpp_reserve_room (pfile, 0,
2200 sizeof (cpp_macro)));
2201 answer->parm.next = NULL;
2202 unsigned count = 0;
2203 for (;;)
2205 const cpp_token *token = cpp_get_token (pfile);
2207 if (token->type == CPP_CLOSE_PAREN)
2208 break;
2210 if (token->type == CPP_EOF)
2212 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2213 return false;
2216 answer = (cpp_macro *)_cpp_reserve_room
2217 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2218 sizeof (cpp_token));
2219 answer->exp.tokens[count++] = *token;
2222 if (!count)
2224 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2225 return false;
2228 /* Drop whitespace at start, for answer equivalence purposes. */
2229 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2231 answer->count = count;
2232 *answer_ptr = answer;
2234 return true;
2237 /* Parses an assertion directive of type TYPE, returning a pointer to
2238 the hash node of the predicate, or 0 on error. The node is
2239 guaranteed to be disjoint from the macro namespace, so can only
2240 have type 'NT_VOID'. If an answer was supplied, it is placed in
2241 *ANSWER_PTR, which is otherwise set to 0. */
2242 static cpp_hashnode *
2243 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2245 cpp_hashnode *result = 0;
2247 /* We don't expand predicates or answers. */
2248 pfile->state.prevent_expansion++;
2250 *answer_ptr = NULL;
2252 const cpp_token *predicate = cpp_get_token (pfile);
2253 if (predicate->type == CPP_EOF)
2254 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2255 else if (predicate->type != CPP_NAME)
2256 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2257 "predicate must be an identifier");
2258 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2260 unsigned int len = NODE_LEN (predicate->val.node.node);
2261 unsigned char *sym = (unsigned char *) alloca (len + 1);
2263 /* Prefix '#' to get it out of macro namespace. */
2264 sym[0] = '#';
2265 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2266 result = cpp_lookup (pfile, sym, len + 1);
2269 pfile->state.prevent_expansion--;
2271 return result;
2274 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2275 or a pointer to NULL if the answer is not in the chain. */
2276 static cpp_macro **
2277 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2279 unsigned int i;
2280 cpp_macro **result = NULL;
2282 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2284 cpp_macro *answer = *result;
2286 if (answer->count == candidate->count)
2288 for (i = 0; i < answer->count; i++)
2289 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2290 &candidate->exp.tokens[i]))
2291 break;
2293 if (i == answer->count)
2294 break;
2298 return result;
2301 /* Test an assertion within a preprocessor conditional. Returns
2302 nonzero on failure, zero on success. On success, the result of
2303 the test is written into VALUE, otherwise the value 0. */
2305 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2307 cpp_macro *answer;
2308 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2310 /* For recovery, an erroneous assertion expression is handled as a
2311 failing assertion. */
2312 *value = 0;
2314 if (node)
2316 if (node->value.answers)
2317 *value = !answer || *find_answer (node, answer);
2319 else if (pfile->cur_token[-1].type == CPP_EOF)
2320 _cpp_backup_tokens (pfile, 1);
2322 /* We don't commit the memory for the answer - it's temporary only. */
2323 return node == 0;
2326 /* Handle #assert. */
2327 static void
2328 do_assert (cpp_reader *pfile)
2330 cpp_macro *answer;
2331 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2333 if (node)
2335 /* Place the new answer in the answer list. First check there
2336 is not a duplicate. */
2337 if (*find_answer (node, answer))
2339 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2340 NODE_NAME (node) + 1);
2341 return;
2344 /* Commit or allocate storage for the answer. */
2345 answer = (cpp_macro *)_cpp_commit_buff
2346 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2347 + sizeof (cpp_token) * answer->count);
2349 /* Chain into the list. */
2350 answer->parm.next = node->value.answers;
2351 node->value.answers = answer;
2353 check_eol (pfile, false);
2357 /* Handle #unassert. */
2358 static void
2359 do_unassert (cpp_reader *pfile)
2361 cpp_macro *answer;
2362 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2364 /* It isn't an error to #unassert something that isn't asserted. */
2365 if (node)
2367 if (answer)
2369 cpp_macro **p = find_answer (node, answer);
2371 /* Remove the assert from the list. */
2372 if (cpp_macro *temp = *p)
2373 *p = temp->parm.next;
2375 check_eol (pfile, false);
2377 else
2378 _cpp_free_definition (node);
2381 /* We don't commit the memory for the answer - it's temporary only. */
2384 /* These are for -D, -U, -A. */
2386 /* Process the string STR as if it appeared as the body of a #define.
2387 If STR is just an identifier, define it with value 1.
2388 If STR has anything after the identifier, then it should
2389 be identifier=definition. */
2390 void
2391 cpp_define (cpp_reader *pfile, const char *str)
2393 char *buf;
2394 const char *p;
2395 size_t count;
2397 /* Copy the entire option so we can modify it.
2398 Change the first "=" in the string to a space. If there is none,
2399 tack " 1" on the end. */
2401 count = strlen (str);
2402 buf = (char *) alloca (count + 3);
2403 memcpy (buf, str, count);
2405 p = strchr (str, '=');
2406 if (p)
2407 buf[p - str] = ' ';
2408 else
2410 buf[count++] = ' ';
2411 buf[count++] = '1';
2413 buf[count] = '\n';
2415 run_directive (pfile, T_DEFINE, buf, count);
2419 /* Use to build macros to be run through cpp_define() as
2420 described above.
2421 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2423 void
2424 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2426 char *ptr;
2428 va_list ap;
2429 va_start (ap, fmt);
2430 ptr = xvasprintf (fmt, ap);
2431 va_end (ap);
2433 cpp_define (pfile, ptr);
2434 free (ptr);
2438 /* Slight variant of the above for use by initialize_builtins. */
2439 void
2440 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2442 size_t len = strlen (str);
2443 char *buf = (char *) alloca (len + 1);
2444 memcpy (buf, str, len);
2445 buf[len] = '\n';
2446 run_directive (pfile, T_DEFINE, buf, len);
2449 /* Process MACRO as if it appeared as the body of an #undef. */
2450 void
2451 cpp_undef (cpp_reader *pfile, const char *macro)
2453 size_t len = strlen (macro);
2454 char *buf = (char *) alloca (len + 1);
2455 memcpy (buf, macro, len);
2456 buf[len] = '\n';
2457 run_directive (pfile, T_UNDEF, buf, len);
2460 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2461 or first element is zero, then the macro should be undefined. */
2462 static void
2463 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2465 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2466 if (node == NULL)
2467 return;
2469 if (pfile->cb.before_define)
2470 pfile->cb.before_define (pfile);
2472 if (cpp_macro_p (node))
2474 if (pfile->cb.undef)
2475 pfile->cb.undef (pfile, pfile->directive_line, node);
2476 if (CPP_OPTION (pfile, warn_unused_macros))
2477 _cpp_warn_if_unused_macro (pfile, node, NULL);
2478 _cpp_free_definition (node);
2481 if (c->is_undef)
2482 return;
2483 if (c->is_builtin)
2485 _cpp_restore_special_builtin (pfile, c);
2486 return;
2490 size_t namelen;
2491 const uchar *dn;
2492 cpp_hashnode *h = NULL;
2493 cpp_buffer *nbuf;
2495 namelen = ustrcspn (c->definition, "( \n");
2496 h = cpp_lookup (pfile, c->definition, namelen);
2497 dn = c->definition + namelen;
2499 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2500 if (nbuf != NULL)
2502 _cpp_clean_line (pfile);
2503 nbuf->sysp = 1;
2504 if (!_cpp_create_definition (pfile, h))
2505 abort ();
2506 _cpp_pop_buffer (pfile);
2508 else
2509 abort ();
2510 h->value.macro->line = c->line;
2511 h->value.macro->syshdr = c->syshdr;
2512 h->value.macro->used = c->used;
2516 /* Process the string STR as if it appeared as the body of a #assert. */
2517 void
2518 cpp_assert (cpp_reader *pfile, const char *str)
2520 handle_assertion (pfile, str, T_ASSERT);
2523 /* Process STR as if it appeared as the body of an #unassert. */
2524 void
2525 cpp_unassert (cpp_reader *pfile, const char *str)
2527 handle_assertion (pfile, str, T_UNASSERT);
2530 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2531 static void
2532 handle_assertion (cpp_reader *pfile, const char *str, int type)
2534 size_t count = strlen (str);
2535 const char *p = strchr (str, '=');
2537 /* Copy the entire option so we can modify it. Change the first
2538 "=" in the string to a '(', and tack a ')' on the end. */
2539 char *buf = (char *) alloca (count + 2);
2541 memcpy (buf, str, count);
2542 if (p)
2544 buf[p - str] = '(';
2545 buf[count++] = ')';
2547 buf[count] = '\n';
2548 str = buf;
2550 run_directive (pfile, type, str, count);
2553 /* The options structure. */
2554 cpp_options *
2555 cpp_get_options (cpp_reader *pfile)
2557 return &pfile->opts;
2560 /* The callbacks structure. */
2561 cpp_callbacks *
2562 cpp_get_callbacks (cpp_reader *pfile)
2564 return &pfile->cb;
2567 /* Copy the given callbacks structure to our own. */
2568 void
2569 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2571 pfile->cb = *cb;
2574 /* The dependencies structure. (Creates one if it hasn't already been.) */
2575 class mkdeps *
2576 cpp_get_deps (cpp_reader *pfile)
2578 if (!pfile->deps)
2579 pfile->deps = deps_init ();
2580 return pfile->deps;
2583 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2584 doesn't fail. It does not generate a file change call back; that
2585 is the responsibility of the caller. */
2586 cpp_buffer *
2587 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2588 int from_stage3)
2590 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2592 /* Clears, amongst other things, if_stack and mi_cmacro. */
2593 memset (new_buffer, 0, sizeof (cpp_buffer));
2595 new_buffer->next_line = new_buffer->buf = buffer;
2596 new_buffer->rlimit = buffer + len;
2597 new_buffer->from_stage3 = from_stage3;
2598 new_buffer->prev = pfile->buffer;
2599 new_buffer->need_line = true;
2601 pfile->buffer = new_buffer;
2603 return new_buffer;
2606 /* Pops a single buffer, with a file change call-back if appropriate.
2607 Then pushes the next -include file, if any remain. */
2608 void
2609 _cpp_pop_buffer (cpp_reader *pfile)
2611 cpp_buffer *buffer = pfile->buffer;
2612 struct _cpp_file *inc = buffer->file;
2613 struct if_stack *ifs;
2614 const unsigned char *to_free;
2616 /* Walk back up the conditional stack till we reach its level at
2617 entry to this file, issuing error messages. */
2618 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2619 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2620 "unterminated #%s", dtable[ifs->type].name);
2622 /* In case of a missing #endif. */
2623 pfile->state.skipping = 0;
2625 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2626 pfile->buffer = buffer->prev;
2628 to_free = buffer->to_free;
2629 free (buffer->notes);
2631 /* Free the buffer object now; we may want to push a new buffer
2632 in _cpp_push_next_include_file. */
2633 obstack_free (&pfile->buffer_ob, buffer);
2635 if (inc)
2637 _cpp_pop_file_buffer (pfile, inc, to_free);
2639 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2641 else if (to_free)
2642 free ((void *)to_free);
2645 /* Enter all recognized directives in the hash table. */
2646 void
2647 _cpp_init_directives (cpp_reader *pfile)
2649 for (int i = 0; i < N_DIRECTIVES; i++)
2651 cpp_hashnode *node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2652 node->is_directive = 1;
2653 node->directive_index = i;
2657 /* Extract header file from a bracket include. Parsing starts after '<'.
2658 The string is malloced and must be freed by the caller. */
2659 char *
2660 _cpp_bracket_include(cpp_reader *pfile)
2662 return glue_header_name (pfile);