gcc/testsuite/
[official-gcc.git] / libcpp / directives.c
blob3486a48d21e9743935258c65a439edc922fef4dd
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986-2014 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 /* Ensure there are no stray tokens at the end of a directive. If
217 EXPAND is true, tokens macro-expanding to nothing are allowed. */
218 static void
219 check_eol (cpp_reader *pfile, bool expand)
221 if (! SEEN_EOL () && (expand
222 ? cpp_get_token (pfile)
223 : _cpp_lex_token (pfile))->type != CPP_EOF)
224 cpp_error (pfile, CPP_DL_PEDWARN, "extra tokens at end of #%s directive",
225 pfile->directive->name);
228 /* Ensure there are no stray tokens other than comments at the end of
229 a directive, and gather the comments. */
230 static const cpp_token **
231 check_eol_return_comments (cpp_reader *pfile)
233 size_t c;
234 size_t capacity = 8;
235 const cpp_token **buf;
237 buf = XNEWVEC (const cpp_token *, capacity);
238 c = 0;
239 if (! SEEN_EOL ())
241 while (1)
243 const cpp_token *tok;
245 tok = _cpp_lex_token (pfile);
246 if (tok->type == CPP_EOF)
247 break;
248 if (tok->type != CPP_COMMENT)
249 cpp_error (pfile, CPP_DL_PEDWARN,
250 "extra tokens at end of #%s directive",
251 pfile->directive->name);
252 else
254 if (c + 1 >= capacity)
256 capacity *= 2;
257 buf = XRESIZEVEC (const cpp_token *, buf, capacity);
259 buf[c] = tok;
260 ++c;
264 buf[c] = NULL;
265 return buf;
268 /* Called when entering a directive, _Pragma or command-line directive. */
269 static void
270 start_directive (cpp_reader *pfile)
272 /* Setup in-directive state. */
273 pfile->state.in_directive = 1;
274 pfile->state.save_comments = 0;
275 pfile->directive_result.type = CPP_PADDING;
277 /* Some handlers need the position of the # for diagnostics. */
278 pfile->directive_line = pfile->line_table->highest_line;
281 /* Called when leaving a directive, _Pragma or command-line directive. */
282 static void
283 end_directive (cpp_reader *pfile, int skip_line)
285 if (CPP_OPTION (pfile, traditional))
287 /* Revert change of prepare_directive_trad. */
288 if (!pfile->state.in_deferred_pragma)
289 pfile->state.prevent_expansion--;
291 if (pfile->directive != &dtable[T_DEFINE])
292 _cpp_remove_overlay (pfile);
294 else if (pfile->state.in_deferred_pragma)
296 /* We don't skip for an assembler #. */
297 else if (skip_line)
299 skip_rest_of_line (pfile);
300 if (!pfile->keep_tokens)
302 pfile->cur_run = &pfile->base_run;
303 pfile->cur_token = pfile->base_run.base;
307 /* Restore state. */
308 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
309 pfile->state.in_directive = 0;
310 pfile->state.in_expression = 0;
311 pfile->state.angled_headers = 0;
312 pfile->directive = 0;
315 /* Prepare to handle the directive in pfile->directive. */
316 static void
317 prepare_directive_trad (cpp_reader *pfile)
319 if (pfile->directive != &dtable[T_DEFINE])
321 bool no_expand = (pfile->directive
322 && ! (pfile->directive->flags & EXPAND));
323 bool was_skipping = pfile->state.skipping;
325 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
326 || pfile->directive == &dtable[T_ELIF]);
327 if (pfile->state.in_expression)
328 pfile->state.skipping = false;
330 if (no_expand)
331 pfile->state.prevent_expansion++;
332 _cpp_scan_out_logical_line (pfile, NULL);
333 if (no_expand)
334 pfile->state.prevent_expansion--;
336 pfile->state.skipping = was_skipping;
337 _cpp_overlay_buffer (pfile, pfile->out.base,
338 pfile->out.cur - pfile->out.base);
341 /* Stop ISO C from expanding anything. */
342 pfile->state.prevent_expansion++;
345 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
346 the '#' was indented. */
347 static void
348 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
350 /* Issue -pedantic or deprecated warnings for extensions. We let
351 -pedantic take precedence if both are applicable. */
352 if (! pfile->state.skipping)
354 if (dir->origin == EXTENSION
355 && !(dir == &dtable[T_IMPORT] && CPP_OPTION (pfile, objc))
356 && CPP_PEDANTIC (pfile))
357 cpp_error (pfile, CPP_DL_PEDWARN, "#%s is a GCC extension", dir->name);
358 else if (((dir->flags & DEPRECATED) != 0
359 || (dir == &dtable[T_IMPORT] && !CPP_OPTION (pfile, objc)))
360 && CPP_OPTION (pfile, cpp_warn_deprecated))
361 cpp_warning (pfile, CPP_W_DEPRECATED,
362 "#%s is a deprecated GCC extension", dir->name);
365 /* Traditionally, a directive is ignored unless its # is in
366 column 1. Therefore in code intended to work with K+R
367 compilers, directives added by C89 must have their #
368 indented, and directives present in traditional C must not.
369 This is true even of directives in skipped conditional
370 blocks. #elif cannot be used at all. */
371 if (CPP_WTRADITIONAL (pfile))
373 if (dir == &dtable[T_ELIF])
374 cpp_warning (pfile, CPP_W_TRADITIONAL,
375 "suggest not using #elif in traditional C");
376 else if (indented && dir->origin == KANDR)
377 cpp_warning (pfile, CPP_W_TRADITIONAL,
378 "traditional C ignores #%s with the # indented",
379 dir->name);
380 else if (!indented && dir->origin != KANDR)
381 cpp_warning (pfile, CPP_W_TRADITIONAL,
382 "suggest hiding #%s from traditional C with an indented #",
383 dir->name);
387 /* Check if we have a known directive. INDENTED is nonzero if the
388 '#' of the directive was indented. This function is in this file
389 to save unnecessarily exporting dtable etc. to lex.c. Returns
390 nonzero if the line of tokens has been handled, zero if we should
391 continue processing the line. */
393 _cpp_handle_directive (cpp_reader *pfile, int indented)
395 const directive *dir = 0;
396 const cpp_token *dname;
397 bool was_parsing_args = pfile->state.parsing_args;
398 bool was_discarding_output = pfile->state.discarding_output;
399 int skip = 1;
401 if (was_discarding_output)
402 pfile->state.prevent_expansion = 0;
404 if (was_parsing_args)
406 if (CPP_OPTION (pfile, cpp_pedantic))
407 cpp_error (pfile, CPP_DL_PEDWARN,
408 "embedding a directive within macro arguments is not portable");
409 pfile->state.parsing_args = 0;
410 pfile->state.prevent_expansion = 0;
412 start_directive (pfile);
413 dname = _cpp_lex_token (pfile);
415 if (dname->type == CPP_NAME)
417 if (dname->val.node.node->is_directive)
418 dir = &dtable[dname->val.node.node->directive_index];
420 /* We do not recognize the # followed by a number extension in
421 assembler code. */
422 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
424 dir = &linemarker_dir;
425 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
426 && ! pfile->state.skipping)
427 cpp_error (pfile, CPP_DL_PEDWARN,
428 "style of line directive is a GCC extension");
431 if (dir)
433 /* If we have a directive that is not an opening conditional,
434 invalidate any control macro. */
435 if (! (dir->flags & IF_COND))
436 pfile->mi_valid = false;
438 /* Kluge alert. In order to be sure that code like this
440 #define HASH #
441 HASH define foo bar
443 does not cause '#define foo bar' to get executed when
444 compiled with -save-temps, we recognize directives in
445 -fpreprocessed mode only if the # is in column 1. macro.c
446 puts a space in front of any '#' at the start of a macro.
448 We exclude the -fdirectives-only case because macro expansion
449 has not been performed yet, and block comments can cause spaces
450 to precede the directive. */
451 if (CPP_OPTION (pfile, preprocessed)
452 && !CPP_OPTION (pfile, directives_only)
453 && (indented || !(dir->flags & IN_I)))
455 skip = 0;
456 dir = 0;
458 else
460 /* In failed conditional groups, all non-conditional
461 directives are ignored. Before doing that, whether
462 skipping or not, we should lex angle-bracketed headers
463 correctly, and maybe output some diagnostics. */
464 pfile->state.angled_headers = dir->flags & INCL;
465 pfile->state.directive_wants_padding = dir->flags & INCL;
466 if (! CPP_OPTION (pfile, preprocessed))
467 directive_diagnostics (pfile, dir, indented);
468 if (pfile->state.skipping && !(dir->flags & COND))
469 dir = 0;
472 else if (dname->type == CPP_EOF)
473 ; /* CPP_EOF is the "null directive". */
474 else
476 /* An unknown directive. Don't complain about it in assembly
477 source: we don't know where the comments are, and # may
478 introduce assembler pseudo-ops. Don't complain about invalid
479 directives in skipped conditional groups (6.10 p4). */
480 if (CPP_OPTION (pfile, lang) == CLK_ASM)
481 skip = 0;
482 else if (!pfile->state.skipping)
483 cpp_error (pfile, CPP_DL_ERROR, "invalid preprocessing directive #%s",
484 cpp_token_as_text (pfile, dname));
487 pfile->directive = dir;
488 if (CPP_OPTION (pfile, traditional))
489 prepare_directive_trad (pfile);
491 if (dir)
492 pfile->directive->handler (pfile);
493 else if (skip == 0)
494 _cpp_backup_tokens (pfile, 1);
496 end_directive (pfile, skip);
497 if (was_parsing_args && !pfile->state.in_deferred_pragma)
499 /* Restore state when within macro args. */
500 pfile->state.parsing_args = 2;
501 pfile->state.prevent_expansion = 1;
503 if (was_discarding_output)
504 pfile->state.prevent_expansion = 1;
505 return skip;
508 /* Directive handler wrapper used by the command line option
509 processor. BUF is \n terminated. */
510 static void
511 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
513 cpp_push_buffer (pfile, (const uchar *) buf, count,
514 /* from_stage3 */ true);
515 start_directive (pfile);
517 /* This is a short-term fix to prevent a leading '#' being
518 interpreted as a directive. */
519 _cpp_clean_line (pfile);
521 pfile->directive = &dtable[dir_no];
522 if (CPP_OPTION (pfile, traditional))
523 prepare_directive_trad (pfile);
524 pfile->directive->handler (pfile);
525 end_directive (pfile, 1);
526 _cpp_pop_buffer (pfile);
529 /* Checks for validity the macro name in #define, #undef, #ifdef and
530 #ifndef directives. IS_DEF_OR_UNDEF is true if this call is
531 processing a #define or #undefine directive, and false
532 otherwise. */
533 static cpp_hashnode *
534 lex_macro_node (cpp_reader *pfile, bool is_def_or_undef)
536 const cpp_token *token = _cpp_lex_token (pfile);
538 /* The token immediately after #define must be an identifier. That
539 identifier may not be "defined", per C99 6.10.8p4.
540 In C++, it may not be any of the "named operators" either,
541 per C++98 [lex.digraph], [lex.key].
542 Finally, the identifier may not have been poisoned. (In that case
543 the lexer has issued the error message for us.) */
545 if (token->type == CPP_NAME)
547 cpp_hashnode *node = token->val.node.node;
549 if (is_def_or_undef && node == pfile->spec_nodes.n_defined)
550 cpp_error (pfile, CPP_DL_ERROR,
551 "\"defined\" cannot be used as a macro name");
552 else if (! (node->flags & NODE_POISONED))
553 return node;
555 else if (token->flags & NAMED_OP)
556 cpp_error (pfile, CPP_DL_ERROR,
557 "\"%s\" cannot be used as a macro name as it is an operator in C++",
558 NODE_NAME (token->val.node.node));
559 else if (token->type == CPP_EOF)
560 cpp_error (pfile, CPP_DL_ERROR, "no macro name given in #%s directive",
561 pfile->directive->name);
562 else
563 cpp_error (pfile, CPP_DL_ERROR, "macro names must be identifiers");
565 return NULL;
568 /* Process a #define directive. Most work is done in macro.c. */
569 static void
570 do_define (cpp_reader *pfile)
572 cpp_hashnode *node = lex_macro_node (pfile, true);
574 if (node)
576 /* If we have been requested to expand comments into macros,
577 then re-enable saving of comments. */
578 pfile->state.save_comments =
579 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
581 if (pfile->cb.before_define)
582 pfile->cb.before_define (pfile);
584 if (_cpp_create_definition (pfile, node))
585 if (pfile->cb.define)
586 pfile->cb.define (pfile, pfile->directive_line, node);
588 node->flags &= ~NODE_USED;
592 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
593 static void
594 do_undef (cpp_reader *pfile)
596 cpp_hashnode *node = lex_macro_node (pfile, true);
598 if (node)
600 if (pfile->cb.before_define)
601 pfile->cb.before_define (pfile);
603 if (pfile->cb.undef)
604 pfile->cb.undef (pfile, pfile->directive_line, node);
606 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified
607 identifier is not currently defined as a macro name. */
608 if (node->type == NT_MACRO)
610 if (node->flags & NODE_WARN)
611 cpp_error (pfile, CPP_DL_WARNING,
612 "undefining \"%s\"", NODE_NAME (node));
614 if (CPP_OPTION (pfile, warn_unused_macros))
615 _cpp_warn_if_unused_macro (pfile, node, NULL);
617 _cpp_free_definition (node);
621 check_eol (pfile, false);
624 /* Undefine a single macro/assertion/whatever. */
626 static int
627 undefine_macros (cpp_reader *pfile ATTRIBUTE_UNUSED, cpp_hashnode *h,
628 void *data_p ATTRIBUTE_UNUSED)
630 /* Body of _cpp_free_definition inlined here for speed.
631 Macros and assertions no longer have anything to free. */
632 h->type = NT_VOID;
633 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
634 return 1;
637 /* Undefine all macros and assertions. */
639 void
640 cpp_undef_all (cpp_reader *pfile)
642 cpp_forall_identifiers (pfile, undefine_macros, NULL);
646 /* Helper routine used by parse_include. Reinterpret the current line
647 as an h-char-sequence (< ... >); we are looking at the first token
648 after the <. Returns a malloced filename. */
649 static char *
650 glue_header_name (cpp_reader *pfile)
652 const cpp_token *token;
653 char *buffer;
654 size_t len, total_len = 0, capacity = 1024;
656 /* To avoid lexed tokens overwriting our glued name, we can only
657 allocate from the string pool once we've lexed everything. */
658 buffer = XNEWVEC (char, capacity);
659 for (;;)
661 token = get_token_no_padding (pfile);
663 if (token->type == CPP_GREATER)
664 break;
665 if (token->type == CPP_EOF)
667 cpp_error (pfile, CPP_DL_ERROR, "missing terminating > character");
668 break;
671 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
672 if (total_len + len > capacity)
674 capacity = (capacity + len) * 2;
675 buffer = XRESIZEVEC (char, buffer, capacity);
678 if (token->flags & PREV_WHITE)
679 buffer[total_len++] = ' ';
681 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len],
682 true)
683 - (uchar *) buffer);
686 buffer[total_len] = '\0';
687 return buffer;
690 /* Returns the file name of #include, #include_next, #import and
691 #pragma dependency. The string is malloced and the caller should
692 free it. Returns NULL on error. LOCATION is the source location
693 of the file name. */
695 static const char *
696 parse_include (cpp_reader *pfile, int *pangle_brackets,
697 const cpp_token ***buf, source_location *location)
699 char *fname;
700 const cpp_token *header;
702 /* Allow macro expansion. */
703 header = get_token_no_padding (pfile);
704 *location = header->src_loc;
705 if ((header->type == CPP_STRING && header->val.str.text[0] != 'R')
706 || header->type == CPP_HEADER_NAME)
708 fname = XNEWVEC (char, header->val.str.len - 1);
709 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
710 fname[header->val.str.len - 2] = '\0';
711 *pangle_brackets = header->type == CPP_HEADER_NAME;
713 else if (header->type == CPP_LESS)
715 fname = glue_header_name (pfile);
716 *pangle_brackets = 1;
718 else
720 const unsigned char *dir;
722 if (pfile->directive == &dtable[T_PRAGMA])
723 dir = UC"pragma dependency";
724 else
725 dir = pfile->directive->name;
726 cpp_error (pfile, CPP_DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
727 dir);
729 return NULL;
732 if (pfile->directive == &dtable[T_PRAGMA])
734 /* This pragma allows extra tokens after the file name. */
736 else if (buf == NULL || CPP_OPTION (pfile, discard_comments))
737 check_eol (pfile, true);
738 else
740 /* If we are not discarding comments, then gather them while
741 doing the eol check. */
742 *buf = check_eol_return_comments (pfile);
745 return fname;
748 /* Handle #include, #include_next and #import. */
749 static void
750 do_include_common (cpp_reader *pfile, enum include_type type)
752 const char *fname;
753 int angle_brackets;
754 const cpp_token **buf = NULL;
755 source_location location;
757 /* Re-enable saving of comments if requested, so that the include
758 callback can dump comments which follow #include. */
759 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
761 fname = parse_include (pfile, &angle_brackets, &buf, &location);
762 if (!fname)
764 if (buf)
765 XDELETEVEC (buf);
766 return;
769 if (!*fname)
771 cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
772 "empty filename in #%s",
773 pfile->directive->name);
774 XDELETEVEC (fname);
775 if (buf)
776 XDELETEVEC (buf);
777 return;
780 /* Prevent #include recursion. */
781 if (pfile->line_table->depth >= CPP_STACK_MAX)
782 cpp_error (pfile, CPP_DL_ERROR, "#include nested too deeply");
783 else
785 /* Get out of macro context, if we are. */
786 skip_rest_of_line (pfile);
788 if (pfile->cb.include)
789 pfile->cb.include (pfile, pfile->directive_line,
790 pfile->directive->name, fname, angle_brackets,
791 buf);
793 _cpp_stack_include (pfile, fname, angle_brackets, type);
796 XDELETEVEC (fname);
797 if (buf)
798 XDELETEVEC (buf);
801 static void
802 do_include (cpp_reader *pfile)
804 do_include_common (pfile, IT_INCLUDE);
807 static void
808 do_import (cpp_reader *pfile)
810 do_include_common (pfile, IT_IMPORT);
813 static void
814 do_include_next (cpp_reader *pfile)
816 enum include_type type = IT_INCLUDE_NEXT;
818 /* If this is the primary source file, warn and use the normal
819 search logic. */
820 if (cpp_in_primary_file (pfile))
822 cpp_error (pfile, CPP_DL_WARNING,
823 "#include_next in primary source file");
824 type = IT_INCLUDE;
826 do_include_common (pfile, type);
829 /* Subroutine of do_linemarker. Read possible flags after file name.
830 LAST is the last flag seen; 0 if this is the first flag. Return the
831 flag if it is valid, 0 at the end of the directive. Otherwise
832 complain. */
833 static unsigned int
834 read_flag (cpp_reader *pfile, unsigned int last)
836 const cpp_token *token = _cpp_lex_token (pfile);
838 if (token->type == CPP_NUMBER && token->val.str.len == 1)
840 unsigned int flag = token->val.str.text[0] - '0';
842 if (flag > last && flag <= 4
843 && (flag != 4 || last == 3)
844 && (flag != 2 || last == 0))
845 return flag;
848 if (token->type != CPP_EOF)
849 cpp_error (pfile, CPP_DL_ERROR, "invalid flag \"%s\" in line directive",
850 cpp_token_as_text (pfile, token));
851 return 0;
854 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
855 of length LEN, to binary; store it in NUMP, and return false if the
856 number was well-formed, true if not. WRAPPED is set to true if the
857 number did not fit into 'unsigned long'. */
858 static bool
859 strtolinenum (const uchar *str, size_t len, linenum_type *nump, bool *wrapped)
861 linenum_type reg = 0;
862 linenum_type reg_prev = 0;
864 uchar c;
865 *wrapped = false;
866 while (len--)
868 c = *str++;
869 if (!ISDIGIT (c))
870 return true;
871 reg *= 10;
872 reg += c - '0';
873 if (reg < reg_prev)
874 *wrapped = true;
875 reg_prev = reg;
877 *nump = reg;
878 return false;
881 /* Interpret #line command.
882 Note that the filename string (if any) is a true string constant
883 (escapes are interpreted), unlike in #line. */
884 static void
885 do_line (cpp_reader *pfile)
887 const struct line_maps *line_table = pfile->line_table;
888 const struct line_map *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
890 /* skip_rest_of_line() may cause line table to be realloc()ed so note down
891 sysp right now. */
893 unsigned char map_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
894 const cpp_token *token;
895 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
896 linenum_type new_lineno;
898 /* C99 raised the minimum limit on #line numbers. */
899 linenum_type cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
900 bool wrapped;
902 /* #line commands expand macros. */
903 token = cpp_get_token (pfile);
904 if (token->type != CPP_NUMBER
905 || strtolinenum (token->val.str.text, token->val.str.len,
906 &new_lineno, &wrapped))
908 if (token->type == CPP_EOF)
909 cpp_error (pfile, CPP_DL_ERROR, "unexpected end of file after #line");
910 else
911 cpp_error (pfile, CPP_DL_ERROR,
912 "\"%s\" after #line is not a positive integer",
913 cpp_token_as_text (pfile, token));
914 return;
917 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap || wrapped))
918 cpp_error (pfile, CPP_DL_PEDWARN, "line number out of range");
919 else if (wrapped)
920 cpp_error (pfile, CPP_DL_WARNING, "line number out of range");
922 token = cpp_get_token (pfile);
923 if (token->type == CPP_STRING)
925 cpp_string s = { 0, 0 };
926 if (cpp_interpret_string_notranslate (pfile, &token->val.str, 1,
927 &s, CPP_STRING))
928 new_file = (const char *)s.text;
929 check_eol (pfile, true);
931 else if (token->type != CPP_EOF)
933 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
934 cpp_token_as_text (pfile, token));
935 return;
938 skip_rest_of_line (pfile);
939 _cpp_do_file_change (pfile, LC_RENAME_VERBATIM, new_file, new_lineno,
940 map_sysp);
943 /* Interpret the # 44 "file" [flags] notation, which has slightly
944 different syntax and semantics from #line: Flags are allowed,
945 and we never complain about the line number being too big. */
946 static void
947 do_linemarker (cpp_reader *pfile)
949 const struct line_maps *line_table = pfile->line_table;
950 const struct line_map *map = LINEMAPS_LAST_ORDINARY_MAP (line_table);
951 const cpp_token *token;
952 const char *new_file = ORDINARY_MAP_FILE_NAME (map);
953 linenum_type new_lineno;
954 unsigned int new_sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (map);
955 enum lc_reason reason = LC_RENAME_VERBATIM;
956 int flag;
957 bool wrapped;
959 /* Back up so we can get the number again. Putting this in
960 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
961 some circumstances, which can segfault. */
962 _cpp_backup_tokens (pfile, 1);
964 /* #line commands expand macros. */
965 token = cpp_get_token (pfile);
966 if (token->type != CPP_NUMBER
967 || strtolinenum (token->val.str.text, token->val.str.len,
968 &new_lineno, &wrapped))
970 /* Unlike #line, there does not seem to be a way to get an EOF
971 here. So, it should be safe to always spell the token. */
972 cpp_error (pfile, CPP_DL_ERROR,
973 "\"%s\" after # is not a positive integer",
974 cpp_token_as_text (pfile, token));
975 return;
978 token = cpp_get_token (pfile);
979 if (token->type == CPP_STRING)
981 cpp_string s = { 0, 0 };
982 if (cpp_interpret_string_notranslate (pfile, &token->val.str,
983 1, &s, CPP_STRING))
984 new_file = (const char *)s.text;
986 new_sysp = 0;
987 flag = read_flag (pfile, 0);
988 if (flag == 1)
990 reason = LC_ENTER;
991 /* Fake an include for cpp_included (). */
992 _cpp_fake_include (pfile, new_file);
993 flag = read_flag (pfile, flag);
995 else if (flag == 2)
997 reason = LC_LEAVE;
998 flag = read_flag (pfile, flag);
1000 if (flag == 3)
1002 new_sysp = 1;
1003 flag = read_flag (pfile, flag);
1004 if (flag == 4)
1005 new_sysp = 2;
1007 pfile->buffer->sysp = new_sysp;
1009 check_eol (pfile, false);
1011 else if (token->type != CPP_EOF)
1013 cpp_error (pfile, CPP_DL_ERROR, "\"%s\" is not a valid filename",
1014 cpp_token_as_text (pfile, token));
1015 return;
1018 skip_rest_of_line (pfile);
1020 /* Compensate for the increment in linemap_add that occurs in
1021 _cpp_do_file_change. We're currently at the start of the line
1022 *following* the #line directive. A separate source_location for this
1023 location makes no sense (until we do the LC_LEAVE), and
1024 complicates LAST_SOURCE_LINE_LOCATION. */
1025 pfile->line_table->highest_location--;
1027 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
1030 /* Arrange the file_change callback. pfile->line has changed to
1031 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
1032 header, 2 for a system header that needs to be extern "C" protected,
1033 and zero otherwise. */
1034 void
1035 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
1036 const char *to_file, linenum_type file_line,
1037 unsigned int sysp)
1039 const struct line_map *map = linemap_add (pfile->line_table, reason, sysp,
1040 to_file, file_line);
1041 if (map != NULL)
1042 linemap_line_start (pfile->line_table,
1043 ORDINARY_MAP_STARTING_LINE_NUMBER (map),
1044 127);
1046 if (pfile->cb.file_change)
1047 pfile->cb.file_change (pfile, map);
1050 /* Report a warning or error detected by the program we are
1051 processing. Use the directive's tokens in the error message. */
1052 static void
1053 do_diagnostic (cpp_reader *pfile, int code, int reason, int print_dir)
1055 const unsigned char *dir_name;
1056 unsigned char *line;
1057 source_location src_loc = pfile->cur_token[-1].src_loc;
1059 if (print_dir)
1060 dir_name = pfile->directive->name;
1061 else
1062 dir_name = NULL;
1063 pfile->state.prevent_expansion++;
1064 line = cpp_output_line_to_string (pfile, dir_name);
1065 pfile->state.prevent_expansion--;
1067 if (code == CPP_DL_WARNING_SYSHDR && reason)
1068 cpp_warning_with_line_syshdr (pfile, reason, src_loc, 0, "%s", line);
1069 else if (code == CPP_DL_WARNING && reason)
1070 cpp_warning_with_line (pfile, reason, src_loc, 0, "%s", line);
1071 else
1072 cpp_error_with_line (pfile, code, src_loc, 0, "%s", line);
1073 free (line);
1076 static void
1077 do_error (cpp_reader *pfile)
1079 do_diagnostic (pfile, CPP_DL_ERROR, 0, 1);
1082 static void
1083 do_warning (cpp_reader *pfile)
1085 /* We want #warning diagnostics to be emitted in system headers too. */
1086 do_diagnostic (pfile, CPP_DL_WARNING_SYSHDR, CPP_W_WARNING_DIRECTIVE, 1);
1089 /* Report program identification. */
1090 static void
1091 do_ident (cpp_reader *pfile)
1093 const cpp_token *str = cpp_get_token (pfile);
1095 if (str->type != CPP_STRING)
1096 cpp_error (pfile, CPP_DL_ERROR, "invalid #%s directive",
1097 pfile->directive->name);
1098 else if (pfile->cb.ident)
1099 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
1101 check_eol (pfile, false);
1104 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
1105 matching entry, or NULL if none is found. The returned entry could
1106 be the start of a namespace chain, or a pragma. */
1107 static struct pragma_entry *
1108 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
1110 while (chain && chain->pragma != pragma)
1111 chain = chain->next;
1113 return chain;
1116 /* Create and insert a blank pragma entry at the beginning of a
1117 singly-linked CHAIN. */
1118 static struct pragma_entry *
1119 new_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain)
1121 struct pragma_entry *new_entry;
1123 new_entry = (struct pragma_entry *)
1124 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1126 memset (new_entry, 0, sizeof (struct pragma_entry));
1127 new_entry->next = *chain;
1129 *chain = new_entry;
1130 return new_entry;
1133 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1134 goes in the global namespace. */
1135 static struct pragma_entry *
1136 register_pragma_1 (cpp_reader *pfile, const char *space, const char *name,
1137 bool allow_name_expansion)
1139 struct pragma_entry **chain = &pfile->pragmas;
1140 struct pragma_entry *entry;
1141 const cpp_hashnode *node;
1143 if (space)
1145 node = cpp_lookup (pfile, UC space, strlen (space));
1146 entry = lookup_pragma_entry (*chain, node);
1147 if (!entry)
1149 entry = new_pragma_entry (pfile, chain);
1150 entry->pragma = node;
1151 entry->is_nspace = true;
1152 entry->allow_expansion = allow_name_expansion;
1154 else if (!entry->is_nspace)
1155 goto clash;
1156 else if (entry->allow_expansion != allow_name_expansion)
1158 cpp_error (pfile, CPP_DL_ICE,
1159 "registering pragmas in namespace \"%s\" with mismatched "
1160 "name expansion", space);
1161 return NULL;
1163 chain = &entry->u.space;
1165 else if (allow_name_expansion)
1167 cpp_error (pfile, CPP_DL_ICE,
1168 "registering pragma \"%s\" with name expansion "
1169 "and no namespace", name);
1170 return NULL;
1173 /* Check for duplicates. */
1174 node = cpp_lookup (pfile, UC name, strlen (name));
1175 entry = lookup_pragma_entry (*chain, node);
1176 if (entry == NULL)
1178 entry = new_pragma_entry (pfile, chain);
1179 entry->pragma = node;
1180 return entry;
1183 if (entry->is_nspace)
1184 clash:
1185 cpp_error (pfile, CPP_DL_ICE,
1186 "registering \"%s\" as both a pragma and a pragma namespace",
1187 NODE_NAME (node));
1188 else if (space)
1189 cpp_error (pfile, CPP_DL_ICE, "#pragma %s %s is already registered",
1190 space, name);
1191 else
1192 cpp_error (pfile, CPP_DL_ICE, "#pragma %s is already registered", name);
1194 return NULL;
1197 /* Register a cpplib internal pragma SPACE NAME with HANDLER. */
1198 static void
1199 register_pragma_internal (cpp_reader *pfile, const char *space,
1200 const char *name, pragma_cb handler)
1202 struct pragma_entry *entry;
1204 entry = register_pragma_1 (pfile, space, name, false);
1205 entry->is_internal = true;
1206 entry->u.handler = handler;
1209 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1210 goes in the global namespace. HANDLER is the handler it will call,
1211 which must be non-NULL. If ALLOW_EXPANSION is set, allow macro
1212 expansion while parsing pragma NAME. This function is exported
1213 from libcpp. */
1214 void
1215 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
1216 pragma_cb handler, bool allow_expansion)
1218 struct pragma_entry *entry;
1220 if (!handler)
1222 cpp_error (pfile, CPP_DL_ICE, "registering pragma with NULL handler");
1223 return;
1226 entry = register_pragma_1 (pfile, space, name, false);
1227 if (entry)
1229 entry->allow_expansion = allow_expansion;
1230 entry->u.handler = handler;
1234 /* Similarly, but create mark the pragma for deferred processing.
1235 When found, a CPP_PRAGMA token will be insertted into the stream
1236 with IDENT in the token->u.pragma slot. */
1237 void
1238 cpp_register_deferred_pragma (cpp_reader *pfile, const char *space,
1239 const char *name, unsigned int ident,
1240 bool allow_expansion, bool allow_name_expansion)
1242 struct pragma_entry *entry;
1244 entry = register_pragma_1 (pfile, space, name, allow_name_expansion);
1245 if (entry)
1247 entry->is_deferred = true;
1248 entry->allow_expansion = allow_expansion;
1249 entry->u.ident = ident;
1253 /* Register the pragmas the preprocessor itself handles. */
1254 void
1255 _cpp_init_internal_pragmas (cpp_reader *pfile)
1257 /* Pragmas in the global namespace. */
1258 register_pragma_internal (pfile, 0, "once", do_pragma_once);
1259 register_pragma_internal (pfile, 0, "push_macro", do_pragma_push_macro);
1260 register_pragma_internal (pfile, 0, "pop_macro", do_pragma_pop_macro);
1262 /* New GCC-specific pragmas should be put in the GCC namespace. */
1263 register_pragma_internal (pfile, "GCC", "poison", do_pragma_poison);
1264 register_pragma_internal (pfile, "GCC", "system_header",
1265 do_pragma_system_header);
1266 register_pragma_internal (pfile, "GCC", "dependency", do_pragma_dependency);
1267 register_pragma_internal (pfile, "GCC", "warning", do_pragma_warning);
1268 register_pragma_internal (pfile, "GCC", "error", do_pragma_error);
1271 /* Return the number of registered pragmas in PE. */
1273 static int
1274 count_registered_pragmas (struct pragma_entry *pe)
1276 int ct = 0;
1277 for (; pe != NULL; pe = pe->next)
1279 if (pe->is_nspace)
1280 ct += count_registered_pragmas (pe->u.space);
1281 ct++;
1283 return ct;
1286 /* Save into SD the names of the registered pragmas referenced by PE,
1287 and return a pointer to the next free space in SD. */
1289 static char **
1290 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1292 for (; pe != NULL; pe = pe->next)
1294 if (pe->is_nspace)
1295 sd = save_registered_pragmas (pe->u.space, sd);
1296 *sd++ = (char *) xmemdup (HT_STR (&pe->pragma->ident),
1297 HT_LEN (&pe->pragma->ident),
1298 HT_LEN (&pe->pragma->ident) + 1);
1300 return sd;
1303 /* Return a newly-allocated array which saves the names of the
1304 registered pragmas. */
1306 char **
1307 _cpp_save_pragma_names (cpp_reader *pfile)
1309 int ct = count_registered_pragmas (pfile->pragmas);
1310 char **result = XNEWVEC (char *, ct);
1311 (void) save_registered_pragmas (pfile->pragmas, result);
1312 return result;
1315 /* Restore from SD the names of the registered pragmas referenced by PE,
1316 and return a pointer to the next unused name in SD. */
1318 static char **
1319 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1320 char **sd)
1322 for (; pe != NULL; pe = pe->next)
1324 if (pe->is_nspace)
1325 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1326 pe->pragma = cpp_lookup (pfile, UC *sd, strlen (*sd));
1327 free (*sd);
1328 sd++;
1330 return sd;
1333 /* Restore the names of the registered pragmas from SAVED. */
1335 void
1336 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1338 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1339 free (saved);
1342 /* Pragmata handling. We handle some, and pass the rest on to the
1343 front end. C99 defines three pragmas and says that no macro
1344 expansion is to be performed on them; whether or not macro
1345 expansion happens for other pragmas is implementation defined.
1346 This implementation allows for a mix of both, since GCC did not
1347 traditionally macro expand its (few) pragmas, whereas OpenMP
1348 specifies that macro expansion should happen. */
1349 static void
1350 do_pragma (cpp_reader *pfile)
1352 const struct pragma_entry *p = NULL;
1353 const cpp_token *token, *pragma_token;
1354 source_location pragma_token_virt_loc = 0;
1355 cpp_token ns_token;
1356 unsigned int count = 1;
1358 pfile->state.prevent_expansion++;
1360 pragma_token = token = cpp_get_token_with_location (pfile,
1361 &pragma_token_virt_loc);
1362 ns_token = *token;
1363 if (token->type == CPP_NAME)
1365 p = lookup_pragma_entry (pfile->pragmas, token->val.node.node);
1366 if (p && p->is_nspace)
1368 bool allow_name_expansion = p->allow_expansion;
1369 if (allow_name_expansion)
1370 pfile->state.prevent_expansion--;
1372 token = cpp_get_token (pfile);
1373 if (token->type == CPP_NAME)
1374 p = lookup_pragma_entry (p->u.space, token->val.node.node);
1375 else
1376 p = NULL;
1377 if (allow_name_expansion)
1378 pfile->state.prevent_expansion++;
1379 count = 2;
1383 if (p)
1385 if (p->is_deferred)
1387 pfile->directive_result.src_loc = pragma_token_virt_loc;
1388 pfile->directive_result.type = CPP_PRAGMA;
1389 pfile->directive_result.flags = pragma_token->flags;
1390 pfile->directive_result.val.pragma = p->u.ident;
1391 pfile->state.in_deferred_pragma = true;
1392 pfile->state.pragma_allow_expansion = p->allow_expansion;
1393 if (!p->allow_expansion)
1394 pfile->state.prevent_expansion++;
1396 else
1398 /* Since the handler below doesn't get the line number, that
1399 it might need for diagnostics, make sure it has the right
1400 numbers in place. */
1401 if (pfile->cb.line_change)
1402 (*pfile->cb.line_change) (pfile, pragma_token, false);
1403 if (p->allow_expansion)
1404 pfile->state.prevent_expansion--;
1405 (*p->u.handler) (pfile);
1406 if (p->allow_expansion)
1407 pfile->state.prevent_expansion++;
1410 else if (pfile->cb.def_pragma)
1412 if (count == 1 || pfile->context->prev == NULL)
1413 _cpp_backup_tokens (pfile, count);
1414 else
1416 /* Invalid name comes from macro expansion, _cpp_backup_tokens
1417 won't allow backing 2 tokens. */
1418 /* ??? The token buffer is leaked. Perhaps if def_pragma hook
1419 reads both tokens, we could perhaps free it, but if it doesn't,
1420 we don't know the exact lifespan. */
1421 cpp_token *toks = XNEWVEC (cpp_token, 2);
1422 toks[0] = ns_token;
1423 toks[0].flags |= NO_EXPAND;
1424 toks[1] = *token;
1425 toks[1].flags |= NO_EXPAND;
1426 _cpp_push_token_context (pfile, NULL, toks, 2);
1428 pfile->cb.def_pragma (pfile, pfile->directive_line);
1431 pfile->state.prevent_expansion--;
1434 /* Handle #pragma once. */
1435 static void
1436 do_pragma_once (cpp_reader *pfile)
1438 if (cpp_in_primary_file (pfile))
1439 cpp_error (pfile, CPP_DL_WARNING, "#pragma once in main file");
1441 check_eol (pfile, false);
1442 _cpp_mark_file_once_only (pfile, pfile->buffer->file);
1445 /* Handle #pragma push_macro(STRING). */
1446 static void
1447 do_pragma_push_macro (cpp_reader *pfile)
1449 cpp_hashnode *node;
1450 size_t defnlen;
1451 const uchar *defn = NULL;
1452 char *macroname, *dest;
1453 const char *limit, *src;
1454 const cpp_token *txt;
1455 struct def_pragma_macro *c;
1457 txt = get__Pragma_string (pfile);
1458 if (!txt)
1460 source_location src_loc = pfile->cur_token[-1].src_loc;
1461 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1462 "invalid #pragma push_macro directive");
1463 check_eol (pfile, false);
1464 skip_rest_of_line (pfile);
1465 return;
1467 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1468 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1469 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1470 while (src < limit)
1472 /* We know there is a character following the backslash. */
1473 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1474 src++;
1475 *dest++ = *src++;
1477 *dest = 0;
1478 check_eol (pfile, false);
1479 skip_rest_of_line (pfile);
1480 c = XNEW (struct def_pragma_macro);
1481 memset (c, 0, sizeof (struct def_pragma_macro));
1482 c->name = XNEWVAR (char, strlen (macroname) + 1);
1483 strcpy (c->name, macroname);
1484 c->next = pfile->pushed_macros;
1485 node = _cpp_lex_identifier (pfile, c->name);
1486 if (node->type == NT_VOID)
1487 c->is_undef = 1;
1488 else
1490 defn = cpp_macro_definition (pfile, node);
1491 defnlen = ustrlen (defn);
1492 c->definition = XNEWVEC (uchar, defnlen + 2);
1493 c->definition[defnlen] = '\n';
1494 c->definition[defnlen + 1] = 0;
1495 c->line = node->value.macro->line;
1496 c->syshdr = node->value.macro->syshdr;
1497 c->used = node->value.macro->used;
1498 memcpy (c->definition, defn, defnlen);
1501 pfile->pushed_macros = c;
1504 /* Handle #pragma pop_macro(STRING). */
1505 static void
1506 do_pragma_pop_macro (cpp_reader *pfile)
1508 char *macroname, *dest;
1509 const char *limit, *src;
1510 const cpp_token *txt;
1511 struct def_pragma_macro *l = NULL, *c = pfile->pushed_macros;
1512 txt = get__Pragma_string (pfile);
1513 if (!txt)
1515 source_location src_loc = pfile->cur_token[-1].src_loc;
1516 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1517 "invalid #pragma pop_macro directive");
1518 check_eol (pfile, false);
1519 skip_rest_of_line (pfile);
1520 return;
1522 dest = macroname = (char *) alloca (txt->val.str.len + 2);
1523 src = (const char *) (txt->val.str.text + 1 + (txt->val.str.text[0] == 'L'));
1524 limit = (const char *) (txt->val.str.text + txt->val.str.len - 1);
1525 while (src < limit)
1527 /* We know there is a character following the backslash. */
1528 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1529 src++;
1530 *dest++ = *src++;
1532 *dest = 0;
1533 check_eol (pfile, false);
1534 skip_rest_of_line (pfile);
1536 while (c != NULL)
1538 if (!strcmp (c->name, macroname))
1540 if (!l)
1541 pfile->pushed_macros = c->next;
1542 else
1543 l->next = c->next;
1544 cpp_pop_definition (pfile, c);
1545 free (c->definition);
1546 free (c->name);
1547 free (c);
1548 break;
1550 l = c;
1551 c = c->next;
1555 /* Handle #pragma GCC poison, to poison one or more identifiers so
1556 that the lexer produces a hard error for each subsequent usage. */
1557 static void
1558 do_pragma_poison (cpp_reader *pfile)
1560 const cpp_token *tok;
1561 cpp_hashnode *hp;
1563 pfile->state.poisoned_ok = 1;
1564 for (;;)
1566 tok = _cpp_lex_token (pfile);
1567 if (tok->type == CPP_EOF)
1568 break;
1569 if (tok->type != CPP_NAME)
1571 cpp_error (pfile, CPP_DL_ERROR,
1572 "invalid #pragma GCC poison directive");
1573 break;
1576 hp = tok->val.node.node;
1577 if (hp->flags & NODE_POISONED)
1578 continue;
1580 if (hp->type == NT_MACRO)
1581 cpp_error (pfile, CPP_DL_WARNING, "poisoning existing macro \"%s\"",
1582 NODE_NAME (hp));
1583 _cpp_free_definition (hp);
1584 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1586 pfile->state.poisoned_ok = 0;
1589 /* Mark the current header as a system header. This will suppress
1590 some categories of warnings (notably those from -pedantic). It is
1591 intended for use in system libraries that cannot be implemented in
1592 conforming C, but cannot be certain that their headers appear in a
1593 system include directory. To prevent abuse, it is rejected in the
1594 primary source file. */
1595 static void
1596 do_pragma_system_header (cpp_reader *pfile)
1598 if (cpp_in_primary_file (pfile))
1599 cpp_error (pfile, CPP_DL_WARNING,
1600 "#pragma system_header ignored outside include file");
1601 else
1603 check_eol (pfile, false);
1604 skip_rest_of_line (pfile);
1605 cpp_make_system_header (pfile, 1, 0);
1609 /* Check the modified date of the current include file against a specified
1610 file. Issue a diagnostic, if the specified file is newer. We use this to
1611 determine if a fixed header should be refixed. */
1612 static void
1613 do_pragma_dependency (cpp_reader *pfile)
1615 const char *fname;
1616 int angle_brackets, ordering;
1617 source_location location;
1619 fname = parse_include (pfile, &angle_brackets, NULL, &location);
1620 if (!fname)
1621 return;
1623 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1624 if (ordering < 0)
1625 cpp_error (pfile, CPP_DL_WARNING, "cannot find source file %s", fname);
1626 else if (ordering > 0)
1628 cpp_error (pfile, CPP_DL_WARNING,
1629 "current file is older than %s", fname);
1630 if (cpp_get_token (pfile)->type != CPP_EOF)
1632 _cpp_backup_tokens (pfile, 1);
1633 do_diagnostic (pfile, CPP_DL_WARNING, 0, 0);
1637 free ((void *) fname);
1640 /* Issue a diagnostic with the message taken from the pragma. If
1641 ERROR is true, the diagnostic is a warning, otherwise, it is an
1642 error. */
1643 static void
1644 do_pragma_warning_or_error (cpp_reader *pfile, bool error)
1646 const cpp_token *tok = _cpp_lex_token (pfile);
1647 cpp_string str;
1648 if (tok->type != CPP_STRING
1649 || !cpp_interpret_string_notranslate (pfile, &tok->val.str, 1, &str,
1650 CPP_STRING)
1651 || str.len == 0)
1653 cpp_error (pfile, CPP_DL_ERROR, "invalid \"#pragma GCC %s\" directive",
1654 error ? "error" : "warning");
1655 return;
1657 cpp_error (pfile, error ? CPP_DL_ERROR : CPP_DL_WARNING,
1658 "%s", str.text);
1659 free ((void *)str.text);
1662 /* Issue a warning diagnostic. */
1663 static void
1664 do_pragma_warning (cpp_reader *pfile)
1666 do_pragma_warning_or_error (pfile, false);
1669 /* Issue an error diagnostic. */
1670 static void
1671 do_pragma_error (cpp_reader *pfile)
1673 do_pragma_warning_or_error (pfile, true);
1676 /* Get a token but skip padding. */
1677 static const cpp_token *
1678 get_token_no_padding (cpp_reader *pfile)
1680 for (;;)
1682 const cpp_token *result = cpp_get_token (pfile);
1683 if (result->type != CPP_PADDING)
1684 return result;
1688 /* Check syntax is "(string-literal)". Returns the string on success,
1689 or NULL on failure. */
1690 static const cpp_token *
1691 get__Pragma_string (cpp_reader *pfile)
1693 const cpp_token *string;
1694 const cpp_token *paren;
1696 paren = get_token_no_padding (pfile);
1697 if (paren->type == CPP_EOF)
1698 _cpp_backup_tokens (pfile, 1);
1699 if (paren->type != CPP_OPEN_PAREN)
1700 return NULL;
1702 string = get_token_no_padding (pfile);
1703 if (string->type == CPP_EOF)
1704 _cpp_backup_tokens (pfile, 1);
1705 if (string->type != CPP_STRING && string->type != CPP_WSTRING
1706 && string->type != CPP_STRING32 && string->type != CPP_STRING16
1707 && string->type != CPP_UTF8STRING)
1708 return NULL;
1710 paren = get_token_no_padding (pfile);
1711 if (paren->type == CPP_EOF)
1712 _cpp_backup_tokens (pfile, 1);
1713 if (paren->type != CPP_CLOSE_PAREN)
1714 return NULL;
1716 return string;
1719 /* Destringize IN into a temporary buffer, by removing the first \ of
1720 \" and \\ sequences, and process the result as a #pragma directive. */
1721 static void
1722 destringize_and_run (cpp_reader *pfile, const cpp_string *in)
1724 const unsigned char *src, *limit;
1725 char *dest, *result;
1726 cpp_context *saved_context;
1727 cpp_token *saved_cur_token;
1728 tokenrun *saved_cur_run;
1729 cpp_token *toks;
1730 int count;
1731 const struct directive *save_directive;
1733 dest = result = (char *) alloca (in->len - 1);
1734 src = in->text + 1 + (in->text[0] == 'L');
1735 limit = in->text + in->len - 1;
1736 while (src < limit)
1738 /* We know there is a character following the backslash. */
1739 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1740 src++;
1741 *dest++ = *src++;
1743 *dest = '\n';
1745 /* Ugh; an awful kludge. We are really not set up to be lexing
1746 tokens when in the middle of a macro expansion. Use a new
1747 context to force cpp_get_token to lex, and so skip_rest_of_line
1748 doesn't go beyond the end of the text. Also, remember the
1749 current lexing position so we can return to it later.
1751 Something like line-at-a-time lexing should remove the need for
1752 this. */
1753 saved_context = pfile->context;
1754 saved_cur_token = pfile->cur_token;
1755 saved_cur_run = pfile->cur_run;
1757 pfile->context = XCNEW (cpp_context);
1759 /* Inline run_directive, since we need to delay the _cpp_pop_buffer
1760 until we've read all of the tokens that we want. */
1761 cpp_push_buffer (pfile, (const uchar *) result, dest - result,
1762 /* from_stage3 */ true);
1763 /* ??? Antique Disgusting Hack. What does this do? */
1764 if (pfile->buffer->prev)
1765 pfile->buffer->file = pfile->buffer->prev->file;
1767 start_directive (pfile);
1768 _cpp_clean_line (pfile);
1769 save_directive = pfile->directive;
1770 pfile->directive = &dtable[T_PRAGMA];
1771 do_pragma (pfile);
1772 end_directive (pfile, 1);
1773 pfile->directive = save_directive;
1775 /* We always insert at least one token, the directive result. It'll
1776 either be a CPP_PADDING or a CPP_PRAGMA. In the later case, we
1777 need to insert *all* of the tokens, including the CPP_PRAGMA_EOL. */
1779 /* If we're not handling the pragma internally, read all of the tokens from
1780 the string buffer now, while the string buffer is still installed. */
1781 /* ??? Note that the token buffer allocated here is leaked. It's not clear
1782 to me what the true lifespan of the tokens are. It would appear that
1783 the lifespan is the entire parse of the main input stream, in which case
1784 this may not be wrong. */
1785 if (pfile->directive_result.type == CPP_PRAGMA)
1787 int maxcount;
1789 count = 1;
1790 maxcount = 50;
1791 toks = XNEWVEC (cpp_token, maxcount);
1792 toks[0] = pfile->directive_result;
1796 if (count == maxcount)
1798 maxcount = maxcount * 3 / 2;
1799 toks = XRESIZEVEC (cpp_token, toks, maxcount);
1801 toks[count] = *cpp_get_token (pfile);
1802 /* Macros have been already expanded by cpp_get_token
1803 if the pragma allowed expansion. */
1804 toks[count++].flags |= NO_EXPAND;
1806 while (toks[count-1].type != CPP_PRAGMA_EOL);
1808 else
1810 count = 1;
1811 toks = XNEW (cpp_token);
1812 toks[0] = pfile->directive_result;
1814 /* If we handled the entire pragma internally, make sure we get the
1815 line number correct for the next token. */
1816 if (pfile->cb.line_change)
1817 pfile->cb.line_change (pfile, pfile->cur_token, false);
1820 /* Finish inlining run_directive. */
1821 pfile->buffer->file = NULL;
1822 _cpp_pop_buffer (pfile);
1824 /* Reset the old macro state before ... */
1825 XDELETE (pfile->context);
1826 pfile->context = saved_context;
1827 pfile->cur_token = saved_cur_token;
1828 pfile->cur_run = saved_cur_run;
1830 /* ... inserting the new tokens we collected. */
1831 _cpp_push_token_context (pfile, NULL, toks, count);
1834 /* Handle the _Pragma operator. Return 0 on error, 1 if ok. */
1836 _cpp_do__Pragma (cpp_reader *pfile)
1838 const cpp_token *string = get__Pragma_string (pfile);
1839 pfile->directive_result.type = CPP_PADDING;
1841 if (string)
1843 destringize_and_run (pfile, &string->val.str);
1844 return 1;
1846 cpp_error (pfile, CPP_DL_ERROR,
1847 "_Pragma takes a parenthesized string literal");
1848 return 0;
1851 /* Handle #ifdef. */
1852 static void
1853 do_ifdef (cpp_reader *pfile)
1855 int skip = 1;
1857 if (! pfile->state.skipping)
1859 cpp_hashnode *node = lex_macro_node (pfile, false);
1861 if (node)
1863 /* Do not treat conditional macros as being defined. This is due to
1864 the powerpc and spu ports using conditional macros for 'vector',
1865 'bool', and 'pixel' to act as conditional keywords. This messes
1866 up tests like #ifndef bool. */
1867 skip = (node->type != NT_MACRO
1868 || ((node->flags & NODE_CONDITIONAL) != 0));
1869 _cpp_mark_macro_used (node);
1870 if (!(node->flags & NODE_USED))
1872 node->flags |= NODE_USED;
1873 if (node->type == NT_MACRO)
1875 if ((node->flags & NODE_BUILTIN)
1876 && pfile->cb.user_builtin_macro)
1877 pfile->cb.user_builtin_macro (pfile, node);
1878 if (pfile->cb.used_define)
1879 pfile->cb.used_define (pfile, pfile->directive_line, node);
1881 else
1883 if (pfile->cb.used_undef)
1884 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1887 if (pfile->cb.used)
1888 pfile->cb.used (pfile, pfile->directive_line, node);
1889 check_eol (pfile, false);
1893 push_conditional (pfile, skip, T_IFDEF, 0);
1896 /* Handle #ifndef. */
1897 static void
1898 do_ifndef (cpp_reader *pfile)
1900 int skip = 1;
1901 cpp_hashnode *node = 0;
1903 if (! pfile->state.skipping)
1905 node = lex_macro_node (pfile, false);
1907 if (node)
1909 /* Do not treat conditional macros as being defined. This is due to
1910 the powerpc and spu ports using conditional macros for 'vector',
1911 'bool', and 'pixel' to act as conditional keywords. This messes
1912 up tests like #ifndef bool. */
1913 skip = (node->type == NT_MACRO
1914 && ((node->flags & NODE_CONDITIONAL) == 0));
1915 _cpp_mark_macro_used (node);
1916 if (!(node->flags & NODE_USED))
1918 node->flags |= NODE_USED;
1919 if (node->type == NT_MACRO)
1921 if ((node->flags & NODE_BUILTIN)
1922 && pfile->cb.user_builtin_macro)
1923 pfile->cb.user_builtin_macro (pfile, node);
1924 if (pfile->cb.used_define)
1925 pfile->cb.used_define (pfile, pfile->directive_line, node);
1927 else
1929 if (pfile->cb.used_undef)
1930 pfile->cb.used_undef (pfile, pfile->directive_line, node);
1933 if (pfile->cb.used)
1934 pfile->cb.used (pfile, pfile->directive_line, node);
1935 check_eol (pfile, false);
1939 push_conditional (pfile, skip, T_IFNDEF, node);
1942 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1943 pfile->mi_ind_cmacro so we can handle multiple-include
1944 optimizations. If macro expansion occurs in the expression, we
1945 cannot treat it as a controlling conditional, since the expansion
1946 could change in the future. That is handled by cpp_get_token. */
1947 static void
1948 do_if (cpp_reader *pfile)
1950 int skip = 1;
1952 if (! pfile->state.skipping)
1953 skip = _cpp_parse_expr (pfile, true) == false;
1955 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1958 /* Flip skipping state if appropriate and continue without changing
1959 if_stack; this is so that the error message for missing #endif's
1960 etc. will point to the original #if. */
1961 static void
1962 do_else (cpp_reader *pfile)
1964 cpp_buffer *buffer = pfile->buffer;
1965 struct if_stack *ifs = buffer->if_stack;
1967 if (ifs == NULL)
1968 cpp_error (pfile, CPP_DL_ERROR, "#else without #if");
1969 else
1971 if (ifs->type == T_ELSE)
1973 cpp_error (pfile, CPP_DL_ERROR, "#else after #else");
1974 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
1975 "the conditional began here");
1977 ifs->type = T_ELSE;
1979 /* Skip any future (erroneous) #elses or #elifs. */
1980 pfile->state.skipping = ifs->skip_elses;
1981 ifs->skip_elses = true;
1983 /* Invalidate any controlling macro. */
1984 ifs->mi_cmacro = 0;
1986 /* Only check EOL if was not originally skipping. */
1987 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1988 check_eol (pfile, false);
1992 /* Handle a #elif directive by not changing if_stack either. See the
1993 comment above do_else. */
1994 static void
1995 do_elif (cpp_reader *pfile)
1997 cpp_buffer *buffer = pfile->buffer;
1998 struct if_stack *ifs = buffer->if_stack;
2000 if (ifs == NULL)
2001 cpp_error (pfile, CPP_DL_ERROR, "#elif without #if");
2002 else
2004 if (ifs->type == T_ELSE)
2006 cpp_error (pfile, CPP_DL_ERROR, "#elif after #else");
2007 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2008 "the conditional began here");
2010 ifs->type = T_ELIF;
2012 if (! ifs->was_skipping)
2014 bool value;
2015 /* The standard mandates that the expression be parsed even
2016 if we are skipping elses at this point -- the lexical
2017 restrictions on #elif only apply to skipped groups, but
2018 this group is not being skipped. Temporarily set
2019 skipping to false to get lexer warnings. */
2020 pfile->state.skipping = 0;
2021 value = _cpp_parse_expr (pfile, false);
2022 if (ifs->skip_elses)
2023 pfile->state.skipping = 1;
2024 else
2026 pfile->state.skipping = ! value;
2027 ifs->skip_elses = value;
2031 /* Invalidate any controlling macro. */
2032 ifs->mi_cmacro = 0;
2036 /* #endif pops the if stack and resets pfile->state.skipping. */
2037 static void
2038 do_endif (cpp_reader *pfile)
2040 cpp_buffer *buffer = pfile->buffer;
2041 struct if_stack *ifs = buffer->if_stack;
2043 if (ifs == NULL)
2044 cpp_error (pfile, CPP_DL_ERROR, "#endif without #if");
2045 else
2047 /* Only check EOL if was not originally skipping. */
2048 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
2049 check_eol (pfile, false);
2051 /* If potential control macro, we go back outside again. */
2052 if (ifs->next == 0 && ifs->mi_cmacro)
2054 pfile->mi_valid = true;
2055 pfile->mi_cmacro = ifs->mi_cmacro;
2058 buffer->if_stack = ifs->next;
2059 pfile->state.skipping = ifs->was_skipping;
2060 obstack_free (&pfile->buffer_ob, ifs);
2064 /* Push an if_stack entry for a preprocessor conditional, and set
2065 pfile->state.skipping to SKIP. If TYPE indicates the conditional
2066 is #if or #ifndef, CMACRO is a potentially controlling macro, and
2067 we need to check here that we are at the top of the file. */
2068 static void
2069 push_conditional (cpp_reader *pfile, int skip, int type,
2070 const cpp_hashnode *cmacro)
2072 struct if_stack *ifs;
2073 cpp_buffer *buffer = pfile->buffer;
2075 ifs = XOBNEW (&pfile->buffer_ob, struct if_stack);
2076 ifs->line = pfile->directive_line;
2077 ifs->next = buffer->if_stack;
2078 ifs->skip_elses = pfile->state.skipping || !skip;
2079 ifs->was_skipping = pfile->state.skipping;
2080 ifs->type = type;
2081 /* This condition is effectively a test for top-of-file. */
2082 if (pfile->mi_valid && pfile->mi_cmacro == 0)
2083 ifs->mi_cmacro = cmacro;
2084 else
2085 ifs->mi_cmacro = 0;
2087 pfile->state.skipping = skip;
2088 buffer->if_stack = ifs;
2091 /* Read the tokens of the answer into the macro pool, in a directive
2092 of type TYPE. Only commit the memory if we intend it as permanent
2093 storage, i.e. the #assert case. Returns 0 on success, and sets
2094 ANSWERP to point to the answer. PRED_LOC is the location of the
2095 predicate. */
2096 static int
2097 parse_answer (cpp_reader *pfile, struct answer **answerp, int type,
2098 source_location pred_loc)
2100 const cpp_token *paren;
2101 struct answer *answer;
2102 unsigned int acount;
2104 /* In a conditional, it is legal to not have an open paren. We
2105 should save the following token in this case. */
2106 paren = cpp_get_token (pfile);
2108 /* If not a paren, see if we're OK. */
2109 if (paren->type != CPP_OPEN_PAREN)
2111 /* In a conditional no answer is a test for any answer. It
2112 could be followed by any token. */
2113 if (type == T_IF)
2115 _cpp_backup_tokens (pfile, 1);
2116 return 0;
2119 /* #unassert with no answer is valid - it removes all answers. */
2120 if (type == T_UNASSERT && paren->type == CPP_EOF)
2121 return 0;
2123 cpp_error_with_line (pfile, CPP_DL_ERROR, pred_loc, 0,
2124 "missing '(' after predicate");
2125 return 1;
2128 for (acount = 0;; acount++)
2130 size_t room_needed;
2131 const cpp_token *token = cpp_get_token (pfile);
2132 cpp_token *dest;
2134 if (token->type == CPP_CLOSE_PAREN)
2135 break;
2137 if (token->type == CPP_EOF)
2139 cpp_error (pfile, CPP_DL_ERROR, "missing ')' to complete answer");
2140 return 1;
2143 /* struct answer includes the space for one token. */
2144 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
2146 if (BUFF_ROOM (pfile->a_buff) < room_needed)
2147 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
2149 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
2150 *dest = *token;
2152 /* Drop whitespace at start, for answer equivalence purposes. */
2153 if (acount == 0)
2154 dest->flags &= ~PREV_WHITE;
2157 if (acount == 0)
2159 cpp_error (pfile, CPP_DL_ERROR, "predicate's answer is empty");
2160 return 1;
2163 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
2164 answer->count = acount;
2165 answer->next = NULL;
2166 *answerp = answer;
2168 return 0;
2171 /* Parses an assertion directive of type TYPE, returning a pointer to
2172 the hash node of the predicate, or 0 on error. If an answer was
2173 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
2174 static cpp_hashnode *
2175 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
2177 cpp_hashnode *result = 0;
2178 const cpp_token *predicate;
2180 /* We don't expand predicates or answers. */
2181 pfile->state.prevent_expansion++;
2183 *answerp = 0;
2184 predicate = cpp_get_token (pfile);
2185 if (predicate->type == CPP_EOF)
2186 cpp_error (pfile, CPP_DL_ERROR, "assertion without predicate");
2187 else if (predicate->type != CPP_NAME)
2188 cpp_error_with_line (pfile, CPP_DL_ERROR, predicate->src_loc, 0,
2189 "predicate must be an identifier");
2190 else if (parse_answer (pfile, answerp, type, predicate->src_loc) == 0)
2192 unsigned int len = NODE_LEN (predicate->val.node.node);
2193 unsigned char *sym = (unsigned char *) alloca (len + 1);
2195 /* Prefix '#' to get it out of macro namespace. */
2196 sym[0] = '#';
2197 memcpy (sym + 1, NODE_NAME (predicate->val.node.node), len);
2198 result = cpp_lookup (pfile, sym, len + 1);
2201 pfile->state.prevent_expansion--;
2202 return result;
2205 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
2206 or a pointer to NULL if the answer is not in the chain. */
2207 static struct answer **
2208 find_answer (cpp_hashnode *node, const struct answer *candidate)
2210 unsigned int i;
2211 struct answer **result;
2213 for (result = &node->value.answers; *result; result = &(*result)->next)
2215 struct answer *answer = *result;
2217 if (answer->count == candidate->count)
2219 for (i = 0; i < answer->count; i++)
2220 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
2221 break;
2223 if (i == answer->count)
2224 break;
2228 return result;
2231 /* Test an assertion within a preprocessor conditional. Returns
2232 nonzero on failure, zero on success. On success, the result of
2233 the test is written into VALUE, otherwise the value 0. */
2235 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
2237 struct answer *answer;
2238 cpp_hashnode *node;
2240 node = parse_assertion (pfile, &answer, T_IF);
2242 /* For recovery, an erroneous assertion expression is handled as a
2243 failing assertion. */
2244 *value = 0;
2246 if (node)
2247 *value = (node->type == NT_ASSERTION &&
2248 (answer == 0 || *find_answer (node, answer) != 0));
2249 else if (pfile->cur_token[-1].type == CPP_EOF)
2250 _cpp_backup_tokens (pfile, 1);
2252 /* We don't commit the memory for the answer - it's temporary only. */
2253 return node == 0;
2256 /* Handle #assert. */
2257 static void
2258 do_assert (cpp_reader *pfile)
2260 struct answer *new_answer;
2261 cpp_hashnode *node;
2263 node = parse_assertion (pfile, &new_answer, T_ASSERT);
2264 if (node)
2266 size_t answer_size;
2268 /* Place the new answer in the answer list. First check there
2269 is not a duplicate. */
2270 new_answer->next = 0;
2271 if (node->type == NT_ASSERTION)
2273 if (*find_answer (node, new_answer))
2275 cpp_error (pfile, CPP_DL_WARNING, "\"%s\" re-asserted",
2276 NODE_NAME (node) + 1);
2277 return;
2279 new_answer->next = node->value.answers;
2282 answer_size = sizeof (struct answer) + ((new_answer->count - 1)
2283 * sizeof (cpp_token));
2284 /* Commit or allocate storage for the object. */
2285 if (pfile->hash_table->alloc_subobject)
2287 struct answer *temp_answer = new_answer;
2288 new_answer = (struct answer *) pfile->hash_table->alloc_subobject
2289 (answer_size);
2290 memcpy (new_answer, temp_answer, answer_size);
2292 else
2293 BUFF_FRONT (pfile->a_buff) += answer_size;
2295 node->type = NT_ASSERTION;
2296 node->value.answers = new_answer;
2297 check_eol (pfile, false);
2301 /* Handle #unassert. */
2302 static void
2303 do_unassert (cpp_reader *pfile)
2305 cpp_hashnode *node;
2306 struct answer *answer;
2308 node = parse_assertion (pfile, &answer, T_UNASSERT);
2309 /* It isn't an error to #unassert something that isn't asserted. */
2310 if (node && node->type == NT_ASSERTION)
2312 if (answer)
2314 struct answer **p = find_answer (node, answer), *temp;
2316 /* Remove the answer from the list. */
2317 temp = *p;
2318 if (temp)
2319 *p = temp->next;
2321 /* Did we free the last answer? */
2322 if (node->value.answers == 0)
2323 node->type = NT_VOID;
2325 check_eol (pfile, false);
2327 else
2328 _cpp_free_definition (node);
2331 /* We don't commit the memory for the answer - it's temporary only. */
2334 /* These are for -D, -U, -A. */
2336 /* Process the string STR as if it appeared as the body of a #define.
2337 If STR is just an identifier, define it with value 1.
2338 If STR has anything after the identifier, then it should
2339 be identifier=definition. */
2340 void
2341 cpp_define (cpp_reader *pfile, const char *str)
2343 char *buf;
2344 const char *p;
2345 size_t count;
2347 /* Copy the entire option so we can modify it.
2348 Change the first "=" in the string to a space. If there is none,
2349 tack " 1" on the end. */
2351 count = strlen (str);
2352 buf = (char *) alloca (count + 3);
2353 memcpy (buf, str, count);
2355 p = strchr (str, '=');
2356 if (p)
2357 buf[p - str] = ' ';
2358 else
2360 buf[count++] = ' ';
2361 buf[count++] = '1';
2363 buf[count] = '\n';
2365 run_directive (pfile, T_DEFINE, buf, count);
2369 /* Use to build macros to be run through cpp_define() as
2370 described above.
2371 Example: cpp_define_formatted (pfile, "MACRO=%d", value); */
2373 void
2374 cpp_define_formatted (cpp_reader *pfile, const char *fmt, ...)
2376 char *ptr = NULL;
2378 va_list ap;
2379 va_start (ap, fmt);
2380 vasprintf (&ptr, fmt, ap);
2381 va_end (ap);
2383 cpp_define (pfile, ptr);
2384 free (ptr);
2388 /* Slight variant of the above for use by initialize_builtins. */
2389 void
2390 _cpp_define_builtin (cpp_reader *pfile, const char *str)
2392 size_t len = strlen (str);
2393 char *buf = (char *) alloca (len + 1);
2394 memcpy (buf, str, len);
2395 buf[len] = '\n';
2396 run_directive (pfile, T_DEFINE, buf, len);
2399 /* Process MACRO as if it appeared as the body of an #undef. */
2400 void
2401 cpp_undef (cpp_reader *pfile, const char *macro)
2403 size_t len = strlen (macro);
2404 char *buf = (char *) alloca (len + 1);
2405 memcpy (buf, macro, len);
2406 buf[len] = '\n';
2407 run_directive (pfile, T_UNDEF, buf, len);
2410 /* Replace a previous definition DEF of the macro STR. If DEF is NULL,
2411 or first element is zero, then the macro should be undefined. */
2412 static void
2413 cpp_pop_definition (cpp_reader *pfile, struct def_pragma_macro *c)
2415 cpp_hashnode *node = _cpp_lex_identifier (pfile, c->name);
2416 if (node == NULL)
2417 return;
2419 if (pfile->cb.before_define)
2420 pfile->cb.before_define (pfile);
2422 if (node->type == NT_MACRO)
2424 if (pfile->cb.undef)
2425 pfile->cb.undef (pfile, pfile->directive_line, node);
2426 if (CPP_OPTION (pfile, warn_unused_macros))
2427 _cpp_warn_if_unused_macro (pfile, node, NULL);
2429 if (node->type != NT_VOID)
2430 _cpp_free_definition (node);
2432 if (c->is_undef)
2433 return;
2435 size_t namelen;
2436 const uchar *dn;
2437 cpp_hashnode *h = NULL;
2438 cpp_buffer *nbuf;
2440 namelen = ustrcspn (c->definition, "( \n");
2441 h = cpp_lookup (pfile, c->definition, namelen);
2442 dn = c->definition + namelen;
2444 h->type = NT_VOID;
2445 h->flags &= ~(NODE_POISONED|NODE_BUILTIN|NODE_DISABLED|NODE_USED);
2446 nbuf = cpp_push_buffer (pfile, dn, ustrchr (dn, '\n') - dn, true);
2447 if (nbuf != NULL)
2449 _cpp_clean_line (pfile);
2450 nbuf->sysp = 1;
2451 if (!_cpp_create_definition (pfile, h))
2452 abort ();
2453 _cpp_pop_buffer (pfile);
2455 else
2456 abort ();
2457 h->value.macro->line = c->line;
2458 h->value.macro->syshdr = c->syshdr;
2459 h->value.macro->used = c->used;
2463 /* Process the string STR as if it appeared as the body of a #assert. */
2464 void
2465 cpp_assert (cpp_reader *pfile, const char *str)
2467 handle_assertion (pfile, str, T_ASSERT);
2470 /* Process STR as if it appeared as the body of an #unassert. */
2471 void
2472 cpp_unassert (cpp_reader *pfile, const char *str)
2474 handle_assertion (pfile, str, T_UNASSERT);
2477 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
2478 static void
2479 handle_assertion (cpp_reader *pfile, const char *str, int type)
2481 size_t count = strlen (str);
2482 const char *p = strchr (str, '=');
2484 /* Copy the entire option so we can modify it. Change the first
2485 "=" in the string to a '(', and tack a ')' on the end. */
2486 char *buf = (char *) alloca (count + 2);
2488 memcpy (buf, str, count);
2489 if (p)
2491 buf[p - str] = '(';
2492 buf[count++] = ')';
2494 buf[count] = '\n';
2495 str = buf;
2497 run_directive (pfile, type, str, count);
2500 /* The options structure. */
2501 cpp_options *
2502 cpp_get_options (cpp_reader *pfile)
2504 return &pfile->opts;
2507 /* The callbacks structure. */
2508 cpp_callbacks *
2509 cpp_get_callbacks (cpp_reader *pfile)
2511 return &pfile->cb;
2514 /* Copy the given callbacks structure to our own. */
2515 void
2516 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
2518 pfile->cb = *cb;
2521 /* The dependencies structure. (Creates one if it hasn't already been.) */
2522 struct deps *
2523 cpp_get_deps (cpp_reader *pfile)
2525 if (!pfile->deps)
2526 pfile->deps = deps_init ();
2527 return pfile->deps;
2530 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2531 doesn't fail. It does not generate a file change call back; that
2532 is the responsibility of the caller. */
2533 cpp_buffer *
2534 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
2535 int from_stage3)
2537 cpp_buffer *new_buffer = XOBNEW (&pfile->buffer_ob, cpp_buffer);
2539 /* Clears, amongst other things, if_stack and mi_cmacro. */
2540 memset (new_buffer, 0, sizeof (cpp_buffer));
2542 new_buffer->next_line = new_buffer->buf = buffer;
2543 new_buffer->rlimit = buffer + len;
2544 new_buffer->from_stage3 = from_stage3;
2545 new_buffer->prev = pfile->buffer;
2546 new_buffer->need_line = true;
2548 pfile->buffer = new_buffer;
2550 return new_buffer;
2553 /* Pops a single buffer, with a file change call-back if appropriate.
2554 Then pushes the next -include file, if any remain. */
2555 void
2556 _cpp_pop_buffer (cpp_reader *pfile)
2558 cpp_buffer *buffer = pfile->buffer;
2559 struct _cpp_file *inc = buffer->file;
2560 struct if_stack *ifs;
2561 const unsigned char *to_free;
2563 /* Walk back up the conditional stack till we reach its level at
2564 entry to this file, issuing error messages. */
2565 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2566 cpp_error_with_line (pfile, CPP_DL_ERROR, ifs->line, 0,
2567 "unterminated #%s", dtable[ifs->type].name);
2569 /* In case of a missing #endif. */
2570 pfile->state.skipping = 0;
2572 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2573 pfile->buffer = buffer->prev;
2575 to_free = buffer->to_free;
2576 free (buffer->notes);
2578 /* Free the buffer object now; we may want to push a new buffer
2579 in _cpp_push_next_include_file. */
2580 obstack_free (&pfile->buffer_ob, buffer);
2582 if (inc)
2584 _cpp_pop_file_buffer (pfile, inc, to_free);
2586 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2590 /* Enter all recognized directives in the hash table. */
2591 void
2592 _cpp_init_directives (cpp_reader *pfile)
2594 unsigned int i;
2595 cpp_hashnode *node;
2597 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2599 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2600 node->is_directive = 1;
2601 node->directive_index = i;