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