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