clang 23.0.0git
LiteralSupport.cpp
Go to the documentation of this file.
1//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the NumericLiteralParser, CharLiteralParser, and
10// StringLiteralParser interfaces.
11//
12//===----------------------------------------------------------------------===//
13
20#include "clang/Lex/Lexer.h"
22#include "clang/Lex/Token.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ScopeExit.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/Support/ConvertUTF.h"
29#include "llvm/Support/Error.h"
30#include "llvm/Support/ErrorHandling.h"
31#include "llvm/Support/Unicode.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <cstdint>
36#include <cstring>
37#include <string>
38
39using namespace clang;
40
42 switch (kind) {
43 default: llvm_unreachable("Unknown token type!");
44 case tok::char_constant:
45 case tok::string_literal:
46 case tok::utf8_char_constant:
47 case tok::utf8_string_literal:
48 return Target.getCharWidth();
49 case tok::wide_char_constant:
50 case tok::wide_string_literal:
51 return Target.getWCharWidth();
52 case tok::utf16_char_constant:
53 case tok::utf16_string_literal:
54 return Target.getChar16Width();
55 case tok::utf32_char_constant:
56 case tok::utf32_string_literal:
57 return Target.getChar32Width();
58 }
59}
60
62 switch (kind) {
63 default:
64 llvm_unreachable("Unknown token type!");
65 case tok::char_constant:
66 case tok::string_literal:
67 return 0;
68 case tok::utf8_char_constant:
69 case tok::utf8_string_literal:
70 return 2;
71 case tok::wide_char_constant:
72 case tok::wide_string_literal:
73 case tok::utf16_char_constant:
74 case tok::utf16_string_literal:
75 case tok::utf32_char_constant:
76 case tok::utf32_string_literal:
77 return 1;
78 }
79}
80
82 FullSourceLoc TokLoc,
83 const char *TokBegin,
84 const char *TokRangeBegin,
85 const char *TokRangeEnd) {
86 SourceLocation Begin =
87 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
88 TokLoc.getManager(), Features);
89 SourceLocation End =
90 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
91 TokLoc.getManager(), Features);
92 return CharSourceRange::getCharRange(Begin, End);
93}
94
95/// Produce a diagnostic highlighting some portion of a literal.
96///
97/// Emits the diagnostic \p DiagID, highlighting the range of characters from
98/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
99/// a substring of a spelling buffer for the token beginning at \p TokBegin.
101 const LangOptions &Features, FullSourceLoc TokLoc,
102 const char *TokBegin, const char *TokRangeBegin,
103 const char *TokRangeEnd, unsigned DiagID) {
104 SourceLocation Begin =
105 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
106 TokLoc.getManager(), Features);
107 return Diags->Report(Begin, DiagID) <<
108 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
109}
110
112 switch (Escape) {
113 case '\'':
114 case '"':
115 case '?':
116 case '\\':
117 case 'a':
118 case 'b':
119 case 'f':
120 case 'n':
121 case 'r':
122 case 't':
123 case 'v':
124 return true;
125 }
126 return false;
127}
128
129/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
130/// either a character or a string literal.
131static unsigned ProcessCharEscape(const char *ThisTokBegin,
132 const char *&ThisTokBuf,
133 const char *ThisTokEnd, bool &HadError,
134 FullSourceLoc Loc, unsigned CharWidth,
135 DiagnosticsEngine *Diags,
136 const LangOptions &Features,
137 StringLiteralEvalMethod EvalMethod) {
138 const char *EscapeBegin = ThisTokBuf;
139 bool Delimited = false;
140 bool EndDelimiterFound = false;
141
142 // Skip the '\' char.
143 ++ThisTokBuf;
144
145 // We know that this character can't be off the end of the buffer, because
146 // that would have been \", which would not have been the end of string.
147 unsigned ResultChar = *ThisTokBuf++;
148 char Escape = ResultChar;
149 switch (ResultChar) {
150 // These map to themselves.
151 case '\\': case '\'': case '"': case '?': break;
152
153 // These have fixed mappings.
154 case 'a':
155 // TODO: K&R: the meaning of '\\a' is different in traditional C
156 ResultChar = 7;
157 break;
158 case 'b':
159 ResultChar = 8;
160 break;
161 case 'e':
162 if (Diags)
163 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
164 diag::ext_nonstandard_escape) << "e";
165 ResultChar = 27;
166 break;
167 case 'E':
168 if (Diags)
169 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
170 diag::ext_nonstandard_escape) << "E";
171 ResultChar = 27;
172 break;
173 case 'f':
174 ResultChar = 12;
175 break;
176 case 'n':
177 ResultChar = 10;
178 break;
179 case 'r':
180 ResultChar = 13;
181 break;
182 case 't':
183 ResultChar = 9;
184 break;
185 case 'v':
186 ResultChar = 11;
187 break;
188 case 'x': { // Hex escape.
189 ResultChar = 0;
190 if (ThisTokBuf != ThisTokEnd && *ThisTokBuf == '{') {
191 Delimited = true;
192 ThisTokBuf++;
193 if (*ThisTokBuf == '}') {
194 HadError = true;
195 if (Diags)
196 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
197 diag::err_delimited_escape_empty);
198 }
199 } else if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
200 if (Diags)
201 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
202 diag::err_hex_escape_no_digits) << "x";
203 return ResultChar;
204 }
205
206 // Hex escapes are a maximal series of hex digits.
207 bool Overflow = false;
208 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
209 if (Delimited && *ThisTokBuf == '}') {
210 ThisTokBuf++;
211 EndDelimiterFound = true;
212 break;
213 }
214 int CharVal = llvm::hexDigitValue(*ThisTokBuf);
215 if (CharVal == -1) {
216 // Non delimited hex escape sequences stop at the first non-hex digit.
217 if (!Delimited)
218 break;
219 HadError = true;
220 if (Diags)
221 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
222 diag::err_delimited_escape_invalid)
223 << StringRef(ThisTokBuf, 1);
224 continue;
225 }
226 // About to shift out a digit?
227 if (ResultChar & 0xF0000000)
228 Overflow = true;
229 ResultChar <<= 4;
230 ResultChar |= CharVal;
231 }
232 // See if any bits will be truncated when evaluated as a character.
233 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
234 Overflow = true;
235 ResultChar &= ~0U >> (32-CharWidth);
236 }
237
238 // Check for overflow.
239 if (!HadError && Overflow) { // Too many digits to fit in
240 HadError = true;
241 if (Diags)
242 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
243 diag::err_escape_too_large)
244 << 0;
245 }
246 break;
247 }
248 case '0': case '1': case '2': case '3':
249 case '4': case '5': case '6': case '7': {
250 // Octal escapes.
251 --ThisTokBuf;
252 ResultChar = 0;
253
254 // Octal escapes are a series of octal digits with maximum length 3.
255 // "\0123" is a two digit sequence equal to "\012" "3".
256 unsigned NumDigits = 0;
257 do {
258 ResultChar <<= 3;
259 ResultChar |= *ThisTokBuf++ - '0';
260 ++NumDigits;
261 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
262 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
263
264 // Check for overflow. Reject '\777', but not L'\777'.
265 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
266 if (Diags)
267 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
268 diag::err_escape_too_large) << 1;
269 ResultChar &= ~0U >> (32-CharWidth);
270 }
271 break;
272 }
273 case 'o': {
274 bool Overflow = false;
275 if (ThisTokBuf == ThisTokEnd || *ThisTokBuf != '{') {
276 HadError = true;
277 if (Diags)
278 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
279 diag::err_delimited_escape_missing_brace)
280 << "o";
281
282 break;
283 }
284 ResultChar = 0;
285 Delimited = true;
286 ++ThisTokBuf;
287 if (*ThisTokBuf == '}') {
288 HadError = true;
289 if (Diags)
290 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
291 diag::err_delimited_escape_empty);
292 }
293
294 while (ThisTokBuf != ThisTokEnd) {
295 if (*ThisTokBuf == '}') {
296 EndDelimiterFound = true;
297 ThisTokBuf++;
298 break;
299 }
300 if (*ThisTokBuf < '0' || *ThisTokBuf > '7') {
301 HadError = true;
302 if (Diags)
303 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
304 diag::err_delimited_escape_invalid)
305 << StringRef(ThisTokBuf, 1);
306 ThisTokBuf++;
307 continue;
308 }
309 // Check if one of the top three bits is set before shifting them out.
310 if (ResultChar & 0xE0000000)
311 Overflow = true;
312
313 ResultChar <<= 3;
314 ResultChar |= *ThisTokBuf++ - '0';
315 }
316 // Check for overflow. Reject '\777', but not L'\777'.
317 if (!HadError &&
318 (Overflow || (CharWidth != 32 && (ResultChar >> CharWidth) != 0))) {
319 HadError = true;
320 if (Diags)
321 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
322 diag::err_escape_too_large)
323 << 1;
324 ResultChar &= ~0U >> (32 - CharWidth);
325 }
326 break;
327 }
328 // Otherwise, these are not valid escapes.
329 case '(': case '{': case '[': case '%':
330 // GCC accepts these as extensions. We warn about them as such though.
331 if (Diags)
332 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
333 diag::ext_nonstandard_escape)
334 << std::string(1, ResultChar);
335 break;
336 default:
337 if (!Diags)
338 break;
339
340 if (isPrintable(ResultChar))
341 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
342 diag::ext_unknown_escape)
343 << std::string(1, ResultChar);
344 else
345 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
346 diag::ext_unknown_escape)
347 << "x" + llvm::utohexstr(ResultChar);
348 break;
349 }
350
351 if (Delimited && Diags) {
352 if (!EndDelimiterFound)
353 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
354 diag::err_expected)
355 << tok::r_brace;
356 else if (!HadError) {
358 *Diags);
359 }
360 }
361
362 if (EvalMethod == StringLiteralEvalMethod::Unevaluated &&
364 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
365 diag::err_unevaluated_string_invalid_escape_sequence)
366 << StringRef(EscapeBegin, ThisTokBuf - EscapeBegin);
367 HadError = true;
368 }
369
370 return ResultChar;
371}
372
373static void appendCodePoint(unsigned Codepoint,
375 char ResultBuf[4];
376 char *ResultPtr = ResultBuf;
377 if (llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr))
378 Str.append(ResultBuf, ResultPtr);
379}
380
381void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
382 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
383 if (*I != '\\') {
384 Buf.push_back(*I);
385 continue;
386 }
387
388 ++I;
389 char Kind = *I;
390 ++I;
391
392 assert(Kind == 'u' || Kind == 'U' || Kind == 'N');
393 uint32_t CodePoint = 0;
394
395 if (Kind == 'u' && *I == '{') {
396 for (++I; *I != '}'; ++I) {
397 unsigned Value = llvm::hexDigitValue(*I);
398 assert(Value != -1U);
399 CodePoint <<= 4;
400 CodePoint += Value;
401 }
402 appendCodePoint(CodePoint, Buf);
403 continue;
404 }
405
406 if (Kind == 'N') {
407 assert(*I == '{');
408 ++I;
409 auto Delim = std::find(I, Input.end(), '}');
410 assert(Delim != Input.end());
411 StringRef Name(I, std::distance(I, Delim));
412 std::optional<llvm::sys::unicode::LooseMatchingResult> Res =
413 llvm::sys::unicode::nameToCodepointLooseMatching(Name);
414 assert(Res && "could not find a codepoint that was previously found");
415 CodePoint = Res->CodePoint;
416 assert(CodePoint != 0xFFFFFFFF);
417 appendCodePoint(CodePoint, Buf);
418 I = Delim;
419 continue;
420 }
421
422 unsigned NumHexDigits;
423 if (Kind == 'u')
424 NumHexDigits = 4;
425 else
426 NumHexDigits = 8;
427
428 assert(I + NumHexDigits <= E);
429
430 for (; NumHexDigits != 0; ++I, --NumHexDigits) {
431 unsigned Value = llvm::hexDigitValue(*I);
432 assert(Value != -1U);
433
434 CodePoint <<= 4;
435 CodePoint += Value;
436 }
437
438 appendCodePoint(CodePoint, Buf);
439 --I;
440 }
441}
442
444 const LangOptions &LO) {
445 return LO.MicrosoftExt &&
446 (K == tok::kw___FUNCTION__ || K == tok::kw_L__FUNCTION__ ||
447 K == tok::kw___FUNCSIG__ || K == tok::kw_L__FUNCSIG__ ||
448 K == tok::kw___FUNCDNAME__);
449}
450
452 return tok::isStringLiteral(Tok.getKind()) ||
454}
455
456static bool ProcessNumericUCNEscape(const char *ThisTokBegin,
457 const char *&ThisTokBuf,
458 const char *ThisTokEnd, uint32_t &UcnVal,
459 unsigned short &UcnLen, bool &Delimited,
461 const LangOptions &Features,
462 bool in_char_string_literal = false) {
463 const char *UcnBegin = ThisTokBuf;
464 bool HasError = false;
465 bool EndDelimiterFound = false;
466
467 // Skip the '\u' char's.
468 ThisTokBuf += 2;
469 Delimited = false;
470 if (UcnBegin[1] == 'u' && in_char_string_literal &&
471 ThisTokBuf != ThisTokEnd && *ThisTokBuf == '{') {
472 Delimited = true;
473 ThisTokBuf++;
474 } else if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
475 if (Diags)
476 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
477 diag::err_hex_escape_no_digits)
478 << StringRef(&ThisTokBuf[-1], 1);
479 return false;
480 }
481 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
482
483 bool Overflow = false;
484 unsigned short Count = 0;
485 for (; ThisTokBuf != ThisTokEnd && (Delimited || Count != UcnLen);
486 ++ThisTokBuf) {
487 if (Delimited && *ThisTokBuf == '}') {
488 ++ThisTokBuf;
489 EndDelimiterFound = true;
490 break;
491 }
492 int CharVal = llvm::hexDigitValue(*ThisTokBuf);
493 if (CharVal == -1) {
494 HasError = true;
495 if (!Delimited)
496 break;
497 if (Diags) {
498 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
499 diag::err_delimited_escape_invalid)
500 << StringRef(ThisTokBuf, 1);
501 }
502 Count++;
503 continue;
504 }
505 if (UcnVal & 0xF0000000) {
506 Overflow = true;
507 continue;
508 }
509 UcnVal <<= 4;
510 UcnVal |= CharVal;
511 Count++;
512 }
513
514 if (Overflow) {
515 if (Diags)
516 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
517 diag::err_escape_too_large)
518 << 0;
519 return false;
520 }
521
522 if (Delimited && !EndDelimiterFound) {
523 if (Diags) {
524 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
525 diag::err_expected)
526 << tok::r_brace;
527 }
528 return false;
529 }
530
531 // If we didn't consume the proper number of digits, there is a problem.
532 if (Count == 0 || (!Delimited && Count != UcnLen)) {
533 if (Diags)
534 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
535 Delimited ? diag::err_delimited_escape_empty
536 : diag::err_ucn_escape_incomplete);
537 return false;
538 }
539 return !HasError;
540}
541
542static bool allowedInCharacterName(char C) {
543 return (C >= 'A' && C <= 'Z') || (C >= '0' && C <= '9') || C == '-' ||
544 C == ' ';
545}
546
548 DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc Loc,
549 const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd,
550 llvm::StringRef Name) {
551
552 Diag(Diags, Features, Loc, TokBegin, TokRangeBegin, TokRangeEnd,
553 diag::err_invalid_ucn_name)
554 << Name;
555
556 namespace u = llvm::sys::unicode;
557
558 bool HasIllegalCharacter = false;
559 for (const char *P = Name.begin(), *E = Name.end(); P != E;) {
560 if (allowedInCharacterName(*P)) {
561 ++P;
562 continue;
563 }
564 const auto *Src = reinterpret_cast<const llvm::UTF8 *>(P);
565 const auto *SrcEnd = reinterpret_cast<const llvm::UTF8 *>(E);
566 llvm::UTF32 CodePoint = 0;
567 if (llvm::convertUTF8Sequence(&Src, SrcEnd, &CodePoint,
568 llvm::strictConversion) != llvm::conversionOK)
569 break;
571 Loc, (TokRangeBegin - TokBegin) + (P - Name.begin()), Loc.getManager(),
572 Features);
573 Diags->Report(CharLoc, diag::note_invalid_ucn_name_character)
574 << DisplayCodePointForDiagnostic(CodePoint);
575 HasIllegalCharacter = true;
576 break;
577 }
578
579 std::optional<u::LooseMatchingResult> Res =
580 u::nameToCodepointLooseMatching(Name);
581 if (Res) {
582 Diag(Diags, Features, Loc, TokBegin, TokRangeBegin, TokRangeEnd,
583 diag::note_invalid_ucn_name_loose_matching)
585 MakeCharSourceRange(Features, Loc, TokBegin, TokRangeBegin,
586 TokRangeEnd),
587 Res->Name);
588 return;
589 }
590
591 // Providing illegal characters suggests a fundamental misuse of the feature,
592 // like providing emoji in \N{}. Offering alternative suggestions is often
593 // unhelpful in that scenario.
594 if (HasIllegalCharacter)
595 return;
596
597 unsigned Distance = 0;
599 u::nearestMatchesForCodepointName(Name, 5);
600 assert(!Matches.empty() && "No unicode characters found");
601
602 for (const auto &Match : Matches) {
603 if (Distance == 0)
604 Distance = Match.Distance;
605 if (std::max(Distance, Match.Distance) -
606 std::min(Distance, Match.Distance) >
607 3)
608 break;
609 Distance = Match.Distance;
610
611 Diag(Diags, Features, Loc, TokBegin, TokRangeBegin, TokRangeEnd,
612 diag::note_invalid_ucn_name_candidate)
615 MakeCharSourceRange(Features, Loc, TokBegin, TokRangeBegin,
616 TokRangeEnd),
617 Match.Name);
618 }
619}
620
621static bool ProcessNamedUCNEscape(const char *ThisTokBegin,
622 const char *&ThisTokBuf,
623 const char *ThisTokEnd, uint32_t &UcnVal,
624 unsigned short &UcnLen, FullSourceLoc Loc,
625 DiagnosticsEngine *Diags,
626 const LangOptions &Features) {
627 const char *UcnBegin = ThisTokBuf;
628 assert(UcnBegin[0] == '\\' && UcnBegin[1] == 'N');
629 ThisTokBuf += 2;
630 if (ThisTokBuf == ThisTokEnd || *ThisTokBuf != '{') {
631 if (Diags) {
632 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
633 diag::err_delimited_escape_missing_brace)
634 << StringRef(&ThisTokBuf[-1], 1);
635 }
636 return false;
637 }
638 ThisTokBuf++;
639 const char *ClosingBrace = std::find_if(ThisTokBuf, ThisTokEnd, [](char C) {
640 return C == '}' || isVerticalWhitespace(C);
641 });
642 bool Incomplete = ClosingBrace == ThisTokEnd;
643 bool Empty = ClosingBrace == ThisTokBuf;
644 if (Incomplete || Empty) {
645 if (Diags) {
646 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
647 Incomplete ? diag::err_ucn_escape_incomplete
648 : diag::err_delimited_escape_empty)
649 << StringRef(&UcnBegin[1], 1);
650 }
651 ThisTokBuf = ClosingBrace == ThisTokEnd ? ClosingBrace : ClosingBrace + 1;
652 return false;
653 }
654 StringRef Name(ThisTokBuf, ClosingBrace - ThisTokBuf);
655 ThisTokBuf = ClosingBrace + 1;
656 std::optional<char32_t> Res = llvm::sys::unicode::nameToCodepointStrict(Name);
657 if (!Res) {
658 if (Diags)
659 DiagnoseInvalidUnicodeCharacterName(Diags, Features, Loc, ThisTokBegin,
660 &UcnBegin[3], ClosingBrace, Name);
661 return false;
662 }
663 UcnVal = *Res;
664 UcnLen = UcnVal > 0xFFFF ? 8 : 4;
665 return true;
666}
667
668/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
669/// return the UTF32.
670static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
671 const char *ThisTokEnd, uint32_t &UcnVal,
672 unsigned short &UcnLen, FullSourceLoc Loc,
673 DiagnosticsEngine *Diags,
674 const LangOptions &Features,
675 bool in_char_string_literal = false) {
676
677 bool HasError;
678 const char *UcnBegin = ThisTokBuf;
679 bool IsDelimitedEscapeSequence = false;
680 bool IsNamedEscapeSequence = false;
681 if (ThisTokBuf[1] == 'N') {
682 IsNamedEscapeSequence = true;
683 HasError = !ProcessNamedUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
684 UcnVal, UcnLen, Loc, Diags, Features);
685 } else {
686 HasError =
687 !ProcessNumericUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
688 UcnLen, IsDelimitedEscapeSequence, Loc, Diags,
689 Features, in_char_string_literal);
690 }
691 if (HasError)
692 return false;
693
694 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
695 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
696 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
697 if (Diags)
698 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
699 diag::err_ucn_escape_invalid);
700 return false;
701 }
702
703 // C23 and C++11 allow UCNs that refer to control characters
704 // and basic source characters inside character and string literals
705 if (UcnVal < 0xa0 &&
706 // $, @, ` are allowed in all language modes
707 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) {
708 bool IsError =
709 (!(Features.CPlusPlus11 || Features.C23) || !in_char_string_literal);
710 if (Diags) {
711 char BasicSCSChar = UcnVal;
712 if (UcnVal >= 0x20 && UcnVal < 0x7f)
713 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
714 IsError ? diag::err_ucn_escape_basic_scs
715 : Features.CPlusPlus
716 ? diag::warn_cxx98_compat_literal_ucn_escape_basic_scs
717 : diag::warn_c23_compat_literal_ucn_escape_basic_scs)
718 << StringRef(&BasicSCSChar, 1);
719 else
720 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
721 IsError ? diag::err_ucn_control_character
722 : Features.CPlusPlus
723 ? diag::warn_cxx98_compat_literal_ucn_control_character
724 : diag::warn_c23_compat_literal_ucn_control_character);
725 }
726 if (IsError)
727 return false;
728 }
729
730 if (!Features.CPlusPlus && !Features.C99 && Diags)
731 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
732 diag::warn_ucn_not_valid_in_c89_literal);
733
734 if ((IsDelimitedEscapeSequence || IsNamedEscapeSequence) && Diags)
735 Lexer::DiagnoseDelimitedOrNamedEscapeSequence(Loc, IsNamedEscapeSequence,
736 Features, *Diags);
737 return true;
738}
739
740/// MeasureUCNEscape - Determine the number of bytes within the resulting string
741/// which this UCN will occupy.
742static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
743 const char *ThisTokEnd, unsigned CharByteWidth,
744 const LangOptions &Features, bool &HadError) {
745 // UTF-32: 4 bytes per escape.
746 if (CharByteWidth == 4)
747 return 4;
748
749 uint32_t UcnVal = 0;
750 unsigned short UcnLen = 0;
751 FullSourceLoc Loc;
752
753 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
754 UcnLen, Loc, nullptr, Features, true)) {
755 HadError = true;
756 return 0;
757 }
758
759 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
760 if (CharByteWidth == 2)
761 return UcnVal <= 0xFFFF ? 2 : 4;
762
763 // UTF-8.
764 if (UcnVal < 0x80)
765 return 1;
766 if (UcnVal < 0x800)
767 return 2;
768 if (UcnVal < 0x10000)
769 return 3;
770 return 4;
771}
772
773/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
774/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
775/// StringLiteralParser. When we decide to implement UCN's for identifiers,
776/// we will likely rework our support for UCN's.
777static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
778 const char *ThisTokEnd,
779 char *&ResultBuf, bool &HadError,
780 FullSourceLoc Loc, unsigned CharByteWidth,
781 DiagnosticsEngine *Diags,
782 const LangOptions &Features) {
783 typedef uint32_t UTF32;
784 UTF32 UcnVal = 0;
785 unsigned short UcnLen = 0;
786 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
787 Loc, Diags, Features, true)) {
788 HadError = true;
789 return;
790 }
791
792 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
793 "only character widths of 1, 2, or 4 bytes supported");
794
795 (void)UcnLen;
796 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
797
798 if (CharByteWidth == 4) {
799 // FIXME: Make the type of the result buffer correct instead of
800 // using reinterpret_cast.
801 llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
802 *ResultPtr = UcnVal;
803 ResultBuf += 4;
804 return;
805 }
806
807 if (CharByteWidth == 2) {
808 // FIXME: Make the type of the result buffer correct instead of
809 // using reinterpret_cast.
810 llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
811
812 if (UcnVal <= (UTF32)0xFFFF) {
813 *ResultPtr = UcnVal;
814 ResultBuf += 2;
815 return;
816 }
817
818 // Convert to UTF16.
819 UcnVal -= 0x10000;
820 *ResultPtr = 0xD800 + (UcnVal >> 10);
821 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
822 ResultBuf += 4;
823 return;
824 }
825
826 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
827
828 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
829 // The conversion below was inspired by:
830 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
831 // First, we determine how many bytes the result will require.
832 typedef uint8_t UTF8;
833
834 unsigned short bytesToWrite = 0;
835 if (UcnVal < (UTF32)0x80)
836 bytesToWrite = 1;
837 else if (UcnVal < (UTF32)0x800)
838 bytesToWrite = 2;
839 else if (UcnVal < (UTF32)0x10000)
840 bytesToWrite = 3;
841 else
842 bytesToWrite = 4;
843
844 const unsigned byteMask = 0xBF;
845 const unsigned byteMark = 0x80;
846
847 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
848 // into the first byte, depending on how many bytes follow.
849 static const UTF8 firstByteMark[5] = {
850 0x00, 0x00, 0xC0, 0xE0, 0xF0
851 };
852 // Finally, we write the bytes into ResultBuf.
853 ResultBuf += bytesToWrite;
854 switch (bytesToWrite) { // note: everything falls through.
855 case 4:
856 *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
857 [[fallthrough]];
858 case 3:
859 *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
860 [[fallthrough]];
861 case 2:
862 *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
863 [[fallthrough]];
864 case 1:
865 *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
866 }
867 // Update the buffer.
868 ResultBuf += bytesToWrite;
869}
870
871/// integer-constant: [C99 6.4.4.1]
872/// decimal-constant integer-suffix
873/// octal-constant integer-suffix
874/// hexadecimal-constant integer-suffix
875/// binary-literal integer-suffix [GNU, C++1y]
876/// user-defined-integer-literal: [C++11 lex.ext]
877/// decimal-literal ud-suffix
878/// octal-literal ud-suffix
879/// hexadecimal-literal ud-suffix
880/// binary-literal ud-suffix [GNU, C++1y]
881/// decimal-constant:
882/// nonzero-digit
883/// decimal-constant digit
884/// octal-constant:
885/// 0
886/// octal-constant octal-digit
887/// hexadecimal-constant:
888/// hexadecimal-prefix hexadecimal-digit
889/// hexadecimal-constant hexadecimal-digit
890/// hexadecimal-prefix: one of
891/// 0x 0X
892/// binary-literal:
893/// 0b binary-digit
894/// 0B binary-digit
895/// binary-literal binary-digit
896/// integer-suffix:
897/// unsigned-suffix [long-suffix]
898/// unsigned-suffix [long-long-suffix]
899/// long-suffix [unsigned-suffix]
900/// long-long-suffix [unsigned-sufix]
901/// nonzero-digit:
902/// 1 2 3 4 5 6 7 8 9
903/// octal-digit:
904/// 0 1 2 3 4 5 6 7
905/// hexadecimal-digit:
906/// 0 1 2 3 4 5 6 7 8 9
907/// a b c d e f
908/// A B C D E F
909/// binary-digit:
910/// 0
911/// 1
912/// unsigned-suffix: one of
913/// u U
914/// long-suffix: one of
915/// l L
916/// long-long-suffix: one of
917/// ll LL
918///
919/// floating-constant: [C99 6.4.4.2]
920/// TODO: add rules...
921///
923 SourceLocation TokLoc,
924 const SourceManager &SM,
925 const LangOptions &LangOpts,
926 const TargetInfo &Target,
927 DiagnosticsEngine &Diags)
928 : SM(SM), LangOpts(LangOpts), Diags(Diags),
929 ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
930
931 s = DigitsBegin = ThisTokBegin;
932 saw_exponent = false;
933 saw_period = false;
934 saw_ud_suffix = false;
935 saw_fixed_point_suffix = false;
936 isLong = false;
937 isUnsigned = false;
938 isLongLong = false;
939 isSizeT = false;
940 isHalf = false;
941 isFloat = false;
942 isImaginary = false;
943 isFloat16 = false;
944 isFloat128 = false;
946 isFract = false;
947 isAccum = false;
948 hadError = false;
949 isBitInt = false;
950
951 // This routine assumes that the range begin/end matches the regex for integer
952 // and FP constants (specifically, the 'pp-number' regex), and assumes that
953 // the byte at "*end" is both valid and not part of the regex. Because of
954 // this, it doesn't have to check for 'overscan' in various places.
955 // Note: For HLSL, the end token is allowed to be '.' which would be in the
956 // 'pp-number' regex. This is required to support vector swizzles on numeric
957 // constants (i.e. 1.xx or 1.5f.rrr).
958 if (isPreprocessingNumberBody(*ThisTokEnd) &&
959 !(LangOpts.HLSL && *ThisTokEnd == '.')) {
960 Diags.Report(TokLoc, diag::err_lexing_numeric);
961 hadError = true;
962 return;
963 }
964
965 if (*s == '0') { // parse radix
966 ParseNumberStartingWithZero(TokLoc);
967 if (hadError)
968 return;
969 } else { // the first digit is non-zero
970 radix = 10;
971 s = SkipDigits(s);
972 if (s == ThisTokEnd) {
973 // Done.
974 } else {
975 ParseDecimalOrOctalCommon(TokLoc);
976 if (hadError)
977 return;
978 }
979 }
980
981 SuffixBegin = s;
982 checkSeparator(TokLoc, s, CSK_AfterDigits);
983
984 // Initial scan to lookahead for fixed point suffix.
985 if (LangOpts.FixedPoint) {
986 for (const char *c = s; c != ThisTokEnd; ++c) {
987 if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
988 saw_fixed_point_suffix = true;
989 break;
990 }
991 }
992 }
993
994 // Parse the suffix. At this point we can classify whether we have an FP or
995 // integer constant.
996 bool isFixedPointConstant = isFixedPointLiteral();
997 bool isFPConstant = isFloatingLiteral();
998 bool HasSize = false;
999 bool DoubleUnderscore = false;
1000
1001 // Loop over all of the characters of the suffix. If we see something bad,
1002 // we break out of the loop.
1003 for (; s != ThisTokEnd; ++s) {
1004 switch (*s) {
1005 case 'R':
1006 case 'r':
1007 if (!LangOpts.FixedPoint)
1008 break;
1009 if (isFract || isAccum) break;
1010 if (!(saw_period || saw_exponent)) break;
1011 isFract = true;
1012 continue;
1013 case 'K':
1014 case 'k':
1015 if (!LangOpts.FixedPoint)
1016 break;
1017 if (isFract || isAccum) break;
1018 if (!(saw_period || saw_exponent)) break;
1019 isAccum = true;
1020 continue;
1021 case 'h': // FP Suffix for "half".
1022 case 'H':
1023 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
1024 if (!(LangOpts.Half || LangOpts.FixedPoint))
1025 break;
1026 if (isIntegerLiteral()) break; // Error for integer constant.
1027 if (HasSize)
1028 break;
1029 HasSize = true;
1030 isHalf = true;
1031 continue; // Success.
1032 case 'f': // FP Suffix for "float"
1033 case 'F':
1034 if (!isFPConstant) break; // Error for integer constant.
1035 if (HasSize)
1036 break;
1037 HasSize = true;
1038
1039 // CUDA host and device may have different _Float16 support, therefore
1040 // allows f16 literals to avoid false alarm.
1041 // When we compile for OpenMP target offloading on NVPTX, f16 suffix
1042 // should also be supported.
1043 // ToDo: more precise check for CUDA.
1044 // TODO: AMDGPU might also support it in the future.
1045 if ((Target.hasFloat16Type() || LangOpts.CUDA ||
1046 (LangOpts.OpenMPIsTargetDevice && Target.getTriple().isNVPTX())) &&
1047 s + 2 < ThisTokEnd && s[1] == '1' && s[2] == '6') {
1048 s += 2; // success, eat up 2 characters.
1049 isFloat16 = true;
1050 continue;
1051 }
1052
1053 isFloat = true;
1054 continue; // Success.
1055 case 'q': // FP Suffix for "__float128"
1056 case 'Q':
1057 if (!isFPConstant) break; // Error for integer constant.
1058 if (HasSize)
1059 break;
1060 HasSize = true;
1061 isFloat128 = true;
1062 continue; // Success.
1063 case 'u':
1064 case 'U':
1065 if (isFPConstant) break; // Error for floating constant.
1066 if (isUnsigned) break; // Cannot be repeated.
1067 isUnsigned = true;
1068 continue; // Success.
1069 case 'l':
1070 case 'L':
1071 if (HasSize)
1072 break;
1073 HasSize = true;
1074
1075 // Check for long long. The L's need to be adjacent and the same case.
1076 if (s[1] == s[0]) {
1077 assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
1078 if (isFPConstant) break; // long long invalid for floats.
1079 isLongLong = true;
1080 ++s; // Eat both of them.
1081 } else {
1082 isLong = true;
1083 }
1084 continue; // Success.
1085 case 'z':
1086 case 'Z':
1087 if (isFPConstant)
1088 break; // Invalid for floats.
1089 if (HasSize)
1090 break;
1091 HasSize = true;
1092 isSizeT = true;
1093 continue;
1094 case 'i':
1095 case 'I':
1096 if (LangOpts.MicrosoftExt && s + 1 < ThisTokEnd && !isFPConstant) {
1097 // Allow i8, i16, i32, i64, and i128. First, look ahead and check if
1098 // suffixes are Microsoft integers and not the imaginary unit.
1099 uint8_t Bits = 0;
1100 size_t ToSkip = 0;
1101 switch (s[1]) {
1102 case '8': // i8 suffix
1103 Bits = 8;
1104 ToSkip = 2;
1105 break;
1106 case '1':
1107 if (s + 2 < ThisTokEnd && s[2] == '6') { // i16 suffix
1108 Bits = 16;
1109 ToSkip = 3;
1110 } else if (s + 3 < ThisTokEnd && s[2] == '2' &&
1111 s[3] == '8') { // i128 suffix
1112 Bits = 128;
1113 ToSkip = 4;
1114 }
1115 break;
1116 case '3':
1117 if (s + 2 < ThisTokEnd && s[2] == '2') { // i32 suffix
1118 Bits = 32;
1119 ToSkip = 3;
1120 }
1121 break;
1122 case '6':
1123 if (s + 2 < ThisTokEnd && s[2] == '4') { // i64 suffix
1124 Bits = 64;
1125 ToSkip = 3;
1126 }
1127 break;
1128 default:
1129 break;
1130 }
1131 if (Bits) {
1132 if (HasSize)
1133 break;
1134 HasSize = true;
1135 MicrosoftInteger = Bits;
1136 s += ToSkip;
1137 assert(s <= ThisTokEnd && "didn't maximally munch?");
1138 break;
1139 }
1140 }
1141 [[fallthrough]];
1142 case 'j':
1143 case 'J':
1144 if (isImaginary) break; // Cannot be repeated.
1145 isImaginary = true;
1146 continue; // Success.
1147 case '_':
1148 if (isFPConstant)
1149 break; // Invalid for floats
1150 if (HasSize)
1151 break;
1152 // There is currently no way to reach this with DoubleUnderscore set.
1153 // If new double underscope literals are added handle it here as above.
1154 assert(!DoubleUnderscore && "unhandled double underscore case");
1155 if (LangOpts.CPlusPlus && s + 2 < ThisTokEnd &&
1156 s[1] == '_') { // s + 2 < ThisTokEnd to ensure some character exists
1157 // after __
1158 DoubleUnderscore = true;
1159 s += 2; // Skip both '_'
1160 if (s + 1 < ThisTokEnd &&
1161 (*s == 'u' || *s == 'U')) { // Ensure some character after 'u'/'U'
1162 isUnsigned = true;
1163 ++s;
1164 }
1165 if (s + 1 < ThisTokEnd &&
1166 ((*s == 'w' && *(++s) == 'b') || (*s == 'W' && *(++s) == 'B'))) {
1167 isBitInt = true;
1168 HasSize = true;
1169 continue;
1170 }
1171 }
1172 break;
1173 case 'w':
1174 case 'W':
1175 if (isFPConstant)
1176 break; // Invalid for floats.
1177 if (HasSize)
1178 break; // Invalid if we already have a size for the literal.
1179
1180 // wb and WB are allowed, but a mixture of cases like Wb or wB is not. We
1181 // explicitly do not support the suffix in C++ as an extension because a
1182 // library-based UDL that resolves to a library type may be more
1183 // appropriate there. The same rules apply for __wb/__WB.
1184 if ((!LangOpts.CPlusPlus || DoubleUnderscore) && s + 1 < ThisTokEnd &&
1185 ((s[0] == 'w' && s[1] == 'b') || (s[0] == 'W' && s[1] == 'B'))) {
1186 isBitInt = true;
1187 HasSize = true;
1188 ++s; // Skip both characters (2nd char skipped on continue).
1189 continue; // Success.
1190 }
1191 }
1192 // If we reached here, there was an error or a ud-suffix.
1193 break;
1194 }
1195
1196 // "i", "if", and "il" are user-defined suffixes in C++1y.
1197 if (s != ThisTokEnd || isImaginary) {
1198 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
1199 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
1200 if (isValidUDSuffix(LangOpts, UDSuffixBuf)) {
1201 if (!isImaginary) {
1202 // Any suffix pieces we might have parsed are actually part of the
1203 // ud-suffix.
1204 isLong = false;
1205 isUnsigned = false;
1206 isLongLong = false;
1207 isSizeT = false;
1208 isFloat = false;
1209 isFloat16 = false;
1210 isHalf = false;
1211 isImaginary = false;
1212 isBitInt = false;
1213 MicrosoftInteger = 0;
1214 saw_fixed_point_suffix = false;
1215 isFract = false;
1216 isAccum = false;
1217 }
1218
1219 saw_ud_suffix = true;
1220 return;
1221 }
1222
1223 if (s != ThisTokEnd) {
1224 // Report an error if there are any.
1225 Diags.Report(Lexer::AdvanceToTokenCharacter(
1226 TokLoc, SuffixBegin - ThisTokBegin, SM, LangOpts),
1227 diag::err_invalid_suffix_constant)
1228 << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)
1229 << (isFixedPointConstant ? 2 : isFPConstant);
1230 hadError = true;
1231 }
1232 }
1233
1234 if (!hadError && saw_fixed_point_suffix) {
1235 assert(isFract || isAccum);
1236 }
1237}
1238
1239/// ParseDecimalOrOctalCommon - This method is called for decimal or octal
1240/// numbers. It issues an error for illegal digits, and handles floating point
1241/// parsing. If it detects a floating point number, the radix is set to 10.
1242void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
1243 assert((radix == 8 || radix == 10) && "Unexpected radix");
1244
1245 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
1246 // the code is using an incorrect base.
1247 if (isHexDigit(*s) && *s != 'e' && *s != 'E' &&
1248 !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
1249 Diags.Report(
1250 Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM, LangOpts),
1251 diag::err_invalid_digit)
1252 << StringRef(s, 1) << (radix == 8 ? 1 : 0);
1253 hadError = true;
1254 return;
1255 }
1256
1257 if (*s == '.') {
1258 checkSeparator(TokLoc, s, CSK_AfterDigits);
1259 s++;
1260 radix = 10;
1261 saw_period = true;
1262 checkSeparator(TokLoc, s, CSK_BeforeDigits);
1263 s = SkipDigits(s); // Skip suffix.
1264 }
1265 if (*s == 'e' || *s == 'E') { // exponent
1266 checkSeparator(TokLoc, s, CSK_AfterDigits);
1267 const char *Exponent = s;
1268 s++;
1269 radix = 10;
1270 saw_exponent = true;
1271 if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
1272 const char *first_non_digit = SkipDigits(s);
1273 if (containsDigits(s, first_non_digit)) {
1274 checkSeparator(TokLoc, s, CSK_BeforeDigits);
1275 s = first_non_digit;
1276 } else {
1277 if (!hadError) {
1278 Diags.Report(Lexer::AdvanceToTokenCharacter(
1279 TokLoc, Exponent - ThisTokBegin, SM, LangOpts),
1280 diag::err_exponent_has_no_digits);
1281 hadError = true;
1282 }
1283 return;
1284 }
1285 }
1286}
1287
1288/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
1289/// suffixes as ud-suffixes, because the diagnostic experience is better if we
1290/// treat it as an invalid suffix.
1292 StringRef Suffix) {
1293 if (!LangOpts.CPlusPlus11 || Suffix.empty())
1294 return false;
1295
1296 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
1297 // Suffixes starting with '__' (double underscore) are for use by
1298 // the implementation.
1299 if (Suffix.starts_with("_") && !Suffix.starts_with("__"))
1300 return true;
1301
1302 // In C++11, there are no library suffixes.
1303 if (!LangOpts.CPlusPlus14)
1304 return false;
1305
1306 // In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
1307 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
1308 // In C++2a "d" and "y" are used in the library.
1309 return llvm::StringSwitch<bool>(Suffix)
1310 .Cases({"h", "min", "s"}, true)
1311 .Cases({"ms", "us", "ns"}, true)
1312 .Cases({"il", "i", "if"}, true)
1313 .Cases({"d", "y"}, LangOpts.CPlusPlus20)
1314 .Default(false);
1315}
1316
1317void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
1318 const char *Pos,
1319 CheckSeparatorKind IsAfterDigits) {
1320 if (IsAfterDigits == CSK_AfterDigits) {
1321 if (Pos == ThisTokBegin)
1322 return;
1323 --Pos;
1324 } else if (Pos == ThisTokEnd)
1325 return;
1326
1327 if (isDigitSeparator(*Pos)) {
1328 Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin, SM,
1329 LangOpts),
1330 diag::err_digit_separator_not_between_digits)
1331 << IsAfterDigits;
1332 hadError = true;
1333 }
1334}
1335
1336/// ParseNumberStartingWithZero - This method is called when the first character
1337/// of the number is found to be a zero. This means it is either an octal
1338/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
1339/// a floating point number (01239.123e4). Eat the prefix, determining the
1340/// radix etc.
1341void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
1342 assert(s[0] == '0' && "Invalid method call");
1343 s++;
1344
1345 int c1 = s[0];
1346
1347 // Handle a hex number like 0x1234.
1348 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
1349 s++;
1350 assert(s < ThisTokEnd && "didn't maximally munch?");
1351 radix = 16;
1352 DigitsBegin = s;
1353 s = SkipHexDigits(s);
1354 bool HasSignificandDigits = containsDigits(DigitsBegin, s);
1355 if (s == ThisTokEnd) {
1356 // Done.
1357 } else if (*s == '.') {
1358 s++;
1359 saw_period = true;
1360 const char *floatDigitsBegin = s;
1361 s = SkipHexDigits(s);
1362 if (containsDigits(floatDigitsBegin, s))
1363 HasSignificandDigits = true;
1364 if (HasSignificandDigits)
1365 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
1366 }
1367
1368 if (!HasSignificandDigits) {
1369 Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
1370 LangOpts),
1371 diag::err_hex_constant_requires)
1372 << LangOpts.CPlusPlus << 1;
1373 hadError = true;
1374 return;
1375 }
1376
1377 // A binary exponent can appear with or with a '.'. If dotted, the
1378 // binary exponent is required.
1379 if (*s == 'p' || *s == 'P') {
1380 checkSeparator(TokLoc, s, CSK_AfterDigits);
1381 const char *Exponent = s;
1382 s++;
1383 saw_exponent = true;
1384 if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
1385 const char *first_non_digit = SkipDigits(s);
1386 if (!containsDigits(s, first_non_digit)) {
1387 if (!hadError) {
1388 Diags.Report(Lexer::AdvanceToTokenCharacter(
1389 TokLoc, Exponent - ThisTokBegin, SM, LangOpts),
1390 diag::err_exponent_has_no_digits);
1391 hadError = true;
1392 }
1393 return;
1394 }
1395 checkSeparator(TokLoc, s, CSK_BeforeDigits);
1396 s = first_non_digit;
1397
1398 if (!LangOpts.HexFloats)
1399 Diags.Report(TokLoc, LangOpts.CPlusPlus
1400 ? diag::ext_hex_literal_invalid
1401 : diag::ext_hex_constant_invalid);
1402 else if (LangOpts.CPlusPlus17)
1403 Diags.Report(TokLoc, diag::warn_cxx17_hex_literal);
1404 } else if (saw_period) {
1405 Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
1406 LangOpts),
1407 diag::err_hex_constant_requires)
1408 << LangOpts.CPlusPlus << 0;
1409 hadError = true;
1410 }
1411 return;
1412 }
1413
1414 // Handle simple binary numbers 0b01010
1415 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
1416 // 0b101010 is a C++14 and C23 extension.
1417 unsigned DiagId;
1418 if (LangOpts.CPlusPlus14)
1419 DiagId = diag::warn_cxx11_compat_binary_literal;
1420 else if (LangOpts.C23)
1421 DiagId = diag::warn_c23_compat_binary_literal;
1422 else if (LangOpts.CPlusPlus)
1423 DiagId = diag::ext_binary_literal_cxx14;
1424 else
1425 DiagId = diag::ext_binary_literal;
1426 Diags.Report(TokLoc, DiagId);
1427 ++s;
1428 assert(s < ThisTokEnd && "didn't maximally munch?");
1429 radix = 2;
1430 DigitsBegin = s;
1431 s = SkipBinaryDigits(s);
1432 if (s == ThisTokEnd) {
1433 // Done.
1434 } else if (isHexDigit(*s) &&
1435 !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
1436 Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
1437 LangOpts),
1438 diag::err_invalid_digit)
1439 << StringRef(s, 1) << 2;
1440 hadError = true;
1441 }
1442 // Other suffixes will be diagnosed by the caller.
1443 return;
1444 }
1445
1446 // Parse a potential octal literal prefix.
1447 bool IsSingleZero = false;
1448 if ((c1 == 'O' || c1 == 'o') && (s[1] >= '0' && s[1] <= '7')) {
1449 unsigned DiagId;
1450 if (LangOpts.C2y)
1451 DiagId = diag::warn_c2y_compat_octal_literal;
1452 else if (LangOpts.CPlusPlus)
1453 DiagId = diag::ext_cpp_octal_literal;
1454 else
1455 DiagId = diag::ext_octal_literal;
1456 // If the token location is from a macro expansion where the macro was
1457 // defined in a system header, suppress the diagnostic.
1458 // FIXME: this is actually a more general issue, for example we have a
1459 // similar need for binary literals above. It would be best for this to be
1460 // handled by the diagnostics engine instead of with ad hoc solutions. This
1461 // same concern exists below for issuing the deprecation warning.
1462 if (!SM.isInSystemMacro(TokLoc))
1463 Diags.Report(TokLoc, DiagId);
1464
1465 ++s;
1466 DigitsBegin = s;
1467 radix = 8;
1468 s = SkipOctalDigits(s);
1469 if (s == ThisTokEnd) {
1470 // Done
1471 } else if ((isHexDigit(*s) && *s != 'e' && *s != 'E' && *s != '.') &&
1472 !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
1473 auto InvalidDigitLoc = Lexer::AdvanceToTokenCharacter(
1474 TokLoc, s - ThisTokBegin, SM, LangOpts);
1475 Diags.Report(InvalidDigitLoc, diag::err_invalid_digit)
1476 << StringRef(s, 1) << 1;
1477 hadError = true;
1478 }
1479 // Other suffixes will be diagnosed by the caller.
1480 return;
1481 }
1482
1483 llvm::scope_exit _([&] {
1484 // If we still have an octal value but we did not see an octal prefix,
1485 // diagnose as being an obsolescent feature starting in C2y. If the token
1486 // location is from a macro expansion where the macro was defined in a
1487 // system header, suppress the diagnostic.
1488 if (radix == 8 && LangOpts.C2y && !hadError && !IsSingleZero &&
1489 !SM.isInSystemMacro(TokLoc))
1490 Diags.Report(TokLoc, diag::warn_unprefixed_octal_deprecated);
1491 });
1492
1493 // For now, the radix is set to 8. If we discover that we have a
1494 // floating point constant, the radix will change to 10. Octal floating
1495 // point constants are not permitted (only decimal and hexadecimal).
1496 radix = 8;
1497 const char *PossibleNewDigitStart = s;
1498 s = SkipOctalDigits(s);
1499 // When the value is 0 followed by a suffix (like 0wb), we want to leave 0
1500 // as the start of the digits. So if skipping octal digits does not skip
1501 // anything, we leave the digit start where it was.
1502 if (s != PossibleNewDigitStart)
1503 DigitsBegin = PossibleNewDigitStart;
1504 else
1505 IsSingleZero = (s == ThisTokBegin + 1);
1506
1507 if (s == ThisTokEnd)
1508 return; // Done, simple octal number like 01234
1509
1510 // If we have some other non-octal digit that *is* a decimal digit, see if
1511 // this is part of a floating point number like 094.123 or 09e1.
1512 if (isDigit(*s)) {
1513 const char *EndDecimal = SkipDigits(s);
1514 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
1515 s = EndDecimal;
1516 radix = 10;
1517 }
1518 }
1519
1520 ParseDecimalOrOctalCommon(TokLoc);
1521}
1522
1523static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
1524 switch (Radix) {
1525 case 2:
1526 return NumDigits <= 64;
1527 case 8:
1528 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
1529 case 10:
1530 return NumDigits <= 19; // floor(log10(2^64))
1531 case 16:
1532 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
1533 default:
1534 llvm_unreachable("impossible Radix");
1535 }
1536}
1537
1538/// GetIntegerValue - Convert this numeric literal value to an APInt that
1539/// matches Val's input width. If there is an overflow, set Val to the low bits
1540/// of the result and return true. Otherwise, return false.
1542 // Fast path: Compute a conservative bound on the maximum number of
1543 // bits per digit in this radix. If we can't possibly overflow a
1544 // uint64 based on that bound then do the simple conversion to
1545 // integer. This avoids the expensive overflow checking below, and
1546 // handles the common cases that matter (small decimal integers and
1547 // hex/octal values which don't overflow).
1548 const unsigned NumDigits = SuffixBegin - DigitsBegin;
1549 if (alwaysFitsInto64Bits(radix, NumDigits)) {
1550 uint64_t N = 0;
1551 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
1552 if (!isDigitSeparator(*Ptr))
1553 N = N * radix + llvm::hexDigitValue(*Ptr);
1554
1555 // This will truncate the value to Val's input width. Simply check
1556 // for overflow by comparing.
1557 Val = N;
1558 return Val.getZExtValue() != N;
1559 }
1560
1561 Val = 0;
1562 const char *Ptr = DigitsBegin;
1563
1564 llvm::APInt RadixVal(Val.getBitWidth(), radix);
1565 llvm::APInt CharVal(Val.getBitWidth(), 0);
1566 llvm::APInt OldVal = Val;
1567
1568 bool OverflowOccurred = false;
1569 while (Ptr < SuffixBegin) {
1570 if (isDigitSeparator(*Ptr)) {
1571 ++Ptr;
1572 continue;
1573 }
1574
1575 unsigned C = llvm::hexDigitValue(*Ptr++);
1576
1577 // If this letter is out of bound for this radix, reject it.
1578 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1579
1580 CharVal = C;
1581
1582 // Add the digit to the value in the appropriate radix. If adding in digits
1583 // made the value smaller, then this overflowed.
1584 OldVal = Val;
1585
1586 // Multiply by radix, did overflow occur on the multiply?
1587 Val *= RadixVal;
1588 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
1589
1590 // Add value, did overflow occur on the value?
1591 // (a + b) ult b <=> overflow
1592 Val += CharVal;
1593 OverflowOccurred |= Val.ult(CharVal);
1594 }
1595 return OverflowOccurred;
1596}
1597
1598llvm::APFloat::opStatus
1600 llvm::RoundingMode RM) {
1601 using llvm::APFloat;
1602
1603 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
1604
1605 llvm::SmallString<16> Buffer;
1606 StringRef Str(ThisTokBegin, n);
1607 if (Str.contains('\'')) {
1608 Buffer.reserve(n);
1609 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
1610 &isDigitSeparator);
1611 Str = Buffer;
1612 }
1613
1614 auto StatusOrErr = Result.convertFromString(Str, RM);
1615 assert(StatusOrErr && "Invalid floating point representation");
1616 return !errorToBool(StatusOrErr.takeError()) ? *StatusOrErr
1617 : APFloat::opInvalidOp;
1618}
1619
1620static inline bool IsExponentPart(char c, bool isHex) {
1621 if (isHex)
1622 return c == 'p' || c == 'P';
1623 return c == 'e' || c == 'E';
1624}
1625
1626bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
1627 assert(radix == 16 || radix == 10);
1628
1629 // Find how many digits are needed to store the whole literal.
1630 unsigned NumDigits = SuffixBegin - DigitsBegin;
1631 if (saw_period) --NumDigits;
1632
1633 // Initial scan of the exponent if it exists
1634 bool ExpOverflowOccurred = false;
1635 bool NegativeExponent = false;
1636 const char *ExponentBegin;
1637 uint64_t Exponent = 0;
1638 int64_t BaseShift = 0;
1639 if (saw_exponent) {
1640 const char *Ptr = DigitsBegin;
1641
1642 while (!IsExponentPart(*Ptr, radix == 16))
1643 ++Ptr;
1644 ExponentBegin = Ptr;
1645 ++Ptr;
1646 NegativeExponent = *Ptr == '-';
1647 if (NegativeExponent) ++Ptr;
1648
1649 unsigned NumExpDigits = SuffixBegin - Ptr;
1650 if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
1651 llvm::StringRef ExpStr(Ptr, NumExpDigits);
1652 llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
1653 Exponent = ExpInt.getZExtValue();
1654 } else {
1655 ExpOverflowOccurred = true;
1656 }
1657
1658 if (NegativeExponent) BaseShift -= Exponent;
1659 else BaseShift += Exponent;
1660 }
1661
1662 // Number of bits needed for decimal literal is
1663 // ceil(NumDigits * log2(10)) Integral part
1664 // + Scale Fractional part
1665 // + ceil(Exponent * log2(10)) Exponent
1666 // --------------------------------------------------
1667 // ceil((NumDigits + Exponent) * log2(10)) + Scale
1668 //
1669 // But for simplicity in handling integers, we can round up log2(10) to 4,
1670 // making:
1671 // 4 * (NumDigits + Exponent) + Scale
1672 //
1673 // Number of digits needed for hexadecimal literal is
1674 // 4 * NumDigits Integral part
1675 // + Scale Fractional part
1676 // + Exponent Exponent
1677 // --------------------------------------------------
1678 // (4 * NumDigits) + Scale + Exponent
1679 uint64_t NumBitsNeeded;
1680 if (radix == 10)
1681 NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
1682 else
1683 NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
1684
1685 if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
1686 ExpOverflowOccurred = true;
1687 llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
1688
1689 bool FoundDecimal = false;
1690
1691 int64_t FractBaseShift = 0;
1692 const char *End = saw_exponent ? ExponentBegin : SuffixBegin;
1693 for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) {
1694 if (*Ptr == '.') {
1695 FoundDecimal = true;
1696 continue;
1697 }
1698
1699 // Normal reading of an integer
1700 unsigned C = llvm::hexDigitValue(*Ptr);
1701 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1702
1703 Val *= radix;
1704 Val += C;
1705
1706 if (FoundDecimal)
1707 // Keep track of how much we will need to adjust this value by from the
1708 // number of digits past the radix point.
1709 --FractBaseShift;
1710 }
1711
1712 // For a radix of 16, we will be multiplying by 2 instead of 16.
1713 if (radix == 16) FractBaseShift *= 4;
1714 BaseShift += FractBaseShift;
1715
1716 Val <<= Scale;
1717
1718 uint64_t Base = (radix == 16) ? 2 : 10;
1719 if (BaseShift > 0) {
1720 for (int64_t i = 0; i < BaseShift; ++i) {
1721 Val *= Base;
1722 }
1723 } else if (BaseShift < 0) {
1724 for (int64_t i = BaseShift; i < 0 && !Val.isZero(); ++i)
1725 Val = Val.udiv(Base);
1726 }
1727
1728 bool IntOverflowOccurred = false;
1729 auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
1730 if (Val.getBitWidth() > StoreVal.getBitWidth()) {
1731 IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
1732 StoreVal = Val.trunc(StoreVal.getBitWidth());
1733 } else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
1734 IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
1735 StoreVal = Val.zext(StoreVal.getBitWidth());
1736 } else {
1737 StoreVal = std::move(Val);
1738 }
1739
1740 return IntOverflowOccurred || ExpOverflowOccurred;
1741}
1742
1743/// \verbatim
1744/// user-defined-character-literal: [C++11 lex.ext]
1745/// character-literal ud-suffix
1746/// ud-suffix:
1747/// identifier
1748/// character-literal: [C++11 lex.ccon]
1749/// ' c-char-sequence '
1750/// u' c-char-sequence '
1751/// U' c-char-sequence '
1752/// L' c-char-sequence '
1753/// u8' c-char-sequence ' [C++1z lex.ccon]
1754/// c-char-sequence:
1755/// c-char
1756/// c-char-sequence c-char
1757/// c-char:
1758/// any member of the source character set except the single-quote ',
1759/// backslash \, or new-line character
1760/// escape-sequence
1761/// universal-character-name
1762/// escape-sequence:
1763/// simple-escape-sequence
1764/// octal-escape-sequence
1765/// hexadecimal-escape-sequence
1766/// simple-escape-sequence:
1767/// one of \' \" \? \\ \a \b \f \n \r \t \v
1768/// octal-escape-sequence:
1769/// \ octal-digit
1770/// \ octal-digit octal-digit
1771/// \ octal-digit octal-digit octal-digit
1772/// hexadecimal-escape-sequence:
1773/// \x hexadecimal-digit
1774/// hexadecimal-escape-sequence hexadecimal-digit
1775/// universal-character-name: [C++11 lex.charset]
1776/// \u hex-quad
1777/// \U hex-quad hex-quad
1778/// hex-quad:
1779/// hex-digit hex-digit hex-digit hex-digit
1780/// \endverbatim
1781///
1782CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
1785 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
1786 HadError = false;
1787
1788 Kind = kind;
1789
1790 const char *TokBegin = begin;
1791
1792 // Skip over wide character determinant.
1793 if (Kind != tok::char_constant)
1794 ++begin;
1795 if (Kind == tok::utf8_char_constant)
1796 ++begin;
1797
1798 // Skip over the entry quote.
1799 if (begin[0] != '\'') {
1800 PP.Diag(Loc, diag::err_lexing_char);
1801 HadError = true;
1802 return;
1803 }
1804
1805 ++begin;
1806
1807 // Remove an optional ud-suffix.
1808 if (end[-1] != '\'') {
1809 const char *UDSuffixEnd = end;
1810 do {
1811 --end;
1812 } while (end[-1] != '\'');
1813 // FIXME: Don't bother with this if !tok.hasUCN().
1814 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
1815 UDSuffixOffset = end - TokBegin;
1816 }
1817
1818 // Trim the ending quote.
1819 assert(end != begin && "Invalid token lexed");
1820 --end;
1821
1822 // FIXME: The "Value" is an uint64_t so we can handle char literals of
1823 // up to 64-bits.
1824 // FIXME: This extensively assumes that 'char' is 8-bits.
1825 assert(PP.getTargetInfo().getCharWidth() == 8 &&
1826 "Assumes char is 8 bits");
1827 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1828 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1829 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1830 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1831 "Assumes sizeof(wchar) on target is <= 64");
1832
1833 SmallVector<uint32_t, 4> codepoint_buffer;
1834 codepoint_buffer.resize(end - begin);
1835 uint32_t *buffer_begin = &codepoint_buffer.front();
1836 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1837
1838 // Unicode escapes representing characters that cannot be correctly
1839 // represented in a single code unit are disallowed in character literals
1840 // by this implementation.
1841 uint32_t largest_character_for_kind;
1842 if (tok::wide_char_constant == Kind) {
1843 largest_character_for_kind =
1844 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1845 } else if (tok::utf8_char_constant == Kind) {
1846 largest_character_for_kind = 0x7F;
1847 } else if (tok::utf16_char_constant == Kind) {
1848 largest_character_for_kind = 0xFFFF;
1849 } else if (tok::utf32_char_constant == Kind) {
1850 largest_character_for_kind = 0x10FFFF;
1851 } else {
1852 largest_character_for_kind = 0x7Fu;
1853 }
1854
1855 while (begin != end) {
1856 // Is this a span of non-escape characters?
1857 if (begin[0] != '\\') {
1858 char const *start = begin;
1859 do {
1860 ++begin;
1861 } while (begin != end && *begin != '\\');
1862
1863 char const *tmp_in_start = start;
1864 uint32_t *tmp_out_start = buffer_begin;
1865 llvm::ConversionResult res =
1866 llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
1867 reinterpret_cast<llvm::UTF8 const *>(begin),
1868 &buffer_begin, buffer_end, llvm::strictConversion);
1869 if (res != llvm::conversionOK) {
1870 // If we see bad encoding for unprefixed character literals, warn and
1871 // simply copy the byte values, for compatibility with gcc and
1872 // older versions of clang.
1873 bool NoErrorOnBadEncoding = isOrdinary();
1874 unsigned Msg = diag::err_bad_character_encoding;
1875 if (NoErrorOnBadEncoding)
1876 Msg = diag::warn_bad_character_encoding;
1877 PP.Diag(Loc, Msg);
1878 if (NoErrorOnBadEncoding) {
1879 start = tmp_in_start;
1880 buffer_begin = tmp_out_start;
1881 for (; start != begin; ++start, ++buffer_begin)
1882 *buffer_begin = static_cast<uint8_t>(*start);
1883 } else {
1884 HadError = true;
1885 }
1886 } else {
1887 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1888 if (*tmp_out_start > largest_character_for_kind) {
1889 HadError = true;
1890 PP.Diag(Loc, diag::err_character_too_large);
1891 }
1892 }
1893 }
1894
1895 continue;
1896 }
1897 // Is this a Universal Character Name escape?
1898 if (begin[1] == 'u' || begin[1] == 'U' || begin[1] == 'N') {
1899 unsigned short UcnLen = 0;
1900 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1902 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1903 HadError = true;
1904 } else if (*buffer_begin > largest_character_for_kind) {
1905 HadError = true;
1906 PP.Diag(Loc, diag::err_character_too_large);
1907 }
1908
1909 ++buffer_begin;
1910 continue;
1911 }
1912 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1913 uint64_t result =
1914 ProcessCharEscape(TokBegin, begin, end, HadError,
1915 FullSourceLoc(Loc, PP.getSourceManager()), CharWidth,
1916 &PP.getDiagnostics(), PP.getLangOpts(),
1918 *buffer_begin++ = result;
1919 }
1920
1921 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1922
1923 if (NumCharsSoFar > 1) {
1924 if (isOrdinary() && NumCharsSoFar == 4)
1925 PP.Diag(Loc, diag::warn_four_char_character_literal);
1926 else if (isOrdinary())
1927 PP.Diag(Loc, diag::warn_multichar_character_literal);
1928 else {
1929 PP.Diag(Loc, diag::err_multichar_character_literal) << (isWide() ? 0 : 1);
1930 HadError = true;
1931 }
1932 IsMultiChar = true;
1933 } else {
1934 IsMultiChar = false;
1935 }
1936
1937 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1938
1939 // Narrow character literals act as though their value is concatenated
1940 // in this implementation, but warn on overflow.
1941 bool multi_char_too_long = false;
1942 if (isOrdinary() && isMultiChar()) {
1943 LitVal = 0;
1944 for (size_t i = 0; i < NumCharsSoFar; ++i) {
1945 // check for enough leading zeros to shift into
1946 multi_char_too_long |= (LitVal.countl_zero() < 8);
1947 LitVal <<= 8;
1948 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1949 }
1950 } else if (NumCharsSoFar > 0) {
1951 // otherwise just take the last character
1952 LitVal = buffer_begin[-1];
1953 }
1954
1955 if (!HadError && multi_char_too_long) {
1956 PP.Diag(Loc, diag::warn_char_constant_too_large);
1957 }
1958
1959 // Transfer the value from APInt to uint64_t
1960 Value = LitVal.getZExtValue();
1961
1962 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1963 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1964 // character constants are not sign extended in the this implementation:
1965 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1966 if (isOrdinary() && NumCharsSoFar == 1 && (Value & 128) &&
1967 PP.getLangOpts().CharIsSigned)
1968 Value = (signed char)Value;
1969}
1970
1971/// \verbatim
1972/// string-literal: [C++0x lex.string]
1973/// encoding-prefix " [s-char-sequence] "
1974/// encoding-prefix R raw-string
1975/// encoding-prefix:
1976/// u8
1977/// u
1978/// U
1979/// L
1980/// s-char-sequence:
1981/// s-char
1982/// s-char-sequence s-char
1983/// s-char:
1984/// any member of the source character set except the double-quote ",
1985/// backslash \, or new-line character
1986/// escape-sequence
1987/// universal-character-name
1988/// raw-string:
1989/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1990/// r-char-sequence:
1991/// r-char
1992/// r-char-sequence r-char
1993/// r-char:
1994/// any member of the source character set, except a right parenthesis )
1995/// followed by the initial d-char-sequence (which may be empty)
1996/// followed by a double quote ".
1997/// d-char-sequence:
1998/// d-char
1999/// d-char-sequence d-char
2000/// d-char:
2001/// any member of the basic source character set except:
2002/// space, the left parenthesis (, the right parenthesis ),
2003/// the backslash \, and the control characters representing horizontal
2004/// tab, vertical tab, form feed, and newline.
2005/// escape-sequence: [C++0x lex.ccon]
2006/// simple-escape-sequence
2007/// octal-escape-sequence
2008/// hexadecimal-escape-sequence
2009/// simple-escape-sequence:
2010/// one of \' \" \? \\ \a \b \f \n \r \t \v
2011/// octal-escape-sequence:
2012/// \ octal-digit
2013/// \ octal-digit octal-digit
2014/// \ octal-digit octal-digit octal-digit
2015/// hexadecimal-escape-sequence:
2016/// \x hexadecimal-digit
2017/// hexadecimal-escape-sequence hexadecimal-digit
2018/// universal-character-name:
2019/// \u hex-quad
2020/// \U hex-quad hex-quad
2021/// hex-quad:
2022/// hex-digit hex-digit hex-digit hex-digit
2023/// \endverbatim
2024///
2026 Preprocessor &PP,
2027 StringLiteralEvalMethod EvalMethod)
2028 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
2029 Target(PP.getTargetInfo()), Diags(&PP.getDiagnostics()),
2030 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
2031 ResultPtr(ResultBuf.data()), EvalMethod(EvalMethod), hadError(false),
2032 Pascal(false) {
2033 init(StringToks);
2034}
2035
2036void StringLiteralParser::init(ArrayRef<Token> StringToks){
2037 // The literal token may have come from an invalid source location (e.g. due
2038 // to a PCH error), in which case the token length will be 0.
2039 if (StringToks.empty() || StringToks[0].getLength() < 2)
2040 return DiagnoseLexingError(SourceLocation());
2041
2042 // Scan all of the string portions, remember the max individual token length,
2043 // computing a bound on the concatenated string length, and see whether any
2044 // piece is a wide-string. If any of the string portions is a wide-string
2045 // literal, the result is a wide-string literal [C99 6.4.5p4].
2046 assert(!StringToks.empty() && "expected at least one token");
2047 MaxTokenLength = StringToks[0].getLength();
2048 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
2049 SizeBound = StringToks[0].getLength() - 2; // -2 for "".
2050 hadError = false;
2051
2052 // Determines the kind of string from the prefix
2053 Kind = tok::string_literal;
2054
2055 /// (C99 5.1.1.2p1). The common case is only one string fragment.
2056 for (const Token &Tok : StringToks) {
2057 if (Tok.getLength() < 2)
2058 return DiagnoseLexingError(Tok.getLocation());
2059
2060 // The string could be shorter than this if it needs cleaning, but this is a
2061 // reasonable bound, which is all we need.
2062 assert(Tok.getLength() >= 2 && "literal token is invalid!");
2063 SizeBound += Tok.getLength() - 2; // -2 for "".
2064
2065 // Remember maximum string piece length.
2066 if (Tok.getLength() > MaxTokenLength)
2067 MaxTokenLength = Tok.getLength();
2068
2069 // Remember if we see any wide or utf-8/16/32 strings.
2070 // Also check for illegal concatenations.
2071 if (isUnevaluated() && Tok.getKind() != tok::string_literal) {
2072 if (Diags) {
2074 Tok.getLocation(), getEncodingPrefixLen(Tok.getKind()), SM,
2075 Features);
2076 CharSourceRange Range =
2077 CharSourceRange::getCharRange({Tok.getLocation(), PrefixEndLoc});
2078 StringRef Prefix(SM.getCharacterData(Tok.getLocation()),
2079 getEncodingPrefixLen(Tok.getKind()));
2080 Diags->Report(Tok.getLocation(),
2081 Features.CPlusPlus26
2082 ? diag::err_unevaluated_string_prefix
2083 : diag::warn_unevaluated_string_prefix)
2084 << Prefix << Features.CPlusPlus << FixItHint::CreateRemoval(Range);
2085 }
2086 if (Features.CPlusPlus26)
2087 hadError = true;
2088 } else if (Tok.isNot(Kind) && Tok.isNot(tok::string_literal)) {
2089 if (isOrdinary()) {
2090 Kind = Tok.getKind();
2091 } else {
2092 if (Diags)
2093 Diags->Report(Tok.getLocation(), diag::err_unsupported_string_concat);
2094 hadError = true;
2095 }
2096 }
2097 }
2098
2099 // Include space for the null terminator.
2100 ++SizeBound;
2101
2102 // TODO: K&R warning: "traditional C rejects string constant concatenation"
2103
2104 // Get the width in bytes of char/wchar_t/char16_t/char32_t
2105 CharByteWidth = getCharWidth(Kind, Target);
2106 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
2107 CharByteWidth /= 8;
2108
2109 // The output buffer size needs to be large enough to hold wide characters.
2110 // This is a worst-case assumption which basically corresponds to L"" "long".
2111 SizeBound *= CharByteWidth;
2112
2113 // Size the temporary buffer to hold the result string data.
2114 ResultBuf.resize(SizeBound);
2115
2116 // Likewise, but for each string piece.
2117 SmallString<512> TokenBuf;
2118 TokenBuf.resize(MaxTokenLength);
2119
2120 // Loop over all the strings, getting their spelling, and expanding them to
2121 // wide strings as appropriate.
2122 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
2123
2124 Pascal = false;
2125
2126 SourceLocation UDSuffixTokLoc;
2127
2128 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
2129 const char *ThisTokBuf = &TokenBuf[0];
2130 // Get the spelling of the token, which eliminates trigraphs, etc. We know
2131 // that ThisTokBuf points to a buffer that is big enough for the whole token
2132 // and 'spelled' tokens can only shrink.
2133 bool StringInvalid = false;
2134 unsigned ThisTokLen =
2135 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
2136 &StringInvalid);
2137 if (StringInvalid)
2138 return DiagnoseLexingError(StringToks[i].getLocation());
2139
2140 const char *ThisTokBegin = ThisTokBuf;
2141 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
2142
2143 // Remove an optional ud-suffix.
2144 if (ThisTokEnd[-1] != '"') {
2145 const char *UDSuffixEnd = ThisTokEnd;
2146 do {
2147 --ThisTokEnd;
2148 } while (ThisTokEnd[-1] != '"');
2149
2150 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
2151
2152 if (UDSuffixBuf.empty()) {
2153 if (StringToks[i].hasUCN())
2154 expandUCNs(UDSuffixBuf, UDSuffix);
2155 else
2156 UDSuffixBuf.assign(UDSuffix);
2157 UDSuffixToken = i;
2158 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
2159 UDSuffixTokLoc = StringToks[i].getLocation();
2160 } else {
2161 SmallString<32> ExpandedUDSuffix;
2162 if (StringToks[i].hasUCN()) {
2163 expandUCNs(ExpandedUDSuffix, UDSuffix);
2164 UDSuffix = ExpandedUDSuffix;
2165 }
2166
2167 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
2168 // result of a concatenation involving at least one user-defined-string-
2169 // literal, all the participating user-defined-string-literals shall
2170 // have the same ud-suffix.
2171 bool UnevaluatedStringHasUDL = isUnevaluated() && !UDSuffix.empty();
2172 if (UDSuffixBuf != UDSuffix || UnevaluatedStringHasUDL) {
2173 if (Diags) {
2174 SourceLocation TokLoc = StringToks[i].getLocation();
2175 if (UnevaluatedStringHasUDL) {
2176 Diags->Report(TokLoc, diag::err_unevaluated_string_udl)
2177 << SourceRange(TokLoc, TokLoc);
2178 } else {
2179 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
2180 << UDSuffixBuf << UDSuffix
2181 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc);
2182 }
2183 }
2184 hadError = true;
2185 }
2186 }
2187 }
2188
2189 // Strip the end quote.
2190 --ThisTokEnd;
2191
2192 // TODO: Input character set mapping support.
2193
2194 // Skip marker for wide or unicode strings.
2195 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
2196 ++ThisTokBuf;
2197 // Skip 8 of u8 marker for utf8 strings.
2198 if (ThisTokBuf[0] == '8')
2199 ++ThisTokBuf;
2200 }
2201
2202 // Check for raw string
2203 if (ThisTokBuf[0] == 'R') {
2204 if (ThisTokBuf[1] != '"') {
2205 // The file may have come from PCH and then changed after loading the
2206 // PCH; Fail gracefully.
2207 return DiagnoseLexingError(StringToks[i].getLocation());
2208 }
2209 ThisTokBuf += 2; // skip R"
2210
2211 // C++11 [lex.string]p2: A `d-char-sequence` shall consist of at most 16
2212 // characters.
2213 constexpr unsigned MaxRawStrDelimLen = 16;
2214
2215 const char *Prefix = ThisTokBuf;
2216 while (static_cast<unsigned>(ThisTokBuf - Prefix) < MaxRawStrDelimLen &&
2217 ThisTokBuf[0] != '(')
2218 ++ThisTokBuf;
2219 if (ThisTokBuf[0] != '(')
2220 return DiagnoseLexingError(StringToks[i].getLocation());
2221 ++ThisTokBuf; // skip '('
2222
2223 // Remove same number of characters from the end
2224 ThisTokEnd -= ThisTokBuf - Prefix;
2225 if (ThisTokEnd < ThisTokBuf)
2226 return DiagnoseLexingError(StringToks[i].getLocation());
2227
2228 // C++14 [lex.string]p4: A source-file new-line in a raw string literal
2229 // results in a new-line in the resulting execution string-literal.
2230 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
2231 while (!RemainingTokenSpan.empty()) {
2232 // Split the string literal on \r\n boundaries.
2233 size_t CRLFPos = RemainingTokenSpan.find("\r\n");
2234 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
2235 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
2236
2237 // Copy everything before the \r\n sequence into the string literal.
2238 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
2239 hadError = true;
2240
2241 // Point into the \n inside the \r\n sequence and operate on the
2242 // remaining portion of the literal.
2243 RemainingTokenSpan = AfterCRLF.substr(1);
2244 }
2245 } else {
2246 if (ThisTokBuf[0] != '"') {
2247 // The file may have come from PCH and then changed after loading the
2248 // PCH; Fail gracefully.
2249 return DiagnoseLexingError(StringToks[i].getLocation());
2250 }
2251 ++ThisTokBuf; // skip "
2252
2253 // Check if this is a pascal string
2254 if (!isUnevaluated() && Features.PascalStrings &&
2255 ThisTokBuf + 1 != ThisTokEnd && ThisTokBuf[0] == '\\' &&
2256 ThisTokBuf[1] == 'p') {
2257
2258 // If the \p sequence is found in the first token, we have a pascal string
2259 // Otherwise, if we already have a pascal string, ignore the first \p
2260 if (i == 0) {
2261 ++ThisTokBuf;
2262 Pascal = true;
2263 } else if (Pascal)
2264 ThisTokBuf += 2;
2265 }
2266
2267 while (ThisTokBuf != ThisTokEnd) {
2268 // Is this a span of non-escape characters?
2269 if (ThisTokBuf[0] != '\\') {
2270 const char *InStart = ThisTokBuf;
2271 do {
2272 ++ThisTokBuf;
2273 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
2274
2275 // Copy the character span over.
2276 if (CopyStringFragment(StringToks[i], ThisTokBegin,
2277 StringRef(InStart, ThisTokBuf - InStart)))
2278 hadError = true;
2279 continue;
2280 }
2281 // Is this a Universal Character Name escape?
2282 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U' ||
2283 ThisTokBuf[1] == 'N') {
2284 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
2285 ResultPtr, hadError,
2286 FullSourceLoc(StringToks[i].getLocation(), SM),
2287 CharByteWidth, Diags, Features);
2288 continue;
2289 }
2290 // Otherwise, this is a non-UCN escape character. Process it.
2291 unsigned ResultChar =
2292 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
2293 FullSourceLoc(StringToks[i].getLocation(), SM),
2294 CharByteWidth * 8, Diags, Features, EvalMethod);
2295
2296 if (CharByteWidth == 4) {
2297 // FIXME: Make the type of the result buffer correct instead of
2298 // using reinterpret_cast.
2299 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
2300 *ResultWidePtr = ResultChar;
2301 ResultPtr += 4;
2302 } else if (CharByteWidth == 2) {
2303 // FIXME: Make the type of the result buffer correct instead of
2304 // using reinterpret_cast.
2305 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
2306 *ResultWidePtr = ResultChar & 0xFFFF;
2307 ResultPtr += 2;
2308 } else {
2309 assert(CharByteWidth == 1 && "Unexpected char width");
2310 *ResultPtr++ = ResultChar & 0xFF;
2311 }
2312 }
2313 }
2314 }
2315
2316 assert((!Pascal || !isUnevaluated()) &&
2317 "Pascal string in unevaluated context");
2318 if (Pascal) {
2319 if (CharByteWidth == 4) {
2320 // FIXME: Make the type of the result buffer correct instead of
2321 // using reinterpret_cast.
2322 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
2323 ResultWidePtr[0] = GetNumStringChars() - 1;
2324 } else if (CharByteWidth == 2) {
2325 // FIXME: Make the type of the result buffer correct instead of
2326 // using reinterpret_cast.
2327 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
2328 ResultWidePtr[0] = GetNumStringChars() - 1;
2329 } else {
2330 assert(CharByteWidth == 1 && "Unexpected char width");
2331 ResultBuf[0] = GetNumStringChars() - 1;
2332 }
2333
2334 // Verify that pascal strings aren't too large.
2335 if (GetStringLength() > 256) {
2336 if (Diags)
2337 Diags->Report(StringToks.front().getLocation(),
2338 diag::err_pascal_string_too_long)
2339 << SourceRange(StringToks.front().getLocation(),
2340 StringToks.back().getLocation());
2341 hadError = true;
2342 return;
2343 }
2344 } else if (Diags) {
2345 // Complain if this string literal has too many characters.
2346 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
2347
2348 if (GetNumStringChars() > MaxChars)
2349 Diags->Report(StringToks.front().getLocation(),
2350 diag::ext_string_too_long)
2351 << GetNumStringChars() << MaxChars
2352 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
2353 << SourceRange(StringToks.front().getLocation(),
2354 StringToks.back().getLocation());
2355 }
2356}
2357
2358static const char *resyncUTF8(const char *Err, const char *End) {
2359 if (Err == End)
2360 return End;
2361 End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
2362 while (++Err != End && (*Err & 0xC0) == 0x80)
2363 ;
2364 return Err;
2365}
2366
2367/// This function copies from Fragment, which is a sequence of bytes
2368/// within Tok's contents (which begin at TokBegin) into ResultPtr.
2369/// Performs widening for multi-byte characters.
2370bool StringLiteralParser::CopyStringFragment(const Token &Tok,
2371 const char *TokBegin,
2372 StringRef Fragment) {
2373 const llvm::UTF8 *ErrorPtrTmp;
2374 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
2375 return false;
2376
2377 // If we see bad encoding for unprefixed string literals, warn and
2378 // simply copy the byte values, for compatibility with gcc and older
2379 // versions of clang.
2380 bool NoErrorOnBadEncoding = isOrdinary();
2381 if (NoErrorOnBadEncoding) {
2382 memcpy(ResultPtr, Fragment.data(), Fragment.size());
2383 ResultPtr += Fragment.size();
2384 }
2385
2386 if (Diags) {
2387 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
2388
2389 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
2390 const DiagnosticBuilder &Builder =
2391 Diag(Diags, Features, SourceLoc, TokBegin,
2392 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
2393 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
2394 : diag::err_bad_string_encoding);
2395
2396 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
2397 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
2398
2399 // Decode into a dummy buffer.
2400 SmallString<512> Dummy;
2401 Dummy.reserve(Fragment.size() * CharByteWidth);
2402 char *Ptr = Dummy.data();
2403
2404 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
2405 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
2406 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
2407 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
2408 ErrorPtr, NextStart);
2409 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
2410 }
2411 }
2412 return !NoErrorOnBadEncoding;
2413}
2414
2415void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
2416 hadError = true;
2417 if (Diags)
2418 Diags->Report(Loc, diag::err_lexing_string);
2419}
2420
2421/// getOffsetOfStringByte - This function returns the offset of the
2422/// specified byte of the string data represented by Token. This handles
2423/// advancing over escape sequences in the string.
2425 unsigned ByteNo) const {
2426 // Get the spelling of the token.
2427 SmallString<32> SpellingBuffer;
2428 SpellingBuffer.resize(Tok.getLength());
2429
2430 bool StringInvalid = false;
2431 const char *SpellingPtr = &SpellingBuffer[0];
2432 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
2433 &StringInvalid);
2434 if (StringInvalid)
2435 return 0;
2436
2437 const char *SpellingStart = SpellingPtr;
2438 const char *SpellingEnd = SpellingPtr+TokLen;
2439
2440 // Handle UTF-8 strings just like narrow strings.
2441 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
2442 SpellingPtr += 2;
2443
2444 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
2445 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
2446
2447 // For raw string literals, this is easy.
2448 if (SpellingPtr[0] == 'R') {
2449 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
2450 // Skip 'R"'.
2451 SpellingPtr += 2;
2452 while (*SpellingPtr != '(') {
2453 ++SpellingPtr;
2454 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
2455 }
2456 // Skip '('.
2457 ++SpellingPtr;
2458 return SpellingPtr - SpellingStart + ByteNo;
2459 }
2460
2461 // Skip over the leading quote
2462 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
2463 ++SpellingPtr;
2464
2465 // Skip over bytes until we find the offset we're looking for.
2466 while (ByteNo) {
2467 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
2468
2469 // Step over non-escapes simply.
2470 if (*SpellingPtr != '\\') {
2471 ++SpellingPtr;
2472 --ByteNo;
2473 continue;
2474 }
2475
2476 // Otherwise, this is an escape character. Advance over it.
2477 bool HadError = false;
2478 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U' ||
2479 SpellingPtr[1] == 'N') {
2480 const char *EscapePtr = SpellingPtr;
2481 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
2482 1, Features, HadError);
2483 if (Len > ByteNo) {
2484 // ByteNo is somewhere within the escape sequence.
2485 SpellingPtr = EscapePtr;
2486 break;
2487 }
2488 ByteNo -= Len;
2489 } else {
2490 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
2491 FullSourceLoc(Tok.getLocation(), SM), CharByteWidth * 8,
2492 Diags, Features, StringLiteralEvalMethod::Evaluated);
2493 --ByteNo;
2494 }
2495 assert(!HadError && "This method isn't valid on erroneous strings");
2496 }
2497
2498 return SpellingPtr-SpellingStart;
2499}
2500
2501/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
2502/// suffixes as ud-suffixes, because the diagnostic experience is better if we
2503/// treat it as an invalid suffix.
2505 StringRef Suffix) {
2506 return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||
2507 Suffix == "sv";
2508}
Token Tok
The Token.
Defines the clang::LangOptions interface.
static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, char *&ResultBuf, bool &HadError, FullSourceLoc Loc, unsigned CharByteWidth, DiagnosticsEngine *Diags, const LangOptions &Features)
EncodeUCNEscape - Read the Universal Character Name, check constraints and convert the UTF32 to UTF8 ...
static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features, bool in_char_string_literal=false)
ProcessUCNEscape - Read the Universal Character Name, check constraints and return the UTF32.
static CharSourceRange MakeCharSourceRange(const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd)
static const char * resyncUTF8(const char *Err, const char *End)
static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, unsigned CharByteWidth, const LangOptions &Features, bool &HadError)
MeasureUCNEscape - Determine the number of bytes within the resulting string which this UCN will occu...
static void appendCodePoint(unsigned Codepoint, llvm::SmallVectorImpl< char > &Str)
static unsigned getEncodingPrefixLen(tok::TokenKind kind)
static void DiagnoseInvalidUnicodeCharacterName(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc Loc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, llvm::StringRef Name)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static bool IsEscapeValidInUnevaluatedStringLiteral(char Escape)
static bool ProcessNumericUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, bool &Delimited, FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features, bool in_char_string_literal=false)
static bool allowedInCharacterName(char C)
static bool ProcessNamedUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features)
static bool IsExponentPart(char c, bool isHex)
static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits)
static unsigned ProcessCharEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, bool &HadError, FullSourceLoc Loc, unsigned CharWidth, DiagnosticsEngine *Diags, const LangOptions &Features, StringLiteralEvalMethod EvalMethod)
ProcessCharEscape - Parse a standard C escape sequence, which can occur in either a character or a st...
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Target Target
Definition MachO.h:51
#define SM(sm)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
CharLiteralParser(const char *begin, const char *end, SourceLocation Loc, Preprocessor &PP, tok::TokenKind kind)
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
A SourceLocation and its associated SourceManager.
const SourceManager & getManager() const
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:407
static void DiagnoseDelimitedOrNamedEscapeSequence(SourceLocation Loc, bool Named, const LangOptions &Opts, DiagnosticsEngine &Diags)
Diagnose use of a delimited or named escape sequence.
Definition Lexer.cpp:3463
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
Definition Lexer.cpp:461
NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc, const SourceManager &SM, const LangOptions &LangOpts, const TargetInfo &Target, DiagnosticsEngine &Diags)
integer-constant: [C99 6.4.4.1] decimal-constant integer-suffix octal-constant integer-suffix hexadec...
llvm::APFloat::opStatus GetFloatValue(llvm::APFloat &Result, llvm::RoundingMode RM)
Convert this numeric literal to a floating value, using the specified APFloat fltSemantics (specifyin...
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
bool GetIntegerValue(llvm::APInt &Val)
GetIntegerValue - Convert this numeric literal value to an APInt that matches Val's input width.
bool GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale)
GetFixedPointValue - Convert this numeric literal value into a scaled integer that represents this va...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
SourceManager & getSourceManager() const
const TargetInfo & getTargetInfo() const
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Encodes a location in the source.
This class handles loading and caching of source files into memory.
unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) const
getOffsetOfStringByte - This function returns the offset of the specified byte of the string data rep...
StringLiteralParser(ArrayRef< Token > StringToks, Preprocessor &PP, StringLiteralEvalMethod StringMethod=StringLiteralEvalMethod::Evaluated)
unsigned GetStringLength() const
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
unsigned GetNumStringChars() const
Exposes information about the current target.
Definition TargetInfo.h:227
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition TargetInfo.h:531
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of 'wchar_t' for this target, in bits.
Definition TargetInfo.h:773
unsigned getCharWidth() const
Definition TargetInfo.h:521
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
tok::TokenKind getKind() const
Definition Token.h:99
bool isNot(tok::TokenKind K) const
Definition Token.h:111
Defines the clang::TargetInfo interface.
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:93
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
Definition CharInfo.h:99
LLVM_READONLY bool isPrintable(unsigned char c)
Return true if this character is an ASCII printable character; that is, a character that should take ...
Definition CharInfo.h:160
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void expandUCNs(SmallVectorImpl< char > &Buf, StringRef Input)
Copy characters from Input to Buf, expanding any UCNs.
bool tokenIsLikeStringLiteral(const Token &Tok, const LangOptions &LO)
Return true if the token is a string literal, or a function local predefined macro,...
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition CharInfo.h:114
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
LLVM_READONLY bool isPreprocessingNumberBody(unsigned char c)
Return true if this is the body character of a C preprocessing number, which is [a-zA-Z0-9_.
Definition CharInfo.h:168
llvm::SmallString< 16 > DisplayCodePointForDiagnostic(llvm::UTF32 CodePoint)
Displays a single Unicode codepoint in U+NNNN notation, optionally prepending the quoted codepoint it...
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
Definition CharInfo.h:144
StringLiteralEvalMethod
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define false
Definition stdbool.h:26