1 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the NumericLiteralParser, CharLiteralParser, and
11 // StringLiteralParser interfaces.
13 //===----------------------------------------------------------------------===//
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;
24 /// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
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;
33 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
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();
52 static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
55 const char *TokRangeBegin,
56 const char *TokRangeEnd) {
57 SourceLocation Begin =
58 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
59 TokLoc.getManager(), Features);
61 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
62 TokLoc.getManager(), Features);
63 return CharSourceRange::getCharRange(Begin, End);
66 /// \brief Produce a diagnostic highlighting some portion of a literal.
68 /// Emits the diagnostic \p DiagID, highlighting the range of characters from
69 /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
70 /// a substring of a spelling buffer for the token beginning at \p TokBegin.
71 static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
72 const LangOptions &Features, FullSourceLoc TokLoc,
73 const char *TokBegin, const char *TokRangeBegin,
74 const char *TokRangeEnd, unsigned DiagID) {
75 SourceLocation Begin =
76 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
77 TokLoc.getManager(), Features);
78 return Diags->Report(Begin, DiagID) <<
79 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
82 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
83 /// either a character or a string literal.
84 static unsigned ProcessCharEscape(const char *ThisTokBegin,
85 const char *&ThisTokBuf,
86 const char *ThisTokEnd, bool &HadError,
87 FullSourceLoc Loc, unsigned CharWidth,
88 DiagnosticsEngine *Diags,
89 const LangOptions &Features) {
90 const char *EscapeBegin = ThisTokBuf;
95 // We know that this character can't be off the end of the buffer, because
96 // that would have been \", which would not have been the end of string.
97 unsigned ResultChar = *ThisTokBuf++;
99 // These map to themselves.
100 case '\\': case '\'': case '"': case '?': break;
102 // These have fixed mappings.
104 // TODO: K&R: the meaning of '\\a' is different in traditional C
112 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
113 diag::ext_nonstandard_escape) << "e";
118 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
119 diag::ext_nonstandard_escape) << "E";
137 case 'x': { // Hex escape.
139 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
141 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
142 diag::err_hex_escape_no_digits);
147 // Hex escapes are a maximal series of hex digits.
148 bool Overflow = false;
149 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
150 int CharVal = HexDigitValue(ThisTokBuf[0]);
151 if (CharVal == -1) break;
152 // About to shift out a digit?
153 Overflow |= (ResultChar & 0xF0000000) ? true : false;
155 ResultChar |= CharVal;
158 // See if any bits will be truncated when evaluated as a character.
159 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
161 ResultChar &= ~0U >> (32-CharWidth);
164 // Check for overflow.
165 if (Overflow && Diags) // Too many digits to fit in
166 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
167 diag::warn_hex_escape_too_large);
170 case '0': case '1': case '2': case '3':
171 case '4': case '5': case '6': case '7': {
176 // Octal escapes are a series of octal digits with maximum length 3.
177 // "\0123" is a two digit sequence equal to "\012" "3".
178 unsigned NumDigits = 0;
181 ResultChar |= *ThisTokBuf++ - '0';
183 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
184 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
186 // Check for overflow. Reject '\777', but not L'\777'.
187 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
189 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
190 diag::warn_octal_escape_too_large);
191 ResultChar &= ~0U >> (32-CharWidth);
196 // Otherwise, these are not valid escapes.
197 case '(': case '{': case '[': case '%':
198 // GCC accepts these as extensions. We warn about them as such though.
200 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
201 diag::ext_nonstandard_escape)
202 << std::string(1, ResultChar);
208 if (isgraph(ResultChar))
209 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
210 diag::ext_unknown_escape)
211 << std::string(1, ResultChar);
213 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
214 diag::ext_unknown_escape)
215 << "x" + llvm::utohexstr(ResultChar);
222 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
223 /// return the UTF32.
224 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
225 const char *ThisTokEnd,
226 uint32_t &UcnVal, unsigned short &UcnLen,
227 FullSourceLoc Loc, DiagnosticsEngine *Diags,
228 const LangOptions &Features,
229 bool in_char_string_literal = false) {
230 const char *UcnBegin = ThisTokBuf;
232 // Skip the '\u' char's.
235 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
237 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
238 diag::err_ucn_escape_no_digits);
241 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
242 unsigned short UcnLenSave = UcnLen;
243 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
244 int CharVal = HexDigitValue(ThisTokBuf[0]);
245 if (CharVal == -1) break;
249 // If we didn't consume the proper number of digits, there is a problem.
252 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
253 diag::err_ucn_escape_incomplete);
257 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
258 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
259 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
261 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
262 diag::err_ucn_escape_invalid);
266 // C++11 allows UCNs that refer to control characters and basic source
267 // characters inside character and string literals
269 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
270 bool IsError = (!Features.CPlusPlus0x || !in_char_string_literal);
272 char BasicSCSChar = UcnVal;
273 if (UcnVal >= 0x20 && UcnVal < 0x7f)
274 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
275 IsError ? diag::err_ucn_escape_basic_scs :
276 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
277 << StringRef(&BasicSCSChar, 1);
279 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
280 IsError ? diag::err_ucn_control_character :
281 diag::warn_cxx98_compat_literal_ucn_control_character);
287 if (!Features.CPlusPlus && !Features.C99 && Diags)
288 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
289 diag::warn_ucn_not_valid_in_c89);
294 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
295 /// which this UCN will occupy.
296 static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
297 const char *ThisTokEnd, unsigned CharByteWidth,
298 const LangOptions &Features, bool &HadError) {
299 // UTF-32: 4 bytes per escape.
300 if (CharByteWidth == 4)
304 unsigned short UcnLen = 0;
307 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
308 UcnLen, Loc, 0, Features, true)) {
313 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
314 if (CharByteWidth == 2)
315 return UcnVal <= 0xFFFF ? 2 : 4;
322 if (UcnVal < 0x10000)
327 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
328 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
329 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
330 /// we will likely rework our support for UCN's.
331 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
332 const char *ThisTokEnd,
333 char *&ResultBuf, bool &HadError,
334 FullSourceLoc Loc, unsigned CharByteWidth,
335 DiagnosticsEngine *Diags,
336 const LangOptions &Features) {
337 typedef uint32_t UTF32;
339 unsigned short UcnLen = 0;
340 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
341 Loc, Diags, Features, true)) {
346 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
347 "only character widths of 1, 2, or 4 bytes supported");
350 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
352 if (CharByteWidth == 4) {
353 // FIXME: Make the type of the result buffer correct instead of
354 // using reinterpret_cast.
355 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
361 if (CharByteWidth == 2) {
362 // FIXME: Make the type of the result buffer correct instead of
363 // using reinterpret_cast.
364 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
366 if (UcnVal <= (UTF32)0xFFFF) {
374 *ResultPtr = 0xD800 + (UcnVal >> 10);
375 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
380 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
382 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
383 // The conversion below was inspired by:
384 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
385 // First, we determine how many bytes the result will require.
386 typedef uint8_t UTF8;
388 unsigned short bytesToWrite = 0;
389 if (UcnVal < (UTF32)0x80)
391 else if (UcnVal < (UTF32)0x800)
393 else if (UcnVal < (UTF32)0x10000)
398 const unsigned byteMask = 0xBF;
399 const unsigned byteMark = 0x80;
401 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
402 // into the first byte, depending on how many bytes follow.
403 static const UTF8 firstByteMark[5] = {
404 0x00, 0x00, 0xC0, 0xE0, 0xF0
406 // Finally, we write the bytes into ResultBuf.
407 ResultBuf += bytesToWrite;
408 switch (bytesToWrite) { // note: everything falls through.
409 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
410 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
411 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
412 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
414 // Update the buffer.
415 ResultBuf += bytesToWrite;
419 /// integer-constant: [C99 6.4.4.1]
420 /// decimal-constant integer-suffix
421 /// octal-constant integer-suffix
422 /// hexadecimal-constant integer-suffix
423 /// user-defined-integer-literal: [C++11 lex.ext]
424 /// decimal-literal ud-suffix
425 /// octal-literal ud-suffix
426 /// hexadecimal-literal ud-suffix
427 /// decimal-constant:
429 /// decimal-constant digit
432 /// octal-constant octal-digit
433 /// hexadecimal-constant:
434 /// hexadecimal-prefix hexadecimal-digit
435 /// hexadecimal-constant hexadecimal-digit
436 /// hexadecimal-prefix: one of
439 /// unsigned-suffix [long-suffix]
440 /// unsigned-suffix [long-long-suffix]
441 /// long-suffix [unsigned-suffix]
442 /// long-long-suffix [unsigned-sufix]
444 /// 1 2 3 4 5 6 7 8 9
447 /// hexadecimal-digit:
448 /// 0 1 2 3 4 5 6 7 8 9
451 /// unsigned-suffix: one of
453 /// long-suffix: one of
455 /// long-long-suffix: one of
458 /// floating-constant: [C99 6.4.4.2]
459 /// TODO: add rules...
461 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
462 SourceLocation TokLoc,
464 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
466 // This routine assumes that the range begin/end matches the regex for integer
467 // and FP constants (specifically, the 'pp-number' regex), and assumes that
468 // the byte at "*end" is both valid and not part of the regex. Because of
469 // this, it doesn't have to check for 'overscan' in various places.
470 assert(!isalnum(*ThisTokEnd) && *ThisTokEnd != '.' && *ThisTokEnd != '_' &&
471 "Lexer didn't maximally munch?");
473 s = DigitsBegin = ThisTokBegin;
474 saw_exponent = false;
476 saw_ud_suffix = false;
482 isMicrosoftInteger = false;
485 if (*s == '0') { // parse radix
486 ParseNumberStartingWithZero(TokLoc);
489 } else { // the first digit is non-zero
492 if (s == ThisTokEnd) {
494 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
495 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
496 diag::err_invalid_decimal_digit) << StringRef(s, 1);
499 } else if (*s == '.') {
504 if ((*s == 'e' || *s == 'E')) { // exponent
505 const char *Exponent = s;
508 if (*s == '+' || *s == '-') s++; // sign
509 const char *first_non_digit = SkipDigits(s);
510 if (first_non_digit != s) {
513 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
514 diag::err_exponent_has_no_digits);
523 // Parse the suffix. At this point we can classify whether we have an FP or
525 bool isFPConstant = isFloatingLiteral();
527 // Loop over all of the characters of the suffix. If we see something bad,
528 // we break out of the loop.
529 for (; s != ThisTokEnd; ++s) {
531 case 'f': // FP Suffix for "float"
533 if (!isFPConstant) break; // Error for integer constant.
534 if (isFloat || isLong) break; // FF, LF invalid.
536 continue; // Success.
539 if (isFPConstant) break; // Error for floating constant.
540 if (isUnsigned) break; // Cannot be repeated.
542 continue; // Success.
545 if (isLong || isLongLong) break; // Cannot be repeated.
546 if (isFloat) break; // LF invalid.
548 // Check for long long. The L's need to be adjacent and the same case.
549 if (s+1 != ThisTokEnd && s[1] == s[0]) {
550 if (isFPConstant) break; // long long invalid for floats.
552 ++s; // Eat both of them.
556 continue; // Success.
559 if (PP.getLangOpts().MicrosoftExt) {
560 if (isFPConstant || isLong || isLongLong) break;
562 // Allow i8, i16, i32, i64, and i128.
563 if (s + 1 != ThisTokEnd) {
567 isMicrosoftInteger = true;
570 if (s + 2 == ThisTokEnd) break;
572 s += 3; // i16 suffix
573 isMicrosoftInteger = true;
575 else if (s[2] == '2') {
576 if (s + 3 == ThisTokEnd) break;
578 s += 4; // i128 suffix
579 isMicrosoftInteger = true;
584 if (s + 2 == ThisTokEnd) break;
586 s += 3; // i32 suffix
588 isMicrosoftInteger = true;
592 if (s + 2 == ThisTokEnd) break;
594 s += 3; // i64 suffix
596 isMicrosoftInteger = true;
608 if (isImaginary) break; // Cannot be repeated.
609 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
610 diag::ext_imaginary_constant);
612 continue; // Success.
614 // If we reached here, there was an error or a ud-suffix.
618 if (s != ThisTokEnd) {
619 if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
620 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
621 // with an '_' are ill-formed.
622 saw_ud_suffix = true;
626 // Report an error if there are any.
627 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
628 isFPConstant ? diag::err_invalid_suffix_float_constant :
629 diag::err_invalid_suffix_integer_constant)
630 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
636 /// ParseNumberStartingWithZero - This method is called when the first character
637 /// of the number is found to be a zero. This means it is either an octal
638 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
639 /// a floating point number (01239.123e4). Eat the prefix, determining the
641 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
642 assert(s[0] == '0' && "Invalid method call");
645 // Handle a hex number like 0x1234.
646 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
650 s = SkipHexDigits(s);
651 bool noSignificand = (s == DigitsBegin);
652 if (s == ThisTokEnd) {
654 } else if (*s == '.') {
657 const char *floatDigitsBegin = s;
658 s = SkipHexDigits(s);
659 noSignificand &= (floatDigitsBegin == s);
663 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
664 diag::err_hexconstant_requires_digits);
669 // A binary exponent can appear with or with a '.'. If dotted, the
670 // binary exponent is required.
671 if (*s == 'p' || *s == 'P') {
672 const char *Exponent = s;
675 if (*s == '+' || *s == '-') s++; // sign
676 const char *first_non_digit = SkipDigits(s);
677 if (first_non_digit == s) {
678 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
679 diag::err_exponent_has_no_digits);
685 if (!PP.getLangOpts().HexFloats)
686 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
687 } else if (saw_period) {
688 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
689 diag::err_hexconstant_requires_exponent);
695 // Handle simple binary numbers 0b01010
696 if (*s == 'b' || *s == 'B') {
697 // 0b101010 is a GCC extension.
698 PP.Diag(TokLoc, diag::ext_binary_literal);
702 s = SkipBinaryDigits(s);
703 if (s == ThisTokEnd) {
705 } else if (isxdigit(*s)) {
706 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
707 diag::err_invalid_binary_digit) << StringRef(s, 1);
710 // Other suffixes will be diagnosed by the caller.
714 // For now, the radix is set to 8. If we discover that we have a
715 // floating point constant, the radix will change to 10. Octal floating
716 // point constants are not permitted (only decimal and hexadecimal).
719 s = SkipOctalDigits(s);
721 return; // Done, simple octal number like 01234
723 // If we have some other non-octal digit that *is* a decimal digit, see if
724 // this is part of a floating point number like 094.123 or 09e1.
726 const char *EndDecimal = SkipDigits(s);
727 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
733 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
734 // the code is using an incorrect base.
735 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
736 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
737 diag::err_invalid_octal_digit) << StringRef(s, 1);
746 s = SkipDigits(s); // Skip suffix.
748 if (*s == 'e' || *s == 'E') { // exponent
749 const char *Exponent = s;
753 if (*s == '+' || *s == '-') s++; // sign
754 const char *first_non_digit = SkipDigits(s);
755 if (first_non_digit != s) {
758 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
759 diag::err_exponent_has_no_digits);
766 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
769 return NumDigits <= 64;
771 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
773 return NumDigits <= 19; // floor(log10(2^64))
775 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
777 llvm_unreachable("impossible Radix");
781 /// GetIntegerValue - Convert this numeric literal value to an APInt that
782 /// matches Val's input width. If there is an overflow, set Val to the low bits
783 /// of the result and return true. Otherwise, return false.
784 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
785 // Fast path: Compute a conservative bound on the maximum number of
786 // bits per digit in this radix. If we can't possibly overflow a
787 // uint64 based on that bound then do the simple conversion to
788 // integer. This avoids the expensive overflow checking below, and
789 // handles the common cases that matter (small decimal integers and
790 // hex/octal values which don't overflow).
791 const unsigned NumDigits = SuffixBegin - DigitsBegin;
792 if (alwaysFitsInto64Bits(radix, NumDigits)) {
794 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
795 N = N * radix + HexDigitValue(*Ptr);
797 // This will truncate the value to Val's input width. Simply check
798 // for overflow by comparing.
800 return Val.getZExtValue() != N;
804 const char *Ptr = DigitsBegin;
806 llvm::APInt RadixVal(Val.getBitWidth(), radix);
807 llvm::APInt CharVal(Val.getBitWidth(), 0);
808 llvm::APInt OldVal = Val;
810 bool OverflowOccurred = false;
811 while (Ptr < SuffixBegin) {
812 unsigned C = HexDigitValue(*Ptr++);
814 // If this letter is out of bound for this radix, reject it.
815 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
819 // Add the digit to the value in the appropriate radix. If adding in digits
820 // made the value smaller, then this overflowed.
823 // Multiply by radix, did overflow occur on the multiply?
825 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
827 // Add value, did overflow occur on the value?
828 // (a + b) ult b <=> overflow
830 OverflowOccurred |= Val.ult(CharVal);
832 return OverflowOccurred;
835 llvm::APFloat::opStatus
836 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
839 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
840 return Result.convertFromString(StringRef(ThisTokBegin, n),
841 APFloat::rmNearestTiesToEven);
846 /// user-defined-character-literal: [C++11 lex.ext]
847 /// character-literal ud-suffix
850 /// character-literal: [C++11 lex.ccon]
851 /// ' c-char-sequence '
852 /// u' c-char-sequence '
853 /// U' c-char-sequence '
854 /// L' c-char-sequence '
857 /// c-char-sequence c-char
859 /// any member of the source character set except the single-quote ',
860 /// backslash \, or new-line character
862 /// universal-character-name
864 /// simple-escape-sequence
865 /// octal-escape-sequence
866 /// hexadecimal-escape-sequence
867 /// simple-escape-sequence:
868 /// one of \' \" \? \\ \a \b \f \n \r \t \v
869 /// octal-escape-sequence:
871 /// \ octal-digit octal-digit
872 /// \ octal-digit octal-digit octal-digit
873 /// hexadecimal-escape-sequence:
874 /// \x hexadecimal-digit
875 /// hexadecimal-escape-sequence hexadecimal-digit
876 /// universal-character-name: [C++11 lex.charset]
878 /// \U hex-quad hex-quad
880 /// hex-digit hex-digit hex-digit hex-digit
883 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
884 SourceLocation Loc, Preprocessor &PP,
885 tok::TokenKind kind) {
886 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
891 const char *TokBegin = begin;
893 // Skip over wide character determinant.
894 if (Kind != tok::char_constant) {
898 // Skip over the entry quote.
899 assert(begin[0] == '\'' && "Invalid token lexed");
902 // Remove an optional ud-suffix.
903 if (end[-1] != '\'') {
904 const char *UDSuffixEnd = end;
907 } while (end[-1] != '\'');
908 UDSuffixBuf.assign(end, UDSuffixEnd);
909 UDSuffixOffset = end - TokBegin;
912 // Trim the ending quote.
913 assert(end != begin && "Invalid token lexed");
916 // FIXME: The "Value" is an uint64_t so we can handle char literals of
918 // FIXME: This extensively assumes that 'char' is 8-bits.
919 assert(PP.getTargetInfo().getCharWidth() == 8 &&
920 "Assumes char is 8 bits");
921 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
922 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
923 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
924 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
925 "Assumes sizeof(wchar) on target is <= 64");
927 SmallVector<uint32_t,4> codepoint_buffer;
928 codepoint_buffer.resize(end-begin);
929 uint32_t *buffer_begin = &codepoint_buffer.front();
930 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
932 // Unicode escapes representing characters that cannot be correctly
933 // represented in a single code unit are disallowed in character literals
934 // by this implementation.
935 uint32_t largest_character_for_kind;
936 if (tok::wide_char_constant == Kind) {
937 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
938 } else if (tok::utf16_char_constant == Kind) {
939 largest_character_for_kind = 0xFFFF;
940 } else if (tok::utf32_char_constant == Kind) {
941 largest_character_for_kind = 0x10FFFF;
943 largest_character_for_kind = 0x7Fu;
947 // Is this a span of non-escape characters?
948 if (begin[0] != '\\') {
949 char const *start = begin;
952 } while (begin != end && *begin != '\\');
954 char const *tmp_in_start = start;
955 uint32_t *tmp_out_start = buffer_begin;
956 ConversionResult res =
957 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
958 reinterpret_cast<UTF8 const *>(begin),
959 &buffer_begin,buffer_end,strictConversion);
960 if (res!=conversionOK) {
961 // If we see bad encoding for unprefixed character literals, warn and
962 // simply copy the byte values, for compatibility with gcc and
963 // older versions of clang.
964 bool NoErrorOnBadEncoding = isAscii();
965 unsigned Msg = diag::err_bad_character_encoding;
966 if (NoErrorOnBadEncoding)
967 Msg = diag::warn_bad_character_encoding;
969 if (NoErrorOnBadEncoding) {
970 start = tmp_in_start;
971 buffer_begin = tmp_out_start;
972 for ( ; start != begin; ++start, ++buffer_begin)
973 *buffer_begin = static_cast<uint8_t>(*start);
978 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
979 if (*tmp_out_start > largest_character_for_kind) {
981 PP.Diag(Loc, diag::err_character_too_large);
988 // Is this a Universal Character Name excape?
989 if (begin[1] == 'u' || begin[1] == 'U') {
990 unsigned short UcnLen = 0;
991 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
992 FullSourceLoc(Loc, PP.getSourceManager()),
993 &PP.getDiagnostics(), PP.getLangOpts(),
997 } else if (*buffer_begin > largest_character_for_kind) {
999 PP.Diag(Loc, diag::err_character_too_large);
1005 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1007 ProcessCharEscape(TokBegin, begin, end, HadError,
1008 FullSourceLoc(Loc,PP.getSourceManager()),
1009 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1010 *buffer_begin++ = result;
1013 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
1015 if (NumCharsSoFar > 1) {
1017 PP.Diag(Loc, diag::warn_extraneous_char_constant);
1018 else if (isAscii() && NumCharsSoFar == 4)
1019 PP.Diag(Loc, diag::ext_four_char_character_literal);
1021 PP.Diag(Loc, diag::ext_multichar_character_literal);
1023 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1026 IsMultiChar = false;
1028 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1030 // Narrow character literals act as though their value is concatenated
1031 // in this implementation, but warn on overflow.
1032 bool multi_char_too_long = false;
1033 if (isAscii() && isMultiChar()) {
1035 for (size_t i=0;i<NumCharsSoFar;++i) {
1036 // check for enough leading zeros to shift into
1037 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1039 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1041 } else if (NumCharsSoFar > 0) {
1042 // otherwise just take the last character
1043 LitVal = buffer_begin[-1];
1046 if (!HadError && multi_char_too_long) {
1047 PP.Diag(Loc,diag::warn_char_constant_too_large);
1050 // Transfer the value from APInt to uint64_t
1051 Value = LitVal.getZExtValue();
1053 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1054 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1055 // character constants are not sign extended in the this implementation:
1056 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1057 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1058 PP.getLangOpts().CharIsSigned)
1059 Value = (signed char)Value;
1063 /// string-literal: [C++0x lex.string]
1064 /// encoding-prefix " [s-char-sequence] "
1065 /// encoding-prefix R raw-string
1066 /// encoding-prefix:
1071 /// s-char-sequence:
1073 /// s-char-sequence s-char
1075 /// any member of the source character set except the double-quote ",
1076 /// backslash \, or new-line character
1078 /// universal-character-name
1080 /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1081 /// r-char-sequence:
1083 /// r-char-sequence r-char
1085 /// any member of the source character set, except a right parenthesis )
1086 /// followed by the initial d-char-sequence (which may be empty)
1087 /// followed by a double quote ".
1088 /// d-char-sequence:
1090 /// d-char-sequence d-char
1092 /// any member of the basic source character set except:
1093 /// space, the left parenthesis (, the right parenthesis ),
1094 /// the backslash \, and the control characters representing horizontal
1095 /// tab, vertical tab, form feed, and newline.
1096 /// escape-sequence: [C++0x lex.ccon]
1097 /// simple-escape-sequence
1098 /// octal-escape-sequence
1099 /// hexadecimal-escape-sequence
1100 /// simple-escape-sequence:
1101 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1102 /// octal-escape-sequence:
1104 /// \ octal-digit octal-digit
1105 /// \ octal-digit octal-digit octal-digit
1106 /// hexadecimal-escape-sequence:
1107 /// \x hexadecimal-digit
1108 /// hexadecimal-escape-sequence hexadecimal-digit
1109 /// universal-character-name:
1111 /// \U hex-quad hex-quad
1113 /// hex-digit hex-digit hex-digit hex-digit
1116 StringLiteralParser::
1117 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1118 Preprocessor &PP, bool Complain)
1119 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1120 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1121 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1122 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1123 init(StringToks, NumStringToks);
1126 void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1127 // The literal token may have come from an invalid source location (e.g. due
1128 // to a PCH error), in which case the token length will be 0.
1129 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1130 return DiagnoseLexingError(SourceLocation());
1132 // Scan all of the string portions, remember the max individual token length,
1133 // computing a bound on the concatenated string length, and see whether any
1134 // piece is a wide-string. If any of the string portions is a wide-string
1135 // literal, the result is a wide-string literal [C99 6.4.5p4].
1136 assert(NumStringToks && "expected at least one token");
1137 MaxTokenLength = StringToks[0].getLength();
1138 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1139 SizeBound = StringToks[0].getLength()-2; // -2 for "".
1140 Kind = StringToks[0].getKind();
1144 // Implement Translation Phase #6: concatenation of string literals
1145 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1146 for (unsigned i = 1; i != NumStringToks; ++i) {
1147 if (StringToks[i].getLength() < 2)
1148 return DiagnoseLexingError(StringToks[i].getLocation());
1150 // The string could be shorter than this if it needs cleaning, but this is a
1151 // reasonable bound, which is all we need.
1152 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1153 SizeBound += StringToks[i].getLength()-2; // -2 for "".
1155 // Remember maximum string piece length.
1156 if (StringToks[i].getLength() > MaxTokenLength)
1157 MaxTokenLength = StringToks[i].getLength();
1159 // Remember if we see any wide or utf-8/16/32 strings.
1160 // Also check for illegal concatenations.
1161 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1163 Kind = StringToks[i].getKind();
1166 Diags->Report(StringToks[i].getLocation(),
1167 diag::err_unsupported_string_concat);
1173 // Include space for the null terminator.
1176 // TODO: K&R warning: "traditional C rejects string constant concatenation"
1178 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1179 CharByteWidth = getCharWidth(Kind, Target);
1180 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1183 // The output buffer size needs to be large enough to hold wide characters.
1184 // This is a worst-case assumption which basically corresponds to L"" "long".
1185 SizeBound *= CharByteWidth;
1187 // Size the temporary buffer to hold the result string data.
1188 ResultBuf.resize(SizeBound);
1190 // Likewise, but for each string piece.
1191 SmallString<512> TokenBuf;
1192 TokenBuf.resize(MaxTokenLength);
1194 // Loop over all the strings, getting their spelling, and expanding them to
1195 // wide strings as appropriate.
1196 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
1200 SourceLocation UDSuffixTokLoc;
1202 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1203 const char *ThisTokBuf = &TokenBuf[0];
1204 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1205 // that ThisTokBuf points to a buffer that is big enough for the whole token
1206 // and 'spelled' tokens can only shrink.
1207 bool StringInvalid = false;
1208 unsigned ThisTokLen =
1209 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1212 return DiagnoseLexingError(StringToks[i].getLocation());
1214 const char *ThisTokBegin = ThisTokBuf;
1215 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1217 // Remove an optional ud-suffix.
1218 if (ThisTokEnd[-1] != '"') {
1219 const char *UDSuffixEnd = ThisTokEnd;
1222 } while (ThisTokEnd[-1] != '"');
1224 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1226 if (UDSuffixBuf.empty()) {
1227 UDSuffixBuf.assign(UDSuffix);
1229 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1230 UDSuffixTokLoc = StringToks[i].getLocation();
1231 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1232 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1233 // result of a concatenation involving at least one user-defined-string-
1234 // literal, all the participating user-defined-string-literals shall
1235 // have the same ud-suffix.
1237 SourceLocation TokLoc = StringToks[i].getLocation();
1238 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1239 << UDSuffixBuf << UDSuffix
1240 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1241 << SourceRange(TokLoc, TokLoc);
1247 // Strip the end quote.
1250 // TODO: Input character set mapping support.
1252 // Skip marker for wide or unicode strings.
1253 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1255 // Skip 8 of u8 marker for utf8 strings.
1256 if (ThisTokBuf[0] == '8')
1260 // Check for raw string
1261 if (ThisTokBuf[0] == 'R') {
1262 ThisTokBuf += 2; // skip R"
1264 const char *Prefix = ThisTokBuf;
1265 while (ThisTokBuf[0] != '(')
1267 ++ThisTokBuf; // skip '('
1269 // Remove same number of characters from the end
1270 ThisTokEnd -= ThisTokBuf - Prefix;
1271 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1273 // Copy the string over
1274 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1275 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1278 if (ThisTokBuf[0] != '"') {
1279 // The file may have come from PCH and then changed after loading the
1280 // PCH; Fail gracefully.
1281 return DiagnoseLexingError(StringToks[i].getLocation());
1283 ++ThisTokBuf; // skip "
1285 // Check if this is a pascal string
1286 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1287 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1289 // If the \p sequence is found in the first token, we have a pascal string
1290 // Otherwise, if we already have a pascal string, ignore the first \p
1298 while (ThisTokBuf != ThisTokEnd) {
1299 // Is this a span of non-escape characters?
1300 if (ThisTokBuf[0] != '\\') {
1301 const char *InStart = ThisTokBuf;
1304 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1306 // Copy the character span over.
1307 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1308 StringRef(InStart, ThisTokBuf - InStart)))
1312 // Is this a Universal Character Name escape?
1313 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1314 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1315 ResultPtr, hadError,
1316 FullSourceLoc(StringToks[i].getLocation(), SM),
1317 CharByteWidth, Diags, Features);
1320 // Otherwise, this is a non-UCN escape character. Process it.
1321 unsigned ResultChar =
1322 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1323 FullSourceLoc(StringToks[i].getLocation(), SM),
1324 CharByteWidth*8, Diags, Features);
1326 if (CharByteWidth == 4) {
1327 // FIXME: Make the type of the result buffer correct instead of
1328 // using reinterpret_cast.
1329 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1330 *ResultWidePtr = ResultChar;
1332 } else if (CharByteWidth == 2) {
1333 // FIXME: Make the type of the result buffer correct instead of
1334 // using reinterpret_cast.
1335 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1336 *ResultWidePtr = ResultChar & 0xFFFF;
1339 assert(CharByteWidth == 1 && "Unexpected char width");
1340 *ResultPtr++ = ResultChar & 0xFF;
1347 if (CharByteWidth == 4) {
1348 // FIXME: Make the type of the result buffer correct instead of
1349 // using reinterpret_cast.
1350 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1351 ResultWidePtr[0] = GetNumStringChars() - 1;
1352 } else if (CharByteWidth == 2) {
1353 // FIXME: Make the type of the result buffer correct instead of
1354 // using reinterpret_cast.
1355 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1356 ResultWidePtr[0] = GetNumStringChars() - 1;
1358 assert(CharByteWidth == 1 && "Unexpected char width");
1359 ResultBuf[0] = GetNumStringChars() - 1;
1362 // Verify that pascal strings aren't too large.
1363 if (GetStringLength() > 256) {
1365 Diags->Report(StringToks[0].getLocation(),
1366 diag::err_pascal_string_too_long)
1367 << SourceRange(StringToks[0].getLocation(),
1368 StringToks[NumStringToks-1].getLocation());
1373 // Complain if this string literal has too many characters.
1374 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1376 if (GetNumStringChars() > MaxChars)
1377 Diags->Report(StringToks[0].getLocation(),
1378 diag::ext_string_too_long)
1379 << GetNumStringChars() << MaxChars
1380 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1381 << SourceRange(StringToks[0].getLocation(),
1382 StringToks[NumStringToks-1].getLocation());
1386 static const char *resyncUTF8(const char *Err, const char *End) {
1389 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1390 while (++Err != End && (*Err & 0xC0) == 0x80)
1395 /// \brief This function copies from Fragment, which is a sequence of bytes
1396 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1397 /// Performs widening for multi-byte characters.
1398 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1399 const char *TokBegin,
1400 StringRef Fragment) {
1401 const UTF8 *ErrorPtrTmp;
1402 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1405 // If we see bad encoding for unprefixed string literals, warn and
1406 // simply copy the byte values, for compatibility with gcc and older
1407 // versions of clang.
1408 bool NoErrorOnBadEncoding = isAscii();
1409 if (NoErrorOnBadEncoding) {
1410 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1411 ResultPtr += Fragment.size();
1415 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1417 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1418 const DiagnosticBuilder &Builder =
1419 Diag(Diags, Features, SourceLoc, TokBegin,
1420 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1421 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1422 : diag::err_bad_string_encoding);
1424 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1425 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1427 // Decode into a dummy buffer.
1428 SmallString<512> Dummy;
1429 Dummy.reserve(Fragment.size() * CharByteWidth);
1430 char *Ptr = Dummy.data();
1432 while (!Builder.hasMaxRanges() &&
1433 !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1434 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1435 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1436 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1437 ErrorPtr, NextStart);
1438 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1441 return !NoErrorOnBadEncoding;
1444 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1447 Diags->Report(Loc, diag::err_lexing_string);
1450 /// getOffsetOfStringByte - This function returns the offset of the
1451 /// specified byte of the string data represented by Token. This handles
1452 /// advancing over escape sequences in the string.
1453 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1454 unsigned ByteNo) const {
1455 // Get the spelling of the token.
1456 SmallString<32> SpellingBuffer;
1457 SpellingBuffer.resize(Tok.getLength());
1459 bool StringInvalid = false;
1460 const char *SpellingPtr = &SpellingBuffer[0];
1461 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1466 const char *SpellingStart = SpellingPtr;
1467 const char *SpellingEnd = SpellingPtr+TokLen;
1469 // Handle UTF-8 strings just like narrow strings.
1470 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1473 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1474 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1476 // For raw string literals, this is easy.
1477 if (SpellingPtr[0] == 'R') {
1478 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1481 while (*SpellingPtr != '(') {
1483 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1487 return SpellingPtr - SpellingStart + ByteNo;
1490 // Skip over the leading quote
1491 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1494 // Skip over bytes until we find the offset we're looking for.
1496 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1498 // Step over non-escapes simply.
1499 if (*SpellingPtr != '\\') {
1505 // Otherwise, this is an escape character. Advance over it.
1506 bool HadError = false;
1507 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1508 const char *EscapePtr = SpellingPtr;
1509 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1510 1, Features, HadError);
1512 // ByteNo is somewhere within the escape sequence.
1513 SpellingPtr = EscapePtr;
1518 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1519 FullSourceLoc(Tok.getLocation(), SM),
1520 CharByteWidth*8, Diags, Features);
1523 assert(!HadError && "This method isn't valid on erroneous strings");
1526 return SpellingPtr-SpellingStart;