gcc:
[official-gcc.git] / libcpp / directives.c
blobf7c460d2f83ba30e44df6f0fd1ae7a5b8b68c950
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2018 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 source_location 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. EXTENSION directives are extensions. */
60 #define KANDR 0
61 #define STDC89 1
62 #define EXTENSION 2
64 /* Values for the flags field of struct directive. COND indicates a
65 conditional; IF_COND an opening conditional. INCL means to treat
66 "..." and <...> as q-char and h-char sequences respectively. IN_I
67 means this directive should be handled even if -fpreprocessed is in
68 effect (these are the directives with callback hooks).
70 EXPAND is set on directives that are always macro-expanded. */
71 #define COND (1 << 0)
72 #define IF_COND (1 << 1)
73 #define INCL (1 << 2)
74 #define IN_I (1 << 3)
75 #define EXPAND (1 << 4)
76 #define DEPRECATED (1 << 5)
78 /* Defines one #-directive, including how to handle it. */
79 typedef void (*directive_handler) (cpp_reader *);
80 typedef struct directive directive;
81 struct directive
83 directive_handler handler; /* Function to handle directive. */
84 const uchar *name; /* Name of directive. */
85 unsigned short length; /* Length of name. */
86 unsigned char origin; /* Origin of directive. */
87 unsigned char flags; /* Flags describing this directive. */
90 /* Forward declarations. */
92 static void skip_rest_of_line (cpp_reader *);
93 static void check_eol (cpp_reader *, bool);
94 static void start_directive (cpp_reader *);
95 static void prepare_directive_trad (cpp_reader *);
96 static void end_directive (cpp_reader *, int);
97 static void directive_diagnostics (cpp_reader *, const directive *, int);
98 static void run_directive (cpp_reader *, int, const char *, size_t);
99 static char *glue_header_name (cpp_reader *);
100 static const char *parse_include (cpp_reader *, int *, const cpp_token ***,
101 source_location *);
102 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
103 static unsigned int read_flag (cpp_reader *, unsigned int);
104 static bool strtolinenum (const uchar *, size_t, linenum_type *, bool *);
105 static void do_diagnostic (cpp_reader *, int, int, int);
106 static cpp_hashnode *lex_macro_node (cpp_reader *, bool);
107 static int undefine_macros (cpp_reader *, cpp_hashnode *, void *);
108 static void do_include_common (cpp_reader *, enum include_type);
109 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
110 const cpp_hashnode *);
111 static int count_registered_pragmas (struct pragma_entry *);
112 static char ** save_registered_pragmas (struct pragma_entry *, char **);
113 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
114 char **);
115 static void do_pragma_once (cpp_reader *);
116 static void do_pragma_poison (cpp_reader *);
117 static void do_pragma_system_header (cpp_reader *);
118 static void do_pragma_dependency (cpp_reader *);
119 static void do_pragma_warning_or_error (cpp_reader *, bool error);
120 static void do_pragma_warning (cpp_reader *);
121 static void do_pragma_error (cpp_reader *);
122 static void do_linemarker (cpp_reader *);
123 static const cpp_token *get_token_no_padding (cpp_reader *);
124 static const cpp_token *get__Pragma_string (cpp_reader *);
125 static void destringize_and_run (cpp_reader *, const cpp_string *,
126 source_location);
127 static bool parse_answer (cpp_reader *, int, source_location, cpp_macro **);
128 static cpp_hashnode *parse_assertion (cpp_reader *, int, cpp_macro **);
129 static cpp_macro **find_answer (cpp_hashnode *, const cpp_macro *);
130 static void handle_assertion (cpp_reader *, const char *, int);
131 static void do_pragma_push_macro (cpp_reader *);
132 static void do_pragma_pop_macro (cpp_reader *);
133 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
135 /* This is the table of directive handlers. It is ordered by
136 frequency of occurrence; the numbers at the end are directive
137 counts from all the source code I have lying around (egcs and libc
138 CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
139 pcmcia-cs-3.0.9). This is no longer important as directive lookup
140 is now O(1). All extensions other than #warning, #include_next,
141 and #import are deprecated. The name is where the extension
142 appears to have come from. */
144 #define DIRECTIVE_TABLE \
145 D(define, T_DEFINE = 0, KANDR, IN_I) /* 270554 */ \
146 D(include, T_INCLUDE, KANDR, INCL | EXPAND) /* 52262 */ \
147 D(endif, T_ENDIF, KANDR, COND) /* 45855 */ \
148 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) /* 22000 */ \
149 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) /* 18162 */ \
150 D(else, T_ELSE, KANDR, COND) /* 9863 */ \
151 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) /* 9675 */ \
152 D(undef, T_UNDEF, KANDR, IN_I) /* 4837 */ \
153 D(line, T_LINE, KANDR, EXPAND) /* 2465 */ \
154 D(elif, T_ELIF, STDC89, COND | EXPAND) /* 610 */ \
155 D(error, T_ERROR, STDC89, 0) /* 475 */ \
156 D(pragma, T_PRAGMA, STDC89, IN_I) /* 195 */ \
157 D(warning, T_WARNING, EXTENSION, 0) /* 22 */ \
158 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) /* 19 */ \
159 D(ident, T_IDENT, EXTENSION, IN_I) /* 11 */ \
160 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* 0 ObjC */ \
161 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
162 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
163 D(sccs, T_SCCS, EXTENSION, IN_I) /* 0 SVR4? */
165 /* #sccs is synonymous with #ident. */
166 #define do_sccs do_ident
168 /* Use the table to generate a series of prototypes, an enum for the
169 directive names, and an array of directive handlers. */
171 #define D(name, t, o, f) static void do_##name (cpp_reader *);
172 DIRECTIVE_TABLE
173 #undef D
175 #define D(n, tag, o, f) tag,
176 enum
178 DIRECTIVE_TABLE
179 N_DIRECTIVES
181 #undef D
183 #define D(name, t, origin, flags) \
184 { do_##name, (const uchar *) #name, \
185 sizeof #name - 1, origin, flags },
186 static const directive dtable[] =
188 DIRECTIVE_TABLE
190 #undef D
192 /* A NULL-terminated array of directive names for use
193 when suggesting corrections for misspelled directives. */
194 #define D(name, t, origin, flags) #name,
195 static const char * const directive_names[] = {
196 DIRECTIVE_TABLE
197 NULL
199 #undef D
201 #undef DIRECTIVE_TABLE
203 /* Wrapper struct directive for linemarkers.
204 The origin is more or less true - the original K+R cpp
205 did use this notation in its preprocessed output. */
206 static const directive linemarker_dir =
208 do_linemarker, UC"#", 1, KANDR, IN_I
211 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
213 /* Skip any remaining tokens in a directive. */
214 static void
215 skip_rest_of_line (cpp_reader *pfile)
217 /* Discard all stacked contexts. */
218 while (pfile->context->prev)
219 _cpp_pop_context (pfile);
221 /* Sweep up all tokens remaining on the line. */
222 if (! SEEN_EOL ())
223 while (_cpp_lex_token (pfile)->type != CPP_EOF)
227 /* Helper function for check_oel. */
229 static void
230 check_eol_1 (cpp_reader *pfile, bool expand, int reason)
232 if (! SEEN_EOL () && (expand
233 ? cpp_get_token (pfile)
234 : _cpp_lex_token (pfile))->type != CPP_EOF)
235 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
236 pfile->directive->name);
239 /* Variant of check_eol used for Wendif-labels warnings. */
241 static void
242 check_eol_endif_labels (cpp_reader *pfile)
244 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
247 /* Ensure there are no stray tokens at the end of a directive. If
248 EXPAND is true, tokens macro-expanding to nothing are allowed. */
250 static void
251 check_eol (cpp_reader *pfile, bool expand)
253 check_eol_1 (pfile, expand, CPP_W_NONE);
256 /* Ensure there are no stray tokens other than comments at the end of
257 a directive, and gather the comments. */
258 static const cpp_token **
259 check_eol_return_comments (cpp_reader *pfile)
261 size_t c;
262 size_t capacity = 8;
263 const cpp_token **buf;
265 buf = XNEWVEC (const cpp_token *, capacity);
266 c = 0;
267 if (! SEEN_EOL ())
269 while (1)
271 const cpp_token *tok;
273 tok = _cpp_lex_token (pfile);
274 if (tok->type == CPP_EOF)
275 break;
276 if (tok->type != CPP_COMMENT)
277 cpp_error (pfile, CPP_DL_PEDWARN,
278 "extra tokens at end of #%s directive",
279 pfile->directive->name);
280 else
282 if (c + 1 >= capacity)
284 capacity *= 2;
285 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
287 buf[c] = tok;
288 ++c;
292 buf[c] = NULL;
293 return buf;
296 /* Called when entering a directive, _Pragma or command-line directive. */
297 static void
298 start_directive (cpp_reader *pfile)
300 /* Setup in-directive state. */
301 pfile->state.in_directive = 1;
302 pfile->state.save_comments = 0;
303 pfile->directive_result.type = CPP_PADDING;
305 /* Some handlers need the position of the # for diagnostics. */
306 pfile->directive_line = pfile->line_table->highest_line;
309 /* Called when leaving a directive, _Pragma or command-line directive. */
310 static void
311 end_directive (cpp_reader *pfile, int skip_line)
313 if (CPP_OPTION (pfile, traditional))
315 /* Revert change of prepare_directive_trad. */
316 if (!pfile->state.in_deferred_pragma)
317 pfile->state.prevent_expansion--;
319 if (pfile->directive != &dtable[T_DEFINE])
320 _cpp_remove_overlay (pfile);
322 else if (pfile->state.in_deferred_pragma)
324 /* We don't skip for an assembler #. */
325 else if (skip_line)
327 skip_rest_of_line (pfile);
328 if (!pfile->keep_tokens)
330 pfile->cur_run = &pfile->base_run;
331 pfile->cur_token = pfile->base_run.base;
335 /* Restore state. */
336 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
337 pfile->state.in_directive = 0;
338 pfile->state.in_expression = 0;
339 pfile->state.angled_headers = 0;
340 pfile->directive = 0;
343 /* Prepare to handle the directive in pfile->directive. */
344 static void
345 prepare_directive_trad (cpp_reader *pfile)
347 if (pfile->directive != &dtable[T_DEFINE])
349 bool no_expand = (pfile->directive
350 && ! (pfile->directive->flags & EXPAND));
351 bool was_skipping = pfile->state.skipping;
353 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
354 || pfile->directive == &dtable[T_ELIF]);
355 if (pfile->state.in_expression)
356 pfile->state.skipping = false;
358 if (no_expand)
359 pfile->state.prevent_expansion++;
360 _cpp_scan_out_logical_line (pfile, NULL, false);
361 if (no_expand)
362 pfile->state.prevent_expansion--;
364 pfile->state.skipping = was_skipping;
365 _cpp_overlay_buffer (pfile, pfile->out.base,
366 pfile->out.cur - pfile->out.base);
369 /* Stop ISO C from expanding anything. */
370 pfile->state.prevent_expansion++;
373 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
374 the '#' was indented. */
375 static void
376 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
378 /* Issue -pedantic or deprecated warnings for extensions. We let
379 -pedantic take precedence if both are applicable. */
380 if (! pfile->state.skipping)
382 if (dir->origin == EXTENSION
383 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
384 && CPP_PEDANTIC (pfile))
385 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
386 else if (((dir->flags & DEPRECATED) != 0
387 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
388 && CPP_OPTION (pfile, cpp_warn_deprecated))
389 cpp_warning (pfile, CPP_W_DEPRECATED,
390 "#%s is a deprecated GCC extension", dir->name);
393 /* Traditionally, a directive is ignored unless its # is in
394 column 1. Therefore in code intended to work with K+R
395 compilers, directives added by C89 must have their #
396 indented, and directives present in traditional C must not.
397 This is true even of directives in skipped conditional
398 blocks. #elif cannot be used at all. */
399 if (CPP_WTRADITIONAL (pfile))
401 if (dir == &dtable[T_ELIF])
402 cpp_warning (pfile, CPP_W_TRADITIONAL,
403 "suggest not using #elif in traditional C");
404 else if (indented && dir->origin == KANDR)
405 cpp_warning (pfile, CPP_W_TRADITIONAL,
406 "traditional C ignores #%s with the # indented",
407 dir->name);
408 else if (!indented && dir->origin != KANDR)
409 cpp_warning (pfile, CPP_W_TRADITIONAL,
410 "suggest hiding #%s from traditional C with an indented #",
411 dir->name);
415 /* Check if we have a known directive. INDENTED is nonzero if the
416 '#' of the directive was indented. This function is in this file
417 to save unnecessarily exporting dtable etc. to lex.c. Returns
418 nonzero if the line of tokens has been handled, zero if we should
419 continue processing the line. */
421 _cpp_handle_directive (cpp_reader *pfile, int indented)
423 const directive *dir = 0;
424 const cpp_token *dname;
425 bool was_parsing_args = pfile->state.parsing_args;
426 bool was_discarding_output = pfile->state.discarding_output;
427 int skip = 1;
429 if (was_discarding_output)
430 pfile->state.prevent_expansion = 0;
432 if (was_parsing_args)
434 if (CPP_OPTION (pfile, cpp_pedantic))
435 cpp_error (pfile, CPP_DL_PEDWARN,
436 "embedding a directive within macro arguments is not portable");
437 pfile->state.parsing_args = 0;
438 pfile->state.prevent_expansion = 0;
440 start_directive (pfile);
441 dname = _cpp_lex_token (pfile);
443 if (dname->type == CPP_NAME)
445 if (dname->val.node.node->is_directive)
446 dir = &dtable[dname->val.node.node->directive_index];
448 /* We do not recognize the # followed by a number extension in
449 assembler code. */
450 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
452 dir = &linemarker_dir;
453 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
454 && ! pfile->state.skipping)
455 cpp_error (pfile, CPP_DL_PEDWARN,
456 "style of line directive is a GCC extension");
459 if (dir)
461 /* If we have a directive that is not an opening conditional,
462 invalidate any control macro. */
463 if (! (dir->flags & IF_COND))
464 pfile->mi_valid = false;
466 /* Kluge alert. In order to be sure that code like this
468 #define HASH #
469 HASH define foo bar
471 does not cause '#define foo bar' to get executed when
472 compiled with -save-temps, we recognize directives in
473 -fpreprocessed mode only if the # is in column 1. macro.c
474 puts a space in front of any '#' at the start of a macro.
476 We exclude the -fdirectives-only case because macro expansion
477 has not been performed yet, and block comments can cause spaces
478 to precede the directive. */
479 if (CPP_OPTION (pfile, preprocessed)
480 && !CPP_OPTION (pfile, directives_only)
481 && (indented || !(dir->flags & IN_I)))
483 skip = 0;
484 dir = 0;
486 else
488 /* In failed conditional groups, all non-conditional
489 directives are ignored. Before doing that, whether
490 skipping or not, we should lex angle-bracketed headers
491 correctly, and maybe output some diagnostics. */
492 pfile->state.angled_headers = dir->flags & INCL;
493 pfile->state.directive_wants_padding = dir->flags & INCL;
494 if (! CPP_OPTION (pfile, preprocessed))
495 directive_diagnostics (pfile, dir, indented);
496 if (pfile->state.skipping && !(dir->flags & COND))
497 dir = 0;
500 else if (dname->type == CPP_EOF)
501 ; /* CPP_EOF is the "null directive". */
502 else
504 /* An unknown directive. Don't complain about it in assembly
505 source: we don't know where the comments are, and # may
506 introduce assembler pseudo-ops. Don't complain about invalid
507 directives in skipped conditional groups (6.10 p4). */
508 if (CPP_OPTION (pfile, lang) == CLK_ASM)
509 skip = 0;
510 else if (!pfile->state.skipping)
512 const char *unrecognized
513 = (const char *)cpp_token_as_text (pfile, dname);
514 const char *hint = NULL;
516 /* Call back into gcc to get a spelling suggestion. Ideally
517 we'd just use best_match from gcc/spellcheck.h (and filter
518 out the uncommon directives), but that requires moving it
519 to a support library. */
520 if (pfile->cb.get_suggestion)
521 hint = pfile->cb.get_suggestion (pfile, unrecognized,
522 directive_names);
524 if (hint)
526 rich_location richloc (pfile->line_table, dname->src_loc);
527 source_range misspelled_token_range
528 = get_range_from_loc (pfile->line_table, dname->src_loc);
529 richloc.add_fixit_replace (misspelled_token_range, hint);
530 cpp_error_at (pfile, CPP_DL_ERROR, &richloc,
531 "invalid preprocessing directive #%s;"
532 " did you mean #%s?",
533 unrecognized, hint);
535 else
536 cpp_error (pfile, CPP_DL_ERROR,
537 "invalid preprocessing directive #%s",
538 unrecognized);
542 pfile->directive = dir;
543 if (CPP_OPTION (pfile, traditional))
544 prepare_directive_trad (pfile);
546 if (dir)
547 pfile->directive->handler (pfile);
548 else if (skip == 0)
549 _cpp_backup_tokens (pfile, 1);
551 end_directive (pfile, skip);
552 if (was_parsing_args && !pfile->state.in_deferred_pragma)
554 /* Restore state when within macro args. */
555 pfile->state.parsing_args = 2;
556 pfile->state.prevent_expansion = 1;
558 if (was_discarding_output)
559 pfile->state.prevent_expansion = 1;
560 return skip;
563 /* Directive handler wrapper used by the command line option
564 processor. BUF is \n terminated. */
565 static void
566 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
568 cpp_push_buffer (pfile, (const uchar *) buf, count,
569 /* from_stage3 */ true);
570 start_directive (pfile);
572 /* This is a short-term fix to prevent a leading '#' being
573 interpreted as a directive. */
574 _cpp_clean_line (pfile);
576 pfile->directive = &dtable[dir_no];
577 if (CPP_OPTION (pfile, traditional))
578 prepare_directive_trad (pfile);
579 pfile->directive->handler (pfile);
580 end_directive (pfile, 1);
581 _cpp_pop_buffer (pfile);
584 /* Checks for validity the macro name in #define, #undef, #ifdef and
585 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
586 processing a #define or #undefine directive, and false
587 otherwise. */
588 static cpp_hashnode *
589 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
591 const cpp_token *token = _cpp_lex_token (pfile);
593 /* The token immediately after #define must be an identifier. That
594 identifier may not be "defined", per C99 6.10.8p4.
595 In C++, it may not be any of the "named operators" either,
596 per C++98 [lex.digraph], [lex.key].
597 Finally, the identifier may not have been poisoned. (In that case
598 the lexer has issued the error message for us.) */
600 if (token->type == CPP_NAME)
602 cpp_hashnode *node = token->val.node.node;
604 if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
605 cpp_error (pfile, CPP_DL_ERROR,
606 "\"defined\" cannot be used as a macro name");
607 else if (is_def_or_undef
608 && (node == pfile->spec_nodes.n__has_include__
609 || node == pfile->spec_nodes.n__has_include_next__))
610 cpp_error (pfile, CPP_DL_ERROR,
611 "\"__has_include__\" cannot be used as a macro name");
612 else if (! (node->flags & NODE_POISONED))
613 return node;
615 else if (token->flags & NAMED_OP)
616 cpp_error (pfile, CPP_DL_ERROR,
617 "\"%s\" cannot be used as a macro name as it is an operator in C++",
618 NODE_NAME (token->val.node.node));
619 else if (token->type == CPP_EOF)
620 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
621 pfile->directive->name);
622 else
623 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
625 return NULL;
628 /* Process a #define directive. Most work is done in macro.c. */
629 static void
630 do_define (cpp_reader *pfile)
632 cpp_hashnode *node = lex_macro_node (pfile, true);
634 if (node)
636 /* If we have been requested to expand comments into macros,
637 then re-enable saving of comments. */
638 pfile->state.save_comments =
639 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
641 if (pfile->cb.before_define)
642 pfile->cb.before_define (pfile);
644 if (_cpp_create_definition (pfile, node))
645 if (pfile->cb.define)
646 pfile->cb.define (pfile, pfile->directive_line, node);
648 node->flags &= ~NODE_USED;
652 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
653 static void
654 do_undef (cpp_reader *pfile)
656 cpp_hashnode *node = lex_macro_node (pfile, true);
658 if (node)
660 if (pfile->cb.before_define)
661 pfile->cb.before_define (pfile);
663 if (pfile->cb.undef)
664 pfile->cb.undef (pfile, pfile->directive_line, node);
666 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
667 identifier is not currently defined as a macro name. */
668 if (cpp_macro_p (node))
670 if (node->flags & NODE_WARN)
671 cpp_error (pfile, CPP_DL_WARNING,
672 "undefining \"%s\"", NODE_NAME (node));
673 else if (cpp_builtin_macro_p (node)
674 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
675 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
676 pfile->directive_line, 0,
677 "undefining \"%s\"", NODE_NAME (node));
679 if (CPP_OPTION (pfile, warn_unused_macros))
680 _cpp_warn_if_unused_macro (pfile, node, NULL);
682 _cpp_free_definition (node);
686 check_eol (pfile, false);
689 /* Undefine a single macro/assertion/whatever. */
691 static int
692 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
693 void *data_p ATTRIBUTE_UNUSED)
695 /* Body of _cpp_free_definition inlined here for speed.
696 Macros and assertions no longer have anything to free. */
697 h->type = NT_VOID;
698 h->value.answers = NULL;
699 h->flags &= ~(NODE_POISONED|NODE_DISABLED|NODE_USED);
700 return 1;
703 /* Undefine all macros and assertions. */
705 void
706 cpp_undef_all (cpp_reader *pfile)
708 cpp_forall_identifiers (pfile, undefine_macros, NULL);
712 /* Helper routine used by parse_include. Reinterpret the current line
713 as an h-char-sequence (< ... >); we are looking at the first token
714 after the <. Returns a malloced filename. */
715 static char *
716 glue_header_name (cpp_reader *pfile)
718 const cpp_token *token;
719 char *buffer;
720 size_t len, total_len = 0, capacity = 1024;
722 /* To avoid lexed tokens overwriting our glued name, we can only
723 allocate from the string pool once we've lexed everything. */
724 buffer = XNEWVEC (char, capacity);
725 for (;;)
727 token = get_token_no_padding (pfile);
729 if (token->type == CPP_GREATER)
730 break;
731 if (token->type == CPP_EOF)
733 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
734 break;
737 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
738 if (total_len + len > capacity)
740 capacity = (capacity + len) * 2;
741 buffer = XRESIZEVEC (char, buffer, capacity);
744 if (token->flags & PREV_WHITE)
745 buffer[total_len++] = ' ';
747 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
748 true)
749 - (uchar *) buffer);
752 buffer[total_len] = '\0';
753 return buffer;
756 /* Returns the file name of #include, #include_next, #import and
757 #pragma dependency. The string is malloced and the caller should
758 free it. Returns NULL on error. LOCATION is the source location
759 of the file name. */
761 static const char *
762 parse_include (cpp_reader *pfile, int *pangle_brackets,
763 const cpp_token ***buf, source_location *location)
765 char *fname;
766 const cpp_token *header;
768 /* Allow macro expansion. */
769 header = get_token_no_padding (pfile);
770 *location = header->src_loc;
771 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
772 || header->type == CPP_HEADER_NAME)
774 fname = XNEWVEC (char, header->val.str.len - 1);
775 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
776 fname[header->val.str.len - 2] = '\0';
777 *pangle_brackets = header->type == CPP_HEADER_NAME;
779 else if (header->type == CPP_LESS)
781 fname = glue_header_name (pfile);
782 *pangle_brackets = 1;
784 else
786 const unsigned char *dir;
788 if (pfile->directive == &dtable[T_PRAGMA])
789 dir = UC"pragma dependency";
790 else
791 dir = pfile->directive->name;
792 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
793 dir);
795 return NULL;
798 if (pfile->directive == &dtable[T_PRAGMA])
800 /* This pragma allows extra tokens after the file name. */
802 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
803 check_eol (pfile, true);
804 else
806 /* If we are not discarding comments, then gather them while
807 doing the eol check. */
808 *buf = check_eol_return_comments (pfile);
811 return fname;
814 /* Handle #include, #include_next and #import. */
815 static void
816 do_include_common (cpp_reader *pfile, enum include_type type)
818 const char *fname;
819 int angle_brackets;
820 const cpp_token **buf = NULL;
821 source_location location;
823 /* Re-enable saving of comments if requested, so that the include
824 callback can dump comments which follow #include. */
825 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
827 fname = parse_include (pfile, &angle_brackets, &buf, &location);
828 if (!fname)
830 if (buf)
831 XDELETEVEC (buf);
832 return;
835 if (!*fname)
837 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
838 "empty filename in #%s",
839 pfile->directive->name);
840 XDELETEVEC (fname);
841 if (buf)
842 XDELETEVEC (buf);
843 return;
846 /* Prevent #include recursion. */
847 if (pfile->line_table->depth >= CPP_STACK_MAX)
848 cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
849 else
851 /* Get out of macro context, if we are. */
852 skip_rest_of_line (pfile);
854 if (pfile->cb.include)
855 pfile->cb.include (pfile, pfile->directive_line,
856 pfile->directive->name, fname, angle_brackets,
857 buf);
859 _cpp_stack_include (pfile, fname, angle_brackets, type, location);
862 XDELETEVEC (fname);
863 if (buf)
864 XDELETEVEC (buf);
867 static void
868 do_include (cpp_reader *pfile)
870 do_include_common (pfile, IT_INCLUDE);
873 static void
874 do_import (cpp_reader *pfile)
876 do_include_common (pfile, IT_IMPORT);
879 static void
880 do_include_next (cpp_reader *pfile)
882 enum include_type type = IT_INCLUDE_NEXT;
884 /* If this is the primary source file, warn and use the normal
885 search logic. */
886 if (cpp_in_primary_file (pfile))
888 cpp_error (pfile, CPP_DL_WARNING,
889 "#include_next in primary source file");
890 type = IT_INCLUDE;
892 do_include_common (pfile, type);
895 /* Subroutine of do_linemarker. Read possible flags after file name.
896 LAST is the last flag seen; 0 if this is the first flag. Return the
897 flag if it is valid, 0 at the end of the directive. Otherwise
898 complain. */
899 static unsigned int
900 read_flag (cpp_reader *pfile, unsigned int last)
902 const cpp_token *token = _cpp_lex_token (pfile);
904 if (token->type == CPP_NUMBER && token->val.str.len == 1)
906 unsigned int flag = token->val.str.text[0] - '0';
908 if (flag > last && flag <= 4
909 && (flag != 4 || last == 3)
910 && (flag != 2 || last == 0))
911 return flag;
914 if (token->type != CPP_EOF)
915 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
916 cpp_token_as_text (pfile, token));
917 return 0;
920 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
921 of length LEN, to binary; store it in NUMP, and return false if the
922 number was well-formed, true if not. WRAPPED is set to true if the
923 number did not fit into 'unsigned long'. */
924 static bool
925 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
927 linenum_type reg = 0;
928 linenum_type reg_prev = 0;
930 uchar c;
931 *wrapped = false;
932 while (len--)
934 c = *str++;
935 if (!ISDIGIT (c))
936 return true;
937 reg *= 10;
938 reg += c - '0';
939 if (reg < reg_prev)
940 *wrapped = true;
941 reg_prev = reg;
943 *nump = reg;
944 return false;
947 /* Interpret #line command.
948 Note that the filename string (if any) is a true string constant
949 (escapes are interpreted), unlike in #line. */
950 static void
951 do_line (cpp_reader *pfile)
953 struct line_maps *line_table = pfile->line_table;
954 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
956 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
957 sysp right now. */
959 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
960 const cpp_token *token;
961 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
962 linenum_type new_lineno;
964 /* C99 raised the minimum limit on #line numbers. */
965 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
966 bool wrapped;
968 /* #line commands expand macros. */
969 token = cpp_get_token (pfile);
970 if (token->type != CPP_NUMBER
971 || strtolinenum (token->val.str.text, token->val.str.len,
972 &new_lineno, &wrapped))
974 if (token->type == CPP_EOF)
975 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
976 else
977 cpp_error (pfile, CPP_DL_ERROR,
978 "\"%s\" after #line is not a positive integer",
979 cpp_token_as_text (pfile, token));
980 return;
983 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
984 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
985 else if (wrapped)
986 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
988 token = cpp_get_token (pfile);
989 if (token->type == CPP_STRING)
991 cpp_string s = { 0, 0 };
992 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
993 &s, CPP_STRING))
994 new_file = (const char *)s.text;
995 check_eol (pfile, true);
997 else if (token->type != CPP_EOF)
999 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1000 cpp_token_as_text (pfile, token));
1001 return;
1004 skip_rest_of_line (pfile);
1005 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
1006 map_sysp);
1007 line_table->seen_line_directive = true;
1010 /* Interpret the # 44 "file" [flags] notation, which has slightly
1011 different syntax and semantics from #line: Flags are allowed,
1012 and we never complain about the line number being too big. */
1013 static void
1014 do_linemarker (cpp_reader *pfile)
1016 struct line_maps *line_table = pfile->line_table;
1017 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1018 const cpp_token *token;
1019 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
1020 linenum_type new_lineno;
1021 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
1022 enum lc_reason reason = LC_RENAME_VERBATIM;
1023 int flag;
1024 bool wrapped;
1026 /* Back up so we can get the number again. Putting this in
1027 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
1028 some circumstances, which can segfault. */
1029 _cpp_backup_tokens (pfile, 1);
1031 /* #line commands expand macros. */
1032 token = cpp_get_token (pfile);
1033 if (token->type != CPP_NUMBER
1034 || strtolinenum (token->val.str.text, token->val.str.len,
1035 &new_lineno, &wrapped))
1037 /* Unlike #line, there does not seem to be a way to get an EOF
1038 here. So, it should be safe to always spell the token. */
1039 cpp_error (pfile, CPP_DL_ERROR,
1040 "\"%s\" after # is not a positive integer",
1041 cpp_token_as_text (pfile, token));
1042 return;
1045 token = cpp_get_token (pfile);
1046 if (token->type == CPP_STRING)
1048 cpp_string s = { 0, 0 };
1049 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1050 1, &s, CPP_STRING))
1051 new_file = (const char *)s.text;
1053 new_sysp = 0;
1054 flag = read_flag (pfile, 0);
1055 if (flag == 1)
1057 reason = LC_ENTER;
1058 /* Fake an include for cpp_included (). */
1059 _cpp_fake_include (pfile, new_file);
1060 flag = read_flag (pfile, flag);
1062 else if (flag == 2)
1064 reason = LC_LEAVE;
1065 flag = read_flag (pfile, flag);
1067 if (flag == 3)
1069 new_sysp = 1;
1070 flag = read_flag (pfile, flag);
1071 if (flag == 4)
1072 new_sysp = 2;
1074 pfile->buffer->sysp = new_sysp;
1076 check_eol (pfile, false);
1078 else if (token->type != CPP_EOF)
1080 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1081 cpp_token_as_text (pfile, token));
1082 return;
1085 skip_rest_of_line (pfile);
1087 if (reason == LC_LEAVE)
1089 /* Reread map since cpp_get_token can invalidate it with a
1090 reallocation. */
1091 map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
1092 const line_map_ordinary *from
1093 = linemap_included_from_linemap (line_table, map);
1094 if (MAIN_FILE_P (map)
1095 || (from
1096 && filename_cmp (ORDINARY_MAP_FILE_NAME (from), new_file) != 0))
1098 cpp_warning (pfile, CPP_W_NONE,
1099 "file \"%s\" linemarker ignored due to "
1100 "incorrect nesting", new_file);
1101 return;
1104 /* Compensate for the increment in linemap_add that occurs in
1105 _cpp_do_file_change. We're currently at the start of the line
1106 *following* the #line directive. A separate source_location for this
1107 location makes no sense (until we do the LC_LEAVE), and
1108 complicates LAST_SOURCE_LINE_LOCATION. */
1109 pfile->line_table->highest_location--;
1111 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1112 line_table->seen_line_directive = true;
1115 /* Arrange the file_change callback. pfile->line has changed to
1116 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
1117 header, 2 for a system header that needs to be extern "C" protected,
1118 and zero otherwise. */
1119 void
1120 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1121 const char *to_file, linenum_type file_line,
1122 unsigned int sysp)
1124 linemap_assert (reason != LC_ENTER_MACRO);
1125 const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1126 to_file, file_line);
1127 const line_map_ordinary *ord_map = NULL;
1128 if (map != NULL)
1130 ord_map = linemap_check_ordinary (map);
1131 linemap_line_start (pfile->line_table,
1132 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1133 127);
1136 if (pfile->cb.file_change)
1137 pfile->cb.file_change (pfile, ord_map);
1140 /* Report a warning or error detected by the program we are
1141 processing. Use the directive's tokens in the error message. */
1142 static void
1143 do_diagnostic (cpp_reader *pfile, int code, int reason, int print_dir)
1145 const unsigned char *dir_name;
1146 unsigned char *line;
1147 source_location src_loc = pfile->cur_token[-1].src_loc;
1149 if (print_dir)
1150 dir_name = pfile->directive->name;
1151 else
1152 dir_name = NULL;
1153 pfile->state.prevent_expansion++;
1154 line = cpp_output_line_to_string (pfile, dir_name);
1155 pfile->state.prevent_expansion--;
1157 if (code == CPP_DL_WARNING_SYSHDR && reason)
1158 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1159 else if (code == CPP_DL_WARNING && reason)
1160 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1161 else
1162 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1163 free (line);
1166 static void
1167 do_error (cpp_reader *pfile)
1169 do_diagnostic (pfile, CPP_DL_ERROR, 0, 1);
1172 static void
1173 do_warning (cpp_reader *pfile)
1175 /* We want #warning diagnostics to be emitted in system headers too. */
1176 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1179 /* Report program identification. */
1180 static void
1181 do_ident (cpp_reader *pfile)
1183 const cpp_token *str = cpp_get_token (pfile);
1185 if (str->type != CPP_STRING)
1186 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1187 pfile->directive->name);
1188 else if (pfile->cb.ident)
1189 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1191 check_eol (pfile, false);
1194 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1195 matching entry, or NULL if none is found. The returned entry could
1196 be the start of a namespace chain, or a pragma. */
1197 static struct pragma_entry *
1198 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1200 while (chain && chain->pragma != pragma)
1201 chain = chain->next;
1203 return chain;
1206 /* Create and insert a blank pragma entry at the beginning of a
1207 singly-linked CHAIN. */
1208 static struct pragma_entry *
1209 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1211 struct pragma_entry *new_entry;
1213 new_entry = (struct pragma_entry *)
1214 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1216 memset (new_entry, 0, sizeof (struct pragma_entry));
1217 new_entry->next = *chain;
1219 *chain = new_entry;
1220 return new_entry;
1223 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1224 goes in the global namespace. */
1225 static struct pragma_entry *
1226 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1227 bool allow_name_expansion)
1229 struct pragma_entry **chain = &pfile->pragmas;
1230 struct pragma_entry *entry;
1231 const cpp_hashnode *node;
1233 if (space)
1235 node = cpp_lookup (pfile, UC space, strlen (space));
1236 entry = lookup_pragma_entry (*chain, node);
1237 if (!entry)
1239 entry = new_pragma_entry (pfile, chain);
1240 entry->pragma = node;
1241 entry->is_nspace = true;
1242 entry->allow_expansion = allow_name_expansion;
1244 else if (!entry->is_nspace)
1245 goto clash;
1246 else if (entry->allow_expansion != allow_name_expansion)
1248 cpp_error (pfile, CPP_DL_ICE,
1249 "registering pragmas in namespace \"%s\" with mismatched "
1250 "name expansion", space);
1251 return NULL;
1253 chain = &entry->u.space;
1255 else if (allow_name_expansion)
1257 cpp_error (pfile, CPP_DL_ICE,
1258 "registering pragma \"%s\" with name expansion "
1259 "and no namespace", name);
1260 return NULL;
1263 /* Check for duplicates. */
1264 node = cpp_lookup (pfile, UC name, strlen (name));
1265 entry = lookup_pragma_entry (*chain, node);
1266 if (entry == NULL)
1268 entry = new_pragma_entry (pfile, chain);
1269 entry->pragma = node;
1270 return entry;
1273 if (entry->is_nspace)
1274 clash:
1275 cpp_error (pfile, CPP_DL_ICE,
1276 "registering \"%s\" as both a pragma and a pragma namespace",
1277 NODE_NAME (node));
1278 else if (space)
1279 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1280 space, name);
1281 else
1282 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1284 return NULL;
1287 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1288 static void
1289 register_pragma_internal (cpp_reader *pfile, const char *space,
1290 const char *name, pragma_cb handler)
1292 struct pragma_entry *entry;
1294 entry = register_pragma_1 (pfile, space, name, false);
1295 entry->is_internal = true;
1296 entry->u.handler = handler;
1299 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1300 goes in the global namespace. HANDLER is the handler it will call,
1301 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1302 expansion while parsing pragma NAME. This function is exported
1303 from libcpp. */
1304 void
1305 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1306 pragma_cb handler, bool allow_expansion)
1308 struct pragma_entry *entry;
1310 if (!handler)
1312 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1313 return;
1316 entry = register_pragma_1 (pfile, space, name, false);
1317 if (entry)
1319 entry->allow_expansion = allow_expansion;
1320 entry->u.handler = handler;
1324 /* Similarly, but create mark the pragma for deferred processing.
1325 When found, a CPP_PRAGMA token will be insertted into the stream
1326 with IDENT in the token->u.pragma slot. */
1327 void
1328 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1329 const char *name, unsigned int ident,
1330 bool allow_expansion, bool allow_name_expansion)
1332 struct pragma_entry *entry;
1334 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1335 if (entry)
1337 entry->is_deferred = true;
1338 entry->allow_expansion = allow_expansion;
1339 entry->u.ident = ident;
1343 /* Register the pragmas the preprocessor itself handles. */
1344 void
1345 _cpp_init_internal_pragmas (cpp_reader *pfile)
1347 /* Pragmas in the global namespace. */
1348 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1349 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1350 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1352 /* New GCC-specific pragmas should be put in the GCC namespace. */
1353 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1354 register_pragma_internal (pfile, "GCC", "system_header",
1355 do_pragma_system_header);
1356 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1357 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1358 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1361 /* Return the number of registered pragmas in PE. */
1363 static int
1364 count_registered_pragmas (struct pragma_entry *pe)
1366 int ct = 0;
1367 for (; pe != NULL; pe = pe->next)
1369 if (pe->is_nspace)
1370 ct += count_registered_pragmas (pe->u.space);
1371 ct++;
1373 return ct;
1376 /* Save into SD the names of the registered pragmas referenced by PE,
1377 and return a pointer to the next free space in SD. */
1379 static char **
1380 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1382 for (; pe != NULL; pe = pe->next)
1384 if (pe->is_nspace)
1385 sd = save_registered_pragmas (pe->u.space, sd);
1386 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1387 HT_LEN (&pe->pragma->ident),
1388 HT_LEN (&pe->pragma->ident) + 1);
1390 return sd;
1393 /* Return a newly-allocated array which saves the names of the
1394 registered pragmas. */
1396 char **
1397 _cpp_save_pragma_names (cpp_reader *pfile)
1399 int ct = count_registered_pragmas (pfile->pragmas);
1400 char **result = XNEWVEC (char *, ct);
1401 (void) save_registered_pragmas (pfile->pragmas, result);
1402 return result;
1405 /* Restore from SD the names of the registered pragmas referenced by PE,
1406 and return a pointer to the next unused name in SD. */
1408 static char **
1409 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1410 char **sd)
1412 for (; pe != NULL; pe = pe->next)
1414 if (pe->is_nspace)
1415 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1416 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1417 free (*sd);
1418 sd++;
1420 return sd;
1423 /* Restore the names of the registered pragmas from SAVED. */
1425 void
1426 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1428 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1429 free (saved);
1432 /* Pragmata handling. We handle some, and pass the rest on to the
1433 front end. C99 defines three pragmas and says that no macro
1434 expansion is to be performed on them; whether or not macro
1435 expansion happens for other pragmas is implementation defined.
1436 This implementation allows for a mix of both, since GCC did not
1437 traditionally macro expand its (few) pragmas, whereas OpenMP
1438 specifies that macro expansion should happen. */
1439 static void
1440 do_pragma (cpp_reader *pfile)
1442 const struct pragma_entry *p = NULL;
1443 const cpp_token *token, *pragma_token;
1444 source_location pragma_token_virt_loc = 0;
1445 cpp_token ns_token;
1446 unsigned int count = 1;
1448 pfile->state.prevent_expansion++;
1450 pragma_token = token = cpp_get_token_with_location (pfile,
1451 &pragma_token_virt_loc);
1452 ns_token = *token;
1453 if (token->type == CPP_NAME)
1455 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1456 if (p && p->is_nspace)
1458 bool allow_name_expansion = p->allow_expansion;
1459 if (allow_name_expansion)
1460 pfile->state.prevent_expansion--;
1462 token = cpp_get_token (pfile);
1463 if (token->type == CPP_NAME)
1464 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1465 else
1466 p = NULL;
1467 if (allow_name_expansion)
1468 pfile->state.prevent_expansion++;
1469 count = 2;
1473 if (p)
1475 if (p->is_deferred)
1477 pfile->directive_result.src_loc = pragma_token_virt_loc;
1478 pfile->directive_result.type = CPP_PRAGMA;
1479 pfile->directive_result.flags = pragma_token->flags;
1480 pfile->directive_result.val.pragma = p->u.ident;
1481 pfile->state.in_deferred_pragma = true;
1482 pfile->state.pragma_allow_expansion = p->allow_expansion;
1483 if (!p->allow_expansion)
1484 pfile->state.prevent_expansion++;
1486 else
1488 /* Since the handler below doesn't get the line number, that
1489 it might need for diagnostics, make sure it has the right
1490 numbers in place. */
1491 if (pfile->cb.line_change)
1492 (*pfile->cb.line_change) (pfile, pragma_token, false);
1493 if (p->allow_expansion)
1494 pfile->state.prevent_expansion--;
1495 (*p->u.handler) (pfile);
1496 if (p->allow_expansion)
1497 pfile->state.prevent_expansion++;
1500 else if (pfile->cb.def_pragma)
1502 if (count == 1 || pfile->context->prev == NULL)
1503 _cpp_backup_tokens (pfile, count);
1504 else
1506 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1507 won't allow backing 2 tokens. */
1508 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1509 reads both tokens, we could perhaps free it, but if it doesn't,
1510 we don't know the exact lifespan. */
1511 cpp_token *toks = XNEWVEC (cpp_token, 2);
1512 toks[0] = ns_token;
1513 toks[0].flags |= NO_EXPAND;
1514 toks[1] = *token;
1515 toks[1].flags |= NO_EXPAND;
1516 _cpp_push_token_context (pfile, NULL, toks, 2);
1518 pfile->cb.def_pragma (pfile, pfile->directive_line);
1521 pfile->state.prevent_expansion--;
1524 /* Handle #pragma once. */
1525 static void
1526 do_pragma_once (cpp_reader *pfile)
1528 if (cpp_in_primary_file (pfile))
1529 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1531 check_eol (pfile, false);
1532 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1535 /* Handle #pragma push_macro(STRING). */
1536 static void
1537 do_pragma_push_macro (cpp_reader *pfile)
1539 cpp_hashnode *node;
1540 size_t defnlen;
1541 const uchar *defn = NULL;
1542 char *macroname, *dest;
1543 const char *limit, *src;
1544 const cpp_token *txt;
1545 struct def_pragma_macro *c;
1547 txt = get__Pragma_string (pfile);
1548 if (!txt)
1550 source_location src_loc = pfile->cur_token[-1].src_loc;
1551 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1552 "invalid #pragma push_macro directive");
1553 check_eol (pfile, false);
1554 skip_rest_of_line (pfile);
1555 return;
1557 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1558 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1559 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1560 while (src < limit)
1562 /* We know there is a character following the backslash. */
1563 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1564 src++;
1565 *dest++ = *src++;
1567 *dest = 0;
1568 check_eol (pfile, false);
1569 skip_rest_of_line (pfile);
1570 c = XNEW (struct def_pragma_macro);
1571 memset (c, 0, sizeof (struct def_pragma_macro));
1572 c->name = XNEWVAR (char, strlen (macroname) + 1);
1573 strcpy (c->name, macroname);
1574 c->next = pfile->pushed_macros;
1575 node = _cpp_lex_identifier (pfile, c->name);
1576 if (node->type == NT_VOID)
1577 c->is_undef = 1;
1578 else
1580 defn = cpp_macro_definition (pfile, node);
1581 defnlen = ustrlen (defn);
1582 c->definition = XNEWVEC (uchar, defnlen + 2);
1583 c->definition[defnlen] = '\n';
1584 c->definition[defnlen + 1] = 0;
1585 c->line = node->value.macro->line;
1586 c->syshdr = node->value.macro->syshdr;
1587 c->used = node->value.macro->used;
1588 memcpy (c->definition, defn, defnlen);
1591 pfile->pushed_macros = c;
1594 /* Handle #pragma pop_macro(STRING). */
1595 static void
1596 do_pragma_pop_macro (cpp_reader *pfile)
1598 char *macroname, *dest;
1599 const char *limit, *src;
1600 const cpp_token *txt;
1601 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1602 txt = get__Pragma_string (pfile);
1603 if (!txt)
1605 source_location src_loc = pfile->cur_token[-1].src_loc;
1606 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1607 "invalid #pragma pop_macro directive");
1608 check_eol (pfile, false);
1609 skip_rest_of_line (pfile);
1610 return;
1612 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1613 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1614 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1615 while (src < limit)
1617 /* We know there is a character following the backslash. */
1618 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1619 src++;
1620 *dest++ = *src++;
1622 *dest = 0;
1623 check_eol (pfile, false);
1624 skip_rest_of_line (pfile);
1626 while (c != NULL)
1628 if (!strcmp (c->name, macroname))
1630 if (!l)
1631 pfile->pushed_macros = c->next;
1632 else
1633 l->next = c->next;
1634 cpp_pop_definition (pfile, c);
1635 free (c->definition);
1636 free (c->name);
1637 free (c);
1638 break;
1640 l = c;
1641 c = c->next;
1645 /* Handle #pragma GCC poison, to poison one or more identifiers so
1646 that the lexer produces a hard error for each subsequent usage. */
1647 static void
1648 do_pragma_poison (cpp_reader *pfile)
1650 const cpp_token *tok;
1651 cpp_hashnode *hp;
1653 pfile->state.poisoned_ok = 1;
1654 for (;;)
1656 tok = _cpp_lex_token (pfile);
1657 if (tok->type == CPP_EOF)
1658 break;
1659 if (tok->type != CPP_NAME)
1661 cpp_error (pfile, CPP_DL_ERROR,
1662 "invalid #pragma GCC poison directive");
1663 break;
1666 hp = tok->val.node.node;
1667 if (hp->flags & NODE_POISONED)
1668 continue;
1670 if (cpp_macro_p (hp))
1671 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1672 NODE_NAME (hp));
1673 _cpp_free_definition (hp);
1674 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1676 pfile->state.poisoned_ok = 0;
1679 /* Mark the current header as a system header. This will suppress
1680 some categories of warnings (notably those from -pedantic). It is
1681 intended for use in system libraries that cannot be implemented in
1682 conforming C, but cannot be certain that their headers appear in a
1683 system include directory. To prevent abuse, it is rejected in the
1684 primary source file. */
1685 static void
1686 do_pragma_system_header (cpp_reader *pfile)
1688 if (cpp_in_primary_file (pfile))
1689 cpp_error (pfile, CPP_DL_WARNING,
1690 "#pragma system_header ignored outside include file");
1691 else
1693 check_eol (pfile, false);
1694 skip_rest_of_line (pfile);
1695 cpp_make_system_header (pfile, 1, 0);
1699 /* Check the modified date of the current include file against a specified
1700 file. Issue a diagnostic, if the specified file is newer. We use this to
1701 determine if a fixed header should be refixed. */
1702 static void
1703 do_pragma_dependency (cpp_reader *pfile)
1705 const char *fname;
1706 int angle_brackets, ordering;
1707 source_location location;
1709 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1710 if (!fname)
1711 return;
1713 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1714 if (ordering < 0)
1715 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1716 else if (ordering > 0)
1718 cpp_error (pfile, CPP_DL_WARNING,
1719 "current file is older than %s", fname);
1720 if (cpp_get_token (pfile)->type != CPP_EOF)
1722 _cpp_backup_tokens (pfile, 1);
1723 do_diagnostic (pfile, CPP_DL_WARNING, 0, 0);
1727 free ((void *) fname);
1730 /* Issue a diagnostic with the message taken from the pragma. If
1731 ERROR is true, the diagnostic is a warning, otherwise, it is an
1732 error. */
1733 static void
1734 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1736 const cpp_token *tok = _cpp_lex_token (pfile);
1737 cpp_string str;
1738 if (tok->type != CPP_STRING
1739 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1740 CPP_STRING)
1741 || str.len == 0)
1743 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1744 error ? "error" : "warning");
1745 return;
1747 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1748 "%s", str.text);
1749 free ((void *)str.text);
1752 /* Issue a warning diagnostic. */
1753 static void
1754 do_pragma_warning (cpp_reader *pfile)
1756 do_pragma_warning_or_error (pfile, false);
1759 /* Issue an error diagnostic. */
1760 static void
1761 do_pragma_error (cpp_reader *pfile)
1763 do_pragma_warning_or_error (pfile, true);
1766 /* Get a token but skip padding. */
1767 static const cpp_token *
1768 get_token_no_padding (cpp_reader *pfile)
1770 for (;;)
1772 const cpp_token *result = cpp_get_token (pfile);
1773 if (result->type != CPP_PADDING)
1774 return result;
1778 /* Check syntax is "(string-literal)". Returns the string on success,
1779 or NULL on failure. */
1780 static const cpp_token *
1781 get__Pragma_string (cpp_reader *pfile)
1783 const cpp_token *string;
1784 const cpp_token *paren;
1786 paren = get_token_no_padding (pfile);
1787 if (paren->type == CPP_EOF)
1788 _cpp_backup_tokens (pfile, 1);
1789 if (paren->type != CPP_OPEN_PAREN)
1790 return NULL;
1792 string = get_token_no_padding (pfile);
1793 if (string->type == CPP_EOF)
1794 _cpp_backup_tokens (pfile, 1);
1795 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1796 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1797 && string->type != CPP_UTF8STRING)
1798 return NULL;
1800 paren = get_token_no_padding (pfile);
1801 if (paren->type == CPP_EOF)
1802 _cpp_backup_tokens (pfile, 1);
1803 if (paren->type != CPP_CLOSE_PAREN)
1804 return NULL;
1806 return string;
1809 /* Destringize IN into a temporary buffer, by removing the first \ of
1810 \" and \\ sequences, and process the result as a #pragma directive. */
1811 static void
1812 destringize_and_run (cpp_reader *pfile, const cpp_string *in,
1813 source_location expansion_loc)
1815 const unsigned char *src, *limit;
1816 char *dest, *result;
1817 cpp_context *saved_context;
1818 cpp_token *saved_cur_token;
1819 tokenrun *saved_cur_run;
1820 cpp_token *toks;
1821 int count;
1822 const struct directive *save_directive;
1824 dest = result = (char *) alloca (in->len - 1);
1825 src = in->text + 1 + (in->text[0] == 'L');
1826 limit = in->text + in->len - 1;
1827 while (src < limit)
1829 /* We know there is a character following the backslash. */
1830 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1831 src++;
1832 *dest++ = *src++;
1834 *dest = '\n';
1836 /* Ugh; an awful kludge. We are really not set up to be lexing
1837 tokens when in the middle of a macro expansion. Use a new
1838 context to force cpp_get_token to lex, and so skip_rest_of_line
1839 doesn't go beyond the end of the text. Also, remember the
1840 current lexing position so we can return to it later.
1842 Something like line-at-a-time lexing should remove the need for
1843 this. */
1844 saved_context = pfile->context;
1845 saved_cur_token = pfile->cur_token;
1846 saved_cur_run = pfile->cur_run;
1848 pfile->context = XCNEW (cpp_context);
1850 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1851 until we've read all of the tokens that we want. */
1852 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1853 /* from_stage3 */ true);
1854 /* ??? Antique Disgusting Hack. What does this do? */
1855 if (pfile->buffer->prev)
1856 pfile->buffer->file = pfile->buffer->prev->file;
1858 start_directive (pfile);
1859 _cpp_clean_line (pfile);
1860 save_directive = pfile->directive;
1861 pfile->directive = &dtable[T_PRAGMA];
1862 do_pragma (pfile);
1863 end_directive (pfile, 1);
1864 pfile->directive = save_directive;
1866 /* We always insert at least one token, the directive result. It'll
1867 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1868 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1870 /* If we're not handling the pragma internally, read all of the tokens from
1871 the string buffer now, while the string buffer is still installed. */
1872 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1873 to me what the true lifespan of the tokens are. It would appear that
1874 the lifespan is the entire parse of the main input stream, in which case
1875 this may not be wrong. */
1876 if (pfile->directive_result.type == CPP_PRAGMA)
1878 int maxcount;
1880 count = 1;
1881 maxcount = 50;
1882 toks = XNEWVEC (cpp_token, maxcount);
1883 toks[0] = pfile->directive_result;
1887 if (count == maxcount)
1889 maxcount = maxcount * 3 / 2;
1890 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1892 toks[count] = *cpp_get_token (pfile);
1893 /* _Pragma is a builtin, so we're not within a macro-map, and so
1894 the token locations are set to bogus ordinary locations
1895 near to, but after that of the "_Pragma".
1896 Paper over this by setting them equal to the location of the
1897 _Pragma itself (PR preprocessor/69126). */
1898 toks[count].src_loc = expansion_loc;
1899 /* Macros have been already expanded by cpp_get_token
1900 if the pragma allowed expansion. */
1901 toks[count++].flags |= NO_EXPAND;
1903 while (toks[count-1].type != CPP_PRAGMA_EOL);
1905 else
1907 count = 1;
1908 toks = XNEW (cpp_token);
1909 toks[0] = pfile->directive_result;
1911 /* If we handled the entire pragma internally, make sure we get the
1912 line number correct for the next token. */
1913 if (pfile->cb.line_change)
1914 pfile->cb.line_change (pfile, pfile->cur_token, false);
1917 /* Finish inlining run_directive. */
1918 pfile->buffer->file = NULL;
1919 _cpp_pop_buffer (pfile);
1921 /* Reset the old macro state before ... */
1922 XDELETE (pfile->context);
1923 pfile->context = saved_context;
1924 pfile->cur_token = saved_cur_token;
1925 pfile->cur_run = saved_cur_run;
1927 /* ... inserting the new tokens we collected. */
1928 _cpp_push_token_context (pfile, NULL, toks, count);
1931 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1933 _cpp_do__Pragma (cpp_reader *pfile, source_location expansion_loc)
1935 const cpp_token *string = get__Pragma_string (pfile);
1936 pfile->directive_result.type = CPP_PADDING;
1938 if (string)
1940 destringize_and_run (pfile, &string->val.str, expansion_loc);
1941 return 1;
1943 cpp_error (pfile, CPP_DL_ERROR,
1944 "_Pragma takes a parenthesized string literal");
1945 return 0;
1948 /* Handle #ifdef. */
1949 static void
1950 do_ifdef (cpp_reader *pfile)
1952 int skip = 1;
1954 if (! pfile->state.skipping)
1956 cpp_hashnode *node = lex_macro_node (pfile, false);
1958 if (node)
1960 /* Do not treat conditional macros as being defined. This is due to
1961 the powerpc and spu ports using conditional macros for 'vector',
1962 'bool', and 'pixel' to act as conditional keywords. This messes
1963 up tests like #ifndef bool. */
1964 skip = !cpp_macro_p (node) || (node->flags & NODE_CONDITIONAL);
1965 _cpp_mark_macro_used (node);
1966 _cpp_maybe_notify_macro_use (pfile, node);
1967 if (pfile->cb.used)
1968 pfile->cb.used (pfile, pfile->directive_line, node);
1969 check_eol (pfile, false);
1973 push_conditional (pfile, skip, T_IFDEF, 0);
1976 /* Handle #ifndef. */
1977 static void
1978 do_ifndef (cpp_reader *pfile)
1980 int skip = 1;
1981 cpp_hashnode *node = 0;
1983 if (! pfile->state.skipping)
1985 node = lex_macro_node (pfile, false);
1987 if (node)
1989 /* Do not treat conditional macros as being defined. This is due to
1990 the powerpc and spu ports using conditional macros for 'vector',
1991 'bool', and 'pixel' to act as conditional keywords. This messes
1992 up tests like #ifndef bool. */
1993 skip = (cpp_macro_p (node)
1994 && !(node->flags & NODE_CONDITIONAL));
1995 _cpp_mark_macro_used (node);
1996 _cpp_maybe_notify_macro_use (pfile, node);
1997 if (pfile->cb.used)
1998 pfile->cb.used (pfile, pfile->directive_line, node);
1999 check_eol (pfile, false);
2003 push_conditional (pfile, skip, T_IFNDEF, node);
2006 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
2007 pfile->mi_ind_cmacro so we can handle multiple-include
2008 optimizations. If macro expansion occurs in the expression, we
2009 cannot treat it as a controlling conditional, since the expansion
2010 could change in the future. That is handled by cpp_get_token. */
2011 static void
2012 do_if (cpp_reader *pfile)
2014 int skip = 1;
2016 if (! pfile->state.skipping)
2017 skip = _cpp_parse_expr (pfile, true) == false;
2019 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
2022 /* Flip skipping state if appropriate and continue without changing
2023 if_stack; this is so that the error message for missing #endif's
2024 etc. will point to the original #if. */
2025 static void
2026 do_else (cpp_reader *pfile)
2028 cpp_buffer *buffer = pfile->buffer;
2029 struct if_stack *ifs = buffer->if_stack;
2031 if (ifs == NULL)
2032 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2033 else
2035 if (ifs->type == T_ELSE)
2037 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2038 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2039 "the conditional began here");
2041 ifs->type = T_ELSE;
2043 /* Skip any future (erroneous) #elses or #elifs. */
2044 pfile->state.skipping = ifs->skip_elses;
2045 ifs->skip_elses = true;
2047 /* Invalidate any controlling macro. */
2048 ifs->mi_cmacro = 0;
2050 /* Only check EOL if was not originally skipping. */
2051 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2052 check_eol_endif_labels (pfile);
2056 /* Handle a #elif directive by not changing if_stack either. See the
2057 comment above do_else. */
2058 static void
2059 do_elif (cpp_reader *pfile)
2061 cpp_buffer *buffer = pfile->buffer;
2062 struct if_stack *ifs = buffer->if_stack;
2064 if (ifs == NULL)
2065 cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2066 else
2068 if (ifs->type == T_ELSE)
2070 cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2071 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2072 "the conditional began here");
2074 ifs->type = T_ELIF;
2076 /* See DR#412: "Only the first group whose control condition
2077 evaluates to true (nonzero) is processed; any following groups
2078 are skipped and their controlling directives are processed as
2079 if they were in a group that is skipped." */
2080 if (ifs->skip_elses)
2081 pfile->state.skipping = 1;
2082 else
2084 pfile->state.skipping = ! _cpp_parse_expr (pfile, false);
2085 ifs->skip_elses = ! pfile->state.skipping;
2088 /* Invalidate any controlling macro. */
2089 ifs->mi_cmacro = 0;
2093 /* #endif pops the if stack and resets pfile->state.skipping. */
2094 static void
2095 do_endif (cpp_reader *pfile)
2097 cpp_buffer *buffer = pfile->buffer;
2098 struct if_stack *ifs = buffer->if_stack;
2100 if (ifs == NULL)
2101 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2102 else
2104 /* Only check EOL if was not originally skipping. */
2105 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2106 check_eol_endif_labels (pfile);
2108 /* If potential control macro, we go back outside again. */
2109 if (ifs->next == 0 && ifs->mi_cmacro)
2111 pfile->mi_valid = true;
2112 pfile->mi_cmacro = ifs->mi_cmacro;
2115 buffer->if_stack = ifs->next;
2116 pfile->state.skipping = ifs->was_skipping;
2117 obstack_free (&pfile->buffer_ob, ifs);
2121 /* Push an if_stack entry for a preprocessor conditional, and set
2122 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2123 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2124 we need to check here that we are at the top of the file. */
2125 static void
2126 push_conditional (cpp_reader *pfile, int skip, int type,
2127 const cpp_hashnode *cmacro)
2129 struct if_stack *ifs;
2130 cpp_buffer *buffer = pfile->buffer;
2132 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2133 ifs->line = pfile->directive_line;
2134 ifs->next = buffer->if_stack;
2135 ifs->skip_elses = pfile->state.skipping || !skip;
2136 ifs->was_skipping = pfile->state.skipping;
2137 ifs->type = type;
2138 /* This condition is effectively a test for top-of-file. */
2139 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2140 ifs->mi_cmacro = cmacro;
2141 else
2142 ifs->mi_cmacro = 0;
2144 pfile->state.skipping = skip;
2145 buffer->if_stack = ifs;
2148 /* Read the tokens of the answer into the macro pool, in a directive
2149 of type TYPE. Only commit the memory if we intend it as permanent
2150 storage, i.e. the #assert case. Returns 0 on success, and sets
2151 ANSWERP to point to the answer. PRED_LOC is the location of the
2152 predicate. */
2153 static bool
2154 parse_answer (cpp_reader *pfile, int type, source_location pred_loc,
2155 cpp_macro **answer_ptr)
2157 /* In a conditional, it is legal to not have an open paren. We
2158 should save the following token in this case. */
2159 const cpp_token *paren = cpp_get_token (pfile);
2161 /* If not a paren, see if we're OK. */
2162 if (paren->type != CPP_OPEN_PAREN)
2164 /* In a conditional no answer is a test for any answer. It
2165 could be followed by any token. */
2166 if (type == T_IF)
2168 _cpp_backup_tokens (pfile, 1);
2169 return true;
2172 /* #unassert with no answer is valid - it removes all answers. */
2173 if (type == T_UNASSERT && paren->type == CPP_EOF)
2174 return true;
2176 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2177 "missing '(' after predicate");
2178 return false;
2181 cpp_macro *answer = _cpp_new_macro (pfile, cmk_assert,
2182 _cpp_reserve_room (pfile, 0,
2183 sizeof (cpp_macro)));
2184 answer->parm.next = NULL;
2185 unsigned count = 0;
2186 for (;;)
2188 const cpp_token *token = cpp_get_token (pfile);
2190 if (token->type == CPP_CLOSE_PAREN)
2191 break;
2193 if (token->type == CPP_EOF)
2195 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2196 return false;
2199 answer = (cpp_macro *)_cpp_reserve_room
2200 (pfile, sizeof (cpp_macro) + count * sizeof (cpp_token),
2201 sizeof (cpp_token));
2202 answer->exp.tokens[count++] = *token;
2205 if (!count)
2207 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2208 return false;
2211 /* Drop whitespace at start, for answer equivalence purposes. */
2212 answer->exp.tokens[0].flags &= ~PREV_WHITE;
2214 answer->count = count;
2215 *answer_ptr = answer;
2217 return true;
2220 /* Parses an assertion directive of type TYPE, returning a pointer to
2221 the hash node of the predicate, or 0 on error. The node is
2222 guaranteed to be disjoint from the macro namespace, so can only
2223 have type 'NT_VOID'. If an answer was supplied, it is placed in
2224 *ANSWER_PTR, which is otherwise set to 0. */
2225 static cpp_hashnode *
2226 parse_assertion (cpp_reader *pfile, int type, cpp_macro **answer_ptr)
2228 cpp_hashnode *result = 0;
2230 /* We don't expand predicates or answers. */
2231 pfile->state.prevent_expansion++;
2233 *answer_ptr = NULL;
2235 const cpp_token *predicate = cpp_get_token (pfile);
2236 if (predicate->type == CPP_EOF)
2237 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2238 else if (predicate->type != CPP_NAME)
2239 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2240 "predicate must be an identifier");
2241 else if (parse_answer (pfile, type, predicate->src_loc, answer_ptr))
2243 unsigned int len = NODE_LEN (predicate->val.node.node);
2244 unsigned char *sym = (unsigned char *) alloca (len + 1);
2246 /* Prefix '#' to get it out of macro namespace. */
2247 sym[0] = '#';
2248 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2249 result = cpp_lookup (pfile, sym, len + 1);
2252 pfile->state.prevent_expansion--;
2254 return result;
2257 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2258 or a pointer to NULL if the answer is not in the chain. */
2259 static cpp_macro **
2260 find_answer (cpp_hashnode *node, const cpp_macro *candidate)
2262 unsigned int i;
2263 cpp_macro **result = NULL;
2265 for (result = &node->value.answers; *result; result = &(*result)->parm.next)
2267 cpp_macro *answer = *result;
2269 if (answer->count == candidate->count)
2271 for (i = 0; i < answer->count; i++)
2272 if (!_cpp_equiv_tokens (&answer->exp.tokens[i],
2273 &candidate->exp.tokens[i]))
2274 break;
2276 if (i == answer->count)
2277 break;
2281 return result;
2284 /* Test an assertion within a preprocessor conditional. Returns
2285 nonzero on failure, zero on success. On success, the result of
2286 the test is written into VALUE, otherwise the value 0. */
2288 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2290 cpp_macro *answer;
2291 cpp_hashnode *node = parse_assertion (pfile, T_IF, &answer);
2293 /* For recovery, an erroneous assertion expression is handled as a
2294 failing assertion. */
2295 *value = 0;
2297 if (node)
2299 if (node->value.answers)
2300 *value = !answer || *find_answer (node, answer);
2302 else if (pfile->cur_token[-1].type == CPP_EOF)
2303 _cpp_backup_tokens (pfile, 1);
2305 /* We don't commit the memory for the answer - it's temporary only. */
2306 return node == 0;
2309 /* Handle #assert. */
2310 static void
2311 do_assert (cpp_reader *pfile)
2313 cpp_macro *answer;
2314 cpp_hashnode *node = parse_assertion (pfile, T_ASSERT, &answer);
2316 if (node)
2318 /* Place the new answer in the answer list. First check there
2319 is not a duplicate. */
2320 if (*find_answer (node, answer))
2322 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2323 NODE_NAME (node) + 1);
2324 return;
2327 /* Commit or allocate storage for the answer. */
2328 answer = (cpp_macro *)_cpp_commit_buff
2329 (pfile, sizeof (cpp_macro) - sizeof (cpp_token)
2330 + sizeof (cpp_token) * answer->count);
2332 /* Chain into the list. */
2333 answer->parm.next = node->value.answers;
2334 node->value.answers = answer;
2336 check_eol (pfile, false);
2340 /* Handle #unassert. */
2341 static void
2342 do_unassert (cpp_reader *pfile)
2344 cpp_macro *answer;
2345 cpp_hashnode *node = parse_assertion (pfile, T_UNASSERT, &answer);
2347 /* It isn't an error to #unassert something that isn't asserted. */
2348 if (node)
2350 if (answer)
2352 cpp_macro **p = find_answer (node, answer);
2354 /* Remove the assert from the list. */
2355 if (cpp_macro *temp = *p)
2356 *p = temp->parm.next;
2358 check_eol (pfile, false);
2360 else
2361 _cpp_free_definition (node);
2364 /* We don't commit the memory for the answer - it's temporary only. */
2367 /* These are for -D, -U, -A. */
2369 /* Process the string STR as if it appeared as the body of a #define.
2370 If STR is just an identifier, define it with value 1.
2371 If STR has anything after the identifier, then it should
2372 be identifier=definition. */
2373 void
2374 cpp_define (cpp_reader *pfile, const char *str)
2376 char *buf;
2377 const char *p;
2378 size_t count;
2380 /* Copy the entire option so we can modify it.
2381 Change the first "=" in the string to a space. If there is none,
2382 tack " 1" on the end. */
2384 count = strlen (str);
2385 buf = (char *) alloca (count + 3);
2386 memcpy (buf, str, count);
2388 p = strchr (str, '=');
2389 if (p)
2390 buf[p - str] = ' ';
2391 else
2393 buf[count++] = ' ';
2394 buf[count++] = '1';
2396 buf[count] = '\n';
2398 run_directive (pfile, T_DEFINE, buf, count);
2402 /* Use to build macros to be run through cpp_define() as
2403 described above.
2404 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2406 void
2407 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2409 char *ptr;
2411 va_list ap;
2412 va_start (ap, fmt);
2413 ptr = xvasprintf (fmt, ap);
2414 va_end (ap);
2416 cpp_define (pfile, ptr);
2417 free (ptr);
2421 /* Slight variant of the above for use by initialize_builtins. */
2422 void
2423 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2425 size_t len = strlen (str);
2426 char *buf = (char *) alloca (len + 1);
2427 memcpy (buf, str, len);
2428 buf[len] = '\n';
2429 run_directive (pfile, T_DEFINE, buf, len);
2432 /* Process MACRO as if it appeared as the body of an #undef. */
2433 void
2434 cpp_undef (cpp_reader *pfile, const char *macro)
2436 size_t len = strlen (macro);
2437 char *buf = (char *) alloca (len + 1);
2438 memcpy (buf, macro, len);
2439 buf[len] = '\n';
2440 run_directive (pfile, T_UNDEF, buf, len);
2443 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2444 or first element is zero, then the macro should be undefined. */
2445 static void
2446 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2448 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2449 if (node == NULL)
2450 return;
2452 if (pfile->cb.before_define)
2453 pfile->cb.before_define (pfile);
2455 if (cpp_macro_p (node))
2457 if (pfile->cb.undef)
2458 pfile->cb.undef (pfile, pfile->directive_line, node);
2459 if (CPP_OPTION (pfile, warn_unused_macros))
2460 _cpp_warn_if_unused_macro (pfile, node, NULL);
2461 _cpp_free_definition (node);
2464 if (c->is_undef)
2465 return;
2468 size_t namelen;
2469 const uchar *dn;
2470 cpp_hashnode *h = NULL;
2471 cpp_buffer *nbuf;
2473 namelen = ustrcspn (c->definition, "( \n");
2474 h = cpp_lookup (pfile, c->definition, namelen);
2475 dn = c->definition + namelen;
2477 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2478 if (nbuf != NULL)
2480 _cpp_clean_line (pfile);
2481 nbuf->sysp = 1;
2482 if (!_cpp_create_definition (pfile, h))
2483 abort ();
2484 _cpp_pop_buffer (pfile);
2486 else
2487 abort ();
2488 h->value.macro->line = c->line;
2489 h->value.macro->syshdr = c->syshdr;
2490 h->value.macro->used = c->used;
2494 /* Process the string STR as if it appeared as the body of a #assert. */
2495 void
2496 cpp_assert (cpp_reader *pfile, const char *str)
2498 handle_assertion (pfile, str, T_ASSERT);
2501 /* Process STR as if it appeared as the body of an #unassert. */
2502 void
2503 cpp_unassert (cpp_reader *pfile, const char *str)
2505 handle_assertion (pfile, str, T_UNASSERT);
2508 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2509 static void
2510 handle_assertion (cpp_reader *pfile, const char *str, int type)
2512 size_t count = strlen (str);
2513 const char *p = strchr (str, '=');
2515 /* Copy the entire option so we can modify it. Change the first
2516 "=" in the string to a '(', and tack a ')' on the end. */
2517 char *buf = (char *) alloca (count + 2);
2519 memcpy (buf, str, count);
2520 if (p)
2522 buf[p - str] = '(';
2523 buf[count++] = ')';
2525 buf[count] = '\n';
2526 str = buf;
2528 run_directive (pfile, type, str, count);
2531 /* The options structure. */
2532 cpp_options *
2533 cpp_get_options (cpp_reader *pfile)
2535 return &pfile->opts;
2538 /* The callbacks structure. */
2539 cpp_callbacks *
2540 cpp_get_callbacks (cpp_reader *pfile)
2542 return &pfile->cb;
2545 /* Copy the given callbacks structure to our own. */
2546 void
2547 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2549 pfile->cb = *cb;
2552 /* The dependencies structure. (Creates one if it hasn't already been.) */
2553 struct deps *
2554 cpp_get_deps (cpp_reader *pfile)
2556 if (!pfile->deps)
2557 pfile->deps = deps_init ();
2558 return pfile->deps;
2561 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2562 doesn't fail. It does not generate a file change call back; that
2563 is the responsibility of the caller. */
2564 cpp_buffer *
2565 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2566 int from_stage3)
2568 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2570 /* Clears, amongst other things, if_stack and mi_cmacro. */
2571 memset (new_buffer, 0, sizeof (cpp_buffer));
2573 new_buffer->next_line = new_buffer->buf = buffer;
2574 new_buffer->rlimit = buffer + len;
2575 new_buffer->from_stage3 = from_stage3;
2576 new_buffer->prev = pfile->buffer;
2577 new_buffer->need_line = true;
2579 pfile->buffer = new_buffer;
2581 return new_buffer;
2584 /* Pops a single buffer, with a file change call-back if appropriate.
2585 Then pushes the next -include file, if any remain. */
2586 void
2587 _cpp_pop_buffer (cpp_reader *pfile)
2589 cpp_buffer *buffer = pfile->buffer;
2590 struct _cpp_file *inc = buffer->file;
2591 struct if_stack *ifs;
2592 const unsigned char *to_free;
2594 /* Walk back up the conditional stack till we reach its level at
2595 entry to this file, issuing error messages. */
2596 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2597 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2598 "unterminated #%s", dtable[ifs->type].name);
2600 /* In case of a missing #endif. */
2601 pfile->state.skipping = 0;
2603 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2604 pfile->buffer = buffer->prev;
2606 to_free = buffer->to_free;
2607 free (buffer->notes);
2609 /* Free the buffer object now; we may want to push a new buffer
2610 in _cpp_push_next_include_file. */
2611 obstack_free (&pfile->buffer_ob, buffer);
2613 if (inc)
2615 _cpp_pop_file_buffer (pfile, inc, to_free);
2617 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2621 /* Enter all recognized directives in the hash table. */
2622 void
2623 _cpp_init_directives (cpp_reader *pfile)
2625 unsigned int i;
2626 cpp_hashnode *node;
2628 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2630 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2631 node->is_directive = 1;
2632 node->directive_index = i;
2636 /* Extract header file from a bracket include. Parsing starts after '<'.
2637 The string is malloced and must be freed by the caller. */
2638 char *
2639 _cpp_bracket_include(cpp_reader *pfile)
2641 return glue_header_name (pfile);