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 "llvm/ADT/StringExtras.h" 20 using namespace clang; 21 22 /// HexDigitValue - Return the value of the specified hex digit, or -1 if it's 23 /// not valid. 24 static int HexDigitValue(char C) { 25 if (C >= '0' && C <= '9') return C-'0'; 26 if (C >= 'a' && C <= 'f') return C-'a'+10; 27 if (C >= 'A' && C <= 'F') return C-'A'+10; 28 return -1; 29 } 30 31 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in 32 /// either a character or a string literal. 33 static unsigned ProcessCharEscape(const char *&ThisTokBuf, 34 const char *ThisTokEnd, bool &HadError, 35 SourceLocation Loc, bool IsWide, 36 Preprocessor &PP) { 37 // Skip the '\' char. 38 ++ThisTokBuf; 39 40 // We know that this character can't be off the end of the buffer, because 41 // that would have been \", which would not have been the end of string. 42 unsigned ResultChar = *ThisTokBuf++; 43 switch (ResultChar) { 44 // These map to themselves. 45 case '\\': case '\'': case '"': case '?': break; 46 47 // These have fixed mappings. 48 case 'a': 49 // TODO: K&R: the meaning of '\\a' is different in traditional C 50 ResultChar = 7; 51 break; 52 case 'b': 53 ResultChar = 8; 54 break; 55 case 'e': 56 PP.Diag(Loc, diag::ext_nonstandard_escape) << "e"; 57 ResultChar = 27; 58 break; 59 case 'E': 60 PP.Diag(Loc, diag::ext_nonstandard_escape) << "E"; 61 ResultChar = 27; 62 break; 63 case 'f': 64 ResultChar = 12; 65 break; 66 case 'n': 67 ResultChar = 10; 68 break; 69 case 'r': 70 ResultChar = 13; 71 break; 72 case 't': 73 ResultChar = 9; 74 break; 75 case 'v': 76 ResultChar = 11; 77 break; 78 case 'x': { // Hex escape. 79 ResultChar = 0; 80 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) { 81 PP.Diag(Loc, diag::err_hex_escape_no_digits); 82 HadError = 1; 83 break; 84 } 85 86 // Hex escapes are a maximal series of hex digits. 87 bool Overflow = false; 88 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) { 89 int CharVal = HexDigitValue(ThisTokBuf[0]); 90 if (CharVal == -1) break; 91 // About to shift out a digit? 92 Overflow |= (ResultChar & 0xF0000000) ? true : false; 93 ResultChar <<= 4; 94 ResultChar |= CharVal; 95 } 96 97 // See if any bits will be truncated when evaluated as a character. 98 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide); 99 100 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { 101 Overflow = true; 102 ResultChar &= ~0U >> (32-CharWidth); 103 } 104 105 // Check for overflow. 106 if (Overflow) // Too many digits to fit in 107 PP.Diag(Loc, diag::warn_hex_escape_too_large); 108 break; 109 } 110 case '0': case '1': case '2': case '3': 111 case '4': case '5': case '6': case '7': { 112 // Octal escapes. 113 --ThisTokBuf; 114 ResultChar = 0; 115 116 // Octal escapes are a series of octal digits with maximum length 3. 117 // "\0123" is a two digit sequence equal to "\012" "3". 118 unsigned NumDigits = 0; 119 do { 120 ResultChar <<= 3; 121 ResultChar |= *ThisTokBuf++ - '0'; 122 ++NumDigits; 123 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 && 124 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7'); 125 126 // Check for overflow. Reject '\777', but not L'\777'. 127 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide); 128 129 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { 130 PP.Diag(Loc, diag::warn_octal_escape_too_large); 131 ResultChar &= ~0U >> (32-CharWidth); 132 } 133 break; 134 } 135 136 // Otherwise, these are not valid escapes. 137 case '(': case '{': case '[': case '%': 138 // GCC accepts these as extensions. We warn about them as such though. 139 PP.Diag(Loc, diag::ext_nonstandard_escape) 140 << std::string()+(char)ResultChar; 141 break; 142 default: 143 if (isgraph(ThisTokBuf[0])) 144 PP.Diag(Loc, diag::ext_unknown_escape) << std::string()+(char)ResultChar; 145 else 146 PP.Diag(Loc, diag::ext_unknown_escape) << "x"+llvm::utohexstr(ResultChar); 147 break; 148 } 149 150 return ResultChar; 151 } 152 153 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and 154 /// convert the UTF32 to UTF8. This is a subroutine of StringLiteralParser. 155 /// When we decide to implement UCN's for character constants and identifiers, 156 /// we will likely rework our support for UCN's. 157 static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd, 158 char *&ResultBuf, bool &HadError, 159 SourceLocation Loc, bool IsWide, Preprocessor &PP) 160 { 161 // FIXME: Add a warning - UCN's are only valid in C++ & C99. 162 // FIXME: Handle wide strings. 163 164 // Save the beginning of the string (for error diagnostics). 165 const char *ThisTokBegin = ThisTokBuf; 166 167 // Skip the '\u' char's. 168 ThisTokBuf += 2; 169 170 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) { 171 PP.Diag(Loc, diag::err_ucn_escape_no_digits); 172 HadError = 1; 173 return; 174 } 175 typedef uint32_t UTF32; 176 177 UTF32 UcnVal = 0; 178 unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8); 179 for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) { 180 int CharVal = HexDigitValue(ThisTokBuf[0]); 181 if (CharVal == -1) break; 182 UcnVal <<= 4; 183 UcnVal |= CharVal; 184 } 185 // If we didn't consume the proper number of digits, there is a problem. 186 if (UcnLen) { 187 PP.Diag(PP.AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin), 188 diag::err_ucn_escape_incomplete); 189 HadError = 1; 190 return; 191 } 192 // Check UCN constraints (C99 6.4.3p2). 193 if ((UcnVal < 0xa0 && 194 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, ` 195 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF) 196 || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ { 197 PP.Diag(Loc, diag::err_ucn_escape_invalid); 198 HadError = 1; 199 return; 200 } 201 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8. 202 // The conversion below was inspired by: 203 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c 204 // First, we determine how many bytes the result will require. 205 typedef uint8_t UTF8; 206 207 unsigned short bytesToWrite = 0; 208 if (UcnVal < (UTF32)0x80) 209 bytesToWrite = 1; 210 else if (UcnVal < (UTF32)0x800) 211 bytesToWrite = 2; 212 else if (UcnVal < (UTF32)0x10000) 213 bytesToWrite = 3; 214 else 215 bytesToWrite = 4; 216 217 const unsigned byteMask = 0xBF; 218 const unsigned byteMark = 0x80; 219 220 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed 221 // into the first byte, depending on how many bytes follow. 222 static const UTF8 firstByteMark[5] = { 223 0x00, 0x00, 0xC0, 0xE0, 0xF0 224 }; 225 // Finally, we write the bytes into ResultBuf. 226 ResultBuf += bytesToWrite; 227 switch (bytesToWrite) { // note: everything falls through. 228 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; 229 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; 230 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; 231 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]); 232 } 233 // Update the buffer. 234 ResultBuf += bytesToWrite; 235 } 236 237 238 /// integer-constant: [C99 6.4.4.1] 239 /// decimal-constant integer-suffix 240 /// octal-constant integer-suffix 241 /// hexadecimal-constant integer-suffix 242 /// decimal-constant: 243 /// nonzero-digit 244 /// decimal-constant digit 245 /// octal-constant: 246 /// 0 247 /// octal-constant octal-digit 248 /// hexadecimal-constant: 249 /// hexadecimal-prefix hexadecimal-digit 250 /// hexadecimal-constant hexadecimal-digit 251 /// hexadecimal-prefix: one of 252 /// 0x 0X 253 /// integer-suffix: 254 /// unsigned-suffix [long-suffix] 255 /// unsigned-suffix [long-long-suffix] 256 /// long-suffix [unsigned-suffix] 257 /// long-long-suffix [unsigned-sufix] 258 /// nonzero-digit: 259 /// 1 2 3 4 5 6 7 8 9 260 /// octal-digit: 261 /// 0 1 2 3 4 5 6 7 262 /// hexadecimal-digit: 263 /// 0 1 2 3 4 5 6 7 8 9 264 /// a b c d e f 265 /// A B C D E F 266 /// unsigned-suffix: one of 267 /// u U 268 /// long-suffix: one of 269 /// l L 270 /// long-long-suffix: one of 271 /// ll LL 272 /// 273 /// floating-constant: [C99 6.4.4.2] 274 /// TODO: add rules... 275 /// 276 NumericLiteralParser:: 277 NumericLiteralParser(const char *begin, const char *end, 278 SourceLocation TokLoc, Preprocessor &pp) 279 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) { 280 281 // This routine assumes that the range begin/end matches the regex for integer 282 // and FP constants (specifically, the 'pp-number' regex), and assumes that 283 // the byte at "*end" is both valid and not part of the regex. Because of 284 // this, it doesn't have to check for 'overscan' in various places. 285 assert(!isalnum(*end) && *end != '.' && *end != '_' && 286 "Lexer didn't maximally munch?"); 287 288 s = DigitsBegin = begin; 289 saw_exponent = false; 290 saw_period = false; 291 isLong = false; 292 isUnsigned = false; 293 isLongLong = false; 294 isFloat = false; 295 isImaginary = false; 296 hadError = false; 297 298 if (*s == '0') { // parse radix 299 ParseNumberStartingWithZero(TokLoc); 300 if (hadError) 301 return; 302 } else { // the first digit is non-zero 303 radix = 10; 304 s = SkipDigits(s); 305 if (s == ThisTokEnd) { 306 // Done. 307 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) { 308 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin), 309 diag::err_invalid_decimal_digit) << std::string(s, s+1); 310 hadError = true; 311 return; 312 } else if (*s == '.') { 313 s++; 314 saw_period = true; 315 s = SkipDigits(s); 316 } 317 if ((*s == 'e' || *s == 'E')) { // exponent 318 const char *Exponent = s; 319 s++; 320 saw_exponent = true; 321 if (*s == '+' || *s == '-') s++; // sign 322 const char *first_non_digit = SkipDigits(s); 323 if (first_non_digit != s) { 324 s = first_non_digit; 325 } else { 326 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin), 327 diag::err_exponent_has_no_digits); 328 hadError = true; 329 return; 330 } 331 } 332 } 333 334 SuffixBegin = s; 335 336 // Parse the suffix. At this point we can classify whether we have an FP or 337 // integer constant. 338 bool isFPConstant = isFloatingLiteral(); 339 340 // Loop over all of the characters of the suffix. If we see something bad, 341 // we break out of the loop. 342 for (; s != ThisTokEnd; ++s) { 343 switch (*s) { 344 case 'f': // FP Suffix for "float" 345 case 'F': 346 if (!isFPConstant) break; // Error for integer constant. 347 if (isFloat || isLong) break; // FF, LF invalid. 348 isFloat = true; 349 continue; // Success. 350 case 'u': 351 case 'U': 352 if (isFPConstant) break; // Error for floating constant. 353 if (isUnsigned) break; // Cannot be repeated. 354 isUnsigned = true; 355 continue; // Success. 356 case 'l': 357 case 'L': 358 if (isLong || isLongLong) break; // Cannot be repeated. 359 if (isFloat) break; // LF invalid. 360 361 // Check for long long. The L's need to be adjacent and the same case. 362 if (s+1 != ThisTokEnd && s[1] == s[0]) { 363 if (isFPConstant) break; // long long invalid for floats. 364 isLongLong = true; 365 ++s; // Eat both of them. 366 } else { 367 isLong = true; 368 } 369 continue; // Success. 370 case 'i': 371 if (PP.getLangOptions().Microsoft) { 372 // Allow i8, i16, i32, i64, and i128. 373 if (++s == ThisTokEnd) break; 374 switch (*s) { 375 case '8': 376 s++; // i8 suffix 377 break; 378 case '1': 379 if (++s == ThisTokEnd) break; 380 if (*s == '6') s++; // i16 suffix 381 else if (*s == '2') { 382 if (++s == ThisTokEnd) break; 383 if (*s == '8') s++; // i128 suffix 384 } 385 break; 386 case '3': 387 if (++s == ThisTokEnd) break; 388 if (*s == '2') s++; // i32 suffix 389 break; 390 case '6': 391 if (++s == ThisTokEnd) break; 392 if (*s == '4') s++; // i64 suffix 393 break; 394 default: 395 break; 396 } 397 break; 398 } 399 // fall through. 400 case 'I': 401 case 'j': 402 case 'J': 403 if (isImaginary) break; // Cannot be repeated. 404 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin), 405 diag::ext_imaginary_constant); 406 isImaginary = true; 407 continue; // Success. 408 } 409 // If we reached here, there was an error. 410 break; 411 } 412 413 // Report an error if there are any. 414 if (s != ThisTokEnd) { 415 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin), 416 isFPConstant ? diag::err_invalid_suffix_float_constant : 417 diag::err_invalid_suffix_integer_constant) 418 << std::string(SuffixBegin, ThisTokEnd); 419 hadError = true; 420 return; 421 } 422 } 423 424 /// ParseNumberStartingWithZero - This method is called when the first character 425 /// of the number is found to be a zero. This means it is either an octal 426 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or 427 /// a floating point number (01239.123e4). Eat the prefix, determining the 428 /// radix etc. 429 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { 430 assert(s[0] == '0' && "Invalid method call"); 431 s++; 432 433 // Handle a hex number like 0x1234. 434 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) { 435 s++; 436 radix = 16; 437 DigitsBegin = s; 438 s = SkipHexDigits(s); 439 if (s == ThisTokEnd) { 440 // Done. 441 } else if (*s == '.') { 442 s++; 443 saw_period = true; 444 s = SkipHexDigits(s); 445 } 446 // A binary exponent can appear with or with a '.'. If dotted, the 447 // binary exponent is required. 448 if (*s == 'p' || *s == 'P') { 449 const char *Exponent = s; 450 s++; 451 saw_exponent = true; 452 if (*s == '+' || *s == '-') s++; // sign 453 const char *first_non_digit = SkipDigits(s); 454 if (first_non_digit == s) { 455 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), 456 diag::err_exponent_has_no_digits); 457 hadError = true; 458 return; 459 } 460 s = first_non_digit; 461 462 if (!PP.getLangOptions().HexFloats) 463 PP.Diag(TokLoc, diag::ext_hexconstant_invalid); 464 } else if (saw_period) { 465 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 466 diag::err_hexconstant_requires_exponent); 467 hadError = true; 468 } 469 return; 470 } 471 472 // Handle simple binary numbers 0b01010 473 if (*s == 'b' || *s == 'B') { 474 // 0b101010 is a GCC extension. 475 PP.Diag(TokLoc, diag::ext_binary_literal); 476 ++s; 477 radix = 2; 478 DigitsBegin = s; 479 s = SkipBinaryDigits(s); 480 if (s == ThisTokEnd) { 481 // Done. 482 } else if (isxdigit(*s)) { 483 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 484 diag::err_invalid_binary_digit) << std::string(s, s+1); 485 hadError = true; 486 } 487 // Other suffixes will be diagnosed by the caller. 488 return; 489 } 490 491 // For now, the radix is set to 8. If we discover that we have a 492 // floating point constant, the radix will change to 10. Octal floating 493 // point constants are not permitted (only decimal and hexadecimal). 494 radix = 8; 495 DigitsBegin = s; 496 s = SkipOctalDigits(s); 497 if (s == ThisTokEnd) 498 return; // Done, simple octal number like 01234 499 500 // If we have some other non-octal digit that *is* a decimal digit, see if 501 // this is part of a floating point number like 094.123 or 09e1. 502 if (isdigit(*s)) { 503 const char *EndDecimal = SkipDigits(s); 504 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') { 505 s = EndDecimal; 506 radix = 10; 507 } 508 } 509 510 // If we have a hex digit other than 'e' (which denotes a FP exponent) then 511 // the code is using an incorrect base. 512 if (isxdigit(*s) && *s != 'e' && *s != 'E') { 513 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 514 diag::err_invalid_octal_digit) << std::string(s, s+1); 515 hadError = true; 516 return; 517 } 518 519 if (*s == '.') { 520 s++; 521 radix = 10; 522 saw_period = true; 523 s = SkipDigits(s); // Skip suffix. 524 } 525 if (*s == 'e' || *s == 'E') { // exponent 526 const char *Exponent = s; 527 s++; 528 radix = 10; 529 saw_exponent = true; 530 if (*s == '+' || *s == '-') s++; // sign 531 const char *first_non_digit = SkipDigits(s); 532 if (first_non_digit != s) { 533 s = first_non_digit; 534 } else { 535 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), 536 diag::err_exponent_has_no_digits); 537 hadError = true; 538 return; 539 } 540 } 541 } 542 543 544 /// GetIntegerValue - Convert this numeric literal value to an APInt that 545 /// matches Val's input width. If there is an overflow, set Val to the low bits 546 /// of the result and return true. Otherwise, return false. 547 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { 548 // Fast path: Compute a conservative bound on the maximum number of 549 // bits per digit in this radix. If we can't possibly overflow a 550 // uint64 based on that bound then do the simple conversion to 551 // integer. This avoids the expensive overflow checking below, and 552 // handles the common cases that matter (small decimal integers and 553 // hex/octal values which don't overflow). 554 unsigned MaxBitsPerDigit = 1; 555 while ((1U << MaxBitsPerDigit) < radix) 556 MaxBitsPerDigit += 1; 557 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) { 558 uint64_t N = 0; 559 for (s = DigitsBegin; s != SuffixBegin; ++s) 560 N = N*radix + HexDigitValue(*s); 561 562 // This will truncate the value to Val's input width. Simply check 563 // for overflow by comparing. 564 Val = N; 565 return Val.getZExtValue() != N; 566 } 567 568 Val = 0; 569 s = DigitsBegin; 570 571 llvm::APInt RadixVal(Val.getBitWidth(), radix); 572 llvm::APInt CharVal(Val.getBitWidth(), 0); 573 llvm::APInt OldVal = Val; 574 575 bool OverflowOccurred = false; 576 while (s < SuffixBegin) { 577 unsigned C = HexDigitValue(*s++); 578 579 // If this letter is out of bound for this radix, reject it. 580 assert(C < radix && "NumericLiteralParser ctor should have rejected this"); 581 582 CharVal = C; 583 584 // Add the digit to the value in the appropriate radix. If adding in digits 585 // made the value smaller, then this overflowed. 586 OldVal = Val; 587 588 // Multiply by radix, did overflow occur on the multiply? 589 Val *= RadixVal; 590 OverflowOccurred |= Val.udiv(RadixVal) != OldVal; 591 592 // Add value, did overflow occur on the value? 593 // (a + b) ult b <=> overflow 594 Val += CharVal; 595 OverflowOccurred |= Val.ult(CharVal); 596 } 597 return OverflowOccurred; 598 } 599 600 llvm::APFloat NumericLiteralParser:: 601 GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) { 602 using llvm::APFloat; 603 604 llvm::SmallVector<char,256> floatChars; 605 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i) 606 floatChars.push_back(ThisTokBegin[i]); 607 608 floatChars.push_back('\0'); 609 610 APFloat V (Format, APFloat::fcZero, false); 611 APFloat::opStatus status; 612 613 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven); 614 615 if (isExact) 616 *isExact = status == APFloat::opOK; 617 618 return V; 619 } 620 621 622 CharLiteralParser::CharLiteralParser(const char *begin, const char *end, 623 SourceLocation Loc, Preprocessor &PP) { 624 // At this point we know that the character matches the regex "L?'.*'". 625 HadError = false; 626 627 // Determine if this is a wide character. 628 IsWide = begin[0] == 'L'; 629 if (IsWide) ++begin; 630 631 // Skip over the entry quote. 632 assert(begin[0] == '\'' && "Invalid token lexed"); 633 ++begin; 634 635 // FIXME: The "Value" is an uint64_t so we can handle char literals of 636 // upto 64-bits. 637 // FIXME: This extensively assumes that 'char' is 8-bits. 638 assert(PP.getTargetInfo().getCharWidth() == 8 && 639 "Assumes char is 8 bits"); 640 assert(PP.getTargetInfo().getIntWidth() <= 64 && 641 (PP.getTargetInfo().getIntWidth() & 7) == 0 && 642 "Assumes sizeof(int) on target is <= 64 and a multiple of char"); 643 assert(PP.getTargetInfo().getWCharWidth() <= 64 && 644 "Assumes sizeof(wchar) on target is <= 64"); 645 646 // This is what we will use for overflow detection 647 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0); 648 649 unsigned NumCharsSoFar = 0; 650 while (begin[0] != '\'') { 651 uint64_t ResultChar; 652 if (begin[0] != '\\') // If this is a normal character, consume it. 653 ResultChar = *begin++; 654 else // Otherwise, this is an escape character. 655 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP); 656 657 // If this is a multi-character constant (e.g. 'abc'), handle it. These are 658 // implementation defined (C99 6.4.4.4p10). 659 if (NumCharsSoFar) { 660 if (IsWide) { 661 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'. 662 LitVal = 0; 663 } else { 664 // Narrow character literals act as though their value is concatenated 665 // in this implementation, but warn on overflow. 666 if (LitVal.countLeadingZeros() < 8) 667 PP.Diag(Loc, diag::warn_char_constant_too_large); 668 LitVal <<= 8; 669 } 670 } 671 672 LitVal = LitVal + ResultChar; 673 ++NumCharsSoFar; 674 } 675 676 // If this is the second character being processed, do special handling. 677 if (NumCharsSoFar > 1) { 678 // Warn about discarding the top bits for multi-char wide-character 679 // constants (L'abcd'). 680 if (IsWide) 681 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant); 682 else if (NumCharsSoFar != 4) 683 PP.Diag(Loc, diag::ext_multichar_character_literal); 684 else 685 PP.Diag(Loc, diag::ext_four_char_character_literal); 686 IsMultiChar = true; 687 } 688 689 // Transfer the value from APInt to uint64_t 690 Value = LitVal.getZExtValue(); 691 692 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1") 693 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple 694 // character constants are not sign extended in the this implementation: 695 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC. 696 if (!IsWide && NumCharsSoFar == 1 && (Value & 128) && 697 PP.getLangOptions().CharIsSigned) 698 Value = (signed char)Value; 699 } 700 701 702 /// string-literal: [C99 6.4.5] 703 /// " [s-char-sequence] " 704 /// L" [s-char-sequence] " 705 /// s-char-sequence: 706 /// s-char 707 /// s-char-sequence s-char 708 /// s-char: 709 /// any source character except the double quote ", 710 /// backslash \, or newline character 711 /// escape-character 712 /// universal-character-name 713 /// escape-character: [C99 6.4.4.4] 714 /// \ escape-code 715 /// universal-character-name 716 /// escape-code: 717 /// character-escape-code 718 /// octal-escape-code 719 /// hex-escape-code 720 /// character-escape-code: one of 721 /// n t b r f v a 722 /// \ ' " ? 723 /// octal-escape-code: 724 /// octal-digit 725 /// octal-digit octal-digit 726 /// octal-digit octal-digit octal-digit 727 /// hex-escape-code: 728 /// x hex-digit 729 /// hex-escape-code hex-digit 730 /// universal-character-name: 731 /// \u hex-quad 732 /// \U hex-quad hex-quad 733 /// hex-quad: 734 /// hex-digit hex-digit hex-digit hex-digit 735 /// 736 StringLiteralParser:: 737 StringLiteralParser(const Token *StringToks, unsigned NumStringToks, 738 Preprocessor &pp) : PP(pp) { 739 // Scan all of the string portions, remember the max individual token length, 740 // computing a bound on the concatenated string length, and see whether any 741 // piece is a wide-string. If any of the string portions is a wide-string 742 // literal, the result is a wide-string literal [C99 6.4.5p4]. 743 MaxTokenLength = StringToks[0].getLength(); 744 SizeBound = StringToks[0].getLength()-2; // -2 for "". 745 AnyWide = StringToks[0].is(tok::wide_string_literal); 746 747 hadError = false; 748 749 // Implement Translation Phase #6: concatenation of string literals 750 /// (C99 5.1.1.2p1). The common case is only one string fragment. 751 for (unsigned i = 1; i != NumStringToks; ++i) { 752 // The string could be shorter than this if it needs cleaning, but this is a 753 // reasonable bound, which is all we need. 754 SizeBound += StringToks[i].getLength()-2; // -2 for "". 755 756 // Remember maximum string piece length. 757 if (StringToks[i].getLength() > MaxTokenLength) 758 MaxTokenLength = StringToks[i].getLength(); 759 760 // Remember if we see any wide strings. 761 AnyWide |= StringToks[i].is(tok::wide_string_literal); 762 } 763 764 // Include space for the null terminator. 765 ++SizeBound; 766 767 // TODO: K&R warning: "traditional C rejects string constant concatenation" 768 769 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not 770 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true. 771 wchar_tByteWidth = ~0U; 772 if (AnyWide) { 773 wchar_tByteWidth = PP.getTargetInfo().getWCharWidth(); 774 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!"); 775 wchar_tByteWidth /= 8; 776 } 777 778 // The output buffer size needs to be large enough to hold wide characters. 779 // This is a worst-case assumption which basically corresponds to L"" "long". 780 if (AnyWide) 781 SizeBound *= wchar_tByteWidth; 782 783 // Size the temporary buffer to hold the result string data. 784 ResultBuf.resize(SizeBound); 785 786 // Likewise, but for each string piece. 787 llvm::SmallString<512> TokenBuf; 788 TokenBuf.resize(MaxTokenLength); 789 790 // Loop over all the strings, getting their spelling, and expanding them to 791 // wide strings as appropriate. 792 ResultPtr = &ResultBuf[0]; // Next byte to fill in. 793 794 Pascal = false; 795 796 for (unsigned i = 0, e = NumStringToks; i != e; ++i) { 797 const char *ThisTokBuf = &TokenBuf[0]; 798 // Get the spelling of the token, which eliminates trigraphs, etc. We know 799 // that ThisTokBuf points to a buffer that is big enough for the whole token 800 // and 'spelled' tokens can only shrink. 801 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf); 802 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote. 803 804 // TODO: Input character set mapping support. 805 806 // Skip L marker for wide strings. 807 bool ThisIsWide = false; 808 if (ThisTokBuf[0] == 'L') { 809 ++ThisTokBuf; 810 ThisIsWide = true; 811 } 812 813 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?"); 814 ++ThisTokBuf; 815 816 // Check if this is a pascal string 817 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd && 818 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') { 819 820 // If the \p sequence is found in the first token, we have a pascal string 821 // Otherwise, if we already have a pascal string, ignore the first \p 822 if (i == 0) { 823 ++ThisTokBuf; 824 Pascal = true; 825 } else if (Pascal) 826 ThisTokBuf += 2; 827 } 828 829 while (ThisTokBuf != ThisTokEnd) { 830 // Is this a span of non-escape characters? 831 if (ThisTokBuf[0] != '\\') { 832 const char *InStart = ThisTokBuf; 833 do { 834 ++ThisTokBuf; 835 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\'); 836 837 // Copy the character span over. 838 unsigned Len = ThisTokBuf-InStart; 839 if (!AnyWide) { 840 memcpy(ResultPtr, InStart, Len); 841 ResultPtr += Len; 842 } else { 843 // Note: our internal rep of wide char tokens is always little-endian. 844 for (; Len; --Len, ++InStart) { 845 *ResultPtr++ = InStart[0]; 846 // Add zeros at the end. 847 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i) 848 *ResultPtr++ = 0; 849 } 850 } 851 continue; 852 } 853 // Is this a Universal Character Name escape? 854 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') { 855 ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr, 856 hadError, StringToks[i].getLocation(), ThisIsWide, PP); 857 continue; 858 } 859 // Otherwise, this is a non-UCN escape character. Process it. 860 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError, 861 StringToks[i].getLocation(), 862 ThisIsWide, PP); 863 864 // Note: our internal rep of wide char tokens is always little-endian. 865 *ResultPtr++ = ResultChar & 0xFF; 866 867 if (AnyWide) { 868 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i) 869 *ResultPtr++ = ResultChar >> i*8; 870 } 871 } 872 } 873 874 if (Pascal) { 875 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1; 876 877 // Verify that pascal strings aren't too large. 878 if (GetStringLength() > 256) { 879 PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long) 880 << SourceRange(StringToks[0].getLocation(), 881 StringToks[NumStringToks-1].getLocation()); 882 hadError = 1; 883 return; 884 } 885 } 886 } 887 888 889 /// getOffsetOfStringByte - This function returns the offset of the 890 /// specified byte of the string data represented by Token. This handles 891 /// advancing over escape sequences in the string. 892 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, 893 unsigned ByteNo, 894 Preprocessor &PP) { 895 // Get the spelling of the token. 896 llvm::SmallString<16> SpellingBuffer; 897 SpellingBuffer.resize(Tok.getLength()); 898 899 const char *SpellingPtr = &SpellingBuffer[0]; 900 unsigned TokLen = PP.getSpelling(Tok, SpellingPtr); 901 902 assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet"); 903 904 905 const char *SpellingStart = SpellingPtr; 906 const char *SpellingEnd = SpellingPtr+TokLen; 907 908 // Skip over the leading quote. 909 assert(SpellingPtr[0] == '"' && "Should be a string literal!"); 910 ++SpellingPtr; 911 912 // Skip over bytes until we find the offset we're looking for. 913 while (ByteNo) { 914 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!"); 915 916 // Step over non-escapes simply. 917 if (*SpellingPtr != '\\') { 918 ++SpellingPtr; 919 --ByteNo; 920 continue; 921 } 922 923 // Otherwise, this is an escape character. Advance over it. 924 bool HadError = false; 925 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError, 926 Tok.getLocation(), false, PP); 927 assert(!HadError && "This method isn't valid on erroneous strings"); 928 --ByteNo; 929 } 930 931 return SpellingPtr-SpellingStart; 932 } 933