Fix declarations of _DINFINITY, _SINFINITY and _SQNAN
[official-gcc.git] / libcpp / directives.cc
blobf804a441f394f1a5830d412b6e41a478a1bd69b5
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2022 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. STDC2X directives come from the C2X standard. EXTENSION
60 directives are extensions. */
61 #define KANDR 0
62 #define STDC89 1
63 #define STDC2X 2
64 #define EXTENSION 3
66 /* Values for the flags field of struct directive. COND indicates a
67 conditional; IF_COND an opening conditional. INCL means to treat
68 "..." and <...> as q-char and h-char sequences respectively. IN_I
69 means this directive should be handled even if -fpreprocessed is in
70 effect (these are the directives with callback hooks).
72 EXPAND is set on directives that are always macro-expanded.
74 ELIFDEF is set on directives that are only handled for standards with the
75 #elifdef / #elifndef feature. */
76 #define COND (1 << 0)
77 #define IF_COND (1 << 1)
78 #define INCL (1 << 2)
79 #define IN_I (1 << 3)
80 #define EXPAND (1 << 4)
81 #define DEPRECATED (1 << 5)
82 #define ELIFDEF (1 << 6)
84 /* Defines one #-directive, including how to handle it. */
85 typedef void (*directive_handler) (cpp_reader *);
86 typedef struct directive directive;
87 struct directive
89 directive_handler handler; /* Function to handle directive. */
90 const uchar *name; /* Name of directive. */
91 unsigned short length; /* Length of name. */
92 unsigned char origin; /* Origin of directive. */
93 unsigned char flags; /* Flags describing this directive. */
96 /* Forward declarations. */
98 static void skip_rest_of_line (cpp_reader *);
99 static void check_eol (cpp_reader *, bool);
100 static void start_directive (cpp_reader *);
101 static void prepare_directive_trad (cpp_reader *);
102 static void end_directive (cpp_reader *, int);
103 static void directive_diagnostics (cpp_reader *, const directive *, int);
104 static void run_directive (cpp_reader *, int, const char *, size_t);
105 static char *glue_header_name (cpp_reader *);
106 static const char *parse_include (cpp_reader *, int *, const cpp_token ***,
107 location_t *);
108 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
109 static unsigned int read_flag (cpp_reader *, unsigned int);
110 static bool strtolinenum (const uchar *, size_t, linenum_type *, bool *);
111 static void do_diagnostic (cpp_reader *, enum cpp_diagnostic_level code,
112 enum cpp_warning_reason reason, int);
113 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
114 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
115 static void do_include_common (cpp_reader *, enum include_type);
116 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
117 const cpp_hashnode *);
118 static int count_registered_pragmas (struct pragma_entry *);
119 static char ** save_registered_pragmas (struct pragma_entry *, char **);
120 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
121 char **);
122 static void do_pragma_once (cpp_reader *);
123 static void do_pragma_poison (cpp_reader *);
124 static void do_pragma_system_header (cpp_reader *);
125 static void do_pragma_dependency (cpp_reader *);
126 static void do_pragma_warning_or_error (cpp_reader *, bool error);
127 static void do_pragma_warning (cpp_reader *);
128 static void do_pragma_error (cpp_reader *);
129 static void do_linemarker (cpp_reader *);
130 static const cpp_token *get_token_no_padding (cpp_reader *);
131 static const cpp_token *get__Pragma_string (cpp_reader *);
132 static void destringize_and_run (cpp_reader *, const cpp_string *,
133 location_t);
134 static bool parse_answer (cpp_reader *, int, location_t, cpp_macro **);
135 static cpp_hashnode *parse_assertion (cpp_reader *, int, cpp_macro **);
136 static cpp_macro **find_answer (cpp_hashnode *, const cpp_macro *);
137 static void handle_assertion (cpp_reader *, const char *, int);
138 static void do_pragma_push_macro (cpp_reader *);
139 static void do_pragma_pop_macro (cpp_reader *);
140 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
142 /* This is the table of directive handlers. All extensions other than
143 #warning, #include_next, and #import are deprecated. The name is
144 where the extension appears to have come from. */
146 #define DIRECTIVE_TABLE \
147 D(define, T_DEFINE = 0, KANDR, IN_I) \
148 D(include, T_INCLUDE, KANDR, INCL | EXPAND) \
149 D(endif, T_ENDIF, KANDR, COND) \
150 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) \
151 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) \
152 D(else, T_ELSE, KANDR, COND) \
153 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) \
154 D(undef, T_UNDEF, KANDR, IN_I) \
155 D(line, T_LINE, KANDR, EXPAND) \
156 D(elif, T_ELIF, STDC89, COND | EXPAND) \
157 D(elifdef, T_ELIFDEF, STDC2X, COND | ELIFDEF) \
158 D(elifndef, T_ELIFNDEF, STDC2X, COND | ELIFDEF) \
159 D(error, T_ERROR, STDC89, 0) \
160 D(pragma, T_PRAGMA, STDC89, IN_I) \
161 D(warning, T_WARNING, EXTENSION, 0) \
162 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) \
163 D(ident, T_IDENT, EXTENSION, IN_I) \
164 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* ObjC */ \
165 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* SVR4 */ \
166 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* SVR4 */ \
167 D(sccs, T_SCCS, EXTENSION, IN_I) /* SVR4? */
169 /* #sccs is synonymous with #ident. */
170 #define do_sccs do_ident
172 /* Use the table to generate a series of prototypes, an enum for the
173 directive names, and an array of directive handlers. */
175 #define D(name, t, o, f) static void do_##name (cpp_reader *);
176 DIRECTIVE_TABLE
177 #undef D
179 #define D(n, tag, o, f) tag,
180 enum
182 DIRECTIVE_TABLE
183 N_DIRECTIVES
185 #undef D
187 #define D(name, t, origin, flags) \
188 { do_##name, (const uchar *) #name, \
189 sizeof #name - 1, origin, flags },
190 static const directive dtable[] =
192 DIRECTIVE_TABLE
194 #undef D
196 /* A NULL-terminated array of directive names for use
197 when suggesting corrections for misspelled directives. */
198 #define D(name, t, origin, flags) #name,
199 static const char * const directive_names[] = {
200 DIRECTIVE_TABLE
201 NULL
203 #undef D
205 #undef DIRECTIVE_TABLE
207 /* Wrapper struct directive for linemarkers.
208 The origin is more or less true - the original K+R cpp
209 did use this notation in its preprocessed output. */
210 static const directive linemarker_dir =
212 do_linemarker, UC"#", 1, KANDR, IN_I
215 /* Skip any remaining tokens in a directive. */
216 static void
217 skip_rest_of_line (cpp_reader *pfile)
219 /* Discard all stacked contexts. */
220 while (pfile->context->prev)
221 _cpp_pop_context (pfile);
223 /* Sweep up all tokens remaining on the line. */
224 if (! SEEN_EOL ())
225 while (_cpp_lex_token (pfile)->type != CPP_EOF)
229 /* Helper function for check_oel. */
231 static void
232 check_eol_1 (cpp_reader *pfile, bool expand, enum cpp_warning_reason reason)
234 if (! SEEN_EOL () && (expand
235 ? cpp_get_token (pfile)
236 : _cpp_lex_token (pfile))->type != CPP_EOF)
237 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
238 pfile->directive->name);
241 /* Variant of check_eol used for Wendif-labels warnings. */
243 static void
244 check_eol_endif_labels (cpp_reader *pfile)
246 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
249 /* Ensure there are no stray tokens at the end of a directive. If
250 EXPAND is true, tokens macro-expanding to nothing are allowed. */
252 static void
253 check_eol (cpp_reader *pfile, bool expand)
255 check_eol_1 (pfile, expand, CPP_W_NONE);
258 /* Ensure there are no stray tokens other than comments at the end of
259 a directive, and gather the comments. */
260 static const cpp_token **
261 check_eol_return_comments (cpp_reader *pfile)
263 size_t c;
264 size_t capacity = 8;
265 const cpp_token **buf;
267 buf = XNEWVEC (const cpp_token *, capacity);
268 c = 0;
269 if (! SEEN_EOL ())
271 while (1)
273 const cpp_token *tok;
275 tok = _cpp_lex_token (pfile);
276 if (tok->type == CPP_EOF)
277 break;
278 if (tok->type != CPP_COMMENT)
279 cpp_error (pfile, CPP_DL_PEDWARN,
280 "extra tokens at end of #%s directive",
281 pfile->directive->name);
282 else
284 if (c + 1 >= capacity)
286 capacity *= 2;
287 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
289 buf[c] = tok;
290 ++c;
294 buf[c] = NULL;
295 return buf;
298 /* Called when entering a directive, _Pragma or command-line directive. */
299 static void
300 start_directive (cpp_reader *pfile)
302 /* Setup in-directive state. */
303 pfile->state.in_directive = 1;
304 pfile->state.save_comments = 0;
305 pfile->directive_result.type = CPP_PADDING;
307 /* Some handlers need the position of the # for diagnostics. */
308 pfile->directive_line = pfile->line_table->highest_line;
311 /* Called when leaving a directive, _Pragma or command-line directive. */
312 static void
313 end_directive (cpp_reader *pfile, int skip_line)
315 if (CPP_OPTION (pfile, traditional))
317 /* Revert change of prepare_directive_trad. */
318 if (!pfile->state.in_deferred_pragma)
319 pfile->state.prevent_expansion--;
321 if (pfile->directive != &dtable[T_DEFINE])
322 _cpp_remove_overlay (pfile);
324 else if (pfile->state.in_deferred_pragma)
326 /* We don't skip for an assembler #. */
327 else if (skip_line)
329 skip_rest_of_line (pfile);
330 if (!pfile->keep_tokens)
332 pfile->cur_run = &pfile->base_run;
333 pfile->cur_token = pfile->base_run.base;
337 /* Restore state. */
338 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
339 pfile->state.in_directive = 0;
340 pfile->state.in_expression = 0;
341 pfile->state.angled_headers = 0;
342 pfile->directive = 0;
345 /* Prepare to handle the directive in pfile->directive. */
346 static void
347 prepare_directive_trad (cpp_reader *pfile)
349 if (pfile->directive != &dtable[T_DEFINE])
351 bool no_expand = (pfile->directive
352 && ! (pfile->directive->flags & EXPAND));
353 bool was_skipping = pfile->state.skipping;
355 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
356 || pfile->directive == &dtable[T_ELIF]);
357 if (pfile->state.in_expression)
358 pfile->state.skipping = false;
360 if (no_expand)
361 pfile->state.prevent_expansion++;
362 _cpp_scan_out_logical_line (pfile, NULL, false);
363 if (no_expand)
364 pfile->state.prevent_expansion--;
366 pfile->state.skipping = was_skipping;
367 _cpp_overlay_buffer (pfile, pfile->out.base,
368 pfile->out.cur - pfile->out.base);
371 /* Stop ISO C from expanding anything. */
372 pfile->state.prevent_expansion++;
375 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
376 the '#' was indented. */
377 static void
378 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
380 /* Issue -pedantic or deprecated warnings for extensions. We let
381 -pedantic take precedence if both are applicable. */
382 if (! pfile->state.skipping)
384 if (dir->origin == EXTENSION
385 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
386 && CPP_PEDANTIC (pfile))
387 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
388 else if (((dir->flags & DEPRECATED) != 0
389 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
390 && CPP_OPTION (pfile, cpp_warn_deprecated))
391 cpp_warning (pfile, CPP_W_DEPRECATED,
392 "#%s is a deprecated GCC extension", dir->name);
395 /* Traditionally, a directive is ignored unless its # is in
396 column 1. Therefore in code intended to work with K+R
397 compilers, directives added by C89 must have their #
398 indented, and directives present in traditional C must not.
399 This is true even of directives in skipped conditional
400 blocks. #elif cannot be used at all. */
401 if (CPP_WTRADITIONAL (pfile))
403 if (dir == &dtable[T_ELIF])
404 cpp_warning (pfile, CPP_W_TRADITIONAL,
405 "suggest not using #elif in traditional C");
406 else if (indented && dir->origin == KANDR)
407 cpp_warning (pfile, CPP_W_TRADITIONAL,
408 "traditional C ignores #%s with the # indented",
409 dir->name);
410 else if (!indented && dir->origin != KANDR)
411 cpp_warning (pfile, CPP_W_TRADITIONAL,
412 "suggest hiding #%s from traditional C with an indented #",
413 dir->name);
417 /* Check if we have a known directive. INDENTED is true if the
418 '#' of the directive was indented. This function is in this file
419 to save unnecessarily exporting dtable etc. to lex.cc. Returns
420 nonzero if the line of tokens has been handled, zero if we should
421 continue processing the line. */
423 _cpp_handle_directive (cpp_reader *pfile, bool indented)
425 const directive *dir = 0;
426 const cpp_token *dname;
427 bool was_parsing_args = pfile->state.parsing_args;
428 bool was_discarding_output = pfile->state.discarding_output;
429 int skip = 1;
431 if (was_discarding_output)
432 pfile->state.prevent_expansion = 0;
434 if (was_parsing_args)
436 if (CPP_OPTION (pfile, cpp_pedantic))
437 cpp_error (pfile, CPP_DL_PEDWARN,
438 "embedding a directive within macro arguments is not portable");
439 pfile->state.parsing_args = 0;
440 pfile->state.prevent_expansion = 0;
442 start_directive (pfile);
443 dname = _cpp_lex_token (pfile);
445 if (dname->type == CPP_NAME)
447 if (dname->val.node.node->is_directive)
449 dir = &dtable[dname->val.node.node->directive_index];
450 if ((dir->flags & ELIFDEF)
451 && !CPP_OPTION (pfile, elifdef)
452 /* For -std=gnu* modes elifdef is supported with
453 a pedwarn if pedantic. */
454 && CPP_OPTION (pfile, std))
455 dir = 0;
458 /* We do not recognize the # followed by a number extension in
459 assembler code. */
460 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
462 dir = &linemarker_dir;
463 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
464 && ! pfile->state.skipping)
465 cpp_error (pfile, CPP_DL_PEDWARN,
466 "style of line directive is a GCC extension");
469 if (dir)
471 /* If we have a directive that is not an opening conditional,
472 invalidate any control macro. */
473 if (! (dir->flags & IF_COND))
474 pfile->mi_valid = false;
476 /* Kluge alert. In order to be sure that code like this
478 #define HASH #
479 HASH define foo bar
481 does not cause '#define foo bar' to get executed when
482 compiled with -save-temps, we recognize directives in
483 -fpreprocessed mode only if the # is in column 1. macro.cc
484 puts a space in front of any '#' at the start of a macro.
486 We exclude the -fdirectives-only case because macro expansion
487 has not been performed yet, and block comments can cause spaces
488 to precede the directive. */
489 if (CPP_OPTION (pfile, preprocessed)
490 && !CPP_OPTION (pfile, directives_only)
491 && (indented || !(dir->flags & IN_I)))
493 skip = 0;
494 dir = 0;
496 else
498 /* In failed conditional groups, all non-conditional
499 directives are ignored. Before doing that, whether
500 skipping or not, we should lex angle-bracketed headers
501 correctly, and maybe output some diagnostics. */
502 pfile->state.angled_headers = dir->flags & INCL;
503 pfile->state.directive_wants_padding = dir->flags & INCL;
504 if (! CPP_OPTION (pfile, preprocessed))
505 directive_diagnostics (pfile, dir, indented);
506 if (pfile->state.skipping && !(dir->flags & COND))
507 dir = 0;
510 else if (dname->type == CPP_EOF)
511 ; /* CPP_EOF is the "null directive". */
512 else
514 /* An unknown directive. Don't complain about it in assembly
515 source: we don't know where the comments are, and # may
516 introduce assembler pseudo-ops. Don't complain about invalid
517 directives in skipped conditional groups (6.10 p4). */
518 if (CPP_OPTION (pfile, lang) == CLK_ASM)
519 skip = 0;
520 else if (!pfile->state.skipping)
522 const char *unrecognized
523 = (const char *)cpp_token_as_text (pfile, dname);
524 const char *hint = NULL;
526 /* Call back into gcc to get a spelling suggestion. Ideally
527 we'd just use best_match from gcc/spellcheck.h (and filter
528 out the uncommon directives), but that requires moving it
529 to a support library. */
530 if (pfile->cb.get_suggestion)
531 hint = pfile->cb.get_suggestion (pfile, unrecognized,
532 directive_names);
534 if (hint)
536 rich_location richloc (pfile->line_table, dname->src_loc);
537 source_range misspelled_token_range
538 = get_range_from_loc (pfile->line_table, dname->src_loc);
539 richloc.add_fixit_replace (misspelled_token_range, hint);
540 cpp_error_at (pfile, CPP_DL_ERROR, &richloc,
541 "invalid preprocessing directive #%s;"
542 " did you mean #%s?",
543 unrecognized, hint);
545 else
546 cpp_error (pfile, CPP_DL_ERROR,
547 "invalid preprocessing directive #%s",
548 unrecognized);
552 pfile->directive = dir;
553 if (CPP_OPTION (pfile, traditional))
554 prepare_directive_trad (pfile);
556 if (dir)
557 pfile->directive->handler (pfile);
558 else if (skip == 0)
559 _cpp_backup_tokens (pfile, 1);
561 end_directive (pfile, skip);
562 if (was_parsing_args && !pfile->state.in_deferred_pragma)
564 /* Restore state when within macro args. */
565 pfile->state.parsing_args = 2;
566 pfile->state.prevent_expansion = 1;
568 if (was_discarding_output)
569 pfile->state.prevent_expansion = 1;
570 return skip;
573 /* Directive handler wrapper used by the command line option
574 processor. BUF is \n terminated. */
575 static void
576 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
578 cpp_push_buffer (pfile, (const uchar *) buf, count,
579 /* from_stage3 */ true);
580 start_directive (pfile);
582 /* This is a short-term fix to prevent a leading '#' being
583 interpreted as a directive. */
584 _cpp_clean_line (pfile);
586 pfile->directive = &dtable[dir_no];
587 if (CPP_OPTION (pfile, traditional))
588 prepare_directive_trad (pfile);
589 pfile->directive->handler (pfile);
590 end_directive (pfile, 1);
591 _cpp_pop_buffer (pfile);
594 /* Checks for validity the macro name in #define, #undef, #ifdef and
595 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
596 processing a #define or #undefine directive, and false
597 otherwise. */
598 static cpp_hashnode *
599 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
601 const cpp_token *token = _cpp_lex_token (pfile);
603 /* The token immediately after #define must be an identifier. That
604 identifier may not be "defined", per C99 6.10.8p4.
605 In C++, it may not be any of the "named operators" either,
606 per C++98 [lex.digraph], [lex.key].
607 Finally, the identifier may not have been poisoned. (In that case
608 the lexer has issued the error message for us.) */
610 if (token->type == CPP_NAME)
612 cpp_hashnode *node = token->val.node.node;
614 if (is_def_or_undef
615 && node == pfile->spec_nodes.n_defined)
616 cpp_error (pfile, CPP_DL_ERROR,
617 "\"%s\" cannot be used as a macro name",
618 NODE_NAME (node));
619 else if (! (node->flags & NODE_POISONED))
620 return node;
622 else if (token->flags & NAMED_OP)
623 cpp_error (pfile, CPP_DL_ERROR,
624 "\"%s\" cannot be used as a macro name as it is an operator in C++",
625 NODE_NAME (token->val.node.node));
626 else if (token->type == CPP_EOF)
627 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
628 pfile->directive->name);
629 else
630 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
632 return NULL;
635 /* Process a #define directive. Most work is done in macro.cc. */
636 static void
637 do_define (cpp_reader *pfile)
639 cpp_hashnode *node = lex_macro_node (pfile, true);
641 if (node)
643 /* If we have been requested to expand comments into macros,
644 then re-enable saving of comments. */
645 pfile->state.save_comments =
646 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
648 if (pfile->cb.before_define)
649 pfile->cb.before_define (pfile);
651 if (_cpp_create_definition (pfile, node))
652 if (pfile->cb.define)
653 pfile->cb.define (pfile, pfile->directive_line, node);
655 node->flags &= ~NODE_USED;
659 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
660 static void
661 do_undef (cpp_reader *pfile)
663 cpp_hashnode *node = lex_macro_node (pfile, true);
665 if (node)
667 if (pfile->cb.before_define)
668 pfile->cb.before_define (pfile);
670 if (pfile->cb.undef)
671 pfile->cb.undef (pfile, pfile->directive_line, node);
673 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
674 identifier is not currently defined as a macro name. */
675 if (cpp_macro_p (node))
677 if (node->flags & NODE_WARN)
678 cpp_error (pfile, CPP_DL_WARNING,
679 "undefining \"%s\"", NODE_NAME (node));
680 else if (cpp_builtin_macro_p (node)
681 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
682 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
683 pfile->directive_line, 0,
684 "undefining \"%s\"", NODE_NAME (node));
686 if (node->value.macro
687 && CPP_OPTION (pfile, warn_unused_macros))
688 _cpp_warn_if_unused_macro (pfile, node, NULL);
690 _cpp_free_definition (node);
694 check_eol (pfile, false);
697 /* Undefine a single macro/assertion/whatever. */
699 static int
700 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
701 void *data_p ATTRIBUTE_UNUSED)
703 /* Body of _cpp_free_definition inlined here for speed.
704 Macros and assertions no longer have anything to free. */
705 h->type = NT_VOID;
706 h->value.answers = NULL;
707 h->flags &= ~(NODE_POISONED|NODE_DISABLED|NODE_USED);
708 return 1;
711 /* Undefine all macros and assertions. */
713 void
714 cpp_undef_all (cpp_reader *pfile)
716 cpp_forall_identifiers (pfile, undefine_macros, NULL);
720 /* Helper routine used by parse_include. Reinterpret the current line
721 as an h-char-sequence (< ... >); we are looking at the first token
722 after the <. Returns a malloced filename. */
723 static char *
724 glue_header_name (cpp_reader *pfile)
726 const cpp_token *token;
727 char *buffer;
728 size_t len, total_len = 0, capacity = 1024;
730 /* To avoid lexed tokens overwriting our glued name, we can only
731 allocate from the string pool once we've lexed everything. */
732 buffer = XNEWVEC (char, capacity);
733 for (;;)
735 token = get_token_no_padding (pfile);
737 if (token->type == CPP_GREATER)
738 break;
739 if (token->type == CPP_EOF)
741 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
742 break;
745 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
746 if (total_len + len > capacity)
748 capacity = (capacity + len) * 2;
749 buffer = XRESIZEVEC (char, buffer, capacity);
752 if (token->flags & PREV_WHITE)
753 buffer[total_len++] = ' ';
755 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
756 true)
757 - (uchar *) buffer);
760 buffer[total_len] = '\0';
761 return buffer;
764 /* Returns the file name of #include, #include_next, #import and
765 #pragma dependency. The string is malloced and the caller should
766 free it. Returns NULL on error. LOCATION is the source location
767 of the file name. */
769 static const char *
770 parse_include (cpp_reader *pfile, int *pangle_brackets,
771 const cpp_token ***buf, location_t *location)
773 char *fname;
774 const cpp_token *header;
776 /* Allow macro expansion. */
777 header = get_token_no_padding (pfile);
778 *location = header->src_loc;
779 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
780 || header->type == CPP_HEADER_NAME)
782 fname = XNEWVEC (char, header->val.str.len - 1);
783 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
784 fname[header->val.str.len - 2] = '\0';
785 *pangle_brackets = header->type == CPP_HEADER_NAME;
787 else if (header->type == CPP_LESS)
789 fname = glue_header_name (pfile);
790 *pangle_brackets = 1;
792 else
794 const unsigned char *dir;
796 if (pfile->directive == &dtable[T_PRAGMA])
797 dir = UC"pragma dependency";
798 else
799 dir = pfile->directive->name;
800 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
801 dir);
803 return NULL;
806 if (pfile->directive == &dtable[T_PRAGMA])
808 /* This pragma allows extra tokens after the file name. */
810 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
811 check_eol (pfile, true);
812 else
814 /* If we are not discarding comments, then gather them while
815 doing the eol check. */
816 *buf = check_eol_return_comments (pfile);
819 return fname;
822 /* Handle #include, #include_next and #import. */
823 static void
824 do_include_common (cpp_reader *pfile, enum include_type type)
826 const char *fname;
827 int angle_brackets;
828 const cpp_token **buf = NULL;
829 location_t location;
831 /* Re-enable saving of comments if requested, so that the include
832 callback can dump comments which follow #include. */
833 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
835 /* Tell the lexer this is an include directive -- we want it to
836 increment the line number even if this is the last line of a file. */
837 pfile->state.in_directive = 2;
839 fname = parse_include (pfile, &angle_brackets, &buf, &location);
840 if (!fname)
841 goto done;
843 if (!*fname)
845 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
846 "empty filename in #%s",
847 pfile->directive->name);
848 goto done;
851 /* Prevent #include recursion. */
852 if (pfile->line_table->depth >= CPP_OPTION (pfile, max_include_depth))
853 cpp_error (pfile,
854 CPP_DL_ERROR,
855 "#include nested depth %u exceeds maximum of %u"
856 " (use -fmax-include-depth=DEPTH to increase the maximum)",
857 pfile->line_table->depth,
858 CPP_OPTION (pfile, max_include_depth));
859 else
861 /* Get out of macro context, if we are. */
862 skip_rest_of_line (pfile);
864 if (pfile->cb.include)
865 pfile->cb.include (pfile, pfile->directive_line,
866 pfile->directive->name, fname, angle_brackets,
867 buf);
869 _cpp_stack_include (pfile, fname, angle_brackets, type, location);
872 done:
873 XDELETEVEC (fname);
874 if (buf)
875 XDELETEVEC (buf);
878 static void
879 do_include (cpp_reader *pfile)
881 do_include_common (pfile, IT_INCLUDE);
884 static void
885 do_import (cpp_reader *pfile)
887 do_include_common (pfile, IT_IMPORT);
890 static void
891 do_include_next (cpp_reader *pfile)
893 enum include_type type = IT_INCLUDE_NEXT;
895 /* If this is the primary source file, warn and use the normal
896 search logic. */
897 if (_cpp_in_main_source_file (pfile))
899 cpp_error (pfile, CPP_DL_WARNING,
900 "#include_next in primary source file");
901 type = IT_INCLUDE;
903 do_include_common (pfile, type);
906 /* Subroutine of do_linemarker. Read possible flags after file name.
907 LAST is the last flag seen; 0 if this is the first flag. Return the
908 flag if it is valid, 0 at the end of the directive. Otherwise
909 complain. */
910 static unsigned int
911 read_flag (cpp_reader *pfile, unsigned int last)
913 const cpp_token *token = _cpp_lex_token (pfile);
915 if (token->type == CPP_NUMBER && token->val.str.len == 1)
917 unsigned int flag = token->val.str.text[0] - '0';
919 if (flag > last && flag <= 4
920 && (flag != 4 || last == 3)
921 && (flag != 2 || last == 0))
922 return flag;
925 if (token->type != CPP_EOF)
926 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
927 cpp_token_as_text (pfile, token));
928 return 0;
931 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
932 of length LEN, to binary; store it in NUMP, and return false if the
933 number was well-formed, true if not. WRAPPED is set to true if the
934 number did not fit into 'linenum_type'. */
935 static bool
936 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
938 linenum_type reg = 0;
940 uchar c;
941 bool seen_digit_sep = false;
942 *wrapped = false;
943 while (len--)
945 c = *str++;
946 if (!seen_digit_sep && c == '\'' && len)
948 seen_digit_sep = true;
949 continue;
951 if (!ISDIGIT (c))
952 return true;
953 seen_digit_sep = false;
954 if (reg > ((linenum_type) -1) / 10)
955 *wrapped = true;
956 reg *= 10;
957 if (reg > ((linenum_type) -1) - (c - '0'))
958 *wrapped = true;
959 reg += c - '0';
961 *nump = reg;
962 return false;
965 /* Interpret #line command.
966 Note that the filename string (if any) is a true string constant
967 (escapes are interpreted). */
968 static void
969 do_line (cpp_reader *pfile)
971 class line_maps *line_table = pfile->line_table;
972 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
974 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
975 sysp right now. */
977 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
978 const cpp_token *token;
979 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
980 linenum_type new_lineno;
982 /* C99 raised the minimum limit on #line numbers. */
983 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
984 bool wrapped;
986 /* #line commands expand macros. */
987 token = cpp_get_token (pfile);
988 if (token->type != CPP_NUMBER
989 || strtolinenum (token->val.str.text, token->val.str.len,
990 &new_lineno, &wrapped))
992 if (token->type == CPP_EOF)
993 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
994 else
995 cpp_error (pfile, CPP_DL_ERROR,
996 "\"%s\" after #line is not a positive integer",
997 cpp_token_as_text (pfile, token));
998 return;
1001 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
1002 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
1003 else if (wrapped)
1004 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
1006 token = cpp_get_token (pfile);
1007 if (token->type == CPP_STRING)
1009 cpp_string s = { 0, 0 };
1010 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
1011 &s, CPP_STRING))
1012 new_file = (const char *)s.text;
1013 check_eol (pfile, true);
1015 else if (token->type != CPP_EOF)
1017 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1018 cpp_token_as_text (pfile, token));
1019 return;
1022 skip_rest_of_line (pfile);
1023 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1024 map_sysp);
1025 line_table->seen_line_directive = true;
1028 /* Interpret the # 44 "file" [flags] notation, which has slightly
1029 different syntax and semantics from #line: Flags are allowed,
1030 and we never complain about the line number being too big. */
1031 static void
1032 do_linemarker (cpp_reader *pfile)
1034 class line_maps *line_table = pfile->line_table;
1035 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1036 const cpp_token *token;
1037 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1038 linenum_type new_lineno;
1039 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1040 enum lc_reason reason = LC_RENAME_VERBATIM;
1041 int flag;
1042 bool wrapped;
1044 /* Back up so we can get the number again. Putting this in
1045 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1046 some circumstances, which can segfault. */
1047 _cpp_backup_tokens (pfile, 1);
1049 /* #line commands expand macros. */
1050 token = cpp_get_token (pfile);
1051 if (token->type != CPP_NUMBER
1052 || strtolinenum (token->val.str.text, token->val.str.len,
1053 &new_lineno, &wrapped))
1055 /* Unlike #line, there does not seem to be a way to get an EOF
1056 here. So, it should be safe to always spell the token. */
1057 cpp_error (pfile, CPP_DL_ERROR,
1058 "\"%s\" after # is not a positive integer",
1059 cpp_token_as_text (pfile, token));
1060 return;
1063 token = cpp_get_token (pfile);
1064 if (token->type == CPP_STRING)
1066 cpp_string s = { 0, 0 };
1067 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1068 1, &s, CPP_STRING))
1069 new_file = (const char *)s.text;
1071 new_sysp = 0;
1072 flag = read_flag (pfile, 0);
1073 if (flag == 1)
1075 reason = LC_ENTER;
1076 /* Fake an include for cpp_included (). */
1077 _cpp_fake_include (pfile, new_file);
1078 flag = read_flag (pfile, flag);
1080 else if (flag == 2)
1082 reason = LC_LEAVE;
1083 flag = read_flag (pfile, flag);
1085 if (flag == 3)
1087 new_sysp = 1;
1088 flag = read_flag (pfile, flag);
1089 if (flag == 4)
1090 new_sysp = 2;
1092 pfile->buffer->sysp = new_sysp;
1094 check_eol (pfile, false);
1096 else if (token->type != CPP_EOF)
1098 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1099 cpp_token_as_text (pfile, token));
1100 return;
1103 skip_rest_of_line (pfile);
1105 if (reason == LC_LEAVE)
1107 /* Reread map since cpp_get_token can invalidate it with a
1108 reallocation. */
1109 map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1110 const line_map_ordinary *from
1111 = linemap_included_from_linemap (line_table, map);
1113 if (!from)
1114 /* Not nested. */;
1115 else if (!new_file[0])
1116 /* Leaving to "" means fill in the popped-to name. */
1117 new_file = ORDINARY_MAP_FILE_NAME (from);
1118 else if (filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0)
1119 /* It's the wrong name, Grommit! */
1120 from = NULL;
1122 if (!from)
1124 cpp_warning (pfile, CPP_W_NONE,
1125 "file \"%s\" linemarker ignored due to "
1126 "incorrect nesting", new_file);
1127 return;
1131 /* Compensate for the increment in linemap_add that occurs in
1132 _cpp_do_file_change. We're currently at the start of the line
1133 *following* the #line directive. A separate location_t for this
1134 location makes no sense (until we do the LC_LEAVE), and
1135 complicates LAST_SOURCE_LINE_LOCATION. */
1136 pfile->line_table->highest_location--;
1138 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1139 line_table->seen_line_directive = true;
1142 /* Arrange the file_change callback. Changing to TO_FILE:TO_LINE for
1143 REASON. SYSP is 1 for a system header, 2 for a system header that
1144 needs to be extern "C" protected, and zero otherwise. */
1145 void
1146 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1147 const char *to_file, linenum_type to_line,
1148 unsigned int sysp)
1150 linemap_assert (reason != LC_ENTER_MACRO);
1152 const line_map_ordinary *ord_map = NULL;
1153 if (!to_line && reason == LC_RENAME_VERBATIM)
1155 /* A linemarker moving to line zero. If we're on the second
1156 line of the current map, and it also starts at zero, just
1157 rewind -- we're probably reading the builtins of a
1158 preprocessed source. */
1159 line_map_ordinary *last = LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table);
1160 if (!ORDINARY_MAP_STARTING_LINE_NUMBER (last)
1161 && 0 == filename_cmp (to_file, ORDINARY_MAP_FILE_NAME (last))
1162 && SOURCE_LINE (last, pfile->line_table->highest_line) == 2)
1164 ord_map = last;
1165 pfile->line_table->highest_location
1166 = pfile->line_table->highest_line = MAP_START_LOCATION (last);
1170 if (!ord_map)
1171 if (const line_map *map = linemap_add (pfile->line_table, reason, sysp,
1172 to_file, to_line))
1174 ord_map = linemap_check_ordinary (map);
1175 linemap_line_start (pfile->line_table,
1176 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1177 127);
1180 if (pfile->cb.file_change)
1181 pfile->cb.file_change (pfile, ord_map);
1184 /* Report a warning or error detected by the program we are
1185 processing. Use the directive's tokens in the error message. */
1186 static void
1187 do_diagnostic (cpp_reader *pfile, enum cpp_diagnostic_level code,
1188 enum cpp_warning_reason reason, int print_dir)
1190 const unsigned char *dir_name;
1191 unsigned char *line;
1192 location_t src_loc = pfile->cur_token[-1].src_loc;
1194 if (print_dir)
1195 dir_name = pfile->directive->name;
1196 else
1197 dir_name = NULL;
1198 pfile->state.prevent_expansion++;
1199 line = cpp_output_line_to_string (pfile, dir_name);
1200 pfile->state.prevent_expansion--;
1202 if (code == CPP_DL_WARNING_SYSHDR && reason)
1203 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1204 else if (code == CPP_DL_WARNING && reason)
1205 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1206 else
1207 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1208 free (line);
1211 static void
1212 do_error (cpp_reader *pfile)
1214 do_diagnostic (pfile, CPP_DL_ERROR, CPP_W_NONE, 1);
1217 static void
1218 do_warning (cpp_reader *pfile)
1220 /* We want #warning diagnostics to be emitted in system headers too. */
1221 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1224 /* Report program identification. */
1225 static void
1226 do_ident (cpp_reader *pfile)
1228 const cpp_token *str = cpp_get_token (pfile);
1230 if (str->type != CPP_STRING)
1231 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1232 pfile->directive->name);
1233 else if (pfile->cb.ident)
1234 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1236 check_eol (pfile, false);
1239 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1240 matching entry, or NULL if none is found. The returned entry could
1241 be the start of a namespace chain, or a pragma. */
1242 static struct pragma_entry *
1243 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1245 while (chain && chain->pragma != pragma)
1246 chain = chain->next;
1248 return chain;
1251 /* Create and insert a blank pragma entry at the beginning of a
1252 singly-linked CHAIN. */
1253 static struct pragma_entry *
1254 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1256 struct pragma_entry *new_entry;
1258 new_entry = (struct pragma_entry *)
1259 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1261 memset (new_entry, 0, sizeof (struct pragma_entry));
1262 new_entry->next = *chain;
1264 *chain = new_entry;
1265 return new_entry;
1268 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1269 goes in the global namespace. */
1270 static struct pragma_entry *
1271 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1272 bool allow_name_expansion)
1274 struct pragma_entry **chain = &pfile->pragmas;
1275 struct pragma_entry *entry;
1276 const cpp_hashnode *node;
1278 if (space)
1280 node = cpp_lookup (pfile, UC space, strlen (space));
1281 entry = lookup_pragma_entry (*chain, node);
1282 if (!entry)
1284 entry = new_pragma_entry (pfile, chain);
1285 entry->pragma = node;
1286 entry->is_nspace = true;
1287 entry->allow_expansion = allow_name_expansion;
1289 else if (!entry->is_nspace)
1290 goto clash;
1291 else if (entry->allow_expansion != allow_name_expansion)
1293 cpp_error (pfile, CPP_DL_ICE,
1294 "registering pragmas in namespace \"%s\" with mismatched "
1295 "name expansion", space);
1296 return NULL;
1298 chain = &entry->u.space;
1300 else if (allow_name_expansion)
1302 cpp_error (pfile, CPP_DL_ICE,
1303 "registering pragma \"%s\" with name expansion "
1304 "and no namespace", name);
1305 return NULL;
1308 /* Check for duplicates. */
1309 node = cpp_lookup (pfile, UC name, strlen (name));
1310 entry = lookup_pragma_entry (*chain, node);
1311 if (entry == NULL)
1313 entry = new_pragma_entry (pfile, chain);
1314 entry->pragma = node;
1315 return entry;
1318 if (entry->is_nspace)
1319 clash:
1320 cpp_error (pfile, CPP_DL_ICE,
1321 "registering \"%s\" as both a pragma and a pragma namespace",
1322 NODE_NAME (node));
1323 else if (space)
1324 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1325 space, name);
1326 else
1327 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1329 return NULL;
1332 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1333 static void
1334 register_pragma_internal (cpp_reader *pfile, const char *space,
1335 const char *name, pragma_cb handler)
1337 struct pragma_entry *entry;
1339 entry = register_pragma_1 (pfile, space, name, false);
1340 entry->is_internal = true;
1341 entry->u.handler = handler;
1344 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1345 goes in the global namespace. HANDLER is the handler it will call,
1346 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1347 expansion while parsing pragma NAME. This function is exported
1348 from libcpp. */
1349 void
1350 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1351 pragma_cb handler, bool allow_expansion)
1353 struct pragma_entry *entry;
1355 if (!handler)
1357 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1358 return;
1361 entry = register_pragma_1 (pfile, space, name, false);
1362 if (entry)
1364 entry->allow_expansion = allow_expansion;
1365 entry->u.handler = handler;
1369 /* Similarly, but create mark the pragma for deferred processing.
1370 When found, a CPP_PRAGMA token will be insertted into the stream
1371 with IDENT in the token->u.pragma slot. */
1372 void
1373 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1374 const char *name, unsigned int ident,
1375 bool allow_expansion, bool allow_name_expansion)
1377 struct pragma_entry *entry;
1379 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1380 if (entry)
1382 entry->is_deferred = true;
1383 entry->allow_expansion = allow_expansion;
1384 entry->u.ident = ident;
1388 /* Register the pragmas the preprocessor itself handles. */
1389 void
1390 _cpp_init_internal_pragmas (cpp_reader *pfile)
1392 /* Pragmas in the global namespace. */
1393 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1394 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1395 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1397 /* New GCC-specific pragmas should be put in the GCC namespace. */
1398 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1399 register_pragma_internal (pfile, "GCC", "system_header",
1400 do_pragma_system_header);
1401 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1402 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1403 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1406 /* Return the number of registered pragmas in PE. */
1408 static int
1409 count_registered_pragmas (struct pragma_entry *pe)
1411 int ct = 0;
1412 for (; pe != NULL; pe = pe->next)
1414 if (pe->is_nspace)
1415 ct += count_registered_pragmas (pe->u.space);
1416 ct++;
1418 return ct;
1421 /* Save into SD the names of the registered pragmas referenced by PE,
1422 and return a pointer to the next free space in SD. */
1424 static char **
1425 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1427 for (; pe != NULL; pe = pe->next)
1429 if (pe->is_nspace)
1430 sd = save_registered_pragmas (pe->u.space, sd);
1431 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1432 HT_LEN (&pe->pragma->ident),
1433 HT_LEN (&pe->pragma->ident) + 1);
1435 return sd;
1438 /* Return a newly-allocated array which saves the names of the
1439 registered pragmas. */
1441 char **
1442 _cpp_save_pragma_names (cpp_reader *pfile)
1444 int ct = count_registered_pragmas (pfile->pragmas);
1445 char **result = XNEWVEC (char *, ct);
1446 (void) save_registered_pragmas (pfile->pragmas, result);
1447 return result;
1450 /* Restore from SD the names of the registered pragmas referenced by PE,
1451 and return a pointer to the next unused name in SD. */
1453 static char **
1454 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1455 char **sd)
1457 for (; pe != NULL; pe = pe->next)
1459 if (pe->is_nspace)
1460 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1461 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1462 free (*sd);
1463 sd++;
1465 return sd;
1468 /* Restore the names of the registered pragmas from SAVED. */
1470 void
1471 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1473 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1474 free (saved);
1477 /* Pragmata handling. We handle some, and pass the rest on to the
1478 front end. C99 defines three pragmas and says that no macro
1479 expansion is to be performed on them; whether or not macro
1480 expansion happens for other pragmas is implementation defined.
1481 This implementation allows for a mix of both, since GCC did not
1482 traditionally macro expand its (few) pragmas, whereas OpenMP
1483 specifies that macro expansion should happen. */
1484 static void
1485 do_pragma (cpp_reader *pfile)
1487 const struct pragma_entry *p = NULL;
1488 const cpp_token *token, *pragma_token;
1489 location_t pragma_token_virt_loc = 0;
1490 cpp_token ns_token;
1491 unsigned int count = 1;
1493 pfile->state.prevent_expansion++;
1495 pragma_token = token = cpp_get_token_with_location (pfile,
1496 &pragma_token_virt_loc);
1497 ns_token = *token;
1498 if (token->type == CPP_NAME)
1500 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1501 if (p && p->is_nspace)
1503 bool allow_name_expansion = p->allow_expansion;
1504 if (allow_name_expansion)
1505 pfile->state.prevent_expansion--;
1507 token = cpp_get_token (pfile);
1508 if (token->type == CPP_NAME)
1509 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1510 else
1511 p = NULL;
1512 if (allow_name_expansion)
1513 pfile->state.prevent_expansion++;
1514 count = 2;
1518 if (p)
1520 if (p->is_deferred)
1522 pfile->directive_result.src_loc = pragma_token_virt_loc;
1523 pfile->directive_result.type = CPP_PRAGMA;
1524 pfile->directive_result.flags = pragma_token->flags;
1525 pfile->directive_result.val.pragma = p->u.ident;
1526 pfile->state.in_deferred_pragma = true;
1527 pfile->state.pragma_allow_expansion = p->allow_expansion;
1528 if (!p->allow_expansion)
1529 pfile->state.prevent_expansion++;
1531 else
1533 /* Since the handler below doesn't get the line number, that
1534 it might need for diagnostics, make sure it has the right
1535 numbers in place. */
1536 if (pfile->cb.line_change)
1537 (*pfile->cb.line_change) (pfile, pragma_token, false);
1538 if (p->allow_expansion)
1539 pfile->state.prevent_expansion--;
1540 (*p->u.handler) (pfile);
1541 if (p->allow_expansion)
1542 pfile->state.prevent_expansion++;
1545 else if (pfile->cb.def_pragma)
1547 if (count == 1 || pfile->context->prev == NULL)
1548 _cpp_backup_tokens (pfile, count);
1549 else
1551 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1552 won't allow backing 2 tokens. */
1553 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1554 reads both tokens, we could perhaps free it, but if it doesn't,
1555 we don't know the exact lifespan. */
1556 cpp_token *toks = XNEWVEC (cpp_token, 2);
1557 toks[0] = ns_token;
1558 toks[0].flags |= NO_EXPAND;
1559 toks[1] = *token;
1560 toks[1].flags |= NO_EXPAND;
1561 _cpp_push_token_context (pfile, NULL, toks, 2);
1563 pfile->cb.def_pragma (pfile, pfile->directive_line);
1566 pfile->state.prevent_expansion--;
1569 /* Handle #pragma once. */
1570 static void
1571 do_pragma_once (cpp_reader *pfile)
1573 if (_cpp_in_main_source_file (pfile))
1574 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1576 check_eol (pfile, false);
1577 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1580 /* Handle #pragma push_macro(STRING). */
1581 static void
1582 do_pragma_push_macro (cpp_reader *pfile)
1584 cpp_hashnode *node;
1585 size_t defnlen;
1586 const uchar *defn = NULL;
1587 char *macroname, *dest;
1588 const char *limit, *src;
1589 const cpp_token *txt;
1590 struct def_pragma_macro *c;
1592 txt = get__Pragma_string (pfile);
1593 if (!txt)
1595 location_t src_loc = pfile->cur_token[-1].src_loc;
1596 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1597 "invalid #pragma push_macro directive");
1598 check_eol (pfile, false);
1599 skip_rest_of_line (pfile);
1600 return;
1602 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1603 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1604 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1605 while (src < limit)
1607 /* We know there is a character following the backslash. */
1608 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1609 src++;
1610 *dest++ = *src++;
1612 *dest = 0;
1613 check_eol (pfile, false);
1614 skip_rest_of_line (pfile);
1615 c = XNEW (struct def_pragma_macro);
1616 memset (c, 0, sizeof (struct def_pragma_macro));
1617 c->name = XNEWVAR (char, strlen (macroname) + 1);
1618 strcpy (c->name, macroname);
1619 c->next = pfile->pushed_macros;
1620 node = _cpp_lex_identifier (pfile, c->name);
1621 if (node->type == NT_VOID)
1622 c->is_undef = 1;
1623 else if (node->type == NT_BUILTIN_MACRO)
1624 c->is_builtin = 1;
1625 else
1627 defn = cpp_macro_definition (pfile, node);
1628 defnlen = ustrlen (defn);
1629 c->definition = XNEWVEC (uchar, defnlen + 2);
1630 c->definition[defnlen] = '\n';
1631 c->definition[defnlen + 1] = 0;
1632 c->line = node->value.macro->line;
1633 c->syshdr = node->value.macro->syshdr;
1634 c->used = node->value.macro->used;
1635 memcpy (c->definition, defn, defnlen);
1638 pfile->pushed_macros = c;
1641 /* Handle #pragma pop_macro(STRING). */
1642 static void
1643 do_pragma_pop_macro (cpp_reader *pfile)
1645 char *macroname, *dest;
1646 const char *limit, *src;
1647 const cpp_token *txt;
1648 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1649 txt = get__Pragma_string (pfile);
1650 if (!txt)
1652 location_t src_loc = pfile->cur_token[-1].src_loc;
1653 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1654 "invalid #pragma pop_macro directive");
1655 check_eol (pfile, false);
1656 skip_rest_of_line (pfile);
1657 return;
1659 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1660 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1661 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1662 while (src < limit)
1664 /* We know there is a character following the backslash. */
1665 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1666 src++;
1667 *dest++ = *src++;
1669 *dest = 0;
1670 check_eol (pfile, false);
1671 skip_rest_of_line (pfile);
1673 while (c != NULL)
1675 if (!strcmp (c->name, macroname))
1677 if (!l)
1678 pfile->pushed_macros = c->next;
1679 else
1680 l->next = c->next;
1681 cpp_pop_definition (pfile, c);
1682 free (c->definition);
1683 free (c->name);
1684 free (c);
1685 break;
1687 l = c;
1688 c = c->next;
1692 /* Handle #pragma GCC poison, to poison one or more identifiers so
1693 that the lexer produces a hard error for each subsequent usage. */
1694 static void
1695 do_pragma_poison (cpp_reader *pfile)
1697 const cpp_token *tok;
1698 cpp_hashnode *hp;
1700 pfile->state.poisoned_ok = 1;
1701 for (;;)
1703 tok = _cpp_lex_token (pfile);
1704 if (tok->type == CPP_EOF)
1705 break;
1706 if (tok->type != CPP_NAME)
1708 cpp_error (pfile, CPP_DL_ERROR,
1709 "invalid #pragma GCC poison directive");
1710 break;
1713 hp = tok->val.node.node;
1714 if (hp->flags & NODE_POISONED)
1715 continue;
1717 if (cpp_macro_p (hp))
1718 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1719 NODE_NAME (hp));
1720 _cpp_free_definition (hp);
1721 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1723 pfile->state.poisoned_ok = 0;
1726 /* Mark the current header as a system header. This will suppress
1727 some categories of warnings (notably those from -pedantic). It is
1728 intended for use in system libraries that cannot be implemented in
1729 conforming C, but cannot be certain that their headers appear in a
1730 system include directory. To prevent abuse, it is rejected in the
1731 primary source file. */
1732 static void
1733 do_pragma_system_header (cpp_reader *pfile)
1735 if (_cpp_in_main_source_file (pfile))
1736 cpp_error (pfile, CPP_DL_WARNING,
1737 "#pragma system_header ignored outside include file");
1738 else
1740 check_eol (pfile, false);
1741 skip_rest_of_line (pfile);
1742 cpp_make_system_header (pfile, 1, 0);
1746 /* Check the modified date of the current include file against a specified
1747 file. Issue a diagnostic, if the specified file is newer. We use this to
1748 determine if a fixed header should be refixed. */
1749 static void
1750 do_pragma_dependency (cpp_reader *pfile)
1752 const char *fname;
1753 int angle_brackets, ordering;
1754 location_t location;
1756 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1757 if (!fname)
1758 return;
1760 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1761 if (ordering < 0)
1762 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1763 else if (ordering > 0)
1765 cpp_error (pfile, CPP_DL_WARNING,
1766 "current file is older than %s", fname);
1767 if (cpp_get_token (pfile)->type != CPP_EOF)
1769 _cpp_backup_tokens (pfile, 1);
1770 do_diagnostic (pfile, CPP_DL_WARNING, CPP_W_NONE, 0);
1774 free ((void *) fname);
1777 /* Issue a diagnostic with the message taken from the pragma. If
1778 ERROR is true, the diagnostic is a warning, otherwise, it is an
1779 error. */
1780 static void
1781 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1783 const cpp_token *tok = _cpp_lex_token (pfile);
1784 cpp_string str;
1785 if (tok->type != CPP_STRING
1786 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1787 CPP_STRING)
1788 || str.len == 0)
1790 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1791 error ? "error" : "warning");
1792 return;
1794 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1795 "%s", str.text);
1796 free ((void *)str.text);
1799 /* Issue a warning diagnostic. */
1800 static void
1801 do_pragma_warning (cpp_reader *pfile)
1803 do_pragma_warning_or_error (pfile, false);
1806 /* Issue an error diagnostic. */
1807 static void
1808 do_pragma_error (cpp_reader *pfile)
1810 do_pragma_warning_or_error (pfile, true);
1813 /* Get a token but skip padding. */
1814 static const cpp_token *
1815 get_token_no_padding (cpp_reader *pfile)
1817 for (;;)
1819 const cpp_token *result = cpp_get_token (pfile);
1820 if (result->type != CPP_PADDING)
1821 return result;
1825 /* Check syntax is "(string-literal)". Returns the string on success,
1826 or NULL on failure. */
1827 static const cpp_token *
1828 get__Pragma_string (cpp_reader *pfile)
1830 const cpp_token *string;
1831 const cpp_token *paren;
1833 paren = get_token_no_padding (pfile);
1834 if (paren->type == CPP_EOF)
1835 _cpp_backup_tokens (pfile, 1);
1836 if (paren->type != CPP_OPEN_PAREN)
1837 return NULL;
1839 string = get_token_no_padding (pfile);
1840 if (string->type == CPP_EOF)
1841 _cpp_backup_tokens (pfile, 1);
1842 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1843 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1844 && string->type != CPP_UTF8STRING)
1845 return NULL;
1847 paren = get_token_no_padding (pfile);
1848 if (paren->type == CPP_EOF)
1849 _cpp_backup_tokens (pfile, 1);
1850 if (paren->type != CPP_CLOSE_PAREN)
1851 return NULL;
1853 return string;
1856 /* Destringize IN into a temporary buffer, by removing the first \ of
1857 \" and \\ sequences, and process the result as a #pragma directive. */
1858 static void
1859 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1860 location_t expansion_loc)
1862 const unsigned char *src, *limit;
1863 char *dest, *result;
1864 cpp_context *saved_context;
1865 cpp_token *saved_cur_token;
1866 tokenrun *saved_cur_run;
1867 cpp_token *toks;
1868 int count;
1869 const struct directive *save_directive;
1871 dest = result = (char *) alloca (in->len - 1);
1872 src = in->text + 1 + (in->text[0] == 'L');
1873 limit = in->text + in->len - 1;
1874 while (src < limit)
1876 /* We know there is a character following the backslash. */
1877 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1878 src++;
1879 *dest++ = *src++;
1881 *dest = '\n';
1883 /* Ugh; an awful kludge. We are really not set up to be lexing
1884 tokens when in the middle of a macro expansion. Use a new
1885 context to force cpp_get_token to lex, and so skip_rest_of_line
1886 doesn't go beyond the end of the text. Also, remember the
1887 current lexing position so we can return to it later.
1889 Something like line-at-a-time lexing should remove the need for
1890 this. */
1891 saved_context = pfile->context;
1892 saved_cur_token = pfile->cur_token;
1893 saved_cur_run = pfile->cur_run;
1895 pfile->context = XCNEW (cpp_context);
1897 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1898 until we've read all of the tokens that we want. */
1899 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1900 /* from_stage3 */ true);
1901 /* ??? Antique Disgusting Hack. What does this do? */
1902 if (pfile->buffer->prev)
1903 pfile->buffer->file = pfile->buffer->prev->file;
1905 start_directive (pfile);
1906 _cpp_clean_line (pfile);
1907 save_directive = pfile->directive;
1908 pfile->directive = &dtable[T_PRAGMA];
1909 do_pragma (pfile);
1910 if (pfile->directive_result.type == CPP_PRAGMA)
1911 pfile->directive_result.flags |= PRAGMA_OP;
1912 end_directive (pfile, 1);
1913 pfile->directive = save_directive;
1915 /* We always insert at least one token, the directive result. It'll
1916 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1917 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1919 /* If we're not handling the pragma internally, read all of the tokens from
1920 the string buffer now, while the string buffer is still installed. */
1921 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1922 to me what the true lifespan of the tokens are. It would appear that
1923 the lifespan is the entire parse of the main input stream, in which case
1924 this may not be wrong. */
1925 if (pfile->directive_result.type == CPP_PRAGMA)
1927 int maxcount;
1929 count = 1;
1930 maxcount = 50;
1931 toks = XNEWVEC (cpp_token, maxcount);
1932 toks[0] = pfile->directive_result;
1936 if (count == maxcount)
1938 maxcount = maxcount * 3 / 2;
1939 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1941 toks[count] = *cpp_get_token (pfile);
1942 /* _Pragma is a builtin, so we're not within a macro-map, and so
1943 the token locations are set to bogus ordinary locations
1944 near to, but after that of the "_Pragma".
1945 Paper over this by setting them equal to the location of the
1946 _Pragma itself (PR preprocessor/69126). */
1947 toks[count].src_loc = expansion_loc;
1948 /* Macros have been already expanded by cpp_get_token
1949 if the pragma allowed expansion. */
1950 toks[count++].flags |= NO_EXPAND;
1952 while (toks[count-1].type != CPP_PRAGMA_EOL);
1954 else
1956 count = 1;
1957 toks = &pfile->avoid_paste;
1959 /* If we handled the entire pragma internally, make sure we get the
1960 line number correct for the next token. */
1961 if (pfile->cb.line_change)
1962 pfile->cb.line_change (pfile, pfile->cur_token, false);
1965 /* Finish inlining run_directive. */
1966 pfile->buffer->file = NULL;
1967 _cpp_pop_buffer (pfile);
1969 /* Reset the old macro state before ... */
1970 XDELETE (pfile->context);
1971 pfile->context = saved_context;
1972 pfile->cur_token = saved_cur_token;
1973 pfile->cur_run = saved_cur_run;
1975 /* ... inserting the new tokens we collected. */
1976 _cpp_push_token_context (pfile, NULL, toks, count);
1979 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1981 _cpp_do__Pragma (cpp_reader *pfile, location_t expansion_loc)
1983 const cpp_token *string = get__Pragma_string (pfile);
1984 pfile->directive_result.type = CPP_PADDING;
1986 if (string)
1988 destringize_and_run (pfile, &string->val.str, expansion_loc);
1989 return 1;
1991 cpp_error (pfile, CPP_DL_ERROR,
1992 "_Pragma takes a parenthesized string literal");
1993 return 0;
1996 /* Handle #ifdef. */
1997 static void
1998 do_ifdef (cpp_reader *pfile)
2000 int skip = 1;
2002 if (! pfile->state.skipping)
2004 cpp_hashnode *node = lex_macro_node (pfile, false);
2006 if (node)
2008 skip = !_cpp_defined_macro_p (node);
2009 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2010 /* It wasn't a macro after all. */
2011 skip = true;
2012 _cpp_mark_macro_used (node);
2013 if (pfile->cb.used)
2014 pfile->cb.used (pfile, pfile->directive_line, node);
2015 check_eol (pfile, false);
2019 push_conditional (pfile, skip, T_IFDEF, 0);
2022 /* Handle #ifndef. */
2023 static void
2024 do_ifndef (cpp_reader *pfile)
2026 int skip = 1;
2027 cpp_hashnode *node = 0;
2029 if (! pfile->state.skipping)
2031 node = lex_macro_node (pfile, false);
2033 if (node)
2035 skip = _cpp_defined_macro_p (node);
2036 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2037 /* It wasn't a macro after all. */
2038 skip = false;
2039 _cpp_mark_macro_used (node);
2040 if (pfile->cb.used)
2041 pfile->cb.used (pfile, pfile->directive_line, node);
2042 check_eol (pfile, false);
2046 push_conditional (pfile, skip, T_IFNDEF, node);
2049 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2050 pfile->mi_ind_cmacro so we can handle multiple-include
2051 optimizations. If macro expansion occurs in the expression, we
2052 cannot treat it as a controlling conditional, since the expansion
2053 could change in the future. That is handled by cpp_get_token. */
2054 static void
2055 do_if (cpp_reader *pfile)
2057 int skip = 1;
2059 if (! pfile->state.skipping)
2060 skip = _cpp_parse_expr (pfile, true) == false;
2062 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2065 /* Flip skipping state if appropriate and continue without changing
2066 if_stack; this is so that the error message for missing #endif's
2067 etc. will point to the original #if. */
2068 static void
2069 do_else (cpp_reader *pfile)
2071 cpp_buffer *buffer = pfile->buffer;
2072 struct if_stack *ifs = buffer->if_stack;
2074 if (ifs == NULL)
2075 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2076 else
2078 if (ifs->type == T_ELSE)
2080 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2081 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2082 "the conditional began here");
2084 ifs->type = T_ELSE;
2086 /* Skip any future (erroneous) #elses or #elifs. */
2087 pfile->state.skipping = ifs->skip_elses;
2088 ifs->skip_elses = true;
2090 /* Invalidate any controlling macro. */
2091 ifs->mi_cmacro = 0;
2093 /* Only check EOL if was not originally skipping. */
2094 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2095 check_eol_endif_labels (pfile);
2099 /* Handle a #elif, #elifdef or #elifndef directive by not changing if_stack
2100 either. See the comment above do_else. */
2101 static void
2102 do_elif (cpp_reader *pfile)
2104 cpp_buffer *buffer = pfile->buffer;
2105 struct if_stack *ifs = buffer->if_stack;
2107 if (ifs == NULL)
2108 cpp_error (pfile, CPP_DL_ERROR, "#%s without #if", pfile->directive->name);
2109 else
2111 if (ifs->type == T_ELSE)
2113 cpp_error (pfile, CPP_DL_ERROR, "#%s after #else",
2114 pfile->directive->name);
2115 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2116 "the conditional began here");
2118 ifs->type = T_ELIF;
2120 /* See DR#412: "Only the first group whose control condition
2121 evaluates to true (nonzero) is processed; any following groups
2122 are skipped and their controlling directives are processed as
2123 if they were in a group that is skipped." */
2124 if (ifs->skip_elses)
2126 /* In older GNU standards, #elifdef/#elifndef is supported
2127 as an extension, but pedwarn if -pedantic if the presence
2128 of the directive would be rejected. */
2129 if (pfile->directive != &dtable[T_ELIF]
2130 && ! CPP_OPTION (pfile, elifdef)
2131 && CPP_PEDANTIC (pfile)
2132 && !pfile->state.skipping)
2134 if (CPP_OPTION (pfile, cplusplus))
2135 cpp_error (pfile, CPP_DL_PEDWARN,
2136 "#%s before C++23 is a GCC extension",
2137 pfile->directive->name);
2138 else
2139 cpp_error (pfile, CPP_DL_PEDWARN,
2140 "#%s before C2X is a GCC extension",
2141 pfile->directive->name);
2143 pfile->state.skipping = 1;
2145 else
2147 if (pfile->directive == &dtable[T_ELIF])
2148 pfile->state.skipping = !_cpp_parse_expr (pfile, false);
2149 else
2151 cpp_hashnode *node = lex_macro_node (pfile, false);
2153 if (node)
2155 bool macro_defined = _cpp_defined_macro_p (node);
2156 if (!_cpp_maybe_notify_macro_use (pfile, node,
2157 pfile->directive_line))
2158 /* It wasn't a macro after all. */
2159 macro_defined = false;
2160 bool skip = (pfile->directive == &dtable[T_ELIFDEF]
2161 ? !macro_defined
2162 : macro_defined);
2163 if (pfile->cb.used)
2164 pfile->cb.used (pfile, pfile->directive_line, node);
2165 check_eol (pfile, false);
2166 /* In older GNU standards, #elifdef/#elifndef is supported
2167 as an extension, but pedwarn if -pedantic if the presence
2168 of the directive would change behavior. */
2169 if (! CPP_OPTION (pfile, elifdef)
2170 && CPP_PEDANTIC (pfile)
2171 && pfile->state.skipping != skip)
2173 if (CPP_OPTION (pfile, cplusplus))
2174 cpp_error (pfile, CPP_DL_PEDWARN,
2175 "#%s before C++23 is a GCC extension",
2176 pfile->directive->name);
2177 else
2178 cpp_error (pfile, CPP_DL_PEDWARN,
2179 "#%s before C2X is a GCC extension",
2180 pfile->directive->name);
2182 pfile->state.skipping = skip;
2185 ifs->skip_elses = !pfile->state.skipping;
2188 /* Invalidate any controlling macro. */
2189 ifs->mi_cmacro = 0;
2193 /* Handle a #elifdef directive. */
2194 static void
2195 do_elifdef (cpp_reader *pfile)
2197 do_elif (pfile);
2200 /* Handle a #elifndef directive. */
2201 static void
2202 do_elifndef (cpp_reader *pfile)
2204 do_elif (pfile);
2207 /* #endif pops the if stack and resets pfile->state.skipping. */
2208 static void
2209 do_endif (cpp_reader *pfile)
2211 cpp_buffer *buffer = pfile->buffer;
2212 struct if_stack *ifs = buffer->if_stack;
2214 if (ifs == NULL)
2215 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2216 else
2218 /* Only check EOL if was not originally skipping. */
2219 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2220 check_eol_endif_labels (pfile);
2222 /* If potential control macro, we go back outside again. */
2223 if (ifs->next == 0 && ifs->mi_cmacro)
2225 pfile->mi_valid = true;
2226 pfile->mi_cmacro = ifs->mi_cmacro;
2229 buffer->if_stack = ifs->next;
2230 pfile->state.skipping = ifs->was_skipping;
2231 obstack_free (&pfile->buffer_ob, ifs);
2235 /* Push an if_stack entry for a preprocessor conditional, and set
2236 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2237 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2238 we need to check here that we are at the top of the file. */
2239 static void
2240 push_conditional (cpp_reader *pfile, int skip, int type,
2241 const cpp_hashnode *cmacro)
2243 struct if_stack *ifs;
2244 cpp_buffer *buffer = pfile->buffer;
2246 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2247 ifs->line = pfile->directive_line;
2248 ifs->next = buffer->if_stack;
2249 ifs->skip_elses = pfile->state.skipping || !skip;
2250 ifs->was_skipping = pfile->state.skipping;
2251 ifs->type = type;
2252 /* This condition is effectively a test for top-of-file. */
2253 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2254 ifs->mi_cmacro = cmacro;
2255 else
2256 ifs->mi_cmacro = 0;
2258 pfile->state.skipping = skip;
2259 buffer->if_stack = ifs;
2262 /* Read the tokens of the answer into the macro pool, in a directive
2263 of type TYPE. Only commit the memory if we intend it as permanent
2264 storage, i.e. the #assert case. Returns 0 on success, and sets
2265 ANSWERP to point to the answer. PRED_LOC is the location of the
2266 predicate. */
2267 static bool
2268 parse_answer (cpp_reader *pfile, int type, location_t pred_loc,
2269 cpp_macro **answer_ptr)
2271 /* In a conditional, it is legal to not have an open paren. We
2272 should save the following token in this case. */
2273 const cpp_token *paren = cpp_get_token (pfile);
2275 /* If not a paren, see if we're OK. */
2276 if (paren->type != CPP_OPEN_PAREN)
2278 /* In a conditional no answer is a test for any answer. It
2279 could be followed by any token. */
2280 if (type == T_IF)
2282 _cpp_backup_tokens (pfile, 1);
2283 return true;
2286 /* #unassert with no answer is valid - it removes all answers. */
2287 if (type == T_UNASSERT && paren->type == CPP_EOF)
2288 return true;
2290 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2291 "missing '(' after predicate");
2292 return false;
2295 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2296 _cpp_reserve_room (pfile, 0,
2297 sizeof (cpp_macro)));
2298 answer->parm.next = NULL;
2299 unsigned count = 0;
2300 for (;;)
2302 const cpp_token *token = cpp_get_token (pfile);
2304 if (token->type == CPP_CLOSE_PAREN)
2305 break;
2307 if (token->type == CPP_EOF)
2309 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2310 return false;
2313 answer = (cpp_macro *)_cpp_reserve_room
2314 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2315 sizeof (cpp_token));
2316 answer->exp.tokens[count++] = *token;
2319 if (!count)
2321 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2322 return false;
2325 /* Drop whitespace at start, for answer equivalence purposes. */
2326 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2328 answer->count = count;
2329 *answer_ptr = answer;
2331 return true;
2334 /* Parses an assertion directive of type TYPE, returning a pointer to
2335 the hash node of the predicate, or 0 on error. The node is
2336 guaranteed to be disjoint from the macro namespace, so can only
2337 have type 'NT_VOID'. If an answer was supplied, it is placed in
2338 *ANSWER_PTR, which is otherwise set to 0. */
2339 static cpp_hashnode *
2340 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2342 cpp_hashnode *result = 0;
2344 /* We don't expand predicates or answers. */
2345 pfile->state.prevent_expansion++;
2347 *answer_ptr = NULL;
2349 const cpp_token *predicate = cpp_get_token (pfile);
2350 if (predicate->type == CPP_EOF)
2351 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2352 else if (predicate->type != CPP_NAME)
2353 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2354 "predicate must be an identifier");
2355 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2357 unsigned int len = NODE_LEN (predicate->val.node.node);
2358 unsigned char *sym = (unsigned char *) alloca (len + 1);
2360 /* Prefix '#' to get it out of macro namespace. */
2361 sym[0] = '#';
2362 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2363 result = cpp_lookup (pfile, sym, len + 1);
2366 pfile->state.prevent_expansion--;
2368 return result;
2371 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2372 or a pointer to NULL if the answer is not in the chain. */
2373 static cpp_macro **
2374 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2376 unsigned int i;
2377 cpp_macro **result = NULL;
2379 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2381 cpp_macro *answer = *result;
2383 if (answer->count == candidate->count)
2385 for (i = 0; i < answer->count; i++)
2386 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2387 &candidate->exp.tokens[i]))
2388 break;
2390 if (i == answer->count)
2391 break;
2395 return result;
2398 /* Test an assertion within a preprocessor conditional. Returns
2399 nonzero on failure, zero on success. On success, the result of
2400 the test is written into VALUE, otherwise the value 0. */
2402 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2404 cpp_macro *answer;
2405 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2407 /* For recovery, an erroneous assertion expression is handled as a
2408 failing assertion. */
2409 *value = 0;
2411 if (node)
2413 if (node->value.answers)
2414 *value = !answer || *find_answer (node, answer);
2416 else if (pfile->cur_token[-1].type == CPP_EOF)
2417 _cpp_backup_tokens (pfile, 1);
2419 /* We don't commit the memory for the answer - it's temporary only. */
2420 return node == 0;
2423 /* Handle #assert. */
2424 static void
2425 do_assert (cpp_reader *pfile)
2427 cpp_macro *answer;
2428 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2430 if (node)
2432 /* Place the new answer in the answer list. First check there
2433 is not a duplicate. */
2434 if (*find_answer (node, answer))
2436 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2437 NODE_NAME (node) + 1);
2438 return;
2441 /* Commit or allocate storage for the answer. */
2442 answer = (cpp_macro *)_cpp_commit_buff
2443 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2444 + sizeof (cpp_token) * answer->count);
2446 /* Chain into the list. */
2447 answer->parm.next = node->value.answers;
2448 node->value.answers = answer;
2450 check_eol (pfile, false);
2454 /* Handle #unassert. */
2455 static void
2456 do_unassert (cpp_reader *pfile)
2458 cpp_macro *answer;
2459 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2461 /* It isn't an error to #unassert something that isn't asserted. */
2462 if (node)
2464 if (answer)
2466 cpp_macro **p = find_answer (node, answer);
2468 /* Remove the assert from the list. */
2469 if (cpp_macro *temp = *p)
2470 *p = temp->parm.next;
2472 check_eol (pfile, false);
2474 else
2475 _cpp_free_definition (node);
2478 /* We don't commit the memory for the answer - it's temporary only. */
2481 /* These are for -D, -U, -A. */
2483 /* Process the string STR as if it appeared as the body of a #define.
2484 If STR is just an identifier, define it with value 1.
2485 If STR has anything after the identifier, then it should
2486 be identifier=definition. */
2487 void
2488 cpp_define (cpp_reader *pfile, const char *str)
2490 char *buf;
2491 const char *p;
2492 size_t count;
2494 /* Copy the entire option so we can modify it.
2495 Change the first "=" in the string to a space. If there is none,
2496 tack " 1" on the end. */
2498 count = strlen (str);
2499 buf = (char *) alloca (count + 3);
2500 memcpy (buf, str, count);
2502 p = strchr (str, '=');
2503 if (p)
2504 buf[p - str] = ' ';
2505 else
2507 buf[count++] = ' ';
2508 buf[count++] = '1';
2510 buf[count] = '\n';
2512 run_directive (pfile, T_DEFINE, buf, count);
2515 /* Like cpp_define, but does not warn about unused macro. */
2516 void
2517 cpp_define_unused (cpp_reader *pfile, const char *str)
2519 unsigned char warn_unused_macros = CPP_OPTION (pfile, warn_unused_macros);
2520 CPP_OPTION (pfile, warn_unused_macros) = 0;
2521 cpp_define (pfile, str);
2522 CPP_OPTION (pfile, warn_unused_macros) = warn_unused_macros;
2525 /* Use to build macros to be run through cpp_define() as
2526 described above.
2527 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2529 void
2530 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2532 char *ptr;
2534 va_list ap;
2535 va_start (ap, fmt);
2536 ptr = xvasprintf (fmt, ap);
2537 va_end (ap);
2539 cpp_define (pfile, ptr);
2540 free (ptr);
2543 /* Like cpp_define_formatted, but does not warn about unused macro. */
2544 void
2545 cpp_define_formatted_unused (cpp_reader *pfile, const char *fmt, ...)
2547 char *ptr;
2549 va_list ap;
2550 va_start (ap, fmt);
2551 ptr = xvasprintf (fmt, ap);
2552 va_end (ap);
2554 cpp_define_unused (pfile, ptr);
2555 free (ptr);
2558 /* Slight variant of the above for use by initialize_builtins. */
2559 void
2560 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2562 size_t len = strlen (str);
2563 char *buf = (char *) alloca (len + 1);
2564 memcpy (buf, str, len);
2565 buf[len] = '\n';
2566 run_directive (pfile, T_DEFINE, buf, len);
2569 /* Process MACRO as if it appeared as the body of an #undef. */
2570 void
2571 cpp_undef (cpp_reader *pfile, const char *macro)
2573 size_t len = strlen (macro);
2574 char *buf = (char *) alloca (len + 1);
2575 memcpy (buf, macro, len);
2576 buf[len] = '\n';
2577 run_directive (pfile, T_UNDEF, buf, len);
2580 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2581 or first element is zero, then the macro should be undefined. */
2582 static void
2583 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2585 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2586 if (node == NULL)
2587 return;
2589 if (pfile->cb.before_define)
2590 pfile->cb.before_define (pfile);
2592 if (cpp_macro_p (node))
2594 if (pfile->cb.undef)
2595 pfile->cb.undef (pfile, pfile->directive_line, node);
2596 if (CPP_OPTION (pfile, warn_unused_macros))
2597 _cpp_warn_if_unused_macro (pfile, node, NULL);
2598 _cpp_free_definition (node);
2601 if (c->is_undef)
2602 return;
2603 if (c->is_builtin)
2605 _cpp_restore_special_builtin (pfile, c);
2606 return;
2610 size_t namelen;
2611 const uchar *dn;
2612 cpp_hashnode *h = NULL;
2613 cpp_buffer *nbuf;
2615 namelen = ustrcspn (c->definition, "( \n");
2616 h = cpp_lookup (pfile, c->definition, namelen);
2617 dn = c->definition + namelen;
2619 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2620 if (nbuf != NULL)
2622 _cpp_clean_line (pfile);
2623 nbuf->sysp = 1;
2624 if (!_cpp_create_definition (pfile, h))
2625 abort ();
2626 _cpp_pop_buffer (pfile);
2628 else
2629 abort ();
2630 h->value.macro->line = c->line;
2631 h->value.macro->syshdr = c->syshdr;
2632 h->value.macro->used = c->used;
2636 /* Process the string STR as if it appeared as the body of a #assert. */
2637 void
2638 cpp_assert (cpp_reader *pfile, const char *str)
2640 handle_assertion (pfile, str, T_ASSERT);
2643 /* Process STR as if it appeared as the body of an #unassert. */
2644 void
2645 cpp_unassert (cpp_reader *pfile, const char *str)
2647 handle_assertion (pfile, str, T_UNASSERT);
2650 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2651 static void
2652 handle_assertion (cpp_reader *pfile, const char *str, int type)
2654 size_t count = strlen (str);
2655 const char *p = strchr (str, '=');
2657 /* Copy the entire option so we can modify it. Change the first
2658 "=" in the string to a '(', and tack a ')' on the end. */
2659 char *buf = (char *) alloca (count + 2);
2661 memcpy (buf, str, count);
2662 if (p)
2664 buf[p - str] = '(';
2665 buf[count++] = ')';
2667 buf[count] = '\n';
2668 str = buf;
2670 run_directive (pfile, type, str, count);
2673 /* The options structure. */
2674 cpp_options *
2675 cpp_get_options (cpp_reader *pfile)
2677 return &pfile->opts;
2680 /* The callbacks structure. */
2681 cpp_callbacks *
2682 cpp_get_callbacks (cpp_reader *pfile)
2684 return &pfile->cb;
2687 /* Copy the given callbacks structure to our own. */
2688 void
2689 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2691 pfile->cb = *cb;
2694 /* The narrow character set identifier. */
2695 const char *
2696 cpp_get_narrow_charset_name (cpp_reader *pfile)
2698 return pfile->narrow_cset_desc.to;
2701 /* The wide character set identifier. */
2702 const char *
2703 cpp_get_wide_charset_name (cpp_reader *pfile)
2705 return pfile->wide_cset_desc.to;
2708 /* The dependencies structure. (Creates one if it hasn't already been.) */
2709 class mkdeps *
2710 cpp_get_deps (cpp_reader *pfile)
2712 if (!pfile->deps && CPP_OPTION (pfile, deps.style) != DEPS_NONE)
2713 pfile->deps = deps_init ();
2714 return pfile->deps;
2717 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2718 doesn't fail. It does not generate a file change call back; that
2719 is the responsibility of the caller. */
2720 cpp_buffer *
2721 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2722 int from_stage3)
2724 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2726 /* Clears, amongst other things, if_stack and mi_cmacro. */
2727 memset (new_buffer, 0, sizeof (cpp_buffer));
2729 new_buffer->next_line = new_buffer->buf = buffer;
2730 new_buffer->rlimit = buffer + len;
2731 new_buffer->from_stage3 = from_stage3;
2732 new_buffer->prev = pfile->buffer;
2733 new_buffer->need_line = true;
2735 pfile->buffer = new_buffer;
2737 return new_buffer;
2740 /* Pops a single buffer, with a file change call-back if appropriate.
2741 Then pushes the next -include file, if any remain. */
2742 void
2743 _cpp_pop_buffer (cpp_reader *pfile)
2745 cpp_buffer *buffer = pfile->buffer;
2746 struct _cpp_file *inc = buffer->file;
2747 struct if_stack *ifs;
2748 const unsigned char *to_free;
2750 /* Walk back up the conditional stack till we reach its level at
2751 entry to this file, issuing error messages. */
2752 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2753 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2754 "unterminated #%s", dtable[ifs->type].name);
2756 /* In case of a missing #endif. */
2757 pfile->state.skipping = 0;
2759 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2760 pfile->buffer = buffer->prev;
2762 to_free = buffer->to_free;
2763 free (buffer->notes);
2765 /* Free the buffer object now; we may want to push a new buffer
2766 in _cpp_push_next_include_file. */
2767 obstack_free (&pfile->buffer_ob, buffer);
2769 if (inc)
2771 _cpp_pop_file_buffer (pfile, inc, to_free);
2773 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2775 else if (to_free)
2776 free ((void *)to_free);
2779 /* Enter all recognized directives in the hash table. */
2780 void
2781 _cpp_init_directives (cpp_reader *pfile)
2783 for (int i = 0; i < N_DIRECTIVES; i++)
2785 cpp_hashnode *node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2786 node->is_directive = 1;
2787 node->directive_index = i;
2791 /* Extract header file from a bracket include. Parsing starts after '<'.
2792 The string is malloced and must be freed by the caller. */
2793 char *
2794 _cpp_bracket_include(cpp_reader *pfile)
2796 return glue_header_name (pfile);