Daily bump.
[official-gcc.git] / libcpp / directives.cc
blobee5419d1f40965aecf7ce641148ef9a4c700b817
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2023 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, STDC2X, 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 == &dtable[T_WARNING])
390 if (CPP_PEDANTIC (pfile) && !CPP_OPTION (pfile, warning_directive))
392 if (CPP_OPTION (pfile, cplusplus))
393 cpp_error (pfile, CPP_DL_PEDWARN,
394 "#%s before C++23 is a GCC extension", dir->name);
395 else
396 cpp_error (pfile, CPP_DL_PEDWARN,
397 "#%s before C2X is a GCC extension", dir->name);
399 else if (CPP_OPTION (pfile, cpp_warn_c11_c2x_compat) > 0)
400 cpp_warning (pfile, CPP_W_C11_C2X_COMPAT,
401 "#%s before C2X is a GCC extension", dir->name);
403 else if (((dir->flags & DEPRECATED) != 0
404 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
405 && CPP_OPTION (pfile, cpp_warn_deprecated))
406 cpp_warning (pfile, CPP_W_DEPRECATED,
407 "#%s is a deprecated GCC extension", dir->name);
410 /* Traditionally, a directive is ignored unless its # is in
411 column 1. Therefore in code intended to work with K+R
412 compilers, directives added by C89 must have their #
413 indented, and directives present in traditional C must not.
414 This is true even of directives in skipped conditional
415 blocks. #elif cannot be used at all. */
416 if (CPP_WTRADITIONAL (pfile))
418 if (dir == &dtable[T_ELIF])
419 cpp_warning (pfile, CPP_W_TRADITIONAL,
420 "suggest not using #elif in traditional C");
421 else if (indented && dir->origin == KANDR)
422 cpp_warning (pfile, CPP_W_TRADITIONAL,
423 "traditional C ignores #%s with the # indented",
424 dir->name);
425 else if (!indented && dir->origin != KANDR)
426 cpp_warning (pfile, CPP_W_TRADITIONAL,
427 "suggest hiding #%s from traditional C with an indented #",
428 dir->name);
432 /* Check if we have a known directive. INDENTED is true if the
433 '#' of the directive was indented. This function is in this file
434 to save unnecessarily exporting dtable etc. to lex.cc. Returns
435 nonzero if the line of tokens has been handled, zero if we should
436 continue processing the line. */
438 _cpp_handle_directive (cpp_reader *pfile, bool indented)
440 const directive *dir = 0;
441 const cpp_token *dname;
442 bool was_parsing_args = pfile->state.parsing_args;
443 bool was_discarding_output = pfile->state.discarding_output;
444 int skip = 1;
446 if (was_discarding_output)
447 pfile->state.prevent_expansion = 0;
449 if (was_parsing_args)
451 if (CPP_OPTION (pfile, cpp_pedantic))
452 cpp_error (pfile, CPP_DL_PEDWARN,
453 "embedding a directive within macro arguments is not portable");
454 pfile->state.parsing_args = 0;
455 pfile->state.prevent_expansion = 0;
457 start_directive (pfile);
458 dname = _cpp_lex_token (pfile);
460 if (dname->type == CPP_NAME)
462 if (dname->val.node.node->is_directive)
464 dir = &dtable[dname->val.node.node->directive_index];
465 if ((dir->flags & ELIFDEF)
466 && !CPP_OPTION (pfile, elifdef)
467 /* For -std=gnu* modes elifdef is supported with
468 a pedwarn if pedantic. */
469 && CPP_OPTION (pfile, std))
470 dir = 0;
473 /* We do not recognize the # followed by a number extension in
474 assembler code. */
475 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
477 dir = &linemarker_dir;
478 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
479 && ! pfile->state.skipping)
480 cpp_error (pfile, CPP_DL_PEDWARN,
481 "style of line directive is a GCC extension");
484 if (dir)
486 /* If we have a directive that is not an opening conditional,
487 invalidate any control macro. */
488 if (! (dir->flags & IF_COND))
489 pfile->mi_valid = false;
491 /* Kluge alert. In order to be sure that code like this
493 #define HASH #
494 HASH define foo bar
496 does not cause '#define foo bar' to get executed when
497 compiled with -save-temps, we recognize directives in
498 -fpreprocessed mode only if the # is in column 1. macro.cc
499 puts a space in front of any '#' at the start of a macro.
501 We exclude the -fdirectives-only case because macro expansion
502 has not been performed yet, and block comments can cause spaces
503 to precede the directive. */
504 if (CPP_OPTION (pfile, preprocessed)
505 && !CPP_OPTION (pfile, directives_only)
506 && (indented || !(dir->flags & IN_I)))
508 skip = 0;
509 dir = 0;
511 else
513 /* In failed conditional groups, all non-conditional
514 directives are ignored. Before doing that, whether
515 skipping or not, we should lex angle-bracketed headers
516 correctly, and maybe output some diagnostics. */
517 pfile->state.angled_headers = dir->flags & INCL;
518 pfile->state.directive_wants_padding = dir->flags & INCL;
519 if (! CPP_OPTION (pfile, preprocessed))
520 directive_diagnostics (pfile, dir, indented);
521 if (pfile->state.skipping && !(dir->flags & COND))
522 dir = 0;
525 else if (dname->type == CPP_EOF)
526 ; /* CPP_EOF is the "null directive". */
527 else
529 /* An unknown directive. Don't complain about it in assembly
530 source: we don't know where the comments are, and # may
531 introduce assembler pseudo-ops. Don't complain about invalid
532 directives in skipped conditional groups (6.10 p4). */
533 if (CPP_OPTION (pfile, lang) == CLK_ASM)
534 skip = 0;
535 else if (!pfile->state.skipping)
537 const char *unrecognized
538 = (const char *)cpp_token_as_text (pfile, dname);
539 const char *hint = NULL;
541 /* Call back into gcc to get a spelling suggestion. Ideally
542 we'd just use best_match from gcc/spellcheck.h (and filter
543 out the uncommon directives), but that requires moving it
544 to a support library. */
545 if (pfile->cb.get_suggestion)
546 hint = pfile->cb.get_suggestion (pfile, unrecognized,
547 directive_names);
549 if (hint)
551 rich_location richloc (pfile->line_table, dname->src_loc);
552 source_range misspelled_token_range
553 = get_range_from_loc (pfile->line_table, dname->src_loc);
554 richloc.add_fixit_replace (misspelled_token_range, hint);
555 cpp_error_at (pfile, CPP_DL_ERROR, &richloc,
556 "invalid preprocessing directive #%s;"
557 " did you mean #%s?",
558 unrecognized, hint);
560 else
561 cpp_error (pfile, CPP_DL_ERROR,
562 "invalid preprocessing directive #%s",
563 unrecognized);
567 pfile->directive = dir;
568 if (CPP_OPTION (pfile, traditional))
569 prepare_directive_trad (pfile);
571 if (dir)
572 pfile->directive->handler (pfile);
573 else if (skip == 0)
574 _cpp_backup_tokens (pfile, 1);
576 end_directive (pfile, skip);
577 if (was_parsing_args && !pfile->state.in_deferred_pragma)
579 /* Restore state when within macro args. */
580 pfile->state.parsing_args = 2;
581 pfile->state.prevent_expansion = 1;
583 if (was_discarding_output)
584 pfile->state.prevent_expansion = 1;
585 return skip;
588 /* Directive handler wrapper used by the command line option
589 processor. BUF is \n terminated. */
590 static void
591 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
593 cpp_push_buffer (pfile, (const uchar *) buf, count,
594 /* from_stage3 */ true);
595 start_directive (pfile);
597 /* This is a short-term fix to prevent a leading '#' being
598 interpreted as a directive. */
599 _cpp_clean_line (pfile);
601 pfile->directive = &dtable[dir_no];
602 if (CPP_OPTION (pfile, traditional))
603 prepare_directive_trad (pfile);
604 pfile->directive->handler (pfile);
605 end_directive (pfile, 1);
606 _cpp_pop_buffer (pfile);
609 /* Checks for validity the macro name in #define, #undef, #ifdef and
610 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
611 processing a #define or #undefine directive, and false
612 otherwise. */
613 static cpp_hashnode *
614 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
616 const cpp_token *token = _cpp_lex_token (pfile);
618 /* The token immediately after #define must be an identifier. That
619 identifier may not be "defined", per C99 6.10.8p4.
620 In C++, it may not be any of the "named operators" either,
621 per C++98 [lex.digraph], [lex.key].
622 Finally, the identifier may not have been poisoned. (In that case
623 the lexer has issued the error message for us.) */
625 if (token->type == CPP_NAME)
627 cpp_hashnode *node = token->val.node.node;
629 if (is_def_or_undef
630 && node == pfile->spec_nodes.n_defined)
631 cpp_error (pfile, CPP_DL_ERROR,
632 "\"%s\" cannot be used as a macro name",
633 NODE_NAME (node));
634 else if (! (node->flags & NODE_POISONED))
635 return node;
637 else if (token->flags & NAMED_OP)
638 cpp_error (pfile, CPP_DL_ERROR,
639 "\"%s\" cannot be used as a macro name as it is an operator in C++",
640 NODE_NAME (token->val.node.node));
641 else if (token->type == CPP_EOF)
642 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
643 pfile->directive->name);
644 else
645 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
647 return NULL;
650 /* Process a #define directive. Most work is done in macro.cc. */
651 static void
652 do_define (cpp_reader *pfile)
654 cpp_hashnode *node = lex_macro_node (pfile, true);
656 if (node)
658 /* This is a better location than pfile->directive_line to store
659 as the macro location. */
660 const location_t name_loc = cpp_diagnostic_get_current_location (pfile);
662 /* If we have been requested to expand comments into macros,
663 then re-enable saving of comments. */
664 pfile->state.save_comments =
665 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
667 if (pfile->cb.before_define)
668 pfile->cb.before_define (pfile);
670 if (_cpp_create_definition (pfile, node, name_loc))
671 if (pfile->cb.define)
672 pfile->cb.define (pfile, pfile->directive_line, node);
674 node->flags &= ~NODE_USED;
678 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
679 static void
680 do_undef (cpp_reader *pfile)
682 cpp_hashnode *node = lex_macro_node (pfile, true);
684 if (node)
686 if (pfile->cb.before_define)
687 pfile->cb.before_define (pfile);
689 if (pfile->cb.undef)
690 pfile->cb.undef (pfile, pfile->directive_line, node);
692 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
693 identifier is not currently defined as a macro name. */
694 if (cpp_macro_p (node))
696 if (node->flags & NODE_WARN)
697 cpp_error (pfile, CPP_DL_WARNING,
698 "undefining \"%s\"", NODE_NAME (node));
699 else if (cpp_builtin_macro_p (node)
700 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
701 cpp_warning (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
702 "undefining \"%s\"", NODE_NAME (node));
704 if (node->value.macro
705 && CPP_OPTION (pfile, warn_unused_macros))
706 _cpp_warn_if_unused_macro (pfile, node, NULL);
708 _cpp_free_definition (node);
712 check_eol (pfile, false);
715 /* Undefine a single macro/assertion/whatever. */
717 static int
718 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
719 void *data_p ATTRIBUTE_UNUSED)
721 /* Body of _cpp_free_definition inlined here for speed.
722 Macros and assertions no longer have anything to free. */
723 h->type = NT_VOID;
724 h->value.answers = NULL;
725 h->flags &= ~(NODE_POISONED|NODE_DISABLED|NODE_USED);
726 return 1;
729 /* Undefine all macros and assertions. */
731 void
732 cpp_undef_all (cpp_reader *pfile)
734 cpp_forall_identifiers (pfile, undefine_macros, NULL);
738 /* Helper routine used by parse_include. Reinterpret the current line
739 as an h-char-sequence (< ... >); we are looking at the first token
740 after the <. Returns a malloced filename. */
741 static char *
742 glue_header_name (cpp_reader *pfile)
744 const cpp_token *token;
745 char *buffer;
746 size_t len, total_len = 0, capacity = 1024;
748 /* To avoid lexed tokens overwriting our glued name, we can only
749 allocate from the string pool once we've lexed everything. */
750 buffer = XNEWVEC (char, capacity);
751 for (;;)
753 token = get_token_no_padding (pfile);
755 if (token->type == CPP_GREATER)
756 break;
757 if (token->type == CPP_EOF)
759 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
760 break;
763 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
764 if (total_len + len > capacity)
766 capacity = (capacity + len) * 2;
767 buffer = XRESIZEVEC (char, buffer, capacity);
770 if (token->flags & PREV_WHITE)
771 buffer[total_len++] = ' ';
773 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
774 true)
775 - (uchar *) buffer);
778 buffer[total_len] = '\0';
779 return buffer;
782 /* Returns the file name of #include, #include_next, #import and
783 #pragma dependency. The string is malloced and the caller should
784 free it. Returns NULL on error. LOCATION is the source location
785 of the file name. */
787 static const char *
788 parse_include (cpp_reader *pfile, int *pangle_brackets,
789 const cpp_token ***buf, location_t *location)
791 char *fname;
792 const cpp_token *header;
794 /* Allow macro expansion. */
795 header = get_token_no_padding (pfile);
796 *location = header->src_loc;
797 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
798 || header->type == CPP_HEADER_NAME)
800 fname = XNEWVEC (char, header->val.str.len - 1);
801 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
802 fname[header->val.str.len - 2] = '\0';
803 *pangle_brackets = header->type == CPP_HEADER_NAME;
805 else if (header->type == CPP_LESS)
807 fname = glue_header_name (pfile);
808 *pangle_brackets = 1;
810 else
812 const unsigned char *dir;
814 if (pfile->directive == &dtable[T_PRAGMA])
815 dir = UC"pragma dependency";
816 else
817 dir = pfile->directive->name;
818 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
819 dir);
821 return NULL;
824 if (pfile->directive == &dtable[T_PRAGMA])
826 /* This pragma allows extra tokens after the file name. */
828 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
829 check_eol (pfile, true);
830 else
832 /* If we are not discarding comments, then gather them while
833 doing the eol check. */
834 *buf = check_eol_return_comments (pfile);
837 return fname;
840 /* Handle #include, #include_next and #import. */
841 static void
842 do_include_common (cpp_reader *pfile, enum include_type type)
844 const char *fname;
845 int angle_brackets;
846 const cpp_token **buf = NULL;
847 location_t location;
849 /* Re-enable saving of comments if requested, so that the include
850 callback can dump comments which follow #include. */
851 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
853 /* Tell the lexer this is an include directive -- we want it to
854 increment the line number even if this is the last line of a file. */
855 pfile->state.in_directive = 2;
857 fname = parse_include (pfile, &angle_brackets, &buf, &location);
858 if (!fname)
859 goto done;
861 if (!*fname)
863 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
864 "empty filename in #%s",
865 pfile->directive->name);
866 goto done;
869 /* Prevent #include recursion. */
870 if (pfile->line_table->depth >= CPP_OPTION (pfile, max_include_depth))
871 cpp_error (pfile,
872 CPP_DL_ERROR,
873 "#include nested depth %u exceeds maximum of %u"
874 " (use -fmax-include-depth=DEPTH to increase the maximum)",
875 pfile->line_table->depth,
876 CPP_OPTION (pfile, max_include_depth));
877 else
879 /* Get out of macro context, if we are. */
880 skip_rest_of_line (pfile);
882 if (pfile->cb.include)
883 pfile->cb.include (pfile, pfile->directive_line,
884 pfile->directive->name, fname, angle_brackets,
885 buf);
887 _cpp_stack_include (pfile, fname, angle_brackets, type, location);
890 done:
891 XDELETEVEC (fname);
892 if (buf)
893 XDELETEVEC (buf);
896 static void
897 do_include (cpp_reader *pfile)
899 do_include_common (pfile, IT_INCLUDE);
902 static void
903 do_import (cpp_reader *pfile)
905 do_include_common (pfile, IT_IMPORT);
908 static void
909 do_include_next (cpp_reader *pfile)
911 enum include_type type = IT_INCLUDE_NEXT;
913 /* If this is the primary source file, warn and use the normal
914 search logic. */
915 if (_cpp_in_main_source_file (pfile))
917 cpp_error (pfile, CPP_DL_WARNING,
918 "#include_next in primary source file");
919 type = IT_INCLUDE;
921 do_include_common (pfile, type);
924 /* Subroutine of do_linemarker. Read possible flags after file name.
925 LAST is the last flag seen; 0 if this is the first flag. Return the
926 flag if it is valid, 0 at the end of the directive. Otherwise
927 complain. */
928 static unsigned int
929 read_flag (cpp_reader *pfile, unsigned int last)
931 const cpp_token *token = _cpp_lex_token (pfile);
933 if (token->type == CPP_NUMBER && token->val.str.len == 1)
935 unsigned int flag = token->val.str.text[0] - '0';
937 if (flag > last && flag <= 4
938 && (flag != 4 || last == 3)
939 && (flag != 2 || last == 0))
940 return flag;
943 if (token->type != CPP_EOF)
944 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
945 cpp_token_as_text (pfile, token));
946 return 0;
949 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
950 of length LEN, to binary; store it in NUMP, and return false if the
951 number was well-formed, true if not. WRAPPED is set to true if the
952 number did not fit into 'linenum_type'. */
953 static bool
954 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
956 linenum_type reg = 0;
958 uchar c;
959 bool seen_digit_sep = false;
960 *wrapped = false;
961 while (len--)
963 c = *str++;
964 if (!seen_digit_sep && c == '\'' && len)
966 seen_digit_sep = true;
967 continue;
969 if (!ISDIGIT (c))
970 return true;
971 seen_digit_sep = false;
972 if (reg > ((linenum_type) -1) / 10)
973 *wrapped = true;
974 reg *= 10;
975 if (reg > ((linenum_type) -1) - (c - '0'))
976 *wrapped = true;
977 reg += c - '0';
979 *nump = reg;
980 return false;
983 /* Interpret #line command.
984 Note that the filename string (if any) is a true string constant
985 (escapes are interpreted). */
986 static void
987 do_line (cpp_reader *pfile)
989 class line_maps *line_table = pfile->line_table;
990 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
992 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
993 sysp right now. */
995 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
996 const cpp_token *token;
997 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
998 linenum_type new_lineno;
1000 /* C99 raised the minimum limit on #line numbers. */
1001 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
1002 bool wrapped;
1004 /* #line commands expand macros. */
1005 token = cpp_get_token (pfile);
1006 if (token->type != CPP_NUMBER
1007 || strtolinenum (token->val.str.text, token->val.str.len,
1008 &new_lineno, &wrapped))
1010 if (token->type == CPP_EOF)
1011 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
1012 else
1013 cpp_error (pfile, CPP_DL_ERROR,
1014 "\"%s\" after #line is not a positive integer",
1015 cpp_token_as_text (pfile, token));
1016 return;
1019 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
1020 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
1021 else if (wrapped)
1022 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
1024 token = cpp_get_token (pfile);
1025 if (token->type == CPP_STRING)
1027 cpp_string s = { 0, 0 };
1028 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
1029 &s, CPP_STRING))
1030 new_file = (const char *)s.text;
1031 check_eol (pfile, true);
1033 else if (token->type != CPP_EOF)
1035 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1036 cpp_token_as_text (pfile, token));
1037 return;
1040 skip_rest_of_line (pfile);
1041 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1042 map_sysp);
1043 line_table->seen_line_directive = true;
1046 /* Interpret the # 44 "file" [flags] notation, which has slightly
1047 different syntax and semantics from #line: Flags are allowed,
1048 and we never complain about the line number being too big. */
1049 static void
1050 do_linemarker (cpp_reader *pfile)
1052 class line_maps *line_table = pfile->line_table;
1053 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1054 const cpp_token *token;
1055 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1056 linenum_type new_lineno;
1057 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1058 enum lc_reason reason = LC_RENAME_VERBATIM;
1059 int flag;
1060 bool wrapped;
1062 /* Back up so we can get the number again. Putting this in
1063 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1064 some circumstances, which can segfault. */
1065 _cpp_backup_tokens (pfile, 1);
1067 /* #line commands expand macros. */
1068 token = cpp_get_token (pfile);
1069 if (token->type != CPP_NUMBER
1070 || strtolinenum (token->val.str.text, token->val.str.len,
1071 &new_lineno, &wrapped))
1073 /* Unlike #line, there does not seem to be a way to get an EOF
1074 here. So, it should be safe to always spell the token. */
1075 cpp_error (pfile, CPP_DL_ERROR,
1076 "\"%s\" after # is not a positive integer",
1077 cpp_token_as_text (pfile, token));
1078 return;
1081 token = cpp_get_token (pfile);
1082 if (token->type == CPP_STRING)
1084 cpp_string s = { 0, 0 };
1085 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1086 1, &s, CPP_STRING))
1087 new_file = (const char *)s.text;
1089 new_sysp = 0;
1090 flag = read_flag (pfile, 0);
1091 if (flag == 1)
1093 reason = LC_ENTER;
1094 /* Fake an include for cpp_included (). */
1095 _cpp_fake_include (pfile, new_file);
1096 flag = read_flag (pfile, flag);
1098 else if (flag == 2)
1100 reason = LC_LEAVE;
1101 flag = read_flag (pfile, flag);
1103 if (flag == 3)
1105 new_sysp = 1;
1106 flag = read_flag (pfile, flag);
1107 if (flag == 4)
1108 new_sysp = 2;
1110 pfile->buffer->sysp = new_sysp;
1112 check_eol (pfile, false);
1114 else if (token->type != CPP_EOF)
1116 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1117 cpp_token_as_text (pfile, token));
1118 return;
1121 skip_rest_of_line (pfile);
1123 if (reason == LC_LEAVE)
1125 /* Reread map since cpp_get_token can invalidate it with a
1126 reallocation. */
1127 map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1128 const line_map_ordinary *from
1129 = linemap_included_from_linemap (line_table, map);
1131 if (!from)
1132 /* Not nested. */;
1133 else if (!new_file[0])
1134 /* Leaving to "" means fill in the popped-to name. */
1135 new_file = ORDINARY_MAP_FILE_NAME (from);
1136 else if (filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0)
1137 /* It's the wrong name, Grommit! */
1138 from = NULL;
1140 if (!from)
1142 cpp_warning (pfile, CPP_W_NONE,
1143 "file \"%s\" linemarker ignored due to "
1144 "incorrect nesting", new_file);
1145 return;
1149 /* Compensate for the increment in linemap_add that occurs in
1150 _cpp_do_file_change. We're currently at the start of the line
1151 *following* the #line directive. A separate location_t for this
1152 location makes no sense (until we do the LC_LEAVE), and
1153 complicates LAST_SOURCE_LINE_LOCATION. */
1154 pfile->line_table->highest_location--;
1156 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1157 line_table->seen_line_directive = true;
1160 /* Arrange the file_change callback. Changing to TO_FILE:TO_LINE for
1161 REASON. SYSP is 1 for a system header, 2 for a system header that
1162 needs to be extern "C" protected, and zero otherwise. */
1163 void
1164 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1165 const char *to_file, linenum_type to_line,
1166 unsigned int sysp)
1168 linemap_assert (reason != LC_ENTER_MACRO);
1170 const line_map_ordinary *ord_map = NULL;
1171 if (!to_line && reason == LC_RENAME_VERBATIM)
1173 /* A linemarker moving to line zero. If we're on the second
1174 line of the current map, and it also starts at zero, just
1175 rewind -- we're probably reading the builtins of a
1176 preprocessed source. */
1177 line_map_ordinary *last = LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table);
1178 if (!ORDINARY_MAP_STARTING_LINE_NUMBER (last)
1179 && 0 == filename_cmp (to_file, ORDINARY_MAP_FILE_NAME (last))
1180 && SOURCE_LINE (last, pfile->line_table->highest_line) == 2)
1182 ord_map = last;
1183 pfile->line_table->highest_location
1184 = pfile->line_table->highest_line = MAP_START_LOCATION (last);
1188 if (!ord_map)
1189 if (const line_map *map = linemap_add (pfile->line_table, reason, sysp,
1190 to_file, to_line))
1192 ord_map = linemap_check_ordinary (map);
1193 linemap_line_start (pfile->line_table,
1194 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1195 127);
1198 if (pfile->cb.file_change)
1199 pfile->cb.file_change (pfile, ord_map);
1202 /* Report a warning or error detected by the program we are
1203 processing. Use the directive's tokens in the error message. */
1204 static void
1205 do_diagnostic (cpp_reader *pfile, enum cpp_diagnostic_level code,
1206 enum cpp_warning_reason reason, int print_dir)
1208 const unsigned char *dir_name;
1209 unsigned char *line;
1210 location_t src_loc = pfile->cur_token[-1].src_loc;
1212 if (print_dir)
1213 dir_name = pfile->directive->name;
1214 else
1215 dir_name = NULL;
1216 pfile->state.prevent_expansion++;
1217 line = cpp_output_line_to_string (pfile, dir_name);
1218 pfile->state.prevent_expansion--;
1220 if (code == CPP_DL_WARNING_SYSHDR && reason)
1221 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1222 else if (code == CPP_DL_WARNING && reason)
1223 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1224 else
1225 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1226 free (line);
1229 static void
1230 do_error (cpp_reader *pfile)
1232 do_diagnostic (pfile, CPP_DL_ERROR, CPP_W_NONE, 1);
1235 static void
1236 do_warning (cpp_reader *pfile)
1238 /* We want #warning diagnostics to be emitted in system headers too. */
1239 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1242 /* Report program identification. */
1243 static void
1244 do_ident (cpp_reader *pfile)
1246 const cpp_token *str = cpp_get_token (pfile);
1248 if (str->type != CPP_STRING)
1249 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1250 pfile->directive->name);
1251 else if (pfile->cb.ident)
1252 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1254 check_eol (pfile, false);
1257 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1258 matching entry, or NULL if none is found. The returned entry could
1259 be the start of a namespace chain, or a pragma. */
1260 static struct pragma_entry *
1261 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1263 while (chain && chain->pragma != pragma)
1264 chain = chain->next;
1266 return chain;
1269 /* Create and insert a blank pragma entry at the beginning of a
1270 singly-linked CHAIN. */
1271 static struct pragma_entry *
1272 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1274 struct pragma_entry *new_entry;
1276 new_entry = (struct pragma_entry *)
1277 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1279 memset (new_entry, 0, sizeof (struct pragma_entry));
1280 new_entry->next = *chain;
1282 *chain = new_entry;
1283 return new_entry;
1286 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1287 goes in the global namespace. */
1288 static struct pragma_entry *
1289 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1290 bool allow_name_expansion)
1292 struct pragma_entry **chain = &pfile->pragmas;
1293 struct pragma_entry *entry;
1294 const cpp_hashnode *node;
1296 if (space)
1298 node = cpp_lookup (pfile, UC space, strlen (space));
1299 entry = lookup_pragma_entry (*chain, node);
1300 if (!entry)
1302 entry = new_pragma_entry (pfile, chain);
1303 entry->pragma = node;
1304 entry->is_nspace = true;
1305 entry->allow_expansion = allow_name_expansion;
1307 else if (!entry->is_nspace)
1308 goto clash;
1309 else if (entry->allow_expansion != allow_name_expansion)
1311 cpp_error (pfile, CPP_DL_ICE,
1312 "registering pragmas in namespace \"%s\" with mismatched "
1313 "name expansion", space);
1314 return NULL;
1316 chain = &entry->u.space;
1318 else if (allow_name_expansion)
1320 cpp_error (pfile, CPP_DL_ICE,
1321 "registering pragma \"%s\" with name expansion "
1322 "and no namespace", name);
1323 return NULL;
1326 /* Check for duplicates. */
1327 node = cpp_lookup (pfile, UC name, strlen (name));
1328 entry = lookup_pragma_entry (*chain, node);
1329 if (entry == NULL)
1331 entry = new_pragma_entry (pfile, chain);
1332 entry->pragma = node;
1333 return entry;
1336 if (entry->is_nspace)
1337 clash:
1338 cpp_error (pfile, CPP_DL_ICE,
1339 "registering \"%s\" as both a pragma and a pragma namespace",
1340 NODE_NAME (node));
1341 else if (space)
1342 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1343 space, name);
1344 else
1345 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1347 return NULL;
1350 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1351 static void
1352 register_pragma_internal (cpp_reader *pfile, const char *space,
1353 const char *name, pragma_cb handler)
1355 struct pragma_entry *entry;
1357 entry = register_pragma_1 (pfile, space, name, false);
1358 entry->is_internal = true;
1359 entry->u.handler = handler;
1362 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1363 goes in the global namespace. HANDLER is the handler it will call,
1364 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1365 expansion while parsing pragma NAME. This function is exported
1366 from libcpp. */
1367 void
1368 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1369 pragma_cb handler, bool allow_expansion)
1371 struct pragma_entry *entry;
1373 if (!handler)
1375 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1376 return;
1379 entry = register_pragma_1 (pfile, space, name, false);
1380 if (entry)
1382 entry->allow_expansion = allow_expansion;
1383 entry->u.handler = handler;
1387 /* Similarly, but create mark the pragma for deferred processing.
1388 When found, a CPP_PRAGMA token will be insertted into the stream
1389 with IDENT in the token->u.pragma slot. */
1390 void
1391 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1392 const char *name, unsigned int ident,
1393 bool allow_expansion, bool allow_name_expansion)
1395 struct pragma_entry *entry;
1397 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1398 if (entry)
1400 entry->is_deferred = true;
1401 entry->allow_expansion = allow_expansion;
1402 entry->u.ident = ident;
1406 /* Register the pragmas the preprocessor itself handles. */
1407 void
1408 _cpp_init_internal_pragmas (cpp_reader *pfile)
1410 /* Pragmas in the global namespace. */
1411 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1412 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1413 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1415 /* New GCC-specific pragmas should be put in the GCC namespace. */
1416 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1417 register_pragma_internal (pfile, "GCC", "system_header",
1418 do_pragma_system_header);
1419 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1420 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1421 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1424 /* Return the number of registered pragmas in PE. */
1426 static int
1427 count_registered_pragmas (struct pragma_entry *pe)
1429 int ct = 0;
1430 for (; pe != NULL; pe = pe->next)
1432 if (pe->is_nspace)
1433 ct += count_registered_pragmas (pe->u.space);
1434 ct++;
1436 return ct;
1439 /* Save into SD the names of the registered pragmas referenced by PE,
1440 and return a pointer to the next free space in SD. */
1442 static char **
1443 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1445 for (; pe != NULL; pe = pe->next)
1447 if (pe->is_nspace)
1448 sd = save_registered_pragmas (pe->u.space, sd);
1449 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1450 HT_LEN (&pe->pragma->ident),
1451 HT_LEN (&pe->pragma->ident) + 1);
1453 return sd;
1456 /* Return a newly-allocated array which saves the names of the
1457 registered pragmas. */
1459 char **
1460 _cpp_save_pragma_names (cpp_reader *pfile)
1462 int ct = count_registered_pragmas (pfile->pragmas);
1463 char **result = XNEWVEC (char *, ct);
1464 (void) save_registered_pragmas (pfile->pragmas, result);
1465 return result;
1468 /* Restore from SD the names of the registered pragmas referenced by PE,
1469 and return a pointer to the next unused name in SD. */
1471 static char **
1472 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1473 char **sd)
1475 for (; pe != NULL; pe = pe->next)
1477 if (pe->is_nspace)
1478 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1479 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1480 free (*sd);
1481 sd++;
1483 return sd;
1486 /* Restore the names of the registered pragmas from SAVED. */
1488 void
1489 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1491 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1492 free (saved);
1495 /* Pragmata handling. We handle some, and pass the rest on to the
1496 front end. C99 defines three pragmas and says that no macro
1497 expansion is to be performed on them; whether or not macro
1498 expansion happens for other pragmas is implementation defined.
1499 This implementation allows for a mix of both, since GCC did not
1500 traditionally macro expand its (few) pragmas, whereas OpenMP
1501 specifies that macro expansion should happen. */
1502 static void
1503 do_pragma (cpp_reader *pfile)
1505 const struct pragma_entry *p = NULL;
1506 const cpp_token *token, *pragma_token;
1507 location_t pragma_token_virt_loc = 0;
1508 cpp_token ns_token;
1509 unsigned int count = 1;
1511 pfile->state.prevent_expansion++;
1513 pragma_token = token = cpp_get_token_with_location (pfile,
1514 &pragma_token_virt_loc);
1515 ns_token = *token;
1516 if (token->type == CPP_NAME)
1518 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1519 if (p && p->is_nspace)
1521 bool allow_name_expansion = p->allow_expansion;
1522 if (allow_name_expansion)
1523 pfile->state.prevent_expansion--;
1525 token = cpp_get_token (pfile);
1526 if (token->type == CPP_NAME)
1527 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1528 else
1529 p = NULL;
1530 if (allow_name_expansion)
1531 pfile->state.prevent_expansion++;
1532 count = 2;
1536 if (p)
1538 if (p->is_deferred)
1540 pfile->directive_result.src_loc = pragma_token_virt_loc;
1541 pfile->directive_result.type = CPP_PRAGMA;
1542 pfile->directive_result.flags = pragma_token->flags;
1543 pfile->directive_result.val.pragma = p->u.ident;
1544 pfile->state.in_deferred_pragma = true;
1545 pfile->state.pragma_allow_expansion = p->allow_expansion;
1546 if (!p->allow_expansion)
1547 pfile->state.prevent_expansion++;
1549 else
1551 /* Since the handler below doesn't get the line number, that
1552 it might need for diagnostics, make sure it has the right
1553 numbers in place. */
1554 if (pfile->cb.line_change)
1555 (*pfile->cb.line_change) (pfile, pragma_token, false);
1556 if (p->allow_expansion)
1557 pfile->state.prevent_expansion--;
1558 (*p->u.handler) (pfile);
1559 if (p->allow_expansion)
1560 pfile->state.prevent_expansion++;
1563 else if (pfile->cb.def_pragma)
1565 if (count == 1 || pfile->context->prev == NULL)
1566 _cpp_backup_tokens (pfile, count);
1567 else
1569 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1570 won't allow backing 2 tokens. */
1571 const auto tok_buff = _cpp_get_buff (pfile, 2 * sizeof (cpp_token));
1572 const auto toks = (cpp_token *)tok_buff->base;
1573 toks[0] = ns_token;
1574 toks[0].flags |= NO_EXPAND;
1575 toks[1] = *token;
1576 toks[1].flags |= NO_EXPAND | PREV_WHITE;
1577 _cpp_push_token_context (pfile, NULL, toks, 2);
1578 /* Arrange to free this buffer when no longer needed. */
1579 pfile->context->buff = tok_buff;
1581 pfile->cb.def_pragma (pfile, pfile->directive_line);
1584 pfile->state.prevent_expansion--;
1587 /* Handle #pragma once. */
1588 static void
1589 do_pragma_once (cpp_reader *pfile)
1591 if (_cpp_in_main_source_file (pfile))
1592 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1594 check_eol (pfile, false);
1595 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1598 /* Handle #pragma push_macro(STRING). */
1599 static void
1600 do_pragma_push_macro (cpp_reader *pfile)
1602 cpp_hashnode *node;
1603 size_t defnlen;
1604 const uchar *defn = NULL;
1605 char *macroname, *dest;
1606 const char *limit, *src;
1607 const cpp_token *txt;
1608 struct def_pragma_macro *c;
1610 txt = get__Pragma_string (pfile);
1611 if (!txt)
1613 location_t src_loc = pfile->cur_token[-1].src_loc;
1614 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1615 "invalid #pragma push_macro directive");
1616 check_eol (pfile, false);
1617 skip_rest_of_line (pfile);
1618 return;
1620 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1621 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1622 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1623 while (src < limit)
1625 /* We know there is a character following the backslash. */
1626 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1627 src++;
1628 *dest++ = *src++;
1630 *dest = 0;
1631 check_eol (pfile, false);
1632 skip_rest_of_line (pfile);
1633 c = XNEW (struct def_pragma_macro);
1634 memset (c, 0, sizeof (struct def_pragma_macro));
1635 c->name = XNEWVAR (char, strlen (macroname) + 1);
1636 strcpy (c->name, macroname);
1637 c->next = pfile->pushed_macros;
1638 node = _cpp_lex_identifier (pfile, c->name);
1639 if (node->type == NT_VOID)
1640 c->is_undef = 1;
1641 else if (node->type == NT_BUILTIN_MACRO)
1642 c->is_builtin = 1;
1643 else
1645 defn = cpp_macro_definition (pfile, node);
1646 defnlen = ustrlen (defn);
1647 c->definition = XNEWVEC (uchar, defnlen + 2);
1648 c->definition[defnlen] = '\n';
1649 c->definition[defnlen + 1] = 0;
1650 c->line = node->value.macro->line;
1651 c->syshdr = node->value.macro->syshdr;
1652 c->used = node->value.macro->used;
1653 memcpy (c->definition, defn, defnlen);
1656 pfile->pushed_macros = c;
1659 /* Handle #pragma pop_macro(STRING). */
1660 static void
1661 do_pragma_pop_macro (cpp_reader *pfile)
1663 char *macroname, *dest;
1664 const char *limit, *src;
1665 const cpp_token *txt;
1666 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1667 txt = get__Pragma_string (pfile);
1668 if (!txt)
1670 location_t src_loc = pfile->cur_token[-1].src_loc;
1671 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1672 "invalid #pragma pop_macro directive");
1673 check_eol (pfile, false);
1674 skip_rest_of_line (pfile);
1675 return;
1677 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1678 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1679 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1680 while (src < limit)
1682 /* We know there is a character following the backslash. */
1683 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1684 src++;
1685 *dest++ = *src++;
1687 *dest = 0;
1688 check_eol (pfile, false);
1689 skip_rest_of_line (pfile);
1691 while (c != NULL)
1693 if (!strcmp (c->name, macroname))
1695 if (!l)
1696 pfile->pushed_macros = c->next;
1697 else
1698 l->next = c->next;
1699 cpp_pop_definition (pfile, c);
1700 free (c->definition);
1701 free (c->name);
1702 free (c);
1703 break;
1705 l = c;
1706 c = c->next;
1710 /* Handle #pragma GCC poison, to poison one or more identifiers so
1711 that the lexer produces a hard error for each subsequent usage. */
1712 static void
1713 do_pragma_poison (cpp_reader *pfile)
1715 const cpp_token *tok;
1716 cpp_hashnode *hp;
1718 pfile->state.poisoned_ok = 1;
1719 for (;;)
1721 tok = _cpp_lex_token (pfile);
1722 if (tok->type == CPP_EOF)
1723 break;
1724 if (tok->type != CPP_NAME)
1726 cpp_error (pfile, CPP_DL_ERROR,
1727 "invalid #pragma GCC poison directive");
1728 break;
1731 hp = tok->val.node.node;
1732 if (hp->flags & NODE_POISONED)
1733 continue;
1735 if (cpp_macro_p (hp))
1736 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1737 NODE_NAME (hp));
1738 _cpp_free_definition (hp);
1739 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1741 pfile->state.poisoned_ok = 0;
1744 /* Mark the current header as a system header. This will suppress
1745 some categories of warnings (notably those from -pedantic). It is
1746 intended for use in system libraries that cannot be implemented in
1747 conforming C, but cannot be certain that their headers appear in a
1748 system include directory. To prevent abuse, it is rejected in the
1749 primary source file. */
1750 static void
1751 do_pragma_system_header (cpp_reader *pfile)
1753 if (_cpp_in_main_source_file (pfile))
1754 cpp_error (pfile, CPP_DL_WARNING,
1755 "#pragma system_header ignored outside include file");
1756 else
1758 check_eol (pfile, false);
1759 skip_rest_of_line (pfile);
1760 cpp_make_system_header (pfile, 1, 0);
1764 /* Check the modified date of the current include file against a specified
1765 file. Issue a diagnostic, if the specified file is newer. We use this to
1766 determine if a fixed header should be refixed. */
1767 static void
1768 do_pragma_dependency (cpp_reader *pfile)
1770 const char *fname;
1771 int angle_brackets, ordering;
1772 location_t location;
1774 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1775 if (!fname)
1776 return;
1778 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1779 if (ordering < 0)
1780 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1781 else if (ordering > 0)
1783 cpp_error (pfile, CPP_DL_WARNING,
1784 "current file is older than %s", fname);
1785 if (cpp_get_token (pfile)->type != CPP_EOF)
1787 _cpp_backup_tokens (pfile, 1);
1788 do_diagnostic (pfile, CPP_DL_WARNING, CPP_W_NONE, 0);
1792 free ((void *) fname);
1795 /* Issue a diagnostic with the message taken from the pragma. If
1796 ERROR is true, the diagnostic is a warning, otherwise, it is an
1797 error. */
1798 static void
1799 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1801 const cpp_token *tok = _cpp_lex_token (pfile);
1802 cpp_string str;
1803 if (tok->type != CPP_STRING
1804 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1805 CPP_STRING)
1806 || str.len == 0)
1808 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1809 error ? "error" : "warning");
1810 return;
1812 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1813 "%s", str.text);
1814 free ((void *)str.text);
1817 /* Issue a warning diagnostic. */
1818 static void
1819 do_pragma_warning (cpp_reader *pfile)
1821 do_pragma_warning_or_error (pfile, false);
1824 /* Issue an error diagnostic. */
1825 static void
1826 do_pragma_error (cpp_reader *pfile)
1828 do_pragma_warning_or_error (pfile, true);
1831 /* Get a token but skip padding. */
1832 static const cpp_token *
1833 get_token_no_padding (cpp_reader *pfile)
1835 for (;;)
1837 const cpp_token *result = cpp_get_token (pfile);
1838 if (result->type != CPP_PADDING)
1839 return result;
1843 /* Check syntax is "(string-literal)". Returns the string on success,
1844 or NULL on failure. */
1845 static const cpp_token *
1846 get__Pragma_string (cpp_reader *pfile)
1848 const cpp_token *string;
1849 const cpp_token *paren;
1851 paren = get_token_no_padding (pfile);
1852 if (paren->type == CPP_EOF)
1853 _cpp_backup_tokens (pfile, 1);
1854 if (paren->type != CPP_OPEN_PAREN)
1855 return NULL;
1857 string = get_token_no_padding (pfile);
1858 if (string->type == CPP_EOF)
1859 _cpp_backup_tokens (pfile, 1);
1860 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1861 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1862 && string->type != CPP_UTF8STRING)
1863 return NULL;
1865 paren = get_token_no_padding (pfile);
1866 if (paren->type == CPP_EOF)
1867 _cpp_backup_tokens (pfile, 1);
1868 if (paren->type != CPP_CLOSE_PAREN)
1869 return NULL;
1871 return string;
1874 /* Destringize IN into a temporary buffer, by removing the first \ of
1875 \" and \\ sequences, and process the result as a #pragma directive. */
1876 static void
1877 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1878 location_t expansion_loc)
1880 const unsigned char *src, *limit;
1881 char *dest, *result;
1882 cpp_context *saved_context;
1883 cpp_token *saved_cur_token;
1884 tokenrun *saved_cur_run;
1885 cpp_token *toks;
1886 int count;
1887 const struct directive *save_directive;
1889 dest = result = (char *) alloca (in->len - 1);
1890 src = in->text + 1 + (in->text[0] == 'L');
1891 limit = in->text + in->len - 1;
1892 while (src < limit)
1894 /* We know there is a character following the backslash. */
1895 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1896 src++;
1897 *dest++ = *src++;
1899 *dest = '\n';
1901 /* Ugh; an awful kludge. We are really not set up to be lexing
1902 tokens when in the middle of a macro expansion. Use a new
1903 context to force cpp_get_token to lex, and so skip_rest_of_line
1904 doesn't go beyond the end of the text. Also, remember the
1905 current lexing position so we can return to it later.
1907 Something like line-at-a-time lexing should remove the need for
1908 this. */
1909 saved_context = pfile->context;
1910 saved_cur_token = pfile->cur_token;
1911 saved_cur_run = pfile->cur_run;
1913 pfile->context = XCNEW (cpp_context);
1915 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1916 until we've read all of the tokens that we want. */
1917 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1918 /* from_stage3 */ true);
1919 /* ??? Antique Disgusting Hack. What does this do? */
1920 if (pfile->buffer->prev)
1921 pfile->buffer->file = pfile->buffer->prev->file;
1923 start_directive (pfile);
1924 _cpp_clean_line (pfile);
1925 save_directive = pfile->directive;
1926 pfile->directive = &dtable[T_PRAGMA];
1927 do_pragma (pfile);
1928 if (pfile->directive_result.type == CPP_PRAGMA)
1929 pfile->directive_result.flags |= PRAGMA_OP;
1930 end_directive (pfile, 1);
1931 pfile->directive = save_directive;
1933 /* We always insert at least one token, the directive result. It'll
1934 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1935 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1937 /* If we're not handling the pragma internally, read all of the tokens from
1938 the string buffer now, while the string buffer is still installed. */
1939 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1940 to me what the true lifespan of the tokens are. It would appear that
1941 the lifespan is the entire parse of the main input stream, in which case
1942 this may not be wrong. */
1943 if (pfile->directive_result.type == CPP_PRAGMA)
1945 int maxcount;
1947 count = 1;
1948 maxcount = 50;
1949 toks = XNEWVEC (cpp_token, maxcount);
1950 toks[0] = pfile->directive_result;
1951 toks[0].src_loc = expansion_loc;
1955 if (count == maxcount)
1957 maxcount = maxcount * 3 / 2;
1958 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1960 toks[count] = *cpp_get_token (pfile);
1961 /* _Pragma is a builtin, so we're not within a macro-map, and so
1962 the token locations are set to bogus ordinary locations
1963 near to, but after that of the "_Pragma".
1964 Paper over this by setting them equal to the location of the
1965 _Pragma itself (PR preprocessor/69126). */
1966 toks[count].src_loc = expansion_loc;
1967 /* Macros have been already expanded by cpp_get_token
1968 if the pragma allowed expansion. */
1969 toks[count++].flags |= NO_EXPAND;
1971 while (toks[count-1].type != CPP_PRAGMA_EOL);
1973 else
1975 count = 1;
1976 toks = &pfile->avoid_paste;
1978 /* If we handled the entire pragma internally, make sure we get the
1979 line number correct for the next token. */
1980 if (pfile->cb.line_change)
1981 pfile->cb.line_change (pfile, pfile->cur_token, false);
1984 /* Finish inlining run_directive. */
1985 pfile->buffer->file = NULL;
1986 _cpp_pop_buffer (pfile);
1988 /* Reset the old macro state before ... */
1989 XDELETE (pfile->context);
1990 pfile->context = saved_context;
1991 pfile->cur_token = saved_cur_token;
1992 pfile->cur_run = saved_cur_run;
1994 /* ... inserting the new tokens we collected. */
1995 _cpp_push_token_context (pfile, NULL, toks, count);
1998 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
2000 _cpp_do__Pragma (cpp_reader *pfile, location_t expansion_loc)
2002 /* Make sure we don't invalidate the string token, if the closing parenthesis
2003 ended up on a different line. */
2004 ++pfile->keep_tokens;
2005 const cpp_token *string = get__Pragma_string (pfile);
2006 --pfile->keep_tokens;
2008 pfile->directive_result.type = CPP_PADDING;
2010 if (string)
2012 destringize_and_run (pfile, &string->val.str, expansion_loc);
2013 return 1;
2015 cpp_error (pfile, CPP_DL_ERROR,
2016 "_Pragma takes a parenthesized string literal");
2017 return 0;
2020 /* Handle #ifdef. */
2021 static void
2022 do_ifdef (cpp_reader *pfile)
2024 int skip = 1;
2026 if (! pfile->state.skipping)
2028 cpp_hashnode *node = lex_macro_node (pfile, false);
2030 if (node)
2032 skip = !_cpp_defined_macro_p (node);
2033 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2034 /* It wasn't a macro after all. */
2035 skip = true;
2036 _cpp_mark_macro_used (node);
2037 if (pfile->cb.used)
2038 pfile->cb.used (pfile, pfile->directive_line, node);
2039 check_eol (pfile, false);
2043 push_conditional (pfile, skip, T_IFDEF, 0);
2046 /* Handle #ifndef. */
2047 static void
2048 do_ifndef (cpp_reader *pfile)
2050 int skip = 1;
2051 cpp_hashnode *node = 0;
2053 if (! pfile->state.skipping)
2055 node = lex_macro_node (pfile, false);
2057 if (node)
2059 skip = _cpp_defined_macro_p (node);
2060 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2061 /* It wasn't a macro after all. */
2062 skip = false;
2063 _cpp_mark_macro_used (node);
2064 if (pfile->cb.used)
2065 pfile->cb.used (pfile, pfile->directive_line, node);
2066 check_eol (pfile, false);
2070 push_conditional (pfile, skip, T_IFNDEF, node);
2073 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2074 pfile->mi_ind_cmacro so we can handle multiple-include
2075 optimizations. If macro expansion occurs in the expression, we
2076 cannot treat it as a controlling conditional, since the expansion
2077 could change in the future. That is handled by cpp_get_token. */
2078 static void
2079 do_if (cpp_reader *pfile)
2081 int skip = 1;
2083 if (! pfile->state.skipping)
2084 skip = _cpp_parse_expr (pfile, true) == false;
2086 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2089 /* Flip skipping state if appropriate and continue without changing
2090 if_stack; this is so that the error message for missing #endif's
2091 etc. will point to the original #if. */
2092 static void
2093 do_else (cpp_reader *pfile)
2095 cpp_buffer *buffer = pfile->buffer;
2096 struct if_stack *ifs = buffer->if_stack;
2098 if (ifs == NULL)
2099 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2100 else
2102 if (ifs->type == T_ELSE)
2104 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2105 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2106 "the conditional began here");
2108 ifs->type = T_ELSE;
2110 /* Skip any future (erroneous) #elses or #elifs. */
2111 pfile->state.skipping = ifs->skip_elses;
2112 ifs->skip_elses = true;
2114 /* Invalidate any controlling macro. */
2115 ifs->mi_cmacro = 0;
2117 /* Only check EOL if was not originally skipping. */
2118 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2119 check_eol_endif_labels (pfile);
2123 /* Handle a #elif, #elifdef or #elifndef directive by not changing if_stack
2124 either. See the comment above do_else. */
2125 static void
2126 do_elif (cpp_reader *pfile)
2128 cpp_buffer *buffer = pfile->buffer;
2129 struct if_stack *ifs = buffer->if_stack;
2131 if (ifs == NULL)
2132 cpp_error (pfile, CPP_DL_ERROR, "#%s without #if", pfile->directive->name);
2133 else
2135 if (ifs->type == T_ELSE)
2137 cpp_error (pfile, CPP_DL_ERROR, "#%s after #else",
2138 pfile->directive->name);
2139 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2140 "the conditional began here");
2142 ifs->type = T_ELIF;
2144 /* See DR#412: "Only the first group whose control condition
2145 evaluates to true (nonzero) is processed; any following groups
2146 are skipped and their controlling directives are processed as
2147 if they were in a group that is skipped." */
2148 if (ifs->skip_elses)
2150 /* In older GNU standards, #elifdef/#elifndef is supported
2151 as an extension, but pedwarn if -pedantic if the presence
2152 of the directive would be rejected. */
2153 if (pfile->directive != &dtable[T_ELIF]
2154 && ! CPP_OPTION (pfile, elifdef)
2155 && CPP_PEDANTIC (pfile)
2156 && !pfile->state.skipping)
2158 if (CPP_OPTION (pfile, cplusplus))
2159 cpp_error (pfile, CPP_DL_PEDWARN,
2160 "#%s before C++23 is a GCC extension",
2161 pfile->directive->name);
2162 else
2163 cpp_error (pfile, CPP_DL_PEDWARN,
2164 "#%s before C2X is a GCC extension",
2165 pfile->directive->name);
2167 pfile->state.skipping = 1;
2169 else
2171 if (pfile->directive == &dtable[T_ELIF])
2172 pfile->state.skipping = !_cpp_parse_expr (pfile, false);
2173 else
2175 cpp_hashnode *node = lex_macro_node (pfile, false);
2177 if (node)
2179 bool macro_defined = _cpp_defined_macro_p (node);
2180 if (!_cpp_maybe_notify_macro_use (pfile, node,
2181 pfile->directive_line))
2182 /* It wasn't a macro after all. */
2183 macro_defined = false;
2184 bool skip = (pfile->directive == &dtable[T_ELIFDEF]
2185 ? !macro_defined
2186 : macro_defined);
2187 if (pfile->cb.used)
2188 pfile->cb.used (pfile, pfile->directive_line, node);
2189 check_eol (pfile, false);
2190 /* In older GNU standards, #elifdef/#elifndef is supported
2191 as an extension, but pedwarn if -pedantic if the presence
2192 of the directive would change behavior. */
2193 if (! CPP_OPTION (pfile, elifdef)
2194 && CPP_PEDANTIC (pfile)
2195 && pfile->state.skipping != skip)
2197 if (CPP_OPTION (pfile, cplusplus))
2198 cpp_error (pfile, CPP_DL_PEDWARN,
2199 "#%s before C++23 is a GCC extension",
2200 pfile->directive->name);
2201 else
2202 cpp_error (pfile, CPP_DL_PEDWARN,
2203 "#%s before C2X is a GCC extension",
2204 pfile->directive->name);
2206 pfile->state.skipping = skip;
2209 ifs->skip_elses = !pfile->state.skipping;
2212 /* Invalidate any controlling macro. */
2213 ifs->mi_cmacro = 0;
2217 /* Handle a #elifdef directive. */
2218 static void
2219 do_elifdef (cpp_reader *pfile)
2221 do_elif (pfile);
2224 /* Handle a #elifndef directive. */
2225 static void
2226 do_elifndef (cpp_reader *pfile)
2228 do_elif (pfile);
2231 /* #endif pops the if stack and resets pfile->state.skipping. */
2232 static void
2233 do_endif (cpp_reader *pfile)
2235 cpp_buffer *buffer = pfile->buffer;
2236 struct if_stack *ifs = buffer->if_stack;
2238 if (ifs == NULL)
2239 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2240 else
2242 /* Only check EOL if was not originally skipping. */
2243 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2244 check_eol_endif_labels (pfile);
2246 /* If potential control macro, we go back outside again. */
2247 if (ifs->next == 0 && ifs->mi_cmacro)
2249 pfile->mi_valid = true;
2250 pfile->mi_cmacro = ifs->mi_cmacro;
2253 buffer->if_stack = ifs->next;
2254 pfile->state.skipping = ifs->was_skipping;
2255 obstack_free (&pfile->buffer_ob, ifs);
2259 /* Push an if_stack entry for a preprocessor conditional, and set
2260 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2261 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2262 we need to check here that we are at the top of the file. */
2263 static void
2264 push_conditional (cpp_reader *pfile, int skip, int type,
2265 const cpp_hashnode *cmacro)
2267 struct if_stack *ifs;
2268 cpp_buffer *buffer = pfile->buffer;
2270 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2271 ifs->line = pfile->directive_line;
2272 ifs->next = buffer->if_stack;
2273 ifs->skip_elses = pfile->state.skipping || !skip;
2274 ifs->was_skipping = pfile->state.skipping;
2275 ifs->type = type;
2276 /* This condition is effectively a test for top-of-file. */
2277 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2278 ifs->mi_cmacro = cmacro;
2279 else
2280 ifs->mi_cmacro = 0;
2282 pfile->state.skipping = skip;
2283 buffer->if_stack = ifs;
2286 /* Read the tokens of the answer into the macro pool, in a directive
2287 of type TYPE. Only commit the memory if we intend it as permanent
2288 storage, i.e. the #assert case. Returns 0 on success, and sets
2289 ANSWERP to point to the answer. PRED_LOC is the location of the
2290 predicate. */
2291 static bool
2292 parse_answer (cpp_reader *pfile, int type, location_t pred_loc,
2293 cpp_macro **answer_ptr)
2295 /* In a conditional, it is legal to not have an open paren. We
2296 should save the following token in this case. */
2297 const cpp_token *paren = cpp_get_token (pfile);
2299 /* If not a paren, see if we're OK. */
2300 if (paren->type != CPP_OPEN_PAREN)
2302 /* In a conditional no answer is a test for any answer. It
2303 could be followed by any token. */
2304 if (type == T_IF)
2306 _cpp_backup_tokens (pfile, 1);
2307 return true;
2310 /* #unassert with no answer is valid - it removes all answers. */
2311 if (type == T_UNASSERT && paren->type == CPP_EOF)
2312 return true;
2314 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2315 "missing '(' after predicate");
2316 return false;
2319 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2320 _cpp_reserve_room (pfile, 0,
2321 sizeof (cpp_macro)));
2322 answer->parm.next = NULL;
2323 unsigned count = 0;
2324 for (;;)
2326 const cpp_token *token = cpp_get_token (pfile);
2328 if (token->type == CPP_CLOSE_PAREN)
2329 break;
2331 if (token->type == CPP_EOF)
2333 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2334 return false;
2337 answer = (cpp_macro *)_cpp_reserve_room
2338 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2339 sizeof (cpp_token));
2340 answer->exp.tokens[count++] = *token;
2343 if (!count)
2345 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2346 return false;
2349 /* Drop whitespace at start, for answer equivalence purposes. */
2350 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2352 answer->count = count;
2353 *answer_ptr = answer;
2355 return true;
2358 /* Parses an assertion directive of type TYPE, returning a pointer to
2359 the hash node of the predicate, or 0 on error. The node is
2360 guaranteed to be disjoint from the macro namespace, so can only
2361 have type 'NT_VOID'. If an answer was supplied, it is placed in
2362 *ANSWER_PTR, which is otherwise set to 0. */
2363 static cpp_hashnode *
2364 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2366 cpp_hashnode *result = 0;
2368 /* We don't expand predicates or answers. */
2369 pfile->state.prevent_expansion++;
2371 *answer_ptr = NULL;
2373 const cpp_token *predicate = cpp_get_token (pfile);
2374 if (predicate->type == CPP_EOF)
2375 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2376 else if (predicate->type != CPP_NAME)
2377 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2378 "predicate must be an identifier");
2379 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2381 unsigned int len = NODE_LEN (predicate->val.node.node);
2382 unsigned char *sym = (unsigned char *) alloca (len + 1);
2384 /* Prefix '#' to get it out of macro namespace. */
2385 sym[0] = '#';
2386 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2387 result = cpp_lookup (pfile, sym, len + 1);
2390 pfile->state.prevent_expansion--;
2392 return result;
2395 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2396 or a pointer to NULL if the answer is not in the chain. */
2397 static cpp_macro **
2398 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2400 unsigned int i;
2401 cpp_macro **result = NULL;
2403 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2405 cpp_macro *answer = *result;
2407 if (answer->count == candidate->count)
2409 for (i = 0; i < answer->count; i++)
2410 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2411 &candidate->exp.tokens[i]))
2412 break;
2414 if (i == answer->count)
2415 break;
2419 return result;
2422 /* Test an assertion within a preprocessor conditional. Returns
2423 nonzero on failure, zero on success. On success, the result of
2424 the test is written into VALUE, otherwise the value 0. */
2426 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2428 cpp_macro *answer;
2429 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2431 /* For recovery, an erroneous assertion expression is handled as a
2432 failing assertion. */
2433 *value = 0;
2435 if (node)
2437 if (node->value.answers)
2438 *value = !answer || *find_answer (node, answer);
2440 else if (pfile->cur_token[-1].type == CPP_EOF)
2441 _cpp_backup_tokens (pfile, 1);
2443 /* We don't commit the memory for the answer - it's temporary only. */
2444 return node == 0;
2447 /* Handle #assert. */
2448 static void
2449 do_assert (cpp_reader *pfile)
2451 cpp_macro *answer;
2452 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2454 if (node)
2456 /* Place the new answer in the answer list. First check there
2457 is not a duplicate. */
2458 if (*find_answer (node, answer))
2460 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2461 NODE_NAME (node) + 1);
2462 return;
2465 /* Commit or allocate storage for the answer. */
2466 answer = (cpp_macro *)_cpp_commit_buff
2467 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2468 + sizeof (cpp_token) * answer->count);
2470 /* Chain into the list. */
2471 answer->parm.next = node->value.answers;
2472 node->value.answers = answer;
2474 check_eol (pfile, false);
2478 /* Handle #unassert. */
2479 static void
2480 do_unassert (cpp_reader *pfile)
2482 cpp_macro *answer;
2483 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2485 /* It isn't an error to #unassert something that isn't asserted. */
2486 if (node)
2488 if (answer)
2490 cpp_macro **p = find_answer (node, answer);
2492 /* Remove the assert from the list. */
2493 if (cpp_macro *temp = *p)
2494 *p = temp->parm.next;
2496 check_eol (pfile, false);
2498 else
2499 _cpp_free_definition (node);
2502 /* We don't commit the memory for the answer - it's temporary only. */
2505 /* These are for -D, -U, -A. */
2507 /* Process the string STR as if it appeared as the body of a #define.
2508 If STR is just an identifier, define it with value 1.
2509 If STR has anything after the identifier, then it should
2510 be identifier=definition. */
2511 void
2512 cpp_define (cpp_reader *pfile, const char *str)
2514 char *buf;
2515 const char *p;
2516 size_t count;
2518 /* Copy the entire option so we can modify it.
2519 Change the first "=" in the string to a space. If there is none,
2520 tack " 1" on the end. */
2522 count = strlen (str);
2523 buf = (char *) alloca (count + 3);
2524 memcpy (buf, str, count);
2526 p = strchr (str, '=');
2527 if (p)
2528 buf[p - str] = ' ';
2529 else
2531 buf[count++] = ' ';
2532 buf[count++] = '1';
2534 buf[count] = '\n';
2536 run_directive (pfile, T_DEFINE, buf, count);
2539 /* Like cpp_define, but does not warn about unused macro. */
2540 void
2541 cpp_define_unused (cpp_reader *pfile, const char *str)
2543 unsigned char warn_unused_macros = CPP_OPTION (pfile, warn_unused_macros);
2544 CPP_OPTION (pfile, warn_unused_macros) = 0;
2545 cpp_define (pfile, str);
2546 CPP_OPTION (pfile, warn_unused_macros) = warn_unused_macros;
2549 /* Use to build macros to be run through cpp_define() as
2550 described above.
2551 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2553 void
2554 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2556 char *ptr;
2558 va_list ap;
2559 va_start (ap, fmt);
2560 ptr = xvasprintf (fmt, ap);
2561 va_end (ap);
2563 cpp_define (pfile, ptr);
2564 free (ptr);
2567 /* Like cpp_define_formatted, but does not warn about unused macro. */
2568 void
2569 cpp_define_formatted_unused (cpp_reader *pfile, const char *fmt, ...)
2571 char *ptr;
2573 va_list ap;
2574 va_start (ap, fmt);
2575 ptr = xvasprintf (fmt, ap);
2576 va_end (ap);
2578 cpp_define_unused (pfile, ptr);
2579 free (ptr);
2582 /* Slight variant of the above for use by initialize_builtins. */
2583 void
2584 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2586 size_t len = strlen (str);
2587 char *buf = (char *) alloca (len + 1);
2588 memcpy (buf, str, len);
2589 buf[len] = '\n';
2590 run_directive (pfile, T_DEFINE, buf, len);
2593 /* Process MACRO as if it appeared as the body of an #undef. */
2594 void
2595 cpp_undef (cpp_reader *pfile, const char *macro)
2597 size_t len = strlen (macro);
2598 char *buf = (char *) alloca (len + 1);
2599 memcpy (buf, macro, len);
2600 buf[len] = '\n';
2601 run_directive (pfile, T_UNDEF, buf, len);
2604 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2605 or first element is zero, then the macro should be undefined. */
2606 static void
2607 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2609 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2610 if (node == NULL)
2611 return;
2613 if (pfile->cb.before_define)
2614 pfile->cb.before_define (pfile);
2616 if (cpp_macro_p (node))
2618 if (pfile->cb.undef)
2619 pfile->cb.undef (pfile, pfile->directive_line, node);
2620 if (CPP_OPTION (pfile, warn_unused_macros))
2621 _cpp_warn_if_unused_macro (pfile, node, NULL);
2622 _cpp_free_definition (node);
2625 if (c->is_undef)
2626 return;
2627 if (c->is_builtin)
2629 _cpp_restore_special_builtin (pfile, c);
2630 return;
2634 size_t namelen;
2635 const uchar *dn;
2636 cpp_hashnode *h = NULL;
2637 cpp_buffer *nbuf;
2639 namelen = ustrcspn (c->definition, "( \n");
2640 h = cpp_lookup (pfile, c->definition, namelen);
2641 dn = c->definition + namelen;
2643 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2644 if (nbuf != NULL)
2646 _cpp_clean_line (pfile);
2647 nbuf->sysp = 1;
2648 if (!_cpp_create_definition (pfile, h, 0))
2649 abort ();
2650 _cpp_pop_buffer (pfile);
2652 else
2653 abort ();
2654 h->value.macro->line = c->line;
2655 h->value.macro->syshdr = c->syshdr;
2656 h->value.macro->used = c->used;
2660 /* Process the string STR as if it appeared as the body of a #assert. */
2661 void
2662 cpp_assert (cpp_reader *pfile, const char *str)
2664 handle_assertion (pfile, str, T_ASSERT);
2667 /* Process STR as if it appeared as the body of an #unassert. */
2668 void
2669 cpp_unassert (cpp_reader *pfile, const char *str)
2671 handle_assertion (pfile, str, T_UNASSERT);
2674 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2675 static void
2676 handle_assertion (cpp_reader *pfile, const char *str, int type)
2678 size_t count = strlen (str);
2679 const char *p = strchr (str, '=');
2681 /* Copy the entire option so we can modify it. Change the first
2682 "=" in the string to a '(', and tack a ')' on the end. */
2683 char *buf = (char *) alloca (count + 2);
2685 memcpy (buf, str, count);
2686 if (p)
2688 buf[p - str] = '(';
2689 buf[count++] = ')';
2691 buf[count] = '\n';
2692 str = buf;
2694 run_directive (pfile, type, str, count);
2697 /* The options structure. */
2698 cpp_options *
2699 cpp_get_options (cpp_reader *pfile)
2701 return &pfile->opts;
2704 /* The callbacks structure. */
2705 cpp_callbacks *
2706 cpp_get_callbacks (cpp_reader *pfile)
2708 return &pfile->cb;
2711 /* Copy the given callbacks structure to our own. */
2712 void
2713 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2715 pfile->cb = *cb;
2718 /* The narrow character set identifier. */
2719 const char *
2720 cpp_get_narrow_charset_name (cpp_reader *pfile)
2722 return pfile->narrow_cset_desc.to;
2725 /* The wide character set identifier. */
2726 const char *
2727 cpp_get_wide_charset_name (cpp_reader *pfile)
2729 return pfile->wide_cset_desc.to;
2732 /* The dependencies structure. (Creates one if it hasn't already been.) */
2733 class mkdeps *
2734 cpp_get_deps (cpp_reader *pfile)
2736 if (!pfile->deps && CPP_OPTION (pfile, deps.style) != DEPS_NONE)
2737 pfile->deps = deps_init ();
2738 return pfile->deps;
2741 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2742 doesn't fail. It does not generate a file change call back; that
2743 is the responsibility of the caller. */
2744 cpp_buffer *
2745 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2746 int from_stage3)
2748 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2750 /* Clears, amongst other things, if_stack and mi_cmacro. */
2751 memset (new_buffer, 0, sizeof (cpp_buffer));
2753 new_buffer->next_line = new_buffer->buf = buffer;
2754 new_buffer->rlimit = buffer + len;
2755 new_buffer->from_stage3 = from_stage3;
2756 new_buffer->prev = pfile->buffer;
2757 new_buffer->need_line = true;
2759 pfile->buffer = new_buffer;
2761 return new_buffer;
2764 /* Pops a single buffer, with a file change call-back if appropriate.
2765 Then pushes the next -include file, if any remain. */
2766 void
2767 _cpp_pop_buffer (cpp_reader *pfile)
2769 cpp_buffer *buffer = pfile->buffer;
2770 struct _cpp_file *inc = buffer->file;
2771 struct if_stack *ifs;
2772 const unsigned char *to_free;
2774 /* Walk back up the conditional stack till we reach its level at
2775 entry to this file, issuing error messages. */
2776 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2777 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2778 "unterminated #%s", dtable[ifs->type].name);
2780 /* In case of a missing #endif. */
2781 pfile->state.skipping = 0;
2783 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2784 pfile->buffer = buffer->prev;
2786 to_free = buffer->to_free;
2787 free (buffer->notes);
2789 /* Free the buffer object now; we may want to push a new buffer
2790 in _cpp_push_next_include_file. */
2791 obstack_free (&pfile->buffer_ob, buffer);
2793 if (inc)
2795 _cpp_pop_file_buffer (pfile, inc, to_free);
2797 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2799 else if (to_free)
2800 free ((void *)to_free);
2803 /* Enter all recognized directives in the hash table. */
2804 void
2805 _cpp_init_directives (cpp_reader *pfile)
2807 for (int i = 0; i < N_DIRECTIVES; i++)
2809 cpp_hashnode *node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2810 node->is_directive = 1;
2811 node->directive_index = i;
2815 /* Extract header file from a bracket include. Parsing starts after '<'.
2816 The string is malloced and must be freed by the caller. */
2817 char *
2818 _cpp_bracket_include(cpp_reader *pfile)
2820 return glue_header_name (pfile);