Revert "Set num_threads to 50 on 32-bit hppa in two libgomp loop tests"
[official-gcc.git] / libcpp / directives.cc
blob479f8c716e8b540436d3ccd89b7fd7430a84b7fa
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2024 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. STDC23 directives come from the C23 standard. EXTENSION
60 directives are extensions. */
61 #define KANDR 0
62 #define STDC89 1
63 #define STDC23 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, STDC23, COND | ELIFDEF) \
158 D(elifndef, T_ELIFNDEF, STDC23, COND | ELIFDEF) \
159 D(error, T_ERROR, STDC89, 0) \
160 D(pragma, T_PRAGMA, STDC89, IN_I) \
161 D(warning, T_WARNING, STDC23, 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 C23 is a GCC extension", dir->name);
399 else if (CPP_OPTION (pfile, cpp_warn_c11_c23_compat) > 0)
400 cpp_warning (pfile, CPP_W_C11_C23_COMPAT,
401 "#%s before C23 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;
1740 const auto data = (cpp_hashnode_extra *)
1741 ht_lookup (pfile->extra_hash_table, hp->ident, HT_ALLOC);
1742 data->poisoned_loc = tok->src_loc;
1744 pfile->state.poisoned_ok = 0;
1747 /* Mark the current header as a system header. This will suppress
1748 some categories of warnings (notably those from -pedantic). It is
1749 intended for use in system libraries that cannot be implemented in
1750 conforming C, but cannot be certain that their headers appear in a
1751 system include directory. To prevent abuse, it is rejected in the
1752 primary source file. */
1753 static void
1754 do_pragma_system_header (cpp_reader *pfile)
1756 if (_cpp_in_main_source_file (pfile))
1757 cpp_error (pfile, CPP_DL_WARNING,
1758 "#pragma system_header ignored outside include file");
1759 else
1761 check_eol (pfile, false);
1762 skip_rest_of_line (pfile);
1763 cpp_make_system_header (pfile, 1, 0);
1767 /* Check the modified date of the current include file against a specified
1768 file. Issue a diagnostic, if the specified file is newer. We use this to
1769 determine if a fixed header should be refixed. */
1770 static void
1771 do_pragma_dependency (cpp_reader *pfile)
1773 const char *fname;
1774 int angle_brackets, ordering;
1775 location_t location;
1777 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1778 if (!fname)
1779 return;
1781 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1782 if (ordering < 0)
1783 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1784 else if (ordering > 0)
1786 cpp_error (pfile, CPP_DL_WARNING,
1787 "current file is older than %s", fname);
1788 if (cpp_get_token (pfile)->type != CPP_EOF)
1790 _cpp_backup_tokens (pfile, 1);
1791 do_diagnostic (pfile, CPP_DL_WARNING, CPP_W_NONE, 0);
1795 free ((void *) fname);
1798 /* Issue a diagnostic with the message taken from the pragma. If
1799 ERROR is true, the diagnostic is a warning, otherwise, it is an
1800 error. */
1801 static void
1802 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1804 const cpp_token *tok = _cpp_lex_token (pfile);
1805 cpp_string str;
1806 if (tok->type != CPP_STRING
1807 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1808 CPP_STRING)
1809 || str.len == 0)
1811 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1812 error ? "error" : "warning");
1813 return;
1815 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1816 "%s", str.text);
1817 free ((void *)str.text);
1820 /* Issue a warning diagnostic. */
1821 static void
1822 do_pragma_warning (cpp_reader *pfile)
1824 do_pragma_warning_or_error (pfile, false);
1827 /* Issue an error diagnostic. */
1828 static void
1829 do_pragma_error (cpp_reader *pfile)
1831 do_pragma_warning_or_error (pfile, true);
1834 /* Get a token but skip padding. */
1835 static const cpp_token *
1836 get_token_no_padding (cpp_reader *pfile)
1838 for (;;)
1840 const cpp_token *result = cpp_get_token (pfile);
1841 if (result->type != CPP_PADDING)
1842 return result;
1846 /* Check syntax is "(string-literal)". Returns the string on success,
1847 or NULL on failure. */
1848 static const cpp_token *
1849 get__Pragma_string (cpp_reader *pfile)
1851 const cpp_token *string;
1852 const cpp_token *paren;
1854 paren = get_token_no_padding (pfile);
1855 if (paren->type == CPP_EOF)
1856 _cpp_backup_tokens (pfile, 1);
1857 if (paren->type != CPP_OPEN_PAREN)
1858 return NULL;
1860 string = get_token_no_padding (pfile);
1861 if (string->type == CPP_EOF)
1862 _cpp_backup_tokens (pfile, 1);
1863 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1864 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1865 && string->type != CPP_UTF8STRING)
1866 return NULL;
1868 paren = get_token_no_padding (pfile);
1869 if (paren->type == CPP_EOF)
1870 _cpp_backup_tokens (pfile, 1);
1871 if (paren->type != CPP_CLOSE_PAREN)
1872 return NULL;
1874 return string;
1877 /* Destringize IN into a temporary buffer, by removing the first \ of
1878 \" and \\ sequences, and process the result as a #pragma directive. */
1879 static void
1880 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1881 location_t expansion_loc)
1883 const unsigned char *src, *limit;
1884 char *dest, *result;
1885 cpp_context *saved_context;
1886 cpp_token *saved_cur_token;
1887 tokenrun *saved_cur_run;
1888 cpp_token *toks;
1889 int count;
1890 const struct directive *save_directive;
1892 dest = result = (char *) alloca (in->len - 1);
1893 src = in->text + 1 + (in->text[0] == 'L');
1894 limit = in->text + in->len - 1;
1895 while (src < limit)
1897 /* We know there is a character following the backslash. */
1898 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1899 src++;
1900 *dest++ = *src++;
1902 *dest = '\n';
1904 /* Ugh; an awful kludge. We are really not set up to be lexing
1905 tokens when in the middle of a macro expansion. Use a new
1906 context to force cpp_get_token to lex, and so skip_rest_of_line
1907 doesn't go beyond the end of the text. Also, remember the
1908 current lexing position so we can return to it later.
1910 Something like line-at-a-time lexing should remove the need for
1911 this. */
1912 saved_context = pfile->context;
1913 saved_cur_token = pfile->cur_token;
1914 saved_cur_run = pfile->cur_run;
1916 pfile->context = XCNEW (cpp_context);
1918 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1919 until we've read all of the tokens that we want. */
1920 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1921 /* from_stage3 */ true);
1922 /* ??? Antique Disgusting Hack. What does this do? */
1923 if (pfile->buffer->prev)
1924 pfile->buffer->file = pfile->buffer->prev->file;
1926 start_directive (pfile);
1927 _cpp_clean_line (pfile);
1928 save_directive = pfile->directive;
1929 pfile->directive = &dtable[T_PRAGMA];
1930 do_pragma (pfile);
1931 if (pfile->directive_result.type == CPP_PRAGMA)
1932 pfile->directive_result.flags |= PRAGMA_OP;
1933 end_directive (pfile, 1);
1934 pfile->directive = save_directive;
1936 /* We always insert at least one token, the directive result. It'll
1937 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1938 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1940 /* If we're not handling the pragma internally, read all of the tokens from
1941 the string buffer now, while the string buffer is still installed. */
1942 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1943 to me what the true lifespan of the tokens are. It would appear that
1944 the lifespan is the entire parse of the main input stream, in which case
1945 this may not be wrong. */
1946 if (pfile->directive_result.type == CPP_PRAGMA)
1948 int maxcount;
1950 count = 1;
1951 maxcount = 50;
1952 toks = XNEWVEC (cpp_token, maxcount);
1953 toks[0] = pfile->directive_result;
1954 toks[0].src_loc = expansion_loc;
1958 if (count == maxcount)
1960 maxcount = maxcount * 3 / 2;
1961 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1963 toks[count] = *cpp_get_token (pfile);
1964 /* _Pragma is a builtin, so we're not within a macro-map, and so
1965 the token locations are set to bogus ordinary locations
1966 near to, but after that of the "_Pragma".
1967 Paper over this by setting them equal to the location of the
1968 _Pragma itself (PR preprocessor/69126). */
1969 toks[count].src_loc = expansion_loc;
1970 /* Macros have been already expanded by cpp_get_token
1971 if the pragma allowed expansion. */
1972 toks[count++].flags |= NO_EXPAND;
1974 while (toks[count-1].type != CPP_PRAGMA_EOL);
1976 else
1978 count = 1;
1979 toks = &pfile->avoid_paste;
1981 /* If we handled the entire pragma internally, make sure we get the
1982 line number correct for the next token. */
1983 if (pfile->cb.line_change)
1984 pfile->cb.line_change (pfile, pfile->cur_token, false);
1987 /* Finish inlining run_directive. */
1988 pfile->buffer->file = NULL;
1989 _cpp_pop_buffer (pfile);
1991 /* Reset the old macro state before ... */
1992 XDELETE (pfile->context);
1993 pfile->context = saved_context;
1994 pfile->cur_token = saved_cur_token;
1995 pfile->cur_run = saved_cur_run;
1997 /* ... inserting the new tokens we collected. */
1998 _cpp_push_token_context (pfile, NULL, toks, count);
2001 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
2003 _cpp_do__Pragma (cpp_reader *pfile, location_t expansion_loc)
2005 /* Make sure we don't invalidate the string token, if the closing parenthesis
2006 ended up on a different line. */
2007 ++pfile->keep_tokens;
2008 const cpp_token *string = get__Pragma_string (pfile);
2009 --pfile->keep_tokens;
2011 pfile->directive_result.type = CPP_PADDING;
2013 if (string)
2015 destringize_and_run (pfile, &string->val.str, expansion_loc);
2016 return 1;
2018 cpp_error (pfile, CPP_DL_ERROR,
2019 "_Pragma takes a parenthesized string literal");
2020 return 0;
2023 /* Handle #ifdef. */
2024 static void
2025 do_ifdef (cpp_reader *pfile)
2027 int skip = 1;
2029 if (! pfile->state.skipping)
2031 cpp_hashnode *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 = true;
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_IFDEF, 0);
2049 /* Handle #ifndef. */
2050 static void
2051 do_ifndef (cpp_reader *pfile)
2053 int skip = 1;
2054 cpp_hashnode *node = 0;
2056 if (! pfile->state.skipping)
2058 node = lex_macro_node (pfile, false);
2060 if (node)
2062 skip = _cpp_defined_macro_p (node);
2063 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2064 /* It wasn't a macro after all. */
2065 skip = false;
2066 _cpp_mark_macro_used (node);
2067 if (pfile->cb.used)
2068 pfile->cb.used (pfile, pfile->directive_line, node);
2069 check_eol (pfile, false);
2073 push_conditional (pfile, skip, T_IFNDEF, node);
2076 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2077 pfile->mi_ind_cmacro so we can handle multiple-include
2078 optimizations. If macro expansion occurs in the expression, we
2079 cannot treat it as a controlling conditional, since the expansion
2080 could change in the future. That is handled by cpp_get_token. */
2081 static void
2082 do_if (cpp_reader *pfile)
2084 int skip = 1;
2086 if (! pfile->state.skipping)
2087 skip = _cpp_parse_expr (pfile, true) == false;
2089 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2092 /* Flip skipping state if appropriate and continue without changing
2093 if_stack; this is so that the error message for missing #endif's
2094 etc. will point to the original #if. */
2095 static void
2096 do_else (cpp_reader *pfile)
2098 cpp_buffer *buffer = pfile->buffer;
2099 struct if_stack *ifs = buffer->if_stack;
2101 if (ifs == NULL)
2102 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2103 else
2105 if (ifs->type == T_ELSE)
2107 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2108 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2109 "the conditional began here");
2111 ifs->type = T_ELSE;
2113 /* Skip any future (erroneous) #elses or #elifs. */
2114 pfile->state.skipping = ifs->skip_elses;
2115 ifs->skip_elses = true;
2117 /* Invalidate any controlling macro. */
2118 ifs->mi_cmacro = 0;
2120 /* Only check EOL if was not originally skipping. */
2121 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2122 check_eol_endif_labels (pfile);
2126 /* Handle a #elif, #elifdef or #elifndef directive by not changing if_stack
2127 either. See the comment above do_else. */
2128 static void
2129 do_elif (cpp_reader *pfile)
2131 cpp_buffer *buffer = pfile->buffer;
2132 struct if_stack *ifs = buffer->if_stack;
2134 if (ifs == NULL)
2135 cpp_error (pfile, CPP_DL_ERROR, "#%s without #if", pfile->directive->name);
2136 else
2138 if (ifs->type == T_ELSE)
2140 cpp_error (pfile, CPP_DL_ERROR, "#%s after #else",
2141 pfile->directive->name);
2142 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2143 "the conditional began here");
2145 ifs->type = T_ELIF;
2147 /* See DR#412: "Only the first group whose control condition
2148 evaluates to true (nonzero) is processed; any following groups
2149 are skipped and their controlling directives are processed as
2150 if they were in a group that is skipped." */
2151 if (ifs->skip_elses)
2153 /* In older GNU standards, #elifdef/#elifndef is supported
2154 as an extension, but pedwarn if -pedantic if the presence
2155 of the directive would be rejected. */
2156 if (pfile->directive != &dtable[T_ELIF]
2157 && ! CPP_OPTION (pfile, elifdef)
2158 && CPP_PEDANTIC (pfile)
2159 && !pfile->state.skipping)
2161 if (CPP_OPTION (pfile, cplusplus))
2162 cpp_error (pfile, CPP_DL_PEDWARN,
2163 "#%s before C++23 is a GCC extension",
2164 pfile->directive->name);
2165 else
2166 cpp_error (pfile, CPP_DL_PEDWARN,
2167 "#%s before C23 is a GCC extension",
2168 pfile->directive->name);
2170 pfile->state.skipping = 1;
2172 else
2174 if (pfile->directive == &dtable[T_ELIF])
2175 pfile->state.skipping = !_cpp_parse_expr (pfile, false);
2176 else
2178 cpp_hashnode *node = lex_macro_node (pfile, false);
2180 if (node)
2182 bool macro_defined = _cpp_defined_macro_p (node);
2183 if (!_cpp_maybe_notify_macro_use (pfile, node,
2184 pfile->directive_line))
2185 /* It wasn't a macro after all. */
2186 macro_defined = false;
2187 bool skip = (pfile->directive == &dtable[T_ELIFDEF]
2188 ? !macro_defined
2189 : macro_defined);
2190 if (pfile->cb.used)
2191 pfile->cb.used (pfile, pfile->directive_line, node);
2192 check_eol (pfile, false);
2193 /* In older GNU standards, #elifdef/#elifndef is supported
2194 as an extension, but pedwarn if -pedantic if the presence
2195 of the directive would change behavior. */
2196 if (! CPP_OPTION (pfile, elifdef)
2197 && CPP_PEDANTIC (pfile)
2198 && pfile->state.skipping != skip)
2200 if (CPP_OPTION (pfile, cplusplus))
2201 cpp_error (pfile, CPP_DL_PEDWARN,
2202 "#%s before C++23 is a GCC extension",
2203 pfile->directive->name);
2204 else
2205 cpp_error (pfile, CPP_DL_PEDWARN,
2206 "#%s before C23 is a GCC extension",
2207 pfile->directive->name);
2209 pfile->state.skipping = skip;
2212 ifs->skip_elses = !pfile->state.skipping;
2215 /* Invalidate any controlling macro. */
2216 ifs->mi_cmacro = 0;
2220 /* Handle a #elifdef directive. */
2221 static void
2222 do_elifdef (cpp_reader *pfile)
2224 do_elif (pfile);
2227 /* Handle a #elifndef directive. */
2228 static void
2229 do_elifndef (cpp_reader *pfile)
2231 do_elif (pfile);
2234 /* #endif pops the if stack and resets pfile->state.skipping. */
2235 static void
2236 do_endif (cpp_reader *pfile)
2238 cpp_buffer *buffer = pfile->buffer;
2239 struct if_stack *ifs = buffer->if_stack;
2241 if (ifs == NULL)
2242 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2243 else
2245 /* Only check EOL if was not originally skipping. */
2246 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2247 check_eol_endif_labels (pfile);
2249 /* If potential control macro, we go back outside again. */
2250 if (ifs->next == 0 && ifs->mi_cmacro)
2252 pfile->mi_valid = true;
2253 pfile->mi_cmacro = ifs->mi_cmacro;
2256 buffer->if_stack = ifs->next;
2257 pfile->state.skipping = ifs->was_skipping;
2258 obstack_free (&pfile->buffer_ob, ifs);
2262 /* Push an if_stack entry for a preprocessor conditional, and set
2263 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2264 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2265 we need to check here that we are at the top of the file. */
2266 static void
2267 push_conditional (cpp_reader *pfile, int skip, int type,
2268 const cpp_hashnode *cmacro)
2270 struct if_stack *ifs;
2271 cpp_buffer *buffer = pfile->buffer;
2273 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2274 ifs->line = pfile->directive_line;
2275 ifs->next = buffer->if_stack;
2276 ifs->skip_elses = pfile->state.skipping || !skip;
2277 ifs->was_skipping = pfile->state.skipping;
2278 ifs->type = type;
2279 /* This condition is effectively a test for top-of-file. */
2280 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2281 ifs->mi_cmacro = cmacro;
2282 else
2283 ifs->mi_cmacro = 0;
2285 pfile->state.skipping = skip;
2286 buffer->if_stack = ifs;
2289 /* Read the tokens of the answer into the macro pool, in a directive
2290 of type TYPE. Only commit the memory if we intend it as permanent
2291 storage, i.e. the #assert case. Returns 0 on success, and sets
2292 ANSWERP to point to the answer. PRED_LOC is the location of the
2293 predicate. */
2294 static bool
2295 parse_answer (cpp_reader *pfile, int type, location_t pred_loc,
2296 cpp_macro **answer_ptr)
2298 /* In a conditional, it is legal to not have an open paren. We
2299 should save the following token in this case. */
2300 const cpp_token *paren = cpp_get_token (pfile);
2302 /* If not a paren, see if we're OK. */
2303 if (paren->type != CPP_OPEN_PAREN)
2305 /* In a conditional no answer is a test for any answer. It
2306 could be followed by any token. */
2307 if (type == T_IF)
2309 _cpp_backup_tokens (pfile, 1);
2310 return true;
2313 /* #unassert with no answer is valid - it removes all answers. */
2314 if (type == T_UNASSERT && paren->type == CPP_EOF)
2315 return true;
2317 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2318 "missing '(' after predicate");
2319 return false;
2322 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2323 _cpp_reserve_room (pfile, 0,
2324 sizeof (cpp_macro)));
2325 answer->parm.next = NULL;
2326 unsigned count = 0;
2327 for (;;)
2329 const cpp_token *token = cpp_get_token (pfile);
2331 if (token->type == CPP_CLOSE_PAREN)
2332 break;
2334 if (token->type == CPP_EOF)
2336 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2337 return false;
2340 answer = (cpp_macro *)_cpp_reserve_room
2341 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2342 sizeof (cpp_token));
2343 answer->exp.tokens[count++] = *token;
2346 if (!count)
2348 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2349 return false;
2352 /* Drop whitespace at start, for answer equivalence purposes. */
2353 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2355 answer->count = count;
2356 *answer_ptr = answer;
2358 return true;
2361 /* Parses an assertion directive of type TYPE, returning a pointer to
2362 the hash node of the predicate, or 0 on error. The node is
2363 guaranteed to be disjoint from the macro namespace, so can only
2364 have type 'NT_VOID'. If an answer was supplied, it is placed in
2365 *ANSWER_PTR, which is otherwise set to 0. */
2366 static cpp_hashnode *
2367 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2369 cpp_hashnode *result = 0;
2371 /* We don't expand predicates or answers. */
2372 pfile->state.prevent_expansion++;
2374 *answer_ptr = NULL;
2376 const cpp_token *predicate = cpp_get_token (pfile);
2377 if (predicate->type == CPP_EOF)
2378 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2379 else if (predicate->type != CPP_NAME)
2380 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2381 "predicate must be an identifier");
2382 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2384 unsigned int len = NODE_LEN (predicate->val.node.node);
2385 unsigned char *sym = (unsigned char *) alloca (len + 1);
2387 /* Prefix '#' to get it out of macro namespace. */
2388 sym[0] = '#';
2389 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2390 result = cpp_lookup (pfile, sym, len + 1);
2393 pfile->state.prevent_expansion--;
2395 return result;
2398 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2399 or a pointer to NULL if the answer is not in the chain. */
2400 static cpp_macro **
2401 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2403 unsigned int i;
2404 cpp_macro **result = NULL;
2406 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2408 cpp_macro *answer = *result;
2410 if (answer->count == candidate->count)
2412 for (i = 0; i < answer->count; i++)
2413 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2414 &candidate->exp.tokens[i]))
2415 break;
2417 if (i == answer->count)
2418 break;
2422 return result;
2425 /* Test an assertion within a preprocessor conditional. Returns
2426 nonzero on failure, zero on success. On success, the result of
2427 the test is written into VALUE, otherwise the value 0. */
2429 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2431 cpp_macro *answer;
2432 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2434 /* For recovery, an erroneous assertion expression is handled as a
2435 failing assertion. */
2436 *value = 0;
2438 if (node)
2440 if (node->value.answers)
2441 *value = !answer || *find_answer (node, answer);
2443 else if (pfile->cur_token[-1].type == CPP_EOF)
2444 _cpp_backup_tokens (pfile, 1);
2446 /* We don't commit the memory for the answer - it's temporary only. */
2447 return node == 0;
2450 /* Handle #assert. */
2451 static void
2452 do_assert (cpp_reader *pfile)
2454 cpp_macro *answer;
2455 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2457 if (node)
2459 /* Place the new answer in the answer list. First check there
2460 is not a duplicate. */
2461 if (*find_answer (node, answer))
2463 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2464 NODE_NAME (node) + 1);
2465 return;
2468 /* Commit or allocate storage for the answer. */
2469 answer = (cpp_macro *)_cpp_commit_buff
2470 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2471 + sizeof (cpp_token) * answer->count);
2473 /* Chain into the list. */
2474 answer->parm.next = node->value.answers;
2475 node->value.answers = answer;
2477 check_eol (pfile, false);
2481 /* Handle #unassert. */
2482 static void
2483 do_unassert (cpp_reader *pfile)
2485 cpp_macro *answer;
2486 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2488 /* It isn't an error to #unassert something that isn't asserted. */
2489 if (node)
2491 if (answer)
2493 cpp_macro **p = find_answer (node, answer);
2495 /* Remove the assert from the list. */
2496 if (cpp_macro *temp = *p)
2497 *p = temp->parm.next;
2499 check_eol (pfile, false);
2501 else
2502 _cpp_free_definition (node);
2505 /* We don't commit the memory for the answer - it's temporary only. */
2508 /* These are for -D, -U, -A. */
2510 /* Process the string STR as if it appeared as the body of a #define.
2511 If STR is just an identifier, define it with value 1.
2512 If STR has anything after the identifier, then it should
2513 be identifier=definition. */
2514 void
2515 cpp_define (cpp_reader *pfile, const char *str)
2517 char *buf;
2518 const char *p;
2519 size_t count;
2521 /* Copy the entire option so we can modify it.
2522 Change the first "=" in the string to a space. If there is none,
2523 tack " 1" on the end. */
2525 count = strlen (str);
2526 buf = (char *) alloca (count + 3);
2527 memcpy (buf, str, count);
2529 p = strchr (str, '=');
2530 if (p)
2531 buf[p - str] = ' ';
2532 else
2534 buf[count++] = ' ';
2535 buf[count++] = '1';
2537 buf[count] = '\n';
2539 run_directive (pfile, T_DEFINE, buf, count);
2542 /* Like cpp_define, but does not warn about unused macro. */
2543 void
2544 cpp_define_unused (cpp_reader *pfile, const char *str)
2546 unsigned char warn_unused_macros = CPP_OPTION (pfile, warn_unused_macros);
2547 CPP_OPTION (pfile, warn_unused_macros) = 0;
2548 cpp_define (pfile, str);
2549 CPP_OPTION (pfile, warn_unused_macros) = warn_unused_macros;
2552 /* Use to build macros to be run through cpp_define() as
2553 described above.
2554 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2556 void
2557 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2559 char *ptr;
2561 va_list ap;
2562 va_start (ap, fmt);
2563 ptr = xvasprintf (fmt, ap);
2564 va_end (ap);
2566 cpp_define (pfile, ptr);
2567 free (ptr);
2570 /* Like cpp_define_formatted, but does not warn about unused macro. */
2571 void
2572 cpp_define_formatted_unused (cpp_reader *pfile, const char *fmt, ...)
2574 char *ptr;
2576 va_list ap;
2577 va_start (ap, fmt);
2578 ptr = xvasprintf (fmt, ap);
2579 va_end (ap);
2581 cpp_define_unused (pfile, ptr);
2582 free (ptr);
2585 /* Slight variant of the above for use by initialize_builtins. */
2586 void
2587 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2589 size_t len = strlen (str);
2590 char *buf = (char *) alloca (len + 1);
2591 memcpy (buf, str, len);
2592 buf[len] = '\n';
2593 run_directive (pfile, T_DEFINE, buf, len);
2596 /* Process MACRO as if it appeared as the body of an #undef. */
2597 void
2598 cpp_undef (cpp_reader *pfile, const char *macro)
2600 size_t len = strlen (macro);
2601 char *buf = (char *) alloca (len + 1);
2602 memcpy (buf, macro, len);
2603 buf[len] = '\n';
2604 run_directive (pfile, T_UNDEF, buf, len);
2607 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2608 or first element is zero, then the macro should be undefined. */
2609 static void
2610 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2612 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2613 if (node == NULL)
2614 return;
2616 if (pfile->cb.before_define)
2617 pfile->cb.before_define (pfile);
2619 if (cpp_macro_p (node))
2621 if (pfile->cb.undef)
2622 pfile->cb.undef (pfile, pfile->directive_line, node);
2623 if (CPP_OPTION (pfile, warn_unused_macros))
2624 _cpp_warn_if_unused_macro (pfile, node, NULL);
2625 _cpp_free_definition (node);
2628 if (c->is_undef)
2629 return;
2630 if (c->is_builtin)
2632 _cpp_restore_special_builtin (pfile, c);
2633 return;
2637 size_t namelen;
2638 const uchar *dn;
2639 cpp_hashnode *h = NULL;
2640 cpp_buffer *nbuf;
2642 namelen = ustrcspn (c->definition, "( \n");
2643 h = cpp_lookup (pfile, c->definition, namelen);
2644 dn = c->definition + namelen;
2646 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2647 if (nbuf != NULL)
2649 _cpp_clean_line (pfile);
2650 nbuf->sysp = 1;
2651 if (!_cpp_create_definition (pfile, h, 0))
2652 abort ();
2653 _cpp_pop_buffer (pfile);
2655 else
2656 abort ();
2657 h->value.macro->line = c->line;
2658 h->value.macro->syshdr = c->syshdr;
2659 h->value.macro->used = c->used;
2663 /* Process the string STR as if it appeared as the body of a #assert. */
2664 void
2665 cpp_assert (cpp_reader *pfile, const char *str)
2667 handle_assertion (pfile, str, T_ASSERT);
2670 /* Process STR as if it appeared as the body of an #unassert. */
2671 void
2672 cpp_unassert (cpp_reader *pfile, const char *str)
2674 handle_assertion (pfile, str, T_UNASSERT);
2677 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2678 static void
2679 handle_assertion (cpp_reader *pfile, const char *str, int type)
2681 size_t count = strlen (str);
2682 const char *p = strchr (str, '=');
2684 /* Copy the entire option so we can modify it. Change the first
2685 "=" in the string to a '(', and tack a ')' on the end. */
2686 char *buf = (char *) alloca (count + 2);
2688 memcpy (buf, str, count);
2689 if (p)
2691 buf[p - str] = '(';
2692 buf[count++] = ')';
2694 buf[count] = '\n';
2695 str = buf;
2697 run_directive (pfile, type, str, count);
2700 /* The options structure. */
2701 cpp_options *
2702 cpp_get_options (cpp_reader *pfile)
2704 return &pfile->opts;
2707 /* The callbacks structure. */
2708 cpp_callbacks *
2709 cpp_get_callbacks (cpp_reader *pfile)
2711 return &pfile->cb;
2714 /* Copy the given callbacks structure to our own. */
2715 void
2716 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2718 pfile->cb = *cb;
2721 /* The narrow character set identifier. */
2722 const char *
2723 cpp_get_narrow_charset_name (cpp_reader *pfile)
2725 return pfile->narrow_cset_desc.to;
2728 /* The wide character set identifier. */
2729 const char *
2730 cpp_get_wide_charset_name (cpp_reader *pfile)
2732 return pfile->wide_cset_desc.to;
2735 /* The dependencies structure. (Creates one if it hasn't already been.) */
2736 class mkdeps *
2737 cpp_get_deps (cpp_reader *pfile)
2739 if (!pfile->deps && CPP_OPTION (pfile, deps.style) != DEPS_NONE)
2740 pfile->deps = deps_init ();
2741 return pfile->deps;
2744 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2745 doesn't fail. It does not generate a file change call back; that
2746 is the responsibility of the caller. */
2747 cpp_buffer *
2748 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2749 int from_stage3)
2751 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2753 /* Clears, amongst other things, if_stack and mi_cmacro. */
2754 memset (new_buffer, 0, sizeof (cpp_buffer));
2756 new_buffer->next_line = new_buffer->buf = buffer;
2757 new_buffer->rlimit = buffer + len;
2758 new_buffer->from_stage3 = from_stage3;
2759 new_buffer->prev = pfile->buffer;
2760 new_buffer->need_line = true;
2762 pfile->buffer = new_buffer;
2764 return new_buffer;
2767 /* Pops a single buffer, with a file change call-back if appropriate.
2768 Then pushes the next -include file, if any remain. */
2769 void
2770 _cpp_pop_buffer (cpp_reader *pfile)
2772 cpp_buffer *buffer = pfile->buffer;
2773 struct _cpp_file *inc = buffer->file;
2774 struct if_stack *ifs;
2775 const unsigned char *to_free;
2777 /* Walk back up the conditional stack till we reach its level at
2778 entry to this file, issuing error messages. */
2779 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2780 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2781 "unterminated #%s", dtable[ifs->type].name);
2783 /* In case of a missing #endif. */
2784 pfile->state.skipping = 0;
2786 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2787 pfile->buffer = buffer->prev;
2789 to_free = buffer->to_free;
2790 free (buffer->notes);
2792 /* Free the buffer object now; we may want to push a new buffer
2793 in _cpp_push_next_include_file. */
2794 obstack_free (&pfile->buffer_ob, buffer);
2796 if (inc)
2798 _cpp_pop_file_buffer (pfile, inc, to_free);
2800 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2802 else if (to_free)
2803 free ((void *)to_free);
2806 /* Enter all recognized directives in the hash table. */
2807 void
2808 _cpp_init_directives (cpp_reader *pfile)
2810 for (int i = 0; i < N_DIRECTIVES; i++)
2812 cpp_hashnode *node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2813 node->is_directive = 1;
2814 node->directive_index = i;
2818 /* Extract header file from a bracket include. Parsing starts after '<'.
2819 The string is malloced and must be freed by the caller. */
2820 char *
2821 _cpp_bracket_include(cpp_reader *pfile)
2823 return glue_header_name (pfile);