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