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