OSDN Git Service

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