Debian Codegraph @

libcpp/lex.cc

raw
1 /* CPP Library - lexical analysis.
2 Copyright (C) 2000-2025 Free Software Foundation, Inc.
3 Contributed by Per Bothner, 1994-95.
4 Based on CCCP program by Paul Rubin, June 1986
5 Adapted to ANSI C, Richard Stallman, Jan 1987
6 Broken out to separate file, Zack Weinberg, Mar 2000
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 3, or (at your option) any
11 later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
21
22 #include "config.h"
23 #include "system.h"
24 #include "cpplib.h"
25 #include "internal.h"
26
27 enum spell_type
28 {
29 SPELL_OPERATOR = 0,
30 SPELL_IDENT,
31 SPELL_LITERAL,
32 SPELL_NONE
33 };
34
35 struct token_spelling
36 {
37 enum spell_type category;
38 const unsigned char *name;
39 };
40
41 static const unsigned char *const digraph_spellings[] =
42 { UC"%:", UC"%:%:", UC"<:", UC":>", UC"<%", UC"%>" };
43
44 #define OP(e, s) { SPELL_OPERATOR, UC s },
45 #define TK(e, s) { SPELL_ ## s, UC #e },
46 static const struct token_spelling token_spellings[N_TTYPES] = { TTYPE_TABLE };
47 #undef OP
48 #undef TK
49
50 #define TOKEN_SPELL(token) (token_spellings[(token)->type].category)
51 #define TOKEN_NAME(token) (token_spellings[(token)->type].name)
52
53 /* ISO 10646 defines the UCS codespace as the range 0-0x10FFFF inclusive. */
54 #define UCS_LIMIT 0x10FFFF
55
56 static void add_line_note (cpp_buffer *, const uchar *, unsigned int);
57 static int skip_line_comment (cpp_reader *);
58 static void skip_whitespace (cpp_reader *, cppchar_t);
59 static void lex_string (cpp_reader *, cpp_token *, const uchar *);
60 static void save_comment (cpp_reader *, cpp_token *, const uchar *, cppchar_t);
61 static void store_comment (cpp_reader *, cpp_token *);
62 static void create_literal (cpp_reader *, cpp_token *, const uchar *,
63 unsigned int, enum cpp_ttype);
64 static bool warn_in_comment (cpp_reader *, _cpp_line_note *);
65 static int name_p (cpp_reader *, const cpp_string *);
66 static tokenrun *next_tokenrun (tokenrun *);
67
68 static _cpp_buff *new_buff (size_t);
69
70
71 /* Utility routine:
72
73 Compares, the token TOKEN to the NUL-terminated string STRING.
74 TOKEN must be a CPP_NAME. Returns 1 for equal, 0 for unequal. */
75 int
76 cpp_ideq (const cpp_token *token, const char *string)
77 {
78 if (token->type != CPP_NAME)
79 return 0;
80
81 return !ustrcmp (NODE_NAME (token->val.node.node), (const uchar *) string);
82 }
83
84 /* Record a note TYPE at byte POS into the current cleaned logical
85 line. */
86 static void
87 add_line_note (cpp_buffer *buffer, const uchar *pos, unsigned int type)
88 {
89 if (buffer->notes_used == buffer->notes_cap)
90 {
91 buffer->notes_cap = buffer->notes_cap * 2 + 200;
92 buffer->notes = XRESIZEVEC (_cpp_line_note, buffer->notes,
93 buffer->notes_cap);
94 }
95
96 buffer->notes[buffer->notes_used].pos = pos;
97 buffer->notes[buffer->notes_used].type = type;
98 buffer->notes_used++;
99 }
100
101
102 /* Fast path to find line special characters using optimized character
103 scanning algorithms. Anything complicated falls back to the slow
104 path below. Since this loop is very hot it's worth doing these kinds
105 of optimizations.
106
107 One of the paths through the ifdefs should provide
108
109 const uchar *search_line_fast (const uchar *s, const uchar *end);
110
111 Between S and END, search for \n, \r, \\, ?. Return a pointer to
112 the found character.
113
114 Note that the last character of the buffer is *always* a newline,
115 as forced by _cpp_convert_input. This fact can be used to avoid
116 explicitly looking for the end of the buffer. */
117
118 /* Configure gives us an ifdef test. */
119 #ifndef WORDS_BIGENDIAN
120 #define WORDS_BIGENDIAN 0
121 #endif
122
123 /* We'd like the largest integer that fits into a register. There's nothing
124 in <stdint.h> that gives us that. For most hosts this is unsigned long,
125 but MS decided on an LLP64 model. Thankfully when building with GCC we
126 can get the "real" word size. */
127 #ifdef __GNUC__
128 typedef unsigned int word_type __attribute__((__mode__(__word__)));
129 #else
130 typedef unsigned long word_type;
131 #endif
132
133 /* The code below is only expecting sizes 4 or 8.
134 Die at compile-time if this expectation is violated. */
135 typedef char check_word_type_size
136 [(sizeof(word_type) == 8 || sizeof(word_type) == 4) * 2 - 1];
137
138 /* Return X with the first N bytes forced to values that won't match one
139 of the interesting characters. Note that NUL is not interesting. */
140
141 static inline word_type
142 acc_char_mask_misalign (word_type val, unsigned int n)
143 {
144 word_type mask = -1;
145 if (WORDS_BIGENDIAN)
146 mask >>= n * 8;
147 else
148 mask <<= n * 8;
149 return val & mask;
150 }
151
152 /* Return X replicated to all byte positions within WORD_TYPE. */
153
154 static inline word_type
155 acc_char_replicate (uchar x)
156 {
157 word_type ret;
158
159 ret = (x << 24) | (x << 16) | (x << 8) | x;
160 if (sizeof(word_type) == 8)
161 ret = (ret << 16 << 16) | ret;
162 return ret;
163 }
164
165 /* Return non-zero if some byte of VAL is (probably) C. */
166
167 static inline word_type
168 acc_char_cmp (word_type val, word_type c)
169 {
170 #if defined(__GNUC__) && defined(__alpha__)
171 /* We can get exact results using a compare-bytes instruction.
172 Get (val == c) via (0 >= (val ^ c)). */
173 return __builtin_alpha_cmpbge (0, val ^ c);
174 #else
175 word_type magic = 0x7efefefeU;
176 if (sizeof(word_type) == 8)
177 magic = (magic << 16 << 16) | 0xfefefefeU;
178 magic |= 1;
179
180 val ^= c;
181 return ((val + magic) ^ ~val) & ~magic;
182 #endif
183 }
184
185 /* Given the result of acc_char_cmp is non-zero, return the index of
186 the found character. If this was a false positive, return -1. */
187
188 static inline int
189 acc_char_index (word_type cmp ATTRIBUTE_UNUSED,
190 word_type val ATTRIBUTE_UNUSED)
191 {
192 #if defined(__GNUC__) && defined(__alpha__) && !WORDS_BIGENDIAN
193 /* The cmpbge instruction sets *bits* of the result corresponding to
194 matches in the bytes with no false positives. */
195 return __builtin_ctzl (cmp);
196 #else
197 unsigned int i;
198
199 /* ??? It would be nice to force unrolling here,
200 and have all of these constants folded. */
201 for (i = 0; i < sizeof(word_type); ++i)
202 {
203 uchar c;
204 if (WORDS_BIGENDIAN)
205 c = (val >> (sizeof(word_type) - i - 1) * 8) & 0xff;
206 else
207 c = (val >> i * 8) & 0xff;
208
209 if (c == '\n' || c == '\r' || c == '\\' || c == '?')
210 return i;
211 }
212
213 return -1;
214 #endif
215 }
216
217 /* A version of the fast scanner using bit fiddling techniques.
218
219 For 32-bit words, one would normally perform 16 comparisons and
220 16 branches. With this algorithm one performs 24 arithmetic
221 operations and one branch. Whether this is faster with a 32-bit
222 word size is going to be somewhat system dependent.
223
224 For 64-bit words, we eliminate twice the number of comparisons
225 and branches without increasing the number of arithmetic operations.
226 It's almost certainly going to be a win with 64-bit word size. */
227
228 static inline const uchar *
229 search_line_acc_char (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
230 {
231 const word_type repl_nl = acc_char_replicate ('\n');
232 const word_type repl_cr = acc_char_replicate ('\r');
233 const word_type repl_bs = acc_char_replicate ('\\');
234 const word_type repl_qm = acc_char_replicate ('?');
235
236 unsigned int misalign;
237 const word_type *p;
238 word_type val, t;
239
240 /* Align the buffer. Mask out any bytes from before the beginning. */
241 p = (word_type *)((uintptr_t)s & -sizeof(word_type));
242 val = *p;
243 misalign = (uintptr_t)s & (sizeof(word_type) - 1);
244 if (misalign)
245 val = acc_char_mask_misalign (val, misalign);
246
247 /* Main loop. */
248 while (1)
249 {
250 t = acc_char_cmp (val, repl_nl);
251 t |= acc_char_cmp (val, repl_cr);
252 t |= acc_char_cmp (val, repl_bs);
253 t |= acc_char_cmp (val, repl_qm);
254
255 if (__builtin_expect (t != 0, 0))
256 {
257 int i = acc_char_index (t, val);
258 if (i >= 0)
259 return (const uchar *)p + i;
260 }
261
262 val = *++p;
263 }
264 }
265
266 /* Disable on Solaris 2/x86 until the following problem can be properly
267 autoconfed:
268
269 The Solaris 10+ assembler tags objects with the instruction set
270 extensions used, so SSE4.2 executables cannot run on machines that
271 don't support that extension. */
272
273 #if (GCC_VERSION >= 4005) && (__GNUC__ >= 5 || !defined(__PIC__)) && (defined(__i386__) || defined(__x86_64__)) && !(defined(__sun__) && defined(__svr4__))
274
275 /* Replicated character data to be shared between implementations.
276 Recall that outside of a context with vector support we can't
277 define compatible vector types, therefore these are all defined
278 in terms of raw characters. */
279 static const char repl_chars[4][16] __attribute__((aligned(16))) = {
280 { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n',
281 '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' },
282 { '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r',
283 '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r' },
284 { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\',
285 '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' },
286 { '?', '?', '?', '?', '?', '?', '?', '?',
287 '?', '?', '?', '?', '?', '?', '?', '?' },
288 };
289
290
291 /* A version of the fast scanner using SSE2 vectorized byte compare insns. */
292
293 static inline const uchar *
294 #ifndef __SSE2__
295 __attribute__((__target__("sse2")))
296 #endif
297 search_line_sse2 (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
298 {
299 typedef char v16qi __attribute__ ((__vector_size__ (16)));
300
301 const v16qi repl_nl = *(const v16qi *)repl_chars[0];
302 const v16qi repl_cr = *(const v16qi *)repl_chars[1];
303 const v16qi repl_bs = *(const v16qi *)repl_chars[2];
304 const v16qi repl_qm = *(const v16qi *)repl_chars[3];
305
306 unsigned int misalign, found, mask;
307 const v16qi *p;
308 v16qi data, t;
309
310 /* Align the source pointer. */
311 misalign = (uintptr_t)s & 15;
312 p = (const v16qi *)((uintptr_t)s & -16);
313 data = *p;
314
315 /* Create a mask for the bytes that are valid within the first
316 16-byte block. The Idea here is that the AND with the mask
317 within the loop is "free", since we need some AND or TEST
318 insn in order to set the flags for the branch anyway. */
319 mask = -1u << misalign;
320
321 /* Main loop processing 16 bytes at a time. */
322 goto start;
323 do
324 {
325 data = *++p;
326 mask = -1;
327
328 start:
329 t = data == repl_nl;
330 t |= data == repl_cr;
331 t |= data == repl_bs;
332 t |= data == repl_qm;
333 found = __builtin_ia32_pmovmskb128 (t);
334 found &= mask;
335 }
336 while (!found);
337
338 /* FOUND contains 1 in bits for which we matched a relevant
339 character. Conversion to the byte index is trivial. */
340 found = __builtin_ctz(found);
341 return (const uchar *)p + found;
342 }
343
344 #ifdef HAVE_SSSE3
345 /* A version of the fast scanner using SSSE3 shuffle (PSHUFB) insns. */
346
347 static inline const uchar *
348 #ifndef __SSSE3__
349 __attribute__((__target__("ssse3")))
350 #endif
351 search_line_ssse3 (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
352 {
353 typedef char v16qi __attribute__ ((__vector_size__ (16)));
354 typedef v16qi v16qi_u __attribute__ ((__aligned__ (1)));
355 /* Helper vector for pshufb-based matching:
356 each character C we're searching for is at position (C % 16). */
357 v16qi lut = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\n', 0, '\\', '\r', 0, '?' };
358 static_assert('\n' == 10 && '\r' == 13 && '\\' == 92 && '?' == 63,
359 "host character encoding is ASCII");
360
361 v16qi d1, d2, t1, t2;
362 /* Unaligned loads, potentially using padding after the final newline. */
363 static_assert (CPP_BUFFER_PADDING >= 64, "");
364 d1 = *(const v16qi_u *)s;
365 d2 = *(const v16qi_u *)(s + 16);
366 unsigned m1, m2, found;
367 /* Process two 16-byte chunks per iteration. */
368 do
369 {
370 t1 = __builtin_ia32_pshufb128 (lut, d1);
371 t2 = __builtin_ia32_pshufb128 (lut, d2);
372 m1 = __builtin_ia32_pmovmskb128 (t1 == d1);
373 m2 = __builtin_ia32_pmovmskb128 (t2 == d2);
374 s += 32;
375 d1 = *(const v16qi_u *)s;
376 d2 = *(const v16qi_u *)(s + 16);
377 found = m1 + (m2 << 16);
378 }
379 while (!found);
380 /* Prefer to compute 's - 32' here, not spend an extra instruction
381 to make a copy of the previous value of 's' in the loop. */
382 __asm__ ("" : "+r"(s));
383 return s - 32 + __builtin_ctz (found);
384 }
385
386 #else
387 /* Work around out-dated assemblers without SSSE3 support. */
388 #define search_line_ssse3 search_line_sse2
389 #endif
390
391 #ifdef __SSSE3__
392 /* No need for CPU probing, just use the best available variant. */
393 #define search_line_fast search_line_ssse3
394 #else
395 /* Check the CPU capabilities. */
396
397 #include "../gcc/config/i386/cpuid.h"
398
399 typedef const uchar * (*search_line_fast_type) (const uchar *, const uchar *);
400 static search_line_fast_type search_line_fast
401 #if defined(__SSE2__)
402 = search_line_sse2;
403 #else
404 = search_line_acc_char;
405 #endif
406
407 #define HAVE_init_vectorized_lexer 1
408 static inline void
409 init_vectorized_lexer (void)
410 {
411 unsigned ax, bx, cx, dx;
412
413 if (!__get_cpuid (1, &ax, &bx, &cx, &dx))
414 return;
415
416 if (cx & bit_SSSE3)
417 search_line_fast = search_line_ssse3;
418 else if (dx & bit_SSE2)
419 search_line_fast = search_line_sse2;
420 }
421 #endif
422
423 #elif (GCC_VERSION >= 4005) && defined(_ARCH_PWR8) && defined(__ALTIVEC__)
424
425 /* A vection of the fast scanner using AltiVec vectorized byte compares
426 and VSX unaligned loads (when VSX is available). This is otherwise
427 the same as the AltiVec version. */
428
429 ATTRIBUTE_NO_SANITIZE_UNDEFINED
430 static const uchar *
431 search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
432 {
433 typedef __attribute__((altivec(vector))) unsigned char vc;
434
435 const vc repl_nl = {
436 '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n',
437 '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'
438 };
439 const vc repl_cr = {
440 '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r',
441 '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r'
442 };
443 const vc repl_bs = {
444 '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\',
445 '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\'
446 };
447 const vc repl_qm = {
448 '?', '?', '?', '?', '?', '?', '?', '?',
449 '?', '?', '?', '?', '?', '?', '?', '?',
450 };
451 const vc zero = { 0 };
452
453 vc data, t;
454
455 /* Main loop processing 16 bytes at a time. */
456 do
457 {
458 vc m_nl, m_cr, m_bs, m_qm;
459
460 data = __builtin_vec_vsx_ld (0, s);
461 s += 16;
462
463 m_nl = (vc) __builtin_vec_cmpeq(data, repl_nl);
464 m_cr = (vc) __builtin_vec_cmpeq(data, repl_cr);
465 m_bs = (vc) __builtin_vec_cmpeq(data, repl_bs);
466 m_qm = (vc) __builtin_vec_cmpeq(data, repl_qm);
467 t = (m_nl | m_cr) | (m_bs | m_qm);
468
469 /* T now contains 0xff in bytes for which we matched one of the relevant
470 characters. We want to exit the loop if any byte in T is non-zero.
471 Below is the expansion of vec_any_ne(t, zero). */
472 }
473 while (!__builtin_vec_vcmpeq_p(/*__CR6_LT_REV*/3, t, zero));
474
475 /* Restore s to to point to the 16 bytes we just processed. */
476 s -= 16;
477
478 {
479 #define N (sizeof(vc) / sizeof(long))
480
481 union {
482 vc v;
483 /* Statically assert that N is 2 or 4. */
484 unsigned long l[(N == 2 || N == 4) ? N : -1];
485 } u;
486 unsigned long l, i = 0;
487
488 u.v = t;
489
490 /* Find the first word of T that is non-zero. */
491 switch (N)
492 {
493 case 4:
494 l = u.l[i++];
495 if (l != 0)
496 break;
497 s += sizeof(unsigned long);
498 l = u.l[i++];
499 if (l != 0)
500 break;
501 s += sizeof(unsigned long);
502 /* FALLTHRU */
503 case 2:
504 l = u.l[i++];
505 if (l != 0)
506 break;
507 s += sizeof(unsigned long);
508 l = u.l[i];
509 }
510
511 /* L now contains 0xff in bytes for which we matched one of the
512 relevant characters. We can find the byte index by finding
513 its bit index and dividing by 8. */
514 #ifdef __BIG_ENDIAN__
515 l = __builtin_clzl(l) >> 3;
516 #else
517 l = __builtin_ctzl(l) >> 3;
518 #endif
519 return s + l;
520
521 #undef N
522 }
523 }
524
525 #elif (GCC_VERSION >= 4005) && defined(__ALTIVEC__) && defined (__BIG_ENDIAN__)
526
527 /* A vection of the fast scanner using AltiVec vectorized byte compares.
528 This cannot be used for little endian because vec_lvsl/lvsr are
529 deprecated for little endian and the code won't work properly. */
530 /* ??? Unfortunately, attribute(target("altivec")) is not yet supported,
531 so we can't compile this function without -maltivec on the command line
532 (or implied by some other switch). */
533
534 static const uchar *
535 search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
536 {
537 typedef __attribute__((altivec(vector))) unsigned char vc;
538
539 const vc repl_nl = {
540 '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n',
541 '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'
542 };
543 const vc repl_cr = {
544 '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r',
545 '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r'
546 };
547 const vc repl_bs = {
548 '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\',
549 '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\'
550 };
551 const vc repl_qm = {
552 '?', '?', '?', '?', '?', '?', '?', '?',
553 '?', '?', '?', '?', '?', '?', '?', '?',
554 };
555 const vc ones = {
556 -1, -1, -1, -1, -1, -1, -1, -1,
557 -1, -1, -1, -1, -1, -1, -1, -1,
558 };
559 const vc zero = { 0 };
560
561 vc data, mask, t;
562
563 /* Altivec loads automatically mask addresses with -16. This lets us
564 issue the first load as early as possible. */
565 data = __builtin_vec_ld(0, (const vc *)s);
566
567 /* Discard bytes before the beginning of the buffer. Do this by
568 beginning with all ones and shifting in zeros according to the
569 mis-alignment. The LVSR instruction pulls the exact shift we
570 want from the address. */
571 mask = __builtin_vec_lvsr(0, s);
572 mask = __builtin_vec_perm(zero, ones, mask);
573 data &= mask;
574
575 /* While altivec loads mask addresses, we still need to align S so
576 that the offset we compute at the end is correct. */
577 s = (const uchar *)((uintptr_t)s & -16);
578
579 /* Main loop processing 16 bytes at a time. */
580 goto start;
581 do
582 {
583 vc m_nl, m_cr, m_bs, m_qm;
584
585 s += 16;
586 data = __builtin_vec_ld(0, (const vc *)s);
587
588 start:
589 m_nl = (vc) __builtin_vec_cmpeq(data, repl_nl);
590 m_cr = (vc) __builtin_vec_cmpeq(data, repl_cr);
591 m_bs = (vc) __builtin_vec_cmpeq(data, repl_bs);
592 m_qm = (vc) __builtin_vec_cmpeq(data, repl_qm);
593 t = (m_nl | m_cr) | (m_bs | m_qm);
594
595 /* T now contains 0xff in bytes for which we matched one of the relevant
596 characters. We want to exit the loop if any byte in T is non-zero.
597 Below is the expansion of vec_any_ne(t, zero). */
598 }
599 while (!__builtin_vec_vcmpeq_p(/*__CR6_LT_REV*/3, t, zero));
600
601 {
602 #define N (sizeof(vc) / sizeof(long))
603
604 union {
605 vc v;
606 /* Statically assert that N is 2 or 4. */
607 unsigned long l[(N == 2 || N == 4) ? N : -1];
608 } u;
609 unsigned long l, i = 0;
610
611 u.v = t;
612
613 /* Find the first word of T that is non-zero. */
614 switch (N)
615 {
616 case 4:
617 l = u.l[i++];
618 if (l != 0)
619 break;
620 s += sizeof(unsigned long);
621 l = u.l[i++];
622 if (l != 0)
623 break;
624 s += sizeof(unsigned long);
625 /* FALLTHROUGH */
626 case 2:
627 l = u.l[i++];
628 if (l != 0)
629 break;
630 s += sizeof(unsigned long);
631 l = u.l[i];
632 }
633
634 /* L now contains 0xff in bytes for which we matched one of the
635 relevant characters. We can find the byte index by finding
636 its bit index and dividing by 8. */
637 l = __builtin_clzl(l) >> 3;
638 return s + l;
639
640 #undef N
641 }
642 }
643
644 #elif defined (__ARM_NEON) && defined (__ARM_64BIT_STATE)
645 #include "arm_neon.h"
646
647 /* This doesn't have to be the exact page size, but no system may use
648 a size smaller than this. ARMv8 requires a minimum page size of
649 4k. The impact of being conservative here is a small number of
650 cases will take the slightly slower entry path into the main
651 loop. */
652
653 #define AARCH64_MIN_PAGE_SIZE 4096
654
655 static const uchar *
656 search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
657 {
658 const uint8x16_t repl_nl = vdupq_n_u8 ('\n');
659 const uint8x16_t repl_cr = vdupq_n_u8 ('\r');
660 const uint8x16_t repl_bs = vdupq_n_u8 ('\\');
661 const uint8x16_t repl_qm = vdupq_n_u8 ('?');
662 const uint8x16_t xmask = (uint8x16_t) vdupq_n_u64 (0x8040201008040201ULL);
663
664 #ifdef __ARM_BIG_ENDIAN
665 const int16x8_t shift = {8, 8, 8, 8, 0, 0, 0, 0};
666 #else
667 const int16x8_t shift = {0, 0, 0, 0, 8, 8, 8, 8};
668 #endif
669
670 unsigned int found;
671 const uint8_t *p;
672 uint8x16_t data;
673 uint8x16_t t;
674 uint16x8_t m;
675 uint8x16_t u, v, w;
676
677 /* Align the source pointer. */
678 p = (const uint8_t *)((uintptr_t)s & -16);
679
680 /* Assuming random string start positions, with a 4k page size we'll take
681 the slow path about 0.37% of the time. */
682 if (__builtin_expect ((AARCH64_MIN_PAGE_SIZE
683 - (((uintptr_t) s) & (AARCH64_MIN_PAGE_SIZE - 1)))
684 < 16, 0))
685 {
686 /* Slow path: the string starts near a possible page boundary. */
687 uint32_t misalign, mask;
688
689 misalign = (uintptr_t)s & 15;
690 mask = (-1u << misalign) & 0xffff;
691 data = vld1q_u8 (p);
692 t = vceqq_u8 (data, repl_nl);
693 u = vceqq_u8 (data, repl_cr);
694 v = vorrq_u8 (t, vceqq_u8 (data, repl_bs));
695 w = vorrq_u8 (u, vceqq_u8 (data, repl_qm));
696 t = vorrq_u8 (v, w);
697 t = vandq_u8 (t, xmask);
698 m = vpaddlq_u8 (t);
699 m = vshlq_u16 (m, shift);
700 found = vaddvq_u16 (m);
701 found &= mask;
702 if (found)
703 return (const uchar*)p + __builtin_ctz (found);
704 }
705 else
706 {
707 data = vld1q_u8 ((const uint8_t *) s);
708 t = vceqq_u8 (data, repl_nl);
709 u = vceqq_u8 (data, repl_cr);
710 v = vorrq_u8 (t, vceqq_u8 (data, repl_bs));
711 w = vorrq_u8 (u, vceqq_u8 (data, repl_qm));
712 t = vorrq_u8 (v, w);
713 if (__builtin_expect (vpaddd_u64 ((uint64x2_t)t) != 0, 0))
714 goto done;
715 }
716
717 do
718 {
719 p += 16;
720 data = vld1q_u8 (p);
721 t = vceqq_u8 (data, repl_nl);
722 u = vceqq_u8 (data, repl_cr);
723 v = vorrq_u8 (t, vceqq_u8 (data, repl_bs));
724 w = vorrq_u8 (u, vceqq_u8 (data, repl_qm));
725 t = vorrq_u8 (v, w);
726 } while (!vpaddd_u64 ((uint64x2_t)t));
727
728 done:
729 /* Now that we've found the terminating substring, work out precisely where
730 we need to stop. */
731 t = vandq_u8 (t, xmask);
732 m = vpaddlq_u8 (t);
733 m = vshlq_u16 (m, shift);
734 found = vaddvq_u16 (m);
735 return (((((uintptr_t) p) < (uintptr_t) s) ? s : (const uchar *)p)
736 + __builtin_ctz (found));
737 }
738
739 #elif defined (__ARM_NEON)
740 #include "arm_neon.h"
741
742 static const uchar *
743 search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED)
744 {
745 const uint8x16_t repl_nl = vdupq_n_u8 ('\n');
746 const uint8x16_t repl_cr = vdupq_n_u8 ('\r');
747 const uint8x16_t repl_bs = vdupq_n_u8 ('\\');
748 const uint8x16_t repl_qm = vdupq_n_u8 ('?');
749 const uint8x16_t xmask = (uint8x16_t) vdupq_n_u64 (0x8040201008040201ULL);
750
751 unsigned int misalign, found, mask;
752 const uint8_t *p;
753 uint8x16_t data;
754
755 /* Align the source pointer. */
756 misalign = (uintptr_t)s & 15;
757 p = (const uint8_t *)((uintptr_t)s & -16);
758 data = vld1q_u8 (p);
759
760 /* Create a mask for the bytes that are valid within the first
761 16-byte block. The Idea here is that the AND with the mask
762 within the loop is "free", since we need some AND or TEST
763 insn in order to set the flags for the branch anyway. */
764 mask = (-1u << misalign) & 0xffff;
765
766 /* Main loop, processing 16 bytes at a time. */
767 goto start;
768
769 do
770 {
771 uint8x8_t l;
772 uint16x4_t m;
773 uint32x2_t n;
774 uint8x16_t t, u, v, w;
775
776 p += 16;
777 data = vld1q_u8 (p);
778 mask = 0xffff;
779
780 start:
781 t = vceqq_u8 (data, repl_nl);
782 u = vceqq_u8 (data, repl_cr);
783 v = vorrq_u8 (t, vceqq_u8 (data, repl_bs));
784 w = vorrq_u8 (u, vceqq_u8 (data, repl_qm));
785 t = vandq_u8 (vorrq_u8 (v, w), xmask);
786 l = vpadd_u8 (vget_low_u8 (t), vget_high_u8 (t));
787 m = vpaddl_u8 (l);
788 n = vpaddl_u16 (m);
789
790 found = vget_lane_u32 ((uint32x2_t) vorr_u64 ((uint64x1_t) n,
791 vshr_n_u64 ((uint64x1_t) n, 24)), 0);
792 found &= mask;
793 }
794 while (!found);
795
796 /* FOUND contains 1 in bits for which we matched a relevant
797 character. Conversion to the byte index is trivial. */
798 found = __builtin_ctz (found);
799 return (const uchar *)p + found;
800 }
801
802 #else
803
804 /* We only have one accelerated alternative. Use a direct call so that
805 we encourage inlining. */
806
807 #define search_line_fast search_line_acc_char
808
809 #endif
810
811 /* Initialize the lexer if needed. */
812
813 void
814 _cpp_init_lexer (void)
815 {
816 #ifdef HAVE_init_vectorized_lexer
817 init_vectorized_lexer ();
818 #endif
819 }
820
821 /* Look for leading whitespace style issues on lines which don't contain
822 just whitespace.
823 For -Wleading-whitespace=spaces report if such lines contain leading
824 whitespace other than spaces.
825 For -Wleading-whitespace=tabs report if such lines contain leading
826 whitespace other than tabs.
827 For -Wleading-whitespace=blanks report if such lines contain leading
828 whitespace other than spaces+tabs, or contain in it tab after space,
829 or -ftabstop= or more consecutive spaces. */
830
831 static void
832 find_leading_whitespace_issues (cpp_reader *pfile, const uchar *s)
833 {
834 const unsigned char *p = NULL;
835 uchar type = 'L';
836 switch (CPP_OPTION (pfile, cpp_warn_leading_whitespace))
837 {
838 case 1: /* spaces */
839 while (*s == ' ')
840 ++s;
841 break;
842 case 2: /* tabs */
843 while (*s == '\t')
844 ++s;
845 break;
846 case 3: /* blanks */
847 while (*s == '\t')
848 ++s;
849 int n;
850 n = CPP_OPTION (pfile, cpp_tabstop);
851 while (*s == ' ')
852 {
853 if (--n == 0)
854 break;
855 ++s;
856 }
857 if (*s == '\t')
858 type = 'T'; /* Tab after space. */
859 else if (*s == ' ')
860 type = 'S'; /* Too many spaces. */
861 break;
862 default:
863 abort ();
864 }
865 if (!IS_NVSPACE (*s))
866 return;
867 p = s++;
868 while (IS_NVSPACE (*s))
869 ++s;
870 if (*s != '\n' && *s != '\r')
871 add_line_note (pfile->buffer, p, type);
872 }
873
874 /* Returns with a logical line that contains no escaped newlines or
875 trigraphs. This is a time-critical inner loop. */
876 void
877 _cpp_clean_line (cpp_reader *pfile)
878 {
879 cpp_buffer *buffer;
880 const uchar *s;
881 uchar c, *d, *p;
882
883 buffer = pfile->buffer;
884 buffer->cur_note = buffer->notes_used = 0;
885 buffer->cur = buffer->line_base = buffer->next_line;
886 buffer->need_line = false;
887 s = buffer->next_line;
888
889 if (!buffer->from_stage3)
890 {
891 const uchar *pbackslash = NULL;
892 bool leading_ws_done = true;
893
894 if (CPP_OPTION (pfile, cpp_warn_leading_whitespace))
895 find_leading_whitespace_issues (pfile, s);
896
897 /* Fast path. This is the common case of an un-escaped line with
898 no trigraphs. The primary win here is by not writing any
899 data back to memory until we have to. */
900 while (1)
901 {
902 /* Perform an optimized search for \n, \r, \\, ?. */
903 s = search_line_fast (s, buffer->rlimit);
904
905 c = *s;
906 if (c == '\\')
907 {
908 /* Record the location of the backslash and continue. */
909 pbackslash = s++;
910 }
911 else if (__builtin_expect (c == '?', 0))
912 {
913 if (__builtin_expect (s[1] == '?', false)
914 && _cpp_trigraph_map[s[2]])
915 {
916 /* Have a trigraph. We may or may not have to convert
917 it. Add a line note regardless, for -Wtrigraphs. */
918 add_line_note (buffer, s, s[2]);
919 if (CPP_OPTION (pfile, trigraphs))
920 {
921 /* We do, and that means we have to switch to the
922 slow path. */
923 d = (uchar *) s;
924 *d = _cpp_trigraph_map[s[2]];
925 s += 2;
926 goto slow_path;
927 }
928 }
929 /* Not a trigraph. Continue on fast-path. */
930 s++;
931 }
932 else
933 break;
934 }
935
936 /* This must be \r or \n. We're either done, or we'll be forced
937 to write back to the buffer and continue on the slow path. */
938 d = (uchar *) s;
939
940 if (__builtin_expect (s == buffer->rlimit, false))
941 goto done;
942
943 /* DOS line ending? */
944 if (__builtin_expect (c == '\r', false) && s[1] == '\n')
945 {
946 s++;
947 if (s == buffer->rlimit)
948 goto done;
949 }
950
951 if (__builtin_expect (pbackslash == NULL, true))
952 goto done;
953
954 /* Check for escaped newline. */
955 p = d;
956 while (is_nvspace (p[-1]))
957 p--;
958 if (p - 1 != pbackslash)
959 goto done;
960
961 /* Have an escaped newline; process it and proceed to
962 the slow path. */
963 add_line_note (buffer, p - 1, p != d ? ' ' : '\\');
964 d = p - 2;
965 buffer->next_line = p - 1;
966 leading_ws_done = false;
967
968 slow_path:
969 while (1)
970 {
971 c = *++s;
972 *++d = c;
973
974 if (c == '\n' || c == '\r')
975 {
976 if (CPP_OPTION (pfile, cpp_warn_leading_whitespace)
977 && !leading_ws_done)
978 find_leading_whitespace_issues (pfile, buffer->next_line);
979
980 /* Handle DOS line endings. */
981 if (c == '\r' && s != buffer->rlimit && s[1] == '\n')
982 s++;
983 if (s == buffer->rlimit)
984 break;
985
986 /* Escaped? */
987 p = d;
988 while (p != buffer->next_line && is_nvspace (p[-1]))
989 p--;
990 if (p == buffer->next_line || p[-1] != '\\')
991 break;
992
993 add_line_note (buffer, p - 1, p != d ? ' ' : '\\');
994 d = p - 2;
995 buffer->next_line = p - 1;
996 leading_ws_done = false;
997 }
998 else if (c == '?' && s[1] == '?' && _cpp_trigraph_map[s[2]])
999 {
1000 if (CPP_OPTION (pfile, cpp_warn_leading_whitespace)
1001 && !leading_ws_done)
1002 {
1003 find_leading_whitespace_issues (pfile, buffer->next_line);
1004 leading_ws_done = true;
1005 }
1006
1007 /* Add a note regardless, for the benefit of -Wtrigraphs. */
1008 add_line_note (buffer, d, s[2]);
1009 if (CPP_OPTION (pfile, trigraphs))
1010 {
1011 *d = _cpp_trigraph_map[s[2]];
1012 s += 2;
1013 }
1014 }
1015 }
1016 done:
1017 if (d > buffer->next_line
1018 && CPP_OPTION (pfile, cpp_warn_trailing_whitespace))
1019 switch (CPP_OPTION (pfile, cpp_warn_trailing_whitespace))
1020 {
1021 case 1:
1022 if (ISBLANK (d[-1]))
1023 add_line_note (buffer, d - 1, 'W');
1024 break;
1025 case 2:
1026 if (IS_NVSPACE (d[-1]) && d[-1])
1027 add_line_note (buffer, d - 1, 'W');
1028 break;
1029 }
1030 }
1031 else
1032 {
1033 while (*s != '\n' && *s != '\r')
1034 s++;
1035 d = (uchar *) s;
1036
1037 /* Handle DOS line endings. */
1038 if (*s == '\r' && s + 1 != buffer->rlimit && s[1] == '\n')
1039 s++;
1040 }
1041
1042 *d = '\n';
1043 /* A sentinel note that should never be processed. */
1044 add_line_note (buffer, d + 1, '\n');
1045 buffer->next_line = s + 1;
1046 }
1047
1048 template <bool lexing_raw_string>
1049 static bool get_fresh_line_impl (cpp_reader *pfile);
1050
1051 /* Return true if the trigraph indicated by NOTE should be warned
1052 about in a comment. */
1053 static bool
1054 warn_in_comment (cpp_reader *pfile, _cpp_line_note *note)
1055 {
1056 const uchar *p;
1057
1058 /* Within comments we don't warn about trigraphs, unless the
1059 trigraph forms an escaped newline, as that may change
1060 behavior. */
1061 if (note->type != '/')
1062 return false;
1063
1064 /* If -trigraphs, then this was an escaped newline iff the next note
1065 is coincident. */
1066 if (CPP_OPTION (pfile, trigraphs))
1067 return note[1].pos == note->pos;
1068
1069 /* Otherwise, see if this forms an escaped newline. */
1070 p = note->pos + 3;
1071 while (is_nvspace (*p))
1072 p++;
1073
1074 /* There might have been escaped newlines between the trigraph and the
1075 newline we found. Hence the position test. */
1076 return (*p == '\n' && p < note[1].pos);
1077 }
1078
1079 /* Process the notes created by add_line_note as far as the current
1080 location. */
1081 void
1082 _cpp_process_line_notes (cpp_reader *pfile, int in_comment)
1083 {
1084 cpp_buffer *buffer = pfile->buffer;
1085
1086 for (;;)
1087 {
1088 _cpp_line_note *note = &buffer->notes[buffer->cur_note];
1089 unsigned int col;
1090
1091 if (note->pos > buffer->cur)
1092 break;
1093
1094 buffer->cur_note++;
1095 col = CPP_BUF_COLUMN (buffer, note->pos + 1);
1096
1097 if (note->type == '\\' || note->type == ' ')
1098 {
1099 if (note->type == ' ')
1100 {
1101 if (!in_comment)
1102 cpp_error_with_line (pfile, CPP_DL_WARNING,
1103 pfile->line_table->highest_line, col,
1104 "backslash and newline separated by "
1105 "space");
1106 else if (CPP_OPTION (pfile, cpp_warn_trailing_whitespace))
1107 cpp_warning_with_line (pfile, CPP_W_TRAILING_WHITESPACE,
1108 pfile->line_table->highest_line, col,
1109 "trailing whitespace");
1110 }
1111
1112 if (buffer->next_line > buffer->rlimit)
1113 {
1114 cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1115 pfile->line_table->highest_line, col,
1116 "backslash-newline at end of file");
1117 /* Prevent "no newline at end of file" warning. */
1118 buffer->next_line = buffer->rlimit;
1119 }
1120
1121 buffer->line_base = note->pos;
1122 CPP_INCREMENT_LINE (pfile, 0);
1123 }
1124 else if (_cpp_trigraph_map[note->type])
1125 {
1126 if (CPP_OPTION (pfile, warn_trigraphs)
1127 && (!in_comment || warn_in_comment (pfile, note)))
1128 {
1129 if (CPP_OPTION (pfile, trigraphs))
1130 cpp_warning_with_line (pfile, CPP_W_TRIGRAPHS,
1131 pfile->line_table->highest_line, col,
1132 "trigraph %<??%c%> converted to %<%c%>",
1133 note->type,
1134 (int) _cpp_trigraph_map[note->type]);
1135 else
1136 cpp_warning_with_line (pfile, CPP_W_TRIGRAPHS,
1137 pfile->line_table->highest_line, col,
1138 "trigraph %<??%c%> ignored, use "
1139 "%<-trigraphs%> to enable", note->type);
1140 }
1141 }
1142 else if (note->type == 'W')
1143 cpp_warning_with_line (pfile, CPP_W_TRAILING_WHITESPACE,
1144 pfile->line_table->highest_line, col,
1145 "trailing whitespace");
1146 else if (note->type == 'S')
1147 cpp_warning_with_line (pfile, CPP_W_LEADING_WHITESPACE,
1148 pfile->line_table->highest_line, col,
1149 "too many consecutive spaces in leading "
1150 "whitespace");
1151 else if (note->type == 'T')
1152 cpp_warning_with_line (pfile, CPP_W_LEADING_WHITESPACE,
1153 pfile->line_table->highest_line, col,
1154 "tab after space in leading whitespace");
1155 else if (note->type == 'L')
1156 switch (CPP_OPTION (pfile, cpp_warn_leading_whitespace))
1157 {
1158 case 1:
1159 cpp_warning_with_line (pfile, CPP_W_LEADING_WHITESPACE,
1160 pfile->line_table->highest_line, col,
1161 "whitespace other than spaces in leading "
1162 "whitespace");
1163 break;
1164 case 2:
1165 cpp_warning_with_line (pfile, CPP_W_LEADING_WHITESPACE,
1166 pfile->line_table->highest_line, col,
1167 "whitespace other than tabs in leading "
1168 "whitespace");
1169 break;
1170 case 3:
1171 cpp_warning_with_line (pfile, CPP_W_LEADING_WHITESPACE,
1172 pfile->line_table->highest_line, col,
1173 "whitespace other than spaces and tabs in "
1174 "leading whitespace");
1175 break;
1176 default:
1177 abort ();
1178 }
1179 else if (note->type == 0)
1180 /* Already processed in lex_raw_string. */;
1181 else
1182 abort ();
1183 }
1184 }
1185
1186 namespace bidi {
1187 enum class kind {
1188 NONE, LRE, RLE, LRO, RLO, LRI, RLI, FSI, PDF, PDI, LTR, RTL
1189 };
1190
1191 /* All the UTF-8 encodings of bidi characters start with E2. */
1192 constexpr uchar utf8_start = 0xe2;
1193
1194 struct context
1195 {
1196 context () {}
1197 context (location_t loc, kind k, bool pdf, bool ucn)
1198 : m_loc (loc), m_kind (k), m_pdf (pdf), m_ucn (ucn)
1199 {
1200 }
1201
1202 kind get_pop_kind () const
1203 {
1204 return m_pdf ? kind::PDF : kind::PDI;
1205 }
1206 bool ucn_p () const
1207 {
1208 return m_ucn;
1209 }
1210
1211 location_t m_loc;
1212 kind m_kind;
1213 unsigned m_pdf : 1;
1214 unsigned m_ucn : 1;
1215 };
1216
1217 /* A vector holding currently open bidi contexts. We use a char for
1218 each context, its LSB is 1 if it represents a PDF context, 0 if it
1219 represents a PDI context. The next bit is 1 if this context was open
1220 by a bidi character written as a UCN, and 0 when it was UTF-8. */
1221 semi_embedded_vec <context, 16> vec;
1222
1223 /* Close the whole comment/identifier/string literal/character constant
1224 context. */
1225 void on_close ()
1226 {
1227 vec.truncate (0);
1228 }
1229
1230 /* Pop the last element in the vector. */
1231 void pop ()
1232 {
1233 unsigned int len = vec.count ();
1234 gcc_checking_assert (len > 0);
1235 vec.truncate (len - 1);
1236 }
1237
1238 /* Return the pop kind of the context of the Ith element. */
1239 kind pop_kind_at (unsigned int i)
1240 {
1241 return vec[i].get_pop_kind ();
1242 }
1243
1244 /* Return the pop kind of the context that is currently opened. */
1245 kind current_ctx ()
1246 {
1247 unsigned int len = vec.count ();
1248 if (len == 0)
1249 return kind::NONE;
1250 return vec[len - 1].get_pop_kind ();
1251 }
1252
1253 /* Return true if the current context comes from a UCN origin, that is,
1254 the bidi char which started this bidi context was written as a UCN. */
1255 bool current_ctx_ucn_p ()
1256 {
1257 unsigned int len = vec.count ();
1258 gcc_checking_assert (len > 0);
1259 return vec[len - 1].m_ucn;
1260 }
1261
1262 location_t current_ctx_loc ()
1263 {
1264 unsigned int len = vec.count ();
1265 gcc_checking_assert (len > 0);
1266 return vec[len - 1].m_loc;
1267 }
1268
1269 /* We've read a bidi char, update the current vector as necessary.
1270 LOC is only valid when K is not kind::NONE. */
1271 void on_char (kind k, bool ucn_p, location_t loc)
1272 {
1273 switch (k)
1274 {
1275 case kind::LRE:
1276 case kind::RLE:
1277 case kind::LRO:
1278 case kind::RLO:
1279 vec.push (context (loc, k, true, ucn_p));
1280 break;
1281 case kind::LRI:
1282 case kind::RLI:
1283 case kind::FSI:
1284 vec.push (context (loc, k, false, ucn_p));
1285 break;
1286 /* PDF terminates the scope of the last LRE, RLE, LRO, or RLO
1287 whose scope has not yet been terminated. */
1288 case kind::PDF:
1289 if (current_ctx () == kind::PDF)
1290 pop ();
1291 break;
1292 /* PDI terminates the scope of the last LRI, RLI, or FSI whose
1293 scope has not yet been terminated, as well as the scopes of
1294 any subsequent LREs, RLEs, LROs, or RLOs whose scopes have not
1295 yet been terminated. */
1296 case kind::PDI:
1297 for (int i = vec.count () - 1; i >= 0; --i)
1298 if (pop_kind_at (i) == kind::PDI)
1299 {
1300 vec.truncate (i);
1301 break;
1302 }
1303 break;
1304 case kind::LTR:
1305 case kind::RTL:
1306 /* These aren't popped by a PDF/PDI. */
1307 break;
1308 ATTR_LIKELY case kind::NONE:
1309 break;
1310 default:
1311 abort ();
1312 }
1313 }
1314
1315 /* Return a descriptive string for K. */
1316 const char *to_str (kind k)
1317 {
1318 switch (k)
1319 {
1320 case kind::LRE:
1321 return "U+202A (LEFT-TO-RIGHT EMBEDDING)";
1322 case kind::RLE:
1323 return "U+202B (RIGHT-TO-LEFT EMBEDDING)";
1324 case kind::LRO:
1325 return "U+202D (LEFT-TO-RIGHT OVERRIDE)";
1326 case kind::RLO:
1327 return "U+202E (RIGHT-TO-LEFT OVERRIDE)";
1328 case kind::LRI:
1329 return "U+2066 (LEFT-TO-RIGHT ISOLATE)";
1330 case kind::RLI:
1331 return "U+2067 (RIGHT-TO-LEFT ISOLATE)";
1332 case kind::FSI:
1333 return "U+2068 (FIRST STRONG ISOLATE)";
1334 case kind::PDF:
1335 return "U+202C (POP DIRECTIONAL FORMATTING)";
1336 case kind::PDI:
1337 return "U+2069 (POP DIRECTIONAL ISOLATE)";
1338 case kind::LTR:
1339 return "U+200E (LEFT-TO-RIGHT MARK)";
1340 case kind::RTL:
1341 return "U+200F (RIGHT-TO-LEFT MARK)";
1342 default:
1343 abort ();
1344 }
1345 }
1346 }
1347
1348 /* Get location_t for the range of bytes [START, START + NUM_BYTES)
1349 within the current line in FILE, with the caret at START. */
1350
1351 static location_t
1352 get_location_for_byte_range_in_cur_line (cpp_reader *pfile,
1353 const unsigned char *const start,
1354 size_t num_bytes)
1355 {
1356 gcc_checking_assert (num_bytes > 0);
1357
1358 /* CPP_BUF_COLUMN and linemap_position_for_column both refer
1359 to offsets in bytes, but CPP_BUF_COLUMN is 0-based,
1360 whereas linemap_position_for_column is 1-based. */
1361
1362 /* Get 0-based offsets within the line. */
1363 size_t start_offset = CPP_BUF_COLUMN (pfile->buffer, start);
1364 size_t end_offset = start_offset + num_bytes - 1;
1365
1366 /* Now convert to location_t, where "columns" are 1-based byte offsets. */
1367 location_t start_loc = linemap_position_for_column (pfile->line_table,
1368 start_offset + 1);
1369 location_t end_loc = linemap_position_for_column (pfile->line_table,
1370 end_offset + 1);
1371
1372 if (start_loc == end_loc)
1373 return start_loc;
1374
1375 source_range src_range;
1376 src_range.m_start = start_loc;
1377 src_range.m_finish = end_loc;
1378 location_t combined_loc
1379 = pfile->line_table->get_or_create_combined_loc (start_loc,
1380 src_range,
1381 nullptr,
1382 0);
1383 return combined_loc;
1384 }
1385
1386 /* Parse a sequence of 3 bytes starting with P and return its bidi code. */
1387
1388 static bidi::kind
1389 get_bidi_utf8_1 (const unsigned char *const p)
1390 {
1391 gcc_checking_assert (p[0] == bidi::utf8_start);
1392
1393 if (p[1] == 0x80)
1394 switch (p[2])
1395 {
1396 case 0xaa:
1397 return bidi::kind::LRE;
1398 case 0xab:
1399 return bidi::kind::RLE;
1400 case 0xac:
1401 return bidi::kind::PDF;
1402 case 0xad:
1403 return bidi::kind::LRO;
1404 case 0xae:
1405 return bidi::kind::RLO;
1406 case 0x8e:
1407 return bidi::kind::LTR;
1408 case 0x8f:
1409 return bidi::kind::RTL;
1410 default:
1411 break;
1412 }
1413 else if (p[1] == 0x81)
1414 switch (p[2])
1415 {
1416 case 0xa6:
1417 return bidi::kind::LRI;
1418 case 0xa7:
1419 return bidi::kind::RLI;
1420 case 0xa8:
1421 return bidi::kind::FSI;
1422 case 0xa9:
1423 return bidi::kind::PDI;
1424 default:
1425 break;
1426 }
1427
1428 return bidi::kind::NONE;
1429 }
1430
1431 /* Parse a sequence of 3 bytes starting with P and return its bidi code.
1432 If the kind is not NONE, write the location to *OUT.*/
1433
1434 static bidi::kind
1435 get_bidi_utf8 (cpp_reader *pfile, const unsigned char *const p, location_t *out)
1436 {
1437 bidi::kind result = get_bidi_utf8_1 (p);
1438 if (result != bidi::kind::NONE)
1439 {
1440 /* We have a sequence of 3 bytes starting at P. */
1441 *out = get_location_for_byte_range_in_cur_line (pfile, p, 3);
1442 }
1443 return result;
1444 }
1445
1446 /* Parse a UCN where P points just past \u or \U and return its bidi code. */
1447
1448 static bidi::kind
1449 get_bidi_ucn_1 (const unsigned char *p, bool is_U, const unsigned char **end)
1450 {
1451 /* 6.4.3 Universal Character Names
1452 \u hex-quad
1453 \U hex-quad hex-quad
1454 \u { simple-hexadecimal-digit-sequence }
1455 where \unnnn means \U0000nnnn. */
1456
1457 *end = p + 4;
1458 if (is_U)
1459 {
1460 if (p[0] != '0' || p[1] != '0' || p[2] != '0' || p[3] != '0')
1461 return bidi::kind::NONE;
1462 /* Skip 4B so we can treat \u and \U the same below. */
1463 p += 4;
1464 *end += 4;
1465 }
1466 else if (p[0] == '{')
1467 {
1468 p++;
1469 while (*p == '0')
1470 p++;
1471 if (p[0] != '2'
1472 || p[1] != '0'
1473 || !ISXDIGIT (p[2])
1474 || !ISXDIGIT (p[3])
1475 || p[4] != '}')
1476 return bidi::kind::NONE;
1477 *end = p + 5;
1478 }
1479
1480 /* All code points we are looking for start with 20xx. */
1481 if (p[0] != '2' || p[1] != '0')
1482 return bidi::kind::NONE;
1483 else if (p[2] == '2')
1484 switch (p[3])
1485 {
1486 case 'a':
1487 case 'A':
1488 return bidi::kind::LRE;
1489 case 'b':
1490 case 'B':
1491 return bidi::kind::RLE;
1492 case 'c':
1493 case 'C':
1494 return bidi::kind::PDF;
1495 case 'd':
1496 case 'D':
1497 return bidi::kind::LRO;
1498 case 'e':
1499 case 'E':
1500 return bidi::kind::RLO;
1501 default:
1502 break;
1503 }
1504 else if (p[2] == '6')
1505 switch (p[3])
1506 {
1507 case '6':
1508 return bidi::kind::LRI;
1509 case '7':
1510 return bidi::kind::RLI;
1511 case '8':
1512 return bidi::kind::FSI;
1513 case '9':
1514 return bidi::kind::PDI;
1515 default:
1516 break;
1517 }
1518 else if (p[2] == '0')
1519 switch (p[3])
1520 {
1521 case 'e':
1522 case 'E':
1523 return bidi::kind::LTR;
1524 case 'f':
1525 case 'F':
1526 return bidi::kind::RTL;
1527 default:
1528 break;
1529 }
1530
1531 return bidi::kind::NONE;
1532 }
1533
1534 /* Parse a UCN where P points just past \u or \U and return its bidi code.
1535 If the kind is not NONE, write the location to *OUT. */
1536
1537 static bidi::kind
1538 get_bidi_ucn (cpp_reader *pfile, const unsigned char *p, bool is_U,
1539 location_t *out)
1540 {
1541 const unsigned char *end;
1542 bidi::kind result = get_bidi_ucn_1 (p, is_U, &end);
1543 if (result != bidi::kind::NONE)
1544 {
1545 const unsigned char *start = p - 2;
1546 size_t num_bytes = end - start;
1547 *out = get_location_for_byte_range_in_cur_line (pfile, start, num_bytes);
1548 }
1549 return result;
1550 }
1551
1552 /* Parse a named universal character escape where P points just past \N and
1553 return its bidi code. If the kind is not NONE, write the location to
1554 *OUT. */
1555
1556 static bidi::kind
1557 get_bidi_named (cpp_reader *pfile, const unsigned char *p, location_t *out)
1558 {
1559 bidi::kind result = bidi::kind::NONE;
1560 if (*p != '{')
1561 return bidi::kind::NONE;
1562 if (strncmp ((const char *) (p + 1), "LEFT-TO-RIGHT ", 14) == 0)
1563 {
1564 if (strncmp ((const char *) (p + 15), "MARK}", 5) == 0)
1565 result = bidi::kind::LTR;
1566 else if (strncmp ((const char *) (p + 15), "EMBEDDING}", 10) == 0)
1567 result = bidi::kind::LRE;
1568 else if (strncmp ((const char *) (p + 15), "OVERRIDE}", 9) == 0)
1569 result = bidi::kind::LRO;
1570 else if (strncmp ((const char *) (p + 15), "ISOLATE}", 8) == 0)
1571 result = bidi::kind::LRI;
1572 }
1573 else if (strncmp ((const char *) (p + 1), "RIGHT-TO-LEFT ", 14) == 0)
1574 {
1575 if (strncmp ((const char *) (p + 15), "MARK}", 5) == 0)
1576 result = bidi::kind::RTL;
1577 else if (strncmp ((const char *) (p + 15), "EMBEDDING}", 10) == 0)
1578 result = bidi::kind::RLE;
1579 else if (strncmp ((const char *) (p + 15), "OVERRIDE}", 9) == 0)
1580 result = bidi::kind::RLO;
1581 else if (strncmp ((const char *) (p + 15), "ISOLATE}", 8) == 0)
1582 result = bidi::kind::RLI;
1583 }
1584 else if (strncmp ((const char *) (p + 1), "POP DIRECTIONAL ", 16) == 0)
1585 {
1586 if (strncmp ((const char *) (p + 16), "FORMATTING}", 11) == 0)
1587 result = bidi::kind::PDF;
1588 else if (strncmp ((const char *) (p + 16), "ISOLATE}", 8) == 0)
1589 result = bidi::kind::PDI;
1590 }
1591 else if (strncmp ((const char *) (p + 1), "FIRST STRONG ISOLATE}", 21) == 0)
1592 result = bidi::kind::FSI;
1593 if (result != bidi::kind::NONE)
1594 *out = get_location_for_byte_range_in_cur_line (pfile, p - 2,
1595 (strchr ((const char *)
1596 (p + 1), '}')
1597 - (const char *) p)
1598 + 3);
1599 return result;
1600 }
1601
1602 /* Subclass of rich_location for reporting on unpaired UTF-8
1603 bidirectional control character(s).
1604 Escape the source lines on output, and show all unclosed
1605 bidi context, labelling everything. */
1606
1607 class unpaired_bidi_rich_location : public rich_location
1608 {
1609 public:
1610 class custom_range_label : public range_label
1611 {
1612 public:
1613 label_text get_text (unsigned range_idx) const final override
1614 {
1615 /* range 0 is the primary location; each subsequent range i + 1
1616 is for bidi::vec[i]. */
1617 if (range_idx > 0)
1618 {
1619 const bidi::context &ctxt (bidi::vec[range_idx - 1]);
1620 return label_text::borrow (bidi::to_str (ctxt.m_kind));
1621 }
1622 else
1623 return label_text::borrow (_("end of bidirectional context"));
1624 }
1625 };
1626
1627 unpaired_bidi_rich_location (cpp_reader *pfile, location_t loc)
1628 : rich_location (pfile->line_table, loc, &m_custom_label)
1629 {
1630 set_escape_on_output (true);
1631 for (unsigned i = 0; i < bidi::vec.count (); i++)
1632 add_range (bidi::vec[i].m_loc,
1633 SHOW_RANGE_WITHOUT_CARET,
1634 &m_custom_label);
1635 }
1636
1637 private:
1638 custom_range_label m_custom_label;
1639 };
1640
1641 /* We're closing a bidi context, that is, we've encountered a newline,
1642 are closing a C-style comment, or are at the end of a string literal,
1643 character constant, or identifier. Warn if this context was not
1644 properly terminated by a PDI or PDF. P points to the last character
1645 in this context. */
1646
1647 static void
1648 maybe_warn_bidi_on_close (cpp_reader *pfile, const uchar *p)
1649 {
1650 const auto warn_bidi = CPP_OPTION (pfile, cpp_warn_bidirectional);
1651 if (bidi::vec.count () > 0
1652 && (warn_bidi & bidirectional_unpaired
1653 && (!bidi::current_ctx_ucn_p ()
1654 || (warn_bidi & bidirectional_ucn))))
1655 {
1656 const location_t loc
1657 = linemap_position_for_column (pfile->line_table,
1658 CPP_BUF_COLUMN (pfile->buffer, p));
1659 unpaired_bidi_rich_location rich_loc (pfile, loc);
1660 /* cpp_callbacks doesn't yet have a way to handle singular vs plural
1661 forms of a diagnostic, so fake it for now. */
1662 if (bidi::vec.count () > 1)
1663 cpp_warning_at (pfile, CPP_W_BIDIRECTIONAL, &rich_loc,
1664 "unpaired UTF-8 bidirectional control characters "
1665 "detected");
1666 else
1667 cpp_warning_at (pfile, CPP_W_BIDIRECTIONAL, &rich_loc,
1668 "unpaired UTF-8 bidirectional control character "
1669 "detected");
1670 }
1671 /* We're done with this context. */
1672 bidi::on_close ();
1673 }
1674
1675 /* We're at the beginning or in the middle of an identifier/comment/string
1676 literal/character constant. Warn if we've encountered a bidi character.
1677 KIND says which bidi control character it was; UCN_P is true iff this bidi
1678 control character was written as a UCN. LOC is the location of the
1679 character, but is only valid if KIND != bidi::kind::NONE. */
1680
1681 static void
1682 maybe_warn_bidi_on_char (cpp_reader *pfile, bidi::kind kind,
1683 bool ucn_p, location_t loc)
1684 {
1685 if (__builtin_expect (kind == bidi::kind::NONE, 1))
1686 return;
1687
1688 const auto warn_bidi = CPP_OPTION (pfile, cpp_warn_bidirectional);
1689
1690 if (warn_bidi & (bidirectional_unpaired|bidirectional_any))
1691 {
1692 rich_location rich_loc (pfile->line_table, loc);
1693 rich_loc.set_escape_on_output (true);
1694
1695 /* It seems excessive to warn about a PDI/PDF that is closing
1696 an opened context because we've already warned about the
1697 opening character. Except warn when we have a UCN x UTF-8
1698 mismatch, if UCN checking is enabled. */
1699 if (kind == bidi::current_ctx ())
1700 {
1701 if (warn_bidi == (bidirectional_unpaired|bidirectional_ucn)
1702 && bidi::current_ctx_ucn_p () != ucn_p)
1703 {
1704 rich_loc.add_range (bidi::current_ctx_loc ());
1705 cpp_warning_at (pfile, CPP_W_BIDIRECTIONAL, &rich_loc,
1706 "UTF-8 vs UCN mismatch when closing "
1707 "a context by %qs", bidi::to_str (kind));
1708 }
1709 }
1710 else if (warn_bidi & bidirectional_any
1711 && (!ucn_p || (warn_bidi & bidirectional_ucn)))
1712 {
1713 if (kind == bidi::kind::PDF || kind == bidi::kind::PDI)
1714 cpp_warning_at (pfile, CPP_W_BIDIRECTIONAL, &rich_loc,
1715 "%qs is closing an unopened context",
1716 bidi::to_str (kind));
1717 else
1718 cpp_warning_at (pfile, CPP_W_BIDIRECTIONAL, &rich_loc,
1719 "found problematic Unicode character %qs",
1720 bidi::to_str (kind));
1721 }
1722 }
1723 /* We're done with this context. */
1724 bidi::on_char (kind, ucn_p, loc);
1725 }
1726
1727 static const cppchar_t utf8_continuation = 0x80;
1728 static const cppchar_t utf8_signifier = 0xC0;
1729
1730 /* Emit -Winvalid-utf8 warning on invalid UTF-8 character starting
1731 at PFILE->buffer->cur. Return a pointer after the diagnosed
1732 invalid character. */
1733
1734 static const uchar *
1735 _cpp_warn_invalid_utf8 (cpp_reader *pfile)
1736 {
1737 cpp_buffer *buffer = pfile->buffer;
1738 const uchar *cur = buffer->cur;
1739 bool pedantic = (CPP_PEDANTIC (pfile)
1740 && CPP_OPTION (pfile, cpp_warn_invalid_utf8) == 2);
1741
1742 if (cur[0] < utf8_signifier
1743 || cur[1] < utf8_continuation || cur[1] >= utf8_signifier)
1744 {
1745 if (pedantic)
1746 cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1747 pfile->line_table->highest_line,
1748 CPP_BUF_COL (buffer),
1749 "invalid UTF-8 character %<<%x>%>",
1750 cur[0]);
1751 else
1752 cpp_warning_with_line (pfile, CPP_W_INVALID_UTF8,
1753 pfile->line_table->highest_line,
1754 CPP_BUF_COL (buffer),
1755 "invalid UTF-8 character %<<%x>%>",
1756 cur[0]);
1757 return cur + 1;
1758 }
1759 else if (cur[2] < utf8_continuation || cur[2] >= utf8_signifier)
1760 {
1761 if (pedantic)
1762 cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1763 pfile->line_table->highest_line,
1764 CPP_BUF_COL (buffer),
1765 "invalid UTF-8 character %<<%x><%x>%>",
1766 cur[0], cur[1]);
1767 else
1768 cpp_warning_with_line (pfile, CPP_W_INVALID_UTF8,
1769 pfile->line_table->highest_line,
1770 CPP_BUF_COL (buffer),
1771 "invalid UTF-8 character %<<%x><%x>%>",
1772 cur[0], cur[1]);
1773 return cur + 2;
1774 }
1775 else if (cur[3] < utf8_continuation || cur[3] >= utf8_signifier)
1776 {
1777 if (pedantic)
1778 cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1779 pfile->line_table->highest_line,
1780 CPP_BUF_COL (buffer),
1781 "invalid UTF-8 character %<<%x><%x><%x>%>",
1782 cur[0], cur[1], cur[2]);
1783 else
1784 cpp_warning_with_line (pfile, CPP_W_INVALID_UTF8,
1785 pfile->line_table->highest_line,
1786 CPP_BUF_COL (buffer),
1787 "invalid UTF-8 character %<<%x><%x><%x>%>",
1788 cur[0], cur[1], cur[2]);
1789 return cur + 3;
1790 }
1791 else
1792 {
1793 if (pedantic)
1794 cpp_error_with_line (pfile, CPP_DL_PEDWARN,
1795 pfile->line_table->highest_line,
1796 CPP_BUF_COL (buffer),
1797 "invalid UTF-8 character %<<%x><%x><%x><%x>%>",
1798 cur[0], cur[1], cur[2], cur[3]);
1799 else
1800 cpp_warning_with_line (pfile, CPP_W_INVALID_UTF8,
1801 pfile->line_table->highest_line,
1802 CPP_BUF_COL (buffer),
1803 "invalid UTF-8 character %<<%x><%x><%x><%x>%>",
1804 cur[0], cur[1], cur[2], cur[3]);
1805 return cur + 4;
1806 }
1807 }
1808
1809 /* Helper function of *skip_*_comment and lex*_string. For C,
1810 character at CUR[-1] with MSB set handle -Wbidi-chars* and
1811 -Winvalid-utf8 diagnostics and return pointer to first character
1812 that should be processed next. */
1813
1814 static inline const uchar *
1815 _cpp_handle_multibyte_utf8 (cpp_reader *pfile, uchar c,
1816 const uchar *cur, bool warn_bidi_p,
1817 bool warn_invalid_utf8_p)
1818 {
1819 /* If this is a beginning of a UTF-8 encoding, it might be
1820 a bidirectional control character. */
1821 if (c == bidi::utf8_start && warn_bidi_p)
1822 {
1823 location_t loc;
1824 bidi::kind kind = get_bidi_utf8 (pfile, cur - 1, &loc);
1825 maybe_warn_bidi_on_char (pfile, kind, /*ucn_p=*/false, loc);
1826 }
1827 if (!warn_invalid_utf8_p)
1828 return cur;
1829 if (c >= utf8_signifier)
1830 {
1831 cppchar_t s;
1832 const uchar *pstr = cur - 1;
1833 if (_cpp_valid_utf8 (pfile, &pstr, pfile->buffer->rlimit, 0, NULL, &s)
1834 && s <= UCS_LIMIT)
1835 return pstr;
1836 }
1837 pfile->buffer->cur = cur - 1;
1838 return _cpp_warn_invalid_utf8 (pfile);
1839 }
1840
1841 /* Skip a C-style block comment. We find the end of the comment by
1842 seeing if an asterisk is before every '/' we encounter. Returns
1843 nonzero if comment terminated by EOF, zero otherwise.
1844
1845 Buffer->cur points to the initial asterisk of the comment. */
1846 bool
1847 _cpp_skip_block_comment (cpp_reader *pfile)
1848 {
1849 cpp_buffer *buffer = pfile->buffer;
1850 const uchar *cur = buffer->cur;
1851 uchar c;
1852 const bool warn_bidi_p = pfile->warn_bidi_p ();
1853 const bool warn_invalid_utf8_p = CPP_OPTION (pfile, cpp_warn_invalid_utf8);
1854 const bool warn_bidi_or_invalid_utf8_p = warn_bidi_p | warn_invalid_utf8_p;
1855
1856 cur++;
1857 if (*cur == '/')
1858 cur++;
1859
1860 for (;;)
1861 {
1862 /* People like decorating comments with '*', so check for '/'
1863 instead for efficiency. */
1864 c = *cur++;
1865
1866 if (c == '/')
1867 {
1868 if (cur[-2] == '*')
1869 {
1870 if (warn_bidi_p)
1871 maybe_warn_bidi_on_close (pfile, cur);
1872 break;
1873 }
1874
1875 /* Warn about potential nested comments, but not if the '/'
1876 comes immediately before the true comment delimiter.
1877 Don't bother to get it right across escaped newlines. */
1878 if (CPP_OPTION (pfile, warn_comments)
1879 && cur[0] == '*' && cur[1] != '/')
1880 {
1881 buffer->cur = cur;
1882 cpp_warning_with_line (pfile, CPP_W_COMMENTS,
1883 pfile->line_table->highest_line,
1884 CPP_BUF_COL (buffer),
1885 "%</*%> within comment");
1886 }
1887 }
1888 else if (c == '\n')
1889 {
1890 unsigned int cols;
1891 buffer->cur = cur - 1;
1892 if (warn_bidi_p)
1893 maybe_warn_bidi_on_close (pfile, cur);
1894 _cpp_process_line_notes (pfile, true);
1895 if (buffer->next_line >= buffer->rlimit)
1896 return true;
1897 _cpp_clean_line (pfile);
1898
1899 cols = buffer->next_line - buffer->line_base;
1900 CPP_INCREMENT_LINE (pfile, cols);
1901
1902 cur = buffer->cur;
1903 }
1904 else if (__builtin_expect (c >= utf8_continuation, 0)
1905 && warn_bidi_or_invalid_utf8_p)
1906 cur = _cpp_handle_multibyte_utf8 (pfile, c, cur, warn_bidi_p,
1907 warn_invalid_utf8_p);
1908 }
1909
1910 buffer->cur = cur;
1911 _cpp_process_line_notes (pfile, true);
1912 return false;
1913 }
1914
1915 /* Skip a C++ line comment, leaving buffer->cur pointing to the
1916 terminating newline. Handles escaped newlines. Returns nonzero
1917 if a multiline comment. */
1918 static int
1919 skip_line_comment (cpp_reader *pfile)
1920 {
1921 cpp_buffer *buffer = pfile->buffer;
1922 location_t orig_line = pfile->line_table->highest_line;
1923 const bool warn_bidi_p = pfile->warn_bidi_p ();
1924 const bool warn_invalid_utf8_p = CPP_OPTION (pfile, cpp_warn_invalid_utf8);
1925 const bool warn_bidi_or_invalid_utf8_p = warn_bidi_p | warn_invalid_utf8_p;
1926
1927 if (!warn_bidi_or_invalid_utf8_p)
1928 while (*buffer->cur != '\n')
1929 buffer->cur++;
1930 else if (!warn_invalid_utf8_p)
1931 {
1932 while (*buffer->cur != '\n'
1933 && *buffer->cur != bidi::utf8_start)
1934 buffer->cur++;
1935 if (__builtin_expect (*buffer->cur == bidi::utf8_start, 0))
1936 {
1937 while (*buffer->cur != '\n')
1938 {
1939 if (__builtin_expect (*buffer->cur == bidi::utf8_start, 0))
1940 {
1941 location_t loc;
1942 bidi::kind kind = get_bidi_utf8 (pfile, buffer->cur, &loc);
1943 maybe_warn_bidi_on_char (pfile, kind, /*ucn_p=*/false, loc);
1944 }
1945 buffer->cur++;
1946 }
1947 maybe_warn_bidi_on_close (pfile, buffer->cur);
1948 }
1949 }
1950 else
1951 {
1952 while (*buffer->cur != '\n')
1953 {
1954 if (*buffer->cur < utf8_continuation)
1955 {
1956 buffer->cur++;
1957 continue;
1958 }
1959 buffer->cur
1960 = _cpp_handle_multibyte_utf8 (pfile, *buffer->cur, buffer->cur + 1,
1961 warn_bidi_p, warn_invalid_utf8_p);
1962 }
1963 if (warn_bidi_p)
1964 maybe_warn_bidi_on_close (pfile, buffer->cur);
1965 }
1966
1967 _cpp_process_line_notes (pfile, true);
1968 return orig_line != pfile->line_table->highest_line;
1969 }
1970
1971 /* Skips whitespace, saving the next non-whitespace character. */
1972 static void
1973 skip_whitespace (cpp_reader *pfile, cppchar_t c)
1974 {
1975 cpp_buffer *buffer = pfile->buffer;
1976 bool saw_NUL = false;
1977
1978 do
1979 {
1980 /* Horizontal space always OK. */
1981 if (c == ' ' || c == '\t')
1982 ;
1983 /* Just \f \v or \0 left. */
1984 else if (c == '\0')
1985 saw_NUL = true;
1986 else if (pfile->state.in_directive)
1987 cpp_pedwarning_with_line (pfile, CPP_W_PEDANTIC,
1988 pfile->line_table->highest_line,
1989 CPP_BUF_COL (buffer),
1990 "%s in preprocessing directive",
1991 c == '\f' ? "form feed" : "vertical tab");
1992
1993 c = *buffer->cur++;
1994 }
1995 /* We only want non-vertical space, i.e. ' ' \t \f \v \0. */
1996 while (is_nvspace (c));
1997
1998 if (saw_NUL)
1999 {
2000 encoding_rich_location rich_loc (pfile);
2001 cpp_error_at (pfile, CPP_DL_WARNING, &rich_loc,
2002 "null character(s) ignored");
2003 }
2004
2005 buffer->cur--;
2006 }
2007
2008 /* See if the characters of a number token are valid in a name (no
2009 '.', '+' or '-'). */
2010 static int
2011 name_p (cpp_reader *pfile, const cpp_string *string)
2012 {
2013 unsigned int i;
2014
2015 for (i = 0; i < string->len; i++)
2016 if (!is_idchar (string->text[i]))
2017 return 0;
2018
2019 return 1;
2020 }
2021
2022 /* After parsing an identifier or other sequence, produce a warning about
2023 sequences not in NFC/NFKC. */
2024 static void
2025 warn_about_normalization (cpp_reader *pfile,
2026 const cpp_token *token,
2027 const struct normalize_state *s,
2028 bool identifier)
2029 {
2030 if (CPP_OPTION (pfile, warn_normalize) < NORMALIZE_STATE_RESULT (s)
2031 && !pfile->state.skipping)
2032 {
2033 location_t loc = token->src_loc;
2034
2035 /* If possible, create a location range for the token. */
2036 if (loc >= RESERVED_LOCATION_COUNT
2037 && token->type != CPP_EOF
2038 /* There must be no line notes to process. */
2039 && (!(pfile->buffer->cur
2040 >= pfile->buffer->notes[pfile->buffer->cur_note].pos
2041 && !pfile->overlaid_buffer)))
2042 {
2043 source_range tok_range;
2044 tok_range.m_start = loc;
2045 tok_range.m_finish
2046 = linemap_position_for_column (pfile->line_table,
2047 CPP_BUF_COLUMN (pfile->buffer,
2048 pfile->buffer->cur));
2049 loc = pfile->line_table->get_or_create_combined_loc (loc, tok_range,
2050 nullptr, 0);
2051 }
2052
2053 encoding_rich_location rich_loc (pfile, loc);
2054
2055 /* Make sure that the token is printed using UCNs, even
2056 if we'd otherwise happily print UTF-8. */
2057 unsigned char *buf = XNEWVEC (unsigned char, cpp_token_len (token));
2058 size_t sz;
2059
2060 sz = cpp_spell_token (pfile, token, buf, false) - buf;
2061 if (NORMALIZE_STATE_RESULT (s) == normalized_C)
2062 cpp_warning_at (pfile, CPP_W_NORMALIZE, &rich_loc,
2063 "%<%.*s%> is not in NFKC", (int) sz, buf);
2064 else if (identifier && CPP_OPTION (pfile, xid_identifiers))
2065 cpp_pedwarning_at (pfile, CPP_W_NORMALIZE, &rich_loc,
2066 "%<%.*s%> is not in NFC", (int) sz, buf);
2067 else
2068 cpp_warning_at (pfile, CPP_W_NORMALIZE, &rich_loc,
2069 "%<%.*s%> is not in NFC", (int) sz, buf);
2070 free (buf);
2071 }
2072 }
2073
2074 /* Returns TRUE if the byte sequence starting at buffer->cur is a valid
2075 extended character in an identifier. If FIRST is TRUE, then the character
2076 must be valid at the beginning of an identifier as well. If the return
2077 value is TRUE, then pfile->buffer->cur has been moved to point to the next
2078 byte after the extended character. */
2079
2080 static bool
2081 forms_identifier_p (cpp_reader *pfile, int first,
2082 struct normalize_state *state)
2083 {
2084 cpp_buffer *buffer = pfile->buffer;
2085 const bool warn_bidi_p = pfile->warn_bidi_p ();
2086
2087 if (*buffer->cur == '$')
2088 {
2089 if (!CPP_OPTION (pfile, dollars_in_ident))
2090 return false;
2091
2092 buffer->cur++;
2093 if (CPP_OPTION (pfile, warn_dollars) && !pfile->state.skipping)
2094 {
2095 CPP_OPTION (pfile, warn_dollars) = 0;
2096 cpp_error (pfile, CPP_DL_PEDWARN, "%<$%> in identifier or number");
2097 }
2098
2099 return true;
2100 }
2101
2102 /* Is this a syntactically valid UCN or a valid UTF-8 char? */
2103 if (CPP_OPTION (pfile, extended_identifiers))
2104 {
2105 cppchar_t s;
2106 if (*buffer->cur >= utf8_signifier)
2107 {
2108 if (__builtin_expect (*buffer->cur == bidi::utf8_start, 0)
2109 && warn_bidi_p)
2110 {
2111 location_t loc;
2112 bidi::kind kind = get_bidi_utf8 (pfile, buffer->cur, &loc);
2113 maybe_warn_bidi_on_char (pfile, kind, /*ucn_p=*/false, loc);
2114 }
2115 if (_cpp_valid_utf8 (pfile, &buffer->cur, buffer->rlimit, 1 + !first,
2116 state, &s))
2117 return true;
2118 }
2119 else if (*buffer->cur == '\\'
2120 && (buffer->cur[1] == 'u'
2121 || buffer->cur[1] == 'U'
2122 || buffer->cur[1] == 'N'))
2123 {
2124 buffer->cur += 2;
2125 if (warn_bidi_p)
2126 {
2127 location_t loc;
2128 bidi::kind kind;
2129 if (buffer->cur[-1] == 'N')
2130 kind = get_bidi_named (pfile, buffer->cur, &loc);
2131 else
2132 kind = get_bidi_ucn (pfile, buffer->cur,
2133 buffer->cur[-1] == 'U', &loc);
2134 maybe_warn_bidi_on_char (pfile, kind, /*ucn_p=*/true, loc);
2135 }
2136 if (_cpp_valid_ucn (pfile, &buffer->cur, buffer->rlimit, 1 + !first,
2137 state, &s, NULL, NULL))
2138 return true;
2139 buffer->cur -= 2;
2140 }
2141 }
2142
2143 return false;
2144 }
2145
2146 /* Helper function to issue error about improper __VA_OPT__ use. */
2147 static void
2148 maybe_va_opt_error (cpp_reader *pfile)
2149 {
2150 if (CPP_PEDANTIC (pfile) && !CPP_OPTION (pfile, va_opt))
2151 {
2152 /* __VA_OPT__ should not be accepted at all, but allow it in
2153 system headers. */
2154 if (!_cpp_in_system_header (pfile))
2155 {
2156 if (CPP_OPTION (pfile, cplusplus))
2157 cpp_pedwarning (pfile, CPP_W_CXX20_EXTENSIONS,
2158 "%<__VA_OPT__%> is not available until C++20");
2159 else
2160 cpp_pedwarning (pfile, CPP_W_PEDANTIC,
2161 "%<__VA_OPT__%> is not available until C23");
2162 }
2163 }
2164 else if (!pfile->state.va_args_ok)
2165 {
2166 /* __VA_OPT__ should only appear in the replacement list of a
2167 variadic macro. */
2168 cpp_error (pfile, CPP_DL_PEDWARN,
2169 "%<__VA_OPT__%> can only appear in the expansion"
2170 " of a C++20 variadic macro");
2171 }
2172 }
2173
2174 /* Helper function to perform diagnostics that are needed (rarely)
2175 when an identifier is lexed. */
2176 static void
2177 identifier_diagnostics_on_lex (cpp_reader *pfile, cpp_hashnode *node)
2178 {
2179 if (__builtin_expect (!(node->flags & NODE_DIAGNOSTIC)
2180 || pfile->state.skipping, 1))
2181 return;
2182
2183 /* It is allowed to poison the same identifier twice. */
2184 if ((node->flags & NODE_POISONED) && !pfile->state.poisoned_ok)
2185 {
2186 cpp_error (pfile, CPP_DL_ERROR, "attempt to use poisoned %qs",
2187 NODE_NAME (node));
2188 const auto data = (cpp_hashnode_extra *)
2189 ht_lookup (pfile->extra_hash_table, node->ident, HT_NO_INSERT);
2190 if (data && data->poisoned_loc)
2191 cpp_error_at (pfile, CPP_DL_NOTE, data->poisoned_loc, "poisoned here");
2192 }
2193
2194 /* Constraint 6.10.3.5: __VA_ARGS__ should only appear in the
2195 replacement list of a variadic macro. */
2196 if (node == pfile->spec_nodes.n__VA_ARGS__
2197 && !pfile->state.va_args_ok)
2198 {
2199 if (CPP_OPTION (pfile, cplusplus))
2200 cpp_error (pfile, CPP_DL_PEDWARN,
2201 "%<__VA_ARGS__%> can only appear in the expansion"
2202 " of a C++11 variadic macro");
2203 else
2204 cpp_error (pfile, CPP_DL_PEDWARN,
2205 "%<__VA_ARGS__%> can only appear in the expansion"
2206 " of a C99 variadic macro");
2207 }
2208
2209 /* __VA_OPT__ should only appear in the replacement list of a
2210 variadic macro. */
2211 if (node == pfile->spec_nodes.n__VA_OPT__)
2212 maybe_va_opt_error (pfile);
2213
2214 /* For -Wc++-compat, warn about use of C++ named operators. */
2215 if (node->flags & NODE_WARN_OPERATOR)
2216 cpp_warning (pfile, CPP_W_CXX_OPERATOR_NAMES,
2217 "identifier %qs is a special operator name in C++",
2218 NODE_NAME (node));
2219 }
2220
2221 /* Lex an identifier starting at BASE. BUFFER->CUR is expected to point
2222 one past the first character at BASE, which may be a (possibly multi-byte)
2223 character if STARTS_UCN is true. */
2224 static cpp_hashnode *
2225 lex_identifier (cpp_reader *pfile, const uchar *base, bool starts_ucn,
2226 struct normalize_state *nst, cpp_hashnode **spelling)
2227 {
2228 cpp_hashnode *result;
2229 const uchar *cur;
2230 unsigned int len;
2231 unsigned int hash = HT_HASHSTEP (0, *base);
2232 const bool warn_bidi_p = pfile->warn_bidi_p ();
2233
2234 cur = pfile->buffer->cur;
2235 if (! starts_ucn)
2236 {
2237 while (ISIDNUM (*cur))
2238 {
2239 hash = HT_HASHSTEP (hash, *cur);
2240 cur++;
2241 }
2242 NORMALIZE_STATE_UPDATE_IDNUM (nst, *(cur - 1));
2243 }
2244 pfile->buffer->cur = cur;
2245 if (starts_ucn || forms_identifier_p (pfile, false, nst))
2246 {
2247 /* Slower version for identifiers containing UCNs
2248 or extended chars (including $). */
2249 do {
2250 while (ISIDNUM (*pfile->buffer->cur))
2251 {
2252 NORMALIZE_STATE_UPDATE_IDNUM (nst, *pfile->buffer->cur);
2253 pfile->buffer->cur++;
2254 }
2255 } while (forms_identifier_p (pfile, false, nst));
2256 if (warn_bidi_p)
2257 maybe_warn_bidi_on_close (pfile, pfile->buffer->cur);
2258 result = _cpp_interpret_identifier (pfile, base,
2259 pfile->buffer->cur - base);
2260 *spelling = cpp_lookup (pfile, base, pfile->buffer->cur - base);
2261 }
2262 else
2263 {
2264 len = cur - base;
2265 hash = HT_HASHFINISH (hash, len);
2266
2267 result = CPP_HASHNODE (ht_lookup_with_hash (pfile->hash_table,
2268 base, len, hash, HT_ALLOC));
2269 *spelling = result;
2270 }
2271
2272 return result;
2273 }
2274
2275 /* Struct to hold the return value of the scan_cur_identifier () helper
2276 function below. */
2277
2278 struct scan_id_result
2279 {
2280 cpp_hashnode *node;
2281 normalize_state nst;
2282
2283 scan_id_result ()
2284 : node (nullptr)
2285 {
2286 nst = INITIAL_NORMALIZE_STATE;
2287 }
2288
2289 explicit operator bool () const { return node; }
2290 };
2291
2292 /* Helper function to scan an entire identifier beginning at
2293 pfile->buffer->cur, and possibly containing extended characters (UCNs
2294 and/or UTF-8). Returns the cpp_hashnode for the identifier on success, or
2295 else nullptr, as well as a normalize_state so that normalization warnings
2296 may be issued once the token lexing is complete. */
2297
2298 static scan_id_result
2299 scan_cur_identifier (cpp_reader *pfile)
2300 {
2301 const auto buffer = pfile->buffer;
2302 const auto begin = buffer->cur;
2303 scan_id_result result;
2304 if (ISIDST (*buffer->cur))
2305 {
2306 ++buffer->cur;
2307 cpp_hashnode *ignore;
2308 result.node = lex_identifier (pfile, begin, false, &result.nst, &ignore);
2309 }
2310 else if (forms_identifier_p (pfile, true, &result.nst))
2311 {
2312 /* buffer->cur has been moved already by the call
2313 to forms_identifier_p. */
2314 cpp_hashnode *ignore;
2315 result.node = lex_identifier (pfile, begin, true, &result.nst, &ignore);
2316 }
2317 return result;
2318 }
2319
2320 /* Lex a number to NUMBER starting at BUFFER->CUR - 1. */
2321 static void
2322 lex_number (cpp_reader *pfile, cpp_string *number,
2323 struct normalize_state *nst)
2324 {
2325 const uchar *cur;
2326 const uchar *base;
2327 uchar *dest;
2328
2329 base = pfile->buffer->cur - 1;
2330 do
2331 {
2332 const uchar *adj_digit_sep = NULL;
2333 cur = pfile->buffer->cur;
2334
2335 /* N.B. ISIDNUM does not include $. */
2336 while (ISIDNUM (*cur)
2337 || (*cur == '.' && !DIGIT_SEP (cur[-1]))
2338 || DIGIT_SEP (*cur)
2339 || (VALID_SIGN (*cur, cur[-1]) && !DIGIT_SEP (cur[-2])))
2340 {
2341 NORMALIZE_STATE_UPDATE_IDNUM (nst, *cur);
2342 /* Adjacent digit separators do not form part of the pp-number syntax.
2343 However, they can safely be diagnosed here as an error, since '' is
2344 not a valid preprocessing token. */
2345 if (DIGIT_SEP (*cur) && DIGIT_SEP (cur[-1]) && !adj_digit_sep)
2346 adj_digit_sep = cur;
2347 cur++;
2348 }
2349 /* A number can't end with a digit separator. */
2350 while (cur > pfile->buffer->cur && DIGIT_SEP (cur[-1]))
2351 --cur;
2352 if (adj_digit_sep && adj_digit_sep < cur)
2353 cpp_error (pfile, CPP_DL_ERROR, "adjacent digit separators");
2354
2355 pfile->buffer->cur = cur;
2356 }
2357 while (forms_identifier_p (pfile, false, nst));
2358
2359 number->len = cur - base;
2360 dest = _cpp_unaligned_alloc (pfile, number->len + 1);
2361 memcpy (dest, base, number->len);
2362 dest[number->len] = '\0';
2363 number->text = dest;
2364 }
2365
2366 /* Create a token of type TYPE with a literal spelling. */
2367 static void
2368 create_literal (cpp_reader *pfile, cpp_token *token, const uchar *base,
2369 unsigned int len, enum cpp_ttype type)
2370 {
2371 token->type = type;
2372 token->val.str.len = len;
2373 token->val.str.text = cpp_alloc_token_string (pfile, base, len);
2374 }
2375
2376 /* Like create_literal(), but construct it from two separate strings
2377 which are concatenated. LEN2 may be 0 if no second string is
2378 required. */
2379 static void
2380 create_literal2 (cpp_reader *pfile, cpp_token *token, const uchar *base1,
2381 unsigned int len1, const uchar *base2, unsigned int len2,
2382 enum cpp_ttype type)
2383 {
2384 token->type = type;
2385 token->val.str.len = len1 + len2;
2386 uchar *const dest = _cpp_unaligned_alloc (pfile, len1 + len2 + 1);
2387 memcpy (dest, base1, len1);
2388 if (len2)
2389 memcpy (dest+len1, base2, len2);
2390 dest[len1 + len2] = 0;
2391 token->val.str.text = dest;
2392 }
2393
2394 const uchar *
2395 cpp_alloc_token_string (cpp_reader *pfile,
2396 const unsigned char *ptr, unsigned len)
2397 {
2398 uchar *dest = _cpp_unaligned_alloc (pfile, len + 1);
2399
2400 dest[len] = 0;
2401 memcpy (dest, ptr, len);
2402 return dest;
2403 }
2404
2405 /* A pair of raw buffer pointers. The currently open one is [1], the
2406 first one is [0]. Used for string literal lexing. */
2407 struct lit_accum {
2408 _cpp_buff *first;
2409 _cpp_buff *last;
2410 const uchar *rpos;
2411 size_t accum;
2412
2413 lit_accum ()
2414 : first (NULL), last (NULL), rpos (0), accum (0)
2415 {
2416 }
2417
2418 void append (cpp_reader *, const uchar *, size_t);
2419
2420 void read_begin (cpp_reader *);
2421 bool reading_p () const
2422 {
2423 return rpos != NULL;
2424 }
2425 char read_char ()
2426 {
2427 char c = *rpos++;
2428 if (rpos == BUFF_FRONT (last))
2429 rpos = NULL;
2430 return c;
2431 }
2432
2433 void create_literal2 (cpp_reader *pfile, cpp_token *token,
2434 const uchar *base1, unsigned int len1,
2435 const uchar *base2, unsigned int len2,
2436 enum cpp_ttype type);
2437 };
2438
2439 /* Subroutine of lex_raw_string: Append LEN chars from BASE to the buffer
2440 sequence from *FIRST_BUFF_P to LAST_BUFF_P. */
2441
2442 void
2443 lit_accum::append (cpp_reader *pfile, const uchar *base, size_t len)
2444 {
2445 if (!last)
2446 /* Starting. */
2447 first = last = _cpp_get_buff (pfile, len);
2448 else if (len > BUFF_ROOM (last))
2449 {
2450 /* There is insufficient room in the buffer. Copy what we can,
2451 and then either extend or create a new one. */
2452 size_t room = BUFF_ROOM (last);
2453 memcpy (BUFF_FRONT (last), base, room);
2454 BUFF_FRONT (last) += room;
2455 base += room;
2456 len -= room;
2457 accum += room;
2458
2459 gcc_checking_assert (!rpos);
2460
2461 last = _cpp_append_extend_buff (pfile, last, len);
2462 }
2463
2464 memcpy (BUFF_FRONT (last), base, len);
2465 BUFF_FRONT (last) += len;
2466 accum += len;
2467 }
2468
2469 void
2470 lit_accum::read_begin (cpp_reader *pfile)
2471 {
2472 /* We never accumulate more than 4 chars to read. */
2473 if (BUFF_ROOM (last) < 4)
2474
2475 last = _cpp_append_extend_buff (pfile, last, 4);
2476 rpos = BUFF_FRONT (last);
2477 }
2478
2479 /* Helper function to check if a string format macro, say from inttypes.h, is
2480 placed touching a string literal, in which case it could be parsed as a C++11
2481 user-defined string literal thus breaking the program. Return TRUE if the
2482 UDL should be ignored for now and preserved for potential macro
2483 expansion. */
2484
2485 static bool
2486 maybe_ignore_udl_macro_suffix (cpp_reader *pfile, location_t src_loc,
2487 const uchar *suffix_begin, cpp_hashnode *node)
2488 {
2489 /* User-defined literals outside of namespace std must start with a single
2490 underscore, so assume anything of that form really is a UDL suffix.
2491 We don't need to worry about UDLs defined inside namespace std because
2492 their names are reserved, so cannot be used as macro names in valid
2493 programs. */
2494 if ((suffix_begin[0] == '_' && suffix_begin[1] != '_')
2495 || !cpp_macro_p (node))
2496 return false;
2497
2498 /* Maybe raise a warning here; caller should arrange not to consume
2499 the tokens. */
2500 if (CPP_OPTION (pfile, warn_literal_suffix) && !pfile->state.skipping)
2501 cpp_warning_with_line (pfile, CPP_W_LITERAL_SUFFIX, src_loc, 0,
2502 "invalid suffix on literal; C++11 requires a space "
2503 "between literal and string macro");
2504 return true;
2505 }
2506
2507 /* Like create_literal2(), but also prepend all the accumulated data from
2508 the lit_accum struct. */
2509 void
2510 lit_accum::create_literal2 (cpp_reader *pfile, cpp_token *token,
2511 const uchar *base1, unsigned int len1,
2512 const uchar *base2, unsigned int len2,
2513 enum cpp_ttype type)
2514 {
2515 const unsigned int tot_len = accum + len1 + len2;
2516 uchar *dest = _cpp_unaligned_alloc (pfile, tot_len + 1);
2517 token->type = type;
2518 token->val.str.len = tot_len;
2519 token->val.str.text = dest;
2520 for (_cpp_buff *buf = first; buf; buf = buf->next)
2521 {
2522 size_t len = BUFF_FRONT (buf) - buf->base;
2523 memcpy (dest, buf->base, len);
2524 dest += len;
2525 }
2526 memcpy (dest, base1, len1);
2527 dest += len1;
2528 if (len2)
2529 memcpy (dest, base2, len2);
2530 dest += len2;
2531 *dest = '\0';
2532 }
2533
2534 /* Lexes a raw string. The stored string contains the spelling,
2535 including double quotes, delimiter string, '(' and ')', any leading
2536 'L', 'u', 'U' or 'u8' and 'R' modifier. The created token contains
2537 the type of the literal, or CPP_OTHER if it was not properly
2538 terminated.
2539
2540 BASE is the start of the token. Updates pfile->buffer->cur to just
2541 after the lexed string.
2542
2543 The spelling is NUL-terminated, but it is not guaranteed that this
2544 is the first NUL since embedded NULs are preserved. */
2545
2546 static void
2547 lex_raw_string (cpp_reader *pfile, cpp_token *token, const uchar *base)
2548 {
2549 const uchar *pos = base;
2550 const bool warn_bidi_p = pfile->warn_bidi_p ();
2551 const bool warn_invalid_utf8_p = CPP_OPTION (pfile, cpp_warn_invalid_utf8);
2552 const bool warn_bidi_or_invalid_utf8_p = warn_bidi_p | warn_invalid_utf8_p;
2553
2554 /* 'tis a pity this information isn't passed down from the lexer's
2555 initial categorization of the token. */
2556 enum cpp_ttype type = CPP_STRING;
2557
2558 if (*pos == 'L')
2559 {
2560 type = CPP_WSTRING;
2561 pos++;
2562 }
2563 else if (*pos == 'U')
2564 {
2565 type = CPP_STRING32;
2566 pos++;
2567 }
2568 else if (*pos == 'u')
2569 {
2570 if (pos[1] == '8')
2571 {
2572 type = CPP_UTF8STRING;
2573 pos++;
2574 }
2575 else
2576 type = CPP_STRING16;
2577 pos++;
2578 }
2579
2580 gcc_checking_assert (pos[0] == 'R' && pos[1] == '"');
2581 pos += 2;
2582
2583 _cpp_line_note *note = &pfile->buffer->notes[pfile->buffer->cur_note];
2584
2585 /* Skip notes before the ". */
2586 while (note->pos < pos)
2587 ++note;
2588
2589 lit_accum accum;
2590
2591 uchar prefix[17];
2592 unsigned prefix_len = 0;
2593 enum Phase
2594 {
2595 PHASE_PREFIX = -2,
2596 PHASE_NONE = -1,
2597 PHASE_SUFFIX = 0
2598 } phase = PHASE_PREFIX;
2599
2600 for (;;)
2601 {
2602 gcc_checking_assert (note->pos >= pos);
2603
2604 /* Undo any escaped newlines and trigraphs. */
2605 if (!accum.reading_p () && note->pos == pos)
2606 switch (note->type)
2607 {
2608 case '\\':
2609 case ' ':
2610 /* Restore backslash followed by newline. */
2611 accum.append (pfile, base, pos - base);
2612 base = pos;
2613 accum.read_begin (pfile);
2614 accum.append (pfile, UC"\\", 1);
2615
2616 after_backslash:
2617 if (note->type == ' ')
2618 /* GNU backslash whitespace newline extension. FIXME
2619 could be any sequence of non-vertical space. When we
2620 can properly restore any such sequence, we should
2621 mark this note as handled so _cpp_process_line_notes
2622 doesn't warn. */
2623 accum.append (pfile, UC" ", 1);
2624
2625 accum.append (pfile, UC"\n", 1);
2626 note++;
2627 break;
2628
2629 case '\n':
2630 /* This can happen for ??/<NEWLINE> when trigraphs are not
2631 being interpretted. */
2632 gcc_checking_assert (!CPP_OPTION (pfile, trigraphs));
2633 note->type = 0;
2634 note++;
2635 break;
2636
2637 case 'W':
2638 case 'L':
2639 case 'S':
2640 case 'T':
2641 /* Don't warn about leading or trailing whitespace in raw string
2642 literals. */
2643 note->type = 0;
2644 note++;
2645 break;
2646
2647 default:
2648 gcc_checking_assert (_cpp_trigraph_map[note->type]);
2649
2650 /* Don't warn about this trigraph in
2651 _cpp_process_line_notes, since trigraphs show up as
2652 trigraphs in raw strings. */
2653 uchar type = note->type;
2654 note->type = 0;
2655
2656 if (CPP_OPTION (pfile, trigraphs))
2657 {
2658 accum.append (pfile, base, pos - base);
2659 base = pos;
2660 accum.read_begin (pfile);
2661 accum.append (pfile, UC"??", 2);
2662 accum.append (pfile, &type, 1);
2663
2664 /* ??/ followed by newline gets two line notes, one for
2665 the trigraph and one for the backslash/newline. */
2666 if (type == '/' && note[1].pos == pos)
2667 {
2668 note++;
2669 gcc_assert (note->type == '\\' || note->type == ' ');
2670 goto after_backslash;
2671 }
2672 /* Skip the replacement character. */
2673 base = ++pos;
2674 }
2675
2676 note++;
2677 break;
2678 }
2679
2680 /* Now get a char to process. Either from an expanded note, or
2681 from the line buffer. */
2682 bool read_note = accum.reading_p ();
2683 char c = read_note ? accum.read_char () : *pos++;
2684
2685 if (phase == PHASE_PREFIX)
2686 {
2687 if (c == '(')
2688 {
2689 /* Done. */
2690 phase = PHASE_NONE;
2691 prefix[prefix_len++] = '"';
2692 }
2693 else if (prefix_len < 16
2694 /* Prefix chars are any of the basic character set,
2695 [lex.charset] except for '
2696 ()\\\t\v\f\n'. Optimized for a contiguous
2697 alphabet. */
2698 /* Unlike a switch, this collapses down to one or
2699 two shift and bitmask operations on an ASCII
2700 system, with an outlier or two. */
2701 && (('Z' - 'A' == 25
2702 ? ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
2703 : ISIDST (c))
2704 || (c >= '0' && c <= '9')
2705 || c == '_' || c == '{' || c == '}'
2706 || c == '[' || c == ']' || c == '#'
2707 || c == '<' || c == '>' || c == '%'
2708 || c == ':' || c == ';' || c == '.' || c == '?'
2709 || c == '*' || c == '+' || c == '-' || c == '/'
2710 || c == '^' || c == '&' || c == '|' || c == '~'
2711 || c == '!' || c == '=' || c == ','
2712 || c == '"' || c == '\''
2713 || ((c == '$' || c == '@' || c == '`')
2714 && CPP_OPTION (pfile, cplusplus)
2715 && CPP_OPTION (pfile, lang) > CLK_CXX23)))
2716 prefix[prefix_len++] = c;
2717 else
2718 {
2719 /* Something is wrong. */
2720 int col = CPP_BUF_COLUMN (pfile->buffer, pos) + read_note;
2721 if (prefix_len == 16)
2722 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc,
2723 col, "raw string delimiter longer "
2724 "than 16 characters");
2725 else if (c == '\n')
2726 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc,
2727 col, "invalid new-line in raw "
2728 "string delimiter");
2729 else
2730 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc,
2731 col, "invalid character '%c' in "
2732 "raw string delimiter", c);
2733 type = CPP_OTHER;
2734 phase = PHASE_NONE;
2735 /* Continue until we get a close quote, that's probably
2736 the best failure mode. */
2737 prefix_len = 0;
2738 }
2739 if (c != '\n')
2740 continue;
2741 }
2742
2743 if (phase != PHASE_NONE)
2744 {
2745 if (prefix[phase] != c)
2746 phase = PHASE_NONE;
2747 else if (unsigned (phase + 1) == prefix_len)
2748 break;
2749 else
2750 {
2751 phase = Phase (phase + 1);
2752 continue;
2753 }
2754 }
2755
2756 if (!prefix_len && c == '"')
2757 /* Failure mode lexing. */
2758 goto out;
2759 else if (prefix_len && c == ')')
2760 phase = PHASE_SUFFIX;
2761 else if (!read_note && c == '\n')
2762 {
2763 pos--;
2764 pfile->buffer->cur = pos;
2765 if ((pfile->state.in_directive || pfile->state.parsing_args
2766 || pfile->state.in_deferred_pragma)
2767 && pfile->buffer->next_line >= pfile->buffer->rlimit)
2768 {
2769 cpp_error_with_line (pfile, CPP_DL_ERROR, token->src_loc, 0,
2770 "unterminated raw string");
2771 type = CPP_OTHER;
2772 goto out;
2773 }
2774
2775 accum.append (pfile, base, pos - base + 1);
2776 _cpp_process_line_notes (pfile, false);
2777
2778 if (pfile->buffer->next_line < pfile->buffer->rlimit)
2779 CPP_INCREMENT_LINE (pfile, 0);
2780 pfile->buffer->need_line = true;
2781
2782 if (!get_fresh_line_impl<true> (pfile))
2783 {
2784 /* We ran out of file and failed to get a line. */
2785 location_t src_loc = token->src_loc;
2786 token->type = CPP_EOF;
2787 /* Tell the compiler the line number of the EOF token. */
2788 token->src_loc = pfile->line_table->highest_line;
2789 token->flags = BOL;
2790 if (accum.first)
2791 _cpp_release_buff (pfile, accum.first);
2792 cpp_error_with_line (pfile, CPP_DL_ERROR, src_loc, 0,
2793 "unterminated raw string");
2794
2795 /* Now pop the buffer that get_fresh_line_impl() did not. Popping
2796 is not safe if processing a directive, however this cannot
2797 happen as we already checked above that a line would be
2798 available, and get_fresh_line_impl() can't fail in this
2799 case. */
2800 gcc_assert (!pfile->state.in_directive);
2801 _cpp_pop_buffer (pfile);
2802
2803 return;
2804 }
2805
2806 pos = base = pfile->buffer->cur;
2807 note = &pfile->buffer->notes[pfile->buffer->cur_note];
2808 }
2809 else if (__builtin_expect ((unsigned char) c >= utf8_continuation, 0)
2810 && warn_bidi_or_invalid_utf8_p)
2811 pos = _cpp_handle_multibyte_utf8 (pfile, c, pos, warn_bidi_p,
2812 warn_invalid_utf8_p);
2813 }
2814
2815 if (warn_bidi_p)
2816 maybe_warn_bidi_on_close (pfile, pos);
2817
2818 if (CPP_OPTION (pfile, user_literals))
2819 {
2820 const uchar *const suffix_begin = pos;
2821 pfile->buffer->cur = pos;
2822
2823 if (const auto sr = scan_cur_identifier (pfile))
2824 {
2825 if (maybe_ignore_udl_macro_suffix (pfile, token->src_loc,
2826 suffix_begin, sr.node))
2827 pfile->buffer->cur = suffix_begin;
2828 else
2829 {
2830 type = cpp_userdef_string_add_type (type);
2831 accum.create_literal2 (pfile, token, base, suffix_begin - base,
2832 NODE_NAME (sr.node), NODE_LEN (sr.node),
2833 type);
2834 if (accum.first)
2835 _cpp_release_buff (pfile, accum.first);
2836 warn_about_normalization (pfile, token, &sr.nst, true);
2837 return;
2838 }
2839 }
2840 }
2841
2842 out:
2843 pfile->buffer->cur = pos;
2844 if (!accum.accum)
2845 create_literal (pfile, token, base, pos - base, type);
2846 else
2847 {
2848 accum.create_literal2 (pfile, token, base, pos - base, nullptr, 0, type);
2849 _cpp_release_buff (pfile, accum.first);
2850 }
2851 }
2852
2853 /* Lexes a string, character constant, or angle-bracketed header file
2854 name. The stored string contains the spelling, including opening
2855 quote and any leading 'L', 'u', 'U' or 'u8' and optional
2856 'R' modifier. It returns the type of the literal, or CPP_OTHER
2857 if it was not properly terminated, or CPP_LESS for an unterminated
2858 header name which must be relexed as normal tokens.
2859
2860 The spelling is NUL-terminated, but it is not guaranteed that this
2861 is the first NUL since embedded NULs are preserved. */
2862 static void
2863 lex_string (cpp_reader *pfile, cpp_token *token, const uchar *base)
2864 {
2865 bool saw_NUL = false;
2866 const uchar *cur;
2867 cppchar_t terminator;
2868 enum cpp_ttype type;
2869
2870 cur = base;
2871 terminator = *cur++;
2872 if (terminator == 'L' || terminator == 'U')
2873 terminator = *cur++;
2874 else if (terminator == 'u')
2875 {
2876 terminator = *cur++;
2877 if (terminator == '8')
2878 terminator = *cur++;
2879 }
2880 if (terminator == 'R')
2881 {
2882 lex_raw_string (pfile, token, base);
2883 return;
2884 }
2885 if (terminator == '"')
2886 type = (*base == 'L' ? CPP_WSTRING :
2887 *base == 'U' ? CPP_STRING32 :
2888 *base == 'u' ? (base[1] == '8' ? CPP_UTF8STRING : CPP_STRING16)
2889 : CPP_STRING);
2890 else if (terminator == '\'')
2891 type = (*base == 'L' ? CPP_WCHAR :
2892 *base == 'U' ? CPP_CHAR32 :
2893 *base == 'u' ? (base[1] == '8' ? CPP_UTF8CHAR : CPP_CHAR16)
2894 : CPP_CHAR);
2895 else
2896 terminator = '>', type = CPP_HEADER_NAME;
2897
2898 const bool warn_bidi_p = pfile->warn_bidi_p ();
2899 const bool warn_invalid_utf8_p = CPP_OPTION (pfile, cpp_warn_invalid_utf8);
2900 const bool warn_bidi_or_invalid_utf8_p = warn_bidi_p | warn_invalid_utf8_p;
2901 for (;;)
2902 {
2903 cppchar_t c = *cur++;
2904
2905 /* In #include-style directives, terminators are not escapable. */
2906 if (c == '\\' && !pfile->state.angled_headers && *cur != '\n')
2907 {
2908 if ((cur[0] == 'u' || cur[0] == 'U' || cur[0] == 'N') && warn_bidi_p)
2909 {
2910 location_t loc;
2911 bidi::kind kind;
2912 if (cur[0] == 'N')
2913 kind = get_bidi_named (pfile, cur + 1, &loc);
2914 else
2915 kind = get_bidi_ucn (pfile, cur + 1, cur[0] == 'U', &loc);
2916 maybe_warn_bidi_on_char (pfile, kind, /*ucn_p=*/true, loc);
2917 }
2918 cur++;
2919 }
2920 else if (c == terminator)
2921 {
2922 if (warn_bidi_p)
2923 maybe_warn_bidi_on_close (pfile, cur - 1);
2924 break;
2925 }
2926 else if (c == '\n')
2927 {
2928 cur--;
2929 /* Unmatched quotes always yield undefined behavior, but
2930 greedy lexing means that what appears to be an unterminated
2931 header name may actually be a legitimate sequence of tokens. */
2932 if (terminator == '>')
2933 {
2934 token->type = CPP_LESS;
2935 return;
2936 }
2937 type = CPP_OTHER;
2938 break;
2939 }
2940 else if (c == '\0')
2941 saw_NUL = true;
2942 else if (__builtin_expect (c >= utf8_continuation, 0)
2943 && warn_bidi_or_invalid_utf8_p)
2944 cur = _cpp_handle_multibyte_utf8 (pfile, c, cur, warn_bidi_p,
2945 warn_invalid_utf8_p);
2946 }
2947
2948 if (saw_NUL && !pfile->state.skipping)
2949 cpp_error (pfile, CPP_DL_WARNING,
2950 "null character(s) preserved in literal");
2951
2952 if (type == CPP_OTHER && CPP_OPTION (pfile, lang) != CLK_ASM)
2953 cpp_error (pfile, CPP_DL_PEDWARN, "missing terminating %c character",
2954 (int) terminator);
2955
2956 pfile->buffer->cur = cur;
2957 const uchar *const suffix_begin = cur;
2958
2959 if (CPP_OPTION (pfile, user_literals))
2960 {
2961 if (const auto sr = scan_cur_identifier (pfile))
2962 {
2963 if (maybe_ignore_udl_macro_suffix (pfile, token->src_loc,
2964 suffix_begin, sr.node))
2965 pfile->buffer->cur = suffix_begin;
2966 else
2967 {
2968 /* Grab user defined literal suffix. */
2969 type = cpp_userdef_char_add_type (type);
2970 type = cpp_userdef_string_add_type (type);
2971 create_literal2 (pfile, token, base, suffix_begin - base,
2972 NODE_NAME (sr.node), NODE_LEN (sr.node), type);
2973 warn_about_normalization (pfile, token, &sr.nst, true);
2974 return;
2975 }
2976 }
2977 }
2978 else if (CPP_OPTION (pfile, cpp_warn_cxx11_compat)
2979 && !pfile->state.skipping)
2980 {
2981 const auto sr = scan_cur_identifier (pfile);
2982 /* Maybe raise a warning, but do not consume the tokens. */
2983 pfile->buffer->cur = suffix_begin;
2984 if (sr && cpp_macro_p (sr.node))
2985 cpp_warning_with_line (pfile, CPP_W_CXX11_COMPAT,
2986 token->src_loc, 0, "C++11 requires a space "
2987 "between string literal and macro");
2988 }
2989
2990 create_literal (pfile, token, base, cur - base, type);
2991 }
2992
2993 /* Return the comment table. The client may not make any assumption
2994 about the ordering of the table. */
2995 cpp_comment_table *
2996 cpp_get_comments (cpp_reader *pfile)
2997 {
2998 return &pfile->comments;
2999 }
3000
3001 /* Append a comment to the end of the comment table. */
3002 static void
3003 store_comment (cpp_reader *pfile, cpp_token *token)
3004 {
3005 int len;
3006
3007 if (pfile->comments.allocated == 0)
3008 {
3009 pfile->comments.allocated = 256;
3010 pfile->comments.entries = (cpp_comment *) xmalloc
3011 (pfile->comments.allocated * sizeof (cpp_comment));
3012 }
3013
3014 if (pfile->comments.count == pfile->comments.allocated)
3015 {
3016 pfile->comments.allocated *= 2;
3017 pfile->comments.entries = (cpp_comment *) xrealloc
3018 (pfile->comments.entries,
3019 pfile->comments.allocated * sizeof (cpp_comment));
3020 }
3021
3022 len = token->val.str.len;
3023
3024 /* Copy comment. Note, token may not be NULL terminated. */
3025 pfile->comments.entries[pfile->comments.count].comment =
3026 (char *) xmalloc (sizeof (char) * (len + 1));
3027 memcpy (pfile->comments.entries[pfile->comments.count].comment,
3028 token->val.str.text, len);
3029 pfile->comments.entries[pfile->comments.count].comment[len] = '\0';
3030
3031 /* Set source location. */
3032 pfile->comments.entries[pfile->comments.count].sloc = token->src_loc;
3033
3034 /* Increment the count of entries in the comment table. */
3035 pfile->comments.count++;
3036 }
3037
3038 /* The stored comment includes the comment start and any terminator. */
3039 static void
3040 save_comment (cpp_reader *pfile, cpp_token *token, const unsigned char *from,
3041 cppchar_t type)
3042 {
3043 unsigned char *buffer;
3044 unsigned int len, clen, i;
3045
3046 len = pfile->buffer->cur - from + 1; /* + 1 for the initial '/'. */
3047
3048 /* C++ comments probably (not definitely) have moved past a new
3049 line, which we don't want to save in the comment. */
3050 if (is_vspace (pfile->buffer->cur[-1]))
3051 len--;
3052
3053 /* If we are currently in a directive or in argument parsing, then
3054 we need to store all C++ comments as C comments internally, and
3055 so we need to allocate a little extra space in that case.
3056
3057 Note that the only time we encounter a directive here is
3058 when we are saving comments in a "#define". */
3059 clen = ((pfile->state.in_directive || pfile->state.parsing_args)
3060 && type == '/') ? len + 2 : len;
3061
3062 buffer = _cpp_unaligned_alloc (pfile, clen);
3063
3064 token->type = CPP_COMMENT;
3065 token->val.str.len = clen;
3066 token->val.str.text = buffer;
3067
3068 buffer[0] = '/';
3069 memcpy (buffer + 1, from, len - 1);
3070
3071 /* Finish conversion to a C comment, if necessary. */
3072 if ((pfile->state.in_directive || pfile->state.parsing_args) && type == '/')
3073 {
3074 buffer[1] = '*';
3075 buffer[clen - 2] = '*';
3076 buffer[clen - 1] = '/';
3077 /* As there can be in a C++ comments illegal sequences for C comments
3078 we need to filter them out. */
3079 for (i = 2; i < (clen - 2); i++)
3080 if (buffer[i] == '/' && (buffer[i - 1] == '*' || buffer[i + 1] == '*'))
3081 buffer[i] = '|';
3082 }
3083
3084 /* Finally store this comment for use by clients of libcpp. */
3085 store_comment (pfile, token);
3086 }
3087
3088 /* Returns true if comment at COMMENT_START is a recognized FALLTHROUGH
3089 comment. */
3090
3091 static bool
3092 fallthrough_comment_p (cpp_reader *pfile, const unsigned char *comment_start)
3093 {
3094 const unsigned char *from = comment_start + 1;
3095
3096 switch (CPP_OPTION (pfile, cpp_warn_implicit_fallthrough))
3097 {
3098 /* For both -Wimplicit-fallthrough=0 and -Wimplicit-fallthrough=5 we
3099 don't recognize any comments. The latter only checks attributes,
3100 the former doesn't warn. */
3101 case 0:
3102 default:
3103 return false;
3104 /* -Wimplicit-fallthrough=1 considers any comment, no matter what
3105 content it has. */
3106 case 1:
3107 return true;
3108 case 2:
3109 /* -Wimplicit-fallthrough=2 looks for (case insensitive)
3110 .*falls?[ \t-]*thr(u|ough).* regex. */
3111 for (; (size_t) (pfile->buffer->cur - from) >= sizeof "fallthru" - 1;
3112 from++)
3113 {
3114 /* Is there anything like strpbrk with upper boundary, or
3115 memchr looking for 2 characters rather than just one? */
3116 if (from[0] != 'f' && from[0] != 'F')
3117 continue;
3118 if (from[1] != 'a' && from[1] != 'A')
3119 continue;
3120 if (from[2] != 'l' && from[2] != 'L')
3121 continue;
3122 if (from[3] != 'l' && from[3] != 'L')
3123 continue;
3124 from += sizeof "fall" - 1;
3125 if (from[0] == 's' || from[0] == 'S')
3126 from++;
3127 while (*from == ' ' || *from == '\t' || *from == '-')
3128 from++;
3129 if (from[0] != 't' && from[0] != 'T')
3130 continue;
3131 if (from[1] != 'h' && from[1] != 'H')
3132 continue;
3133 if (from[2] != 'r' && from[2] != 'R')
3134 continue;
3135 if (from[3] == 'u' || from[3] == 'U')
3136 return true;
3137 if (from[3] != 'o' && from[3] != 'O')
3138 continue;
3139 if (from[4] != 'u' && from[4] != 'U')
3140 continue;
3141 if (from[5] != 'g' && from[5] != 'G')
3142 continue;
3143 if (from[6] != 'h' && from[6] != 'H')
3144 continue;
3145 return true;
3146 }
3147 return false;
3148 case 3:
3149 case 4:
3150 break;
3151 }
3152
3153 /* Whole comment contents:
3154 -fallthrough
3155 @fallthrough@
3156 */
3157 if (*from == '-' || *from == '@')
3158 {
3159 size_t len = sizeof "fallthrough" - 1;
3160 if ((size_t) (pfile->buffer->cur - from - 1) < len)
3161 return false;
3162 if (memcmp (from + 1, "fallthrough", len))
3163 return false;
3164 if (*from == '@')
3165 {
3166 if (from[len + 1] != '@')
3167 return false;
3168 len++;
3169 }
3170 from += 1 + len;
3171 }
3172 /* Whole comment contents (regex):
3173 lint -fallthrough[ \t]*
3174 */
3175 else if (*from == 'l')
3176 {
3177 size_t len = sizeof "int -fallthrough" - 1;
3178 if ((size_t) (pfile->buffer->cur - from - 1) < len)
3179 return false;
3180 if (memcmp (from + 1, "int -fallthrough", len))
3181 return false;
3182 from += 1 + len;
3183 while (*from == ' ' || *from == '\t')
3184 from++;
3185 }
3186 /* Whole comment contents (regex):
3187 [ \t]*FALLTHR(U|OUGH)[ \t]*
3188 */
3189 else if (CPP_OPTION (pfile, cpp_warn_implicit_fallthrough) == 4)
3190 {
3191 while (*from == ' ' || *from == '\t')
3192 from++;
3193 if ((size_t) (pfile->buffer->cur - from) < sizeof "FALLTHRU" - 1)
3194 return false;
3195 if (memcmp (from, "FALLTHR", sizeof "FALLTHR" - 1))
3196 return false;
3197 from += sizeof "FALLTHR" - 1;
3198 if (*from == 'U')
3199 from++;
3200 else if ((size_t) (pfile->buffer->cur - from) < sizeof "OUGH" - 1)
3201 return false;
3202 else if (memcmp (from, "OUGH", sizeof "OUGH" - 1))
3203 return false;
3204 else
3205 from += sizeof "OUGH" - 1;
3206 while (*from == ' ' || *from == '\t')
3207 from++;
3208 }
3209 /* Whole comment contents (regex):
3210 [ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?
3211 [ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?
3212 [ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?
3213 */
3214 else
3215 {
3216 while (*from == ' ' || *from == '\t' || *from == '.' || *from == '!')
3217 from++;
3218 unsigned char f = *from;
3219 bool all_upper = false;
3220 if (f == 'E' || f == 'e')
3221 {
3222 if ((size_t) (pfile->buffer->cur - from)
3223 < sizeof "else fallthru" - 1)
3224 return false;
3225 if (f == 'E' && memcmp (from + 1, "LSE", sizeof "LSE" - 1) == 0)
3226 all_upper = true;
3227 else if (memcmp (from + 1, "lse", sizeof "lse" - 1))
3228 return false;
3229 from += sizeof "else" - 1;
3230 if (*from == ',')
3231 from++;
3232 if (*from != ' ')
3233 return false;
3234 from++;
3235 if (all_upper && *from == 'f')
3236 return false;
3237 if (f == 'e' && *from == 'F')
3238 return false;
3239 f = *from;
3240 }
3241 else if (f == 'I' || f == 'i')
3242 {
3243 if ((size_t) (pfile->buffer->cur - from)
3244 < sizeof "intentional fallthru" - 1)
3245 return false;
3246 if (f == 'I' && memcmp (from + 1, "NTENTIONAL",
3247 sizeof "NTENTIONAL" - 1) == 0)
3248 all_upper = true;
3249 else if (memcmp (from + 1, "ntentional",
3250 sizeof "ntentional" - 1))
3251 return false;
3252 from += sizeof "intentional" - 1;
3253 if (*from == ' ')
3254 {
3255 from++;
3256 if (all_upper && *from == 'f')
3257 return false;
3258 }
3259 else if (all_upper)
3260 {
3261 if (memcmp (from, "LY F", sizeof "LY F" - 1))
3262 return false;
3263 from += sizeof "LY " - 1;
3264 }
3265 else
3266 {
3267 if (memcmp (from, "ly ", sizeof "ly " - 1))
3268 return false;
3269 from += sizeof "ly " - 1;
3270 }
3271 if (f == 'i' && *from == 'F')
3272 return false;
3273 f = *from;
3274 }
3275 if (f != 'F' && f != 'f')
3276 return false;
3277 if ((size_t) (pfile->buffer->cur - from) < sizeof "fallthru" - 1)
3278 return false;
3279 if (f == 'F' && memcmp (from + 1, "ALL", sizeof "ALL" - 1) == 0)
3280 all_upper = true;
3281 else if (all_upper)
3282 return false;
3283 else if (memcmp (from + 1, "all", sizeof "all" - 1))
3284 return false;
3285 from += sizeof "fall" - 1;
3286 if (*from == (all_upper ? 'S' : 's') && from[1] == ' ')
3287 from += 2;
3288 else if (*from == ' ' || *from == '-')
3289 from++;
3290 else if (*from != (all_upper ? 'T' : 't'))
3291 return false;
3292 if ((f == 'f' || *from != 'T') && (all_upper || *from != 't'))
3293 return false;
3294 if ((size_t) (pfile->buffer->cur - from) < sizeof "thru" - 1)
3295 return false;
3296 if (memcmp (from + 1, all_upper ? "HRU" : "hru", sizeof "hru" - 1))
3297 {
3298 if ((size_t) (pfile->buffer->cur - from) < sizeof "through" - 1)
3299 return false;
3300 if (memcmp (from + 1, all_upper ? "HROUGH" : "hrough",
3301 sizeof "hrough" - 1))
3302 return false;
3303 from += sizeof "through" - 1;
3304 }
3305 else
3306 from += sizeof "thru" - 1;
3307 while (*from == ' ' || *from == '\t' || *from == '.' || *from == '!')
3308 from++;
3309 if (*from == '-')
3310 {
3311 from++;
3312 if (*comment_start == '*')
3313 {
3314 do
3315 {
3316 while (*from && *from != '*'
3317 && *from != '\n' && *from != '\r')
3318 from++;
3319 if (*from != '*' || from[1] == '/')
3320 break;
3321 from++;
3322 }
3323 while (1);
3324 }
3325 else
3326 while (*from && *from != '\n' && *from != '\r')
3327 from++;
3328 }
3329 }
3330 /* C block comment. */
3331 if (*comment_start == '*')
3332 {
3333 if (*from != '*' || from[1] != '/')
3334 return false;
3335 }
3336 /* C++ line comment. */
3337 else if (*from != '\n')
3338 return false;
3339
3340 return true;
3341 }
3342
3343 /* Allocate COUNT tokens for RUN. */
3344 void
3345 _cpp_init_tokenrun (tokenrun *run, unsigned int count)
3346 {
3347 run->base = XNEWVEC (cpp_token, count);
3348 run->limit = run->base + count;
3349 run->next = NULL;
3350 }
3351
3352 /* Returns the next tokenrun, or creates one if there is none. */
3353 static tokenrun *
3354 next_tokenrun (tokenrun *run)
3355 {
3356 if (run->next == NULL)
3357 {
3358 run->next = XNEW (tokenrun);
3359 run->next->prev = run;
3360 _cpp_init_tokenrun (run->next, 250);
3361 }
3362
3363 return run->next;
3364 }
3365
3366 /* Return the number of not yet processed token in a given
3367 context. */
3368 int
3369 _cpp_remaining_tokens_num_in_context (cpp_context *context)
3370 {
3371 if (context->tokens_kind == TOKENS_KIND_DIRECT)
3372 return (LAST (context).token - FIRST (context).token);
3373 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
3374 || context->tokens_kind == TOKENS_KIND_EXTENDED)
3375 return (LAST (context).ptoken - FIRST (context).ptoken);
3376 else
3377 abort ();
3378 }
3379
3380 /* Returns the token present at index INDEX in a given context. If
3381 INDEX is zero, the next token to be processed is returned. */
3382 static const cpp_token*
3383 _cpp_token_from_context_at (cpp_context *context, int index)
3384 {
3385 if (context->tokens_kind == TOKENS_KIND_DIRECT)
3386 return &(FIRST (context).token[index]);
3387 else if (context->tokens_kind == TOKENS_KIND_INDIRECT
3388 || context->tokens_kind == TOKENS_KIND_EXTENDED)
3389 return FIRST (context).ptoken[index];
3390 else
3391 abort ();
3392 }
3393
3394 /* Look ahead in the input stream. */
3395 const cpp_token *
3396 cpp_peek_token (cpp_reader *pfile, int index)
3397 {
3398 cpp_context *context = pfile->context;
3399 const cpp_token *peektok;
3400 int count;
3401
3402 /* First, scan through any pending cpp_context objects. */
3403 while (context->prev)
3404 {
3405 ptrdiff_t sz = _cpp_remaining_tokens_num_in_context (context);
3406
3407 if (index < (int) sz)
3408 return _cpp_token_from_context_at (context, index);
3409 index -= (int) sz;
3410 context = context->prev;
3411 }
3412
3413 /* We will have to read some new tokens after all (and do so
3414 without invalidating preceding tokens). */
3415 count = index;
3416 pfile->keep_tokens++;
3417
3418 /* For peeked tokens temporarily disable line_change reporting,
3419 until the tokens are parsed for real. */
3420 void (*line_change) (cpp_reader *, const cpp_token *, int)
3421 = pfile->cb.line_change;
3422 pfile->cb.line_change = NULL;
3423
3424 do
3425 {
3426 peektok = _cpp_lex_token (pfile);
3427 if (peektok->type == CPP_EOF)
3428 {
3429 index--;
3430 break;
3431 }
3432 else if (peektok->type == CPP_PRAGMA)
3433 {
3434 /* Don't peek past a pragma. */
3435 if (peektok == &pfile->directive_result)
3436 /* Save the pragma in the buffer. */
3437 *pfile->cur_token++ = *peektok;
3438 index--;
3439 break;
3440 }
3441 }
3442 while (index--);
3443
3444 _cpp_backup_tokens_direct (pfile, count - index);
3445 pfile->keep_tokens--;
3446 pfile->cb.line_change = line_change;
3447
3448 return peektok;
3449 }
3450
3451 /* Allocate a single token that is invalidated at the same time as the
3452 rest of the tokens on the line. Has its line and col set to the
3453 same as the last lexed token, so that diagnostics appear in the
3454 right place. */
3455 cpp_token *
3456 _cpp_temp_token (cpp_reader *pfile)
3457 {
3458 cpp_token *old, *result;
3459 ptrdiff_t sz = pfile->cur_run->limit - pfile->cur_token;
3460 ptrdiff_t la = (ptrdiff_t) pfile->lookaheads;
3461
3462 old = pfile->cur_token - 1;
3463 /* Any pre-existing lookaheads must not be clobbered. */
3464 if (la)
3465 {
3466 if (sz <= la)
3467 {
3468 tokenrun *next = next_tokenrun (pfile->cur_run);
3469
3470 if (sz < la)
3471 memmove (next->base + 1, next->base,
3472 (la - sz) * sizeof (cpp_token));
3473
3474 next->base[0] = pfile->cur_run->limit[-1];
3475 }
3476
3477 if (sz > 1)
3478 memmove (pfile->cur_token + 1, pfile->cur_token,
3479 MIN (la, sz - 1) * sizeof (cpp_token));
3480 }
3481
3482 if (!sz && pfile->cur_token == pfile->cur_run->limit)
3483 {
3484 pfile->cur_run = next_tokenrun (pfile->cur_run);
3485 pfile->cur_token = pfile->cur_run->base;
3486 }
3487
3488 result = pfile->cur_token++;
3489 result->src_loc = old->src_loc;
3490 return result;
3491 }
3492
3493 /* We're at the beginning of a logical line (so not in
3494 directives-mode) and RESULT is a CPP_NAME with NODE_MODULE set. See
3495 if we should enter deferred_pragma mode to tokenize the rest of the
3496 line as a module control-line. */
3497
3498 static void
3499 cpp_maybe_module_directive (cpp_reader *pfile, cpp_token *result)
3500 {
3501 unsigned backup = 0; /* Tokens we peeked. */
3502 cpp_hashnode *node = result->val.node.node;
3503 cpp_token *peek = result;
3504 cpp_token *keyword = peek;
3505 cpp_hashnode *(&n_modules)[spec_nodes::M_HWM][2] = pfile->spec_nodes.n_modules;
3506 int header_count = 0;
3507 bool eol = false;
3508
3509 /* Make sure the incoming state is as we expect it. This way we
3510 can restore it using constants. */
3511 gcc_checking_assert (!pfile->state.in_deferred_pragma
3512 && !pfile->state.skipping
3513 && !pfile->state.parsing_args
3514 && !pfile->state.angled_headers
3515 && (pfile->state.save_comments
3516 == !CPP_OPTION (pfile, discard_comments)));
3517
3518 /* Enter directives mode sufficiently for peeking. We don't have
3519 to actually set in_directive. */
3520 pfile->state.in_deferred_pragma = true;
3521
3522 /* These two fields are needed to process tokenization in deferred
3523 pragma mode. They are not used outside deferred pragma mode or
3524 directives mode. */
3525 pfile->state.pragma_allow_expansion = true;
3526 pfile->directive_line = result->src_loc;
3527
3528 /* Saving comments is incompatible with directives mode. */
3529 pfile->state.save_comments = 0;
3530
3531 if (node == n_modules[spec_nodes::M_EXPORT][0])
3532 {
3533 peek = _cpp_lex_direct (pfile);
3534 keyword = peek;
3535 backup++;
3536 if (keyword->type != CPP_NAME)
3537 goto not_module;
3538 node = keyword->val.node.node;
3539 if (!(node->flags & NODE_MODULE))
3540 goto not_module;
3541 }
3542
3543 if (node == n_modules[spec_nodes::M__IMPORT][0])
3544 /* __import */
3545 header_count = backup + 2 + 16;
3546 else if (node == n_modules[spec_nodes::M_IMPORT][0])
3547 /* import */
3548 header_count = backup + 2 + (CPP_OPTION (pfile, preprocessed) ? 16 : 0);
3549 else if (node == n_modules[spec_nodes::M_MODULE][0])
3550 ; /* module */
3551 else
3552 goto not_module;
3553
3554 /* We've seen [export] {module|import|__import}. Check the next token. */
3555 if (header_count)
3556 /* After '{,__}import' a header name may appear. */
3557 pfile->state.angled_headers = true;
3558 peek = _cpp_lex_direct (pfile);
3559 backup++;
3560
3561 /* ... import followed by identifier, ':', '<' or
3562 header-name preprocessing tokens, or module
3563 followed by cpp-identifier, ':' or ';' preprocessing
3564 tokens. C++ keywords are not yet relevant. */
3565 if (peek->type == CPP_NAME
3566 || peek->type == CPP_COLON
3567 || (header_count
3568 ? (peek->type == CPP_LESS
3569 || (peek->type == CPP_STRING && peek->val.str.text[0] != 'R')
3570 || peek->type == CPP_HEADER_NAME)
3571 : peek->type == CPP_SEMICOLON))
3572 {
3573 pfile->state.pragma_allow_expansion = !CPP_OPTION (pfile, preprocessed);
3574 if (!pfile->state.pragma_allow_expansion)
3575 pfile->state.prevent_expansion++;
3576
3577 if (!header_count && linemap_included_from
3578 (LINEMAPS_LAST_ORDINARY_MAP (pfile->line_table)))
3579 cpp_error_with_line (pfile, CPP_DL_ERROR, keyword->src_loc, 0,
3580 "module control-line cannot be in included file");
3581
3582 /* The first one or two tokens cannot be macro names. */
3583 for (int ix = backup; ix--;)
3584 {
3585 cpp_token *tok = ix ? keyword : result;
3586 cpp_hashnode *node = tok->val.node.node;
3587
3588 /* Don't attempt to expand the token. */
3589 tok->flags |= NO_EXPAND;
3590 if (_cpp_defined_macro_p (node)
3591 && _cpp_maybe_notify_macro_use (pfile, node, tok->src_loc)
3592 && !cpp_fun_like_macro_p (node))
3593 cpp_error_with_line (pfile, CPP_DL_ERROR, tok->src_loc, 0,
3594 "module control-line %qs cannot be"
3595 " an object-like macro",
3596 NODE_NAME (node));
3597 }
3598
3599 /* Map to underbar variants. */
3600 keyword->val.node.node = n_modules[header_count
3601 ? spec_nodes::M_IMPORT
3602 : spec_nodes::M_MODULE][1];
3603 if (backup != 1)
3604 result->val.node.node = n_modules[spec_nodes::M_EXPORT][1];
3605
3606 /* Maybe tell the tokenizer we expect a header-name down the
3607 road. */
3608 pfile->state.directive_file_token = header_count;
3609
3610 /* According to P3034R1, pp-module-name and pp-module-partition tokens
3611 if any shouldn't be macro expanded and identifiers shouldn't be
3612 defined as object-like macro. */
3613 if (!header_count && peek->type == CPP_NAME)
3614 {
3615 int state = 0;
3616 do
3617 {
3618 cpp_token *tok = peek;
3619 if (tok->type == CPP_NAME)
3620 {
3621 cpp_hashnode *node = tok->val.node.node;
3622 /* Don't attempt to expand the token. */
3623 tok->flags |= NO_EXPAND;
3624 if (_cpp_defined_macro_p (node)
3625 && _cpp_maybe_notify_macro_use (pfile, node,
3626 tok->src_loc)
3627 && !cpp_fun_like_macro_p (node))
3628 {
3629 if (state == 0)
3630 cpp_error_with_line (pfile, CPP_DL_ERROR,
3631 tok->src_loc, 0,
3632 "module name %qs cannot "
3633 "be an object-like macro",
3634 NODE_NAME (node));
3635 else
3636 cpp_error_with_line (pfile, CPP_DL_ERROR,
3637 tok->src_loc, 0,
3638 "module partition %qs cannot "
3639 "be an object-like macro",
3640 NODE_NAME (node));
3641 }
3642 }
3643 peek = _cpp_lex_direct (pfile);
3644 backup++;
3645 if (tok->type == CPP_NAME)
3646 {
3647 if (peek->type == CPP_DOT)
3648 continue;
3649 else if (peek->type == CPP_COLON && state == 0)
3650 {
3651 ++state;
3652 continue;
3653 }
3654 else if (peek->type == CPP_OPEN_PAREN)
3655 {
3656 if (state == 0)
3657 cpp_error_with_line (pfile, CPP_DL_ERROR,
3658 peek->src_loc, 0,
3659 "module name followed by %<(%>");
3660 else
3661 cpp_error_with_line (pfile, CPP_DL_ERROR,
3662 peek->src_loc, 0,
3663 "module partition followed by "
3664 "%<(%>");
3665 break;
3666 }
3667 else if (peek->type == CPP_NAME
3668 && _cpp_defined_macro_p (peek->val.node.node))
3669 {
3670 peek->flags |= NO_DOT_COLON;
3671 break;
3672 }
3673 else if (peek->type == CPP_PRAGMA_EOL)
3674 {
3675 /* This is a broken module-directive; undo the clearing
3676 of in_deferred_pragma from _cpp_lex_direct so callers
3677 don't crash, and make sure we process the EOL again. */
3678 pfile->state.in_deferred_pragma = true;
3679 eol = true;
3680 break;
3681 }
3682 else
3683 break;
3684 }
3685 else if (peek->type != CPP_NAME)
3686 break;
3687 }
3688 while (true);
3689 }
3690 }
3691 else
3692 {
3693 not_module:
3694 /* Drop out of directive mode. */
3695 /* We aaserted save_comments had this value upon entry. */
3696 pfile->state.save_comments
3697 = !CPP_OPTION (pfile, discard_comments);
3698 pfile->state.in_deferred_pragma = false;
3699 /* Do not let this remain on. */
3700 pfile->state.angled_headers = false;
3701 /* If we saw EOL, we should drop it, because this isn't a module
3702 control-line after all. */
3703 eol = peek->type == CPP_PRAGMA_EOL;
3704 }
3705
3706 /* In either case we want to backup the peeked tokens. */
3707 if (backup && (!eol || backup > 1))
3708 {
3709 /* Put the peeked tokens back. */
3710 _cpp_backup_tokens_direct (pfile, backup);
3711 /* But if the last one was an EOL, forget it. */
3712 if (eol)
3713 pfile->lookaheads--;
3714 }
3715 }
3716
3717 /* Lex a token into RESULT (external interface). Takes care of issues
3718 like directive handling, token lookahead, multiple include
3719 optimization and skipping. */
3720 const cpp_token *
3721 _cpp_lex_token (cpp_reader *pfile)
3722 {
3723 cpp_token *result;
3724
3725 for (;;)
3726 {
3727 if (pfile->cur_token == pfile->cur_run->limit)
3728 {
3729 pfile->cur_run = next_tokenrun (pfile->cur_run);
3730 pfile->cur_token = pfile->cur_run->base;
3731 }
3732 /* We assume that the current token is somewhere in the current
3733 run. */
3734 if (pfile->cur_token < pfile->cur_run->base
3735 || pfile->cur_token >= pfile->cur_run->limit)
3736 abort ();
3737
3738 if (pfile->lookaheads)
3739 {
3740 pfile->lookaheads--;
3741 result = pfile->cur_token++;
3742 }
3743 else
3744 result = _cpp_lex_direct (pfile);
3745
3746 if (result->flags & BOL)
3747 {
3748 /* Is this a directive. If _cpp_handle_directive returns
3749 false, it is an assembler #. */
3750 if (result->type == CPP_HASH
3751 /* 6.10.3 p 11: Directives in a list of macro arguments
3752 gives undefined behavior. This implementation
3753 handles the directive as normal. */
3754 && pfile->state.parsing_args != 1)
3755 {
3756 if (_cpp_handle_directive (pfile, result->flags & PREV_WHITE))
3757 {
3758 if (pfile->directive_result.type == CPP_PADDING)
3759 continue;
3760 result = &pfile->directive_result;
3761 }
3762 }
3763 else if (pfile->state.in_deferred_pragma)
3764 result = &pfile->directive_result;
3765 else if (result->type == CPP_NAME
3766 && (result->val.node.node->flags & NODE_MODULE)
3767 && !pfile->state.skipping
3768 /* Unlike regular directives, we do not deal with
3769 tokenizing module directives as macro arguments.
3770 That's not permitted. */
3771 && !pfile->state.parsing_args)
3772 {
3773 /* P1857. Before macro expansion, At start of logical
3774 line ... */
3775 /* We don't have to consider lookaheads at this point. */
3776 gcc_checking_assert (!pfile->lookaheads);
3777
3778 cpp_maybe_module_directive (pfile, result);
3779 }
3780
3781 if (pfile->cb.line_change && !pfile->state.skipping)
3782 pfile->cb.line_change (pfile, result, pfile->state.parsing_args);
3783 }
3784
3785 /* We don't skip tokens in directives. */
3786 if (pfile->state.in_directive || pfile->state.in_deferred_pragma)
3787 break;
3788
3789 /* Outside a directive, invalidate controlling macros. At file
3790 EOF, _cpp_lex_direct takes care of popping the buffer, so we never
3791 get here and MI optimization works. */
3792 pfile->mi_valid = false;
3793
3794 if (!pfile->state.skipping || result->type == CPP_EOF)
3795 break;
3796 }
3797
3798 return result;
3799 }
3800
3801 /* Returns true if a fresh line has been loaded. */
3802 template <bool lexing_raw_string>
3803 static bool
3804 get_fresh_line_impl (cpp_reader *pfile)
3805 {
3806 /* We can't get a new line until we leave the current directive, unless we
3807 are lexing a raw string, in which case it will be OK as long as we don't
3808 pop the current buffer. */
3809 if (!lexing_raw_string && pfile->state.in_directive)
3810 return false;
3811
3812 for (;;)
3813 {
3814 cpp_buffer *buffer = pfile->buffer;
3815
3816 if (!buffer->need_line)
3817 return true;
3818
3819 if (buffer->next_line < buffer->rlimit)
3820 {
3821 _cpp_clean_line (pfile);
3822 return true;
3823 }
3824
3825 /* We can't change buffers until we leave the current directive. */
3826 if (lexing_raw_string && pfile->state.in_directive)
3827 return false;
3828
3829 /* First, get out of parsing arguments state. */
3830 if (pfile->state.parsing_args)
3831 return false;
3832
3833 /* End of buffer. Non-empty files should end in a newline. */
3834 if (buffer->buf != buffer->rlimit
3835 && buffer->next_line > buffer->rlimit
3836 && !buffer->from_stage3)
3837 {
3838 /* Clip to buffer size. */
3839 buffer->next_line = buffer->rlimit;
3840 }
3841
3842 if (buffer->prev && !buffer->return_at_eof)
3843 _cpp_pop_buffer (pfile);
3844 else
3845 {
3846 /* End of translation. Do not pop the buffer yet. Increment
3847 line number so that the EOF token is on a line of its own
3848 (_cpp_lex_direct doesn't increment in that case, because
3849 it's hard for it to distinguish this special case). */
3850 CPP_INCREMENT_LINE (pfile, 0);
3851 return false;
3852 }
3853 }
3854 }
3855
3856 bool
3857 _cpp_get_fresh_line (cpp_reader *pfile)
3858 {
3859 return get_fresh_line_impl<false> (pfile);
3860 }
3861
3862
3863 #define IF_NEXT_IS(CHAR, THEN_TYPE, ELSE_TYPE) \
3864 do \
3865 { \
3866 result->type = ELSE_TYPE; \
3867 if (*buffer->cur == CHAR) \
3868 buffer->cur++, result->type = THEN_TYPE; \
3869 } \
3870 while (0)
3871
3872 /* Lex a token into pfile->cur_token, which is also incremented, to
3873 get diagnostics pointing to the correct location.
3874
3875 Does not handle issues such as token lookahead, multiple-include
3876 optimization, directives, skipping etc. This function is only
3877 suitable for use by _cpp_lex_token, and in special cases like
3878 lex_expansion_token which doesn't care for any of these issues.
3879
3880 When meeting a newline, returns CPP_EOF if parsing a directive,
3881 otherwise returns to the start of the token buffer if permissible.
3882 Returns the location of the lexed token. */
3883 cpp_token *
3884 _cpp_lex_direct (cpp_reader *pfile)
3885 {
3886 cppchar_t c = 0;
3887 cpp_buffer *buffer;
3888 const unsigned char *comment_start;
3889 bool fallthrough_comment = false;
3890 cpp_token *result = pfile->cur_token++;
3891
3892 fresh_line:
3893 result->flags = 0;
3894 buffer = pfile->buffer;
3895 if (buffer->need_line)
3896 {
3897 if (pfile->state.in_deferred_pragma)
3898 {
3899 /* This can happen in cases like:
3900 #define loop(x) whatever
3901 #pragma omp loop
3902 where when trying to expand loop we need to peek
3903 next token after loop, but aren't still in_deferred_pragma
3904 mode but are in in_directive mode, so buffer->need_line
3905 is set, a CPP_EOF is peeked. */
3906 result->type = CPP_PRAGMA_EOL;
3907 pfile->state.in_deferred_pragma = false;
3908 if (!pfile->state.pragma_allow_expansion)
3909 pfile->state.prevent_expansion--;
3910 result->src_loc = pfile->line_table->highest_line;
3911 return result;
3912 }
3913 if (!_cpp_get_fresh_line (pfile))
3914 {
3915 result->type = CPP_EOF;
3916 /* Not a real EOF in a directive or arg parsing -- we refuse
3917 to advance to the next file now, and will once we're out
3918 of those modes. */
3919 if (!pfile->state.in_directive && !pfile->state.parsing_args)
3920 {
3921 /* Tell the compiler the line number of the EOF token. */
3922 result->src_loc = pfile->line_table->highest_line;
3923 result->flags = BOL;
3924 /* Now pop the buffer that _cpp_get_fresh_line did not. */
3925 _cpp_pop_buffer (pfile);
3926 }
3927 else if (c == 0)
3928 result->src_loc = pfile->line_table->highest_line;
3929 return result;
3930 }
3931 if (buffer != pfile->buffer)
3932 fallthrough_comment = false;
3933 if (!pfile->keep_tokens)
3934 {
3935 pfile->cur_run = &pfile->base_run;
3936 result = pfile->base_run.base;
3937 pfile->cur_token = result + 1;
3938 }
3939 result->flags = BOL;
3940 if (pfile->state.parsing_args == 2)
3941 result->flags |= PREV_WHITE;
3942 }
3943 buffer = pfile->buffer;
3944 update_tokens_line:
3945 result->src_loc = pfile->line_table->highest_line;
3946
3947 skipped_white:
3948 if (buffer->cur >= buffer->notes[buffer->cur_note].pos
3949 && !pfile->overlaid_buffer)
3950 {
3951 _cpp_process_line_notes (pfile, false);
3952 result->src_loc = pfile->line_table->highest_line;
3953 }
3954 c = *buffer->cur++;
3955
3956 if (pfile->forced_token_location)
3957 result->src_loc = pfile->forced_token_location;
3958 else
3959 result->src_loc = linemap_position_for_column (pfile->line_table,
3960 CPP_BUF_COLUMN (buffer, buffer->cur));
3961
3962 switch (c)
3963 {
3964 case ' ': case '\t': case '\f': case '\v': case '\0':
3965 result->flags |= PREV_WHITE;
3966 skip_whitespace (pfile, c);
3967 goto skipped_white;
3968
3969 case '\n':
3970 /* Increment the line, unless this is the last line ... */
3971 if (buffer->cur < buffer->rlimit
3972 /* ... or this is a #include, (where _cpp_stack_file needs to
3973 unwind by one line) ... */
3974 || (pfile->state.in_directive > 1
3975 /* ... except traditional-cpp increments this elsewhere. */
3976 && !CPP_OPTION (pfile, traditional)))
3977 CPP_INCREMENT_LINE (pfile, 0);
3978 buffer->need_line = true;
3979 if (pfile->state.in_deferred_pragma)
3980 {
3981 /* Produce the PRAGMA_EOL on this line. File reading
3982 ensures there is always a \n at end of the buffer, thus
3983 in a deferred pragma we always see CPP_PRAGMA_EOL before
3984 any CPP_EOF. */
3985 result->type = CPP_PRAGMA_EOL;
3986 result->flags &= ~PREV_WHITE;
3987 pfile->state.in_deferred_pragma = false;
3988 if (!pfile->state.pragma_allow_expansion)
3989 pfile->state.prevent_expansion--;
3990 return result;
3991 }
3992 goto fresh_line;
3993
3994 case '0': case '1': case '2': case '3': case '4':
3995 case '5': case '6': case '7': case '8': case '9':
3996 {
3997 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
3998 result->type = CPP_NUMBER;
3999 lex_number (pfile, &result->val.str, &nst);
4000 warn_about_normalization (pfile, result, &nst, false);
4001 break;
4002 }
4003
4004 case 'L':
4005 case 'u':
4006 case 'U':
4007 case 'R':
4008 /* 'L', 'u', 'U', 'u8' or 'R' may introduce wide characters,
4009 wide strings or raw strings. */
4010 if (c == 'L' || CPP_OPTION (pfile, rliterals)
4011 || (c != 'R' && CPP_OPTION (pfile, uliterals)))
4012 {
4013 if ((*buffer->cur == '\'' && c != 'R')
4014 || *buffer->cur == '"'
4015 || (*buffer->cur == 'R'
4016 && c != 'R'
4017 && buffer->cur[1] == '"'
4018 && CPP_OPTION (pfile, rliterals))
4019 || (*buffer->cur == '8'
4020 && c == 'u'
4021 && ((buffer->cur[1] == '"' || (buffer->cur[1] == '\''
4022 && CPP_OPTION (pfile, utf8_char_literals)))
4023 || (buffer->cur[1] == 'R' && buffer->cur[2] == '"'
4024 && CPP_OPTION (pfile, rliterals)))))
4025 {
4026 lex_string (pfile, result, buffer->cur - 1);
4027 break;
4028 }
4029 }
4030 /* Fall through. */
4031
4032 case '_':
4033 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
4034 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
4035 case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
4036 case 's': case 't': case 'v': case 'w': case 'x':
4037 case 'y': case 'z':
4038 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
4039 case 'G': case 'H': case 'I': case 'J': case 'K':
4040 case 'M': case 'N': case 'O': case 'P': case 'Q':
4041 case 'S': case 'T': case 'V': case 'W': case 'X':
4042 case 'Y': case 'Z':
4043 result->type = CPP_NAME;
4044 {
4045 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
4046 const auto node = lex_identifier (pfile, buffer->cur - 1, false, &nst,
4047 &result->val.node.spelling);
4048 result->val.node.node = node;
4049 identifier_diagnostics_on_lex (pfile, node);
4050 warn_about_normalization (pfile, result, &nst, true);
4051 }
4052
4053 /* Convert named operators to their proper types. */
4054 if (result->val.node.node->flags & NODE_OPERATOR)
4055 {
4056 result->flags |= NAMED_OP;
4057 result->type = (enum cpp_ttype) result->val.node.node->directive_index;
4058 }
4059
4060 /* Signal FALLTHROUGH comment followed by another token. */
4061 if (fallthrough_comment)
4062 result->flags |= PREV_FALLTHROUGH;
4063 break;
4064
4065 case '\'':
4066 case '"':
4067 lex_string (pfile, result, buffer->cur - 1);
4068 break;
4069
4070 case '/':
4071 /* A potential block or line comment. */
4072 comment_start = buffer->cur;
4073 c = *buffer->cur;
4074
4075 if (c == '*')
4076 {
4077 if (_cpp_skip_block_comment (pfile))
4078 cpp_error (pfile, CPP_DL_ERROR, "unterminated comment");
4079 }
4080 else if (c == '/' && ! CPP_OPTION (pfile, traditional))
4081 {
4082 /* Don't warn for system headers. */
4083 if (_cpp_in_system_header (pfile))
4084 ;
4085 /* Warn about comments if pedantically GNUC89, and not
4086 in system headers. */
4087 else if (CPP_OPTION (pfile, lang) == CLK_GNUC89
4088 && CPP_PEDANTIC (pfile)
4089 && ! buffer->warned_cplusplus_comments)
4090 {
4091 if (cpp_pedwarning (pfile, CPP_W_PEDANTIC,
4092 "C++ style comments are not allowed "
4093 "in ISO C90"))
4094 cpp_error (pfile, CPP_DL_NOTE,
4095 "(this will be reported only once per input file)");
4096 buffer->warned_cplusplus_comments = 1;
4097 }
4098 /* Or if specifically desired via -Wc90-c99-compat. */
4099 else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
4100 && ! CPP_OPTION (pfile, cplusplus)
4101 && ! buffer->warned_cplusplus_comments)
4102 {
4103 if (cpp_error (pfile, CPP_DL_WARNING,
4104 "C++ style comments are incompatible with C90"))
4105 cpp_error (pfile, CPP_DL_NOTE,
4106 "(this will be reported only once per input file)");
4107 buffer->warned_cplusplus_comments = 1;
4108 }
4109 /* In C89/C94, C++ style comments are forbidden. */
4110 else if ((CPP_OPTION (pfile, lang) == CLK_STDC89
4111 || CPP_OPTION (pfile, lang) == CLK_STDC94))
4112 {
4113 /* But don't be confused about valid code such as
4114 - // immediately followed by *,
4115 - // in a preprocessing directive,
4116 - // in an #if 0 block. */
4117 if (buffer->cur[1] == '*'
4118 || pfile->state.in_directive
4119 || pfile->state.skipping)
4120 {
4121 result->type = CPP_DIV;
4122 break;
4123 }
4124 else if (! buffer->warned_cplusplus_comments)
4125 {
4126 if (cpp_error (pfile, CPP_DL_ERROR,
4127 "C++ style comments are not allowed in "
4128 "ISO C90"))
4129 cpp_error (pfile, CPP_DL_NOTE,
4130 "(this will be reported only once per input "
4131 "file)");
4132 buffer->warned_cplusplus_comments = 1;
4133 }
4134 }
4135 if (skip_line_comment (pfile) && CPP_OPTION (pfile, warn_comments))
4136 cpp_warning (pfile, CPP_W_COMMENTS, "multi-line comment");
4137 }
4138 else if (c == '=')
4139 {
4140 buffer->cur++;
4141 result->type = CPP_DIV_EQ;
4142 break;
4143 }
4144 else
4145 {
4146 result->type = CPP_DIV;
4147 break;
4148 }
4149
4150 if (fallthrough_comment_p (pfile, comment_start))
4151 fallthrough_comment = true;
4152
4153 if (pfile->cb.comment)
4154 {
4155 size_t len = pfile->buffer->cur - comment_start;
4156 pfile->cb.comment (pfile, result->src_loc, comment_start - 1,
4157 len + 1);
4158 }
4159
4160 if (!pfile->state.save_comments)
4161 {
4162 result->flags |= PREV_WHITE;
4163 goto update_tokens_line;
4164 }
4165
4166 if (fallthrough_comment)
4167 result->flags |= PREV_FALLTHROUGH;
4168
4169 /* Save the comment as a token in its own right. */
4170 save_comment (pfile, result, comment_start, c);
4171 break;
4172
4173 case '<':
4174 if (pfile->state.angled_headers)
4175 {
4176 lex_string (pfile, result, buffer->cur - 1);
4177 if (result->type != CPP_LESS)
4178 break;
4179 }
4180
4181 result->type = CPP_LESS;
4182 if (*buffer->cur == '=')
4183 {
4184 buffer->cur++, result->type = CPP_LESS_EQ;
4185 if (*buffer->cur == '>'
4186 && CPP_OPTION (pfile, cplusplus)
4187 && CPP_OPTION (pfile, lang) >= CLK_GNUCXX20)
4188 buffer->cur++, result->type = CPP_SPACESHIP;
4189 }
4190 else if (*buffer->cur == '<')
4191 {
4192 buffer->cur++;
4193 IF_NEXT_IS ('=', CPP_LSHIFT_EQ, CPP_LSHIFT);
4194 }
4195 else if (CPP_OPTION (pfile, digraphs))
4196 {
4197 if (*buffer->cur == ':')
4198 {
4199 /* C++11 [2.5/3 lex.pptoken], "Otherwise, if the next
4200 three characters are <:: and the subsequent character
4201 is neither : nor >, the < is treated as a preprocessor
4202 token by itself". */
4203 if (CPP_OPTION (pfile, cplusplus)
4204 && CPP_OPTION (pfile, lang) != CLK_CXX98
4205 && CPP_OPTION (pfile, lang) != CLK_GNUCXX
4206 && buffer->cur[1] == ':'
4207 && buffer->cur[2] != ':' && buffer->cur[2] != '>')
4208 break;
4209
4210 buffer->cur++;
4211 result->flags |= DIGRAPH;
4212 result->type = CPP_OPEN_SQUARE;
4213 }
4214 else if (*buffer->cur == '%')
4215 {
4216 buffer->cur++;
4217 result->flags |= DIGRAPH;
4218 result->type = CPP_OPEN_BRACE;
4219 }
4220 }
4221 break;
4222
4223 case '>':
4224 result->type = CPP_GREATER;
4225 if (*buffer->cur == '=')
4226 buffer->cur++, result->type = CPP_GREATER_EQ;
4227 else if (*buffer->cur == '>')
4228 {
4229 buffer->cur++;
4230 IF_NEXT_IS ('=', CPP_RSHIFT_EQ, CPP_RSHIFT);
4231 }
4232 break;
4233
4234 case '%':
4235 result->type = CPP_MOD;
4236 if (*buffer->cur == '=')
4237 buffer->cur++, result->type = CPP_MOD_EQ;
4238 else if (CPP_OPTION (pfile, digraphs))
4239 {
4240 if (*buffer->cur == ':')
4241 {
4242 buffer->cur++;
4243 result->flags |= DIGRAPH;
4244 result->type = CPP_HASH;
4245 if (*buffer->cur == '%' && buffer->cur[1] == ':')
4246 buffer->cur += 2, result->type = CPP_PASTE, result->val.token_no = 0;
4247 }
4248 else if (*buffer->cur == '>')
4249 {
4250 buffer->cur++;
4251 result->flags |= DIGRAPH;
4252 result->type = CPP_CLOSE_BRACE;
4253 }
4254 }
4255 break;
4256
4257 case '.':
4258 result->type = CPP_DOT;
4259 if (ISDIGIT (*buffer->cur))
4260 {
4261 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
4262 result->type = CPP_NUMBER;
4263 lex_number (pfile, &result->val.str, &nst);
4264 warn_about_normalization (pfile, result, &nst, false);
4265 }
4266 else if (*buffer->cur == '.' && buffer->cur[1] == '.')
4267 buffer->cur += 2, result->type = CPP_ELLIPSIS;
4268 else if (*buffer->cur == '*' && CPP_OPTION (pfile, cplusplus))
4269 buffer->cur++, result->type = CPP_DOT_STAR;
4270 break;
4271
4272 case '+':
4273 result->type = CPP_PLUS;
4274 if (*buffer->cur == '+')
4275 buffer->cur++, result->type = CPP_PLUS_PLUS;
4276 else if (*buffer->cur == '=')
4277 buffer->cur++, result->type = CPP_PLUS_EQ;
4278 break;
4279
4280 case '-':
4281 result->type = CPP_MINUS;
4282 if (*buffer->cur == '>')
4283 {
4284 buffer->cur++;
4285 result->type = CPP_DEREF;
4286 if (*buffer->cur == '*' && CPP_OPTION (pfile, cplusplus))
4287 buffer->cur++, result->type = CPP_DEREF_STAR;
4288 }
4289 else if (*buffer->cur == '-')
4290 buffer->cur++, result->type = CPP_MINUS_MINUS;
4291 else if (*buffer->cur == '=')
4292 buffer->cur++, result->type = CPP_MINUS_EQ;
4293 break;
4294
4295 case '&':
4296 result->type = CPP_AND;
4297 if (*buffer->cur == '&')
4298 buffer->cur++, result->type = CPP_AND_AND;
4299 else if (*buffer->cur == '=')
4300 buffer->cur++, result->type = CPP_AND_EQ;
4301 break;
4302
4303 case '|':
4304 result->type = CPP_OR;
4305 if (*buffer->cur == '|')
4306 buffer->cur++, result->type = CPP_OR_OR;
4307 else if (*buffer->cur == '=')
4308 buffer->cur++, result->type = CPP_OR_EQ;
4309 break;
4310
4311 case ':':
4312 result->type = CPP_COLON;
4313 if (*buffer->cur == ':')
4314 {
4315 if (CPP_OPTION (pfile, scope))
4316 buffer->cur++, result->type = CPP_SCOPE;
4317 else
4318 result->flags |= COLON_SCOPE;
4319 }
4320 else if (*buffer->cur == '>' && CPP_OPTION (pfile, digraphs))
4321 {
4322 buffer->cur++;
4323 result->flags |= DIGRAPH;
4324 result->type = CPP_CLOSE_SQUARE;
4325 }
4326 break;
4327
4328 case '*': IF_NEXT_IS ('=', CPP_MULT_EQ, CPP_MULT); break;
4329 case '=': IF_NEXT_IS ('=', CPP_EQ_EQ, CPP_EQ); break;
4330 case '!': IF_NEXT_IS ('=', CPP_NOT_EQ, CPP_NOT); break;
4331 case '^': IF_NEXT_IS ('=', CPP_XOR_EQ, CPP_XOR); break;
4332 case '#': IF_NEXT_IS ('#', CPP_PASTE, CPP_HASH); result->val.token_no = 0; break;
4333
4334 case '?': result->type = CPP_QUERY; break;
4335 case '~': result->type = CPP_COMPL; break;
4336 case ',': result->type = CPP_COMMA; break;
4337 case '(': result->type = CPP_OPEN_PAREN; break;
4338 case ')': result->type = CPP_CLOSE_PAREN; break;
4339 case '[': result->type = CPP_OPEN_SQUARE; break;
4340 case ']': result->type = CPP_CLOSE_SQUARE; break;
4341 case '{': result->type = CPP_OPEN_BRACE; break;
4342 case '}': result->type = CPP_CLOSE_BRACE; break;
4343 case ';': result->type = CPP_SEMICOLON; break;
4344
4345 /* @ is a punctuator in Objective-C. */
4346 case '@': result->type = CPP_ATSIGN; break;
4347
4348 default:
4349 {
4350 const uchar *base = --buffer->cur;
4351 static int no_warn_cnt;
4352
4353 /* Check for an extended identifier ($ or UCN or UTF-8). */
4354 struct normalize_state nst = INITIAL_NORMALIZE_STATE;
4355 if (forms_identifier_p (pfile, true, &nst))
4356 {
4357 result->type = CPP_NAME;
4358 const auto node = lex_identifier (pfile, base, true, &nst,
4359 &result->val.node.spelling);
4360 result->val.node.node = node;
4361 identifier_diagnostics_on_lex (pfile, node);
4362 warn_about_normalization (pfile, result, &nst, true);
4363 break;
4364 }
4365
4366 /* Otherwise this will form a CPP_OTHER token. Parse valid UTF-8 as a
4367 single token. */
4368 buffer->cur++;
4369 if (c >= utf8_signifier)
4370 {
4371 const uchar *pstr = base;
4372 cppchar_t s;
4373 if (_cpp_valid_utf8 (pfile, &pstr, buffer->rlimit, 0, NULL, &s))
4374 {
4375 if (s > UCS_LIMIT && CPP_OPTION (pfile, cpp_warn_invalid_utf8))
4376 {
4377 buffer->cur = base;
4378 _cpp_warn_invalid_utf8 (pfile);
4379 }
4380 buffer->cur = pstr;
4381 }
4382 else if (CPP_OPTION (pfile, cpp_warn_invalid_utf8))
4383 {
4384 buffer->cur = base;
4385 const uchar *end = _cpp_warn_invalid_utf8 (pfile);
4386 buffer->cur = base + 1;
4387 no_warn_cnt = end - buffer->cur;
4388 }
4389 }
4390 else if (c >= utf8_continuation
4391 && CPP_OPTION (pfile, cpp_warn_invalid_utf8))
4392 {
4393 if (no_warn_cnt)
4394 --no_warn_cnt;
4395 else
4396 {
4397 buffer->cur = base;
4398 _cpp_warn_invalid_utf8 (pfile);
4399 buffer->cur = base + 1;
4400 }
4401 }
4402 create_literal (pfile, result, base, buffer->cur - base, CPP_OTHER);
4403 break;
4404 }
4405
4406 }
4407
4408 /* Potentially convert the location of the token to a range. */
4409 if (result->src_loc >= RESERVED_LOCATION_COUNT
4410 && result->type != CPP_EOF)
4411 {
4412 /* Ensure that any line notes are processed, so that we have the
4413 correct physical line/column for the end-point of the token even
4414 when a logical line is split via one or more backslashes. */
4415 if (buffer->cur >= buffer->notes[buffer->cur_note].pos
4416 && !pfile->overlaid_buffer)
4417 _cpp_process_line_notes (pfile, false);
4418
4419 source_range tok_range;
4420 tok_range.m_start = result->src_loc;
4421 tok_range.m_finish
4422 = linemap_position_for_column (pfile->line_table,
4423 CPP_BUF_COLUMN (buffer, buffer->cur));
4424
4425 result->src_loc
4426 = pfile->line_table->get_or_create_combined_loc (result->src_loc,
4427 tok_range, nullptr, 0);
4428 }
4429
4430 return result;
4431 }
4432
4433 /* An upper bound on the number of bytes needed to spell TOKEN.
4434 Does not include preceding whitespace. */
4435 unsigned int
4436 cpp_token_len (const cpp_token *token)
4437 {
4438 unsigned int len;
4439
4440 switch (TOKEN_SPELL (token))
4441 {
4442 default: len = 6; break;
4443 case SPELL_LITERAL: len = token->val.str.len; break;
4444 case SPELL_IDENT: len = NODE_LEN (token->val.node.node) * 10; break;
4445 }
4446
4447 return len;
4448 }
4449
4450 /* Parse UTF-8 out of NAMEP and place a \U escape in BUFFER.
4451 Return the number of bytes read out of NAME. (There are always
4452 10 bytes written to BUFFER.) */
4453
4454 static size_t
4455 utf8_to_ucn (unsigned char *buffer, const unsigned char *name)
4456 {
4457 int j;
4458 int ucn_len = 0;
4459 int ucn_len_c;
4460 unsigned t;
4461 unsigned long utf32;
4462
4463 /* Compute the length of the UTF-8 sequence. */
4464 for (t = *name; t & 0x80; t <<= 1)
4465 ucn_len++;
4466
4467 utf32 = *name & (0x7F >> ucn_len);
4468 for (ucn_len_c = 1; ucn_len_c < ucn_len; ucn_len_c++)
4469 {
4470 utf32 = (utf32 << 6) | (*++name & 0x3F);
4471
4472 /* Ill-formed UTF-8. */
4473 if ((*name & ~0x3F) != 0x80)
4474 abort ();
4475 }
4476
4477 *buffer++ = '\\';
4478 *buffer++ = 'U';
4479 for (j = 7; j >= 0; j--)
4480 *buffer++ = "0123456789abcdef"[(utf32 >> (4 * j)) & 0xF];
4481 return ucn_len;
4482 }
4483
4484 /* Given a token TYPE corresponding to a digraph, return a pointer to
4485 the spelling of the digraph. */
4486 static const unsigned char *
4487 cpp_digraph2name (enum cpp_ttype type)
4488 {
4489 return digraph_spellings[(int) type - (int) CPP_FIRST_DIGRAPH];
4490 }
4491
4492 /* Write the spelling of an identifier IDENT, using UCNs, to BUFFER.
4493 The buffer must already contain enough space to hold the
4494 token's spelling. Returns a pointer to the character after the
4495 last character written. */
4496 unsigned char *
4497 _cpp_spell_ident_ucns (unsigned char *buffer, cpp_hashnode *ident)
4498 {
4499 size_t i;
4500 const unsigned char *name = NODE_NAME (ident);
4501
4502 for (i = 0; i < NODE_LEN (ident); i++)
4503 if (name[i] & ~0x7F)
4504 {
4505 i += utf8_to_ucn (buffer, name + i) - 1;
4506 buffer += 10;
4507 }
4508 else
4509 *buffer++ = name[i];
4510
4511 return buffer;
4512 }
4513
4514 /* Write the spelling of a token TOKEN to BUFFER. The buffer must
4515 already contain enough space to hold the token's spelling.
4516 Returns a pointer to the character after the last character written.
4517 FORSTRING is true if this is to be the spelling after translation
4518 phase 1 (with the original spelling of extended identifiers), false
4519 if extended identifiers should always be written using UCNs (there is
4520 no option for always writing them in the internal UTF-8 form).
4521 FIXME: Would be nice if we didn't need the PFILE argument. */
4522 unsigned char *
4523 cpp_spell_token (cpp_reader *pfile, const cpp_token *token,
4524 unsigned char *buffer, bool forstring)
4525 {
4526 switch (TOKEN_SPELL (token))
4527 {
4528 case SPELL_OPERATOR:
4529 {
4530 const unsigned char *spelling;
4531 unsigned char c;
4532
4533 if (token->flags & DIGRAPH)
4534 spelling = cpp_digraph2name (token->type);
4535 else if (token->flags & NAMED_OP)
4536 goto spell_ident;
4537 else
4538 spelling = TOKEN_NAME (token);
4539
4540 while ((c = *spelling++) != '\0')
4541 *buffer++ = c;
4542 }
4543 break;
4544
4545 spell_ident:
4546 case SPELL_IDENT:
4547 if (forstring)
4548 {
4549 memcpy (buffer, NODE_NAME (token->val.node.spelling),
4550 NODE_LEN (token->val.node.spelling));
4551 buffer += NODE_LEN (token->val.node.spelling);
4552 }
4553 else
4554 buffer = _cpp_spell_ident_ucns (buffer, token->val.node.node);
4555 break;
4556
4557 case SPELL_LITERAL:
4558 memcpy (buffer, token->val.str.text, token->val.str.len);
4559 buffer += token->val.str.len;
4560 break;
4561
4562 case SPELL_NONE:
4563 cpp_error (pfile, CPP_DL_ICE,
4564 "unspellable token %s", TOKEN_NAME (token));
4565 break;
4566 }
4567
4568 return buffer;
4569 }
4570
4571 /* Returns TOKEN spelt as a null-terminated string. The string is
4572 freed when the reader is destroyed. Useful for diagnostics. */
4573 unsigned char *
4574 cpp_token_as_text (cpp_reader *pfile, const cpp_token *token)
4575 {
4576 unsigned int len = cpp_token_len (token) + 1;
4577 unsigned char *start = _cpp_unaligned_alloc (pfile, len), *end;
4578
4579 end = cpp_spell_token (pfile, token, start, false);
4580 end[0] = '\0';
4581
4582 return start;
4583 }
4584
4585 /* Returns a pointer to a string which spells the token defined by
4586 TYPE and FLAGS. Used by C front ends, which really should move to
4587 using cpp_token_as_text. */
4588 const char *
4589 cpp_type2name (enum cpp_ttype type, unsigned char flags)
4590 {
4591 if (flags & DIGRAPH)
4592 return (const char *) cpp_digraph2name (type);
4593 else if (flags & NAMED_OP)
4594 return cpp_named_operator2name (type);
4595
4596 return (const char *) token_spellings[type].name;
4597 }
4598
4599 /* Writes the spelling of token to FP, without any preceding space.
4600 Separated from cpp_spell_token for efficiency - to avoid stdio
4601 double-buffering. */
4602 void
4603 cpp_output_token (const cpp_token *token, FILE *fp)
4604 {
4605 switch (TOKEN_SPELL (token))
4606 {
4607 case SPELL_OPERATOR:
4608 {
4609 const unsigned char *spelling;
4610 int c;
4611
4612 if (token->flags & DIGRAPH)
4613 spelling = cpp_digraph2name (token->type);
4614 else if (token->flags & NAMED_OP)
4615 goto spell_ident;
4616 else
4617 spelling = TOKEN_NAME (token);
4618
4619 c = *spelling;
4620 do
4621 putc (c, fp);
4622 while ((c = *++spelling) != '\0');
4623 }
4624 break;
4625
4626 spell_ident:
4627 case SPELL_IDENT:
4628 {
4629 size_t i;
4630 const unsigned char * name = NODE_NAME (token->val.node.node);
4631 unsigned len = NODE_LEN (token->val.node.node);
4632
4633 for (i = 0; i < len; i++)
4634 if (name[i] & ~0x7F)
4635 {
4636 unsigned char buffer[10];
4637 i += utf8_to_ucn (buffer, name + i) - 1;
4638 fwrite (buffer, 1, 10, fp);
4639 }
4640 else if (name[i] == ' ' && i == len - 1)
4641 /* Omit terminal space in "export ". */;
4642 else
4643 fputc (NODE_NAME (token->val.node.node)[i], fp);
4644 }
4645 break;
4646
4647 case SPELL_LITERAL:
4648 if (token->type == CPP_HEADER_NAME)
4649 fputc ('"', fp);
4650 fwrite (token->val.str.text, 1, token->val.str.len, fp);
4651 if (token->type == CPP_HEADER_NAME)
4652 fputc ('"', fp);
4653 break;
4654
4655 case SPELL_NONE:
4656 /* An error, most probably. */
4657 break;
4658 }
4659 }
4660
4661 /* Compare two tokens. */
4662 int
4663 _cpp_equiv_tokens (const cpp_token *a, const cpp_token *b)
4664 {
4665 if (a->type == b->type && a->flags == b->flags)
4666 switch (TOKEN_SPELL (a))
4667 {
4668 default: /* Keep compiler happy. */
4669 case SPELL_OPERATOR:
4670 /* token_no is used to track where multiple consecutive ##
4671 tokens were originally located. */
4672 return (a->type != CPP_PASTE || a->val.token_no == b->val.token_no);
4673 case SPELL_NONE:
4674 return (a->type != CPP_MACRO_ARG
4675 || (a->val.macro_arg.arg_no == b->val.macro_arg.arg_no
4676 && a->val.macro_arg.spelling == b->val.macro_arg.spelling));
4677 case SPELL_IDENT:
4678 return (a->val.node.node == b->val.node.node
4679 && a->val.node.spelling == b->val.node.spelling);
4680 case SPELL_LITERAL:
4681 return (a->val.str.len == b->val.str.len
4682 && !memcmp (a->val.str.text, b->val.str.text,
4683 a->val.str.len));
4684 }
4685
4686 return 0;
4687 }
4688
4689 /* Returns nonzero if a space should be inserted to avoid an
4690 accidental token paste for output. For simplicity, it is
4691 conservative, and occasionally advises a space where one is not
4692 needed, e.g. "." and ".2". */
4693 int
4694 cpp_avoid_paste (cpp_reader *pfile, const cpp_token *token1,
4695 const cpp_token *token2)
4696 {
4697 enum cpp_ttype a = token1->type, b = token2->type;
4698 cppchar_t c;
4699
4700 if (token1->flags & NAMED_OP)
4701 a = CPP_NAME;
4702 if (token2->flags & NAMED_OP)
4703 b = CPP_NAME;
4704
4705 c = EOF;
4706 if (token2->flags & DIGRAPH)
4707 c = digraph_spellings[(int) b - (int) CPP_FIRST_DIGRAPH][0];
4708 else if (token_spellings[b].category == SPELL_OPERATOR)
4709 c = token_spellings[b].name[0];
4710
4711 /* Quickly get everything that can paste with an '='. */
4712 if ((int) a <= (int) CPP_LAST_EQ && c == '=')
4713 return 1;
4714
4715 switch (a)
4716 {
4717 case CPP_GREATER: return c == '>';
4718 case CPP_LESS: return c == '<' || c == '%' || c == ':';
4719 case CPP_PLUS: return c == '+';
4720 case CPP_MINUS: return c == '-' || c == '>';
4721 case CPP_DIV: return c == '/' || c == '*'; /* Comments. */
4722 case CPP_MOD: return c == ':' || c == '>';
4723 case CPP_AND: return c == '&';
4724 case CPP_OR: return c == '|';
4725 case CPP_COLON: return c == ':' || c == '>';
4726 case CPP_DEREF: return c == '*';
4727 case CPP_DOT: return c == '.' || c == '%' || b == CPP_NUMBER;
4728 case CPP_HASH: return c == '#' || c == '%'; /* Digraph form. */
4729 case CPP_PRAGMA:
4730 case CPP_NAME: return ((b == CPP_NUMBER
4731 && name_p (pfile, &token2->val.str))
4732 || b == CPP_NAME
4733 || b == CPP_CHAR || b == CPP_STRING); /* L */
4734 case CPP_NUMBER: return (b == CPP_NUMBER || b == CPP_NAME
4735 || b == CPP_CHAR
4736 || c == '.' || c == '+' || c == '-');
4737 /* UCNs */
4738 case CPP_OTHER: return ((token1->val.str.text[0] == '\\'
4739 && b == CPP_NAME)
4740 || (CPP_OPTION (pfile, objc)
4741 && token1->val.str.text[0] == '@'
4742 && (b == CPP_NAME || b == CPP_STRING)));
4743 case CPP_LESS_EQ: return c == '>';
4744 case CPP_STRING:
4745 case CPP_WSTRING:
4746 case CPP_UTF8STRING:
4747 case CPP_STRING16:
4748 case CPP_STRING32: return (CPP_OPTION (pfile, user_literals)
4749 && (b == CPP_NAME
4750 || (TOKEN_SPELL (token2) == SPELL_LITERAL
4751 && ISIDST (token2->val.str.text[0]))));
4752
4753 default: break;
4754 }
4755
4756 return 0;
4757 }
4758
4759 /* Output all the remaining tokens on the current line, and a newline
4760 character, to FP. Leading whitespace is removed. If there are
4761 macros, special token padding is not performed. */
4762 void
4763 cpp_output_line (cpp_reader *pfile, FILE *fp)
4764 {
4765 const cpp_token *token;
4766
4767 token = cpp_get_token (pfile);
4768 while (token->type != CPP_EOF)
4769 {
4770 cpp_output_token (token, fp);
4771 token = cpp_get_token (pfile);
4772 if (token->flags & PREV_WHITE)
4773 putc (' ', fp);
4774 }
4775
4776 putc ('\n', fp);
4777 }
4778
4779 /* Return a string representation of all the remaining tokens on the
4780 current line. The result is allocated using xmalloc and must be
4781 freed by the caller. */
4782 unsigned char *
4783 cpp_output_line_to_string (cpp_reader *pfile, const unsigned char *dir_name)
4784 {
4785 const cpp_token *token;
4786 unsigned int out = dir_name ? ustrlen (dir_name) : 0;
4787 unsigned int alloced = 120 + out;
4788 unsigned char *result = (unsigned char *) xmalloc (alloced);
4789
4790 /* If DIR_NAME is empty, there are no initial contents. */
4791 if (dir_name)
4792 {
4793 sprintf ((char *) result, "#%s ", dir_name);
4794 out += 2;
4795 }
4796
4797 token = cpp_get_token (pfile);
4798 while (token->type != CPP_EOF)
4799 {
4800 unsigned char *last;
4801 /* Include room for a possible space and the terminating nul. */
4802 unsigned int len = cpp_token_len (token) + 2;
4803
4804 if (out + len > alloced)
4805 {
4806 alloced *= 2;
4807 if (out + len > alloced)
4808 alloced = out + len;
4809 result = (unsigned char *) xrealloc (result, alloced);
4810 }
4811
4812 last = cpp_spell_token (pfile, token, &result[out], 0);
4813 out = last - result;
4814
4815 token = cpp_get_token (pfile);
4816 if (token->flags & PREV_WHITE)
4817 result[out++] = ' ';
4818 }
4819
4820 result[out] = '\0';
4821 return result;
4822 }
4823
4824 /* Memory buffers. Changing these three constants can have a dramatic
4825 effect on performance. The values here are reasonable defaults,
4826 but might be tuned. If you adjust them, be sure to test across a
4827 range of uses of cpplib, including heavy nested function-like macro
4828 expansion. Also check the change in peak memory usage (NJAMD is a
4829 good tool for this). */
4830 #define MIN_BUFF_SIZE 8000
4831 #define BUFF_SIZE_UPPER_BOUND(MIN_SIZE) (MIN_BUFF_SIZE + (MIN_SIZE) * 3 / 2)
4832 #define EXTENDED_BUFF_SIZE(BUFF, MIN_EXTRA) \
4833 (MIN_EXTRA + ((BUFF)->limit - (BUFF)->cur) * 2)
4834
4835 #if MIN_BUFF_SIZE > BUFF_SIZE_UPPER_BOUND (0)
4836 #error BUFF_SIZE_UPPER_BOUND must be at least as large as MIN_BUFF_SIZE!
4837 #endif
4838
4839 /* Create a new allocation buffer. Place the control block at the end
4840 of the buffer, so that buffer overflows will cause immediate chaos. */
4841 static _cpp_buff *
4842 new_buff (size_t len)
4843 {
4844 _cpp_buff *result;
4845 unsigned char *base;
4846
4847 if (len < MIN_BUFF_SIZE)
4848 len = MIN_BUFF_SIZE;
4849 len = CPP_ALIGN (len);
4850
4851 #ifdef ENABLE_VALGRIND_WORKAROUNDS
4852 /* Valgrind warns about uses of interior pointers, so put _cpp_buff
4853 struct first. */
4854 size_t slen = CPP_ALIGN2 (sizeof (_cpp_buff), 2 * DEFAULT_ALIGNMENT);
4855 base = XNEWVEC (unsigned char, len + slen);
4856 result = (_cpp_buff *) base;
4857 base += slen;
4858 #else
4859 base = XNEWVEC (unsigned char, len + sizeof (_cpp_buff));
4860 result = (_cpp_buff *) (base + len);
4861 #endif
4862 result->base = base;
4863 result->cur = base;
4864 result->limit = base + len;
4865 result->next = NULL;
4866 return result;
4867 }
4868
4869 /* Place a chain of unwanted allocation buffers on the free list. */
4870 void
4871 _cpp_release_buff (cpp_reader *pfile, _cpp_buff *buff)
4872 {
4873 _cpp_buff *end = buff;
4874
4875 while (end->next)
4876 end = end->next;
4877 end->next = pfile->free_buffs;
4878 pfile->free_buffs = buff;
4879 }
4880
4881 /* Return a free buffer of size at least MIN_SIZE. */
4882 _cpp_buff *
4883 _cpp_get_buff (cpp_reader *pfile, size_t min_size)
4884 {
4885 _cpp_buff *result, **p;
4886
4887 for (p = &pfile->free_buffs;; p = &(*p)->next)
4888 {
4889 size_t size;
4890
4891 if (*p == NULL)
4892 return new_buff (min_size);
4893 result = *p;
4894 size = result->limit - result->base;
4895 /* Return a buffer that's big enough, but don't waste one that's
4896 way too big. */
4897 if (size >= min_size && size <= BUFF_SIZE_UPPER_BOUND (min_size))
4898 break;
4899 }
4900
4901 *p = result->next;
4902 result->next = NULL;
4903 result->cur = result->base;
4904 return result;
4905 }
4906
4907 /* Creates a new buffer with enough space to hold the uncommitted
4908 remaining bytes of BUFF, and at least MIN_EXTRA more bytes. Copies
4909 the excess bytes to the new buffer. Chains the new buffer after
4910 BUFF, and returns the new buffer. */
4911 _cpp_buff *
4912 _cpp_append_extend_buff (cpp_reader *pfile, _cpp_buff *buff, size_t min_extra)
4913 {
4914 size_t size = EXTENDED_BUFF_SIZE (buff, min_extra);
4915 _cpp_buff *new_buff = _cpp_get_buff (pfile, size);
4916
4917 buff->next = new_buff;
4918 memcpy (new_buff->base, buff->cur, BUFF_ROOM (buff));
4919 return new_buff;
4920 }
4921
4922 /* Creates a new buffer with enough space to hold the uncommitted
4923 remaining bytes of the buffer pointed to by BUFF, and at least
4924 MIN_EXTRA more bytes. Copies the excess bytes to the new buffer.
4925 Chains the new buffer before the buffer pointed to by BUFF, and
4926 updates the pointer to point to the new buffer. */
4927 void
4928 _cpp_extend_buff (cpp_reader *pfile, _cpp_buff **pbuff, size_t min_extra)
4929 {
4930 _cpp_buff *new_buff, *old_buff = *pbuff;
4931 size_t size = EXTENDED_BUFF_SIZE (old_buff, min_extra);
4932
4933 new_buff = _cpp_get_buff (pfile, size);
4934 memcpy (new_buff->base, old_buff->cur, BUFF_ROOM (old_buff));
4935 new_buff->next = old_buff;
4936 *pbuff = new_buff;
4937 }
4938
4939 /* Free a chain of buffers starting at BUFF. */
4940 void
4941 _cpp_free_buff (_cpp_buff *buff)
4942 {
4943 _cpp_buff *next;
4944
4945 for (; buff; buff = next)
4946 {
4947 next = buff->next;
4948 #ifdef ENABLE_VALGRIND_WORKAROUNDS
4949 free (buff);
4950 #else
4951 free (buff->base);
4952 #endif
4953 }
4954 }
4955
4956 /* Allocate permanent, unaligned storage of length LEN. */
4957 unsigned char *
4958 _cpp_unaligned_alloc (cpp_reader *pfile, size_t len)
4959 {
4960 _cpp_buff *buff = pfile->u_buff;
4961 unsigned char *result = buff->cur;
4962
4963 if (len > (size_t) (buff->limit - result))
4964 {
4965 buff = _cpp_get_buff (pfile, len);
4966 buff->next = pfile->u_buff;
4967 pfile->u_buff = buff;
4968 result = buff->cur;
4969 }
4970
4971 buff->cur = result + len;
4972 return result;
4973 }
4974
4975 /* Allocate permanent, unaligned storage of length LEN from a_buff.
4976 That buffer is used for growing allocations when saving macro
4977 replacement lists in a #define, and when parsing an answer to an
4978 assertion in #assert, #unassert or #if (and therefore possibly
4979 whilst expanding macros). It therefore must not be used by any
4980 code that they might call: specifically the lexer and the guts of
4981 the macro expander.
4982
4983 All existing other uses clearly fit this restriction: storing
4984 registered pragmas during initialization. */
4985 unsigned char *
4986 _cpp_aligned_alloc (cpp_reader *pfile, size_t len)
4987 {
4988 _cpp_buff *buff = pfile->a_buff;
4989 unsigned char *result = buff->cur;
4990
4991 if (len > (size_t) (buff->limit - result))
4992 {
4993 buff = _cpp_get_buff (pfile, len);
4994 buff->next = pfile->a_buff;
4995 pfile->a_buff = buff;
4996 result = buff->cur;
4997 }
4998
4999 buff->cur = result + len;
5000 return result;
5001 }
5002
5003 /* Commit or allocate storage from a buffer. */
5004
5005 void *
5006 _cpp_commit_buff (cpp_reader *pfile, size_t size)
5007 {
5008 const auto buff = pfile->a_buff;
5009 void *ptr = BUFF_FRONT (buff);
5010
5011 if (pfile->hash_table->alloc_subobject)
5012 {
5013 void *copy = pfile->hash_table->alloc_subobject (size);
5014 memcpy (copy, ptr, size);
5015 ptr = copy;
5016 }
5017 else
5018 {
5019 BUFF_FRONT (buff) += size;
5020 /* Make sure the remaining space is maximally aligned for whatever this
5021 buffer holds next. */
5022 BUFF_FRONT (buff) += BUFF_ROOM (buff) % DEFAULT_ALIGNMENT;
5023 }
5024
5025 return ptr;
5026 }
5027
5028 /* Say which field of TOK is in use. */
5029
5030 enum cpp_token_fld_kind
5031 cpp_token_val_index (const cpp_token *tok)
5032 {
5033 switch (TOKEN_SPELL (tok))
5034 {
5035 case SPELL_IDENT:
5036 return CPP_TOKEN_FLD_NODE;
5037 case SPELL_LITERAL:
5038 return CPP_TOKEN_FLD_STR;
5039 case SPELL_OPERATOR:
5040 /* Operands which were originally spelled as ident keep around
5041 the node for the exact spelling. */
5042 if (tok->flags & NAMED_OP)
5043 return CPP_TOKEN_FLD_NODE;
5044 else if (tok->type == CPP_PASTE)
5045 return CPP_TOKEN_FLD_TOKEN_NO;
5046 else
5047 return CPP_TOKEN_FLD_NONE;
5048 case SPELL_NONE:
5049 if (tok->type == CPP_MACRO_ARG)
5050 return CPP_TOKEN_FLD_ARG_NO;
5051 else if (tok->type == CPP_PADDING)
5052 return CPP_TOKEN_FLD_SOURCE;
5053 else if (tok->type == CPP_PRAGMA)
5054 return CPP_TOKEN_FLD_PRAGMA;
5055 /* fall through */
5056 default:
5057 return CPP_TOKEN_FLD_NONE;
5058 }
5059 }
5060
5061 /* All tokens lexed in R after calling this function will be forced to
5062 have their location_t to be P, until
5063 cpp_stop_forcing_token_locations is called for R. */
5064
5065 void
5066 cpp_force_token_locations (cpp_reader *r, location_t loc)
5067 {
5068 r->forced_token_location = loc;
5069 }
5070
5071 /* Go back to assigning locations naturally for lexed tokens. */
5072
5073 void
5074 cpp_stop_forcing_token_locations (cpp_reader *r)
5075 {
5076 r->forced_token_location = 0;
5077 }
5078
5079 /* We're looking at \, if it's escaping EOL, look past it. If at
5080 LIMIT, don't advance. */
5081
5082 static const unsigned char *
5083 do_peek_backslash (const unsigned char *peek, const unsigned char *limit)
5084 {
5085 const unsigned char *probe = peek;
5086
5087 if (__builtin_expect (peek[1] == '\n', true))
5088 {
5089 eol:
5090 probe += 2;
5091 if (__builtin_expect (probe < limit, true))
5092 {
5093 peek = probe;
5094 if (*peek == '\\')
5095 /* The user might be perverse. */
5096 return do_peek_backslash (peek, limit);
5097 }
5098 }
5099 else if (__builtin_expect (peek[1] == '\r', false))
5100 {
5101 if (probe[2] == '\n')
5102 probe++;
5103 goto eol;
5104 }
5105
5106 return peek;
5107 }
5108
5109 static const unsigned char *
5110 do_peek_next (const unsigned char *peek, const unsigned char *limit)
5111 {
5112 if (__builtin_expect (*peek == '\\', false))
5113 peek = do_peek_backslash (peek, limit);
5114 return peek;
5115 }
5116
5117 static const unsigned char *
5118 do_peek_prev (const unsigned char *peek, const unsigned char *bound)
5119 {
5120 if (peek == bound)
5121 return NULL;
5122
5123 unsigned char c = *--peek;
5124 if (__builtin_expect (c == '\n', false)
5125 || __builtin_expect (c == '\r', false))
5126 {
5127 if (peek == bound)
5128 return peek;
5129 int ix = -1;
5130 if (c == '\n' && peek[ix] == '\r')
5131 {
5132 if (peek + ix == bound)
5133 return peek;
5134 ix--;
5135 }
5136
5137 if (peek[ix] == '\\')
5138 return do_peek_prev (peek + ix, bound);
5139
5140 return peek;
5141 }
5142 else
5143 return peek;
5144 }
5145
5146 /* If PEEK[-1] is identifier MATCH, scan past it and trailing white
5147 space. Otherwise return NULL. */
5148
5149 static const unsigned char *
5150 do_peek_ident (const char *match, const unsigned char *peek,
5151 const unsigned char *limit)
5152 {
5153 for (; *++match; peek++)
5154 if (*peek != *match)
5155 {
5156 peek = do_peek_next (peek, limit);
5157 if (*peek != *match)
5158 return NULL;
5159 }
5160
5161 /* Must now not be looking at an identifier char. */
5162 peek = do_peek_next (peek, limit);
5163 if (ISIDNUM (*peek))
5164 return NULL;
5165
5166 /* Skip control-line whitespace. */
5167 ws:
5168 while (*peek == ' ' || *peek == '\t')
5169 peek++;
5170 if (__builtin_expect (*peek == '\\', false))
5171 {
5172 peek = do_peek_backslash (peek, limit);
5173 if (*peek != '\\')
5174 goto ws;
5175 }
5176
5177 return peek;
5178 }
5179
5180 /* Are we looking at a module control line starting as PEEK - 1? */
5181
5182 static bool
5183 do_peek_module (cpp_reader *pfile, unsigned char c,
5184 const unsigned char *peek, const unsigned char *limit)
5185 {
5186 bool import = false;
5187
5188 if (__builtin_expect (c == 'e', false))
5189 {
5190 if (!((peek[0] == 'x' || peek[0] == '\\')
5191 && (peek = do_peek_ident ("export", peek, limit))))
5192 return false;
5193
5194 /* export, peek for import or module. No need to peek __import
5195 here. */
5196 if (peek[0] == 'i')
5197 {
5198 if (!((peek[1] == 'm' || peek[1] == '\\')
5199 && (peek = do_peek_ident ("import", peek + 1, limit))))
5200 return false;
5201 import = true;
5202 }
5203 else if (peek[0] == 'm')
5204 {
5205 if (!((peek[1] == 'o' || peek[1] == '\\')
5206 && (peek = do_peek_ident ("module", peek + 1, limit))))
5207 return false;
5208 }
5209 else
5210 return false;
5211 }
5212 else if (__builtin_expect (c == 'i', false))
5213 {
5214 if (!((peek[0] == 'm' || peek[0] == '\\')
5215 && (peek = do_peek_ident ("import", peek, limit))))
5216 return false;
5217 import = true;
5218 }
5219 else if (__builtin_expect (c == '_', false))
5220 {
5221 /* Needed for translated includes. */
5222 if (!((peek[0] == '_' || peek[0] == '\\')
5223 && (peek = do_peek_ident ("__import", peek, limit))))
5224 return false;
5225 import = true;
5226 }
5227 else if (__builtin_expect (c == 'm', false))
5228 {
5229 if (!((peek[0] == 'o' || peek[0] == '\\')
5230 && (peek = do_peek_ident ("module", peek, limit))))
5231 return false;
5232 }
5233 else
5234 return false;
5235
5236 /* Peek the next character to see if it's good enough. We'll be at
5237 the first non-whitespace char, including skipping an escaped
5238 newline. */
5239 /* ... import followed by identifier, ':', '<' or header-name
5240 preprocessing tokens, or module followed by identifier, ':' or
5241 ';' preprocessing tokens. */
5242 unsigned char p = *peek++;
5243
5244 /* A character literal is ... single quotes, ... optionally preceded
5245 by u8, u, U, or L */
5246 /* A string-literal is a ... double quotes, optionally prefixed by
5247 R, u8, u8R, u, uR, U, UR, L, or LR */
5248 if (p == 'u')
5249 {
5250 peek = do_peek_next (peek, limit);
5251 if (*peek == '8')
5252 {
5253 peek++;
5254 goto peek_u8;
5255 }
5256 goto peek_u;
5257 }
5258 else if (p == 'U' || p == 'L')
5259 {
5260 peek_u8:
5261 peek = do_peek_next (peek, limit);
5262 peek_u:
5263 if (*peek == '\"' || *peek == '\'')
5264 return false;
5265
5266 if (*peek == 'R')
5267 goto peek_R;
5268 /* Identifier. Ok. */
5269 }
5270 else if (p == 'R')
5271 {
5272 peek_R:
5273 if (CPP_OPTION (pfile, rliterals))
5274 {
5275 peek = do_peek_next (peek, limit);
5276 if (*peek == '\"')
5277 return false;
5278 }
5279 /* Identifier. Ok. */
5280 }
5281 else if ('Z' - 'A' == 25
5282 ? ((p >= 'A' && p <= 'Z') || (p >= 'a' && p <= 'z') || p == '_')
5283 : ISIDST (p))
5284 {
5285 /* Identifier. Ok. */
5286 }
5287 else if (p == '<')
5288 {
5289 /* Maybe angle header, ok for import. Reject
5290 '<=', '<<' digraph:'<:'. */
5291 if (!import)
5292 return false;
5293 peek = do_peek_next (peek, limit);
5294 if (*peek == '=' || *peek == '<'
5295 || (*peek == ':' && CPP_OPTION (pfile, digraphs)))
5296 return false;
5297 }
5298 else if (p == ';')
5299 {
5300 /* SEMICOLON, ok for module. */
5301 if (import)
5302 return false;
5303 }
5304 else if (p == '"')
5305 {
5306 /* STRING, ok for import. */
5307 if (!import)
5308 return false;
5309 }
5310 else if (p == ':')
5311 {
5312 /* Maybe COLON, ok. Reject '::', digraph:':>'. */
5313 peek = do_peek_next (peek, limit);
5314 if (*peek == ':' || (*peek == '>' && CPP_OPTION (pfile, digraphs)))
5315 return false;
5316 }
5317 else
5318 /* FIXME: Detect a unicode character, excluding those not
5319 permitted as the initial character. [lex.name]/1. I presume
5320 we need to check the \[uU] spellings, and directly using
5321 Unicode in say UTF8 form? Or perhaps we do the phase-1
5322 conversion of UTF8 to universal-character-names? */
5323 return false;
5324
5325 return true;
5326 }
5327
5328 /* Directives-only scanning. Somewhat more relaxed than correct
5329 parsing -- some ill-formed programs will not be rejected. */
5330
5331 void
5332 cpp_directive_only_process (cpp_reader *pfile,
5333 void *data,
5334 void (*cb) (cpp_reader *, CPP_DO_task, void *, ...))
5335 {
5336 bool module_p = CPP_OPTION (pfile, module_directives);
5337
5338 do
5339 {
5340 restart:
5341 /* Buffer initialization, but no line cleaning. */
5342 cpp_buffer *buffer = pfile->buffer;
5343 buffer->cur_note = buffer->notes_used = 0;
5344 buffer->cur = buffer->line_base = buffer->next_line;
5345 buffer->need_line = false;
5346 /* Files always end in a newline or carriage return. We rely on this for
5347 character peeking safety. */
5348 gcc_assert (buffer->rlimit[0] == '\n' || buffer->rlimit[0] == '\r');
5349
5350 const unsigned char *base = buffer->cur;
5351 unsigned line_count = 0;
5352 const unsigned char *line_start = base;
5353
5354 bool bol = true;
5355 bool raw = false;
5356
5357 const unsigned char *lwm = base;
5358 for (const unsigned char *pos = base, *limit = buffer->rlimit;
5359 pos < limit;)
5360 {
5361 unsigned char c = *pos++;
5362 /* This matches the switch in _cpp_lex_direct. */
5363 switch (c)
5364 {
5365 case ' ': case '\t': case '\f': case '\v':
5366 /* Whitespace, do nothing. */
5367 break;
5368
5369 case '\r': /* MAC line ending, or Windows \r\n */
5370 if (*pos == '\n')
5371 pos++;
5372 /* FALLTHROUGH */
5373
5374 case '\n':
5375 bol = true;
5376
5377 next_line:
5378 CPP_INCREMENT_LINE (pfile, 0);
5379 line_count++;
5380 line_start = pos;
5381 break;
5382
5383 case '\\':
5384 /* <backslash><newline> is removed, and doesn't undo any
5385 preceeding escape or whatnot. */
5386 if (*pos == '\n')
5387 {
5388 pos++;
5389 goto next_line;
5390 }
5391 else if (*pos == '\r')
5392 {
5393 if (pos[1] == '\n')
5394 pos++;
5395 pos++;
5396 goto next_line;
5397 }
5398 goto dflt;
5399
5400 case '#':
5401 if (bol)
5402 {
5403 /* Line directive. */
5404 if (pos - 1 > base && !pfile->state.skipping)
5405 cb (pfile, CPP_DO_print, data,
5406 line_count, base, pos - 1 - base);
5407
5408 /* Prep things for directive handling. */
5409 buffer->next_line = pos;
5410 buffer->need_line = true;
5411 bool ok = _cpp_get_fresh_line (pfile);
5412 gcc_checking_assert (ok);
5413
5414 /* Ensure proper column numbering for generated
5415 error messages. */
5416 buffer->line_base -= pos - line_start;
5417
5418 if (_cpp_handle_directive (pfile, line_start + 1 != pos) == 2)
5419 {
5420 if (pfile->directive_result.type != CPP_PADDING)
5421 cb (pfile, CPP_DO_token, data,
5422 &pfile->directive_result, pfile->directive_result.src_loc);
5423 if (pfile->context->prev)
5424 {
5425 gcc_assert (pfile->context->tokens_kind == TOKENS_KIND_DIRECT);
5426 for (const cpp_token *tok = FIRST (pfile->context).token;
5427 tok != LAST (pfile->context).token; ++tok)
5428 cb (pfile, CPP_DO_token, data, tok, tok->src_loc);
5429 _cpp_pop_context (pfile);
5430 }
5431 }
5432
5433 /* Sanitize the line settings. Duplicate #include's can
5434 mess things up. */
5435 // FIXME: Necessary?
5436 pfile->line_table->highest_location
5437 = pfile->line_table->highest_line;
5438
5439 if (!pfile->state.skipping
5440 && pfile->buffer->next_line < pfile->buffer->rlimit)
5441 cb (pfile, CPP_DO_location, data,
5442 pfile->line_table->highest_line);
5443
5444 goto restart;
5445 }
5446 goto dflt;
5447
5448 case '/':
5449 {
5450 const unsigned char *peek = do_peek_next (pos, limit);
5451 if (!(*peek == '/' || *peek == '*'))
5452 goto dflt;
5453
5454 /* Line or block comment */
5455 bool is_block = *peek == '*';
5456 bool star = false;
5457 bool esc = false;
5458 location_t sloc
5459 = linemap_position_for_column (pfile->line_table,
5460 pos - line_start);
5461
5462 while (pos < limit)
5463 {
5464 char c = *pos++;
5465 switch (c)
5466 {
5467 case '\\':
5468 if (esc)
5469 {
5470 star = false;
5471 esc = false;
5472 }
5473 else
5474 esc = true;
5475 break;
5476
5477 case '\r':
5478 if (*pos == '\n')
5479 pos++;
5480 /* FALLTHROUGH */
5481
5482 case '\n':
5483 {
5484 CPP_INCREMENT_LINE (pfile, 0);
5485 line_count++;
5486 line_start = pos;
5487 if (!esc && !is_block)
5488 {
5489 bol = true;
5490 goto done_comment;
5491 }
5492 }
5493 if (!esc)
5494 star = false;
5495 esc = false;
5496 break;
5497
5498 case '*':
5499 if (pos > peek)
5500 star = is_block;
5501 esc = false;
5502 break;
5503
5504 case '/':
5505 if (star && !esc)
5506 goto done_comment;
5507 /* FALLTHROUGH */
5508
5509 default:
5510 star = false;
5511 esc = false;
5512 break;
5513 }
5514 }
5515 if (pos < limit || is_block)
5516 cpp_error_with_line (pfile, CPP_DL_ERROR, sloc, 0,
5517 "unterminated comment");
5518 done_comment:
5519 lwm = pos;
5520 break;
5521 }
5522
5523 case '\'':
5524 if (!CPP_OPTION (pfile, digit_separators))
5525 goto delimited_string;
5526
5527 /* Possibly a number punctuator. */
5528 if (!ISIDNUM (*do_peek_next (pos, limit)))
5529 goto delimited_string;
5530
5531 goto quote_peek;
5532
5533 case '\"':
5534 if (!CPP_OPTION (pfile, rliterals))
5535 goto delimited_string;
5536
5537 quote_peek:
5538 {
5539 /* For ' see if it's a number punctuator
5540 \.?<digit>(<digit>|<identifier-nondigit>
5541 |'<digit>|'<nondigit>|[eEpP]<sign>|\.)* */
5542 /* For " see if it's a raw string
5543 {U,L,u,u8}R. This includes CPP_NUMBER detection,
5544 because that could be 0e+R. */
5545 const unsigned char *peek = pos - 1;
5546 bool quote_first = c == '"';
5547 bool quote_eight = false;
5548 bool maybe_number_start = false;
5549 bool want_number = false;
5550
5551 while ((peek = do_peek_prev (peek, lwm)))
5552 {
5553 unsigned char p = *peek;
5554 if (quote_first)
5555 {
5556 if (!raw)
5557 {
5558 if (p != 'R')
5559 break;
5560 raw = true;
5561 continue;
5562 }
5563
5564 quote_first = false;
5565 if (p == 'L' || p == 'U' || p == 'u')
5566 ;
5567 else if (p == '8')
5568 quote_eight = true;
5569 else
5570 goto second_raw;
5571 }
5572 else if (quote_eight)
5573 {
5574 if (p != 'u')
5575 {
5576 raw = false;
5577 break;
5578 }
5579 quote_eight = false;
5580 }
5581 else if (c == '"')
5582 {
5583 second_raw:;
5584 if (!want_number && ISIDNUM (p))
5585 {
5586 raw = false;
5587 break;
5588 }
5589 }
5590
5591 if (ISDIGIT (p))
5592 maybe_number_start = true;
5593 else if (p == '.')
5594 want_number = true;
5595 else if (ISIDNUM (p))
5596 maybe_number_start = false;
5597 else if (p == '+' || p == '-')
5598 {
5599 if (const unsigned char *peek_prev
5600 = do_peek_prev (peek, lwm))
5601 {
5602 p = *peek_prev;
5603 if (p == 'e' || p == 'E'
5604 || p == 'p' || p == 'P')
5605 {
5606 want_number = true;
5607 maybe_number_start = false;
5608 }
5609 else
5610 break;
5611 }
5612 else
5613 break;
5614 }
5615 else if (p == '\'' || p == '\"')
5616 {
5617 /* If this is lwm, this must be the end of a
5618 previous string. So this is a trailing
5619 literal type, (a) if those are allowed,
5620 and (b) maybe_start is false. Otherwise
5621 this must be a CPP_NUMBER because we've
5622 met another ', and we'd have checked that
5623 in its own right. */
5624 if (peek == lwm && CPP_OPTION (pfile, uliterals))
5625 {
5626 if (!maybe_number_start && !want_number)
5627 /* Must be a literal type. */
5628 raw = false;
5629 }
5630 else if (p == '\''
5631 && CPP_OPTION (pfile, digit_separators))
5632 maybe_number_start = true;
5633 break;
5634 }
5635 else if (c == '\'')
5636 break;
5637 else if (!quote_first && !quote_eight)
5638 break;
5639 }
5640
5641 if (maybe_number_start)
5642 {
5643 if (c == '\'')
5644 /* A CPP NUMBER. */
5645 goto dflt;
5646 raw = false;
5647 }
5648
5649 goto delimited_string;
5650 }
5651
5652 delimited_string:
5653 {
5654 /* (Possibly raw) string or char literal. */
5655 unsigned char end = c;
5656 int delim_len = -1;
5657 const unsigned char *delim = NULL;
5658 location_t sloc = linemap_position_for_column (pfile->line_table,
5659 pos - line_start);
5660 int esc = 0;
5661
5662 if (raw)
5663 {
5664 /* There can be no line breaks in the delimiter. */
5665 delim = pos;
5666 for (delim_len = 0; (c = *pos++) != '('; delim_len++)
5667 {
5668 if (delim_len == 16)
5669 {
5670 cpp_error_with_line (pfile, CPP_DL_ERROR,
5671 sloc, 0,
5672 "raw string delimiter"
5673 " longer than %d"
5674 " characters",
5675 delim_len);
5676 raw = false;
5677 pos = delim;
5678 break;
5679 }
5680 if (strchr (") \\\t\v\f\n", c))
5681 {
5682 cpp_error_with_line (pfile, CPP_DL_ERROR,
5683 sloc, 0,
5684 "invalid character '%c'"
5685 " in raw string"
5686 " delimiter", c);
5687 raw = false;
5688 pos = delim;
5689 break;
5690 }
5691 if (pos >= limit)
5692 goto bad_string;
5693 }
5694 }
5695
5696 while (pos < limit)
5697 {
5698 char c = *pos++;
5699 switch (c)
5700 {
5701 case '\\':
5702 if (!raw)
5703 esc++;
5704 break;
5705
5706 case '\r':
5707 if (*pos == '\n')
5708 pos++;
5709 /* FALLTHROUGH */
5710
5711 case '\n':
5712 {
5713 CPP_INCREMENT_LINE (pfile, 0);
5714 line_count++;
5715 line_start = pos;
5716 }
5717 if (esc)
5718 esc--;
5719 break;
5720
5721 case ')':
5722 if (raw
5723 && pos + delim_len + 1 < limit
5724 && pos[delim_len] == end
5725 && !memcmp (delim, pos, delim_len))
5726 {
5727 pos += delim_len + 1;
5728 raw = false;
5729 goto done_string;
5730 }
5731 break;
5732
5733 default:
5734 if (!raw && !(esc & 1) && c == end)
5735 goto done_string;
5736 esc = 0;
5737 break;
5738 }
5739 }
5740 bad_string:
5741 cpp_error_with_line (pfile, CPP_DL_ERROR, sloc, 0,
5742 "unterminated literal");
5743
5744 done_string:
5745 raw = false;
5746 lwm = pos - 1;
5747 }
5748 goto dflt;
5749
5750 case '_':
5751 case 'e':
5752 case 'i':
5753 case 'm':
5754 if (bol && module_p && !pfile->state.skipping
5755 && do_peek_module (pfile, c, pos, limit))
5756 {
5757 /* We've seen the start of a module control line.
5758 Start up the tokenizer. */
5759 pos--; /* Backup over the first character. */
5760
5761 /* Backup over whitespace to start of line. */
5762 while (pos > line_start
5763 && (pos[-1] == ' ' || pos[-1] == '\t'))
5764 pos--;
5765
5766 if (pos > base)
5767 cb (pfile, CPP_DO_print, data, line_count, base, pos - base);
5768
5769 /* Prep things for directive handling. */
5770 buffer->next_line = pos;
5771 buffer->need_line = true;
5772
5773 /* Now get tokens until the PRAGMA_EOL. */
5774 do
5775 {
5776 location_t spelling;
5777 const cpp_token *tok
5778 = cpp_get_token_with_location (pfile, &spelling);
5779
5780 gcc_assert (pfile->state.in_deferred_pragma
5781 || tok->type == CPP_PRAGMA_EOL);
5782 cb (pfile, CPP_DO_token, data, tok, spelling);
5783 }
5784 while (pfile->state.in_deferred_pragma);
5785
5786 if (pfile->buffer->next_line < pfile->buffer->rlimit)
5787 cb (pfile, CPP_DO_location, data,
5788 pfile->line_table->highest_line);
5789
5790 pfile->mi_valid = false;
5791 goto restart;
5792 }
5793 goto dflt;
5794
5795 default:
5796 dflt:
5797 bol = false;
5798 pfile->mi_valid = false;
5799 break;
5800 }
5801 }
5802
5803 if (buffer->rlimit > base && !pfile->state.skipping)
5804 {
5805 const unsigned char *limit = buffer->rlimit;
5806 /* If the file was not newline terminated, add rlimit, which is
5807 guaranteed to point to a newline, to the end of our range. */
5808 if (limit[-1] != '\n')
5809 {
5810 limit++;
5811 CPP_INCREMENT_LINE (pfile, 0);
5812 line_count++;
5813 }
5814 cb (pfile, CPP_DO_print, data, line_count, base, limit - base);
5815 }
5816
5817 _cpp_pop_buffer (pfile);
5818 }
5819 while (pfile->buffer);
5820 }