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