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