OSDN Git Service

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