OSDN Git Service

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