OSDN Git Service

* cppexp.c (parse_assertion): New.
[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 #include "config.h"
24 #include "system.h"
25 #include "intl.h"
26 #include "cpplib.h"
27 #include "cpphash.h"
28
29 #define PEEKBUF(BUFFER, N) \
30   ((BUFFER)->rlimit - (BUFFER)->cur > (N) ? (BUFFER)->cur[N] : EOF)
31 #define GETBUF(BUFFER) \
32   ((BUFFER)->cur < (BUFFER)->rlimit ? *(BUFFER)->cur++ : EOF)
33 #define FORWARDBUF(BUFFER, N) ((BUFFER)->cur += (N))
34
35 #define PEEKN(N) PEEKBUF (CPP_BUFFER (pfile), N)
36 #define FORWARD(N) FORWARDBUF (CPP_BUFFER (pfile), (N))
37 #define GETC() GETBUF (CPP_BUFFER (pfile))
38 #define PEEKC() PEEKBUF (CPP_BUFFER (pfile), 0)
39
40 static void skip_block_comment  PARAMS ((cpp_reader *));
41 static void skip_line_comment   PARAMS ((cpp_reader *));
42 static int maybe_macroexpand    PARAMS ((cpp_reader *, long));
43 static int skip_comment         PARAMS ((cpp_reader *, int));
44 static int copy_comment         PARAMS ((cpp_reader *, int));
45 static void skip_string         PARAMS ((cpp_reader *, int));
46 static void parse_string        PARAMS ((cpp_reader *, int));
47 static U_CHAR *find_position    PARAMS ((U_CHAR *, U_CHAR *, unsigned long *));
48 static void null_warning        PARAMS ((cpp_reader *, unsigned int));
49
50 static void safe_fwrite         PARAMS ((cpp_reader *, const U_CHAR *,
51                                          size_t, FILE *));
52 static void output_line_command PARAMS ((cpp_reader *, cpp_printer *,
53                                          unsigned int));
54 static void bump_column         PARAMS ((cpp_printer *, unsigned int,
55                                          unsigned int));
56 static void expand_name_space   PARAMS ((cpp_toklist *, unsigned int));
57 static void expand_token_space  PARAMS ((cpp_toklist *));
58 static void pedantic_whitespace PARAMS ((cpp_reader *, U_CHAR *,
59                                          unsigned int));
60
61 #define auto_expand_name_space(list) \
62     expand_name_space ((list), 1 + (list)->name_cap / 2)
63
64 #ifdef NEW_LEXER
65
66 static void expand_comment_space PARAMS ((cpp_toklist *));
67 void init_trigraph_map PARAMS ((void));
68 static unsigned char* trigraph_replace PARAMS ((cpp_reader *, unsigned char *,
69                                                 unsigned char *));
70 static const unsigned char *backslash_start PARAMS ((cpp_reader *,
71                                                      const unsigned char *));
72 static int skip_block_comment2 PARAMS ((cpp_reader *));
73 static int skip_line_comment2 PARAMS ((cpp_reader *));
74 static void skip_whitespace PARAMS ((cpp_reader *, int));
75 static void parse_name PARAMS ((cpp_reader *, cpp_toklist *, cpp_name *));
76 static void parse_number PARAMS ((cpp_reader *, cpp_toklist *, cpp_name *));
77 static void parse_string2 PARAMS ((cpp_reader *, cpp_toklist *, cpp_name *,
78                                   unsigned int));
79 static int trigraph_ok PARAMS ((cpp_reader *, const unsigned char *));
80 static void save_comment PARAMS ((cpp_toklist *, const unsigned char *,
81                                   unsigned int, unsigned int, unsigned int));
82 void _cpp_lex_line PARAMS ((cpp_reader *, cpp_toklist *));
83
84 static void _cpp_output_list PARAMS ((cpp_reader *, cpp_toklist *));
85
86 static unsigned char * spell_token PARAMS ((cpp_reader *, cpp_token *,
87                                             unsigned char *, int));
88
89 typedef unsigned int (* speller) PARAMS ((unsigned char *, cpp_toklist *,
90                                           cpp_token *));
91
92 /* Macros on a cpp_name.  */
93 #define INIT_NAME(list, name) \
94   do {(name).len = 0; \
95       (name).text = (list)->namebuf + (list)->name_used;} while (0)
96
97 #define IS_DIRECTIVE(list) (TOK_TYPE (list, 0) == CPP_HASH)
98
99 /* Maybe put these in the ISTABLE eventually.  */
100 #define IS_HSPACE(c) ((c) == ' ' || (c) == '\t')
101 #define IS_NEWLINE(c) ((c) == '\n' || (c) == '\r')
102
103 /* Handle LF, CR, CR-LF and LF-CR style newlines.  Assumes next
104    character, if any, is in buffer.  */
105 #define handle_newline(cur, limit, c) \
106   do {\
107   if ((cur) < (limit) && *(cur) == '\r' + '\n' - c) \
108     (cur)++; \
109   CPP_BUMP_LINE_CUR (pfile, (cur)); \
110   pfile->col_adjust = 0; \
111   } while (0)
112
113 #define IMMED_TOKEN() (!(cur_token->flags & PREV_WHITESPACE))
114 #define PREV_TOKEN_TYPE (cur_token[-1].type)
115
116 #define PUSH_TOKEN(ttype) cur_token++->type = ttype
117 #define REVISE_TOKEN(ttype) cur_token[-1].type = ttype
118 #define BACKUP_TOKEN(ttype) (--cur_token)->type = ttype
119 #define BACKUP_DIGRAPH(ttype) do { \
120   BACKUP_TOKEN(ttype); cur_token->flags |= DIGRAPH;} while (0)
121
122 /* An upper bound on the number of bytes needed to spell a token,
123    including preceding whitespace.  */
124 #define TOKEN_LEN(token) (5 + (token_spellings[token->type].type > \
125                                SPELL_NONE ? token->val.name.len: 0))
126
127 #endif
128
129 /* Order here matters.  Those beyond SPELL_NONE store their spelling
130    in the token list, and it's length in the token->val.name.len.  */
131 #define SPELL_OPERATOR 0
132 #define SPELL_CHAR     2        /* FIXME: revert order after transition. */
133 #define SPELL_NONE     1
134 #define SPELL_IDENT    3
135 #define SPELL_STRING   4
136
137 #define T(e, s) {SPELL_OPERATOR, (const U_CHAR *) s},
138 #define I(e, s) {SPELL_IDENT, s},
139 #define S(e, s) {SPELL_STRING, s},
140 #define C(e, s) {SPELL_CHAR, s},
141 #define N(e, s) {SPELL_NONE, s},
142
143 static const struct token_spelling
144 {
145   U_CHAR type;
146   const U_CHAR *spelling;
147 } token_spellings [N_TTYPES + 1] = {TTYPE_TABLE {0, 0} };
148
149 #undef T
150 #undef I
151 #undef S
152 #undef C
153 #undef N
154
155 /* Re-allocates PFILE->token_buffer so it will hold at least N more chars.  */
156
157 void
158 _cpp_grow_token_buffer (pfile, n)
159      cpp_reader *pfile;
160      long n;
161 {
162   long old_written = CPP_WRITTEN (pfile);
163   pfile->token_buffer_size = n + 2 * pfile->token_buffer_size;
164   pfile->token_buffer = (U_CHAR *)
165     xrealloc(pfile->token_buffer, pfile->token_buffer_size);
166   CPP_SET_WRITTEN (pfile, old_written);
167 }
168
169 /* Allocate a new cpp_buffer for PFILE, and push it on the input buffer stack.
170    If BUFFER != NULL, then use the LENGTH characters in BUFFER
171    as the new input buffer.
172    Return the new buffer, or NULL on failure.  */
173
174 cpp_buffer *
175 cpp_push_buffer (pfile, buffer, length)
176      cpp_reader *pfile;
177      const U_CHAR *buffer;
178      long length;
179 {
180   cpp_buffer *buf = CPP_BUFFER (pfile);
181   cpp_buffer *new;
182   if (++pfile->buffer_stack_depth == CPP_STACK_MAX)
183     {
184       cpp_fatal (pfile, "macro or `#include' recursion too deep");
185       return NULL;
186     }
187
188   new = (cpp_buffer *) xcalloc (1, sizeof (cpp_buffer));
189
190   new->if_stack = pfile->if_stack;
191   new->buf = new->cur = buffer;
192   new->rlimit = buffer + length;
193   new->prev = buf;
194   new->mark = NULL;
195   new->line_base = NULL;
196
197   CPP_BUFFER (pfile) = new;
198   return new;
199 }
200
201 cpp_buffer *
202 cpp_pop_buffer (pfile)
203      cpp_reader *pfile;
204 {
205   cpp_buffer *buf = CPP_BUFFER (pfile);
206   if (ACTIVE_MARK_P (pfile))
207     cpp_ice (pfile, "mark active in cpp_pop_buffer");
208
209   if (buf->ihash)
210     {
211       _cpp_unwind_if_stack (pfile, buf);
212       if (buf->buf)
213         free ((PTR) buf->buf);
214       if (pfile->system_include_depth)
215         pfile->system_include_depth--;
216       if (pfile->potential_control_macro)
217         {
218           buf->ihash->control_macro = pfile->potential_control_macro;
219           pfile->potential_control_macro = 0;
220         }
221       pfile->input_stack_listing_current = 0;
222     }
223   else if (buf->macro)
224     {
225       HASHNODE *m = buf->macro;
226   
227       m->disabled = 0;
228       if ((m->type == T_FMACRO && buf->mapped)
229           || m->type == T_SPECLINE || m->type == T_FILE
230           || m->type == T_BASE_FILE || m->type == T_INCLUDE_LEVEL
231           || m->type == T_STDC)
232         free ((PTR) buf->buf);
233     }
234   CPP_BUFFER (pfile) = CPP_PREV_BUFFER (buf);
235   free (buf);
236   pfile->buffer_stack_depth--;
237   return CPP_BUFFER (pfile);
238 }
239
240 /* Deal with the annoying semantics of fwrite.  */
241 static void
242 safe_fwrite (pfile, buf, len, fp)
243      cpp_reader *pfile;
244      const U_CHAR *buf;
245      size_t len;
246      FILE *fp;
247 {
248   size_t count;
249
250   while (len)
251     {
252       count = fwrite (buf, 1, len, fp);
253       if (count == 0)
254         goto error;
255       len -= count;
256       buf += count;
257     }
258   return;
259
260  error:
261   cpp_notice_from_errno (pfile, CPP_OPTION (pfile, out_fname));
262 }
263
264 /* Notify the compiler proper that the current line number has jumped,
265    or the current file name has changed.  */
266
267 static void
268 output_line_command (pfile, print, line)
269      cpp_reader *pfile;
270      cpp_printer *print;
271      unsigned int line;
272 {
273   cpp_buffer *ip = cpp_file_buffer (pfile);
274   enum { same = 0, enter, leave, rname } change;
275   static const char * const codes[] = { "", " 1", " 2", "" };
276
277   if (CPP_OPTION (pfile, no_line_commands))
278     return;
279
280   /* Determine whether the current filename has changed, and if so,
281      how.  'nominal_fname' values are unique, so they can be compared
282      by comparing pointers.  */
283   if (ip->nominal_fname == print->last_fname)
284     change = same;
285   else
286     {
287       if (pfile->buffer_stack_depth == print->last_bsd)
288         change = rname;
289       else
290         {
291           if (pfile->buffer_stack_depth > print->last_bsd)
292             change = enter;
293           else
294             change = leave;
295           print->last_bsd = pfile->buffer_stack_depth;
296         }
297       print->last_fname = ip->nominal_fname;
298     }
299   /* If the current file has not changed, we can output a few newlines
300      instead if we want to increase the line number by a small amount.
301      We cannot do this if print->lineno is zero, because that means we
302      haven't output any line commands yet.  (The very first line
303      command output is a `same_file' command.)  */
304   if (change == same && print->lineno != 0
305       && line >= print->lineno && line < print->lineno + 8)
306     {
307       while (line > print->lineno)
308         {
309           putc ('\n', print->outf);
310           print->lineno++;
311         }
312       return;
313     }
314
315 #ifndef NO_IMPLICIT_EXTERN_C
316   if (CPP_OPTION (pfile, cplusplus))
317     fprintf (print->outf, "# %u \"%s\"%s%s%s\n", line, ip->nominal_fname,
318              codes[change],
319              ip->system_header_p ? " 3" : "",
320              (ip->system_header_p == 2) ? " 4" : "");
321   else
322 #endif
323     fprintf (print->outf, "# %u \"%s\"%s%s\n", line, ip->nominal_fname,
324              codes[change],
325              ip->system_header_p ? " 3" : "");
326   print->lineno = line;
327 }
328
329 /* Write the contents of the token_buffer to the output stream, and
330    clear the token_buffer.  Also handles generating line commands and
331    keeping track of file transitions.  */
332
333 void
334 cpp_output_tokens (pfile, print)
335      cpp_reader *pfile;
336      cpp_printer *print;
337 {
338   cpp_buffer *ip;
339
340   if (CPP_WRITTEN (pfile) - print->written)
341     {
342       if (CPP_PWRITTEN (pfile)[-1] == '\n' && print->lineno)
343         print->lineno++;
344       safe_fwrite (pfile, pfile->token_buffer,
345                    CPP_WRITTEN (pfile) - print->written, print->outf);
346     }
347
348   ip = cpp_file_buffer (pfile);
349   if (ip)
350     output_line_command (pfile, print, CPP_BUF_LINE (ip));
351
352   CPP_SET_WRITTEN (pfile, print->written);
353 }
354
355 /* Helper for cpp_output_list - increases the column number to match
356    what we expect it to be.  */
357
358 static void
359 bump_column (print, from, to)
360      cpp_printer *print;
361      unsigned int from, to;
362 {
363   unsigned int tabs, spcs;
364   unsigned int delta = to - from;
365
366   /* Only if FROM is 0, advance by tabs.  */
367   if (from == 0)
368     tabs = delta / 8, spcs = delta % 8;
369   else
370     tabs = 0, spcs = delta;
371
372   while (tabs--) putc ('\t', print->outf);
373   while (spcs--) putc (' ', print->outf);
374 }
375
376 /* Write out the list L onto pfile->token_buffer.  This function is
377    incomplete:
378
379    1) pfile->token_buffer is not going to continue to exist.
380    2) At the moment, tokens don't carry the information described
381    in cpplib.h; they are all strings.
382    3) The list has to be a complete line, and has to be written starting
383    at the beginning of a line.  */
384
385 void
386 cpp_output_list (pfile, print, list)
387      cpp_reader *pfile;
388      cpp_printer *print;
389      const cpp_toklist *list;
390 {
391   unsigned int i;
392   unsigned int curcol = 1;
393
394   /* XXX Probably does not do what is intended.  */
395   if (print->lineno != list->line)
396     output_line_command (pfile, print, list->line);
397   
398   for (i = 0; i < list->tokens_used; i++)
399     {
400       if (TOK_TYPE (list, i) == CPP_VSPACE)
401         {
402           output_line_command (pfile, print, list->tokens[i].aux);
403           continue;
404         }
405           
406       if (curcol < TOK_COL (list, i))
407         {
408           /* Insert space to bring the column to what it should be.  */
409           bump_column (print, curcol - 1, TOK_COL (list, i));
410           curcol = TOK_COL (list, i);
411         }
412       /* XXX We may have to insert space to prevent an accidental
413          token paste.  */
414       safe_fwrite (pfile, TOK_NAME (list, i), TOK_LEN (list, i), print->outf);
415       curcol += TOK_LEN (list, i);
416     }
417 }
418
419 /* Scan a string (which may have escape marks), perform macro expansion,
420    and write the result to the token_buffer.  */
421
422 void
423 _cpp_expand_to_buffer (pfile, buf, length)
424      cpp_reader *pfile;
425      const U_CHAR *buf;
426      int length;
427 {
428   cpp_buffer *stop;
429   enum cpp_ttype token;
430   U_CHAR *buf1;
431
432   if (length < 0)
433     {
434       cpp_ice (pfile, "length < 0 in cpp_expand_to_buffer");
435       return;
436     }
437
438   /* Copy the buffer, because it might be in an unsafe place - for
439      example, a sequence on the token_buffer, where the pointers will
440      be invalidated if we enlarge the token_buffer.  */
441   buf1 = alloca (length);
442   memcpy (buf1, buf, length);
443
444   /* Set up the input on the input stack.  */
445   stop = CPP_BUFFER (pfile);
446   if (cpp_push_buffer (pfile, buf1, length) == NULL)
447     return;
448   CPP_BUFFER (pfile)->has_escapes = 1;
449
450   /* Scan the input, create the output.  */
451   for (;;)
452     {
453       token = cpp_get_token (pfile);
454       if (token == CPP_EOF && CPP_BUFFER (pfile) == stop)
455         break;
456     }
457 }
458
459 /* Scan until CPP_BUFFER (PFILE) is exhausted, discarding output.  */
460
461 void
462 cpp_scan_buffer_nooutput (pfile)
463      cpp_reader *pfile;
464 {
465   cpp_buffer *stop = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
466   enum cpp_ttype token;
467   unsigned int old_written = CPP_WRITTEN (pfile);
468   /* In no-output mode, we can ignore everything but directives.  */
469   for (;;)
470     {
471       if (! pfile->only_seen_white)
472         _cpp_skip_rest_of_line (pfile);
473       token = cpp_get_token (pfile);
474       if (token == CPP_EOF && CPP_BUFFER (pfile) == stop)
475         break;
476     }
477   CPP_SET_WRITTEN (pfile, old_written);
478 }
479
480 /* Scan until CPP_BUFFER (pfile) is exhausted, writing output to PRINT.  */
481
482 void
483 cpp_scan_buffer (pfile, print)
484      cpp_reader *pfile;
485      cpp_printer *print;
486 {
487   cpp_buffer *stop = CPP_PREV_BUFFER (CPP_BUFFER (pfile));
488   enum cpp_ttype token;
489
490   for (;;)
491     {
492       token = cpp_get_token (pfile);
493       if (token == CPP_VSPACE || token == CPP_EOF
494           /* XXX Temporary kluge - force flush after #include only */
495           || (token == CPP_DIRECTIVE
496               && CPP_BUFFER (pfile)->nominal_fname != print->last_fname))
497         {
498           cpp_output_tokens (pfile, print);
499           if (token == CPP_EOF && CPP_BUFFER (pfile) == stop)
500             return;
501         }
502     }
503 }
504
505 /* Return the topmost cpp_buffer that corresponds to a file (not a macro).  */
506
507 cpp_buffer *
508 cpp_file_buffer (pfile)
509      cpp_reader *pfile;
510 {
511   cpp_buffer *ip;
512
513   for (ip = CPP_BUFFER (pfile); ip; ip = CPP_PREV_BUFFER (ip))
514     if (ip->ihash != NULL)
515       return ip;
516   return NULL;
517 }
518
519 /* Token-buffer helper functions.  */
520
521 /* Expand a token list's string space.  */
522 static void
523 expand_name_space (list, len)
524      cpp_toklist *list;
525      unsigned int len;
526 {
527   const U_CHAR *old_namebuf;
528
529   old_namebuf = list->namebuf;
530   list->name_cap += len;
531   list->namebuf = (unsigned char *) xrealloc (list->namebuf, list->name_cap);
532
533   /* Fix up token text pointers.  */
534   if (list->namebuf != old_namebuf)
535     {
536       unsigned int i;
537
538       for (i = 0; i < list->tokens_used; i++)
539         if (token_spellings[list->tokens[i].type].type > SPELL_NONE)
540           list->tokens[i].val.name.text += (list->namebuf - old_namebuf);
541     }
542 }
543
544 /* Expand the number of tokens in a list.  */
545 static void
546 expand_token_space (list)
547      cpp_toklist *list;
548 {
549   list->tokens_cap *= 2;
550   if (list->flags & LIST_OFFSET)
551     list->tokens--;
552   list->tokens = (cpp_token *)
553     xrealloc (list->tokens, (list->tokens_cap + 1) * sizeof (cpp_token));
554   if (list->flags & LIST_OFFSET)
555     list->tokens++;             /* Skip the dummy.  */
556 }
557
558 /* Initialize a token list.  We allocate an extra token in front of
559    the token list, as this allows us to always peek at the previous
560    token without worrying about underflowing the list.  */
561 void
562 _cpp_init_toklist (list)
563      cpp_toklist *list;
564 {
565   /* Initialize token space.  Put a dummy token before the start
566      that will fail matches.  */
567   list->tokens_cap = 256;       /* 4K's worth.  */
568   list->tokens = (cpp_token *)
569     xmalloc ((list->tokens_cap + 1) * sizeof (cpp_token));
570   list->tokens[0].type = CPP_EOF;
571   list->tokens++;
572
573   /* Initialize name space.  */
574   list->name_cap = 1024;
575   list->namebuf = (unsigned char *) xmalloc (list->name_cap);
576
577   /* Only create a comment space on demand.  */
578   list->comments_cap = 0;
579   list->comments = 0;
580
581   list->flags = LIST_OFFSET;
582   _cpp_clear_toklist (list);
583 }
584
585 /* Clear a token list.  */
586 void
587 _cpp_clear_toklist (list)
588      cpp_toklist *list;
589 {
590   list->tokens_used = 0;
591   list->name_used = 0;
592   list->comments_used = 0;
593   list->dirno = -1;
594   list->flags &= LIST_OFFSET;  /* clear all but that one */
595 }
596
597 /* Free a token list.  Does not free the list itself, which may be
598    embedded in a larger structure.  */
599 void
600 _cpp_free_toklist (list)
601      cpp_toklist *list;
602 {
603   if (list->comments)
604     free (list->comments);
605   if (list->flags & LIST_OFFSET)
606     free (list->tokens - 1);    /* Backup over dummy token.  */
607   else
608     free (list->tokens);
609   free (list->namebuf);
610 }
611
612 /* Slice a token list: copy the sublist [START, FINISH) into COPY.
613    COPY is assumed not to be initialized.  The comment space is not
614    copied.  */
615 void
616 _cpp_slice_toklist (copy, start, finish)
617      cpp_toklist *copy;
618      const cpp_token *start, *finish;
619 {
620   unsigned int i, n;
621   size_t bytes;
622
623   n = finish - start;
624   copy->tokens_cap = n;
625   copy->tokens = (cpp_token *) xmalloc (n * sizeof (cpp_token));
626   memcpy (copy->tokens, start, n * sizeof (cpp_token));
627
628   bytes = 0;
629   for (i = 0; i < n; i++)
630     if (token_spellings[start[i].type].type > SPELL_NONE)
631       bytes += start[i].val.name.len;
632
633   copy->namebuf = xmalloc (bytes);
634   bytes = 0;
635   for (i = 0; i < n; i++)
636     if (token_spellings[start[i].type].type > SPELL_NONE)
637       {
638         memcpy (copy->namebuf + bytes,
639                 start[i].val.name.text, start[i].val.name.len);
640         copy->tokens[i].val.name.text = copy->namebuf + bytes;
641         bytes += start[i].val.name.len;
642       }
643
644   copy->tokens_cap = n;
645   copy->tokens_used = n;
646   copy->name_used = bytes;
647   copy->name_cap = bytes;
648   copy->comments = 0;
649   copy->comments_cap = 0;
650   copy->comments_used = 0;
651   
652   copy->flags = 0;
653   copy->dirno = -1;
654 }
655
656 /* Shrink a token list down to the minimum size.  */
657 void
658 _cpp_squeeze_toklist (list)
659      cpp_toklist *list;
660 {
661   long delta;
662   const U_CHAR *old_namebuf;
663
664   if (list->flags & LIST_OFFSET)
665     {
666       list->tokens--;
667       memmove (list->tokens, list->tokens + 1,
668                list->tokens_used * sizeof (cpp_token));
669       list->tokens = xrealloc (list->tokens,
670                                list->tokens_used * sizeof (cpp_token));
671       list->flags &= ~LIST_OFFSET;
672     }
673   else
674     list->tokens = xrealloc (list->tokens,
675                              list->tokens_used * sizeof (cpp_token));
676   list->tokens_cap = list->tokens_used;
677
678   old_namebuf = list->namebuf;
679   list->namebuf = xrealloc (list->namebuf, list->name_used);
680   list->name_cap = list->name_used;
681
682   /* Fix up token text pointers.  */
683   delta = list->namebuf - old_namebuf;
684   if (delta)
685     {
686       unsigned int i;
687
688       for (i = 0; i < list->tokens_used; i++)
689         if (token_spellings[list->tokens[i].type].type > SPELL_NONE)
690           list->tokens[i].val.name.text += delta;
691     }
692   
693   if (list->comments_cap)
694     {
695       list->comments = xrealloc (list->comments,
696                                  list->comments_used * sizeof (cpp_token));
697       list->comments_cap = list->comments_used;
698     }
699 }
700
701 /* Compare two tokens.  */
702 int
703 _cpp_equiv_tokens (a, b)
704      const cpp_token *a, *b;
705 {
706   if (a->type != b->type
707       || a->flags != b->flags
708       || a->aux != b->aux)
709     return 0;
710
711   if (token_spellings[a->type].type > SPELL_NONE)
712     {
713       if (a->val.name.len != b->val.name.len
714           || ustrncmp(a->val.name.text,
715                       b->val.name.text,
716                       a->val.name.len))
717         return 0;
718     }
719   return 1;
720 }
721
722 /* Compare two token lists.  */
723 int
724 _cpp_equiv_toklists (a, b)
725      const cpp_toklist *a, *b;
726 {
727   unsigned int i;
728
729   if (a->tokens_used != b->tokens_used)
730     return 0;
731
732   for (i = 0; i < a->tokens_used; i++)
733     if (! _cpp_equiv_tokens (&a->tokens[i], &b->tokens[i]))
734       return 0;
735   return 1;
736 }
737
738 /* Scan until we encounter a token of type STOP or a newline, and
739    create a token list for it.  Does not macro-expand or execute
740    directives.  The final token is not included in the list or
741    consumed from the input.  Returns the type of the token stopped at. */
742
743 enum cpp_ttype
744 _cpp_scan_until (pfile, list, stop)
745      cpp_reader *pfile;
746      cpp_toklist *list;
747      enum cpp_ttype stop;
748 {
749   int i, col;
750   long written, len;
751   enum cpp_ttype type;
752   int space_before;
753
754   _cpp_clear_toklist (list);
755   list->line = CPP_BUF_LINE (CPP_BUFFER (pfile));
756
757   written = CPP_WRITTEN (pfile);
758   i = 0;
759   space_before = 0;
760   for (;;)
761     {
762       col = CPP_BUFFER (pfile)->cur - CPP_BUFFER (pfile)->line_base;
763       type = _cpp_lex_token (pfile);
764       len = CPP_WRITTEN (pfile) - written;
765       CPP_SET_WRITTEN (pfile, written);
766       if (type == CPP_HSPACE)
767         {
768           if (CPP_PEDANTIC (pfile))
769             pedantic_whitespace (pfile, pfile->token_buffer + written, len);
770           space_before = 1;
771           continue;
772         }
773       else if (type == CPP_COMMENT)
774         /* Only happens when processing -traditional macro definitions.
775            Do not give this a token entry, but do not change space_before
776            either.  */
777         continue;
778
779       if (list->tokens_used >= list->tokens_cap)
780         expand_token_space (list);
781       if (list->name_used + len >= list->name_cap)
782         expand_name_space (list, list->name_used + len + 1 - list->name_cap);
783
784       if (type == CPP_MACRO)
785         type = CPP_NAME;
786
787       if (type == CPP_VSPACE || type == stop)
788         break;
789
790       list->tokens_used++;
791       TOK_TYPE  (list, i) = type;
792       TOK_COL   (list, i) = col;
793       TOK_FLAGS (list, i) = space_before ? PREV_WHITESPACE : 0;
794       
795       TOK_LEN (list, i) = len;
796       if (token_spellings[type].type > SPELL_NONE)
797         {
798           memcpy (list->namebuf + list->name_used, CPP_PWRITTEN (pfile), len);
799           TOK_NAME (list, i) = list->namebuf + list->name_used;
800           list->name_used += len;
801         }
802       else
803         TOK_NAME (list, i) = token_spellings[type].spelling;
804       i++;
805       space_before = 0;
806     }
807
808   /* XXX Temporary kluge: put back the newline (or whatever).  */
809   FORWARD(-1);
810
811   /* Don't consider the first token to have white before.  */
812   TOK_FLAGS (list, 0) &= ~PREV_WHITESPACE;
813   return type;
814 }
815
816 /* Skip a C-style block comment.  We know it's a comment, and point is
817    at the second character of the starter.  */
818 static void
819 skip_block_comment (pfile)
820      cpp_reader *pfile;
821 {
822   unsigned int line, col;
823   const U_CHAR *limit, *cur;
824
825   FORWARD(1);
826   line = CPP_BUF_LINE (CPP_BUFFER (pfile));
827   col = CPP_BUF_COL (CPP_BUFFER (pfile));
828   limit = CPP_BUFFER (pfile)->rlimit;
829   cur = CPP_BUFFER (pfile)->cur;
830
831   while (cur < limit)
832     {
833       char c = *cur++;
834       if (c == '\n' || c == '\r')
835         {
836           /* \r cannot be a macro escape marker here. */
837           if (!ACTIVE_MARK_P (pfile))
838             CPP_BUMP_LINE_CUR (pfile, cur);
839         }
840       else if (c == '*')
841         {
842           /* Check for teminator.  */
843           if (cur < limit && *cur == '/')
844             goto out;
845
846           /* Warn about comment starter embedded in comment.  */
847           if (cur[-2] == '/' && CPP_OPTION (pfile, warn_comments))
848             cpp_warning_with_line (pfile, CPP_BUFFER (pfile)->lineno,
849                                    cur - CPP_BUFFER (pfile)->line_base,
850                                    "'/*' within comment");
851         }
852     }
853
854   cpp_error_with_line (pfile, line, col, "unterminated comment");
855   cur--;
856  out:
857   CPP_BUFFER (pfile)->cur = cur + 1;
858 }
859
860 /* Skip a C++/Chill line comment.  We know it's a comment, and point
861    is at the second character of the initiator.  */
862 static void
863 skip_line_comment (pfile)
864      cpp_reader *pfile;
865 {
866   FORWARD(1);
867   for (;;)
868     {
869       int c = GETC ();
870
871       /* We don't have to worry about EOF in here.  */
872       if (c == '\n')
873         {
874           /* Don't consider final '\n' to be part of comment.  */
875           FORWARD(-1);
876           return;
877         }
878       else if (c == '\r')
879         {
880           /* \r cannot be a macro escape marker here. */
881           if (!ACTIVE_MARK_P (pfile))
882             CPP_BUMP_LINE (pfile);
883           if (CPP_OPTION (pfile, warn_comments))
884             cpp_warning (pfile, "backslash-newline within line comment");
885         }
886     }
887 }
888
889 /* Skip a comment - C, C++, or Chill style.  M is the first character
890    of the comment marker.  If this really is a comment, skip to its
891    end and return ' '.  If this is not a comment, return M (which will
892    be '/' or '-').  */
893
894 static int
895 skip_comment (pfile, m)
896      cpp_reader *pfile;
897      int m;
898 {
899   if (m == '/' && PEEKC() == '*')
900     {
901       skip_block_comment (pfile);
902       return ' ';
903     }
904   else if (m == '/' && PEEKC() == '/')
905     {
906       if (CPP_BUFFER (pfile)->system_header_p)
907         {
908           /* We silently allow C++ comments in system headers, irrespective
909              of conformance mode, because lots of busted systems do that
910              and trying to clean it up in fixincludes is a nightmare.  */
911           skip_line_comment (pfile);
912           return ' ';
913         }
914       else if (CPP_OPTION (pfile, cplusplus_comments))
915         {
916           if (! CPP_BUFFER (pfile)->warned_cplusplus_comments)
917             {
918               if (CPP_WTRADITIONAL (pfile))
919                 cpp_pedwarn (pfile,
920                         "C++ style comments are not allowed in traditional C");
921               else if (CPP_OPTION (pfile, c89) && CPP_PEDANTIC (pfile))
922                 cpp_pedwarn (pfile,
923                         "C++ style comments are not allowed in ISO C89");
924               if (CPP_WTRADITIONAL (pfile)
925                   || (CPP_OPTION (pfile, c89) && CPP_PEDANTIC (pfile)))
926                 cpp_pedwarn (pfile,
927                            "(this will be reported only once per input file)");
928               CPP_BUFFER (pfile)->warned_cplusplus_comments = 1;
929             }
930           skip_line_comment (pfile);
931           return ' ';
932         }
933       else
934         return m;
935     }
936   else if (m == '-' && PEEKC() == '-'
937            && CPP_OPTION (pfile, chill))
938     {
939       skip_line_comment (pfile);
940       return ' ';
941     }
942   else
943     return m;
944 }
945
946 /* Identical to skip_comment except that it copies the comment into the
947    token_buffer.  This is used if !discard_comments.  */
948 static int
949 copy_comment (pfile, m)
950      cpp_reader *pfile;
951      int m;
952 {
953   const U_CHAR *start = CPP_BUFFER (pfile)->cur;  /* XXX Layering violation */
954   const U_CHAR *limit;
955
956   if (skip_comment (pfile, m) == m)
957     return m;
958
959   limit = CPP_BUFFER (pfile)->cur;
960   CPP_RESERVE (pfile, limit - start + 2);
961   CPP_PUTC_Q (pfile, m);
962   for (; start <= limit; start++)
963     if (*start != '\r')
964       CPP_PUTC_Q (pfile, *start);
965
966   return ' ';
967 }
968
969 static void
970 null_warning (pfile, count)
971      cpp_reader *pfile;
972      unsigned int count;
973 {
974   if (count == 1)
975     cpp_warning (pfile, "embedded null character ignored");
976   else
977     cpp_warning (pfile, "embedded null characters ignored");
978 }
979
980 /* Skip whitespace \-newline and comments.  Does not macro-expand.  */
981
982 void
983 _cpp_skip_hspace (pfile)
984      cpp_reader *pfile;
985 {
986   unsigned int null_count = 0;
987   int c;
988
989   while (1)
990     {
991       c = GETC();
992       if (c == EOF)
993         goto out;
994       else if (is_hspace(c))
995         {
996           if ((c == '\f' || c == '\v') && CPP_PEDANTIC (pfile))
997             cpp_pedwarn (pfile, "%s in preprocessing directive",
998                          c == '\f' ? "formfeed" : "vertical tab");
999           else if (c == '\0')
1000             null_count++;
1001         }
1002       else if (c == '\r')
1003         {
1004           /* \r is a backslash-newline marker if !has_escapes, and
1005              a deletable-whitespace or no-reexpansion marker otherwise. */
1006           if (CPP_BUFFER (pfile)->has_escapes)
1007             {
1008               if (PEEKC() == ' ')
1009                 FORWARD(1);
1010               else
1011                 break;
1012             }
1013           else
1014             CPP_BUMP_LINE (pfile);
1015         }
1016       else if (c == '/' || c == '-')
1017         {
1018           c = skip_comment (pfile, c);
1019           if (c  != ' ')
1020             break;
1021         }
1022       else
1023         break;
1024     }
1025   FORWARD(-1);
1026  out:
1027   if (null_count)
1028     null_warning (pfile, null_count);
1029 }
1030
1031 /* Read and discard the rest of the current line.  */
1032
1033 void
1034 _cpp_skip_rest_of_line (pfile)
1035      cpp_reader *pfile;
1036 {
1037   for (;;)
1038     {
1039       int c = GETC();
1040       switch (c)
1041         {
1042         case '\n':
1043           FORWARD(-1);
1044         case EOF:
1045           return;
1046
1047         case '\r':
1048           if (! CPP_BUFFER (pfile)->has_escapes)
1049             CPP_BUMP_LINE (pfile);
1050           break;
1051           
1052         case '\'':
1053         case '\"':
1054           skip_string (pfile, c);
1055           break;
1056
1057         case '/':
1058         case '-':
1059           skip_comment (pfile, c);
1060           break;
1061
1062         case '\f':
1063         case '\v':
1064           if (CPP_PEDANTIC (pfile))
1065             cpp_pedwarn (pfile, "%s in preprocessing directive",
1066                          c == '\f' ? "formfeed" : "vertical tab");
1067           break;
1068
1069         }
1070     }
1071 }
1072
1073 /* Parse an identifier starting with C.  */
1074
1075 void
1076 _cpp_parse_name (pfile, c)
1077      cpp_reader *pfile;
1078      int c;
1079 {
1080   for (;;)
1081   {
1082       if (! is_idchar(c))
1083       {
1084           FORWARD (-1);
1085           break;
1086       }
1087
1088       if (c == '$' && CPP_PEDANTIC (pfile))
1089         cpp_pedwarn (pfile, "`$' in identifier");
1090
1091       CPP_RESERVE(pfile, 2); /* One more for final NUL.  */
1092       CPP_PUTC_Q (pfile, c);
1093       c = GETC();
1094       if (c == EOF)
1095         break;
1096   }
1097   return;
1098 }
1099
1100 /* Parse and skip over a string starting with C.  A single quoted
1101    string is treated like a double -- some programs (e.g., troff) are
1102    perverse this way.  (However, a single quoted string is not allowed
1103    to extend over multiple lines.)  */
1104 static void
1105 skip_string (pfile, c)
1106      cpp_reader *pfile;
1107      int c;
1108 {
1109   unsigned int start_line, start_column;
1110   unsigned int null_count = 0;
1111
1112   start_line = CPP_BUF_LINE (CPP_BUFFER (pfile));
1113   start_column = CPP_BUF_COL (CPP_BUFFER (pfile));
1114   while (1)
1115     {
1116       int cc = GETC();
1117       switch (cc)
1118         {
1119         case EOF:
1120           cpp_error_with_line (pfile, start_line, start_column,
1121                                "unterminated string or character constant");
1122           if (pfile->multiline_string_line != start_line
1123               && pfile->multiline_string_line != 0)
1124             cpp_error_with_line (pfile,
1125                                  pfile->multiline_string_line, -1,
1126                          "possible real start of unterminated constant");
1127           pfile->multiline_string_line = 0;
1128           goto out;
1129
1130         case '\0':
1131           null_count++;
1132           break;
1133           
1134         case '\n':
1135           CPP_BUMP_LINE (pfile);
1136           /* In Fortran and assembly language, silently terminate
1137              strings of either variety at end of line.  This is a
1138              kludge around not knowing where comments are in these
1139              languages.  */
1140           if (CPP_OPTION (pfile, lang_fortran)
1141               || CPP_OPTION (pfile, lang_asm))
1142             {
1143               FORWARD(-1);
1144               goto out;
1145             }
1146           /* Character constants may not extend over multiple lines.
1147              In Standard C, neither may strings.  We accept multiline
1148              strings as an extension.  */
1149           if (c == '\'')
1150             {
1151               cpp_error_with_line (pfile, start_line, start_column,
1152                                    "unterminated character constant");
1153               FORWARD(-1);
1154               goto out;
1155             }
1156           if (CPP_PEDANTIC (pfile) && pfile->multiline_string_line == 0)
1157             cpp_pedwarn_with_line (pfile, start_line, start_column,
1158                                    "string constant runs past end of line");
1159           if (pfile->multiline_string_line == 0)
1160             pfile->multiline_string_line = start_line;
1161           break;
1162
1163         case '\r':
1164           if (CPP_BUFFER (pfile)->has_escapes)
1165             {
1166               cpp_ice (pfile, "\\r escape inside string constant");
1167               FORWARD(1);
1168             }
1169           else
1170             /* Backslash newline is replaced by nothing at all.  */
1171             CPP_BUMP_LINE (pfile);
1172           break;
1173
1174         case '\\':
1175           FORWARD(1);
1176           break;
1177
1178         case '\"':
1179         case '\'':
1180           if (cc == c)
1181             goto out;
1182           break;
1183         }
1184     }
1185
1186  out:
1187   if (null_count == 1)
1188     cpp_warning (pfile, "null character in string or character constant");
1189   else if (null_count > 1)
1190     cpp_warning (pfile, "null characters in string or character constant");
1191 }
1192
1193 /* Parse a string and copy it to the output.  */
1194
1195 static void
1196 parse_string (pfile, c)
1197      cpp_reader *pfile;
1198      int c;
1199 {
1200   const U_CHAR *start = CPP_BUFFER (pfile)->cur;  /* XXX Layering violation */
1201   const U_CHAR *limit;
1202
1203   skip_string (pfile, c);
1204
1205   limit = CPP_BUFFER (pfile)->cur;
1206   CPP_RESERVE (pfile, limit - start + 2);
1207   CPP_PUTC_Q (pfile, c);
1208   for (; start < limit; start++)
1209     if (*start != '\r')
1210       CPP_PUTC_Q (pfile, *start);
1211 }
1212
1213 /* Get the next token, and add it to the text in pfile->token_buffer.
1214    Return the kind of token we got.  */
1215
1216 enum cpp_ttype
1217 _cpp_lex_token (pfile)
1218      cpp_reader *pfile;
1219 {
1220   register int c, c2;
1221   enum cpp_ttype token;
1222
1223   if (CPP_BUFFER (pfile) == NULL)
1224     return CPP_EOF;
1225
1226  get_next:
1227   c = GETC();
1228   switch (c)
1229     {
1230     case EOF:
1231       return CPP_EOF;
1232
1233     case '/':
1234       if (PEEKC () == '=')
1235         goto op2;
1236
1237     comment:
1238       if (CPP_OPTION (pfile, discard_comments))
1239         c = skip_comment (pfile, c);
1240       else
1241         c = copy_comment (pfile, c);
1242       if (c != ' ')
1243         goto randomchar;
1244           
1245       /* Comments are equivalent to spaces.
1246          For -traditional, a comment is equivalent to nothing.  */
1247       if (!CPP_OPTION (pfile, discard_comments))
1248         return CPP_COMMENT;
1249       else if (CPP_TRADITIONAL (pfile))
1250         goto get_next;
1251       else
1252         {
1253           CPP_PUTC (pfile, c);
1254           return CPP_HSPACE;
1255         }
1256
1257     case '#':
1258       CPP_PUTC (pfile, c);
1259
1260     hash:
1261       c2 = PEEKC ();
1262       if (c2 == '#')
1263         {
1264           FORWARD (1);
1265           CPP_PUTC (pfile, c2);
1266           return CPP_PASTE;
1267         }
1268       else if (c2 == '%' && PEEKN (1) == ':')
1269         {
1270           /* Digraph: "%:" == "#".  */
1271           FORWARD (1);
1272           CPP_RESERVE (pfile, 2);
1273           CPP_PUTC_Q (pfile, c2);
1274           CPP_PUTC_Q (pfile, GETC ());
1275           return CPP_PASTE;
1276         }
1277       else
1278         return CPP_HASH;
1279
1280     case '\"':
1281     case '\'':
1282       parse_string (pfile, c);
1283       return c == '\'' ? CPP_CHAR : CPP_STRING;
1284
1285     case '$':
1286       if (!CPP_OPTION (pfile, dollars_in_ident))
1287         goto randomchar;
1288       goto letter;
1289
1290     case ':':
1291       c2 = PEEKC ();
1292       /* Digraph: ":>" == "]".  */
1293       if (c2 == '>'
1294           || (c2 == ':' && CPP_OPTION (pfile, cplusplus)))
1295         goto op2;
1296       goto randomchar;
1297
1298     case '&':
1299     case '+':
1300     case '|':
1301       c2 = PEEKC ();
1302       if (c2 == c || c2 == '=')
1303         goto op2;
1304       goto randomchar;
1305
1306     case '%':
1307       /* Digraphs: "%:" == "#", "%>" == "}".  */
1308       c2 = PEEKC ();
1309       if (c2 == ':')
1310         {
1311           FORWARD (1);
1312           CPP_RESERVE (pfile, 2);
1313           CPP_PUTC_Q (pfile, c);
1314           CPP_PUTC_Q (pfile, c2);
1315           goto hash;
1316         }
1317       else if (c2 == '>')
1318         {
1319           FORWARD (1);
1320           CPP_RESERVE (pfile, 2);
1321           CPP_PUTC_Q (pfile, c);
1322           CPP_PUTC_Q (pfile, c2);
1323           return CPP_OPEN_BRACE;
1324         }
1325       /* else fall through */
1326
1327     case '*':
1328     case '!':
1329     case '=':
1330     case '^':
1331       if (PEEKC () == '=')
1332         goto op2;
1333       goto randomchar;
1334
1335     case '-':
1336       c2 = PEEKC ();
1337       if (c2 == '-')
1338         {
1339           if (CPP_OPTION (pfile, chill))
1340             goto comment;  /* Chill style comment */
1341           else
1342             goto op2;
1343         }
1344       else if (c2 == '=')
1345         goto op2;
1346       else if (c2 == '>')
1347         {
1348           if (CPP_OPTION (pfile, cplusplus) && PEEKN (1) == '*')
1349             {
1350               /* In C++, there's a ->* operator.  */
1351               token = CPP_OTHER;
1352               CPP_RESERVE (pfile, 4);
1353               CPP_PUTC_Q (pfile, c);
1354               CPP_PUTC_Q (pfile, GETC ());
1355               CPP_PUTC_Q (pfile, GETC ());
1356               return token;
1357             }
1358           goto op2;
1359         }
1360       goto randomchar;
1361
1362     case '<':
1363       if (pfile->parsing_include_directive)
1364         {
1365           for (;;)
1366             {
1367               CPP_PUTC (pfile, c);
1368               if (c == '>')
1369                 break;
1370               c = GETC ();
1371               if (c == '\n' || c == EOF)
1372                 {
1373                   cpp_error (pfile,
1374                              "missing '>' in `#include <FILENAME>'");
1375                   break;
1376                 }
1377               else if (c == '\r')
1378                 {
1379                   if (!CPP_BUFFER (pfile)->has_escapes)
1380                     {
1381                       /* Backslash newline is replaced by nothing. */
1382                       CPP_ADJUST_WRITTEN (pfile, -1);
1383                       CPP_BUMP_LINE (pfile);
1384                     }
1385                   else
1386                     {
1387                       /* We might conceivably get \r- or \r<space> in
1388                          here.  Just delete 'em. */
1389                       int d = GETC();
1390                       if (d != '-' && d != ' ')
1391                         cpp_ice (pfile, "unrecognized escape \\r%c", d);
1392                       CPP_ADJUST_WRITTEN (pfile, -1);
1393                     }                     
1394                 }
1395             }
1396           return CPP_STRING;
1397         }
1398       /* Digraphs: "<%" == "{", "<:" == "[".  */
1399       c2 = PEEKC ();
1400       if (c2 == '%')
1401         {
1402           FORWARD (1);
1403           CPP_RESERVE (pfile, 2);
1404           CPP_PUTC_Q (pfile, c);
1405           CPP_PUTC_Q (pfile, c2);
1406           return CPP_CLOSE_BRACE;
1407         }
1408       else if (c2 == ':')
1409         goto op2;
1410       /* else fall through */
1411     case '>':
1412       c2 = PEEKC ();
1413       if (c2 == '=')
1414         goto op2;
1415       /* GNU C++ supports MIN and MAX operators <? and >?.  */
1416       if (c2 != c && (!CPP_OPTION (pfile, cplusplus) || c2 != '?'))
1417         goto randomchar;
1418       FORWARD(1);
1419       CPP_RESERVE (pfile, 3);
1420       CPP_PUTC_Q (pfile, c);
1421       CPP_PUTC_Q (pfile, c2);
1422       if (PEEKC () == '=')
1423         CPP_PUTC_Q (pfile, GETC ());
1424       return CPP_OTHER;
1425
1426     case '.':
1427       c2 = PEEKC ();
1428       if (ISDIGIT (c2))
1429         {
1430           CPP_PUTC (pfile, c);
1431           c = GETC ();
1432           goto number;
1433         }
1434
1435       /* In C++ there's a .* operator.  */
1436       if (CPP_OPTION (pfile, cplusplus) && c2 == '*')
1437         goto op2;
1438
1439       if (c2 == '.' && PEEKN(1) == '.')
1440         {
1441           CPP_RESERVE (pfile, 3);
1442           CPP_PUTC_Q (pfile, '.');
1443           CPP_PUTC_Q (pfile, '.');
1444           CPP_PUTC_Q (pfile, '.');
1445           FORWARD (2);
1446           return CPP_ELLIPSIS;
1447         }
1448       goto randomchar;
1449
1450     op2:
1451       CPP_RESERVE (pfile, 2);
1452       CPP_PUTC_Q (pfile, c);
1453       CPP_PUTC_Q (pfile, GETC ());
1454       return CPP_OTHER;
1455
1456     case 'L':
1457       c2 = PEEKC ();
1458       if ((c2 == '\'' || c2 == '\"') && !CPP_TRADITIONAL (pfile))
1459         {
1460           CPP_PUTC (pfile, c);
1461           c = GETC ();
1462           parse_string (pfile, c);
1463           return c == '\'' ? CPP_WCHAR : CPP_WSTRING;
1464         }
1465       goto letter;
1466
1467     case '0': case '1': case '2': case '3': case '4':
1468     case '5': case '6': case '7': case '8': case '9':
1469     number:
1470     c2  = '.';
1471     for (;;)
1472       {
1473         CPP_RESERVE (pfile, 2);
1474         CPP_PUTC_Q (pfile, c);
1475         c = PEEKC ();
1476         if (c == EOF)
1477           break;
1478         if (!is_numchar(c) && c != '.'
1479             && ((c2 != 'e' && c2 != 'E'
1480                  && ((c2 != 'p' && c2 != 'P')
1481                      || CPP_OPTION (pfile, c89)))
1482                 || (c != '+' && c != '-')))
1483           break;
1484         FORWARD(1);
1485         c2= c;
1486       }
1487     return CPP_NUMBER;
1488     case 'b': case 'c': case 'd': case 'h': case 'o':
1489     case 'B': case 'C': case 'D': case 'H': case 'O':
1490       if (CPP_OPTION (pfile, chill) && PEEKC () == '\'')
1491         {
1492           CPP_RESERVE (pfile, 2);
1493           CPP_PUTC_Q (pfile, c);
1494           CPP_PUTC_Q (pfile, '\'');
1495           FORWARD(1);
1496           for (;;)
1497             {
1498               c = GETC();
1499               if (c == EOF)
1500                 goto chill_number_eof;
1501               if (!is_numchar(c))
1502                 break;
1503               CPP_PUTC (pfile, c);
1504             }
1505           if (c == '\'')
1506             {
1507               CPP_RESERVE (pfile, 2);
1508               CPP_PUTC_Q (pfile, c);
1509               return CPP_STRING;
1510             }
1511           else
1512             {
1513               FORWARD(-1);
1514             chill_number_eof:
1515               return CPP_NUMBER;
1516             }
1517         }
1518       else
1519         goto letter;
1520     case '_':
1521     case 'a': case 'e': case 'f': case 'g': case 'i': case 'j':
1522     case 'k': case 'l': case 'm': case 'n': case 'p': case 'q':
1523     case 'r': case 's': case 't': case 'u': case 'v': case 'w':
1524     case 'x': case 'y': case 'z':
1525     case 'A': case 'E': case 'F': case 'G': case 'I': case 'J':
1526     case 'K': case 'M': case 'N': case 'P': case 'Q': case 'R':
1527     case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1528     case 'Y': case 'Z':
1529     letter:
1530     _cpp_parse_name (pfile, c);
1531     return CPP_MACRO;
1532
1533     case ' ':  case '\t':  case '\v': case '\f': case '\0':
1534       {
1535         int null_count = 0;
1536
1537         for (;;)
1538           {
1539             if (c == '\0')
1540               null_count++;
1541             else
1542               CPP_PUTC (pfile, c);
1543             c = PEEKC ();
1544             if (c == EOF || !is_hspace(c))
1545               break;
1546             FORWARD(1);
1547           }
1548         if (null_count)
1549           null_warning (pfile, null_count);
1550         return CPP_HSPACE;
1551       }
1552
1553     case '\r':
1554       if (CPP_BUFFER (pfile)->has_escapes)
1555         {
1556           c = GETC ();
1557           if (c == '-')
1558             {
1559               if (pfile->output_escapes)
1560                 CPP_PUTS (pfile, "\r-", 2);
1561               _cpp_parse_name (pfile, GETC ());
1562               return CPP_NAME;
1563             }
1564           else if (c == ' ')
1565             {
1566               /* "\r " means a space, but only if necessary to prevent
1567                  accidental token concatenation.  */
1568               CPP_RESERVE (pfile, 2);
1569               if (pfile->output_escapes)
1570                 CPP_PUTC_Q (pfile, '\r');
1571               CPP_PUTC_Q (pfile, c);
1572               return CPP_HSPACE;
1573             }
1574           else
1575             {
1576               cpp_ice (pfile, "unrecognized escape \\r%c", c);
1577               goto get_next;
1578             }
1579         }
1580       else
1581         {
1582           /* Backslash newline is ignored. */
1583           if (!ACTIVE_MARK_P (pfile))
1584             CPP_BUMP_LINE (pfile);
1585           goto get_next;
1586         }
1587
1588     case '\n':
1589       CPP_PUTC (pfile, c);
1590       return CPP_VSPACE;
1591
1592     case '(': token = CPP_OPEN_PAREN;  goto char1;
1593     case ')': token = CPP_CLOSE_PAREN; goto char1;
1594     case '{': token = CPP_OPEN_BRACE;  goto char1;
1595     case '}': token = CPP_CLOSE_BRACE; goto char1;
1596     case ',': token = CPP_COMMA;       goto char1;
1597     case ';': token = CPP_SEMICOLON;   goto char1;
1598
1599     randomchar:
1600     default:
1601       token = CPP_OTHER;
1602     char1:
1603       CPP_PUTC (pfile, c);
1604       return token;
1605     }
1606 }
1607
1608 /* Check for and expand a macro, which is from WRITTEN to CPP_WRITTEN (pfile).
1609    Caller is expected to have checked no_macro_expand.  */
1610 static int
1611 maybe_macroexpand (pfile, written)
1612      cpp_reader *pfile;
1613      long written;
1614 {
1615   U_CHAR *macro = pfile->token_buffer + written;
1616   size_t len = CPP_WRITTEN (pfile) - written;
1617   HASHNODE *hp = _cpp_lookup (pfile, macro, len);
1618
1619   /* _cpp_lookup never returns null.  */
1620   if (hp->type == T_VOID)
1621     return 0;
1622   if (hp->disabled || hp->type == T_IDENTITY)
1623     {
1624       if (pfile->output_escapes)
1625         {
1626           /* Insert a no-reexpand marker before IDENT.  */
1627           CPP_RESERVE (pfile, 2);
1628           CPP_ADJUST_WRITTEN (pfile, 2);
1629           macro = pfile->token_buffer + written;
1630
1631           memmove (macro + 2, macro, len);
1632           macro[0] = '\r';
1633           macro[1] = '-';
1634         }
1635       return 0;
1636     }
1637   if (hp->type == T_EMPTY)
1638     {
1639       /* Special case optimization: macro expands to nothing.  */
1640       CPP_SET_WRITTEN (pfile, written);
1641       CPP_PUTC_Q (pfile, ' ');
1642       return 1;
1643     }
1644
1645   /* If macro wants an arglist, verify that a '(' follows.  */
1646   if (hp->type == T_FMACRO)
1647     {
1648       int macbuf_whitespace = 0;
1649       int c;
1650
1651       while (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
1652         {
1653           const U_CHAR *point = CPP_BUFFER (pfile)->cur;
1654           for (;;)
1655             {
1656               _cpp_skip_hspace (pfile);
1657               c = PEEKC ();
1658               if (c == '\n')
1659                 FORWARD(1);
1660               else
1661                 break;
1662             }
1663           if (point != CPP_BUFFER (pfile)->cur)
1664             macbuf_whitespace = 1;
1665           if (c == '(')
1666             goto is_macro_call;
1667           else if (c != EOF)
1668             goto not_macro_call;
1669           cpp_pop_buffer (pfile);
1670         }
1671
1672       CPP_SET_MARK (pfile);
1673       for (;;)
1674         {
1675           _cpp_skip_hspace (pfile);
1676           c = PEEKC ();
1677           if (c == '\n')
1678             FORWARD(1);
1679           else
1680             break;
1681         }
1682       CPP_GOTO_MARK (pfile);
1683
1684       if (c != '(')
1685         {
1686         not_macro_call:
1687           if (macbuf_whitespace)
1688             CPP_PUTC (pfile, ' ');
1689           return 0;
1690         }
1691     }
1692
1693  is_macro_call:
1694   /* This is now known to be a macro call.
1695      Expand the macro, reading arguments as needed,
1696      and push the expansion on the input stack.  */
1697   _cpp_macroexpand (pfile, hp);
1698   CPP_SET_WRITTEN (pfile, written);
1699   return 1;
1700 }
1701
1702 /* Complain about \v or \f in a preprocessing directive (constraint
1703    violation, C99 6.10 para 5).  Caller has checked CPP_PEDANTIC.  */
1704 static void
1705 pedantic_whitespace (pfile, p, len)
1706      cpp_reader *pfile;
1707      U_CHAR *p;
1708      unsigned int len;
1709 {
1710   while (len)
1711     {
1712       if (*p == '\v')
1713         cpp_pedwarn (pfile, "vertical tab in preprocessing directive");
1714       else if (*p == '\f')
1715         cpp_pedwarn (pfile, "form feed in preprocessing directive");
1716       p++;
1717       len--;
1718     }
1719 }
1720
1721
1722 enum cpp_ttype
1723 cpp_get_token (pfile)
1724      cpp_reader *pfile;
1725 {
1726   enum cpp_ttype token;
1727   long written = CPP_WRITTEN (pfile);
1728
1729  get_next:
1730   token = _cpp_lex_token (pfile);
1731
1732   switch (token)
1733     {
1734     default:
1735       pfile->potential_control_macro = 0;
1736       pfile->only_seen_white = 0;
1737       return token;
1738
1739     case CPP_VSPACE:
1740       if (pfile->only_seen_white == 0)
1741         pfile->only_seen_white = 1;
1742       CPP_BUMP_LINE (pfile);
1743       return token;
1744
1745     case CPP_HSPACE:
1746     case CPP_COMMENT:
1747       return token;
1748
1749     case CPP_HASH:
1750       pfile->potential_control_macro = 0;
1751       if (!pfile->only_seen_white)
1752         return CPP_HASH;
1753       /* XXX shouldn't have to do this - remove the hash or %: from
1754          the token buffer.  */
1755       if (CPP_PWRITTEN (pfile)[-1] == '#')
1756         CPP_ADJUST_WRITTEN (pfile, -1);
1757       else
1758         CPP_ADJUST_WRITTEN (pfile, -2);
1759
1760       if (_cpp_handle_directive (pfile))
1761         return CPP_DIRECTIVE; 
1762       pfile->only_seen_white = 0;
1763       CPP_PUTC (pfile, '#');
1764       return CPP_HASH;
1765
1766     case CPP_MACRO:
1767       pfile->potential_control_macro = 0;
1768       pfile->only_seen_white = 0;
1769       if (! pfile->no_macro_expand
1770           && maybe_macroexpand (pfile, written))
1771         goto get_next;
1772       return CPP_NAME;
1773
1774     case CPP_EOF:
1775       if (CPP_BUFFER (pfile) == NULL)
1776         return CPP_EOF;
1777       if (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
1778         {
1779           cpp_pop_buffer (pfile);
1780           goto get_next;
1781         }
1782       cpp_pop_buffer (pfile);
1783       return CPP_EOF;
1784     }
1785 }
1786
1787 /* Like cpp_get_token, but skip spaces and comments.  */
1788
1789 enum cpp_ttype
1790 cpp_get_non_space_token (pfile)
1791      cpp_reader *pfile;
1792 {
1793   int old_written = CPP_WRITTEN (pfile);
1794   for (;;)
1795     {
1796       enum cpp_ttype token = cpp_get_token (pfile);
1797       if (token != CPP_COMMENT && token != CPP_HSPACE && token != CPP_VSPACE)
1798         return token;
1799       CPP_SET_WRITTEN (pfile, old_written);
1800     }
1801 }
1802
1803 /* Like cpp_get_token, except that it does not execute directives,
1804    does not consume vertical space, and discards horizontal space.  */
1805 enum cpp_ttype
1806 _cpp_get_directive_token (pfile)
1807      cpp_reader *pfile;
1808 {
1809   long old_written;
1810   enum cpp_ttype token;
1811   int at_bol;
1812
1813  get_next:
1814   at_bol = (CPP_BUFFER (pfile)->cur == CPP_BUFFER (pfile)->line_base);
1815   old_written = CPP_WRITTEN (pfile);
1816   token = _cpp_lex_token (pfile);
1817   switch (token)
1818     {
1819     default:
1820       return token;
1821
1822     case CPP_VSPACE:
1823       /* Put it back and return VSPACE.  */
1824       FORWARD(-1);
1825       CPP_ADJUST_WRITTEN (pfile, -1);
1826       return CPP_VSPACE;
1827
1828     case CPP_HSPACE:
1829       /* The purpose of this rather strange check is to prevent pedantic
1830          warnings for ^L in an #ifdefed out block.  */
1831       if (CPP_PEDANTIC (pfile) && ! at_bol)
1832         pedantic_whitespace (pfile, pfile->token_buffer + old_written,
1833                              CPP_WRITTEN (pfile) - old_written);
1834       CPP_SET_WRITTEN (pfile, old_written);
1835       goto get_next;
1836       return CPP_HSPACE;
1837
1838     case CPP_MACRO:
1839       if (! pfile->no_macro_expand
1840           && maybe_macroexpand (pfile, old_written))
1841         goto get_next;
1842       return CPP_NAME;
1843
1844     case CPP_EOF:
1845       if (CPP_IS_MACRO_BUFFER (CPP_BUFFER (pfile)))
1846         {
1847           cpp_pop_buffer (pfile);
1848           goto get_next;
1849         }
1850       else
1851         /* This can happen for files that don't end with a newline,
1852            and for cpp_define and friends.  Pretend they do, so
1853            callers don't have to deal.  A warning will be issued by
1854            someone else, if necessary.  */
1855         return CPP_VSPACE;
1856     }
1857 }
1858
1859 /* Determine the current line and column.  Used only by read_and_prescan. */
1860 static U_CHAR *
1861 find_position (start, limit, linep)
1862      U_CHAR *start;
1863      U_CHAR *limit;
1864      unsigned long *linep;
1865 {
1866   unsigned long line = *linep;
1867   U_CHAR *lbase = start;
1868   while (start < limit)
1869     {
1870       U_CHAR ch = *start++;
1871       if (ch == '\n' || ch == '\r')
1872         {
1873           line++;
1874           lbase = start;
1875         }
1876     }
1877   *linep = line;
1878   return lbase;
1879 }
1880
1881 /* The following table is used by _cpp_read_and_prescan.  If we have
1882    designated initializers, it can be constant data; otherwise, it is
1883    set up at runtime by _cpp_init_input_buffer.  */
1884
1885 #ifndef UCHAR_MAX
1886 #define UCHAR_MAX 255   /* assume 8-bit bytes */
1887 #endif
1888
1889 #if (GCC_VERSION >= 2007)
1890 #define init_chartab()  /* nothing */
1891 #define CHARTAB __extension__ static const U_CHAR chartab[UCHAR_MAX + 1] = {
1892 #define END };
1893 #define s(p, v) [p] = v,
1894 #else
1895 #define CHARTAB static U_CHAR chartab[UCHAR_MAX + 1] = { 0 }; \
1896  static void init_chartab PARAMS ((void)) { \
1897  unsigned char *x = chartab;
1898 #define END }
1899 #define s(p, v) x[p] = v;
1900 #endif
1901
1902 /* Table of characters that can't be handled in the inner loop.
1903    Also contains the mapping between trigraph third characters and their
1904    replacements.  */
1905 #define SPECCASE_CR        1
1906 #define SPECCASE_BACKSLASH 2
1907 #define SPECCASE_QUESTION  3
1908  
1909 CHARTAB
1910   s('\r', SPECCASE_CR)
1911   s('\\', SPECCASE_BACKSLASH)
1912   s('?',  SPECCASE_QUESTION)
1913
1914   s('=', '#')   s(')', ']')     s('!', '|')
1915   s('(', '[')   s('\'', '^')    s('>', '}')
1916   s('/', '\\')  s('<', '{')     s('-', '~')
1917 END
1918
1919 #undef CHARTAB
1920 #undef END
1921 #undef s
1922
1923 #define NORMAL(c) ((chartab[c]) == 0 || (chartab[c]) > SPECCASE_QUESTION)
1924 #define NONTRI(c) ((c) <= SPECCASE_QUESTION)
1925
1926 /* Read the entire contents of file DESC into buffer BUF.  LEN is how
1927    much memory to allocate initially; more will be allocated if
1928    necessary.  Convert end-of-line markers (\n, \r, \r\n, \n\r) to
1929    canonical form (\n).  If enabled, convert and/or warn about
1930    trigraphs.  Convert backslash-newline to a one-character escape
1931    (\r) and remove it from "embarrassing" places (i.e. the middle of a
1932    token).  If there is no newline at the end of the file, add one and
1933    warn.  Returns -1 on failure, or the actual length of the data to
1934    be scanned.
1935
1936    This function does a lot of work, and can be a serious performance
1937    bottleneck.  It has been tuned heavily; make sure you understand it
1938    before hacking.  The common case - no trigraphs, Unix style line
1939    breaks, backslash-newline set off by whitespace, newline at EOF -
1940    has been optimized at the expense of the others.  The performance
1941    penalty for DOS style line breaks (\r\n) is about 15%.
1942    
1943    Warnings lose particularly heavily since we have to determine the
1944    line number, which involves scanning from the beginning of the file
1945    or from the last warning.  The penalty for the absence of a newline
1946    at the end of reload1.c is about 60%.  (reload1.c is 329k.)
1947
1948    If your file has more than one kind of end-of-line marker, you
1949    will get messed-up line numbering.
1950    
1951    So that the cases of the switch statement do not have to concern
1952    themselves with the complications of reading beyond the end of the
1953    buffer, the buffer is guaranteed to have at least 3 characters in
1954    it (or however many are left in the file, if less) on entry to the
1955    switch.  This is enough to handle trigraphs and the "\\\n\r" and
1956    "\\\r\n" cases.
1957    
1958    The end of the buffer is marked by a '\\', which, being a special
1959    character, guarantees we will exit the fast-scan loops and perform
1960    a refill. */
1961  
1962 long
1963 _cpp_read_and_prescan (pfile, fp, desc, len)
1964      cpp_reader *pfile;
1965      cpp_buffer *fp;
1966      int desc;
1967      size_t len;
1968 {
1969   U_CHAR *buf = (U_CHAR *) xmalloc (len);
1970   U_CHAR *ip, *op, *line_base;
1971   U_CHAR *ibase;
1972   unsigned long line;
1973   unsigned int deferred_newlines;
1974   size_t offset;
1975   int count = 0;
1976
1977   offset = 0;
1978   deferred_newlines = 0;
1979   op = buf;
1980   line_base = buf;
1981   line = 1;
1982   ibase = pfile->input_buffer + 3;
1983   ip = ibase;
1984   ip[-1] = '\0';  /* Guarantee no match with \n for SPECCASE_CR */
1985
1986   for (;;)
1987     {
1988       U_CHAR *near_buff_end;
1989
1990       count = read (desc, ibase, pfile->input_buffer_len);
1991       if (count < 0)
1992         goto error;
1993       
1994       ibase[count] = '\\';  /* Marks end of buffer */
1995       if (count)
1996         {
1997           near_buff_end = pfile->input_buffer + count;
1998           offset += count;
1999           if (offset > len)
2000             {
2001               size_t delta_op;
2002               size_t delta_line_base;
2003               len = offset * 2;
2004               if (offset > len)
2005                 /* len overflowed.
2006                    This could happen if the file is larger than half the
2007                    maximum address space of the machine. */
2008                 goto too_big;
2009
2010               delta_op = op - buf;
2011               delta_line_base = line_base - buf;
2012               buf = (U_CHAR *) xrealloc (buf, len);
2013               op = buf + delta_op;
2014               line_base = buf + delta_line_base;
2015             }
2016         }
2017       else
2018         {
2019           if (ip == ibase)
2020             break;
2021           /* Allow normal processing of the (at most 2) remaining
2022              characters.  The end-of-buffer marker is still present
2023              and prevents false matches within the switch. */
2024           near_buff_end = ibase - 1;
2025         }
2026
2027       for (;;)
2028         {
2029           unsigned int span;
2030
2031           /* Deal with \-newline, potentially in the middle of a token. */
2032           if (deferred_newlines)
2033             {
2034               if (op != buf && ! is_space (op[-1]) && op[-1] != '\r')
2035                 {
2036                   /* Previous was not white space.  Skip to white
2037                      space, if we can, before outputting the \r's */
2038                   span = 0;
2039                   while (ip[span] != ' '
2040                          && ip[span] != '\t'
2041                          && ip[span] != '\n'
2042                          && NORMAL(ip[span]))
2043                     span++;
2044                   memcpy (op, ip, span);
2045                   op += span;
2046                   ip += span;
2047                   if (! NORMAL(ip[0]))
2048                     goto do_speccase;
2049                 }
2050               while (deferred_newlines)
2051                 deferred_newlines--, *op++ = '\r';
2052             }
2053
2054           /* Copy as much as we can without special treatment. */
2055           span = 0;
2056           while (NORMAL (ip[span])) span++;
2057           memcpy (op, ip, span);
2058           op += span;
2059           ip += span;
2060
2061         do_speccase:
2062           if (ip > near_buff_end) /* Do we have enough chars? */
2063             break;
2064           switch (chartab[*ip++])
2065             {
2066             case SPECCASE_CR:  /* \r */
2067               if (ip[-2] != '\n')
2068                 {
2069                   if (*ip == '\n')
2070                     ip++;
2071                   *op++ = '\n';
2072                 }
2073               break;
2074
2075             case SPECCASE_BACKSLASH:  /* \ */
2076               if (*ip == '\n')
2077                 {
2078                   deferred_newlines++;
2079                   ip++;
2080                   if (*ip == '\r') ip++;
2081                 }
2082               else if (*ip == '\r')
2083                 {
2084                   deferred_newlines++;
2085                   ip++;
2086                   if (*ip == '\n') ip++;
2087                 }
2088               else
2089                 *op++ = '\\';
2090               break;
2091
2092             case SPECCASE_QUESTION: /* ? */
2093               {
2094                 unsigned int d, t;
2095
2096                 *op++ = '?'; /* Normal non-trigraph case */
2097                 if (ip[0] != '?')
2098                   break;
2099                     
2100                 d = ip[1];
2101                 t = chartab[d];
2102                 if (NONTRI (t))
2103                   break;
2104
2105                 if (CPP_OPTION (pfile, warn_trigraphs))
2106                   {
2107                     unsigned long col;
2108                     line_base = find_position (line_base, op, &line);
2109                     col = op - line_base + 1;
2110                     if (CPP_OPTION (pfile, trigraphs))
2111                       cpp_warning_with_line (pfile, line, col,
2112                                              "trigraph ??%c converted to %c", d, t);
2113                     else
2114                       cpp_warning_with_line (pfile, line, col,
2115                                              "trigraph ??%c ignored", d);
2116                   }
2117
2118                 ip += 2;
2119                 if (CPP_OPTION (pfile, trigraphs))
2120                   {
2121                     op[-1] = t;     /* Overwrite '?' */
2122                     if (t == '\\')
2123                       {
2124                         op--;
2125                         *--ip = '\\';
2126                         goto do_speccase; /* May need buffer refill */
2127                       }
2128                   }
2129                 else
2130                   {
2131                     *op++ = '?';
2132                     *op++ = d;
2133                   }
2134               }
2135               break;
2136             }
2137         }
2138       /* Copy previous char plus unprocessed (at most 2) chars
2139          to beginning of buffer, refill it with another
2140          read(), and continue processing */
2141       memmove (ip - count - 1, ip - 1, 4 - (ip - near_buff_end));
2142       ip -= count;
2143     }
2144
2145   if (offset == 0)
2146     return 0;
2147
2148   if (op[-1] != '\n')
2149     {
2150       unsigned long col;
2151       line_base = find_position (line_base, op, &line);
2152       col = op - line_base + 1;
2153       cpp_warning_with_line (pfile, line, col, "no newline at end of file");
2154       if (offset + 1 > len)
2155         {
2156           len += 1;
2157           if (offset + 1 > len)
2158             goto too_big;
2159           buf = (U_CHAR *) xrealloc (buf, len);
2160           op = buf + offset;
2161         }
2162       *op++ = '\n';
2163     }
2164
2165   fp->buf = ((len - offset < 20) ? buf : (U_CHAR *)xrealloc (buf, op - buf));
2166   return op - buf;
2167
2168  too_big:
2169   cpp_notice (pfile, "%s is too large (>%lu bytes)", fp->ihash->name,
2170               (unsigned long)offset);
2171   free (buf);
2172   return -1;
2173
2174  error:
2175   cpp_error_from_errno (pfile, fp->ihash->name);
2176   free (buf);
2177   return -1;
2178 }
2179
2180 /* Allocate pfile->input_buffer, and initialize chartab[]
2181    if it hasn't happened already.  */
2182  
2183 void
2184 _cpp_init_input_buffer (pfile)
2185      cpp_reader *pfile;
2186 {
2187   U_CHAR *tmp;
2188
2189   init_chartab ();
2190   _cpp_init_toklist (&pfile->directbuf);
2191
2192   /* Determine the appropriate size for the input buffer.  Normal C
2193      source files are smaller than eight K.  */
2194   /* 8Kbytes of buffer proper, 1 to detect running off the end without
2195      address arithmetic all the time, and 3 for pushback during buffer
2196      refill, in case there's a potential trigraph or end-of-line
2197      digraph at the end of a block. */
2198
2199   tmp = (U_CHAR *) xmalloc (8192 + 1 + 3);
2200   pfile->input_buffer = tmp;
2201   pfile->input_buffer_len = 8192;
2202 }
2203
2204 /* Utility routine:
2205    Compares, in the manner of strcmp(3), the token beginning at TOKEN
2206    and extending for LEN characters to the NUL-terminated string
2207    STRING.  Typical usage:
2208
2209    if (! cpp_idcmp (pfile->token_buffer + here, CPP_WRITTEN (pfile) - here,
2210                  "inline"))
2211      { ... }
2212  */
2213
2214 int
2215 cpp_idcmp (token, len, string)
2216      const U_CHAR *token;
2217      size_t len;
2218      const char *string;
2219 {
2220   size_t len2 = strlen (string);
2221   int r;
2222
2223   if ((r = memcmp (token, string, MIN (len, len2))))
2224     return r;
2225
2226   /* The longer of the two strings sorts after the shorter.  */
2227   if (len == len2)
2228     return 0;
2229   else if (len < len2)
2230     return -1;
2231   else
2232     return 1;
2233 }
2234
2235 #ifdef NEW_LEXER
2236
2237 /* Lexing algorithm.
2238
2239  The original lexer in cpplib was made up of two passes: a first pass
2240  that replaced trigraphs and deleted esacped newlines, and a second
2241  pass that tokenized the result of the first pass.  Tokenisation was
2242  performed by peeking at the next character in the input stream.  For
2243  example, if the input stream contained "!=", the handler for the !
2244  character would peek at the next character, and if it were a '='
2245  would skip over it, and return a "!=" token, otherwise it would
2246  return just the "!" token.
2247
2248  To implement a single-pass lexer, this peeking ahead is unworkable.
2249  An arbitrary number of escaped newlines, and trigraphs (in particular
2250  ??/ which translates to the escape \), could separate the '!' and '='
2251  in the input stream, yet the next token is still a "!=".
2252
2253  Suppose instead that we lex by one logical line at a time, producing
2254  a token list or stack for each logical line, and when seeing the '!'
2255  push a CPP_NOT token on the list.  Then if the '!' is part of a
2256  longer token ("!=") we know we must see the remainder of the token by
2257  the time we reach the end of the logical line.  Thus we can have the
2258  '=' handler look at the previous token (at the end of the list / top
2259  of the stack) and see if it is a "!" token, and if so, instead of
2260  pushing a "=" token revise the existing token to be a "!=" token.
2261
2262  This works in the presence of escaped newlines, because the '\' would
2263  have been pushed on the top of the stack as a CPP_BACKSLASH.  The
2264  newline ('\n' or '\r') handler looks at the token at the top of the
2265  stack to see if it is a CPP_BACKSLASH, and if so discards both.
2266  Otherwise it pushes the newline (CPP_VSPACE) token as normal.  Hence
2267  the '=' handler would never see any intervening escaped newlines.
2268
2269  To make trigraphs work in this context, as in precedence trigraphs
2270  are highest and converted before anything else, the '?' handler does
2271  lookahead to see if it is a trigraph, and if so skips the trigraph
2272  and pushes the token it represents onto the top of the stack.  This
2273  also works in the particular case of a CPP_BACKSLASH trigraph.
2274
2275  To the preprocessor, whitespace is only significant to the point of
2276  knowing whether whitespace precedes a particular token.  For example,
2277  the '=' handler needs to know whether there was whitespace between it
2278  and a "!" token on the top of the stack, to make the token conversion
2279  decision correctly.  So each token has a PREV_WHITESPACE flag to
2280  indicate this - the standard permits consecutive whitespace to be
2281  regarded as a single space.  The compiler front ends are not
2282  interested in whitespace at all; they just require a token stream.
2283  Another place where whitespace is significant to the preprocessor is
2284  a #define statment - if there is whitespace between the macro name
2285  and an initial "(" token the macro is "object-like", otherwise it is
2286  a function-like macro that takes arguments.
2287
2288  However, all is not rosy.  Parsing of identifiers, numbers, comments
2289  and strings becomes trickier because of the possibility of raw
2290  trigraphs and escaped newlines in the input stream.
2291
2292  The trigraphs are three consecutive characters beginning with two
2293  question marks.  A question mark is not valid as part of a number or
2294  identifier, so parsing of a number or identifier terminates normally
2295  upon reaching it, returning to the mainloop which handles the
2296  trigraph just like it would in any other position.  Similarly for the
2297  backslash of a backslash-newline combination.  So we just need the
2298  escaped-newline dropper in the mainloop to check if the token on the
2299  top of the stack after dropping the escaped newline is a number or
2300  identifier, and if so to continue the processing it as if nothing had
2301  happened.
2302
2303  For strings, we replace trigraphs whenever we reach a quote or
2304  newline, because there might be a backslash trigraph escaping them.
2305  We need to be careful that we start trigraph replacing from where we
2306  left off previously, because it is possible for a first scan to leave
2307  "fake" trigraphs that a second scan would pick up as real (e.g. the
2308  sequence "????/\n=" would find a fake ??= trigraph after removing the
2309  escaped newline.)
2310
2311  For line comments, on reaching a newline we scan the previous
2312  character(s) to see if it escaped, and continue if it is.  Block
2313  comments ignore everything and just focus on finding the comment
2314  termination mark.  The only difficult thing, and it is surprisingly
2315  tricky, is checking if an asterisk precedes the final slash since
2316  they could be separated by escaped newlines.  If the preprocessor is
2317  invoked with the output comments option, we don't bother removing
2318  escaped newlines and replacing trigraphs for output.
2319
2320  Finally, numbers can begin with a period, which is pushed initially
2321  as a CPP_DOT token in its own right.  The digit handler checks if the
2322  previous token was a CPP_DOT not separated by whitespace, and if so
2323  pops it off the stack and pushes a period into the number's buffer
2324  before calling the number parser.
2325
2326 */
2327
2328 static const unsigned char *digraph_spellings [] = {U"%:", U"%:%:", U"<:",
2329                                                     U":>", U"<%", U"%>"};
2330 static unsigned char trigraph_map[256];
2331
2332 static void
2333 expand_comment_space (list)
2334      cpp_toklist *list;
2335 {
2336   if (list->comments_cap == 0)
2337     {
2338       list->comments_cap = 10;
2339       list->comments = (cpp_token *)
2340         xmalloc (list->comments_cap * sizeof (cpp_token));
2341     }
2342   else
2343     {
2344       list->comments_cap *= 2;
2345       list->comments = (cpp_token *)
2346         xrealloc (list->comments, list->comments_cap);
2347     }
2348 }
2349
2350 void
2351 init_trigraph_map ()
2352 {
2353   trigraph_map['='] = '#';
2354   trigraph_map['('] = '[';
2355   trigraph_map[')'] = ']';
2356   trigraph_map['/'] = '\\';
2357   trigraph_map['\''] = '^';
2358   trigraph_map['<'] = '{';
2359   trigraph_map['>'] = '}';
2360   trigraph_map['!'] = '|';
2361   trigraph_map['-'] = '~';
2362 }
2363
2364 /* Call when a trigraph is encountered.  It warns if necessary, and
2365    returns true if the trigraph should be honoured.  END is the third
2366    character of a trigraph in the input stream.  */
2367 static int
2368 trigraph_ok (pfile, end)
2369      cpp_reader *pfile;
2370      const unsigned char *end;
2371 {
2372   int accept = CPP_OPTION (pfile, trigraphs);
2373   
2374   if (CPP_OPTION (pfile, warn_trigraphs))
2375     {
2376       unsigned int col = end - 1 - pfile->buffer->line_base;
2377       if (accept)
2378         cpp_warning_with_line (pfile, pfile->buffer->lineno, col, 
2379                                "trigraph ??%c converted to %c",
2380                                (int) *end, (int) trigraph_map[*end]);
2381       else
2382         cpp_warning_with_line (pfile, pfile->buffer->lineno, col,
2383                                "trigraph ??%c ignored", (int) *end);
2384     }
2385   return accept;
2386 }
2387
2388 /* Scan a string for trigraphs, warning or replacing them inline as
2389    appropriate.  When parsing a string, we must call this routine
2390    before processing a newline character (if trigraphs are enabled),
2391    since the newline might be escaped by a preceding backslash
2392    trigraph sequence.  Returns a pointer to the end of the name after
2393    replacement.  */
2394
2395 static unsigned char*
2396 trigraph_replace (pfile, src, limit)
2397      cpp_reader *pfile;
2398      unsigned char *src;
2399      unsigned char* limit;
2400 {
2401   unsigned char *dest;
2402
2403   /* Starting with src[1], find two consecutive '?'.  The case of no
2404      trigraphs is streamlined.  */
2405   
2406   for (; src + 1 < limit; src += 2)
2407     {
2408       if (src[0] != '?')
2409         continue;
2410
2411       /* Make src point to the 1st (NOT 2nd) of two consecutive '?'s.  */
2412       if (src[-1] == '?')
2413         src--;
2414       else if (src + 2 == limit || src[1] != '?')
2415         continue;
2416
2417       /* Check if it really is a trigraph.  */
2418       if (trigraph_map[src[2]] == 0)
2419         continue;
2420
2421       dest = src;
2422       goto trigraph_found;
2423     }
2424   return limit;
2425
2426   /* Now we have a trigraph, we need to scan the remaining buffer, and
2427      copy-shifting its contents left if replacement is enabled.  */
2428   for (; src + 2 < limit; dest++, src++)
2429     if ((*dest = *src) == '?' && src[1] == '?' && trigraph_map[src[2]])
2430       {
2431       trigraph_found:
2432         src += 2;
2433         if (trigraph_ok (pfile, pfile->buffer->cur - (limit - src)))
2434           *dest = trigraph_map[*src];
2435       }
2436   
2437   /* Copy remaining (at most 2) characters.  */
2438   while (src < limit)
2439     *dest++ = *src++;
2440   return dest;
2441 }
2442
2443 /* If CUR is a backslash or the end of a trigraphed backslash, return
2444    a pointer to its beginning, otherwise NULL.  We don't read beyond
2445    the buffer start, because there is the start of the comment in the
2446    buffer.  */
2447 static const unsigned char *
2448 backslash_start (pfile, cur)
2449      cpp_reader *pfile;
2450      const unsigned char *cur;
2451 {
2452   if (cur[0] == '\\')
2453     return cur;
2454   if (cur[0] == '/' && cur[-1] == '?' && cur[-2] == '?'
2455       && trigraph_ok (pfile, cur))
2456     return cur - 2;
2457   return 0;
2458 }
2459
2460 /* Skip a C-style block comment.  This is probably the trickiest
2461    handler.  We find the end of the comment by seeing if an asterisk
2462    is before every '/' we encounter.  The nasty complication is that a
2463    previous asterisk may be separated by one or more escaped newlines.
2464    Returns non-zero if comment terminated by EOF, zero otherwise.  */
2465 static int
2466 skip_block_comment2 (pfile)
2467      cpp_reader *pfile;
2468 {
2469   cpp_buffer *buffer = pfile->buffer;
2470   const unsigned char *char_after_star = 0;
2471   register const unsigned char *cur = buffer->cur;
2472   int seen_eof = 0;
2473   
2474   /* Inner loop would think the comment has ended if the first comment
2475      character is a '/'.  Avoid this and keep the inner loop clean by
2476      skipping such a character.  */
2477   if (cur < buffer->rlimit && cur[0] == '/')
2478     cur++;
2479
2480   for (; cur < buffer->rlimit; )
2481     {
2482       unsigned char c = *cur++;
2483
2484       /* People like decorating comments with '*', so check for
2485          '/' instead for efficiency.  */
2486       if (c == '/')
2487         {
2488           if (cur[-2] == '*' || cur - 1 == char_after_star)
2489             goto out;
2490
2491           /* Warn about potential nested comments, but not when
2492              the final character inside the comment is a '/'.
2493              Don't bother to get it right across escaped newlines.  */
2494           if (CPP_OPTION (pfile, warn_comments) && cur + 1 < buffer->rlimit
2495               && cur[0] == '*' && cur[1] != '/') 
2496             {
2497               buffer->cur = cur;
2498               cpp_warning (pfile, "'/*' within comment");
2499             }
2500         }
2501       else if (IS_NEWLINE(c))
2502         {
2503           const unsigned char* bslash = backslash_start (pfile, cur - 2);
2504
2505           handle_newline (cur, buffer->rlimit, c);
2506           /* Work correctly if there is an asterisk before an
2507              arbirtrarily long sequence of escaped newlines.  */
2508           if (bslash && (bslash[-1] == '*' || bslash == char_after_star))
2509             char_after_star = cur;
2510           else
2511             char_after_star = 0;
2512         }
2513     }
2514   seen_eof = 1;
2515
2516  out:
2517   buffer->cur = cur;
2518   return seen_eof;
2519 }
2520
2521 /* Skip a C++ or Chill line comment.  Handles escaped newlines.
2522    Returns non-zero if a multiline comment.  */
2523 static int
2524 skip_line_comment2 (pfile)
2525      cpp_reader *pfile;
2526 {
2527   cpp_buffer *buffer = pfile->buffer;
2528   register const unsigned char *cur = buffer->cur;
2529   int multiline = 0;
2530
2531   for (; cur < buffer->rlimit; )
2532     {
2533       unsigned char c = *cur++;
2534
2535       if (IS_NEWLINE (c))
2536         {
2537           /* Check for a (trigaph?) backslash escaping the newline.  */
2538           if (!backslash_start (pfile, cur - 2))
2539             goto out;
2540           multiline = 1;
2541           handle_newline (cur, buffer->rlimit, c);
2542         }
2543     }
2544   cur++;
2545
2546  out:
2547   buffer->cur = cur - 1;        /* Leave newline for caller.  */
2548   return multiline;
2549 }
2550
2551 /* Skips whitespace, stopping at next non-whitespace character.
2552    Adjusts pfile->col_adjust to account for tabs.  This enables tokens
2553    to be assigned the correct column.  */
2554 static void
2555 skip_whitespace (pfile, in_directive)
2556      cpp_reader *pfile;
2557      int in_directive;
2558 {
2559   cpp_buffer *buffer = pfile->buffer;
2560   register const unsigned char *cur = buffer->cur;
2561   unsigned short null_count = 0;
2562
2563   for (; cur < buffer->rlimit; )
2564     {
2565       unsigned char c = *cur++;
2566
2567       if (c == '\t')
2568         {
2569           unsigned int col = CPP_BUF_COLUMN (buffer, cur - 1);
2570           pfile->col_adjust += (CPP_OPTION (pfile, tabstop) - 1
2571                                 - col % CPP_OPTION(pfile, tabstop));
2572         }
2573       if (IS_HSPACE(c))         /* FIXME: Fix ISTABLE.  */
2574         continue;
2575       if (!is_space(c) || IS_NEWLINE (c)) /* Main loop handles newlines.  */
2576         goto out;
2577       if (c == '\0')
2578         null_count++;
2579       /* Mut be '\f' or '\v' */
2580       else if (in_directive && CPP_PEDANTIC (pfile))
2581         cpp_pedwarn (pfile, "%s in preprocessing directive",
2582                      c == '\f' ? "formfeed" : "vertical tab");
2583     }
2584   cur++;
2585
2586  out:
2587   buffer->cur = cur - 1;
2588   if (null_count)
2589     cpp_warning (pfile, null_count > 1 ? "embedded null characters ignored"
2590                  : "embedded null character ignored");
2591 }
2592
2593 /* Parse (append) an identifier.  */
2594 static void
2595 parse_name (pfile, list, name)
2596      cpp_reader *pfile;
2597      cpp_toklist *list;
2598      cpp_name *name;
2599 {
2600   const unsigned char *name_limit;
2601   unsigned char *namebuf;
2602   cpp_buffer *buffer = pfile->buffer;
2603   register const unsigned char *cur = buffer->cur;
2604
2605  expanded:
2606   name_limit = list->namebuf + list->name_cap;
2607   namebuf = list->namebuf + list->name_used;
2608
2609   for (; cur < buffer->rlimit && namebuf < name_limit; )
2610     {
2611       unsigned char c = *namebuf = *cur; /* Copy a single char.  */
2612
2613       if (! is_idchar(c))
2614         goto out;
2615       namebuf++;
2616       cur++;
2617       if (c == '$' && CPP_PEDANTIC (pfile))
2618         {
2619           buffer->cur = cur;
2620           cpp_pedwarn (pfile, "'$' character in identifier");
2621         }
2622     }
2623
2624   /* Run out of name space?  */
2625   if (cur < buffer->rlimit)
2626     {
2627       list->name_used = namebuf - list->namebuf;
2628       auto_expand_name_space (list);
2629       goto expanded;
2630     }
2631
2632  out:
2633   buffer->cur = cur;
2634   name->len = namebuf - name->text;
2635   list->name_used = namebuf - list->namebuf;
2636 }
2637
2638 /* Parse (append) a number.  */
2639
2640 #define VALID_SIGN(c, prevc) \
2641   (((c) == '+' || (c) == '-') && \
2642    ((prevc) == 'e' || (prevc) == 'E' \
2643     || (((prevc) == 'p' || (prevc) == 'P') && !CPP_OPTION (pfile, c89))))
2644
2645 static void
2646 parse_number (pfile, list, name)
2647      cpp_reader *pfile;
2648      cpp_toklist *list;
2649      cpp_name *name;
2650 {
2651   const unsigned char *name_limit;
2652   unsigned char *namebuf;
2653   cpp_buffer *buffer = pfile->buffer;
2654   register const unsigned char *cur = buffer->cur;
2655
2656  expanded:
2657   name_limit = list->namebuf + list->name_cap;
2658   namebuf = list->namebuf + list->name_used;
2659
2660   for (; cur < buffer->rlimit && namebuf < name_limit; )
2661     {
2662       unsigned char c = *namebuf = *cur; /* Copy a single char.  */
2663
2664       /* Perhaps we should accept '$' here if we accept it for
2665          identifiers.  We know namebuf[-1] is safe, because for c to
2666          be a sign we must have pushed at least one character.  */
2667       if (!is_numchar (c) && c != '.' && ! VALID_SIGN (c, namebuf[-1]))
2668         goto out;
2669
2670       namebuf++;
2671       cur++;
2672     }
2673
2674   /* Run out of name space?  */
2675   if (cur < buffer->rlimit)
2676     {
2677       list->name_used = namebuf - list->namebuf;
2678       auto_expand_name_space (list);
2679       goto expanded;
2680     }
2681   
2682  out:
2683   buffer->cur = cur;
2684   name->len = namebuf - name->text;
2685   list->name_used = namebuf - list->namebuf;
2686 }
2687
2688 /* Places a string terminated by an unescaped TERMINATOR into a
2689    cpp_name, which should be expandable and thus at the top of the
2690    list's stack.  Handles embedded trigraphs, if necessary, and
2691    escaped newlines.
2692
2693    Can be used for character constants (terminator = '\''), string
2694    constants ('"') and angled headers ('>').  Multi-line strings are
2695    allowed, except for within directives.  */
2696
2697 static void
2698 parse_string2 (pfile, list, name, terminator)
2699      cpp_reader *pfile;
2700      cpp_toklist *list;
2701      cpp_name *name;
2702      unsigned int terminator;
2703 {
2704   cpp_buffer *buffer = pfile->buffer;
2705   register const unsigned char *cur = buffer->cur;
2706   const unsigned char *name_limit;
2707   unsigned char *namebuf;
2708   unsigned int null_count = 0;
2709   int trigraphed_len = 0;
2710
2711  expanded:
2712   name_limit = list->namebuf + list->name_cap;
2713   namebuf = list->namebuf + list->name_used;
2714
2715   for (; cur < buffer->rlimit && namebuf < name_limit; )
2716     {
2717       unsigned int c = *namebuf++ = *cur++; /* Copy a single char.  */
2718
2719       if (c == '\0')
2720         null_count++;
2721       else if (c == terminator || IS_NEWLINE (c))
2722         {
2723           /* Needed for trigraph_replace and multiline string warning.  */
2724           buffer->cur = cur;
2725
2726           /* Scan for trigraphs before checking if backslash-escaped.  */
2727           if (CPP_OPTION (pfile, trigraphs)
2728               || CPP_OPTION (pfile, warn_trigraphs))
2729             {
2730               namebuf = trigraph_replace (pfile, name->text + trigraphed_len,
2731                                             namebuf);
2732               trigraphed_len = namebuf - 2 - (name->text + trigraphed_len);
2733               if (trigraphed_len < 0)
2734                 trigraphed_len = 0;
2735             }
2736
2737           namebuf--;     /* Drop the newline / terminator from the name.  */
2738           if (IS_NEWLINE (c))
2739             {
2740               /* Drop a backslash newline, and continue. */
2741               if (namebuf[-1] == '\\')
2742                 {
2743                   handle_newline (cur, buffer->rlimit, c);
2744                   namebuf--;
2745                   continue;
2746                 }
2747
2748               cur--;
2749
2750               /* In Fortran and assembly language, silently terminate
2751                  strings of either variety at end of line.  This is a
2752                  kludge around not knowing where comments are in these
2753                  languages.  */
2754               if (CPP_OPTION (pfile, lang_fortran)
2755                   || CPP_OPTION (pfile, lang_asm))
2756                 goto out;
2757
2758               /* Character constants, headers and asserts may not
2759                  extend over multiple lines.  In Standard C, neither
2760                  may strings.  We accept multiline strings as an
2761                  extension, but not in directives.  */
2762               if (terminator != '"' || IS_DIRECTIVE (list))
2763                 goto unterminated;
2764                 
2765               cur++;  /* Move forwards again.  */
2766
2767               if (pfile->multiline_string_line == 0)
2768                 {
2769                   pfile->multiline_string_line = list->line;
2770                   if (CPP_PEDANTIC (pfile))
2771                     cpp_pedwarn (pfile, "multi-line string constant");
2772                 }
2773
2774               *namebuf++ = '\n';
2775               handle_newline (cur, buffer->rlimit, c);
2776             }
2777           else
2778             {
2779               unsigned char *temp;
2780
2781               /* An odd number of consecutive backslashes represents
2782                  an escaped terminator.  */
2783               temp = namebuf - 1;
2784               while (temp >= name->text && *temp == '\\')
2785                 temp--;
2786
2787               if ((namebuf - temp) & 1)
2788                 goto out;
2789               namebuf++;
2790             }
2791         }
2792     }
2793
2794   /* Run out of name space?  */
2795   if (cur < buffer->rlimit)
2796     {
2797       list->name_used = namebuf - list->namebuf;
2798       auto_expand_name_space (list);
2799       goto expanded;
2800     }
2801
2802   /* We may not have trigraph-replaced the input for this code path,
2803      but as the input is in error by being unterminated we don't
2804      bother.  Prevent warnings about no newlines at EOF.  */
2805   if (IS_NEWLINE(cur[-1]))
2806     cur--;
2807
2808  unterminated:
2809   cpp_error (pfile, "missing terminating %c character", (int) terminator);
2810
2811   if (terminator == '\"' && pfile->multiline_string_line != list->line
2812       && pfile->multiline_string_line != 0)
2813     {
2814       cpp_error_with_line (pfile, pfile->multiline_string_line, -1,
2815                            "possible start of unterminated string literal");
2816       pfile->multiline_string_line = 0;
2817     }
2818   
2819  out:
2820   buffer->cur = cur;
2821   name->len = namebuf - name->text;
2822   list->name_used = namebuf - list->namebuf;
2823
2824   if (null_count > 0)
2825     cpp_warning (pfile, (null_count > 1 ? "null characters preserved"
2826                          : "null character preserved"));
2827 }
2828
2829 /* The character TYPE helps us distinguish comment types: '*' = C
2830    style, '-' = Chill-style and '/' = C++ style.  For code simplicity,
2831    the stored comment includes the comment start and any terminator.  */
2832
2833 #define COMMENT_START_LEN 2
2834 static void
2835 save_comment (list, from, len, tok_no, type)
2836      cpp_toklist *list;
2837      const unsigned char *from;
2838      unsigned int len;
2839      unsigned int tok_no;
2840      unsigned int type;
2841 {
2842   cpp_token *comment;
2843   unsigned char *buffer;
2844   
2845   len += COMMENT_START_LEN;
2846
2847   if (list->comments_used == list->comments_cap)
2848     expand_comment_space (list);
2849
2850   if (list->name_used + len > list->name_cap)
2851     expand_name_space (list, len);
2852
2853   buffer = list->namebuf + list->name_used;
2854
2855   comment = &list->comments[list->comments_used++];
2856   comment->type = CPP_COMMENT;
2857   comment->aux = tok_no;
2858   comment->val.name.len = len;
2859   comment->val.name.text = buffer;
2860
2861   if (type == '*')
2862     {
2863       *buffer++ = '/';
2864       *buffer++ = '*';
2865     }
2866   else
2867     {
2868       *buffer++ = type;
2869       *buffer++ = type;
2870     }
2871
2872   memcpy (buffer, from, len - COMMENT_START_LEN);
2873   list->name_used += len;
2874 }
2875
2876 /*
2877  *  The tokenizer's main loop.  Returns a token list, representing a
2878  *  logical line in the input file, terminated with a CPP_VSPACE
2879  *  token.  On EOF, a token list containing the single CPP_EOF token
2880  *  is returned.
2881  *
2882  *  Implementation relies almost entirely on lookback, rather than
2883  *  looking forwards.  This means that tokenization requires just
2884  *  a single pass of the file, even in the presence of trigraphs and
2885  *  escaped newlines, providing significant performance benefits.
2886  *  Trigraph overhead is negligible if they are disabled, and low
2887  *  even when enabled.
2888  */
2889
2890 void
2891 _cpp_lex_line (pfile, list)
2892      cpp_reader *pfile;
2893      cpp_toklist *list;
2894 {
2895   cpp_token *cur_token, *token_limit;
2896   cpp_buffer *buffer = pfile->buffer;
2897   register const unsigned char *cur = buffer->cur;
2898   unsigned char flags = 0;
2899
2900   pfile->col_adjust = 0;
2901  expanded:
2902   token_limit = list->tokens + list->tokens_cap;
2903   cur_token = list->tokens + list->tokens_used;
2904
2905   for (; cur < buffer->rlimit && cur_token < token_limit;)
2906     {
2907       unsigned char c = *cur++;
2908
2909       /* Optimize whitespace skipping, as most tokens are probably
2910          separated by whitespace. (' ' '\t' '\v' '\f' '\0').  */
2911
2912       if (is_hspace ((unsigned int) c))
2913         {
2914           /* Step back to get the null warning and tab correction.  */
2915           buffer->cur = cur - 1;
2916           skip_whitespace (pfile, IS_DIRECTIVE (list));
2917           cur = buffer->cur;
2918
2919           flags = PREV_WHITESPACE;
2920           if (cur == buffer->rlimit)
2921             break;
2922           c = *cur++;
2923         }
2924
2925       /* Initialize current token.  Its type is set in the switch.  */
2926       cur_token->col = CPP_BUF_COLUMN (buffer, cur);
2927       cur_token->flags = flags;
2928       flags = 0;
2929
2930       switch (c)
2931         {
2932         case '0': case '1': case '2': case '3': case '4':
2933         case '5': case '6': case '7': case '8': case '9':
2934           cur--;                /* Backup character.  */
2935           if (PREV_TOKEN_TYPE == CPP_DOT && IMMED_TOKEN ())
2936             {
2937               /* Prepend an immediately previous CPP_DOT token.  */
2938               cur_token--;
2939               if (list->name_cap == list->name_used)
2940                 auto_expand_name_space (list);
2941
2942               cur_token->val.name.len = 1;
2943               cur_token->val.name.text = list->namebuf + list->name_used;
2944               list->namebuf[list->name_used++] = '.';
2945             }
2946           else
2947             INIT_NAME (list, cur_token->val.name);
2948
2949         continue_number:
2950           buffer->cur = cur;
2951           parse_number (pfile, list, &cur_token->val.name);
2952           cur = buffer->cur;
2953
2954           PUSH_TOKEN (CPP_NUMBER); /* Number not yet interpreted.  */
2955           break;
2956
2957         letter:
2958         case '_':
2959         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2960         case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2961         case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2962         case 's': case 't': case 'u': case 'v': case 'w': case 'x':
2963         case 'y': case 'z':
2964         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2965         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
2966         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
2967         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
2968         case 'Y': case 'Z':
2969           cur--;                     /* Backup character.  */
2970           INIT_NAME (list, cur_token->val.name);
2971           cur_token->type = CPP_NAME; /* Identifier, macro etc.  */
2972
2973         continue_name:
2974           buffer->cur = cur;
2975           parse_name (pfile, list, &cur_token->val.name);
2976           cur = buffer->cur;
2977
2978           /* Find handler for newly created / extended directive.  */
2979           if (IS_DIRECTIVE (list) && cur_token == &list->tokens[1])
2980             _cpp_check_directive (list, cur_token);
2981           cur_token++;
2982           break;
2983
2984         case '\'':
2985           /* Fall through.  */
2986         case '\"':
2987           cur_token->type = c == '\'' ? CPP_CHAR : CPP_STRING;
2988           /* Do we have a wide string?  */
2989           if (cur_token[-1].type == CPP_NAME && IMMED_TOKEN ()
2990               && cur_token[-1].val.name.len == 1
2991               && cur_token[-1].val.name.text[0] == 'L'
2992               && !CPP_TRADITIONAL (pfile))
2993             {
2994               /* No need for 'L' any more.  */
2995               list->name_used--;
2996               (--cur_token)->type = (c == '\'' ? CPP_WCHAR : CPP_WSTRING);
2997             }
2998
2999         do_parse_string:
3000           /* Here c is one of ' " or >.  */
3001           INIT_NAME (list, cur_token->val.name);
3002           buffer->cur = cur;
3003           parse_string2 (pfile, list, &cur_token->val.name, c);
3004           cur = buffer->cur;
3005           cur_token++;
3006           break;
3007
3008         case '/':
3009           cur_token->type = CPP_DIV;
3010           if (IMMED_TOKEN ())
3011             {
3012               if (PREV_TOKEN_TYPE == CPP_DIV)
3013                 {
3014                   /* We silently allow C++ comments in system headers,
3015                      irrespective of conformance mode, because lots of
3016                      broken systems do that and trying to clean it up
3017                      in fixincludes is a nightmare.  */
3018                   if (buffer->system_header_p)
3019                     goto do_line_comment;
3020                   else if (CPP_OPTION (pfile, cplusplus_comments))
3021                     {
3022                       if (CPP_OPTION (pfile, c89) && CPP_PEDANTIC (pfile)
3023                           && ! buffer->warned_cplusplus_comments)
3024                         {
3025                           buffer->cur = cur;
3026                           cpp_pedwarn (pfile,
3027                              "C++ style comments are not allowed in ISO C89");
3028                           cpp_pedwarn (pfile,
3029                           "(this will be reported only once per input file)");
3030                           buffer->warned_cplusplus_comments = 1;
3031                         }
3032                     do_line_comment:
3033                       buffer->cur = cur;
3034                       if (cur[-2] != c)
3035                         cpp_warning (pfile,
3036                                      "comment start split across lines");
3037                       if (skip_line_comment2 (pfile))
3038                         cpp_error_with_line (pfile, list->line,
3039                                              cur_token[-1].col,
3040                                              "multi-line comment");
3041                       if (!CPP_OPTION (pfile, discard_comments))
3042                         save_comment (list, cur, buffer->cur - cur,
3043                                       cur_token - 1 - list->tokens, c);
3044                       cur = buffer->cur;
3045
3046                       /* Back-up to first '-' or '/'.  */
3047                       cur_token -= 2;
3048                       if (!CPP_OPTION (pfile, traditional))
3049                         flags = PREV_WHITESPACE;
3050                     }
3051                 }
3052             }
3053           cur_token++;
3054           break;
3055                       
3056         case '*':
3057           cur_token->type = CPP_MULT;
3058           if (IMMED_TOKEN ())
3059             {
3060               if (PREV_TOKEN_TYPE == CPP_DIV)
3061                 {
3062                   buffer->cur = cur;
3063                   if (cur[-2] != '/')
3064                     cpp_warning (pfile,
3065                                  "comment start '/*' split across lines");
3066                   if (skip_block_comment2 (pfile))
3067                     cpp_error_with_line (pfile, list->line, cur_token[-1].col,
3068                                          "unterminated comment");
3069                   else if (buffer->cur[-2] != '*')
3070                     cpp_warning (pfile,
3071                                  "comment end '*/' split across lines");
3072                   if (!CPP_OPTION (pfile, discard_comments))
3073                     save_comment (list, cur, buffer->cur - cur,
3074                                  cur_token - 1 - list->tokens, c);
3075                   cur = buffer->cur;
3076
3077                   cur_token--;
3078                   if (!CPP_OPTION (pfile, traditional))
3079                     flags = PREV_WHITESPACE;
3080                   break;
3081                 }
3082               else if (CPP_OPTION (pfile, cplusplus))
3083                 {
3084                   /* In C++, there are .* and ->* operators.  */
3085                   if (PREV_TOKEN_TYPE == CPP_DEREF)
3086                     BACKUP_TOKEN (CPP_DEREF_STAR);
3087                   else if (PREV_TOKEN_TYPE == CPP_DOT)
3088                     BACKUP_TOKEN (CPP_DOT_STAR);
3089                 }
3090             }
3091           cur_token++;
3092           break;
3093
3094         case '\n':
3095         case '\r':
3096           handle_newline (cur, buffer->rlimit, c);
3097           if (PREV_TOKEN_TYPE == CPP_BACKSLASH && IMMED_TOKEN ())
3098             {
3099               /* Remove the escaped newline.  Then continue to process
3100                  any interrupted name or number.  */
3101               cur_token--;
3102               if (IMMED_TOKEN ())
3103                 {
3104                   cur_token--;
3105                   if (cur_token->type == CPP_NAME)
3106                     goto continue_name;
3107                   else if (cur_token->type == CPP_NUMBER)
3108                     goto continue_number;
3109                   cur_token++;
3110                 }
3111               /* Remember whitespace setting.  */
3112               flags = cur_token->flags;
3113               break;
3114             }
3115           if (PREV_TOKEN_TYPE == CPP_BACKSLASH)
3116             {
3117               buffer->cur = cur;
3118               cpp_warning (pfile, "backslash and newline separated by space");
3119             }
3120           PUSH_TOKEN (CPP_VSPACE);
3121           goto out;
3122
3123         case '-':
3124           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_MINUS)
3125             {
3126               if (CPP_OPTION (pfile, chill))
3127                 goto do_line_comment;
3128               REVISE_TOKEN (CPP_MINUS_MINUS);
3129             }
3130           else
3131             PUSH_TOKEN (CPP_MINUS);
3132           break;
3133
3134           /* The digraph flag checking ensures that ## and %:%:
3135              are interpreted as CPP_PASTE, but #%: and %:# are not.  */
3136         make_hash:
3137         case '#':
3138           if (PREV_TOKEN_TYPE == CPP_HASH && IMMED_TOKEN ()
3139               && ((cur_token->flags ^ cur_token[-1].flags) & DIGRAPH) == 0)
3140             REVISE_TOKEN (CPP_PASTE);
3141           else
3142             PUSH_TOKEN (CPP_HASH);
3143           break;
3144
3145         case ':':
3146           cur_token->type = CPP_COLON;
3147           if (IMMED_TOKEN ())
3148             {
3149               if (PREV_TOKEN_TYPE == CPP_COLON
3150                   && CPP_OPTION (pfile, cplusplus))
3151                 BACKUP_TOKEN (CPP_SCOPE);
3152               /* Digraph: "<:" is a '['  */
3153               else if (PREV_TOKEN_TYPE == CPP_LESS)
3154                 BACKUP_DIGRAPH (CPP_OPEN_SQUARE);
3155               /* Digraph: "%:" is a '#'  */
3156               else if (PREV_TOKEN_TYPE == CPP_MOD)
3157                 {
3158                   (--cur_token)->flags |= DIGRAPH;
3159                   goto make_hash;
3160                 }
3161             }
3162           cur_token++;
3163           break;
3164
3165         case '&':
3166           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_AND)
3167             REVISE_TOKEN (CPP_AND_AND);
3168           else
3169             PUSH_TOKEN (CPP_AND);
3170           break;
3171
3172         make_or:
3173         case '|':
3174           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_OR)
3175             REVISE_TOKEN (CPP_OR_OR);
3176           else
3177             PUSH_TOKEN (CPP_OR);
3178           break;
3179
3180         case '+':
3181           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_PLUS)
3182             REVISE_TOKEN (CPP_PLUS_PLUS);
3183           else
3184             PUSH_TOKEN (CPP_PLUS);
3185           break;
3186
3187         case '=':
3188             /* This relies on equidistance of "?=" and "?" tokens.  */
3189           if (IMMED_TOKEN () && PREV_TOKEN_TYPE <= CPP_LAST_EQ)
3190             REVISE_TOKEN (PREV_TOKEN_TYPE + (CPP_EQ_EQ - CPP_EQ));
3191           else
3192             PUSH_TOKEN (CPP_EQ);
3193           break;
3194
3195         case '>':
3196           cur_token->type = CPP_GREATER;
3197           if (IMMED_TOKEN ())
3198             {
3199               if (PREV_TOKEN_TYPE == CPP_GREATER)
3200                 BACKUP_TOKEN (CPP_RSHIFT);
3201               else if (PREV_TOKEN_TYPE == CPP_MINUS)
3202                 BACKUP_TOKEN (CPP_DEREF);
3203               /* Digraph: ":>" is a ']'  */
3204               else if (PREV_TOKEN_TYPE == CPP_COLON)
3205                 BACKUP_DIGRAPH (CPP_CLOSE_SQUARE);
3206               /* Digraph: "%>" is a '}'  */
3207               else if (PREV_TOKEN_TYPE == CPP_MOD)
3208                 BACKUP_DIGRAPH (CPP_CLOSE_BRACE);
3209             }
3210           cur_token++;
3211           break;
3212           
3213         case '<':
3214           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_LESS)
3215             {
3216               REVISE_TOKEN (CPP_LSHIFT);
3217               break;
3218             }
3219           /* Is this the beginning of a header name?  */
3220           if (list->flags & SYNTAX_INCLUDE)
3221             {
3222               c = '>';  /* Terminator.  */
3223               cur_token->type = CPP_HEADER_NAME;
3224               goto do_parse_string;
3225             }
3226           PUSH_TOKEN (CPP_LESS);
3227           break;
3228
3229         case '%':
3230           /* Digraph: "<%" is a '{'  */
3231           cur_token->type = CPP_MOD;
3232           if (IMMED_TOKEN () && PREV_TOKEN_TYPE == CPP_LESS)
3233             BACKUP_DIGRAPH (CPP_OPEN_BRACE);
3234           cur_token++;
3235           break;
3236
3237         case '?':
3238           if (cur + 1 < buffer->rlimit && *cur == '?'
3239               && trigraph_map[cur[1]] && trigraph_ok (pfile, cur + 1))
3240             {
3241               /* Handle trigraph.  */
3242               cur++;
3243               switch (*cur++)
3244                 {
3245                 case '(': goto make_open_square;
3246                 case ')': goto make_close_square;
3247                 case '<': goto make_open_brace;
3248                 case '>': goto make_close_brace;
3249                 case '=': goto make_hash;
3250                 case '!': goto make_or;
3251                 case '-': goto make_complement;
3252                 case '/': goto make_backslash;
3253                 case '\'': goto make_xor;
3254                 }
3255             }
3256           if (IMMED_TOKEN () && CPP_OPTION (pfile, cplusplus))
3257             {
3258               /* GNU C++ defines <? and >? operators.  */
3259               if (PREV_TOKEN_TYPE == CPP_LESS)
3260                 {
3261                   REVISE_TOKEN (CPP_MIN);
3262                   break;
3263                 }
3264               else if (PREV_TOKEN_TYPE == CPP_GREATER)
3265                 {
3266                   REVISE_TOKEN (CPP_MAX);
3267                   break;
3268                 }
3269             }
3270           PUSH_TOKEN (CPP_QUERY);
3271           break;
3272
3273         case '.':
3274           if (PREV_TOKEN_TYPE == CPP_DOT && cur_token[-2].type == CPP_DOT
3275               && IMMED_TOKEN ()
3276               && !(cur_token[-1].flags & PREV_WHITESPACE))
3277             {
3278               cur_token -= 2;
3279               PUSH_TOKEN (CPP_ELLIPSIS);
3280             }
3281           else
3282             PUSH_TOKEN (CPP_DOT);
3283           break;
3284
3285         make_complement:
3286         case '~': PUSH_TOKEN (CPP_COMPL); break;
3287         make_xor:
3288         case '^': PUSH_TOKEN (CPP_XOR); break;
3289         make_open_brace:
3290         case '{': PUSH_TOKEN (CPP_OPEN_BRACE); break;
3291         make_close_brace:
3292         case '}': PUSH_TOKEN (CPP_CLOSE_BRACE); break;
3293         make_open_square:
3294         case '[': PUSH_TOKEN (CPP_OPEN_SQUARE); break;
3295         make_close_square:
3296         case ']': PUSH_TOKEN (CPP_CLOSE_SQUARE); break;
3297         make_backslash:
3298         case '\\': PUSH_TOKEN (CPP_BACKSLASH); break;
3299         case '!': PUSH_TOKEN (CPP_NOT); break;
3300         case ',': PUSH_TOKEN (CPP_COMMA); break;
3301         case ';': PUSH_TOKEN (CPP_SEMICOLON); break;
3302         case '(': PUSH_TOKEN (CPP_OPEN_PAREN); break;
3303         case ')': PUSH_TOKEN (CPP_CLOSE_PAREN); break;
3304
3305         case '$':
3306           if (CPP_OPTION (pfile, dollars_in_ident))
3307             goto letter;
3308           /* Fall through */
3309         default:
3310           cur_token->aux = c;
3311           cur_token->val.name.len = 0; /* FIXME: needed for transition only */
3312           PUSH_TOKEN (CPP_OTHER);
3313           break;
3314         }
3315     }
3316
3317   /* Run out of token space?  */
3318   if (cur_token == token_limit)
3319     {
3320       list->tokens_used = cur_token - list->tokens;
3321       expand_token_space (list);
3322       goto expanded;
3323     }
3324
3325   cur_token->type = CPP_EOF;
3326   cur_token->flags = flags;
3327
3328   if (cur_token != &list->tokens[0])
3329     {
3330       /* Next call back will get just a CPP_EOF.  */
3331       buffer->cur = cur;
3332       cpp_warning (pfile, "no newline at end of file");
3333       PUSH_TOKEN (CPP_VSPACE);
3334     }
3335
3336  out:
3337   buffer->cur = cur;
3338
3339   list->tokens_used = cur_token - list->tokens;
3340
3341   /* FIXME:  take this check out and put it in the caller.
3342      list->directive == 0 indicates an unknown directive (but null
3343      directive is OK).  This is the first time we can be sure the
3344      directive is invalid, and thus warn about it, because it might
3345      have been split by escaped newlines.  Also, don't complain about
3346      invalid directives in assembly source, we don't know where the
3347      comments are, and # may introduce assembler pseudo-ops.  */
3348
3349   if (IS_DIRECTIVE (list) && list->dirno == -1
3350       && list->tokens[1].type != CPP_VSPACE
3351       && !CPP_OPTION (pfile, lang_asm))
3352     cpp_error_with_line (pfile, list->line, list->tokens[1].col,
3353                          "invalid preprocessing directive");
3354 }
3355
3356 /* Write the spelling of a token TOKEN to BUFFER.  The buffer must
3357    already contain the enough space to hold the token's spelling.  If
3358    WHITESPACE is true, and the token was preceded by whitespace,
3359    output a single space before the token proper.  Returns a pointer
3360    to the character after the last character written.  */
3361
3362 static unsigned char *
3363 spell_token (pfile, token, buffer, whitespace)
3364      cpp_reader *pfile;         /* Would be nice to be rid of this...  */
3365      cpp_token *token;
3366      unsigned char *buffer;
3367      int whitespace;
3368 {
3369   /* Whitespace will not be wanted by handlers of the # and ##
3370      operators calling this function, but will be wanted by the
3371      function that writes out the preprocessed file.  */
3372   if (whitespace && token->flags & PREV_WHITESPACE)
3373     *buffer++ = ' ';
3374
3375   switch (token_spellings[token->type].type)
3376     {
3377     case SPELL_OPERATOR:
3378       {
3379         const unsigned char *spelling;
3380         unsigned char c;
3381
3382         if (token->flags & DIGRAPH)
3383           spelling = digraph_spellings[token->type - CPP_FIRST_DIGRAPH];
3384         else
3385           spelling = token_spellings[token->type].spelling;
3386         
3387         while ((c = *spelling++) != '\0')
3388           *buffer++ = c;
3389       }
3390       break;
3391
3392     case SPELL_IDENT:
3393       memcpy (buffer, token->val.name.text, token->val.name.len);
3394       buffer += token->val.name.len;
3395       break;
3396
3397     case SPELL_STRING:
3398       {
3399         unsigned char c;
3400
3401         if (token->type == CPP_WSTRING || token->type == CPP_WCHAR)
3402           *buffer++ = 'L';
3403         c = '\'';
3404         if (token->type == CPP_STRING || token->type == CPP_WSTRING)
3405           c = '"';
3406         *buffer++ = c;
3407         memcpy (buffer, token->val.name.text, token->val.name.len);
3408         buffer += token->val.name.len;
3409         *buffer++ = c;
3410       }
3411       break;
3412
3413     case SPELL_CHAR:
3414       *buffer++ = token->aux;
3415       break;
3416
3417     case SPELL_NONE:
3418       cpp_ice (pfile, "Unspellable token");
3419       break;
3420     }
3421
3422   return buffer;
3423 }
3424
3425 /* Temporary function for illustrative purposes.  */
3426 void
3427 _cpp_lex_file (pfile)
3428      cpp_reader* pfile;
3429 {
3430   cpp_toklist* list;
3431
3432   init_trigraph_map ();
3433   list = (cpp_toklist *) xmalloc (sizeof (cpp_toklist));
3434   _cpp_init_toklist (list);
3435
3436   for (;;)
3437     {
3438       _cpp_lex_line (pfile, list);
3439       if (list->tokens[0].type == CPP_EOF)
3440         break;
3441
3442 #if 0
3443       if (list->dirno)
3444         _cpp_handle_directive (pfile, list);
3445       else
3446 #endif
3447         _cpp_output_list (pfile, list);
3448       _cpp_clear_toklist (list);
3449     }
3450 }
3451
3452 /* Temporary function for illustrative purposes.  */
3453 static void
3454 _cpp_output_list (pfile, list)
3455      cpp_reader *pfile;
3456      cpp_toklist *list;
3457 {
3458   cpp_token *token, *comment, *comment_before = 0;
3459
3460   if (list->comments_used > 0)
3461     {
3462       comment = &list->comments[0];
3463       comment_before = &list->tokens[comment->aux];
3464     }
3465
3466   token = &list->tokens[0];
3467   do
3468     {
3469       /* Output comments if -C.  */
3470       while (token == comment_before)
3471         {
3472           /* Make space for the comment, and copy it out.  */
3473           CPP_RESERVE (pfile, TOKEN_LEN (comment));
3474           pfile->limit = spell_token (pfile, comment, pfile->limit, 0);
3475
3476           /* Stop if no comments left, or no more comments appear
3477              before the current token.  */
3478           comment++;
3479           if (comment == list->comments + list->comments_used)
3480             break;
3481           comment_before = &list->tokens[comment->aux];
3482         }
3483
3484       CPP_RESERVE (pfile, TOKEN_LEN (token));
3485       pfile->limit = spell_token (pfile, token, pfile->limit, 1);
3486     }
3487   while (token++->type != CPP_VSPACE);
3488 }
3489
3490 #endif