2003-02-06 Andreas Tobler <a.tobler@schweiz.ch>
[official-gcc.git] / gcc / cpplib.c
bloba40fe1229ff4e5f5f111ce36dbc983484112b0d6
1 /* CPP Library. (Directive handling.)
2 Copyright (C) 1986, 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000, 2001, 2002 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 _cpp_read_logical_line_trad (pfile);
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 if (! CPP_OPTION (pfile, preprocessed))
418 directive_diagnostics (pfile, dir, indented);
419 if (pfile->state.skipping && !(dir->flags & COND))
420 dir = 0;
423 else if (dname->type == CPP_EOF)
424 ; /* CPP_EOF is the "null directive". */
425 else
427 /* An unknown directive. Don't complain about it in assembly
428 source: we don't know where the comments are, and # may
429 introduce assembler pseudo-ops. Don't complain about invalid
430 directives in skipped conditional groups (6.10 p4). */
431 if (CPP_OPTION (pfile, lang) == CLK_ASM)
432 skip = 0;
433 else if (!pfile->state.skipping)
434 cpp_error (pfile, DL_ERROR, "invalid preprocessing directive #%s",
435 cpp_token_as_text (pfile, dname));
438 pfile->directive = dir;
439 if (CPP_OPTION (pfile, traditional))
440 prepare_directive_trad (pfile);
442 if (dir)
443 (*pfile->directive->handler) (pfile);
444 else if (skip == 0)
445 _cpp_backup_tokens (pfile, 1);
447 end_directive (pfile, skip);
448 if (was_parsing_args)
450 /* Restore state when within macro args. */
451 pfile->state.parsing_args = 2;
452 pfile->state.prevent_expansion = 1;
453 pfile->buffer->saved_flags |= PREV_WHITE;
455 return skip;
458 /* Directive handler wrapper used by the command line option
459 processor. */
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);
473 /* We don't want a leading # to be interpreted as a directive. */
474 pfile->buffer->saved_flags = 0;
475 pfile->directive = &dtable[dir_no];
476 if (CPP_OPTION (pfile, traditional))
477 prepare_directive_trad (pfile);
478 (void) (*pfile->directive->handler) (pfile);
479 end_directive (pfile, 1);
480 if (dir_no == T_PRAGMA)
481 pfile->buffer->inc = NULL;
482 _cpp_pop_buffer (pfile);
485 /* Checks for validity the macro name in #define, #undef, #ifdef and
486 #ifndef directives. */
487 static cpp_hashnode *
488 lex_macro_node (pfile)
489 cpp_reader *pfile;
491 const cpp_token *token = _cpp_lex_token (pfile);
493 /* The token immediately after #define must be an identifier. That
494 identifier may not be "defined", per C99 6.10.8p4.
495 In C++, it may not be any of the "named operators" either,
496 per C++98 [lex.digraph], [lex.key].
497 Finally, the identifier may not have been poisoned. (In that case
498 the lexer has issued the error message for us.) */
500 if (token->type == CPP_NAME)
502 cpp_hashnode *node = token->val.node;
504 if (node == pfile->spec_nodes.n_defined)
505 cpp_error (pfile, DL_ERROR,
506 "\"defined\" cannot be used as a macro name");
507 else if (! (node->flags & NODE_POISONED))
508 return node;
510 else if (token->flags & NAMED_OP)
511 cpp_error (pfile, DL_ERROR,
512 "\"%s\" cannot be used as a macro name as it is an operator in C++",
513 NODE_NAME (token->val.node));
514 else if (token->type == CPP_EOF)
515 cpp_error (pfile, DL_ERROR, "no macro name given in #%s directive",
516 pfile->directive->name);
517 else
518 cpp_error (pfile, DL_ERROR, "macro names must be identifiers");
520 return NULL;
523 /* Process a #define directive. Most work is done in cppmacro.c. */
524 static void
525 do_define (pfile)
526 cpp_reader *pfile;
528 cpp_hashnode *node = lex_macro_node (pfile);
530 if (node)
532 /* If we have been requested to expand comments into macros,
533 then re-enable saving of comments. */
534 pfile->state.save_comments =
535 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
537 if (_cpp_create_definition (pfile, node))
538 if (pfile->cb.define)
539 (*pfile->cb.define) (pfile, pfile->directive_line, node);
543 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
544 static void
545 do_undef (pfile)
546 cpp_reader *pfile;
548 cpp_hashnode *node = lex_macro_node (pfile);
550 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified identifier
551 is not currently defined as a macro name. */
552 if (node && node->type == NT_MACRO)
554 if (pfile->cb.undef)
555 (*pfile->cb.undef) (pfile, pfile->directive_line, node);
557 if (node->flags & NODE_WARN)
558 cpp_error (pfile, DL_WARNING, "undefining \"%s\"", NODE_NAME (node));
560 if (CPP_OPTION (pfile, warn_unused_macros))
561 _cpp_warn_if_unused_macro (pfile, node, NULL);
563 _cpp_free_definition (node);
565 check_eol (pfile);
568 /* Helper routine used by parse_include. Reinterpret the current line
569 as an h-char-sequence (< ... >); we are looking at the first token
570 after the <. Returns the header as a token, or NULL on failure. */
571 static const cpp_token *
572 glue_header_name (pfile)
573 cpp_reader *pfile;
575 cpp_token *header = NULL;
576 const cpp_token *token;
577 unsigned char *buffer;
578 size_t len, total_len = 0, capacity = 1024;
580 /* To avoid lexed tokens overwriting our glued name, we can only
581 allocate from the string pool once we've lexed everything. */
582 buffer = (unsigned char *) xmalloc (capacity);
583 for (;;)
585 token = cpp_get_token (pfile);
587 if (token->type == CPP_GREATER || token->type == CPP_EOF)
588 break;
590 len = cpp_token_len (token);
591 if (total_len + len > capacity)
593 capacity = (capacity + len) * 2;
594 buffer = (unsigned char *) xrealloc (buffer, capacity);
597 if (token->flags & PREV_WHITE)
598 buffer[total_len++] = ' ';
600 total_len = cpp_spell_token (pfile, token, &buffer[total_len]) - buffer;
603 if (token->type == CPP_EOF)
604 cpp_error (pfile, DL_ERROR, "missing terminating > character");
605 else
607 unsigned char *token_mem = _cpp_unaligned_alloc (pfile, total_len + 1);
608 memcpy (token_mem, buffer, total_len);
609 token_mem[total_len] = '\0';
611 header = _cpp_temp_token (pfile);
612 header->type = CPP_HEADER_NAME;
613 header->flags = 0;
614 header->val.str.len = total_len;
615 header->val.str.text = token_mem;
618 free ((PTR) buffer);
619 return header;
622 /* Returns the header string of #include, #include_next, #import and
623 #pragma dependency. Returns NULL on error. */
624 static const cpp_token *
625 parse_include (pfile)
626 cpp_reader *pfile;
628 const unsigned char *dir;
629 const cpp_token *header;
631 if (pfile->directive == &dtable[T_PRAGMA])
632 dir = U"pragma dependency";
633 else
634 dir = pfile->directive->name;
636 /* Allow macro expansion. */
637 header = cpp_get_token (pfile);
638 if (header->type != CPP_STRING && header->type != CPP_HEADER_NAME)
640 if (header->type != CPP_LESS)
642 cpp_error (pfile, DL_ERROR,
643 "#%s expects \"FILENAME\" or <FILENAME>", dir);
644 return NULL;
647 header = glue_header_name (pfile);
648 if (header == NULL)
649 return header;
652 if (header->val.str.len == 0)
654 cpp_error (pfile, DL_ERROR, "empty file name in #%s", dir);
655 return NULL;
658 return header;
661 /* Handle #include, #include_next and #import. */
662 static void
663 do_include_common (pfile, type)
664 cpp_reader *pfile;
665 enum include_type type;
667 const cpp_token *header;
669 /* For #include_next, if this is the primary source file, warn and
670 use the normal search logic. */
671 if (type == IT_INCLUDE_NEXT && ! pfile->buffer->prev)
673 cpp_error (pfile, DL_WARNING, "#include_next in primary source file");
674 type = IT_INCLUDE;
676 else if (type == IT_IMPORT && CPP_OPTION (pfile, warn_import))
678 CPP_OPTION (pfile, warn_import) = 0;
679 cpp_error (pfile, DL_WARNING,
680 "#import is obsolete, use an #ifndef wrapper in the header file");
683 header = parse_include (pfile);
684 if (header)
686 /* Prevent #include recursion. */
687 if (pfile->line_maps.depth >= CPP_STACK_MAX)
688 cpp_error (pfile, DL_ERROR, "#include nested too deeply");
689 else
691 check_eol (pfile);
692 /* Get out of macro context, if we are. */
693 skip_rest_of_line (pfile);
694 if (pfile->cb.include)
695 (*pfile->cb.include) (pfile, pfile->directive_line,
696 pfile->directive->name, header);
697 _cpp_execute_include (pfile, header, type);
702 static void
703 do_include (pfile)
704 cpp_reader *pfile;
706 do_include_common (pfile, IT_INCLUDE);
709 static void
710 do_import (pfile)
711 cpp_reader *pfile;
713 do_include_common (pfile, IT_IMPORT);
716 static void
717 do_include_next (pfile)
718 cpp_reader *pfile;
720 do_include_common (pfile, IT_INCLUDE_NEXT);
723 /* Subroutine of do_linemarker. Read possible flags after file name.
724 LAST is the last flag seen; 0 if this is the first flag. Return the
725 flag if it is valid, 0 at the end of the directive. Otherwise
726 complain. */
727 static unsigned int
728 read_flag (pfile, last)
729 cpp_reader *pfile;
730 unsigned int last;
732 const cpp_token *token = _cpp_lex_token (pfile);
734 if (token->type == CPP_NUMBER && token->val.str.len == 1)
736 unsigned int flag = token->val.str.text[0] - '0';
738 if (flag > last && flag <= 4
739 && (flag != 4 || last == 3)
740 && (flag != 2 || last == 0))
741 return flag;
744 if (token->type != CPP_EOF)
745 cpp_error (pfile, DL_ERROR, "invalid flag \"%s\" in line directive",
746 cpp_token_as_text (pfile, token));
747 return 0;
750 /* Subroutine of do_line and do_linemarker. Returns a version of STR
751 which has a NUL terminator and all escape sequences converted to
752 their equivalents. Temporary, hopefully. */
753 static uchar *
754 dequote_string (pfile, str, len)
755 cpp_reader *pfile;
756 const uchar *str;
757 unsigned int len;
759 uchar *result = _cpp_unaligned_alloc (pfile, len + 1);
760 uchar *dst = result;
761 const uchar *limit = str + len;
762 cppchar_t c;
764 while (str < limit)
766 c = *str++;
767 if (c != '\\')
768 *dst++ = c;
769 else
770 *dst++ = cpp_parse_escape (pfile, &str, limit, 0);
772 *dst++ = '\0';
773 return result;
776 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
777 of length LEN, to binary; store it in NUMP, and return 0 if the
778 number was well-formed, 1 if not. Temporary, hopefully. */
779 static int
780 strtoul_for_line (str, len, nump)
781 const uchar *str;
782 unsigned int len;
783 unsigned long *nump;
785 unsigned long reg = 0;
786 uchar c;
787 while (len--)
789 c = *str++;
790 if (!ISDIGIT (c))
791 return 1;
792 reg *= 10;
793 reg += c - '0';
795 *nump = reg;
796 return 0;
799 /* Interpret #line command.
800 Note that the filename string (if any) is a true string constant
801 (escapes are interpreted), unlike in #line. */
802 static void
803 do_line (pfile)
804 cpp_reader *pfile;
806 const cpp_token *token;
807 const char *new_file = pfile->map->to_file;
808 unsigned long new_lineno;
810 /* C99 raised the minimum limit on #line numbers. */
811 unsigned int cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
813 /* #line commands expand macros. */
814 token = cpp_get_token (pfile);
815 if (token->type != CPP_NUMBER
816 || strtoul_for_line (token->val.str.text, token->val.str.len,
817 &new_lineno))
819 cpp_error (pfile, DL_ERROR,
820 "\"%s\" after #line is not a positive integer",
821 cpp_token_as_text (pfile, token));
822 return;
825 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap))
826 cpp_error (pfile, DL_PEDWARN, "line number out of range");
828 token = cpp_get_token (pfile);
829 if (token->type == CPP_STRING)
831 new_file = (const char *) dequote_string (pfile, token->val.str.text,
832 token->val.str.len);
833 check_eol (pfile);
835 else if (token->type != CPP_EOF)
837 cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
838 cpp_token_as_text (pfile, token));
839 return;
842 skip_rest_of_line (pfile);
843 _cpp_do_file_change (pfile, LC_RENAME, new_file, new_lineno,
844 pfile->map->sysp);
847 /* Interpret the # 44 "file" [flags] notation, which has slightly
848 different syntax and semantics from #line: Flags are allowed,
849 and we never complain about the line number being too big. */
850 static void
851 do_linemarker (pfile)
852 cpp_reader *pfile;
854 const cpp_token *token;
855 const char *new_file = pfile->map->to_file;
856 unsigned long new_lineno;
857 unsigned int new_sysp = pfile->map->sysp;
858 enum lc_reason reason = LC_RENAME;
859 int flag;
861 /* Back up so we can get the number again. Putting this in
862 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
863 some circumstances, which can segfault. */
864 _cpp_backup_tokens (pfile, 1);
866 /* #line commands expand macros. */
867 token = cpp_get_token (pfile);
868 if (token->type != CPP_NUMBER
869 || strtoul_for_line (token->val.str.text, token->val.str.len,
870 &new_lineno))
872 cpp_error (pfile, DL_ERROR, "\"%s\" after # is not a positive integer",
873 cpp_token_as_text (pfile, token));
874 return;
877 token = cpp_get_token (pfile);
878 if (token->type == CPP_STRING)
880 new_file = (const char *) dequote_string (pfile, token->val.str.text,
881 token->val.str.len);
882 new_sysp = 0;
883 flag = read_flag (pfile, 0);
884 if (flag == 1)
886 reason = LC_ENTER;
887 /* Fake an include for cpp_included (). */
888 _cpp_fake_include (pfile, new_file);
889 flag = read_flag (pfile, flag);
891 else if (flag == 2)
893 reason = LC_LEAVE;
894 flag = read_flag (pfile, flag);
896 if (flag == 3)
898 new_sysp = 1;
899 flag = read_flag (pfile, flag);
900 if (flag == 4)
901 new_sysp = 2;
904 check_eol (pfile);
906 else if (token->type != CPP_EOF)
908 cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
909 cpp_token_as_text (pfile, token));
910 return;
913 skip_rest_of_line (pfile);
914 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
917 /* Arrange the file_change callback. pfile->line has changed to
918 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
919 header, 2 for a system header that needs to be extern "C" protected,
920 and zero otherwise. */
921 void
922 _cpp_do_file_change (pfile, reason, to_file, file_line, sysp)
923 cpp_reader *pfile;
924 enum lc_reason reason;
925 const char *to_file;
926 unsigned int file_line;
927 unsigned int sysp;
929 pfile->map = add_line_map (&pfile->line_maps, reason, sysp,
930 pfile->line, to_file, file_line);
932 if (pfile->cb.file_change)
933 (*pfile->cb.file_change) (pfile, pfile->map);
936 /* Report a warning or error detected by the program we are
937 processing. Use the directive's tokens in the error message. */
938 static void
939 do_diagnostic (pfile, code, print_dir)
940 cpp_reader *pfile;
941 int code;
942 int print_dir;
944 if (_cpp_begin_message (pfile, code,
945 pfile->cur_token[-1].line,
946 pfile->cur_token[-1].col))
948 if (print_dir)
949 fprintf (stderr, "#%s ", pfile->directive->name);
950 pfile->state.prevent_expansion++;
951 cpp_output_line (pfile, stderr);
952 pfile->state.prevent_expansion--;
956 static void
957 do_error (pfile)
958 cpp_reader *pfile;
960 do_diagnostic (pfile, DL_ERROR, 1);
963 static void
964 do_warning (pfile)
965 cpp_reader *pfile;
967 /* We want #warning diagnostics to be emitted in system headers too. */
968 do_diagnostic (pfile, DL_WARNING_SYSHDR, 1);
971 /* Report program identification. */
972 static void
973 do_ident (pfile)
974 cpp_reader *pfile;
976 const cpp_token *str = cpp_get_token (pfile);
978 if (str->type != CPP_STRING)
979 cpp_error (pfile, DL_ERROR, "invalid #ident directive");
980 else if (pfile->cb.ident)
981 (*pfile->cb.ident) (pfile, pfile->directive_line, &str->val.str);
983 check_eol (pfile);
986 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
987 matching entry, or NULL if none is found. The returned entry could
988 be the start of a namespace chain, or a pragma. */
989 static struct pragma_entry *
990 lookup_pragma_entry (chain, pragma)
991 struct pragma_entry *chain;
992 const cpp_hashnode *pragma;
994 while (chain && chain->pragma != pragma)
995 chain = chain->next;
997 return chain;
1000 /* Create and insert a pragma entry for NAME at the beginning of a
1001 singly-linked CHAIN. If handler is NULL, it is a namespace,
1002 otherwise it is a pragma and its handler. */
1003 static struct pragma_entry *
1004 insert_pragma_entry (pfile, chain, pragma, handler)
1005 cpp_reader *pfile;
1006 struct pragma_entry **chain;
1007 const cpp_hashnode *pragma;
1008 pragma_cb handler;
1010 struct pragma_entry *new;
1012 new = (struct pragma_entry *)
1013 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1014 new->pragma = pragma;
1015 if (handler)
1017 new->is_nspace = 0;
1018 new->u.handler = handler;
1020 else
1022 new->is_nspace = 1;
1023 new->u.space = NULL;
1026 new->next = *chain;
1027 *chain = new;
1028 return new;
1031 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
1032 goes in the global namespace. HANDLER is the handler it will call,
1033 which must be non-NULL. */
1034 void
1035 cpp_register_pragma (pfile, space, name, handler)
1036 cpp_reader *pfile;
1037 const char *space;
1038 const char *name;
1039 pragma_cb handler;
1041 struct pragma_entry **chain = &pfile->pragmas;
1042 struct pragma_entry *entry;
1043 const cpp_hashnode *node;
1045 if (!handler)
1046 abort ();
1048 if (space)
1050 node = cpp_lookup (pfile, U space, strlen (space));
1051 entry = lookup_pragma_entry (*chain, node);
1052 if (!entry)
1053 entry = insert_pragma_entry (pfile, chain, node, NULL);
1054 else if (!entry->is_nspace)
1055 goto clash;
1056 chain = &entry->u.space;
1059 /* Check for duplicates. */
1060 node = cpp_lookup (pfile, U name, strlen (name));
1061 entry = lookup_pragma_entry (*chain, node);
1062 if (entry)
1064 if (entry->is_nspace)
1065 clash:
1066 cpp_error (pfile, DL_ICE,
1067 "registering \"%s\" as both a pragma and a pragma namespace",
1068 NODE_NAME (node));
1069 else if (space)
1070 cpp_error (pfile, DL_ICE, "#pragma %s %s is already registered",
1071 space, name);
1072 else
1073 cpp_error (pfile, DL_ICE, "#pragma %s is already registered", name);
1075 else
1076 insert_pragma_entry (pfile, chain, node, handler);
1079 /* Register the pragmas the preprocessor itself handles. */
1080 void
1081 _cpp_init_internal_pragmas (pfile)
1082 cpp_reader *pfile;
1084 /* Pragmas in the global namespace. */
1085 cpp_register_pragma (pfile, 0, "once", do_pragma_once);
1087 /* New GCC-specific pragmas should be put in the GCC namespace. */
1088 cpp_register_pragma (pfile, "GCC", "poison", do_pragma_poison);
1089 cpp_register_pragma (pfile, "GCC", "system_header", do_pragma_system_header);
1090 cpp_register_pragma (pfile, "GCC", "dependency", do_pragma_dependency);
1093 /* Return the number of registered pragmas in PE. */
1095 static int
1096 count_registered_pragmas (pe)
1097 struct pragma_entry *pe;
1099 int ct = 0;
1100 for (; pe != NULL; pe = pe->next)
1102 if (pe->is_nspace)
1103 ct += count_registered_pragmas (pe->u.space);
1104 ct++;
1106 return ct;
1109 /* Save into SD the names of the registered pragmas referenced by PE,
1110 and return a pointer to the next free space in SD. */
1112 static char **
1113 save_registered_pragmas (pe, sd)
1114 struct pragma_entry *pe;
1115 char **sd;
1117 for (; pe != NULL; pe = pe->next)
1119 if (pe->is_nspace)
1120 sd = save_registered_pragmas (pe->u.space, sd);
1121 *sd++ = xmemdup (HT_STR (&pe->pragma->ident),
1122 HT_LEN (&pe->pragma->ident),
1123 HT_LEN (&pe->pragma->ident) + 1);
1125 return sd;
1128 /* Return a newly-allocated array which saves the names of the
1129 registered pragmas. */
1131 char **
1132 _cpp_save_pragma_names (pfile)
1133 cpp_reader *pfile;
1135 int ct = count_registered_pragmas (pfile->pragmas);
1136 char **result = xnewvec (char *, ct);
1137 (void) save_registered_pragmas (pfile->pragmas, result);
1138 return result;
1141 /* Restore from SD the names of the registered pragmas referenced by PE,
1142 and return a pointer to the next unused name in SD. */
1144 static char **
1145 restore_registered_pragmas (pfile, pe, sd)
1146 cpp_reader *pfile;
1147 struct pragma_entry *pe;
1148 char **sd;
1150 for (; pe != NULL; pe = pe->next)
1152 if (pe->is_nspace)
1153 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1154 pe->pragma = cpp_lookup (pfile, U *sd, strlen (*sd));
1155 free (*sd);
1156 sd++;
1158 return sd;
1161 /* Restore the names of the registered pragmas from SAVED. */
1163 void
1164 _cpp_restore_pragma_names (pfile, saved)
1165 cpp_reader *pfile;
1166 char **saved;
1168 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1169 free (saved);
1172 /* Pragmata handling. We handle some, and pass the rest on to the
1173 front end. C99 defines three pragmas and says that no macro
1174 expansion is to be performed on them; whether or not macro
1175 expansion happens for other pragmas is implementation defined.
1176 This implementation never macro-expands the text after #pragma. */
1177 static void
1178 do_pragma (pfile)
1179 cpp_reader *pfile;
1181 const struct pragma_entry *p = NULL;
1182 const cpp_token *token;
1183 unsigned int count = 1;
1185 pfile->state.prevent_expansion++;
1187 token = cpp_get_token (pfile);
1188 if (token->type == CPP_NAME)
1190 p = lookup_pragma_entry (pfile->pragmas, token->val.node);
1191 if (p && p->is_nspace)
1193 count = 2;
1194 token = cpp_get_token (pfile);
1195 if (token->type == CPP_NAME)
1196 p = lookup_pragma_entry (p->u.space, token->val.node);
1197 else
1198 p = NULL;
1202 /* FIXME. This is an awful kludge to get the front ends to update
1203 their notion of line number for diagnostic purposes. The line
1204 number should be passed to the handler and they should do it
1205 themselves. Stand-alone CPP must ignore us, otherwise it will
1206 prefix the directive with spaces, hence the 1. Ugh. */
1207 if (pfile->cb.line_change)
1208 (*pfile->cb.line_change)(pfile, token, 1);
1210 if (p)
1211 (*p->u.handler) (pfile);
1212 else if (pfile->cb.def_pragma)
1214 _cpp_backup_tokens (pfile, count);
1215 (*pfile->cb.def_pragma) (pfile, pfile->directive_line);
1218 pfile->state.prevent_expansion--;
1221 /* Handle #pragma once. */
1222 static void
1223 do_pragma_once (pfile)
1224 cpp_reader *pfile;
1226 if (CPP_OPTION (pfile, warn_deprecated))
1227 cpp_error (pfile, DL_WARNING, "#pragma once is obsolete");
1229 if (pfile->buffer->prev == NULL)
1230 cpp_error (pfile, DL_WARNING, "#pragma once in main file");
1231 else
1232 _cpp_never_reread (pfile->buffer->inc);
1234 check_eol (pfile);
1237 /* Handle #pragma GCC poison, to poison one or more identifiers so
1238 that the lexer produces a hard error for each subsequent usage. */
1239 static void
1240 do_pragma_poison (pfile)
1241 cpp_reader *pfile;
1243 const cpp_token *tok;
1244 cpp_hashnode *hp;
1246 pfile->state.poisoned_ok = 1;
1247 for (;;)
1249 tok = _cpp_lex_token (pfile);
1250 if (tok->type == CPP_EOF)
1251 break;
1252 if (tok->type != CPP_NAME)
1254 cpp_error (pfile, DL_ERROR, "invalid #pragma GCC poison directive");
1255 break;
1258 hp = tok->val.node;
1259 if (hp->flags & NODE_POISONED)
1260 continue;
1262 if (hp->type == NT_MACRO)
1263 cpp_error (pfile, DL_WARNING, "poisoning existing macro \"%s\"",
1264 NODE_NAME (hp));
1265 _cpp_free_definition (hp);
1266 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1268 pfile->state.poisoned_ok = 0;
1271 /* Mark the current header as a system header. This will suppress
1272 some categories of warnings (notably those from -pedantic). It is
1273 intended for use in system libraries that cannot be implemented in
1274 conforming C, but cannot be certain that their headers appear in a
1275 system include directory. To prevent abuse, it is rejected in the
1276 primary source file. */
1277 static void
1278 do_pragma_system_header (pfile)
1279 cpp_reader *pfile;
1281 cpp_buffer *buffer = pfile->buffer;
1283 if (buffer->prev == 0)
1284 cpp_error (pfile, DL_WARNING,
1285 "#pragma system_header ignored outside include file");
1286 else
1288 check_eol (pfile);
1289 skip_rest_of_line (pfile);
1290 cpp_make_system_header (pfile, 1, 0);
1294 /* Check the modified date of the current include file against a specified
1295 file. Issue a diagnostic, if the specified file is newer. We use this to
1296 determine if a fixed header should be refixed. */
1297 static void
1298 do_pragma_dependency (pfile)
1299 cpp_reader *pfile;
1301 const cpp_token *header;
1302 int ordering;
1304 header = parse_include (pfile);
1305 if (!header)
1306 return;
1308 ordering = _cpp_compare_file_date (pfile, header);
1309 if (ordering < 0)
1310 cpp_error (pfile, DL_WARNING, "cannot find source %s",
1311 cpp_token_as_text (pfile, header));
1312 else if (ordering > 0)
1314 cpp_error (pfile, DL_WARNING, "current file is older than %s",
1315 cpp_token_as_text (pfile, header));
1316 if (cpp_get_token (pfile)->type != CPP_EOF)
1318 _cpp_backup_tokens (pfile, 1);
1319 do_diagnostic (pfile, DL_WARNING, 0);
1324 /* Get a token but skip padding. */
1325 static const cpp_token *
1326 get_token_no_padding (pfile)
1327 cpp_reader *pfile;
1329 for (;;)
1331 const cpp_token *result = cpp_get_token (pfile);
1332 if (result->type != CPP_PADDING)
1333 return result;
1337 /* Check syntax is "(string-literal)". Returns the string on success,
1338 or NULL on failure. */
1339 static const cpp_token *
1340 get__Pragma_string (pfile)
1341 cpp_reader *pfile;
1343 const cpp_token *string;
1345 if (get_token_no_padding (pfile)->type != CPP_OPEN_PAREN)
1346 return NULL;
1348 string = get_token_no_padding (pfile);
1349 if (string->type != CPP_STRING && string->type != CPP_WSTRING)
1350 return NULL;
1352 if (get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
1353 return NULL;
1355 return string;
1358 /* Destringize IN into a temporary buffer, by removing the first \ of
1359 \" and \\ sequences, and process the result as a #pragma directive. */
1360 static void
1361 destringize_and_run (pfile, in)
1362 cpp_reader *pfile;
1363 const cpp_string *in;
1365 const unsigned char *src, *limit;
1366 char *dest, *result;
1368 dest = result = alloca (in->len + 1);
1369 for (src = in->text, limit = src + in->len; src < limit;)
1371 /* We know there is a character following the backslash. */
1372 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1373 src++;
1374 *dest++ = *src++;
1376 *dest = '\0';
1378 /* Ugh; an awful kludge. We are really not set up to be lexing
1379 tokens when in the middle of a macro expansion. Use a new
1380 context to force cpp_get_token to lex, and so skip_rest_of_line
1381 doesn't go beyond the end of the text. Also, remember the
1382 current lexing position so we can return to it later.
1384 Something like line-at-a-time lexing should remove the need for
1385 this. */
1387 cpp_context *saved_context = pfile->context;
1388 cpp_token *saved_cur_token = pfile->cur_token;
1389 tokenrun *saved_cur_run = pfile->cur_run;
1391 pfile->context = xnew (cpp_context);
1392 pfile->context->macro = 0;
1393 pfile->context->prev = 0;
1394 run_directive (pfile, T_PRAGMA, result, dest - result);
1395 free (pfile->context);
1396 pfile->context = saved_context;
1397 pfile->cur_token = saved_cur_token;
1398 pfile->cur_run = saved_cur_run;
1399 pfile->line--;
1402 /* See above comment. For the moment, we'd like
1404 token1 _Pragma ("foo") token2
1406 to be output as
1408 token1
1409 # 7 "file.c"
1410 #pragma foo
1411 # 7 "file.c"
1412 token2
1414 Getting the line markers is a little tricky. */
1415 if (pfile->cb.line_change)
1416 (*pfile->cb.line_change) (pfile, pfile->cur_token, false);
1419 /* Handle the _Pragma operator. */
1420 void
1421 _cpp_do__Pragma (pfile)
1422 cpp_reader *pfile;
1424 const cpp_token *string = get__Pragma_string (pfile);
1426 if (string)
1427 destringize_and_run (pfile, &string->val.str);
1428 else
1429 cpp_error (pfile, DL_ERROR,
1430 "_Pragma takes a parenthesized string literal");
1433 /* Just ignore #sccs on all systems. */
1434 static void
1435 do_sccs (pfile)
1436 cpp_reader *pfile ATTRIBUTE_UNUSED;
1440 /* Handle #ifdef. */
1441 static void
1442 do_ifdef (pfile)
1443 cpp_reader *pfile;
1445 int skip = 1;
1447 if (! pfile->state.skipping)
1449 const cpp_hashnode *node = lex_macro_node (pfile);
1451 if (node)
1453 skip = node->type != NT_MACRO;
1454 _cpp_mark_macro_used (node);
1455 check_eol (pfile);
1459 push_conditional (pfile, skip, T_IFDEF, 0);
1462 /* Handle #ifndef. */
1463 static void
1464 do_ifndef (pfile)
1465 cpp_reader *pfile;
1467 int skip = 1;
1468 const cpp_hashnode *node = 0;
1470 if (! pfile->state.skipping)
1472 node = lex_macro_node (pfile);
1474 if (node)
1476 skip = node->type == NT_MACRO;
1477 _cpp_mark_macro_used (node);
1478 check_eol (pfile);
1482 push_conditional (pfile, skip, T_IFNDEF, node);
1485 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1486 pfile->mi_ind_cmacro so we can handle multiple-include
1487 optimisations. If macro expansion occurs in the expression, we
1488 cannot treat it as a controlling conditional, since the expansion
1489 could change in the future. That is handled by cpp_get_token. */
1490 static void
1491 do_if (pfile)
1492 cpp_reader *pfile;
1494 int skip = 1;
1496 if (! pfile->state.skipping)
1497 skip = _cpp_parse_expr (pfile) == false;
1499 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1502 /* Flip skipping state if appropriate and continue without changing
1503 if_stack; this is so that the error message for missing #endif's
1504 etc. will point to the original #if. */
1505 static void
1506 do_else (pfile)
1507 cpp_reader *pfile;
1509 cpp_buffer *buffer = pfile->buffer;
1510 struct if_stack *ifs = buffer->if_stack;
1512 if (ifs == NULL)
1513 cpp_error (pfile, DL_ERROR, "#else without #if");
1514 else
1516 if (ifs->type == T_ELSE)
1518 cpp_error (pfile, DL_ERROR, "#else after #else");
1519 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1520 "the conditional began here");
1522 ifs->type = T_ELSE;
1524 /* Skip any future (erroneous) #elses or #elifs. */
1525 pfile->state.skipping = ifs->skip_elses;
1526 ifs->skip_elses = true;
1528 /* Invalidate any controlling macro. */
1529 ifs->mi_cmacro = 0;
1531 /* Only check EOL if was not originally skipping. */
1532 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1533 check_eol (pfile);
1537 /* Handle a #elif directive by not changing if_stack either. See the
1538 comment above do_else. */
1539 static void
1540 do_elif (pfile)
1541 cpp_reader *pfile;
1543 cpp_buffer *buffer = pfile->buffer;
1544 struct if_stack *ifs = buffer->if_stack;
1546 if (ifs == NULL)
1547 cpp_error (pfile, DL_ERROR, "#elif without #if");
1548 else
1550 if (ifs->type == T_ELSE)
1552 cpp_error (pfile, DL_ERROR, "#elif after #else");
1553 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1554 "the conditional began here");
1556 ifs->type = T_ELIF;
1558 /* Only evaluate this if we aren't skipping elses. During
1559 evaluation, set skipping to false to get lexer warnings. */
1560 if (ifs->skip_elses)
1561 pfile->state.skipping = 1;
1562 else
1564 pfile->state.skipping = 0;
1565 pfile->state.skipping = ! _cpp_parse_expr (pfile);
1566 ifs->skip_elses = ! pfile->state.skipping;
1569 /* Invalidate any controlling macro. */
1570 ifs->mi_cmacro = 0;
1574 /* #endif pops the if stack and resets pfile->state.skipping. */
1575 static void
1576 do_endif (pfile)
1577 cpp_reader *pfile;
1579 cpp_buffer *buffer = pfile->buffer;
1580 struct if_stack *ifs = buffer->if_stack;
1582 if (ifs == NULL)
1583 cpp_error (pfile, DL_ERROR, "#endif without #if");
1584 else
1586 /* Only check EOL if was not originally skipping. */
1587 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1588 check_eol (pfile);
1590 /* If potential control macro, we go back outside again. */
1591 if (ifs->next == 0 && ifs->mi_cmacro)
1593 pfile->mi_valid = true;
1594 pfile->mi_cmacro = ifs->mi_cmacro;
1597 buffer->if_stack = ifs->next;
1598 pfile->state.skipping = ifs->was_skipping;
1599 obstack_free (&pfile->buffer_ob, ifs);
1603 /* Push an if_stack entry for a preprocessor conditional, and set
1604 pfile->state.skipping to SKIP. If TYPE indicates the conditional
1605 is #if or #ifndef, CMACRO is a potentially controlling macro, and
1606 we need to check here that we are at the top of the file. */
1607 static void
1608 push_conditional (pfile, skip, type, cmacro)
1609 cpp_reader *pfile;
1610 int skip;
1611 int type;
1612 const cpp_hashnode *cmacro;
1614 struct if_stack *ifs;
1615 cpp_buffer *buffer = pfile->buffer;
1617 ifs = xobnew (&pfile->buffer_ob, struct if_stack);
1618 ifs->line = pfile->directive_line;
1619 ifs->next = buffer->if_stack;
1620 ifs->skip_elses = pfile->state.skipping || !skip;
1621 ifs->was_skipping = pfile->state.skipping;
1622 ifs->type = type;
1623 /* This condition is effectively a test for top-of-file. */
1624 if (pfile->mi_valid && pfile->mi_cmacro == 0)
1625 ifs->mi_cmacro = cmacro;
1626 else
1627 ifs->mi_cmacro = 0;
1629 pfile->state.skipping = skip;
1630 buffer->if_stack = ifs;
1633 /* Read the tokens of the answer into the macro pool, in a directive
1634 of type TYPE. Only commit the memory if we intend it as permanent
1635 storage, i.e. the #assert case. Returns 0 on success, and sets
1636 ANSWERP to point to the answer. */
1637 static int
1638 parse_answer (pfile, answerp, type)
1639 cpp_reader *pfile;
1640 struct answer **answerp;
1641 int type;
1643 const cpp_token *paren;
1644 struct answer *answer;
1645 unsigned int acount;
1647 /* In a conditional, it is legal to not have an open paren. We
1648 should save the following token in this case. */
1649 paren = cpp_get_token (pfile);
1651 /* If not a paren, see if we're OK. */
1652 if (paren->type != CPP_OPEN_PAREN)
1654 /* In a conditional no answer is a test for any answer. It
1655 could be followed by any token. */
1656 if (type == T_IF)
1658 _cpp_backup_tokens (pfile, 1);
1659 return 0;
1662 /* #unassert with no answer is valid - it removes all answers. */
1663 if (type == T_UNASSERT && paren->type == CPP_EOF)
1664 return 0;
1666 cpp_error (pfile, DL_ERROR, "missing '(' after predicate");
1667 return 1;
1670 for (acount = 0;; acount++)
1672 size_t room_needed;
1673 const cpp_token *token = cpp_get_token (pfile);
1674 cpp_token *dest;
1676 if (token->type == CPP_CLOSE_PAREN)
1677 break;
1679 if (token->type == CPP_EOF)
1681 cpp_error (pfile, DL_ERROR, "missing ')' to complete answer");
1682 return 1;
1685 /* struct answer includes the space for one token. */
1686 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
1688 if (BUFF_ROOM (pfile->a_buff) < room_needed)
1689 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
1691 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
1692 *dest = *token;
1694 /* Drop whitespace at start, for answer equivalence purposes. */
1695 if (acount == 0)
1696 dest->flags &= ~PREV_WHITE;
1699 if (acount == 0)
1701 cpp_error (pfile, DL_ERROR, "predicate's answer is empty");
1702 return 1;
1705 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
1706 answer->count = acount;
1707 answer->next = NULL;
1708 *answerp = answer;
1710 return 0;
1713 /* Parses an assertion directive of type TYPE, returning a pointer to
1714 the hash node of the predicate, or 0 on error. If an answer was
1715 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
1716 static cpp_hashnode *
1717 parse_assertion (pfile, answerp, type)
1718 cpp_reader *pfile;
1719 struct answer **answerp;
1720 int type;
1722 cpp_hashnode *result = 0;
1723 const cpp_token *predicate;
1725 /* We don't expand predicates or answers. */
1726 pfile->state.prevent_expansion++;
1728 *answerp = 0;
1729 predicate = cpp_get_token (pfile);
1730 if (predicate->type == CPP_EOF)
1731 cpp_error (pfile, DL_ERROR, "assertion without predicate");
1732 else if (predicate->type != CPP_NAME)
1733 cpp_error (pfile, DL_ERROR, "predicate must be an identifier");
1734 else if (parse_answer (pfile, answerp, type) == 0)
1736 unsigned int len = NODE_LEN (predicate->val.node);
1737 unsigned char *sym = alloca (len + 1);
1739 /* Prefix '#' to get it out of macro namespace. */
1740 sym[0] = '#';
1741 memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
1742 result = cpp_lookup (pfile, sym, len + 1);
1745 pfile->state.prevent_expansion--;
1746 return result;
1749 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
1750 or a pointer to NULL if the answer is not in the chain. */
1751 static struct answer **
1752 find_answer (node, candidate)
1753 cpp_hashnode *node;
1754 const struct answer *candidate;
1756 unsigned int i;
1757 struct answer **result;
1759 for (result = &node->value.answers; *result; result = &(*result)->next)
1761 struct answer *answer = *result;
1763 if (answer->count == candidate->count)
1765 for (i = 0; i < answer->count; i++)
1766 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
1767 break;
1769 if (i == answer->count)
1770 break;
1774 return result;
1777 /* Test an assertion within a preprocessor conditional. Returns
1778 nonzero on failure, zero on success. On success, the result of
1779 the test is written into VALUE, otherwise the value 0. */
1781 _cpp_test_assertion (pfile, value)
1782 cpp_reader *pfile;
1783 unsigned int *value;
1785 struct answer *answer;
1786 cpp_hashnode *node;
1788 node = parse_assertion (pfile, &answer, T_IF);
1790 /* For recovery, an erroneous assertion expression is handled as a
1791 failing assertion. */
1792 *value = 0;
1794 if (node)
1795 *value = (node->type == NT_ASSERTION &&
1796 (answer == 0 || *find_answer (node, answer) != 0));
1797 else if (pfile->cur_token[-1].type == CPP_EOF)
1798 _cpp_backup_tokens (pfile, 1);
1800 /* We don't commit the memory for the answer - it's temporary only. */
1801 return node == 0;
1804 /* Handle #assert. */
1805 static void
1806 do_assert (pfile)
1807 cpp_reader *pfile;
1809 struct answer *new_answer;
1810 cpp_hashnode *node;
1812 node = parse_assertion (pfile, &new_answer, T_ASSERT);
1813 if (node)
1815 /* Place the new answer in the answer list. First check there
1816 is not a duplicate. */
1817 new_answer->next = 0;
1818 if (node->type == NT_ASSERTION)
1820 if (*find_answer (node, new_answer))
1822 cpp_error (pfile, DL_WARNING, "\"%s\" re-asserted",
1823 NODE_NAME (node) + 1);
1824 return;
1826 new_answer->next = node->value.answers;
1829 node->type = NT_ASSERTION;
1830 node->value.answers = new_answer;
1831 BUFF_FRONT (pfile->a_buff) += (sizeof (struct answer)
1832 + (new_answer->count - 1)
1833 * sizeof (cpp_token));
1834 check_eol (pfile);
1838 /* Handle #unassert. */
1839 static void
1840 do_unassert (pfile)
1841 cpp_reader *pfile;
1843 cpp_hashnode *node;
1844 struct answer *answer;
1846 node = parse_assertion (pfile, &answer, T_UNASSERT);
1847 /* It isn't an error to #unassert something that isn't asserted. */
1848 if (node && node->type == NT_ASSERTION)
1850 if (answer)
1852 struct answer **p = find_answer (node, answer), *temp;
1854 /* Remove the answer from the list. */
1855 temp = *p;
1856 if (temp)
1857 *p = temp->next;
1859 /* Did we free the last answer? */
1860 if (node->value.answers == 0)
1861 node->type = NT_VOID;
1863 check_eol (pfile);
1865 else
1866 _cpp_free_definition (node);
1869 /* We don't commit the memory for the answer - it's temporary only. */
1872 /* These are for -D, -U, -A. */
1874 /* Process the string STR as if it appeared as the body of a #define.
1875 If STR is just an identifier, define it with value 1.
1876 If STR has anything after the identifier, then it should
1877 be identifier=definition. */
1878 void
1879 cpp_define (pfile, str)
1880 cpp_reader *pfile;
1881 const char *str;
1883 char *buf, *p;
1884 size_t count;
1886 /* Copy the entire option so we can modify it.
1887 Change the first "=" in the string to a space. If there is none,
1888 tack " 1" on the end. */
1890 count = strlen (str);
1891 buf = (char *) alloca (count + 3);
1892 memcpy (buf, str, count);
1894 p = strchr (str, '=');
1895 if (p)
1896 buf[p - str] = ' ';
1897 else
1899 buf[count++] = ' ';
1900 buf[count++] = '1';
1902 buf[count] = '\0';
1904 run_directive (pfile, T_DEFINE, buf, count);
1907 /* Slight variant of the above for use by initialize_builtins. */
1908 void
1909 _cpp_define_builtin (pfile, str)
1910 cpp_reader *pfile;
1911 const char *str;
1913 run_directive (pfile, T_DEFINE, str, strlen (str));
1916 /* Process MACRO as if it appeared as the body of an #undef. */
1917 void
1918 cpp_undef (pfile, macro)
1919 cpp_reader *pfile;
1920 const char *macro;
1922 run_directive (pfile, T_UNDEF, macro, strlen (macro));
1925 /* Process the string STR as if it appeared as the body of a #assert. */
1926 void
1927 cpp_assert (pfile, str)
1928 cpp_reader *pfile;
1929 const char *str;
1931 handle_assertion (pfile, str, T_ASSERT);
1934 /* Process STR as if it appeared as the body of an #unassert. */
1935 void
1936 cpp_unassert (pfile, str)
1937 cpp_reader *pfile;
1938 const char *str;
1940 handle_assertion (pfile, str, T_UNASSERT);
1943 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
1944 static void
1945 handle_assertion (pfile, str, type)
1946 cpp_reader *pfile;
1947 const char *str;
1948 int type;
1950 size_t count = strlen (str);
1951 const char *p = strchr (str, '=');
1953 if (p)
1955 /* Copy the entire option so we can modify it. Change the first
1956 "=" in the string to a '(', and tack a ')' on the end. */
1957 char *buf = (char *) alloca (count + 2);
1959 memcpy (buf, str, count);
1960 buf[p - str] = '(';
1961 buf[count++] = ')';
1962 buf[count] = '\0';
1963 str = buf;
1966 run_directive (pfile, type, str, count);
1969 /* The number of errors for a given reader. */
1970 unsigned int
1971 cpp_errors (pfile)
1972 cpp_reader *pfile;
1974 return pfile->errors;
1977 /* The options structure. */
1978 cpp_options *
1979 cpp_get_options (pfile)
1980 cpp_reader *pfile;
1982 return &pfile->opts;
1985 /* The callbacks structure. */
1986 cpp_callbacks *
1987 cpp_get_callbacks (pfile)
1988 cpp_reader *pfile;
1990 return &pfile->cb;
1993 /* The line map set. */
1994 const struct line_maps *
1995 cpp_get_line_maps (pfile)
1996 cpp_reader *pfile;
1998 return &pfile->line_maps;
2001 /* Copy the given callbacks structure to our own. */
2002 void
2003 cpp_set_callbacks (pfile, cb)
2004 cpp_reader *pfile;
2005 cpp_callbacks *cb;
2007 pfile->cb = *cb;
2010 /* Push a new buffer on the buffer stack. Returns the new buffer; it
2011 doesn't fail. It does not generate a file change call back; that
2012 is the responsibility of the caller. */
2013 cpp_buffer *
2014 cpp_push_buffer (pfile, buffer, len, from_stage3, return_at_eof)
2015 cpp_reader *pfile;
2016 const uchar *buffer;
2017 size_t len;
2018 int from_stage3;
2019 int return_at_eof;
2021 cpp_buffer *new = xobnew (&pfile->buffer_ob, cpp_buffer);
2023 /* Clears, amongst other things, if_stack and mi_cmacro. */
2024 memset (new, 0, sizeof (cpp_buffer));
2026 new->line_base = new->buf = new->cur = buffer;
2027 new->rlimit = buffer + len;
2028 new->from_stage3 = from_stage3 || CPP_OPTION (pfile, traditional);
2029 new->prev = pfile->buffer;
2030 new->return_at_eof = return_at_eof;
2031 new->saved_flags = BOL;
2033 pfile->buffer = new;
2035 return new;
2038 /* Pops a single buffer, with a file change call-back if appropriate.
2039 Then pushes the next -include file, if any remain. */
2040 void
2041 _cpp_pop_buffer (pfile)
2042 cpp_reader *pfile;
2044 cpp_buffer *buffer = pfile->buffer;
2045 struct include_file *inc = buffer->inc;
2046 struct if_stack *ifs;
2048 /* Walk back up the conditional stack till we reach its level at
2049 entry to this file, issuing error messages. */
2050 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
2051 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
2052 "unterminated #%s", dtable[ifs->type].name);
2054 /* In case of a missing #endif. */
2055 pfile->state.skipping = 0;
2057 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
2058 pfile->buffer = buffer->prev;
2060 /* Free the buffer object now; we may want to push a new buffer
2061 in _cpp_push_next_include_file. */
2062 obstack_free (&pfile->buffer_ob, buffer);
2064 if (inc)
2066 _cpp_pop_file_buffer (pfile, inc);
2068 /* Don't generate a callback for popping the main file. */
2069 if (pfile->buffer)
2071 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
2073 /* If this is the main file, there may be some -include
2074 files left to push. */
2075 if (!pfile->buffer->prev)
2076 _cpp_maybe_push_include_file (pfile);
2081 /* Enter all recognized directives in the hash table. */
2082 void
2083 _cpp_init_directives (pfile)
2084 cpp_reader *pfile;
2086 unsigned int i;
2087 cpp_hashnode *node;
2089 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
2091 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
2092 node->is_directive = 1;
2093 node->directive_index = i;