OSDN Git Service

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