ada: Fix internal error on array constant in expression function
[official-gcc.git] / libcpp / directives.cc
blob1fdd73edcb8696044bb78b059e140f7408d6628e
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 /* If we have been requested to expand comments into macros,
659 then re-enable saving of comments. */
660 pfile->state.save_comments =
661 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
663 if (pfile->cb.before_define)
664 pfile->cb.before_define (pfile);
666 if (_cpp_create_definition (pfile, node))
667 if (pfile->cb.define)
668 pfile->cb.define (pfile, pfile->directive_line, node);
670 node->flags &= ~NODE_USED;
674 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
675 static void
676 do_undef (cpp_reader *pfile)
678 cpp_hashnode *node = lex_macro_node (pfile, true);
680 if (node)
682 if (pfile->cb.before_define)
683 pfile->cb.before_define (pfile);
685 if (pfile->cb.undef)
686 pfile->cb.undef (pfile, pfile->directive_line, node);
688 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
689 identifier is not currently defined as a macro name. */
690 if (cpp_macro_p (node))
692 if (node->flags & NODE_WARN)
693 cpp_error (pfile, CPP_DL_WARNING,
694 "undefining \"%s\"", NODE_NAME (node));
695 else if (cpp_builtin_macro_p (node)
696 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
697 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
698 pfile->directive_line, 0,
699 "undefining \"%s\"", NODE_NAME (node));
701 if (node->value.macro
702 && CPP_OPTION (pfile, warn_unused_macros))
703 _cpp_warn_if_unused_macro (pfile, node, NULL);
705 _cpp_free_definition (node);
709 check_eol (pfile, false);
712 /* Undefine a single macro/assertion/whatever. */
714 static int
715 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
716 void *data_p ATTRIBUTE_UNUSED)
718 /* Body of _cpp_free_definition inlined here for speed.
719 Macros and assertions no longer have anything to free. */
720 h->type = NT_VOID;
721 h->value.answers = NULL;
722 h->flags &= ~(NODE_POISONED|NODE_DISABLED|NODE_USED);
723 return 1;
726 /* Undefine all macros and assertions. */
728 void
729 cpp_undef_all (cpp_reader *pfile)
731 cpp_forall_identifiers (pfile, undefine_macros, NULL);
735 /* Helper routine used by parse_include. Reinterpret the current line
736 as an h-char-sequence (< ... >); we are looking at the first token
737 after the <. Returns a malloced filename. */
738 static char *
739 glue_header_name (cpp_reader *pfile)
741 const cpp_token *token;
742 char *buffer;
743 size_t len, total_len = 0, capacity = 1024;
745 /* To avoid lexed tokens overwriting our glued name, we can only
746 allocate from the string pool once we've lexed everything. */
747 buffer = XNEWVEC (char, capacity);
748 for (;;)
750 token = get_token_no_padding (pfile);
752 if (token->type == CPP_GREATER)
753 break;
754 if (token->type == CPP_EOF)
756 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
757 break;
760 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
761 if (total_len + len > capacity)
763 capacity = (capacity + len) * 2;
764 buffer = XRESIZEVEC (char, buffer, capacity);
767 if (token->flags & PREV_WHITE)
768 buffer[total_len++] = ' ';
770 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
771 true)
772 - (uchar *) buffer);
775 buffer[total_len] = '\0';
776 return buffer;
779 /* Returns the file name of #include, #include_next, #import and
780 #pragma dependency. The string is malloced and the caller should
781 free it. Returns NULL on error. LOCATION is the source location
782 of the file name. */
784 static const char *
785 parse_include (cpp_reader *pfile, int *pangle_brackets,
786 const cpp_token ***buf, location_t *location)
788 char *fname;
789 const cpp_token *header;
791 /* Allow macro expansion. */
792 header = get_token_no_padding (pfile);
793 *location = header->src_loc;
794 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
795 || header->type == CPP_HEADER_NAME)
797 fname = XNEWVEC (char, header->val.str.len - 1);
798 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
799 fname[header->val.str.len - 2] = '\0';
800 *pangle_brackets = header->type == CPP_HEADER_NAME;
802 else if (header->type == CPP_LESS)
804 fname = glue_header_name (pfile);
805 *pangle_brackets = 1;
807 else
809 const unsigned char *dir;
811 if (pfile->directive == &dtable[T_PRAGMA])
812 dir = UC"pragma dependency";
813 else
814 dir = pfile->directive->name;
815 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
816 dir);
818 return NULL;
821 if (pfile->directive == &dtable[T_PRAGMA])
823 /* This pragma allows extra tokens after the file name. */
825 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
826 check_eol (pfile, true);
827 else
829 /* If we are not discarding comments, then gather them while
830 doing the eol check. */
831 *buf = check_eol_return_comments (pfile);
834 return fname;
837 /* Handle #include, #include_next and #import. */
838 static void
839 do_include_common (cpp_reader *pfile, enum include_type type)
841 const char *fname;
842 int angle_brackets;
843 const cpp_token **buf = NULL;
844 location_t location;
846 /* Re-enable saving of comments if requested, so that the include
847 callback can dump comments which follow #include. */
848 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
850 /* Tell the lexer this is an include directive -- we want it to
851 increment the line number even if this is the last line of a file. */
852 pfile->state.in_directive = 2;
854 fname = parse_include (pfile, &angle_brackets, &buf, &location);
855 if (!fname)
856 goto done;
858 if (!*fname)
860 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
861 "empty filename in #%s",
862 pfile->directive->name);
863 goto done;
866 /* Prevent #include recursion. */
867 if (pfile->line_table->depth >= CPP_OPTION (pfile, max_include_depth))
868 cpp_error (pfile,
869 CPP_DL_ERROR,
870 "#include nested depth %u exceeds maximum of %u"
871 " (use -fmax-include-depth=DEPTH to increase the maximum)",
872 pfile->line_table->depth,
873 CPP_OPTION (pfile, max_include_depth));
874 else
876 /* Get out of macro context, if we are. */
877 skip_rest_of_line (pfile);
879 if (pfile->cb.include)
880 pfile->cb.include (pfile, pfile->directive_line,
881 pfile->directive->name, fname, angle_brackets,
882 buf);
884 _cpp_stack_include (pfile, fname, angle_brackets, type, location);
887 done:
888 XDELETEVEC (fname);
889 if (buf)
890 XDELETEVEC (buf);
893 static void
894 do_include (cpp_reader *pfile)
896 do_include_common (pfile, IT_INCLUDE);
899 static void
900 do_import (cpp_reader *pfile)
902 do_include_common (pfile, IT_IMPORT);
905 static void
906 do_include_next (cpp_reader *pfile)
908 enum include_type type = IT_INCLUDE_NEXT;
910 /* If this is the primary source file, warn and use the normal
911 search logic. */
912 if (_cpp_in_main_source_file (pfile))
914 cpp_error (pfile, CPP_DL_WARNING,
915 "#include_next in primary source file");
916 type = IT_INCLUDE;
918 do_include_common (pfile, type);
921 /* Subroutine of do_linemarker. Read possible flags after file name.
922 LAST is the last flag seen; 0 if this is the first flag. Return the
923 flag if it is valid, 0 at the end of the directive. Otherwise
924 complain. */
925 static unsigned int
926 read_flag (cpp_reader *pfile, unsigned int last)
928 const cpp_token *token = _cpp_lex_token (pfile);
930 if (token->type == CPP_NUMBER && token->val.str.len == 1)
932 unsigned int flag = token->val.str.text[0] - '0';
934 if (flag > last && flag <= 4
935 && (flag != 4 || last == 3)
936 && (flag != 2 || last == 0))
937 return flag;
940 if (token->type != CPP_EOF)
941 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
942 cpp_token_as_text (pfile, token));
943 return 0;
946 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
947 of length LEN, to binary; store it in NUMP, and return false if the
948 number was well-formed, true if not. WRAPPED is set to true if the
949 number did not fit into 'linenum_type'. */
950 static bool
951 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
953 linenum_type reg = 0;
955 uchar c;
956 bool seen_digit_sep = false;
957 *wrapped = false;
958 while (len--)
960 c = *str++;
961 if (!seen_digit_sep && c == '\'' && len)
963 seen_digit_sep = true;
964 continue;
966 if (!ISDIGIT (c))
967 return true;
968 seen_digit_sep = false;
969 if (reg > ((linenum_type) -1) / 10)
970 *wrapped = true;
971 reg *= 10;
972 if (reg > ((linenum_type) -1) - (c - '0'))
973 *wrapped = true;
974 reg += c - '0';
976 *nump = reg;
977 return false;
980 /* Interpret #line command.
981 Note that the filename string (if any) is a true string constant
982 (escapes are interpreted). */
983 static void
984 do_line (cpp_reader *pfile)
986 class line_maps *line_table = pfile->line_table;
987 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
989 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
990 sysp right now. */
992 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
993 const cpp_token *token;
994 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
995 linenum_type new_lineno;
997 /* C99 raised the minimum limit on #line numbers. */
998 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
999 bool wrapped;
1001 /* #line commands expand macros. */
1002 token = cpp_get_token (pfile);
1003 if (token->type != CPP_NUMBER
1004 || strtolinenum (token->val.str.text, token->val.str.len,
1005 &new_lineno, &wrapped))
1007 if (token->type == CPP_EOF)
1008 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
1009 else
1010 cpp_error (pfile, CPP_DL_ERROR,
1011 "\"%s\" after #line is not a positive integer",
1012 cpp_token_as_text (pfile, token));
1013 return;
1016 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
1017 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
1018 else if (wrapped)
1019 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
1021 token = cpp_get_token (pfile);
1022 if (token->type == CPP_STRING)
1024 cpp_string s = { 0, 0 };
1025 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
1026 &s, CPP_STRING))
1027 new_file = (const char *)s.text;
1028 check_eol (pfile, true);
1030 else if (token->type != CPP_EOF)
1032 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1033 cpp_token_as_text (pfile, token));
1034 return;
1037 skip_rest_of_line (pfile);
1038 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1039 map_sysp);
1040 line_table->seen_line_directive = true;
1043 /* Interpret the # 44 "file" [flags] notation, which has slightly
1044 different syntax and semantics from #line: Flags are allowed,
1045 and we never complain about the line number being too big. */
1046 static void
1047 do_linemarker (cpp_reader *pfile)
1049 class line_maps *line_table = pfile->line_table;
1050 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1051 const cpp_token *token;
1052 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1053 linenum_type new_lineno;
1054 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1055 enum lc_reason reason = LC_RENAME_VERBATIM;
1056 int flag;
1057 bool wrapped;
1059 /* Back up so we can get the number again. Putting this in
1060 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1061 some circumstances, which can segfault. */
1062 _cpp_backup_tokens (pfile, 1);
1064 /* #line commands expand macros. */
1065 token = cpp_get_token (pfile);
1066 if (token->type != CPP_NUMBER
1067 || strtolinenum (token->val.str.text, token->val.str.len,
1068 &new_lineno, &wrapped))
1070 /* Unlike #line, there does not seem to be a way to get an EOF
1071 here. So, it should be safe to always spell the token. */
1072 cpp_error (pfile, CPP_DL_ERROR,
1073 "\"%s\" after # is not a positive integer",
1074 cpp_token_as_text (pfile, token));
1075 return;
1078 token = cpp_get_token (pfile);
1079 if (token->type == CPP_STRING)
1081 cpp_string s = { 0, 0 };
1082 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1083 1, &s, CPP_STRING))
1084 new_file = (const char *)s.text;
1086 new_sysp = 0;
1087 flag = read_flag (pfile, 0);
1088 if (flag == 1)
1090 reason = LC_ENTER;
1091 /* Fake an include for cpp_included (). */
1092 _cpp_fake_include (pfile, new_file);
1093 flag = read_flag (pfile, flag);
1095 else if (flag == 2)
1097 reason = LC_LEAVE;
1098 flag = read_flag (pfile, flag);
1100 if (flag == 3)
1102 new_sysp = 1;
1103 flag = read_flag (pfile, flag);
1104 if (flag == 4)
1105 new_sysp = 2;
1107 pfile->buffer->sysp = new_sysp;
1109 check_eol (pfile, false);
1111 else if (token->type != CPP_EOF)
1113 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1114 cpp_token_as_text (pfile, token));
1115 return;
1118 skip_rest_of_line (pfile);
1120 if (reason == LC_LEAVE)
1122 /* Reread map since cpp_get_token can invalidate it with a
1123 reallocation. */
1124 map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1125 const line_map_ordinary *from
1126 = linemap_included_from_linemap (line_table, map);
1128 if (!from)
1129 /* Not nested. */;
1130 else if (!new_file[0])
1131 /* Leaving to "" means fill in the popped-to name. */
1132 new_file = ORDINARY_MAP_FILE_NAME (from);
1133 else if (filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0)
1134 /* It's the wrong name, Grommit! */
1135 from = NULL;
1137 if (!from)
1139 cpp_warning (pfile, CPP_W_NONE,
1140 "file \"%s\" linemarker ignored due to "
1141 "incorrect nesting", new_file);
1142 return;
1146 /* Compensate for the increment in linemap_add that occurs in
1147 _cpp_do_file_change. We're currently at the start of the line
1148 *following* the #line directive. A separate location_t for this
1149 location makes no sense (until we do the LC_LEAVE), and
1150 complicates LAST_SOURCE_LINE_LOCATION. */
1151 pfile->line_table->highest_location--;
1153 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1154 line_table->seen_line_directive = true;
1157 /* Arrange the file_change callback. Changing to TO_FILE:TO_LINE for
1158 REASON. SYSP is 1 for a system header, 2 for a system header that
1159 needs to be extern "C" protected, and zero otherwise. */
1160 void
1161 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1162 const char *to_file, linenum_type to_line,
1163 unsigned int sysp)
1165 linemap_assert (reason != LC_ENTER_MACRO);
1167 const line_map_ordinary *ord_map = NULL;
1168 if (!to_line && reason == LC_RENAME_VERBATIM)
1170 /* A linemarker moving to line zero. If we're on the second
1171 line of the current map, and it also starts at zero, just
1172 rewind -- we're probably reading the builtins of a
1173 preprocessed source. */
1174 line_map_ordinary *last = LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table);
1175 if (!ORDINARY_MAP_STARTING_LINE_NUMBER (last)
1176 && 0 == filename_cmp (to_file, ORDINARY_MAP_FILE_NAME (last))
1177 && SOURCE_LINE (last, pfile->line_table->highest_line) == 2)
1179 ord_map = last;
1180 pfile->line_table->highest_location
1181 = pfile->line_table->highest_line = MAP_START_LOCATION (last);
1185 if (!ord_map)
1186 if (const line_map *map = linemap_add (pfile->line_table, reason, sysp,
1187 to_file, to_line))
1189 ord_map = linemap_check_ordinary (map);
1190 linemap_line_start (pfile->line_table,
1191 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1192 127);
1195 if (pfile->cb.file_change)
1196 pfile->cb.file_change (pfile, ord_map);
1199 /* Report a warning or error detected by the program we are
1200 processing. Use the directive's tokens in the error message. */
1201 static void
1202 do_diagnostic (cpp_reader *pfile, enum cpp_diagnostic_level code,
1203 enum cpp_warning_reason reason, int print_dir)
1205 const unsigned char *dir_name;
1206 unsigned char *line;
1207 location_t src_loc = pfile->cur_token[-1].src_loc;
1209 if (print_dir)
1210 dir_name = pfile->directive->name;
1211 else
1212 dir_name = NULL;
1213 pfile->state.prevent_expansion++;
1214 line = cpp_output_line_to_string (pfile, dir_name);
1215 pfile->state.prevent_expansion--;
1217 if (code == CPP_DL_WARNING_SYSHDR && reason)
1218 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1219 else if (code == CPP_DL_WARNING && reason)
1220 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1221 else
1222 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1223 free (line);
1226 static void
1227 do_error (cpp_reader *pfile)
1229 do_diagnostic (pfile, CPP_DL_ERROR, CPP_W_NONE, 1);
1232 static void
1233 do_warning (cpp_reader *pfile)
1235 /* We want #warning diagnostics to be emitted in system headers too. */
1236 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1239 /* Report program identification. */
1240 static void
1241 do_ident (cpp_reader *pfile)
1243 const cpp_token *str = cpp_get_token (pfile);
1245 if (str->type != CPP_STRING)
1246 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1247 pfile->directive->name);
1248 else if (pfile->cb.ident)
1249 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1251 check_eol (pfile, false);
1254 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1255 matching entry, or NULL if none is found. The returned entry could
1256 be the start of a namespace chain, or a pragma. */
1257 static struct pragma_entry *
1258 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1260 while (chain && chain->pragma != pragma)
1261 chain = chain->next;
1263 return chain;
1266 /* Create and insert a blank pragma entry at the beginning of a
1267 singly-linked CHAIN. */
1268 static struct pragma_entry *
1269 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1271 struct pragma_entry *new_entry;
1273 new_entry = (struct pragma_entry *)
1274 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1276 memset (new_entry, 0, sizeof (struct pragma_entry));
1277 new_entry->next = *chain;
1279 *chain = new_entry;
1280 return new_entry;
1283 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1284 goes in the global namespace. */
1285 static struct pragma_entry *
1286 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1287 bool allow_name_expansion)
1289 struct pragma_entry **chain = &pfile->pragmas;
1290 struct pragma_entry *entry;
1291 const cpp_hashnode *node;
1293 if (space)
1295 node = cpp_lookup (pfile, UC space, strlen (space));
1296 entry = lookup_pragma_entry (*chain, node);
1297 if (!entry)
1299 entry = new_pragma_entry (pfile, chain);
1300 entry->pragma = node;
1301 entry->is_nspace = true;
1302 entry->allow_expansion = allow_name_expansion;
1304 else if (!entry->is_nspace)
1305 goto clash;
1306 else if (entry->allow_expansion != allow_name_expansion)
1308 cpp_error (pfile, CPP_DL_ICE,
1309 "registering pragmas in namespace \"%s\" with mismatched "
1310 "name expansion", space);
1311 return NULL;
1313 chain = &entry->u.space;
1315 else if (allow_name_expansion)
1317 cpp_error (pfile, CPP_DL_ICE,
1318 "registering pragma \"%s\" with name expansion "
1319 "and no namespace", name);
1320 return NULL;
1323 /* Check for duplicates. */
1324 node = cpp_lookup (pfile, UC name, strlen (name));
1325 entry = lookup_pragma_entry (*chain, node);
1326 if (entry == NULL)
1328 entry = new_pragma_entry (pfile, chain);
1329 entry->pragma = node;
1330 return entry;
1333 if (entry->is_nspace)
1334 clash:
1335 cpp_error (pfile, CPP_DL_ICE,
1336 "registering \"%s\" as both a pragma and a pragma namespace",
1337 NODE_NAME (node));
1338 else if (space)
1339 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1340 space, name);
1341 else
1342 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1344 return NULL;
1347 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1348 static void
1349 register_pragma_internal (cpp_reader *pfile, const char *space,
1350 const char *name, pragma_cb handler)
1352 struct pragma_entry *entry;
1354 entry = register_pragma_1 (pfile, space, name, false);
1355 entry->is_internal = true;
1356 entry->u.handler = handler;
1359 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1360 goes in the global namespace. HANDLER is the handler it will call,
1361 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1362 expansion while parsing pragma NAME. This function is exported
1363 from libcpp. */
1364 void
1365 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1366 pragma_cb handler, bool allow_expansion)
1368 struct pragma_entry *entry;
1370 if (!handler)
1372 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1373 return;
1376 entry = register_pragma_1 (pfile, space, name, false);
1377 if (entry)
1379 entry->allow_expansion = allow_expansion;
1380 entry->u.handler = handler;
1384 /* Similarly, but create mark the pragma for deferred processing.
1385 When found, a CPP_PRAGMA token will be insertted into the stream
1386 with IDENT in the token->u.pragma slot. */
1387 void
1388 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1389 const char *name, unsigned int ident,
1390 bool allow_expansion, bool allow_name_expansion)
1392 struct pragma_entry *entry;
1394 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1395 if (entry)
1397 entry->is_deferred = true;
1398 entry->allow_expansion = allow_expansion;
1399 entry->u.ident = ident;
1403 /* Register the pragmas the preprocessor itself handles. */
1404 void
1405 _cpp_init_internal_pragmas (cpp_reader *pfile)
1407 /* Pragmas in the global namespace. */
1408 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1409 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1410 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1412 /* New GCC-specific pragmas should be put in the GCC namespace. */
1413 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1414 register_pragma_internal (pfile, "GCC", "system_header",
1415 do_pragma_system_header);
1416 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1417 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1418 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1421 /* Return the number of registered pragmas in PE. */
1423 static int
1424 count_registered_pragmas (struct pragma_entry *pe)
1426 int ct = 0;
1427 for (; pe != NULL; pe = pe->next)
1429 if (pe->is_nspace)
1430 ct += count_registered_pragmas (pe->u.space);
1431 ct++;
1433 return ct;
1436 /* Save into SD the names of the registered pragmas referenced by PE,
1437 and return a pointer to the next free space in SD. */
1439 static char **
1440 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1442 for (; pe != NULL; pe = pe->next)
1444 if (pe->is_nspace)
1445 sd = save_registered_pragmas (pe->u.space, sd);
1446 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1447 HT_LEN (&pe->pragma->ident),
1448 HT_LEN (&pe->pragma->ident) + 1);
1450 return sd;
1453 /* Return a newly-allocated array which saves the names of the
1454 registered pragmas. */
1456 char **
1457 _cpp_save_pragma_names (cpp_reader *pfile)
1459 int ct = count_registered_pragmas (pfile->pragmas);
1460 char **result = XNEWVEC (char *, ct);
1461 (void) save_registered_pragmas (pfile->pragmas, result);
1462 return result;
1465 /* Restore from SD the names of the registered pragmas referenced by PE,
1466 and return a pointer to the next unused name in SD. */
1468 static char **
1469 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1470 char **sd)
1472 for (; pe != NULL; pe = pe->next)
1474 if (pe->is_nspace)
1475 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1476 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1477 free (*sd);
1478 sd++;
1480 return sd;
1483 /* Restore the names of the registered pragmas from SAVED. */
1485 void
1486 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1488 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1489 free (saved);
1492 /* Pragmata handling. We handle some, and pass the rest on to the
1493 front end. C99 defines three pragmas and says that no macro
1494 expansion is to be performed on them; whether or not macro
1495 expansion happens for other pragmas is implementation defined.
1496 This implementation allows for a mix of both, since GCC did not
1497 traditionally macro expand its (few) pragmas, whereas OpenMP
1498 specifies that macro expansion should happen. */
1499 static void
1500 do_pragma (cpp_reader *pfile)
1502 const struct pragma_entry *p = NULL;
1503 const cpp_token *token, *pragma_token;
1504 location_t pragma_token_virt_loc = 0;
1505 cpp_token ns_token;
1506 unsigned int count = 1;
1508 pfile->state.prevent_expansion++;
1510 pragma_token = token = cpp_get_token_with_location (pfile,
1511 &pragma_token_virt_loc);
1512 ns_token = *token;
1513 if (token->type == CPP_NAME)
1515 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1516 if (p && p->is_nspace)
1518 bool allow_name_expansion = p->allow_expansion;
1519 if (allow_name_expansion)
1520 pfile->state.prevent_expansion--;
1522 token = cpp_get_token (pfile);
1523 if (token->type == CPP_NAME)
1524 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1525 else
1526 p = NULL;
1527 if (allow_name_expansion)
1528 pfile->state.prevent_expansion++;
1529 count = 2;
1533 if (p)
1535 if (p->is_deferred)
1537 pfile->directive_result.src_loc = pragma_token_virt_loc;
1538 pfile->directive_result.type = CPP_PRAGMA;
1539 pfile->directive_result.flags = pragma_token->flags;
1540 pfile->directive_result.val.pragma = p->u.ident;
1541 pfile->state.in_deferred_pragma = true;
1542 pfile->state.pragma_allow_expansion = p->allow_expansion;
1543 if (!p->allow_expansion)
1544 pfile->state.prevent_expansion++;
1546 else
1548 /* Since the handler below doesn't get the line number, that
1549 it might need for diagnostics, make sure it has the right
1550 numbers in place. */
1551 if (pfile->cb.line_change)
1552 (*pfile->cb.line_change) (pfile, pragma_token, false);
1553 if (p->allow_expansion)
1554 pfile->state.prevent_expansion--;
1555 (*p->u.handler) (pfile);
1556 if (p->allow_expansion)
1557 pfile->state.prevent_expansion++;
1560 else if (pfile->cb.def_pragma)
1562 if (count == 1 || pfile->context->prev == NULL)
1563 _cpp_backup_tokens (pfile, count);
1564 else
1566 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1567 won't allow backing 2 tokens. */
1568 const auto tok_buff = _cpp_get_buff (pfile, 2 * sizeof (cpp_token));
1569 const auto toks = (cpp_token *)tok_buff->base;
1570 toks[0] = ns_token;
1571 toks[0].flags |= NO_EXPAND;
1572 toks[1] = *token;
1573 toks[1].flags |= NO_EXPAND | PREV_WHITE;
1574 _cpp_push_token_context (pfile, NULL, toks, 2);
1575 /* Arrange to free this buffer when no longer needed. */
1576 pfile->context->buff = tok_buff;
1578 pfile->cb.def_pragma (pfile, pfile->directive_line);
1581 pfile->state.prevent_expansion--;
1584 /* Handle #pragma once. */
1585 static void
1586 do_pragma_once (cpp_reader *pfile)
1588 if (_cpp_in_main_source_file (pfile))
1589 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1591 check_eol (pfile, false);
1592 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1595 /* Handle #pragma push_macro(STRING). */
1596 static void
1597 do_pragma_push_macro (cpp_reader *pfile)
1599 cpp_hashnode *node;
1600 size_t defnlen;
1601 const uchar *defn = NULL;
1602 char *macroname, *dest;
1603 const char *limit, *src;
1604 const cpp_token *txt;
1605 struct def_pragma_macro *c;
1607 txt = get__Pragma_string (pfile);
1608 if (!txt)
1610 location_t src_loc = pfile->cur_token[-1].src_loc;
1611 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1612 "invalid #pragma push_macro directive");
1613 check_eol (pfile, false);
1614 skip_rest_of_line (pfile);
1615 return;
1617 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1618 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1619 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1620 while (src < limit)
1622 /* We know there is a character following the backslash. */
1623 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1624 src++;
1625 *dest++ = *src++;
1627 *dest = 0;
1628 check_eol (pfile, false);
1629 skip_rest_of_line (pfile);
1630 c = XNEW (struct def_pragma_macro);
1631 memset (c, 0, sizeof (struct def_pragma_macro));
1632 c->name = XNEWVAR (char, strlen (macroname) + 1);
1633 strcpy (c->name, macroname);
1634 c->next = pfile->pushed_macros;
1635 node = _cpp_lex_identifier (pfile, c->name);
1636 if (node->type == NT_VOID)
1637 c->is_undef = 1;
1638 else if (node->type == NT_BUILTIN_MACRO)
1639 c->is_builtin = 1;
1640 else
1642 defn = cpp_macro_definition (pfile, node);
1643 defnlen = ustrlen (defn);
1644 c->definition = XNEWVEC (uchar, defnlen + 2);
1645 c->definition[defnlen] = '\n';
1646 c->definition[defnlen + 1] = 0;
1647 c->line = node->value.macro->line;
1648 c->syshdr = node->value.macro->syshdr;
1649 c->used = node->value.macro->used;
1650 memcpy (c->definition, defn, defnlen);
1653 pfile->pushed_macros = c;
1656 /* Handle #pragma pop_macro(STRING). */
1657 static void
1658 do_pragma_pop_macro (cpp_reader *pfile)
1660 char *macroname, *dest;
1661 const char *limit, *src;
1662 const cpp_token *txt;
1663 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1664 txt = get__Pragma_string (pfile);
1665 if (!txt)
1667 location_t src_loc = pfile->cur_token[-1].src_loc;
1668 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1669 "invalid #pragma pop_macro directive");
1670 check_eol (pfile, false);
1671 skip_rest_of_line (pfile);
1672 return;
1674 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1675 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1676 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1677 while (src < limit)
1679 /* We know there is a character following the backslash. */
1680 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1681 src++;
1682 *dest++ = *src++;
1684 *dest = 0;
1685 check_eol (pfile, false);
1686 skip_rest_of_line (pfile);
1688 while (c != NULL)
1690 if (!strcmp (c->name, macroname))
1692 if (!l)
1693 pfile->pushed_macros = c->next;
1694 else
1695 l->next = c->next;
1696 cpp_pop_definition (pfile, c);
1697 free (c->definition);
1698 free (c->name);
1699 free (c);
1700 break;
1702 l = c;
1703 c = c->next;
1707 /* Handle #pragma GCC poison, to poison one or more identifiers so
1708 that the lexer produces a hard error for each subsequent usage. */
1709 static void
1710 do_pragma_poison (cpp_reader *pfile)
1712 const cpp_token *tok;
1713 cpp_hashnode *hp;
1715 pfile->state.poisoned_ok = 1;
1716 for (;;)
1718 tok = _cpp_lex_token (pfile);
1719 if (tok->type == CPP_EOF)
1720 break;
1721 if (tok->type != CPP_NAME)
1723 cpp_error (pfile, CPP_DL_ERROR,
1724 "invalid #pragma GCC poison directive");
1725 break;
1728 hp = tok->val.node.node;
1729 if (hp->flags & NODE_POISONED)
1730 continue;
1732 if (cpp_macro_p (hp))
1733 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1734 NODE_NAME (hp));
1735 _cpp_free_definition (hp);
1736 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1738 pfile->state.poisoned_ok = 0;
1741 /* Mark the current header as a system header. This will suppress
1742 some categories of warnings (notably those from -pedantic). It is
1743 intended for use in system libraries that cannot be implemented in
1744 conforming C, but cannot be certain that their headers appear in a
1745 system include directory. To prevent abuse, it is rejected in the
1746 primary source file. */
1747 static void
1748 do_pragma_system_header (cpp_reader *pfile)
1750 if (_cpp_in_main_source_file (pfile))
1751 cpp_error (pfile, CPP_DL_WARNING,
1752 "#pragma system_header ignored outside include file");
1753 else
1755 check_eol (pfile, false);
1756 skip_rest_of_line (pfile);
1757 cpp_make_system_header (pfile, 1, 0);
1761 /* Check the modified date of the current include file against a specified
1762 file. Issue a diagnostic, if the specified file is newer. We use this to
1763 determine if a fixed header should be refixed. */
1764 static void
1765 do_pragma_dependency (cpp_reader *pfile)
1767 const char *fname;
1768 int angle_brackets, ordering;
1769 location_t location;
1771 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1772 if (!fname)
1773 return;
1775 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1776 if (ordering < 0)
1777 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1778 else if (ordering > 0)
1780 cpp_error (pfile, CPP_DL_WARNING,
1781 "current file is older than %s", fname);
1782 if (cpp_get_token (pfile)->type != CPP_EOF)
1784 _cpp_backup_tokens (pfile, 1);
1785 do_diagnostic (pfile, CPP_DL_WARNING, CPP_W_NONE, 0);
1789 free ((void *) fname);
1792 /* Issue a diagnostic with the message taken from the pragma. If
1793 ERROR is true, the diagnostic is a warning, otherwise, it is an
1794 error. */
1795 static void
1796 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1798 const cpp_token *tok = _cpp_lex_token (pfile);
1799 cpp_string str;
1800 if (tok->type != CPP_STRING
1801 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1802 CPP_STRING)
1803 || str.len == 0)
1805 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1806 error ? "error" : "warning");
1807 return;
1809 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1810 "%s", str.text);
1811 free ((void *)str.text);
1814 /* Issue a warning diagnostic. */
1815 static void
1816 do_pragma_warning (cpp_reader *pfile)
1818 do_pragma_warning_or_error (pfile, false);
1821 /* Issue an error diagnostic. */
1822 static void
1823 do_pragma_error (cpp_reader *pfile)
1825 do_pragma_warning_or_error (pfile, true);
1828 /* Get a token but skip padding. */
1829 static const cpp_token *
1830 get_token_no_padding (cpp_reader *pfile)
1832 for (;;)
1834 const cpp_token *result = cpp_get_token (pfile);
1835 if (result->type != CPP_PADDING)
1836 return result;
1840 /* Check syntax is "(string-literal)". Returns the string on success,
1841 or NULL on failure. */
1842 static const cpp_token *
1843 get__Pragma_string (cpp_reader *pfile)
1845 const cpp_token *string;
1846 const cpp_token *paren;
1848 paren = get_token_no_padding (pfile);
1849 if (paren->type == CPP_EOF)
1850 _cpp_backup_tokens (pfile, 1);
1851 if (paren->type != CPP_OPEN_PAREN)
1852 return NULL;
1854 string = get_token_no_padding (pfile);
1855 if (string->type == CPP_EOF)
1856 _cpp_backup_tokens (pfile, 1);
1857 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1858 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1859 && string->type != CPP_UTF8STRING)
1860 return NULL;
1862 paren = get_token_no_padding (pfile);
1863 if (paren->type == CPP_EOF)
1864 _cpp_backup_tokens (pfile, 1);
1865 if (paren->type != CPP_CLOSE_PAREN)
1866 return NULL;
1868 return string;
1871 /* Destringize IN into a temporary buffer, by removing the first \ of
1872 \" and \\ sequences, and process the result as a #pragma directive. */
1873 static void
1874 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1875 location_t expansion_loc)
1877 const unsigned char *src, *limit;
1878 char *dest, *result;
1879 cpp_context *saved_context;
1880 cpp_token *saved_cur_token;
1881 tokenrun *saved_cur_run;
1882 cpp_token *toks;
1883 int count;
1884 const struct directive *save_directive;
1886 dest = result = (char *) alloca (in->len - 1);
1887 src = in->text + 1 + (in->text[0] == 'L');
1888 limit = in->text + in->len - 1;
1889 while (src < limit)
1891 /* We know there is a character following the backslash. */
1892 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1893 src++;
1894 *dest++ = *src++;
1896 *dest = '\n';
1898 /* Ugh; an awful kludge. We are really not set up to be lexing
1899 tokens when in the middle of a macro expansion. Use a new
1900 context to force cpp_get_token to lex, and so skip_rest_of_line
1901 doesn't go beyond the end of the text. Also, remember the
1902 current lexing position so we can return to it later.
1904 Something like line-at-a-time lexing should remove the need for
1905 this. */
1906 saved_context = pfile->context;
1907 saved_cur_token = pfile->cur_token;
1908 saved_cur_run = pfile->cur_run;
1910 pfile->context = XCNEW (cpp_context);
1912 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1913 until we've read all of the tokens that we want. */
1914 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1915 /* from_stage3 */ true);
1916 /* ??? Antique Disgusting Hack. What does this do? */
1917 if (pfile->buffer->prev)
1918 pfile->buffer->file = pfile->buffer->prev->file;
1920 start_directive (pfile);
1921 _cpp_clean_line (pfile);
1922 save_directive = pfile->directive;
1923 pfile->directive = &dtable[T_PRAGMA];
1924 do_pragma (pfile);
1925 if (pfile->directive_result.type == CPP_PRAGMA)
1926 pfile->directive_result.flags |= PRAGMA_OP;
1927 end_directive (pfile, 1);
1928 pfile->directive = save_directive;
1930 /* We always insert at least one token, the directive result. It'll
1931 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1932 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1934 /* If we're not handling the pragma internally, read all of the tokens from
1935 the string buffer now, while the string buffer is still installed. */
1936 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1937 to me what the true lifespan of the tokens are. It would appear that
1938 the lifespan is the entire parse of the main input stream, in which case
1939 this may not be wrong. */
1940 if (pfile->directive_result.type == CPP_PRAGMA)
1942 int maxcount;
1944 count = 1;
1945 maxcount = 50;
1946 toks = XNEWVEC (cpp_token, maxcount);
1947 toks[0] = pfile->directive_result;
1948 toks[0].src_loc = expansion_loc;
1952 if (count == maxcount)
1954 maxcount = maxcount * 3 / 2;
1955 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1957 toks[count] = *cpp_get_token (pfile);
1958 /* _Pragma is a builtin, so we're not within a macro-map, and so
1959 the token locations are set to bogus ordinary locations
1960 near to, but after that of the "_Pragma".
1961 Paper over this by setting them equal to the location of the
1962 _Pragma itself (PR preprocessor/69126). */
1963 toks[count].src_loc = expansion_loc;
1964 /* Macros have been already expanded by cpp_get_token
1965 if the pragma allowed expansion. */
1966 toks[count++].flags |= NO_EXPAND;
1968 while (toks[count-1].type != CPP_PRAGMA_EOL);
1970 else
1972 count = 1;
1973 toks = &pfile->avoid_paste;
1975 /* If we handled the entire pragma internally, make sure we get the
1976 line number correct for the next token. */
1977 if (pfile->cb.line_change)
1978 pfile->cb.line_change (pfile, pfile->cur_token, false);
1981 /* Finish inlining run_directive. */
1982 pfile->buffer->file = NULL;
1983 _cpp_pop_buffer (pfile);
1985 /* Reset the old macro state before ... */
1986 XDELETE (pfile->context);
1987 pfile->context = saved_context;
1988 pfile->cur_token = saved_cur_token;
1989 pfile->cur_run = saved_cur_run;
1991 /* ... inserting the new tokens we collected. */
1992 _cpp_push_token_context (pfile, NULL, toks, count);
1995 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1997 _cpp_do__Pragma (cpp_reader *pfile, location_t expansion_loc)
1999 /* Make sure we don't invalidate the string token, if the closing parenthesis
2000 ended up on a different line. */
2001 ++pfile->keep_tokens;
2002 const cpp_token *string = get__Pragma_string (pfile);
2003 --pfile->keep_tokens;
2005 pfile->directive_result.type = CPP_PADDING;
2007 if (string)
2009 destringize_and_run (pfile, &string->val.str, expansion_loc);
2010 return 1;
2012 cpp_error (pfile, CPP_DL_ERROR,
2013 "_Pragma takes a parenthesized string literal");
2014 return 0;
2017 /* Handle #ifdef. */
2018 static void
2019 do_ifdef (cpp_reader *pfile)
2021 int skip = 1;
2023 if (! pfile->state.skipping)
2025 cpp_hashnode *node = lex_macro_node (pfile, false);
2027 if (node)
2029 skip = !_cpp_defined_macro_p (node);
2030 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2031 /* It wasn't a macro after all. */
2032 skip = true;
2033 _cpp_mark_macro_used (node);
2034 if (pfile->cb.used)
2035 pfile->cb.used (pfile, pfile->directive_line, node);
2036 check_eol (pfile, false);
2040 push_conditional (pfile, skip, T_IFDEF, 0);
2043 /* Handle #ifndef. */
2044 static void
2045 do_ifndef (cpp_reader *pfile)
2047 int skip = 1;
2048 cpp_hashnode *node = 0;
2050 if (! pfile->state.skipping)
2052 node = lex_macro_node (pfile, false);
2054 if (node)
2056 skip = _cpp_defined_macro_p (node);
2057 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2058 /* It wasn't a macro after all. */
2059 skip = false;
2060 _cpp_mark_macro_used (node);
2061 if (pfile->cb.used)
2062 pfile->cb.used (pfile, pfile->directive_line, node);
2063 check_eol (pfile, false);
2067 push_conditional (pfile, skip, T_IFNDEF, node);
2070 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2071 pfile->mi_ind_cmacro so we can handle multiple-include
2072 optimizations. If macro expansion occurs in the expression, we
2073 cannot treat it as a controlling conditional, since the expansion
2074 could change in the future. That is handled by cpp_get_token. */
2075 static void
2076 do_if (cpp_reader *pfile)
2078 int skip = 1;
2080 if (! pfile->state.skipping)
2081 skip = _cpp_parse_expr (pfile, true) == false;
2083 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2086 /* Flip skipping state if appropriate and continue without changing
2087 if_stack; this is so that the error message for missing #endif's
2088 etc. will point to the original #if. */
2089 static void
2090 do_else (cpp_reader *pfile)
2092 cpp_buffer *buffer = pfile->buffer;
2093 struct if_stack *ifs = buffer->if_stack;
2095 if (ifs == NULL)
2096 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2097 else
2099 if (ifs->type == T_ELSE)
2101 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2102 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2103 "the conditional began here");
2105 ifs->type = T_ELSE;
2107 /* Skip any future (erroneous) #elses or #elifs. */
2108 pfile->state.skipping = ifs->skip_elses;
2109 ifs->skip_elses = true;
2111 /* Invalidate any controlling macro. */
2112 ifs->mi_cmacro = 0;
2114 /* Only check EOL if was not originally skipping. */
2115 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2116 check_eol_endif_labels (pfile);
2120 /* Handle a #elif, #elifdef or #elifndef directive by not changing if_stack
2121 either. See the comment above do_else. */
2122 static void
2123 do_elif (cpp_reader *pfile)
2125 cpp_buffer *buffer = pfile->buffer;
2126 struct if_stack *ifs = buffer->if_stack;
2128 if (ifs == NULL)
2129 cpp_error (pfile, CPP_DL_ERROR, "#%s without #if", pfile->directive->name);
2130 else
2132 if (ifs->type == T_ELSE)
2134 cpp_error (pfile, CPP_DL_ERROR, "#%s after #else",
2135 pfile->directive->name);
2136 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2137 "the conditional began here");
2139 ifs->type = T_ELIF;
2141 /* See DR#412: "Only the first group whose control condition
2142 evaluates to true (nonzero) is processed; any following groups
2143 are skipped and their controlling directives are processed as
2144 if they were in a group that is skipped." */
2145 if (ifs->skip_elses)
2147 /* In older GNU standards, #elifdef/#elifndef is supported
2148 as an extension, but pedwarn if -pedantic if the presence
2149 of the directive would be rejected. */
2150 if (pfile->directive != &dtable[T_ELIF]
2151 && ! CPP_OPTION (pfile, elifdef)
2152 && CPP_PEDANTIC (pfile)
2153 && !pfile->state.skipping)
2155 if (CPP_OPTION (pfile, cplusplus))
2156 cpp_error (pfile, CPP_DL_PEDWARN,
2157 "#%s before C++23 is a GCC extension",
2158 pfile->directive->name);
2159 else
2160 cpp_error (pfile, CPP_DL_PEDWARN,
2161 "#%s before C2X is a GCC extension",
2162 pfile->directive->name);
2164 pfile->state.skipping = 1;
2166 else
2168 if (pfile->directive == &dtable[T_ELIF])
2169 pfile->state.skipping = !_cpp_parse_expr (pfile, false);
2170 else
2172 cpp_hashnode *node = lex_macro_node (pfile, false);
2174 if (node)
2176 bool macro_defined = _cpp_defined_macro_p (node);
2177 if (!_cpp_maybe_notify_macro_use (pfile, node,
2178 pfile->directive_line))
2179 /* It wasn't a macro after all. */
2180 macro_defined = false;
2181 bool skip = (pfile->directive == &dtable[T_ELIFDEF]
2182 ? !macro_defined
2183 : macro_defined);
2184 if (pfile->cb.used)
2185 pfile->cb.used (pfile, pfile->directive_line, node);
2186 check_eol (pfile, false);
2187 /* In older GNU standards, #elifdef/#elifndef is supported
2188 as an extension, but pedwarn if -pedantic if the presence
2189 of the directive would change behavior. */
2190 if (! CPP_OPTION (pfile, elifdef)
2191 && CPP_PEDANTIC (pfile)
2192 && pfile->state.skipping != skip)
2194 if (CPP_OPTION (pfile, cplusplus))
2195 cpp_error (pfile, CPP_DL_PEDWARN,
2196 "#%s before C++23 is a GCC extension",
2197 pfile->directive->name);
2198 else
2199 cpp_error (pfile, CPP_DL_PEDWARN,
2200 "#%s before C2X is a GCC extension",
2201 pfile->directive->name);
2203 pfile->state.skipping = skip;
2206 ifs->skip_elses = !pfile->state.skipping;
2209 /* Invalidate any controlling macro. */
2210 ifs->mi_cmacro = 0;
2214 /* Handle a #elifdef directive. */
2215 static void
2216 do_elifdef (cpp_reader *pfile)
2218 do_elif (pfile);
2221 /* Handle a #elifndef directive. */
2222 static void
2223 do_elifndef (cpp_reader *pfile)
2225 do_elif (pfile);
2228 /* #endif pops the if stack and resets pfile->state.skipping. */
2229 static void
2230 do_endif (cpp_reader *pfile)
2232 cpp_buffer *buffer = pfile->buffer;
2233 struct if_stack *ifs = buffer->if_stack;
2235 if (ifs == NULL)
2236 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2237 else
2239 /* Only check EOL if was not originally skipping. */
2240 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2241 check_eol_endif_labels (pfile);
2243 /* If potential control macro, we go back outside again. */
2244 if (ifs->next == 0 && ifs->mi_cmacro)
2246 pfile->mi_valid = true;
2247 pfile->mi_cmacro = ifs->mi_cmacro;
2250 buffer->if_stack = ifs->next;
2251 pfile->state.skipping = ifs->was_skipping;
2252 obstack_free (&pfile->buffer_ob, ifs);
2256 /* Push an if_stack entry for a preprocessor conditional, and set
2257 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2258 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2259 we need to check here that we are at the top of the file. */
2260 static void
2261 push_conditional (cpp_reader *pfile, int skip, int type,
2262 const cpp_hashnode *cmacro)
2264 struct if_stack *ifs;
2265 cpp_buffer *buffer = pfile->buffer;
2267 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2268 ifs->line = pfile->directive_line;
2269 ifs->next = buffer->if_stack;
2270 ifs->skip_elses = pfile->state.skipping || !skip;
2271 ifs->was_skipping = pfile->state.skipping;
2272 ifs->type = type;
2273 /* This condition is effectively a test for top-of-file. */
2274 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2275 ifs->mi_cmacro = cmacro;
2276 else
2277 ifs->mi_cmacro = 0;
2279 pfile->state.skipping = skip;
2280 buffer->if_stack = ifs;
2283 /* Read the tokens of the answer into the macro pool, in a directive
2284 of type TYPE. Only commit the memory if we intend it as permanent
2285 storage, i.e. the #assert case. Returns 0 on success, and sets
2286 ANSWERP to point to the answer. PRED_LOC is the location of the
2287 predicate. */
2288 static bool
2289 parse_answer (cpp_reader *pfile, int type, location_t pred_loc,
2290 cpp_macro **answer_ptr)
2292 /* In a conditional, it is legal to not have an open paren. We
2293 should save the following token in this case. */
2294 const cpp_token *paren = cpp_get_token (pfile);
2296 /* If not a paren, see if we're OK. */
2297 if (paren->type != CPP_OPEN_PAREN)
2299 /* In a conditional no answer is a test for any answer. It
2300 could be followed by any token. */
2301 if (type == T_IF)
2303 _cpp_backup_tokens (pfile, 1);
2304 return true;
2307 /* #unassert with no answer is valid - it removes all answers. */
2308 if (type == T_UNASSERT && paren->type == CPP_EOF)
2309 return true;
2311 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2312 "missing '(' after predicate");
2313 return false;
2316 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2317 _cpp_reserve_room (pfile, 0,
2318 sizeof (cpp_macro)));
2319 answer->parm.next = NULL;
2320 unsigned count = 0;
2321 for (;;)
2323 const cpp_token *token = cpp_get_token (pfile);
2325 if (token->type == CPP_CLOSE_PAREN)
2326 break;
2328 if (token->type == CPP_EOF)
2330 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2331 return false;
2334 answer = (cpp_macro *)_cpp_reserve_room
2335 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2336 sizeof (cpp_token));
2337 answer->exp.tokens[count++] = *token;
2340 if (!count)
2342 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2343 return false;
2346 /* Drop whitespace at start, for answer equivalence purposes. */
2347 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2349 answer->count = count;
2350 *answer_ptr = answer;
2352 return true;
2355 /* Parses an assertion directive of type TYPE, returning a pointer to
2356 the hash node of the predicate, or 0 on error. The node is
2357 guaranteed to be disjoint from the macro namespace, so can only
2358 have type 'NT_VOID'. If an answer was supplied, it is placed in
2359 *ANSWER_PTR, which is otherwise set to 0. */
2360 static cpp_hashnode *
2361 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2363 cpp_hashnode *result = 0;
2365 /* We don't expand predicates or answers. */
2366 pfile->state.prevent_expansion++;
2368 *answer_ptr = NULL;
2370 const cpp_token *predicate = cpp_get_token (pfile);
2371 if (predicate->type == CPP_EOF)
2372 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2373 else if (predicate->type != CPP_NAME)
2374 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2375 "predicate must be an identifier");
2376 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2378 unsigned int len = NODE_LEN (predicate->val.node.node);
2379 unsigned char *sym = (unsigned char *) alloca (len + 1);
2381 /* Prefix '#' to get it out of macro namespace. */
2382 sym[0] = '#';
2383 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2384 result = cpp_lookup (pfile, sym, len + 1);
2387 pfile->state.prevent_expansion--;
2389 return result;
2392 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2393 or a pointer to NULL if the answer is not in the chain. */
2394 static cpp_macro **
2395 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2397 unsigned int i;
2398 cpp_macro **result = NULL;
2400 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2402 cpp_macro *answer = *result;
2404 if (answer->count == candidate->count)
2406 for (i = 0; i < answer->count; i++)
2407 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2408 &candidate->exp.tokens[i]))
2409 break;
2411 if (i == answer->count)
2412 break;
2416 return result;
2419 /* Test an assertion within a preprocessor conditional. Returns
2420 nonzero on failure, zero on success. On success, the result of
2421 the test is written into VALUE, otherwise the value 0. */
2423 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2425 cpp_macro *answer;
2426 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2428 /* For recovery, an erroneous assertion expression is handled as a
2429 failing assertion. */
2430 *value = 0;
2432 if (node)
2434 if (node->value.answers)
2435 *value = !answer || *find_answer (node, answer);
2437 else if (pfile->cur_token[-1].type == CPP_EOF)
2438 _cpp_backup_tokens (pfile, 1);
2440 /* We don't commit the memory for the answer - it's temporary only. */
2441 return node == 0;
2444 /* Handle #assert. */
2445 static void
2446 do_assert (cpp_reader *pfile)
2448 cpp_macro *answer;
2449 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2451 if (node)
2453 /* Place the new answer in the answer list. First check there
2454 is not a duplicate. */
2455 if (*find_answer (node, answer))
2457 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2458 NODE_NAME (node) + 1);
2459 return;
2462 /* Commit or allocate storage for the answer. */
2463 answer = (cpp_macro *)_cpp_commit_buff
2464 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2465 + sizeof (cpp_token) * answer->count);
2467 /* Chain into the list. */
2468 answer->parm.next = node->value.answers;
2469 node->value.answers = answer;
2471 check_eol (pfile, false);
2475 /* Handle #unassert. */
2476 static void
2477 do_unassert (cpp_reader *pfile)
2479 cpp_macro *answer;
2480 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2482 /* It isn't an error to #unassert something that isn't asserted. */
2483 if (node)
2485 if (answer)
2487 cpp_macro **p = find_answer (node, answer);
2489 /* Remove the assert from the list. */
2490 if (cpp_macro *temp = *p)
2491 *p = temp->parm.next;
2493 check_eol (pfile, false);
2495 else
2496 _cpp_free_definition (node);
2499 /* We don't commit the memory for the answer - it's temporary only. */
2502 /* These are for -D, -U, -A. */
2504 /* Process the string STR as if it appeared as the body of a #define.
2505 If STR is just an identifier, define it with value 1.
2506 If STR has anything after the identifier, then it should
2507 be identifier=definition. */
2508 void
2509 cpp_define (cpp_reader *pfile, const char *str)
2511 char *buf;
2512 const char *p;
2513 size_t count;
2515 /* Copy the entire option so we can modify it.
2516 Change the first "=" in the string to a space. If there is none,
2517 tack " 1" on the end. */
2519 count = strlen (str);
2520 buf = (char *) alloca (count + 3);
2521 memcpy (buf, str, count);
2523 p = strchr (str, '=');
2524 if (p)
2525 buf[p - str] = ' ';
2526 else
2528 buf[count++] = ' ';
2529 buf[count++] = '1';
2531 buf[count] = '\n';
2533 run_directive (pfile, T_DEFINE, buf, count);
2536 /* Like cpp_define, but does not warn about unused macro. */
2537 void
2538 cpp_define_unused (cpp_reader *pfile, const char *str)
2540 unsigned char warn_unused_macros = CPP_OPTION (pfile, warn_unused_macros);
2541 CPP_OPTION (pfile, warn_unused_macros) = 0;
2542 cpp_define (pfile, str);
2543 CPP_OPTION (pfile, warn_unused_macros) = warn_unused_macros;
2546 /* Use to build macros to be run through cpp_define() as
2547 described above.
2548 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2550 void
2551 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2553 char *ptr;
2555 va_list ap;
2556 va_start (ap, fmt);
2557 ptr = xvasprintf (fmt, ap);
2558 va_end (ap);
2560 cpp_define (pfile, ptr);
2561 free (ptr);
2564 /* Like cpp_define_formatted, but does not warn about unused macro. */
2565 void
2566 cpp_define_formatted_unused (cpp_reader *pfile, const char *fmt, ...)
2568 char *ptr;
2570 va_list ap;
2571 va_start (ap, fmt);
2572 ptr = xvasprintf (fmt, ap);
2573 va_end (ap);
2575 cpp_define_unused (pfile, ptr);
2576 free (ptr);
2579 /* Slight variant of the above for use by initialize_builtins. */
2580 void
2581 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2583 size_t len = strlen (str);
2584 char *buf = (char *) alloca (len + 1);
2585 memcpy (buf, str, len);
2586 buf[len] = '\n';
2587 run_directive (pfile, T_DEFINE, buf, len);
2590 /* Process MACRO as if it appeared as the body of an #undef. */
2591 void
2592 cpp_undef (cpp_reader *pfile, const char *macro)
2594 size_t len = strlen (macro);
2595 char *buf = (char *) alloca (len + 1);
2596 memcpy (buf, macro, len);
2597 buf[len] = '\n';
2598 run_directive (pfile, T_UNDEF, buf, len);
2601 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2602 or first element is zero, then the macro should be undefined. */
2603 static void
2604 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2606 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2607 if (node == NULL)
2608 return;
2610 if (pfile->cb.before_define)
2611 pfile->cb.before_define (pfile);
2613 if (cpp_macro_p (node))
2615 if (pfile->cb.undef)
2616 pfile->cb.undef (pfile, pfile->directive_line, node);
2617 if (CPP_OPTION (pfile, warn_unused_macros))
2618 _cpp_warn_if_unused_macro (pfile, node, NULL);
2619 _cpp_free_definition (node);
2622 if (c->is_undef)
2623 return;
2624 if (c->is_builtin)
2626 _cpp_restore_special_builtin (pfile, c);
2627 return;
2631 size_t namelen;
2632 const uchar *dn;
2633 cpp_hashnode *h = NULL;
2634 cpp_buffer *nbuf;
2636 namelen = ustrcspn (c->definition, "( \n");
2637 h = cpp_lookup (pfile, c->definition, namelen);
2638 dn = c->definition + namelen;
2640 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2641 if (nbuf != NULL)
2643 _cpp_clean_line (pfile);
2644 nbuf->sysp = 1;
2645 if (!_cpp_create_definition (pfile, h))
2646 abort ();
2647 _cpp_pop_buffer (pfile);
2649 else
2650 abort ();
2651 h->value.macro->line = c->line;
2652 h->value.macro->syshdr = c->syshdr;
2653 h->value.macro->used = c->used;
2657 /* Process the string STR as if it appeared as the body of a #assert. */
2658 void
2659 cpp_assert (cpp_reader *pfile, const char *str)
2661 handle_assertion (pfile, str, T_ASSERT);
2664 /* Process STR as if it appeared as the body of an #unassert. */
2665 void
2666 cpp_unassert (cpp_reader *pfile, const char *str)
2668 handle_assertion (pfile, str, T_UNASSERT);
2671 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2672 static void
2673 handle_assertion (cpp_reader *pfile, const char *str, int type)
2675 size_t count = strlen (str);
2676 const char *p = strchr (str, '=');
2678 /* Copy the entire option so we can modify it. Change the first
2679 "=" in the string to a '(', and tack a ')' on the end. */
2680 char *buf = (char *) alloca (count + 2);
2682 memcpy (buf, str, count);
2683 if (p)
2685 buf[p - str] = '(';
2686 buf[count++] = ')';
2688 buf[count] = '\n';
2689 str = buf;
2691 run_directive (pfile, type, str, count);
2694 /* The options structure. */
2695 cpp_options *
2696 cpp_get_options (cpp_reader *pfile)
2698 return &pfile->opts;
2701 /* The callbacks structure. */
2702 cpp_callbacks *
2703 cpp_get_callbacks (cpp_reader *pfile)
2705 return &pfile->cb;
2708 /* Copy the given callbacks structure to our own. */
2709 void
2710 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2712 pfile->cb = *cb;
2715 /* The narrow character set identifier. */
2716 const char *
2717 cpp_get_narrow_charset_name (cpp_reader *pfile)
2719 return pfile->narrow_cset_desc.to;
2722 /* The wide character set identifier. */
2723 const char *
2724 cpp_get_wide_charset_name (cpp_reader *pfile)
2726 return pfile->wide_cset_desc.to;
2729 /* The dependencies structure. (Creates one if it hasn't already been.) */
2730 class mkdeps *
2731 cpp_get_deps (cpp_reader *pfile)
2733 if (!pfile->deps && CPP_OPTION (pfile, deps.style) != DEPS_NONE)
2734 pfile->deps = deps_init ();
2735 return pfile->deps;
2738 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2739 doesn't fail. It does not generate a file change call back; that
2740 is the responsibility of the caller. */
2741 cpp_buffer *
2742 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2743 int from_stage3)
2745 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2747 /* Clears, amongst other things, if_stack and mi_cmacro. */
2748 memset (new_buffer, 0, sizeof (cpp_buffer));
2750 new_buffer->next_line = new_buffer->buf = buffer;
2751 new_buffer->rlimit = buffer + len;
2752 new_buffer->from_stage3 = from_stage3;
2753 new_buffer->prev = pfile->buffer;
2754 new_buffer->need_line = true;
2756 pfile->buffer = new_buffer;
2758 return new_buffer;
2761 /* Pops a single buffer, with a file change call-back if appropriate.
2762 Then pushes the next -include file, if any remain. */
2763 void
2764 _cpp_pop_buffer (cpp_reader *pfile)
2766 cpp_buffer *buffer = pfile->buffer;
2767 struct _cpp_file *inc = buffer->file;
2768 struct if_stack *ifs;
2769 const unsigned char *to_free;
2771 /* Walk back up the conditional stack till we reach its level at
2772 entry to this file, issuing error messages. */
2773 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2774 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2775 "unterminated #%s", dtable[ifs->type].name);
2777 /* In case of a missing #endif. */
2778 pfile->state.skipping = 0;
2780 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2781 pfile->buffer = buffer->prev;
2783 to_free = buffer->to_free;
2784 free (buffer->notes);
2786 /* Free the buffer object now; we may want to push a new buffer
2787 in _cpp_push_next_include_file. */
2788 obstack_free (&pfile->buffer_ob, buffer);
2790 if (inc)
2792 _cpp_pop_file_buffer (pfile, inc, to_free);
2794 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2796 else if (to_free)
2797 free ((void *)to_free);
2800 /* Enter all recognized directives in the hash table. */
2801 void
2802 _cpp_init_directives (cpp_reader *pfile)
2804 for (int i = 0; i < N_DIRECTIVES; i++)
2806 cpp_hashnode *node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2807 node->is_directive = 1;
2808 node->directive_index = i;
2812 /* Extract header file from a bracket include. Parsing starts after '<'.
2813 The string is malloced and must be freed by the caller. */
2814 char *
2815 _cpp_bracket_include(cpp_reader *pfile)
2817 return glue_header_name (pfile);