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