OSDN Git Service

* cpplex.c (cpp_scan_buffer): Output line command even at the stop
[pf3gnuchains/gcc-fork.git] / gcc / cpplex.c
1 /* CPP Library - lexical analysis.
2    Copyright (C) 2000 Free Software Foundation, Inc.
3    Contributed by Per Bothner, 1994-95.
4    Based on CCCP program by Paul Rubin, June 1986
5    Adapted to ANSI C, Richard Stallman, Jan 1987
6    Broken out to separate file, Zack Weinberg, Mar 2000
7    Single-pass line tokenization by Neil Booth, April 2000
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
22
23 /*
24
25 Cleanups to do:-
26
27 o -dM and with _cpp_dump_list: too many \n output.
28 o Put a printer object in cpp_reader?
29 o Check line numbers assigned to all errors.
30 o Replace strncmp with memcmp almost everywhere.
31 o lex_line's use of cur_token, flags and list->token_used is a bit opaque.
32 o Convert do_ functions to return void.  Kaveh thinks its OK; and said he'll
33   give it a run when we've got some code.
34 o Distinguish integers, floats, and 'other' pp-numbers.
35 o Store ints and char constants as binary values.
36 o New command-line assertion syntax.
37 o Work towards functions in cpperror.c taking a message level parameter.
38   If we do this, merge the common code of do_warning and do_error.
39 o Comment all functions, and describe macro expansion algorithm.
40 o Move as much out of header files as possible.
41 o Remove single quote pairs `', and some '', from diagnostics.
42 o Correct pastability test for CPP_NAME and CPP_NUMBER.
43
44 */
45
46 #include "config.h"
47 #include "system.h"
48 #include "intl.h"
49 #include "cpplib.h"
50 #include "cpphash.h"
51 #include "symcat.h"
52
53 static const cpp_token placemarker_token = {0, 0, CPP_PLACEMARKER, 0 UNION_INIT_ZERO};
54 static const cpp_token eof_token = {0, 0, CPP_EOF, 0 UNION_INIT_ZERO};
55
56 /* Flags for cpp_context.  */
57 #define CONTEXT_PASTEL  (1 << 0) /* An argument context on LHS of ##.  */
58 #define CONTEXT_PASTER  (1 << 1) /* An argument context on RHS of ##.  */
59 #define CONTEXT_RAW     (1 << 2) /* If argument tokens already expanded.  */
60 #define CONTEXT_ARG     (1 << 3) /* If an argument context.  */
61
62 typedef struct cpp_context cpp_context;
63 struct cpp_context
64 {
65   union
66   {
67     const cpp_toklist *list;    /* Used for macro contexts only.  */
68     const cpp_token **arg;      /* Used for arg contexts only.  */
69   } u;
70
71   /* Pushed token to be returned by next call to get_raw_token.  */
72   const cpp_token *pushed_token;
73
74   struct macro_args *args;      /* The arguments for a function-like
75                                    macro.  NULL otherwise.  */
76   unsigned short posn;          /* Current posn, index into u.  */
77   unsigned short count;         /* No. of tokens in u.  */
78   unsigned short level;
79   unsigned char flags;
80 };
81
82 typedef struct macro_args macro_args;
83 struct macro_args
84 {
85   unsigned int *ends;
86   const cpp_token **tokens;
87   unsigned int capacity;
88   unsigned int used;
89   unsigned short level;
90 };
91
92 static const cpp_token *get_raw_token PARAMS ((cpp_reader *));
93 static const cpp_token *parse_arg PARAMS ((cpp_reader *, int, unsigned int,
94                                            macro_args *, unsigned int *));
95 static int parse_args PARAMS ((cpp_reader *, cpp_hashnode *, macro_args *));
96 static void save_token PARAMS ((macro_args *, const cpp_token *));
97 static int pop_context PARAMS ((cpp_reader *));
98 static int push_macro_context PARAMS ((cpp_reader *, const cpp_token *));
99 static void push_arg_context PARAMS ((cpp_reader *, const cpp_token *));
100 static void free_macro_args PARAMS ((macro_args *));
101
102 #define auto_expand_name_space(list) \
103     _cpp_expand_name_space ((list), 1 + (list)->name_cap / 2)
104 static void safe_fwrite         PARAMS ((cpp_reader *, const U_CHAR *,
105                                          size_t, FILE *));
106 static void dump_param_spelling PARAMS ((cpp_reader *, const cpp_toklist *,
107                                          unsigned int));
108 static void output_line_command PARAMS ((cpp_reader *, cpp_printer *,
109                                          unsigned int));
110
111 static void process_directive   PARAMS ((cpp_reader *, const cpp_token *));
112 static unsigned char *trigraph_replace PARAMS ((cpp_reader *, unsigned char *,
113                                                 unsigned char *));
114 static const unsigned char *backslash_start PARAMS ((cpp_reader *,
115                                                      const unsigned char *));
116 static int skip_block_comment PARAMS ((cpp_reader *));
117 static int skip_line_comment PARAMS ((cpp_reader *));
118 static void adjust_column PARAMS ((cpp_reader *, const U_CHAR *));
119 static void skip_whitespace PARAMS ((cpp_reader *, int));
120 static const U_CHAR *parse_name PARAMS ((cpp_reader *, cpp_token *,
121                                    const U_CHAR *, const U_CHAR *));
122 static void parse_number PARAMS ((cpp_reader *, cpp_toklist *, cpp_string *));
123 static void parse_string PARAMS ((cpp_reader *, cpp_toklist *, cpp_token *,
124                                   unsigned int));
125 static int trigraph_ok PARAMS ((cpp_reader *, const unsigned char *));
126 static void save_comment PARAMS ((cpp_toklist *, cpp_token *,
127                                   const unsigned char *,
128                                   unsigned int, unsigned int));
129 static void lex_line PARAMS ((cpp_reader *, cpp_toklist *));
130 static int lex_next PARAMS ((cpp_reader *, int));
131 static int is_macro_disabled PARAMS ((cpp_reader *, const cpp_toklist *,
132                                       const cpp_token *));
133
134 static cpp_token *stringify_arg PARAMS ((cpp_reader *, const cpp_token *));
135 static void expand_context_stack PARAMS ((cpp_reader *));
136 static unsigned char * spell_token PARAMS ((cpp_reader *, const cpp_token *,
137                                             unsigned char *));
138 static void output_token PARAMS ((cpp_reader *, const cpp_token *,
139                                   const cpp_token *));
140 typedef unsigned int (* speller) PARAMS ((unsigned char *, cpp_toklist *,
141                                           cpp_token *));
142 static cpp_token *make_string_token PARAMS ((cpp_token *, const U_CHAR *,
143                                             unsigned int));
144 static cpp_token *alloc_number_token PARAMS ((cpp_reader *, int number));
145 static const cpp_token *special_symbol PARAMS ((cpp_reader *, cpp_hashnode *,
146                                                 const cpp_token *));
147 static cpp_token *duplicate_token PARAMS ((cpp_reader *, const cpp_token *));
148 static const cpp_token *maybe_paste_with_next PARAMS ((cpp_reader *,
149                                                        const cpp_token *));
150 static enum cpp_ttype can_paste PARAMS ((cpp_reader *, const cpp_token *,
151                                          const cpp_token *, int *));
152 static unsigned int prevent_macro_expansion     PARAMS ((cpp_reader *));
153 static void restore_macro_expansion     PARAMS ((cpp_reader *, unsigned int));
154 static cpp_token *get_temp_token        PARAMS ((cpp_reader *));
155 static void release_temp_tokens         PARAMS ((cpp_reader *));
156 static U_CHAR * quote_string PARAMS ((U_CHAR *, const U_CHAR *, unsigned int));
157 static void process_directive PARAMS ((cpp_reader *, const cpp_token *));
158
159 #define INIT_TOKEN_STR(list, token) \
160   do {(token)->val.str.len = 0; \
161       (token)->val.str.text = (list)->namebuf + (list)->name_used; \
162   } while (0)
163
164 #define VALID_SIGN(c, prevc) \
165   (((c) == '+' || (c) == '-') && \
166    ((prevc) == 'e' || (prevc) == 'E' \
167     || (((prevc) == 'p' || (prevc) == 'P') && !CPP_OPTION (pfile, c89))))
168
169 /* Handle LF, CR, CR-LF and LF-CR style newlines.  Assumes next
170    character, if any, is in buffer.  */
171
172 #define handle_newline(cur, limit, c) \
173  do { \
174   if ((cur) < (limit) && *(cur) == '\r' + '\n' - c) \
175     (cur)++; \
176   pfile->buffer->lineno++; \
177   pfile->buffer->line_base = (cur); \
178   pfile->col_adjust = 0; \
179  } while (0)
180
181 #define IMMED_TOKEN() (!(cur_token->flags & PREV_WHITE))
182 #define PREV_TOKEN_TYPE (cur_token[-1].type)
183
184 #define PUSH_TOKEN(ttype) cur_token++->type = (ttype)
185 #define REVISE_TOKEN(ttype) cur_token[-1].type = (ttype)
186 #define BACKUP_TOKEN(ttype) (--cur_token)->type = (ttype)
187 #define BACKUP_DIGRAPH(ttype) do { \
188   BACKUP_TOKEN(ttype); cur_token->flags |= DIGRAPH;} while (0)
189
190 /* An upper bound on the number of bytes needed to spell a token,
191    including preceding whitespace.  */
192 #define TOKEN_LEN(token) (5 + (TOKEN_SPELL(token) == SPELL_STRING       \
193                                ? (token)->val.str.len                   \
194                                : (TOKEN_SPELL(token) == SPELL_IDENT     \
195                                   ? (token)->val.node->length           \
196                                   : 0)))
197
198 #define IS_ARG_CONTEXT(c) ((c)->flags & CONTEXT_ARG)
199 #define CURRENT_CONTEXT(pfile) ((pfile)->contexts + (pfile)->cur_context)
200
201 #define ASSIGN_FLAGS_AND_POS(d, s) \
202   do {(d)->flags = (s)->flags & (PREV_WHITE | BOL | PASTE_LEFT); \
203       if ((d)->flags & BOL) {(d)->col = (s)->col; (d)->line = (s)->line;} \
204   } while (0)
205
206 /* f is flags, just consisting of PREV_WHITE | BOL.  */
207 #define MODIFY_FLAGS_AND_POS(d, s, f) \
208   do {(d)->flags &= ~(PREV_WHITE | BOL); (d)->flags |= (f); \
209       if ((f) & BOL) {(d)->col = (s)->col; (d)->line = (s)->line;} \
210   } while (0)
211
212 #define T(e, s) {SPELL_OPERATOR, (const U_CHAR *) s},
213 #define I(e, s) {SPELL_IDENT, s},
214 #define S(e, s) {SPELL_STRING, s},
215 #define C(e, s) {SPELL_CHAR, s},
216 #define N(e, s) {SPELL_NONE, s},
217
218 const struct token_spelling
219 token_spellings [N_TTYPES + 1] = {TTYPE_TABLE {0, 0} };
220
221 #undef T
222 #undef I
223 #undef S
224 #undef C
225 #undef N
226
227 /* For debugging: the internal names of the tokens.  */
228 #define T(e, s) U STRINGX(e),
229 #define I(e, s) U STRINGX(e),
230 #define S(e, s) U STRINGX(e),
231 #define C(e, s) U STRINGX(e),
232 #define N(e, s) U STRINGX(e),
233
234 const U_CHAR *const token_names[N_TTYPES] = { TTYPE_TABLE };
235
236 #undef T
237 #undef I
238 #undef S
239 #undef C
240 #undef N
241
242 /* The following table is used by trigraph_ok/trigraph_replace.  If we
243    have designated initializers, it can be constant data; otherwise,
244    it is set up at runtime by _cpp_init_input_buffer.  */
245
246 #if (GCC_VERSION >= 2007)
247 #define init_trigraph_map()  /* nothing */
248 #define TRIGRAPH_MAP \
249 __extension__ static const U_CHAR trigraph_map[UCHAR_MAX + 1] = {
250 #define END };
251 #define s(p, v) [p] = v,
252 #else
253 #define TRIGRAPH_MAP static U_CHAR trigraph_map[UCHAR_MAX + 1] = { 0 }; \
254  static void init_trigraph_map PARAMS ((void)) { \
255  unsigned char *x = trigraph_map;
256 #define END }
257 #define s(p, v) x[p] = v;
258 #endif
259
260 TRIGRAPH_MAP
261   s('=', '#')   s(')', ']')     s('!', '|')
262   s('(', '[')   s('\'', '^')    s('>', '}')
263   s('/', '\\')  s('<', '{')     s('-', '~')
264 END
265
266 #undef TRIGRAPH_MAP
267 #undef END
268 #undef s
269
270 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars.  */
271
272 void
273 _cpp_grow_token_buffer (pfile, n)
274      cpp_reader *pfile;
275      long n;
276 {
277   long old_written = CPP_WRITTEN (pfile);
278   pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
279   pfile->token_buffer = (U_CHAR *)
280     xrealloc(pfile->token_buffer, pfile->token_buffer_size);
281   CPP_SET_WRITTEN (pfile, old_written);
282 }
283
284 /* Deal with the annoying semantics of fwrite.  */
285 static void
286 safe_fwrite (pfile, buf, len, fp)
287      cpp_reader *pfile;
288      const U_CHAR *buf;
289      size_t len;
290      FILE *fp;
291 {
292   size_t count;
293
294   while (len)
295     {
296       count = fwrite (buf, 1, len, fp);
297       if (count == 0)
298         goto error;
299       len -= count;
300       buf += count;
301     }
302   return;
303
304  error:
305   cpp_notice_from_errno (pfile, CPP_OPTION (pfile, out_fname));
306 }
307
308 /* Notify the compiler proper that the current line number has jumped,
309    or the current file name has changed.  */
310
311 static void
312 output_line_command (pfile, print, line)
313      cpp_reader *pfile;
314      cpp_printer *print;
315      unsigned int line;
316 {
317   cpp_buffer *ip = CPP_BUFFER (pfile);
318   enum { same = 0, enter, leave, rname } change;
319   static const char * const codes[] = { "", " 1", " 2", "" };
320
321   if (line == 0)
322     return;
323
324   /* End the previous line of text.  */
325   if (pfile->need_newline)
326     putc ('\n', print->outf);
327   pfile->need_newline = 0;
328
329   if (CPP_OPTION (pfile, no_line_commands))
330     return;
331
332   /* If ip is null, we've been called from cpp_finish, and they just
333      needed the final flush and trailing newline.  */
334   if (!ip)
335     return;
336
337   if (pfile->include_depth == print->last_id)
338     {
339       /* Determine whether the current filename has changed, and if so,
340          how.  'nominal_fname' values are unique, so they can be compared
341          by comparing pointers.  */
342       if (ip->nominal_fname == print->last_fname)
343         change = same;
344       else
345         change = rname;
346     }
347   else
348     {
349       if (pfile->include_depth > print->last_id)
350         change = enter;
351       else
352         change = leave;
353       print->last_id = pfile->include_depth;
354     }
355   print->last_fname = ip->nominal_fname;
356
357   /* If the current file has not changed, we can output a few newlines
358      instead if we want to increase the line number by a small amount.
359      We cannot do this if print->lineno is zero, because that means we
360      haven't output any line commands yet.  (The very first line
361      command output is a `same_file' command.)  */
362   if (change == same && print->lineno > 0
363       && line >= print->lineno && line < print->lineno + 8)
364     {
365       while (line > print->lineno)
366         {
367           putc ('\n', print->outf);
368           print->lineno++;
369         }
370       return;
371     }
372
373 #ifndef NO_IMPLICIT_EXTERN_C
374   if (CPP_OPTION (pfile, cplusplus))
375     fprintf (print->outf, "# %u \"%s\"%s%s%s\n", line, ip->nominal_fname,
376              codes[change],
377              ip->inc->sysp ? " 3" : "",
378              (ip->inc->sysp == 2) ? " 4" : "");
379   else
380 #endif
381     fprintf (print->outf, "# %u \"%s\"%s%s\n", line, ip->nominal_fname,
382              codes[change],
383              ip->inc->sysp ? " 3" : "");
384   print->lineno = line;
385 }
386
387 /* Write the contents of the token_buffer to the output stream, and
388    clear the token_buffer.  Also handles generating line commands and
389    keeping track of file transitions.  */
390
391 void
392 cpp_output_tokens (pfile, print, line)
393      cpp_reader *pfile;
394      cpp_printer *print;
395      unsigned int line;
396 {
397   if (CPP_WRITTEN (pfile) - print->written)
398     {
399       safe_fwrite (pfile, pfile->token_buffer,
400                    CPP_WRITTEN (pfile) - print->written, print->outf);
401       pfile->need_newline = 1;
402       if (print->lineno)
403         print->lineno++;
404
405       CPP_SET_WRITTEN (pfile, print->written);
406     }
407   output_line_command (pfile, print, line);
408 }
409
410 /* Scan until CPP_BUFFER (PFILE) is exhausted, discarding output.  */
411
412 void
413 cpp_scan_buffer_nooutput (pfile)
414      cpp_reader *pfile;
415 {
416   cpp_buffer *stop = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
417   const cpp_token *token;
418
419   /* In no-output mode, we can ignore everything but directives.  */
420   for (;;)
421     {
422       token = _cpp_get_token (pfile);
423
424       if (token->type == CPP_EOF)
425         {
426           cpp_pop_buffer (pfile);
427           if (CPP_BUFFER (pfile) == stop)
428             break;
429         }
430
431       if (token->type == CPP_HASH && token->flags & BOL
432           && pfile->token_list.directive)
433         {
434           process_directive (pfile, token);
435           continue;
436         }
437
438       _cpp_skip_rest_of_line (pfile);
439     }
440 }
441
442 /* Scan until CPP_BUFFER (pfile) is exhausted, writing output to PRINT.  */
443 void
444 cpp_scan_buffer (pfile, print)
445      cpp_reader *pfile;
446      cpp_printer *print;
447 {
448   cpp_buffer *stop = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
449   const cpp_token *token, *prev = 0;
450
451   for (;;)
452     {
453       token = _cpp_get_token (pfile);
454       if (token->type == CPP_EOF)
455         {
456           cpp_pop_buffer (pfile);
457
458           if (CPP_BUFFER (pfile))
459             cpp_output_tokens (pfile, print, CPP_BUF_LINE (CPP_BUFFER (pfile)));
460
461           if (CPP_BUFFER (pfile) == stop)
462             return;
463
464           prev = 0;
465           continue;
466         }
467
468       if (token->flags & BOL)
469         {
470           if (token->type == CPP_HASH && pfile->token_list.directive)
471             {
472               process_directive (pfile, token);
473               continue;
474             }
475
476           cpp_output_tokens (pfile, print, pfile->token_list.line);
477           prev = 0;
478         }
479
480       if (token->type != CPP_PLACEMARKER)
481         output_token (pfile, token, prev);
482
483       prev = token;
484     }
485 }
486
487 /* Scan a single line of the input into the token_buffer.  */
488 int
489 cpp_scan_line (pfile)
490      cpp_reader *pfile;
491 {
492   const cpp_token *token, *prev = 0;
493
494   if (pfile->buffer == NULL)
495     return 0;
496
497   do
498     {
499       token = cpp_get_token (pfile);
500       if (token->type == CPP_EOF)
501         {
502           cpp_pop_buffer (pfile);
503           break;
504         }
505
506       /* If the last token on a line results from a macro expansion,
507          the check below will fail to stop us from proceeding to the
508          next line - so make sure we stick in a newline, at least.  */
509       if (token->flags & BOL)
510         CPP_PUTC (pfile, '\n');
511
512       output_token (pfile, token, prev);
513       prev = token;
514     }
515   while (pfile->cur_context > 0
516          || pfile->contexts[0].posn < pfile->contexts[0].count);
517   return 1;
518 }
519
520 /* Helper routine used by parse_include, which can't see spell_token.
521    Reinterpret the current line as an h-char-sequence (< ... >); we are
522    looking at the first token after the <.  */
523 const cpp_token *
524 _cpp_glue_header_name (pfile)
525      cpp_reader *pfile;
526 {
527   unsigned int written = CPP_WRITTEN (pfile);
528   const cpp_token *t;
529   cpp_token *hdr;
530   U_CHAR *buf;
531   size_t len;
532
533   for (;;)
534     {
535       t = _cpp_get_token (pfile);
536       if (t->type == CPP_GREATER || t->type == CPP_EOF)
537         break;
538
539       CPP_RESERVE (pfile, TOKEN_LEN (t));
540       if (t->flags & PREV_WHITE)
541         CPP_PUTC_Q (pfile, ' ');
542       pfile->limit = spell_token (pfile, t, pfile->limit);
543     }
544
545   if (t->type == CPP_EOF)
546     cpp_error (pfile, "missing terminating > character");
547
548   len = CPP_WRITTEN (pfile) - written;
549   buf = xmalloc (len);
550   memcpy (buf, pfile->token_buffer + written, len);
551   CPP_SET_WRITTEN (pfile, written);
552
553   hdr = get_temp_token (pfile);
554   hdr->type = CPP_HEADER_NAME;
555   hdr->flags = 0;
556   hdr->val.str.text = buf;
557   hdr->val.str.len = len;
558   return hdr;
559 }
560
561 /* Token-buffer helper functions.  */
562
563 /* Expand a token list's string space. It is *vital* that
564    list->tokens_used is correct, to get pointer fix-up right.  */
565 void
566 _cpp_expand_name_space (list, len)
567      cpp_toklist *list;
568      unsigned int len;
569 {
570   const U_CHAR *old_namebuf;
571
572   old_namebuf = list->namebuf;
573   list->name_cap += len;
574   list->namebuf = (unsigned char *) xrealloc (list->namebuf, list->name_cap);
575
576   /* Fix up token text pointers.  */
577   if (list->namebuf != old_namebuf)
578     {
579       unsigned int i;
580
581       for (i = 0; i < list->tokens_used; i++)
582         if (token_spellings[list->tokens[i].type].type == SPELL_STRING)
583           list->tokens[i].val.str.text += (list->namebuf - old_namebuf);
584     }
585 }
586
587 /* If there is not enough room for LEN more characters, expand the
588    list by just enough to have room for LEN characters.  */
589 void
590 _cpp_reserve_name_space (list, len)
591      cpp_toklist *list;
592      unsigned int len;
593 {
594   unsigned int room = list->name_cap - list->name_used;
595
596   if (room < len)
597     _cpp_expand_name_space (list, len - room);
598 }
599
600 /* Expand the number of tokens in a list.  */
601 void
602 _cpp_expand_token_space (list, count)
603      cpp_toklist *list;
604      unsigned int count;
605 {
606   unsigned int n;
607
608   list->tokens_cap += count;
609   n = list->tokens_cap;
610   if (list->flags & LIST_OFFSET)
611     list->tokens--, n++;
612   list->tokens = (cpp_token *)
613     xrealloc (list->tokens, n * sizeof (cpp_token));
614   if (list->flags & LIST_OFFSET)
615     list->tokens++;             /* Skip the dummy.  */
616 }
617
618 /* Initialize a token list.  If flags is DUMMY_TOKEN, we allocate
619    an extra token in front of the token list, as this allows the lexer
620    to always peek at the previous token without worrying about
621    underflowing the list, and some initial space.  Otherwise, no
622    token- or name-space is allocated, and there is no dummy token.  */
623 void
624 _cpp_init_toklist (list, flags)
625      cpp_toklist *list;
626      int flags;
627 {
628   if (flags == NO_DUMMY_TOKEN)
629     {
630       list->tokens_cap = 0;
631       list->tokens = 0;
632       list->name_cap = 0;
633       list->namebuf = 0;
634       list->flags = 0;
635     }
636   else
637     {
638       /* Initialize token space.  Put a dummy token before the start
639          that will fail matches.  */
640       list->tokens_cap = 256;   /* 4K's worth.  */
641       list->tokens = (cpp_token *)
642         xmalloc ((list->tokens_cap + 1) * sizeof (cpp_token));
643       list->tokens[0].type = CPP_EOF;
644       list->tokens++;
645
646       /* Initialize name space.  */
647       list->name_cap = 1024;
648       list->namebuf = (unsigned char *) xmalloc (list->name_cap);
649       list->flags = LIST_OFFSET;
650     }
651
652   _cpp_clear_toklist (list);
653 }
654
655 /* Clear a token list.  */
656 void
657 _cpp_clear_toklist (list)
658      cpp_toklist *list;
659 {
660   list->tokens_used = 0;
661   list->name_used = 0;
662   list->directive = 0;
663   list->paramc = 0;
664   list->params_len = 0;
665   list->flags &= LIST_OFFSET;  /* clear all but that one */
666 }
667
668 /* Free a token list.  Does not free the list itself, which may be
669    embedded in a larger structure.  */
670 void
671 _cpp_free_toklist (list)
672      const cpp_toklist *list;
673 {
674   if (list->flags & LIST_OFFSET)
675     free (list->tokens - 1);    /* Backup over dummy token.  */
676   else
677     free (list->tokens);
678   free (list->namebuf);
679 }
680
681 /* Compare two tokens.  */
682 int
683 _cpp_equiv_tokens (a, b)
684      const cpp_token *a, *b;
685 {
686   if (a->type == b->type && a->flags == b->flags)
687     switch (token_spellings[a->type].type)
688       {
689       default:                  /* Keep compiler happy.  */
690       case SPELL_OPERATOR:
691         return 1;
692       case SPELL_CHAR:
693       case SPELL_NONE:
694         return a->val.aux == b->val.aux; /* arg_no or character.  */
695       case SPELL_IDENT:
696         return a->val.node == b->val.node;
697       case SPELL_STRING:
698         return (a->val.str.len == b->val.str.len
699                 && !memcmp (a->val.str.text, b->val.str.text,
700                             a->val.str.len));
701       }
702
703   return 0;
704 }
705
706 /* Compare two token lists.  */
707 int
708 _cpp_equiv_toklists (a, b)
709      const cpp_toklist *a, *b;
710 {
711   unsigned int i;
712
713   if (a->tokens_used != b->tokens_used
714       || a->flags != b->flags
715       || a->paramc != b->paramc)
716     return 0;
717
718   for (i = 0; i < a->tokens_used; i++)
719     if (! _cpp_equiv_tokens (&a->tokens[i], &b->tokens[i]))
720       return 0;
721   return 1;
722 }
723
724 /* Utility routine:
725
726    Compares, the token TOKEN to the NUL-terminated string STRING.
727    TOKEN must be a CPP_NAME.  Returns 1 for equal, 0 for unequal.  */
728
729 int
730 cpp_ideq (token, string)
731      const cpp_token *token;
732      const char *string;
733 {
734   if (token->type != CPP_NAME)
735     return 0;
736
737   return !ustrcmp (token->val.node->name, (const U_CHAR *)string);
738 }
739
740 /* Lexing algorithm.
741
742  The original lexer in cpplib was made up of two passes: a first pass
743  that replaced trigraphs and deleted esacped newlines, and a second
744  pass that tokenized the result of the first pass.  Tokenisation was
745  performed by peeking at the next character in the input stream.  For
746  example, if the input stream contained "!=", the handler for the !
747  character would peek at the next character, and if it were a '='
748  would skip over it, and return a "!=" token, otherwise it would
749  return just the "!" token.
750
751  To implement a single-pass lexer, this peeking ahead is unworkable.
752  An arbitrary number of escaped newlines, and trigraphs (in particular
753  ??/ which translates to the escape \), could separate the '!' and '='
754  in the input stream, yet the next token is still a "!=".
755
756  Suppose instead that we lex by one logical line at a time, producing
757  a token list or stack for each logical line, and when seeing the '!'
758  push a CPP_NOT token on the list.  Then if the '!' is part of a
759  longer token ("!=") we know we must see the remainder of the token by
760  the time we reach the end of the logical line.  Thus we can have the
761  '=' handler look at the previous token (at the end of the list / top
762  of the stack) and see if it is a "!" token, and if so, instead of
763  pushing a "=" token revise the existing token to be a "!=" token.
764
765  This works in the presence of escaped newlines, because the '\' would
766  have been pushed on the top of the stack as a CPP_BACKSLASH.  The
767  newline ('\n' or '\r') handler looks at the token at the top of the
768  stack to see if it is a CPP_BACKSLASH, and if so discards both.
769  Hence the '=' handler would never see any intervening tokens.
770
771  To make trigraphs work in this context, as in precedence trigraphs
772  are highest and converted before anything else, the '?' handler does
773  lookahead to see if it is a trigraph, and if so skips the trigraph
774  and pushes the token it represents onto the top of the stack.  This
775  also works in the particular case of a CPP_BACKSLASH trigraph.
776
777  To the preprocessor, whitespace is only significant to the point of
778  knowing whether whitespace precedes a particular token.  For example,
779  the '=' handler needs to know whether there was whitespace between it
780  and a "!" token on the top of the stack, to make the token conversion
781  decision correctly.  So each token has a PREV_WHITE flag to
782  indicate this - the standard permits consecutive whitespace to be
783  regarded as a single space.  The compiler front ends are not
784  interested in whitespace at all; they just require a token stream.
785  Another place where whitespace is significant to the preprocessor is
786  a #define statment - if there is whitespace between the macro name
787  and an initial "(" token the macro is "object-like", otherwise it is
788  a function-like macro that takes arguments.
789
790  However, all is not rosy.  Parsing of identifiers, numbers, comments
791  and strings becomes trickier because of the possibility of raw
792  trigraphs and escaped newlines in the input stream.
793
794  The trigraphs are three consecutive characters beginning with two
795  question marks.  A question mark is not valid as part of a number or
796  identifier, so parsing of a number or identifier terminates normally
797  upon reaching it, returning to the mainloop which handles the
798  trigraph just like it would in any other position.  Similarly for the
799  backslash of a backslash-newline combination.  So we just need the
800  escaped-newline dropper in the mainloop to check if the token on the
801  top of the stack after dropping the escaped newline is a number or
802  identifier, and if so to continue the processing it as if nothing had
803  happened.
804
805  For strings, we replace trigraphs whenever we reach a quote or
806  newline, because there might be a backslash trigraph escaping them.
807  We need to be careful that we start trigraph replacing from where we
808  left off previously, because it is possible for a first scan to leave
809  "fake" trigraphs that a second scan would pick up as real (e.g. the
810  sequence "????/\n=" would find a fake ??= trigraph after removing the
811  escaped newline.)
812
813  For line comments, on reaching a newline we scan the previous
814  character(s) to see if it escaped, and continue if it is.  Block
815  comments ignore everything and just focus on finding the comment
816  termination mark.  The only difficult thing, and it is surprisingly
817  tricky, is checking if an asterisk precedes the final slash since
818  they could be separated by escaped newlines.  If the preprocessor is
819  invoked with the output comments option, we don't bother removing
820  escaped newlines and replacing trigraphs for output.
821
822  Finally, numbers can begin with a period, which is pushed initially
823  as a CPP_DOT token in its own right.  The digit handler checks if the
824  previous token was a CPP_DOT not separated by whitespace, and if so
825  pops it off the stack and pushes a period into the number's buffer
826  before calling the number parser.
827
828 */
829
830 static const unsigned char *digraph_spellings [] = {U"%:", U"%:%:", U"<:",
831                                                     U":>", U"<%", U"%>"};
832
833 /* Call when a trigraph is encountered.  It warns if necessary, and
834    returns true if the trigraph should be honoured.  END is the third
835    character of a trigraph in the input stream.  */
836 static int
837 trigraph_ok (pfile, end)
838      cpp_reader *pfile;
839      const unsigned char *end;
840 {
841   int accept = CPP_OPTION (pfile, trigraphs);
842   
843   if (CPP_OPTION (pfile, warn_trigraphs))
844     {
845       unsigned int col = end - 1 - pfile->buffer->line_base;
846       if (accept)
847         cpp_warning_with_line (pfile, pfile->buffer->lineno, col, 
848                                "trigraph ??%c converted to %c",
849                                (int) *end, (int) trigraph_map[*end]);
850       else
851         cpp_warning_with_line (pfile, pfile->buffer->lineno, col,
852                                "trigraph ??%c ignored", (int) *end);
853     }
854   return accept;
855 }
856
857 /* Scan a string for trigraphs, warning or replacing them inline as
858    appropriate.  When parsing a string, we must call this routine
859    before processing a newline character (if trigraphs are enabled),
860    since the newline might be escaped by a preceding backslash
861    trigraph sequence.  Returns a pointer to the end of the name after
862    replacement.  */
863
864 static unsigned char *
865 trigraph_replace (pfile, src, limit)
866      cpp_reader *pfile;
867      unsigned char *src;
868      unsigned char *limit;
869 {
870   unsigned char *dest;
871
872   /* Starting with src[1], find two consecutive '?'.  The case of no
873      trigraphs is streamlined.  */
874   
875   for (src++; src + 1 < limit; src += 2)
876     {
877       if (src[0] != '?')
878         continue;
879
880       /* Make src point to the 1st (NOT 2nd) of two consecutive '?'s.  */
881       if (src[-1] == '?')
882         src--;
883       else if (src + 2 == limit || src[1] != '?')
884         continue;
885
886       /* Check if it really is a trigraph.  */
887       if (trigraph_map[src[2]] == 0)
888         continue;
889
890       dest = src;
891       goto trigraph_found;
892     }
893   return limit;
894
895   /* Now we have a trigraph, we need to scan the remaining buffer, and
896      copy-shifting its contents left if replacement is enabled.  */
897   for (; src + 2 < limit; dest++, src++)
898     if ((*dest = *src) == '?' && src[1] == '?' && trigraph_map[src[2]])
899       {
900       trigraph_found:
901         src += 2;
902         if (trigraph_ok (pfile, pfile->buffer->cur - (limit - src)))
903           *dest = trigraph_map[*src];
904       }
905   
906   /* Copy remaining (at most 2) characters.  */
907   while (src < limit)
908     *dest++ = *src++;
909   return dest;
910 }
911
912 /* If CUR is a backslash or the end of a trigraphed backslash, return
913    a pointer to its beginning, otherwise NULL.  We don't read beyond
914    the buffer start, because there is the start of the comment in the
915    buffer.  */
916 static const unsigned char *
917 backslash_start (pfile, cur)
918      cpp_reader *pfile;
919      const unsigned char *cur;
920 {
921   if (cur[0] == '\\')
922     return cur;
923   if (cur[0] == '/' && cur[-1] == '?' && cur[-2] == '?'
924       && trigraph_ok (pfile, cur))
925     return cur - 2;
926   return 0;
927 }
928
929 /* Skip a C-style block comment.  This is probably the trickiest
930    handler.  We find the end of the comment by seeing if an asterisk
931    is before every '/' we encounter.  The nasty complication is that a
932    previous asterisk may be separated by one or more escaped newlines.
933    Returns non-zero if comment terminated by EOF, zero otherwise.  */
934 static int
935 skip_block_comment (pfile)
936      cpp_reader *pfile;
937 {
938   cpp_buffer *buffer = pfile->buffer;
939   const unsigned char *char_after_star = 0;
940   const unsigned char *cur = buffer->cur;
941   
942   for (; cur < buffer->rlimit; )
943     {
944       unsigned char c = *cur++;
945
946       /* People like decorating comments with '*', so check for
947          '/' instead for efficiency.  */
948       if (c == '/')
949         {
950           /* Don't view / then * then / as finishing the comment.  */
951           if ((cur[-2] == '*' && cur - 1 > buffer->cur)
952               || cur - 1 == char_after_star)
953             {
954               buffer->cur = cur;
955               return 0;
956             }
957
958           /* Warn about potential nested comments, but not when
959              the final character inside the comment is a '/'.
960              Don't bother to get it right across escaped newlines.  */
961           if (CPP_OPTION (pfile, warn_comments) && cur + 1 < buffer->rlimit
962               && cur[0] == '*' && cur[1] != '/') 
963             {
964               buffer->cur = cur;
965               cpp_warning (pfile, "'/*' within comment");
966             }
967         }
968       else if (is_vspace (c))
969         {
970           const unsigned char* bslash = backslash_start (pfile, cur - 2);
971
972           handle_newline (cur, buffer->rlimit, c);
973           /* Work correctly if there is an asterisk before an
974              arbirtrarily long sequence of escaped newlines.  */
975           if (bslash && (bslash[-1] == '*' || bslash == char_after_star))
976             char_after_star = cur;
977           else
978             char_after_star = 0;
979         }
980       else if (c == '\t')
981         adjust_column (pfile, cur - 1);
982     }
983
984   buffer->cur = cur;
985   return 1;
986 }
987
988 /* Skip a C++ line comment.  Handles escaped newlines.  Returns
989    non-zero if a multiline comment.  */
990 static int
991 skip_line_comment (pfile)
992      cpp_reader *pfile;
993 {
994   cpp_buffer *buffer = pfile->buffer;
995   register const unsigned char *cur = buffer->cur;
996   int multiline = 0;
997
998   for (; cur < buffer->rlimit; )
999     {
1000       unsigned char c = *cur++;
1001
1002       if (is_vspace (c))
1003         {
1004           /* Check for a (trigaph?) backslash escaping the newline.  */
1005           if (!backslash_start (pfile, cur - 2))
1006             goto out;
1007           multiline = 1;
1008           handle_newline (cur, buffer->rlimit, c);
1009         }
1010     }
1011   cur++;
1012
1013  out:
1014   buffer->cur = cur - 1;        /* Leave newline for caller.  */
1015   return multiline;
1016 }
1017
1018 /* TAB points to a \t character.  Update col_adjust so we track the
1019    column correctly.  */
1020 static void
1021 adjust_column (pfile, tab)
1022      cpp_reader *pfile;
1023      const U_CHAR *tab;
1024 {
1025   /* Zero-based column.  */
1026   unsigned int col = CPP_BUF_COLUMN (pfile->buffer, tab);
1027
1028   /* Round it up to multiple of the tabstop, but subtract 1 since the
1029      tab itself occupies a character position.  */
1030   pfile->col_adjust += (CPP_OPTION (pfile, tabstop)
1031                         - col % CPP_OPTION (pfile, tabstop)) - 1;
1032 }
1033
1034 /* Skips whitespace, stopping at next non-whitespace character.
1035    Adjusts pfile->col_adjust to account for tabs.  This enables tokens
1036    to be assigned the correct column.  */
1037 static void
1038 skip_whitespace (pfile, in_directive)
1039      cpp_reader *pfile;
1040      int in_directive;
1041 {
1042   cpp_buffer *buffer = pfile->buffer;
1043   unsigned short warned = 0;
1044
1045   /* We only want non-vertical space, i.e. ' ' \t \f \v \0. */
1046   while (buffer->cur < buffer->rlimit)
1047     {
1048       unsigned char c = *buffer->cur;
1049
1050       if (!is_nvspace (c))
1051         break;
1052
1053       buffer->cur++;
1054       /* Horizontal space always OK.  */
1055       if (c == ' ')
1056         continue;
1057       else if (c == '\t')
1058         adjust_column (pfile, buffer->cur - 1);
1059       /* Must be \f \v or \0.  */
1060       else if (c == '\0')
1061         {
1062           if (!warned)
1063             cpp_warning_with_line (pfile, CPP_BUF_LINE (buffer),
1064                                    CPP_BUF_COL (buffer),
1065                                    "embedded null character ignored");
1066           warned = 1;
1067         }
1068       else if (in_directive && CPP_PEDANTIC (pfile))
1069         cpp_pedwarn_with_line (pfile, CPP_BUF_LINE (buffer),
1070                                CPP_BUF_COL (buffer),
1071                                "%s in preprocessing directive",
1072                                c == '\f' ? "form feed" : "vertical tab");
1073     }
1074 }
1075
1076 /* Parse (append) an identifier.  Calculates the hash value of the
1077    token while parsing, for performance.  The algorithm *must* match
1078    cpp_lookup().  */
1079 static const U_CHAR *
1080 parse_name (pfile, tok, cur, rlimit)
1081      cpp_reader *pfile;
1082      cpp_token *tok;
1083      const U_CHAR *cur, *rlimit;
1084 {
1085   const U_CHAR *name;
1086   unsigned int len;
1087   unsigned int r;
1088
1089   name = cur;
1090   r = 0;
1091   while (cur < rlimit)
1092     {
1093       if (! is_idchar (*cur))
1094         break;
1095       /* $ is not a legal identifier character in the standard, but is
1096          commonly accepted as an extension.  Don't warn about it in
1097          skipped conditional blocks. */
1098       if (*cur == '$' && CPP_PEDANTIC (pfile) && ! pfile->skipping)
1099         {
1100           CPP_BUFFER (pfile)->cur = cur;
1101           cpp_pedwarn (pfile, "'$' character in identifier");
1102         }
1103
1104       r = HASHSTEP (r, cur);
1105       cur++;
1106     }
1107   len = cur - name;
1108
1109   if (tok->val.node == 0)
1110     tok->val.node = _cpp_lookup_with_hash (pfile, name, len, r);
1111   else
1112     {
1113       unsigned int oldlen = tok->val.node->length;
1114       U_CHAR *newname = alloca (oldlen + len);
1115       memcpy (newname, tok->val.node->name, oldlen);
1116       memcpy (newname + oldlen, name, len);
1117       tok->val.node = cpp_lookup (pfile, newname, len + oldlen);
1118     }
1119
1120   return cur;
1121 }
1122
1123 /* Parse (append) a number.  */
1124 static void
1125 parse_number (pfile, list, name)
1126      cpp_reader *pfile;
1127      cpp_toklist *list;
1128      cpp_string *name;
1129 {
1130   const unsigned char *name_limit;
1131   unsigned char *namebuf;
1132   cpp_buffer *buffer = pfile->buffer;
1133   register const unsigned char *cur = buffer->cur;
1134
1135  expanded:
1136   name_limit = list->namebuf + list->name_cap;
1137   namebuf = list->namebuf + list->name_used;
1138
1139   for (; cur < buffer->rlimit && namebuf < name_limit; )
1140     {
1141       unsigned char c = *namebuf = *cur; /* Copy a single char.  */
1142
1143       /* Perhaps we should accept '$' here if we accept it for
1144          identifiers.  We know namebuf[-1] is safe, because for c to
1145          be a sign we must have pushed at least one character.  */
1146       if (!is_numchar (c) && c != '.' && ! VALID_SIGN (c, namebuf[-1]))
1147         goto out;
1148
1149       namebuf++;
1150       cur++;
1151     }
1152
1153   /* Run out of name space?  */
1154   if (cur < buffer->rlimit)
1155     {
1156       list->name_used = namebuf - list->namebuf;
1157       auto_expand_name_space (list);
1158       goto expanded;
1159     }
1160   
1161  out:
1162   buffer->cur = cur;
1163   name->len = namebuf - name->text;
1164   list->name_used = namebuf - list->namebuf;
1165 }
1166
1167 /* Places a string terminated by an unescaped TERMINATOR into a
1168    cpp_string, which should be expandable and thus at the top of the
1169    list's stack.  Handles embedded trigraphs, if necessary, and
1170    escaped newlines.
1171
1172    Can be used for character constants (terminator = '\''), string
1173    constants ('"') and angled headers ('>').  Multi-line strings are
1174    allowed, except for within directives.  */
1175
1176 static void
1177 parse_string (pfile, list, token, terminator)
1178      cpp_reader *pfile;
1179      cpp_toklist *list;
1180      cpp_token *token;
1181      unsigned int terminator;
1182 {
1183   cpp_buffer *buffer = pfile->buffer;
1184   cpp_string *name = &token->val.str;
1185   register const unsigned char *cur = buffer->cur;
1186   const unsigned char *name_limit;
1187   unsigned char *namebuf;
1188   unsigned int null_count = 0;
1189   unsigned int trigraphed = list->name_used;
1190
1191  expanded:
1192   name_limit = list->namebuf + list->name_cap;
1193   namebuf = list->namebuf + list->name_used;
1194
1195   for (; cur < buffer->rlimit && namebuf < name_limit; )
1196     {
1197       unsigned int c = *namebuf++ = *cur++; /* Copy a single char.  */
1198
1199       if (c == '\0')
1200         null_count++;
1201       else if (c == terminator || is_vspace (c))
1202         {
1203           /* Needed for trigraph_replace and multiline string warning.  */
1204           buffer->cur = cur;
1205
1206           /* Scan for trigraphs before checking if backslash-escaped.  */
1207           if ((CPP_OPTION (pfile, trigraphs)
1208                || CPP_OPTION (pfile, warn_trigraphs))
1209               && namebuf - (list->namebuf + trigraphed) >= 3)
1210             {
1211               namebuf = trigraph_replace (pfile, list->namebuf + trigraphed,
1212                                           namebuf);
1213               /* The test above guarantees trigraphed will be positive.  */
1214               trigraphed = namebuf - list->namebuf - 2;
1215             }
1216
1217           namebuf--;     /* Drop the newline / terminator from the name.  */
1218           if (is_vspace (c))
1219             {
1220               /* Drop a backslash newline, and continue. */
1221               if (namebuf[-1] == '\\')
1222                 {
1223                   handle_newline (cur, buffer->rlimit, c);
1224                   namebuf--;
1225                   continue;
1226                 }
1227
1228               cur--;
1229
1230               /* In assembly language, silently terminate strings of
1231                  either variety at end of line.  This is a kludge
1232                  around not knowing where comments are.  */
1233               if (CPP_OPTION (pfile, lang_asm))
1234                 goto out;
1235
1236               /* Character constants and header names may not extend
1237                  over multiple lines.  In Standard C, neither may
1238                  strings.  We accept multiline strings as an
1239                  extension.  (Even in directives - otherwise, glibc's
1240                  longlong.h breaks.)  */
1241               if (terminator != '"')
1242                 goto unterminated;
1243                 
1244               cur++;  /* Move forwards again.  */
1245
1246               if (pfile->multiline_string_line == 0)
1247                 {
1248                   pfile->multiline_string_line = token->line;
1249                   pfile->multiline_string_column = token->col;
1250                   if (CPP_PEDANTIC (pfile))
1251                     cpp_pedwarn (pfile, "multi-line string constant");
1252                 }
1253
1254               *namebuf++ = '\n';
1255               handle_newline (cur, buffer->rlimit, c);
1256             }
1257           else
1258             {
1259               unsigned char *temp;
1260
1261               /* An odd number of consecutive backslashes represents
1262                  an escaped terminator.  */
1263               temp = namebuf - 1;
1264               while (temp >= name->text && *temp == '\\')
1265                 temp--;
1266
1267               if ((namebuf - temp) & 1)
1268                 goto out;
1269               namebuf++;
1270             }
1271         }
1272     }
1273
1274   /* Run out of name space?  */
1275   if (cur < buffer->rlimit)
1276     {
1277       list->name_used = namebuf - list->namebuf;
1278       auto_expand_name_space (list);
1279       goto expanded;
1280     }
1281
1282   /* We may not have trigraph-replaced the input for this code path,
1283      but as the input is in error by being unterminated we don't
1284      bother.  Prevent warnings about no newlines at EOF.  */
1285   if (is_vspace (cur[-1]))
1286     cur--;
1287
1288  unterminated:
1289   cpp_error (pfile, "missing terminating %c character", (int) terminator);
1290
1291   if (terminator == '\"' && pfile->multiline_string_line != list->line
1292       && pfile->multiline_string_line != 0)
1293     {
1294       cpp_error_with_line (pfile, pfile->multiline_string_line,
1295                            pfile->multiline_string_column,
1296                            "possible start of unterminated string literal");
1297       pfile->multiline_string_line = 0;
1298     }
1299   
1300  out:
1301   buffer->cur = cur;
1302   name->len = namebuf - name->text;
1303   list->name_used = namebuf - list->namebuf;
1304
1305   if (null_count > 0)
1306     cpp_warning (pfile, (null_count > 1 ? "null characters preserved"
1307                          : "null character preserved"));
1308 }
1309
1310 /* The character TYPE helps us distinguish comment types: '*' = C
1311    style, '/' = C++ style.  For code simplicity, the stored comment
1312    includes the comment start and any terminator.  */
1313
1314 #define COMMENT_START_LEN 2
1315 static void
1316 save_comment (list, token, from, len, type)
1317      cpp_toklist *list;
1318      cpp_token *token;
1319      const unsigned char *from;
1320      unsigned int len;
1321      unsigned int type;
1322 {
1323   unsigned char *buffer;
1324   
1325   len += COMMENT_START_LEN;
1326
1327   if (list->name_used + len > list->name_cap)
1328     _cpp_expand_name_space (list, len);
1329
1330   INIT_TOKEN_STR (list, token);
1331   token->type = CPP_COMMENT;
1332   token->val.str.len = len;
1333
1334   buffer = list->namebuf + list->name_used;
1335   list->name_used += len;
1336
1337   /* Copy the comment.  */
1338   if (type == '*')
1339     {
1340       *buffer++ = '/';
1341       *buffer++ = '*';
1342     }
1343   else
1344     {
1345       *buffer++ = type;
1346       *buffer++ = type;
1347     }
1348   memcpy (buffer, from, len - COMMENT_START_LEN);
1349 }
1350
1351 /*
1352  *  The tokenizer's main loop.  Returns a token list, representing a
1353  *  logical line in the input file.  On EOF after some tokens have
1354  *  been processed, we return immediately.  Then in next call, or if
1355  *  EOF occurred at the beginning of a logical line, a single CPP_EOF
1356  *  token is placed in the list.
1357  *
1358  *  Implementation relies almost entirely on lookback, rather than
1359  *  looking forwards.  This means that tokenization requires just
1360  *  a single pass of the file, even in the presence of trigraphs and
1361  *  escaped newlines, providing significant performance benefits.
1362  *  Trigraph overhead is negligible if they are disabled, and low
1363  *  even when enabled.
1364  */
1365
1366 #define KNOWN_DIRECTIVE() (list->directive != 0)
1367 #define MIGHT_BE_DIRECTIVE() \
1368 (cur_token == &list->tokens[first_token + 1] && cur_token[-1].type == CPP_HASH)
1369
1370 static void
1371 lex_line (pfile, list)
1372      cpp_reader *pfile;
1373      cpp_toklist *list;
1374 {
1375   cpp_token *cur_token, *token_limit, *first;
1376   cpp_buffer *buffer = pfile->buffer;
1377   const unsigned char *cur = buffer->cur;
1378   unsigned char flags = 0;
1379   unsigned int first_token = list->tokens_used;
1380
1381   if (!(list->flags & LIST_OFFSET))
1382     (abort) ();
1383   
1384   list->file = buffer->nominal_fname;
1385   list->line = CPP_BUF_LINE (buffer);
1386   pfile->col_adjust = 0;
1387   pfile->in_lex_line = 1;
1388   if (cur == buffer->buf)
1389     list->flags |= BEG_OF_FILE;
1390
1391  expanded:
1392   token_limit = list->tokens + list->tokens_cap;
1393   cur_token = list->tokens + list->tokens_used;
1394
1395   for (; cur < buffer->rlimit && cur_token < token_limit;)
1396     {
1397       unsigned char c;
1398
1399       /* Optimize non-vertical whitespace skipping; most tokens are
1400          probably separated by whitespace. (' ' '\t' '\v' '\f' '\0').  */
1401       c = *cur;
1402       if (is_nvspace (c))
1403         {
1404           buffer->cur = cur;
1405           skip_whitespace (pfile, (list->tokens[first_token].type == CPP_HASH
1406                                    && cur_token > &list->tokens[first_token]));
1407           cur = buffer->cur;
1408
1409           flags = PREV_WHITE;
1410           if (cur == buffer->rlimit)
1411             break;
1412           c = *cur;
1413         }
1414       cur++;
1415
1416       /* Initialize current token.  CPP_EOF will not be fixed up by
1417          expand_name_space.  */
1418       list->tokens_used = cur_token - list->tokens + 1;
1419       cur_token->type = CPP_EOF;
1420       cur_token->col = CPP_BUF_COLUMN (buffer, cur);
1421       cur_token->line = CPP_BUF_LINE (buffer);
1422       cur_token->flags = flags;
1423       flags = 0;
1424
1425       switch (c)
1426         {
1427         case '0': case '1': case '2': case '3': case '4':
1428         case '5': case '6': case '7': case '8': case '9':
1429           {
1430             int prev_dot;
1431
1432             cur--;              /* Backup character.  */
1433             prev_dot = PREV_TOKEN_TYPE == CPP_DOT && IMMED_TOKEN ();
1434             if (prev_dot)
1435               cur_token--;
1436             INIT_TOKEN_STR (list, cur_token);
1437             /* Prepend an immediately previous CPP_DOT token.  */
1438             if (prev_dot)
1439               {
1440                 if (list->name_cap == list->name_used)
1441                   auto_expand_name_space (list);
1442
1443                 cur_token->val.str.len = 1;
1444                 list->namebuf[list->name_used++] = '.';
1445               }
1446
1447           continue_number:
1448             cur_token->type = CPP_NUMBER; /* Before parse_number.  */
1449             buffer->cur = cur;
1450             parse_number (pfile, list, &cur_token->val.str);
1451             cur = buffer->cur;
1452           }
1453           /* Check for # 123 form of #line.  */
1454           if (MIGHT_BE_DIRECTIVE ())
1455             list->directive = _cpp_check_linemarker (pfile, cur_token,
1456                                                      !(cur_token[-1].flags
1457                                                        & PREV_WHITE));
1458           cur_token++;
1459           break;
1460
1461         letter:
1462         case '_':
1463         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1464         case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1465         case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1466         case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1467         case 'y': case 'z':
1468         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1469         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1470         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1471         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1472         case 'Y': case 'Z':
1473           cur--;                     /* Backup character.  */
1474           cur_token->val.node = 0;
1475           cur_token->type = CPP_NAME; /* Identifier, macro etc.  */
1476
1477         continue_name:
1478           cur = parse_name (pfile, cur_token, cur, buffer->rlimit);
1479
1480           if (MIGHT_BE_DIRECTIVE ())
1481             list->directive = _cpp_check_directive (pfile, cur_token,
1482                                                     !(list->tokens[0].flags
1483                                                       & PREV_WHITE));
1484           cur_token++;
1485           break;
1486
1487         case '\'':
1488         case '\"':
1489           cur_token->type = c == '\'' ? CPP_CHAR : CPP_STRING;
1490           /* Do we have a wide string?  */
1491           if (cur_token[-1].type == CPP_NAME && IMMED_TOKEN ()
1492               && cur_token[-1].val.node == pfile->spec_nodes->n_L)
1493             BACKUP_TOKEN (c == '\'' ? CPP_WCHAR : CPP_WSTRING);
1494
1495         do_parse_string:
1496           /* Here c is one of ' " or >.  */
1497           INIT_TOKEN_STR (list, cur_token);
1498           buffer->cur = cur;
1499           parse_string (pfile, list, cur_token, c);
1500           cur = buffer->cur;
1501           cur_token++;
1502           break;
1503
1504         case '/':
1505           cur_token->type = CPP_DIV;
1506           if (IMMED_TOKEN ())
1507             {
1508               if (PREV_TOKEN_TYPE == CPP_DIV)
1509                 {
1510                   /* We silently allow C++ comments in system headers,
1511                      irrespective of conformance mode, because lots of
1512                      broken systems do that and trying to clean it up
1513                      in fixincludes is a nightmare.  */
1514                   if (CPP_IN_SYSTEM_HEADER (pfile))
1515                     goto do_line_comment;
1516                   else if (CPP_OPTION (pfile, cplusplus_comments))
1517                     {
1518                       if (CPP_OPTION (pfile, c89) && CPP_PEDANTIC (pfile)
1519                           && ! buffer->warned_cplusplus_comments)
1520                         {
1521                           buffer->cur = cur;
1522                           cpp_pedwarn (pfile,
1523                              "C++ style comments are not allowed in ISO C89");
1524                           cpp_pedwarn (pfile,
1525                           "(this will be reported only once per input file)");
1526                           buffer->warned_cplusplus_comments = 1;
1527                         }
1528                     do_line_comment:
1529                       buffer->cur = cur;
1530 #if 0 /* Leave until new lexer in place.  */
1531                       if (cur[-2] != c)
1532                         cpp_warning (pfile,
1533                                      "comment start split across lines");
1534 #endif
1535                       if (skip_line_comment (pfile))
1536                         cpp_warning (pfile, "multi-line comment");
1537
1538                       /* Back-up to first '-' or '/'.  */
1539                       cur_token--;
1540                       if (!CPP_OPTION (pfile, discard_comments)
1541                           && (!KNOWN_DIRECTIVE()
1542                               || (list->directive->flags & COMMENTS)))
1543                         save_comment (list, cur_token++, cur,
1544                                       buffer->cur - cur, c);
1545                       else
1546                         flags = PREV_WHITE;
1547
1548                       cur = buffer->cur;
1549                       break;
1550                     }
1551                 }
1552             }
1553           cur_token++;
1554           break;
1555                       
1556         case '*':
1557           cur_token->type = CPP_MULT;
1558           if (IMMED_TOKEN ())
1559             {
1560               if (PREV_TOKEN_TYPE == CPP_DIV)
1561                 {
1562                   buffer->cur = cur;
1563 #if 0 /* Leave until new lexer in place.  */
1564                   if (cur[-2] != '/')
1565                     cpp_warning (pfile,
1566                                  "comment start '/*' split across lines");
1567 #endif
1568                   if (skip_block_comment (pfile))
1569                     cpp_error_with_line (pfile, list->line, cur_token[-1].col,
1570                                          "unterminated comment");
1571 #if 0 /* Leave until new lexer in place.  */
1572                   else if (buffer->cur[-2] != '*')
1573                     cpp_warning (pfile,
1574                                  "comment end '*/' split across lines");
1575 #endif
1576                   /* Back up to opening '/'.  */
1577                   cur_token--;
1578                   if (!CPP_OPTION (pfile, discard_comments)
1579                       && (!KNOWN_DIRECTIVE()
1580                           || (list->directive->flags & COMMENTS)))
1581                     save_comment (list, cur_token++, cur,
1582                                   buffer->cur - cur, c);
1583                   else
1584                     flags = PREV_WHITE;
1585
1586                   cur = buffer->cur;
1587                   break;
1588                 }
1589               else if (CPP_OPTION (pfile, cplusplus))
1590                 {
1591                   /* In C++, there are .* and ->* operators.  */
1592                   if (PREV_TOKEN_TYPE == CPP_DEREF)
1593                     BACKUP_TOKEN (CPP_DEREF_STAR);
1594                   else if (PREV_TOKEN_TYPE == CPP_DOT)
1595                     BACKUP_TOKEN (CPP_DOT_STAR);
1596                 }
1597             }
1598           cur_token++;
1599           break;
1600
1601         case '\n':
1602         case '\r':
1603           handle_newline (cur, buffer->rlimit, c);
1604           if (PREV_TOKEN_TYPE == CPP_BACKSLASH)
1605             {
1606               if (IMMED_TOKEN ())
1607                 {
1608                   /* Remove the escaped newline.  Then continue to process
1609                      any interrupted name or number.  */
1610                   cur_token--;
1611                   /* Backslash-newline may not be immediately followed by
1612                      EOF (C99 5.1.1.2).  */
1613                   if (cur >= buffer->rlimit)
1614                     {
1615                       cpp_pedwarn (pfile, "backslash-newline at end of file");
1616                       break;
1617                     }
1618                   if (IMMED_TOKEN ())
1619                     {
1620                       cur_token--;
1621                       if (cur_token->type == CPP_NAME)
1622                         goto continue_name;
1623                       else if (cur_token->type == CPP_NUMBER)
1624                         goto continue_number;
1625                       cur_token++;
1626                     }
1627                   /* Remember whitespace setting.  */
1628                   flags = cur_token->flags;
1629                   break;
1630                 }
1631               else
1632                 {
1633                   buffer->cur = cur;
1634                   cpp_warning (pfile,
1635                                "backslash and newline separated by space");
1636                 }
1637             }
1638           else if (MIGHT_BE_DIRECTIVE ())
1639             {
1640               /* "Null directive." C99 6.10.7: A preprocessing
1641                  directive of the form # <new-line> has no effect.
1642
1643                  But it is still a directive, and therefore disappears
1644                  from the output. */
1645               cur_token--;
1646               if (cur_token->flags & PREV_WHITE
1647                   && CPP_WTRADITIONAL (pfile))
1648                 cpp_warning (pfile, "K+R C ignores #\\n with the # indented");
1649             }
1650
1651           /* Skip vertical space until we have at least one token to
1652              return.  */
1653           if (cur_token != &list->tokens[first_token])
1654             goto out;
1655           list->line = CPP_BUF_LINE (buffer);
1656           break;
1657
1658         case '-':
1659           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_MINUS)
1660             REVISE_TOKEN (CPP_MINUS_MINUS);
1661           else
1662             PUSH_TOKEN (CPP_MINUS);
1663           break;
1664
1665         make_hash:
1666         case '#':
1667           /* The digraph flag checking ensures that ## and %:%:
1668              are interpreted as CPP_PASTE, but #%: and %:# are not.  */
1669           if (PREV_TOKEN_TYPE == CPP_HASH && IMMED_TOKEN ()
1670               && ((cur_token->flags ^ cur_token[-1].flags) & DIGRAPH) == 0)
1671             REVISE_TOKEN (CPP_PASTE);
1672           else
1673             PUSH_TOKEN (CPP_HASH);
1674           break;
1675
1676         case ':':
1677           cur_token->type = CPP_COLON;
1678           if (IMMED_TOKEN ())
1679             {
1680               if (PREV_TOKEN_TYPE == CPP_COLON
1681                   && CPP_OPTION (pfile, cplusplus))
1682                 BACKUP_TOKEN (CPP_SCOPE);
1683               else if (CPP_OPTION (pfile, digraphs))
1684                 {
1685                   /* Digraph: "<:" is a '['  */
1686                   if (PREV_TOKEN_TYPE == CPP_LESS)
1687                     BACKUP_DIGRAPH (CPP_OPEN_SQUARE);
1688                   /* Digraph: "%:" is a '#'  */
1689                   else if (PREV_TOKEN_TYPE == CPP_MOD)
1690                     {
1691                       (--cur_token)->flags |= DIGRAPH;
1692                       goto make_hash;
1693                     }
1694                 }
1695             }
1696           cur_token++;
1697           break;
1698
1699         case '&':
1700           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_AND)
1701             REVISE_TOKEN (CPP_AND_AND);
1702           else
1703             PUSH_TOKEN (CPP_AND);
1704           break;
1705
1706         make_or:
1707         case '|':
1708           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_OR)
1709             REVISE_TOKEN (CPP_OR_OR);
1710           else
1711             PUSH_TOKEN (CPP_OR);
1712           break;
1713
1714         case '+':
1715           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_PLUS)
1716             REVISE_TOKEN (CPP_PLUS_PLUS);
1717           else
1718             PUSH_TOKEN (CPP_PLUS);
1719           break;
1720
1721         case '=':
1722             /* This relies on equidistance of "?=" and "?" tokens.  */
1723           if (IMMED_TOKEN () && PREV_TOKEN_TYPE <= CPP_LAST_EQ)
1724             REVISE_TOKEN (PREV_TOKEN_TYPE + (CPP_EQ_EQ - CPP_EQ));
1725           else
1726             PUSH_TOKEN (CPP_EQ);
1727           break;
1728
1729         case '>':
1730           cur_token->type = CPP_GREATER;
1731           if (IMMED_TOKEN ())
1732             {
1733               if (PREV_TOKEN_TYPE == CPP_GREATER)
1734                 BACKUP_TOKEN (CPP_RSHIFT);
1735               else if (PREV_TOKEN_TYPE == CPP_MINUS)
1736                 BACKUP_TOKEN (CPP_DEREF);
1737               else if (CPP_OPTION (pfile, digraphs))
1738                 {
1739                   /* Digraph: ":>" is a ']'  */
1740                   if (PREV_TOKEN_TYPE == CPP_COLON)
1741                     BACKUP_DIGRAPH (CPP_CLOSE_SQUARE);
1742                   /* Digraph: "%>" is a '}'  */
1743                   else if (PREV_TOKEN_TYPE == CPP_MOD)
1744                     BACKUP_DIGRAPH (CPP_CLOSE_BRACE);
1745                 }
1746             }
1747           cur_token++;
1748           break;
1749           
1750         case '<':
1751           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_LESS)
1752             {
1753               REVISE_TOKEN (CPP_LSHIFT);
1754               break;
1755             }
1756           /* Is this the beginning of a header name?  */
1757           if (KNOWN_DIRECTIVE () && (list->directive->flags & INCL))
1758             {
1759               c = '>';  /* Terminator.  */
1760               cur_token->type = CPP_HEADER_NAME;
1761               goto do_parse_string;
1762             }
1763           PUSH_TOKEN (CPP_LESS);
1764           break;
1765
1766         case '%':
1767           /* Digraph: "<%" is a '{'  */
1768           cur_token->type = CPP_MOD;
1769           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_LESS
1770               && CPP_OPTION (pfile, digraphs))
1771             BACKUP_DIGRAPH (CPP_OPEN_BRACE);
1772           cur_token++;
1773           break;
1774
1775         case '?':
1776           if (cur + 1 < buffer->rlimit && *cur == '?'
1777               && trigraph_map[cur[1]] && trigraph_ok (pfile, cur + 1))
1778             {
1779               /* Handle trigraph.  */
1780               cur++;
1781               switch (*cur++)
1782                 {
1783                 case '(': goto make_open_square;
1784                 case ')': goto make_close_square;
1785                 case '<': goto make_open_brace;
1786                 case '>': goto make_close_brace;
1787                 case '=': goto make_hash;
1788                 case '!': goto make_or;
1789                 case '-': goto make_complement;
1790                 case '/': goto make_backslash;
1791                 case '\'': goto make_xor;
1792                 }
1793             }
1794           if (IMMED_TOKEN () && CPP_OPTION (pfile, cplusplus))
1795             {
1796               /* GNU C++ defines <? and >? operators.  */
1797               if (PREV_TOKEN_TYPE == CPP_LESS)
1798                 {
1799                   REVISE_TOKEN (CPP_MIN);
1800                   break;
1801                 }
1802               else if (PREV_TOKEN_TYPE == CPP_GREATER)
1803                 {
1804                   REVISE_TOKEN (CPP_MAX);
1805                   break;
1806                 }
1807             }
1808           PUSH_TOKEN (CPP_QUERY);
1809           break;
1810
1811         case '.':
1812           if (PREV_TOKEN_TYPE == CPP_DOT && cur_token[-2].type == CPP_DOT
1813               && IMMED_TOKEN ()
1814               && !(cur_token[-1].flags & PREV_WHITE))
1815             {
1816               cur_token -= 2;
1817               PUSH_TOKEN (CPP_ELLIPSIS);
1818             }
1819           else
1820             PUSH_TOKEN (CPP_DOT);
1821           break;
1822
1823         make_complement:
1824         case '~': PUSH_TOKEN (CPP_COMPL); break;
1825         make_xor:
1826         case '^': PUSH_TOKEN (CPP_XOR); break;
1827         make_open_brace:
1828         case '{': PUSH_TOKEN (CPP_OPEN_BRACE); break;
1829         make_close_brace:
1830         case '}': PUSH_TOKEN (CPP_CLOSE_BRACE); break;
1831         make_open_square:
1832         case '[': PUSH_TOKEN (CPP_OPEN_SQUARE); break;
1833         make_close_square:
1834         case ']': PUSH_TOKEN (CPP_CLOSE_SQUARE); break;
1835         make_backslash:
1836         case '\\': PUSH_TOKEN (CPP_BACKSLASH); break;
1837         case '!': PUSH_TOKEN (CPP_NOT); break;
1838         case ',': PUSH_TOKEN (CPP_COMMA); break;
1839         case ';': PUSH_TOKEN (CPP_SEMICOLON); break;
1840         case '(': PUSH_TOKEN (CPP_OPEN_PAREN); break;
1841         case ')': PUSH_TOKEN (CPP_CLOSE_PAREN); break;
1842
1843         case '$':
1844           if (CPP_OPTION (pfile, dollars_in_ident))
1845             goto letter;
1846           /* Fall through */
1847         default:
1848           cur_token->val.aux = c;
1849           PUSH_TOKEN (CPP_OTHER);
1850           break;
1851         }
1852     }
1853
1854   /* Run out of token space?  */
1855   if (cur_token == token_limit)
1856     {
1857       list->tokens_used = cur_token - list->tokens;
1858       _cpp_expand_token_space (list, 256);
1859       goto expanded;
1860     }
1861
1862   cur_token->flags = flags;
1863   if (cur_token == &list->tokens[first_token] && pfile->done_initializing)
1864     {
1865       if (cur > buffer->buf && !is_vspace (cur[-1]))
1866         cpp_pedwarn_with_line (pfile, CPP_BUF_LINE (buffer),
1867                                CPP_BUF_COLUMN (buffer, cur),
1868                                "no newline at end of file");
1869       cur_token++->type = CPP_EOF;
1870     }
1871
1872  out:
1873   /* All tokens are allocated, so the memory location is fixed.  */
1874   first = &list->tokens[first_token];
1875
1876   /* Don't complain about the null directive, nor directives in
1877      assembly source: we don't know where the comments are, and # may
1878      introduce assembler pseudo-ops.  Don't complain about invalid
1879      directives in skipped conditional groups (6.10 p4).  */
1880   if (first->type == CPP_HASH && list->directive == 0 && !pfile->skipping
1881       && cur_token > first + 1 && !CPP_OPTION (pfile, lang_asm))
1882     {
1883       if (first[1].type == CPP_NAME)
1884         cpp_error (pfile, "invalid preprocessing directive #%.*s",
1885                    (int) first[1].val.node->length, first[1].val.node->name);
1886       else
1887         cpp_error (pfile, "invalid preprocessing directive");
1888     }
1889
1890   /* Put EOF at end of known directives.  This covers "directives do
1891      not extend beyond the end of the line (description 6.10 part 2)".  */
1892   if (KNOWN_DIRECTIVE () || !pfile->done_initializing)
1893     {
1894       pfile->first_directive_token = first;
1895       cur_token++->type = CPP_EOF;
1896     }
1897
1898   /* Directives, known or not, always start a new line.  */
1899   if (first_token == 0 || list->tokens[first_token].type == CPP_HASH)
1900     first->flags |= BOL;
1901   else
1902     /* 6.10.3.10: Within the sequence of preprocessing tokens making
1903        up the invocation of a function-like macro, new line is
1904        considered a normal white-space character.  */
1905     first->flags |= PREV_WHITE;
1906
1907   buffer->cur = cur;
1908   list->tokens_used = cur_token - list->tokens;
1909   pfile->in_lex_line = 0;
1910 }
1911
1912 /* Write the spelling of a token TOKEN, with any appropriate
1913    whitespace before it, to the token_buffer.  PREV is the previous
1914    token, which is used to determine if we need to shove in an extra
1915    space in order to avoid accidental token paste.  */
1916 static void
1917 output_token (pfile, token, prev)
1918      cpp_reader *pfile;
1919      const cpp_token *token, *prev;
1920 {
1921   int dummy;
1922
1923   if (token->col && (token->flags & BOL))
1924     {
1925       /* Supply enough whitespace to put this token in its original
1926          column.  Don't bother trying to reconstruct tabs; we can't
1927          get it right in general, and nothing ought to care.  (Yes,
1928          some things do care; the fault lies with them.)  */
1929       unsigned char *buffer;
1930       unsigned int spaces = token->col - 1;
1931
1932       CPP_RESERVE (pfile, token->col);
1933       buffer = pfile->limit;
1934
1935       while (spaces--)
1936         *buffer++ = ' ';
1937       pfile->limit = buffer;
1938     }
1939   else if (token->flags & PREV_WHITE)
1940     CPP_PUTC (pfile, ' ');
1941   else if (prev)
1942     {
1943       /* Check for and prevent accidental token pasting.  */
1944       if (can_paste (pfile, prev, token, &dummy) != CPP_EOF)
1945         CPP_PUTC (pfile, ' ');
1946       /* can_paste doesn't catch all the accidental pastes.
1947          Consider a + ++b - if there is not a space between the + and ++, it
1948          will be misparsed as a++ + b.  */
1949       else if ((prev->type == CPP_PLUS && token->type == CPP_PLUS_PLUS)
1950                || (prev->type == CPP_MINUS && token->type == CPP_MINUS_MINUS))
1951         CPP_PUTC (pfile, ' ');
1952     }
1953
1954   CPP_RESERVE (pfile, TOKEN_LEN (token));
1955   pfile->limit = spell_token (pfile, token, pfile->limit);
1956 }
1957
1958 /* Write the spelling of a token TOKEN to BUFFER.  The buffer must
1959    already contain the enough space to hold the token's spelling.
1960    Returns a pointer to the character after the last character
1961    written.  */
1962
1963 static unsigned char *
1964 spell_token (pfile, token, buffer)
1965      cpp_reader *pfile;         /* Would be nice to be rid of this...  */
1966      const cpp_token *token;
1967      unsigned char *buffer;
1968 {
1969   switch (token_spellings[token->type].type)
1970     {
1971     case SPELL_OPERATOR:
1972       {
1973         const unsigned char *spelling;
1974         unsigned char c;
1975
1976         if (token->flags & DIGRAPH)
1977           spelling = digraph_spellings[token->type - CPP_FIRST_DIGRAPH];
1978         else
1979           spelling = token_spellings[token->type].spelling;
1980         
1981         while ((c = *spelling++) != '\0')
1982           *buffer++ = c;
1983       }
1984       break;
1985
1986     case SPELL_IDENT:
1987       memcpy (buffer, token->val.node->name, token->val.node->length);
1988       buffer += token->val.node->length;
1989       break;
1990
1991     case SPELL_STRING:
1992       {
1993         if (token->type == CPP_WSTRING || token->type == CPP_WCHAR)
1994           *buffer++ = 'L';
1995
1996         if (token->type == CPP_STRING || token->type == CPP_WSTRING)
1997           *buffer++ = '"';
1998         if (token->type == CPP_CHAR || token->type == CPP_WCHAR)
1999           *buffer++ = '\'';
2000
2001         memcpy (buffer, token->val.str.text, token->val.str.len);
2002         buffer += token->val.str.len;
2003         
2004         if (token->type == CPP_STRING || token->type == CPP_WSTRING)
2005           *buffer++ = '"';
2006         if (token->type == CPP_CHAR || token->type == CPP_WCHAR)
2007           *buffer++ = '\'';
2008       }
2009       break;
2010
2011     case SPELL_CHAR:
2012       *buffer++ = token->val.aux;
2013       break;
2014
2015     case SPELL_NONE:
2016       cpp_ice (pfile, "Unspellable token %s", token_names[token->type]);
2017       break;
2018     }
2019
2020   return buffer;
2021 }
2022
2023 /* Return the spelling of a token known to be an operator.
2024    Does not distinguish digraphs from their counterparts.  */
2025 const unsigned char *
2026 _cpp_spell_operator (type)
2027      enum cpp_ttype type;
2028 {
2029   if (token_spellings[type].type == SPELL_OPERATOR)
2030     return token_spellings[type].spelling;
2031   else
2032     return token_names[type];
2033 }
2034
2035
2036 /* Macro expansion algorithm.
2037
2038 Macro expansion is implemented by a single-pass algorithm; there are
2039 no rescan passes involved.  cpp_get_token expands just enough to be
2040 able to return a token to the caller, a consequence is that when it
2041 returns the preprocessor can be in a state of mid-expansion.  The
2042 algorithm does not work by fully expanding a macro invocation into
2043 some kind of token list, and then returning them one by one.
2044
2045 Our expansion state is recorded in a context stack.  We start out with
2046 a single context on the stack, let's call it base context.  This
2047 consists of the token list returned by lex_line that forms the next
2048 logical line in the source file.
2049
2050 The current level in the context stack is stored in the cur_context
2051 member of the cpp_reader structure.  The context it references keeps,
2052 amongst other things, a count of how many tokens form that context and
2053 our position within those tokens.
2054
2055 Fundamentally, calling cpp_get_token will return the next token from
2056 the current context.  If we're at the end of the current context, that
2057 context is popped from the stack first, unless it is the base context,
2058 in which case the next logical line is lexed from the source file.
2059
2060 However, before returning the token, if it is a CPP_NAME token
2061 _cpp_get_token checks to see if it is a macro and if it is enabled.
2062 Each time it encounters a macro name, it calls push_macro_context.
2063 This function checks that the macro should be expanded (with
2064 is_macro_enabled), and if so pushes a new macro context on the stack
2065 which becomes the current context.  It then loops back to read the
2066 first token of the macro context.
2067
2068 A macro context basically consists of the token list representing the
2069 macro's replacement list, which was saved in the hash table by
2070 save_macro_expansion when its #define statement was parsed.  If the
2071 macro is function-like, it also contains the tokens that form the
2072 arguments to the macro.  I say more about macro arguments below, but
2073 for now just saying that each argument is a set of pointers to tokens
2074 is enough.
2075
2076 When taking tokens from a macro context, we may get a CPP_MACRO_ARG
2077 token.  This represents an argument passed to the macro, with the
2078 argument number stored in the token's AUX field.  The argument should
2079 be substituted, this is achieved by pushing an "argument context".  An
2080 argument context is just refers to the tokens forming the argument,
2081 which are obtained directly from the macro context.  The STRINGIFY
2082 flag on a CPP_MACRO_ARG token indicates that the argument should be
2083 stringified.
2084
2085 Here's a few simple rules the context stack obeys:-
2086
2087   1) The lex_line token list is always context zero.
2088
2089   2) Context 1, if it exists, must be a macro context.
2090
2091   3) An argument context can only appear above a macro context.
2092
2093   4) A macro context can appear above the base context, another macro
2094   context, or an argument context.
2095
2096   5) These imply that the minimal level of an argument context is 2.
2097
2098 The only tricky thing left is ensuring that macros are enabled and
2099 disabled correctly.  The algorithm controls macro expansion by the
2100 level of the context a token is taken from in the context stack.  If a
2101 token is taken from a level equal to no_expand_level (a member of
2102 struct cpp_reader), no expansion is performed.
2103
2104 When popping a context off the stack, if no_expand_level equals the
2105 level of the popped context, it is reduced by one to match the new
2106 context level, so that expansion is still disabled.  It does not
2107 increase if a context is pushed, though.  It starts out life as
2108 UINT_MAX, which has the effect that initially macro expansion is
2109 enabled.  I explain how this mechanism works below.
2110
2111 The standard requires:-
2112
2113   1) Arguments to be fully expanded before substitution.
2114
2115   2) Stringified arguments to not be expanded, nor the tokens
2116   immediately surrounding a ## operator.
2117
2118   3) Continual rescanning until there are no more macros left to
2119   replace.
2120
2121   4) Once a macro has been expanded in stage 1) or 3), it cannot be
2122   expanded again during later rescans.  This prevents infinite
2123   recursion.
2124
2125 The first thing to observe is that stage 3) is mostly redundant.
2126 Since a macro is disabled once it has been expanded, how can a rescan
2127 find an unexpanded macro name?  There are only two cases where this is
2128 possible:-
2129
2130   a) If the macro name results from a token paste operation.
2131
2132   b) If the macro in question is a function-like macro that hasn't
2133   already been expanded because previously there was not the required
2134   '(' token immediately following it.  This is only possible when an
2135   argument is substituted, and after substitution the last token of
2136   the argument can bind with a parenthesis appearing in the tokens
2137   following the substitution.  Note that if the '(' appears within the
2138   argument, the ')' must too, as expanding macro arguments cannot
2139   "suck in" tokens outside the argument.
2140
2141 So we tackle this as follows.  When parsing the macro invocation for
2142 arguments, we record the tokens forming each argument as a list of
2143 pointers to those tokens.  We do not expand any tokens that are "raw",
2144 i.e. directly from the macro invocation, but other tokens that come
2145 from (nested) argument substitution are fully expanded.
2146
2147 This is achieved by setting the no_expand_level to that of the macro
2148 invocation.  A CPP_MACRO_ARG token never appears in the list of tokens
2149 forming an argument, because parse_args (indirectly) calls
2150 get_raw_token which automatically pushes argument contexts and traces
2151 into them.  Since these contexts are at a higher level than the
2152 no_expand_level, they get fully macro expanded.
2153
2154 "Raw" and non-raw tokens are separated in arguments by null pointers,
2155 with the policy that the initial state of an argument is raw.  If the
2156 first token is not raw, it should be preceded by a null pointer.  When
2157 tracing through the tokens of an argument context, each time
2158 get_raw_token encounters a null pointer, it toggles the flag
2159 CONTEXT_RAW.
2160
2161 This flag, when set, indicates to is_macro_disabled that we are
2162 reading raw tokens which should be macro-expanded.  Similarly, if
2163 clear, is_macro_disabled suppresses re-expansion.
2164
2165 It's probably time for an example.
2166
2167 #define hash #
2168 #define str(x) #x
2169 #define xstr(y) str(y hash)
2170 str(hash)                       // "hash"
2171 xstr(hash)                      // "# hash"
2172
2173 In the invocation of str, parse_args turns off macro expansion and so
2174 parses the argument as <hash>.  This is the only token (pointer)
2175 passed as the argument to str.  Since <hash> is raw there is no need
2176 for an initial null pointer.  stringify_arg is called from
2177 get_raw_token when tracing through the expansion of str, since the
2178 argument has the STRINGIFY flag set.  stringify_arg turns off
2179 macro_expansion by setting the no_expand_level to that of the argument
2180 context.  Thus it gets the token <hash> and stringifies it to "hash"
2181 correctly.
2182
2183 Similary xstr is passed <hash>.  However, when parse_args is parsing
2184 the invocation of str() in xstr's expansion, get_raw_token encounters
2185 a CPP_MACRO_ARG token for y.  Transparently to parse_args, it pushes
2186 an argument context, and enters the tokens of the argument,
2187 i.e. <hash>.  This is at a higher context level than parse_args
2188 disabled, and so is_macro_disabled permits expansion of it and a macro
2189 context is pushed on top of the argument context.  This contains the
2190 <#> token, and the end result is that <hash> is macro expanded.
2191 However, after popping off the argument context, the <hash> of xstr's
2192 expansion does not get macro expanded because we're back at the
2193 no_expand_level.  The end result is that the argument passed to str is
2194 <NULL> <#> <NULL> <hash>.  Note the nulls - policy is we start off
2195 raw, <#> is not raw, but then <hash> is.
2196
2197 */
2198
2199
2200 /* Free the storage allocated for macro arguments.  */
2201 static void
2202 free_macro_args (args)
2203      macro_args *args;
2204 {
2205   if (args->tokens)
2206     free ((PTR) args->tokens);
2207   free (args->ends);
2208   free (args);
2209 }
2210
2211 /* Determines if a macro has been already used (and is therefore
2212    disabled).  */
2213 static int
2214 is_macro_disabled (pfile, expansion, token)
2215      cpp_reader *pfile;
2216      const cpp_toklist *expansion;
2217      const cpp_token *token;
2218 {
2219   cpp_context *context = CURRENT_CONTEXT (pfile);
2220
2221   /* Don't expand anything if this file has already been preprocessed.  */
2222   if (CPP_OPTION (pfile, preprocessed))
2223     return 1;
2224
2225   /* Arguments on either side of ## are inserted in place without
2226      macro expansion (6.10.3.3.2).  Conceptually, any macro expansion
2227      occurs during a later rescan pass.  The effect is that we expand
2228      iff we would as part of the macro's expansion list, so we should
2229      drop to the macro's context.  */
2230   if (IS_ARG_CONTEXT (context))
2231     {
2232       if (token->flags & PASTED)
2233         context--;
2234       else if (!(context->flags & CONTEXT_RAW))
2235         return 1;
2236       else if (context->flags & (CONTEXT_PASTEL | CONTEXT_PASTER))
2237         context--;
2238     }
2239
2240   /* Have we already used this macro?  */
2241   while (context->level > 0)
2242     {
2243       if (!IS_ARG_CONTEXT (context) && context->u.list == expansion)
2244         return 1;
2245       /* Raw argument tokens are judged based on the token list they
2246          came from.  */
2247       if (context->flags & CONTEXT_RAW)
2248         context = pfile->contexts + context->level;
2249       else
2250         context--;
2251     }
2252
2253   /* Function-like macros may be disabled if the '(' is not in the
2254      current context.  We check this without disrupting the context
2255      stack.  */
2256   if (expansion->paramc >= 0)
2257     {
2258       const cpp_token *next;
2259       unsigned int prev_nme;
2260
2261       context = CURRENT_CONTEXT (pfile);
2262       /* Drop down any contexts we're at the end of: the '(' may
2263          appear in lower macro expansions, or in the rest of the file.  */
2264       while (context->posn == context->count && context > pfile->contexts)
2265         {
2266           context--;
2267           /* If we matched, we are disabled, as we appear in the
2268              expansion of each macro we meet.  */
2269           if (!IS_ARG_CONTEXT (context) && context->u.list == expansion)
2270             return 1;
2271         }
2272
2273       prev_nme = pfile->no_expand_level;
2274       pfile->no_expand_level = context - pfile->contexts;
2275       next = _cpp_get_token (pfile);
2276       restore_macro_expansion (pfile, prev_nme);
2277       if (next->type != CPP_OPEN_PAREN)
2278         {
2279           _cpp_push_token (pfile, next);
2280           if (CPP_WTRADITIONAL (pfile))
2281             cpp_warning (pfile,
2282          "function macro %.*s must be used with arguments in traditional C",
2283                          (int) token->val.node->length, token->val.node->name);
2284           return 1;
2285         }
2286     }
2287
2288   return 0;
2289 }
2290
2291 /* Add a token to the set of tokens forming the arguments to the macro
2292    being parsed in parse_args.  */
2293 static void
2294 save_token (args, token)
2295      macro_args *args;
2296      const cpp_token *token;
2297 {
2298   if (args->used == args->capacity)
2299     {
2300       args->capacity += args->capacity + 100;
2301       args->tokens = (const cpp_token **)
2302         xrealloc ((PTR) args->tokens,
2303                   args->capacity * sizeof (const cpp_token *));
2304     }
2305   args->tokens[args->used++] = token;
2306 }
2307
2308 /* Take and save raw tokens until we finish one argument.  Empty
2309    arguments are saved as a single CPP_PLACEMARKER token.  */
2310 static const cpp_token *
2311 parse_arg (pfile, var_args, paren_context, args, pcount)
2312      cpp_reader *pfile;
2313      int var_args;
2314      unsigned int paren_context;
2315      macro_args *args;
2316      unsigned int *pcount;
2317 {
2318   const cpp_token *token;
2319   unsigned int paren = 0, count = 0;
2320   int raw, was_raw = 1;
2321   
2322   for (count = 0;; count++)
2323     {
2324       token = _cpp_get_token (pfile);
2325
2326       switch (token->type)
2327         {
2328         default:
2329           break;
2330
2331         case CPP_OPEN_PAREN:
2332           paren++;
2333           break;
2334
2335         case CPP_CLOSE_PAREN:
2336           if (paren-- != 0)
2337             break;
2338           goto out;
2339
2340         case CPP_COMMA:
2341           /* Commas are not terminators within parantheses or var_args.  */
2342           if (paren || var_args)
2343             break;
2344           goto out;
2345
2346         case CPP_EOF:           /* Error reported by caller.  */
2347           goto out;
2348         }
2349
2350       raw = pfile->cur_context <= paren_context;
2351       if (raw != was_raw)
2352         {
2353           was_raw = raw;
2354           save_token (args, 0);
2355           count++;
2356         }
2357       save_token (args, token);
2358     }
2359
2360  out:
2361   if (count == 0)
2362     {
2363       /* Duplicate the placemarker.  Then we can set its flags and
2364          position and safely be using more than one.  */
2365       save_token (args, duplicate_token (pfile, &placemarker_token));
2366       count++;
2367     }
2368
2369   *pcount = count;
2370   return token;
2371 }
2372
2373 /* This macro returns true if the argument starting at offset O of arglist
2374    A is empty - that is, it's either a single PLACEMARKER token, or a null
2375    pointer followed by a PLACEMARKER.  */
2376
2377 #define empty_argument(A, O) \
2378  ((A)->tokens[O] ? (A)->tokens[O]->type == CPP_PLACEMARKER \
2379                  : (A)->tokens[(O)+1]->type == CPP_PLACEMARKER)
2380    
2381 /* Parse the arguments making up a macro invocation.  Nested arguments
2382    are automatically macro expanded, but immediate macros are not
2383    expanded; this enables e.g. operator # to work correctly.  Returns
2384    non-zero on error.  */
2385 static int
2386 parse_args (pfile, hp, args)
2387      cpp_reader *pfile;
2388      cpp_hashnode *hp;
2389      macro_args *args;
2390 {
2391   const cpp_token *token;
2392   const cpp_toklist *macro;
2393   unsigned int total = 0;
2394   unsigned int paren_context = pfile->cur_context;
2395   int argc = 0;
2396
2397   macro = hp->value.expansion;
2398   do
2399     {
2400       unsigned int count;
2401
2402       token = parse_arg (pfile, (argc + 1 == macro->paramc
2403                                  && (macro->flags & VAR_ARGS)),
2404                          paren_context, args, &count);
2405       if (argc < macro->paramc)
2406         {
2407           total += count;
2408           args->ends[argc] = total;
2409         }
2410       argc++;
2411     }
2412   while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
2413
2414   if (token->type == CPP_EOF)
2415     {
2416       cpp_error (pfile, "unterminated invocation of macro \"%.*s\"",
2417                  hp->length, hp->name);
2418       return 1;
2419     }
2420   else if (argc < macro->paramc)
2421     {
2422       /* A rest argument is allowed to not appear in the invocation at all.
2423          e.g. #define debug(format, args...) ...
2424          debug("string");
2425          This is exactly the same as if the rest argument had received no
2426          tokens - debug("string",);  This extension is deprecated.  */
2427         
2428       if (argc + 1 == macro->paramc && (macro->flags & GNU_REST_ARGS))
2429         {
2430           /* Duplicate the placemarker.  Then we can set its flags and
2431              position and safely be using more than one.  */
2432           save_token (args, duplicate_token (pfile, &placemarker_token));
2433           args->ends[argc] = total + 1;
2434           return 0;
2435         }
2436       else
2437         {
2438           cpp_error (pfile,
2439                      "insufficient arguments in invocation of macro \"%.*s\"",
2440                      hp->length, hp->name);
2441           return 1;
2442         }
2443     }
2444   /* An empty argument to an empty function-like macro is fine.  */
2445   else if (argc > macro->paramc
2446            && !(macro->paramc == 0 && argc == 1 && empty_argument (args, 0)))
2447     {
2448       cpp_error (pfile,
2449                  "too many arguments in invocation of macro \"%.*s\"",
2450                  hp->length, hp->name);
2451       return 1;
2452     }
2453
2454   return 0;
2455 }
2456
2457 /* Adds backslashes before all backslashes and double quotes appearing
2458    in strings.  Non-printable characters are converted to octal.  */
2459 static U_CHAR *
2460 quote_string (dest, src, len)
2461      U_CHAR *dest;
2462      const U_CHAR *src;
2463      unsigned int len;
2464 {
2465   while (len--)
2466     {
2467       U_CHAR c = *src++;
2468
2469       if (c == '\\' || c == '"')
2470         {
2471           *dest++ = '\\';
2472           *dest++ = c;
2473         }
2474       else
2475         {
2476           if (ISPRINT (c))
2477             *dest++ = c;
2478           else
2479             {
2480               sprintf ((char *) dest, "\\%03o", c);
2481               dest += 4;
2482             }
2483         }
2484     }
2485
2486   return dest;
2487 }
2488
2489 /* Allocates a buffer to hold a token's TEXT, and converts TOKEN to a
2490    CPP_STRING token containing TEXT in quoted form.  */
2491 static cpp_token *
2492 make_string_token (token, text, len)
2493      cpp_token *token;
2494      const U_CHAR *text;
2495      unsigned int len;
2496 {
2497   U_CHAR *buf;
2498  
2499   buf = (U_CHAR *) xmalloc (len * 4);
2500   token->type = CPP_STRING;
2501   token->flags = 0;
2502   token->val.str.text = buf;
2503   token->val.str.len = quote_string (buf, text, len) - buf;
2504   return token;
2505 }
2506
2507 /* Allocates and converts a temporary token to a CPP_NUMBER token,
2508    evaluating to NUMBER.  */
2509 static cpp_token *
2510 alloc_number_token (pfile, number)
2511      cpp_reader *pfile;
2512      int number;
2513 {
2514   cpp_token *result;
2515   char *buf;
2516
2517   result = get_temp_token (pfile);
2518   buf = xmalloc (20);
2519   sprintf (buf, "%d", number);
2520
2521   result->type = CPP_NUMBER;
2522   result->flags = 0;
2523   result->val.str.text = (U_CHAR *) buf;
2524   result->val.str.len = strlen (buf);
2525   return result;
2526 }
2527
2528 /* Returns a temporary token from the temporary token store of PFILE.  */
2529 static cpp_token *
2530 get_temp_token (pfile)
2531      cpp_reader *pfile;
2532 {
2533   if (pfile->temp_used == pfile->temp_alloced)
2534     {
2535       if (pfile->temp_used == pfile->temp_cap)
2536         {
2537           pfile->temp_cap += pfile->temp_cap + 20;
2538           pfile->temp_tokens = (cpp_token **) xrealloc
2539             (pfile->temp_tokens, pfile->temp_cap * sizeof (cpp_token *));
2540         }
2541       pfile->temp_tokens[pfile->temp_alloced++] = (cpp_token *) xmalloc
2542         (sizeof (cpp_token));
2543     }
2544
2545   return pfile->temp_tokens[pfile->temp_used++];
2546 }
2547
2548 /* Release (not free) for re-use the temporary tokens of PFILE.  */
2549 static void
2550 release_temp_tokens (pfile)
2551      cpp_reader *pfile;
2552 {
2553   while (pfile->temp_used)
2554     {
2555       cpp_token *token = pfile->temp_tokens[--pfile->temp_used];
2556
2557       if (token_spellings[token->type].type == SPELL_STRING)
2558         {
2559           free ((char *) token->val.str.text);
2560           token->val.str.text = 0;
2561         }
2562     }
2563 }
2564
2565 /* Free all of PFILE's dynamically-allocated temporary tokens.  */
2566 void
2567 _cpp_free_temp_tokens (pfile)
2568      cpp_reader *pfile;
2569 {
2570   if (pfile->temp_tokens)
2571     {
2572       /* It is possible, though unlikely (looking for '(' of a funlike
2573          macro into EOF), that we haven't released the tokens yet.  */
2574       release_temp_tokens (pfile);
2575       while (pfile->temp_alloced)
2576         free (pfile->temp_tokens[--pfile->temp_alloced]);
2577       free (pfile->temp_tokens);
2578     }
2579
2580   if (pfile->date)
2581     {
2582       free ((char *) pfile->date->val.str.text);
2583       free (pfile->date);
2584       free ((char *) pfile->time->val.str.text);
2585       free (pfile->time);
2586     }
2587 }
2588
2589 /* Copy TOKEN into a temporary token from PFILE's store.  */
2590 static cpp_token *
2591 duplicate_token (pfile, token)
2592      cpp_reader *pfile;
2593      const cpp_token *token;
2594 {
2595   cpp_token *result = get_temp_token (pfile);
2596
2597   *result = *token;
2598   if (token_spellings[token->type].type == SPELL_STRING)
2599     {
2600       U_CHAR *buff = (U_CHAR *) xmalloc (token->val.str.len);
2601       memcpy (buff, token->val.str.text, token->val.str.len);
2602       result->val.str.text = buff;
2603     }
2604   return result;
2605 }
2606
2607 /* Determine whether two tokens can be pasted together, and if so,
2608    what the resulting token is.  Returns CPP_EOF if the tokens cannot
2609    be pasted, or the appropriate type for the merged token if they
2610    can.  */
2611 static enum cpp_ttype
2612 can_paste (pfile, token1, token2, digraph)
2613      cpp_reader * pfile;
2614      const cpp_token *token1, *token2;
2615      int* digraph;
2616 {
2617   enum cpp_ttype a = token1->type, b = token2->type;
2618   int cxx = CPP_OPTION (pfile, cplusplus);
2619
2620   if (a <= CPP_LAST_EQ && b == CPP_EQ)
2621     return a + (CPP_EQ_EQ - CPP_EQ);
2622
2623   switch (a)
2624     {
2625     case CPP_GREATER:
2626       if (b == a) return CPP_RSHIFT;
2627       if (b == CPP_QUERY && cxx)        return CPP_MAX;
2628       if (b == CPP_GREATER_EQ)  return CPP_RSHIFT_EQ;
2629       break;
2630     case CPP_LESS:
2631       if (b == a) return CPP_LSHIFT;
2632       if (b == CPP_QUERY && cxx)        return CPP_MIN;
2633       if (b == CPP_LESS_EQ)     return CPP_LSHIFT_EQ;
2634       if (CPP_OPTION (pfile, digraphs))
2635         {
2636           if (b == CPP_COLON)
2637             {*digraph = 1; return CPP_OPEN_SQUARE;} /* <: digraph */
2638           if (b == CPP_MOD)
2639             {*digraph = 1; return CPP_OPEN_BRACE;}      /* <% digraph */
2640         }
2641       break;
2642
2643     case CPP_PLUS: if (b == a)  return CPP_PLUS_PLUS; break;
2644     case CPP_AND:  if (b == a)  return CPP_AND_AND; break;
2645     case CPP_OR:   if (b == a)  return CPP_OR_OR;   break;
2646
2647     case CPP_MINUS:
2648       if (b == a)               return CPP_MINUS_MINUS;
2649       if (b == CPP_GREATER)     return CPP_DEREF;
2650       break;
2651     case CPP_COLON:
2652       if (b == a && cxx)        return CPP_SCOPE;
2653       if (b == CPP_GREATER && CPP_OPTION (pfile, digraphs))
2654         {*digraph = 1; return CPP_CLOSE_SQUARE;} /* :> digraph */
2655       break;
2656
2657     case CPP_MOD:
2658       if (CPP_OPTION (pfile, digraphs))
2659         {
2660           if (b == CPP_GREATER)
2661             {*digraph = 1; return CPP_CLOSE_BRACE;}  /* %> digraph */
2662           if (b == CPP_COLON)
2663             {*digraph = 1; return CPP_HASH;}         /* %: digraph */
2664         }
2665       break;
2666     case CPP_DEREF:
2667       if (b == CPP_MULT && cxx) return CPP_DEREF_STAR;
2668       break;
2669     case CPP_DOT:
2670       if (b == CPP_MULT && cxx) return CPP_DOT_STAR;
2671       if (b == CPP_NUMBER)      return CPP_NUMBER;
2672       break;
2673
2674     case CPP_HASH:
2675       if (b == a && (token1->flags & DIGRAPH) == (token2->flags & DIGRAPH))
2676         /* %:%: digraph */
2677         {*digraph = (token1->flags & DIGRAPH); return CPP_PASTE;}
2678       break;
2679
2680     case CPP_NAME:
2681       if (b == CPP_NAME)        return CPP_NAME;
2682       if (b == CPP_NUMBER
2683           && is_numstart(token2->val.str.text[0]))       return CPP_NAME;
2684       if (b == CPP_CHAR
2685           && token1->val.node == pfile->spec_nodes->n_L) return CPP_WCHAR;
2686       if (b == CPP_STRING
2687           && token1->val.node == pfile->spec_nodes->n_L) return CPP_WSTRING;
2688       break;
2689
2690     case CPP_NUMBER:
2691       if (b == CPP_NUMBER)      return CPP_NUMBER;
2692       if (b == CPP_NAME)        return CPP_NUMBER;
2693       if (b == CPP_DOT)         return CPP_NUMBER;
2694       /* Numbers cannot have length zero, so this is safe.  */
2695       if ((b == CPP_PLUS || b == CPP_MINUS)
2696           && VALID_SIGN ('+', token1->val.str.text[token1->val.str.len - 1]))
2697         return CPP_NUMBER;
2698       break;
2699
2700     default:
2701       break;
2702     }
2703
2704   return CPP_EOF;
2705 }
2706
2707 /* Check if TOKEN is to be ##-pasted with the token after it.  */
2708 static const cpp_token *
2709 maybe_paste_with_next (pfile, token)
2710      cpp_reader *pfile;
2711      const cpp_token *token;
2712 {
2713   cpp_token *pasted;
2714   const cpp_token *second;
2715   cpp_context *context = CURRENT_CONTEXT (pfile);
2716
2717   /* Is this token on the LHS of ## ? */
2718
2719   while ((token->flags & PASTE_LEFT)
2720          || ((context->flags & CONTEXT_PASTEL)
2721              && context->posn == context->count))
2722     {
2723       /* Suppress macro expansion for next token, but don't conflict
2724          with the other method of suppression.  If it is an argument,
2725          macro expansion within the argument will still occur.  */
2726       pfile->paste_level = pfile->cur_context;
2727       second = _cpp_get_token (pfile);
2728       pfile->paste_level = 0;
2729
2730       /* Ignore placemarker argument tokens (cannot be from an empty
2731          macro since macros are not expanded).  */
2732       if (token->type == CPP_PLACEMARKER)
2733         pasted = duplicate_token (pfile, second);
2734       else if (second->type == CPP_PLACEMARKER)
2735         {
2736           cpp_context *mac_context = CURRENT_CONTEXT (pfile) - 1;
2737           /* GCC has special extended semantics for a ## b where b is
2738              a varargs parameter: a disappears if b consists of no
2739              tokens.  This extension is deprecated.  */
2740           if ((mac_context->u.list->flags & GNU_REST_ARGS)
2741               && (mac_context->u.list->tokens[mac_context->posn-1].val.aux + 1
2742                   == (unsigned) mac_context->u.list->paramc))
2743             {
2744               cpp_warning (pfile, "deprecated GNU ## extension used");
2745               pasted = duplicate_token (pfile, second);
2746             }
2747           else
2748             pasted = duplicate_token (pfile, token);
2749         }
2750       else
2751         {
2752           int digraph = 0;
2753           enum cpp_ttype type = can_paste (pfile, token, second, &digraph);
2754
2755           if (type == CPP_EOF)
2756             {
2757               if (CPP_OPTION (pfile, warn_paste))
2758                 cpp_warning (pfile,
2759                         "pasting would not give a valid preprocessing token");
2760               _cpp_push_token (pfile, second);
2761               return token;
2762             }
2763
2764           if (type == CPP_NAME || type == CPP_NUMBER)
2765             {
2766               /* Join spellings.  */
2767               U_CHAR *buf, *end;
2768
2769               pasted = get_temp_token (pfile);
2770               buf = (U_CHAR *) alloca (TOKEN_LEN (token) + TOKEN_LEN (second));
2771               end = spell_token (pfile, token, buf);
2772               end = spell_token (pfile, second, end);
2773               *end = '\0';
2774
2775               if (type == CPP_NAME)
2776                 pasted->val.node = cpp_lookup (pfile, buf, end - buf);
2777               else
2778                 {
2779                   pasted->val.str.text = uxstrdup (buf);
2780                   pasted->val.str.len = end - buf;
2781                 }
2782             }
2783           else if (type == CPP_WCHAR || type == CPP_WSTRING)
2784             pasted = duplicate_token (pfile, second);
2785           else
2786             {
2787               pasted = get_temp_token (pfile);
2788               pasted->val.integer = 0;
2789             }
2790
2791           pasted->type = type;
2792           pasted->flags = digraph ? DIGRAPH : 0;
2793         }
2794
2795       /* The pasted token gets the whitespace flags and position of the
2796          first token, the PASTE_LEFT flag of the second token, plus the
2797          PASTED flag to indicate it is the result of a paste.  However, we
2798          want to preserve the DIGRAPH flag.  */
2799       pasted->flags &= ~(PREV_WHITE | BOL | PASTE_LEFT);
2800       pasted->flags |= ((token->flags & (PREV_WHITE | BOL))
2801                         | (second->flags & PASTE_LEFT) | PASTED);
2802       pasted->col = token->col;
2803       pasted->line = token->line;
2804
2805       /* See if there is another token to be pasted onto the one we just
2806          constructed.  */
2807       token = pasted;
2808       context = CURRENT_CONTEXT (pfile);
2809       /* and loop */
2810     }
2811   return token;
2812 }
2813
2814 /* Convert a token sequence to a single string token according to the
2815    rules of the ISO C #-operator.  */
2816 #define INIT_SIZE 200
2817 static cpp_token *
2818 stringify_arg (pfile, token)
2819      cpp_reader *pfile;
2820      const cpp_token *token;
2821 {
2822   cpp_token *result;
2823   unsigned char *main_buf;
2824   unsigned int prev_value, backslash_count = 0;
2825   unsigned int buf_used = 0, whitespace = 0, buf_cap = INIT_SIZE;
2826
2827   push_arg_context (pfile, token);
2828   prev_value  = prevent_macro_expansion (pfile);
2829   main_buf = (unsigned char *) xmalloc (buf_cap);
2830
2831   result = get_temp_token (pfile);
2832   ASSIGN_FLAGS_AND_POS (result, token);
2833
2834   for (; (token = _cpp_get_token (pfile))->type != CPP_EOF; )
2835     {
2836       int escape;
2837       unsigned char *buf;
2838       unsigned int len = TOKEN_LEN (token);
2839
2840       escape = (token->type == CPP_STRING || token->type == CPP_WSTRING
2841                 || token->type == CPP_CHAR || token->type == CPP_WCHAR);
2842       if (escape)
2843         len *= 4 + 1;
2844
2845       if (buf_used + len > buf_cap)
2846         {
2847           buf_cap = buf_used + len + INIT_SIZE;
2848           main_buf = xrealloc (main_buf, buf_cap);
2849         }
2850
2851       if (whitespace && (token->flags & PREV_WHITE))
2852         main_buf[buf_used++] = ' ';
2853
2854       if (escape)
2855         buf = (unsigned char *) xmalloc (len);
2856       else
2857         buf = main_buf + buf_used;
2858       
2859       len = spell_token (pfile, token, buf) - buf;
2860       if (escape)
2861         {
2862           buf_used = quote_string (&main_buf[buf_used], buf, len) - main_buf;
2863           free (buf);
2864         }
2865       else
2866         buf_used += len;
2867
2868       whitespace = 1;
2869       if (token->type == CPP_BACKSLASH)
2870         backslash_count++;
2871       else
2872         backslash_count = 0;
2873     }
2874
2875   /* Ignore the final \ of invalid string literals.  */
2876   if (backslash_count & 1)
2877     {
2878       cpp_warning (pfile, "invalid string literal, ignoring final '\\'");
2879       buf_used--;
2880     }
2881
2882   result->type = CPP_STRING;
2883   result->val.str.text = main_buf;
2884   result->val.str.len = buf_used;
2885   restore_macro_expansion (pfile, prev_value);
2886   return result;
2887 }
2888
2889 /* Allocate more room on the context stack of PFILE.  */
2890 static void
2891 expand_context_stack (pfile)
2892      cpp_reader *pfile;
2893 {
2894   pfile->context_cap += pfile->context_cap + 20;
2895   pfile->contexts = (cpp_context *)
2896     xrealloc (pfile->contexts, pfile->context_cap * sizeof (cpp_context));
2897 }
2898
2899 /* Push the context of macro NODE onto the context stack.  TOKEN is
2900    the CPP_NAME token invoking the macro.  */
2901 static int
2902 push_macro_context (pfile, token)
2903      cpp_reader *pfile;
2904      const cpp_token *token;
2905 {
2906   unsigned char orig_flags;
2907   macro_args *args;
2908   cpp_context *context;
2909   cpp_hashnode *node = token->val.node;
2910
2911   /* Token's flags may change when parsing args containing a nested
2912      invocation of this macro.  */
2913   orig_flags = token->flags & (PREV_WHITE | BOL);
2914   args = 0;
2915   if (node->value.expansion->paramc >= 0)
2916     {
2917       unsigned int error, prev_nme;
2918
2919       /* Allocate room for the argument contexts, and parse them.  */
2920       args  = (macro_args *) xmalloc (sizeof (macro_args));
2921       args->ends = (unsigned int *)
2922         xmalloc (node->value.expansion->paramc * sizeof (unsigned int));
2923       args->tokens = 0;
2924       args->capacity = 0;
2925       args->used = 0;
2926       args->level = pfile->cur_context;
2927
2928       prev_nme = prevent_macro_expansion (pfile);
2929       pfile->args = args;
2930       error = parse_args (pfile, node, args);
2931       pfile->args = 0;
2932       restore_macro_expansion (pfile, prev_nme);
2933       if (error)
2934         {
2935           free_macro_args (args);
2936           return 1;
2937         }
2938     }
2939
2940   /* Now push its context.  */
2941   pfile->cur_context++;
2942   if (pfile->cur_context == pfile->context_cap)
2943     expand_context_stack (pfile);
2944
2945   context = CURRENT_CONTEXT (pfile);
2946   context->u.list = node->value.expansion;
2947   context->args = args;
2948   context->posn = 0;
2949   context->count = context->u.list->tokens_used;
2950   context->level = pfile->cur_context;
2951   context->flags = 0;
2952   context->pushed_token = 0;
2953
2954   /* Set the flags of the first token.  We know there must
2955      be one, empty macros are a single placemarker token.  */
2956   MODIFY_FLAGS_AND_POS (&context->u.list->tokens[0], token, orig_flags);
2957
2958   return 0;
2959 }
2960
2961 /* Push an argument to the current macro onto the context stack.
2962    TOKEN is the MACRO_ARG token representing the argument expansion.  */
2963 static void
2964 push_arg_context (pfile, token)
2965      cpp_reader *pfile;
2966      const cpp_token *token;
2967 {
2968   cpp_context *context;
2969   macro_args *args;
2970
2971   pfile->cur_context++;
2972   if (pfile->cur_context == pfile->context_cap)
2973       expand_context_stack (pfile);
2974
2975   context = CURRENT_CONTEXT (pfile);
2976   args = context[-1].args;
2977
2978   context->count = token->val.aux ? args->ends[token->val.aux - 1]: 0;
2979   context->u.arg = args->tokens + context->count;
2980   context->count = args->ends[token->val.aux] - context->count;
2981   context->args = 0;
2982   context->posn = 0;
2983   context->level = args->level;
2984   context->flags = CONTEXT_ARG | CONTEXT_RAW;
2985   context->pushed_token = 0;
2986
2987   /* Set the flags of the first token.  There is one.  */
2988   {
2989     const cpp_token *first = context->u.arg[0];
2990     if (!first)
2991       first = context->u.arg[1];
2992
2993     MODIFY_FLAGS_AND_POS ((cpp_token *) first, token,
2994                           token->flags & (PREV_WHITE | BOL));
2995   }
2996
2997   if (token->flags & PASTE_LEFT)
2998     context->flags |= CONTEXT_PASTEL;
2999   if (pfile->paste_level)
3000     context->flags |= CONTEXT_PASTER;
3001 }
3002
3003 /* "Unget" a token.  It is effectively inserted in the token queue and
3004    will be returned by the next call to get_raw_token.  */
3005 void
3006 _cpp_push_token (pfile, token)
3007      cpp_reader *pfile;
3008      const cpp_token *token;
3009 {
3010   cpp_context *context = CURRENT_CONTEXT (pfile);
3011   if (context->pushed_token)
3012     cpp_ice (pfile, "two tokens pushed in a row");
3013   if (token->type != CPP_EOF)
3014     context->pushed_token = token;
3015   /* Don't push back a directive's CPP_EOF, step back instead.  */
3016   else if (pfile->cur_context == 0)
3017     pfile->contexts[0].posn--;
3018 }
3019
3020 /* Handle a preprocessing directive.  TOKEN is the CPP_HASH token
3021    introducing the directive.  */
3022 static void
3023 process_directive (pfile, token)
3024      cpp_reader *pfile;
3025      const cpp_token *token;
3026 {
3027   const struct directive *d = pfile->token_list.directive;
3028   int prev_nme = 0;
3029
3030   /* Skip over the directive name.  */
3031   if (token[1].type == CPP_NAME)
3032     _cpp_get_raw_token (pfile);
3033   else if (token[1].type != CPP_NUMBER)
3034     cpp_ice (pfile, "directive begins with %s?!",
3035              token_names[token[1].type]);
3036
3037   /* Flush pending tokens at this point, in case the directive produces
3038      output.  XXX Directive output won't be visible to a direct caller of
3039      cpp_get_token.  */
3040   if (pfile->printer && CPP_WRITTEN (pfile) - pfile->printer->written)
3041     cpp_output_tokens (pfile, pfile->printer, pfile->token_list.line);
3042
3043   if (! (d->flags & EXPAND))
3044     prev_nme = prevent_macro_expansion (pfile);
3045   (void) (*d->handler) (pfile);
3046   if (! (d->flags & EXPAND))
3047     restore_macro_expansion (pfile, prev_nme);
3048   _cpp_skip_rest_of_line (pfile);
3049 }
3050
3051 /* The external interface to return the next token.  All macro
3052    expansion and directive processing is handled internally, the
3053    caller only ever sees the output after preprocessing.  */
3054 const cpp_token *
3055 cpp_get_token (pfile)
3056      cpp_reader *pfile;
3057 {
3058   const cpp_token *token;
3059   /* Loop till we hit a non-directive, non-placemarker token.  */
3060   for (;;)
3061     {
3062       token = _cpp_get_token (pfile);
3063
3064       if (token->type == CPP_PLACEMARKER)
3065         continue;
3066
3067       if (token->type == CPP_HASH && token->flags & BOL
3068           && pfile->token_list.directive)
3069         {
3070           process_directive (pfile, token);
3071           continue;
3072         }
3073
3074       return token;
3075     }
3076 }
3077
3078 /* The internal interface to return the next token.  There are two
3079    differences between the internal and external interfaces: the
3080    internal interface may return a PLACEMARKER token, and it does not
3081    process directives.  */
3082 const cpp_token *
3083 _cpp_get_token (pfile)
3084      cpp_reader *pfile;
3085 {
3086   const cpp_token *token;
3087   cpp_hashnode *node;
3088
3089   /* Loop until we hit a non-macro token.  */
3090   for (;;)
3091     {
3092       token = get_raw_token (pfile);
3093
3094       /* Short circuit EOF. */
3095       if (token->type == CPP_EOF)
3096         return token;
3097
3098       /* If we are skipping... */
3099       if (pfile->skipping)
3100         {
3101           /* we still have to process directives,  */
3102           if (pfile->token_list.directive)
3103             return token;
3104
3105           /* but everything else is ignored.  */
3106           _cpp_skip_rest_of_line (pfile);
3107           continue;
3108         }
3109
3110       /* If there's a potential control macro and we get here, then that
3111          #ifndef didn't cover the entire file and its argument shouldn't
3112          be taken as a control macro.  */
3113       pfile->potential_control_macro = 0;
3114
3115       /* See if there's a token to paste with this one.  */
3116       if (!pfile->paste_level)
3117         token = maybe_paste_with_next (pfile, token);
3118
3119       /* If it isn't a macro, return it now.  */
3120       if (token->type != CPP_NAME
3121           || token->val.node->type == T_VOID)
3122         return token;
3123
3124       /* Is macro expansion disabled in general?  */
3125       if (pfile->no_expand_level == pfile->cur_context || pfile->paste_level)
3126         return token;
3127  
3128       node = token->val.node;
3129       if (node->type != T_MACRO)
3130         return special_symbol (pfile, node, token);
3131
3132       if (is_macro_disabled (pfile, node->value.expansion, token))
3133         return token;
3134
3135       if (pfile->cur_context > CPP_STACK_MAX)
3136         {
3137           cpp_error (pfile, "macros nested too deep invoking '%s'", node->name);
3138           return token;
3139         }
3140
3141       if (push_macro_context (pfile, token))
3142         return token;
3143       /* else loop */
3144     }
3145 }
3146
3147 /* Returns the next raw token, i.e. without performing macro
3148    expansion.  Argument contexts are automatically entered.  */
3149 static const cpp_token *
3150 get_raw_token (pfile)
3151      cpp_reader *pfile;
3152 {
3153   const cpp_token *result;
3154   cpp_context *context;
3155
3156   for (;;)
3157     {
3158       context = CURRENT_CONTEXT (pfile);
3159       if (context->pushed_token)
3160         {
3161           result = context->pushed_token;
3162           context->pushed_token = 0;
3163         }
3164       else if (context->posn == context->count)
3165         {
3166           if (pop_context (pfile))
3167             return &eof_token;
3168           continue;
3169         }
3170       else
3171         {
3172           if (IS_ARG_CONTEXT (context))
3173             {
3174               result = context->u.arg[context->posn++];
3175               if (result == 0)
3176                 {
3177                   context->flags ^= CONTEXT_RAW;
3178                   result = context->u.arg[context->posn++];
3179                 }
3180               return result;    /* Cannot be a CPP_MACRO_ARG */
3181             }
3182           result = &context->u.list->tokens[context->posn++];
3183         }
3184
3185       if (result->type != CPP_MACRO_ARG)
3186         return result;
3187
3188       if (result->flags & STRINGIFY_ARG)
3189         return stringify_arg (pfile, result);
3190
3191       push_arg_context (pfile, result);
3192     }
3193 }
3194
3195 /* Internal interface to get the token without macro expanding.  */
3196 const cpp_token *
3197 _cpp_get_raw_token (pfile)
3198      cpp_reader *pfile;
3199 {
3200   int prev_nme = prevent_macro_expansion (pfile);
3201   const cpp_token *result = _cpp_get_token (pfile);
3202   restore_macro_expansion (pfile, prev_nme);
3203   return result;
3204 }
3205
3206 /* A thin wrapper to lex_line.  CLEAR is non-zero if the current token
3207    list should be overwritten, or zero if we need to append
3208    (typically, if we are within the arguments to a macro, or looking
3209    for the '(' to start a function-like macro invocation).  */
3210 static int
3211 lex_next (pfile, clear)
3212      cpp_reader *pfile;
3213      int clear;
3214 {
3215   cpp_toklist *list = &pfile->token_list;
3216   const cpp_token *old_list = list->tokens;
3217   unsigned int old_used = list->tokens_used;
3218
3219   if (clear)
3220     {
3221       /* Release all temporary tokens.  */
3222       _cpp_clear_toklist (list);
3223       pfile->contexts[0].posn = 0;
3224       if (pfile->temp_used)
3225         release_temp_tokens (pfile);
3226     }
3227      
3228   lex_line (pfile, list);
3229   pfile->contexts[0].count = list->tokens_used;
3230
3231   if (!clear && pfile->args)
3232     {
3233       /* Fix up argument token pointers.  */
3234       if (old_list != list->tokens)
3235         {
3236           unsigned int i;
3237
3238           for (i = 0; i < pfile->args->used; i++)
3239             {
3240               const cpp_token *token = pfile->args->tokens[i];
3241               if (token >= old_list && token < old_list + old_used)
3242                 pfile->args->tokens[i] = (const cpp_token *)
3243                 ((char *) token + ((char *) list->tokens - (char *) old_list));
3244             }
3245         }
3246
3247       /* 6.10.3 paragraph 11: If there are sequences of preprocessing
3248          tokens within the list of arguments that would otherwise act as
3249          preprocessing directives, the behavior is undefined.
3250
3251          This implementation will report a hard error and treat the
3252          'sequence of preprocessing tokens' as part of the macro argument,
3253          not a directive.  
3254
3255          Note if pfile->args == 0, we're OK since we're only inside a
3256          macro argument after a '('.  */
3257       if (list->directive)
3258         {
3259           cpp_error_with_line (pfile, list->tokens[old_used].line,
3260                                list->tokens[old_used].col,
3261                                "#%s may not be used inside a macro argument",
3262                                list->directive->name);
3263           return 1;
3264         }
3265     }
3266
3267   return 0;
3268 }
3269
3270 /* Pops a context off the context stack.  If we're at the bottom, lexes
3271    the next logical line.  Returns EOF if we're at the end of the
3272    argument list to the # operator, or if it is illegal to "overflow"
3273    into the rest of the file (e.g. 6.10.3.1.1).  */
3274 static int
3275 pop_context (pfile)
3276      cpp_reader *pfile;
3277 {
3278   cpp_context *context;
3279
3280   if (pfile->cur_context == 0)
3281     {
3282       /* If we are currently processing a directive, do not advance.  6.10
3283          paragraph 2: A new-line character ends the directive even if it
3284          occurs within what would otherwise be an invocation of a
3285          function-like macro.  */
3286       if (pfile->token_list.directive)
3287         return 1;
3288
3289       return lex_next (pfile, pfile->no_expand_level == UINT_MAX);
3290     }
3291
3292   /* Argument contexts, when parsing args or handling # operator
3293      return CPP_EOF at the end.  */
3294   context = CURRENT_CONTEXT (pfile);
3295   if (IS_ARG_CONTEXT (context) && pfile->cur_context == pfile->no_expand_level)
3296     return 1;
3297
3298   /* Free resources when leaving macro contexts.  */
3299   if (context->args)
3300     free_macro_args (context->args);
3301
3302   if (pfile->cur_context == pfile->no_expand_level)
3303     pfile->no_expand_level--;
3304   pfile->cur_context--;
3305
3306   return 0;
3307 }
3308
3309 /* Turn off macro expansion at the current context level.  */
3310 static unsigned int
3311 prevent_macro_expansion (pfile)
3312      cpp_reader *pfile;
3313 {
3314   unsigned int prev_value = pfile->no_expand_level;
3315   pfile->no_expand_level = pfile->cur_context;
3316   return prev_value;
3317 }
3318
3319 /* Restore macro expansion to its previous state.  */
3320 static void
3321 restore_macro_expansion (pfile, prev_value)
3322      cpp_reader *pfile;
3323      unsigned int prev_value;
3324 {
3325   pfile->no_expand_level = prev_value;
3326 }
3327
3328 /* Used by cpperror.c to obtain the correct line and column to report
3329    in a diagnostic.  */
3330 unsigned int
3331 _cpp_get_line (pfile, pcol)
3332      cpp_reader *pfile;
3333      unsigned int *pcol;
3334 {
3335   unsigned int index;
3336   const cpp_token *cur_token;
3337
3338   if (pfile->in_lex_line)
3339     index = pfile->token_list.tokens_used;
3340   else
3341     index = pfile->contexts[0].posn;
3342
3343   cur_token = &pfile->token_list.tokens[index - 1];
3344   if (pcol)
3345     *pcol = cur_token->col;
3346   return cur_token->line;
3347 }
3348
3349 #define DSC(str) (const U_CHAR *)str, sizeof str - 1
3350 static const char * const monthnames[] =
3351 {
3352   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3353   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
3354 };
3355
3356 /* Handle builtin macros like __FILE__.  */
3357 static const cpp_token *
3358 special_symbol (pfile, node, token)
3359      cpp_reader *pfile;
3360      cpp_hashnode *node;
3361      const cpp_token *token;
3362 {
3363   cpp_token *result;
3364   cpp_buffer *ip;
3365
3366   switch (node->type)
3367     {
3368     case T_FILE:
3369     case T_BASE_FILE:
3370       {
3371         const char *file;
3372
3373         ip = CPP_BUFFER (pfile);
3374         if (ip == 0)
3375           file = "";
3376         else
3377           {
3378             if (node->type == T_BASE_FILE)
3379               while (CPP_PREV_BUFFER (ip) != NULL)
3380                 ip = CPP_PREV_BUFFER (ip);
3381
3382             file = ip->nominal_fname;
3383           }
3384         result = make_string_token (get_temp_token (pfile), (U_CHAR *) file,
3385                                     strlen (file));
3386       }
3387       break;
3388         
3389     case T_INCLUDE_LEVEL:
3390       /* pfile->include_depth counts the primary source as level 1,
3391          but historically __INCLUDE_DEPTH__ has called the primary
3392          source level 0.  */
3393       result = alloc_number_token (pfile, pfile->include_depth - 1);
3394       break;
3395
3396     case T_SPECLINE:
3397       /* If __LINE__ is embedded in a macro, it must expand to the
3398          line of the macro's invocation, not its definition.
3399          Otherwise things like assert() will not work properly.  */
3400       result = alloc_number_token (pfile, _cpp_get_line (pfile, NULL));
3401       break;
3402
3403     case T_STDC:
3404       {
3405         int stdc = 1;
3406
3407 #ifdef STDC_0_IN_SYSTEM_HEADERS
3408         if (CPP_IN_SYSTEM_HEADER (pfile)
3409             && pfile->spec_nodes->n__STRICT_ANSI__->type == T_VOID)
3410           stdc = 0;
3411 #endif
3412         result = alloc_number_token (pfile, stdc);
3413       }
3414       break;
3415
3416     case T_DATE:
3417     case T_TIME:
3418       if (pfile->date == 0)
3419         {
3420           /* Allocate __DATE__ and __TIME__ from permanent storage,
3421              and save them in pfile so we don't have to do this again.
3422              We don't generate these strings at init time because
3423              time() and localtime() are very slow on some systems.  */
3424           time_t tt = time (NULL);
3425           struct tm *tb = localtime (&tt);
3426
3427           pfile->date = make_string_token
3428             ((cpp_token *) xmalloc (sizeof (cpp_token)), DSC("Oct 11 1347"));
3429           pfile->time = make_string_token
3430             ((cpp_token *) xmalloc (sizeof (cpp_token)), DSC("12:34:56"));
3431
3432           sprintf ((char *) pfile->date->val.str.text, "%s %2d %4d",
3433                    monthnames[tb->tm_mon], tb->tm_mday, tb->tm_year + 1900);
3434           sprintf ((char *) pfile->time->val.str.text, "%02d:%02d:%02d",
3435                    tb->tm_hour, tb->tm_min, tb->tm_sec);
3436         }
3437       result = node->type == T_DATE ? pfile->date: pfile->time;
3438       break;
3439
3440     case T_POISON:
3441       cpp_error (pfile, "attempt to use poisoned \"%s\"", node->name);
3442       return token;
3443
3444     default:
3445       cpp_ice (pfile, "invalid special hash type");
3446       return token;
3447     }
3448
3449   ASSIGN_FLAGS_AND_POS (result, token);
3450   return result;
3451 }
3452 #undef DSC
3453
3454 /* Dump the original user's spelling of argument index ARG_NO to the
3455    macro whose expansion is LIST.  */
3456 static void
3457 dump_param_spelling (pfile, list, arg_no)
3458      cpp_reader *pfile;
3459      const cpp_toklist *list;
3460      unsigned int arg_no;
3461 {
3462   const U_CHAR *param = list->namebuf;
3463
3464   while (arg_no--)
3465     param += ustrlen (param) + 1;
3466   CPP_PUTS (pfile, param, ustrlen (param));
3467 }
3468
3469 /* Dump a token list to the output.  */
3470 void
3471 _cpp_dump_list (pfile, list, token, flush)
3472      cpp_reader *pfile;
3473      const cpp_toklist *list;
3474      const cpp_token *token;
3475      int flush;
3476 {
3477   const cpp_token *limit = list->tokens + list->tokens_used;
3478   const cpp_token *prev = 0;
3479
3480   /* Avoid the CPP_EOF.  */
3481   if (list->directive)
3482     limit--;
3483
3484   while (token < limit)
3485     {
3486       if (token->type == CPP_MACRO_ARG)
3487         {
3488           if (token->flags & PREV_WHITE)
3489             CPP_PUTC (pfile, ' ');
3490           if (token->flags & STRINGIFY_ARG)
3491             CPP_PUTC (pfile, '#');
3492           dump_param_spelling (pfile, list, token->val.aux);
3493         }
3494       else
3495         output_token (pfile, token, prev);
3496       if (token->flags & PASTE_LEFT)
3497         CPP_PUTS (pfile, " ##", 3);
3498       prev = token;
3499       token++;
3500     }
3501
3502   if (flush && pfile->printer)
3503     cpp_output_tokens (pfile, pfile->printer, pfile->token_list.line);
3504 }
3505
3506 /* Allocate pfile->input_buffer, and initialize trigraph_map[]
3507    if it hasn't happened already.  */
3508
3509 void
3510 _cpp_init_input_buffer (pfile)
3511      cpp_reader *pfile;
3512 {
3513   cpp_context *base;
3514
3515   init_trigraph_map ();
3516   _cpp_init_toklist (&pfile->token_list, DUMMY_TOKEN);
3517   pfile->no_expand_level = UINT_MAX;
3518   pfile->context_cap = 20;
3519   pfile->cur_context = 0;
3520
3521   pfile->contexts = (cpp_context *)
3522     xmalloc (pfile->context_cap * sizeof (cpp_context));
3523
3524   /* Clear the base context.  */
3525   base = &pfile->contexts[0];
3526   base->u.list = &pfile->token_list;
3527   base->posn = 0;
3528   base->count = 0;
3529   base->args = 0;
3530   base->level = 0;
3531   base->flags = 0;
3532   base->pushed_token = 0;
3533 }
3534
3535 /* Moves to the end of the directive line, popping contexts as
3536    necessary.  */
3537 void
3538 _cpp_skip_rest_of_line (pfile)
3539      cpp_reader *pfile;
3540 {
3541   /* Discard all stacked contexts.  */
3542   int i;
3543   for (i = pfile->cur_context; i > 0; i--)
3544     if (pfile->contexts[i].args)
3545       free_macro_args (pfile->contexts[i].args);
3546
3547   if (pfile->no_expand_level <= pfile->cur_context)
3548     pfile->no_expand_level = 0;
3549   pfile->cur_context = 0;
3550
3551   /* Clear the base context, and clear the directive pointer so that
3552      get_raw_token will advance to the next line.  */
3553   pfile->contexts[0].count = 0;
3554   pfile->contexts[0].posn = 0;
3555   pfile->token_list.directive = 0;
3556 }
3557
3558 /* Directive handler wrapper used by the command line option
3559    processor.  */
3560 void
3561 _cpp_run_directive (pfile, dir, buf, count)
3562      cpp_reader *pfile;
3563      const struct directive *dir;
3564      const char *buf;
3565      size_t count;
3566 {
3567   if (cpp_push_buffer (pfile, (const U_CHAR *)buf, count) != NULL)
3568     {
3569       unsigned int prev_lvl = 0;
3570
3571       /* Scan the line now, else prevent_macro_expansion won't work.  */
3572       lex_next (pfile, 1);
3573       if (! (dir->flags & EXPAND))
3574         prev_lvl = prevent_macro_expansion (pfile);
3575
3576       (void) (*dir->handler) (pfile);
3577
3578       if (! (dir->flags & EXPAND))
3579         restore_macro_expansion (pfile, prev_lvl);
3580       
3581       _cpp_skip_rest_of_line (pfile);
3582       cpp_pop_buffer (pfile);
3583     }
3584 }