gcc/
[official-gcc.git] / libcpp / directives.c
blob1e9bc3da0fc69793065765e85a35aeddc28cc9cc
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2015 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 static int parse_answer (cpp_reader *, struct answer **, int, source_location);
127 static cpp_hashnode *parse_assertion (cpp_reader *, struct answer **, int);
128 static struct answer ** find_answer (cpp_hashnode *, const struct answer *);
129 static void handle_assertion (cpp_reader *, const char *, int);
130 static void do_pragma_push_macro (cpp_reader *);
131 static void do_pragma_pop_macro (cpp_reader *);
132 static void cpp_pop_definition (cpp_reader *, struct def_pragma_macro *);
134 /* This is the table of directive handlers. It is ordered by
135 frequency of occurrence; the numbers at the end are directive
136 counts from all the source code I have lying around (egcs and libc
137 CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
138 pcmcia-cs-3.0.9). This is no longer important as directive lookup
139 is now O(1). All extensions other than #warning, #include_next,
140 and #import are deprecated. The name is where the extension
141 appears to have come from. */
143 #define DIRECTIVE_TABLE \
144 D(define, T_DEFINE = 0, KANDR, IN_I) /* 270554 */ \
145 D(include, T_INCLUDE, KANDR, INCL | EXPAND) /* 52262 */ \
146 D(endif, T_ENDIF, KANDR, COND) /* 45855 */ \
147 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) /* 22000 */ \
148 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) /* 18162 */ \
149 D(else, T_ELSE, KANDR, COND) /* 9863 */ \
150 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) /* 9675 */ \
151 D(undef, T_UNDEF, KANDR, IN_I) /* 4837 */ \
152 D(line, T_LINE, KANDR, EXPAND) /* 2465 */ \
153 D(elif, T_ELIF, STDC89, COND | EXPAND) /* 610 */ \
154 D(error, T_ERROR, STDC89, 0) /* 475 */ \
155 D(pragma, T_PRAGMA, STDC89, IN_I) /* 195 */ \
156 D(warning, T_WARNING, EXTENSION, 0) /* 22 */ \
157 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) /* 19 */ \
158 D(ident, T_IDENT, EXTENSION, IN_I) /* 11 */ \
159 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* 0 ObjC */ \
160 D(assert, T_ASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
161 D(unassert, T_UNASSERT, EXTENSION, DEPRECATED) /* 0 SVR4 */ \
162 D(sccs, T_SCCS, EXTENSION, IN_I) /* 0 SVR4? */
164 /* #sccs is synonymous with #ident. */
165 #define do_sccs do_ident
167 /* Use the table to generate a series of prototypes, an enum for the
168 directive names, and an array of directive handlers. */
170 #define D(name, t, o, f) static void do_##name (cpp_reader *);
171 DIRECTIVE_TABLE
172 #undef D
174 #define D(n, tag, o, f) tag,
175 enum
177 DIRECTIVE_TABLE
178 N_DIRECTIVES
180 #undef D
182 #define D(name, t, origin, flags) \
183 { do_##name, (const uchar *) #name, \
184 sizeof #name - 1, origin, flags },
185 static const directive dtable[] =
187 DIRECTIVE_TABLE
189 #undef D
190 #undef DIRECTIVE_TABLE
192 /* Wrapper struct directive for linemarkers.
193 The origin is more or less true - the original K+R cpp
194 did use this notation in its preprocessed output. */
195 static const directive linemarker_dir =
197 do_linemarker, UC"#", 1, KANDR, IN_I
200 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
202 /* Skip any remaining tokens in a directive. */
203 static void
204 skip_rest_of_line (cpp_reader *pfile)
206 /* Discard all stacked contexts. */
207 while (pfile->context->prev)
208 _cpp_pop_context (pfile);
210 /* Sweep up all tokens remaining on the line. */
211 if (! SEEN_EOL ())
212 while (_cpp_lex_token (pfile)->type != CPP_EOF)
216 /* Helper function for check_oel. */
218 static void
219 check_eol_1 (cpp_reader *pfile, bool expand, int reason)
221 if (! SEEN_EOL () && (expand
222 ? cpp_get_token (pfile)
223 : _cpp_lex_token (pfile))->type != CPP_EOF)
224 cpp_pedwarning (pfile, reason, "extra tokens at end of #%s directive",
225 pfile->directive->name);
228 /* Variant of check_eol used for Wendif-labels warnings. */
230 static void
231 check_eol_endif_labels (cpp_reader *pfile)
233 check_eol_1 (pfile, false, CPP_W_ENDIF_LABELS);
236 /* Ensure there are no stray tokens at the end of a directive. If
237 EXPAND is true, tokens macro-expanding to nothing are allowed. */
239 static void
240 check_eol (cpp_reader *pfile, bool expand)
242 check_eol_1 (pfile, expand, CPP_W_NONE);
245 /* Ensure there are no stray tokens other than comments at the end of
246 a directive, and gather the comments. */
247 static const cpp_token **
248 check_eol_return_comments (cpp_reader *pfile)
250 size_t c;
251 size_t capacity = 8;
252 const cpp_token **buf;
254 buf = XNEWVEC (const cpp_token *, capacity);
255 c = 0;
256 if (! SEEN_EOL ())
258 while (1)
260 const cpp_token *tok;
262 tok = _cpp_lex_token (pfile);
263 if (tok->type == CPP_EOF)
264 break;
265 if (tok->type != CPP_COMMENT)
266 cpp_error (pfile, CPP_DL_PEDWARN,
267 "extra tokens at end of #%s directive",
268 pfile->directive->name);
269 else
271 if (c + 1 >= capacity)
273 capacity *= 2;
274 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
276 buf[c] = tok;
277 ++c;
281 buf[c] = NULL;
282 return buf;
285 /* Called when entering a directive, _Pragma or command-line directive. */
286 static void
287 start_directive (cpp_reader *pfile)
289 /* Setup in-directive state. */
290 pfile->state.in_directive = 1;
291 pfile->state.save_comments = 0;
292 pfile->directive_result.type = CPP_PADDING;
294 /* Some handlers need the position of the # for diagnostics. */
295 pfile->directive_line = pfile->line_table->highest_line;
298 /* Called when leaving a directive, _Pragma or command-line directive. */
299 static void
300 end_directive (cpp_reader *pfile, int skip_line)
302 if (CPP_OPTION (pfile, traditional))
304 /* Revert change of prepare_directive_trad. */
305 if (!pfile->state.in_deferred_pragma)
306 pfile->state.prevent_expansion--;
308 if (pfile->directive != &dtable[T_DEFINE])
309 _cpp_remove_overlay (pfile);
311 else if (pfile->state.in_deferred_pragma)
313 /* We don't skip for an assembler #. */
314 else if (skip_line)
316 skip_rest_of_line (pfile);
317 if (!pfile->keep_tokens)
319 pfile->cur_run = &pfile->base_run;
320 pfile->cur_token = pfile->base_run.base;
324 /* Restore state. */
325 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
326 pfile->state.in_directive = 0;
327 pfile->state.in_expression = 0;
328 pfile->state.angled_headers = 0;
329 pfile->directive = 0;
332 /* Prepare to handle the directive in pfile->directive. */
333 static void
334 prepare_directive_trad (cpp_reader *pfile)
336 if (pfile->directive != &dtable[T_DEFINE])
338 bool no_expand = (pfile->directive
339 && ! (pfile->directive->flags & EXPAND));
340 bool was_skipping = pfile->state.skipping;
342 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
343 || pfile->directive == &dtable[T_ELIF]);
344 if (pfile->state.in_expression)
345 pfile->state.skipping = false;
347 if (no_expand)
348 pfile->state.prevent_expansion++;
349 _cpp_scan_out_logical_line (pfile, NULL, false);
350 if (no_expand)
351 pfile->state.prevent_expansion--;
353 pfile->state.skipping = was_skipping;
354 _cpp_overlay_buffer (pfile, pfile->out.base,
355 pfile->out.cur - pfile->out.base);
358 /* Stop ISO C from expanding anything. */
359 pfile->state.prevent_expansion++;
362 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
363 the '#' was indented. */
364 static void
365 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
367 /* Issue -pedantic or deprecated warnings for extensions. We let
368 -pedantic take precedence if both are applicable. */
369 if (! pfile->state.skipping)
371 if (dir->origin == EXTENSION
372 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
373 && CPP_PEDANTIC (pfile))
374 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
375 else if (((dir->flags & DEPRECATED) != 0
376 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
377 && CPP_OPTION (pfile, cpp_warn_deprecated))
378 cpp_warning (pfile, CPP_W_DEPRECATED,
379 "#%s is a deprecated GCC extension", dir->name);
382 /* Traditionally, a directive is ignored unless its # is in
383 column 1. Therefore in code intended to work with K+R
384 compilers, directives added by C89 must have their #
385 indented, and directives present in traditional C must not.
386 This is true even of directives in skipped conditional
387 blocks. #elif cannot be used at all. */
388 if (CPP_WTRADITIONAL (pfile))
390 if (dir == &dtable[T_ELIF])
391 cpp_warning (pfile, CPP_W_TRADITIONAL,
392 "suggest not using #elif in traditional C");
393 else if (indented && dir->origin == KANDR)
394 cpp_warning (pfile, CPP_W_TRADITIONAL,
395 "traditional C ignores #%s with the # indented",
396 dir->name);
397 else if (!indented && dir->origin != KANDR)
398 cpp_warning (pfile, CPP_W_TRADITIONAL,
399 "suggest hiding #%s from traditional C with an indented #",
400 dir->name);
404 /* Check if we have a known directive. INDENTED is nonzero if the
405 '#' of the directive was indented. This function is in this file
406 to save unnecessarily exporting dtable etc. to lex.c. Returns
407 nonzero if the line of tokens has been handled, zero if we should
408 continue processing the line. */
410 _cpp_handle_directive (cpp_reader *pfile, int indented)
412 const directive *dir = 0;
413 const cpp_token *dname;
414 bool was_parsing_args = pfile->state.parsing_args;
415 bool was_discarding_output = pfile->state.discarding_output;
416 int skip = 1;
418 if (was_discarding_output)
419 pfile->state.prevent_expansion = 0;
421 if (was_parsing_args)
423 if (CPP_OPTION (pfile, cpp_pedantic))
424 cpp_error (pfile, CPP_DL_PEDWARN,
425 "embedding a directive within macro arguments is not portable");
426 pfile->state.parsing_args = 0;
427 pfile->state.prevent_expansion = 0;
429 start_directive (pfile);
430 dname = _cpp_lex_token (pfile);
432 if (dname->type == CPP_NAME)
434 if (dname->val.node.node->is_directive)
435 dir = &dtable[dname->val.node.node->directive_index];
437 /* We do not recognize the # followed by a number extension in
438 assembler code. */
439 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
441 dir = &linemarker_dir;
442 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
443 && ! pfile->state.skipping)
444 cpp_error (pfile, CPP_DL_PEDWARN,
445 "style of line directive is a GCC extension");
448 if (dir)
450 /* If we have a directive that is not an opening conditional,
451 invalidate any control macro. */
452 if (! (dir->flags & IF_COND))
453 pfile->mi_valid = false;
455 /* Kluge alert. In order to be sure that code like this
457 #define HASH #
458 HASH define foo bar
460 does not cause '#define foo bar' to get executed when
461 compiled with -save-temps, we recognize directives in
462 -fpreprocessed mode only if the # is in column 1. macro.c
463 puts a space in front of any '#' at the start of a macro.
465 We exclude the -fdirectives-only case because macro expansion
466 has not been performed yet, and block comments can cause spaces
467 to precede the directive. */
468 if (CPP_OPTION (pfile, preprocessed)
469 && !CPP_OPTION (pfile, directives_only)
470 && (indented || !(dir->flags & IN_I)))
472 skip = 0;
473 dir = 0;
475 else
477 /* In failed conditional groups, all non-conditional
478 directives are ignored. Before doing that, whether
479 skipping or not, we should lex angle-bracketed headers
480 correctly, and maybe output some diagnostics. */
481 pfile->state.angled_headers = dir->flags & INCL;
482 pfile->state.directive_wants_padding = dir->flags & INCL;
483 if (! CPP_OPTION (pfile, preprocessed))
484 directive_diagnostics (pfile, dir, indented);
485 if (pfile->state.skipping && !(dir->flags & COND))
486 dir = 0;
489 else if (dname->type == CPP_EOF)
490 ; /* CPP_EOF is the "null directive". */
491 else
493 /* An unknown directive. Don't complain about it in assembly
494 source: we don't know where the comments are, and # may
495 introduce assembler pseudo-ops. Don't complain about invalid
496 directives in skipped conditional groups (6.10 p4). */
497 if (CPP_OPTION (pfile, lang) == CLK_ASM)
498 skip = 0;
499 else if (!pfile->state.skipping)
500 cpp_error (pfile, CPP_DL_ERROR, "invalid preprocessing directive #%s",
501 cpp_token_as_text (pfile, dname));
504 pfile->directive = dir;
505 if (CPP_OPTION (pfile, traditional))
506 prepare_directive_trad (pfile);
508 if (dir)
509 pfile->directive->handler (pfile);
510 else if (skip == 0)
511 _cpp_backup_tokens (pfile, 1);
513 end_directive (pfile, skip);
514 if (was_parsing_args && !pfile->state.in_deferred_pragma)
516 /* Restore state when within macro args. */
517 pfile->state.parsing_args = 2;
518 pfile->state.prevent_expansion = 1;
520 if (was_discarding_output)
521 pfile->state.prevent_expansion = 1;
522 return skip;
525 /* Directive handler wrapper used by the command line option
526 processor. BUF is \n terminated. */
527 static void
528 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
530 cpp_push_buffer (pfile, (const uchar *) buf, count,
531 /* from_stage3 */ true);
532 start_directive (pfile);
534 /* This is a short-term fix to prevent a leading '#' being
535 interpreted as a directive. */
536 _cpp_clean_line (pfile);
538 pfile->directive = &dtable[dir_no];
539 if (CPP_OPTION (pfile, traditional))
540 prepare_directive_trad (pfile);
541 pfile->directive->handler (pfile);
542 end_directive (pfile, 1);
543 _cpp_pop_buffer (pfile);
546 /* Checks for validity the macro name in #define, #undef, #ifdef and
547 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
548 processing a #define or #undefine directive, and false
549 otherwise. */
550 static cpp_hashnode *
551 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
553 const cpp_token *token = _cpp_lex_token (pfile);
555 /* The token immediately after #define must be an identifier. That
556 identifier may not be "defined", per C99 6.10.8p4.
557 In C++, it may not be any of the "named operators" either,
558 per C++98 [lex.digraph], [lex.key].
559 Finally, the identifier may not have been poisoned. (In that case
560 the lexer has issued the error message for us.) */
562 if (token->type == CPP_NAME)
564 cpp_hashnode *node = token->val.node.node;
566 if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
567 cpp_error (pfile, CPP_DL_ERROR,
568 "\"defined\" cannot be used as a macro name");
569 else if (is_def_or_undef
570 && (node == pfile->spec_nodes.n__has_include__
571 || node == pfile->spec_nodes.n__has_include_next__))
572 cpp_error (pfile, CPP_DL_ERROR,
573 "\"__has_include__\" cannot be used as a macro name");
574 else if (! (node->flags & NODE_POISONED))
575 return node;
577 else if (token->flags & NAMED_OP)
578 cpp_error (pfile, CPP_DL_ERROR,
579 "\"%s\" cannot be used as a macro name as it is an operator in C++",
580 NODE_NAME (token->val.node.node));
581 else if (token->type == CPP_EOF)
582 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
583 pfile->directive->name);
584 else
585 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
587 return NULL;
590 /* Process a #define directive. Most work is done in macro.c. */
591 static void
592 do_define (cpp_reader *pfile)
594 cpp_hashnode *node = lex_macro_node (pfile, true);
596 if (node)
598 /* If we have been requested to expand comments into macros,
599 then re-enable saving of comments. */
600 pfile->state.save_comments =
601 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
603 if (pfile->cb.before_define)
604 pfile->cb.before_define (pfile);
606 if (_cpp_create_definition (pfile, node))
607 if (pfile->cb.define)
608 pfile->cb.define (pfile, pfile->directive_line, node);
610 node->flags &= ~NODE_USED;
614 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
615 static void
616 do_undef (cpp_reader *pfile)
618 cpp_hashnode *node = lex_macro_node (pfile, true);
620 if (node)
622 if (pfile->cb.before_define)
623 pfile->cb.before_define (pfile);
625 if (pfile->cb.undef)
626 pfile->cb.undef (pfile, pfile->directive_line, node);
628 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
629 identifier is not currently defined as a macro name. */
630 if (node->type == NT_MACRO)
632 if (node->flags & NODE_WARN)
633 cpp_error (pfile, CPP_DL_WARNING,
634 "undefining \"%s\"", NODE_NAME (node));
635 else if ((node->flags & NODE_BUILTIN)
636 && CPP_OPTION (pfile, warn_builtin_macro_redefined))
637 cpp_warning_with_line (pfile, CPP_W_BUILTIN_MACRO_REDEFINED,
638 pfile->directive_line, 0,
639 "undefining \"%s\"", NODE_NAME (node));
641 if (CPP_OPTION (pfile, warn_unused_macros))
642 _cpp_warn_if_unused_macro (pfile, node, NULL);
644 _cpp_free_definition (node);
648 check_eol (pfile, false);
651 /* Undefine a single macro/assertion/whatever. */
653 static int
654 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
655 void *data_p ATTRIBUTE_UNUSED)
657 /* Body of _cpp_free_definition inlined here for speed.
658 Macros and assertions no longer have anything to free. */
659 h->type = NT_VOID;
660 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
661 return 1;
664 /* Undefine all macros and assertions. */
666 void
667 cpp_undef_all (cpp_reader *pfile)
669 cpp_forall_identifiers (pfile, undefine_macros, NULL);
673 /* Helper routine used by parse_include. Reinterpret the current line
674 as an h-char-sequence (< ... >); we are looking at the first token
675 after the <. Returns a malloced filename. */
676 static char *
677 glue_header_name (cpp_reader *pfile)
679 const cpp_token *token;
680 char *buffer;
681 size_t len, total_len = 0, capacity = 1024;
683 /* To avoid lexed tokens overwriting our glued name, we can only
684 allocate from the string pool once we've lexed everything. */
685 buffer = XNEWVEC (char, capacity);
686 for (;;)
688 token = get_token_no_padding (pfile);
690 if (token->type == CPP_GREATER)
691 break;
692 if (token->type == CPP_EOF)
694 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
695 break;
698 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
699 if (total_len + len > capacity)
701 capacity = (capacity + len) * 2;
702 buffer = XRESIZEVEC (char, buffer, capacity);
705 if (token->flags & PREV_WHITE)
706 buffer[total_len++] = ' ';
708 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
709 true)
710 - (uchar *) buffer);
713 buffer[total_len] = '\0';
714 return buffer;
717 /* Returns the file name of #include, #include_next, #import and
718 #pragma dependency. The string is malloced and the caller should
719 free it. Returns NULL on error. LOCATION is the source location
720 of the file name. */
722 static const char *
723 parse_include (cpp_reader *pfile, int *pangle_brackets,
724 const cpp_token ***buf, source_location *location)
726 char *fname;
727 const cpp_token *header;
729 /* Allow macro expansion. */
730 header = get_token_no_padding (pfile);
731 *location = header->src_loc;
732 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
733 || header->type == CPP_HEADER_NAME)
735 fname = XNEWVEC (char, header->val.str.len - 1);
736 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
737 fname[header->val.str.len - 2] = '\0';
738 *pangle_brackets = header->type == CPP_HEADER_NAME;
740 else if (header->type == CPP_LESS)
742 fname = glue_header_name (pfile);
743 *pangle_brackets = 1;
745 else
747 const unsigned char *dir;
749 if (pfile->directive == &dtable[T_PRAGMA])
750 dir = UC"pragma dependency";
751 else
752 dir = pfile->directive->name;
753 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
754 dir);
756 return NULL;
759 if (pfile->directive == &dtable[T_PRAGMA])
761 /* This pragma allows extra tokens after the file name. */
763 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
764 check_eol (pfile, true);
765 else
767 /* If we are not discarding comments, then gather them while
768 doing the eol check. */
769 *buf = check_eol_return_comments (pfile);
772 return fname;
775 /* Handle #include, #include_next and #import. */
776 static void
777 do_include_common (cpp_reader *pfile, enum include_type type)
779 const char *fname;
780 int angle_brackets;
781 const cpp_token **buf = NULL;
782 source_location location;
784 /* Re-enable saving of comments if requested, so that the include
785 callback can dump comments which follow #include. */
786 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
788 fname = parse_include (pfile, &angle_brackets, &buf, &location);
789 if (!fname)
791 if (buf)
792 XDELETEVEC (buf);
793 return;
796 if (!*fname)
798 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
799 "empty filename in #%s",
800 pfile->directive->name);
801 XDELETEVEC (fname);
802 if (buf)
803 XDELETEVEC (buf);
804 return;
807 /* Prevent #include recursion. */
808 if (pfile->line_table->depth >= CPP_STACK_MAX)
809 cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
810 else
812 /* Get out of macro context, if we are. */
813 skip_rest_of_line (pfile);
815 if (pfile->cb.include)
816 pfile->cb.include (pfile, pfile->directive_line,
817 pfile->directive->name, fname, angle_brackets,
818 buf);
820 _cpp_stack_include (pfile, fname, angle_brackets, type);
823 XDELETEVEC (fname);
824 if (buf)
825 XDELETEVEC (buf);
828 static void
829 do_include (cpp_reader *pfile)
831 do_include_common (pfile, IT_INCLUDE);
834 static void
835 do_import (cpp_reader *pfile)
837 do_include_common (pfile, IT_IMPORT);
840 static void
841 do_include_next (cpp_reader *pfile)
843 enum include_type type = IT_INCLUDE_NEXT;
845 /* If this is the primary source file, warn and use the normal
846 search logic. */
847 if (cpp_in_primary_file (pfile))
849 cpp_error (pfile, CPP_DL_WARNING,
850 "#include_next in primary source file");
851 type = IT_INCLUDE;
853 do_include_common (pfile, type);
856 /* Subroutine of do_linemarker. Read possible flags after file name.
857 LAST is the last flag seen; 0 if this is the first flag. Return the
858 flag if it is valid, 0 at the end of the directive. Otherwise
859 complain. */
860 static unsigned int
861 read_flag (cpp_reader *pfile, unsigned int last)
863 const cpp_token *token = _cpp_lex_token (pfile);
865 if (token->type == CPP_NUMBER && token->val.str.len == 1)
867 unsigned int flag = token->val.str.text[0] - '0';
869 if (flag > last && flag <= 4
870 && (flag != 4 || last == 3)
871 && (flag != 2 || last == 0))
872 return flag;
875 if (token->type != CPP_EOF)
876 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
877 cpp_token_as_text (pfile, token));
878 return 0;
881 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
882 of length LEN, to binary; store it in NUMP, and return false if the
883 number was well-formed, true if not. WRAPPED is set to true if the
884 number did not fit into 'unsigned long'. */
885 static bool
886 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
888 linenum_type reg = 0;
889 linenum_type reg_prev = 0;
891 uchar c;
892 *wrapped = false;
893 while (len--)
895 c = *str++;
896 if (!ISDIGIT (c))
897 return true;
898 reg *= 10;
899 reg += c - '0';
900 if (reg < reg_prev)
901 *wrapped = true;
902 reg_prev = reg;
904 *nump = reg;
905 return false;
908 /* Interpret #line command.
909 Note that the filename string (if any) is a true string constant
910 (escapes are interpreted), unlike in #line. */
911 static void
912 do_line (cpp_reader *pfile)
914 struct line_maps *line_table = pfile->line_table;
915 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
917 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
918 sysp right now. */
920 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
921 const cpp_token *token;
922 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
923 linenum_type new_lineno;
925 /* C99 raised the minimum limit on #line numbers. */
926 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
927 bool wrapped;
929 /* #line commands expand macros. */
930 token = cpp_get_token (pfile);
931 if (token->type != CPP_NUMBER
932 || strtolinenum (token->val.str.text, token->val.str.len,
933 &new_lineno, &wrapped))
935 if (token->type == CPP_EOF)
936 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
937 else
938 cpp_error (pfile, CPP_DL_ERROR,
939 "\"%s\" after #line is not a positive integer",
940 cpp_token_as_text (pfile, token));
941 return;
944 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
945 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
946 else if (wrapped)
947 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
949 token = cpp_get_token (pfile);
950 if (token->type == CPP_STRING)
952 cpp_string s = { 0, 0 };
953 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
954 &s, CPP_STRING))
955 new_file = (const char *)s.text;
956 check_eol (pfile, true);
958 else if (token->type != CPP_EOF)
960 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
961 cpp_token_as_text (pfile, token));
962 return;
965 skip_rest_of_line (pfile);
966 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
967 map_sysp);
968 line_table->seen_line_directive = true;
971 /* Interpret the # 44 "file" [flags] notation, which has slightly
972 different syntax and semantics from #line: Flags are allowed,
973 and we never complain about the line number being too big. */
974 static void
975 do_linemarker (cpp_reader *pfile)
977 struct line_maps *line_table = pfile->line_table;
978 const line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
979 const cpp_token *token;
980 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
981 linenum_type new_lineno;
982 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
983 enum lc_reason reason = LC_RENAME_VERBATIM;
984 int flag;
985 bool wrapped;
987 /* Back up so we can get the number again. Putting this in
988 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
989 some circumstances, which can segfault. */
990 _cpp_backup_tokens (pfile, 1);
992 /* #line commands expand macros. */
993 token = cpp_get_token (pfile);
994 if (token->type != CPP_NUMBER
995 || strtolinenum (token->val.str.text, token->val.str.len,
996 &new_lineno, &wrapped))
998 /* Unlike #line, there does not seem to be a way to get an EOF
999 here. So, it should be safe to always spell the token. */
1000 cpp_error (pfile, CPP_DL_ERROR,
1001 "\"%s\" after # is not a positive integer",
1002 cpp_token_as_text (pfile, token));
1003 return;
1006 token = cpp_get_token (pfile);
1007 if (token->type == CPP_STRING)
1009 cpp_string s = { 0, 0 };
1010 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
1011 1, &s, CPP_STRING))
1012 new_file = (const char *)s.text;
1014 new_sysp = 0;
1015 flag = read_flag (pfile, 0);
1016 if (flag == 1)
1018 reason = LC_ENTER;
1019 /* Fake an include for cpp_included (). */
1020 _cpp_fake_include (pfile, new_file);
1021 flag = read_flag (pfile, flag);
1023 else if (flag == 2)
1025 reason = LC_LEAVE;
1026 flag = read_flag (pfile, flag);
1028 if (flag == 3)
1030 new_sysp = 1;
1031 flag = read_flag (pfile, flag);
1032 if (flag == 4)
1033 new_sysp = 2;
1035 pfile->buffer->sysp = new_sysp;
1037 check_eol (pfile, false);
1039 else if (token->type != CPP_EOF)
1041 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1042 cpp_token_as_text (pfile, token));
1043 return;
1046 skip_rest_of_line (pfile);
1048 /* Compensate for the increment in linemap_add that occurs in
1049 _cpp_do_file_change. We're currently at the start of the line
1050 *following* the #line directive. A separate source_location for this
1051 location makes no sense (until we do the LC_LEAVE), and
1052 complicates LAST_SOURCE_LINE_LOCATION. */
1053 pfile->line_table->highest_location--;
1055 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1056 line_table->seen_line_directive = true;
1059 /* Arrange the file_change callback. pfile->line has changed to
1060 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
1061 header, 2 for a system header that needs to be extern "C" protected,
1062 and zero otherwise. */
1063 void
1064 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1065 const char *to_file, linenum_type file_line,
1066 unsigned int sysp)
1068 linemap_assert (reason != LC_ENTER_MACRO);
1069 const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1070 to_file, file_line);
1071 const line_map_ordinary *ord_map = NULL;
1072 if (map != NULL)
1074 ord_map = linemap_check_ordinary (map);
1075 linemap_line_start (pfile->line_table,
1076 ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map),
1077 127);
1080 if (pfile->cb.file_change)
1081 pfile->cb.file_change (pfile, ord_map);
1084 /* Report a warning or error detected by the program we are
1085 processing. Use the directive's tokens in the error message. */
1086 static void
1087 do_diagnostic (cpp_reader *pfile, int code, int reason, int print_dir)
1089 const unsigned char *dir_name;
1090 unsigned char *line;
1091 source_location src_loc = pfile->cur_token[-1].src_loc;
1093 if (print_dir)
1094 dir_name = pfile->directive->name;
1095 else
1096 dir_name = NULL;
1097 pfile->state.prevent_expansion++;
1098 line = cpp_output_line_to_string (pfile, dir_name);
1099 pfile->state.prevent_expansion--;
1101 if (code == CPP_DL_WARNING_SYSHDR && reason)
1102 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1103 else if (code == CPP_DL_WARNING && reason)
1104 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1105 else
1106 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1107 free (line);
1110 static void
1111 do_error (cpp_reader *pfile)
1113 do_diagnostic (pfile, CPP_DL_ERROR, 0, 1);
1116 static void
1117 do_warning (cpp_reader *pfile)
1119 /* We want #warning diagnostics to be emitted in system headers too. */
1120 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1123 /* Report program identification. */
1124 static void
1125 do_ident (cpp_reader *pfile)
1127 const cpp_token *str = cpp_get_token (pfile);
1129 if (str->type != CPP_STRING)
1130 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1131 pfile->directive->name);
1132 else if (pfile->cb.ident)
1133 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1135 check_eol (pfile, false);
1138 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1139 matching entry, or NULL if none is found. The returned entry could
1140 be the start of a namespace chain, or a pragma. */
1141 static struct pragma_entry *
1142 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1144 while (chain && chain->pragma != pragma)
1145 chain = chain->next;
1147 return chain;
1150 /* Create and insert a blank pragma entry at the beginning of a
1151 singly-linked CHAIN. */
1152 static struct pragma_entry *
1153 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1155 struct pragma_entry *new_entry;
1157 new_entry = (struct pragma_entry *)
1158 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1160 memset (new_entry, 0, sizeof (struct pragma_entry));
1161 new_entry->next = *chain;
1163 *chain = new_entry;
1164 return new_entry;
1167 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1168 goes in the global namespace. */
1169 static struct pragma_entry *
1170 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1171 bool allow_name_expansion)
1173 struct pragma_entry **chain = &pfile->pragmas;
1174 struct pragma_entry *entry;
1175 const cpp_hashnode *node;
1177 if (space)
1179 node = cpp_lookup (pfile, UC space, strlen (space));
1180 entry = lookup_pragma_entry (*chain, node);
1181 if (!entry)
1183 entry = new_pragma_entry (pfile, chain);
1184 entry->pragma = node;
1185 entry->is_nspace = true;
1186 entry->allow_expansion = allow_name_expansion;
1188 else if (!entry->is_nspace)
1189 goto clash;
1190 else if (entry->allow_expansion != allow_name_expansion)
1192 cpp_error (pfile, CPP_DL_ICE,
1193 "registering pragmas in namespace \"%s\" with mismatched "
1194 "name expansion", space);
1195 return NULL;
1197 chain = &entry->u.space;
1199 else if (allow_name_expansion)
1201 cpp_error (pfile, CPP_DL_ICE,
1202 "registering pragma \"%s\" with name expansion "
1203 "and no namespace", name);
1204 return NULL;
1207 /* Check for duplicates. */
1208 node = cpp_lookup (pfile, UC name, strlen (name));
1209 entry = lookup_pragma_entry (*chain, node);
1210 if (entry == NULL)
1212 entry = new_pragma_entry (pfile, chain);
1213 entry->pragma = node;
1214 return entry;
1217 if (entry->is_nspace)
1218 clash:
1219 cpp_error (pfile, CPP_DL_ICE,
1220 "registering \"%s\" as both a pragma and a pragma namespace",
1221 NODE_NAME (node));
1222 else if (space)
1223 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1224 space, name);
1225 else
1226 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1228 return NULL;
1231 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1232 static void
1233 register_pragma_internal (cpp_reader *pfile, const char *space,
1234 const char *name, pragma_cb handler)
1236 struct pragma_entry *entry;
1238 entry = register_pragma_1 (pfile, space, name, false);
1239 entry->is_internal = true;
1240 entry->u.handler = handler;
1243 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1244 goes in the global namespace. HANDLER is the handler it will call,
1245 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1246 expansion while parsing pragma NAME. This function is exported
1247 from libcpp. */
1248 void
1249 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1250 pragma_cb handler, bool allow_expansion)
1252 struct pragma_entry *entry;
1254 if (!handler)
1256 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1257 return;
1260 entry = register_pragma_1 (pfile, space, name, false);
1261 if (entry)
1263 entry->allow_expansion = allow_expansion;
1264 entry->u.handler = handler;
1268 /* Similarly, but create mark the pragma for deferred processing.
1269 When found, a CPP_PRAGMA token will be insertted into the stream
1270 with IDENT in the token->u.pragma slot. */
1271 void
1272 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1273 const char *name, unsigned int ident,
1274 bool allow_expansion, bool allow_name_expansion)
1276 struct pragma_entry *entry;
1278 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1279 if (entry)
1281 entry->is_deferred = true;
1282 entry->allow_expansion = allow_expansion;
1283 entry->u.ident = ident;
1287 /* Register the pragmas the preprocessor itself handles. */
1288 void
1289 _cpp_init_internal_pragmas (cpp_reader *pfile)
1291 /* Pragmas in the global namespace. */
1292 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1293 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1294 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1296 /* New GCC-specific pragmas should be put in the GCC namespace. */
1297 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1298 register_pragma_internal (pfile, "GCC", "system_header",
1299 do_pragma_system_header);
1300 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1301 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1302 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1305 /* Return the number of registered pragmas in PE. */
1307 static int
1308 count_registered_pragmas (struct pragma_entry *pe)
1310 int ct = 0;
1311 for (; pe != NULL; pe = pe->next)
1313 if (pe->is_nspace)
1314 ct += count_registered_pragmas (pe->u.space);
1315 ct++;
1317 return ct;
1320 /* Save into SD the names of the registered pragmas referenced by PE,
1321 and return a pointer to the next free space in SD. */
1323 static char **
1324 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1326 for (; pe != NULL; pe = pe->next)
1328 if (pe->is_nspace)
1329 sd = save_registered_pragmas (pe->u.space, sd);
1330 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1331 HT_LEN (&pe->pragma->ident),
1332 HT_LEN (&pe->pragma->ident) + 1);
1334 return sd;
1337 /* Return a newly-allocated array which saves the names of the
1338 registered pragmas. */
1340 char **
1341 _cpp_save_pragma_names (cpp_reader *pfile)
1343 int ct = count_registered_pragmas (pfile->pragmas);
1344 char **result = XNEWVEC (char *, ct);
1345 (void) save_registered_pragmas (pfile->pragmas, result);
1346 return result;
1349 /* Restore from SD the names of the registered pragmas referenced by PE,
1350 and return a pointer to the next unused name in SD. */
1352 static char **
1353 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1354 char **sd)
1356 for (; pe != NULL; pe = pe->next)
1358 if (pe->is_nspace)
1359 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1360 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1361 free (*sd);
1362 sd++;
1364 return sd;
1367 /* Restore the names of the registered pragmas from SAVED. */
1369 void
1370 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1372 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1373 free (saved);
1376 /* Pragmata handling. We handle some, and pass the rest on to the
1377 front end. C99 defines three pragmas and says that no macro
1378 expansion is to be performed on them; whether or not macro
1379 expansion happens for other pragmas is implementation defined.
1380 This implementation allows for a mix of both, since GCC did not
1381 traditionally macro expand its (few) pragmas, whereas OpenMP
1382 specifies that macro expansion should happen. */
1383 static void
1384 do_pragma (cpp_reader *pfile)
1386 const struct pragma_entry *p = NULL;
1387 const cpp_token *token, *pragma_token;
1388 source_location pragma_token_virt_loc = 0;
1389 cpp_token ns_token;
1390 unsigned int count = 1;
1392 pfile->state.prevent_expansion++;
1394 pragma_token = token = cpp_get_token_with_location (pfile,
1395 &pragma_token_virt_loc);
1396 ns_token = *token;
1397 if (token->type == CPP_NAME)
1399 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1400 if (p && p->is_nspace)
1402 bool allow_name_expansion = p->allow_expansion;
1403 if (allow_name_expansion)
1404 pfile->state.prevent_expansion--;
1406 token = cpp_get_token (pfile);
1407 if (token->type == CPP_NAME)
1408 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1409 else
1410 p = NULL;
1411 if (allow_name_expansion)
1412 pfile->state.prevent_expansion++;
1413 count = 2;
1417 if (p)
1419 if (p->is_deferred)
1421 pfile->directive_result.src_loc = pragma_token_virt_loc;
1422 pfile->directive_result.type = CPP_PRAGMA;
1423 pfile->directive_result.flags = pragma_token->flags;
1424 pfile->directive_result.val.pragma = p->u.ident;
1425 pfile->state.in_deferred_pragma = true;
1426 pfile->state.pragma_allow_expansion = p->allow_expansion;
1427 if (!p->allow_expansion)
1428 pfile->state.prevent_expansion++;
1430 else
1432 /* Since the handler below doesn't get the line number, that
1433 it might need for diagnostics, make sure it has the right
1434 numbers in place. */
1435 if (pfile->cb.line_change)
1436 (*pfile->cb.line_change) (pfile, pragma_token, false);
1437 if (p->allow_expansion)
1438 pfile->state.prevent_expansion--;
1439 (*p->u.handler) (pfile);
1440 if (p->allow_expansion)
1441 pfile->state.prevent_expansion++;
1444 else if (pfile->cb.def_pragma)
1446 if (count == 1 || pfile->context->prev == NULL)
1447 _cpp_backup_tokens (pfile, count);
1448 else
1450 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1451 won't allow backing 2 tokens. */
1452 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1453 reads both tokens, we could perhaps free it, but if it doesn't,
1454 we don't know the exact lifespan. */
1455 cpp_token *toks = XNEWVEC (cpp_token, 2);
1456 toks[0] = ns_token;
1457 toks[0].flags |= NO_EXPAND;
1458 toks[1] = *token;
1459 toks[1].flags |= NO_EXPAND;
1460 _cpp_push_token_context (pfile, NULL, toks, 2);
1462 pfile->cb.def_pragma (pfile, pfile->directive_line);
1465 pfile->state.prevent_expansion--;
1468 /* Handle #pragma once. */
1469 static void
1470 do_pragma_once (cpp_reader *pfile)
1472 if (cpp_in_primary_file (pfile))
1473 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1475 check_eol (pfile, false);
1476 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1479 /* Handle #pragma push_macro(STRING). */
1480 static void
1481 do_pragma_push_macro (cpp_reader *pfile)
1483 cpp_hashnode *node;
1484 size_t defnlen;
1485 const uchar *defn = NULL;
1486 char *macroname, *dest;
1487 const char *limit, *src;
1488 const cpp_token *txt;
1489 struct def_pragma_macro *c;
1491 txt = get__Pragma_string (pfile);
1492 if (!txt)
1494 source_location src_loc = pfile->cur_token[-1].src_loc;
1495 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1496 "invalid #pragma push_macro directive");
1497 check_eol (pfile, false);
1498 skip_rest_of_line (pfile);
1499 return;
1501 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1502 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1503 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1504 while (src < limit)
1506 /* We know there is a character following the backslash. */
1507 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1508 src++;
1509 *dest++ = *src++;
1511 *dest = 0;
1512 check_eol (pfile, false);
1513 skip_rest_of_line (pfile);
1514 c = XNEW (struct def_pragma_macro);
1515 memset (c, 0, sizeof (struct def_pragma_macro));
1516 c->name = XNEWVAR (char, strlen (macroname) + 1);
1517 strcpy (c->name, macroname);
1518 c->next = pfile->pushed_macros;
1519 node = _cpp_lex_identifier (pfile, c->name);
1520 if (node->type == NT_VOID)
1521 c->is_undef = 1;
1522 else
1524 defn = cpp_macro_definition (pfile, node);
1525 defnlen = ustrlen (defn);
1526 c->definition = XNEWVEC (uchar, defnlen + 2);
1527 c->definition[defnlen] = '\n';
1528 c->definition[defnlen + 1] = 0;
1529 c->line = node->value.macro->line;
1530 c->syshdr = node->value.macro->syshdr;
1531 c->used = node->value.macro->used;
1532 memcpy (c->definition, defn, defnlen);
1535 pfile->pushed_macros = c;
1538 /* Handle #pragma pop_macro(STRING). */
1539 static void
1540 do_pragma_pop_macro (cpp_reader *pfile)
1542 char *macroname, *dest;
1543 const char *limit, *src;
1544 const cpp_token *txt;
1545 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1546 txt = get__Pragma_string (pfile);
1547 if (!txt)
1549 source_location src_loc = pfile->cur_token[-1].src_loc;
1550 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1551 "invalid #pragma pop_macro directive");
1552 check_eol (pfile, false);
1553 skip_rest_of_line (pfile);
1554 return;
1556 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1557 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1558 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1559 while (src < limit)
1561 /* We know there is a character following the backslash. */
1562 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1563 src++;
1564 *dest++ = *src++;
1566 *dest = 0;
1567 check_eol (pfile, false);
1568 skip_rest_of_line (pfile);
1570 while (c != NULL)
1572 if (!strcmp (c->name, macroname))
1574 if (!l)
1575 pfile->pushed_macros = c->next;
1576 else
1577 l->next = c->next;
1578 cpp_pop_definition (pfile, c);
1579 free (c->definition);
1580 free (c->name);
1581 free (c);
1582 break;
1584 l = c;
1585 c = c->next;
1589 /* Handle #pragma GCC poison, to poison one or more identifiers so
1590 that the lexer produces a hard error for each subsequent usage. */
1591 static void
1592 do_pragma_poison (cpp_reader *pfile)
1594 const cpp_token *tok;
1595 cpp_hashnode *hp;
1597 pfile->state.poisoned_ok = 1;
1598 for (;;)
1600 tok = _cpp_lex_token (pfile);
1601 if (tok->type == CPP_EOF)
1602 break;
1603 if (tok->type != CPP_NAME)
1605 cpp_error (pfile, CPP_DL_ERROR,
1606 "invalid #pragma GCC poison directive");
1607 break;
1610 hp = tok->val.node.node;
1611 if (hp->flags & NODE_POISONED)
1612 continue;
1614 if (hp->type == NT_MACRO)
1615 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1616 NODE_NAME (hp));
1617 _cpp_free_definition (hp);
1618 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1620 pfile->state.poisoned_ok = 0;
1623 /* Mark the current header as a system header. This will suppress
1624 some categories of warnings (notably those from -pedantic). It is
1625 intended for use in system libraries that cannot be implemented in
1626 conforming C, but cannot be certain that their headers appear in a
1627 system include directory. To prevent abuse, it is rejected in the
1628 primary source file. */
1629 static void
1630 do_pragma_system_header (cpp_reader *pfile)
1632 if (cpp_in_primary_file (pfile))
1633 cpp_error (pfile, CPP_DL_WARNING,
1634 "#pragma system_header ignored outside include file");
1635 else
1637 check_eol (pfile, false);
1638 skip_rest_of_line (pfile);
1639 cpp_make_system_header (pfile, 1, 0);
1643 /* Check the modified date of the current include file against a specified
1644 file. Issue a diagnostic, if the specified file is newer. We use this to
1645 determine if a fixed header should be refixed. */
1646 static void
1647 do_pragma_dependency (cpp_reader *pfile)
1649 const char *fname;
1650 int angle_brackets, ordering;
1651 source_location location;
1653 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1654 if (!fname)
1655 return;
1657 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1658 if (ordering < 0)
1659 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1660 else if (ordering > 0)
1662 cpp_error (pfile, CPP_DL_WARNING,
1663 "current file is older than %s", fname);
1664 if (cpp_get_token (pfile)->type != CPP_EOF)
1666 _cpp_backup_tokens (pfile, 1);
1667 do_diagnostic (pfile, CPP_DL_WARNING, 0, 0);
1671 free ((void *) fname);
1674 /* Issue a diagnostic with the message taken from the pragma. If
1675 ERROR is true, the diagnostic is a warning, otherwise, it is an
1676 error. */
1677 static void
1678 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1680 const cpp_token *tok = _cpp_lex_token (pfile);
1681 cpp_string str;
1682 if (tok->type != CPP_STRING
1683 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1684 CPP_STRING)
1685 || str.len == 0)
1687 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1688 error ? "error" : "warning");
1689 return;
1691 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1692 "%s", str.text);
1693 free ((void *)str.text);
1696 /* Issue a warning diagnostic. */
1697 static void
1698 do_pragma_warning (cpp_reader *pfile)
1700 do_pragma_warning_or_error (pfile, false);
1703 /* Issue an error diagnostic. */
1704 static void
1705 do_pragma_error (cpp_reader *pfile)
1707 do_pragma_warning_or_error (pfile, true);
1710 /* Get a token but skip padding. */
1711 static const cpp_token *
1712 get_token_no_padding (cpp_reader *pfile)
1714 for (;;)
1716 const cpp_token *result = cpp_get_token (pfile);
1717 if (result->type != CPP_PADDING)
1718 return result;
1722 /* Check syntax is "(string-literal)". Returns the string on success,
1723 or NULL on failure. */
1724 static const cpp_token *
1725 get__Pragma_string (cpp_reader *pfile)
1727 const cpp_token *string;
1728 const cpp_token *paren;
1730 paren = get_token_no_padding (pfile);
1731 if (paren->type == CPP_EOF)
1732 _cpp_backup_tokens (pfile, 1);
1733 if (paren->type != CPP_OPEN_PAREN)
1734 return NULL;
1736 string = get_token_no_padding (pfile);
1737 if (string->type == CPP_EOF)
1738 _cpp_backup_tokens (pfile, 1);
1739 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1740 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1741 && string->type != CPP_UTF8STRING)
1742 return NULL;
1744 paren = get_token_no_padding (pfile);
1745 if (paren->type == CPP_EOF)
1746 _cpp_backup_tokens (pfile, 1);
1747 if (paren->type != CPP_CLOSE_PAREN)
1748 return NULL;
1750 return string;
1753 /* Destringize IN into a temporary buffer, by removing the first \ of
1754 \" and \\ sequences, and process the result as a #pragma directive. */
1755 static void
1756 destringize_and_run (cpp_reader *pfile, const cpp_string *in)
1758 const unsigned char *src, *limit;
1759 char *dest, *result;
1760 cpp_context *saved_context;
1761 cpp_token *saved_cur_token;
1762 tokenrun *saved_cur_run;
1763 cpp_token *toks;
1764 int count;
1765 const struct directive *save_directive;
1767 dest = result = (char *) alloca (in->len - 1);
1768 src = in->text + 1 + (in->text[0] == 'L');
1769 limit = in->text + in->len - 1;
1770 while (src < limit)
1772 /* We know there is a character following the backslash. */
1773 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1774 src++;
1775 *dest++ = *src++;
1777 *dest = '\n';
1779 /* Ugh; an awful kludge. We are really not set up to be lexing
1780 tokens when in the middle of a macro expansion. Use a new
1781 context to force cpp_get_token to lex, and so skip_rest_of_line
1782 doesn't go beyond the end of the text. Also, remember the
1783 current lexing position so we can return to it later.
1785 Something like line-at-a-time lexing should remove the need for
1786 this. */
1787 saved_context = pfile->context;
1788 saved_cur_token = pfile->cur_token;
1789 saved_cur_run = pfile->cur_run;
1791 pfile->context = XCNEW (cpp_context);
1793 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1794 until we've read all of the tokens that we want. */
1795 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1796 /* from_stage3 */ true);
1797 /* ??? Antique Disgusting Hack. What does this do? */
1798 if (pfile->buffer->prev)
1799 pfile->buffer->file = pfile->buffer->prev->file;
1801 start_directive (pfile);
1802 _cpp_clean_line (pfile);
1803 save_directive = pfile->directive;
1804 pfile->directive = &dtable[T_PRAGMA];
1805 do_pragma (pfile);
1806 end_directive (pfile, 1);
1807 pfile->directive = save_directive;
1809 /* We always insert at least one token, the directive result. It'll
1810 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1811 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1813 /* If we're not handling the pragma internally, read all of the tokens from
1814 the string buffer now, while the string buffer is still installed. */
1815 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1816 to me what the true lifespan of the tokens are. It would appear that
1817 the lifespan is the entire parse of the main input stream, in which case
1818 this may not be wrong. */
1819 if (pfile->directive_result.type == CPP_PRAGMA)
1821 int maxcount;
1823 count = 1;
1824 maxcount = 50;
1825 toks = XNEWVEC (cpp_token, maxcount);
1826 toks[0] = pfile->directive_result;
1830 if (count == maxcount)
1832 maxcount = maxcount * 3 / 2;
1833 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1835 toks[count] = *cpp_get_token (pfile);
1836 /* Macros have been already expanded by cpp_get_token
1837 if the pragma allowed expansion. */
1838 toks[count++].flags |= NO_EXPAND;
1840 while (toks[count-1].type != CPP_PRAGMA_EOL);
1842 else
1844 count = 1;
1845 toks = XNEW (cpp_token);
1846 toks[0] = pfile->directive_result;
1848 /* If we handled the entire pragma internally, make sure we get the
1849 line number correct for the next token. */
1850 if (pfile->cb.line_change)
1851 pfile->cb.line_change (pfile, pfile->cur_token, false);
1854 /* Finish inlining run_directive. */
1855 pfile->buffer->file = NULL;
1856 _cpp_pop_buffer (pfile);
1858 /* Reset the old macro state before ... */
1859 XDELETE (pfile->context);
1860 pfile->context = saved_context;
1861 pfile->cur_token = saved_cur_token;
1862 pfile->cur_run = saved_cur_run;
1864 /* ... inserting the new tokens we collected. */
1865 _cpp_push_token_context (pfile, NULL, toks, count);
1868 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1870 _cpp_do__Pragma (cpp_reader *pfile)
1872 const cpp_token *string = get__Pragma_string (pfile);
1873 pfile->directive_result.type = CPP_PADDING;
1875 if (string)
1877 destringize_and_run (pfile, &string->val.str);
1878 return 1;
1880 cpp_error (pfile, CPP_DL_ERROR,
1881 "_Pragma takes a parenthesized string literal");
1882 return 0;
1885 /* Handle #ifdef. */
1886 static void
1887 do_ifdef (cpp_reader *pfile)
1889 int skip = 1;
1891 if (! pfile->state.skipping)
1893 cpp_hashnode *node = lex_macro_node (pfile, false);
1895 if (node)
1897 /* Do not treat conditional macros as being defined. This is due to
1898 the powerpc and spu ports using conditional macros for 'vector',
1899 'bool', and 'pixel' to act as conditional keywords. This messes
1900 up tests like #ifndef bool. */
1901 skip = (node->type != NT_MACRO
1902 || ((node->flags & NODE_CONDITIONAL) != 0));
1903 _cpp_mark_macro_used (node);
1904 if (!(node->flags & NODE_USED))
1906 node->flags |= NODE_USED;
1907 if (node->type == NT_MACRO)
1909 if ((node->flags & NODE_BUILTIN)
1910 && pfile->cb.user_builtin_macro)
1911 pfile->cb.user_builtin_macro (pfile, node);
1912 if (pfile->cb.used_define)
1913 pfile->cb.used_define (pfile, pfile->directive_line, node);
1915 else
1917 if (pfile->cb.used_undef)
1918 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1921 if (pfile->cb.used)
1922 pfile->cb.used (pfile, pfile->directive_line, node);
1923 check_eol (pfile, false);
1927 push_conditional (pfile, skip, T_IFDEF, 0);
1930 /* Handle #ifndef. */
1931 static void
1932 do_ifndef (cpp_reader *pfile)
1934 int skip = 1;
1935 cpp_hashnode *node = 0;
1937 if (! pfile->state.skipping)
1939 node = lex_macro_node (pfile, false);
1941 if (node)
1943 /* Do not treat conditional macros as being defined. This is due to
1944 the powerpc and spu ports using conditional macros for 'vector',
1945 'bool', and 'pixel' to act as conditional keywords. This messes
1946 up tests like #ifndef bool. */
1947 skip = (node->type == NT_MACRO
1948 && ((node->flags & NODE_CONDITIONAL) == 0));
1949 _cpp_mark_macro_used (node);
1950 if (!(node->flags & NODE_USED))
1952 node->flags |= NODE_USED;
1953 if (node->type == NT_MACRO)
1955 if ((node->flags & NODE_BUILTIN)
1956 && pfile->cb.user_builtin_macro)
1957 pfile->cb.user_builtin_macro (pfile, node);
1958 if (pfile->cb.used_define)
1959 pfile->cb.used_define (pfile, pfile->directive_line, node);
1961 else
1963 if (pfile->cb.used_undef)
1964 pfile->cb.used_undef (pfile, pfile->directive_line, 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_IFNDEF, node);
1976 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1977 pfile->mi_ind_cmacro so we can handle multiple-include
1978 optimizations. If macro expansion occurs in the expression, we
1979 cannot treat it as a controlling conditional, since the expansion
1980 could change in the future. That is handled by cpp_get_token. */
1981 static void
1982 do_if (cpp_reader *pfile)
1984 int skip = 1;
1986 if (! pfile->state.skipping)
1987 skip = _cpp_parse_expr (pfile, true) == false;
1989 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1992 /* Flip skipping state if appropriate and continue without changing
1993 if_stack; this is so that the error message for missing #endif's
1994 etc. will point to the original #if. */
1995 static void
1996 do_else (cpp_reader *pfile)
1998 cpp_buffer *buffer = pfile->buffer;
1999 struct if_stack *ifs = buffer->if_stack;
2001 if (ifs == NULL)
2002 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
2003 else
2005 if (ifs->type == T_ELSE)
2007 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
2008 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2009 "the conditional began here");
2011 ifs->type = T_ELSE;
2013 /* Skip any future (erroneous) #elses or #elifs. */
2014 pfile->state.skipping = ifs->skip_elses;
2015 ifs->skip_elses = true;
2017 /* Invalidate any controlling macro. */
2018 ifs->mi_cmacro = 0;
2020 /* Only check EOL if was not originally skipping. */
2021 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2022 check_eol_endif_labels (pfile);
2026 /* Handle a #elif directive by not changing if_stack either. See the
2027 comment above do_else. */
2028 static void
2029 do_elif (cpp_reader *pfile)
2031 cpp_buffer *buffer = pfile->buffer;
2032 struct if_stack *ifs = buffer->if_stack;
2034 if (ifs == NULL)
2035 cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2036 else
2038 if (ifs->type == T_ELSE)
2040 cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2041 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2042 "the conditional began here");
2044 ifs->type = T_ELIF;
2046 /* See DR#412: "Only the first group whose control condition
2047 evaluates to true (nonzero) is processed; any following groups
2048 are skipped and their controlling directives are processed as
2049 if they were in a group that is skipped." */
2050 if (ifs->skip_elses)
2051 pfile->state.skipping = 1;
2052 else
2054 pfile->state.skipping = ! _cpp_parse_expr (pfile, false);
2055 ifs->skip_elses = ! pfile->state.skipping;
2058 /* Invalidate any controlling macro. */
2059 ifs->mi_cmacro = 0;
2063 /* #endif pops the if stack and resets pfile->state.skipping. */
2064 static void
2065 do_endif (cpp_reader *pfile)
2067 cpp_buffer *buffer = pfile->buffer;
2068 struct if_stack *ifs = buffer->if_stack;
2070 if (ifs == NULL)
2071 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2072 else
2074 /* Only check EOL if was not originally skipping. */
2075 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2076 check_eol_endif_labels (pfile);
2078 /* If potential control macro, we go back outside again. */
2079 if (ifs->next == 0 && ifs->mi_cmacro)
2081 pfile->mi_valid = true;
2082 pfile->mi_cmacro = ifs->mi_cmacro;
2085 buffer->if_stack = ifs->next;
2086 pfile->state.skipping = ifs->was_skipping;
2087 obstack_free (&pfile->buffer_ob, ifs);
2091 /* Push an if_stack entry for a preprocessor conditional, and set
2092 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2093 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2094 we need to check here that we are at the top of the file. */
2095 static void
2096 push_conditional (cpp_reader *pfile, int skip, int type,
2097 const cpp_hashnode *cmacro)
2099 struct if_stack *ifs;
2100 cpp_buffer *buffer = pfile->buffer;
2102 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2103 ifs->line = pfile->directive_line;
2104 ifs->next = buffer->if_stack;
2105 ifs->skip_elses = pfile->state.skipping || !skip;
2106 ifs->was_skipping = pfile->state.skipping;
2107 ifs->type = type;
2108 /* This condition is effectively a test for top-of-file. */
2109 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2110 ifs->mi_cmacro = cmacro;
2111 else
2112 ifs->mi_cmacro = 0;
2114 pfile->state.skipping = skip;
2115 buffer->if_stack = ifs;
2118 /* Read the tokens of the answer into the macro pool, in a directive
2119 of type TYPE. Only commit the memory if we intend it as permanent
2120 storage, i.e. the #assert case. Returns 0 on success, and sets
2121 ANSWERP to point to the answer. PRED_LOC is the location of the
2122 predicate. */
2123 static int
2124 parse_answer (cpp_reader *pfile, struct answer **answerp, int type,
2125 source_location pred_loc)
2127 const cpp_token *paren;
2128 struct answer *answer;
2129 unsigned int acount;
2131 /* In a conditional, it is legal to not have an open paren. We
2132 should save the following token in this case. */
2133 paren = cpp_get_token (pfile);
2135 /* If not a paren, see if we're OK. */
2136 if (paren->type != CPP_OPEN_PAREN)
2138 /* In a conditional no answer is a test for any answer. It
2139 could be followed by any token. */
2140 if (type == T_IF)
2142 _cpp_backup_tokens (pfile, 1);
2143 return 0;
2146 /* #unassert with no answer is valid - it removes all answers. */
2147 if (type == T_UNASSERT && paren->type == CPP_EOF)
2148 return 0;
2150 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2151 "missing '(' after predicate");
2152 return 1;
2155 for (acount = 0;; acount++)
2157 size_t room_needed;
2158 const cpp_token *token = cpp_get_token (pfile);
2159 cpp_token *dest;
2161 if (token->type == CPP_CLOSE_PAREN)
2162 break;
2164 if (token->type == CPP_EOF)
2166 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2167 return 1;
2170 /* struct answer includes the space for one token. */
2171 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
2173 if (BUFF_ROOM (pfile->a_buff) < room_needed)
2174 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
2176 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
2177 *dest = *token;
2179 /* Drop whitespace at start, for answer equivalence purposes. */
2180 if (acount == 0)
2181 dest->flags &= ~PREV_WHITE;
2184 if (acount == 0)
2186 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2187 return 1;
2190 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
2191 answer->count = acount;
2192 answer->next = NULL;
2193 *answerp = answer;
2195 return 0;
2198 /* Parses an assertion directive of type TYPE, returning a pointer to
2199 the hash node of the predicate, or 0 on error. If an answer was
2200 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
2201 static cpp_hashnode *
2202 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
2204 cpp_hashnode *result = 0;
2205 const cpp_token *predicate;
2207 /* We don't expand predicates or answers. */
2208 pfile->state.prevent_expansion++;
2210 *answerp = 0;
2211 predicate = cpp_get_token (pfile);
2212 if (predicate->type == CPP_EOF)
2213 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2214 else if (predicate->type != CPP_NAME)
2215 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2216 "predicate must be an identifier");
2217 else if (parse_answer (pfile, answerp, type, predicate->src_loc) == 0)
2219 unsigned int len = NODE_LEN (predicate->val.node.node);
2220 unsigned char *sym = (unsigned char *) alloca (len + 1);
2222 /* Prefix '#' to get it out of macro namespace. */
2223 sym[0] = '#';
2224 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2225 result = cpp_lookup (pfile, sym, len + 1);
2228 pfile->state.prevent_expansion--;
2229 return result;
2232 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2233 or a pointer to NULL if the answer is not in the chain. */
2234 static struct answer **
2235 find_answer (cpp_hashnode *node, const struct answer *candidate)
2237 unsigned int i;
2238 struct answer **result;
2240 for (result = &node->value.answers; *result; result = &(*result)->next)
2242 struct answer *answer = *result;
2244 if (answer->count == candidate->count)
2246 for (i = 0; i < answer->count; i++)
2247 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
2248 break;
2250 if (i == answer->count)
2251 break;
2255 return result;
2258 /* Test an assertion within a preprocessor conditional. Returns
2259 nonzero on failure, zero on success. On success, the result of
2260 the test is written into VALUE, otherwise the value 0. */
2262 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2264 struct answer *answer;
2265 cpp_hashnode *node;
2267 node = parse_assertion (pfile, &answer, T_IF);
2269 /* For recovery, an erroneous assertion expression is handled as a
2270 failing assertion. */
2271 *value = 0;
2273 if (node)
2274 *value = (node->type == NT_ASSERTION &&
2275 (answer == 0 || *find_answer (node, answer) != 0));
2276 else if (pfile->cur_token[-1].type == CPP_EOF)
2277 _cpp_backup_tokens (pfile, 1);
2279 /* We don't commit the memory for the answer - it's temporary only. */
2280 return node == 0;
2283 /* Handle #assert. */
2284 static void
2285 do_assert (cpp_reader *pfile)
2287 struct answer *new_answer;
2288 cpp_hashnode *node;
2290 node = parse_assertion (pfile, &new_answer, T_ASSERT);
2291 if (node)
2293 size_t answer_size;
2295 /* Place the new answer in the answer list. First check there
2296 is not a duplicate. */
2297 new_answer->next = 0;
2298 if (node->type == NT_ASSERTION)
2300 if (*find_answer (node, new_answer))
2302 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2303 NODE_NAME (node) + 1);
2304 return;
2306 new_answer->next = node->value.answers;
2309 answer_size = sizeof (struct answer) + ((new_answer->count - 1)
2310 * sizeof (cpp_token));
2311 /* Commit or allocate storage for the object. */
2312 if (pfile->hash_table->alloc_subobject)
2314 struct answer *temp_answer = new_answer;
2315 new_answer = (struct answer *) pfile->hash_table->alloc_subobject
2316 (answer_size);
2317 memcpy (new_answer, temp_answer, answer_size);
2319 else
2320 BUFF_FRONT (pfile->a_buff) += answer_size;
2322 node->type = NT_ASSERTION;
2323 node->value.answers = new_answer;
2324 check_eol (pfile, false);
2328 /* Handle #unassert. */
2329 static void
2330 do_unassert (cpp_reader *pfile)
2332 cpp_hashnode *node;
2333 struct answer *answer;
2335 node = parse_assertion (pfile, &answer, T_UNASSERT);
2336 /* It isn't an error to #unassert something that isn't asserted. */
2337 if (node && node->type == NT_ASSERTION)
2339 if (answer)
2341 struct answer **p = find_answer (node, answer), *temp;
2343 /* Remove the answer from the list. */
2344 temp = *p;
2345 if (temp)
2346 *p = temp->next;
2348 /* Did we free the last answer? */
2349 if (node->value.answers == 0)
2350 node->type = NT_VOID;
2352 check_eol (pfile, false);
2354 else
2355 _cpp_free_definition (node);
2358 /* We don't commit the memory for the answer - it's temporary only. */
2361 /* These are for -D, -U, -A. */
2363 /* Process the string STR as if it appeared as the body of a #define.
2364 If STR is just an identifier, define it with value 1.
2365 If STR has anything after the identifier, then it should
2366 be identifier=definition. */
2367 void
2368 cpp_define (cpp_reader *pfile, const char *str)
2370 char *buf;
2371 const char *p;
2372 size_t count;
2374 /* Copy the entire option so we can modify it.
2375 Change the first "=" in the string to a space. If there is none,
2376 tack " 1" on the end. */
2378 count = strlen (str);
2379 buf = (char *) alloca (count + 3);
2380 memcpy (buf, str, count);
2382 p = strchr (str, '=');
2383 if (p)
2384 buf[p - str] = ' ';
2385 else
2387 buf[count++] = ' ';
2388 buf[count++] = '1';
2390 buf[count] = '\n';
2392 run_directive (pfile, T_DEFINE, buf, count);
2396 /* Use to build macros to be run through cpp_define() as
2397 described above.
2398 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2400 void
2401 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2403 char *ptr;
2405 va_list ap;
2406 va_start (ap, fmt);
2407 ptr = xvasprintf (fmt, ap);
2408 va_end (ap);
2410 cpp_define (pfile, ptr);
2411 free (ptr);
2415 /* Slight variant of the above for use by initialize_builtins. */
2416 void
2417 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2419 size_t len = strlen (str);
2420 char *buf = (char *) alloca (len + 1);
2421 memcpy (buf, str, len);
2422 buf[len] = '\n';
2423 run_directive (pfile, T_DEFINE, buf, len);
2426 /* Process MACRO as if it appeared as the body of an #undef. */
2427 void
2428 cpp_undef (cpp_reader *pfile, const char *macro)
2430 size_t len = strlen (macro);
2431 char *buf = (char *) alloca (len + 1);
2432 memcpy (buf, macro, len);
2433 buf[len] = '\n';
2434 run_directive (pfile, T_UNDEF, buf, len);
2437 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2438 or first element is zero, then the macro should be undefined. */
2439 static void
2440 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2442 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2443 if (node == NULL)
2444 return;
2446 if (pfile->cb.before_define)
2447 pfile->cb.before_define (pfile);
2449 if (node->type == NT_MACRO)
2451 if (pfile->cb.undef)
2452 pfile->cb.undef (pfile, pfile->directive_line, node);
2453 if (CPP_OPTION (pfile, warn_unused_macros))
2454 _cpp_warn_if_unused_macro (pfile, node, NULL);
2456 if (node->type != NT_VOID)
2457 _cpp_free_definition (node);
2459 if (c->is_undef)
2460 return;
2462 size_t namelen;
2463 const uchar *dn;
2464 cpp_hashnode *h = NULL;
2465 cpp_buffer *nbuf;
2467 namelen = ustrcspn (c->definition, "( \n");
2468 h = cpp_lookup (pfile, c->definition, namelen);
2469 dn = c->definition + namelen;
2471 h->type = NT_VOID;
2472 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
2473 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2474 if (nbuf != NULL)
2476 _cpp_clean_line (pfile);
2477 nbuf->sysp = 1;
2478 if (!_cpp_create_definition (pfile, h))
2479 abort ();
2480 _cpp_pop_buffer (pfile);
2482 else
2483 abort ();
2484 h->value.macro->line = c->line;
2485 h->value.macro->syshdr = c->syshdr;
2486 h->value.macro->used = c->used;
2490 /* Process the string STR as if it appeared as the body of a #assert. */
2491 void
2492 cpp_assert (cpp_reader *pfile, const char *str)
2494 handle_assertion (pfile, str, T_ASSERT);
2497 /* Process STR as if it appeared as the body of an #unassert. */
2498 void
2499 cpp_unassert (cpp_reader *pfile, const char *str)
2501 handle_assertion (pfile, str, T_UNASSERT);
2504 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2505 static void
2506 handle_assertion (cpp_reader *pfile, const char *str, int type)
2508 size_t count = strlen (str);
2509 const char *p = strchr (str, '=');
2511 /* Copy the entire option so we can modify it. Change the first
2512 "=" in the string to a '(', and tack a ')' on the end. */
2513 char *buf = (char *) alloca (count + 2);
2515 memcpy (buf, str, count);
2516 if (p)
2518 buf[p - str] = '(';
2519 buf[count++] = ')';
2521 buf[count] = '\n';
2522 str = buf;
2524 run_directive (pfile, type, str, count);
2527 /* The options structure. */
2528 cpp_options *
2529 cpp_get_options (cpp_reader *pfile)
2531 return &pfile->opts;
2534 /* The callbacks structure. */
2535 cpp_callbacks *
2536 cpp_get_callbacks (cpp_reader *pfile)
2538 return &pfile->cb;
2541 /* Copy the given callbacks structure to our own. */
2542 void
2543 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2545 pfile->cb = *cb;
2548 /* The dependencies structure. (Creates one if it hasn't already been.) */
2549 struct deps *
2550 cpp_get_deps (cpp_reader *pfile)
2552 if (!pfile->deps)
2553 pfile->deps = deps_init ();
2554 return pfile->deps;
2557 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2558 doesn't fail. It does not generate a file change call back; that
2559 is the responsibility of the caller. */
2560 cpp_buffer *
2561 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2562 int from_stage3)
2564 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2566 /* Clears, amongst other things, if_stack and mi_cmacro. */
2567 memset (new_buffer, 0, sizeof (cpp_buffer));
2569 new_buffer->next_line = new_buffer->buf = buffer;
2570 new_buffer->rlimit = buffer + len;
2571 new_buffer->from_stage3 = from_stage3;
2572 new_buffer->prev = pfile->buffer;
2573 new_buffer->need_line = true;
2575 pfile->buffer = new_buffer;
2577 return new_buffer;
2580 /* Pops a single buffer, with a file change call-back if appropriate.
2581 Then pushes the next -include file, if any remain. */
2582 void
2583 _cpp_pop_buffer (cpp_reader *pfile)
2585 cpp_buffer *buffer = pfile->buffer;
2586 struct _cpp_file *inc = buffer->file;
2587 struct if_stack *ifs;
2588 const unsigned char *to_free;
2590 /* Walk back up the conditional stack till we reach its level at
2591 entry to this file, issuing error messages. */
2592 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2593 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2594 "unterminated #%s", dtable[ifs->type].name);
2596 /* In case of a missing #endif. */
2597 pfile->state.skipping = 0;
2599 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2600 pfile->buffer = buffer->prev;
2602 to_free = buffer->to_free;
2603 free (buffer->notes);
2605 /* Free the buffer object now; we may want to push a new buffer
2606 in _cpp_push_next_include_file. */
2607 obstack_free (&pfile->buffer_ob, buffer);
2609 if (inc)
2611 _cpp_pop_file_buffer (pfile, inc, to_free);
2613 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2617 /* Enter all recognized directives in the hash table. */
2618 void
2619 _cpp_init_directives (cpp_reader *pfile)
2621 unsigned int i;
2622 cpp_hashnode *node;
2624 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2626 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2627 node->is_directive = 1;
2628 node->directive_index = i;
2632 /* Extract header file from a bracket include. Parsing starts after '<'.
2633 The string is malloced and must be freed by the caller. */
2634 char *
2635 _cpp_bracket_include(cpp_reader *pfile)
2637 return glue_header_name (pfile);