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