Missed one in last change.
[official-gcc.git] / gcc / cpplib.c
blob2fac44e62fdaa92d830bb194baec6694b2ffd5ce
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) (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) (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 (cpp_reader *);
99 static void check_eol (cpp_reader *);
100 static void start_directive (cpp_reader *);
101 static void prepare_directive_trad (cpp_reader *);
102 static void end_directive (cpp_reader *, int);
103 static void directive_diagnostics (cpp_reader *, const directive *, int);
104 static void run_directive (cpp_reader *, int, const char *, size_t);
105 static char *glue_header_name (cpp_reader *);
106 static const char *parse_include (cpp_reader *, int *);
107 static void push_conditional (cpp_reader *, int, int, const cpp_hashnode *);
108 static unsigned int read_flag (cpp_reader *, unsigned int);
109 static int strtoul_for_line (const uchar *, unsigned int, unsigned long *);
110 static void do_diagnostic (cpp_reader *, int, int);
111 static cpp_hashnode *lex_macro_node (cpp_reader *);
112 static void do_include_common (cpp_reader *, enum include_type);
113 static struct pragma_entry *lookup_pragma_entry (struct pragma_entry *,
114 const cpp_hashnode *);
115 static struct pragma_entry *insert_pragma_entry (cpp_reader *,
116 struct pragma_entry **,
117 const cpp_hashnode *,
118 pragma_cb);
119 static int count_registered_pragmas (struct pragma_entry *);
120 static char ** save_registered_pragmas (struct pragma_entry *, char **);
121 static char ** restore_registered_pragmas (cpp_reader *, struct pragma_entry *,
122 char **);
123 static void do_pragma_once (cpp_reader *);
124 static void do_pragma_poison (cpp_reader *);
125 static void do_pragma_system_header (cpp_reader *);
126 static void do_pragma_dependency (cpp_reader *);
127 static void do_linemarker (cpp_reader *);
128 static const cpp_token *get_token_no_padding (cpp_reader *);
129 static const cpp_token *get__Pragma_string (cpp_reader *);
130 static void destringize_and_run (cpp_reader *, const cpp_string *);
131 static int parse_answer (cpp_reader *, struct answer **, int);
132 static cpp_hashnode *parse_assertion (cpp_reader *, struct answer **, int);
133 static struct answer ** find_answer (cpp_hashnode *, const struct answer *);
134 static void handle_assertion (cpp_reader *, const char *, int);
136 /* This is the table of directive handlers. It is ordered by
137 frequency of occurrence; the numbers at the end are directive
138 counts from all the source code I have lying around (egcs and libc
139 CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
140 pcmcia-cs-3.0.9). This is no longer important as directive lookup
141 is now O(1). All extensions other than #warning and #include_next
142 are deprecated. The name is where the extension appears to have
143 come from. */
145 #define DIRECTIVE_TABLE \
146 D(define, T_DEFINE = 0, KANDR, IN_I) /* 270554 */ \
147 D(include, T_INCLUDE, KANDR, INCL | EXPAND) /* 52262 */ \
148 D(endif, T_ENDIF, KANDR, COND) /* 45855 */ \
149 D(ifdef, T_IFDEF, KANDR, COND | IF_COND) /* 22000 */ \
150 D(if, T_IF, KANDR, COND | IF_COND | EXPAND) /* 18162 */ \
151 D(else, T_ELSE, KANDR, COND) /* 9863 */ \
152 D(ifndef, T_IFNDEF, KANDR, COND | IF_COND) /* 9675 */ \
153 D(undef, T_UNDEF, KANDR, IN_I) /* 4837 */ \
154 D(line, T_LINE, KANDR, EXPAND) /* 2465 */ \
155 D(elif, T_ELIF, STDC89, COND | EXPAND) /* 610 */ \
156 D(error, T_ERROR, STDC89, 0) /* 475 */ \
157 D(pragma, T_PRAGMA, STDC89, IN_I) /* 195 */ \
158 D(warning, T_WARNING, EXTENSION, 0) /* 22 */ \
159 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND) /* 19 */ \
160 D(ident, T_IDENT, EXTENSION, IN_I) /* 11 */ \
161 D(import, T_IMPORT, EXTENSION, INCL | EXPAND) /* 0 ObjC */ \
162 D(assert, T_ASSERT, EXTENSION, 0) /* 0 SVR4 */ \
163 D(unassert, T_UNASSERT, EXTENSION, 0) /* 0 SVR4 */ \
164 D(sccs, T_SCCS, EXTENSION, 0) /* 0 SVR4? */
166 /* Use the table to generate a series of prototypes, an enum for the
167 directive names, and an array of directive handlers. */
169 #define D(name, t, o, f) static void do_##name (cpp_reader *);
170 DIRECTIVE_TABLE
171 #undef D
173 #define D(n, tag, o, f) tag,
174 enum
176 DIRECTIVE_TABLE
177 N_DIRECTIVES
179 #undef D
181 #define D(name, t, origin, flags) \
182 { do_##name, (const uchar *) #name, \
183 sizeof #name - 1, origin, flags },
184 static const directive dtable[] =
186 DIRECTIVE_TABLE
188 #undef D
189 #undef DIRECTIVE_TABLE
191 /* Wrapper struct directive for linemarkers.
192 The origin is more or less true - the original K+R cpp
193 did use this notation in its preprocessed output. */
194 static const directive linemarker_dir =
196 do_linemarker, U"#", 1, KANDR, IN_I
199 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
201 /* Skip any remaining tokens in a directive. */
202 static void
203 skip_rest_of_line (cpp_reader *pfile)
205 /* Discard all stacked contexts. */
206 while (pfile->context->prev)
207 _cpp_pop_context (pfile);
209 /* Sweep up all tokens remaining on the line. */
210 if (! SEEN_EOL ())
211 while (_cpp_lex_token (pfile)->type != CPP_EOF)
215 /* Ensure there are no stray tokens at the end of a directive. */
216 static void
217 check_eol (cpp_reader *pfile)
219 if (! SEEN_EOL () && _cpp_lex_token (pfile)->type != CPP_EOF)
220 cpp_error (pfile, DL_PEDWARN, "extra tokens at end of #%s directive",
221 pfile->directive->name);
224 /* Called when entering a directive, _Pragma or command-line directive. */
225 static void
226 start_directive (cpp_reader *pfile)
228 /* Setup in-directive state. */
229 pfile->state.in_directive = 1;
230 pfile->state.save_comments = 0;
232 /* Some handlers need the position of the # for diagnostics. */
233 pfile->directive_line = pfile->line;
236 /* Called when leaving a directive, _Pragma or command-line directive. */
237 static void
238 end_directive (cpp_reader *pfile, int skip_line)
240 if (CPP_OPTION (pfile, traditional))
242 /* Revert change of prepare_directive_trad. */
243 pfile->state.prevent_expansion--;
245 if (pfile->directive != &dtable[T_DEFINE])
246 _cpp_remove_overlay (pfile);
248 /* We don't skip for an assembler #. */
249 else if (skip_line)
251 skip_rest_of_line (pfile);
252 if (!pfile->keep_tokens)
254 pfile->cur_run = &pfile->base_run;
255 pfile->cur_token = pfile->base_run.base;
259 /* Restore state. */
260 pfile->state.save_comments = ! CPP_OPTION (pfile, discard_comments);
261 pfile->state.in_directive = 0;
262 pfile->state.in_expression = 0;
263 pfile->state.angled_headers = 0;
264 pfile->directive = 0;
267 /* Prepare to handle the directive in pfile->directive. */
268 static void
269 prepare_directive_trad (cpp_reader *pfile)
271 if (pfile->directive != &dtable[T_DEFINE])
273 bool no_expand = (pfile->directive
274 && ! (pfile->directive->flags & EXPAND));
275 bool was_skipping = pfile->state.skipping;
277 pfile->state.skipping = false;
278 pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
279 || pfile->directive == &dtable[T_ELIF]);
280 if (no_expand)
281 pfile->state.prevent_expansion++;
282 scan_out_logical_line (pfile, NULL);
283 if (no_expand)
284 pfile->state.prevent_expansion--;
285 pfile->state.skipping = was_skipping;
286 _cpp_overlay_buffer (pfile, pfile->out.base,
287 pfile->out.cur - pfile->out.base);
290 /* Stop ISO C from expanding anything. */
291 pfile->state.prevent_expansion++;
294 /* Output diagnostics for a directive DIR. INDENTED is nonzero if
295 the '#' was indented. */
296 static void
297 directive_diagnostics (cpp_reader *pfile, const directive *dir, int indented)
299 /* Issue -pedantic warnings for extensions. */
300 if (CPP_PEDANTIC (pfile)
301 && ! pfile->state.skipping
302 && dir->origin == EXTENSION)
303 cpp_error (pfile, DL_PEDWARN, "#%s is a GCC extension", dir->name);
305 /* Traditionally, a directive is ignored unless its # is in
306 column 1. Therefore in code intended to work with K+R
307 compilers, directives added by C89 must have their #
308 indented, and directives present in traditional C must not.
309 This is true even of directives in skipped conditional
310 blocks. #elif cannot be used at all. */
311 if (CPP_WTRADITIONAL (pfile))
313 if (dir == &dtable[T_ELIF])
314 cpp_error (pfile, DL_WARNING,
315 "suggest not using #elif in traditional C");
316 else if (indented && dir->origin == KANDR)
317 cpp_error (pfile, DL_WARNING,
318 "traditional C ignores #%s with the # indented",
319 dir->name);
320 else if (!indented && dir->origin != KANDR)
321 cpp_error (pfile, DL_WARNING,
322 "suggest hiding #%s from traditional C with an indented #",
323 dir->name);
327 /* Check if we have a known directive. INDENTED is nonzero if the
328 '#' of the directive was indented. This function is in this file
329 to save unnecessarily exporting dtable etc. to cpplex.c. Returns
330 nonzero if the line of tokens has been handled, zero if we should
331 continue processing the line. */
333 _cpp_handle_directive (cpp_reader *pfile, int indented)
335 const directive *dir = 0;
336 const cpp_token *dname;
337 bool was_parsing_args = pfile->state.parsing_args;
338 int skip = 1;
340 if (was_parsing_args)
342 if (CPP_OPTION (pfile, pedantic))
343 cpp_error (pfile, DL_PEDWARN,
344 "embedding a directive within macro arguments is not portable");
345 pfile->state.parsing_args = 0;
346 pfile->state.prevent_expansion = 0;
348 start_directive (pfile);
349 dname = _cpp_lex_token (pfile);
351 if (dname->type == CPP_NAME)
353 if (dname->val.node->is_directive)
354 dir = &dtable[dname->val.node->directive_index];
356 /* We do not recognize the # followed by a number extension in
357 assembler code. */
358 else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
360 dir = &linemarker_dir;
361 if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
362 && ! pfile->state.skipping)
363 cpp_error (pfile, DL_PEDWARN,
364 "style of line directive is a GCC extension");
367 if (dir)
369 /* If we have a directive that is not an opening conditional,
370 invalidate any control macro. */
371 if (! (dir->flags & IF_COND))
372 pfile->mi_valid = false;
374 /* Kluge alert. In order to be sure that code like this
376 #define HASH #
377 HASH define foo bar
379 does not cause '#define foo bar' to get executed when
380 compiled with -save-temps, we recognize directives in
381 -fpreprocessed mode only if the # is in column 1. cppmacro.c
382 puts a space in front of any '#' at the start of a macro. */
383 if (CPP_OPTION (pfile, preprocessed)
384 && (indented || !(dir->flags & IN_I)))
386 skip = 0;
387 dir = 0;
389 else
391 /* In failed conditional groups, all non-conditional
392 directives are ignored. Before doing that, whether
393 skipping or not, we should lex angle-bracketed headers
394 correctly, and maybe output some diagnostics. */
395 pfile->state.angled_headers = dir->flags & INCL;
396 pfile->state.directive_wants_padding = dir->flags & INCL;
397 if (! CPP_OPTION (pfile, preprocessed))
398 directive_diagnostics (pfile, dir, indented);
399 if (pfile->state.skipping && !(dir->flags & COND))
400 dir = 0;
403 else if (dname->type == CPP_EOF)
404 ; /* CPP_EOF is the "null directive". */
405 else
407 /* An unknown directive. Don't complain about it in assembly
408 source: we don't know where the comments are, and # may
409 introduce assembler pseudo-ops. Don't complain about invalid
410 directives in skipped conditional groups (6.10 p4). */
411 if (CPP_OPTION (pfile, lang) == CLK_ASM)
412 skip = 0;
413 else if (!pfile->state.skipping)
414 cpp_error (pfile, DL_ERROR, "invalid preprocessing directive #%s",
415 cpp_token_as_text (pfile, dname));
418 pfile->directive = dir;
419 if (CPP_OPTION (pfile, traditional))
420 prepare_directive_trad (pfile);
422 if (dir)
423 pfile->directive->handler (pfile);
424 else if (skip == 0)
425 _cpp_backup_tokens (pfile, 1);
427 end_directive (pfile, skip);
428 if (was_parsing_args)
430 /* Restore state when within macro args. */
431 pfile->state.parsing_args = 2;
432 pfile->state.prevent_expansion = 1;
434 return skip;
437 /* Directive handler wrapper used by the command line option
438 processor. BUF is \n terminated. */
439 static void
440 run_directive (cpp_reader *pfile, int dir_no, const char *buf, size_t count)
442 cpp_push_buffer (pfile, (const uchar *) buf, count,
443 /* from_stage3 */ true, 1);
444 /* Disgusting hack. */
445 if (dir_no == T_PRAGMA)
446 pfile->buffer->inc = pfile->buffer->prev->inc;
447 start_directive (pfile);
449 /* This is a short-term fix to prevent a leading '#' being
450 interpreted as a directive. */
451 _cpp_clean_line (pfile);
453 pfile->directive = &dtable[dir_no];
454 if (CPP_OPTION (pfile, traditional))
455 prepare_directive_trad (pfile);
456 pfile->directive->handler (pfile);
457 end_directive (pfile, 1);
458 if (dir_no == T_PRAGMA)
459 pfile->buffer->inc = NULL;
460 _cpp_pop_buffer (pfile);
463 /* Checks for validity the macro name in #define, #undef, #ifdef and
464 #ifndef directives. */
465 static cpp_hashnode *
466 lex_macro_node (cpp_reader *pfile)
468 const cpp_token *token = _cpp_lex_token (pfile);
470 /* The token immediately after #define must be an identifier. That
471 identifier may not be "defined", per C99 6.10.8p4.
472 In C++, it may not be any of the "named operators" either,
473 per C++98 [lex.digraph], [lex.key].
474 Finally, the identifier may not have been poisoned. (In that case
475 the lexer has issued the error message for us.) */
477 if (token->type == CPP_NAME)
479 cpp_hashnode *node = token->val.node;
481 if (node == pfile->spec_nodes.n_defined)
482 cpp_error (pfile, DL_ERROR,
483 "\"defined\" cannot be used as a macro name");
484 else if (! (node->flags & NODE_POISONED))
485 return node;
487 else if (token->flags & NAMED_OP)
488 cpp_error (pfile, DL_ERROR,
489 "\"%s\" cannot be used as a macro name as it is an operator in C++",
490 NODE_NAME (token->val.node));
491 else if (token->type == CPP_EOF)
492 cpp_error (pfile, DL_ERROR, "no macro name given in #%s directive",
493 pfile->directive->name);
494 else
495 cpp_error (pfile, DL_ERROR, "macro names must be identifiers");
497 return NULL;
500 /* Process a #define directive. Most work is done in cppmacro.c. */
501 static void
502 do_define (cpp_reader *pfile)
504 cpp_hashnode *node = lex_macro_node (pfile);
506 if (node)
508 /* If we have been requested to expand comments into macros,
509 then re-enable saving of comments. */
510 pfile->state.save_comments =
511 ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
513 if (_cpp_create_definition (pfile, node))
514 if (pfile->cb.define)
515 pfile->cb.define (pfile, pfile->directive_line, node);
519 /* Handle #undef. Mark the identifier NT_VOID in the hash table. */
520 static void
521 do_undef (cpp_reader *pfile)
523 cpp_hashnode *node = lex_macro_node (pfile);
525 /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified identifier
526 is not currently defined as a macro name. */
527 if (node && node->type == NT_MACRO)
529 if (pfile->cb.undef)
530 pfile->cb.undef (pfile, pfile->directive_line, node);
532 if (node->flags & NODE_WARN)
533 cpp_error (pfile, DL_WARNING, "undefining \"%s\"", NODE_NAME (node));
535 if (CPP_OPTION (pfile, warn_unused_macros))
536 _cpp_warn_if_unused_macro (pfile, node, NULL);
538 _cpp_free_definition (node);
540 check_eol (pfile);
543 /* Helper routine used by parse_include. Reinterpret the current line
544 as an h-char-sequence (< ... >); we are looking at the first token
545 after the <. Returns a malloced filename. */
546 static char *
547 glue_header_name (cpp_reader *pfile)
549 const cpp_token *token;
550 char *buffer;
551 size_t len, total_len = 0, capacity = 1024;
553 /* To avoid lexed tokens overwriting our glued name, we can only
554 allocate from the string pool once we've lexed everything. */
555 buffer = xmalloc (capacity);
556 for (;;)
558 token = get_token_no_padding (pfile);
560 if (token->type == CPP_GREATER)
561 break;
562 if (token->type == CPP_EOF)
564 cpp_error (pfile, DL_ERROR, "missing terminating > character");
565 break;
568 len = cpp_token_len (token) + 2; /* Leading space, terminating \0. */
569 if (total_len + len > capacity)
571 capacity = (capacity + len) * 2;
572 buffer = xrealloc (buffer, capacity);
575 if (token->flags & PREV_WHITE)
576 buffer[total_len++] = ' ';
578 total_len = (cpp_spell_token (pfile, token, (uchar *) &buffer[total_len])
579 - (uchar *) buffer);
582 buffer[total_len] = '\0';
583 return buffer;
586 /* Returns the file name of #include, #include_next, #import and
587 #pragma dependency. The string is malloced and the caller should
588 free it. Returns NULL on error. */
589 static const char *
590 parse_include (cpp_reader *pfile, int *pangle_brackets)
592 char *fname;
593 const cpp_token *header;
595 /* Allow macro expansion. */
596 header = get_token_no_padding (pfile);
597 if (header->type == CPP_STRING || header->type == CPP_HEADER_NAME)
599 fname = xmalloc (header->val.str.len - 1);
600 memcpy (fname, header->val.str.text + 1, header->val.str.len - 2);
601 fname[header->val.str.len - 2] = '\0';
602 *pangle_brackets = header->type == CPP_HEADER_NAME;
604 else if (header->type == CPP_LESS)
606 fname = glue_header_name (pfile);
607 *pangle_brackets = 1;
609 else
611 const unsigned char *dir;
613 if (pfile->directive == &dtable[T_PRAGMA])
614 dir = U"pragma dependency";
615 else
616 dir = pfile->directive->name;
617 cpp_error (pfile, DL_ERROR, "#%s expects \"FILENAME\" or <FILENAME>",
618 dir);
620 return NULL;
623 check_eol (pfile);
624 return fname;
627 /* Handle #include, #include_next and #import. */
628 static void
629 do_include_common (cpp_reader *pfile, enum include_type type)
631 const char *fname;
632 int angle_brackets;
634 fname = parse_include (pfile, &angle_brackets);
635 if (!fname)
636 return;
638 /* Prevent #include recursion. */
639 if (pfile->line_maps.depth >= CPP_STACK_MAX)
640 cpp_error (pfile, DL_ERROR, "#include nested too deeply");
641 else
643 /* Get out of macro context, if we are. */
644 skip_rest_of_line (pfile);
646 if (pfile->cb.include)
647 pfile->cb.include (pfile, pfile->directive_line,
648 pfile->directive->name, fname, angle_brackets);
650 _cpp_execute_include (pfile, fname, angle_brackets, type);
653 free ((void *) fname);
656 static void
657 do_include (cpp_reader *pfile)
659 do_include_common (pfile, IT_INCLUDE);
662 static void
663 do_import (cpp_reader *pfile)
665 if (CPP_OPTION (pfile, warn_import))
667 CPP_OPTION (pfile, warn_import) = 0;
668 cpp_error (pfile, DL_WARNING,
669 "#import is obsolete, use an #ifndef wrapper in the header file");
672 do_include_common (pfile, IT_IMPORT);
675 static void
676 do_include_next (cpp_reader *pfile)
678 enum include_type type = IT_INCLUDE_NEXT;
680 /* If this is the primary source file, warn and use the normal
681 search logic. */
682 if (! pfile->buffer->prev)
684 cpp_error (pfile, DL_WARNING,
685 "#include_next in primary source file");
686 type = IT_INCLUDE;
688 do_include_common (pfile, type);
691 /* Subroutine of do_linemarker. Read possible flags after file name.
692 LAST is the last flag seen; 0 if this is the first flag. Return the
693 flag if it is valid, 0 at the end of the directive. Otherwise
694 complain. */
695 static unsigned int
696 read_flag (cpp_reader *pfile, unsigned int last)
698 const cpp_token *token = _cpp_lex_token (pfile);
700 if (token->type == CPP_NUMBER && token->val.str.len == 1)
702 unsigned int flag = token->val.str.text[0] - '0';
704 if (flag > last && flag <= 4
705 && (flag != 4 || last == 3)
706 && (flag != 2 || last == 0))
707 return flag;
710 if (token->type != CPP_EOF)
711 cpp_error (pfile, DL_ERROR, "invalid flag \"%s\" in line directive",
712 cpp_token_as_text (pfile, token));
713 return 0;
716 /* Subroutine of do_line and do_linemarker. Convert a number in STR,
717 of length LEN, to binary; store it in NUMP, and return 0 if the
718 number was well-formed, 1 if not. Temporary, hopefully. */
719 static int
720 strtoul_for_line (const uchar *str, unsigned int len, long unsigned int *nump)
722 unsigned long reg = 0;
723 uchar c;
724 while (len--)
726 c = *str++;
727 if (!ISDIGIT (c))
728 return 1;
729 reg *= 10;
730 reg += c - '0';
732 *nump = reg;
733 return 0;
736 /* Subroutine of do_line and do_linemarker. Convert escape sequences
737 in a string, but do not perform character set conversion. */
738 static bool
739 interpret_string_notranslate (cpp_reader *pfile, const cpp_string *in,
740 cpp_string *out)
742 iconv_t save_narrow_cset_desc = pfile->narrow_cset_desc;
743 bool retval;
745 pfile->narrow_cset_desc = (iconv_t) -1;
746 retval = cpp_interpret_string (pfile, in, 1, out, false);
747 pfile->narrow_cset_desc = save_narrow_cset_desc;
748 return retval;
751 /* Interpret #line command.
752 Note that the filename string (if any) is a true string constant
753 (escapes are interpreted), unlike in #line. */
754 static void
755 do_line (cpp_reader *pfile)
757 const cpp_token *token;
758 const char *new_file = pfile->map->to_file;
759 unsigned long new_lineno;
761 /* C99 raised the minimum limit on #line numbers. */
762 unsigned int cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
764 /* #line commands expand macros. */
765 token = cpp_get_token (pfile);
766 if (token->type != CPP_NUMBER
767 || strtoul_for_line (token->val.str.text, token->val.str.len,
768 &new_lineno))
770 cpp_error (pfile, DL_ERROR,
771 "\"%s\" after #line is not a positive integer",
772 cpp_token_as_text (pfile, token));
773 return;
776 if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap))
777 cpp_error (pfile, DL_PEDWARN, "line number out of range");
779 token = cpp_get_token (pfile);
780 if (token->type == CPP_STRING)
782 cpp_string s = { 0, 0 };
783 if (interpret_string_notranslate (pfile, &token->val.str, &s))
784 new_file = (const char *)s.text;
785 check_eol (pfile);
787 else if (token->type != CPP_EOF)
789 cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
790 cpp_token_as_text (pfile, token));
791 return;
794 skip_rest_of_line (pfile);
795 _cpp_do_file_change (pfile, LC_RENAME, new_file, new_lineno,
796 pfile->map->sysp);
799 /* Interpret the # 44 "file" [flags] notation, which has slightly
800 different syntax and semantics from #line: Flags are allowed,
801 and we never complain about the line number being too big. */
802 static void
803 do_linemarker (cpp_reader *pfile)
805 const cpp_token *token;
806 const char *new_file = pfile->map->to_file;
807 unsigned long new_lineno;
808 unsigned int new_sysp = pfile->map->sysp;
809 enum lc_reason reason = LC_RENAME;
810 int flag;
812 /* Back up so we can get the number again. Putting this in
813 _cpp_handle_directive risks two calls to _cpp_backup_tokens in
814 some circumstances, which can segfault. */
815 _cpp_backup_tokens (pfile, 1);
817 /* #line commands expand macros. */
818 token = cpp_get_token (pfile);
819 if (token->type != CPP_NUMBER
820 || strtoul_for_line (token->val.str.text, token->val.str.len,
821 &new_lineno))
823 cpp_error (pfile, DL_ERROR, "\"%s\" after # is not a positive integer",
824 cpp_token_as_text (pfile, token));
825 return;
828 token = cpp_get_token (pfile);
829 if (token->type == CPP_STRING)
831 cpp_string s = { 0, 0 };
832 if (interpret_string_notranslate (pfile, &token->val.str, &s))
833 new_file = (const char *)s.text;
835 new_sysp = 0;
836 flag = read_flag (pfile, 0);
837 if (flag == 1)
839 reason = LC_ENTER;
840 /* Fake an include for cpp_included (). */
841 _cpp_fake_include (pfile, new_file);
842 flag = read_flag (pfile, flag);
844 else if (flag == 2)
846 reason = LC_LEAVE;
847 flag = read_flag (pfile, flag);
849 if (flag == 3)
851 new_sysp = 1;
852 flag = read_flag (pfile, flag);
853 if (flag == 4)
854 new_sysp = 2;
857 check_eol (pfile);
859 else if (token->type != CPP_EOF)
861 cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
862 cpp_token_as_text (pfile, token));
863 return;
866 skip_rest_of_line (pfile);
867 _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
870 /* Arrange the file_change callback. pfile->line has changed to
871 FILE_LINE of TO_FILE, for reason REASON. SYSP is 1 for a system
872 header, 2 for a system header that needs to be extern "C" protected,
873 and zero otherwise. */
874 void
875 _cpp_do_file_change (cpp_reader *pfile, enum lc_reason reason,
876 const char *to_file, unsigned int file_line,
877 unsigned int sysp)
879 pfile->map = add_line_map (&pfile->line_maps, reason, sysp,
880 pfile->line, to_file, file_line);
882 if (pfile->cb.file_change)
883 pfile->cb.file_change (pfile, pfile->map);
886 /* Report a warning or error detected by the program we are
887 processing. Use the directive's tokens in the error message. */
888 static void
889 do_diagnostic (cpp_reader *pfile, int code, int print_dir)
891 if (_cpp_begin_message (pfile, code,
892 pfile->cur_token[-1].line,
893 pfile->cur_token[-1].col))
895 if (print_dir)
896 fprintf (stderr, "#%s ", pfile->directive->name);
897 pfile->state.prevent_expansion++;
898 cpp_output_line (pfile, stderr);
899 pfile->state.prevent_expansion--;
903 static void
904 do_error (cpp_reader *pfile)
906 do_diagnostic (pfile, DL_ERROR, 1);
909 static void
910 do_warning (cpp_reader *pfile)
912 /* We want #warning diagnostics to be emitted in system headers too. */
913 do_diagnostic (pfile, DL_WARNING_SYSHDR, 1);
916 /* Report program identification. */
917 static void
918 do_ident (cpp_reader *pfile)
920 const cpp_token *str = cpp_get_token (pfile);
922 if (str->type != CPP_STRING)
923 cpp_error (pfile, DL_ERROR, "invalid #ident directive");
924 else if (pfile->cb.ident)
925 pfile->cb.ident (pfile, pfile->directive_line, &str->val.str);
927 check_eol (pfile);
930 /* Lookup a PRAGMA name in a singly-linked CHAIN. Returns the
931 matching entry, or NULL if none is found. The returned entry could
932 be the start of a namespace chain, or a pragma. */
933 static struct pragma_entry *
934 lookup_pragma_entry (struct pragma_entry *chain, const cpp_hashnode *pragma)
936 while (chain && chain->pragma != pragma)
937 chain = chain->next;
939 return chain;
942 /* Create and insert a pragma entry for NAME at the beginning of a
943 singly-linked CHAIN. If handler is NULL, it is a namespace,
944 otherwise it is a pragma and its handler. */
945 static struct pragma_entry *
946 insert_pragma_entry (cpp_reader *pfile, struct pragma_entry **chain,
947 const cpp_hashnode *pragma, pragma_cb handler)
949 struct pragma_entry *new;
951 new = (struct pragma_entry *)
952 _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
953 new->pragma = pragma;
954 if (handler)
956 new->is_nspace = 0;
957 new->u.handler = handler;
959 else
961 new->is_nspace = 1;
962 new->u.space = NULL;
965 new->next = *chain;
966 *chain = new;
967 return new;
970 /* Register a pragma NAME in namespace SPACE. If SPACE is null, it
971 goes in the global namespace. HANDLER is the handler it will call,
972 which must be non-NULL. */
973 void
974 cpp_register_pragma (cpp_reader *pfile, const char *space, const char *name,
975 pragma_cb handler)
977 struct pragma_entry **chain = &pfile->pragmas;
978 struct pragma_entry *entry;
979 const cpp_hashnode *node;
981 if (!handler)
982 abort ();
984 if (space)
986 node = cpp_lookup (pfile, U space, strlen (space));
987 entry = lookup_pragma_entry (*chain, node);
988 if (!entry)
989 entry = insert_pragma_entry (pfile, chain, node, NULL);
990 else if (!entry->is_nspace)
991 goto clash;
992 chain = &entry->u.space;
995 /* Check for duplicates. */
996 node = cpp_lookup (pfile, U name, strlen (name));
997 entry = lookup_pragma_entry (*chain, node);
998 if (entry)
1000 if (entry->is_nspace)
1001 clash:
1002 cpp_error (pfile, DL_ICE,
1003 "registering \"%s\" as both a pragma and a pragma namespace",
1004 NODE_NAME (node));
1005 else if (space)
1006 cpp_error (pfile, DL_ICE, "#pragma %s %s is already registered",
1007 space, name);
1008 else
1009 cpp_error (pfile, DL_ICE, "#pragma %s is already registered", name);
1011 else
1012 insert_pragma_entry (pfile, chain, node, handler);
1015 /* Register the pragmas the preprocessor itself handles. */
1016 void
1017 _cpp_init_internal_pragmas (cpp_reader *pfile)
1019 /* Pragmas in the global namespace. */
1020 cpp_register_pragma (pfile, 0, "once", do_pragma_once);
1022 /* New GCC-specific pragmas should be put in the GCC namespace. */
1023 cpp_register_pragma (pfile, "GCC", "poison", do_pragma_poison);
1024 cpp_register_pragma (pfile, "GCC", "system_header", do_pragma_system_header);
1025 cpp_register_pragma (pfile, "GCC", "dependency", do_pragma_dependency);
1028 /* Return the number of registered pragmas in PE. */
1030 static int
1031 count_registered_pragmas (struct pragma_entry *pe)
1033 int ct = 0;
1034 for (; pe != NULL; pe = pe->next)
1036 if (pe->is_nspace)
1037 ct += count_registered_pragmas (pe->u.space);
1038 ct++;
1040 return ct;
1043 /* Save into SD the names of the registered pragmas referenced by PE,
1044 and return a pointer to the next free space in SD. */
1046 static char **
1047 save_registered_pragmas (struct pragma_entry *pe, char **sd)
1049 for (; pe != NULL; pe = pe->next)
1051 if (pe->is_nspace)
1052 sd = save_registered_pragmas (pe->u.space, sd);
1053 *sd++ = xmemdup (HT_STR (&pe->pragma->ident),
1054 HT_LEN (&pe->pragma->ident),
1055 HT_LEN (&pe->pragma->ident) + 1);
1057 return sd;
1060 /* Return a newly-allocated array which saves the names of the
1061 registered pragmas. */
1063 char **
1064 _cpp_save_pragma_names (cpp_reader *pfile)
1066 int ct = count_registered_pragmas (pfile->pragmas);
1067 char **result = xnewvec (char *, ct);
1068 (void) save_registered_pragmas (pfile->pragmas, result);
1069 return result;
1072 /* Restore from SD the names of the registered pragmas referenced by PE,
1073 and return a pointer to the next unused name in SD. */
1075 static char **
1076 restore_registered_pragmas (cpp_reader *pfile, struct pragma_entry *pe,
1077 char **sd)
1079 for (; pe != NULL; pe = pe->next)
1081 if (pe->is_nspace)
1082 sd = restore_registered_pragmas (pfile, pe->u.space, sd);
1083 pe->pragma = cpp_lookup (pfile, U *sd, strlen (*sd));
1084 free (*sd);
1085 sd++;
1087 return sd;
1090 /* Restore the names of the registered pragmas from SAVED. */
1092 void
1093 _cpp_restore_pragma_names (cpp_reader *pfile, char **saved)
1095 (void) restore_registered_pragmas (pfile, pfile->pragmas, saved);
1096 free (saved);
1099 /* Pragmata handling. We handle some, and pass the rest on to the
1100 front end. C99 defines three pragmas and says that no macro
1101 expansion is to be performed on them; whether or not macro
1102 expansion happens for other pragmas is implementation defined.
1103 This implementation never macro-expands the text after #pragma. */
1104 static void
1105 do_pragma (cpp_reader *pfile)
1107 const struct pragma_entry *p = NULL;
1108 const cpp_token *token;
1109 unsigned int count = 1;
1111 pfile->state.prevent_expansion++;
1113 token = cpp_get_token (pfile);
1114 if (token->type == CPP_NAME)
1116 p = lookup_pragma_entry (pfile->pragmas, token->val.node);
1117 if (p && p->is_nspace)
1119 count = 2;
1120 token = cpp_get_token (pfile);
1121 if (token->type == CPP_NAME)
1122 p = lookup_pragma_entry (p->u.space, token->val.node);
1123 else
1124 p = NULL;
1128 /* FIXME. This is an awful kludge to get the front ends to update
1129 their notion of line number for diagnostic purposes. The line
1130 number should be passed to the handler and they should do it
1131 themselves. Stand-alone CPP must ignore us, otherwise it will
1132 prefix the directive with spaces, hence the 1. Ugh. */
1133 if (pfile->cb.line_change)
1134 pfile->cb.line_change (pfile, token, 1);
1136 if (p)
1137 p->u.handler (pfile);
1138 else if (pfile->cb.def_pragma)
1140 _cpp_backup_tokens (pfile, count);
1141 pfile->cb.def_pragma (pfile, pfile->directive_line);
1144 pfile->state.prevent_expansion--;
1147 /* Handle #pragma once. */
1148 static void
1149 do_pragma_once (cpp_reader *pfile)
1151 if (CPP_OPTION (pfile, warn_deprecated))
1152 cpp_error (pfile, DL_WARNING, "#pragma once is obsolete");
1154 if (pfile->buffer->prev == NULL)
1155 cpp_error (pfile, DL_WARNING, "#pragma once in main file");
1156 else
1157 _cpp_never_reread (pfile->buffer->inc);
1159 check_eol (pfile);
1162 /* Handle #pragma GCC poison, to poison one or more identifiers so
1163 that the lexer produces a hard error for each subsequent usage. */
1164 static void
1165 do_pragma_poison (cpp_reader *pfile)
1167 const cpp_token *tok;
1168 cpp_hashnode *hp;
1170 pfile->state.poisoned_ok = 1;
1171 for (;;)
1173 tok = _cpp_lex_token (pfile);
1174 if (tok->type == CPP_EOF)
1175 break;
1176 if (tok->type != CPP_NAME)
1178 cpp_error (pfile, DL_ERROR, "invalid #pragma GCC poison directive");
1179 break;
1182 hp = tok->val.node;
1183 if (hp->flags & NODE_POISONED)
1184 continue;
1186 if (hp->type == NT_MACRO)
1187 cpp_error (pfile, DL_WARNING, "poisoning existing macro \"%s\"",
1188 NODE_NAME (hp));
1189 _cpp_free_definition (hp);
1190 hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1192 pfile->state.poisoned_ok = 0;
1195 /* Mark the current header as a system header. This will suppress
1196 some categories of warnings (notably those from -pedantic). It is
1197 intended for use in system libraries that cannot be implemented in
1198 conforming C, but cannot be certain that their headers appear in a
1199 system include directory. To prevent abuse, it is rejected in the
1200 primary source file. */
1201 static void
1202 do_pragma_system_header (cpp_reader *pfile)
1204 cpp_buffer *buffer = pfile->buffer;
1206 if (buffer->prev == 0)
1207 cpp_error (pfile, DL_WARNING,
1208 "#pragma system_header ignored outside include file");
1209 else
1211 check_eol (pfile);
1212 skip_rest_of_line (pfile);
1213 cpp_make_system_header (pfile, 1, 0);
1217 /* Check the modified date of the current include file against a specified
1218 file. Issue a diagnostic, if the specified file is newer. We use this to
1219 determine if a fixed header should be refixed. */
1220 static void
1221 do_pragma_dependency (cpp_reader *pfile)
1223 const char *fname;
1224 int angle_brackets, ordering;
1226 fname = parse_include (pfile, &angle_brackets);
1227 if (!fname)
1228 return;
1230 ordering = _cpp_compare_file_date (pfile, fname, angle_brackets);
1231 if (ordering < 0)
1232 cpp_error (pfile, DL_WARNING, "cannot find source file %s", fname);
1233 else if (ordering > 0)
1235 cpp_error (pfile, DL_WARNING, "current file is older than %s", fname);
1236 if (cpp_get_token (pfile)->type != CPP_EOF)
1238 _cpp_backup_tokens (pfile, 1);
1239 do_diagnostic (pfile, DL_WARNING, 0);
1243 free ((void *) fname);
1246 /* Get a token but skip padding. */
1247 static const cpp_token *
1248 get_token_no_padding (cpp_reader *pfile)
1250 for (;;)
1252 const cpp_token *result = cpp_get_token (pfile);
1253 if (result->type != CPP_PADDING)
1254 return result;
1258 /* Check syntax is "(string-literal)". Returns the string on success,
1259 or NULL on failure. */
1260 static const cpp_token *
1261 get__Pragma_string (cpp_reader *pfile)
1263 const cpp_token *string;
1265 if (get_token_no_padding (pfile)->type != CPP_OPEN_PAREN)
1266 return NULL;
1268 string = get_token_no_padding (pfile);
1269 if (string->type != CPP_STRING && string->type != CPP_WSTRING)
1270 return NULL;
1272 if (get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
1273 return NULL;
1275 return string;
1278 /* Destringize IN into a temporary buffer, by removing the first \ of
1279 \" and \\ sequences, and process the result as a #pragma directive. */
1280 static void
1281 destringize_and_run (cpp_reader *pfile, const cpp_string *in)
1283 const unsigned char *src, *limit;
1284 char *dest, *result;
1286 dest = result = alloca (in->len - 1);
1287 src = in->text + 1 + (in->text[0] == 'L');
1288 limit = in->text + in->len - 1;
1289 while (src < limit)
1291 /* We know there is a character following the backslash. */
1292 if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1293 src++;
1294 *dest++ = *src++;
1296 *dest = '\n';
1298 /* Ugh; an awful kludge. We are really not set up to be lexing
1299 tokens when in the middle of a macro expansion. Use a new
1300 context to force cpp_get_token to lex, and so skip_rest_of_line
1301 doesn't go beyond the end of the text. Also, remember the
1302 current lexing position so we can return to it later.
1304 Something like line-at-a-time lexing should remove the need for
1305 this. */
1307 cpp_context *saved_context = pfile->context;
1308 cpp_token *saved_cur_token = pfile->cur_token;
1309 tokenrun *saved_cur_run = pfile->cur_run;
1311 pfile->context = xnew (cpp_context);
1312 pfile->context->macro = 0;
1313 pfile->context->prev = 0;
1314 run_directive (pfile, T_PRAGMA, result, dest - result);
1315 free (pfile->context);
1316 pfile->context = saved_context;
1317 pfile->cur_token = saved_cur_token;
1318 pfile->cur_run = saved_cur_run;
1319 pfile->line--;
1322 /* See above comment. For the moment, we'd like
1324 token1 _Pragma ("foo") token2
1326 to be output as
1328 token1
1329 # 7 "file.c"
1330 #pragma foo
1331 # 7 "file.c"
1332 token2
1334 Getting the line markers is a little tricky. */
1335 if (pfile->cb.line_change)
1336 pfile->cb.line_change (pfile, pfile->cur_token, false);
1339 /* Handle the _Pragma operator. */
1340 void
1341 _cpp_do__Pragma (cpp_reader *pfile)
1343 const cpp_token *string = get__Pragma_string (pfile);
1345 if (string)
1346 destringize_and_run (pfile, &string->val.str);
1347 else
1348 cpp_error (pfile, DL_ERROR,
1349 "_Pragma takes a parenthesized string literal");
1352 /* Ignore #sccs on all systems. */
1353 static void
1354 do_sccs (cpp_reader *pfile ATTRIBUTE_UNUSED)
1358 /* Handle #ifdef. */
1359 static void
1360 do_ifdef (cpp_reader *pfile)
1362 int skip = 1;
1364 if (! pfile->state.skipping)
1366 const cpp_hashnode *node = lex_macro_node (pfile);
1368 if (node)
1370 skip = node->type != NT_MACRO;
1371 _cpp_mark_macro_used (node);
1372 check_eol (pfile);
1376 push_conditional (pfile, skip, T_IFDEF, 0);
1379 /* Handle #ifndef. */
1380 static void
1381 do_ifndef (cpp_reader *pfile)
1383 int skip = 1;
1384 const cpp_hashnode *node = 0;
1386 if (! pfile->state.skipping)
1388 node = lex_macro_node (pfile);
1390 if (node)
1392 skip = node->type == NT_MACRO;
1393 _cpp_mark_macro_used (node);
1394 check_eol (pfile);
1398 push_conditional (pfile, skip, T_IFNDEF, node);
1401 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1402 pfile->mi_ind_cmacro so we can handle multiple-include
1403 optimizations. If macro expansion occurs in the expression, we
1404 cannot treat it as a controlling conditional, since the expansion
1405 could change in the future. That is handled by cpp_get_token. */
1406 static void
1407 do_if (cpp_reader *pfile)
1409 int skip = 1;
1411 if (! pfile->state.skipping)
1412 skip = _cpp_parse_expr (pfile) == false;
1414 push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1417 /* Flip skipping state if appropriate and continue without changing
1418 if_stack; this is so that the error message for missing #endif's
1419 etc. will point to the original #if. */
1420 static void
1421 do_else (cpp_reader *pfile)
1423 cpp_buffer *buffer = pfile->buffer;
1424 struct if_stack *ifs = buffer->if_stack;
1426 if (ifs == NULL)
1427 cpp_error (pfile, DL_ERROR, "#else without #if");
1428 else
1430 if (ifs->type == T_ELSE)
1432 cpp_error (pfile, DL_ERROR, "#else after #else");
1433 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1434 "the conditional began here");
1436 ifs->type = T_ELSE;
1438 /* Skip any future (erroneous) #elses or #elifs. */
1439 pfile->state.skipping = ifs->skip_elses;
1440 ifs->skip_elses = true;
1442 /* Invalidate any controlling macro. */
1443 ifs->mi_cmacro = 0;
1445 /* Only check EOL if was not originally skipping. */
1446 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1447 check_eol (pfile);
1451 /* Handle a #elif directive by not changing if_stack either. See the
1452 comment above do_else. */
1453 static void
1454 do_elif (cpp_reader *pfile)
1456 cpp_buffer *buffer = pfile->buffer;
1457 struct if_stack *ifs = buffer->if_stack;
1459 if (ifs == NULL)
1460 cpp_error (pfile, DL_ERROR, "#elif without #if");
1461 else
1463 if (ifs->type == T_ELSE)
1465 cpp_error (pfile, DL_ERROR, "#elif after #else");
1466 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1467 "the conditional began here");
1469 ifs->type = T_ELIF;
1471 /* Only evaluate this if we aren't skipping elses. During
1472 evaluation, set skipping to false to get lexer warnings. */
1473 if (ifs->skip_elses)
1474 pfile->state.skipping = 1;
1475 else
1477 pfile->state.skipping = 0;
1478 pfile->state.skipping = ! _cpp_parse_expr (pfile);
1479 ifs->skip_elses = ! pfile->state.skipping;
1482 /* Invalidate any controlling macro. */
1483 ifs->mi_cmacro = 0;
1487 /* #endif pops the if stack and resets pfile->state.skipping. */
1488 static void
1489 do_endif (cpp_reader *pfile)
1491 cpp_buffer *buffer = pfile->buffer;
1492 struct if_stack *ifs = buffer->if_stack;
1494 if (ifs == NULL)
1495 cpp_error (pfile, DL_ERROR, "#endif without #if");
1496 else
1498 /* Only check EOL if was not originally skipping. */
1499 if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1500 check_eol (pfile);
1502 /* If potential control macro, we go back outside again. */
1503 if (ifs->next == 0 && ifs->mi_cmacro)
1505 pfile->mi_valid = true;
1506 pfile->mi_cmacro = ifs->mi_cmacro;
1509 buffer->if_stack = ifs->next;
1510 pfile->state.skipping = ifs->was_skipping;
1511 obstack_free (&pfile->buffer_ob, ifs);
1515 /* Push an if_stack entry for a preprocessor conditional, and set
1516 pfile->state.skipping to SKIP. If TYPE indicates the conditional
1517 is #if or #ifndef, CMACRO is a potentially controlling macro, and
1518 we need to check here that we are at the top of the file. */
1519 static void
1520 push_conditional (cpp_reader *pfile, int skip, int type,
1521 const cpp_hashnode *cmacro)
1523 struct if_stack *ifs;
1524 cpp_buffer *buffer = pfile->buffer;
1526 ifs = xobnew (&pfile->buffer_ob, struct if_stack);
1527 ifs->line = pfile->directive_line;
1528 ifs->next = buffer->if_stack;
1529 ifs->skip_elses = pfile->state.skipping || !skip;
1530 ifs->was_skipping = pfile->state.skipping;
1531 ifs->type = type;
1532 /* This condition is effectively a test for top-of-file. */
1533 if (pfile->mi_valid && pfile->mi_cmacro == 0)
1534 ifs->mi_cmacro = cmacro;
1535 else
1536 ifs->mi_cmacro = 0;
1538 pfile->state.skipping = skip;
1539 buffer->if_stack = ifs;
1542 /* Read the tokens of the answer into the macro pool, in a directive
1543 of type TYPE. Only commit the memory if we intend it as permanent
1544 storage, i.e. the #assert case. Returns 0 on success, and sets
1545 ANSWERP to point to the answer. */
1546 static int
1547 parse_answer (cpp_reader *pfile, struct answer **answerp, int type)
1549 const cpp_token *paren;
1550 struct answer *answer;
1551 unsigned int acount;
1553 /* In a conditional, it is legal to not have an open paren. We
1554 should save the following token in this case. */
1555 paren = cpp_get_token (pfile);
1557 /* If not a paren, see if we're OK. */
1558 if (paren->type != CPP_OPEN_PAREN)
1560 /* In a conditional no answer is a test for any answer. It
1561 could be followed by any token. */
1562 if (type == T_IF)
1564 _cpp_backup_tokens (pfile, 1);
1565 return 0;
1568 /* #unassert with no answer is valid - it removes all answers. */
1569 if (type == T_UNASSERT && paren->type == CPP_EOF)
1570 return 0;
1572 cpp_error (pfile, DL_ERROR, "missing '(' after predicate");
1573 return 1;
1576 for (acount = 0;; acount++)
1578 size_t room_needed;
1579 const cpp_token *token = cpp_get_token (pfile);
1580 cpp_token *dest;
1582 if (token->type == CPP_CLOSE_PAREN)
1583 break;
1585 if (token->type == CPP_EOF)
1587 cpp_error (pfile, DL_ERROR, "missing ')' to complete answer");
1588 return 1;
1591 /* struct answer includes the space for one token. */
1592 room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
1594 if (BUFF_ROOM (pfile->a_buff) < room_needed)
1595 _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
1597 dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
1598 *dest = *token;
1600 /* Drop whitespace at start, for answer equivalence purposes. */
1601 if (acount == 0)
1602 dest->flags &= ~PREV_WHITE;
1605 if (acount == 0)
1607 cpp_error (pfile, DL_ERROR, "predicate's answer is empty");
1608 return 1;
1611 answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
1612 answer->count = acount;
1613 answer->next = NULL;
1614 *answerp = answer;
1616 return 0;
1619 /* Parses an assertion directive of type TYPE, returning a pointer to
1620 the hash node of the predicate, or 0 on error. If an answer was
1621 supplied, it is placed in ANSWERP, otherwise it is set to 0. */
1622 static cpp_hashnode *
1623 parse_assertion (cpp_reader *pfile, struct answer **answerp, int type)
1625 cpp_hashnode *result = 0;
1626 const cpp_token *predicate;
1628 /* We don't expand predicates or answers. */
1629 pfile->state.prevent_expansion++;
1631 *answerp = 0;
1632 predicate = cpp_get_token (pfile);
1633 if (predicate->type == CPP_EOF)
1634 cpp_error (pfile, DL_ERROR, "assertion without predicate");
1635 else if (predicate->type != CPP_NAME)
1636 cpp_error (pfile, DL_ERROR, "predicate must be an identifier");
1637 else if (parse_answer (pfile, answerp, type) == 0)
1639 unsigned int len = NODE_LEN (predicate->val.node);
1640 unsigned char *sym = alloca (len + 1);
1642 /* Prefix '#' to get it out of macro namespace. */
1643 sym[0] = '#';
1644 memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
1645 result = cpp_lookup (pfile, sym, len + 1);
1648 pfile->state.prevent_expansion--;
1649 return result;
1652 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
1653 or a pointer to NULL if the answer is not in the chain. */
1654 static struct answer **
1655 find_answer (cpp_hashnode *node, const struct answer *candidate)
1657 unsigned int i;
1658 struct answer **result;
1660 for (result = &node->value.answers; *result; result = &(*result)->next)
1662 struct answer *answer = *result;
1664 if (answer->count == candidate->count)
1666 for (i = 0; i < answer->count; i++)
1667 if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
1668 break;
1670 if (i == answer->count)
1671 break;
1675 return result;
1678 /* Test an assertion within a preprocessor conditional. Returns
1679 nonzero on failure, zero on success. On success, the result of
1680 the test is written into VALUE, otherwise the value 0. */
1682 _cpp_test_assertion (cpp_reader *pfile, unsigned int *value)
1684 struct answer *answer;
1685 cpp_hashnode *node;
1687 node = parse_assertion (pfile, &answer, T_IF);
1689 /* For recovery, an erroneous assertion expression is handled as a
1690 failing assertion. */
1691 *value = 0;
1693 if (node)
1694 *value = (node->type == NT_ASSERTION &&
1695 (answer == 0 || *find_answer (node, answer) != 0));
1696 else if (pfile->cur_token[-1].type == CPP_EOF)
1697 _cpp_backup_tokens (pfile, 1);
1699 /* We don't commit the memory for the answer - it's temporary only. */
1700 return node == 0;
1703 /* Handle #assert. */
1704 static void
1705 do_assert (cpp_reader *pfile)
1707 struct answer *new_answer;
1708 cpp_hashnode *node;
1710 node = parse_assertion (pfile, &new_answer, T_ASSERT);
1711 if (node)
1713 /* Place the new answer in the answer list. First check there
1714 is not a duplicate. */
1715 new_answer->next = 0;
1716 if (node->type == NT_ASSERTION)
1718 if (*find_answer (node, new_answer))
1720 cpp_error (pfile, DL_WARNING, "\"%s\" re-asserted",
1721 NODE_NAME (node) + 1);
1722 return;
1724 new_answer->next = node->value.answers;
1727 node->type = NT_ASSERTION;
1728 node->value.answers = new_answer;
1729 BUFF_FRONT (pfile->a_buff) += (sizeof (struct answer)
1730 + (new_answer->count - 1)
1731 * sizeof (cpp_token));
1732 check_eol (pfile);
1736 /* Handle #unassert. */
1737 static void
1738 do_unassert (cpp_reader *pfile)
1740 cpp_hashnode *node;
1741 struct answer *answer;
1743 node = parse_assertion (pfile, &answer, T_UNASSERT);
1744 /* It isn't an error to #unassert something that isn't asserted. */
1745 if (node && node->type == NT_ASSERTION)
1747 if (answer)
1749 struct answer **p = find_answer (node, answer), *temp;
1751 /* Remove the answer from the list. */
1752 temp = *p;
1753 if (temp)
1754 *p = temp->next;
1756 /* Did we free the last answer? */
1757 if (node->value.answers == 0)
1758 node->type = NT_VOID;
1760 check_eol (pfile);
1762 else
1763 _cpp_free_definition (node);
1766 /* We don't commit the memory for the answer - it's temporary only. */
1769 /* These are for -D, -U, -A. */
1771 /* Process the string STR as if it appeared as the body of a #define.
1772 If STR is just an identifier, define it with value 1.
1773 If STR has anything after the identifier, then it should
1774 be identifier=definition. */
1775 void
1776 cpp_define (cpp_reader *pfile, const char *str)
1778 char *buf, *p;
1779 size_t count;
1781 /* Copy the entire option so we can modify it.
1782 Change the first "=" in the string to a space. If there is none,
1783 tack " 1" on the end. */
1785 count = strlen (str);
1786 buf = (char *) alloca (count + 3);
1787 memcpy (buf, str, count);
1789 p = strchr (str, '=');
1790 if (p)
1791 buf[p - str] = ' ';
1792 else
1794 buf[count++] = ' ';
1795 buf[count++] = '1';
1797 buf[count] = '\n';
1799 run_directive (pfile, T_DEFINE, buf, count);
1802 /* Slight variant of the above for use by initialize_builtins. */
1803 void
1804 _cpp_define_builtin (cpp_reader *pfile, const char *str)
1806 size_t len = strlen (str);
1807 char *buf = alloca (len + 1);
1808 memcpy (buf, str, len);
1809 buf[len] = '\n';
1810 run_directive (pfile, T_DEFINE, buf, len);
1813 /* Process MACRO as if it appeared as the body of an #undef. */
1814 void
1815 cpp_undef (cpp_reader *pfile, const char *macro)
1817 size_t len = strlen (macro);
1818 char *buf = alloca (len + 1);
1819 memcpy (buf, macro, len);
1820 buf[len] = '\n';
1821 run_directive (pfile, T_UNDEF, buf, len);
1824 /* Process the string STR as if it appeared as the body of a #assert. */
1825 void
1826 cpp_assert (cpp_reader *pfile, const char *str)
1828 handle_assertion (pfile, str, T_ASSERT);
1831 /* Process STR as if it appeared as the body of an #unassert. */
1832 void
1833 cpp_unassert (cpp_reader *pfile, const char *str)
1835 handle_assertion (pfile, str, T_UNASSERT);
1838 /* Common code for cpp_assert (-A) and cpp_unassert (-A-). */
1839 static void
1840 handle_assertion (cpp_reader *pfile, const char *str, int type)
1842 size_t count = strlen (str);
1843 const char *p = strchr (str, '=');
1845 /* Copy the entire option so we can modify it. Change the first
1846 "=" in the string to a '(', and tack a ')' on the end. */
1847 char *buf = (char *) alloca (count + 2);
1849 memcpy (buf, str, count);
1850 if (p)
1852 buf[p - str] = '(';
1853 buf[count++] = ')';
1855 buf[count] = '\n';
1856 str = buf;
1858 run_directive (pfile, type, str, count);
1861 /* The number of errors for a given reader. */
1862 unsigned int
1863 cpp_errors (cpp_reader *pfile)
1865 return pfile->errors;
1868 /* The options structure. */
1869 cpp_options *
1870 cpp_get_options (cpp_reader *pfile)
1872 return &pfile->opts;
1875 /* The callbacks structure. */
1876 cpp_callbacks *
1877 cpp_get_callbacks (cpp_reader *pfile)
1879 return &pfile->cb;
1882 /* The line map set. */
1883 const struct line_maps *
1884 cpp_get_line_maps (cpp_reader *pfile)
1886 return &pfile->line_maps;
1889 /* Copy the given callbacks structure to our own. */
1890 void
1891 cpp_set_callbacks (cpp_reader *pfile, cpp_callbacks *cb)
1893 pfile->cb = *cb;
1896 /* Push a new buffer on the buffer stack. Returns the new buffer; it
1897 doesn't fail. It does not generate a file change call back; that
1898 is the responsibility of the caller. */
1899 cpp_buffer *
1900 cpp_push_buffer (cpp_reader *pfile, const uchar *buffer, size_t len,
1901 int from_stage3, int return_at_eof)
1903 cpp_buffer *new = xobnew (&pfile->buffer_ob, cpp_buffer);
1905 /* Clears, amongst other things, if_stack and mi_cmacro. */
1906 memset (new, 0, sizeof (cpp_buffer));
1908 new->next_line = new->buf = buffer;
1909 new->rlimit = buffer + len;
1910 new->from_stage3 = from_stage3;
1911 new->prev = pfile->buffer;
1912 new->return_at_eof = return_at_eof;
1913 new->need_line = true;
1915 pfile->buffer = new;
1916 return new;
1919 /* Pops a single buffer, with a file change call-back if appropriate.
1920 Then pushes the next -include file, if any remain. */
1921 void
1922 _cpp_pop_buffer (cpp_reader *pfile)
1924 cpp_buffer *buffer = pfile->buffer;
1925 struct include_file *inc = buffer->inc;
1926 struct if_stack *ifs;
1928 /* Walk back up the conditional stack till we reach its level at
1929 entry to this file, issuing error messages. */
1930 for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
1931 cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1932 "unterminated #%s", dtable[ifs->type].name);
1934 /* In case of a missing #endif. */
1935 pfile->state.skipping = 0;
1937 /* _cpp_do_file_change expects pfile->buffer to be the new one. */
1938 pfile->buffer = buffer->prev;
1940 free (buffer->notes);
1942 /* Free the buffer object now; we may want to push a new buffer
1943 in _cpp_push_next_include_file. */
1944 obstack_free (&pfile->buffer_ob, buffer);
1946 if (inc)
1948 _cpp_pop_file_buffer (pfile, inc);
1950 /* Don't generate a callback for popping the main file. */
1951 if (pfile->buffer)
1952 _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
1956 /* Enter all recognized directives in the hash table. */
1957 void
1958 _cpp_init_directives (cpp_reader *pfile)
1960 unsigned int i;
1961 cpp_hashnode *node;
1963 for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
1965 node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
1966 node->is_directive = 1;
1967 node->directive_index = i;