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