]> git.ipfire.org Git - thirdparty/gcc.git/blame - libcpp/lex.c
m32c.h (CLASS_MAX_NREGS): Remove macro.
[thirdparty/gcc.git] / libcpp / lex.c
CommitLineData
45b966db 1/* CPP Library - lexical analysis.
a48e3dd1
JM
2 Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010,
3 2011 Free Software Foundation, Inc.
45b966db
ZW
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
9This program is free software; you can redistribute it and/or modify it
10under the terms of the GNU General Public License as published by the
748086b7 11Free Software Foundation; either version 3, or (at your option) any
45b966db
ZW
12later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
748086b7
JJ
20along with this program; see the file COPYING3. If not see
21<http://www.gnu.org/licenses/>. */
45b966db
ZW
22
23#include "config.h"
24#include "system.h"
45b966db 25#include "cpplib.h"
4f4e53dd 26#include "internal.h"
45b966db 27
93c80368 28enum spell_type
f9a0e96c 29{
93c80368 30 SPELL_OPERATOR = 0,
93c80368 31 SPELL_IDENT,
6338b358 32 SPELL_LITERAL,
93c80368 33 SPELL_NONE
f9a0e96c
ZW
34};
35
93c80368 36struct token_spelling
f9a0e96c 37{
93c80368
NB
38 enum spell_type category;
39 const unsigned char *name;
f9a0e96c
ZW
40};
41
8206c799 42static const unsigned char *const digraph_spellings[] =
b6baa67d 43{ UC"%:", UC"%:%:", UC"<:", UC":>", UC"<%", UC"%>" };
93c80368 44
b6baa67d
KVH
45#define OP(e, s) { SPELL_OPERATOR, UC s },
46#define TK(e, s) { SPELL_ ## s, UC #e },
8206c799 47static const struct token_spelling token_spellings[N_TTYPES] = { TTYPE_TABLE };
93c80368
NB
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)
f2d5f0cc 53
6cf87ca4
ZW
54static void add_line_note (cpp_buffer *, const uchar *, unsigned int);
55static int skip_line_comment (cpp_reader *);
56static void skip_whitespace (cpp_reader *, cppchar_t);
6cf87ca4
ZW
57static void lex_string (cpp_reader *, cpp_token *, const uchar *);
58static void save_comment (cpp_reader *, cpp_token *, const uchar *, cppchar_t);
631d0d36 59static void store_comment (cpp_reader *, cpp_token *);
6cf87ca4
ZW
60static void create_literal (cpp_reader *, cpp_token *, const uchar *,
61 unsigned int, enum cpp_ttype);
62static bool warn_in_comment (cpp_reader *, _cpp_line_note *);
63static int name_p (cpp_reader *, const cpp_string *);
6cf87ca4
ZW
64static tokenrun *next_tokenrun (tokenrun *);
65
6cf87ca4 66static _cpp_buff *new_buff (size_t);
15dad1d9 67
9d10c9a9 68
041c3194 69/* Utility routine:
9e62c811 70
bfb9dc7f
ZW
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. */
041c3194 73int
6cf87ca4 74cpp_ideq (const cpp_token *token, const char *string)
041c3194 75{
bfb9dc7f 76 if (token->type != CPP_NAME)
041c3194 77 return 0;
bfb9dc7f 78
9a0c6187 79 return !ustrcmp (NODE_NAME (token->val.node.node), (const uchar *) string);
15dad1d9 80}
1368ee70 81
26aea073
NB
82/* Record a note TYPE at byte POS into the current cleaned logical
83 line. */
87062813 84static void
6cf87ca4 85add_line_note (cpp_buffer *buffer, const uchar *pos, unsigned int type)
0d9f234d 86{
26aea073
NB
87 if (buffer->notes_used == buffer->notes_cap)
88 {
89 buffer->notes_cap = buffer->notes_cap * 2 + 200;
c3f829c1
GDR
90 buffer->notes = XRESIZEVEC (_cpp_line_note, buffer->notes,
91 buffer->notes_cap);
26aea073 92 }
0d9f234d 93
26aea073
NB
94 buffer->notes[buffer->notes_used].pos = pos;
95 buffer->notes[buffer->notes_used].type = type;
96 buffer->notes_used++;
0d9f234d
NB
97}
98
246a2fcb
RH
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__
126typedef unsigned int word_type __attribute__((__mode__(__word__)));
127#else
128typedef 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. */
133typedef 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
139static inline word_type
140acc_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
152static inline word_type
153acc_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
165static inline word_type
166acc_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
186static inline int
187acc_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
226static const uchar * search_line_acc_char (const uchar *, const uchar *)
227 ATTRIBUTE_UNUSED;
228
229static const uchar *
230search_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
789d73cb
RO
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__))
246a2fcb
RH
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. */
283static 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",
ef230b38 297 which was packaged into SSE1; it is also present in the AMD MMX
246a2fcb
RH
298 extension. Mark the function as using "sse" so that we emit a real
299 "emms" instruction, rather than the 3dNOW "femms" instruction. */
300
301static const uchar *
302#ifndef __SSE__
303__attribute__((__target__("sse")))
304#endif
305search_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
362static const uchar *
363#ifndef __SSE2__
364__attribute__((__target__("sse2")))
365#endif
366search_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
6f173e52 413#ifdef HAVE_SSE4
246a2fcb
RH
414/* A version of the fast scanner using SSE 4.2 vectorized string insns. */
415
416static const uchar *
417#ifndef __SSE4_2__
418__attribute__((__target__("sse4.2")))
419#endif
420search_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
6f173e52
RH
468#else
469/* Work around out-dated assemblers without sse4 support. */
470#define search_line_sse42 search_line_sse2
471#endif
472
246a2fcb
RH
473/* Check the CPU capabilities. */
474
475#include "../gcc/config/i386/cpuid.h"
476
477typedef const uchar * (*search_line_fast_type) (const uchar *, const uchar *);
478static search_line_fast_type search_line_fast;
479
480static void __attribute__((constructor))
481init_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;
ef230b38 491#elif defined(__SSE__)
246a2fcb
RH
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 {
5e70c0b5
UB
508 if (minimum == 1
509 || (edx & (bit_MMXEXT | bit_CMOV)) == (bit_MMXEXT | bit_CMOV))
246a2fcb
RH
510 impl = search_line_mmx;
511 }
512
513 search_line_fast = impl;
514}
515
01956319 516#elif (GCC_VERSION >= 4005) && defined(__ALTIVEC__)
246a2fcb
RH
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
523static const uchar *
524search_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
26aea073
NB
641/* Returns with a logical line that contains no escaped newlines or
642 trigraphs. This is a time-critical inner loop. */
643void
6cf87ca4 644_cpp_clean_line (cpp_reader *pfile)
45b966db 645{
26aea073
NB
646 cpp_buffer *buffer;
647 const uchar *s;
648 uchar c, *d, *p;
87062813 649
26aea073
NB
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;
246a2fcb 654 s = buffer->next_line;
87062813 655
26aea073 656 if (!buffer->from_stage3)
45b966db 657 {
7af45bd4
ILT
658 const uchar *pbackslash = NULL;
659
246a2fcb 660 /* Fast path. This is the common case of an un-escaped line with
d08dcf87
ZW
661 no trigraphs. The primary win here is by not writing any
662 data back to memory until we have to. */
246a2fcb 663 while (1)
d08dcf87 664 {
246a2fcb
RH
665 /* Perform an optimized search for \n, \r, \\, ?. */
666 s = search_line_fast (s, buffer->rlimit);
d08dcf87 667
246a2fcb
RH
668 c = *s;
669 if (c == '\\')
670 {
671 /* Record the location of the backslash and continue. */
672 pbackslash = s++;
d08dcf87 673 }
246a2fcb 674 else if (__builtin_expect (c == '?', 0))
d08dcf87 675 {
246a2fcb
RH
676 if (__builtin_expect (s[1] == '?', false)
677 && _cpp_trigraph_map[s[2]])
d08dcf87 678 {
246a2fcb
RH
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 }
d08dcf87 691 }
246a2fcb
RH
692 /* Not a trigraph. Continue on fast-path. */
693 s++;
d08dcf87 694 }
246a2fcb
RH
695 else
696 break;
d08dcf87
ZW
697 }
698
246a2fcb
RH
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;
26aea073 729
246a2fcb
RH
730 slow_path:
731 while (1)
4a5b68a2 732 {
26aea073
NB
733 c = *++s;
734 *++d = c;
735
736 if (c == '\n' || c == '\r')
737 {
246a2fcb 738 /* Handle DOS line endings. */
26aea073
NB
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
41c32c98 751 add_line_note (buffer, p - 1, p != d ? ' ': '\\');
26aea073
NB
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. */
41c32c98 758 add_line_note (buffer, d, s[2]);
26aea073
NB
759 if (CPP_OPTION (pfile, trigraphs))
760 {
761 *d = _cpp_trigraph_map[s[2]];
762 s += 2;
763 }
764 }
4a5b68a2 765 }
45b966db 766 }
26aea073
NB
767 else
768 {
246a2fcb 769 while (*s != '\n' && *s != '\r')
26aea073 770 s++;
26aea073
NB
771 d = (uchar *) s;
772
773 /* Handle DOS line endings. */
774 if (*s == '\r' && s != buffer->rlimit && s[1] == '\n')
775 s++;
776 }
0d9f234d 777
d08dcf87 778 done:
26aea073 779 *d = '\n';
41c32c98
NB
780 /* A sentinel note that should never be processed. */
781 add_line_note (buffer, d + 1, '\n');
26aea073 782 buffer->next_line = s + 1;
45b966db
ZW
783}
784
a8eb6044
NB
785/* Return true if the trigraph indicated by NOTE should be warned
786 about in a comment. */
787static bool
6cf87ca4 788warn_in_comment (cpp_reader *pfile, _cpp_line_note *note)
a8eb6044
NB
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
6356f892 794 behavior. */
a8eb6044
NB
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
26aea073
NB
813/* Process the notes created by add_line_note as far as the current
814 location. */
815void
6cf87ca4 816_cpp_process_line_notes (cpp_reader *pfile, int in_comment)
45b966db 817{
29401c30
NB
818 cpp_buffer *buffer = pfile->buffer;
819
26aea073 820 for (;;)
041c3194 821 {
26aea073
NB
822 _cpp_line_note *note = &buffer->notes[buffer->cur_note];
823 unsigned int col;
a5c3cccd 824
26aea073
NB
825 if (note->pos > buffer->cur)
826 break;
a5c3cccd 827
26aea073
NB
828 buffer->cur_note++;
829 col = CPP_BUF_COLUMN (buffer, note->pos + 1);
4d6baafa 830
41c32c98 831 if (note->type == '\\' || note->type == ' ')
26aea073 832 {
41c32c98 833 if (note->type == ' ' && !in_comment)
500bee0a 834 cpp_error_with_line (pfile, CPP_DL_WARNING, pfile->line_table->highest_line, col,
26aea073 835 "backslash and newline separated by space");
41c32c98 836
26aea073 837 if (buffer->next_line > buffer->rlimit)
87062813 838 {
500bee0a 839 cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->line_table->highest_line, col,
26aea073
NB
840 "backslash-newline at end of file");
841 /* Prevent "no newline at end of file" warning. */
842 buffer->next_line = buffer->rlimit;
87062813 843 }
26aea073
NB
844
845 buffer->line_base = note->pos;
12f9df4e 846 CPP_INCREMENT_LINE (pfile, 0);
0d9f234d 847 }
41c32c98
NB
848 else if (_cpp_trigraph_map[note->type])
849 {
a8eb6044
NB
850 if (CPP_OPTION (pfile, warn_trigraphs)
851 && (!in_comment || warn_in_comment (pfile, note)))
41c32c98
NB
852 {
853 if (CPP_OPTION (pfile, trigraphs))
87cf0651
SB
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]);
41c32c98 859 else
905bd7b5 860 {
87cf0651
SB
861 cpp_warning_with_line
862 (pfile, CPP_W_TRIGRAPHS,
863 pfile->line_table->highest_line, col,
905bd7b5
GK
864 "trigraph ??%c ignored, use -trigraphs to enable",
865 note->type);
866 }
41c32c98
NB
867 }
868 }
00a81b8b
JM
869 else if (note->type == 0)
870 /* Already processed in lex_raw_string. */;
41c32c98
NB
871 else
872 abort ();
041c3194 873 }
45b966db
ZW
874}
875
0d9f234d
NB
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
6f572ac2
NB
878 nonzero if comment terminated by EOF, zero otherwise.
879
880 Buffer->cur points to the initial asterisk of the comment. */
26aea073 881bool
6cf87ca4 882_cpp_skip_block_comment (cpp_reader *pfile)
45b966db 883{
041c3194 884 cpp_buffer *buffer = pfile->buffer;
d08dcf87
ZW
885 const uchar *cur = buffer->cur;
886 uchar c;
0d9f234d 887
d08dcf87
ZW
888 cur++;
889 if (*cur == '/')
890 cur++;
0d9f234d 891
26aea073
NB
892 for (;;)
893 {
0d9f234d
NB
894 /* People like decorating comments with '*', so check for '/'
895 instead for efficiency. */
d08dcf87
ZW
896 c = *cur++;
897
041c3194 898 if (c == '/')
45b966db 899 {
d08dcf87 900 if (cur[-2] == '*')
0d9f234d 901 break;
041c3194 902
0d9f234d 903 /* Warn about potential nested comments, but not if the '/'
a1f300c0 904 comes immediately before the true comment delimiter.
041c3194 905 Don't bother to get it right across escaped newlines. */
0d9f234d 906 if (CPP_OPTION (pfile, warn_comments)
d08dcf87
ZW
907 && cur[0] == '*' && cur[1] != '/')
908 {
909 buffer->cur = cur;
87cf0651
SB
910 cpp_warning_with_line (pfile, CPP_W_COMMENTS,
911 pfile->line_table->highest_line,
912 CPP_BUF_COL (buffer),
913 "\"/*\" within comment");
d08dcf87 914 }
45b966db 915 }
26aea073
NB
916 else if (c == '\n')
917 {
12f9df4e 918 unsigned int cols;
d08dcf87 919 buffer->cur = cur - 1;
26aea073
NB
920 _cpp_process_line_notes (pfile, true);
921 if (buffer->next_line >= buffer->rlimit)
922 return true;
923 _cpp_clean_line (pfile);
12f9df4e
PB
924
925 cols = buffer->next_line - buffer->line_base;
926 CPP_INCREMENT_LINE (pfile, cols);
927
d08dcf87 928 cur = buffer->cur;
26aea073 929 }
45b966db 930 }
041c3194 931
d08dcf87 932 buffer->cur = cur;
a8eb6044 933 _cpp_process_line_notes (pfile, true);
26aea073 934 return false;
45b966db
ZW
935}
936
480709cc 937/* Skip a C++ line comment, leaving buffer->cur pointing to the
da7d8304 938 terminating newline. Handles escaped newlines. Returns nonzero
480709cc 939 if a multiline comment. */
041c3194 940static int
6cf87ca4 941skip_line_comment (cpp_reader *pfile)
45b966db 942{
cbcff6df 943 cpp_buffer *buffer = pfile->buffer;
1bb64668 944 source_location orig_line = pfile->line_table->highest_line;
041c3194 945
26aea073
NB
946 while (*buffer->cur != '\n')
947 buffer->cur++;
480709cc 948
26aea073 949 _cpp_process_line_notes (pfile, true);
500bee0a 950 return orig_line != pfile->line_table->highest_line;
041c3194 951}
45b966db 952
26aea073 953/* Skips whitespace, saving the next non-whitespace character. */
52fadca8 954static void
6cf87ca4 955skip_whitespace (cpp_reader *pfile, cppchar_t c)
041c3194
ZW
956{
957 cpp_buffer *buffer = pfile->buffer;
f7d151fb 958 bool saw_NUL = false;
45b966db 959
0d9f234d 960 do
041c3194 961 {
91fcd158 962 /* Horizontal space always OK. */
26aea073 963 if (c == ' ' || c == '\t')
0d9f234d 964 ;
0d9f234d 965 /* Just \f \v or \0 left. */
91fcd158 966 else if (c == '\0')
f7d151fb 967 saw_NUL = true;
93c80368 968 else if (pfile->state.in_directive && CPP_PEDANTIC (pfile))
500bee0a 969 cpp_error_with_line (pfile, CPP_DL_PEDWARN, pfile->line_table->highest_line,
ebef4e8c
NB
970 CPP_BUF_COL (buffer),
971 "%s in preprocessing directive",
972 c == '\f' ? "form feed" : "vertical tab");
0d9f234d 973
0d9f234d 974 c = *buffer->cur++;
45b966db 975 }
ec5c56db 976 /* We only want non-vertical space, i.e. ' ' \t \f \v \0. */
0d9f234d
NB
977 while (is_nvspace (c));
978
f7d151fb 979 if (saw_NUL)
0527bc4e 980 cpp_error (pfile, CPP_DL_WARNING, "null character(s) ignored");
f7d151fb 981
480709cc 982 buffer->cur--;
041c3194 983}
45b966db 984
93c80368
NB
985/* See if the characters of a number token are valid in a name (no
986 '.', '+' or '-'). */
987static int
6cf87ca4 988name_p (cpp_reader *pfile, const cpp_string *string)
93c80368
NB
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
df383483 996 return 1;
93c80368
NB
997}
998
50668cf6
GK
999/* After parsing an identifier or other sequence, produce a warning about
1000 sequences not in NFC/NFKC. */
1001static void
1002warn_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. */
c3f829c1 1011 unsigned char *buf = XNEWVEC (unsigned char, cpp_token_len (token));
50668cf6
GK
1012 size_t sz;
1013
1014 sz = cpp_spell_token (pfile, token, buf, false) - buf;
1015 if (NORMALIZE_STATE_RESULT (s) == normalized_C)
87cf0651
SB
1016 cpp_warning_with_line (pfile, CPP_W_NORMALIZE, token->src_loc, 0,
1017 "`%.*s' is not in NFKC", (int) sz, buf);
50668cf6 1018 else
87cf0651
SB
1019 cpp_warning_with_line (pfile, CPP_W_NORMALIZE, token->src_loc, 0,
1020 "`%.*s' is not in NFC", (int) sz, buf);
50668cf6
GK
1021 }
1022}
1023
bced6edf 1024/* Returns TRUE if the sequence starting at buffer->cur is invalid in
1613e52b 1025 an identifier. FIRST is TRUE if this starts an identifier. */
bced6edf 1026static bool
50668cf6
GK
1027forms_identifier_p (cpp_reader *pfile, int first,
1028 struct normalize_state *state)
bced6edf 1029{
1613e52b
NB
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++;
78b8811a 1038 if (CPP_OPTION (pfile, warn_dollars) && !pfile->state.skipping)
1613e52b 1039 {
78b8811a 1040 CPP_OPTION (pfile, warn_dollars) = 0;
0527bc4e 1041 cpp_error (pfile, CPP_DL_PEDWARN, "'$' in identifier or number");
1613e52b
NB
1042 }
1043
1044 return true;
1045 }
bced6edf 1046
1613e52b 1047 /* Is this a syntactically valid UCN? */
af15a2fe 1048 if (CPP_OPTION (pfile, extended_identifiers)
6baba9bb 1049 && *buffer->cur == '\\'
1613e52b 1050 && (buffer->cur[1] == 'u' || buffer->cur[1] == 'U'))
bced6edf 1051 {
1613e52b 1052 buffer->cur += 2;
50668cf6
GK
1053 if (_cpp_valid_ucn (pfile, &buffer->cur, buffer->rlimit, 1 + !first,
1054 state))
1613e52b
NB
1055 return true;
1056 buffer->cur -= 2;
bced6edf 1057 }
bced6edf 1058
1613e52b 1059 return false;
bced6edf
NB
1060}
1061
17e7cb85
KT
1062/* Helper function to get the cpp_hashnode of the identifier BASE. */
1063static cpp_hashnode *
1064lex_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)
87cf0651
SB
1101 cpp_warning (pfile, CPP_W_CXX_OPERATOR_NAMES,
1102 "identifier \"%s\" is a special operator name in C++",
1103 NODE_NAME (result));
17e7cb85
KT
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. */
1111cpp_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
bced6edf 1119/* Lex an identifier starting at BUFFER->CUR - 1. */
0d9f234d 1120static cpp_hashnode *
50668cf6
GK
1121lex_identifier (cpp_reader *pfile, const uchar *base, bool starts_ucn,
1122 struct normalize_state *nst)
45b966db 1123{
93c80368 1124 cpp_hashnode *result;
47e20491 1125 const uchar *cur;
c6e83800
ZW
1126 unsigned int len;
1127 unsigned int hash = HT_HASHSTEP (0, *base);
2c3fcba6 1128
c6e83800 1129 cur = pfile->buffer->cur;
47e20491
GK
1130 if (! starts_ucn)
1131 while (ISIDNUM (*cur))
1132 {
1133 hash = HT_HASHSTEP (hash, *cur);
1134 cur++;
1135 }
1136 pfile->buffer->cur = cur;
50668cf6 1137 if (starts_ucn || forms_identifier_p (pfile, false, nst))
10cf9bde 1138 {
47e20491
GK
1139 /* Slower version for identifiers containing UCNs (or $). */
1140 do {
1141 while (ISIDNUM (*pfile->buffer->cur))
50668cf6
GK
1142 {
1143 pfile->buffer->cur++;
1144 NORMALIZE_STATE_UPDATE_IDNUM (nst);
1145 }
1146 } while (forms_identifier_p (pfile, false, nst));
47e20491
GK
1147 result = _cpp_interpret_identifier (pfile, base,
1148 pfile->buffer->cur - base);
2c3fcba6 1149 }
47e20491
GK
1150 else
1151 {
1152 len = cur - base;
1153 hash = HT_HASHFINISH (hash, len);
bced6edf 1154
2bf41bf0
TT
1155 result = CPP_HASHNODE (ht_lookup_with_hash (pfile->hash_table,
1156 base, len, hash, HT_ALLOC));
47e20491 1157 }
2c3fcba6 1158
bced6edf 1159 /* Rarely, identifiers require diagnostics when lexed. */
2c3fcba6
ZW
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)
0527bc4e 1165 cpp_error (pfile, CPP_DL_ERROR, "attempt to use poisoned \"%s\"",
2c3fcba6
ZW
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)
0527bc4e 1172 cpp_error (pfile, CPP_DL_PEDWARN,
6cf87ca4
ZW
1173 "__VA_ARGS__ can only appear in the expansion"
1174 " of a C99 variadic macro");
3d8b2a98
ILT
1175
1176 /* For -Wc++-compat, warn about use of C++ named operators. */
1177 if (result->flags & NODE_WARN_OPERATOR)
87cf0651
SB
1178 cpp_warning (pfile, CPP_W_CXX_OPERATOR_NAMES,
1179 "identifier \"%s\" is a special operator name in C++",
1180 NODE_NAME (result));
2c3fcba6
ZW
1181 }
1182
1183 return result;
1184}
1185
bced6edf 1186/* Lex a number to NUMBER starting at BUFFER->CUR - 1. */
45b966db 1187static void
50668cf6
GK
1188lex_number (cpp_reader *pfile, cpp_string *number,
1189 struct normalize_state *nst)
45b966db 1190{
562a5c27 1191 const uchar *cur;
bced6edf
NB
1192 const uchar *base;
1193 uchar *dest;
45b966db 1194
bced6edf
NB
1195 base = pfile->buffer->cur - 1;
1196 do
041c3194 1197 {
bced6edf 1198 cur = pfile->buffer->cur;
0d9f234d 1199
bced6edf
NB
1200 /* N.B. ISIDNUM does not include $. */
1201 while (ISIDNUM (*cur) || *cur == '.' || VALID_SIGN (*cur, cur[-1]))
50668cf6
GK
1202 {
1203 cur++;
1204 NORMALIZE_STATE_UPDATE_IDNUM (nst);
1205 }
45b966db 1206
10cf9bde 1207 pfile->buffer->cur = cur;
45b966db 1208 }
50668cf6 1209 while (forms_identifier_p (pfile, false, nst));
93c80368 1210
bced6edf
NB
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;
93c80368
NB
1216}
1217
6338b358
NB
1218/* Create a token of type TYPE with a literal spelling. */
1219static void
6cf87ca4
ZW
1220create_literal (cpp_reader *pfile, cpp_token *token, const uchar *base,
1221 unsigned int len, enum cpp_ttype type)
6338b358
NB
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
00a81b8b
JM
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
1235static void
1236bufring_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
2c6e3f55 1261/* Lexes a raw string. The stored string contains the spelling, including
00a81b8b 1262 double quotes, delimiter string, '(' and ')', any leading
2c6e3f55
JJ
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
1269static void
1270lex_raw_string (cpp_reader *pfile, cpp_token *token, const uchar *base,
1271 const uchar *cur)
1272{
2c6e3f55
JJ
1273 const uchar *raw_prefix;
1274 unsigned int raw_prefix_len = 0;
1275 enum cpp_ttype type;
1276 size_t total_len = 0;
1277 _cpp_buff *first_buff = NULL, *last_buff = NULL;
00a81b8b 1278 _cpp_line_note *note = &pfile->buffer->notes[pfile->buffer->cur_note];
2c6e3f55
JJ
1279
1280 type = (*base == 'L' ? CPP_WSTRING :
1281 *base == 'U' ? CPP_STRING32 :
1282 *base == 'u' ? (base[1] == '8' ? CPP_UTF8STRING : CPP_STRING16)
1283 : CPP_STRING);
1284
1285 raw_prefix = cur + 1;
1286 while (raw_prefix_len < 16)
1287 {
1288 switch (raw_prefix[raw_prefix_len])
1289 {
52150625 1290 case ' ': case '(': case ')': case '\\': case '\t':
2c6e3f55
JJ
1291 case '\v': case '\f': case '\n': default:
1292 break;
1293 /* Basic source charset except the above chars. */
1294 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1295 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
1296 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
1297 case 's': case 't': case 'u': case 'v': case 'w': case 'x':
1298 case 'y': case 'z':
1299 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1300 case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
1301 case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
1302 case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
1303 case 'Y': case 'Z':
1304 case '0': case '1': case '2': case '3': case '4': case '5':
1305 case '6': case '7': case '8': case '9':
52150625 1306 case '_': case '{': case '}': case '#': case '[': case ']':
2c6e3f55
JJ
1307 case '<': case '>': case '%': case ':': case ';': case '.':
1308 case '?': case '*': case '+': case '-': case '/': case '^':
1309 case '&': case '|': case '~': case '!': case '=': case ',':
52150625 1310 case '"': case '\'':
2c6e3f55
JJ
1311 raw_prefix_len++;
1312 continue;
1313 }
1314 break;
1315 }
1316
52150625 1317 if (raw_prefix[raw_prefix_len] != '(')
2c6e3f55
JJ
1318 {
1319 int col = CPP_BUF_COLUMN (pfile->buffer, raw_prefix + raw_prefix_len)
1320 + 1;
1321 if (raw_prefix_len == 16)
1322 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, col,
1323 "raw string delimiter longer than 16 characters");
1324 else
1325 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, col,
1326 "invalid character '%c' in raw string delimiter",
1327 (int) raw_prefix[raw_prefix_len]);
1328 pfile->buffer->cur = raw_prefix - 1;
1329 create_literal (pfile, token, base, raw_prefix - 1 - base, CPP_OTHER);
1330 return;
1331 }
1332
1333 cur = raw_prefix + raw_prefix_len + 1;
1334 for (;;)
1335 {
00a81b8b
JM
1336#define BUF_APPEND(STR,LEN) \
1337 do { \
1338 bufring_append (pfile, (const uchar *)(STR), (LEN), \
1339 &first_buff, &last_buff); \
1340 total_len += (LEN); \
1341 } while (0);
1342
1343 cppchar_t c;
1344
1345 /* If we previously performed any trigraph or line splicing
1346 transformations, undo them within the body of the raw string. */
1347 while (note->pos < cur)
1348 ++note;
1349 for (; note->pos == cur; ++note)
1350 {
1351 switch (note->type)
1352 {
1353 case '\\':
1354 case ' ':
1355 /* Restore backslash followed by newline. */
1356 BUF_APPEND (base, cur - base);
1357 base = cur;
1358 BUF_APPEND ("\\", 1);
1359 after_backslash:
1360 if (note->type == ' ')
1361 {
1362 /* GNU backslash whitespace newline extension. FIXME
1363 could be any sequence of non-vertical space. When we
1364 can properly restore any such sequence, we should mark
1365 this note as handled so _cpp_process_line_notes
1366 doesn't warn. */
1367 BUF_APPEND (" ", 1);
1368 }
1369
1370 BUF_APPEND ("\n", 1);
1371 break;
1372
1373 case 0:
1374 /* Already handled. */
1375 break;
1376
1377 default:
1378 if (_cpp_trigraph_map[note->type])
1379 {
1380 /* Don't warn about this trigraph in
1381 _cpp_process_line_notes, since trigraphs show up as
1382 trigraphs in raw strings. */
d947ada0 1383 uchar type = note->type;
00a81b8b
JM
1384 note->type = 0;
1385
1386 if (!CPP_OPTION (pfile, trigraphs))
1387 /* If we didn't convert the trigraph in the first
1388 place, don't do anything now either. */
1389 break;
1390
1391 BUF_APPEND (base, cur - base);
1392 base = cur;
1393 BUF_APPEND ("??", 2);
1394
1395 /* ??/ followed by newline gets two line notes, one for
1396 the trigraph and one for the backslash/newline. */
1397 if (type == '/' && note[1].pos == cur)
1398 {
1399 if (note[1].type != '\\'
1400 && note[1].type != ' ')
1401 abort ();
1402 BUF_APPEND ("/", 1);
1403 ++note;
1404 goto after_backslash;
1405 }
1406 /* The ) from ??) could be part of the suffix. */
1407 else if (type == ')'
1408 && strncmp ((const char *) cur+1,
1409 (const char *) raw_prefix,
1410 raw_prefix_len) == 0
1411 && cur[raw_prefix_len+1] == '"')
1412 {
6cfae070
JJ
1413 BUF_APPEND (")", 1);
1414 base++;
1415 cur += raw_prefix_len + 2;
00a81b8b
JM
1416 goto break_outer_loop;
1417 }
1418 else
1419 {
1420 /* Skip the replacement character. */
1421 base = ++cur;
1422 BUF_APPEND (&type, 1);
1423 }
1424 }
1425 else
1426 abort ();
1427 break;
1428 }
1429 }
1430 c = *cur++;
2c6e3f55 1431
52150625 1432 if (c == ')'
2c6e3f55
JJ
1433 && strncmp ((const char *) cur, (const char *) raw_prefix,
1434 raw_prefix_len) == 0
1435 && cur[raw_prefix_len] == '"')
1436 {
1437 cur += raw_prefix_len + 1;
1438 break;
1439 }
1440 else if (c == '\n')
1441 {
1442 if (pfile->state.in_directive
1443 || pfile->state.parsing_args
1444 || pfile->state.in_deferred_pragma)
1445 {
1446 cur--;
1447 type = CPP_OTHER;
1448 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, 0,
1449 "unterminated raw string");
1450 break;
1451 }
1452
00a81b8b 1453 BUF_APPEND (base, cur - base);
2c6e3f55
JJ
1454
1455 if (pfile->buffer->cur < pfile->buffer->rlimit)
1456 CPP_INCREMENT_LINE (pfile, 0);
1457 pfile->buffer->need_line = true;
1458
00a81b8b
JM
1459 pfile->buffer->cur = cur-1;
1460 _cpp_process_line_notes (pfile, false);
2c6e3f55
JJ
1461 if (!_cpp_get_fresh_line (pfile))
1462 {
1463 source_location src_loc = token->src_loc;
1464 token->type = CPP_EOF;
1465 /* Tell the compiler the line number of the EOF token. */
1466 token->src_loc = pfile->line_table->highest_line;
1467 token->flags = BOL;
1468 if (first_buff != NULL)
1469 _cpp_release_buff (pfile, first_buff);
1470 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
1471 "unterminated raw string");
1472 return;
1473 }
1474
1475 cur = base = pfile->buffer->cur;
00a81b8b 1476 note = &pfile->buffer->notes[pfile->buffer->cur_note];
2c6e3f55 1477 }
2c6e3f55 1478 }
00a81b8b 1479 break_outer_loop:
2c6e3f55 1480
2c6e3f55
JJ
1481 pfile->buffer->cur = cur;
1482 if (first_buff == NULL)
1483 create_literal (pfile, token, base, cur - base, type);
1484 else
1485 {
1486 uchar *dest = _cpp_unaligned_alloc (pfile, total_len + (cur - base) + 1);
1487
1488 token->type = type;
1489 token->val.str.len = total_len + (cur - base);
1490 token->val.str.text = dest;
1491 last_buff = first_buff;
1492 while (last_buff != NULL)
1493 {
1494 memcpy (dest, last_buff->base,
1495 BUFF_FRONT (last_buff) - last_buff->base);
1496 dest += BUFF_FRONT (last_buff) - last_buff->base;
1497 last_buff = last_buff->next;
1498 }
1499 _cpp_release_buff (pfile, first_buff);
1500 memcpy (dest, base, cur - base);
1501 dest[cur - base] = '\0';
1502 }
1503}
1504
bced6edf 1505/* Lexes a string, character constant, or angle-bracketed header file
6338b358 1506 name. The stored string contains the spelling, including opening
2c6e3f55
JJ
1507 quote and any leading 'L', 'u', 'U' or 'u8' and optional
1508 'R' modifier. It returns the type of the literal, or CPP_OTHER
1509 if it was not properly terminated, or CPP_LESS for an unterminated
1510 header name which must be relexed as normal tokens.
6338b358
NB
1511
1512 The spelling is NUL-terminated, but it is not guaranteed that this
1513 is the first NUL since embedded NULs are preserved. */
041c3194 1514static void
6cf87ca4 1515lex_string (cpp_reader *pfile, cpp_token *token, const uchar *base)
45b966db 1516{
6338b358
NB
1517 bool saw_NUL = false;
1518 const uchar *cur;
bced6edf 1519 cppchar_t terminator;
6338b358
NB
1520 enum cpp_ttype type;
1521
1522 cur = base;
1523 terminator = *cur++;
2c6e3f55 1524 if (terminator == 'L' || terminator == 'U')
6338b358 1525 terminator = *cur++;
2c6e3f55
JJ
1526 else if (terminator == 'u')
1527 {
1528 terminator = *cur++;
1529 if (terminator == '8')
1530 terminator = *cur++;
1531 }
1532 if (terminator == 'R')
1533 {
1534 lex_raw_string (pfile, token, base, cur);
1535 return;
1536 }
1537 if (terminator == '"')
b6baa67d
KVH
1538 type = (*base == 'L' ? CPP_WSTRING :
1539 *base == 'U' ? CPP_STRING32 :
2c6e3f55
JJ
1540 *base == 'u' ? (base[1] == '8' ? CPP_UTF8STRING : CPP_STRING16)
1541 : CPP_STRING);
6338b358 1542 else if (terminator == '\'')
b6baa67d
KVH
1543 type = (*base == 'L' ? CPP_WCHAR :
1544 *base == 'U' ? CPP_CHAR32 :
1545 *base == 'u' ? CPP_CHAR16 : CPP_CHAR);
6338b358
NB
1546 else
1547 terminator = '>', type = CPP_HEADER_NAME;
93c80368 1548
0d9f234d 1549 for (;;)
45b966db 1550 {
6338b358 1551 cppchar_t c = *cur++;
7868b4a2 1552
6f572ac2 1553 /* In #include-style directives, terminators are not escapable. */
6338b358
NB
1554 if (c == '\\' && !pfile->state.angled_headers && *cur != '\n')
1555 cur++;
1556 else if (c == terminator)
bced6edf 1557 break;
6338b358 1558 else if (c == '\n')
0d9f234d 1559 {
6338b358 1560 cur--;
4bb09c26
JM
1561 /* Unmatched quotes always yield undefined behavior, but
1562 greedy lexing means that what appears to be an unterminated
1563 header name may actually be a legitimate sequence of tokens. */
1564 if (terminator == '>')
1565 {
1566 token->type = CPP_LESS;
1567 return;
1568 }
6338b358
NB
1569 type = CPP_OTHER;
1570 break;
45b966db 1571 }
6338b358
NB
1572 else if (c == '\0')
1573 saw_NUL = true;
45b966db
ZW
1574 }
1575
6338b358 1576 if (saw_NUL && !pfile->state.skipping)
0527bc4e
JDA
1577 cpp_error (pfile, CPP_DL_WARNING,
1578 "null character(s) preserved in literal");
45b966db 1579
c663e301
JM
1580 if (type == CPP_OTHER && CPP_OPTION (pfile, lang) != CLK_ASM)
1581 cpp_error (pfile, CPP_DL_PEDWARN, "missing terminating %c character",
1582 (int) terminator);
1583
6338b358
NB
1584 pfile->buffer->cur = cur;
1585 create_literal (pfile, token, base, cur - base, type);
0d9f234d 1586}
041c3194 1587
631d0d36
MG
1588/* Return the comment table. The client may not make any assumption
1589 about the ordering of the table. */
1590cpp_comment_table *
1591cpp_get_comments (cpp_reader *pfile)
1592{
1593 return &pfile->comments;
1594}
1595
1596/* Append a comment to the end of the comment table. */
1597static void
1598store_comment (cpp_reader *pfile, cpp_token *token)
1599{
1600 int len;
1601
1602 if (pfile->comments.allocated == 0)
1603 {
1604 pfile->comments.allocated = 256;
1605 pfile->comments.entries = (cpp_comment *) xmalloc
1606 (pfile->comments.allocated * sizeof (cpp_comment));
1607 }
1608
1609 if (pfile->comments.count == pfile->comments.allocated)
1610 {
1611 pfile->comments.allocated *= 2;
1612 pfile->comments.entries = (cpp_comment *) xrealloc
1613 (pfile->comments.entries,
1614 pfile->comments.allocated * sizeof (cpp_comment));
1615 }
1616
1617 len = token->val.str.len;
1618
1619 /* Copy comment. Note, token may not be NULL terminated. */
1620 pfile->comments.entries[pfile->comments.count].comment =
1621 (char *) xmalloc (sizeof (char) * (len + 1));
1622 memcpy (pfile->comments.entries[pfile->comments.count].comment,
1623 token->val.str.text, len);
1624 pfile->comments.entries[pfile->comments.count].comment[len] = '\0';
1625
1626 /* Set source location. */
1627 pfile->comments.entries[pfile->comments.count].sloc = token->src_loc;
1628
1629 /* Increment the count of entries in the comment table. */
1630 pfile->comments.count++;
1631}
1632
93c80368 1633/* The stored comment includes the comment start and any terminator. */
9e62c811 1634static void
6cf87ca4
ZW
1635save_comment (cpp_reader *pfile, cpp_token *token, const unsigned char *from,
1636 cppchar_t type)
9e62c811 1637{
041c3194 1638 unsigned char *buffer;
651a20b5 1639 unsigned int len, clen, i;
df383483 1640
1c6d33ef 1641 len = pfile->buffer->cur - from + 1; /* + 1 for the initial '/'. */
480709cc 1642
3542203b
NB
1643 /* C++ comments probably (not definitely) have moved past a new
1644 line, which we don't want to save in the comment. */
480709cc 1645 if (is_vspace (pfile->buffer->cur[-1]))
3542203b 1646 len--;
477cdac7 1647
651a20b5
KT
1648 /* If we are currently in a directive or in argument parsing, then
1649 we need to store all C++ comments as C comments internally, and
1650 so we need to allocate a little extra space in that case.
477cdac7
JT
1651
1652 Note that the only time we encounter a directive here is
1653 when we are saving comments in a "#define". */
651a20b5
KT
1654 clen = ((pfile->state.in_directive || pfile->state.parsing_args)
1655 && type == '/') ? len + 2 : len;
477cdac7
JT
1656
1657 buffer = _cpp_unaligned_alloc (pfile, clen);
df383483 1658
041c3194 1659 token->type = CPP_COMMENT;
477cdac7 1660 token->val.str.len = clen;
0d9f234d 1661 token->val.str.text = buffer;
45b966db 1662
1c6d33ef
NB
1663 buffer[0] = '/';
1664 memcpy (buffer + 1, from, len - 1);
477cdac7 1665
1eeeb6a4 1666 /* Finish conversion to a C comment, if necessary. */
651a20b5 1667 if ((pfile->state.in_directive || pfile->state.parsing_args) && type == '/')
477cdac7
JT
1668 {
1669 buffer[1] = '*';
1670 buffer[clen - 2] = '*';
1671 buffer[clen - 1] = '/';
651a20b5
KT
1672 /* As there can be in a C++ comments illegal sequences for C comments
1673 we need to filter them out. */
1674 for (i = 2; i < (clen - 2); i++)
1675 if (buffer[i] == '/' && (buffer[i - 1] == '*' || buffer[i + 1] == '*'))
1676 buffer[i] = '|';
477cdac7 1677 }
631d0d36
MG
1678
1679 /* Finally store this comment for use by clients of libcpp. */
1680 store_comment (pfile, token);
0d9f234d 1681}
45b966db 1682
5fddcffc
NB
1683/* Allocate COUNT tokens for RUN. */
1684void
6cf87ca4 1685_cpp_init_tokenrun (tokenrun *run, unsigned int count)
5fddcffc 1686{
72bb2c39 1687 run->base = XNEWVEC (cpp_token, count);
5fddcffc
NB
1688 run->limit = run->base + count;
1689 run->next = NULL;
1690}
1691
1692/* Returns the next tokenrun, or creates one if there is none. */
1693static tokenrun *
6cf87ca4 1694next_tokenrun (tokenrun *run)
5fddcffc
NB
1695{
1696 if (run->next == NULL)
1697 {
72bb2c39 1698 run->next = XNEW (tokenrun);
bdcbe496 1699 run->next->prev = run;
5fddcffc
NB
1700 _cpp_init_tokenrun (run->next, 250);
1701 }
1702
1703 return run->next;
1704}
1705
5950c3c9
BE
1706/* Look ahead in the input stream. */
1707const cpp_token *
1708cpp_peek_token (cpp_reader *pfile, int index)
1709{
1710 cpp_context *context = pfile->context;
1711 const cpp_token *peektok;
1712 int count;
1713
1714 /* First, scan through any pending cpp_context objects. */
1715 while (context->prev)
1716 {
1717 ptrdiff_t sz = (context->direct_p
1718 ? LAST (context).token - FIRST (context).token
1719 : LAST (context).ptoken - FIRST (context).ptoken);
1720
1721 if (index < (int) sz)
1722 return (context->direct_p
1723 ? FIRST (context).token + index
1724 : *(FIRST (context).ptoken + index));
1725
1726 index -= (int) sz;
1727 context = context->prev;
1728 }
1729
1730 /* We will have to read some new tokens after all (and do so
1731 without invalidating preceding tokens). */
1732 count = index;
1733 pfile->keep_tokens++;
1734
1735 do
1736 {
1737 peektok = _cpp_lex_token (pfile);
1738 if (peektok->type == CPP_EOF)
1739 return peektok;
1740 }
1741 while (index--);
1742
1743 _cpp_backup_tokens_direct (pfile, count + 1);
1744 pfile->keep_tokens--;
1745
1746 return peektok;
1747}
1748
4ed5bcfb
NB
1749/* Allocate a single token that is invalidated at the same time as the
1750 rest of the tokens on the line. Has its line and col set to the
1751 same as the last lexed token, so that diagnostics appear in the
1752 right place. */
1753cpp_token *
6cf87ca4 1754_cpp_temp_token (cpp_reader *pfile)
4ed5bcfb
NB
1755{
1756 cpp_token *old, *result;
5950c3c9
BE
1757 ptrdiff_t sz = pfile->cur_run->limit - pfile->cur_token;
1758 ptrdiff_t la = (ptrdiff_t) pfile->lookaheads;
4ed5bcfb
NB
1759
1760 old = pfile->cur_token - 1;
5950c3c9
BE
1761 /* Any pre-existing lookaheads must not be clobbered. */
1762 if (la)
1763 {
1764 if (sz <= la)
1765 {
1766 tokenrun *next = next_tokenrun (pfile->cur_run);
1767
1768 if (sz < la)
1769 memmove (next->base + 1, next->base,
1770 (la - sz) * sizeof (cpp_token));
1771
1772 next->base[0] = pfile->cur_run->limit[-1];
1773 }
1774
1775 if (sz > 1)
1776 memmove (pfile->cur_token + 1, pfile->cur_token,
1777 MIN (la, sz - 1) * sizeof (cpp_token));
1778 }
1779
1780 if (!sz && pfile->cur_token == pfile->cur_run->limit)
4ed5bcfb
NB
1781 {
1782 pfile->cur_run = next_tokenrun (pfile->cur_run);
1783 pfile->cur_token = pfile->cur_run->base;
1784 }
1785
1786 result = pfile->cur_token++;
12f9df4e 1787 result->src_loc = old->src_loc;
4ed5bcfb
NB
1788 return result;
1789}
1790
14baae01
NB
1791/* Lex a token into RESULT (external interface). Takes care of issues
1792 like directive handling, token lookahead, multiple include
a1f300c0 1793 optimization and skipping. */
345894b4 1794const cpp_token *
6cf87ca4 1795_cpp_lex_token (cpp_reader *pfile)
5fddcffc 1796{
bdcbe496 1797 cpp_token *result;
5fddcffc 1798
bdcbe496 1799 for (;;)
5fddcffc 1800 {
bdcbe496 1801 if (pfile->cur_token == pfile->cur_run->limit)
5fddcffc 1802 {
bdcbe496
NB
1803 pfile->cur_run = next_tokenrun (pfile->cur_run);
1804 pfile->cur_token = pfile->cur_run->base;
5fddcffc 1805 }
ee380365
TT
1806 /* We assume that the current token is somewhere in the current
1807 run. */
1808 if (pfile->cur_token < pfile->cur_run->base
1809 || pfile->cur_token >= pfile->cur_run->limit)
1810 abort ();
5fddcffc 1811
bdcbe496 1812 if (pfile->lookaheads)
14baae01
NB
1813 {
1814 pfile->lookaheads--;
1815 result = pfile->cur_token++;
1816 }
bdcbe496 1817 else
14baae01 1818 result = _cpp_lex_direct (pfile);
bdcbe496
NB
1819
1820 if (result->flags & BOL)
5fddcffc 1821 {
bdcbe496
NB
1822 /* Is this a directive. If _cpp_handle_directive returns
1823 false, it is an assembler #. */
1824 if (result->type == CPP_HASH
e808ec9c
NB
1825 /* 6.10.3 p 11: Directives in a list of macro arguments
1826 gives undefined behavior. This implementation
1827 handles the directive as normal. */
bc4071dd 1828 && pfile->state.parsing_args != 1)
21b11495 1829 {
bc4071dd 1830 if (_cpp_handle_directive (pfile, result->flags & PREV_WHITE))
21b11495 1831 {
bc4071dd
RH
1832 if (pfile->directive_result.type == CPP_PADDING)
1833 continue;
21b11495 1834 result = &pfile->directive_result;
21b11495
ZW
1835 }
1836 }
bc4071dd
RH
1837 else if (pfile->state.in_deferred_pragma)
1838 result = &pfile->directive_result;
21b11495 1839
97293897 1840 if (pfile->cb.line_change && !pfile->state.skipping)
6cf87ca4 1841 pfile->cb.line_change (pfile, result, pfile->state.parsing_args);
5fddcffc 1842 }
5fddcffc 1843
bdcbe496 1844 /* We don't skip tokens in directives. */
bc4071dd 1845 if (pfile->state.in_directive || pfile->state.in_deferred_pragma)
bdcbe496 1846 break;
5fddcffc 1847
bdcbe496 1848 /* Outside a directive, invalidate controlling macros. At file
14baae01 1849 EOF, _cpp_lex_direct takes care of popping the buffer, so we never
6356f892 1850 get here and MI optimization works. */
5fddcffc 1851 pfile->mi_valid = false;
bdcbe496
NB
1852
1853 if (!pfile->state.skipping || result->type == CPP_EOF)
1854 break;
5fddcffc
NB
1855 }
1856
345894b4 1857 return result;
5fddcffc
NB
1858}
1859
26aea073
NB
1860/* Returns true if a fresh line has been loaded. */
1861bool
6cf87ca4 1862_cpp_get_fresh_line (cpp_reader *pfile)
004cb263 1863{
22234f56
PB
1864 int return_at_eof;
1865
26aea073
NB
1866 /* We can't get a new line until we leave the current directive. */
1867 if (pfile->state.in_directive)
1868 return false;
df383483 1869
26aea073 1870 for (;;)
1a76916c 1871 {
26aea073 1872 cpp_buffer *buffer = pfile->buffer;
1a76916c 1873
26aea073
NB
1874 if (!buffer->need_line)
1875 return true;
1876
1877 if (buffer->next_line < buffer->rlimit)
004cb263 1878 {
26aea073
NB
1879 _cpp_clean_line (pfile);
1880 return true;
1881 }
004cb263 1882
26aea073
NB
1883 /* First, get out of parsing arguments state. */
1884 if (pfile->state.parsing_args)
1885 return false;
1886
1887 /* End of buffer. Non-empty files should end in a newline. */
1888 if (buffer->buf != buffer->rlimit
1889 && buffer->next_line > buffer->rlimit
1890 && !buffer->from_stage3)
1891 {
ed0e74e0 1892 /* Clip to buffer size. */
26aea073 1893 buffer->next_line = buffer->rlimit;
26aea073 1894 }
22234f56
PB
1895
1896 return_at_eof = buffer->return_at_eof;
26aea073 1897 _cpp_pop_buffer (pfile);
22234f56 1898 if (pfile->buffer == NULL || return_at_eof)
a506c55c 1899 return false;
26aea073 1900 }
004cb263
NB
1901}
1902
6f572ac2
NB
1903#define IF_NEXT_IS(CHAR, THEN_TYPE, ELSE_TYPE) \
1904 do \
1905 { \
1906 result->type = ELSE_TYPE; \
1907 if (*buffer->cur == CHAR) \
1908 buffer->cur++, result->type = THEN_TYPE; \
1909 } \
1910 while (0)
480709cc 1911
14baae01
NB
1912/* Lex a token into pfile->cur_token, which is also incremented, to
1913 get diagnostics pointing to the correct location.
1914
1915 Does not handle issues such as token lookahead, multiple-include
f1ba665b 1916 optimization, directives, skipping etc. This function is only
14baae01
NB
1917 suitable for use by _cpp_lex_token, and in special cases like
1918 lex_expansion_token which doesn't care for any of these issues.
1919
1920 When meeting a newline, returns CPP_EOF if parsing a directive,
1921 otherwise returns to the start of the token buffer if permissible.
1922 Returns the location of the lexed token. */
1923cpp_token *
6cf87ca4 1924_cpp_lex_direct (cpp_reader *pfile)
45b966db 1925{
0d9f234d 1926 cppchar_t c;
adb84b42 1927 cpp_buffer *buffer;
0d9f234d 1928 const unsigned char *comment_start;
14baae01 1929 cpp_token *result = pfile->cur_token++;
9ec7291f 1930
5fddcffc 1931 fresh_line:
26aea073 1932 result->flags = 0;
2be570f9 1933 buffer = pfile->buffer;
a506c55c 1934 if (buffer->need_line)
26aea073 1935 {
bc4071dd
RH
1936 if (pfile->state.in_deferred_pragma)
1937 {
1938 result->type = CPP_PRAGMA_EOL;
1939 pfile->state.in_deferred_pragma = false;
1940 if (!pfile->state.pragma_allow_expansion)
1941 pfile->state.prevent_expansion--;
1942 return result;
1943 }
26aea073
NB
1944 if (!_cpp_get_fresh_line (pfile))
1945 {
1946 result->type = CPP_EOF;
9ff7868d
NB
1947 if (!pfile->state.in_directive)
1948 {
1949 /* Tell the compiler the line number of the EOF token. */
500bee0a 1950 result->src_loc = pfile->line_table->highest_line;
9ff7868d
NB
1951 result->flags = BOL;
1952 }
26aea073
NB
1953 return result;
1954 }
1955 if (!pfile->keep_tokens)
1956 {
1957 pfile->cur_run = &pfile->base_run;
1958 result = pfile->base_run.base;
1959 pfile->cur_token = result + 1;
1960 }
1961 result->flags = BOL;
1962 if (pfile->state.parsing_args == 2)
1963 result->flags |= PREV_WHITE;
1964 }
a506c55c 1965 buffer = pfile->buffer;
5fddcffc 1966 update_tokens_line:
500bee0a 1967 result->src_loc = pfile->line_table->highest_line;
041c3194 1968
5fddcffc 1969 skipped_white:
26aea073
NB
1970 if (buffer->cur >= buffer->notes[buffer->cur_note].pos
1971 && !pfile->overlaid_buffer)
1972 {
1973 _cpp_process_line_notes (pfile, false);
500bee0a 1974 result->src_loc = pfile->line_table->highest_line;
26aea073 1975 }
480709cc 1976 c = *buffer->cur++;
12f9df4e 1977
3f6ced10
GC
1978 result->src_loc = linemap_position_for_column (pfile->line_table,
1979 CPP_BUF_COLUMN (buffer, buffer->cur));
5fddcffc 1980
0d9f234d 1981 switch (c)
45b966db 1982 {
4d6baafa
NB
1983 case ' ': case '\t': case '\f': case '\v': case '\0':
1984 result->flags |= PREV_WHITE;
26aea073
NB
1985 skip_whitespace (pfile, c);
1986 goto skipped_white;
0d9f234d 1987
26aea073 1988 case '\n':
12f9df4e
PB
1989 if (buffer->cur < buffer->rlimit)
1990 CPP_INCREMENT_LINE (pfile, 0);
26aea073
NB
1991 buffer->need_line = true;
1992 goto fresh_line;
46d07497 1993
0d9f234d
NB
1994 case '0': case '1': case '2': case '3': case '4':
1995 case '5': case '6': case '7': case '8': case '9':
50668cf6
GK
1996 {
1997 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
1998 result->type = CPP_NUMBER;
1999 lex_number (pfile, &result->val.str, &nst);
2000 warn_about_normalization (pfile, result, &nst);
2001 break;
2002 }
46d07497 2003
0abc6a6a 2004 case 'L':
b6baa67d
KVH
2005 case 'u':
2006 case 'U':
2c6e3f55
JJ
2007 case 'R':
2008 /* 'L', 'u', 'U', 'u8' or 'R' may introduce wide characters,
2009 wide strings or raw strings. */
a48e3dd1
JM
2010 if (c == 'L' || CPP_OPTION (pfile, rliterals)
2011 || (c != 'R' && CPP_OPTION (pfile, uliterals)))
bced6edf 2012 {
2c6e3f55
JJ
2013 if ((*buffer->cur == '\'' && c != 'R')
2014 || *buffer->cur == '"'
2015 || (*buffer->cur == 'R'
2016 && c != 'R'
2017 && buffer->cur[1] == '"'
a48e3dd1 2018 && CPP_OPTION (pfile, rliterals))
2c6e3f55
JJ
2019 || (*buffer->cur == '8'
2020 && c == 'u'
2021 && (buffer->cur[1] == '"'
a48e3dd1
JM
2022 || (buffer->cur[1] == 'R' && buffer->cur[2] == '"'
2023 && CPP_OPTION (pfile, rliterals)))))
b6baa67d
KVH
2024 {
2025 lex_string (pfile, result, buffer->cur - 1);
2026 break;
2027 }
bced6edf 2028 }
df383483 2029 /* Fall through. */
0abc6a6a 2030
0d9f234d
NB
2031 case '_':
2032 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2033 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2034 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
b6baa67d 2035 case 's': case 't': case 'v': case 'w': case 'x':
0d9f234d
NB
2036 case 'y': case 'z':
2037 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
0abc6a6a 2038 case 'G': case 'H': case 'I': case 'J': case 'K':
2c6e3f55 2039 case 'M': case 'N': case 'O': case 'P': case 'Q':
b6baa67d 2040 case 'S': case 'T': case 'V': case 'W': case 'X':
0d9f234d
NB
2041 case 'Y': case 'Z':
2042 result->type = CPP_NAME;
50668cf6
GK
2043 {
2044 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
9a0c6187
JM
2045 result->val.node.node = lex_identifier (pfile, buffer->cur - 1, false,
2046 &nst);
50668cf6
GK
2047 warn_about_normalization (pfile, result, &nst);
2048 }
0d9f234d 2049
0d9f234d 2050 /* Convert named operators to their proper types. */
9a0c6187 2051 if (result->val.node.node->flags & NODE_OPERATOR)
0d9f234d
NB
2052 {
2053 result->flags |= NAMED_OP;
9a0c6187 2054 result->type = (enum cpp_ttype) result->val.node.node->directive_index;
0d9f234d
NB
2055 }
2056 break;
2057
2058 case '\'':
2059 case '"':
6338b358 2060 lex_string (pfile, result, buffer->cur - 1);
0d9f234d 2061 break;
041c3194 2062
0d9f234d 2063 case '/':
1c6d33ef
NB
2064 /* A potential block or line comment. */
2065 comment_start = buffer->cur;
6f572ac2
NB
2066 c = *buffer->cur;
2067
1c6d33ef
NB
2068 if (c == '*')
2069 {
26aea073 2070 if (_cpp_skip_block_comment (pfile))
0527bc4e 2071 cpp_error (pfile, CPP_DL_ERROR, "unterminated comment");
0d9f234d 2072 }
480709cc 2073 else if (c == '/' && (CPP_OPTION (pfile, cplusplus_comments)
12f9df4e 2074 || cpp_in_system_header (pfile)))
0d9f234d 2075 {
bdb05a7b
NB
2076 /* Warn about comments only if pedantically GNUC89, and not
2077 in system headers. */
2078 if (CPP_OPTION (pfile, lang) == CLK_GNUC89 && CPP_PEDANTIC (pfile)
a94c1199 2079 && ! buffer->warned_cplusplus_comments)
041c3194 2080 {
0527bc4e 2081 cpp_error (pfile, CPP_DL_PEDWARN,
56508306 2082 "C++ style comments are not allowed in ISO C90");
0527bc4e 2083 cpp_error (pfile, CPP_DL_PEDWARN,
ebef4e8c 2084 "(this will be reported only once per input file)");
1c6d33ef
NB
2085 buffer->warned_cplusplus_comments = 1;
2086 }
0d9f234d 2087
01ef6563 2088 if (skip_line_comment (pfile) && CPP_OPTION (pfile, warn_comments))
87cf0651 2089 cpp_warning (pfile, CPP_W_COMMENTS, "multi-line comment");
1c6d33ef 2090 }
480709cc
NB
2091 else if (c == '=')
2092 {
6f572ac2 2093 buffer->cur++;
480709cc
NB
2094 result->type = CPP_DIV_EQ;
2095 break;
2096 }
2097 else
2098 {
480709cc
NB
2099 result->type = CPP_DIV;
2100 break;
2101 }
0d9f234d 2102
1c6d33ef
NB
2103 if (!pfile->state.save_comments)
2104 {
2105 result->flags |= PREV_WHITE;
5fddcffc 2106 goto update_tokens_line;
0d9f234d 2107 }
1c6d33ef
NB
2108
2109 /* Save the comment as a token in its own right. */
477cdac7 2110 save_comment (pfile, result, comment_start, c);
bdcbe496 2111 break;
0d9f234d
NB
2112
2113 case '<':
2114 if (pfile->state.angled_headers)
2115 {
6338b358 2116 lex_string (pfile, result, buffer->cur - 1);
4bb09c26
JM
2117 if (result->type != CPP_LESS)
2118 break;
0d9f234d 2119 }
45b966db 2120
6f572ac2
NB
2121 result->type = CPP_LESS;
2122 if (*buffer->cur == '=')
2123 buffer->cur++, result->type = CPP_LESS_EQ;
2124 else if (*buffer->cur == '<')
0d9f234d 2125 {
6f572ac2
NB
2126 buffer->cur++;
2127 IF_NEXT_IS ('=', CPP_LSHIFT_EQ, CPP_LSHIFT);
0d9f234d 2128 }
6f572ac2 2129 else if (CPP_OPTION (pfile, digraphs))
480709cc 2130 {
6f572ac2
NB
2131 if (*buffer->cur == ':')
2132 {
2133 buffer->cur++;
2134 result->flags |= DIGRAPH;
2135 result->type = CPP_OPEN_SQUARE;
2136 }
2137 else if (*buffer->cur == '%')
2138 {
2139 buffer->cur++;
2140 result->flags |= DIGRAPH;
2141 result->type = CPP_OPEN_BRACE;
2142 }
480709cc 2143 }
0d9f234d
NB
2144 break;
2145
2146 case '>':
6f572ac2
NB
2147 result->type = CPP_GREATER;
2148 if (*buffer->cur == '=')
2149 buffer->cur++, result->type = CPP_GREATER_EQ;
2150 else if (*buffer->cur == '>')
0d9f234d 2151 {
6f572ac2
NB
2152 buffer->cur++;
2153 IF_NEXT_IS ('=', CPP_RSHIFT_EQ, CPP_RSHIFT);
2154 }
0d9f234d
NB
2155 break;
2156
cbcff6df 2157 case '%':
6f572ac2
NB
2158 result->type = CPP_MOD;
2159 if (*buffer->cur == '=')
2160 buffer->cur++, result->type = CPP_MOD_EQ;
2161 else if (CPP_OPTION (pfile, digraphs))
480709cc 2162 {
6f572ac2 2163 if (*buffer->cur == ':')
480709cc 2164 {
6f572ac2
NB
2165 buffer->cur++;
2166 result->flags |= DIGRAPH;
2167 result->type = CPP_HASH;
2168 if (*buffer->cur == '%' && buffer->cur[1] == ':')
9a0c6187 2169 buffer->cur += 2, result->type = CPP_PASTE, result->val.token_no = 0;
6f572ac2
NB
2170 }
2171 else if (*buffer->cur == '>')
2172 {
2173 buffer->cur++;
2174 result->flags |= DIGRAPH;
2175 result->type = CPP_CLOSE_BRACE;
480709cc 2176 }
480709cc 2177 }
0d9f234d
NB
2178 break;
2179
cbcff6df 2180 case '.':
480709cc 2181 result->type = CPP_DOT;
6f572ac2 2182 if (ISDIGIT (*buffer->cur))
480709cc 2183 {
50668cf6 2184 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
480709cc 2185 result->type = CPP_NUMBER;
50668cf6
GK
2186 lex_number (pfile, &result->val.str, &nst);
2187 warn_about_normalization (pfile, result, &nst);
480709cc 2188 }
6f572ac2
NB
2189 else if (*buffer->cur == '.' && buffer->cur[1] == '.')
2190 buffer->cur += 2, result->type = CPP_ELLIPSIS;
2191 else if (*buffer->cur == '*' && CPP_OPTION (pfile, cplusplus))
2192 buffer->cur++, result->type = CPP_DOT_STAR;
0d9f234d 2193 break;
45b966db 2194
0d9f234d 2195 case '+':
6f572ac2
NB
2196 result->type = CPP_PLUS;
2197 if (*buffer->cur == '+')
2198 buffer->cur++, result->type = CPP_PLUS_PLUS;
2199 else if (*buffer->cur == '=')
2200 buffer->cur++, result->type = CPP_PLUS_EQ;
0d9f234d 2201 break;
04e3ec78 2202
0d9f234d 2203 case '-':
6f572ac2
NB
2204 result->type = CPP_MINUS;
2205 if (*buffer->cur == '>')
0d9f234d 2206 {
6f572ac2 2207 buffer->cur++;
480709cc 2208 result->type = CPP_DEREF;
6f572ac2
NB
2209 if (*buffer->cur == '*' && CPP_OPTION (pfile, cplusplus))
2210 buffer->cur++, result->type = CPP_DEREF_STAR;
480709cc 2211 }
6f572ac2
NB
2212 else if (*buffer->cur == '-')
2213 buffer->cur++, result->type = CPP_MINUS_MINUS;
2214 else if (*buffer->cur == '=')
2215 buffer->cur++, result->type = CPP_MINUS_EQ;
0d9f234d 2216 break;
45b966db 2217
0d9f234d 2218 case '&':
6f572ac2
NB
2219 result->type = CPP_AND;
2220 if (*buffer->cur == '&')
2221 buffer->cur++, result->type = CPP_AND_AND;
2222 else if (*buffer->cur == '=')
2223 buffer->cur++, result->type = CPP_AND_EQ;
0d9f234d 2224 break;
df383483 2225
0d9f234d 2226 case '|':
6f572ac2
NB
2227 result->type = CPP_OR;
2228 if (*buffer->cur == '|')
2229 buffer->cur++, result->type = CPP_OR_OR;
2230 else if (*buffer->cur == '=')
2231 buffer->cur++, result->type = CPP_OR_EQ;
0d9f234d 2232 break;
45b966db 2233
0d9f234d 2234 case ':':
6f572ac2
NB
2235 result->type = CPP_COLON;
2236 if (*buffer->cur == ':' && CPP_OPTION (pfile, cplusplus))
2237 buffer->cur++, result->type = CPP_SCOPE;
2238 else if (*buffer->cur == '>' && CPP_OPTION (pfile, digraphs))
0d9f234d 2239 {
6f572ac2 2240 buffer->cur++;
0d9f234d 2241 result->flags |= DIGRAPH;
480709cc
NB
2242 result->type = CPP_CLOSE_SQUARE;
2243 }
0d9f234d 2244 break;
45b966db 2245
480709cc
NB
2246 case '*': IF_NEXT_IS ('=', CPP_MULT_EQ, CPP_MULT); break;
2247 case '=': IF_NEXT_IS ('=', CPP_EQ_EQ, CPP_EQ); break;
2248 case '!': IF_NEXT_IS ('=', CPP_NOT_EQ, CPP_NOT); break;
2249 case '^': IF_NEXT_IS ('=', CPP_XOR_EQ, CPP_XOR); break;
9a0c6187 2250 case '#': IF_NEXT_IS ('#', CPP_PASTE, CPP_HASH); result->val.token_no = 0; break;
480709cc 2251
26aea073 2252 case '?': result->type = CPP_QUERY; break;
0d9f234d
NB
2253 case '~': result->type = CPP_COMPL; break;
2254 case ',': result->type = CPP_COMMA; break;
2255 case '(': result->type = CPP_OPEN_PAREN; break;
2256 case ')': result->type = CPP_CLOSE_PAREN; break;
2257 case '[': result->type = CPP_OPEN_SQUARE; break;
2258 case ']': result->type = CPP_CLOSE_SQUARE; break;
2259 case '{': result->type = CPP_OPEN_BRACE; break;
2260 case '}': result->type = CPP_CLOSE_BRACE; break;
2261 case ';': result->type = CPP_SEMICOLON; break;
2262
40f03658 2263 /* @ is a punctuator in Objective-C. */
cc937581 2264 case '@': result->type = CPP_ATSIGN; break;
0d9f234d 2265
0abc6a6a 2266 case '$':
1613e52b
NB
2267 case '\\':
2268 {
2269 const uchar *base = --buffer->cur;
50668cf6 2270 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
0abc6a6a 2271
50668cf6 2272 if (forms_identifier_p (pfile, true, &nst))
1613e52b
NB
2273 {
2274 result->type = CPP_NAME;
9a0c6187 2275 result->val.node.node = lex_identifier (pfile, base, true, &nst);
50668cf6 2276 warn_about_normalization (pfile, result, &nst);
1613e52b
NB
2277 break;
2278 }
2279 buffer->cur++;
1067694a 2280 }
1613e52b 2281
1067694a 2282 default:
6338b358
NB
2283 create_literal (pfile, result, buffer->cur - 1, 1, CPP_OTHER);
2284 break;
0d9f234d 2285 }
bdcbe496
NB
2286
2287 return result;
0d9f234d
NB
2288}
2289
59325650
NB
2290/* An upper bound on the number of bytes needed to spell TOKEN.
2291 Does not include preceding whitespace. */
93c80368 2292unsigned int
6cf87ca4 2293cpp_token_len (const cpp_token *token)
0d9f234d 2294{
93c80368 2295 unsigned int len;
6d2c2047 2296
93c80368 2297 switch (TOKEN_SPELL (token))
041c3194 2298 {
cc955282 2299 default: len = 6; break;
6338b358 2300 case SPELL_LITERAL: len = token->val.str.len; break;
9a0c6187 2301 case SPELL_IDENT: len = NODE_LEN (token->val.node.node) * 10; break;
041c3194 2302 }
59325650
NB
2303
2304 return len;
6d2c2047
ZW
2305}
2306
47e20491
GK
2307/* Parse UTF-8 out of NAMEP and place a \U escape in BUFFER.
2308 Return the number of bytes read out of NAME. (There are always
2309 10 bytes written to BUFFER.) */
2310
2311static size_t
2312utf8_to_ucn (unsigned char *buffer, const unsigned char *name)
2313{
2314 int j;
2315 int ucn_len = 0;
2316 int ucn_len_c;
2317 unsigned t;
2318 unsigned long utf32;
2319
2320 /* Compute the length of the UTF-8 sequence. */
2321 for (t = *name; t & 0x80; t <<= 1)
2322 ucn_len++;
2323
2324 utf32 = *name & (0x7F >> ucn_len);
2325 for (ucn_len_c = 1; ucn_len_c < ucn_len; ucn_len_c++)
2326 {
2327 utf32 = (utf32 << 6) | (*++name & 0x3F);
2328
2329 /* Ill-formed UTF-8. */
2330 if ((*name & ~0x3F) != 0x80)
2331 abort ();
2332 }
2333
2334 *buffer++ = '\\';
2335 *buffer++ = 'U';
2336 for (j = 7; j >= 0; j--)
2337 *buffer++ = "0123456789abcdef"[(utf32 >> (4 * j)) & 0xF];
2338 return ucn_len;
2339}
2340
cfc93532
MLI
2341/* Given a token TYPE corresponding to a digraph, return a pointer to
2342 the spelling of the digraph. */
2343static const unsigned char *
2344cpp_digraph2name (enum cpp_ttype type)
2345{
2346 return digraph_spellings[(int) type - (int) CPP_FIRST_DIGRAPH];
2347}
47e20491 2348
041c3194 2349/* Write the spelling of a token TOKEN to BUFFER. The buffer must
cf00a885 2350 already contain the enough space to hold the token's spelling.
6cf87ca4 2351 Returns a pointer to the character after the last character written.
47e20491
GK
2352 FORSTRING is true if this is to be the spelling after translation
2353 phase 1 (this is different for UCNs).
6cf87ca4 2354 FIXME: Would be nice if we didn't need the PFILE argument. */
93c80368 2355unsigned char *
6cf87ca4 2356cpp_spell_token (cpp_reader *pfile, const cpp_token *token,
47e20491 2357 unsigned char *buffer, bool forstring)
041c3194 2358{
96be6998 2359 switch (TOKEN_SPELL (token))
041c3194
ZW
2360 {
2361 case SPELL_OPERATOR:
2362 {
2363 const unsigned char *spelling;
2364 unsigned char c;
d6d5f795 2365
041c3194 2366 if (token->flags & DIGRAPH)
cfc93532 2367 spelling = cpp_digraph2name (token->type);
92936ecf
ZW
2368 else if (token->flags & NAMED_OP)
2369 goto spell_ident;
041c3194 2370 else
96be6998 2371 spelling = TOKEN_NAME (token);
df383483 2372
041c3194
ZW
2373 while ((c = *spelling++) != '\0')
2374 *buffer++ = c;
2375 }
2376 break;
d6d5f795 2377
47ad4138 2378 spell_ident:
041c3194 2379 case SPELL_IDENT:
47e20491
GK
2380 if (forstring)
2381 {
9a0c6187
JM
2382 memcpy (buffer, NODE_NAME (token->val.node.node),
2383 NODE_LEN (token->val.node.node));
2384 buffer += NODE_LEN (token->val.node.node);
47e20491
GK
2385 }
2386 else
2387 {
2388 size_t i;
9a0c6187 2389 const unsigned char * name = NODE_NAME (token->val.node.node);
47e20491 2390
9a0c6187 2391 for (i = 0; i < NODE_LEN (token->val.node.node); i++)
47e20491
GK
2392 if (name[i] & ~0x7F)
2393 {
2394 i += utf8_to_ucn (buffer, name + i) - 1;
2395 buffer += 10;
2396 }
2397 else
9a0c6187 2398 *buffer++ = NODE_NAME (token->val.node.node)[i];
47e20491 2399 }
041c3194 2400 break;
d6d5f795 2401
6338b358 2402 case SPELL_LITERAL:
47ad4138
ZW
2403 memcpy (buffer, token->val.str.text, token->val.str.len);
2404 buffer += token->val.str.len;
2405 break;
2406
041c3194 2407 case SPELL_NONE:
0527bc4e
JDA
2408 cpp_error (pfile, CPP_DL_ICE,
2409 "unspellable token %s", TOKEN_NAME (token));
041c3194
ZW
2410 break;
2411 }
d6d5f795 2412
041c3194
ZW
2413 return buffer;
2414}
d6d5f795 2415
5d8ebbd8
NB
2416/* Returns TOKEN spelt as a null-terminated string. The string is
2417 freed when the reader is destroyed. Useful for diagnostics. */
93c80368 2418unsigned char *
6cf87ca4 2419cpp_token_as_text (cpp_reader *pfile, const cpp_token *token)
59325650
NB
2420{
2421 unsigned int len = cpp_token_len (token) + 1;
ece54d54 2422 unsigned char *start = _cpp_unaligned_alloc (pfile, len), *end;
c5a04734 2423
47e20491 2424 end = cpp_spell_token (pfile, token, start, false);
93c80368 2425 end[0] = '\0';
c5a04734 2426
93c80368
NB
2427 return start;
2428}
c5a04734 2429
cfc93532
MLI
2430/* Returns a pointer to a string which spells the token defined by
2431 TYPE and FLAGS. Used by C front ends, which really should move to
2432 using cpp_token_as_text. */
93c80368 2433const char *
cfc93532 2434cpp_type2name (enum cpp_ttype type, unsigned char flags)
93c80368 2435{
cfc93532
MLI
2436 if (flags & DIGRAPH)
2437 return (const char *) cpp_digraph2name (type);
2438 else if (flags & NAMED_OP)
2439 return cpp_named_operator2name (type);
2440
93c80368
NB
2441 return (const char *) token_spellings[type].name;
2442}
c5a04734 2443
4ed5bcfb
NB
2444/* Writes the spelling of token to FP, without any preceding space.
2445 Separated from cpp_spell_token for efficiency - to avoid stdio
2446 double-buffering. */
93c80368 2447void
6cf87ca4 2448cpp_output_token (const cpp_token *token, FILE *fp)
93c80368 2449{
93c80368 2450 switch (TOKEN_SPELL (token))
c5a04734 2451 {
93c80368
NB
2452 case SPELL_OPERATOR:
2453 {
2454 const unsigned char *spelling;
3b681e9d 2455 int c;
c5a04734 2456
93c80368 2457 if (token->flags & DIGRAPH)
cfc93532 2458 spelling = cpp_digraph2name (token->type);
93c80368
NB
2459 else if (token->flags & NAMED_OP)
2460 goto spell_ident;
2461 else
2462 spelling = TOKEN_NAME (token);
041c3194 2463
3b681e9d
ZW
2464 c = *spelling;
2465 do
2466 putc (c, fp);
2467 while ((c = *++spelling) != '\0');
93c80368
NB
2468 }
2469 break;
041c3194 2470
93c80368
NB
2471 spell_ident:
2472 case SPELL_IDENT:
47e20491
GK
2473 {
2474 size_t i;
9a0c6187 2475 const unsigned char * name = NODE_NAME (token->val.node.node);
47e20491 2476
9a0c6187 2477 for (i = 0; i < NODE_LEN (token->val.node.node); i++)
47e20491
GK
2478 if (name[i] & ~0x7F)
2479 {
2480 unsigned char buffer[10];
2481 i += utf8_to_ucn (buffer, name + i) - 1;
2482 fwrite (buffer, 1, 10, fp);
2483 }
2484 else
9a0c6187 2485 fputc (NODE_NAME (token->val.node.node)[i], fp);
47e20491
GK
2486 }
2487 break;
041c3194 2488
6338b358 2489 case SPELL_LITERAL:
47ad4138
ZW
2490 fwrite (token->val.str.text, 1, token->val.str.len, fp);
2491 break;
2492
93c80368
NB
2493 case SPELL_NONE:
2494 /* An error, most probably. */
2495 break;
041c3194 2496 }
c5a04734
ZW
2497}
2498
93c80368
NB
2499/* Compare two tokens. */
2500int
6cf87ca4 2501_cpp_equiv_tokens (const cpp_token *a, const cpp_token *b)
c5a04734 2502{
93c80368
NB
2503 if (a->type == b->type && a->flags == b->flags)
2504 switch (TOKEN_SPELL (a))
2505 {
2506 default: /* Keep compiler happy. */
2507 case SPELL_OPERATOR:
9a0c6187 2508 /* token_no is used to track where multiple consecutive ##
aa508502 2509 tokens were originally located. */
9a0c6187 2510 return (a->type != CPP_PASTE || a->val.token_no == b->val.token_no);
93c80368 2511 case SPELL_NONE:
9a0c6187
JM
2512 return (a->type != CPP_MACRO_ARG
2513 || a->val.macro_arg.arg_no == b->val.macro_arg.arg_no);
93c80368 2514 case SPELL_IDENT:
9a0c6187 2515 return a->val.node.node == b->val.node.node;
6338b358 2516 case SPELL_LITERAL:
93c80368
NB
2517 return (a->val.str.len == b->val.str.len
2518 && !memcmp (a->val.str.text, b->val.str.text,
2519 a->val.str.len));
2520 }
c5a04734 2521
041c3194
ZW
2522 return 0;
2523}
2524
93c80368
NB
2525/* Returns nonzero if a space should be inserted to avoid an
2526 accidental token paste for output. For simplicity, it is
2527 conservative, and occasionally advises a space where one is not
2528 needed, e.g. "." and ".2". */
93c80368 2529int
6cf87ca4
ZW
2530cpp_avoid_paste (cpp_reader *pfile, const cpp_token *token1,
2531 const cpp_token *token2)
c5a04734 2532{
93c80368
NB
2533 enum cpp_ttype a = token1->type, b = token2->type;
2534 cppchar_t c;
c5a04734 2535
93c80368
NB
2536 if (token1->flags & NAMED_OP)
2537 a = CPP_NAME;
2538 if (token2->flags & NAMED_OP)
2539 b = CPP_NAME;
c5a04734 2540
93c80368
NB
2541 c = EOF;
2542 if (token2->flags & DIGRAPH)
37b8524c 2543 c = digraph_spellings[(int) b - (int) CPP_FIRST_DIGRAPH][0];
93c80368
NB
2544 else if (token_spellings[b].category == SPELL_OPERATOR)
2545 c = token_spellings[b].name[0];
c5a04734 2546
93c80368 2547 /* Quickly get everything that can paste with an '='. */
37b8524c 2548 if ((int) a <= (int) CPP_LAST_EQ && c == '=')
93c80368 2549 return 1;
c5a04734 2550
93c80368 2551 switch (a)
c5a04734 2552 {
b52dbbf8
SE
2553 case CPP_GREATER: return c == '>';
2554 case CPP_LESS: return c == '<' || c == '%' || c == ':';
93c80368
NB
2555 case CPP_PLUS: return c == '+';
2556 case CPP_MINUS: return c == '-' || c == '>';
2557 case CPP_DIV: return c == '/' || c == '*'; /* Comments. */
2558 case CPP_MOD: return c == ':' || c == '>';
2559 case CPP_AND: return c == '&';
2560 case CPP_OR: return c == '|';
2561 case CPP_COLON: return c == ':' || c == '>';
2562 case CPP_DEREF: return c == '*';
26ec42ee 2563 case CPP_DOT: return c == '.' || c == '%' || b == CPP_NUMBER;
93c80368
NB
2564 case CPP_HASH: return c == '#' || c == '%'; /* Digraph form. */
2565 case CPP_NAME: return ((b == CPP_NUMBER
2566 && name_p (pfile, &token2->val.str))
2567 || b == CPP_NAME
2568 || b == CPP_CHAR || b == CPP_STRING); /* L */
2569 case CPP_NUMBER: return (b == CPP_NUMBER || b == CPP_NAME
2570 || c == '.' || c == '+' || c == '-');
1613e52b 2571 /* UCNs */
1067694a
NB
2572 case CPP_OTHER: return ((token1->val.str.text[0] == '\\'
2573 && b == CPP_NAME)
1613e52b 2574 || (CPP_OPTION (pfile, objc)
1067694a 2575 && token1->val.str.text[0] == '@'
1613e52b 2576 && (b == CPP_NAME || b == CPP_STRING)));
93c80368 2577 default: break;
c5a04734 2578 }
c5a04734 2579
417f3e3a 2580 return 0;
c5a04734
ZW
2581}
2582
93c80368 2583/* Output all the remaining tokens on the current line, and a newline
4ed5bcfb
NB
2584 character, to FP. Leading whitespace is removed. If there are
2585 macros, special token padding is not performed. */
c5a04734 2586void
6cf87ca4 2587cpp_output_line (cpp_reader *pfile, FILE *fp)
c5a04734 2588{
4ed5bcfb 2589 const cpp_token *token;
96be6998 2590
4ed5bcfb
NB
2591 token = cpp_get_token (pfile);
2592 while (token->type != CPP_EOF)
96be6998 2593 {
4ed5bcfb
NB
2594 cpp_output_token (token, fp);
2595 token = cpp_get_token (pfile);
2596 if (token->flags & PREV_WHITE)
2597 putc (' ', fp);
96be6998
ZW
2598 }
2599
93c80368 2600 putc ('\n', fp);
041c3194 2601}
c5a04734 2602
5d6342eb
TT
2603/* Return a string representation of all the remaining tokens on the
2604 current line. The result is allocated using xmalloc and must be
2605 freed by the caller. */
2606unsigned char *
2607cpp_output_line_to_string (cpp_reader *pfile, const unsigned char *dir_name)
2608{
2609 const cpp_token *token;
2610 unsigned int out = dir_name ? ustrlen (dir_name) : 0;
2611 unsigned int alloced = 120 + out;
2612 unsigned char *result = (unsigned char *) xmalloc (alloced);
2613
2614 /* If DIR_NAME is empty, there are no initial contents. */
2615 if (dir_name)
2616 {
2617 sprintf ((char *) result, "#%s ", dir_name);
2618 out += 2;
2619 }
2620
2621 token = cpp_get_token (pfile);
2622 while (token->type != CPP_EOF)
2623 {
2624 unsigned char *last;
2625 /* Include room for a possible space and the terminating nul. */
2626 unsigned int len = cpp_token_len (token) + 2;
2627
2628 if (out + len > alloced)
2629 {
2630 alloced *= 2;
2631 if (out + len > alloced)
2632 alloced = out + len;
2633 result = (unsigned char *) xrealloc (result, alloced);
2634 }
2635
2636 last = cpp_spell_token (pfile, token, &result[out], 0);
2637 out = last - result;
2638
2639 token = cpp_get_token (pfile);
2640 if (token->flags & PREV_WHITE)
2641 result[out++] = ' ';
2642 }
2643
2644 result[out] = '\0';
2645 return result;
2646}
2647
1e013d2e
NB
2648/* Memory buffers. Changing these three constants can have a dramatic
2649 effect on performance. The values here are reasonable defaults,
2650 but might be tuned. If you adjust them, be sure to test across a
2651 range of uses of cpplib, including heavy nested function-like macro
2652 expansion. Also check the change in peak memory usage (NJAMD is a
2653 good tool for this). */
2654#define MIN_BUFF_SIZE 8000
87062813 2655#define BUFF_SIZE_UPPER_BOUND(MIN_SIZE) (MIN_BUFF_SIZE + (MIN_SIZE) * 3 / 2)
1e013d2e
NB
2656#define EXTENDED_BUFF_SIZE(BUFF, MIN_EXTRA) \
2657 (MIN_EXTRA + ((BUFF)->limit - (BUFF)->cur) * 2)
417f3e3a 2658
87062813
NB
2659#if MIN_BUFF_SIZE > BUFF_SIZE_UPPER_BOUND (0)
2660 #error BUFF_SIZE_UPPER_BOUND must be at least as large as MIN_BUFF_SIZE!
2661#endif
2662
c9e7a609
NB
2663/* Create a new allocation buffer. Place the control block at the end
2664 of the buffer, so that buffer overflows will cause immediate chaos. */
b8af0ca5 2665static _cpp_buff *
6cf87ca4 2666new_buff (size_t len)
b8af0ca5
NB
2667{
2668 _cpp_buff *result;
ece54d54 2669 unsigned char *base;
b8af0ca5 2670
1e013d2e
NB
2671 if (len < MIN_BUFF_SIZE)
2672 len = MIN_BUFF_SIZE;
c70f6ed3 2673 len = CPP_ALIGN (len);
b8af0ca5 2674
c3f829c1 2675 base = XNEWVEC (unsigned char, len + sizeof (_cpp_buff));
b8af0ca5
NB
2676 result = (_cpp_buff *) (base + len);
2677 result->base = base;
2678 result->cur = base;
2679 result->limit = base + len;
2680 result->next = NULL;
2681 return result;
2682}
2683
2684/* Place a chain of unwanted allocation buffers on the free list. */
2685void
6cf87ca4 2686_cpp_release_buff (cpp_reader *pfile, _cpp_buff *buff)
b8af0ca5
NB
2687{
2688 _cpp_buff *end = buff;
2689
2690 while (end->next)
2691 end = end->next;
2692 end->next = pfile->free_buffs;
2693 pfile->free_buffs = buff;
2694}
2695
2696/* Return a free buffer of size at least MIN_SIZE. */
2697_cpp_buff *
6cf87ca4 2698_cpp_get_buff (cpp_reader *pfile, size_t min_size)
b8af0ca5
NB
2699{
2700 _cpp_buff *result, **p;
2701
2702 for (p = &pfile->free_buffs;; p = &(*p)->next)
2703 {
6142088c 2704 size_t size;
1e013d2e
NB
2705
2706 if (*p == NULL)
b8af0ca5 2707 return new_buff (min_size);
1e013d2e
NB
2708 result = *p;
2709 size = result->limit - result->base;
2710 /* Return a buffer that's big enough, but don't waste one that's
2711 way too big. */
34f5271d 2712 if (size >= min_size && size <= BUFF_SIZE_UPPER_BOUND (min_size))
b8af0ca5
NB
2713 break;
2714 }
2715
2716 *p = result->next;
2717 result->next = NULL;
2718 result->cur = result->base;
2719 return result;
2720}
2721
4fe9b91c 2722/* Creates a new buffer with enough space to hold the uncommitted
8c3b2693
NB
2723 remaining bytes of BUFF, and at least MIN_EXTRA more bytes. Copies
2724 the excess bytes to the new buffer. Chains the new buffer after
2725 BUFF, and returns the new buffer. */
b8af0ca5 2726_cpp_buff *
6cf87ca4 2727_cpp_append_extend_buff (cpp_reader *pfile, _cpp_buff *buff, size_t min_extra)
b8af0ca5 2728{
6142088c 2729 size_t size = EXTENDED_BUFF_SIZE (buff, min_extra);
8c3b2693 2730 _cpp_buff *new_buff = _cpp_get_buff (pfile, size);
b8af0ca5 2731
8c3b2693
NB
2732 buff->next = new_buff;
2733 memcpy (new_buff->base, buff->cur, BUFF_ROOM (buff));
2734 return new_buff;
2735}
2736
4fe9b91c 2737/* Creates a new buffer with enough space to hold the uncommitted
8c3b2693
NB
2738 remaining bytes of the buffer pointed to by BUFF, and at least
2739 MIN_EXTRA more bytes. Copies the excess bytes to the new buffer.
2740 Chains the new buffer before the buffer pointed to by BUFF, and
2741 updates the pointer to point to the new buffer. */
2742void
6cf87ca4 2743_cpp_extend_buff (cpp_reader *pfile, _cpp_buff **pbuff, size_t min_extra)
8c3b2693
NB
2744{
2745 _cpp_buff *new_buff, *old_buff = *pbuff;
2746 size_t size = EXTENDED_BUFF_SIZE (old_buff, min_extra);
2747
2748 new_buff = _cpp_get_buff (pfile, size);
2749 memcpy (new_buff->base, old_buff->cur, BUFF_ROOM (old_buff));
2750 new_buff->next = old_buff;
2751 *pbuff = new_buff;
b8af0ca5
NB
2752}
2753
2754/* Free a chain of buffers starting at BUFF. */
2755void
5671bf27 2756_cpp_free_buff (_cpp_buff *buff)
b8af0ca5
NB
2757{
2758 _cpp_buff *next;
2759
2760 for (; buff; buff = next)
2761 {
2762 next = buff->next;
2763 free (buff->base);
2764 }
2765}
417f3e3a 2766
ece54d54
NB
2767/* Allocate permanent, unaligned storage of length LEN. */
2768unsigned char *
6cf87ca4 2769_cpp_unaligned_alloc (cpp_reader *pfile, size_t len)
ece54d54
NB
2770{
2771 _cpp_buff *buff = pfile->u_buff;
2772 unsigned char *result = buff->cur;
2773
2774 if (len > (size_t) (buff->limit - result))
2775 {
2776 buff = _cpp_get_buff (pfile, len);
2777 buff->next = pfile->u_buff;
2778 pfile->u_buff = buff;
2779 result = buff->cur;
2780 }
2781
2782 buff->cur = result + len;
2783 return result;
2784}
2785
87062813
NB
2786/* Allocate permanent, unaligned storage of length LEN from a_buff.
2787 That buffer is used for growing allocations when saving macro
2788 replacement lists in a #define, and when parsing an answer to an
2789 assertion in #assert, #unassert or #if (and therefore possibly
2790 whilst expanding macros). It therefore must not be used by any
2791 code that they might call: specifically the lexer and the guts of
2792 the macro expander.
2793
2794 All existing other uses clearly fit this restriction: storing
2795 registered pragmas during initialization. */
93c80368 2796unsigned char *
6cf87ca4 2797_cpp_aligned_alloc (cpp_reader *pfile, size_t len)
3fef5b2b 2798{
8c3b2693
NB
2799 _cpp_buff *buff = pfile->a_buff;
2800 unsigned char *result = buff->cur;
3fef5b2b 2801
8c3b2693 2802 if (len > (size_t) (buff->limit - result))
3fef5b2b 2803 {
8c3b2693
NB
2804 buff = _cpp_get_buff (pfile, len);
2805 buff->next = pfile->a_buff;
2806 pfile->a_buff = buff;
2807 result = buff->cur;
3fef5b2b 2808 }
041c3194 2809
8c3b2693 2810 buff->cur = result + len;
93c80368 2811 return result;
041c3194 2812}
d8044160
GK
2813
2814/* Say which field of TOK is in use. */
2815
2816enum cpp_token_fld_kind
2817cpp_token_val_index (cpp_token *tok)
2818{
2819 switch (TOKEN_SPELL (tok))
2820 {
2821 case SPELL_IDENT:
2822 return CPP_TOKEN_FLD_NODE;
2823 case SPELL_LITERAL:
2824 return CPP_TOKEN_FLD_STR;
aa508502
JM
2825 case SPELL_OPERATOR:
2826 if (tok->type == CPP_PASTE)
9a0c6187 2827 return CPP_TOKEN_FLD_TOKEN_NO;
aa508502
JM
2828 else
2829 return CPP_TOKEN_FLD_NONE;
d8044160
GK
2830 case SPELL_NONE:
2831 if (tok->type == CPP_MACRO_ARG)
2832 return CPP_TOKEN_FLD_ARG_NO;
2833 else if (tok->type == CPP_PADDING)
2834 return CPP_TOKEN_FLD_SOURCE;
21b11495 2835 else if (tok->type == CPP_PRAGMA)
bc4071dd 2836 return CPP_TOKEN_FLD_PRAGMA;
d8044160
GK
2837 /* else fall through */
2838 default:
2839 return CPP_TOKEN_FLD_NONE;
2840 }
2841}