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