OSDN Git Service

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