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