1 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the NumericLiteralParser, CharLiteralParser, and 11 // StringLiteralParser interfaces. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/LiteralSupport.h" 16 #include "clang/Basic/CharInfo.h" 17 #include "clang/Basic/LangOptions.h" 18 #include "clang/Basic/SourceLocation.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Lex/LexDiagnostic.h" 21 #include "clang/Lex/Lexer.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Lex/Token.h" 24 #include "llvm/ADT/APInt.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/Support/ConvertUTF.h" 29 #include "llvm/Support/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 isFPConstant = isFloatingLiteral(); 587 588 // Loop over all of the characters of the suffix. If we see something bad, 589 // we break out of the loop. 590 for (; s != ThisTokEnd; ++s) { 591 switch (*s) { 592 case 'R': 593 case 'r': 594 if (!PP.getLangOpts().FixedPoint) break; 595 if (isFract || isAccum) break; 596 if (!(saw_period || saw_exponent)) break; 597 isFract = true; 598 continue; 599 case 'K': 600 case 'k': 601 if (!PP.getLangOpts().FixedPoint) break; 602 if (isFract || isAccum) break; 603 if (!(saw_period || saw_exponent)) break; 604 isAccum = true; 605 continue; 606 case 'h': // FP Suffix for "half". 607 case 'H': 608 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type. 609 if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break; 610 if (isIntegerLiteral()) break; // Error for integer constant. 611 if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid. 612 isHalf = true; 613 continue; // Success. 614 case 'f': // FP Suffix for "float" 615 case 'F': 616 if (!isFPConstant) break; // Error for integer constant. 617 if (isHalf || isFloat || isLong || isFloat128) 618 break; // HF, FF, LF, QF invalid. 619 620 if (s + 2 < ThisTokEnd && s[1] == '1' && s[2] == '6') { 621 s += 2; // success, eat up 2 characters. 622 isFloat16 = true; 623 continue; 624 } 625 626 isFloat = true; 627 continue; // Success. 628 case 'q': // FP Suffix for "__float128" 629 case 'Q': 630 if (!isFPConstant) break; // Error for integer constant. 631 if (isHalf || isFloat || isLong || isFloat128) 632 break; // HQ, FQ, LQ, QQ invalid. 633 isFloat128 = true; 634 continue; // Success. 635 case 'u': 636 case 'U': 637 if (isFPConstant) break; // Error for floating constant. 638 if (isUnsigned) break; // Cannot be repeated. 639 isUnsigned = true; 640 continue; // Success. 641 case 'l': 642 case 'L': 643 if (isLong || isLongLong) break; // Cannot be repeated. 644 if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid. 645 646 // Check for long long. The L's need to be adjacent and the same case. 647 if (s[1] == s[0]) { 648 assert(s + 1 < ThisTokEnd && "didn't maximally munch?"); 649 if (isFPConstant) break; // long long invalid for floats. 650 isLongLong = true; 651 ++s; // Eat both of them. 652 } else { 653 isLong = true; 654 } 655 continue; // Success. 656 case 'i': 657 case 'I': 658 if (PP.getLangOpts().MicrosoftExt) { 659 if (isLong || isLongLong || MicrosoftInteger) 660 break; 661 662 if (!isFPConstant) { 663 // Allow i8, i16, i32, and i64. 664 switch (s[1]) { 665 case '8': 666 s += 2; // i8 suffix 667 MicrosoftInteger = 8; 668 break; 669 case '1': 670 if (s[2] == '6') { 671 s += 3; // i16 suffix 672 MicrosoftInteger = 16; 673 } 674 break; 675 case '3': 676 if (s[2] == '2') { 677 s += 3; // i32 suffix 678 MicrosoftInteger = 32; 679 } 680 break; 681 case '6': 682 if (s[2] == '4') { 683 s += 3; // i64 suffix 684 MicrosoftInteger = 64; 685 } 686 break; 687 default: 688 break; 689 } 690 } 691 if (MicrosoftInteger) { 692 assert(s <= ThisTokEnd && "didn't maximally munch?"); 693 break; 694 } 695 } 696 // fall through. 697 case 'j': 698 case 'J': 699 if (isImaginary) break; // Cannot be repeated. 700 isImaginary = true; 701 continue; // Success. 702 } 703 // If we reached here, there was an error or a ud-suffix. 704 break; 705 } 706 707 // "i", "if", and "il" are user-defined suffixes in C++1y. 708 if (s != ThisTokEnd || isImaginary) { 709 // FIXME: Don't bother expanding UCNs if !tok.hasUCN(). 710 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)); 711 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) { 712 if (!isImaginary) { 713 // Any suffix pieces we might have parsed are actually part of the 714 // ud-suffix. 715 isLong = false; 716 isUnsigned = false; 717 isLongLong = false; 718 isFloat = false; 719 isFloat16 = false; 720 isHalf = false; 721 isImaginary = false; 722 MicrosoftInteger = 0; 723 saw_fixed_point_suffix = false; 724 isFract = false; 725 isAccum = false; 726 } 727 728 saw_ud_suffix = true; 729 return; 730 } 731 732 if (s != ThisTokEnd) { 733 // Report an error if there are any. 734 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin), 735 diag::err_invalid_suffix_constant) 736 << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant; 737 hadError = true; 738 } 739 } 740 741 if (!hadError && saw_fixed_point_suffix) { 742 assert(isFract || isAccum); 743 } 744 } 745 746 /// ParseDecimalOrOctalCommon - This method is called for decimal or octal 747 /// numbers. It issues an error for illegal digits, and handles floating point 748 /// parsing. If it detects a floating point number, the radix is set to 10. 749 void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){ 750 assert((radix == 8 || radix == 10) && "Unexpected radix"); 751 752 // If we have a hex digit other than 'e' (which denotes a FP exponent) then 753 // the code is using an incorrect base. 754 if (isHexDigit(*s) && *s != 'e' && *s != 'E') { 755 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 756 diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0); 757 hadError = true; 758 return; 759 } 760 761 if (*s == '.') { 762 checkSeparator(TokLoc, s, CSK_AfterDigits); 763 s++; 764 radix = 10; 765 saw_period = true; 766 checkSeparator(TokLoc, s, CSK_BeforeDigits); 767 s = SkipDigits(s); // Skip suffix. 768 } 769 if (*s == 'e' || *s == 'E') { // exponent 770 checkSeparator(TokLoc, s, CSK_AfterDigits); 771 const char *Exponent = s; 772 s++; 773 radix = 10; 774 saw_exponent = true; 775 if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign 776 const char *first_non_digit = SkipDigits(s); 777 if (containsDigits(s, first_non_digit)) { 778 checkSeparator(TokLoc, s, CSK_BeforeDigits); 779 s = first_non_digit; 780 } else { 781 if (!hadError) { 782 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), 783 diag::err_exponent_has_no_digits); 784 hadError = true; 785 } 786 return; 787 } 788 } 789 } 790 791 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved 792 /// suffixes as ud-suffixes, because the diagnostic experience is better if we 793 /// treat it as an invalid suffix. 794 bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts, 795 StringRef Suffix) { 796 if (!LangOpts.CPlusPlus11 || Suffix.empty()) 797 return false; 798 799 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid. 800 if (Suffix[0] == '_') 801 return true; 802 803 // In C++11, there are no library suffixes. 804 if (!LangOpts.CPlusPlus14) 805 return false; 806 807 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library. 808 // Per tweaked N3660, "il", "i", and "if" are also used in the library. 809 return llvm::StringSwitch<bool>(Suffix) 810 .Cases("h", "min", "s", true) 811 .Cases("ms", "us", "ns", true) 812 .Cases("il", "i", "if", true) 813 .Default(false); 814 } 815 816 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc, 817 const char *Pos, 818 CheckSeparatorKind IsAfterDigits) { 819 if (IsAfterDigits == CSK_AfterDigits) { 820 if (Pos == ThisTokBegin) 821 return; 822 --Pos; 823 } else if (Pos == ThisTokEnd) 824 return; 825 826 if (isDigitSeparator(*Pos)) { 827 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin), 828 diag::err_digit_separator_not_between_digits) 829 << IsAfterDigits; 830 hadError = true; 831 } 832 } 833 834 /// ParseNumberStartingWithZero - This method is called when the first character 835 /// of the number is found to be a zero. This means it is either an octal 836 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or 837 /// a floating point number (01239.123e4). Eat the prefix, determining the 838 /// radix etc. 839 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { 840 assert(s[0] == '0' && "Invalid method call"); 841 s++; 842 843 int c1 = s[0]; 844 845 // Handle a hex number like 0x1234. 846 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) { 847 s++; 848 assert(s < ThisTokEnd && "didn't maximally munch?"); 849 radix = 16; 850 DigitsBegin = s; 851 s = SkipHexDigits(s); 852 bool HasSignificandDigits = containsDigits(DigitsBegin, s); 853 if (s == ThisTokEnd) { 854 // Done. 855 } else if (*s == '.') { 856 s++; 857 saw_period = true; 858 const char *floatDigitsBegin = s; 859 s = SkipHexDigits(s); 860 if (containsDigits(floatDigitsBegin, s)) 861 HasSignificandDigits = true; 862 if (HasSignificandDigits) 863 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits); 864 } 865 866 if (!HasSignificandDigits) { 867 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), 868 diag::err_hex_constant_requires) 869 << PP.getLangOpts().CPlusPlus << 1; 870 hadError = true; 871 return; 872 } 873 874 // A binary exponent can appear with or with a '.'. If dotted, the 875 // binary exponent is required. 876 if (*s == 'p' || *s == 'P') { 877 checkSeparator(TokLoc, s, CSK_AfterDigits); 878 const char *Exponent = s; 879 s++; 880 saw_exponent = true; 881 if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign 882 const char *first_non_digit = SkipDigits(s); 883 if (!containsDigits(s, first_non_digit)) { 884 if (!hadError) { 885 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), 886 diag::err_exponent_has_no_digits); 887 hadError = true; 888 } 889 return; 890 } 891 checkSeparator(TokLoc, s, CSK_BeforeDigits); 892 s = first_non_digit; 893 894 if (!PP.getLangOpts().HexFloats) 895 PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus 896 ? diag::ext_hex_literal_invalid 897 : diag::ext_hex_constant_invalid); 898 else if (PP.getLangOpts().CPlusPlus17) 899 PP.Diag(TokLoc, diag::warn_cxx17_hex_literal); 900 } else if (saw_period) { 901 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), 902 diag::err_hex_constant_requires) 903 << PP.getLangOpts().CPlusPlus << 0; 904 hadError = true; 905 } 906 return; 907 } 908 909 // Handle simple binary numbers 0b01010 910 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) { 911 // 0b101010 is a C++1y / GCC extension. 912 PP.Diag(TokLoc, 913 PP.getLangOpts().CPlusPlus14 914 ? diag::warn_cxx11_compat_binary_literal 915 : PP.getLangOpts().CPlusPlus 916 ? diag::ext_binary_literal_cxx14 917 : diag::ext_binary_literal); 918 ++s; 919 assert(s < ThisTokEnd && "didn't maximally munch?"); 920 radix = 2; 921 DigitsBegin = s; 922 s = SkipBinaryDigits(s); 923 if (s == ThisTokEnd) { 924 // Done. 925 } else if (isHexDigit(*s)) { 926 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 927 diag::err_invalid_digit) << StringRef(s, 1) << 2; 928 hadError = true; 929 } 930 // Other suffixes will be diagnosed by the caller. 931 return; 932 } 933 934 // For now, the radix is set to 8. If we discover that we have a 935 // floating point constant, the radix will change to 10. Octal floating 936 // point constants are not permitted (only decimal and hexadecimal). 937 radix = 8; 938 DigitsBegin = s; 939 s = SkipOctalDigits(s); 940 if (s == ThisTokEnd) 941 return; // Done, simple octal number like 01234 942 943 // If we have some other non-octal digit that *is* a decimal digit, see if 944 // this is part of a floating point number like 094.123 or 09e1. 945 if (isDigit(*s)) { 946 const char *EndDecimal = SkipDigits(s); 947 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') { 948 s = EndDecimal; 949 radix = 10; 950 } 951 } 952 953 ParseDecimalOrOctalCommon(TokLoc); 954 } 955 956 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) { 957 switch (Radix) { 958 case 2: 959 return NumDigits <= 64; 960 case 8: 961 return NumDigits <= 64 / 3; // Digits are groups of 3 bits. 962 case 10: 963 return NumDigits <= 19; // floor(log10(2^64)) 964 case 16: 965 return NumDigits <= 64 / 4; // Digits are groups of 4 bits. 966 default: 967 llvm_unreachable("impossible Radix"); 968 } 969 } 970 971 /// GetIntegerValue - Convert this numeric literal value to an APInt that 972 /// matches Val's input width. If there is an overflow, set Val to the low bits 973 /// of the result and return true. Otherwise, return false. 974 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { 975 // Fast path: Compute a conservative bound on the maximum number of 976 // bits per digit in this radix. If we can't possibly overflow a 977 // uint64 based on that bound then do the simple conversion to 978 // integer. This avoids the expensive overflow checking below, and 979 // handles the common cases that matter (small decimal integers and 980 // hex/octal values which don't overflow). 981 const unsigned NumDigits = SuffixBegin - DigitsBegin; 982 if (alwaysFitsInto64Bits(radix, NumDigits)) { 983 uint64_t N = 0; 984 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr) 985 if (!isDigitSeparator(*Ptr)) 986 N = N * radix + llvm::hexDigitValue(*Ptr); 987 988 // This will truncate the value to Val's input width. Simply check 989 // for overflow by comparing. 990 Val = N; 991 return Val.getZExtValue() != N; 992 } 993 994 Val = 0; 995 const char *Ptr = DigitsBegin; 996 997 llvm::APInt RadixVal(Val.getBitWidth(), radix); 998 llvm::APInt CharVal(Val.getBitWidth(), 0); 999 llvm::APInt OldVal = Val; 1000 1001 bool OverflowOccurred = false; 1002 while (Ptr < SuffixBegin) { 1003 if (isDigitSeparator(*Ptr)) { 1004 ++Ptr; 1005 continue; 1006 } 1007 1008 unsigned C = llvm::hexDigitValue(*Ptr++); 1009 1010 // If this letter is out of bound for this radix, reject it. 1011 assert(C < radix && "NumericLiteralParser ctor should have rejected this"); 1012 1013 CharVal = C; 1014 1015 // Add the digit to the value in the appropriate radix. If adding in digits 1016 // made the value smaller, then this overflowed. 1017 OldVal = Val; 1018 1019 // Multiply by radix, did overflow occur on the multiply? 1020 Val *= RadixVal; 1021 OverflowOccurred |= Val.udiv(RadixVal) != OldVal; 1022 1023 // Add value, did overflow occur on the value? 1024 // (a + b) ult b <=> overflow 1025 Val += CharVal; 1026 OverflowOccurred |= Val.ult(CharVal); 1027 } 1028 return OverflowOccurred; 1029 } 1030 1031 llvm::APFloat::opStatus 1032 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) { 1033 using llvm::APFloat; 1034 1035 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin); 1036 1037 llvm::SmallString<16> Buffer; 1038 StringRef Str(ThisTokBegin, n); 1039 if (Str.find('\'') != StringRef::npos) { 1040 Buffer.reserve(n); 1041 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer), 1042 &isDigitSeparator); 1043 Str = Buffer; 1044 } 1045 1046 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven); 1047 } 1048 1049 static inline bool IsExponentPart(char c) { 1050 return c == 'p' || c == 'P' || c == 'e' || c == 'E'; 1051 } 1052 1053 bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) { 1054 assert(radix == 16 || radix == 10); 1055 1056 // Find how many digits are needed to store the whole literal. 1057 unsigned NumDigits = SuffixBegin - DigitsBegin; 1058 if (saw_period) --NumDigits; 1059 1060 // Initial scan of the exponent if it exists 1061 bool ExpOverflowOccurred = false; 1062 bool NegativeExponent = false; 1063 const char *ExponentBegin; 1064 uint64_t Exponent = 0; 1065 int64_t BaseShift = 0; 1066 if (saw_exponent) { 1067 const char *Ptr = DigitsBegin; 1068 1069 while (!IsExponentPart(*Ptr)) ++Ptr; 1070 ExponentBegin = Ptr; 1071 ++Ptr; 1072 NegativeExponent = *Ptr == '-'; 1073 if (NegativeExponent) ++Ptr; 1074 1075 unsigned NumExpDigits = SuffixBegin - Ptr; 1076 if (alwaysFitsInto64Bits(radix, NumExpDigits)) { 1077 llvm::StringRef ExpStr(Ptr, NumExpDigits); 1078 llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10); 1079 Exponent = ExpInt.getZExtValue(); 1080 } else { 1081 ExpOverflowOccurred = true; 1082 } 1083 1084 if (NegativeExponent) BaseShift -= Exponent; 1085 else BaseShift += Exponent; 1086 } 1087 1088 // Number of bits needed for decimal literal is 1089 // ceil(NumDigits * log2(10)) Integral part 1090 // + Scale Fractional part 1091 // + ceil(Exponent * log2(10)) Exponent 1092 // -------------------------------------------------- 1093 // ceil((NumDigits + Exponent) * log2(10)) + Scale 1094 // 1095 // But for simplicity in handling integers, we can round up log2(10) to 4, 1096 // making: 1097 // 4 * (NumDigits + Exponent) + Scale 1098 // 1099 // Number of digits needed for hexadecimal literal is 1100 // 4 * NumDigits Integral part 1101 // + Scale Fractional part 1102 // + Exponent Exponent 1103 // -------------------------------------------------- 1104 // (4 * NumDigits) + Scale + Exponent 1105 uint64_t NumBitsNeeded; 1106 if (radix == 10) 1107 NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale; 1108 else 1109 NumBitsNeeded = 4 * NumDigits + Exponent + Scale; 1110 1111 if (NumBitsNeeded > std::numeric_limits<unsigned>::max()) 1112 ExpOverflowOccurred = true; 1113 llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false); 1114 1115 bool FoundDecimal = false; 1116 1117 int64_t FractBaseShift = 0; 1118 const char *End = saw_exponent ? ExponentBegin : SuffixBegin; 1119 for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) { 1120 if (*Ptr == '.') { 1121 FoundDecimal = true; 1122 continue; 1123 } 1124 1125 // Normal reading of an integer 1126 unsigned C = llvm::hexDigitValue(*Ptr); 1127 assert(C < radix && "NumericLiteralParser ctor should have rejected this"); 1128 1129 Val *= radix; 1130 Val += C; 1131 1132 if (FoundDecimal) 1133 // Keep track of how much we will need to adjust this value by from the 1134 // number of digits past the radix point. 1135 --FractBaseShift; 1136 } 1137 1138 // For a radix of 16, we will be multiplying by 2 instead of 16. 1139 if (radix == 16) FractBaseShift *= 4; 1140 BaseShift += FractBaseShift; 1141 1142 Val <<= Scale; 1143 1144 uint64_t Base = (radix == 16) ? 2 : 10; 1145 if (BaseShift > 0) { 1146 for (int64_t i = 0; i < BaseShift; ++i) { 1147 Val *= Base; 1148 } 1149 } else if (BaseShift < 0) { 1150 for (int64_t i = BaseShift; i < 0 && !Val.isNullValue(); ++i) 1151 Val = Val.udiv(Base); 1152 } 1153 1154 bool IntOverflowOccurred = false; 1155 auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth()); 1156 if (Val.getBitWidth() > StoreVal.getBitWidth()) { 1157 IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth())); 1158 StoreVal = Val.trunc(StoreVal.getBitWidth()); 1159 } else if (Val.getBitWidth() < StoreVal.getBitWidth()) { 1160 IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal); 1161 StoreVal = Val.zext(StoreVal.getBitWidth()); 1162 } else { 1163 StoreVal = Val; 1164 } 1165 1166 return IntOverflowOccurred || ExpOverflowOccurred; 1167 } 1168 1169 /// \verbatim 1170 /// user-defined-character-literal: [C++11 lex.ext] 1171 /// character-literal ud-suffix 1172 /// ud-suffix: 1173 /// identifier 1174 /// character-literal: [C++11 lex.ccon] 1175 /// ' c-char-sequence ' 1176 /// u' c-char-sequence ' 1177 /// U' c-char-sequence ' 1178 /// L' c-char-sequence ' 1179 /// u8' c-char-sequence ' [C++1z lex.ccon] 1180 /// c-char-sequence: 1181 /// c-char 1182 /// c-char-sequence c-char 1183 /// c-char: 1184 /// any member of the source character set except the single-quote ', 1185 /// backslash \, or new-line character 1186 /// escape-sequence 1187 /// universal-character-name 1188 /// escape-sequence: 1189 /// simple-escape-sequence 1190 /// octal-escape-sequence 1191 /// hexadecimal-escape-sequence 1192 /// simple-escape-sequence: 1193 /// one of \' \" \? \\ \a \b \f \n \r \t \v 1194 /// octal-escape-sequence: 1195 /// \ octal-digit 1196 /// \ octal-digit octal-digit 1197 /// \ octal-digit octal-digit octal-digit 1198 /// hexadecimal-escape-sequence: 1199 /// \x hexadecimal-digit 1200 /// hexadecimal-escape-sequence hexadecimal-digit 1201 /// universal-character-name: [C++11 lex.charset] 1202 /// \u hex-quad 1203 /// \U hex-quad hex-quad 1204 /// hex-quad: 1205 /// hex-digit hex-digit hex-digit hex-digit 1206 /// \endverbatim 1207 /// 1208 CharLiteralParser::CharLiteralParser(const char *begin, const char *end, 1209 SourceLocation Loc, Preprocessor &PP, 1210 tok::TokenKind kind) { 1211 // At this point we know that the character matches the regex "(L|u|U)?'.*'". 1212 HadError = false; 1213 1214 Kind = kind; 1215 1216 const char *TokBegin = begin; 1217 1218 // Skip over wide character determinant. 1219 if (Kind != tok::char_constant) 1220 ++begin; 1221 if (Kind == tok::utf8_char_constant) 1222 ++begin; 1223 1224 // Skip over the entry quote. 1225 assert(begin[0] == '\'' && "Invalid token lexed"); 1226 ++begin; 1227 1228 // Remove an optional ud-suffix. 1229 if (end[-1] != '\'') { 1230 const char *UDSuffixEnd = end; 1231 do { 1232 --end; 1233 } while (end[-1] != '\''); 1234 // FIXME: Don't bother with this if !tok.hasUCN(). 1235 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end)); 1236 UDSuffixOffset = end - TokBegin; 1237 } 1238 1239 // Trim the ending quote. 1240 assert(end != begin && "Invalid token lexed"); 1241 --end; 1242 1243 // FIXME: The "Value" is an uint64_t so we can handle char literals of 1244 // up to 64-bits. 1245 // FIXME: This extensively assumes that 'char' is 8-bits. 1246 assert(PP.getTargetInfo().getCharWidth() == 8 && 1247 "Assumes char is 8 bits"); 1248 assert(PP.getTargetInfo().getIntWidth() <= 64 && 1249 (PP.getTargetInfo().getIntWidth() & 7) == 0 && 1250 "Assumes sizeof(int) on target is <= 64 and a multiple of char"); 1251 assert(PP.getTargetInfo().getWCharWidth() <= 64 && 1252 "Assumes sizeof(wchar) on target is <= 64"); 1253 1254 SmallVector<uint32_t, 4> codepoint_buffer; 1255 codepoint_buffer.resize(end - begin); 1256 uint32_t *buffer_begin = &codepoint_buffer.front(); 1257 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size(); 1258 1259 // Unicode escapes representing characters that cannot be correctly 1260 // represented in a single code unit are disallowed in character literals 1261 // by this implementation. 1262 uint32_t largest_character_for_kind; 1263 if (tok::wide_char_constant == Kind) { 1264 largest_character_for_kind = 1265 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth()); 1266 } else if (tok::utf8_char_constant == Kind) { 1267 largest_character_for_kind = 0x7F; 1268 } else if (tok::utf16_char_constant == Kind) { 1269 largest_character_for_kind = 0xFFFF; 1270 } else if (tok::utf32_char_constant == Kind) { 1271 largest_character_for_kind = 0x10FFFF; 1272 } else { 1273 largest_character_for_kind = 0x7Fu; 1274 } 1275 1276 while (begin != end) { 1277 // Is this a span of non-escape characters? 1278 if (begin[0] != '\\') { 1279 char const *start = begin; 1280 do { 1281 ++begin; 1282 } while (begin != end && *begin != '\\'); 1283 1284 char const *tmp_in_start = start; 1285 uint32_t *tmp_out_start = buffer_begin; 1286 llvm::ConversionResult res = 1287 llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start), 1288 reinterpret_cast<llvm::UTF8 const *>(begin), 1289 &buffer_begin, buffer_end, llvm::strictConversion); 1290 if (res != llvm::conversionOK) { 1291 // If we see bad encoding for unprefixed character literals, warn and 1292 // simply copy the byte values, for compatibility with gcc and 1293 // older versions of clang. 1294 bool NoErrorOnBadEncoding = isAscii(); 1295 unsigned Msg = diag::err_bad_character_encoding; 1296 if (NoErrorOnBadEncoding) 1297 Msg = diag::warn_bad_character_encoding; 1298 PP.Diag(Loc, Msg); 1299 if (NoErrorOnBadEncoding) { 1300 start = tmp_in_start; 1301 buffer_begin = tmp_out_start; 1302 for (; start != begin; ++start, ++buffer_begin) 1303 *buffer_begin = static_cast<uint8_t>(*start); 1304 } else { 1305 HadError = true; 1306 } 1307 } else { 1308 for (; tmp_out_start < buffer_begin; ++tmp_out_start) { 1309 if (*tmp_out_start > largest_character_for_kind) { 1310 HadError = true; 1311 PP.Diag(Loc, diag::err_character_too_large); 1312 } 1313 } 1314 } 1315 1316 continue; 1317 } 1318 // Is this a Universal Character Name escape? 1319 if (begin[1] == 'u' || begin[1] == 'U') { 1320 unsigned short UcnLen = 0; 1321 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen, 1322 FullSourceLoc(Loc, PP.getSourceManager()), 1323 &PP.getDiagnostics(), PP.getLangOpts(), true)) { 1324 HadError = true; 1325 } else if (*buffer_begin > largest_character_for_kind) { 1326 HadError = true; 1327 PP.Diag(Loc, diag::err_character_too_large); 1328 } 1329 1330 ++buffer_begin; 1331 continue; 1332 } 1333 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo()); 1334 uint64_t result = 1335 ProcessCharEscape(TokBegin, begin, end, HadError, 1336 FullSourceLoc(Loc,PP.getSourceManager()), 1337 CharWidth, &PP.getDiagnostics(), PP.getLangOpts()); 1338 *buffer_begin++ = result; 1339 } 1340 1341 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front(); 1342 1343 if (NumCharsSoFar > 1) { 1344 if (isWide()) 1345 PP.Diag(Loc, diag::warn_extraneous_char_constant); 1346 else if (isAscii() && NumCharsSoFar == 4) 1347 PP.Diag(Loc, diag::ext_four_char_character_literal); 1348 else if (isAscii()) 1349 PP.Diag(Loc, diag::ext_multichar_character_literal); 1350 else 1351 PP.Diag(Loc, diag::err_multichar_utf_character_literal); 1352 IsMultiChar = true; 1353 } else { 1354 IsMultiChar = false; 1355 } 1356 1357 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0); 1358 1359 // Narrow character literals act as though their value is concatenated 1360 // in this implementation, but warn on overflow. 1361 bool multi_char_too_long = false; 1362 if (isAscii() && isMultiChar()) { 1363 LitVal = 0; 1364 for (size_t i = 0; i < NumCharsSoFar; ++i) { 1365 // check for enough leading zeros to shift into 1366 multi_char_too_long |= (LitVal.countLeadingZeros() < 8); 1367 LitVal <<= 8; 1368 LitVal = LitVal + (codepoint_buffer[i] & 0xFF); 1369 } 1370 } else if (NumCharsSoFar > 0) { 1371 // otherwise just take the last character 1372 LitVal = buffer_begin[-1]; 1373 } 1374 1375 if (!HadError && multi_char_too_long) { 1376 PP.Diag(Loc, diag::warn_char_constant_too_large); 1377 } 1378 1379 // Transfer the value from APInt to uint64_t 1380 Value = LitVal.getZExtValue(); 1381 1382 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1") 1383 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple 1384 // character constants are not sign extended in the this implementation: 1385 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC. 1386 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) && 1387 PP.getLangOpts().CharIsSigned) 1388 Value = (signed char)Value; 1389 } 1390 1391 /// \verbatim 1392 /// string-literal: [C++0x lex.string] 1393 /// encoding-prefix " [s-char-sequence] " 1394 /// encoding-prefix R raw-string 1395 /// encoding-prefix: 1396 /// u8 1397 /// u 1398 /// U 1399 /// L 1400 /// s-char-sequence: 1401 /// s-char 1402 /// s-char-sequence s-char 1403 /// s-char: 1404 /// any member of the source character set except the double-quote ", 1405 /// backslash \, or new-line character 1406 /// escape-sequence 1407 /// universal-character-name 1408 /// raw-string: 1409 /// " d-char-sequence ( r-char-sequence ) d-char-sequence " 1410 /// r-char-sequence: 1411 /// r-char 1412 /// r-char-sequence r-char 1413 /// r-char: 1414 /// any member of the source character set, except a right parenthesis ) 1415 /// followed by the initial d-char-sequence (which may be empty) 1416 /// followed by a double quote ". 1417 /// d-char-sequence: 1418 /// d-char 1419 /// d-char-sequence d-char 1420 /// d-char: 1421 /// any member of the basic source character set except: 1422 /// space, the left parenthesis (, the right parenthesis ), 1423 /// the backslash \, and the control characters representing horizontal 1424 /// tab, vertical tab, form feed, and newline. 1425 /// escape-sequence: [C++0x lex.ccon] 1426 /// simple-escape-sequence 1427 /// octal-escape-sequence 1428 /// hexadecimal-escape-sequence 1429 /// simple-escape-sequence: 1430 /// one of \' \" \? \\ \a \b \f \n \r \t \v 1431 /// octal-escape-sequence: 1432 /// \ octal-digit 1433 /// \ octal-digit octal-digit 1434 /// \ octal-digit octal-digit octal-digit 1435 /// hexadecimal-escape-sequence: 1436 /// \x hexadecimal-digit 1437 /// hexadecimal-escape-sequence hexadecimal-digit 1438 /// universal-character-name: 1439 /// \u hex-quad 1440 /// \U hex-quad hex-quad 1441 /// hex-quad: 1442 /// hex-digit hex-digit hex-digit hex-digit 1443 /// \endverbatim 1444 /// 1445 StringLiteralParser:: 1446 StringLiteralParser(ArrayRef<Token> StringToks, 1447 Preprocessor &PP, bool Complain) 1448 : SM(PP.getSourceManager()), Features(PP.getLangOpts()), 1449 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr), 1450 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown), 1451 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) { 1452 init(StringToks); 1453 } 1454 1455 void StringLiteralParser::init(ArrayRef<Token> StringToks){ 1456 // The literal token may have come from an invalid source location (e.g. due 1457 // to a PCH error), in which case the token length will be 0. 1458 if (StringToks.empty() || StringToks[0].getLength() < 2) 1459 return DiagnoseLexingError(SourceLocation()); 1460 1461 // Scan all of the string portions, remember the max individual token length, 1462 // computing a bound on the concatenated string length, and see whether any 1463 // piece is a wide-string. If any of the string portions is a wide-string 1464 // literal, the result is a wide-string literal [C99 6.4.5p4]. 1465 assert(!StringToks.empty() && "expected at least one token"); 1466 MaxTokenLength = StringToks[0].getLength(); 1467 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!"); 1468 SizeBound = StringToks[0].getLength()-2; // -2 for "". 1469 Kind = StringToks[0].getKind(); 1470 1471 hadError = false; 1472 1473 // Implement Translation Phase #6: concatenation of string literals 1474 /// (C99 5.1.1.2p1). The common case is only one string fragment. 1475 for (unsigned i = 1; i != StringToks.size(); ++i) { 1476 if (StringToks[i].getLength() < 2) 1477 return DiagnoseLexingError(StringToks[i].getLocation()); 1478 1479 // The string could be shorter than this if it needs cleaning, but this is a 1480 // reasonable bound, which is all we need. 1481 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!"); 1482 SizeBound += StringToks[i].getLength()-2; // -2 for "". 1483 1484 // Remember maximum string piece length. 1485 if (StringToks[i].getLength() > MaxTokenLength) 1486 MaxTokenLength = StringToks[i].getLength(); 1487 1488 // Remember if we see any wide or utf-8/16/32 strings. 1489 // Also check for illegal concatenations. 1490 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) { 1491 if (isAscii()) { 1492 Kind = StringToks[i].getKind(); 1493 } else { 1494 if (Diags) 1495 Diags->Report(StringToks[i].getLocation(), 1496 diag::err_unsupported_string_concat); 1497 hadError = true; 1498 } 1499 } 1500 } 1501 1502 // Include space for the null terminator. 1503 ++SizeBound; 1504 1505 // TODO: K&R warning: "traditional C rejects string constant concatenation" 1506 1507 // Get the width in bytes of char/wchar_t/char16_t/char32_t 1508 CharByteWidth = getCharWidth(Kind, Target); 1509 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); 1510 CharByteWidth /= 8; 1511 1512 // The output buffer size needs to be large enough to hold wide characters. 1513 // This is a worst-case assumption which basically corresponds to L"" "long". 1514 SizeBound *= CharByteWidth; 1515 1516 // Size the temporary buffer to hold the result string data. 1517 ResultBuf.resize(SizeBound); 1518 1519 // Likewise, but for each string piece. 1520 SmallString<512> TokenBuf; 1521 TokenBuf.resize(MaxTokenLength); 1522 1523 // Loop over all the strings, getting their spelling, and expanding them to 1524 // wide strings as appropriate. 1525 ResultPtr = &ResultBuf[0]; // Next byte to fill in. 1526 1527 Pascal = false; 1528 1529 SourceLocation UDSuffixTokLoc; 1530 1531 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) { 1532 const char *ThisTokBuf = &TokenBuf[0]; 1533 // Get the spelling of the token, which eliminates trigraphs, etc. We know 1534 // that ThisTokBuf points to a buffer that is big enough for the whole token 1535 // and 'spelled' tokens can only shrink. 1536 bool StringInvalid = false; 1537 unsigned ThisTokLen = 1538 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features, 1539 &StringInvalid); 1540 if (StringInvalid) 1541 return DiagnoseLexingError(StringToks[i].getLocation()); 1542 1543 const char *ThisTokBegin = ThisTokBuf; 1544 const char *ThisTokEnd = ThisTokBuf+ThisTokLen; 1545 1546 // Remove an optional ud-suffix. 1547 if (ThisTokEnd[-1] != '"') { 1548 const char *UDSuffixEnd = ThisTokEnd; 1549 do { 1550 --ThisTokEnd; 1551 } while (ThisTokEnd[-1] != '"'); 1552 1553 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd); 1554 1555 if (UDSuffixBuf.empty()) { 1556 if (StringToks[i].hasUCN()) 1557 expandUCNs(UDSuffixBuf, UDSuffix); 1558 else 1559 UDSuffixBuf.assign(UDSuffix); 1560 UDSuffixToken = i; 1561 UDSuffixOffset = ThisTokEnd - ThisTokBuf; 1562 UDSuffixTokLoc = StringToks[i].getLocation(); 1563 } else { 1564 SmallString<32> ExpandedUDSuffix; 1565 if (StringToks[i].hasUCN()) { 1566 expandUCNs(ExpandedUDSuffix, UDSuffix); 1567 UDSuffix = ExpandedUDSuffix; 1568 } 1569 1570 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the 1571 // result of a concatenation involving at least one user-defined-string- 1572 // literal, all the participating user-defined-string-literals shall 1573 // have the same ud-suffix. 1574 if (UDSuffixBuf != UDSuffix) { 1575 if (Diags) { 1576 SourceLocation TokLoc = StringToks[i].getLocation(); 1577 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix) 1578 << UDSuffixBuf << UDSuffix 1579 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc) 1580 << SourceRange(TokLoc, TokLoc); 1581 } 1582 hadError = true; 1583 } 1584 } 1585 } 1586 1587 // Strip the end quote. 1588 --ThisTokEnd; 1589 1590 // TODO: Input character set mapping support. 1591 1592 // Skip marker for wide or unicode strings. 1593 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') { 1594 ++ThisTokBuf; 1595 // Skip 8 of u8 marker for utf8 strings. 1596 if (ThisTokBuf[0] == '8') 1597 ++ThisTokBuf; 1598 } 1599 1600 // Check for raw string 1601 if (ThisTokBuf[0] == 'R') { 1602 ThisTokBuf += 2; // skip R" 1603 1604 const char *Prefix = ThisTokBuf; 1605 while (ThisTokBuf[0] != '(') 1606 ++ThisTokBuf; 1607 ++ThisTokBuf; // skip '(' 1608 1609 // Remove same number of characters from the end 1610 ThisTokEnd -= ThisTokBuf - Prefix; 1611 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal"); 1612 1613 // C++14 [lex.string]p4: A source-file new-line in a raw string literal 1614 // results in a new-line in the resulting execution string-literal. 1615 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf); 1616 while (!RemainingTokenSpan.empty()) { 1617 // Split the string literal on \r\n boundaries. 1618 size_t CRLFPos = RemainingTokenSpan.find("\r\n"); 1619 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos); 1620 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos); 1621 1622 // Copy everything before the \r\n sequence into the string literal. 1623 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF)) 1624 hadError = true; 1625 1626 // Point into the \n inside the \r\n sequence and operate on the 1627 // remaining portion of the literal. 1628 RemainingTokenSpan = AfterCRLF.substr(1); 1629 } 1630 } else { 1631 if (ThisTokBuf[0] != '"') { 1632 // The file may have come from PCH and then changed after loading the 1633 // PCH; Fail gracefully. 1634 return DiagnoseLexingError(StringToks[i].getLocation()); 1635 } 1636 ++ThisTokBuf; // skip " 1637 1638 // Check if this is a pascal string 1639 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd && 1640 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') { 1641 1642 // If the \p sequence is found in the first token, we have a pascal string 1643 // Otherwise, if we already have a pascal string, ignore the first \p 1644 if (i == 0) { 1645 ++ThisTokBuf; 1646 Pascal = true; 1647 } else if (Pascal) 1648 ThisTokBuf += 2; 1649 } 1650 1651 while (ThisTokBuf != ThisTokEnd) { 1652 // Is this a span of non-escape characters? 1653 if (ThisTokBuf[0] != '\\') { 1654 const char *InStart = ThisTokBuf; 1655 do { 1656 ++ThisTokBuf; 1657 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\'); 1658 1659 // Copy the character span over. 1660 if (CopyStringFragment(StringToks[i], ThisTokBegin, 1661 StringRef(InStart, ThisTokBuf - InStart))) 1662 hadError = true; 1663 continue; 1664 } 1665 // Is this a Universal Character Name escape? 1666 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') { 1667 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, 1668 ResultPtr, hadError, 1669 FullSourceLoc(StringToks[i].getLocation(), SM), 1670 CharByteWidth, Diags, Features); 1671 continue; 1672 } 1673 // Otherwise, this is a non-UCN escape character. Process it. 1674 unsigned ResultChar = 1675 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError, 1676 FullSourceLoc(StringToks[i].getLocation(), SM), 1677 CharByteWidth*8, Diags, Features); 1678 1679 if (CharByteWidth == 4) { 1680 // FIXME: Make the type of the result buffer correct instead of 1681 // using reinterpret_cast. 1682 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr); 1683 *ResultWidePtr = ResultChar; 1684 ResultPtr += 4; 1685 } else if (CharByteWidth == 2) { 1686 // FIXME: Make the type of the result buffer correct instead of 1687 // using reinterpret_cast. 1688 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr); 1689 *ResultWidePtr = ResultChar & 0xFFFF; 1690 ResultPtr += 2; 1691 } else { 1692 assert(CharByteWidth == 1 && "Unexpected char width"); 1693 *ResultPtr++ = ResultChar & 0xFF; 1694 } 1695 } 1696 } 1697 } 1698 1699 if (Pascal) { 1700 if (CharByteWidth == 4) { 1701 // FIXME: Make the type of the result buffer correct instead of 1702 // using reinterpret_cast. 1703 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data()); 1704 ResultWidePtr[0] = GetNumStringChars() - 1; 1705 } else if (CharByteWidth == 2) { 1706 // FIXME: Make the type of the result buffer correct instead of 1707 // using reinterpret_cast. 1708 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data()); 1709 ResultWidePtr[0] = GetNumStringChars() - 1; 1710 } else { 1711 assert(CharByteWidth == 1 && "Unexpected char width"); 1712 ResultBuf[0] = GetNumStringChars() - 1; 1713 } 1714 1715 // Verify that pascal strings aren't too large. 1716 if (GetStringLength() > 256) { 1717 if (Diags) 1718 Diags->Report(StringToks.front().getLocation(), 1719 diag::err_pascal_string_too_long) 1720 << SourceRange(StringToks.front().getLocation(), 1721 StringToks.back().getLocation()); 1722 hadError = true; 1723 return; 1724 } 1725 } else if (Diags) { 1726 // Complain if this string literal has too many characters. 1727 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509; 1728 1729 if (GetNumStringChars() > MaxChars) 1730 Diags->Report(StringToks.front().getLocation(), 1731 diag::ext_string_too_long) 1732 << GetNumStringChars() << MaxChars 1733 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0) 1734 << SourceRange(StringToks.front().getLocation(), 1735 StringToks.back().getLocation()); 1736 } 1737 } 1738 1739 static const char *resyncUTF8(const char *Err, const char *End) { 1740 if (Err == End) 1741 return End; 1742 End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err); 1743 while (++Err != End && (*Err & 0xC0) == 0x80) 1744 ; 1745 return Err; 1746 } 1747 1748 /// This function copies from Fragment, which is a sequence of bytes 1749 /// within Tok's contents (which begin at TokBegin) into ResultPtr. 1750 /// Performs widening for multi-byte characters. 1751 bool StringLiteralParser::CopyStringFragment(const Token &Tok, 1752 const char *TokBegin, 1753 StringRef Fragment) { 1754 const llvm::UTF8 *ErrorPtrTmp; 1755 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp)) 1756 return false; 1757 1758 // If we see bad encoding for unprefixed string literals, warn and 1759 // simply copy the byte values, for compatibility with gcc and older 1760 // versions of clang. 1761 bool NoErrorOnBadEncoding = isAscii(); 1762 if (NoErrorOnBadEncoding) { 1763 memcpy(ResultPtr, Fragment.data(), Fragment.size()); 1764 ResultPtr += Fragment.size(); 1765 } 1766 1767 if (Diags) { 1768 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp); 1769 1770 FullSourceLoc SourceLoc(Tok.getLocation(), SM); 1771 const DiagnosticBuilder &Builder = 1772 Diag(Diags, Features, SourceLoc, TokBegin, 1773 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()), 1774 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding 1775 : diag::err_bad_string_encoding); 1776 1777 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end()); 1778 StringRef NextFragment(NextStart, Fragment.end()-NextStart); 1779 1780 // Decode into a dummy buffer. 1781 SmallString<512> Dummy; 1782 Dummy.reserve(Fragment.size() * CharByteWidth); 1783 char *Ptr = Dummy.data(); 1784 1785 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) { 1786 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp); 1787 NextStart = resyncUTF8(ErrorPtr, Fragment.end()); 1788 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin, 1789 ErrorPtr, NextStart); 1790 NextFragment = StringRef(NextStart, Fragment.end()-NextStart); 1791 } 1792 } 1793 return !NoErrorOnBadEncoding; 1794 } 1795 1796 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) { 1797 hadError = true; 1798 if (Diags) 1799 Diags->Report(Loc, diag::err_lexing_string); 1800 } 1801 1802 /// getOffsetOfStringByte - This function returns the offset of the 1803 /// specified byte of the string data represented by Token. This handles 1804 /// advancing over escape sequences in the string. 1805 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, 1806 unsigned ByteNo) const { 1807 // Get the spelling of the token. 1808 SmallString<32> SpellingBuffer; 1809 SpellingBuffer.resize(Tok.getLength()); 1810 1811 bool StringInvalid = false; 1812 const char *SpellingPtr = &SpellingBuffer[0]; 1813 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features, 1814 &StringInvalid); 1815 if (StringInvalid) 1816 return 0; 1817 1818 const char *SpellingStart = SpellingPtr; 1819 const char *SpellingEnd = SpellingPtr+TokLen; 1820 1821 // Handle UTF-8 strings just like narrow strings. 1822 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8') 1823 SpellingPtr += 2; 1824 1825 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' && 1826 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet"); 1827 1828 // For raw string literals, this is easy. 1829 if (SpellingPtr[0] == 'R') { 1830 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!"); 1831 // Skip 'R"'. 1832 SpellingPtr += 2; 1833 while (*SpellingPtr != '(') { 1834 ++SpellingPtr; 1835 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal"); 1836 } 1837 // Skip '('. 1838 ++SpellingPtr; 1839 return SpellingPtr - SpellingStart + ByteNo; 1840 } 1841 1842 // Skip over the leading quote 1843 assert(SpellingPtr[0] == '"' && "Should be a string literal!"); 1844 ++SpellingPtr; 1845 1846 // Skip over bytes until we find the offset we're looking for. 1847 while (ByteNo) { 1848 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!"); 1849 1850 // Step over non-escapes simply. 1851 if (*SpellingPtr != '\\') { 1852 ++SpellingPtr; 1853 --ByteNo; 1854 continue; 1855 } 1856 1857 // Otherwise, this is an escape character. Advance over it. 1858 bool HadError = false; 1859 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') { 1860 const char *EscapePtr = SpellingPtr; 1861 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd, 1862 1, Features, HadError); 1863 if (Len > ByteNo) { 1864 // ByteNo is somewhere within the escape sequence. 1865 SpellingPtr = EscapePtr; 1866 break; 1867 } 1868 ByteNo -= Len; 1869 } else { 1870 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError, 1871 FullSourceLoc(Tok.getLocation(), SM), 1872 CharByteWidth*8, Diags, Features); 1873 --ByteNo; 1874 } 1875 assert(!HadError && "This method isn't valid on erroneous strings"); 1876 } 1877 1878 return SpellingPtr-SpellingStart; 1879 } 1880 1881 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved 1882 /// suffixes as ud-suffixes, because the diagnostic experience is better if we 1883 /// treat it as an invalid suffix. 1884 bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts, 1885 StringRef Suffix) { 1886 return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) || 1887 Suffix == "sv"; 1888 } 1889