OSDN Git Service

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