OSDN Git Service

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