Improve packed record layout support with -fdump-ada-spec
[official-gcc.git] / libcpp / directives.c
blob261a584c550936a9f725893cd51887008819995e
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2021 Free Software Foundation, Inc.
3 Contributed by Per Bothner, 1994-95.
4 Based on CCCP program by Paul Rubin, June 1986
5 Adapted to ANSI C, Richard Stallman, Jan 1987
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "cpplib.h"
24 #include "internal.h"
25 #include "mkdeps.h"
26 #include "obstack.h"
28 /* Stack of conditionals currently in progress
29 (including both successful and failing conditionals). */
30 struct if_stack
32 struct if_stack *next;
33 location_t line; /* Line where condition started. */
34 const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
35 bool skip_elses; /* Can future #else / #elif be skipped? */
36 bool was_skipping; /* If were skipping on entry. */
37 int type; /* Most recent conditional for diagnostics. */
40 /* Contains a registered pragma or pragma namespace. */
41 typedef void (*pragma_cb) (cpp_reader *);
42 struct pragma_entry
44 struct pragma_entry *next;
45 const cpp_hashnode *pragma; /* Name and length. */
46 bool is_nspace;
47 bool is_internal;
48 bool is_deferred;
49 bool allow_expansion;
50 union {
51 pragma_cb handler;
52 struct pragma_entry *space;
53 unsigned int ident;
54 } u;
57 /* Values for the origin field of struct directive. KANDR directives
58 come from traditional (K&R) C. STDC89 directives come from the
59 1989 C standard. STDC2X directives come from the C2X standard. EXTENSION
60 directives are extensions. */
61 #define KANDR 0
62 #define STDC89 1
63 #define STDC2X 2
64 #define EXTENSION 3
66 /* Values for the flags field of struct directive. COND indicates a
67 conditional; IF_COND an opening conditional. INCL means to treat
68 "..." and <...> as q-char and h-char sequences respectively. IN_I
69 means this directive should be handled even if -fpreprocessed is in
70 effect (these are the directives with callback hooks).
72 EXPAND is set on directives that are always macro-expanded.
74 ELIFDEF is set on directives that are only handled for standards with the
75 #elifdef / #elifndef feature. */
76 #define COND (1 << 0)
77 #define IF_COND (1 << 1)
78 #define INCL (1 << 2)
79 #define IN_I (1 << 3)
80 #define EXPAND (1 << 4)
81 #define DEPRECATED (1 << 5)
82 #define ELIFDEF (1 << 6)
84 /* Defines one #-directive, including how to handle it. */
85 typedef void (*directive_handler) (cpp_reader *);
86 typedef struct directive directive;
87 struct directive
89 directive_handler handler; /* Function to handle directive. */
90 const uchar *name; /* Name of directive. */
91 unsigned short length; /* Length of name. */
92 unsigned char origin; /* Origin of directive. */
93 unsigned char flags; /* Flags describing this directive. */
96 /* Forward declarations. */
98 static void skip_rest_of_line (cpp_reader *);
99 static void check_eol (cpp_reader *, bool);
100 static void start_directive (cpp_reader *);
101 static void prepare_directive_trad (cpp_reader *);
102 static void end_directive (cpp_reader *, int);
103 static void directive_diagnostics (cpp_reader *, const directive *, int);
104 static void run_directive (cpp_reader *, int, const char *, size_t);
105 static char *glue_header_name (cpp_reader *);
106 static const char *parse_include (cpp_reader *, int *, const cpp_token ***,
107 location_t *);
108 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
109 static unsigned int read_flag (cpp_reader *, unsigned int);
110 static bool strtolinenum (const uchar *, size_t, linenum_type *, bool *);
111 static void do_diagnostic (cpp_reader *, enum cpp_diagnostic_level code,
112 enum cpp_warning_reason reason, int);
113 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
114 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
115 static void do_include_common (cpp_reader *, enum include_type);
116 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
117 const cpp_hashnode *);
118 static int count_registered_pragmas (struct pragma_entry *);
119 static char ** save_registered_pragmas (struct pragma_entry *, char **);
120 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
121 char **);
122 static void do_pragma_once (cpp_reader *);
123 static void do_pragma_poison (cpp_reader *);
124 static void do_pragma_system_header (cpp_reader *);
125 static void do_pragma_dependency (cpp_reader *);
126 static void do_pragma_warning_or_error (cpp_reader *, bool error);
127 static void do_pragma_warning (cpp_reader *);
128 static void do_pragma_error (cpp_reader *);
129 static void do_linemarker (cpp_reader *);
130 static const cpp_token *get_token_no_padding (cpp_reader *);
131 static const cpp_token *get__Pragma_string (cpp_reader *);
132 static void destringize_and_run (cpp_reader *, const cpp_string *,
133 location_t);
134 static bool parse_answer (cpp_reader *, int, location_t, cpp_macro **);
135 static cpp_hashnode *parse_assertion (cpp_reader *, int, cpp_macro **);
136 static cpp_macro **find_answer (cpp_hashnode *, const cpp_macro *);
137 static void handle_assertion (cpp_reader *, const char *, int);
138 static void do_pragma_push_macro (cpp_reader *);
139 static void do_pragma_pop_macro (cpp_reader *);
140 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
142 /* This is the table of directive handlers. All extensions other than
143 #warning, #include_next, and #import are deprecated. The name is
144 where the extension appears to have come from. */
146 #define DIRECTIVE_TABLE \
147 D(define, T_DEFINE = 0, KANDR, IN_I) \
148 D(include, T_INCLUDE, KANDR, INCL | EXPAND) \
149 D(endif, T_ENDIF, KANDR, COND) \
150 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) \
151 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) \
152 D(else, T_ELSE, KANDR, COND) \
153 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) \
154 D(undef, T_UNDEF, KANDR, IN_I) \
155 D(line, T_LINE, KANDR, EXPAND) \
156 D(elif, T_ELIF, STDC89, COND | EXPAND) \
157 D(elifdef, T_ELIFDEF, STDC2X, COND | ELIFDEF) \
158 D(elifndef, T_ELIFNDEF, STDC2X, COND | ELIFDEF) \
159 D(error, T_ERROR, STDC89, 0) \
160 D(pragma, T_PRAGMA, STDC89, IN_I) \
161 D(warning, T_WARNING, EXTENSION, 0) \
162 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) \
163 D(ident, T_IDENT, EXTENSION, IN_I) \
164 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* ObjC */ \
165 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* SVR4 */ \
166 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* SVR4 */ \
167 D(sccs, T_SCCS, EXTENSION, IN_I) /* SVR4? */
169 /* #sccs is synonymous with #ident. */
170 #define do_sccs do_ident
172 /* Use the table to generate a series of prototypes, an enum for the
173 directive names, and an array of directive handlers. */
175 #define D(name, t, o, f) static void do_##name (cpp_reader *);
176 DIRECTIVE_TABLE
177 #undef D
179 #define D(n, tag, o, f) tag,
180 enum
182 DIRECTIVE_TABLE
183 N_DIRECTIVES
185 #undef D
187 #define D(name, t, origin, flags) \
188 { do_##name, (const uchar *) #name, \
189 sizeof #name - 1, origin, flags },
190 static const directive dtable[] =
192 DIRECTIVE_TABLE
194 #undef D
196 /* A NULL-terminated array of directive names for use
197 when suggesting corrections for misspelled directives. */
198 #define D(name, t, origin, flags) #name,
199 static const char * const directive_names[] = {
200 DIRECTIVE_TABLE
201 NULL
203 #undef D
205 #undef DIRECTIVE_TABLE
207 /* Wrapper struct directive for linemarkers.
208 The origin is more or less true - the original K+R cpp
209 did use this notation in its preprocessed output. */
210 static const directive linemarker_dir =
212 do_linemarker, UC"#", 1, KANDR, IN_I
215 /* Skip any remaining tokens in a directive. */
216 static void
217 skip_rest_of_line (cpp_reader *pfile)
219 /* Discard all stacked contexts. */
220 while (pfile->context->prev)
221 _cpp_pop_context (pfile);
223 /* Sweep up all tokens remaining on the line. */
224 if (! SEEN_EOL ())
225 while (_cpp_lex_token (pfile)->type != CPP_EOF)
229 /* Helper function for check_oel. */
231 static void
232 check_eol_1 (cpp_reader *pfile, bool expand, enum cpp_warning_reason reason)
234 if (! SEEN_EOL () && (expand
235 ? cpp_get_token (pfile)
236 : _cpp_lex_token (pfile))->type != CPP_EOF)
237 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
238 pfile->directive->name);
241 /* Variant of check_eol used for Wendif-labels warnings. */
243 static void
244 check_eol_endif_labels (cpp_reader *pfile)
246 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
249 /* Ensure there are no stray tokens at the end of a directive. If
250 EXPAND is true, tokens macro-expanding to nothing are allowed. */
252 static void
253 check_eol (cpp_reader *pfile, bool expand)
255 check_eol_1 (pfile, expand, CPP_W_NONE);
258 /* Ensure there are no stray tokens other than comments at the end of
259 a directive, and gather the comments. */
260 static const cpp_token **
261 check_eol_return_comments (cpp_reader *pfile)
263 size_t c;
264 size_t capacity = 8;
265 const cpp_token **buf;
267 buf = XNEWVEC (const cpp_token *, capacity);
268 c = 0;
269 if (! SEEN_EOL ())
271 while (1)
273 const cpp_token *tok;
275 tok = _cpp_lex_token (pfile);
276 if (tok->type == CPP_EOF)
277 break;
278 if (tok->type != CPP_COMMENT)
279 cpp_error (pfile, CPP_DL_PEDWARN,
280 "extra tokens at end of #%s directive",
281 pfile->directive->name);
282 else
284 if (c + 1 >= capacity)
286 capacity *= 2;
287 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
289 buf[c] = tok;
290 ++c;
294 buf[c] = NULL;
295 return buf;
298 /* Called when entering a directive, _Pragma or command-line directive. */
299 static void
300 start_directive (cpp_reader *pfile)
302 /* Setup in-directive state. */
303 pfile->state.in_directive = 1;
304 pfile->state.save_comments = 0;
305 pfile->directive_result.type = CPP_PADDING;
307 /* Some handlers need the position of the # for diagnostics. */
308 pfile->directive_line = pfile->line_table->highest_line;
311 /* Called when leaving a directive, _Pragma or command-line directive. */
312 static void
313 end_directive (cpp_reader *pfile, int skip_line)
315 if (CPP_OPTION (pfile, traditional))
317 /* Revert change of prepare_directive_trad. */
318 if (!pfile->state.in_deferred_pragma)
319 pfile->state.prevent_expansion--;
321 if (pfile->directive != &dtable[T_DEFINE])
322 _cpp_remove_overlay (pfile);
324 else if (pfile->state.in_deferred_pragma)
326 /* We don't skip for an assembler #. */
327 else if (skip_line)
329 skip_rest_of_line (pfile);
330 if (!pfile->keep_tokens)
332 pfile->cur_run = &pfile->base_run;
333 pfile->cur_token = pfile->base_run.base;
337 /* Restore state. */
338 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
339 pfile->state.in_directive = 0;
340 pfile->state.in_expression = 0;
341 pfile->state.angled_headers = 0;
342 pfile->directive = 0;
345 /* Prepare to handle the directive in pfile->directive. */
346 static void
347 prepare_directive_trad (cpp_reader *pfile)
349 if (pfile->directive != &dtable[T_DEFINE])
351 bool no_expand = (pfile->directive
352 && ! (pfile->directive->flags & EXPAND));
353 bool was_skipping = pfile->state.skipping;
355 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
356 || pfile->directive == &dtable[T_ELIF]);
357 if (pfile->state.in_expression)
358 pfile->state.skipping = false;
360 if (no_expand)
361 pfile->state.prevent_expansion++;
362 _cpp_scan_out_logical_line (pfile, NULL, false);
363 if (no_expand)
364 pfile->state.prevent_expansion--;
366 pfile->state.skipping = was_skipping;
367 _cpp_overlay_buffer (pfile, pfile->out.base,
368 pfile->out.cur - pfile->out.base);
371 /* Stop ISO C from expanding anything. */
372 pfile->state.prevent_expansion++;
375 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
376 the '#' was indented. */
377 static void
378 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
380 /* Issue -pedantic or deprecated warnings for extensions. We let
381 -pedantic take precedence if both are applicable. */
382 if (! pfile->state.skipping)
384 if (dir->origin == EXTENSION
385 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
386 && CPP_PEDANTIC (pfile))
387 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
388 else if (((dir->flags & DEPRECATED) != 0
389 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
390 && CPP_OPTION (pfile, cpp_warn_deprecated))
391 cpp_warning (pfile, CPP_W_DEPRECATED,
392 "#%s is a deprecated GCC extension", dir->name);
395 /* Traditionally, a directive is ignored unless its # is in
396 column 1. Therefore in code intended to work with K+R
397 compilers, directives added by C89 must have their #
398 indented, and directives present in traditional C must not.
399 This is true even of directives in skipped conditional
400 blocks. #elif cannot be used at all. */
401 if (CPP_WTRADITIONAL (pfile))
403 if (dir == &dtable[T_ELIF])
404 cpp_warning (pfile, CPP_W_TRADITIONAL,
405 "suggest not using #elif in traditional C");
406 else if (indented && dir->origin == KANDR)
407 cpp_warning (pfile, CPP_W_TRADITIONAL,
408 "traditional C ignores #%s with the # indented",
409 dir->name);
410 else if (!indented && dir->origin != KANDR)
411 cpp_warning (pfile, CPP_W_TRADITIONAL,
412 "suggest hiding #%s from traditional C with an indented #",
413 dir->name);
417 /* Check if we have a known directive. INDENTED is true if the
418 '#' of the directive was indented. This function is in this file
419 to save unnecessarily exporting dtable etc. to lex.c. Returns
420 nonzero if the line of tokens has been handled, zero if we should
421 continue processing the line. */
423 _cpp_handle_directive (cpp_reader *pfile, bool indented)
425 const directive *dir = 0;
426 const cpp_token *dname;
427 bool was_parsing_args = pfile->state.parsing_args;
428 bool was_discarding_output = pfile->state.discarding_output;
429 int skip = 1;
431 if (was_discarding_output)
432 pfile->state.prevent_expansion = 0;
434 if (was_parsing_args)
436 if (CPP_OPTION (pfile, cpp_pedantic))
437 cpp_error (pfile, CPP_DL_PEDWARN,
438 "embedding a directive within macro arguments is not portable");
439 pfile->state.parsing_args = 0;
440 pfile->state.prevent_expansion = 0;
442 start_directive (pfile);
443 dname = _cpp_lex_token (pfile);
445 if (dname->type == CPP_NAME)
447 if (dname->val.node.node->is_directive)
449 dir = &dtable[dname->val.node.node->directive_index];
450 if ((dir->flags & ELIFDEF) && !CPP_OPTION (pfile, elifdef))
451 dir = 0;
454 /* We do not recognize the # followed by a number extension in
455 assembler code. */
456 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
458 dir = &linemarker_dir;
459 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
460 && ! pfile->state.skipping)
461 cpp_error (pfile, CPP_DL_PEDWARN,
462 "style of line directive is a GCC extension");
465 if (dir)
467 /* If we have a directive that is not an opening conditional,
468 invalidate any control macro. */
469 if (! (dir->flags & IF_COND))
470 pfile->mi_valid = false;
472 /* Kluge alert. In order to be sure that code like this
474 #define HASH #
475 HASH define foo bar
477 does not cause '#define foo bar' to get executed when
478 compiled with -save-temps, we recognize directives in
479 -fpreprocessed mode only if the # is in column 1. macro.c
480 puts a space in front of any '#' at the start of a macro.
482 We exclude the -fdirectives-only case because macro expansion
483 has not been performed yet, and block comments can cause spaces
484 to precede the directive. */
485 if (CPP_OPTION (pfile, preprocessed)
486 && !CPP_OPTION (pfile, directives_only)
487 && (indented || !(dir->flags & IN_I)))
489 skip = 0;
490 dir = 0;
492 else
494 /* In failed conditional groups, all non-conditional
495 directives are ignored. Before doing that, whether
496 skipping or not, we should lex angle-bracketed headers
497 correctly, and maybe output some diagnostics. */
498 pfile->state.angled_headers = dir->flags & INCL;
499 pfile->state.directive_wants_padding = dir->flags & INCL;
500 if (! CPP_OPTION (pfile, preprocessed))
501 directive_diagnostics (pfile, dir, indented);
502 if (pfile->state.skipping && !(dir->flags & COND))
503 dir = 0;
506 else if (dname->type == CPP_EOF)
507 ; /* CPP_EOF is the "null directive". */
508 else
510 /* An unknown directive. Don't complain about it in assembly
511 source: we don't know where the comments are, and # may
512 introduce assembler pseudo-ops. Don't complain about invalid
513 directives in skipped conditional groups (6.10 p4). */
514 if (CPP_OPTION (pfile, lang) == CLK_ASM)
515 skip = 0;
516 else if (!pfile->state.skipping)
518 const char *unrecognized
519 = (const char *)cpp_token_as_text (pfile, dname);
520 const char *hint = NULL;
522 /* Call back into gcc to get a spelling suggestion. Ideally
523 we'd just use best_match from gcc/spellcheck.h (and filter
524 out the uncommon directives), but that requires moving it
525 to a support library. */
526 if (pfile->cb.get_suggestion)
527 hint = pfile->cb.get_suggestion (pfile, unrecognized,
528 directive_names);
530 if (hint)
532 rich_location richloc (pfile->line_table, dname->src_loc);
533 source_range misspelled_token_range
534 = get_range_from_loc (pfile->line_table, dname->src_loc);
535 richloc.add_fixit_replace (misspelled_token_range, hint);
536 cpp_error_at (pfile, CPP_DL_ERROR, &richloc,
537 "invalid preprocessing directive #%s;"
538 " did you mean #%s?",
539 unrecognized, hint);
541 else
542 cpp_error (pfile, CPP_DL_ERROR,
543 "invalid preprocessing directive #%s",
544 unrecognized);
548 pfile->directive = dir;
549 if (CPP_OPTION (pfile, traditional))
550 prepare_directive_trad (pfile);
552 if (dir)
553 pfile->directive->handler (pfile);
554 else if (skip == 0)
555 _cpp_backup_tokens (pfile, 1);
557 end_directive (pfile, skip);
558 if (was_parsing_args && !pfile->state.in_deferred_pragma)
560 /* Restore state when within macro args. */
561 pfile->state.parsing_args = 2;
562 pfile->state.prevent_expansion = 1;
564 if (was_discarding_output)
565 pfile->state.prevent_expansion = 1;
566 return skip;
569 /* Directive handler wrapper used by the command line option
570 processor. BUF is \n terminated. */
571 static void
572 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
574 cpp_push_buffer (pfile, (const uchar *) buf, count,
575 /* from_stage3 */ true);
576 start_directive (pfile);
578 /* This is a short-term fix to prevent a leading '#' being
579 interpreted as a directive. */
580 _cpp_clean_line (pfile);
582 pfile->directive = &dtable[dir_no];
583 if (CPP_OPTION (pfile, traditional))
584 prepare_directive_trad (pfile);
585 pfile->directive->handler (pfile);
586 end_directive (pfile, 1);
587 _cpp_pop_buffer (pfile);
590 /* Checks for validity the macro name in #define, #undef, #ifdef and
591 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
592 processing a #define or #undefine directive, and false
593 otherwise. */
594 static cpp_hashnode *
595 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
597 const cpp_token *token = _cpp_lex_token (pfile);
599 /* The token immediately after #define must be an identifier. That
600 identifier may not be "defined", per C99 6.10.8p4.
601 In C++, it may not be any of the "named operators" either,
602 per C++98 [lex.digraph], [lex.key].
603 Finally, the identifier may not have been poisoned. (In that case
604 the lexer has issued the error message for us.) */
606 if (token->type == CPP_NAME)
608 cpp_hashnode *node = token->val.node.node;
610 if (is_def_or_undef
611 && node == pfile->spec_nodes.n_defined)
612 cpp_error (pfile, CPP_DL_ERROR,
613 "\"%s\" cannot be used as a macro name",
614 NODE_NAME (node));
615 else if (! (node->flags & NODE_POISONED))
616 return node;
618 else if (token->flags & NAMED_OP)
619 cpp_error (pfile, CPP_DL_ERROR,
620 "\"%s\" cannot be used as a macro name as it is an operator in C++",
621 NODE_NAME (token->val.node.node));
622 else if (token->type == CPP_EOF)
623 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
624 pfile->directive->name);
625 else
626 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
628 return NULL;
631 /* Process a #define directive. Most work is done in macro.c. */
632 static void
633 do_define (cpp_reader *pfile)
635 cpp_hashnode *node = lex_macro_node (pfile, true);
637 if (node)
639 /* If we have been requested to expand comments into macros,
640 then re-enable saving of comments. */
641 pfile->state.save_comments =
642 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
644 if (pfile->cb.before_define)
645 pfile->cb.before_define (pfile);
647 if (_cpp_create_definition (pfile, node))
648 if (pfile->cb.define)
649 pfile->cb.define (pfile, pfile->directive_line, node);
651 node->flags &= ~NODE_USED;
655 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
656 static void
657 do_undef (cpp_reader *pfile)
659 cpp_hashnode *node = lex_macro_node (pfile, true);
661 if (node)
663 if (pfile->cb.before_define)
664 pfile->cb.before_define (pfile);
666 if (pfile->cb.undef)
667 pfile->cb.undef (pfile, pfile->directive_line, node);
669 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
670 identifier is not currently defined as a macro name. */
671 if (cpp_macro_p (node))
673 if (node->flags & NODE_WARN)
674 cpp_error (pfile, CPP_DL_WARNING,
675 "undefining \"%s\"", NODE_NAME (node));
676 else if (cpp_builtin_macro_p (node)
677 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
678 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
679 pfile->directive_line, 0,
680 "undefining \"%s\"", NODE_NAME (node));
682 if (node->value.macro
683 && CPP_OPTION (pfile, warn_unused_macros))
684 _cpp_warn_if_unused_macro (pfile, node, NULL);
686 _cpp_free_definition (node);
690 check_eol (pfile, false);
693 /* Undefine a single macro/assertion/whatever. */
695 static int
696 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
697 void *data_p ATTRIBUTE_UNUSED)
699 /* Body of _cpp_free_definition inlined here for speed.
700 Macros and assertions no longer have anything to free. */
701 h->type = NT_VOID;
702 h->value.answers = NULL;
703 h->flags &= ~(NODE_POISONED|NODE_DISABLED|NODE_USED);
704 return 1;
707 /* Undefine all macros and assertions. */
709 void
710 cpp_undef_all (cpp_reader *pfile)
712 cpp_forall_identifiers (pfile, undefine_macros, NULL);
716 /* Helper routine used by parse_include. Reinterpret the current line
717 as an h-char-sequence (< ... >); we are looking at the first token
718 after the <. Returns a malloced filename. */
719 static char *
720 glue_header_name (cpp_reader *pfile)
722 const cpp_token *token;
723 char *buffer;
724 size_t len, total_len = 0, capacity = 1024;
726 /* To avoid lexed tokens overwriting our glued name, we can only
727 allocate from the string pool once we've lexed everything. */
728 buffer = XNEWVEC (char, capacity);
729 for (;;)
731 token = get_token_no_padding (pfile);
733 if (token->type == CPP_GREATER)
734 break;
735 if (token->type == CPP_EOF)
737 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
738 break;
741 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
742 if (total_len + len > capacity)
744 capacity = (capacity + len) * 2;
745 buffer = XRESIZEVEC (char, buffer, capacity);
748 if (token->flags & PREV_WHITE)
749 buffer[total_len++] = ' ';
751 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
752 true)
753 - (uchar *) buffer);
756 buffer[total_len] = '\0';
757 return buffer;
760 /* Returns the file name of #include, #include_next, #import and
761 #pragma dependency. The string is malloced and the caller should
762 free it. Returns NULL on error. LOCATION is the source location
763 of the file name. */
765 static const char *
766 parse_include (cpp_reader *pfile, int *pangle_brackets,
767 const cpp_token ***buf, location_t *location)
769 char *fname;
770 const cpp_token *header;
772 /* Allow macro expansion. */
773 header = get_token_no_padding (pfile);
774 *location = header->src_loc;
775 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
776 || header->type == CPP_HEADER_NAME)
778 fname = XNEWVEC (char, header->val.str.len - 1);
779 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
780 fname[header->val.str.len - 2] = '\0';
781 *pangle_brackets = header->type == CPP_HEADER_NAME;
783 else if (header->type == CPP_LESS)
785 fname = glue_header_name (pfile);
786 *pangle_brackets = 1;
788 else
790 const unsigned char *dir;
792 if (pfile->directive == &dtable[T_PRAGMA])
793 dir = UC"pragma dependency";
794 else
795 dir = pfile->directive->name;
796 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
797 dir);
799 return NULL;
802 if (pfile->directive == &dtable[T_PRAGMA])
804 /* This pragma allows extra tokens after the file name. */
806 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
807 check_eol (pfile, true);
808 else
810 /* If we are not discarding comments, then gather them while
811 doing the eol check. */
812 *buf = check_eol_return_comments (pfile);
815 return fname;
818 /* Handle #include, #include_next and #import. */
819 static void
820 do_include_common (cpp_reader *pfile, enum include_type type)
822 const char *fname;
823 int angle_brackets;
824 const cpp_token **buf = NULL;
825 location_t location;
827 /* Re-enable saving of comments if requested, so that the include
828 callback can dump comments which follow #include. */
829 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
831 /* Tell the lexer this is an include directive -- we want it to
832 increment the line number even if this is the last line of a file. */
833 pfile->state.in_directive = 2;
835 fname = parse_include (pfile, &angle_brackets, &buf, &location);
836 if (!fname)
837 goto done;
839 if (!*fname)
841 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
842 "empty filename in #%s",
843 pfile->directive->name);
844 goto done;
847 /* Prevent #include recursion. */
848 if (pfile->line_table->depth >= CPP_OPTION (pfile, max_include_depth))
849 cpp_error (pfile,
850 CPP_DL_ERROR,
851 "#include nested depth %u exceeds maximum of %u"
852 " (use -fmax-include-depth=DEPTH to increase the maximum)",
853 pfile->line_table->depth,
854 CPP_OPTION (pfile, max_include_depth));
855 else
857 /* Get out of macro context, if we are. */
858 skip_rest_of_line (pfile);
860 if (pfile->cb.include)
861 pfile->cb.include (pfile, pfile->directive_line,
862 pfile->directive->name, fname, angle_brackets,
863 buf);
865 _cpp_stack_include (pfile, fname, angle_brackets, type, location);
868 done:
869 XDELETEVEC (fname);
870 if (buf)
871 XDELETEVEC (buf);
874 static void
875 do_include (cpp_reader *pfile)
877 do_include_common (pfile, IT_INCLUDE);
880 static void
881 do_import (cpp_reader *pfile)
883 do_include_common (pfile, IT_IMPORT);
886 static void
887 do_include_next (cpp_reader *pfile)
889 enum include_type type = IT_INCLUDE_NEXT;
891 /* If this is the primary source file, warn and use the normal
892 search logic. */
893 if (_cpp_in_main_source_file (pfile))
895 cpp_error (pfile, CPP_DL_WARNING,
896 "#include_next in primary source file");
897 type = IT_INCLUDE;
899 do_include_common (pfile, type);
902 /* Subroutine of do_linemarker. Read possible flags after file name.
903 LAST is the last flag seen; 0 if this is the first flag. Return the
904 flag if it is valid, 0 at the end of the directive. Otherwise
905 complain. */
906 static unsigned int
907 read_flag (cpp_reader *pfile, unsigned int last)
909 const cpp_token *token = _cpp_lex_token (pfile);
911 if (token->type == CPP_NUMBER && token->val.str.len == 1)
913 unsigned int flag = token->val.str.text[0] - '0';
915 if (flag > last && flag <= 4
916 && (flag != 4 || last == 3)
917 && (flag != 2 || last == 0))
918 return flag;
921 if (token->type != CPP_EOF)
922 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
923 cpp_token_as_text (pfile, token));
924 return 0;
927 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
928 of length LEN, to binary; store it in NUMP, and return false if the
929 number was well-formed, true if not. WRAPPED is set to true if the
930 number did not fit into 'linenum_type'. */
931 static bool
932 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
934 linenum_type reg = 0;
936 uchar c;
937 bool seen_digit_sep = false;
938 *wrapped = false;
939 while (len--)
941 c = *str++;
942 if (!seen_digit_sep && c == '\'' && len)
944 seen_digit_sep = true;
945 continue;
947 if (!ISDIGIT (c))
948 return true;
949 seen_digit_sep = false;
950 if (reg > ((linenum_type) -1) / 10)
951 *wrapped = true;
952 reg *= 10;
953 if (reg > ((linenum_type) -1) - (c - '0'))
954 *wrapped = true;
955 reg += c - '0';
957 *nump = reg;
958 return false;
961 /* Interpret #line command.
962 Note that the filename string (if any) is a true string constant
963 (escapes are interpreted). */
964 static void
965 do_line (cpp_reader *pfile)
967 class line_maps *line_table = pfile->line_table;
968 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
970 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
971 sysp right now. */
973 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
974 const cpp_token *token;
975 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
976 linenum_type new_lineno;
978 /* C99 raised the minimum limit on #line numbers. */
979 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
980 bool wrapped;
982 /* #line commands expand macros. */
983 token = cpp_get_token (pfile);
984 if (token->type != CPP_NUMBER
985 || strtolinenum (token->val.str.text, token->val.str.len,
986 &new_lineno, &wrapped))
988 if (token->type == CPP_EOF)
989 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
990 else
991 cpp_error (pfile, CPP_DL_ERROR,
992 "\"%s\" after #line is not a positive integer",
993 cpp_token_as_text (pfile, token));
994 return;
997 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
998 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
999 else if (wrapped)
1000 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
1002 token = cpp_get_token (pfile);
1003 if (token->type == CPP_STRING)
1005 cpp_string s = { 0, 0 };
1006 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
1007 &s, CPP_STRING))
1008 new_file = (const char *)s.text;
1009 check_eol (pfile, true);
1011 else if (token->type != CPP_EOF)
1013 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1014 cpp_token_as_text (pfile, token));
1015 return;
1018 skip_rest_of_line (pfile);
1019 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1020 map_sysp);
1021 line_table->seen_line_directive = true;
1024 /* Interpret the # 44 "file" [flags] notation, which has slightly
1025 different syntax and semantics from #line: Flags are allowed,
1026 and we never complain about the line number being too big. */
1027 static void
1028 do_linemarker (cpp_reader *pfile)
1030 class line_maps *line_table = pfile->line_table;
1031 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1032 const cpp_token *token;
1033 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1034 linenum_type new_lineno;
1035 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1036 enum lc_reason reason = LC_RENAME_VERBATIM;
1037 int flag;
1038 bool wrapped;
1040 /* Back up so we can get the number again. Putting this in
1041 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1042 some circumstances, which can segfault. */
1043 _cpp_backup_tokens (pfile, 1);
1045 /* #line commands expand macros. */
1046 token = cpp_get_token (pfile);
1047 if (token->type != CPP_NUMBER
1048 || strtolinenum (token->val.str.text, token->val.str.len,
1049 &new_lineno, &wrapped))
1051 /* Unlike #line, there does not seem to be a way to get an EOF
1052 here. So, it should be safe to always spell the token. */
1053 cpp_error (pfile, CPP_DL_ERROR,
1054 "\"%s\" after # is not a positive integer",
1055 cpp_token_as_text (pfile, token));
1056 return;
1059 token = cpp_get_token (pfile);
1060 if (token->type == CPP_STRING)
1062 cpp_string s = { 0, 0 };
1063 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1064 1, &s, CPP_STRING))
1065 new_file = (const char *)s.text;
1067 new_sysp = 0;
1068 flag = read_flag (pfile, 0);
1069 if (flag == 1)
1071 reason = LC_ENTER;
1072 /* Fake an include for cpp_included (). */
1073 _cpp_fake_include (pfile, new_file);
1074 flag = read_flag (pfile, flag);
1076 else if (flag == 2)
1078 reason = LC_LEAVE;
1079 flag = read_flag (pfile, flag);
1081 if (flag == 3)
1083 new_sysp = 1;
1084 flag = read_flag (pfile, flag);
1085 if (flag == 4)
1086 new_sysp = 2;
1088 pfile->buffer->sysp = new_sysp;
1090 check_eol (pfile, false);
1092 else if (token->type != CPP_EOF)
1094 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1095 cpp_token_as_text (pfile, token));
1096 return;
1099 skip_rest_of_line (pfile);
1101 if (reason == LC_LEAVE)
1103 /* Reread map since cpp_get_token can invalidate it with a
1104 reallocation. */
1105 map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1106 const line_map_ordinary *from
1107 = linemap_included_from_linemap (line_table, map);
1109 if (!from)
1110 /* Not nested. */;
1111 else if (!new_file[0])
1112 /* Leaving to "" means fill in the popped-to name. */
1113 new_file = ORDINARY_MAP_FILE_NAME (from);
1114 else if (filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0)
1115 /* It's the wrong name, Grommit! */
1116 from = NULL;
1118 if (!from)
1120 cpp_warning (pfile, CPP_W_NONE,
1121 "file \"%s\" linemarker ignored due to "
1122 "incorrect nesting", new_file);
1123 return;
1127 /* Compensate for the increment in linemap_add that occurs in
1128 _cpp_do_file_change. We're currently at the start of the line
1129 *following* the #line directive. A separate location_t for this
1130 location makes no sense (until we do the LC_LEAVE), and
1131 complicates LAST_SOURCE_LINE_LOCATION. */
1132 pfile->line_table->highest_location--;
1134 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1135 line_table->seen_line_directive = true;
1138 /* Arrange the file_change callback. Changing to TO_FILE:TO_LINE for
1139 REASON. SYSP is 1 for a system header, 2 for a system header that
1140 needs to be extern "C" protected, and zero otherwise. */
1141 void
1142 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1143 const char *to_file, linenum_type to_line,
1144 unsigned int sysp)
1146 linemap_assert (reason != LC_ENTER_MACRO);
1148 const line_map_ordinary *ord_map = NULL;
1149 if (!to_line && reason == LC_RENAME_VERBATIM)
1151 /* A linemarker moving to line zero. If we're on the second
1152 line of the current map, and it also starts at zero, just
1153 rewind -- we're probably reading the builtins of a
1154 preprocessed source. */
1155 line_map_ordinary *last = LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table);
1156 if (!ORDINARY_MAP_STARTING_LINE_NUMBER (last)
1157 && 0 == filename_cmp (to_file, ORDINARY_MAP_FILE_NAME (last))
1158 && SOURCE_LINE (last, pfile->line_table->highest_line) == 2)
1160 ord_map = last;
1161 pfile->line_table->highest_location
1162 = pfile->line_table->highest_line = MAP_START_LOCATION (last);
1166 if (!ord_map)
1167 if (const line_map *map = linemap_add (pfile->line_table, reason, sysp,
1168 to_file, to_line))
1170 ord_map = linemap_check_ordinary (map);
1171 linemap_line_start (pfile->line_table,
1172 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1173 127);
1176 if (pfile->cb.file_change)
1177 pfile->cb.file_change (pfile, ord_map);
1180 /* Report a warning or error detected by the program we are
1181 processing. Use the directive's tokens in the error message. */
1182 static void
1183 do_diagnostic (cpp_reader *pfile, enum cpp_diagnostic_level code,
1184 enum cpp_warning_reason reason, int print_dir)
1186 const unsigned char *dir_name;
1187 unsigned char *line;
1188 location_t src_loc = pfile->cur_token[-1].src_loc;
1190 if (print_dir)
1191 dir_name = pfile->directive->name;
1192 else
1193 dir_name = NULL;
1194 pfile->state.prevent_expansion++;
1195 line = cpp_output_line_to_string (pfile, dir_name);
1196 pfile->state.prevent_expansion--;
1198 if (code == CPP_DL_WARNING_SYSHDR && reason)
1199 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1200 else if (code == CPP_DL_WARNING && reason)
1201 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1202 else
1203 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1204 free (line);
1207 static void
1208 do_error (cpp_reader *pfile)
1210 do_diagnostic (pfile, CPP_DL_ERROR, CPP_W_NONE, 1);
1213 static void
1214 do_warning (cpp_reader *pfile)
1216 /* We want #warning diagnostics to be emitted in system headers too. */
1217 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1220 /* Report program identification. */
1221 static void
1222 do_ident (cpp_reader *pfile)
1224 const cpp_token *str = cpp_get_token (pfile);
1226 if (str->type != CPP_STRING)
1227 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1228 pfile->directive->name);
1229 else if (pfile->cb.ident)
1230 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1232 check_eol (pfile, false);
1235 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1236 matching entry, or NULL if none is found. The returned entry could
1237 be the start of a namespace chain, or a pragma. */
1238 static struct pragma_entry *
1239 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1241 while (chain && chain->pragma != pragma)
1242 chain = chain->next;
1244 return chain;
1247 /* Create and insert a blank pragma entry at the beginning of a
1248 singly-linked CHAIN. */
1249 static struct pragma_entry *
1250 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1252 struct pragma_entry *new_entry;
1254 new_entry = (struct pragma_entry *)
1255 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1257 memset (new_entry, 0, sizeof (struct pragma_entry));
1258 new_entry->next = *chain;
1260 *chain = new_entry;
1261 return new_entry;
1264 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1265 goes in the global namespace. */
1266 static struct pragma_entry *
1267 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1268 bool allow_name_expansion)
1270 struct pragma_entry **chain = &pfile->pragmas;
1271 struct pragma_entry *entry;
1272 const cpp_hashnode *node;
1274 if (space)
1276 node = cpp_lookup (pfile, UC space, strlen (space));
1277 entry = lookup_pragma_entry (*chain, node);
1278 if (!entry)
1280 entry = new_pragma_entry (pfile, chain);
1281 entry->pragma = node;
1282 entry->is_nspace = true;
1283 entry->allow_expansion = allow_name_expansion;
1285 else if (!entry->is_nspace)
1286 goto clash;
1287 else if (entry->allow_expansion != allow_name_expansion)
1289 cpp_error (pfile, CPP_DL_ICE,
1290 "registering pragmas in namespace \"%s\" with mismatched "
1291 "name expansion", space);
1292 return NULL;
1294 chain = &entry->u.space;
1296 else if (allow_name_expansion)
1298 cpp_error (pfile, CPP_DL_ICE,
1299 "registering pragma \"%s\" with name expansion "
1300 "and no namespace", name);
1301 return NULL;
1304 /* Check for duplicates. */
1305 node = cpp_lookup (pfile, UC name, strlen (name));
1306 entry = lookup_pragma_entry (*chain, node);
1307 if (entry == NULL)
1309 entry = new_pragma_entry (pfile, chain);
1310 entry->pragma = node;
1311 return entry;
1314 if (entry->is_nspace)
1315 clash:
1316 cpp_error (pfile, CPP_DL_ICE,
1317 "registering \"%s\" as both a pragma and a pragma namespace",
1318 NODE_NAME (node));
1319 else if (space)
1320 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1321 space, name);
1322 else
1323 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1325 return NULL;
1328 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1329 static void
1330 register_pragma_internal (cpp_reader *pfile, const char *space,
1331 const char *name, pragma_cb handler)
1333 struct pragma_entry *entry;
1335 entry = register_pragma_1 (pfile, space, name, false);
1336 entry->is_internal = true;
1337 entry->u.handler = handler;
1340 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1341 goes in the global namespace. HANDLER is the handler it will call,
1342 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1343 expansion while parsing pragma NAME. This function is exported
1344 from libcpp. */
1345 void
1346 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1347 pragma_cb handler, bool allow_expansion)
1349 struct pragma_entry *entry;
1351 if (!handler)
1353 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1354 return;
1357 entry = register_pragma_1 (pfile, space, name, false);
1358 if (entry)
1360 entry->allow_expansion = allow_expansion;
1361 entry->u.handler = handler;
1365 /* Similarly, but create mark the pragma for deferred processing.
1366 When found, a CPP_PRAGMA token will be insertted into the stream
1367 with IDENT in the token->u.pragma slot. */
1368 void
1369 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1370 const char *name, unsigned int ident,
1371 bool allow_expansion, bool allow_name_expansion)
1373 struct pragma_entry *entry;
1375 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1376 if (entry)
1378 entry->is_deferred = true;
1379 entry->allow_expansion = allow_expansion;
1380 entry->u.ident = ident;
1384 /* Register the pragmas the preprocessor itself handles. */
1385 void
1386 _cpp_init_internal_pragmas (cpp_reader *pfile)
1388 /* Pragmas in the global namespace. */
1389 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1390 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1391 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1393 /* New GCC-specific pragmas should be put in the GCC namespace. */
1394 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1395 register_pragma_internal (pfile, "GCC", "system_header",
1396 do_pragma_system_header);
1397 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1398 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1399 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1402 /* Return the number of registered pragmas in PE. */
1404 static int
1405 count_registered_pragmas (struct pragma_entry *pe)
1407 int ct = 0;
1408 for (; pe != NULL; pe = pe->next)
1410 if (pe->is_nspace)
1411 ct += count_registered_pragmas (pe->u.space);
1412 ct++;
1414 return ct;
1417 /* Save into SD the names of the registered pragmas referenced by PE,
1418 and return a pointer to the next free space in SD. */
1420 static char **
1421 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1423 for (; pe != NULL; pe = pe->next)
1425 if (pe->is_nspace)
1426 sd = save_registered_pragmas (pe->u.space, sd);
1427 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1428 HT_LEN (&pe->pragma->ident),
1429 HT_LEN (&pe->pragma->ident) + 1);
1431 return sd;
1434 /* Return a newly-allocated array which saves the names of the
1435 registered pragmas. */
1437 char **
1438 _cpp_save_pragma_names (cpp_reader *pfile)
1440 int ct = count_registered_pragmas (pfile->pragmas);
1441 char **result = XNEWVEC (char *, ct);
1442 (void) save_registered_pragmas (pfile->pragmas, result);
1443 return result;
1446 /* Restore from SD the names of the registered pragmas referenced by PE,
1447 and return a pointer to the next unused name in SD. */
1449 static char **
1450 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1451 char **sd)
1453 for (; pe != NULL; pe = pe->next)
1455 if (pe->is_nspace)
1456 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1457 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1458 free (*sd);
1459 sd++;
1461 return sd;
1464 /* Restore the names of the registered pragmas from SAVED. */
1466 void
1467 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1469 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1470 free (saved);
1473 /* Pragmata handling. We handle some, and pass the rest on to the
1474 front end. C99 defines three pragmas and says that no macro
1475 expansion is to be performed on them; whether or not macro
1476 expansion happens for other pragmas is implementation defined.
1477 This implementation allows for a mix of both, since GCC did not
1478 traditionally macro expand its (few) pragmas, whereas OpenMP
1479 specifies that macro expansion should happen. */
1480 static void
1481 do_pragma (cpp_reader *pfile)
1483 const struct pragma_entry *p = NULL;
1484 const cpp_token *token, *pragma_token;
1485 location_t pragma_token_virt_loc = 0;
1486 cpp_token ns_token;
1487 unsigned int count = 1;
1489 pfile->state.prevent_expansion++;
1491 pragma_token = token = cpp_get_token_with_location (pfile,
1492 &pragma_token_virt_loc);
1493 ns_token = *token;
1494 if (token->type == CPP_NAME)
1496 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1497 if (p && p->is_nspace)
1499 bool allow_name_expansion = p->allow_expansion;
1500 if (allow_name_expansion)
1501 pfile->state.prevent_expansion--;
1503 token = cpp_get_token (pfile);
1504 if (token->type == CPP_NAME)
1505 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1506 else
1507 p = NULL;
1508 if (allow_name_expansion)
1509 pfile->state.prevent_expansion++;
1510 count = 2;
1514 if (p)
1516 if (p->is_deferred)
1518 pfile->directive_result.src_loc = pragma_token_virt_loc;
1519 pfile->directive_result.type = CPP_PRAGMA;
1520 pfile->directive_result.flags = pragma_token->flags;
1521 pfile->directive_result.val.pragma = p->u.ident;
1522 pfile->state.in_deferred_pragma = true;
1523 pfile->state.pragma_allow_expansion = p->allow_expansion;
1524 if (!p->allow_expansion)
1525 pfile->state.prevent_expansion++;
1527 else
1529 /* Since the handler below doesn't get the line number, that
1530 it might need for diagnostics, make sure it has the right
1531 numbers in place. */
1532 if (pfile->cb.line_change)
1533 (*pfile->cb.line_change) (pfile, pragma_token, false);
1534 if (p->allow_expansion)
1535 pfile->state.prevent_expansion--;
1536 (*p->u.handler) (pfile);
1537 if (p->allow_expansion)
1538 pfile->state.prevent_expansion++;
1541 else if (pfile->cb.def_pragma)
1543 if (count == 1 || pfile->context->prev == NULL)
1544 _cpp_backup_tokens (pfile, count);
1545 else
1547 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1548 won't allow backing 2 tokens. */
1549 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1550 reads both tokens, we could perhaps free it, but if it doesn't,
1551 we don't know the exact lifespan. */
1552 cpp_token *toks = XNEWVEC (cpp_token, 2);
1553 toks[0] = ns_token;
1554 toks[0].flags |= NO_EXPAND;
1555 toks[1] = *token;
1556 toks[1].flags |= NO_EXPAND;
1557 _cpp_push_token_context (pfile, NULL, toks, 2);
1559 pfile->cb.def_pragma (pfile, pfile->directive_line);
1562 pfile->state.prevent_expansion--;
1565 /* Handle #pragma once. */
1566 static void
1567 do_pragma_once (cpp_reader *pfile)
1569 if (_cpp_in_main_source_file (pfile))
1570 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1572 check_eol (pfile, false);
1573 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1576 /* Handle #pragma push_macro(STRING). */
1577 static void
1578 do_pragma_push_macro (cpp_reader *pfile)
1580 cpp_hashnode *node;
1581 size_t defnlen;
1582 const uchar *defn = NULL;
1583 char *macroname, *dest;
1584 const char *limit, *src;
1585 const cpp_token *txt;
1586 struct def_pragma_macro *c;
1588 txt = get__Pragma_string (pfile);
1589 if (!txt)
1591 location_t src_loc = pfile->cur_token[-1].src_loc;
1592 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1593 "invalid #pragma push_macro directive");
1594 check_eol (pfile, false);
1595 skip_rest_of_line (pfile);
1596 return;
1598 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1599 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1600 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1601 while (src < limit)
1603 /* We know there is a character following the backslash. */
1604 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1605 src++;
1606 *dest++ = *src++;
1608 *dest = 0;
1609 check_eol (pfile, false);
1610 skip_rest_of_line (pfile);
1611 c = XNEW (struct def_pragma_macro);
1612 memset (c, 0, sizeof (struct def_pragma_macro));
1613 c->name = XNEWVAR (char, strlen (macroname) + 1);
1614 strcpy (c->name, macroname);
1615 c->next = pfile->pushed_macros;
1616 node = _cpp_lex_identifier (pfile, c->name);
1617 if (node->type == NT_VOID)
1618 c->is_undef = 1;
1619 else if (node->type == NT_BUILTIN_MACRO)
1620 c->is_builtin = 1;
1621 else
1623 defn = cpp_macro_definition (pfile, node);
1624 defnlen = ustrlen (defn);
1625 c->definition = XNEWVEC (uchar, defnlen + 2);
1626 c->definition[defnlen] = '\n';
1627 c->definition[defnlen + 1] = 0;
1628 c->line = node->value.macro->line;
1629 c->syshdr = node->value.macro->syshdr;
1630 c->used = node->value.macro->used;
1631 memcpy (c->definition, defn, defnlen);
1634 pfile->pushed_macros = c;
1637 /* Handle #pragma pop_macro(STRING). */
1638 static void
1639 do_pragma_pop_macro (cpp_reader *pfile)
1641 char *macroname, *dest;
1642 const char *limit, *src;
1643 const cpp_token *txt;
1644 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1645 txt = get__Pragma_string (pfile);
1646 if (!txt)
1648 location_t src_loc = pfile->cur_token[-1].src_loc;
1649 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1650 "invalid #pragma pop_macro directive");
1651 check_eol (pfile, false);
1652 skip_rest_of_line (pfile);
1653 return;
1655 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1656 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1657 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1658 while (src < limit)
1660 /* We know there is a character following the backslash. */
1661 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1662 src++;
1663 *dest++ = *src++;
1665 *dest = 0;
1666 check_eol (pfile, false);
1667 skip_rest_of_line (pfile);
1669 while (c != NULL)
1671 if (!strcmp (c->name, macroname))
1673 if (!l)
1674 pfile->pushed_macros = c->next;
1675 else
1676 l->next = c->next;
1677 cpp_pop_definition (pfile, c);
1678 free (c->definition);
1679 free (c->name);
1680 free (c);
1681 break;
1683 l = c;
1684 c = c->next;
1688 /* Handle #pragma GCC poison, to poison one or more identifiers so
1689 that the lexer produces a hard error for each subsequent usage. */
1690 static void
1691 do_pragma_poison (cpp_reader *pfile)
1693 const cpp_token *tok;
1694 cpp_hashnode *hp;
1696 pfile->state.poisoned_ok = 1;
1697 for (;;)
1699 tok = _cpp_lex_token (pfile);
1700 if (tok->type == CPP_EOF)
1701 break;
1702 if (tok->type != CPP_NAME)
1704 cpp_error (pfile, CPP_DL_ERROR,
1705 "invalid #pragma GCC poison directive");
1706 break;
1709 hp = tok->val.node.node;
1710 if (hp->flags & NODE_POISONED)
1711 continue;
1713 if (cpp_macro_p (hp))
1714 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1715 NODE_NAME (hp));
1716 _cpp_free_definition (hp);
1717 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1719 pfile->state.poisoned_ok = 0;
1722 /* Mark the current header as a system header. This will suppress
1723 some categories of warnings (notably those from -pedantic). It is
1724 intended for use in system libraries that cannot be implemented in
1725 conforming C, but cannot be certain that their headers appear in a
1726 system include directory. To prevent abuse, it is rejected in the
1727 primary source file. */
1728 static void
1729 do_pragma_system_header (cpp_reader *pfile)
1731 if (_cpp_in_main_source_file (pfile))
1732 cpp_error (pfile, CPP_DL_WARNING,
1733 "#pragma system_header ignored outside include file");
1734 else
1736 check_eol (pfile, false);
1737 skip_rest_of_line (pfile);
1738 cpp_make_system_header (pfile, 1, 0);
1742 /* Check the modified date of the current include file against a specified
1743 file. Issue a diagnostic, if the specified file is newer. We use this to
1744 determine if a fixed header should be refixed. */
1745 static void
1746 do_pragma_dependency (cpp_reader *pfile)
1748 const char *fname;
1749 int angle_brackets, ordering;
1750 location_t location;
1752 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1753 if (!fname)
1754 return;
1756 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1757 if (ordering < 0)
1758 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1759 else if (ordering > 0)
1761 cpp_error (pfile, CPP_DL_WARNING,
1762 "current file is older than %s", fname);
1763 if (cpp_get_token (pfile)->type != CPP_EOF)
1765 _cpp_backup_tokens (pfile, 1);
1766 do_diagnostic (pfile, CPP_DL_WARNING, CPP_W_NONE, 0);
1770 free ((void *) fname);
1773 /* Issue a diagnostic with the message taken from the pragma. If
1774 ERROR is true, the diagnostic is a warning, otherwise, it is an
1775 error. */
1776 static void
1777 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1779 const cpp_token *tok = _cpp_lex_token (pfile);
1780 cpp_string str;
1781 if (tok->type != CPP_STRING
1782 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1783 CPP_STRING)
1784 || str.len == 0)
1786 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1787 error ? "error" : "warning");
1788 return;
1790 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1791 "%s", str.text);
1792 free ((void *)str.text);
1795 /* Issue a warning diagnostic. */
1796 static void
1797 do_pragma_warning (cpp_reader *pfile)
1799 do_pragma_warning_or_error (pfile, false);
1802 /* Issue an error diagnostic. */
1803 static void
1804 do_pragma_error (cpp_reader *pfile)
1806 do_pragma_warning_or_error (pfile, true);
1809 /* Get a token but skip padding. */
1810 static const cpp_token *
1811 get_token_no_padding (cpp_reader *pfile)
1813 for (;;)
1815 const cpp_token *result = cpp_get_token (pfile);
1816 if (result->type != CPP_PADDING)
1817 return result;
1821 /* Check syntax is "(string-literal)". Returns the string on success,
1822 or NULL on failure. */
1823 static const cpp_token *
1824 get__Pragma_string (cpp_reader *pfile)
1826 const cpp_token *string;
1827 const cpp_token *paren;
1829 paren = get_token_no_padding (pfile);
1830 if (paren->type == CPP_EOF)
1831 _cpp_backup_tokens (pfile, 1);
1832 if (paren->type != CPP_OPEN_PAREN)
1833 return NULL;
1835 string = get_token_no_padding (pfile);
1836 if (string->type == CPP_EOF)
1837 _cpp_backup_tokens (pfile, 1);
1838 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1839 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1840 && string->type != CPP_UTF8STRING)
1841 return NULL;
1843 paren = get_token_no_padding (pfile);
1844 if (paren->type == CPP_EOF)
1845 _cpp_backup_tokens (pfile, 1);
1846 if (paren->type != CPP_CLOSE_PAREN)
1847 return NULL;
1849 return string;
1852 /* Destringize IN into a temporary buffer, by removing the first \ of
1853 \" and \\ sequences, and process the result as a #pragma directive. */
1854 static void
1855 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1856 location_t expansion_loc)
1858 const unsigned char *src, *limit;
1859 char *dest, *result;
1860 cpp_context *saved_context;
1861 cpp_token *saved_cur_token;
1862 tokenrun *saved_cur_run;
1863 cpp_token *toks;
1864 int count;
1865 const struct directive *save_directive;
1867 dest = result = (char *) alloca (in->len - 1);
1868 src = in->text + 1 + (in->text[0] == 'L');
1869 limit = in->text + in->len - 1;
1870 while (src < limit)
1872 /* We know there is a character following the backslash. */
1873 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1874 src++;
1875 *dest++ = *src++;
1877 *dest = '\n';
1879 /* Ugh; an awful kludge. We are really not set up to be lexing
1880 tokens when in the middle of a macro expansion. Use a new
1881 context to force cpp_get_token to lex, and so skip_rest_of_line
1882 doesn't go beyond the end of the text. Also, remember the
1883 current lexing position so we can return to it later.
1885 Something like line-at-a-time lexing should remove the need for
1886 this. */
1887 saved_context = pfile->context;
1888 saved_cur_token = pfile->cur_token;
1889 saved_cur_run = pfile->cur_run;
1891 pfile->context = XCNEW (cpp_context);
1893 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1894 until we've read all of the tokens that we want. */
1895 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1896 /* from_stage3 */ true);
1897 /* ??? Antique Disgusting Hack. What does this do? */
1898 if (pfile->buffer->prev)
1899 pfile->buffer->file = pfile->buffer->prev->file;
1901 start_directive (pfile);
1902 _cpp_clean_line (pfile);
1903 save_directive = pfile->directive;
1904 pfile->directive = &dtable[T_PRAGMA];
1905 do_pragma (pfile);
1906 end_directive (pfile, 1);
1907 pfile->directive = save_directive;
1909 /* We always insert at least one token, the directive result. It'll
1910 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1911 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1913 /* If we're not handling the pragma internally, read all of the tokens from
1914 the string buffer now, while the string buffer is still installed. */
1915 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1916 to me what the true lifespan of the tokens are. It would appear that
1917 the lifespan is the entire parse of the main input stream, in which case
1918 this may not be wrong. */
1919 if (pfile->directive_result.type == CPP_PRAGMA)
1921 int maxcount;
1923 count = 1;
1924 maxcount = 50;
1925 toks = XNEWVEC (cpp_token, maxcount);
1926 toks[0] = pfile->directive_result;
1930 if (count == maxcount)
1932 maxcount = maxcount * 3 / 2;
1933 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1935 toks[count] = *cpp_get_token (pfile);
1936 /* _Pragma is a builtin, so we're not within a macro-map, and so
1937 the token locations are set to bogus ordinary locations
1938 near to, but after that of the "_Pragma".
1939 Paper over this by setting them equal to the location of the
1940 _Pragma itself (PR preprocessor/69126). */
1941 toks[count].src_loc = expansion_loc;
1942 /* Macros have been already expanded by cpp_get_token
1943 if the pragma allowed expansion. */
1944 toks[count++].flags |= NO_EXPAND;
1946 while (toks[count-1].type != CPP_PRAGMA_EOL);
1948 else
1950 count = 1;
1951 toks = XNEW (cpp_token);
1952 toks[0] = pfile->directive_result;
1954 /* If we handled the entire pragma internally, make sure we get the
1955 line number correct for the next token. */
1956 if (pfile->cb.line_change)
1957 pfile->cb.line_change (pfile, pfile->cur_token, false);
1960 /* Finish inlining run_directive. */
1961 pfile->buffer->file = NULL;
1962 _cpp_pop_buffer (pfile);
1964 /* Reset the old macro state before ... */
1965 XDELETE (pfile->context);
1966 pfile->context = saved_context;
1967 pfile->cur_token = saved_cur_token;
1968 pfile->cur_run = saved_cur_run;
1970 /* ... inserting the new tokens we collected. */
1971 _cpp_push_token_context (pfile, NULL, toks, count);
1974 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1976 _cpp_do__Pragma (cpp_reader *pfile, location_t expansion_loc)
1978 const cpp_token *string = get__Pragma_string (pfile);
1979 pfile->directive_result.type = CPP_PADDING;
1981 if (string)
1983 destringize_and_run (pfile, &string->val.str, expansion_loc);
1984 return 1;
1986 cpp_error (pfile, CPP_DL_ERROR,
1987 "_Pragma takes a parenthesized string literal");
1988 return 0;
1991 /* Handle #ifdef. */
1992 static void
1993 do_ifdef (cpp_reader *pfile)
1995 int skip = 1;
1997 if (! pfile->state.skipping)
1999 cpp_hashnode *node = lex_macro_node (pfile, false);
2001 if (node)
2003 skip = !_cpp_defined_macro_p (node);
2004 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2005 /* It wasn't a macro after all. */
2006 skip = true;
2007 _cpp_mark_macro_used (node);
2008 if (pfile->cb.used)
2009 pfile->cb.used (pfile, pfile->directive_line, node);
2010 check_eol (pfile, false);
2014 push_conditional (pfile, skip, T_IFDEF, 0);
2017 /* Handle #ifndef. */
2018 static void
2019 do_ifndef (cpp_reader *pfile)
2021 int skip = 1;
2022 cpp_hashnode *node = 0;
2024 if (! pfile->state.skipping)
2026 node = lex_macro_node (pfile, false);
2028 if (node)
2030 skip = _cpp_defined_macro_p (node);
2031 if (!_cpp_maybe_notify_macro_use (pfile, node, pfile->directive_line))
2032 /* It wasn't a macro after all. */
2033 skip = false;
2034 _cpp_mark_macro_used (node);
2035 if (pfile->cb.used)
2036 pfile->cb.used (pfile, pfile->directive_line, node);
2037 check_eol (pfile, false);
2041 push_conditional (pfile, skip, T_IFNDEF, node);
2044 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2045 pfile->mi_ind_cmacro so we can handle multiple-include
2046 optimizations. If macro expansion occurs in the expression, we
2047 cannot treat it as a controlling conditional, since the expansion
2048 could change in the future. That is handled by cpp_get_token. */
2049 static void
2050 do_if (cpp_reader *pfile)
2052 int skip = 1;
2054 if (! pfile->state.skipping)
2055 skip = _cpp_parse_expr (pfile, true) == false;
2057 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2060 /* Flip skipping state if appropriate and continue without changing
2061 if_stack; this is so that the error message for missing #endif's
2062 etc. will point to the original #if. */
2063 static void
2064 do_else (cpp_reader *pfile)
2066 cpp_buffer *buffer = pfile->buffer;
2067 struct if_stack *ifs = buffer->if_stack;
2069 if (ifs == NULL)
2070 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2071 else
2073 if (ifs->type == T_ELSE)
2075 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2076 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2077 "the conditional began here");
2079 ifs->type = T_ELSE;
2081 /* Skip any future (erroneous) #elses or #elifs. */
2082 pfile->state.skipping = ifs->skip_elses;
2083 ifs->skip_elses = true;
2085 /* Invalidate any controlling macro. */
2086 ifs->mi_cmacro = 0;
2088 /* Only check EOL if was not originally skipping. */
2089 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2090 check_eol_endif_labels (pfile);
2094 /* Handle a #elif, #elifdef or #elifndef directive by not changing if_stack
2095 either. See the comment above do_else. */
2096 static void
2097 do_elif (cpp_reader *pfile)
2099 cpp_buffer *buffer = pfile->buffer;
2100 struct if_stack *ifs = buffer->if_stack;
2102 if (ifs == NULL)
2103 cpp_error (pfile, CPP_DL_ERROR, "#%s without #if", pfile->directive->name);
2104 else
2106 if (ifs->type == T_ELSE)
2108 cpp_error (pfile, CPP_DL_ERROR, "#%s after #else",
2109 pfile->directive->name);
2110 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2111 "the conditional began here");
2113 ifs->type = T_ELIF;
2115 /* See DR#412: "Only the first group whose control condition
2116 evaluates to true (nonzero) is processed; any following groups
2117 are skipped and their controlling directives are processed as
2118 if they were in a group that is skipped." */
2119 if (ifs->skip_elses)
2120 pfile->state.skipping = 1;
2121 else
2123 if (pfile->directive == &dtable[T_ELIF])
2124 pfile->state.skipping = !_cpp_parse_expr (pfile, false);
2125 else
2127 cpp_hashnode *node = lex_macro_node (pfile, false);
2129 if (node)
2131 bool macro_defined = _cpp_defined_macro_p (node);
2132 if (!_cpp_maybe_notify_macro_use (pfile, node,
2133 pfile->directive_line))
2134 /* It wasn't a macro after all. */
2135 macro_defined = false;
2136 bool skip = (pfile->directive == &dtable[T_ELIFDEF]
2137 ? !macro_defined
2138 : macro_defined);
2139 if (pfile->cb.used)
2140 pfile->cb.used (pfile, pfile->directive_line, node);
2141 check_eol (pfile, false);
2142 pfile->state.skipping = skip;
2145 ifs->skip_elses = !pfile->state.skipping;
2148 /* Invalidate any controlling macro. */
2149 ifs->mi_cmacro = 0;
2153 /* Handle a #elifdef directive. */
2154 static void
2155 do_elifdef (cpp_reader *pfile)
2157 do_elif (pfile);
2160 /* Handle a #elifndef directive. */
2161 static void
2162 do_elifndef (cpp_reader *pfile)
2164 do_elif (pfile);
2167 /* #endif pops the if stack and resets pfile->state.skipping. */
2168 static void
2169 do_endif (cpp_reader *pfile)
2171 cpp_buffer *buffer = pfile->buffer;
2172 struct if_stack *ifs = buffer->if_stack;
2174 if (ifs == NULL)
2175 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2176 else
2178 /* Only check EOL if was not originally skipping. */
2179 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2180 check_eol_endif_labels (pfile);
2182 /* If potential control macro, we go back outside again. */
2183 if (ifs->next == 0 && ifs->mi_cmacro)
2185 pfile->mi_valid = true;
2186 pfile->mi_cmacro = ifs->mi_cmacro;
2189 buffer->if_stack = ifs->next;
2190 pfile->state.skipping = ifs->was_skipping;
2191 obstack_free (&pfile->buffer_ob, ifs);
2195 /* Push an if_stack entry for a preprocessor conditional, and set
2196 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2197 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2198 we need to check here that we are at the top of the file. */
2199 static void
2200 push_conditional (cpp_reader *pfile, int skip, int type,
2201 const cpp_hashnode *cmacro)
2203 struct if_stack *ifs;
2204 cpp_buffer *buffer = pfile->buffer;
2206 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2207 ifs->line = pfile->directive_line;
2208 ifs->next = buffer->if_stack;
2209 ifs->skip_elses = pfile->state.skipping || !skip;
2210 ifs->was_skipping = pfile->state.skipping;
2211 ifs->type = type;
2212 /* This condition is effectively a test for top-of-file. */
2213 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2214 ifs->mi_cmacro = cmacro;
2215 else
2216 ifs->mi_cmacro = 0;
2218 pfile->state.skipping = skip;
2219 buffer->if_stack = ifs;
2222 /* Read the tokens of the answer into the macro pool, in a directive
2223 of type TYPE. Only commit the memory if we intend it as permanent
2224 storage, i.e. the #assert case. Returns 0 on success, and sets
2225 ANSWERP to point to the answer. PRED_LOC is the location of the
2226 predicate. */
2227 static bool
2228 parse_answer (cpp_reader *pfile, int type, location_t pred_loc,
2229 cpp_macro **answer_ptr)
2231 /* In a conditional, it is legal to not have an open paren. We
2232 should save the following token in this case. */
2233 const cpp_token *paren = cpp_get_token (pfile);
2235 /* If not a paren, see if we're OK. */
2236 if (paren->type != CPP_OPEN_PAREN)
2238 /* In a conditional no answer is a test for any answer. It
2239 could be followed by any token. */
2240 if (type == T_IF)
2242 _cpp_backup_tokens (pfile, 1);
2243 return true;
2246 /* #unassert with no answer is valid - it removes all answers. */
2247 if (type == T_UNASSERT && paren->type == CPP_EOF)
2248 return true;
2250 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2251 "missing '(' after predicate");
2252 return false;
2255 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2256 _cpp_reserve_room (pfile, 0,
2257 sizeof (cpp_macro)));
2258 answer->parm.next = NULL;
2259 unsigned count = 0;
2260 for (;;)
2262 const cpp_token *token = cpp_get_token (pfile);
2264 if (token->type == CPP_CLOSE_PAREN)
2265 break;
2267 if (token->type == CPP_EOF)
2269 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2270 return false;
2273 answer = (cpp_macro *)_cpp_reserve_room
2274 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2275 sizeof (cpp_token));
2276 answer->exp.tokens[count++] = *token;
2279 if (!count)
2281 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2282 return false;
2285 /* Drop whitespace at start, for answer equivalence purposes. */
2286 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2288 answer->count = count;
2289 *answer_ptr = answer;
2291 return true;
2294 /* Parses an assertion directive of type TYPE, returning a pointer to
2295 the hash node of the predicate, or 0 on error. The node is
2296 guaranteed to be disjoint from the macro namespace, so can only
2297 have type 'NT_VOID'. If an answer was supplied, it is placed in
2298 *ANSWER_PTR, which is otherwise set to 0. */
2299 static cpp_hashnode *
2300 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2302 cpp_hashnode *result = 0;
2304 /* We don't expand predicates or answers. */
2305 pfile->state.prevent_expansion++;
2307 *answer_ptr = NULL;
2309 const cpp_token *predicate = cpp_get_token (pfile);
2310 if (predicate->type == CPP_EOF)
2311 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2312 else if (predicate->type != CPP_NAME)
2313 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2314 "predicate must be an identifier");
2315 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2317 unsigned int len = NODE_LEN (predicate->val.node.node);
2318 unsigned char *sym = (unsigned char *) alloca (len + 1);
2320 /* Prefix '#' to get it out of macro namespace. */
2321 sym[0] = '#';
2322 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2323 result = cpp_lookup (pfile, sym, len + 1);
2326 pfile->state.prevent_expansion--;
2328 return result;
2331 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2332 or a pointer to NULL if the answer is not in the chain. */
2333 static cpp_macro **
2334 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2336 unsigned int i;
2337 cpp_macro **result = NULL;
2339 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2341 cpp_macro *answer = *result;
2343 if (answer->count == candidate->count)
2345 for (i = 0; i < answer->count; i++)
2346 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2347 &candidate->exp.tokens[i]))
2348 break;
2350 if (i == answer->count)
2351 break;
2355 return result;
2358 /* Test an assertion within a preprocessor conditional. Returns
2359 nonzero on failure, zero on success. On success, the result of
2360 the test is written into VALUE, otherwise the value 0. */
2362 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2364 cpp_macro *answer;
2365 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2367 /* For recovery, an erroneous assertion expression is handled as a
2368 failing assertion. */
2369 *value = 0;
2371 if (node)
2373 if (node->value.answers)
2374 *value = !answer || *find_answer (node, answer);
2376 else if (pfile->cur_token[-1].type == CPP_EOF)
2377 _cpp_backup_tokens (pfile, 1);
2379 /* We don't commit the memory for the answer - it's temporary only. */
2380 return node == 0;
2383 /* Handle #assert. */
2384 static void
2385 do_assert (cpp_reader *pfile)
2387 cpp_macro *answer;
2388 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2390 if (node)
2392 /* Place the new answer in the answer list. First check there
2393 is not a duplicate. */
2394 if (*find_answer (node, answer))
2396 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2397 NODE_NAME (node) + 1);
2398 return;
2401 /* Commit or allocate storage for the answer. */
2402 answer = (cpp_macro *)_cpp_commit_buff
2403 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2404 + sizeof (cpp_token) * answer->count);
2406 /* Chain into the list. */
2407 answer->parm.next = node->value.answers;
2408 node->value.answers = answer;
2410 check_eol (pfile, false);
2414 /* Handle #unassert. */
2415 static void
2416 do_unassert (cpp_reader *pfile)
2418 cpp_macro *answer;
2419 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2421 /* It isn't an error to #unassert something that isn't asserted. */
2422 if (node)
2424 if (answer)
2426 cpp_macro **p = find_answer (node, answer);
2428 /* Remove the assert from the list. */
2429 if (cpp_macro *temp = *p)
2430 *p = temp->parm.next;
2432 check_eol (pfile, false);
2434 else
2435 _cpp_free_definition (node);
2438 /* We don't commit the memory for the answer - it's temporary only. */
2441 /* These are for -D, -U, -A. */
2443 /* Process the string STR as if it appeared as the body of a #define.
2444 If STR is just an identifier, define it with value 1.
2445 If STR has anything after the identifier, then it should
2446 be identifier=definition. */
2447 void
2448 cpp_define (cpp_reader *pfile, const char *str)
2450 char *buf;
2451 const char *p;
2452 size_t count;
2454 /* Copy the entire option so we can modify it.
2455 Change the first "=" in the string to a space. If there is none,
2456 tack " 1" on the end. */
2458 count = strlen (str);
2459 buf = (char *) alloca (count + 3);
2460 memcpy (buf, str, count);
2462 p = strchr (str, '=');
2463 if (p)
2464 buf[p - str] = ' ';
2465 else
2467 buf[count++] = ' ';
2468 buf[count++] = '1';
2470 buf[count] = '\n';
2472 run_directive (pfile, T_DEFINE, buf, count);
2475 /* Like cpp_define, but does not warn about unused macro. */
2476 void
2477 cpp_define_unused (cpp_reader *pfile, const char *str)
2479 unsigned char warn_unused_macros = CPP_OPTION (pfile, warn_unused_macros);
2480 CPP_OPTION (pfile, warn_unused_macros) = 0;
2481 cpp_define (pfile, str);
2482 CPP_OPTION (pfile, warn_unused_macros) = warn_unused_macros;
2485 /* Use to build macros to be run through cpp_define() as
2486 described above.
2487 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2489 void
2490 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2492 char *ptr;
2494 va_list ap;
2495 va_start (ap, fmt);
2496 ptr = xvasprintf (fmt, ap);
2497 va_end (ap);
2499 cpp_define (pfile, ptr);
2500 free (ptr);
2503 /* Like cpp_define_formatted, but does not warn about unused macro. */
2504 void
2505 cpp_define_formatted_unused (cpp_reader *pfile, const char *fmt, ...)
2507 char *ptr;
2509 va_list ap;
2510 va_start (ap, fmt);
2511 ptr = xvasprintf (fmt, ap);
2512 va_end (ap);
2514 cpp_define_unused (pfile, ptr);
2515 free (ptr);
2518 /* Slight variant of the above for use by initialize_builtins. */
2519 void
2520 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2522 size_t len = strlen (str);
2523 char *buf = (char *) alloca (len + 1);
2524 memcpy (buf, str, len);
2525 buf[len] = '\n';
2526 run_directive (pfile, T_DEFINE, buf, len);
2529 /* Process MACRO as if it appeared as the body of an #undef. */
2530 void
2531 cpp_undef (cpp_reader *pfile, const char *macro)
2533 size_t len = strlen (macro);
2534 char *buf = (char *) alloca (len + 1);
2535 memcpy (buf, macro, len);
2536 buf[len] = '\n';
2537 run_directive (pfile, T_UNDEF, buf, len);
2540 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2541 or first element is zero, then the macro should be undefined. */
2542 static void
2543 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2545 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2546 if (node == NULL)
2547 return;
2549 if (pfile->cb.before_define)
2550 pfile->cb.before_define (pfile);
2552 if (cpp_macro_p (node))
2554 if (pfile->cb.undef)
2555 pfile->cb.undef (pfile, pfile->directive_line, node);
2556 if (CPP_OPTION (pfile, warn_unused_macros))
2557 _cpp_warn_if_unused_macro (pfile, node, NULL);
2558 _cpp_free_definition (node);
2561 if (c->is_undef)
2562 return;
2563 if (c->is_builtin)
2565 _cpp_restore_special_builtin (pfile, c);
2566 return;
2570 size_t namelen;
2571 const uchar *dn;
2572 cpp_hashnode *h = NULL;
2573 cpp_buffer *nbuf;
2575 namelen = ustrcspn (c->definition, "( \n");
2576 h = cpp_lookup (pfile, c->definition, namelen);
2577 dn = c->definition + namelen;
2579 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2580 if (nbuf != NULL)
2582 _cpp_clean_line (pfile);
2583 nbuf->sysp = 1;
2584 if (!_cpp_create_definition (pfile, h))
2585 abort ();
2586 _cpp_pop_buffer (pfile);
2588 else
2589 abort ();
2590 h->value.macro->line = c->line;
2591 h->value.macro->syshdr = c->syshdr;
2592 h->value.macro->used = c->used;
2596 /* Process the string STR as if it appeared as the body of a #assert. */
2597 void
2598 cpp_assert (cpp_reader *pfile, const char *str)
2600 handle_assertion (pfile, str, T_ASSERT);
2603 /* Process STR as if it appeared as the body of an #unassert. */
2604 void
2605 cpp_unassert (cpp_reader *pfile, const char *str)
2607 handle_assertion (pfile, str, T_UNASSERT);
2610 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2611 static void
2612 handle_assertion (cpp_reader *pfile, const char *str, int type)
2614 size_t count = strlen (str);
2615 const char *p = strchr (str, '=');
2617 /* Copy the entire option so we can modify it. Change the first
2618 "=" in the string to a '(', and tack a ')' on the end. */
2619 char *buf = (char *) alloca (count + 2);
2621 memcpy (buf, str, count);
2622 if (p)
2624 buf[p - str] = '(';
2625 buf[count++] = ')';
2627 buf[count] = '\n';
2628 str = buf;
2630 run_directive (pfile, type, str, count);
2633 /* The options structure. */
2634 cpp_options *
2635 cpp_get_options (cpp_reader *pfile)
2637 return &pfile->opts;
2640 /* The callbacks structure. */
2641 cpp_callbacks *
2642 cpp_get_callbacks (cpp_reader *pfile)
2644 return &pfile->cb;
2647 /* Copy the given callbacks structure to our own. */
2648 void
2649 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2651 pfile->cb = *cb;
2654 /* The narrow character set identifier. */
2655 const char *
2656 cpp_get_narrow_charset_name (cpp_reader *pfile)
2658 return pfile->narrow_cset_desc.to;
2661 /* The wide character set identifier. */
2662 const char *
2663 cpp_get_wide_charset_name (cpp_reader *pfile)
2665 return pfile->wide_cset_desc.to;
2668 /* The dependencies structure. (Creates one if it hasn't already been.) */
2669 class mkdeps *
2670 cpp_get_deps (cpp_reader *pfile)
2672 if (!pfile->deps && CPP_OPTION (pfile, deps.style) != DEPS_NONE)
2673 pfile->deps = deps_init ();
2674 return pfile->deps;
2677 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2678 doesn't fail. It does not generate a file change call back; that
2679 is the responsibility of the caller. */
2680 cpp_buffer *
2681 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2682 int from_stage3)
2684 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2686 /* Clears, amongst other things, if_stack and mi_cmacro. */
2687 memset (new_buffer, 0, sizeof (cpp_buffer));
2689 new_buffer->next_line = new_buffer->buf = buffer;
2690 new_buffer->rlimit = buffer + len;
2691 new_buffer->from_stage3 = from_stage3;
2692 new_buffer->prev = pfile->buffer;
2693 new_buffer->need_line = true;
2695 pfile->buffer = new_buffer;
2697 return new_buffer;
2700 /* Pops a single buffer, with a file change call-back if appropriate.
2701 Then pushes the next -include file, if any remain. */
2702 void
2703 _cpp_pop_buffer (cpp_reader *pfile)
2705 cpp_buffer *buffer = pfile->buffer;
2706 struct _cpp_file *inc = buffer->file;
2707 struct if_stack *ifs;
2708 const unsigned char *to_free;
2710 /* Walk back up the conditional stack till we reach its level at
2711 entry to this file, issuing error messages. */
2712 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2713 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2714 "unterminated #%s", dtable[ifs->type].name);
2716 /* In case of a missing #endif. */
2717 pfile->state.skipping = 0;
2719 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2720 pfile->buffer = buffer->prev;
2722 to_free = buffer->to_free;
2723 free (buffer->notes);
2725 /* Free the buffer object now; we may want to push a new buffer
2726 in _cpp_push_next_include_file. */
2727 obstack_free (&pfile->buffer_ob, buffer);
2729 if (inc)
2731 _cpp_pop_file_buffer (pfile, inc, to_free);
2733 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2735 else if (to_free)
2736 free ((void *)to_free);
2739 /* Enter all recognized directives in the hash table. */
2740 void
2741 _cpp_init_directives (cpp_reader *pfile)
2743 for (int i = 0; i < N_DIRECTIVES; i++)
2745 cpp_hashnode *node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2746 node->is_directive = 1;
2747 node->directive_index = i;
2751 /* Extract header file from a bracket include. Parsing starts after '<'.
2752 The string is malloced and must be freed by the caller. */
2753 char *
2754 _cpp_bracket_include(cpp_reader *pfile)
2756 return glue_header_name (pfile);