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