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