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