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