OSDN Git Service

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