OSDN Git Service

* lex.c (init_vectorized_lexer): Fix comparison of masked value.
[pf3gnuchains/gcc-fork.git] / libcpp / lex.c
1 /* CPP Library - lexical analysis.
2    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Per Bothner, 1994-95.
5    Based on CCCP program by Paul Rubin, June 1986
6    Adapted to ANSI C, Richard Stallman, Jan 1987
7    Broken out to separate file, Zack Weinberg, Mar 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 3, 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; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "cpplib.h"
26 #include "internal.h"
27
28 enum spell_type
29 {
30   SPELL_OPERATOR = 0,
31   SPELL_IDENT,
32   SPELL_LITERAL,
33   SPELL_NONE
34 };
35
36 struct token_spelling
37 {
38   enum spell_type category;
39   const unsigned char *name;
40 };
41
42 static const unsigned char *const digraph_spellings[] =
43 { UC"%:", UC"%:%:", UC"<:", UC":>", UC"<%", UC"%>" };
44
45 #define OP(e, s) { SPELL_OPERATOR, UC s  },
46 #define TK(e, s) { SPELL_ ## s,    UC #e },
47 static const struct token_spelling token_spellings[N_TTYPES] = { TTYPE_TABLE };
48 #undef OP
49 #undef TK
50
51 #define TOKEN_SPELL(token) (token_spellings[(token)->type].category)
52 #define TOKEN_NAME(token) (token_spellings[(token)->type].name)
53
54 static void add_line_note (cpp_buffer *, const uchar *, unsigned int);
55 static int skip_line_comment (cpp_reader *);
56 static void skip_whitespace (cpp_reader *, cppchar_t);
57 static void lex_string (cpp_reader *, cpp_token *, const uchar *);
58 static void save_comment (cpp_reader *, cpp_token *, const uchar *, cppchar_t);
59 static void store_comment (cpp_reader *, cpp_token *);
60 static void create_literal (cpp_reader *, cpp_token *, const uchar *,
61                             unsigned int, enum cpp_ttype);
62 static bool warn_in_comment (cpp_reader *, _cpp_line_note *);
63 static int name_p (cpp_reader *, const cpp_string *);
64 static tokenrun *next_tokenrun (tokenrun *);
65
66 static _cpp_buff *new_buff (size_t);
67
68
69 /* Utility routine:
70
71    Compares, the token TOKEN to the NUL-terminated string STRING.
72    TOKEN must be a CPP_NAME.  Returns 1 for equal, 0 for unequal.  */
73 int
74 cpp_ideq (const cpp_token *token, const char *string)
75 {
76   if (token->type != CPP_NAME)
77     return 0;
78
79   return !ustrcmp (NODE_NAME (token->val.node.node), (const uchar *) string);
80 }
81
82 /* Record a note TYPE at byte POS into the current cleaned logical
83    line.  */
84 static void
85 add_line_note (cpp_buffer *buffer, const uchar *pos, unsigned int type)
86 {
87   if (buffer->notes_used == buffer->notes_cap)
88     {
89       buffer->notes_cap = buffer->notes_cap * 2 + 200;
90       buffer->notes = XRESIZEVEC (_cpp_line_note, buffer->notes,
91                                   buffer->notes_cap);
92     }
93
94   buffer->notes[buffer->notes_used].pos = pos;
95   buffer->notes[buffer->notes_used].type = type;
96   buffer->notes_used++;
97 }
98
99 \f
100 /* Fast path to find line special characters using optimized character
101    scanning algorithms.  Anything complicated falls back to the slow
102    path below.  Since this loop is very hot it's worth doing these kinds
103    of optimizations.
104
105    One of the paths through the ifdefs should provide 
106
107      const uchar *search_line_fast (const uchar *s, const uchar *end);
108
109    Between S and END, search for \n, \r, \\, ?.  Return a pointer to
110    the found character.
111
112    Note that the last character of the buffer is *always* a newline,
113    as forced by _cpp_convert_input.  This fact can be used to avoid
114    explicitly looking for the end of the buffer.  */
115
116 /* Configure gives us an ifdef test.  */
117 #ifndef WORDS_BIGENDIAN
118 #define WORDS_BIGENDIAN 0
119 #endif
120
121 /* We'd like the largest integer that fits into a register.  There's nothing
122    in <stdint.h> that gives us that.  For most hosts this is unsigned long,
123    but MS decided on an LLP64 model.  Thankfully when building with GCC we
124    can get the "real" word size.  */
125 #ifdef __GNUC__
126 typedef unsigned int word_type __attribute__((__mode__(__word__)));
127 #else
128 typedef unsigned long word_type;
129 #endif
130
131 /* The code below is only expecting sizes 4 or 8.
132    Die at compile-time if this expectation is violated.  */
133 typedef char check_word_type_size
134   [(sizeof(word_type) == 8 || sizeof(word_type) == 4) * 2 - 1];
135
136 /* Return X with the first N bytes forced to values that won't match one
137    of the interesting characters.  Note that NUL is not interesting.  */
138
139 static inline word_type
140 acc_char_mask_misalign (word_type val, unsigned int n)
141 {
142   word_type mask = -1;
143   if (WORDS_BIGENDIAN)
144     mask >>= n * 8;
145   else
146     mask <<= n * 8;
147   return val & mask;
148 }
149
150 /* Return X replicated to all byte positions within WORD_TYPE.  */
151
152 static inline word_type
153 acc_char_replicate (uchar x)
154 {
155   word_type ret;
156
157   ret = (x << 24) | (x << 16) | (x << 8) | x;
158   if (sizeof(word_type) == 8)
159     ret = (ret << 16 << 16) | ret;
160   return ret;
161 }
162
163 /* Return non-zero if some byte of VAL is (probably) C.  */
164
165 static inline word_type
166 acc_char_cmp (word_type val, word_type c)
167 {
168 #if defined(__GNUC__) && defined(__alpha__)
169   /* We can get exact results using a compare-bytes instruction.  
170      Get (val == c) via (0 >= (val ^ c)).  */
171   return __builtin_alpha_cmpbge (0, val ^ c);
172 #else
173   word_type magic = 0x7efefefeU;
174   if (sizeof(word_type) == 8)
175     magic = (magic << 16 << 16) | 0xfefefefeU;
176   magic |= 1;
177
178   val ^= c;
179   return ((val + magic) ^ ~val) & ~magic;
180 #endif
181 }
182
183 /* Given the result of acc_char_cmp is non-zero, return the index of
184    the found character.  If this was a false positive, return -1.  */
185
186 static inline int
187 acc_char_index (word_type cmp ATTRIBUTE_UNUSED,
188                 word_type val ATTRIBUTE_UNUSED)
189 {
190 #if defined(__GNUC__) && defined(__alpha__) && !WORDS_BIGENDIAN
191   /* The cmpbge instruction sets *bits* of the result corresponding to
192      matches in the bytes with no false positives.  */
193   return __builtin_ctzl (cmp);
194 #else
195   unsigned int i;
196
197   /* ??? It would be nice to force unrolling here,
198      and have all of these constants folded.  */
199   for (i = 0; i < sizeof(word_type); ++i)
200     {
201       uchar c;
202       if (WORDS_BIGENDIAN)
203         c = (val >> (sizeof(word_type) - i - 1) * 8) & 0xff;
204       else
205         c = (val >> i * 8) & 0xff;
206
207       if (c == '\n' || c == '\r' || c == '\\' || c == '?')
208         return i;
209     }
210
211   return -1;
212 #endif
213 }
214
215 /* A version of the fast scanner using bit fiddling techniques.
216  
217    For 32-bit words, one would normally perform 16 comparisons and
218    16 branches.  With this algorithm one performs 24 arithmetic
219    operations and one branch.  Whether this is faster with a 32-bit
220    word size is going to be somewhat system dependent.
221
222    For 64-bit words, we eliminate twice the number of comparisons
223    and branches without increasing the number of arithmetic operations.
224    It's almost certainly going to be a win with 64-bit word size.  */
225
226 static const uchar * search_line_acc_char (const uchar *, const uchar *)
227   ATTRIBUTE_UNUSED;
228
229 static const uchar *
230 search_line_acc_char (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
231 {
232   const word_type repl_nl = acc_char_replicate ('\n');
233   const word_type repl_cr = acc_char_replicate ('\r');
234   const word_type repl_bs = acc_char_replicate ('\\');
235   const word_type repl_qm = acc_char_replicate ('?');
236
237   unsigned int misalign;
238   const word_type *p;
239   word_type val, t;
240   
241   /* Align the buffer.  Mask out any bytes from before the beginning.  */
242   p = (word_type *)((uintptr_t)s & -sizeof(word_type));
243   val = *p;
244   misalign = (uintptr_t)s & (sizeof(word_type) - 1);
245   if (misalign)
246     val = acc_char_mask_misalign (val, misalign);
247
248   /* Main loop.  */
249   while (1)
250     {
251       t  = acc_char_cmp (val, repl_nl);
252       t |= acc_char_cmp (val, repl_cr);
253       t |= acc_char_cmp (val, repl_bs);
254       t |= acc_char_cmp (val, repl_qm);
255
256       if (__builtin_expect (t != 0, 0))
257         {
258           int i = acc_char_index (t, val);
259           if (i >= 0)
260             return (const uchar *)p + i;
261         }
262
263       val = *++p;
264     }
265 }
266
267 /* Disable on Solaris 2/x86 until the following problems can be properly
268    autoconfed:
269
270    The Solaris 8 assembler cannot assemble SSE2/SSE4.2 insns.
271    The Solaris 9 assembler cannot assemble SSE4.2 insns.
272    Before Solaris 9 Update 6, SSE insns cannot be executed.
273    The Solaris 10+ assembler tags objects with the instruction set
274    extensions used, so SSE4.2 executables cannot run on machines that
275    don't support that extension.  */
276
277 #if (GCC_VERSION >= 4005) && (defined(__i386__) || defined(__x86_64__)) && !(defined(__sun__) && defined(__svr4__))
278
279 /* Replicated character data to be shared between implementations.
280    Recall that outside of a context with vector support we can't
281    define compatible vector types, therefore these are all defined
282    in terms of raw characters.  */
283 static const char repl_chars[4][16] __attribute__((aligned(16))) = {
284   { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n',
285     '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' },
286   { '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r',
287     '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r' },
288   { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\',
289     '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' },
290   { '?', '?', '?', '?', '?', '?', '?', '?',
291     '?', '?', '?', '?', '?', '?', '?', '?' },
292 };
293
294 /* A version of the fast scanner using MMX vectorized byte compare insns.
295
296    This uses the PMOVMSKB instruction which was introduced with "MMX2",
297    which was packaged into SSE1; it is also present in the AMD MMX
298    extension.  Mark the function as using "sse" so that we emit a real
299    "emms" instruction, rather than the 3dNOW "femms" instruction.  */
300
301 static const uchar *
302 #ifndef __SSE__
303 __attribute__((__target__("sse")))
304 #endif
305 search_line_mmx (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
306 {
307   typedef char v8qi __attribute__ ((__vector_size__ (8)));
308   typedef int __m64 __attribute__ ((__vector_size__ (8), __may_alias__));
309
310   const v8qi repl_nl = *(const v8qi *)repl_chars[0];
311   const v8qi repl_cr = *(const v8qi *)repl_chars[1];
312   const v8qi repl_bs = *(const v8qi *)repl_chars[2];
313   const v8qi repl_qm = *(const v8qi *)repl_chars[3];
314
315   unsigned int misalign, found, mask;
316   const v8qi *p;
317   v8qi data, t, c;
318
319   /* Align the source pointer.  While MMX doesn't generate unaligned data
320      faults, this allows us to safely scan to the end of the buffer without
321      reading beyond the end of the last page.  */
322   misalign = (uintptr_t)s & 7;
323   p = (const v8qi *)((uintptr_t)s & -8);
324   data = *p;
325
326   /* Create a mask for the bytes that are valid within the first
327      16-byte block.  The Idea here is that the AND with the mask
328      within the loop is "free", since we need some AND or TEST
329      insn in order to set the flags for the branch anyway.  */
330   mask = -1u << misalign;
331
332   /* Main loop processing 8 bytes at a time.  */
333   goto start;
334   do
335     {
336       data = *++p;
337       mask = -1;
338
339     start:
340       t = __builtin_ia32_pcmpeqb(data, repl_nl);
341       c = __builtin_ia32_pcmpeqb(data, repl_cr);
342       t = (v8qi) __builtin_ia32_por ((__m64)t, (__m64)c);
343       c = __builtin_ia32_pcmpeqb(data, repl_bs);
344       t = (v8qi) __builtin_ia32_por ((__m64)t, (__m64)c);
345       c = __builtin_ia32_pcmpeqb(data, repl_qm);
346       t = (v8qi) __builtin_ia32_por ((__m64)t, (__m64)c);
347       found = __builtin_ia32_pmovmskb (t);
348       found &= mask;
349     }
350   while (!found);
351
352   __builtin_ia32_emms ();
353
354   /* FOUND contains 1 in bits for which we matched a relevant
355      character.  Conversion to the byte index is trivial.  */
356   found = __builtin_ctz(found);
357   return (const uchar *)p + found;
358 }
359
360 /* A version of the fast scanner using SSE2 vectorized byte compare insns.  */
361
362 static const uchar *
363 #ifndef __SSE2__
364 __attribute__((__target__("sse2")))
365 #endif
366 search_line_sse2 (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
367 {
368   typedef char v16qi __attribute__ ((__vector_size__ (16)));
369
370   const v16qi repl_nl = *(const v16qi *)repl_chars[0];
371   const v16qi repl_cr = *(const v16qi *)repl_chars[1];
372   const v16qi repl_bs = *(const v16qi *)repl_chars[2];
373   const v16qi repl_qm = *(const v16qi *)repl_chars[3];
374
375   unsigned int misalign, found, mask;
376   const v16qi *p;
377   v16qi data, t;
378
379   /* Align the source pointer.  */
380   misalign = (uintptr_t)s & 15;
381   p = (const v16qi *)((uintptr_t)s & -16);
382   data = *p;
383
384   /* Create a mask for the bytes that are valid within the first
385      16-byte block.  The Idea here is that the AND with the mask
386      within the loop is "free", since we need some AND or TEST
387      insn in order to set the flags for the branch anyway.  */
388   mask = -1u << misalign;
389
390   /* Main loop processing 16 bytes at a time.  */
391   goto start;
392   do
393     {
394       data = *++p;
395       mask = -1;
396
397     start:
398       t  = __builtin_ia32_pcmpeqb128(data, repl_nl);
399       t |= __builtin_ia32_pcmpeqb128(data, repl_cr);
400       t |= __builtin_ia32_pcmpeqb128(data, repl_bs);
401       t |= __builtin_ia32_pcmpeqb128(data, repl_qm);
402       found = __builtin_ia32_pmovmskb128 (t);
403       found &= mask;
404     }
405   while (!found);
406
407   /* FOUND contains 1 in bits for which we matched a relevant
408      character.  Conversion to the byte index is trivial.  */
409   found = __builtin_ctz(found);
410   return (const uchar *)p + found;
411 }
412
413 #ifdef HAVE_SSE4
414 /* A version of the fast scanner using SSE 4.2 vectorized string insns.  */
415
416 static const uchar *
417 #ifndef __SSE4_2__
418 __attribute__((__target__("sse4.2")))
419 #endif
420 search_line_sse42 (const uchar *s, const uchar *end)
421 {
422   typedef char v16qi __attribute__ ((__vector_size__ (16)));
423   static const v16qi search = { '\n', '\r', '?', '\\' };
424
425   uintptr_t si = (uintptr_t)s;
426   uintptr_t index;
427
428   /* Check for unaligned input.  */
429   if (si & 15)
430     {
431       if (__builtin_expect (end - s < 16, 0)
432           && __builtin_expect ((si & 0xfff) > 0xff0, 0))
433         {
434           /* There are less than 16 bytes left in the buffer, and less
435              than 16 bytes left on the page.  Reading 16 bytes at this
436              point might generate a spurious page fault.  Defer to the
437              SSE2 implementation, which already handles alignment.  */
438           return search_line_sse2 (s, end);
439         }
440
441       /* ??? The builtin doesn't understand that the PCMPESTRI read from
442          memory need not be aligned.  */
443       __asm ("%vpcmpestri $0, (%1), %2"
444              : "=c"(index) : "r"(s), "x"(search), "a"(4), "d"(16));
445       if (__builtin_expect (index < 16, 0))
446         goto found;
447
448       /* Advance the pointer to an aligned address.  We will re-scan a
449          few bytes, but we no longer need care for reading past the
450          end of a page, since we're guaranteed a match.  */
451       s = (const uchar *)((si + 16) & -16);
452     }
453
454   /* Main loop, processing 16 bytes at a time.  By doing the whole loop
455      in inline assembly, we can make proper use of the flags set.  */
456   __asm (      "sub $16, %1\n"
457         "       .balign 16\n"
458         "0:     add $16, %1\n"
459         "       %vpcmpestri $0, (%1), %2\n"
460         "       jnc 0b"
461         : "=&c"(index), "+r"(s)
462         : "x"(search), "a"(4), "d"(16));
463
464  found:
465   return s + index;
466 }
467
468 #else
469 /* Work around out-dated assemblers without sse4 support.  */
470 #define search_line_sse42 search_line_sse2
471 #endif
472
473 /* Check the CPU capabilities.  */
474
475 #include "../gcc/config/i386/cpuid.h"
476
477 typedef const uchar * (*search_line_fast_type) (const uchar *, const uchar *);
478 static search_line_fast_type search_line_fast;
479
480 static void __attribute__((constructor))
481 init_vectorized_lexer (void)
482 {
483   unsigned dummy, ecx = 0, edx = 0;
484   search_line_fast_type impl = search_line_acc_char;
485   int minimum = 0;
486
487 #if defined(__SSE4_2__)
488   minimum = 3;
489 #elif defined(__SSE2__)
490   minimum = 2;
491 #elif defined(__SSE__)
492   minimum = 1;
493 #endif
494
495   if (minimum == 3)
496     impl = search_line_sse42;
497   else if (__get_cpuid (1, &dummy, &dummy, &ecx, &edx) || minimum == 2)
498     {
499       if (minimum == 3 || (ecx & bit_SSE4_2))
500         impl = search_line_sse42;
501       else if (minimum == 2 || (edx & bit_SSE2))
502         impl = search_line_sse2;
503       else if (minimum == 1 || (edx & bit_SSE))
504         impl = search_line_mmx;
505     }
506   else if (__get_cpuid (0x80000001, &dummy, &dummy, &dummy, &edx))
507     {
508       if (minimum == 1
509           || (edx & (bit_MMXEXT | bit_CMOV)) == (bit_MMXEXT | bit_CMOV))
510         impl = search_line_mmx;
511     }
512
513   search_line_fast = impl;
514 }
515
516 #elif (GCC_VERSION >= 4005) && defined(__ALTIVEC__)
517
518 /* A vection of the fast scanner using AltiVec vectorized byte compares.  */
519 /* ??? Unfortunately, attribute(target("altivec")) is not yet supported,
520    so we can't compile this function without -maltivec on the command line
521    (or implied by some other switch).  */
522
523 static const uchar *
524 search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
525 {
526   typedef __attribute__((altivec(vector))) unsigned char vc;
527
528   const vc repl_nl = {
529     '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', 
530     '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'
531   };
532   const vc repl_cr = {
533     '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', 
534     '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r'
535   };
536   const vc repl_bs = {
537     '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', 
538     '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\'
539   };
540   const vc repl_qm = {
541     '?', '?', '?', '?', '?', '?', '?', '?', 
542     '?', '?', '?', '?', '?', '?', '?', '?', 
543   };
544   const vc ones = {
545     -1, -1, -1, -1, -1, -1, -1, -1,
546     -1, -1, -1, -1, -1, -1, -1, -1,
547   };
548   const vc zero = { 0 };
549
550   vc data, mask, t;
551
552   /* Altivec loads automatically mask addresses with -16.  This lets us
553      issue the first load as early as possible.  */
554   data = __builtin_vec_ld(0, (const vc *)s);
555
556   /* Discard bytes before the beginning of the buffer.  Do this by
557      beginning with all ones and shifting in zeros according to the
558      mis-alignment.  The LVSR instruction pulls the exact shift we
559      want from the address.  */
560   mask = __builtin_vec_lvsr(0, s);
561   mask = __builtin_vec_perm(zero, ones, mask);
562   data &= mask;
563
564   /* While altivec loads mask addresses, we still need to align S so
565      that the offset we compute at the end is correct.  */
566   s = (const uchar *)((uintptr_t)s & -16);
567
568   /* Main loop processing 16 bytes at a time.  */
569   goto start;
570   do
571     {
572       vc m_nl, m_cr, m_bs, m_qm;
573
574       s += 16;
575       data = __builtin_vec_ld(0, (const vc *)s);
576
577     start:
578       m_nl = (vc) __builtin_vec_cmpeq(data, repl_nl);
579       m_cr = (vc) __builtin_vec_cmpeq(data, repl_cr);
580       m_bs = (vc) __builtin_vec_cmpeq(data, repl_bs);
581       m_qm = (vc) __builtin_vec_cmpeq(data, repl_qm);
582       t = (m_nl | m_cr) | (m_bs | m_qm);
583
584       /* T now contains 0xff in bytes for which we matched one of the relevant
585          characters.  We want to exit the loop if any byte in T is non-zero.
586          Below is the expansion of vec_any_ne(t, zero).  */
587     }
588   while (!__builtin_vec_vcmpeq_p(/*__CR6_LT_REV*/3, t, zero));
589
590   {
591 #define N  (sizeof(vc) / sizeof(long))
592
593     typedef char check_count[(N == 2 || N == 4) * 2 - 1];
594     union {
595       vc v;
596       unsigned long l[N];
597     } u;
598     unsigned long l, i = 0;
599
600     u.v = t;
601
602     /* Find the first word of T that is non-zero.  */
603     switch (N)
604       {
605       case 4:
606         l = u.l[i++];
607         if (l != 0)
608           break;
609         s += sizeof(unsigned long);
610         l = u.l[i++];
611         if (l != 0)
612           break;
613         s += sizeof(unsigned long);
614       case 2:
615         l = u.l[i++];
616         if (l != 0)
617           break;
618         s += sizeof(unsigned long);
619         l = u.l[i];
620       }
621
622     /* L now contains 0xff in bytes for which we matched one of the
623        relevant characters.  We can find the byte index by finding
624        its bit index and dividing by 8.  */
625     l = __builtin_clzl(l) >> 3;
626     return s + l;
627
628 #undef N
629   }
630 }
631
632 #else
633
634 /* We only have one accellerated alternative.  Use a direct call so that
635    we encourage inlining.  */
636
637 #define search_line_fast  search_line_acc_char
638
639 #endif
640
641 /* Returns with a logical line that contains no escaped newlines or
642    trigraphs.  This is a time-critical inner loop.  */
643 void
644 _cpp_clean_line (cpp_reader *pfile)
645 {
646   cpp_buffer *buffer;
647   const uchar *s;
648   uchar c, *d, *p;
649
650   buffer = pfile->buffer;
651   buffer->cur_note = buffer->notes_used = 0;
652   buffer->cur = buffer->line_base = buffer->next_line;
653   buffer->need_line = false;
654   s = buffer->next_line;
655
656   if (!buffer->from_stage3)
657     {
658       const uchar *pbackslash = NULL;
659
660       /* Fast path.  This is the common case of an un-escaped line with
661          no trigraphs.  The primary win here is by not writing any
662          data back to memory until we have to.  */
663       while (1)
664         {
665           /* Perform an optimized search for \n, \r, \\, ?.  */
666           s = search_line_fast (s, buffer->rlimit);
667
668           c = *s;
669           if (c == '\\')
670             {
671               /* Record the location of the backslash and continue.  */
672               pbackslash = s++;
673             }
674           else if (__builtin_expect (c == '?', 0))
675             {
676               if (__builtin_expect (s[1] == '?', false)
677                    && _cpp_trigraph_map[s[2]])
678                 {
679                   /* Have a trigraph.  We may or may not have to convert
680                      it.  Add a line note regardless, for -Wtrigraphs.  */
681                   add_line_note (buffer, s, s[2]);
682                   if (CPP_OPTION (pfile, trigraphs))
683                     {
684                       /* We do, and that means we have to switch to the
685                          slow path.  */
686                       d = (uchar *) s;
687                       *d = _cpp_trigraph_map[s[2]];
688                       s += 2;
689                       goto slow_path;
690                     }
691                 }
692               /* Not a trigraph.  Continue on fast-path.  */
693               s++;
694             }
695           else
696             break;
697         }
698
699       /* This must be \r or \n.  We're either done, or we'll be forced
700          to write back to the buffer and continue on the slow path.  */
701       d = (uchar *) s;
702
703       if (__builtin_expect (s == buffer->rlimit, false))
704         goto done;
705
706       /* DOS line ending? */
707       if (__builtin_expect (c == '\r', false) && s[1] == '\n')
708         {
709           s++;
710           if (s == buffer->rlimit)
711             goto done;
712         }
713
714       if (__builtin_expect (pbackslash == NULL, true))
715         goto done;
716
717       /* Check for escaped newline.  */
718       p = d;
719       while (is_nvspace (p[-1]))
720         p--;
721       if (p - 1 != pbackslash)
722         goto done;
723
724       /* Have an escaped newline; process it and proceed to
725          the slow path.  */
726       add_line_note (buffer, p - 1, p != d ? ' ' : '\\');
727       d = p - 2;
728       buffer->next_line = p - 1;
729
730     slow_path:
731       while (1)
732         {
733           c = *++s;
734           *++d = c;
735
736           if (c == '\n' || c == '\r')
737             {
738               /* Handle DOS line endings.  */
739               if (c == '\r' && s != buffer->rlimit && s[1] == '\n')
740                 s++;
741               if (s == buffer->rlimit)
742                 break;
743
744               /* Escaped?  */
745               p = d;
746               while (p != buffer->next_line && is_nvspace (p[-1]))
747                 p--;
748               if (p == buffer->next_line || p[-1] != '\\')
749                 break;
750
751               add_line_note (buffer, p - 1, p != d ? ' ': '\\');
752               d = p - 2;
753               buffer->next_line = p - 1;
754             }
755           else if (c == '?' && s[1] == '?' && _cpp_trigraph_map[s[2]])
756             {
757               /* Add a note regardless, for the benefit of -Wtrigraphs.  */
758               add_line_note (buffer, d, s[2]);
759               if (CPP_OPTION (pfile, trigraphs))
760                 {
761                   *d = _cpp_trigraph_map[s[2]];
762                   s += 2;
763                 }
764             }
765         }
766     }
767   else
768     {
769       while (*s != '\n' && *s != '\r')
770         s++;
771       d = (uchar *) s;
772
773       /* Handle DOS line endings.  */
774       if (*s == '\r' && s != buffer->rlimit && s[1] == '\n')
775         s++;
776     }
777
778  done:
779   *d = '\n';
780   /* A sentinel note that should never be processed.  */
781   add_line_note (buffer, d + 1, '\n');
782   buffer->next_line = s + 1;
783 }
784
785 /* Return true if the trigraph indicated by NOTE should be warned
786    about in a comment.  */
787 static bool
788 warn_in_comment (cpp_reader *pfile, _cpp_line_note *note)
789 {
790   const uchar *p;
791
792   /* Within comments we don't warn about trigraphs, unless the
793      trigraph forms an escaped newline, as that may change
794      behavior.  */
795   if (note->type != '/')
796     return false;
797
798   /* If -trigraphs, then this was an escaped newline iff the next note
799      is coincident.  */
800   if (CPP_OPTION (pfile, trigraphs))
801     return note[1].pos == note->pos;
802
803   /* Otherwise, see if this forms an escaped newline.  */
804   p = note->pos + 3;
805   while (is_nvspace (*p))
806     p++;
807
808   /* There might have been escaped newlines between the trigraph and the
809      newline we found.  Hence the position test.  */
810   return (*p == '\n' && p < note[1].pos);
811 }
812
813 /* Process the notes created by add_line_note as far as the current
814    location.  */
815 void
816 _cpp_process_line_notes (cpp_reader *pfile, int in_comment)
817 {
818   cpp_buffer *buffer = pfile->buffer;
819
820   for (;;)
821     {
822       _cpp_line_note *note = &buffer->notes[buffer->cur_note];
823       unsigned int col;
824
825       if (note->pos > buffer->cur)
826         break;
827
828       buffer->cur_note++;
829       col = CPP_BUF_COLUMN (buffer, note->pos + 1);
830
831       if (note->type == '\\' || note->type == ' ')
832         {
833           if (note->type == ' ' && !in_comment)
834             cpp_error_with_line (pfile, CPP_DL_WARNING, pfile->line_table->highest_line, col,
835                                  "backslash and newline separated by space");
836
837           if (buffer->next_line > buffer->rlimit)
838             {
839               cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->line_table->highest_line, col,
840                                    "backslash-newline at end of file");
841               /* Prevent "no newline at end of file" warning.  */
842               buffer->next_line = buffer->rlimit;
843             }
844
845           buffer->line_base = note->pos;
846           CPP_INCREMENT_LINE (pfile, 0);
847         }
848       else if (_cpp_trigraph_map[note->type])
849         {
850           if (CPP_OPTION (pfile, warn_trigraphs)
851               && (!in_comment || warn_in_comment (pfile, note)))
852             {
853               if (CPP_OPTION (pfile, trigraphs))
854                 cpp_warning_with_line (pfile, CPP_W_TRIGRAPHS,
855                                        pfile->line_table->highest_line, col,
856                                        "trigraph ??%c converted to %c",
857                                        note->type,
858                                        (int) _cpp_trigraph_map[note->type]);
859               else
860                 {
861                   cpp_warning_with_line 
862                     (pfile, CPP_W_TRIGRAPHS,
863                      pfile->line_table->highest_line, col,
864                      "trigraph ??%c ignored, use -trigraphs to enable",
865                      note->type);
866                 }
867             }
868         }
869       else if (note->type == 0)
870         /* Already processed in lex_raw_string.  */;
871       else
872         abort ();
873     }
874 }
875
876 /* Skip a C-style block comment.  We find the end of the comment by
877    seeing if an asterisk is before every '/' we encounter.  Returns
878    nonzero if comment terminated by EOF, zero otherwise.
879
880    Buffer->cur points to the initial asterisk of the comment.  */
881 bool
882 _cpp_skip_block_comment (cpp_reader *pfile)
883 {
884   cpp_buffer *buffer = pfile->buffer;
885   const uchar *cur = buffer->cur;
886   uchar c;
887
888   cur++;
889   if (*cur == '/')
890     cur++;
891
892   for (;;)
893     {
894       /* People like decorating comments with '*', so check for '/'
895          instead for efficiency.  */
896       c = *cur++;
897
898       if (c == '/')
899         {
900           if (cur[-2] == '*')
901             break;
902
903           /* Warn about potential nested comments, but not if the '/'
904              comes immediately before the true comment delimiter.
905              Don't bother to get it right across escaped newlines.  */
906           if (CPP_OPTION (pfile, warn_comments)
907               && cur[0] == '*' && cur[1] != '/')
908             {
909               buffer->cur = cur;
910               cpp_warning_with_line (pfile, CPP_W_COMMENTS,
911                                      pfile->line_table->highest_line,
912                                      CPP_BUF_COL (buffer),
913                                      "\"/*\" within comment");
914             }
915         }
916       else if (c == '\n')
917         {
918           unsigned int cols;
919           buffer->cur = cur - 1;
920           _cpp_process_line_notes (pfile, true);
921           if (buffer->next_line >= buffer->rlimit)
922             return true;
923           _cpp_clean_line (pfile);
924
925           cols = buffer->next_line - buffer->line_base;
926           CPP_INCREMENT_LINE (pfile, cols);
927
928           cur = buffer->cur;
929         }
930     }
931
932   buffer->cur = cur;
933   _cpp_process_line_notes (pfile, true);
934   return false;
935 }
936
937 /* Skip a C++ line comment, leaving buffer->cur pointing to the
938    terminating newline.  Handles escaped newlines.  Returns nonzero
939    if a multiline comment.  */
940 static int
941 skip_line_comment (cpp_reader *pfile)
942 {
943   cpp_buffer *buffer = pfile->buffer;
944   source_location orig_line = pfile->line_table->highest_line;
945
946   while (*buffer->cur != '\n')
947     buffer->cur++;
948
949   _cpp_process_line_notes (pfile, true);
950   return orig_line != pfile->line_table->highest_line;
951 }
952
953 /* Skips whitespace, saving the next non-whitespace character.  */
954 static void
955 skip_whitespace (cpp_reader *pfile, cppchar_t c)
956 {
957   cpp_buffer *buffer = pfile->buffer;
958   bool saw_NUL = false;
959
960   do
961     {
962       /* Horizontal space always OK.  */
963       if (c == ' ' || c == '\t')
964         ;
965       /* Just \f \v or \0 left.  */
966       else if (c == '\0')
967         saw_NUL = true;
968       else if (pfile->state.in_directive && CPP_PEDANTIC (pfile))
969         cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->line_table->highest_line,
970                              CPP_BUF_COL (buffer),
971                              "%s in preprocessing directive",
972                              c == '\f' ? "form feed" : "vertical tab");
973
974       c = *buffer->cur++;
975     }
976   /* We only want non-vertical space, i.e. ' ' \t \f \v \0.  */
977   while (is_nvspace (c));
978
979   if (saw_NUL)
980     cpp_error (pfile, CPP_DL_WARNING, "null character(s) ignored");
981
982   buffer->cur--;
983 }
984
985 /* See if the characters of a number token are valid in a name (no
986    '.', '+' or '-').  */
987 static int
988 name_p (cpp_reader *pfile, const cpp_string *string)
989 {
990   unsigned int i;
991
992   for (i = 0; i < string->len; i++)
993     if (!is_idchar (string->text[i]))
994       return 0;
995
996   return 1;
997 }
998
999 /* After parsing an identifier or other sequence, produce a warning about
1000    sequences not in NFC/NFKC.  */
1001 static void
1002 warn_about_normalization (cpp_reader *pfile, 
1003                           const cpp_token *token,
1004                           const struct normalize_state *s)
1005 {
1006   if (CPP_OPTION (pfile, warn_normalize) < NORMALIZE_STATE_RESULT (s)
1007       && !pfile->state.skipping)
1008     {
1009       /* Make sure that the token is printed using UCNs, even
1010          if we'd otherwise happily print UTF-8.  */
1011       unsigned char *buf = XNEWVEC (unsigned char, cpp_token_len (token));
1012       size_t sz;
1013
1014       sz = cpp_spell_token (pfile, token, buf, false) - buf;
1015       if (NORMALIZE_STATE_RESULT (s) == normalized_C)
1016         cpp_warning_with_line (pfile, CPP_W_NORMALIZE, token->src_loc, 0,
1017                                "`%.*s' is not in NFKC", (int) sz, buf);
1018       else
1019         cpp_warning_with_line (pfile, CPP_W_NORMALIZE, token->src_loc, 0,
1020                                "`%.*s' is not in NFC", (int) sz, buf);
1021     }
1022 }
1023
1024 /* Returns TRUE if the sequence starting at buffer->cur is invalid in
1025    an identifier.  FIRST is TRUE if this starts an identifier.  */
1026 static bool
1027 forms_identifier_p (cpp_reader *pfile, int first,
1028                     struct normalize_state *state)
1029 {
1030   cpp_buffer *buffer = pfile->buffer;
1031
1032   if (*buffer->cur == '$')
1033     {
1034       if (!CPP_OPTION (pfile, dollars_in_ident))
1035         return false;
1036
1037       buffer->cur++;
1038       if (CPP_OPTION (pfile, warn_dollars) && !pfile->state.skipping)
1039         {
1040           CPP_OPTION (pfile, warn_dollars) = 0;
1041           cpp_error (pfile, CPP_DL_PEDWARN, "'$' in identifier or number");
1042         }
1043
1044       return true;
1045     }
1046
1047   /* Is this a syntactically valid UCN?  */
1048   if (CPP_OPTION (pfile, extended_identifiers)
1049       && *buffer->cur == '\\'
1050       && (buffer->cur[1] == 'u' || buffer->cur[1] == 'U'))
1051     {
1052       buffer->cur += 2;
1053       if (_cpp_valid_ucn (pfile, &buffer->cur, buffer->rlimit, 1 + !first,
1054                           state))
1055         return true;
1056       buffer->cur -= 2;
1057     }
1058
1059   return false;
1060 }
1061
1062 /* Helper function to get the cpp_hashnode of the identifier BASE.  */
1063 static cpp_hashnode *
1064 lex_identifier_intern (cpp_reader *pfile, const uchar *base)
1065 {
1066   cpp_hashnode *result;
1067   const uchar *cur;
1068   unsigned int len;
1069   unsigned int hash = HT_HASHSTEP (0, *base);
1070
1071   cur = base + 1;
1072   while (ISIDNUM (*cur))
1073     {
1074       hash = HT_HASHSTEP (hash, *cur);
1075       cur++;
1076     }
1077   len = cur - base;
1078   hash = HT_HASHFINISH (hash, len);
1079   result = CPP_HASHNODE (ht_lookup_with_hash (pfile->hash_table,
1080                                               base, len, hash, HT_ALLOC));
1081
1082   /* Rarely, identifiers require diagnostics when lexed.  */
1083   if (__builtin_expect ((result->flags & NODE_DIAGNOSTIC)
1084                         && !pfile->state.skipping, 0))
1085     {
1086       /* It is allowed to poison the same identifier twice.  */
1087       if ((result->flags & NODE_POISONED) && !pfile->state.poisoned_ok)
1088         cpp_error (pfile, CPP_DL_ERROR, "attempt to use poisoned \"%s\"",
1089                    NODE_NAME (result));
1090
1091       /* Constraint 6.10.3.5: __VA_ARGS__ should only appear in the
1092          replacement list of a variadic macro.  */
1093       if (result == pfile->spec_nodes.n__VA_ARGS__
1094           && !pfile->state.va_args_ok)
1095         cpp_error (pfile, CPP_DL_PEDWARN,
1096                    "__VA_ARGS__ can only appear in the expansion"
1097                    " of a C99 variadic macro");
1098
1099       /* For -Wc++-compat, warn about use of C++ named operators.  */
1100       if (result->flags & NODE_WARN_OPERATOR)
1101         cpp_warning (pfile, CPP_W_CXX_OPERATOR_NAMES,
1102                      "identifier \"%s\" is a special operator name in C++",
1103                      NODE_NAME (result));
1104     }
1105
1106   return result;
1107 }
1108
1109 /* Get the cpp_hashnode of an identifier specified by NAME in
1110    the current cpp_reader object.  If none is found, NULL is returned.  */
1111 cpp_hashnode *
1112 _cpp_lex_identifier (cpp_reader *pfile, const char *name)
1113 {
1114   cpp_hashnode *result;
1115   result = lex_identifier_intern (pfile, (uchar *) name);
1116   return result;
1117 }
1118
1119 /* Lex an identifier starting at BUFFER->CUR - 1.  */
1120 static cpp_hashnode *
1121 lex_identifier (cpp_reader *pfile, const uchar *base, bool starts_ucn,
1122                 struct normalize_state *nst)
1123 {
1124   cpp_hashnode *result;
1125   const uchar *cur;
1126   unsigned int len;
1127   unsigned int hash = HT_HASHSTEP (0, *base);
1128
1129   cur = pfile->buffer->cur;
1130   if (! starts_ucn)
1131     while (ISIDNUM (*cur))
1132       {
1133         hash = HT_HASHSTEP (hash, *cur);
1134         cur++;
1135       }
1136   pfile->buffer->cur = cur;
1137   if (starts_ucn || forms_identifier_p (pfile, false, nst))
1138     {
1139       /* Slower version for identifiers containing UCNs (or $).  */
1140       do {
1141         while (ISIDNUM (*pfile->buffer->cur))
1142           {
1143             pfile->buffer->cur++;
1144             NORMALIZE_STATE_UPDATE_IDNUM (nst);
1145           }
1146       } while (forms_identifier_p (pfile, false, nst));
1147       result = _cpp_interpret_identifier (pfile, base,
1148                                           pfile->buffer->cur - base);
1149     }
1150   else
1151     {
1152       len = cur - base;
1153       hash = HT_HASHFINISH (hash, len);
1154
1155       result = CPP_HASHNODE (ht_lookup_with_hash (pfile->hash_table,
1156                                                   base, len, hash, HT_ALLOC));
1157     }
1158
1159   /* Rarely, identifiers require diagnostics when lexed.  */
1160   if (__builtin_expect ((result->flags & NODE_DIAGNOSTIC)
1161                         && !pfile->state.skipping, 0))
1162     {
1163       /* It is allowed to poison the same identifier twice.  */
1164       if ((result->flags & NODE_POISONED) && !pfile->state.poisoned_ok)
1165         cpp_error (pfile, CPP_DL_ERROR, "attempt to use poisoned \"%s\"",
1166                    NODE_NAME (result));
1167
1168       /* Constraint 6.10.3.5: __VA_ARGS__ should only appear in the
1169          replacement list of a variadic macro.  */
1170       if (result == pfile->spec_nodes.n__VA_ARGS__
1171           && !pfile->state.va_args_ok)
1172         cpp_error (pfile, CPP_DL_PEDWARN,
1173                    "__VA_ARGS__ can only appear in the expansion"
1174                    " of a C99 variadic macro");
1175
1176       /* For -Wc++-compat, warn about use of C++ named operators.  */
1177       if (result->flags & NODE_WARN_OPERATOR)
1178         cpp_warning (pfile, CPP_W_CXX_OPERATOR_NAMES,
1179                      "identifier \"%s\" is a special operator name in C++",
1180                      NODE_NAME (result));
1181     }
1182
1183   return result;
1184 }
1185
1186 /* Lex a number to NUMBER starting at BUFFER->CUR - 1.  */
1187 static void
1188 lex_number (cpp_reader *pfile, cpp_string *number,
1189             struct normalize_state *nst)
1190 {
1191   const uchar *cur;
1192   const uchar *base;
1193   uchar *dest;
1194
1195   base = pfile->buffer->cur - 1;
1196   do
1197     {
1198       cur = pfile->buffer->cur;
1199
1200       /* N.B. ISIDNUM does not include $.  */
1201       while (ISIDNUM (*cur) || *cur == '.' || VALID_SIGN (*cur, cur[-1]))
1202         {
1203           cur++;
1204           NORMALIZE_STATE_UPDATE_IDNUM (nst);
1205         }
1206
1207       pfile->buffer->cur = cur;
1208     }
1209   while (forms_identifier_p (pfile, false, nst));
1210
1211   number->len = cur - base;
1212   dest = _cpp_unaligned_alloc (pfile, number->len + 1);
1213   memcpy (dest, base, number->len);
1214   dest[number->len] = '\0';
1215   number->text = dest;
1216 }
1217
1218 /* Create a token of type TYPE with a literal spelling.  */
1219 static void
1220 create_literal (cpp_reader *pfile, cpp_token *token, const uchar *base,
1221                 unsigned int len, enum cpp_ttype type)
1222 {
1223   uchar *dest = _cpp_unaligned_alloc (pfile, len + 1);
1224
1225   memcpy (dest, base, len);
1226   dest[len] = '\0';
1227   token->type = type;
1228   token->val.str.len = len;
1229   token->val.str.text = dest;
1230 }
1231
1232 /* Subroutine of lex_raw_string: Append LEN chars from BASE to the buffer
1233    sequence from *FIRST_BUFF_P to LAST_BUFF_P.  */
1234
1235 static void
1236 bufring_append (cpp_reader *pfile, const uchar *base, size_t len,
1237                 _cpp_buff **first_buff_p, _cpp_buff **last_buff_p)
1238 {
1239   _cpp_buff *first_buff = *first_buff_p;
1240   _cpp_buff *last_buff = *last_buff_p;
1241
1242   if (first_buff == NULL)
1243     first_buff = last_buff = _cpp_get_buff (pfile, len);
1244   else if (len > BUFF_ROOM (last_buff))
1245     {
1246       size_t room = BUFF_ROOM (last_buff);
1247       memcpy (BUFF_FRONT (last_buff), base, room);
1248       BUFF_FRONT (last_buff) += room;
1249       base += room;
1250       len -= room;
1251       last_buff = _cpp_append_extend_buff (pfile, last_buff, len);
1252     }
1253
1254   memcpy (BUFF_FRONT (last_buff), base, len);
1255   BUFF_FRONT (last_buff) += len;
1256
1257   *first_buff_p = first_buff;
1258   *last_buff_p = last_buff;
1259 }
1260
1261 /* Lexes a raw string.  The stored string contains the spelling, including
1262    double quotes, delimiter string, '(' and ')', any leading
1263    'L', 'u', 'U' or 'u8' and 'R' modifier.  It returns the type of the
1264    literal, or CPP_OTHER if it was not properly terminated.
1265
1266    The spelling is NUL-terminated, but it is not guaranteed that this
1267    is the first NUL since embedded NULs are preserved.  */
1268
1269 static void
1270 lex_raw_string (cpp_reader *pfile, cpp_token *token, const uchar *base,
1271                 const uchar *cur)
1272 {
1273   source_location saw_NUL = 0;
1274   const uchar *raw_prefix;
1275   unsigned int raw_prefix_len = 0;
1276   enum cpp_ttype type;
1277   size_t total_len = 0;
1278   _cpp_buff *first_buff = NULL, *last_buff = NULL;
1279   _cpp_line_note *note = &pfile->buffer->notes[pfile->buffer->cur_note];
1280
1281   type = (*base == 'L' ? CPP_WSTRING :
1282           *base == 'U' ? CPP_STRING32 :
1283           *base == 'u' ? (base[1] == '8' ? CPP_UTF8STRING : CPP_STRING16)
1284           : CPP_STRING);
1285
1286   raw_prefix = cur + 1;
1287   while (raw_prefix_len < 16)
1288     {
1289       switch (raw_prefix[raw_prefix_len])
1290         {
1291         case ' ': case '(': case ')': case '\\': case '\t':
1292         case '\v': case '\f': case '\n': default:
1293           break;
1294         /* Basic source charset except the above chars.  */
1295         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1296         case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1297         case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1298         case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1299         case 'y': case 'z':
1300         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1301         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1302         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1303         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1304         case 'Y': case 'Z':
1305         case '0': case '1': case '2': case '3': case '4': case '5':
1306         case '6': case '7': case '8': case '9':
1307         case '_': case '{': case '}': case '#': case '[': case ']':
1308         case '<': case '>': case '%': case ':': case ';': case '.':
1309         case '?': case '*': case '+': case '-': case '/': case '^':
1310         case '&': case '|': case '~': case '!': case '=': case ',':
1311         case '"': case '\'':
1312           raw_prefix_len++;
1313           continue;
1314         }
1315       break;
1316     }
1317
1318   if (raw_prefix[raw_prefix_len] != '(')
1319     {
1320       int col = CPP_BUF_COLUMN (pfile->buffer, raw_prefix + raw_prefix_len)
1321                 + 1;
1322       if (raw_prefix_len == 16)
1323         cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, col,
1324                              "raw string delimiter longer than 16 characters");
1325       else
1326         cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, col,
1327                              "invalid character '%c' in raw string delimiter",
1328                              (int) raw_prefix[raw_prefix_len]);
1329       pfile->buffer->cur = raw_prefix - 1;
1330       create_literal (pfile, token, base, raw_prefix - 1 - base, CPP_OTHER);
1331       return;
1332     }
1333
1334   cur = raw_prefix + raw_prefix_len + 1;
1335   for (;;)
1336     {
1337 #define BUF_APPEND(STR,LEN)                                     \
1338       do {                                                      \
1339         bufring_append (pfile, (const uchar *)(STR), (LEN),     \
1340                         &first_buff, &last_buff);               \
1341         total_len += (LEN);                                     \
1342       } while (0);
1343
1344       cppchar_t c;
1345
1346       /* If we previously performed any trigraph or line splicing
1347          transformations, undo them within the body of the raw string.  */
1348       while (note->pos < cur)
1349         ++note;
1350       for (; note->pos == cur; ++note)
1351         {
1352           switch (note->type)
1353             {
1354             case '\\':
1355             case ' ':
1356               /* Restore backslash followed by newline.  */
1357               BUF_APPEND (base, cur - base);
1358               base = cur;
1359               BUF_APPEND ("\\", 1);
1360             after_backslash:
1361               if (note->type == ' ')
1362                 {
1363                   /* GNU backslash whitespace newline extension.  FIXME
1364                      could be any sequence of non-vertical space.  When we
1365                      can properly restore any such sequence, we should mark
1366                      this note as handled so _cpp_process_line_notes
1367                      doesn't warn.  */
1368                   BUF_APPEND (" ", 1);
1369                 }
1370
1371               BUF_APPEND ("\n", 1);
1372               break;
1373
1374             case 0:
1375               /* Already handled.  */
1376               break;
1377
1378             default:
1379               if (_cpp_trigraph_map[note->type])
1380                 {
1381                   /* Don't warn about this trigraph in
1382                      _cpp_process_line_notes, since trigraphs show up as
1383                      trigraphs in raw strings.  */
1384                   uchar type = note->type;
1385                   note->type = 0;
1386
1387                   if (!CPP_OPTION (pfile, trigraphs))
1388                     /* If we didn't convert the trigraph in the first
1389                        place, don't do anything now either.  */
1390                     break;
1391
1392                   BUF_APPEND (base, cur - base);
1393                   base = cur;
1394                   BUF_APPEND ("??", 2);
1395
1396                   /* ??/ followed by newline gets two line notes, one for
1397                      the trigraph and one for the backslash/newline.  */
1398                   if (type == '/' && note[1].pos == cur)
1399                     {
1400                       if (note[1].type != '\\'
1401                           && note[1].type != ' ')
1402                         abort ();
1403                       BUF_APPEND ("/", 1);
1404                       ++note;
1405                       goto after_backslash;
1406                     }
1407                   /* The ) from ??) could be part of the suffix.  */
1408                   else if (type == ')'
1409                            && strncmp ((const char *) cur+1,
1410                                        (const char *) raw_prefix,
1411                                        raw_prefix_len) == 0
1412                            && cur[raw_prefix_len+1] == '"')
1413                     {
1414                       BUF_APPEND (")", 1);
1415                       base++;
1416                       cur += raw_prefix_len + 2;
1417                       goto break_outer_loop;
1418                     }
1419                   else
1420                     {
1421                       /* Skip the replacement character.  */
1422                       base = ++cur;
1423                       BUF_APPEND (&type, 1);
1424                     }
1425                 }
1426               else
1427                 abort ();
1428               break;
1429             }
1430         }
1431       c = *cur++;
1432
1433       if (c == ')'
1434           && strncmp ((const char *) cur, (const char *) raw_prefix,
1435                       raw_prefix_len) == 0
1436           && cur[raw_prefix_len] == '"')
1437         {
1438           cur += raw_prefix_len + 1;
1439           break;
1440         }
1441       else if (c == '\n')
1442         {
1443           if (pfile->state.in_directive
1444               || pfile->state.parsing_args
1445               || pfile->state.in_deferred_pragma)
1446             {
1447               cur--;
1448               type = CPP_OTHER;
1449               cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, 0,
1450                                    "unterminated raw string");
1451               break;
1452             }
1453
1454           BUF_APPEND (base, cur - base);
1455
1456           if (pfile->buffer->cur < pfile->buffer->rlimit)
1457             CPP_INCREMENT_LINE (pfile, 0);
1458           pfile->buffer->need_line = true;
1459
1460           pfile->buffer->cur = cur-1;
1461           _cpp_process_line_notes (pfile, false);
1462           if (!_cpp_get_fresh_line (pfile))
1463             {
1464               source_location src_loc = token->src_loc;
1465               token->type = CPP_EOF;
1466               /* Tell the compiler the line number of the EOF token.  */
1467               token->src_loc = pfile->line_table->highest_line;
1468               token->flags = BOL;
1469               if (first_buff != NULL)
1470                 _cpp_release_buff (pfile, first_buff);
1471               cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1472                                    "unterminated raw string");
1473               return;
1474             }
1475
1476           cur = base = pfile->buffer->cur;
1477           note = &pfile->buffer->notes[pfile->buffer->cur_note];
1478         }
1479       else if (c == '\0' && !saw_NUL)
1480         LINEMAP_POSITION_FOR_COLUMN (saw_NUL, pfile->line_table,
1481                                      CPP_BUF_COLUMN (pfile->buffer, cur));
1482     }
1483  break_outer_loop:
1484
1485   if (saw_NUL && !pfile->state.skipping)
1486     cpp_error_with_line (pfile, CPP_DL_WARNING, saw_NUL, 0,
1487                "null character(s) preserved in literal");
1488
1489   pfile->buffer->cur = cur;
1490   if (first_buff == NULL)
1491     create_literal (pfile, token, base, cur - base, type);
1492   else
1493     {
1494       uchar *dest = _cpp_unaligned_alloc (pfile, total_len + (cur - base) + 1);
1495
1496       token->type = type;
1497       token->val.str.len = total_len + (cur - base);
1498       token->val.str.text = dest;
1499       last_buff = first_buff;
1500       while (last_buff != NULL)
1501         {
1502           memcpy (dest, last_buff->base,
1503                   BUFF_FRONT (last_buff) - last_buff->base);
1504           dest += BUFF_FRONT (last_buff) - last_buff->base;
1505           last_buff = last_buff->next;
1506         }
1507       _cpp_release_buff (pfile, first_buff);
1508       memcpy (dest, base, cur - base);
1509       dest[cur - base] = '\0';
1510     }
1511 }
1512
1513 /* Lexes a string, character constant, or angle-bracketed header file
1514    name.  The stored string contains the spelling, including opening
1515    quote and any leading 'L', 'u', 'U' or 'u8' and optional
1516    'R' modifier.  It returns the type of the literal, or CPP_OTHER
1517    if it was not properly terminated, or CPP_LESS for an unterminated
1518    header name which must be relexed as normal tokens.
1519
1520    The spelling is NUL-terminated, but it is not guaranteed that this
1521    is the first NUL since embedded NULs are preserved.  */
1522 static void
1523 lex_string (cpp_reader *pfile, cpp_token *token, const uchar *base)
1524 {
1525   bool saw_NUL = false;
1526   const uchar *cur;
1527   cppchar_t terminator;
1528   enum cpp_ttype type;
1529
1530   cur = base;
1531   terminator = *cur++;
1532   if (terminator == 'L' || terminator == 'U')
1533     terminator = *cur++;
1534   else if (terminator == 'u')
1535     {
1536       terminator = *cur++;
1537       if (terminator == '8')
1538         terminator = *cur++;
1539     }
1540   if (terminator == 'R')
1541     {
1542       lex_raw_string (pfile, token, base, cur);
1543       return;
1544     }
1545   if (terminator == '"')
1546     type = (*base == 'L' ? CPP_WSTRING :
1547             *base == 'U' ? CPP_STRING32 :
1548             *base == 'u' ? (base[1] == '8' ? CPP_UTF8STRING : CPP_STRING16)
1549                          : CPP_STRING);
1550   else if (terminator == '\'')
1551     type = (*base == 'L' ? CPP_WCHAR :
1552             *base == 'U' ? CPP_CHAR32 :
1553             *base == 'u' ? CPP_CHAR16 : CPP_CHAR);
1554   else
1555     terminator = '>', type = CPP_HEADER_NAME;
1556
1557   for (;;)
1558     {
1559       cppchar_t c = *cur++;
1560
1561       /* In #include-style directives, terminators are not escapable.  */
1562       if (c == '\\' && !pfile->state.angled_headers && *cur != '\n')
1563         cur++;
1564       else if (c == terminator)
1565         break;
1566       else if (c == '\n')
1567         {
1568           cur--;
1569           /* Unmatched quotes always yield undefined behavior, but
1570              greedy lexing means that what appears to be an unterminated
1571              header name may actually be a legitimate sequence of tokens.  */
1572           if (terminator == '>')
1573             {
1574               token->type = CPP_LESS;
1575               return;
1576             }
1577           type = CPP_OTHER;
1578           break;
1579         }
1580       else if (c == '\0')
1581         saw_NUL = true;
1582     }
1583
1584   if (saw_NUL && !pfile->state.skipping)
1585     cpp_error (pfile, CPP_DL_WARNING,
1586                "null character(s) preserved in literal");
1587
1588   if (type == CPP_OTHER && CPP_OPTION (pfile, lang) != CLK_ASM)
1589     cpp_error (pfile, CPP_DL_PEDWARN, "missing terminating %c character",
1590                (int) terminator);
1591
1592   pfile->buffer->cur = cur;
1593   create_literal (pfile, token, base, cur - base, type);
1594 }
1595
1596 /* Return the comment table. The client may not make any assumption
1597    about the ordering of the table.  */
1598 cpp_comment_table *
1599 cpp_get_comments (cpp_reader *pfile)
1600 {
1601   return &pfile->comments;
1602 }
1603
1604 /* Append a comment to the end of the comment table. */
1605 static void 
1606 store_comment (cpp_reader *pfile, cpp_token *token) 
1607 {
1608   int len;
1609
1610   if (pfile->comments.allocated == 0)
1611     {
1612       pfile->comments.allocated = 256; 
1613       pfile->comments.entries = (cpp_comment *) xmalloc
1614         (pfile->comments.allocated * sizeof (cpp_comment));
1615     }
1616
1617   if (pfile->comments.count == pfile->comments.allocated)
1618     {
1619       pfile->comments.allocated *= 2;
1620       pfile->comments.entries = (cpp_comment *) xrealloc
1621         (pfile->comments.entries,
1622          pfile->comments.allocated * sizeof (cpp_comment));
1623     }
1624
1625   len = token->val.str.len;
1626
1627   /* Copy comment. Note, token may not be NULL terminated. */
1628   pfile->comments.entries[pfile->comments.count].comment = 
1629     (char *) xmalloc (sizeof (char) * (len + 1));
1630   memcpy (pfile->comments.entries[pfile->comments.count].comment,
1631           token->val.str.text, len);
1632   pfile->comments.entries[pfile->comments.count].comment[len] = '\0';
1633
1634   /* Set source location. */
1635   pfile->comments.entries[pfile->comments.count].sloc = token->src_loc;
1636
1637   /* Increment the count of entries in the comment table. */
1638   pfile->comments.count++;
1639 }
1640
1641 /* The stored comment includes the comment start and any terminator.  */
1642 static void
1643 save_comment (cpp_reader *pfile, cpp_token *token, const unsigned char *from,
1644               cppchar_t type)
1645 {
1646   unsigned char *buffer;
1647   unsigned int len, clen, i;
1648
1649   len = pfile->buffer->cur - from + 1; /* + 1 for the initial '/'.  */
1650
1651   /* C++ comments probably (not definitely) have moved past a new
1652      line, which we don't want to save in the comment.  */
1653   if (is_vspace (pfile->buffer->cur[-1]))
1654     len--;
1655
1656   /* If we are currently in a directive or in argument parsing, then
1657      we need to store all C++ comments as C comments internally, and
1658      so we need to allocate a little extra space in that case.
1659
1660      Note that the only time we encounter a directive here is
1661      when we are saving comments in a "#define".  */
1662   clen = ((pfile->state.in_directive || pfile->state.parsing_args)
1663           && type == '/') ? len + 2 : len;
1664
1665   buffer = _cpp_unaligned_alloc (pfile, clen);
1666
1667   token->type = CPP_COMMENT;
1668   token->val.str.len = clen;
1669   token->val.str.text = buffer;
1670
1671   buffer[0] = '/';
1672   memcpy (buffer + 1, from, len - 1);
1673
1674   /* Finish conversion to a C comment, if necessary.  */
1675   if ((pfile->state.in_directive || pfile->state.parsing_args) && type == '/')
1676     {
1677       buffer[1] = '*';
1678       buffer[clen - 2] = '*';
1679       buffer[clen - 1] = '/';
1680       /* As there can be in a C++ comments illegal sequences for C comments
1681          we need to filter them out.  */
1682       for (i = 2; i < (clen - 2); i++)
1683         if (buffer[i] == '/' && (buffer[i - 1] == '*' || buffer[i + 1] == '*'))
1684           buffer[i] = '|';
1685     }
1686
1687   /* Finally store this comment for use by clients of libcpp. */
1688   store_comment (pfile, token);
1689 }
1690
1691 /* Allocate COUNT tokens for RUN.  */
1692 void
1693 _cpp_init_tokenrun (tokenrun *run, unsigned int count)
1694 {
1695   run->base = XNEWVEC (cpp_token, count);
1696   run->limit = run->base + count;
1697   run->next = NULL;
1698 }
1699
1700 /* Returns the next tokenrun, or creates one if there is none.  */
1701 static tokenrun *
1702 next_tokenrun (tokenrun *run)
1703 {
1704   if (run->next == NULL)
1705     {
1706       run->next = XNEW (tokenrun);
1707       run->next->prev = run;
1708       _cpp_init_tokenrun (run->next, 250);
1709     }
1710
1711   return run->next;
1712 }
1713
1714 /* Look ahead in the input stream.  */
1715 const cpp_token *
1716 cpp_peek_token (cpp_reader *pfile, int index)
1717 {
1718   cpp_context *context = pfile->context;
1719   const cpp_token *peektok;
1720   int count;
1721
1722   /* First, scan through any pending cpp_context objects.  */
1723   while (context->prev)
1724     {
1725       ptrdiff_t sz = (context->direct_p
1726                       ? LAST (context).token - FIRST (context).token
1727                       : LAST (context).ptoken - FIRST (context).ptoken);
1728
1729       if (index < (int) sz)
1730         return (context->direct_p
1731                 ? FIRST (context).token + index
1732                 : *(FIRST (context).ptoken + index));
1733
1734       index -= (int) sz;
1735       context = context->prev;
1736     }
1737
1738   /* We will have to read some new tokens after all (and do so
1739      without invalidating preceding tokens).  */
1740   count = index;
1741   pfile->keep_tokens++;
1742
1743   do
1744     {
1745       peektok = _cpp_lex_token (pfile);
1746       if (peektok->type == CPP_EOF)
1747         return peektok;
1748     }
1749   while (index--);
1750
1751   _cpp_backup_tokens_direct (pfile, count + 1);
1752   pfile->keep_tokens--;
1753
1754   return peektok;
1755 }
1756
1757 /* Allocate a single token that is invalidated at the same time as the
1758    rest of the tokens on the line.  Has its line and col set to the
1759    same as the last lexed token, so that diagnostics appear in the
1760    right place.  */
1761 cpp_token *
1762 _cpp_temp_token (cpp_reader *pfile)
1763 {
1764   cpp_token *old, *result;
1765   ptrdiff_t sz = pfile->cur_run->limit - pfile->cur_token;
1766   ptrdiff_t la = (ptrdiff_t) pfile->lookaheads;
1767
1768   old = pfile->cur_token - 1;
1769   /* Any pre-existing lookaheads must not be clobbered.  */
1770   if (la)
1771     {
1772       if (sz <= la)
1773         {
1774           tokenrun *next = next_tokenrun (pfile->cur_run);
1775
1776           if (sz < la)
1777             memmove (next->base + 1, next->base,
1778                      (la - sz) * sizeof (cpp_token));
1779
1780           next->base[0] = pfile->cur_run->limit[-1];
1781         }
1782
1783       if (sz > 1)
1784         memmove (pfile->cur_token + 1, pfile->cur_token,
1785                  MIN (la, sz - 1) * sizeof (cpp_token));
1786     }
1787
1788   if (!sz && pfile->cur_token == pfile->cur_run->limit)
1789     {
1790       pfile->cur_run = next_tokenrun (pfile->cur_run);
1791       pfile->cur_token = pfile->cur_run->base;
1792     }
1793
1794   result = pfile->cur_token++;
1795   result->src_loc = old->src_loc;
1796   return result;
1797 }
1798
1799 /* Lex a token into RESULT (external interface).  Takes care of issues
1800    like directive handling, token lookahead, multiple include
1801    optimization and skipping.  */
1802 const cpp_token *
1803 _cpp_lex_token (cpp_reader *pfile)
1804 {
1805   cpp_token *result;
1806
1807   for (;;)
1808     {
1809       if (pfile->cur_token == pfile->cur_run->limit)
1810         {
1811           pfile->cur_run = next_tokenrun (pfile->cur_run);
1812           pfile->cur_token = pfile->cur_run->base;
1813         }
1814       /* We assume that the current token is somewhere in the current
1815          run.  */
1816       if (pfile->cur_token < pfile->cur_run->base
1817           || pfile->cur_token >= pfile->cur_run->limit)
1818         abort ();
1819
1820       if (pfile->lookaheads)
1821         {
1822           pfile->lookaheads--;
1823           result = pfile->cur_token++;
1824         }
1825       else
1826         result = _cpp_lex_direct (pfile);
1827
1828       if (result->flags & BOL)
1829         {
1830           /* Is this a directive.  If _cpp_handle_directive returns
1831              false, it is an assembler #.  */
1832           if (result->type == CPP_HASH
1833               /* 6.10.3 p 11: Directives in a list of macro arguments
1834                  gives undefined behavior.  This implementation
1835                  handles the directive as normal.  */
1836               && pfile->state.parsing_args != 1)
1837             {
1838               if (_cpp_handle_directive (pfile, result->flags & PREV_WHITE))
1839                 {
1840                   if (pfile->directive_result.type == CPP_PADDING)
1841                     continue;
1842                   result = &pfile->directive_result;
1843                 }
1844             }
1845           else if (pfile->state.in_deferred_pragma)
1846             result = &pfile->directive_result;
1847
1848           if (pfile->cb.line_change && !pfile->state.skipping)
1849             pfile->cb.line_change (pfile, result, pfile->state.parsing_args);
1850         }
1851
1852       /* We don't skip tokens in directives.  */
1853       if (pfile->state.in_directive || pfile->state.in_deferred_pragma)
1854         break;
1855
1856       /* Outside a directive, invalidate controlling macros.  At file
1857          EOF, _cpp_lex_direct takes care of popping the buffer, so we never
1858          get here and MI optimization works.  */
1859       pfile->mi_valid = false;
1860
1861       if (!pfile->state.skipping || result->type == CPP_EOF)
1862         break;
1863     }
1864
1865   return result;
1866 }
1867
1868 /* Returns true if a fresh line has been loaded.  */
1869 bool
1870 _cpp_get_fresh_line (cpp_reader *pfile)
1871 {
1872   int return_at_eof;
1873
1874   /* We can't get a new line until we leave the current directive.  */
1875   if (pfile->state.in_directive)
1876     return false;
1877
1878   for (;;)
1879     {
1880       cpp_buffer *buffer = pfile->buffer;
1881
1882       if (!buffer->need_line)
1883         return true;
1884
1885       if (buffer->next_line < buffer->rlimit)
1886         {
1887           _cpp_clean_line (pfile);
1888           return true;
1889         }
1890
1891       /* First, get out of parsing arguments state.  */
1892       if (pfile->state.parsing_args)
1893         return false;
1894
1895       /* End of buffer.  Non-empty files should end in a newline.  */
1896       if (buffer->buf != buffer->rlimit
1897           && buffer->next_line > buffer->rlimit
1898           && !buffer->from_stage3)
1899         {
1900           /* Clip to buffer size.  */
1901           buffer->next_line = buffer->rlimit;
1902         }
1903
1904       return_at_eof = buffer->return_at_eof;
1905       _cpp_pop_buffer (pfile);
1906       if (pfile->buffer == NULL || return_at_eof)
1907         return false;
1908     }
1909 }
1910
1911 #define IF_NEXT_IS(CHAR, THEN_TYPE, ELSE_TYPE)          \
1912   do                                                    \
1913     {                                                   \
1914       result->type = ELSE_TYPE;                         \
1915       if (*buffer->cur == CHAR)                         \
1916         buffer->cur++, result->type = THEN_TYPE;        \
1917     }                                                   \
1918   while (0)
1919
1920 /* Lex a token into pfile->cur_token, which is also incremented, to
1921    get diagnostics pointing to the correct location.
1922
1923    Does not handle issues such as token lookahead, multiple-include
1924    optimization, directives, skipping etc.  This function is only
1925    suitable for use by _cpp_lex_token, and in special cases like
1926    lex_expansion_token which doesn't care for any of these issues.
1927
1928    When meeting a newline, returns CPP_EOF if parsing a directive,
1929    otherwise returns to the start of the token buffer if permissible.
1930    Returns the location of the lexed token.  */
1931 cpp_token *
1932 _cpp_lex_direct (cpp_reader *pfile)
1933 {
1934   cppchar_t c;
1935   cpp_buffer *buffer;
1936   const unsigned char *comment_start;
1937   cpp_token *result = pfile->cur_token++;
1938
1939  fresh_line:
1940   result->flags = 0;
1941   buffer = pfile->buffer;
1942   if (buffer->need_line)
1943     {
1944       if (pfile->state.in_deferred_pragma)
1945         {
1946           result->type = CPP_PRAGMA_EOL;
1947           pfile->state.in_deferred_pragma = false;
1948           if (!pfile->state.pragma_allow_expansion)
1949             pfile->state.prevent_expansion--;
1950           return result;
1951         }
1952       if (!_cpp_get_fresh_line (pfile))
1953         {
1954           result->type = CPP_EOF;
1955           if (!pfile->state.in_directive)
1956             {
1957               /* Tell the compiler the line number of the EOF token.  */
1958               result->src_loc = pfile->line_table->highest_line;
1959               result->flags = BOL;
1960             }
1961           return result;
1962         }
1963       if (!pfile->keep_tokens)
1964         {
1965           pfile->cur_run = &pfile->base_run;
1966           result = pfile->base_run.base;
1967           pfile->cur_token = result + 1;
1968         }
1969       result->flags = BOL;
1970       if (pfile->state.parsing_args == 2)
1971         result->flags |= PREV_WHITE;
1972     }
1973   buffer = pfile->buffer;
1974  update_tokens_line:
1975   result->src_loc = pfile->line_table->highest_line;
1976
1977  skipped_white:
1978   if (buffer->cur >= buffer->notes[buffer->cur_note].pos
1979       && !pfile->overlaid_buffer)
1980     {
1981       _cpp_process_line_notes (pfile, false);
1982       result->src_loc = pfile->line_table->highest_line;
1983     }
1984   c = *buffer->cur++;
1985
1986   LINEMAP_POSITION_FOR_COLUMN (result->src_loc, pfile->line_table,
1987                                CPP_BUF_COLUMN (buffer, buffer->cur));
1988
1989   switch (c)
1990     {
1991     case ' ': case '\t': case '\f': case '\v': case '\0':
1992       result->flags |= PREV_WHITE;
1993       skip_whitespace (pfile, c);
1994       goto skipped_white;
1995
1996     case '\n':
1997       if (buffer->cur < buffer->rlimit)
1998         CPP_INCREMENT_LINE (pfile, 0);
1999       buffer->need_line = true;
2000       goto fresh_line;
2001
2002     case '0': case '1': case '2': case '3': case '4':
2003     case '5': case '6': case '7': case '8': case '9':
2004       {
2005         struct normalize_state nst = INITIAL_NORMALIZE_STATE;
2006         result->type = CPP_NUMBER;
2007         lex_number (pfile, &result->val.str, &nst);
2008         warn_about_normalization (pfile, result, &nst);
2009         break;
2010       }
2011
2012     case 'L':
2013     case 'u':
2014     case 'U':
2015     case 'R':
2016       /* 'L', 'u', 'U', 'u8' or 'R' may introduce wide characters,
2017          wide strings or raw strings.  */
2018       if (c == 'L' || CPP_OPTION (pfile, uliterals))
2019         {
2020           if ((*buffer->cur == '\'' && c != 'R')
2021               || *buffer->cur == '"'
2022               || (*buffer->cur == 'R'
2023                   && c != 'R'
2024                   && buffer->cur[1] == '"'
2025                   && CPP_OPTION (pfile, uliterals))
2026               || (*buffer->cur == '8'
2027                   && c == 'u'
2028                   && (buffer->cur[1] == '"'
2029                       || (buffer->cur[1] == 'R' && buffer->cur[2] == '"'))))
2030             {
2031               lex_string (pfile, result, buffer->cur - 1);
2032               break;
2033             }
2034         }
2035       /* Fall through.  */
2036
2037     case '_':
2038     case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2039     case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2040     case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
2041     case 's': case 't':           case 'v': case 'w': case 'x':
2042     case 'y': case 'z':
2043     case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2044     case 'G': case 'H': case 'I': case 'J': case 'K':
2045     case 'M': case 'N': case 'O': case 'P': case 'Q':
2046     case 'S': case 'T':           case 'V': case 'W': case 'X':
2047     case 'Y': case 'Z':
2048       result->type = CPP_NAME;
2049       {
2050         struct normalize_state nst = INITIAL_NORMALIZE_STATE;
2051         result->val.node.node = lex_identifier (pfile, buffer->cur - 1, false,
2052                                                 &nst);
2053         warn_about_normalization (pfile, result, &nst);
2054       }
2055
2056       /* Convert named operators to their proper types.  */
2057       if (result->val.node.node->flags & NODE_OPERATOR)
2058         {
2059           result->flags |= NAMED_OP;
2060           result->type = (enum cpp_ttype) result->val.node.node->directive_index;
2061         }
2062       break;
2063
2064     case '\'':
2065     case '"':
2066       lex_string (pfile, result, buffer->cur - 1);
2067       break;
2068
2069     case '/':
2070       /* A potential block or line comment.  */
2071       comment_start = buffer->cur;
2072       c = *buffer->cur;
2073       
2074       if (c == '*')
2075         {
2076           if (_cpp_skip_block_comment (pfile))
2077             cpp_error (pfile, CPP_DL_ERROR, "unterminated comment");
2078         }
2079       else if (c == '/' && (CPP_OPTION (pfile, cplusplus_comments)
2080                             || cpp_in_system_header (pfile)))
2081         {
2082           /* Warn about comments only if pedantically GNUC89, and not
2083              in system headers.  */
2084           if (CPP_OPTION (pfile, lang) == CLK_GNUC89 && CPP_PEDANTIC (pfile)
2085               && ! buffer->warned_cplusplus_comments)
2086             {
2087               cpp_error (pfile, CPP_DL_PEDWARN,
2088                          "C++ style comments are not allowed in ISO C90");
2089               cpp_error (pfile, CPP_DL_PEDWARN,
2090                          "(this will be reported only once per input file)");
2091               buffer->warned_cplusplus_comments = 1;
2092             }
2093
2094           if (skip_line_comment (pfile) && CPP_OPTION (pfile, warn_comments))
2095             cpp_warning (pfile, CPP_W_COMMENTS, "multi-line comment");
2096         }
2097       else if (c == '=')
2098         {
2099           buffer->cur++;
2100           result->type = CPP_DIV_EQ;
2101           break;
2102         }
2103       else
2104         {
2105           result->type = CPP_DIV;
2106           break;
2107         }
2108
2109       if (!pfile->state.save_comments)
2110         {
2111           result->flags |= PREV_WHITE;
2112           goto update_tokens_line;
2113         }
2114
2115       /* Save the comment as a token in its own right.  */
2116       save_comment (pfile, result, comment_start, c);
2117       break;
2118
2119     case '<':
2120       if (pfile->state.angled_headers)
2121         {
2122           lex_string (pfile, result, buffer->cur - 1);
2123           if (result->type != CPP_LESS)
2124             break;
2125         }
2126
2127       result->type = CPP_LESS;
2128       if (*buffer->cur == '=')
2129         buffer->cur++, result->type = CPP_LESS_EQ;
2130       else if (*buffer->cur == '<')
2131         {
2132           buffer->cur++;
2133           IF_NEXT_IS ('=', CPP_LSHIFT_EQ, CPP_LSHIFT);
2134         }
2135       else if (CPP_OPTION (pfile, digraphs))
2136         {
2137           if (*buffer->cur == ':')
2138             {
2139               buffer->cur++;
2140               result->flags |= DIGRAPH;
2141               result->type = CPP_OPEN_SQUARE;
2142             }
2143           else if (*buffer->cur == '%')
2144             {
2145               buffer->cur++;
2146               result->flags |= DIGRAPH;
2147               result->type = CPP_OPEN_BRACE;
2148             }
2149         }
2150       break;
2151
2152     case '>':
2153       result->type = CPP_GREATER;
2154       if (*buffer->cur == '=')
2155         buffer->cur++, result->type = CPP_GREATER_EQ;
2156       else if (*buffer->cur == '>')
2157         {
2158           buffer->cur++;
2159           IF_NEXT_IS ('=', CPP_RSHIFT_EQ, CPP_RSHIFT);
2160         }
2161       break;
2162
2163     case '%':
2164       result->type = CPP_MOD;
2165       if (*buffer->cur == '=')
2166         buffer->cur++, result->type = CPP_MOD_EQ;
2167       else if (CPP_OPTION (pfile, digraphs))
2168         {
2169           if (*buffer->cur == ':')
2170             {
2171               buffer->cur++;
2172               result->flags |= DIGRAPH;
2173               result->type = CPP_HASH;
2174               if (*buffer->cur == '%' && buffer->cur[1] == ':')
2175                 buffer->cur += 2, result->type = CPP_PASTE, result->val.token_no = 0;
2176             }
2177           else if (*buffer->cur == '>')
2178             {
2179               buffer->cur++;
2180               result->flags |= DIGRAPH;
2181               result->type = CPP_CLOSE_BRACE;
2182             }
2183         }
2184       break;
2185
2186     case '.':
2187       result->type = CPP_DOT;
2188       if (ISDIGIT (*buffer->cur))
2189         {
2190           struct normalize_state nst = INITIAL_NORMALIZE_STATE;
2191           result->type = CPP_NUMBER;
2192           lex_number (pfile, &result->val.str, &nst);
2193           warn_about_normalization (pfile, result, &nst);
2194         }
2195       else if (*buffer->cur == '.' && buffer->cur[1] == '.')
2196         buffer->cur += 2, result->type = CPP_ELLIPSIS;
2197       else if (*buffer->cur == '*' && CPP_OPTION (pfile, cplusplus))
2198         buffer->cur++, result->type = CPP_DOT_STAR;
2199       break;
2200
2201     case '+':
2202       result->type = CPP_PLUS;
2203       if (*buffer->cur == '+')
2204         buffer->cur++, result->type = CPP_PLUS_PLUS;
2205       else if (*buffer->cur == '=')
2206         buffer->cur++, result->type = CPP_PLUS_EQ;
2207       break;
2208
2209     case '-':
2210       result->type = CPP_MINUS;
2211       if (*buffer->cur == '>')
2212         {
2213           buffer->cur++;
2214           result->type = CPP_DEREF;
2215           if (*buffer->cur == '*' && CPP_OPTION (pfile, cplusplus))
2216             buffer->cur++, result->type = CPP_DEREF_STAR;
2217         }
2218       else if (*buffer->cur == '-')
2219         buffer->cur++, result->type = CPP_MINUS_MINUS;
2220       else if (*buffer->cur == '=')
2221         buffer->cur++, result->type = CPP_MINUS_EQ;
2222       break;
2223
2224     case '&':
2225       result->type = CPP_AND;
2226       if (*buffer->cur == '&')
2227         buffer->cur++, result->type = CPP_AND_AND;
2228       else if (*buffer->cur == '=')
2229         buffer->cur++, result->type = CPP_AND_EQ;
2230       break;
2231
2232     case '|':
2233       result->type = CPP_OR;
2234       if (*buffer->cur == '|')
2235         buffer->cur++, result->type = CPP_OR_OR;
2236       else if (*buffer->cur == '=')
2237         buffer->cur++, result->type = CPP_OR_EQ;
2238       break;
2239
2240     case ':':
2241       result->type = CPP_COLON;
2242       if (*buffer->cur == ':' && CPP_OPTION (pfile, cplusplus))
2243         buffer->cur++, result->type = CPP_SCOPE;
2244       else if (*buffer->cur == '>' && CPP_OPTION (pfile, digraphs))
2245         {
2246           buffer->cur++;
2247           result->flags |= DIGRAPH;
2248           result->type = CPP_CLOSE_SQUARE;
2249         }
2250       break;
2251
2252     case '*': IF_NEXT_IS ('=', CPP_MULT_EQ, CPP_MULT); break;
2253     case '=': IF_NEXT_IS ('=', CPP_EQ_EQ, CPP_EQ); break;
2254     case '!': IF_NEXT_IS ('=', CPP_NOT_EQ, CPP_NOT); break;
2255     case '^': IF_NEXT_IS ('=', CPP_XOR_EQ, CPP_XOR); break;
2256     case '#': IF_NEXT_IS ('#', CPP_PASTE, CPP_HASH); result->val.token_no = 0; break;
2257
2258     case '?': result->type = CPP_QUERY; break;
2259     case '~': result->type = CPP_COMPL; break;
2260     case ',': result->type = CPP_COMMA; break;
2261     case '(': result->type = CPP_OPEN_PAREN; break;
2262     case ')': result->type = CPP_CLOSE_PAREN; break;
2263     case '[': result->type = CPP_OPEN_SQUARE; break;
2264     case ']': result->type = CPP_CLOSE_SQUARE; break;
2265     case '{': result->type = CPP_OPEN_BRACE; break;
2266     case '}': result->type = CPP_CLOSE_BRACE; break;
2267     case ';': result->type = CPP_SEMICOLON; break;
2268
2269       /* @ is a punctuator in Objective-C.  */
2270     case '@': result->type = CPP_ATSIGN; break;
2271
2272     case '$':
2273     case '\\':
2274       {
2275         const uchar *base = --buffer->cur;
2276         struct normalize_state nst = INITIAL_NORMALIZE_STATE;
2277
2278         if (forms_identifier_p (pfile, true, &nst))
2279           {
2280             result->type = CPP_NAME;
2281             result->val.node.node = lex_identifier (pfile, base, true, &nst);
2282             warn_about_normalization (pfile, result, &nst);
2283             break;
2284           }
2285         buffer->cur++;
2286       }
2287
2288     default:
2289       create_literal (pfile, result, buffer->cur - 1, 1, CPP_OTHER);
2290       break;
2291     }
2292
2293   return result;
2294 }
2295
2296 /* An upper bound on the number of bytes needed to spell TOKEN.
2297    Does not include preceding whitespace.  */
2298 unsigned int
2299 cpp_token_len (const cpp_token *token)
2300 {
2301   unsigned int len;
2302
2303   switch (TOKEN_SPELL (token))
2304     {
2305     default:            len = 6;                                break;
2306     case SPELL_LITERAL: len = token->val.str.len;               break;
2307     case SPELL_IDENT:   len = NODE_LEN (token->val.node.node) * 10;     break;
2308     }
2309
2310   return len;
2311 }
2312
2313 /* Parse UTF-8 out of NAMEP and place a \U escape in BUFFER.
2314    Return the number of bytes read out of NAME.  (There are always
2315    10 bytes written to BUFFER.)  */
2316
2317 static size_t
2318 utf8_to_ucn (unsigned char *buffer, const unsigned char *name)
2319 {
2320   int j;
2321   int ucn_len = 0;
2322   int ucn_len_c;
2323   unsigned t;
2324   unsigned long utf32;
2325   
2326   /* Compute the length of the UTF-8 sequence.  */
2327   for (t = *name; t & 0x80; t <<= 1)
2328     ucn_len++;
2329   
2330   utf32 = *name & (0x7F >> ucn_len);
2331   for (ucn_len_c = 1; ucn_len_c < ucn_len; ucn_len_c++)
2332     {
2333       utf32 = (utf32 << 6) | (*++name & 0x3F);
2334       
2335       /* Ill-formed UTF-8.  */
2336       if ((*name & ~0x3F) != 0x80)
2337         abort ();
2338     }
2339   
2340   *buffer++ = '\\';
2341   *buffer++ = 'U';
2342   for (j = 7; j >= 0; j--)
2343     *buffer++ = "0123456789abcdef"[(utf32 >> (4 * j)) & 0xF];
2344   return ucn_len;
2345 }
2346
2347 /* Given a token TYPE corresponding to a digraph, return a pointer to
2348    the spelling of the digraph.  */
2349 static const unsigned char *
2350 cpp_digraph2name (enum cpp_ttype type)
2351 {
2352   return digraph_spellings[(int) type - (int) CPP_FIRST_DIGRAPH];
2353 }
2354
2355 /* Write the spelling of a token TOKEN to BUFFER.  The buffer must
2356    already contain the enough space to hold the token's spelling.
2357    Returns a pointer to the character after the last character written.
2358    FORSTRING is true if this is to be the spelling after translation
2359    phase 1 (this is different for UCNs).
2360    FIXME: Would be nice if we didn't need the PFILE argument.  */
2361 unsigned char *
2362 cpp_spell_token (cpp_reader *pfile, const cpp_token *token,
2363                  unsigned char *buffer, bool forstring)
2364 {
2365   switch (TOKEN_SPELL (token))
2366     {
2367     case SPELL_OPERATOR:
2368       {
2369         const unsigned char *spelling;
2370         unsigned char c;
2371
2372         if (token->flags & DIGRAPH)
2373           spelling = cpp_digraph2name (token->type);
2374         else if (token->flags & NAMED_OP)
2375           goto spell_ident;
2376         else
2377           spelling = TOKEN_NAME (token);
2378
2379         while ((c = *spelling++) != '\0')
2380           *buffer++ = c;
2381       }
2382       break;
2383
2384     spell_ident:
2385     case SPELL_IDENT:
2386       if (forstring)
2387         {
2388           memcpy (buffer, NODE_NAME (token->val.node.node),
2389                   NODE_LEN (token->val.node.node));
2390           buffer += NODE_LEN (token->val.node.node);
2391         }
2392       else
2393         {
2394           size_t i;
2395           const unsigned char * name = NODE_NAME (token->val.node.node);
2396           
2397           for (i = 0; i < NODE_LEN (token->val.node.node); i++)
2398             if (name[i] & ~0x7F)
2399               {
2400                 i += utf8_to_ucn (buffer, name + i) - 1;
2401                 buffer += 10;
2402               }
2403             else
2404               *buffer++ = NODE_NAME (token->val.node.node)[i];
2405         }
2406       break;
2407
2408     case SPELL_LITERAL:
2409       memcpy (buffer, token->val.str.text, token->val.str.len);
2410       buffer += token->val.str.len;
2411       break;
2412
2413     case SPELL_NONE:
2414       cpp_error (pfile, CPP_DL_ICE,
2415                  "unspellable token %s", TOKEN_NAME (token));
2416       break;
2417     }
2418
2419   return buffer;
2420 }
2421
2422 /* Returns TOKEN spelt as a null-terminated string.  The string is
2423    freed when the reader is destroyed.  Useful for diagnostics.  */
2424 unsigned char *
2425 cpp_token_as_text (cpp_reader *pfile, const cpp_token *token)
2426
2427   unsigned int len = cpp_token_len (token) + 1;
2428   unsigned char *start = _cpp_unaligned_alloc (pfile, len), *end;
2429
2430   end = cpp_spell_token (pfile, token, start, false);
2431   end[0] = '\0';
2432
2433   return start;
2434 }
2435
2436 /* Returns a pointer to a string which spells the token defined by
2437    TYPE and FLAGS.  Used by C front ends, which really should move to
2438    using cpp_token_as_text.  */
2439 const char *
2440 cpp_type2name (enum cpp_ttype type, unsigned char flags)
2441 {
2442   if (flags & DIGRAPH)
2443     return (const char *) cpp_digraph2name (type);
2444   else if (flags & NAMED_OP)
2445     return cpp_named_operator2name (type);
2446
2447   return (const char *) token_spellings[type].name;
2448 }
2449
2450 /* Writes the spelling of token to FP, without any preceding space.
2451    Separated from cpp_spell_token for efficiency - to avoid stdio
2452    double-buffering.  */
2453 void
2454 cpp_output_token (const cpp_token *token, FILE *fp)
2455 {
2456   switch (TOKEN_SPELL (token))
2457     {
2458     case SPELL_OPERATOR:
2459       {
2460         const unsigned char *spelling;
2461         int c;
2462
2463         if (token->flags & DIGRAPH)
2464           spelling = cpp_digraph2name (token->type);
2465         else if (token->flags & NAMED_OP)
2466           goto spell_ident;
2467         else
2468           spelling = TOKEN_NAME (token);
2469
2470         c = *spelling;
2471         do
2472           putc (c, fp);
2473         while ((c = *++spelling) != '\0');
2474       }
2475       break;
2476
2477     spell_ident:
2478     case SPELL_IDENT:
2479       {
2480         size_t i;
2481         const unsigned char * name = NODE_NAME (token->val.node.node);
2482         
2483         for (i = 0; i < NODE_LEN (token->val.node.node); i++)
2484           if (name[i] & ~0x7F)
2485             {
2486               unsigned char buffer[10];
2487               i += utf8_to_ucn (buffer, name + i) - 1;
2488               fwrite (buffer, 1, 10, fp);
2489             }
2490           else
2491             fputc (NODE_NAME (token->val.node.node)[i], fp);
2492       }
2493       break;
2494
2495     case SPELL_LITERAL:
2496       fwrite (token->val.str.text, 1, token->val.str.len, fp);
2497       break;
2498
2499     case SPELL_NONE:
2500       /* An error, most probably.  */
2501       break;
2502     }
2503 }
2504
2505 /* Compare two tokens.  */
2506 int
2507 _cpp_equiv_tokens (const cpp_token *a, const cpp_token *b)
2508 {
2509   if (a->type == b->type && a->flags == b->flags)
2510     switch (TOKEN_SPELL (a))
2511       {
2512       default:                  /* Keep compiler happy.  */
2513       case SPELL_OPERATOR:
2514         /* token_no is used to track where multiple consecutive ##
2515            tokens were originally located.  */
2516         return (a->type != CPP_PASTE || a->val.token_no == b->val.token_no);
2517       case SPELL_NONE:
2518         return (a->type != CPP_MACRO_ARG
2519                 || a->val.macro_arg.arg_no == b->val.macro_arg.arg_no);
2520       case SPELL_IDENT:
2521         return a->val.node.node == b->val.node.node;
2522       case SPELL_LITERAL:
2523         return (a->val.str.len == b->val.str.len
2524                 && !memcmp (a->val.str.text, b->val.str.text,
2525                             a->val.str.len));
2526       }
2527
2528   return 0;
2529 }
2530
2531 /* Returns nonzero if a space should be inserted to avoid an
2532    accidental token paste for output.  For simplicity, it is
2533    conservative, and occasionally advises a space where one is not
2534    needed, e.g. "." and ".2".  */
2535 int
2536 cpp_avoid_paste (cpp_reader *pfile, const cpp_token *token1,
2537                  const cpp_token *token2)
2538 {
2539   enum cpp_ttype a = token1->type, b = token2->type;
2540   cppchar_t c;
2541
2542   if (token1->flags & NAMED_OP)
2543     a = CPP_NAME;
2544   if (token2->flags & NAMED_OP)
2545     b = CPP_NAME;
2546
2547   c = EOF;
2548   if (token2->flags & DIGRAPH)
2549     c = digraph_spellings[(int) b - (int) CPP_FIRST_DIGRAPH][0];
2550   else if (token_spellings[b].category == SPELL_OPERATOR)
2551     c = token_spellings[b].name[0];
2552
2553   /* Quickly get everything that can paste with an '='.  */
2554   if ((int) a <= (int) CPP_LAST_EQ && c == '=')
2555     return 1;
2556
2557   switch (a)
2558     {
2559     case CPP_GREATER:   return c == '>';
2560     case CPP_LESS:      return c == '<' || c == '%' || c == ':';
2561     case CPP_PLUS:      return c == '+';
2562     case CPP_MINUS:     return c == '-' || c == '>';
2563     case CPP_DIV:       return c == '/' || c == '*'; /* Comments.  */
2564     case CPP_MOD:       return c == ':' || c == '>';
2565     case CPP_AND:       return c == '&';
2566     case CPP_OR:        return c == '|';
2567     case CPP_COLON:     return c == ':' || c == '>';
2568     case CPP_DEREF:     return c == '*';
2569     case CPP_DOT:       return c == '.' || c == '%' || b == CPP_NUMBER;
2570     case CPP_HASH:      return c == '#' || c == '%'; /* Digraph form.  */
2571     case CPP_NAME:      return ((b == CPP_NUMBER
2572                                  && name_p (pfile, &token2->val.str))
2573                                 || b == CPP_NAME
2574                                 || b == CPP_CHAR || b == CPP_STRING); /* L */
2575     case CPP_NUMBER:    return (b == CPP_NUMBER || b == CPP_NAME
2576                                 || c == '.' || c == '+' || c == '-');
2577                                       /* UCNs */
2578     case CPP_OTHER:     return ((token1->val.str.text[0] == '\\'
2579                                  && b == CPP_NAME)
2580                                 || (CPP_OPTION (pfile, objc)
2581                                     && token1->val.str.text[0] == '@'
2582                                     && (b == CPP_NAME || b == CPP_STRING)));
2583     default:            break;
2584     }
2585
2586   return 0;
2587 }
2588
2589 /* Output all the remaining tokens on the current line, and a newline
2590    character, to FP.  Leading whitespace is removed.  If there are
2591    macros, special token padding is not performed.  */
2592 void
2593 cpp_output_line (cpp_reader *pfile, FILE *fp)
2594 {
2595   const cpp_token *token;
2596
2597   token = cpp_get_token (pfile);
2598   while (token->type != CPP_EOF)
2599     {
2600       cpp_output_token (token, fp);
2601       token = cpp_get_token (pfile);
2602       if (token->flags & PREV_WHITE)
2603         putc (' ', fp);
2604     }
2605
2606   putc ('\n', fp);
2607 }
2608
2609 /* Return a string representation of all the remaining tokens on the
2610    current line.  The result is allocated using xmalloc and must be
2611    freed by the caller.  */
2612 unsigned char *
2613 cpp_output_line_to_string (cpp_reader *pfile, const unsigned char *dir_name)
2614 {
2615   const cpp_token *token;
2616   unsigned int out = dir_name ? ustrlen (dir_name) : 0;
2617   unsigned int alloced = 120 + out;
2618   unsigned char *result = (unsigned char *) xmalloc (alloced);
2619
2620   /* If DIR_NAME is empty, there are no initial contents.  */
2621   if (dir_name)
2622     {
2623       sprintf ((char *) result, "#%s ", dir_name);
2624       out += 2;
2625     }
2626
2627   token = cpp_get_token (pfile);
2628   while (token->type != CPP_EOF)
2629     {
2630       unsigned char *last;
2631       /* Include room for a possible space and the terminating nul.  */
2632       unsigned int len = cpp_token_len (token) + 2;
2633
2634       if (out + len > alloced)
2635         {
2636           alloced *= 2;
2637           if (out + len > alloced)
2638             alloced = out + len;
2639           result = (unsigned char *) xrealloc (result, alloced);
2640         }
2641
2642       last = cpp_spell_token (pfile, token, &result[out], 0);
2643       out = last - result;
2644
2645       token = cpp_get_token (pfile);
2646       if (token->flags & PREV_WHITE)
2647         result[out++] = ' ';
2648     }
2649
2650   result[out] = '\0';
2651   return result;
2652 }
2653
2654 /* Memory buffers.  Changing these three constants can have a dramatic
2655    effect on performance.  The values here are reasonable defaults,
2656    but might be tuned.  If you adjust them, be sure to test across a
2657    range of uses of cpplib, including heavy nested function-like macro
2658    expansion.  Also check the change in peak memory usage (NJAMD is a
2659    good tool for this).  */
2660 #define MIN_BUFF_SIZE 8000
2661 #define BUFF_SIZE_UPPER_BOUND(MIN_SIZE) (MIN_BUFF_SIZE + (MIN_SIZE) * 3 / 2)
2662 #define EXTENDED_BUFF_SIZE(BUFF, MIN_EXTRA) \
2663         (MIN_EXTRA + ((BUFF)->limit - (BUFF)->cur) * 2)
2664
2665 #if MIN_BUFF_SIZE > BUFF_SIZE_UPPER_BOUND (0)
2666   #error BUFF_SIZE_UPPER_BOUND must be at least as large as MIN_BUFF_SIZE!
2667 #endif
2668
2669 /* Create a new allocation buffer.  Place the control block at the end
2670    of the buffer, so that buffer overflows will cause immediate chaos.  */
2671 static _cpp_buff *
2672 new_buff (size_t len)
2673 {
2674   _cpp_buff *result;
2675   unsigned char *base;
2676
2677   if (len < MIN_BUFF_SIZE)
2678     len = MIN_BUFF_SIZE;
2679   len = CPP_ALIGN (len);
2680
2681   base = XNEWVEC (unsigned char, len + sizeof (_cpp_buff));
2682   result = (_cpp_buff *) (base + len);
2683   result->base = base;
2684   result->cur = base;
2685   result->limit = base + len;
2686   result->next = NULL;
2687   return result;
2688 }
2689
2690 /* Place a chain of unwanted allocation buffers on the free list.  */
2691 void
2692 _cpp_release_buff (cpp_reader *pfile, _cpp_buff *buff)
2693 {
2694   _cpp_buff *end = buff;
2695
2696   while (end->next)
2697     end = end->next;
2698   end->next = pfile->free_buffs;
2699   pfile->free_buffs = buff;
2700 }
2701
2702 /* Return a free buffer of size at least MIN_SIZE.  */
2703 _cpp_buff *
2704 _cpp_get_buff (cpp_reader *pfile, size_t min_size)
2705 {
2706   _cpp_buff *result, **p;
2707
2708   for (p = &pfile->free_buffs;; p = &(*p)->next)
2709     {
2710       size_t size;
2711
2712       if (*p == NULL)
2713         return new_buff (min_size);
2714       result = *p;
2715       size = result->limit - result->base;
2716       /* Return a buffer that's big enough, but don't waste one that's
2717          way too big.  */
2718       if (size >= min_size && size <= BUFF_SIZE_UPPER_BOUND (min_size))
2719         break;
2720     }
2721
2722   *p = result->next;
2723   result->next = NULL;
2724   result->cur = result->base;
2725   return result;
2726 }
2727
2728 /* Creates a new buffer with enough space to hold the uncommitted
2729    remaining bytes of BUFF, and at least MIN_EXTRA more bytes.  Copies
2730    the excess bytes to the new buffer.  Chains the new buffer after
2731    BUFF, and returns the new buffer.  */
2732 _cpp_buff *
2733 _cpp_append_extend_buff (cpp_reader *pfile, _cpp_buff *buff, size_t min_extra)
2734 {
2735   size_t size = EXTENDED_BUFF_SIZE (buff, min_extra);
2736   _cpp_buff *new_buff = _cpp_get_buff (pfile, size);
2737
2738   buff->next = new_buff;
2739   memcpy (new_buff->base, buff->cur, BUFF_ROOM (buff));
2740   return new_buff;
2741 }
2742
2743 /* Creates a new buffer with enough space to hold the uncommitted
2744    remaining bytes of the buffer pointed to by BUFF, and at least
2745    MIN_EXTRA more bytes.  Copies the excess bytes to the new buffer.
2746    Chains the new buffer before the buffer pointed to by BUFF, and
2747    updates the pointer to point to the new buffer.  */
2748 void
2749 _cpp_extend_buff (cpp_reader *pfile, _cpp_buff **pbuff, size_t min_extra)
2750 {
2751   _cpp_buff *new_buff, *old_buff = *pbuff;
2752   size_t size = EXTENDED_BUFF_SIZE (old_buff, min_extra);
2753
2754   new_buff = _cpp_get_buff (pfile, size);
2755   memcpy (new_buff->base, old_buff->cur, BUFF_ROOM (old_buff));
2756   new_buff->next = old_buff;
2757   *pbuff = new_buff;
2758 }
2759
2760 /* Free a chain of buffers starting at BUFF.  */
2761 void
2762 _cpp_free_buff (_cpp_buff *buff)
2763 {
2764   _cpp_buff *next;
2765
2766   for (; buff; buff = next)
2767     {
2768       next = buff->next;
2769       free (buff->base);
2770     }
2771 }
2772
2773 /* Allocate permanent, unaligned storage of length LEN.  */
2774 unsigned char *
2775 _cpp_unaligned_alloc (cpp_reader *pfile, size_t len)
2776 {
2777   _cpp_buff *buff = pfile->u_buff;
2778   unsigned char *result = buff->cur;
2779
2780   if (len > (size_t) (buff->limit - result))
2781     {
2782       buff = _cpp_get_buff (pfile, len);
2783       buff->next = pfile->u_buff;
2784       pfile->u_buff = buff;
2785       result = buff->cur;
2786     }
2787
2788   buff->cur = result + len;
2789   return result;
2790 }
2791
2792 /* Allocate permanent, unaligned storage of length LEN from a_buff.
2793    That buffer is used for growing allocations when saving macro
2794    replacement lists in a #define, and when parsing an answer to an
2795    assertion in #assert, #unassert or #if (and therefore possibly
2796    whilst expanding macros).  It therefore must not be used by any
2797    code that they might call: specifically the lexer and the guts of
2798    the macro expander.
2799
2800    All existing other uses clearly fit this restriction: storing
2801    registered pragmas during initialization.  */
2802 unsigned char *
2803 _cpp_aligned_alloc (cpp_reader *pfile, size_t len)
2804 {
2805   _cpp_buff *buff = pfile->a_buff;
2806   unsigned char *result = buff->cur;
2807
2808   if (len > (size_t) (buff->limit - result))
2809     {
2810       buff = _cpp_get_buff (pfile, len);
2811       buff->next = pfile->a_buff;
2812       pfile->a_buff = buff;
2813       result = buff->cur;
2814     }
2815
2816   buff->cur = result + len;
2817   return result;
2818 }
2819
2820 /* Say which field of TOK is in use.  */
2821
2822 enum cpp_token_fld_kind
2823 cpp_token_val_index (cpp_token *tok)
2824 {
2825   switch (TOKEN_SPELL (tok))
2826     {
2827     case SPELL_IDENT:
2828       return CPP_TOKEN_FLD_NODE;
2829     case SPELL_LITERAL:
2830       return CPP_TOKEN_FLD_STR;
2831     case SPELL_OPERATOR:
2832       if (tok->type == CPP_PASTE)
2833         return CPP_TOKEN_FLD_TOKEN_NO;
2834       else
2835         return CPP_TOKEN_FLD_NONE;
2836     case SPELL_NONE:
2837       if (tok->type == CPP_MACRO_ARG)
2838         return CPP_TOKEN_FLD_ARG_NO;
2839       else if (tok->type == CPP_PADDING)
2840         return CPP_TOKEN_FLD_SOURCE;
2841       else if (tok->type == CPP_PRAGMA)
2842         return CPP_TOKEN_FLD_PRAGMA;
2843       /* else fall through */
2844     default:
2845       return CPP_TOKEN_FLD_NONE;
2846     }
2847 }