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