* target.h (encode_section_info): Add new argument carrying
[official-gcc.git] / gcc / cpplib.c
blobbb983b04a292682705db9593ced632eb1df30da2
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
4 Contributed by Per Bothner, 1994-95.
5 Based on CCCP program by Paul Rubin, June 1986
6 Adapted to ANSI C, Richard Stallman, Jan 1987
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
27 #include "cpplib.h"
28 #include "cpphash.h"
29 #include "obstack.h"
31 /* Chained list of answers to an assertion. */
32 struct answer
34 struct answer *next;
35 unsigned int count;
36 cpp_token first[1];
39 /* Stack of conditionals currently in progress
40 (including both successful and failing conditionals). */
41 struct if_stack
43 struct if_stack *next;
44 unsigned int line; /* Line where condition started. */
45 const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
46 bool skip_elses; /* Can future #else / #elif be skipped? */
47 bool was_skipping; /* If were skipping on entry. */
48 int type; /* Most recent conditional, for diagnostics. */
51 /* Contains a registered pragma or pragma namespace. */
52 typedef void (*pragma_cb) PARAMS ((cpp_reader *));
53 struct pragma_entry
55 struct pragma_entry *next;
56 const cpp_hashnode *pragma; /* Name and length. */
57 int is_nspace;
58 union {
59 pragma_cb handler;
60 struct pragma_entry *space;
61 } u;
64 /* Values for the origin field of struct directive. KANDR directives
65 come from traditional (K&R) C. STDC89 directives come from the
66 1989 C standard. EXTENSION directives are extensions. */
67 #define KANDR 0
68 #define STDC89 1
69 #define EXTENSION 2
71 /* Values for the flags field of struct directive. COND indicates a
72 conditional; IF_COND an opening conditional. INCL means to treat
73 "..." and <...> as q-char and h-char sequences respectively. IN_I
74 means this directive should be handled even if -fpreprocessed is in
75 effect (these are the directives with callback hooks).
77 EXPAND is set on directives that are always macro-expanded. */
78 #define COND (1 << 0)
79 #define IF_COND (1 << 1)
80 #define INCL (1 << 2)
81 #define IN_I (1 << 3)
82 #define EXPAND (1 << 4)
84 /* Defines one #-directive, including how to handle it. */
85 typedef void (*directive_handler) PARAMS ((cpp_reader *));
86 typedef struct directive directive;
87 struct directive
89 directive_handler handler; /* Function to handle directive. */
90 const uchar *name; /* Name of directive. */
91 unsigned short length; /* Length of name. */
92 unsigned char origin; /* Origin of directive. */
93 unsigned char flags; /* Flags describing this directive. */
96 /* Forward declarations. */
98 static void skip_rest_of_line PARAMS ((cpp_reader *));
99 static void check_eol PARAMS ((cpp_reader *));
100 static void start_directive PARAMS ((cpp_reader *));
101 static void prepare_directive_trad PARAMS ((cpp_reader *));
102 static void end_directive PARAMS ((cpp_reader *, int));
103 static void directive_diagnostics
104 PARAMS ((cpp_reader *, const directive *, int));
105 static void run_directive PARAMS ((cpp_reader *, int,
106 const char *, size_t));
107 static const cpp_token *glue_header_name PARAMS ((cpp_reader *));
108 static const cpp_token *parse_include PARAMS ((cpp_reader *));
109 static void push_conditional PARAMS ((cpp_reader *, int, int,
110 const cpp_hashnode *));
111 static unsigned int read_flag PARAMS ((cpp_reader *, unsigned int));
112 static uchar *dequote_string PARAMS ((cpp_reader *, const uchar *,
113 unsigned int));
114 static int strtoul_for_line PARAMS ((const uchar *, unsigned int,
115 unsigned long *));
116 static void do_diagnostic PARAMS ((cpp_reader *, int, int));
117 static cpp_hashnode *lex_macro_node PARAMS ((cpp_reader *));
118 static void do_include_common PARAMS ((cpp_reader *, enum include_type));
119 static struct pragma_entry *lookup_pragma_entry
120 PARAMS ((struct pragma_entry *, const cpp_hashnode *pragma));
121 static struct pragma_entry *insert_pragma_entry
122 PARAMS ((cpp_reader *, struct pragma_entry **, const cpp_hashnode *,
123 pragma_cb));
124 static int count_registered_pragmas PARAMS ((struct pragma_entry *));
125 static char ** save_registered_pragmas
126 PARAMS ((struct pragma_entry *, char **));
127 static char ** restore_registered_pragmas
128 PARAMS ((cpp_reader *, struct pragma_entry *, char **));
129 static void do_pragma_once PARAMS ((cpp_reader *));
130 static void do_pragma_poison PARAMS ((cpp_reader *));
131 static void do_pragma_system_header PARAMS ((cpp_reader *));
132 static void do_pragma_dependency PARAMS ((cpp_reader *));
133 static void do_linemarker PARAMS ((cpp_reader *));
134 static const cpp_token *get_token_no_padding PARAMS ((cpp_reader *));
135 static const cpp_token *get__Pragma_string PARAMS ((cpp_reader *));
136 static void destringize_and_run PARAMS ((cpp_reader *, const cpp_string *));
137 static int parse_answer PARAMS ((cpp_reader *, struct answer **, int));
138 static cpp_hashnode *parse_assertion PARAMS ((cpp_reader *, struct answer **,
139 int));
140 static struct answer ** find_answer PARAMS ((cpp_hashnode *,
141 const struct answer *));
142 static void handle_assertion PARAMS ((cpp_reader *, const char *, int));
144 /* This is the table of directive handlers. It is ordered by
145 frequency of occurrence; the numbers at the end are directive
146 counts from all the source code I have lying around (egcs and libc
147 CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
148 pcmcia-cs-3.0.9). This is no longer important as directive lookup
149 is now O(1). All extensions other than #warning and #include_next
150 are deprecated. The name is where the extension appears to have
151 come from. */
153 #define DIRECTIVE_TABLE \
154 D(define, T_DEFINE = 0, KANDR, IN_I) /* 270554 */ \
155 D(include, T_INCLUDE, KANDR, INCL | EXPAND) /* 52262 */ \
156 D(endif, T_ENDIF, KANDR, COND) /* 45855 */ \
157 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) /* 22000 */ \
158 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) /* 18162 */ \
159 D(else, T_ELSE, KANDR, COND) /* 9863 */ \
160 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) /* 9675 */ \
161 D(undef, T_UNDEF, KANDR, IN_I) /* 4837 */ \
162 D(line, T_LINE, KANDR, EXPAND) /* 2465 */ \
163 D(elif, T_ELIF, STDC89, COND | EXPAND) /* 610 */ \
164 D(error, T_ERROR, STDC89, 0) /* 475 */ \
165 D(pragma, T_PRAGMA, STDC89, IN_I) /* 195 */ \
166 D(warning, T_WARNING, EXTENSION, 0) /* 22 */ \
167 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) /* 19 */ \
168 D(ident, T_IDENT, EXTENSION, IN_I) /* 11 */ \
169 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* 0 ObjC */ \
170 D(assert, T_ASSERT, EXTENSION, 0) /* 0 SVR4 */ \
171 D(unassert, T_UNASSERT, EXTENSION, 0) /* 0 SVR4 */ \
172 D(sccs, T_SCCS, EXTENSION, 0) /* 0 SVR4? */
174 /* Use the table to generate a series of prototypes, an enum for the
175 directive names, and an array of directive handlers. */
177 /* Don't invoke CONCAT2 with any whitespace or K&R cc will fail. */
178 #define D(name, t, o, f) static void CONCAT2(do_,name) PARAMS ((cpp_reader *));
179 DIRECTIVE_TABLE
180 #undef D
182 #define D(n, tag, o, f) tag,
183 enum
185 DIRECTIVE_TABLE
186 N_DIRECTIVES
188 #undef D
190 /* Don't invoke CONCAT2 with any whitespace or K&R cc will fail. */
191 #define D(name, t, origin, flags) \
192 { CONCAT2(do_,name), (const uchar *) STRINGX(name), \
193 sizeof STRINGX(name) - 1, origin, flags },
194 static const directive dtable[] =
196 DIRECTIVE_TABLE
198 #undef D
199 #undef DIRECTIVE_TABLE
201 /* Wrapper struct directive for linemarkers.
202 The origin is more or less true - the original K+R cpp
203 did use this notation in its preprocessed output. */
204 static const directive linemarker_dir =
206 do_linemarker, U"#", 1, KANDR, IN_I
209 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
211 /* Skip any remaining tokens in a directive. */
212 static void
213 skip_rest_of_line (pfile)
214 cpp_reader *pfile;
216 /* Discard all stacked contexts. */
217 while (pfile->context->prev)
218 _cpp_pop_context (pfile);
220 /* Sweep up all tokens remaining on the line. */
221 if (! SEEN_EOL ())
222 while (_cpp_lex_token (pfile)->type != CPP_EOF)
226 /* Ensure there are no stray tokens at the end of a directive. */
227 static void
228 check_eol (pfile)
229 cpp_reader *pfile;
231 if (! SEEN_EOL () && _cpp_lex_token (pfile)->type != CPP_EOF)
232 cpp_error (pfile, DL_PEDWARN, "extra tokens at end of #%s directive",
233 pfile->directive->name);
236 /* Called when entering a directive, _Pragma or command-line directive. */
237 static void
238 start_directive (pfile)
239 cpp_reader *pfile;
241 /* Setup in-directive state. */
242 pfile->state.in_directive = 1;
243 pfile->state.save_comments = 0;
245 /* Some handlers need the position of the # for diagnostics. */
246 pfile->directive_line = pfile->line;
249 /* Called when leaving a directive, _Pragma or command-line directive. */
250 static void
251 end_directive (pfile, skip_line)
252 cpp_reader *pfile;
253 int skip_line;
255 if (CPP_OPTION (pfile, traditional))
257 /* Revert change of prepare_directive_trad. */
258 pfile->state.prevent_expansion--;
260 if (pfile->directive != &dtable[T_DEFINE])
261 _cpp_remove_overlay (pfile);
263 /* We don't skip for an assembler #. */
264 else if (skip_line)
266 skip_rest_of_line (pfile);
267 if (!pfile->keep_tokens)
269 pfile->cur_run = &pfile->base_run;
270 pfile->cur_token = pfile->base_run.base;
274 /* Restore state. */
275 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
276 pfile->state.in_directive = 0;
277 pfile->state.in_expression = 0;
278 pfile->state.angled_headers = 0;
279 pfile->directive = 0;
282 /* Prepare to handle the directive in pfile->directive. */
283 static void
284 prepare_directive_trad (pfile)
285 cpp_reader *pfile;
287 if (pfile->directive != &dtable[T_DEFINE])
289 bool no_expand = (pfile->directive
290 && ! (pfile->directive->flags & EXPAND));
291 bool was_skipping = pfile->state.skipping;
293 pfile->state.skipping = false;
294 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
295 || pfile->directive == &dtable[T_ELIF]);
296 if (no_expand)
297 pfile->state.prevent_expansion++;
298 scan_out_logical_line (pfile, NULL);
299 if (no_expand)
300 pfile->state.prevent_expansion--;
301 pfile->state.skipping = was_skipping;
302 _cpp_overlay_buffer (pfile, pfile->out.base,
303 pfile->out.cur - pfile->out.base);
306 /* Stop ISO C from expanding anything. */
307 pfile->state.prevent_expansion++;
310 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
311 the '#' was indented. */
312 static void
313 directive_diagnostics (pfile, dir, indented)
314 cpp_reader *pfile;
315 const directive *dir;
316 int indented;
318 /* Issue -pedantic warnings for extensions. */
319 if (CPP_PEDANTIC (pfile)
320 && ! pfile->state.skipping
321 && dir->origin == EXTENSION)
322 cpp_error (pfile, DL_PEDWARN, "#%s is a GCC extension", dir->name);
324 /* Traditionally, a directive is ignored unless its # is in
325 column 1. Therefore in code intended to work with K+R
326 compilers, directives added by C89 must have their #
327 indented, and directives present in traditional C must not.
328 This is true even of directives in skipped conditional
329 blocks. #elif cannot be used at all. */
330 if (CPP_WTRADITIONAL (pfile))
332 if (dir == &dtable[T_ELIF])
333 cpp_error (pfile, DL_WARNING,
334 "suggest not using #elif in traditional C");
335 else if (indented && dir->origin == KANDR)
336 cpp_error (pfile, DL_WARNING,
337 "traditional C ignores #%s with the # indented",
338 dir->name);
339 else if (!indented && dir->origin != KANDR)
340 cpp_error (pfile, DL_WARNING,
341 "suggest hiding #%s from traditional C with an indented #",
342 dir->name);
346 /* Check if we have a known directive. INDENTED is nonzero if the
347 '#' of the directive was indented. This function is in this file
348 to save unnecessarily exporting dtable etc. to cpplex.c. Returns
349 nonzero if the line of tokens has been handled, zero if we should
350 continue processing the line. */
352 _cpp_handle_directive (pfile, indented)
353 cpp_reader *pfile;
354 int indented;
356 const directive *dir = 0;
357 const cpp_token *dname;
358 bool was_parsing_args = pfile->state.parsing_args;
359 int skip = 1;
361 if (was_parsing_args)
363 if (CPP_OPTION (pfile, pedantic))
364 cpp_error (pfile, DL_PEDWARN,
365 "embedding a directive within macro arguments is not portable");
366 pfile->state.parsing_args = 0;
367 pfile->state.prevent_expansion = 0;
369 start_directive (pfile);
370 dname = _cpp_lex_token (pfile);
372 if (dname->type == CPP_NAME)
374 if (dname->val.node->is_directive)
375 dir = &dtable[dname->val.node->directive_index];
377 /* We do not recognize the # followed by a number extension in
378 assembler code. */
379 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
381 dir = &linemarker_dir;
382 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
383 && ! pfile->state.skipping)
384 cpp_error (pfile, DL_PEDWARN,
385 "style of line directive is a GCC extension");
388 if (dir)
390 /* If we have a directive that is not an opening conditional,
391 invalidate any control macro. */
392 if (! (dir->flags & IF_COND))
393 pfile->mi_valid = false;
395 /* Kluge alert. In order to be sure that code like this
397 #define HASH #
398 HASH define foo bar
400 does not cause '#define foo bar' to get executed when
401 compiled with -save-temps, we recognize directives in
402 -fpreprocessed mode only if the # is in column 1. cppmacro.c
403 puts a space in front of any '#' at the start of a macro. */
404 if (CPP_OPTION (pfile, preprocessed)
405 && (indented || !(dir->flags & IN_I)))
407 skip = 0;
408 dir = 0;
410 else
412 /* In failed conditional groups, all non-conditional
413 directives are ignored. Before doing that, whether
414 skipping or not, we should lex angle-bracketed headers
415 correctly, and maybe output some diagnostics. */
416 pfile->state.angled_headers = dir->flags & INCL;
417 pfile->state.directive_wants_padding = dir->flags & INCL;
418 if (! CPP_OPTION (pfile, preprocessed))
419 directive_diagnostics (pfile, dir, indented);
420 if (pfile->state.skipping && !(dir->flags & COND))
421 dir = 0;
424 else if (dname->type == CPP_EOF)
425 ; /* CPP_EOF is the "null directive". */
426 else
428 /* An unknown directive. Don't complain about it in assembly
429 source: we don't know where the comments are, and # may
430 introduce assembler pseudo-ops. Don't complain about invalid
431 directives in skipped conditional groups (6.10 p4). */
432 if (CPP_OPTION (pfile, lang) == CLK_ASM)
433 skip = 0;
434 else if (!pfile->state.skipping)
435 cpp_error (pfile, DL_ERROR, "invalid preprocessing directive #%s",
436 cpp_token_as_text (pfile, dname));
439 pfile->directive = dir;
440 if (CPP_OPTION (pfile, traditional))
441 prepare_directive_trad (pfile);
443 if (dir)
444 (*pfile->directive->handler) (pfile);
445 else if (skip == 0)
446 _cpp_backup_tokens (pfile, 1);
448 end_directive (pfile, skip);
449 if (was_parsing_args)
451 /* Restore state when within macro args. */
452 pfile->state.parsing_args = 2;
453 pfile->state.prevent_expansion = 1;
455 return skip;
458 /* Directive handler wrapper used by the command line option
459 processor. BUF is \n terminated. */
460 static void
461 run_directive (pfile, dir_no, buf, count)
462 cpp_reader *pfile;
463 int dir_no;
464 const char *buf;
465 size_t count;
467 cpp_push_buffer (pfile, (const uchar *) buf, count,
468 /* from_stage3 */ true, 1);
469 /* Disgusting hack. */
470 if (dir_no == T_PRAGMA)
471 pfile->buffer->inc = pfile->buffer->prev->inc;
472 start_directive (pfile);
474 /* This is a short-term fix to prevent a leading '#' being
475 interpreted as a directive. */
476 _cpp_clean_line (pfile);
478 pfile->directive = &dtable[dir_no];
479 if (CPP_OPTION (pfile, traditional))
480 prepare_directive_trad (pfile);
481 (void) (*pfile->directive->handler) (pfile);
482 end_directive (pfile, 1);
483 if (dir_no == T_PRAGMA)
484 pfile->buffer->inc = NULL;
485 _cpp_pop_buffer (pfile);
488 /* Checks for validity the macro name in #define, #undef, #ifdef and
489 #ifndef directives. */
490 static cpp_hashnode *
491 lex_macro_node (pfile)
492 cpp_reader *pfile;
494 const cpp_token *token = _cpp_lex_token (pfile);
496 /* The token immediately after #define must be an identifier. That
497 identifier may not be "defined", per C99 6.10.8p4.
498 In C++, it may not be any of the "named operators" either,
499 per C++98 [lex.digraph], [lex.key].
500 Finally, the identifier may not have been poisoned. (In that case
501 the lexer has issued the error message for us.) */
503 if (token->type == CPP_NAME)
505 cpp_hashnode *node = token->val.node;
507 if (node == pfile->spec_nodes.n_defined)
508 cpp_error (pfile, DL_ERROR,
509 "\"defined\" cannot be used as a macro name");
510 else if (! (node->flags & NODE_POISONED))
511 return node;
513 else if (token->flags & NAMED_OP)
514 cpp_error (pfile, DL_ERROR,
515 "\"%s\" cannot be used as a macro name as it is an operator in C++",
516 NODE_NAME (token->val.node));
517 else if (token->type == CPP_EOF)
518 cpp_error (pfile, DL_ERROR, "no macro name given in #%s directive",
519 pfile->directive->name);
520 else
521 cpp_error (pfile, DL_ERROR, "macro names must be identifiers");
523 return NULL;
526 /* Process a #define directive. Most work is done in cppmacro.c. */
527 static void
528 do_define (pfile)
529 cpp_reader *pfile;
531 cpp_hashnode *node = lex_macro_node (pfile);
533 if (node)
535 /* If we have been requested to expand comments into macros,
536 then re-enable saving of comments. */
537 pfile->state.save_comments =
538 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
540 if (_cpp_create_definition (pfile, node))
541 if (pfile->cb.define)
542 (*pfile->cb.define) (pfile, pfile->directive_line, node);
546 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
547 static void
548 do_undef (pfile)
549 cpp_reader *pfile;
551 cpp_hashnode *node = lex_macro_node (pfile);
553 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified identifier
554 is not currently defined as a macro name. */
555 if (node && node->type == NT_MACRO)
557 if (pfile->cb.undef)
558 (*pfile->cb.undef) (pfile, pfile->directive_line, node);
560 if (node->flags & NODE_WARN)
561 cpp_error (pfile, DL_WARNING, "undefining \"%s\"", NODE_NAME (node));
563 if (CPP_OPTION (pfile, warn_unused_macros))
564 _cpp_warn_if_unused_macro (pfile, node, NULL);
566 _cpp_free_definition (node);
568 check_eol (pfile);
571 /* Helper routine used by parse_include. Reinterpret the current line
572 as an h-char-sequence (< ... >); we are looking at the first token
573 after the <. Returns the header as a token, or NULL on failure. */
574 static const cpp_token *
575 glue_header_name (pfile)
576 cpp_reader *pfile;
578 cpp_token *header = NULL;
579 const cpp_token *token;
580 unsigned char *buffer;
581 size_t len, total_len = 0, capacity = 1024;
583 /* To avoid lexed tokens overwriting our glued name, we can only
584 allocate from the string pool once we've lexed everything. */
585 buffer = (unsigned char *) xmalloc (capacity);
586 for (;;)
588 token = get_token_no_padding (pfile);
590 if (token->type == CPP_GREATER || token->type == CPP_EOF)
591 break;
593 len = cpp_token_len (token);
594 if (total_len + len > capacity)
596 capacity = (capacity + len) * 2;
597 buffer = (unsigned char *) xrealloc (buffer, capacity);
600 if (token->flags & PREV_WHITE)
601 buffer[total_len++] = ' ';
603 total_len = cpp_spell_token (pfile, token, &buffer[total_len]) - buffer;
606 if (token->type == CPP_EOF)
607 cpp_error (pfile, DL_ERROR, "missing terminating > character");
608 else
610 unsigned char *token_mem = _cpp_unaligned_alloc (pfile, total_len + 1);
611 memcpy (token_mem, buffer, total_len);
612 token_mem[total_len] = '\0';
614 header = _cpp_temp_token (pfile);
615 header->type = CPP_HEADER_NAME;
616 header->flags = 0;
617 header->val.str.len = total_len;
618 header->val.str.text = token_mem;
621 free ((PTR) buffer);
622 return header;
625 /* Returns the header string of #include, #include_next, #import and
626 #pragma dependency. Returns NULL on error. */
627 static const cpp_token *
628 parse_include (pfile)
629 cpp_reader *pfile;
631 const unsigned char *dir;
632 const cpp_token *header;
634 if (pfile->directive == &dtable[T_PRAGMA])
635 dir = U"pragma dependency";
636 else
637 dir = pfile->directive->name;
639 /* Allow macro expansion. */
640 header = get_token_no_padding (pfile);
641 if (header->type != CPP_STRING && header->type != CPP_HEADER_NAME)
643 if (header->type != CPP_LESS)
645 cpp_error (pfile, DL_ERROR,
646 "#%s expects \"FILENAME\" or <FILENAME>", dir);
647 return NULL;
650 header = glue_header_name (pfile);
651 if (header == NULL)
652 return header;
655 if (header->val.str.len == 0)
657 cpp_error (pfile, DL_ERROR, "empty file name in #%s", dir);
658 return NULL;
661 check_eol (pfile);
662 return header;
665 /* Handle #include, #include_next and #import. */
666 static void
667 do_include_common (pfile, type)
668 cpp_reader *pfile;
669 enum include_type type;
671 const cpp_token *header = parse_include (pfile);
672 if (!header)
673 return;
675 /* Prevent #include recursion. */
676 if (pfile->line_maps.depth >= CPP_STACK_MAX)
678 cpp_error (pfile, DL_ERROR, "#include nested too deeply");
679 return;
682 /* Get out of macro context, if we are. */
683 skip_rest_of_line (pfile);
685 if (pfile->cb.include)
686 (*pfile->cb.include) (pfile, pfile->directive_line,
687 pfile->directive->name, header);
689 _cpp_execute_include (pfile, header, type);
692 static void
693 do_include (pfile)
694 cpp_reader *pfile;
696 do_include_common (pfile, IT_INCLUDE);
699 static void
700 do_import (pfile)
701 cpp_reader *pfile;
703 if (CPP_OPTION (pfile, warn_import))
705 CPP_OPTION (pfile, warn_import) = 0;
706 cpp_error (pfile, DL_WARNING,
707 "#import is obsolete, use an #ifndef wrapper in the header file");
710 do_include_common (pfile, IT_IMPORT);
713 static void
714 do_include_next (pfile)
715 cpp_reader *pfile;
717 enum include_type type = IT_INCLUDE_NEXT;
719 /* If this is the primary source file, warn and use the normal
720 search logic. */
721 if (! pfile->buffer->prev)
723 cpp_error (pfile, DL_WARNING,
724 "#include_next in primary source file");
725 type = IT_INCLUDE;
727 do_include_common (pfile, type);
730 /* Subroutine of do_linemarker. Read possible flags after file name.
731 LAST is the last flag seen; 0 if this is the first flag. Return the
732 flag if it is valid, 0 at the end of the directive. Otherwise
733 complain. */
734 static unsigned int
735 read_flag (pfile, last)
736 cpp_reader *pfile;
737 unsigned int last;
739 const cpp_token *token = _cpp_lex_token (pfile);
741 if (token->type == CPP_NUMBER && token->val.str.len == 1)
743 unsigned int flag = token->val.str.text[0] - '0';
745 if (flag > last && flag <= 4
746 && (flag != 4 || last == 3)
747 && (flag != 2 || last == 0))
748 return flag;
751 if (token->type != CPP_EOF)
752 cpp_error (pfile, DL_ERROR, "invalid flag \"%s\" in line directive",
753 cpp_token_as_text (pfile, token));
754 return 0;
757 /* Subroutine of do_line and do_linemarker. Returns a version of STR
758 which has a NUL terminator and all escape sequences converted to
759 their equivalents. Temporary, hopefully. */
760 static uchar *
761 dequote_string (pfile, str, len)
762 cpp_reader *pfile;
763 const uchar *str;
764 unsigned int len;
766 uchar *result = _cpp_unaligned_alloc (pfile, len + 1);
767 uchar *dst = result;
768 const uchar *limit = str + len;
769 cppchar_t c;
771 while (str < limit)
773 c = *str++;
774 if (c != '\\')
775 *dst++ = c;
776 else
777 *dst++ = cpp_parse_escape (pfile, &str, limit, 0);
779 *dst++ = '\0';
780 return result;
783 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
784 of length LEN, to binary; store it in NUMP, and return 0 if the
785 number was well-formed, 1 if not. Temporary, hopefully. */
786 static int
787 strtoul_for_line (str, len, nump)
788 const uchar *str;
789 unsigned int len;
790 unsigned long *nump;
792 unsigned long reg = 0;
793 uchar c;
794 while (len--)
796 c = *str++;
797 if (!ISDIGIT (c))
798 return 1;
799 reg *= 10;
800 reg += c - '0';
802 *nump = reg;
803 return 0;
806 /* Interpret #line command.
807 Note that the filename string (if any) is a true string constant
808 (escapes are interpreted), unlike in #line. */
809 static void
810 do_line (pfile)
811 cpp_reader *pfile;
813 const cpp_token *token;
814 const char *new_file = pfile->map->to_file;
815 unsigned long new_lineno;
817 /* C99 raised the minimum limit on #line numbers. */
818 unsigned int cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
820 /* #line commands expand macros. */
821 token = cpp_get_token (pfile);
822 if (token->type != CPP_NUMBER
823 || strtoul_for_line (token->val.str.text, token->val.str.len,
824 &new_lineno))
826 cpp_error (pfile, DL_ERROR,
827 "\"%s\" after #line is not a positive integer",
828 cpp_token_as_text (pfile, token));
829 return;
832 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap))
833 cpp_error (pfile, DL_PEDWARN, "line number out of range");
835 token = cpp_get_token (pfile);
836 if (token->type == CPP_STRING)
838 new_file = (const char *) dequote_string (pfile, token->val.str.text,
839 token->val.str.len);
840 check_eol (pfile);
842 else if (token->type != CPP_EOF)
844 cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
845 cpp_token_as_text (pfile, token));
846 return;
849 skip_rest_of_line (pfile);
850 _cpp_do_file_change (pfile, LC_RENAME, new_file, new_lineno,
851 pfile->map->sysp);
854 /* Interpret the # 44 "file" [flags] notation, which has slightly
855 different syntax and semantics from #line: Flags are allowed,
856 and we never complain about the line number being too big. */
857 static void
858 do_linemarker (pfile)
859 cpp_reader *pfile;
861 const cpp_token *token;
862 const char *new_file = pfile->map->to_file;
863 unsigned long new_lineno;
864 unsigned int new_sysp = pfile->map->sysp;
865 enum lc_reason reason = LC_RENAME;
866 int flag;
868 /* Back up so we can get the number again. Putting this in
869 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
870 some circumstances, which can segfault. */
871 _cpp_backup_tokens (pfile, 1);
873 /* #line commands expand macros. */
874 token = cpp_get_token (pfile);
875 if (token->type != CPP_NUMBER
876 || strtoul_for_line (token->val.str.text, token->val.str.len,
877 &new_lineno))
879 cpp_error (pfile, DL_ERROR, "\"%s\" after # is not a positive integer",
880 cpp_token_as_text (pfile, token));
881 return;
884 token = cpp_get_token (pfile);
885 if (token->type == CPP_STRING)
887 new_file = (const char *) dequote_string (pfile, token->val.str.text,
888 token->val.str.len);
889 new_sysp = 0;
890 flag = read_flag (pfile, 0);
891 if (flag == 1)
893 reason = LC_ENTER;
894 /* Fake an include for cpp_included (). */
895 _cpp_fake_include (pfile, new_file);
896 flag = read_flag (pfile, flag);
898 else if (flag == 2)
900 reason = LC_LEAVE;
901 flag = read_flag (pfile, flag);
903 if (flag == 3)
905 new_sysp = 1;
906 flag = read_flag (pfile, flag);
907 if (flag == 4)
908 new_sysp = 2;
911 check_eol (pfile);
913 else if (token->type != CPP_EOF)
915 cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
916 cpp_token_as_text (pfile, token));
917 return;
920 skip_rest_of_line (pfile);
921 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
924 /* Arrange the file_change callback. pfile->line has changed to
925 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
926 header, 2 for a system header that needs to be extern "C" protected,
927 and zero otherwise. */
928 void
929 _cpp_do_file_change (pfile, reason, to_file, file_line, sysp)
930 cpp_reader *pfile;
931 enum lc_reason reason;
932 const char *to_file;
933 unsigned int file_line;
934 unsigned int sysp;
936 pfile->map = add_line_map (&pfile->line_maps, reason, sysp,
937 pfile->line, to_file, file_line);
939 if (pfile->cb.file_change)
940 (*pfile->cb.file_change) (pfile, pfile->map);
943 /* Report a warning or error detected by the program we are
944 processing. Use the directive's tokens in the error message. */
945 static void
946 do_diagnostic (pfile, code, print_dir)
947 cpp_reader *pfile;
948 int code;
949 int print_dir;
951 if (_cpp_begin_message (pfile, code,
952 pfile->cur_token[-1].line,
953 pfile->cur_token[-1].col))
955 if (print_dir)
956 fprintf (stderr, "#%s ", pfile->directive->name);
957 pfile->state.prevent_expansion++;
958 cpp_output_line (pfile, stderr);
959 pfile->state.prevent_expansion--;
963 static void
964 do_error (pfile)
965 cpp_reader *pfile;
967 do_diagnostic (pfile, DL_ERROR, 1);
970 static void
971 do_warning (pfile)
972 cpp_reader *pfile;
974 /* We want #warning diagnostics to be emitted in system headers too. */
975 do_diagnostic (pfile, DL_WARNING_SYSHDR, 1);
978 /* Report program identification. */
979 static void
980 do_ident (pfile)
981 cpp_reader *pfile;
983 const cpp_token *str = cpp_get_token (pfile);
985 if (str->type != CPP_STRING)
986 cpp_error (pfile, DL_ERROR, "invalid #ident directive");
987 else if (pfile->cb.ident)
988 (*pfile->cb.ident) (pfile, pfile->directive_line, &str->val.str);
990 check_eol (pfile);
993 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
994 matching entry, or NULL if none is found. The returned entry could
995 be the start of a namespace chain, or a pragma. */
996 static struct pragma_entry *
997 lookup_pragma_entry (chain, pragma)
998 struct pragma_entry *chain;
999 const cpp_hashnode *pragma;
1001 while (chain && chain->pragma != pragma)
1002 chain = chain->next;
1004 return chain;
1007 /* Create and insert a pragma entry for NAME at the beginning of a
1008 singly-linked CHAIN. If handler is NULL, it is a namespace,
1009 otherwise it is a pragma and its handler. */
1010 static struct pragma_entry *
1011 insert_pragma_entry (pfile, chain, pragma, handler)
1012 cpp_reader *pfile;
1013 struct pragma_entry **chain;
1014 const cpp_hashnode *pragma;
1015 pragma_cb handler;
1017 struct pragma_entry *new;
1019 new = (struct pragma_entry *)
1020 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1021 new->pragma = pragma;
1022 if (handler)
1024 new->is_nspace = 0;
1025 new->u.handler = handler;
1027 else
1029 new->is_nspace = 1;
1030 new->u.space = NULL;
1033 new->next = *chain;
1034 *chain = new;
1035 return new;
1038 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1039 goes in the global namespace. HANDLER is the handler it will call,
1040 which must be non-NULL. */
1041 void
1042 cpp_register_pragma (pfile, space, name, handler)
1043 cpp_reader *pfile;
1044 const char *space;
1045 const char *name;
1046 pragma_cb handler;
1048 struct pragma_entry **chain = &pfile->pragmas;
1049 struct pragma_entry *entry;
1050 const cpp_hashnode *node;
1052 if (!handler)
1053 abort ();
1055 if (space)
1057 node = cpp_lookup (pfile, U space, strlen (space));
1058 entry = lookup_pragma_entry (*chain, node);
1059 if (!entry)
1060 entry = insert_pragma_entry (pfile, chain, node, NULL);
1061 else if (!entry->is_nspace)
1062 goto clash;
1063 chain = &entry->u.space;
1066 /* Check for duplicates. */
1067 node = cpp_lookup (pfile, U name, strlen (name));
1068 entry = lookup_pragma_entry (*chain, node);
1069 if (entry)
1071 if (entry->is_nspace)
1072 clash:
1073 cpp_error (pfile, DL_ICE,
1074 "registering \"%s\" as both a pragma and a pragma namespace",
1075 NODE_NAME (node));
1076 else if (space)
1077 cpp_error (pfile, DL_ICE, "#pragma %s %s is already registered",
1078 space, name);
1079 else
1080 cpp_error (pfile, DL_ICE, "#pragma %s is already registered", name);
1082 else
1083 insert_pragma_entry (pfile, chain, node, handler);
1086 /* Register the pragmas the preprocessor itself handles. */
1087 void
1088 _cpp_init_internal_pragmas (pfile)
1089 cpp_reader *pfile;
1091 /* Pragmas in the global namespace. */
1092 cpp_register_pragma (pfile, 0, "once", do_pragma_once);
1094 /* New GCC-specific pragmas should be put in the GCC namespace. */
1095 cpp_register_pragma (pfile, "GCC", "poison", do_pragma_poison);
1096 cpp_register_pragma (pfile, "GCC", "system_header", do_pragma_system_header);
1097 cpp_register_pragma (pfile, "GCC", "dependency", do_pragma_dependency);
1100 /* Return the number of registered pragmas in PE. */
1102 static int
1103 count_registered_pragmas (pe)
1104 struct pragma_entry *pe;
1106 int ct = 0;
1107 for (; pe != NULL; pe = pe->next)
1109 if (pe->is_nspace)
1110 ct += count_registered_pragmas (pe->u.space);
1111 ct++;
1113 return ct;
1116 /* Save into SD the names of the registered pragmas referenced by PE,
1117 and return a pointer to the next free space in SD. */
1119 static char **
1120 save_registered_pragmas (pe, sd)
1121 struct pragma_entry *pe;
1122 char **sd;
1124 for (; pe != NULL; pe = pe->next)
1126 if (pe->is_nspace)
1127 sd = save_registered_pragmas (pe->u.space, sd);
1128 *sd++ = xmemdup (HT_STR (&pe->pragma->ident),
1129 HT_LEN (&pe->pragma->ident),
1130 HT_LEN (&pe->pragma->ident) + 1);
1132 return sd;
1135 /* Return a newly-allocated array which saves the names of the
1136 registered pragmas. */
1138 char **
1139 _cpp_save_pragma_names (pfile)
1140 cpp_reader *pfile;
1142 int ct = count_registered_pragmas (pfile->pragmas);
1143 char **result = xnewvec (char *, ct);
1144 (void) save_registered_pragmas (pfile->pragmas, result);
1145 return result;
1148 /* Restore from SD the names of the registered pragmas referenced by PE,
1149 and return a pointer to the next unused name in SD. */
1151 static char **
1152 restore_registered_pragmas (pfile, pe, sd)
1153 cpp_reader *pfile;
1154 struct pragma_entry *pe;
1155 char **sd;
1157 for (; pe != NULL; pe = pe->next)
1159 if (pe->is_nspace)
1160 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1161 pe->pragma = cpp_lookup (pfile, U *sd, strlen (*sd));
1162 free (*sd);
1163 sd++;
1165 return sd;
1168 /* Restore the names of the registered pragmas from SAVED. */
1170 void
1171 _cpp_restore_pragma_names (pfile, saved)
1172 cpp_reader *pfile;
1173 char **saved;
1175 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1176 free (saved);
1179 /* Pragmata handling. We handle some, and pass the rest on to the
1180 front end. C99 defines three pragmas and says that no macro
1181 expansion is to be performed on them; whether or not macro
1182 expansion happens for other pragmas is implementation defined.
1183 This implementation never macro-expands the text after #pragma. */
1184 static void
1185 do_pragma (pfile)
1186 cpp_reader *pfile;
1188 const struct pragma_entry *p = NULL;
1189 const cpp_token *token;
1190 unsigned int count = 1;
1192 pfile->state.prevent_expansion++;
1194 token = cpp_get_token (pfile);
1195 if (token->type == CPP_NAME)
1197 p = lookup_pragma_entry (pfile->pragmas, token->val.node);
1198 if (p && p->is_nspace)
1200 count = 2;
1201 token = cpp_get_token (pfile);
1202 if (token->type == CPP_NAME)
1203 p = lookup_pragma_entry (p->u.space, token->val.node);
1204 else
1205 p = NULL;
1209 /* FIXME. This is an awful kludge to get the front ends to update
1210 their notion of line number for diagnostic purposes. The line
1211 number should be passed to the handler and they should do it
1212 themselves. Stand-alone CPP must ignore us, otherwise it will
1213 prefix the directive with spaces, hence the 1. Ugh. */
1214 if (pfile->cb.line_change)
1215 (*pfile->cb.line_change)(pfile, token, 1);
1217 if (p)
1218 (*p->u.handler) (pfile);
1219 else if (pfile->cb.def_pragma)
1221 _cpp_backup_tokens (pfile, count);
1222 (*pfile->cb.def_pragma) (pfile, pfile->directive_line);
1225 pfile->state.prevent_expansion--;
1228 /* Handle #pragma once. */
1229 static void
1230 do_pragma_once (pfile)
1231 cpp_reader *pfile;
1233 if (CPP_OPTION (pfile, warn_deprecated))
1234 cpp_error (pfile, DL_WARNING, "#pragma once is obsolete");
1236 if (pfile->buffer->prev == NULL)
1237 cpp_error (pfile, DL_WARNING, "#pragma once in main file");
1238 else
1239 _cpp_never_reread (pfile->buffer->inc);
1241 check_eol (pfile);
1244 /* Handle #pragma GCC poison, to poison one or more identifiers so
1245 that the lexer produces a hard error for each subsequent usage. */
1246 static void
1247 do_pragma_poison (pfile)
1248 cpp_reader *pfile;
1250 const cpp_token *tok;
1251 cpp_hashnode *hp;
1253 pfile->state.poisoned_ok = 1;
1254 for (;;)
1256 tok = _cpp_lex_token (pfile);
1257 if (tok->type == CPP_EOF)
1258 break;
1259 if (tok->type != CPP_NAME)
1261 cpp_error (pfile, DL_ERROR, "invalid #pragma GCC poison directive");
1262 break;
1265 hp = tok->val.node;
1266 if (hp->flags & NODE_POISONED)
1267 continue;
1269 if (hp->type == NT_MACRO)
1270 cpp_error (pfile, DL_WARNING, "poisoning existing macro \"%s\"",
1271 NODE_NAME (hp));
1272 _cpp_free_definition (hp);
1273 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1275 pfile->state.poisoned_ok = 0;
1278 /* Mark the current header as a system header. This will suppress
1279 some categories of warnings (notably those from -pedantic). It is
1280 intended for use in system libraries that cannot be implemented in
1281 conforming C, but cannot be certain that their headers appear in a
1282 system include directory. To prevent abuse, it is rejected in the
1283 primary source file. */
1284 static void
1285 do_pragma_system_header (pfile)
1286 cpp_reader *pfile;
1288 cpp_buffer *buffer = pfile->buffer;
1290 if (buffer->prev == 0)
1291 cpp_error (pfile, DL_WARNING,
1292 "#pragma system_header ignored outside include file");
1293 else
1295 check_eol (pfile);
1296 skip_rest_of_line (pfile);
1297 cpp_make_system_header (pfile, 1, 0);
1301 /* Check the modified date of the current include file against a specified
1302 file. Issue a diagnostic, if the specified file is newer. We use this to
1303 determine if a fixed header should be refixed. */
1304 static void
1305 do_pragma_dependency (pfile)
1306 cpp_reader *pfile;
1308 const cpp_token *header;
1309 int ordering;
1311 header = parse_include (pfile);
1312 if (!header)
1313 return;
1315 ordering = _cpp_compare_file_date (pfile, header);
1316 if (ordering < 0)
1317 cpp_error (pfile, DL_WARNING, "cannot find source %s",
1318 cpp_token_as_text (pfile, header));
1319 else if (ordering > 0)
1321 cpp_error (pfile, DL_WARNING, "current file is older than %s",
1322 cpp_token_as_text (pfile, header));
1323 if (cpp_get_token (pfile)->type != CPP_EOF)
1325 _cpp_backup_tokens (pfile, 1);
1326 do_diagnostic (pfile, DL_WARNING, 0);
1331 /* Get a token but skip padding. */
1332 static const cpp_token *
1333 get_token_no_padding (pfile)
1334 cpp_reader *pfile;
1336 for (;;)
1338 const cpp_token *result = cpp_get_token (pfile);
1339 if (result->type != CPP_PADDING)
1340 return result;
1344 /* Check syntax is "(string-literal)". Returns the string on success,
1345 or NULL on failure. */
1346 static const cpp_token *
1347 get__Pragma_string (pfile)
1348 cpp_reader *pfile;
1350 const cpp_token *string;
1352 if (get_token_no_padding (pfile)->type != CPP_OPEN_PAREN)
1353 return NULL;
1355 string = get_token_no_padding (pfile);
1356 if (string->type != CPP_STRING && string->type != CPP_WSTRING)
1357 return NULL;
1359 if (get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
1360 return NULL;
1362 return string;
1365 /* Destringize IN into a temporary buffer, by removing the first \ of
1366 \" and \\ sequences, and process the result as a #pragma directive. */
1367 static void
1368 destringize_and_run (pfile, in)
1369 cpp_reader *pfile;
1370 const cpp_string *in;
1372 const unsigned char *src, *limit;
1373 char *dest, *result;
1375 dest = result = alloca (in->len + 1);
1376 for (src = in->text, limit = src + in->len; src < limit;)
1378 /* We know there is a character following the backslash. */
1379 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1380 src++;
1381 *dest++ = *src++;
1383 *dest = '\n';
1385 /* Ugh; an awful kludge. We are really not set up to be lexing
1386 tokens when in the middle of a macro expansion. Use a new
1387 context to force cpp_get_token to lex, and so skip_rest_of_line
1388 doesn't go beyond the end of the text. Also, remember the
1389 current lexing position so we can return to it later.
1391 Something like line-at-a-time lexing should remove the need for
1392 this. */
1394 cpp_context *saved_context = pfile->context;
1395 cpp_token *saved_cur_token = pfile->cur_token;
1396 tokenrun *saved_cur_run = pfile->cur_run;
1398 pfile->context = xnew (cpp_context);
1399 pfile->context->macro = 0;
1400 pfile->context->prev = 0;
1401 run_directive (pfile, T_PRAGMA, result, dest - result);
1402 free (pfile->context);
1403 pfile->context = saved_context;
1404 pfile->cur_token = saved_cur_token;
1405 pfile->cur_run = saved_cur_run;
1406 pfile->line--;
1409 /* See above comment. For the moment, we'd like
1411 token1 _Pragma ("foo") token2
1413 to be output as
1415 token1
1416 # 7 "file.c"
1417 #pragma foo
1418 # 7 "file.c"
1419 token2
1421 Getting the line markers is a little tricky. */
1422 if (pfile->cb.line_change)
1423 (*pfile->cb.line_change) (pfile, pfile->cur_token, false);
1426 /* Handle the _Pragma operator. */
1427 void
1428 _cpp_do__Pragma (pfile)
1429 cpp_reader *pfile;
1431 const cpp_token *string = get__Pragma_string (pfile);
1433 if (string)
1434 destringize_and_run (pfile, &string->val.str);
1435 else
1436 cpp_error (pfile, DL_ERROR,
1437 "_Pragma takes a parenthesized string literal");
1440 /* Just ignore #sccs on all systems. */
1441 static void
1442 do_sccs (pfile)
1443 cpp_reader *pfile ATTRIBUTE_UNUSED;
1447 /* Handle #ifdef. */
1448 static void
1449 do_ifdef (pfile)
1450 cpp_reader *pfile;
1452 int skip = 1;
1454 if (! pfile->state.skipping)
1456 const cpp_hashnode *node = lex_macro_node (pfile);
1458 if (node)
1460 skip = node->type != NT_MACRO;
1461 _cpp_mark_macro_used (node);
1462 check_eol (pfile);
1466 push_conditional (pfile, skip, T_IFDEF, 0);
1469 /* Handle #ifndef. */
1470 static void
1471 do_ifndef (pfile)
1472 cpp_reader *pfile;
1474 int skip = 1;
1475 const cpp_hashnode *node = 0;
1477 if (! pfile->state.skipping)
1479 node = lex_macro_node (pfile);
1481 if (node)
1483 skip = node->type == NT_MACRO;
1484 _cpp_mark_macro_used (node);
1485 check_eol (pfile);
1489 push_conditional (pfile, skip, T_IFNDEF, node);
1492 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1493 pfile->mi_ind_cmacro so we can handle multiple-include
1494 optimisations. If macro expansion occurs in the expression, we
1495 cannot treat it as a controlling conditional, since the expansion
1496 could change in the future. That is handled by cpp_get_token. */
1497 static void
1498 do_if (pfile)
1499 cpp_reader *pfile;
1501 int skip = 1;
1503 if (! pfile->state.skipping)
1504 skip = _cpp_parse_expr (pfile) == false;
1506 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1509 /* Flip skipping state if appropriate and continue without changing
1510 if_stack; this is so that the error message for missing #endif's
1511 etc. will point to the original #if. */
1512 static void
1513 do_else (pfile)
1514 cpp_reader *pfile;
1516 cpp_buffer *buffer = pfile->buffer;
1517 struct if_stack *ifs = buffer->if_stack;
1519 if (ifs == NULL)
1520 cpp_error (pfile, DL_ERROR, "#else without #if");
1521 else
1523 if (ifs->type == T_ELSE)
1525 cpp_error (pfile, DL_ERROR, "#else after #else");
1526 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1527 "the conditional began here");
1529 ifs->type = T_ELSE;
1531 /* Skip any future (erroneous) #elses or #elifs. */
1532 pfile->state.skipping = ifs->skip_elses;
1533 ifs->skip_elses = true;
1535 /* Invalidate any controlling macro. */
1536 ifs->mi_cmacro = 0;
1538 /* Only check EOL if was not originally skipping. */
1539 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1540 check_eol (pfile);
1544 /* Handle a #elif directive by not changing if_stack either. See the
1545 comment above do_else. */
1546 static void
1547 do_elif (pfile)
1548 cpp_reader *pfile;
1550 cpp_buffer *buffer = pfile->buffer;
1551 struct if_stack *ifs = buffer->if_stack;
1553 if (ifs == NULL)
1554 cpp_error (pfile, DL_ERROR, "#elif without #if");
1555 else
1557 if (ifs->type == T_ELSE)
1559 cpp_error (pfile, DL_ERROR, "#elif after #else");
1560 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1561 "the conditional began here");
1563 ifs->type = T_ELIF;
1565 /* Only evaluate this if we aren't skipping elses. During
1566 evaluation, set skipping to false to get lexer warnings. */
1567 if (ifs->skip_elses)
1568 pfile->state.skipping = 1;
1569 else
1571 pfile->state.skipping = 0;
1572 pfile->state.skipping = ! _cpp_parse_expr (pfile);
1573 ifs->skip_elses = ! pfile->state.skipping;
1576 /* Invalidate any controlling macro. */
1577 ifs->mi_cmacro = 0;
1581 /* #endif pops the if stack and resets pfile->state.skipping. */
1582 static void
1583 do_endif (pfile)
1584 cpp_reader *pfile;
1586 cpp_buffer *buffer = pfile->buffer;
1587 struct if_stack *ifs = buffer->if_stack;
1589 if (ifs == NULL)
1590 cpp_error (pfile, DL_ERROR, "#endif without #if");
1591 else
1593 /* Only check EOL if was not originally skipping. */
1594 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1595 check_eol (pfile);
1597 /* If potential control macro, we go back outside again. */
1598 if (ifs->next == 0 && ifs->mi_cmacro)
1600 pfile->mi_valid = true;
1601 pfile->mi_cmacro = ifs->mi_cmacro;
1604 buffer->if_stack = ifs->next;
1605 pfile->state.skipping = ifs->was_skipping;
1606 obstack_free (&pfile->buffer_ob, ifs);
1610 /* Push an if_stack entry for a preprocessor conditional, and set
1611 pfile->state.skipping to SKIP. If TYPE indicates the conditional
1612 is #if or #ifndef, CMACRO is a potentially controlling macro, and
1613 we need to check here that we are at the top of the file. */
1614 static void
1615 push_conditional (pfile, skip, type, cmacro)
1616 cpp_reader *pfile;
1617 int skip;
1618 int type;
1619 const cpp_hashnode *cmacro;
1621 struct if_stack *ifs;
1622 cpp_buffer *buffer = pfile->buffer;
1624 ifs = xobnew (&pfile->buffer_ob, struct if_stack);
1625 ifs->line = pfile->directive_line;
1626 ifs->next = buffer->if_stack;
1627 ifs->skip_elses = pfile->state.skipping || !skip;
1628 ifs->was_skipping = pfile->state.skipping;
1629 ifs->type = type;
1630 /* This condition is effectively a test for top-of-file. */
1631 if (pfile->mi_valid && pfile->mi_cmacro == 0)
1632 ifs->mi_cmacro = cmacro;
1633 else
1634 ifs->mi_cmacro = 0;
1636 pfile->state.skipping = skip;
1637 buffer->if_stack = ifs;
1640 /* Read the tokens of the answer into the macro pool, in a directive
1641 of type TYPE. Only commit the memory if we intend it as permanent
1642 storage, i.e. the #assert case. Returns 0 on success, and sets
1643 ANSWERP to point to the answer. */
1644 static int
1645 parse_answer (pfile, answerp, type)
1646 cpp_reader *pfile;
1647 struct answer **answerp;
1648 int type;
1650 const cpp_token *paren;
1651 struct answer *answer;
1652 unsigned int acount;
1654 /* In a conditional, it is legal to not have an open paren. We
1655 should save the following token in this case. */
1656 paren = cpp_get_token (pfile);
1658 /* If not a paren, see if we're OK. */
1659 if (paren->type != CPP_OPEN_PAREN)
1661 /* In a conditional no answer is a test for any answer. It
1662 could be followed by any token. */
1663 if (type == T_IF)
1665 _cpp_backup_tokens (pfile, 1);
1666 return 0;
1669 /* #unassert with no answer is valid - it removes all answers. */
1670 if (type == T_UNASSERT && paren->type == CPP_EOF)
1671 return 0;
1673 cpp_error (pfile, DL_ERROR, "missing '(' after predicate");
1674 return 1;
1677 for (acount = 0;; acount++)
1679 size_t room_needed;
1680 const cpp_token *token = cpp_get_token (pfile);
1681 cpp_token *dest;
1683 if (token->type == CPP_CLOSE_PAREN)
1684 break;
1686 if (token->type == CPP_EOF)
1688 cpp_error (pfile, DL_ERROR, "missing ')' to complete answer");
1689 return 1;
1692 /* struct answer includes the space for one token. */
1693 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
1695 if (BUFF_ROOM (pfile->a_buff) < room_needed)
1696 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
1698 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
1699 *dest = *token;
1701 /* Drop whitespace at start, for answer equivalence purposes. */
1702 if (acount == 0)
1703 dest->flags &= ~PREV_WHITE;
1706 if (acount == 0)
1708 cpp_error (pfile, DL_ERROR, "predicate's answer is empty");
1709 return 1;
1712 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
1713 answer->count = acount;
1714 answer->next = NULL;
1715 *answerp = answer;
1717 return 0;
1720 /* Parses an assertion directive of type TYPE, returning a pointer to
1721 the hash node of the predicate, or 0 on error. If an answer was
1722 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
1723 static cpp_hashnode *
1724 parse_assertion (pfile, answerp, type)
1725 cpp_reader *pfile;
1726 struct answer **answerp;
1727 int type;
1729 cpp_hashnode *result = 0;
1730 const cpp_token *predicate;
1732 /* We don't expand predicates or answers. */
1733 pfile->state.prevent_expansion++;
1735 *answerp = 0;
1736 predicate = cpp_get_token (pfile);
1737 if (predicate->type == CPP_EOF)
1738 cpp_error (pfile, DL_ERROR, "assertion without predicate");
1739 else if (predicate->type != CPP_NAME)
1740 cpp_error (pfile, DL_ERROR, "predicate must be an identifier");
1741 else if (parse_answer (pfile, answerp, type) == 0)
1743 unsigned int len = NODE_LEN (predicate->val.node);
1744 unsigned char *sym = alloca (len + 1);
1746 /* Prefix '#' to get it out of macro namespace. */
1747 sym[0] = '#';
1748 memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
1749 result = cpp_lookup (pfile, sym, len + 1);
1752 pfile->state.prevent_expansion--;
1753 return result;
1756 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
1757 or a pointer to NULL if the answer is not in the chain. */
1758 static struct answer **
1759 find_answer (node, candidate)
1760 cpp_hashnode *node;
1761 const struct answer *candidate;
1763 unsigned int i;
1764 struct answer **result;
1766 for (result = &node->value.answers; *result; result = &(*result)->next)
1768 struct answer *answer = *result;
1770 if (answer->count == candidate->count)
1772 for (i = 0; i < answer->count; i++)
1773 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
1774 break;
1776 if (i == answer->count)
1777 break;
1781 return result;
1784 /* Test an assertion within a preprocessor conditional. Returns
1785 nonzero on failure, zero on success. On success, the result of
1786 the test is written into VALUE, otherwise the value 0. */
1788 _cpp_test_assertion (pfile, value)
1789 cpp_reader *pfile;
1790 unsigned int *value;
1792 struct answer *answer;
1793 cpp_hashnode *node;
1795 node = parse_assertion (pfile, &answer, T_IF);
1797 /* For recovery, an erroneous assertion expression is handled as a
1798 failing assertion. */
1799 *value = 0;
1801 if (node)
1802 *value = (node->type == NT_ASSERTION &&
1803 (answer == 0 || *find_answer (node, answer) != 0));
1804 else if (pfile->cur_token[-1].type == CPP_EOF)
1805 _cpp_backup_tokens (pfile, 1);
1807 /* We don't commit the memory for the answer - it's temporary only. */
1808 return node == 0;
1811 /* Handle #assert. */
1812 static void
1813 do_assert (pfile)
1814 cpp_reader *pfile;
1816 struct answer *new_answer;
1817 cpp_hashnode *node;
1819 node = parse_assertion (pfile, &new_answer, T_ASSERT);
1820 if (node)
1822 /* Place the new answer in the answer list. First check there
1823 is not a duplicate. */
1824 new_answer->next = 0;
1825 if (node->type == NT_ASSERTION)
1827 if (*find_answer (node, new_answer))
1829 cpp_error (pfile, DL_WARNING, "\"%s\" re-asserted",
1830 NODE_NAME (node) + 1);
1831 return;
1833 new_answer->next = node->value.answers;
1836 node->type = NT_ASSERTION;
1837 node->value.answers = new_answer;
1838 BUFF_FRONT (pfile->a_buff) += (sizeof (struct answer)
1839 + (new_answer->count - 1)
1840 * sizeof (cpp_token));
1841 check_eol (pfile);
1845 /* Handle #unassert. */
1846 static void
1847 do_unassert (pfile)
1848 cpp_reader *pfile;
1850 cpp_hashnode *node;
1851 struct answer *answer;
1853 node = parse_assertion (pfile, &answer, T_UNASSERT);
1854 /* It isn't an error to #unassert something that isn't asserted. */
1855 if (node && node->type == NT_ASSERTION)
1857 if (answer)
1859 struct answer **p = find_answer (node, answer), *temp;
1861 /* Remove the answer from the list. */
1862 temp = *p;
1863 if (temp)
1864 *p = temp->next;
1866 /* Did we free the last answer? */
1867 if (node->value.answers == 0)
1868 node->type = NT_VOID;
1870 check_eol (pfile);
1872 else
1873 _cpp_free_definition (node);
1876 /* We don't commit the memory for the answer - it's temporary only. */
1879 /* These are for -D, -U, -A. */
1881 /* Process the string STR as if it appeared as the body of a #define.
1882 If STR is just an identifier, define it with value 1.
1883 If STR has anything after the identifier, then it should
1884 be identifier=definition. */
1885 void
1886 cpp_define (pfile, str)
1887 cpp_reader *pfile;
1888 const char *str;
1890 char *buf, *p;
1891 size_t count;
1893 /* Copy the entire option so we can modify it.
1894 Change the first "=" in the string to a space. If there is none,
1895 tack " 1" on the end. */
1897 count = strlen (str);
1898 buf = (char *) alloca (count + 3);
1899 memcpy (buf, str, count);
1901 p = strchr (str, '=');
1902 if (p)
1903 buf[p - str] = ' ';
1904 else
1906 buf[count++] = ' ';
1907 buf[count++] = '1';
1909 buf[count] = '\n';
1911 run_directive (pfile, T_DEFINE, buf, count);
1914 /* Slight variant of the above for use by initialize_builtins. */
1915 void
1916 _cpp_define_builtin (pfile, str)
1917 cpp_reader *pfile;
1918 const char *str;
1920 size_t len = strlen (str);
1921 char *buf = alloca (len + 1);
1922 memcpy (buf, str, len);
1923 buf[len] = '\n';
1924 run_directive (pfile, T_DEFINE, buf, len);
1927 /* Process MACRO as if it appeared as the body of an #undef. */
1928 void
1929 cpp_undef (pfile, macro)
1930 cpp_reader *pfile;
1931 const char *macro;
1933 size_t len = strlen (macro);
1934 char *buf = alloca (len + 1);
1935 memcpy (buf, macro, len);
1936 buf[len] = '\n';
1937 run_directive (pfile, T_UNDEF, buf, len);
1940 /* Process the string STR as if it appeared as the body of a #assert. */
1941 void
1942 cpp_assert (pfile, str)
1943 cpp_reader *pfile;
1944 const char *str;
1946 handle_assertion (pfile, str, T_ASSERT);
1949 /* Process STR as if it appeared as the body of an #unassert. */
1950 void
1951 cpp_unassert (pfile, str)
1952 cpp_reader *pfile;
1953 const char *str;
1955 handle_assertion (pfile, str, T_UNASSERT);
1958 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
1959 static void
1960 handle_assertion (pfile, str, type)
1961 cpp_reader *pfile;
1962 const char *str;
1963 int type;
1965 size_t count = strlen (str);
1966 const char *p = strchr (str, '=');
1968 /* Copy the entire option so we can modify it. Change the first
1969 "=" in the string to a '(', and tack a ')' on the end. */
1970 char *buf = (char *) alloca (count + 2);
1972 memcpy (buf, str, count);
1973 if (p)
1975 buf[p - str] = '(';
1976 buf[count++] = ')';
1978 buf[count] = '\n';
1979 str = buf;
1981 run_directive (pfile, type, str, count);
1984 /* The number of errors for a given reader. */
1985 unsigned int
1986 cpp_errors (pfile)
1987 cpp_reader *pfile;
1989 return pfile->errors;
1992 /* The options structure. */
1993 cpp_options *
1994 cpp_get_options (pfile)
1995 cpp_reader *pfile;
1997 return &pfile->opts;
2000 /* The callbacks structure. */
2001 cpp_callbacks *
2002 cpp_get_callbacks (pfile)
2003 cpp_reader *pfile;
2005 return &pfile->cb;
2008 /* The line map set. */
2009 const struct line_maps *
2010 cpp_get_line_maps (pfile)
2011 cpp_reader *pfile;
2013 return &pfile->line_maps;
2016 /* Copy the given callbacks structure to our own. */
2017 void
2018 cpp_set_callbacks (pfile, cb)
2019 cpp_reader *pfile;
2020 cpp_callbacks *cb;
2022 pfile->cb = *cb;
2025 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2026 doesn't fail. It does not generate a file change call back; that
2027 is the responsibility of the caller. */
2028 cpp_buffer *
2029 cpp_push_buffer (pfile, buffer, len, from_stage3, return_at_eof)
2030 cpp_reader *pfile;
2031 const uchar *buffer;
2032 size_t len;
2033 int from_stage3;
2034 int return_at_eof;
2036 cpp_buffer *new = xobnew (&pfile->buffer_ob, cpp_buffer);
2038 /* Clears, amongst other things, if_stack and mi_cmacro. */
2039 memset (new, 0, sizeof (cpp_buffer));
2041 new->next_line = new->buf = buffer;
2042 new->rlimit = buffer + len;
2043 new->from_stage3 = from_stage3;
2044 new->prev = pfile->buffer;
2045 new->return_at_eof = return_at_eof;
2046 new->need_line = true;
2048 pfile->buffer = new;
2049 return new;
2052 /* Pops a single buffer, with a file change call-back if appropriate.
2053 Then pushes the next -include file, if any remain. */
2054 void
2055 _cpp_pop_buffer (pfile)
2056 cpp_reader *pfile;
2058 cpp_buffer *buffer = pfile->buffer;
2059 struct include_file *inc = buffer->inc;
2060 struct if_stack *ifs;
2062 /* Walk back up the conditional stack till we reach its level at
2063 entry to this file, issuing error messages. */
2064 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2065 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
2066 "unterminated #%s", dtable[ifs->type].name);
2068 /* In case of a missing #endif. */
2069 pfile->state.skipping = 0;
2071 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2072 pfile->buffer = buffer->prev;
2074 free (buffer->notes);
2076 /* Free the buffer object now; we may want to push a new buffer
2077 in _cpp_push_next_include_file. */
2078 obstack_free (&pfile->buffer_ob, buffer);
2080 if (inc)
2082 _cpp_pop_file_buffer (pfile, inc);
2084 /* Don't generate a callback for popping the main file. */
2085 if (pfile->buffer)
2086 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2090 /* Enter all recognized directives in the hash table. */
2091 void
2092 _cpp_init_directives (pfile)
2093 cpp_reader *pfile;
2095 unsigned int i;
2096 cpp_hashnode *node;
2098 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2100 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2101 node->is_directive = 1;
2102 node->directive_index = i;