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