OSDN Git Service

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