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