OSDN Git Service

* config/h8300/h8300.c (TARGET_INSERT_ATTRIBUTES): Define.
[pf3gnuchains/gcc-fork.git] / gcc / cpplib.c
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
7
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.
12
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.
17
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.  */
21
22 #include "config.h"
23 #include "system.h"
24
25 #include "cpplib.h"
26 #include "cpphash.h"
27 #include "obstack.h"
28
29 /* Chained list of answers to an assertion.  */
30 struct answer
31 {
32   struct answer *next;
33   unsigned int count;
34   cpp_token first[1];
35 };
36
37 /* Stack of conditionals currently in progress
38    (including both successful and failing conditionals).  */
39 struct if_stack
40 {
41   struct if_stack *next;
42   unsigned int line;            /* Line where condition started.  */
43   const cpp_hashnode *mi_cmacro;/* macro name for #ifndef around entire file */
44   bool skip_elses;              /* Can future #else / #elif be skipped?  */
45   bool was_skipping;            /* If were skipping on entry.  */
46   int type;                     /* Most recent conditional, for diagnostics.  */
47 };
48
49 /* Contains a registered pragma or pragma namespace.  */
50 typedef void (*pragma_cb) PARAMS ((cpp_reader *));
51 struct pragma_entry
52 {
53   struct pragma_entry *next;
54   const cpp_hashnode *pragma;   /* Name and length.  */
55   int is_nspace;
56   union {
57     pragma_cb handler;
58     struct pragma_entry *space;
59   } u;
60 };
61
62 /* Values for the origin field of struct directive.  KANDR directives
63    come from traditional (K&R) C.  STDC89 directives come from the
64    1989 C standard.  EXTENSION directives are extensions.  */
65 #define KANDR           0
66 #define STDC89          1
67 #define EXTENSION       2
68
69 /* Values for the flags field of struct directive.  COND indicates a
70    conditional; IF_COND an opening conditional.  INCL means to treat
71    "..." and <...> as q-char and h-char sequences respectively.  IN_I
72    means this directive should be handled even if -fpreprocessed is in
73    effect (these are the directives with callback hooks).
74
75    EXPAND is set on directives that are always macro-expanded.  */
76 #define COND            (1 << 0)
77 #define IF_COND         (1 << 1)
78 #define INCL            (1 << 2)
79 #define IN_I            (1 << 3)
80 #define EXPAND          (1 << 4)
81
82 /* Defines one #-directive, including how to handle it.  */
83 typedef void (*directive_handler) PARAMS ((cpp_reader *));
84 typedef struct directive directive;
85 struct directive
86 {
87   directive_handler handler;    /* Function to handle directive.  */
88   const uchar *name;            /* Name of directive.  */
89   unsigned short length;        /* Length of name.  */
90   unsigned char origin;         /* Origin of directive.  */
91   unsigned char flags;          /* Flags describing this directive.  */
92 };
93
94 /* Forward declarations.  */
95
96 static void skip_rest_of_line   PARAMS ((cpp_reader *));
97 static void check_eol           PARAMS ((cpp_reader *));
98 static void start_directive     PARAMS ((cpp_reader *));
99 static void prepare_directive_trad PARAMS ((cpp_reader *));
100 static void end_directive       PARAMS ((cpp_reader *, int));
101 static void directive_diagnostics
102         PARAMS ((cpp_reader *, const directive *, int));
103 static void run_directive       PARAMS ((cpp_reader *, int,
104                                          const char *, size_t));
105 static const cpp_token *glue_header_name PARAMS ((cpp_reader *));
106 static const cpp_token *parse_include PARAMS ((cpp_reader *));
107 static void push_conditional    PARAMS ((cpp_reader *, int, int,
108                                          const cpp_hashnode *));
109 static unsigned int read_flag   PARAMS ((cpp_reader *, unsigned int));
110 static uchar *dequote_string    PARAMS ((cpp_reader *, const uchar *,
111                                          unsigned int));
112 static int  strtoul_for_line    PARAMS ((const uchar *, unsigned int,
113                                          unsigned long *));
114 static void do_diagnostic       PARAMS ((cpp_reader *, int, int));
115 static cpp_hashnode *lex_macro_node     PARAMS ((cpp_reader *));
116 static void do_include_common   PARAMS ((cpp_reader *, enum include_type));
117 static struct pragma_entry *lookup_pragma_entry
118   PARAMS ((struct pragma_entry *, const cpp_hashnode *pragma));
119 static struct pragma_entry *insert_pragma_entry
120   PARAMS ((cpp_reader *, struct pragma_entry **, const cpp_hashnode *,
121            pragma_cb));
122 static void do_pragma_once      PARAMS ((cpp_reader *));
123 static void do_pragma_poison    PARAMS ((cpp_reader *));
124 static void do_pragma_system_header     PARAMS ((cpp_reader *));
125 static void do_pragma_dependency        PARAMS ((cpp_reader *));
126 static void do_linemarker               PARAMS ((cpp_reader *));
127 static const cpp_token *get_token_no_padding PARAMS ((cpp_reader *));
128 static const cpp_token *get__Pragma_string PARAMS ((cpp_reader *));
129 static void destringize_and_run PARAMS ((cpp_reader *, const cpp_string *));
130 static int parse_answer PARAMS ((cpp_reader *, struct answer **, int));
131 static cpp_hashnode *parse_assertion PARAMS ((cpp_reader *, struct answer **,
132                                               int));
133 static struct answer ** find_answer PARAMS ((cpp_hashnode *,
134                                              const struct answer *));
135 static void handle_assertion    PARAMS ((cpp_reader *, const char *, int));
136
137 /* This is the table of directive handlers.  It is ordered by
138    frequency of occurrence; the numbers at the end are directive
139    counts from all the source code I have lying around (egcs and libc
140    CVS as of 1999-05-18, plus grub-0.5.91, linux-2.2.9, and
141    pcmcia-cs-3.0.9).  This is no longer important as directive lookup
142    is now O(1).  All extensions other than #warning and #include_next
143    are deprecated.  The name is where the extension appears to have
144    come from.  */
145
146 #define DIRECTIVE_TABLE                                                 \
147 D(define,       T_DEFINE = 0,   KANDR,     IN_I)           /* 270554 */ \
148 D(include,      T_INCLUDE,      KANDR,     INCL | EXPAND)  /*  52262 */ \
149 D(endif,        T_ENDIF,        KANDR,     COND)           /*  45855 */ \
150 D(ifdef,        T_IFDEF,        KANDR,     COND | IF_COND) /*  22000 */ \
151 D(if,           T_IF,           KANDR, COND | IF_COND | EXPAND) /*  18162 */ \
152 D(else,         T_ELSE,         KANDR,     COND)           /*   9863 */ \
153 D(ifndef,       T_IFNDEF,       KANDR,     COND | IF_COND) /*   9675 */ \
154 D(undef,        T_UNDEF,        KANDR,     IN_I)           /*   4837 */ \
155 D(line,         T_LINE,         KANDR,     EXPAND)         /*   2465 */ \
156 D(elif,         T_ELIF,         STDC89,    COND | EXPAND)  /*    610 */ \
157 D(error,        T_ERROR,        STDC89,    0)              /*    475 */ \
158 D(pragma,       T_PRAGMA,       STDC89,    IN_I)           /*    195 */ \
159 D(warning,      T_WARNING,      EXTENSION, 0)              /*     22 */ \
160 D(include_next, T_INCLUDE_NEXT, EXTENSION, INCL | EXPAND)  /*     19 */ \
161 D(ident,        T_IDENT,        EXTENSION, IN_I)           /*     11 */ \
162 D(import,       T_IMPORT,       EXTENSION, INCL | EXPAND)  /* 0 ObjC */ \
163 D(assert,       T_ASSERT,       EXTENSION, 0)              /* 0 SVR4 */ \
164 D(unassert,     T_UNASSERT,     EXTENSION, 0)              /* 0 SVR4 */ \
165 SCCS_ENTRY                                                 /* 0 SVR4? */
166
167 /* #sccs is not always recognized.  */
168 #ifdef SCCS_DIRECTIVE
169 # define SCCS_ENTRY D(sccs, T_SCCS, EXTENSION, 0)
170 #else
171 # define SCCS_ENTRY /* nothing */
172 #endif
173
174 /* Use the table to generate a series of prototypes, an enum for the
175    directive names, and an array of directive handlers.  */
176
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
181
182 #define D(n, tag, o, f) tag,
183 enum
184 {
185   DIRECTIVE_TABLE
186   N_DIRECTIVES
187 };
188 #undef D
189
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[] =
195 {
196 DIRECTIVE_TABLE
197 };
198 #undef D
199 #undef DIRECTIVE_TABLE
200
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 =
205 {
206   do_linemarker, U"#", 1, KANDR, IN_I
207 };
208
209 #define SEEN_EOL() (pfile->cur_token[-1].type == CPP_EOF)
210
211 /* Skip any remaining tokens in a directive.  */
212 static void
213 skip_rest_of_line (pfile)
214      cpp_reader *pfile;
215 {
216   /* Discard all stacked contexts.  */
217   while (pfile->context != &pfile->base_context)
218     _cpp_pop_context (pfile);
219
220   /* Sweep up all tokens remaining on the line.  */
221   if (! SEEN_EOL ())
222     while (_cpp_lex_token (pfile)->type != CPP_EOF)
223       ;
224 }
225
226 /* Ensure there are no stray tokens at the end of a directive.  */
227 static void
228 check_eol (pfile)
229      cpp_reader *pfile;
230 {
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);
234 }
235
236 /* Called when entering a directive, _Pragma or command-line directive.  */
237 static void
238 start_directive (pfile)
239      cpp_reader *pfile;
240 {
241   /* Setup in-directive state.  */
242   pfile->state.in_directive = 1;
243   pfile->state.save_comments = 0;
244
245   /* Some handlers need the position of the # for diagnostics.  */
246   pfile->directive_line = pfile->line;
247 }
248
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;
254 {
255   if (CPP_OPTION (pfile, traditional))
256     {
257       /* Revert change of prepare_directive_trad.  */
258       pfile->state.prevent_expansion--;
259
260       if (pfile->directive != &dtable[T_DEFINE])
261         _cpp_remove_overlay (pfile);
262     }
263   /* We don't skip for an assembler #.  */
264   else if (skip_line)
265     {
266       skip_rest_of_line (pfile);
267       if (!pfile->keep_tokens)
268         {
269           pfile->cur_run = &pfile->base_run;
270           pfile->cur_token = pfile->base_run.base;
271         }
272     }
273
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;
280 }
281
282 /* Prepare to handle the directive in pfile->directive.  */
283 static void
284 prepare_directive_trad (pfile)
285      cpp_reader *pfile;
286 {
287   if (pfile->directive == &dtable[T_DEFINE])
288     CUR (pfile->context) = pfile->buffer->cur;
289   else
290     {
291       bool no_expand = (pfile->directive
292                         && ! (pfile->directive->flags & EXPAND));
293       bool was_skipping = pfile->state.skipping;
294
295       pfile->state.skipping = false;
296       pfile->state.in_expression = (pfile->directive == &dtable[T_IF]
297                                     || pfile->directive == &dtable[T_ELIF]);
298       if (no_expand)
299         pfile->state.prevent_expansion++;
300       _cpp_read_logical_line_trad (pfile);
301       if (no_expand)
302         pfile->state.prevent_expansion--;
303       pfile->state.skipping = was_skipping;
304       _cpp_overlay_buffer (pfile, pfile->out.base,
305                            pfile->out.cur - pfile->out.base);
306     }
307
308   /* Stop ISO C from expanding anything.  */
309   pfile->state.prevent_expansion++;
310 }
311
312 /* Output diagnostics for a directive DIR.  INDENTED is non-zero if
313    the '#' was indented.  */
314 static void
315 directive_diagnostics (pfile, dir, indented)
316      cpp_reader *pfile;
317      const directive *dir;
318      int indented;
319 {
320   /* Issue -pedantic warnings for extensions.  */
321   if (CPP_PEDANTIC (pfile)
322       && ! pfile->state.skipping
323       && dir->origin == EXTENSION)
324     cpp_error (pfile, DL_PEDWARN, "#%s is a GCC extension", dir->name);
325
326   /* Traditionally, a directive is ignored unless its # is in
327      column 1.  Therefore in code intended to work with K+R
328      compilers, directives added by C89 must have their #
329      indented, and directives present in traditional C must not.
330      This is true even of directives in skipped conditional
331      blocks.  #elif cannot be used at all.  */
332   if (CPP_WTRADITIONAL (pfile))
333     {
334       if (dir == &dtable[T_ELIF])
335         cpp_error (pfile, DL_WARNING,
336                    "suggest not using #elif in traditional C");
337       else if (indented && dir->origin == KANDR)
338         cpp_error (pfile, DL_WARNING,
339                    "traditional C ignores #%s with the # indented",
340                    dir->name);
341       else if (!indented && dir->origin != KANDR)
342         cpp_error (pfile, DL_WARNING,
343                    "suggest hiding #%s from traditional C with an indented #",
344                    dir->name);
345     }
346 }
347
348 /* Check if we have a known directive.  INDENTED is non-zero if the
349    '#' of the directive was indented.  This function is in this file
350    to save unnecessarily exporting dtable etc. to cpplex.c.  Returns
351    non-zero if the line of tokens has been handled, zero if we should
352    continue processing the line.  */
353 int
354 _cpp_handle_directive (pfile, indented)
355      cpp_reader *pfile;
356      int indented;
357 {
358   const directive *dir = 0;
359   const cpp_token *dname;
360   bool was_parsing_args = pfile->state.parsing_args;
361   int skip = 1;
362
363   if (was_parsing_args)
364     {
365       if (CPP_OPTION (pfile, pedantic))
366         cpp_error (pfile, DL_PEDWARN,
367              "embedding a directive within macro arguments is not portable");
368       pfile->state.parsing_args = 0;
369       pfile->state.prevent_expansion = 0;
370     }
371   start_directive (pfile);
372   dname = _cpp_lex_token (pfile);
373
374   if (dname->type == CPP_NAME)
375     {
376       if (dname->val.node->directive_index)
377         dir = &dtable[dname->val.node->directive_index - 1];
378     }
379   /* We do not recognise the # followed by a number extension in
380      assembler code.  */
381   else if (dname->type == CPP_NUMBER && CPP_OPTION (pfile, lang) != CLK_ASM)
382     {
383       dir = &linemarker_dir;
384       if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, preprocessed)
385           && ! pfile->state.skipping)
386         cpp_error (pfile, DL_PEDWARN,
387                    "style of line directive is a GCC extension");
388     }
389
390   pfile->directive = dir;
391   if (CPP_OPTION (pfile, traditional))
392     prepare_directive_trad (pfile);
393
394   if (dir)
395     {
396       /* If we have a directive that is not an opening conditional,
397          invalidate any control macro.  */
398       if (! (dir->flags & IF_COND))
399         pfile->mi_valid = false;
400
401       /* Kluge alert.  In order to be sure that code like this
402
403          #define HASH #
404          HASH define foo bar
405
406          does not cause '#define foo bar' to get executed when
407          compiled with -save-temps, we recognize directives in
408          -fpreprocessed mode only if the # is in column 1.  cppmacro.c
409          puts a space in front of any '#' at the start of a macro.  */
410       if (CPP_OPTION (pfile, preprocessed)
411           && (indented || !(dir->flags & IN_I)))
412         {
413           skip = 0;
414           dir = 0;
415         }
416       else
417         {
418           /* In failed conditional groups, all non-conditional
419              directives are ignored.  Before doing that, whether
420              skipping or not, we should lex angle-bracketed headers
421              correctly, and maybe output some diagnostics.  */
422           pfile->state.angled_headers = dir->flags & INCL;
423           if (! CPP_OPTION (pfile, preprocessed))
424             directive_diagnostics (pfile, dir, indented);
425           if (pfile->state.skipping && !(dir->flags & COND))
426             dir = 0;
427         }
428     }
429   else if (dname->type == CPP_EOF)
430     ;   /* CPP_EOF is the "null directive".  */
431   else
432     {
433       /* An unknown directive.  Don't complain about it in assembly
434          source: we don't know where the comments are, and # may
435          introduce assembler pseudo-ops.  Don't complain about invalid
436          directives in skipped conditional groups (6.10 p4).  */
437       if (CPP_OPTION (pfile, lang) == CLK_ASM)
438         skip = 0;
439       else if (!pfile->state.skipping)
440         cpp_error (pfile, DL_ERROR, "invalid preprocessing directive #%s",
441                    cpp_token_as_text (pfile, dname));
442     }
443
444   if (dir)
445     {
446       /* If we are processing a `#define' directive and we have been
447          requested to expand comments into macros, then re-enable
448          saving of comments.  */
449       if (dir == &dtable[T_DEFINE])
450         pfile->state.save_comments =
451           ! CPP_OPTION (pfile, discard_comments_in_macro_exp);
452
453       (*pfile->directive->handler) (pfile);
454     }
455   else if (skip == 0)
456     _cpp_backup_tokens (pfile, 1);
457
458   end_directive (pfile, skip);
459   if (was_parsing_args)
460     {
461       /* Restore state when within macro args.  */
462       pfile->state.parsing_args = 2;
463       pfile->state.prevent_expansion = 1;
464       pfile->buffer->saved_flags |= PREV_WHITE;
465     }
466   return skip;
467 }
468
469 /* Directive handler wrapper used by the command line option
470    processor.  */
471 static void
472 run_directive (pfile, dir_no, buf, count)
473      cpp_reader *pfile;
474      int dir_no;
475      const char *buf;
476      size_t count;
477 {
478   cpp_push_buffer (pfile, (const uchar *) buf, count,
479                    /* from_stage3 */ true, 1);
480   start_directive (pfile);
481   /* We don't want a leading # to be interpreted as a directive.  */
482   pfile->buffer->saved_flags = 0;
483   pfile->directive = &dtable[dir_no];
484   if (CPP_OPTION (pfile, traditional))
485     prepare_directive_trad (pfile);
486   (void) (*pfile->directive->handler) (pfile);
487   end_directive (pfile, 1);
488   _cpp_pop_buffer (pfile);
489 }
490
491 /* Checks for validity the macro name in #define, #undef, #ifdef and
492    #ifndef directives.  */
493 static cpp_hashnode *
494 lex_macro_node (pfile)
495      cpp_reader *pfile;
496 {
497   const cpp_token *token = _cpp_lex_token (pfile);
498
499   /* The token immediately after #define must be an identifier.  That
500      identifier may not be "defined", per C99 6.10.8p4.
501      In C++, it may not be any of the "named operators" either,
502      per C++98 [lex.digraph], [lex.key].
503      Finally, the identifier may not have been poisoned.  (In that case
504      the lexer has issued the error message for us.)
505
506      Note that if we're copying comments into macro expansions, we
507      could encounter comment tokens here, so eat them all up first.  */
508
509   if (! CPP_OPTION (pfile, discard_comments_in_macro_exp))
510     {
511       while (token->type == CPP_COMMENT)
512         token = _cpp_lex_token (pfile);
513     }
514
515   if (token->type == CPP_NAME)
516     {
517       cpp_hashnode *node = token->val.node;
518
519       if (node == pfile->spec_nodes.n_defined)
520         cpp_error (pfile, DL_ERROR,
521                    "\"defined\" cannot be used as a macro name");
522       else if (! (node->flags & NODE_POISONED))
523         return node;
524     }
525   else if (token->flags & NAMED_OP)
526     cpp_error (pfile, DL_ERROR,
527        "\"%s\" cannot be used as a macro name as it is an operator in C++",
528                NODE_NAME (token->val.node));
529   else if (token->type == CPP_EOF)
530     cpp_error (pfile, DL_ERROR, "no macro name given in #%s directive",
531                pfile->directive->name);
532   else
533     cpp_error (pfile, DL_ERROR, "macro names must be identifiers");
534
535   return NULL;
536 }
537
538 /* Process a #define directive.  Most work is done in cppmacro.c.  */
539 static void
540 do_define (pfile)
541      cpp_reader *pfile;
542 {
543   cpp_hashnode *node = lex_macro_node (pfile);
544
545   if (node)
546     {
547       if (_cpp_create_definition (pfile, node))
548         if (pfile->cb.define)
549           (*pfile->cb.define) (pfile, pfile->directive_line, node);
550     }
551 }
552
553 /* Handle #undef.  Mark the identifier NT_VOID in the hash table.  */
554 static void
555 do_undef (pfile)
556      cpp_reader *pfile;
557 {
558   cpp_hashnode *node = lex_macro_node (pfile);
559
560   /* 6.10.3.5 paragraph 2: [#undef] is ignored if the specified identifier
561      is not currently defined as a macro name.  */
562   if (node && node->type == NT_MACRO)
563     {
564       if (pfile->cb.undef)
565         (*pfile->cb.undef) (pfile, pfile->directive_line, node);
566
567       if (node->flags & NODE_WARN)
568         cpp_error (pfile, DL_WARNING, "undefining \"%s\"", NODE_NAME (node));
569
570       _cpp_free_definition (node);
571     }
572   check_eol (pfile);
573 }
574
575 /* Helper routine used by parse_include.  Reinterpret the current line
576    as an h-char-sequence (< ... >); we are looking at the first token
577    after the <.  Returns the header as a token, or NULL on failure.  */
578 static const cpp_token *
579 glue_header_name (pfile)
580      cpp_reader *pfile;
581 {
582   cpp_token *header = NULL;
583   const cpp_token *token;
584   unsigned char *buffer;
585   size_t len, total_len = 0, capacity = 1024;
586
587   /* To avoid lexed tokens overwriting our glued name, we can only
588      allocate from the string pool once we've lexed everything.  */
589   buffer = (unsigned char *) xmalloc (capacity);
590   for (;;)
591     {
592       token = cpp_get_token (pfile);
593
594       if (token->type == CPP_GREATER || token->type == CPP_EOF)
595         break;
596
597       len = cpp_token_len (token);
598       if (total_len + len > capacity)
599         {
600           capacity = (capacity + len) * 2;
601           buffer = (unsigned char *) xrealloc (buffer, capacity);
602         }
603
604       if (token->flags & PREV_WHITE)
605         buffer[total_len++] = ' ';
606
607       total_len = cpp_spell_token (pfile, token, &buffer[total_len]) - buffer;
608     }
609
610   if (token->type == CPP_EOF)
611     cpp_error (pfile, DL_ERROR, "missing terminating > character");
612   else
613     {
614       unsigned char *token_mem = _cpp_unaligned_alloc (pfile, total_len + 1);
615       memcpy (token_mem, buffer, total_len);
616       token_mem[total_len] = '\0';
617
618       header = _cpp_temp_token (pfile);
619       header->type = CPP_HEADER_NAME;
620       header->flags = 0;
621       header->val.str.len = total_len;
622       header->val.str.text = token_mem;
623     }
624
625   free ((PTR) buffer);
626   return header;
627 }
628
629 /* Returns the header string of #include, #include_next, #import and
630    #pragma dependency.  Returns NULL on error.  */
631 static const cpp_token *
632 parse_include (pfile)
633      cpp_reader *pfile;
634 {
635   const unsigned char *dir;
636   const cpp_token *header;
637
638   if (pfile->directive == &dtable[T_PRAGMA])
639     dir = U"pragma dependency";
640   else
641     dir = pfile->directive->name;
642
643   /* Allow macro expansion.  */
644   header = cpp_get_token (pfile);
645   if (header->type != CPP_STRING && header->type != CPP_HEADER_NAME)
646     {
647       if (header->type != CPP_LESS)
648         {
649           cpp_error (pfile, DL_ERROR,
650                      "#%s expects \"FILENAME\" or <FILENAME>", dir);
651           return NULL;
652         }
653
654       header = glue_header_name (pfile);
655       if (header == NULL)
656         return header;
657     }
658
659   if (header->val.str.len == 0)
660     {
661       cpp_error (pfile, DL_ERROR, "empty file name in #%s", dir);
662       return NULL;
663     }
664
665   return header;
666 }
667
668 /* Handle #include, #include_next and #import.  */
669 static void
670 do_include_common (pfile, type)
671      cpp_reader *pfile;
672      enum include_type type;
673 {
674   const cpp_token *header;
675
676   /* For #include_next, if this is the primary source file, warn and
677      use the normal search logic.  */
678   if (type == IT_INCLUDE_NEXT && ! pfile->buffer->prev)
679     {
680       cpp_error (pfile, DL_WARNING, "#include_next in primary source file");
681       type = IT_INCLUDE;
682     }
683   else if (type == IT_IMPORT && CPP_OPTION (pfile, warn_import))
684     {
685       CPP_OPTION (pfile, warn_import) = 0;
686       cpp_error (pfile, DL_WARNING,
687            "#import is obsolete, use an #ifndef wrapper in the header file");
688     }
689
690   header = parse_include (pfile);
691   if (header)
692     {
693       /* Prevent #include recursion.  */
694       if (pfile->line_maps.depth >= CPP_STACK_MAX)
695         cpp_error (pfile, DL_ERROR, "#include nested too deeply");
696       else
697         {
698           check_eol (pfile);
699           /* Get out of macro context, if we are.  */
700           skip_rest_of_line (pfile);
701           if (pfile->cb.include)
702             (*pfile->cb.include) (pfile, pfile->directive_line,
703                                   pfile->directive->name, header);
704
705           _cpp_execute_include (pfile, header, type);
706         }
707     }
708 }
709
710 static void
711 do_include (pfile)
712      cpp_reader *pfile;
713 {
714   do_include_common (pfile, IT_INCLUDE);
715 }
716
717 static void
718 do_import (pfile)
719      cpp_reader *pfile;
720 {
721   do_include_common (pfile, IT_IMPORT);
722 }
723
724 static void
725 do_include_next (pfile)
726      cpp_reader *pfile;
727 {
728   do_include_common (pfile, IT_INCLUDE_NEXT);
729 }
730
731 /* Subroutine of do_linemarker.  Read possible flags after file name.
732    LAST is the last flag seen; 0 if this is the first flag. Return the
733    flag if it is valid, 0 at the end of the directive. Otherwise
734    complain.  */
735 static unsigned int
736 read_flag (pfile, last)
737      cpp_reader *pfile;
738      unsigned int last;
739 {
740   const cpp_token *token = _cpp_lex_token (pfile);
741
742   if (token->type == CPP_NUMBER && token->val.str.len == 1)
743     {
744       unsigned int flag = token->val.str.text[0] - '0';
745
746       if (flag > last && flag <= 4
747           && (flag != 4 || last == 3)
748           && (flag != 2 || last == 0))
749         return flag;
750     }
751
752   if (token->type != CPP_EOF)
753     cpp_error (pfile, DL_ERROR, "invalid flag \"%s\" in line directive",
754                cpp_token_as_text (pfile, token));
755   return 0;
756 }
757
758 /* Subroutine of do_line and do_linemarker.  Returns a version of STR
759    which has a NUL terminator and all escape sequences converted to
760    their equivalents.  Temporary, hopefully.  */
761 static uchar *
762 dequote_string (pfile, str, len)
763      cpp_reader *pfile;
764      const uchar *str;
765      unsigned int len;
766 {
767   uchar *result = _cpp_unaligned_alloc (pfile, len + 1);
768   uchar *dst = result;
769   const uchar *limit = str + len;
770   cppchar_t c;
771
772   while (str < limit)
773     {
774       c = *str++;
775       if (c != '\\')
776         *dst++ = c;
777       else
778         *dst++ = cpp_parse_escape (pfile, &str, limit, 0);
779     }
780   *dst++ = '\0';
781   return result;
782 }
783
784 /* Subroutine of do_line and do_linemarker.  Convert a number in STR,
785    of length LEN, to binary; store it in NUMP, and return 0 if the
786    number was well-formed, 1 if not.  Temporary, hopefully.  */
787 static int
788 strtoul_for_line (str, len, nump)
789      const uchar *str;
790      unsigned int len;
791      unsigned long *nump;
792 {
793   unsigned long reg = 0;
794   uchar c;
795   while (len--)
796     {
797       c = *str++;
798       if (!ISDIGIT (c))
799         return 1;
800       reg *= 10;
801       reg += c - '0';
802     }
803   *nump = reg;
804   return 0;
805 }
806
807 /* Interpret #line command.
808    Note that the filename string (if any) is a true string constant
809    (escapes are interpreted), unlike in #line.  */
810 static void
811 do_line (pfile)
812      cpp_reader *pfile;
813 {
814   const cpp_token *token;
815   const char *new_file = pfile->map->to_file;
816   unsigned long new_lineno;
817
818   /* C99 raised the minimum limit on #line numbers.  */
819   unsigned int cap = CPP_OPTION (pfile, c99) ? 2147483647 : 32767;
820
821   /* #line commands expand macros.  */
822   token = cpp_get_token (pfile);
823   if (token->type != CPP_NUMBER
824       || strtoul_for_line (token->val.str.text, token->val.str.len,
825                            &new_lineno))
826     {
827       cpp_error (pfile, DL_ERROR,
828                  "\"%s\" after #line is not a positive integer",
829                  cpp_token_as_text (pfile, token));
830       return;
831     }
832
833   if (CPP_PEDANTIC (pfile) && (new_lineno == 0 || new_lineno > cap))
834     cpp_error (pfile, DL_PEDWARN, "line number out of range");
835
836   token = cpp_get_token (pfile);
837   if (token->type == CPP_STRING)
838     {
839       new_file = (const char *) dequote_string (pfile, token->val.str.text,
840                                                 token->val.str.len);
841       check_eol (pfile);
842     }
843   else if (token->type != CPP_EOF)
844     {
845       cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
846                  cpp_token_as_text (pfile, token));
847       return;
848     }
849
850   skip_rest_of_line (pfile);
851   _cpp_do_file_change (pfile, LC_RENAME, new_file, new_lineno,
852                        pfile->map->sysp);
853 }
854
855 /* Interpret the # 44 "file" [flags] notation, which has slightly
856    different syntax and semantics from #line:  Flags are allowed,
857    and we never complain about the line number being too big.  */
858 static void
859 do_linemarker (pfile)
860      cpp_reader *pfile;
861 {
862   const cpp_token *token;
863   const char *new_file = pfile->map->to_file;
864   unsigned long new_lineno;
865   unsigned int new_sysp = pfile->map->sysp;
866   enum lc_reason reason = LC_RENAME;
867   int flag;
868
869   /* Back up so we can get the number again.  Putting this in
870      _cpp_handle_directive risks two calls to _cpp_backup_tokens in
871      some circumstances, which can segfault.  */
872   _cpp_backup_tokens (pfile, 1);
873
874   /* #line commands expand macros.  */
875   token = cpp_get_token (pfile);
876   if (token->type != CPP_NUMBER
877       || strtoul_for_line (token->val.str.text, token->val.str.len,
878                            &new_lineno))
879     {
880       cpp_error (pfile, DL_ERROR, "\"%s\" after # is not a positive integer",
881                  cpp_token_as_text (pfile, token));
882       return;
883     }
884
885   token = cpp_get_token (pfile);
886   if (token->type == CPP_STRING)
887     {
888       new_file = (const char *) dequote_string (pfile, token->val.str.text,
889                                                 token->val.str.len);
890       new_sysp = 0;
891       flag = read_flag (pfile, 0);
892       if (flag == 1)
893         {
894           reason = LC_ENTER;
895           /* Fake an include for cpp_included ().  */
896           _cpp_fake_include (pfile, new_file);
897           flag = read_flag (pfile, flag);
898         }
899       else if (flag == 2)
900         {
901           reason = LC_LEAVE;
902           flag = read_flag (pfile, flag);
903         }
904       if (flag == 3)
905         {
906           new_sysp = 1;
907           flag = read_flag (pfile, flag);
908           if (flag == 4)
909             new_sysp = 2;
910         }
911
912       check_eol (pfile);
913     }
914   else if (token->type != CPP_EOF)
915     {
916       cpp_error (pfile, DL_ERROR, "\"%s\" is not a valid filename",
917                  cpp_token_as_text (pfile, token));
918       return;
919     }
920
921   skip_rest_of_line (pfile);
922   _cpp_do_file_change (pfile, reason, new_file, new_lineno, new_sysp);
923 }
924
925 /* Arrange the file_change callback.  pfile->line has changed to
926    FILE_LINE of TO_FILE, for reason REASON.  SYSP is 1 for a system
927    header, 2 for a system header that needs to be extern "C" protected,
928    and zero otherwise.  */
929 void
930 _cpp_do_file_change (pfile, reason, to_file, file_line, sysp)
931      cpp_reader *pfile;
932      enum lc_reason reason;
933      const char *to_file;
934      unsigned int file_line;
935      unsigned int sysp;
936 {
937   pfile->map = add_line_map (&pfile->line_maps, reason, sysp,
938                              pfile->line, to_file, file_line);
939
940   if (pfile->cb.file_change)
941     (*pfile->cb.file_change) (pfile, pfile->map);
942 }
943
944 /* Report a warning or error detected by the program we are
945    processing.  Use the directive's tokens in the error message.  */
946 static void
947 do_diagnostic (pfile, code, print_dir)
948      cpp_reader *pfile;
949      int code;
950      int print_dir;
951 {
952   if (_cpp_begin_message (pfile, code,
953                           pfile->cur_token[-1].line,
954                           pfile->cur_token[-1].col))
955     {
956       if (print_dir)
957         fprintf (stderr, "#%s ", pfile->directive->name);
958       pfile->state.prevent_expansion++;
959       cpp_output_line (pfile, stderr);
960       pfile->state.prevent_expansion--;
961     }
962 }
963
964 static void
965 do_error (pfile)
966      cpp_reader *pfile;
967 {
968   do_diagnostic (pfile, DL_ERROR, 1);
969 }
970
971 static void
972 do_warning (pfile)
973      cpp_reader *pfile;
974 {
975   /* We want #warning diagnostics to be emitted in system headers too.  */
976   do_diagnostic (pfile, DL_WARNING_SYSHDR, 1);
977 }
978
979 /* Report program identification.  */
980 static void
981 do_ident (pfile)
982      cpp_reader *pfile;
983 {
984   const cpp_token *str = cpp_get_token (pfile);
985
986   if (str->type != CPP_STRING)
987     cpp_error (pfile, DL_ERROR, "invalid #ident directive");
988   else if (pfile->cb.ident)
989     (*pfile->cb.ident) (pfile, pfile->directive_line, &str->val.str);
990
991   check_eol (pfile);
992 }
993
994 /* Lookup a PRAGMA name in a singly-linked CHAIN.  Returns the
995    matching entry, or NULL if none is found.  The returned entry could
996    be the start of a namespace chain, or a pragma.  */
997 static struct pragma_entry *
998 lookup_pragma_entry (chain, pragma)
999      struct pragma_entry *chain;
1000      const cpp_hashnode *pragma;
1001 {
1002   while (chain && chain->pragma != pragma)
1003     chain = chain->next;
1004
1005   return chain;
1006 }
1007
1008 /* Create and insert a pragma entry for NAME at the beginning of a
1009    singly-linked CHAIN.  If handler is NULL, it is a namespace,
1010    otherwise it is a pragma and its handler.  */
1011 static struct pragma_entry *
1012 insert_pragma_entry (pfile, chain, pragma, handler)
1013      cpp_reader *pfile;
1014      struct pragma_entry **chain;
1015      const cpp_hashnode *pragma;
1016      pragma_cb handler;
1017 {
1018   struct pragma_entry *new;
1019
1020   new = (struct pragma_entry *)
1021     _cpp_aligned_alloc (pfile, sizeof (struct pragma_entry));
1022   new->pragma = pragma;
1023   if (handler)
1024     {
1025       new->is_nspace = 0;
1026       new->u.handler = handler;
1027     }
1028   else
1029     {
1030       new->is_nspace = 1;
1031       new->u.space = NULL;
1032     }
1033
1034   new->next = *chain;
1035   *chain = new;
1036   return new;
1037 }
1038
1039 /* Register a pragma NAME in namespace SPACE.  If SPACE is null, it
1040    goes in the global namespace.  HANDLER is the handler it will call,
1041    which must be non-NULL.  */
1042 void
1043 cpp_register_pragma (pfile, space, name, handler)
1044      cpp_reader *pfile;
1045      const char *space;
1046      const char *name;
1047      pragma_cb handler;
1048 {
1049   struct pragma_entry **chain = &pfile->pragmas;
1050   struct pragma_entry *entry;
1051   const cpp_hashnode *node;
1052
1053   if (!handler)
1054     abort ();
1055
1056   if (space)
1057     {
1058       node = cpp_lookup (pfile, U space, strlen (space));
1059       entry = lookup_pragma_entry (*chain, node);
1060       if (!entry)
1061         entry = insert_pragma_entry (pfile, chain, node, NULL);
1062       else if (!entry->is_nspace)
1063         goto clash;
1064       chain = &entry->u.space;
1065     }
1066
1067   /* Check for duplicates.  */
1068   node = cpp_lookup (pfile, U name, strlen (name));
1069   entry = lookup_pragma_entry (*chain, node);
1070   if (entry)
1071     {
1072       if (entry->is_nspace)
1073         clash:
1074         cpp_error (pfile, DL_ICE,
1075                  "registering \"%s\" as both a pragma and a pragma namespace",
1076                  NODE_NAME (node));
1077       else if (space)
1078         cpp_error (pfile, DL_ICE, "#pragma %s %s is already registered",
1079                    space, name);
1080       else
1081         cpp_error (pfile, DL_ICE, "#pragma %s is already registered", name);
1082     }
1083   else
1084     insert_pragma_entry (pfile, chain, node, handler);
1085 }
1086
1087 /* Register the pragmas the preprocessor itself handles.  */
1088 void
1089 _cpp_init_internal_pragmas (pfile)
1090      cpp_reader *pfile;
1091 {
1092   /* Pragmas in the global namespace.  */
1093   cpp_register_pragma (pfile, 0, "once", do_pragma_once);
1094
1095   /* New GCC-specific pragmas should be put in the GCC namespace.  */
1096   cpp_register_pragma (pfile, "GCC", "poison", do_pragma_poison);
1097   cpp_register_pragma (pfile, "GCC", "system_header", do_pragma_system_header);
1098   cpp_register_pragma (pfile, "GCC", "dependency", do_pragma_dependency);
1099 }
1100
1101 /* Pragmata handling.  We handle some, and pass the rest on to the
1102    front end.  C99 defines three pragmas and says that no macro
1103    expansion is to be performed on them; whether or not macro
1104    expansion happens for other pragmas is implementation defined.
1105    This implementation never macro-expands the text after #pragma.  */
1106 static void
1107 do_pragma (pfile)
1108      cpp_reader *pfile;
1109 {
1110   const struct pragma_entry *p = NULL;
1111   const cpp_token *token;
1112   unsigned int count = 1;
1113
1114   pfile->state.prevent_expansion++;
1115
1116   token = cpp_get_token (pfile);
1117   if (token->type == CPP_NAME)
1118     {
1119       p = lookup_pragma_entry (pfile->pragmas, token->val.node);
1120       if (p && p->is_nspace)
1121         {
1122           count = 2;
1123           token = cpp_get_token (pfile);
1124           if (token->type == CPP_NAME)
1125             p = lookup_pragma_entry (p->u.space, token->val.node);
1126           else
1127             p = NULL;
1128         }
1129     }
1130
1131   /* FIXME.  This is an awful kludge to get the front ends to update
1132      their notion of line number for diagnostic purposes.  The line
1133      number should be passed to the handler and they should do it
1134      themselves.  Stand-alone CPP must ignore us, otherwise it will
1135      prefix the directive with spaces, hence the 1.  Ugh.  */
1136   if (pfile->cb.line_change)
1137     (*pfile->cb.line_change)(pfile, token, 1);
1138
1139   if (p)
1140     (*p->u.handler) (pfile);
1141   else if (pfile->cb.def_pragma)
1142     {
1143       _cpp_backup_tokens (pfile, count);
1144       (*pfile->cb.def_pragma) (pfile, pfile->directive_line);
1145     }
1146
1147   pfile->state.prevent_expansion--;
1148 }
1149
1150 /* Handle #pragma once.  */
1151 static void
1152 do_pragma_once (pfile)
1153      cpp_reader *pfile;
1154 {
1155   cpp_error (pfile, DL_WARNING, "#pragma once is obsolete");
1156
1157   if (pfile->buffer->prev == NULL)
1158     cpp_error (pfile, DL_WARNING, "#pragma once in main file");
1159   else
1160     _cpp_never_reread (pfile->buffer->inc);
1161
1162   check_eol (pfile);
1163 }
1164
1165 /* Handle #pragma GCC poison, to poison one or more identifiers so
1166    that the lexer produces a hard error for each subsequent usage.  */
1167 static void
1168 do_pragma_poison (pfile)
1169      cpp_reader *pfile;
1170 {
1171   const cpp_token *tok;
1172   cpp_hashnode *hp;
1173
1174   pfile->state.poisoned_ok = 1;
1175   for (;;)
1176     {
1177       tok = _cpp_lex_token (pfile);
1178       if (tok->type == CPP_EOF)
1179         break;
1180       if (tok->type != CPP_NAME)
1181         {
1182           cpp_error (pfile, DL_ERROR, "invalid #pragma GCC poison directive");
1183           break;
1184         }
1185
1186       hp = tok->val.node;
1187       if (hp->flags & NODE_POISONED)
1188         continue;
1189
1190       if (hp->type == NT_MACRO)
1191         cpp_error (pfile, DL_WARNING, "poisoning existing macro \"%s\"",
1192                    NODE_NAME (hp));
1193       _cpp_free_definition (hp);
1194       hp->flags |= NODE_POISONED | NODE_DIAGNOSTIC;
1195     }
1196   pfile->state.poisoned_ok = 0;
1197 }
1198
1199 /* Mark the current header as a system header.  This will suppress
1200    some categories of warnings (notably those from -pedantic).  It is
1201    intended for use in system libraries that cannot be implemented in
1202    conforming C, but cannot be certain that their headers appear in a
1203    system include directory.  To prevent abuse, it is rejected in the
1204    primary source file.  */
1205 static void
1206 do_pragma_system_header (pfile)
1207      cpp_reader *pfile;
1208 {
1209   cpp_buffer *buffer = pfile->buffer;
1210
1211   if (buffer->prev == 0)
1212     cpp_error (pfile, DL_WARNING,
1213                "#pragma system_header ignored outside include file");
1214   else
1215     {
1216       check_eol (pfile);
1217       skip_rest_of_line (pfile);
1218       cpp_make_system_header (pfile, 1, 0);
1219     }
1220 }
1221
1222 /* Check the modified date of the current include file against a specified
1223    file. Issue a diagnostic, if the specified file is newer. We use this to
1224    determine if a fixed header should be refixed.  */
1225 static void
1226 do_pragma_dependency (pfile)
1227      cpp_reader *pfile;
1228 {
1229   const cpp_token *header;
1230   int ordering;
1231
1232   header = parse_include (pfile);
1233   if (!header)
1234     return;
1235
1236   ordering = _cpp_compare_file_date (pfile, header);
1237   if (ordering < 0)
1238     cpp_error (pfile, DL_WARNING, "cannot find source %s",
1239                cpp_token_as_text (pfile, header));
1240   else if (ordering > 0)
1241     {
1242       cpp_error (pfile, DL_WARNING, "current file is older than %s",
1243                  cpp_token_as_text (pfile, header));
1244       if (cpp_get_token (pfile)->type != CPP_EOF)
1245         {
1246           _cpp_backup_tokens (pfile, 1);
1247           do_diagnostic (pfile, DL_WARNING, 0);
1248         }
1249     }
1250 }
1251
1252 /* Get a token but skip padding.  */
1253 static const cpp_token *
1254 get_token_no_padding (pfile)
1255      cpp_reader *pfile;
1256 {
1257   for (;;)
1258     {
1259       const cpp_token *result = cpp_get_token (pfile);
1260       if (result->type != CPP_PADDING)
1261         return result;
1262     }
1263 }
1264
1265 /* Check syntax is "(string-literal)".  Returns the string on success,
1266    or NULL on failure.  */
1267 static const cpp_token *
1268 get__Pragma_string (pfile)
1269      cpp_reader *pfile;
1270 {
1271   const cpp_token *string;
1272
1273   if (get_token_no_padding (pfile)->type != CPP_OPEN_PAREN)
1274     return NULL;
1275
1276   string = get_token_no_padding (pfile);
1277   if (string->type != CPP_STRING && string->type != CPP_WSTRING)
1278     return NULL;
1279
1280   if (get_token_no_padding (pfile)->type != CPP_CLOSE_PAREN)
1281     return NULL;
1282
1283   return string;
1284 }
1285
1286 /* Destringize IN into a temporary buffer, by removing the first \ of
1287    \" and \\ sequences, and process the result as a #pragma directive.  */
1288 static void
1289 destringize_and_run (pfile, in)
1290      cpp_reader *pfile;
1291      const cpp_string *in;
1292 {
1293   const unsigned char *src, *limit;
1294   char *dest, *result;
1295
1296   dest = result = alloca (in->len + 1);
1297   for (src = in->text, limit = src + in->len; src < limit;)
1298     {
1299       /* We know there is a character following the backslash.  */
1300       if (*src == '\\' && (src[1] == '\\' || src[1] == '"'))
1301         src++;
1302       *dest++ = *src++;
1303     }
1304   *dest = '\0';
1305
1306   run_directive (pfile, T_PRAGMA, result, dest - result);
1307 }
1308
1309 /* Handle the _Pragma operator.  */
1310 void
1311 _cpp_do__Pragma (pfile)
1312      cpp_reader *pfile;
1313 {
1314   const cpp_token *string = get__Pragma_string (pfile);
1315
1316   if (!string)
1317     cpp_error (pfile, DL_ERROR,
1318                "_Pragma takes a parenthesized string literal");
1319   else
1320     {
1321       /* Ideally, we'd like
1322                         token1 _Pragma ("foo") token2
1323          to be output as
1324                         token1
1325                         # 7 "file.c"
1326                         #pragma foo
1327                         # 7 "file.c"
1328                                                token2
1329          Getting these correct line markers is a little tricky.  */
1330
1331       unsigned int orig_line = pfile->line;
1332       destringize_and_run (pfile, &string->val.str);
1333       pfile->line = orig_line;
1334       pfile->buffer->saved_flags = BOL;
1335     }
1336 }
1337
1338 /* Just ignore #sccs, on systems where we define it at all.  */
1339 #ifdef SCCS_DIRECTIVE
1340 static void
1341 do_sccs (pfile)
1342      cpp_reader *pfile ATTRIBUTE_UNUSED;
1343 {
1344 }
1345 #endif
1346
1347 /* Handle #ifdef.  */
1348 static void
1349 do_ifdef (pfile)
1350      cpp_reader *pfile;
1351 {
1352   int skip = 1;
1353
1354   if (! pfile->state.skipping)
1355     {
1356       const cpp_hashnode *node = lex_macro_node (pfile);
1357
1358       if (node)
1359         skip = node->type != NT_MACRO;
1360
1361       if (node)
1362         check_eol (pfile);
1363     }
1364
1365   push_conditional (pfile, skip, T_IFDEF, 0);
1366 }
1367
1368 /* Handle #ifndef.  */
1369 static void
1370 do_ifndef (pfile)
1371      cpp_reader *pfile;
1372 {
1373   int skip = 1;
1374   const cpp_hashnode *node = 0;
1375
1376   if (! pfile->state.skipping)
1377     {
1378       node = lex_macro_node (pfile);
1379       if (node)
1380         skip = node->type == NT_MACRO;
1381
1382       if (node)
1383         check_eol (pfile);
1384     }
1385
1386   push_conditional (pfile, skip, T_IFNDEF, node);
1387 }
1388
1389 /* _cpp_parse_expr puts a macro in a "#if !defined ()" expression in
1390    pfile->mi_ind_cmacro so we can handle multiple-include
1391    optimisations.  If macro expansion occurs in the expression, we
1392    cannot treat it as a controlling conditional, since the expansion
1393    could change in the future.  That is handled by cpp_get_token.  */
1394 static void
1395 do_if (pfile)
1396      cpp_reader *pfile;
1397 {
1398   int skip = 1;
1399
1400   if (! pfile->state.skipping)
1401     skip = _cpp_parse_expr (pfile) == false;
1402
1403   push_conditional (pfile, skip, T_IF, pfile->mi_ind_cmacro);
1404 }
1405
1406 /* Flip skipping state if appropriate and continue without changing
1407    if_stack; this is so that the error message for missing #endif's
1408    etc. will point to the original #if.  */
1409 static void
1410 do_else (pfile)
1411      cpp_reader *pfile;
1412 {
1413   cpp_buffer *buffer = pfile->buffer;
1414   struct if_stack *ifs = buffer->if_stack;
1415
1416   if (ifs == NULL)
1417     cpp_error (pfile, DL_ERROR, "#else without #if");
1418   else
1419     {
1420       if (ifs->type == T_ELSE)
1421         {
1422           cpp_error (pfile, DL_ERROR, "#else after #else");
1423           cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1424                                "the conditional began here");
1425         }
1426       ifs->type = T_ELSE;
1427
1428       /* Skip any future (erroneous) #elses or #elifs.  */
1429       pfile->state.skipping = ifs->skip_elses;
1430       ifs->skip_elses = true;
1431
1432       /* Invalidate any controlling macro.  */
1433       ifs->mi_cmacro = 0;
1434
1435       /* Only check EOL if was not originally skipping.  */
1436       if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1437         check_eol (pfile);
1438     }
1439 }
1440
1441 /* Handle a #elif directive by not changing if_stack either.  See the
1442    comment above do_else.  */
1443 static void
1444 do_elif (pfile)
1445      cpp_reader *pfile;
1446 {
1447   cpp_buffer *buffer = pfile->buffer;
1448   struct if_stack *ifs = buffer->if_stack;
1449
1450   if (ifs == NULL)
1451     cpp_error (pfile, DL_ERROR, "#elif without #if");
1452   else
1453     {
1454       if (ifs->type == T_ELSE)
1455         {
1456           cpp_error (pfile, DL_ERROR, "#elif after #else");
1457           cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1458                                "the conditional began here");
1459         }
1460       ifs->type = T_ELIF;
1461
1462       /* Only evaluate this if we aren't skipping elses.  During
1463          evaluation, set skipping to false to get lexer warnings.  */
1464       if (ifs->skip_elses)
1465         pfile->state.skipping = 1;
1466       else
1467         {
1468           pfile->state.skipping = 0;
1469           pfile->state.skipping = ! _cpp_parse_expr (pfile);
1470           ifs->skip_elses = ! pfile->state.skipping;
1471         }
1472
1473       /* Invalidate any controlling macro.  */
1474       ifs->mi_cmacro = 0;
1475     }
1476 }
1477
1478 /* #endif pops the if stack and resets pfile->state.skipping.  */
1479 static void
1480 do_endif (pfile)
1481      cpp_reader *pfile;
1482 {
1483   cpp_buffer *buffer = pfile->buffer;
1484   struct if_stack *ifs = buffer->if_stack;
1485
1486   if (ifs == NULL)
1487     cpp_error (pfile, DL_ERROR, "#endif without #if");
1488   else
1489     {
1490       /* Only check EOL if was not originally skipping.  */
1491       if (!ifs->was_skipping && CPP_OPTION (pfile, warn_endif_labels))
1492         check_eol (pfile);
1493
1494       /* If potential control macro, we go back outside again.  */
1495       if (ifs->next == 0 && ifs->mi_cmacro)
1496         {
1497           pfile->mi_valid = true;
1498           pfile->mi_cmacro = ifs->mi_cmacro;
1499         }
1500
1501       buffer->if_stack = ifs->next;
1502       pfile->state.skipping = ifs->was_skipping;
1503       obstack_free (&pfile->buffer_ob, ifs);
1504     }
1505 }
1506
1507 /* Push an if_stack entry for a preprocessor conditional, and set
1508    pfile->state.skipping to SKIP.  If TYPE indicates the conditional
1509    is #if or #ifndef, CMACRO is a potentially controlling macro, and
1510    we need to check here that we are at the top of the file.  */
1511 static void
1512 push_conditional (pfile, skip, type, cmacro)
1513      cpp_reader *pfile;
1514      int skip;
1515      int type;
1516      const cpp_hashnode *cmacro;
1517 {
1518   struct if_stack *ifs;
1519   cpp_buffer *buffer = pfile->buffer;
1520
1521   ifs = xobnew (&pfile->buffer_ob, struct if_stack);
1522   ifs->line = pfile->directive_line;
1523   ifs->next = buffer->if_stack;
1524   ifs->skip_elses = pfile->state.skipping || !skip;
1525   ifs->was_skipping = pfile->state.skipping;
1526   ifs->type = type;
1527   /* This condition is effectively a test for top-of-file.  */
1528   if (pfile->mi_valid && pfile->mi_cmacro == 0)
1529     ifs->mi_cmacro = cmacro;
1530   else
1531     ifs->mi_cmacro = 0;
1532
1533   pfile->state.skipping = skip;
1534   buffer->if_stack = ifs;
1535 }
1536
1537 /* Read the tokens of the answer into the macro pool, in a directive
1538    of type TYPE.  Only commit the memory if we intend it as permanent
1539    storage, i.e. the #assert case.  Returns 0 on success, and sets
1540    ANSWERP to point to the answer.  */
1541 static int
1542 parse_answer (pfile, answerp, type)
1543      cpp_reader *pfile;
1544      struct answer **answerp;
1545      int type;
1546 {
1547   const cpp_token *paren;
1548   struct answer *answer;
1549   unsigned int acount;
1550
1551   /* In a conditional, it is legal to not have an open paren.  We
1552      should save the following token in this case.  */
1553   paren = cpp_get_token (pfile);
1554
1555   /* If not a paren, see if we're OK.  */
1556   if (paren->type != CPP_OPEN_PAREN)
1557     {
1558       /* In a conditional no answer is a test for any answer.  It
1559          could be followed by any token.  */
1560       if (type == T_IF)
1561         {
1562           _cpp_backup_tokens (pfile, 1);
1563           return 0;
1564         }
1565
1566       /* #unassert with no answer is valid - it removes all answers.  */
1567       if (type == T_UNASSERT && paren->type == CPP_EOF)
1568         return 0;
1569
1570       cpp_error (pfile, DL_ERROR, "missing '(' after predicate");
1571       return 1;
1572     }
1573
1574   for (acount = 0;; acount++)
1575     {
1576       size_t room_needed;
1577       const cpp_token *token = cpp_get_token (pfile);
1578       cpp_token *dest;
1579
1580       if (token->type == CPP_CLOSE_PAREN)
1581         break;
1582
1583       if (token->type == CPP_EOF)
1584         {
1585           cpp_error (pfile, DL_ERROR, "missing ')' to complete answer");
1586           return 1;
1587         }
1588
1589       /* struct answer includes the space for one token.  */
1590       room_needed = (sizeof (struct answer) + acount * sizeof (cpp_token));
1591
1592       if (BUFF_ROOM (pfile->a_buff) < room_needed)
1593         _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (struct answer));
1594
1595       dest = &((struct answer *) BUFF_FRONT (pfile->a_buff))->first[acount];
1596       *dest = *token;
1597
1598       /* Drop whitespace at start, for answer equivalence purposes.  */
1599       if (acount == 0)
1600         dest->flags &= ~PREV_WHITE;
1601     }
1602
1603   if (acount == 0)
1604     {
1605       cpp_error (pfile, DL_ERROR, "predicate's answer is empty");
1606       return 1;
1607     }
1608
1609   answer = (struct answer *) BUFF_FRONT (pfile->a_buff);
1610   answer->count = acount;
1611   answer->next = NULL;
1612   *answerp = answer;
1613
1614   return 0;
1615 }
1616
1617 /* Parses an assertion directive of type TYPE, returning a pointer to
1618    the hash node of the predicate, or 0 on error.  If an answer was
1619    supplied, it is placed in ANSWERP, otherwise it is set to 0.  */
1620 static cpp_hashnode *
1621 parse_assertion (pfile, answerp, type)
1622      cpp_reader *pfile;
1623      struct answer **answerp;
1624      int type;
1625 {
1626   cpp_hashnode *result = 0;
1627   const cpp_token *predicate;
1628
1629   /* We don't expand predicates or answers.  */
1630   pfile->state.prevent_expansion++;
1631
1632   *answerp = 0;
1633   predicate = cpp_get_token (pfile);
1634   if (predicate->type == CPP_EOF)
1635     cpp_error (pfile, DL_ERROR, "assertion without predicate");
1636   else if (predicate->type != CPP_NAME)
1637     cpp_error (pfile, DL_ERROR, "predicate must be an identifier");
1638   else if (parse_answer (pfile, answerp, type) == 0)
1639     {
1640       unsigned int len = NODE_LEN (predicate->val.node);
1641       unsigned char *sym = alloca (len + 1);
1642
1643       /* Prefix '#' to get it out of macro namespace.  */
1644       sym[0] = '#';
1645       memcpy (sym + 1, NODE_NAME (predicate->val.node), len);
1646       result = cpp_lookup (pfile, sym, len + 1);
1647     }
1648
1649   pfile->state.prevent_expansion--;
1650   return result;
1651 }
1652
1653 /* Returns a pointer to the pointer to CANDIDATE in the answer chain,
1654    or a pointer to NULL if the answer is not in the chain.  */
1655 static struct answer **
1656 find_answer (node, candidate)
1657      cpp_hashnode *node;
1658      const struct answer *candidate;
1659 {
1660   unsigned int i;
1661   struct answer **result;
1662
1663   for (result = &node->value.answers; *result; result = &(*result)->next)
1664     {
1665       struct answer *answer = *result;
1666
1667       if (answer->count == candidate->count)
1668         {
1669           for (i = 0; i < answer->count; i++)
1670             if (! _cpp_equiv_tokens (&answer->first[i], &candidate->first[i]))
1671               break;
1672
1673           if (i == answer->count)
1674             break;
1675         }
1676     }
1677
1678   return result;
1679 }
1680
1681 /* Test an assertion within a preprocessor conditional.  Returns
1682    non-zero on failure, zero on success.  On success, the result of
1683    the test is written into VALUE.  */
1684 int
1685 _cpp_test_assertion (pfile, value)
1686      cpp_reader *pfile;
1687      unsigned int *value;
1688 {
1689   struct answer *answer;
1690   cpp_hashnode *node;
1691
1692   node = parse_assertion (pfile, &answer, T_IF);
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);
1698
1699   /* We don't commit the memory for the answer - it's temporary only.  */
1700   return node == 0;
1701 }
1702
1703 /* Handle #assert.  */
1704 static void
1705 do_assert (pfile)
1706      cpp_reader *pfile;
1707 {
1708   struct answer *new_answer;
1709   cpp_hashnode *node;
1710
1711   node = parse_assertion (pfile, &new_answer, T_ASSERT);
1712   if (node)
1713     {
1714       /* Place the new answer in the answer list.  First check there
1715          is not a duplicate.  */
1716       new_answer->next = 0;
1717       if (node->type == NT_ASSERTION)
1718         {
1719           if (*find_answer (node, new_answer))
1720             {
1721               cpp_error (pfile, DL_WARNING, "\"%s\" re-asserted",
1722                          NODE_NAME (node) + 1);
1723               return;
1724             }
1725           new_answer->next = node->value.answers;
1726         }
1727
1728       node->type = NT_ASSERTION;
1729       node->value.answers = new_answer;
1730       BUFF_FRONT (pfile->a_buff) += (sizeof (struct answer)
1731                                      + (new_answer->count - 1)
1732                                      * sizeof (cpp_token));
1733       check_eol (pfile);
1734     }
1735 }
1736
1737 /* Handle #unassert.  */
1738 static void
1739 do_unassert (pfile)
1740      cpp_reader *pfile;
1741 {
1742   cpp_hashnode *node;
1743   struct answer *answer;
1744
1745   node = parse_assertion (pfile, &answer, T_UNASSERT);
1746   /* It isn't an error to #unassert something that isn't asserted.  */
1747   if (node && node->type == NT_ASSERTION)
1748     {
1749       if (answer)
1750         {
1751           struct answer **p = find_answer (node, answer), *temp;
1752
1753           /* Remove the answer from the list.  */
1754           temp = *p;
1755           if (temp)
1756             *p = temp->next;
1757
1758           /* Did we free the last answer?  */
1759           if (node->value.answers == 0)
1760             node->type = NT_VOID;
1761
1762           check_eol (pfile);
1763         }
1764       else
1765         _cpp_free_definition (node);
1766     }
1767
1768   /* We don't commit the memory for the answer - it's temporary only.  */
1769 }
1770
1771 /* These are for -D, -U, -A.  */
1772
1773 /* Process the string STR as if it appeared as the body of a #define.
1774    If STR is just an identifier, define it with value 1.
1775    If STR has anything after the identifier, then it should
1776    be identifier=definition.  */
1777 void
1778 cpp_define (pfile, str)
1779      cpp_reader *pfile;
1780      const char *str;
1781 {
1782   char *buf, *p;
1783   size_t count;
1784
1785   /* Copy the entire option so we can modify it.
1786      Change the first "=" in the string to a space.  If there is none,
1787      tack " 1" on the end.  */
1788
1789   count = strlen (str);
1790   buf = (char *) alloca (count + 3);
1791   memcpy (buf, str, count);
1792
1793   p = strchr (str, '=');
1794   if (p)
1795     buf[p - str] = ' ';
1796   else
1797     {
1798       buf[count++] = ' ';
1799       buf[count++] = '1';
1800     }
1801   buf[count] = '\0';
1802
1803   run_directive (pfile, T_DEFINE, buf, count);
1804 }
1805
1806 /* Slight variant of the above for use by initialize_builtins.  */
1807 void
1808 _cpp_define_builtin (pfile, str)
1809      cpp_reader *pfile;
1810      const char *str;
1811 {
1812   run_directive (pfile, T_DEFINE, str, strlen (str));
1813 }
1814
1815 /* Process MACRO as if it appeared as the body of an #undef.  */
1816 void
1817 cpp_undef (pfile, macro)
1818      cpp_reader *pfile;
1819      const char *macro;
1820 {
1821   run_directive (pfile, T_UNDEF, macro, strlen (macro));
1822 }
1823
1824 /* Process the string STR as if it appeared as the body of a #assert.  */
1825 void
1826 cpp_assert (pfile, str)
1827      cpp_reader *pfile;
1828      const char *str;
1829 {
1830   handle_assertion (pfile, str, T_ASSERT);
1831 }
1832
1833 /* Process STR as if it appeared as the body of an #unassert.  */
1834 void
1835 cpp_unassert (pfile, str)
1836      cpp_reader *pfile;
1837      const char *str;
1838 {
1839   handle_assertion (pfile, str, T_UNASSERT);
1840 }
1841
1842 /* Common code for cpp_assert (-A) and cpp_unassert (-A-).  */
1843 static void
1844 handle_assertion (pfile, str, type)
1845      cpp_reader *pfile;
1846      const char *str;
1847      int type;
1848 {
1849   size_t count = strlen (str);
1850   const char *p = strchr (str, '=');
1851
1852   if (p)
1853     {
1854       /* Copy the entire option so we can modify it.  Change the first
1855          "=" in the string to a '(', and tack a ')' on the end.  */
1856       char *buf = (char *) alloca (count + 2);
1857
1858       memcpy (buf, str, count);
1859       buf[p - str] = '(';
1860       buf[count++] = ')';
1861       buf[count] = '\0';
1862       str = buf;
1863     }
1864
1865   run_directive (pfile, type, str, count);
1866 }
1867
1868 /* The number of errors for a given reader.  */
1869 unsigned int
1870 cpp_errors (pfile)
1871      cpp_reader *pfile;
1872 {
1873   return pfile->errors;
1874 }
1875
1876 /* The options structure.  */
1877 cpp_options *
1878 cpp_get_options (pfile)
1879      cpp_reader *pfile;
1880 {
1881   return &pfile->opts;
1882 }
1883
1884 /* The callbacks structure.  */
1885 cpp_callbacks *
1886 cpp_get_callbacks (pfile)
1887      cpp_reader *pfile;
1888 {
1889   return &pfile->cb;
1890 }
1891
1892 /* The line map set.  */
1893 const struct line_maps *
1894 cpp_get_line_maps (pfile)
1895      cpp_reader *pfile;
1896 {
1897   return &pfile->line_maps;
1898 }
1899
1900 /* Copy the given callbacks structure to our own.  */
1901 void
1902 cpp_set_callbacks (pfile, cb)
1903      cpp_reader *pfile;
1904      cpp_callbacks *cb;
1905 {
1906   pfile->cb = *cb;
1907 }
1908
1909 /* Push a new buffer on the buffer stack.  Returns the new buffer; it
1910    doesn't fail.  It does not generate a file change call back; that
1911    is the responsibility of the caller.  */
1912 cpp_buffer *
1913 cpp_push_buffer (pfile, buffer, len, from_stage3, return_at_eof)
1914      cpp_reader *pfile;
1915      const uchar *buffer;
1916      size_t len;
1917      int from_stage3;
1918      int return_at_eof;
1919 {
1920   cpp_buffer *new = xobnew (&pfile->buffer_ob, cpp_buffer);
1921
1922   /* Clears, amongst other things, if_stack and mi_cmacro.  */
1923   memset (new, 0, sizeof (cpp_buffer));
1924
1925   new->line_base = new->buf = new->cur = buffer;
1926   new->rlimit = buffer + len;
1927   new->from_stage3 = from_stage3 || CPP_OPTION (pfile, traditional);
1928   new->prev = pfile->buffer;
1929   new->return_at_eof = return_at_eof;
1930   new->saved_flags = BOL;
1931
1932   pfile->buffer = new;
1933
1934   if (CPP_OPTION (pfile, traditional))
1935     _cpp_set_trad_context (pfile);
1936
1937   return new;
1938 }
1939
1940 /* Pops a single buffer, with a file change call-back if appropriate.
1941    Then pushes the next -include file, if any remain.  */
1942 void
1943 _cpp_pop_buffer (pfile)
1944      cpp_reader *pfile;
1945 {
1946   cpp_buffer *buffer = pfile->buffer;
1947   struct include_file *inc = buffer->inc;
1948   struct if_stack *ifs;
1949
1950   /* Walk back up the conditional stack till we reach its level at
1951      entry to this file, issuing error messages.  */
1952   for (ifs = buffer->if_stack; ifs; ifs = ifs->next)
1953     cpp_error_with_line (pfile, DL_ERROR, ifs->line, 0,
1954                          "unterminated #%s", dtable[ifs->type].name);
1955
1956   /* In case of a missing #endif.  */
1957   pfile->state.skipping = 0;
1958
1959   /* _cpp_do_file_change expects pfile->buffer to be the new one.  */
1960   pfile->buffer = buffer->prev;
1961
1962   /* Free the buffer object now; we may want to push a new buffer
1963      in _cpp_push_next_include_file.  */
1964   obstack_free (&pfile->buffer_ob, buffer);
1965
1966   if (inc)
1967     {
1968       _cpp_pop_file_buffer (pfile, inc);
1969
1970       /* Don't generate a callback for popping the main file.  */
1971       if (pfile->buffer)
1972         {
1973           _cpp_do_file_change (pfile, LC_LEAVE, 0, 0, 0);
1974
1975           /* If this is the main file, there may be some -include
1976              files left to push.  */
1977           if (!pfile->buffer->prev)
1978             _cpp_maybe_push_include_file (pfile);
1979         }
1980     }
1981
1982   if (pfile->buffer && CPP_OPTION (pfile, traditional))
1983     _cpp_set_trad_context (pfile);
1984 }
1985
1986 /* Enter all recognised directives in the hash table.  */
1987 void
1988 _cpp_init_directives (pfile)
1989      cpp_reader *pfile;
1990 {
1991   unsigned int i;
1992   cpp_hashnode *node;
1993
1994   for (i = 0; i < (unsigned int) N_DIRECTIVES; i++)
1995     {
1996       node = cpp_lookup (pfile, dtable[i].name, dtable[i].length);
1997       node->directive_index = i + 1;
1998     }
1999 }