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/Basic/CharInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/LexDiagnostic.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/ConvertUTF.h"
22 #include "llvm/Support/ErrorHandling.h"
24 using namespace clang;
26 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
28 default: llvm_unreachable("Unknown token type!");
29 case tok::char_constant:
30 case tok::string_literal:
31 case tok::utf8_char_constant:
32 case tok::utf8_string_literal:
33 return Target.getCharWidth();
34 case tok::wide_char_constant:
35 case tok::wide_string_literal:
36 return Target.getWCharWidth();
37 case tok::utf16_char_constant:
38 case tok::utf16_string_literal:
39 return Target.getChar16Width();
40 case tok::utf32_char_constant:
41 case tok::utf32_string_literal:
42 return Target.getChar32Width();
46 static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
49 const char *TokRangeBegin,
50 const char *TokRangeEnd) {
51 SourceLocation Begin =
52 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
53 TokLoc.getManager(), Features);
55 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
56 TokLoc.getManager(), Features);
57 return CharSourceRange::getCharRange(Begin, End);
60 /// \brief Produce a diagnostic highlighting some portion of a literal.
62 /// Emits the diagnostic \p DiagID, highlighting the range of characters from
63 /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
64 /// a substring of a spelling buffer for the token beginning at \p TokBegin.
65 static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
66 const LangOptions &Features, FullSourceLoc TokLoc,
67 const char *TokBegin, const char *TokRangeBegin,
68 const char *TokRangeEnd, unsigned DiagID) {
69 SourceLocation Begin =
70 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
71 TokLoc.getManager(), Features);
72 return Diags->Report(Begin, DiagID) <<
73 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
76 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
77 /// either a character or a string literal.
78 static unsigned ProcessCharEscape(const char *ThisTokBegin,
79 const char *&ThisTokBuf,
80 const char *ThisTokEnd, bool &HadError,
81 FullSourceLoc Loc, unsigned CharWidth,
82 DiagnosticsEngine *Diags,
83 const LangOptions &Features) {
84 const char *EscapeBegin = ThisTokBuf;
89 // We know that this character can't be off the end of the buffer, because
90 // that would have been \", which would not have been the end of string.
91 unsigned ResultChar = *ThisTokBuf++;
93 // These map to themselves.
94 case '\\': case '\'': case '"': case '?': break;
96 // These have fixed mappings.
98 // TODO: K&R: the meaning of '\\a' is different in traditional C
106 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
107 diag::ext_nonstandard_escape) << "e";
112 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
113 diag::ext_nonstandard_escape) << "E";
131 case 'x': { // Hex escape.
133 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
135 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
136 diag::err_hex_escape_no_digits) << "x";
141 // Hex escapes are a maximal series of hex digits.
142 bool Overflow = false;
143 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
144 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
145 if (CharVal == -1) break;
146 // About to shift out a digit?
147 if (ResultChar & 0xF0000000)
150 ResultChar |= CharVal;
153 // See if any bits will be truncated when evaluated as a character.
154 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
156 ResultChar &= ~0U >> (32-CharWidth);
159 // Check for overflow.
160 if (Overflow && Diags) // Too many digits to fit in
161 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
162 diag::err_escape_too_large) << 0;
165 case '0': case '1': case '2': case '3':
166 case '4': case '5': case '6': case '7': {
171 // Octal escapes are a series of octal digits with maximum length 3.
172 // "\0123" is a two digit sequence equal to "\012" "3".
173 unsigned NumDigits = 0;
176 ResultChar |= *ThisTokBuf++ - '0';
178 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
179 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
181 // Check for overflow. Reject '\777', but not L'\777'.
182 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
184 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
185 diag::err_escape_too_large) << 1;
186 ResultChar &= ~0U >> (32-CharWidth);
191 // Otherwise, these are not valid escapes.
192 case '(': case '{': case '[': case '%':
193 // GCC accepts these as extensions. We warn about them as such though.
195 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
196 diag::ext_nonstandard_escape)
197 << std::string(1, ResultChar);
203 if (isPrintable(ResultChar))
204 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
205 diag::ext_unknown_escape)
206 << std::string(1, ResultChar);
208 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
209 diag::ext_unknown_escape)
210 << "x" + llvm::utohexstr(ResultChar);
217 static void appendCodePoint(unsigned Codepoint,
218 llvm::SmallVectorImpl<char> &Str) {
220 char *ResultPtr = ResultBuf;
221 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
223 assert(Res && "Unexpected conversion failure");
224 Str.append(ResultBuf, ResultPtr);
227 void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
228 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
235 assert(*I == 'u' || *I == 'U');
237 unsigned NumHexDigits;
243 assert(I + NumHexDigits <= E);
245 uint32_t CodePoint = 0;
246 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
247 unsigned Value = llvm::hexDigitValue(*I);
248 assert(Value != -1U);
254 appendCodePoint(CodePoint, Buf);
259 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
260 /// return the UTF32.
261 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
262 const char *ThisTokEnd,
263 uint32_t &UcnVal, unsigned short &UcnLen,
264 FullSourceLoc Loc, DiagnosticsEngine *Diags,
265 const LangOptions &Features,
266 bool in_char_string_literal = false) {
267 const char *UcnBegin = ThisTokBuf;
269 // Skip the '\u' char's.
272 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
274 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
275 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
278 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
279 unsigned short UcnLenSave = UcnLen;
280 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
281 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
282 if (CharVal == -1) break;
286 // If we didn't consume the proper number of digits, there is a problem.
289 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
290 diag::err_ucn_escape_incomplete);
294 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
295 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
296 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
298 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
299 diag::err_ucn_escape_invalid);
303 // C++11 allows UCNs that refer to control characters and basic source
304 // characters inside character and string literals
306 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
307 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
309 char BasicSCSChar = UcnVal;
310 if (UcnVal >= 0x20 && UcnVal < 0x7f)
311 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
312 IsError ? diag::err_ucn_escape_basic_scs :
313 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
314 << StringRef(&BasicSCSChar, 1);
316 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
317 IsError ? diag::err_ucn_control_character :
318 diag::warn_cxx98_compat_literal_ucn_control_character);
324 if (!Features.CPlusPlus && !Features.C99 && Diags)
325 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
326 diag::warn_ucn_not_valid_in_c89_literal);
331 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
332 /// which this UCN will occupy.
333 static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
334 const char *ThisTokEnd, unsigned CharByteWidth,
335 const LangOptions &Features, bool &HadError) {
336 // UTF-32: 4 bytes per escape.
337 if (CharByteWidth == 4)
341 unsigned short UcnLen = 0;
344 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
345 UcnLen, Loc, nullptr, Features, true)) {
350 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
351 if (CharByteWidth == 2)
352 return UcnVal <= 0xFFFF ? 2 : 4;
359 if (UcnVal < 0x10000)
364 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
365 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
366 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
367 /// we will likely rework our support for UCN's.
368 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
369 const char *ThisTokEnd,
370 char *&ResultBuf, bool &HadError,
371 FullSourceLoc Loc, unsigned CharByteWidth,
372 DiagnosticsEngine *Diags,
373 const LangOptions &Features) {
374 typedef uint32_t UTF32;
376 unsigned short UcnLen = 0;
377 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
378 Loc, Diags, Features, true)) {
383 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
384 "only character widths of 1, 2, or 4 bytes supported");
387 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
389 if (CharByteWidth == 4) {
390 // FIXME: Make the type of the result buffer correct instead of
391 // using reinterpret_cast.
392 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
398 if (CharByteWidth == 2) {
399 // FIXME: Make the type of the result buffer correct instead of
400 // using reinterpret_cast.
401 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
403 if (UcnVal <= (UTF32)0xFFFF) {
411 *ResultPtr = 0xD800 + (UcnVal >> 10);
412 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
417 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
419 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
420 // The conversion below was inspired by:
421 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
422 // First, we determine how many bytes the result will require.
423 typedef uint8_t UTF8;
425 unsigned short bytesToWrite = 0;
426 if (UcnVal < (UTF32)0x80)
428 else if (UcnVal < (UTF32)0x800)
430 else if (UcnVal < (UTF32)0x10000)
435 const unsigned byteMask = 0xBF;
436 const unsigned byteMark = 0x80;
438 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
439 // into the first byte, depending on how many bytes follow.
440 static const UTF8 firstByteMark[5] = {
441 0x00, 0x00, 0xC0, 0xE0, 0xF0
443 // Finally, we write the bytes into ResultBuf.
444 ResultBuf += bytesToWrite;
445 switch (bytesToWrite) { // note: everything falls through.
446 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
447 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
448 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
449 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
451 // Update the buffer.
452 ResultBuf += bytesToWrite;
456 /// integer-constant: [C99 6.4.4.1]
457 /// decimal-constant integer-suffix
458 /// octal-constant integer-suffix
459 /// hexadecimal-constant integer-suffix
460 /// binary-literal integer-suffix [GNU, C++1y]
461 /// user-defined-integer-literal: [C++11 lex.ext]
462 /// decimal-literal ud-suffix
463 /// octal-literal ud-suffix
464 /// hexadecimal-literal ud-suffix
465 /// binary-literal ud-suffix [GNU, C++1y]
466 /// decimal-constant:
468 /// decimal-constant digit
471 /// octal-constant octal-digit
472 /// hexadecimal-constant:
473 /// hexadecimal-prefix hexadecimal-digit
474 /// hexadecimal-constant hexadecimal-digit
475 /// hexadecimal-prefix: one of
480 /// binary-literal binary-digit
482 /// unsigned-suffix [long-suffix]
483 /// unsigned-suffix [long-long-suffix]
484 /// long-suffix [unsigned-suffix]
485 /// long-long-suffix [unsigned-sufix]
487 /// 1 2 3 4 5 6 7 8 9
490 /// hexadecimal-digit:
491 /// 0 1 2 3 4 5 6 7 8 9
497 /// unsigned-suffix: one of
499 /// long-suffix: one of
501 /// long-long-suffix: one of
504 /// floating-constant: [C99 6.4.4.2]
505 /// TODO: add rules...
507 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
508 SourceLocation TokLoc,
510 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
512 // This routine assumes that the range begin/end matches the regex for integer
513 // and FP constants (specifically, the 'pp-number' regex), and assumes that
514 // the byte at "*end" is both valid and not part of the regex. Because of
515 // this, it doesn't have to check for 'overscan' in various places.
516 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
518 s = DigitsBegin = ThisTokBegin;
519 saw_exponent = false;
521 saw_ud_suffix = false;
529 MicrosoftInteger = 0;
532 if (*s == '0') { // parse radix
533 ParseNumberStartingWithZero(TokLoc);
536 } else { // the first digit is non-zero
539 if (s == ThisTokEnd) {
542 ParseDecimalOrOctalCommon(TokLoc);
549 checkSeparator(TokLoc, s, CSK_AfterDigits);
551 // Parse the suffix. At this point we can classify whether we have an FP or
553 bool isFPConstant = isFloatingLiteral();
554 const char *ImaginarySuffixLoc = nullptr;
556 // Loop over all of the characters of the suffix. If we see something bad,
557 // we break out of the loop.
558 for (; s != ThisTokEnd; ++s) {
560 case 'h': // FP Suffix for "half".
562 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
563 if (!PP.getLangOpts().Half) break;
564 if (!isFPConstant) break; // Error for integer constant.
565 if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
567 continue; // Success.
568 case 'f': // FP Suffix for "float"
570 if (!isFPConstant) break; // Error for integer constant.
571 if (isHalf || isFloat || isLong || isFloat128)
572 break; // HF, FF, LF, QF invalid.
574 continue; // Success.
575 case 'q': // FP Suffix for "__float128"
577 if (!isFPConstant) break; // Error for integer constant.
578 if (isHalf || isFloat || isLong || isFloat128)
579 break; // HQ, FQ, LQ, QQ invalid.
581 continue; // Success.
584 if (isFPConstant) break; // Error for floating constant.
585 if (isUnsigned) break; // Cannot be repeated.
587 continue; // Success.
590 if (isLong || isLongLong) break; // Cannot be repeated.
591 if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid.
593 // Check for long long. The L's need to be adjacent and the same case.
595 assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
596 if (isFPConstant) break; // long long invalid for floats.
598 ++s; // Eat both of them.
602 continue; // Success.
605 if (PP.getLangOpts().MicrosoftExt) {
606 if (isLong || isLongLong || MicrosoftInteger)
610 // Allow i8, i16, i32, and i64.
614 MicrosoftInteger = 8;
618 s += 3; // i16 suffix
619 MicrosoftInteger = 16;
624 s += 3; // i32 suffix
625 MicrosoftInteger = 32;
630 s += 3; // i64 suffix
631 MicrosoftInteger = 64;
638 if (MicrosoftInteger) {
639 assert(s <= ThisTokEnd && "didn't maximally munch?");
643 // "i", "if", and "il" are user-defined suffixes in C++1y.
644 if (*s == 'i' && PP.getLangOpts().CPlusPlus14)
649 if (isImaginary) break; // Cannot be repeated.
651 ImaginarySuffixLoc = s;
652 continue; // Success.
654 // If we reached here, there was an error or a ud-suffix.
658 if (s != ThisTokEnd) {
659 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
660 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
661 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
662 // Any suffix pieces we might have parsed are actually part of the
670 MicrosoftInteger = 0;
672 saw_ud_suffix = true;
676 // Report an error if there are any.
677 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
678 diag::err_invalid_suffix_constant)
679 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin) << isFPConstant;
685 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
686 ImaginarySuffixLoc - ThisTokBegin),
687 diag::ext_imaginary_constant);
691 /// ParseDecimalOrOctalCommon - This method is called for decimal or octal
692 /// numbers. It issues an error for illegal digits, and handles floating point
693 /// parsing. If it detects a floating point number, the radix is set to 10.
694 void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
695 assert((radix == 8 || radix == 10) && "Unexpected radix");
697 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
698 // the code is using an incorrect base.
699 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
700 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
701 diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
707 checkSeparator(TokLoc, s, CSK_AfterDigits);
711 checkSeparator(TokLoc, s, CSK_BeforeDigits);
712 s = SkipDigits(s); // Skip suffix.
714 if (*s == 'e' || *s == 'E') { // exponent
715 checkSeparator(TokLoc, s, CSK_AfterDigits);
716 const char *Exponent = s;
720 if (*s == '+' || *s == '-') s++; // sign
721 const char *first_non_digit = SkipDigits(s);
722 if (containsDigits(s, first_non_digit)) {
723 checkSeparator(TokLoc, s, CSK_BeforeDigits);
726 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
727 diag::err_exponent_has_no_digits);
734 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
735 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
736 /// treat it as an invalid suffix.
737 bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
739 if (!LangOpts.CPlusPlus11 || Suffix.empty())
742 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
743 if (Suffix[0] == '_')
746 // In C++11, there are no library suffixes.
747 if (!LangOpts.CPlusPlus14)
750 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
751 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
752 return llvm::StringSwitch<bool>(Suffix)
753 .Cases("h", "min", "s", true)
754 .Cases("ms", "us", "ns", true)
755 .Cases("il", "i", "if", true)
759 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
761 CheckSeparatorKind IsAfterDigits) {
762 if (IsAfterDigits == CSK_AfterDigits) {
763 if (Pos == ThisTokBegin)
766 } else if (Pos == ThisTokEnd)
769 if (isDigitSeparator(*Pos))
770 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
771 diag::err_digit_separator_not_between_digits)
775 /// ParseNumberStartingWithZero - This method is called when the first character
776 /// of the number is found to be a zero. This means it is either an octal
777 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
778 /// a floating point number (01239.123e4). Eat the prefix, determining the
780 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
781 assert(s[0] == '0' && "Invalid method call");
786 // Handle a hex number like 0x1234.
787 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
789 assert(s < ThisTokEnd && "didn't maximally munch?");
792 s = SkipHexDigits(s);
793 bool HasSignificandDigits = containsDigits(DigitsBegin, s);
794 if (s == ThisTokEnd) {
796 } else if (*s == '.') {
799 const char *floatDigitsBegin = s;
800 s = SkipHexDigits(s);
801 if (containsDigits(floatDigitsBegin, s))
802 HasSignificandDigits = true;
803 if (HasSignificandDigits)
804 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
807 if (!HasSignificandDigits) {
808 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
809 diag::err_hex_constant_requires)
810 << PP.getLangOpts().CPlusPlus << 1;
815 // A binary exponent can appear with or with a '.'. If dotted, the
816 // binary exponent is required.
817 if (*s == 'p' || *s == 'P') {
818 checkSeparator(TokLoc, s, CSK_AfterDigits);
819 const char *Exponent = s;
822 if (*s == '+' || *s == '-') s++; // sign
823 const char *first_non_digit = SkipDigits(s);
824 if (!containsDigits(s, first_non_digit)) {
825 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
826 diag::err_exponent_has_no_digits);
830 checkSeparator(TokLoc, s, CSK_BeforeDigits);
833 if (!PP.getLangOpts().HexFloats)
834 PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
835 ? diag::ext_hex_literal_invalid
836 : diag::ext_hex_constant_invalid);
837 else if (PP.getLangOpts().CPlusPlus1z)
838 PP.Diag(TokLoc, diag::warn_cxx1z_hex_literal);
839 } else if (saw_period) {
840 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
841 diag::err_hex_constant_requires)
842 << PP.getLangOpts().CPlusPlus << 0;
848 // Handle simple binary numbers 0b01010
849 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
850 // 0b101010 is a C++1y / GCC extension.
852 PP.getLangOpts().CPlusPlus14
853 ? diag::warn_cxx11_compat_binary_literal
854 : PP.getLangOpts().CPlusPlus
855 ? diag::ext_binary_literal_cxx14
856 : diag::ext_binary_literal);
858 assert(s < ThisTokEnd && "didn't maximally munch?");
861 s = SkipBinaryDigits(s);
862 if (s == ThisTokEnd) {
864 } else if (isHexDigit(*s)) {
865 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
866 diag::err_invalid_digit) << StringRef(s, 1) << 2;
869 // Other suffixes will be diagnosed by the caller.
873 // For now, the radix is set to 8. If we discover that we have a
874 // floating point constant, the radix will change to 10. Octal floating
875 // point constants are not permitted (only decimal and hexadecimal).
878 s = SkipOctalDigits(s);
880 return; // Done, simple octal number like 01234
882 // If we have some other non-octal digit that *is* a decimal digit, see if
883 // this is part of a floating point number like 094.123 or 09e1.
885 const char *EndDecimal = SkipDigits(s);
886 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
892 ParseDecimalOrOctalCommon(TokLoc);
895 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
898 return NumDigits <= 64;
900 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
902 return NumDigits <= 19; // floor(log10(2^64))
904 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
906 llvm_unreachable("impossible Radix");
910 /// GetIntegerValue - Convert this numeric literal value to an APInt that
911 /// matches Val's input width. If there is an overflow, set Val to the low bits
912 /// of the result and return true. Otherwise, return false.
913 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
914 // Fast path: Compute a conservative bound on the maximum number of
915 // bits per digit in this radix. If we can't possibly overflow a
916 // uint64 based on that bound then do the simple conversion to
917 // integer. This avoids the expensive overflow checking below, and
918 // handles the common cases that matter (small decimal integers and
919 // hex/octal values which don't overflow).
920 const unsigned NumDigits = SuffixBegin - DigitsBegin;
921 if (alwaysFitsInto64Bits(radix, NumDigits)) {
923 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
924 if (!isDigitSeparator(*Ptr))
925 N = N * radix + llvm::hexDigitValue(*Ptr);
927 // This will truncate the value to Val's input width. Simply check
928 // for overflow by comparing.
930 return Val.getZExtValue() != N;
934 const char *Ptr = DigitsBegin;
936 llvm::APInt RadixVal(Val.getBitWidth(), radix);
937 llvm::APInt CharVal(Val.getBitWidth(), 0);
938 llvm::APInt OldVal = Val;
940 bool OverflowOccurred = false;
941 while (Ptr < SuffixBegin) {
942 if (isDigitSeparator(*Ptr)) {
947 unsigned C = llvm::hexDigitValue(*Ptr++);
949 // If this letter is out of bound for this radix, reject it.
950 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
954 // Add the digit to the value in the appropriate radix. If adding in digits
955 // made the value smaller, then this overflowed.
958 // Multiply by radix, did overflow occur on the multiply?
960 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
962 // Add value, did overflow occur on the value?
963 // (a + b) ult b <=> overflow
965 OverflowOccurred |= Val.ult(CharVal);
967 return OverflowOccurred;
970 llvm::APFloat::opStatus
971 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
974 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
976 llvm::SmallString<16> Buffer;
977 StringRef Str(ThisTokBegin, n);
978 if (Str.find('\'') != StringRef::npos) {
980 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
985 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
990 /// user-defined-character-literal: [C++11 lex.ext]
991 /// character-literal ud-suffix
994 /// character-literal: [C++11 lex.ccon]
995 /// ' c-char-sequence '
996 /// u' c-char-sequence '
997 /// U' c-char-sequence '
998 /// L' c-char-sequence '
999 /// u8' c-char-sequence ' [C++1z lex.ccon]
1000 /// c-char-sequence:
1002 /// c-char-sequence c-char
1004 /// any member of the source character set except the single-quote ',
1005 /// backslash \, or new-line character
1007 /// universal-character-name
1008 /// escape-sequence:
1009 /// simple-escape-sequence
1010 /// octal-escape-sequence
1011 /// hexadecimal-escape-sequence
1012 /// simple-escape-sequence:
1013 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1014 /// octal-escape-sequence:
1016 /// \ octal-digit octal-digit
1017 /// \ octal-digit octal-digit octal-digit
1018 /// hexadecimal-escape-sequence:
1019 /// \x hexadecimal-digit
1020 /// hexadecimal-escape-sequence hexadecimal-digit
1021 /// universal-character-name: [C++11 lex.charset]
1023 /// \U hex-quad hex-quad
1025 /// hex-digit hex-digit hex-digit hex-digit
1028 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
1029 SourceLocation Loc, Preprocessor &PP,
1030 tok::TokenKind kind) {
1031 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
1036 const char *TokBegin = begin;
1038 // Skip over wide character determinant.
1039 if (Kind != tok::char_constant)
1041 if (Kind == tok::utf8_char_constant)
1044 // Skip over the entry quote.
1045 assert(begin[0] == '\'' && "Invalid token lexed");
1048 // Remove an optional ud-suffix.
1049 if (end[-1] != '\'') {
1050 const char *UDSuffixEnd = end;
1053 } while (end[-1] != '\'');
1054 // FIXME: Don't bother with this if !tok.hasUCN().
1055 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
1056 UDSuffixOffset = end - TokBegin;
1059 // Trim the ending quote.
1060 assert(end != begin && "Invalid token lexed");
1063 // FIXME: The "Value" is an uint64_t so we can handle char literals of
1065 // FIXME: This extensively assumes that 'char' is 8-bits.
1066 assert(PP.getTargetInfo().getCharWidth() == 8 &&
1067 "Assumes char is 8 bits");
1068 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1069 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1070 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1071 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1072 "Assumes sizeof(wchar) on target is <= 64");
1074 SmallVector<uint32_t, 4> codepoint_buffer;
1075 codepoint_buffer.resize(end - begin);
1076 uint32_t *buffer_begin = &codepoint_buffer.front();
1077 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1079 // Unicode escapes representing characters that cannot be correctly
1080 // represented in a single code unit are disallowed in character literals
1081 // by this implementation.
1082 uint32_t largest_character_for_kind;
1083 if (tok::wide_char_constant == Kind) {
1084 largest_character_for_kind =
1085 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1086 } else if (tok::utf8_char_constant == Kind) {
1087 largest_character_for_kind = 0x7F;
1088 } else if (tok::utf16_char_constant == Kind) {
1089 largest_character_for_kind = 0xFFFF;
1090 } else if (tok::utf32_char_constant == Kind) {
1091 largest_character_for_kind = 0x10FFFF;
1093 largest_character_for_kind = 0x7Fu;
1096 while (begin != end) {
1097 // Is this a span of non-escape characters?
1098 if (begin[0] != '\\') {
1099 char const *start = begin;
1102 } while (begin != end && *begin != '\\');
1104 char const *tmp_in_start = start;
1105 uint32_t *tmp_out_start = buffer_begin;
1106 ConversionResult res =
1107 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1108 reinterpret_cast<UTF8 const *>(begin),
1109 &buffer_begin, buffer_end, strictConversion);
1110 if (res != conversionOK) {
1111 // If we see bad encoding for unprefixed character literals, warn and
1112 // simply copy the byte values, for compatibility with gcc and
1113 // older versions of clang.
1114 bool NoErrorOnBadEncoding = isAscii();
1115 unsigned Msg = diag::err_bad_character_encoding;
1116 if (NoErrorOnBadEncoding)
1117 Msg = diag::warn_bad_character_encoding;
1119 if (NoErrorOnBadEncoding) {
1120 start = tmp_in_start;
1121 buffer_begin = tmp_out_start;
1122 for (; start != begin; ++start, ++buffer_begin)
1123 *buffer_begin = static_cast<uint8_t>(*start);
1128 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1129 if (*tmp_out_start > largest_character_for_kind) {
1131 PP.Diag(Loc, diag::err_character_too_large);
1138 // Is this a Universal Character Name escape?
1139 if (begin[1] == 'u' || begin[1] == 'U') {
1140 unsigned short UcnLen = 0;
1141 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1142 FullSourceLoc(Loc, PP.getSourceManager()),
1143 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1145 } else if (*buffer_begin > largest_character_for_kind) {
1147 PP.Diag(Loc, diag::err_character_too_large);
1153 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1155 ProcessCharEscape(TokBegin, begin, end, HadError,
1156 FullSourceLoc(Loc,PP.getSourceManager()),
1157 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1158 *buffer_begin++ = result;
1161 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1163 if (NumCharsSoFar > 1) {
1165 PP.Diag(Loc, diag::warn_extraneous_char_constant);
1166 else if (isAscii() && NumCharsSoFar == 4)
1167 PP.Diag(Loc, diag::ext_four_char_character_literal);
1169 PP.Diag(Loc, diag::ext_multichar_character_literal);
1171 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1174 IsMultiChar = false;
1177 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1179 // Narrow character literals act as though their value is concatenated
1180 // in this implementation, but warn on overflow.
1181 bool multi_char_too_long = false;
1182 if (isAscii() && isMultiChar()) {
1184 for (size_t i = 0; i < NumCharsSoFar; ++i) {
1185 // check for enough leading zeros to shift into
1186 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1188 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1190 } else if (NumCharsSoFar > 0) {
1191 // otherwise just take the last character
1192 LitVal = buffer_begin[-1];
1195 if (!HadError && multi_char_too_long) {
1196 PP.Diag(Loc, diag::warn_char_constant_too_large);
1199 // Transfer the value from APInt to uint64_t
1200 Value = LitVal.getZExtValue();
1202 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1203 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1204 // character constants are not sign extended in the this implementation:
1205 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1206 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1207 PP.getLangOpts().CharIsSigned)
1208 Value = (signed char)Value;
1212 /// string-literal: [C++0x lex.string]
1213 /// encoding-prefix " [s-char-sequence] "
1214 /// encoding-prefix R raw-string
1215 /// encoding-prefix:
1220 /// s-char-sequence:
1222 /// s-char-sequence s-char
1224 /// any member of the source character set except the double-quote ",
1225 /// backslash \, or new-line character
1227 /// universal-character-name
1229 /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1230 /// r-char-sequence:
1232 /// r-char-sequence r-char
1234 /// any member of the source character set, except a right parenthesis )
1235 /// followed by the initial d-char-sequence (which may be empty)
1236 /// followed by a double quote ".
1237 /// d-char-sequence:
1239 /// d-char-sequence d-char
1241 /// any member of the basic source character set except:
1242 /// space, the left parenthesis (, the right parenthesis ),
1243 /// the backslash \, and the control characters representing horizontal
1244 /// tab, vertical tab, form feed, and newline.
1245 /// escape-sequence: [C++0x lex.ccon]
1246 /// simple-escape-sequence
1247 /// octal-escape-sequence
1248 /// hexadecimal-escape-sequence
1249 /// simple-escape-sequence:
1250 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1251 /// octal-escape-sequence:
1253 /// \ octal-digit octal-digit
1254 /// \ octal-digit octal-digit octal-digit
1255 /// hexadecimal-escape-sequence:
1256 /// \x hexadecimal-digit
1257 /// hexadecimal-escape-sequence hexadecimal-digit
1258 /// universal-character-name:
1260 /// \U hex-quad hex-quad
1262 /// hex-digit hex-digit hex-digit hex-digit
1265 StringLiteralParser::
1266 StringLiteralParser(ArrayRef<Token> StringToks,
1267 Preprocessor &PP, bool Complain)
1268 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1269 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
1270 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1271 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1275 void StringLiteralParser::init(ArrayRef<Token> StringToks){
1276 // The literal token may have come from an invalid source location (e.g. due
1277 // to a PCH error), in which case the token length will be 0.
1278 if (StringToks.empty() || StringToks[0].getLength() < 2)
1279 return DiagnoseLexingError(SourceLocation());
1281 // Scan all of the string portions, remember the max individual token length,
1282 // computing a bound on the concatenated string length, and see whether any
1283 // piece is a wide-string. If any of the string portions is a wide-string
1284 // literal, the result is a wide-string literal [C99 6.4.5p4].
1285 assert(!StringToks.empty() && "expected at least one token");
1286 MaxTokenLength = StringToks[0].getLength();
1287 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1288 SizeBound = StringToks[0].getLength()-2; // -2 for "".
1289 Kind = StringToks[0].getKind();
1293 // Implement Translation Phase #6: concatenation of string literals
1294 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1295 for (unsigned i = 1; i != StringToks.size(); ++i) {
1296 if (StringToks[i].getLength() < 2)
1297 return DiagnoseLexingError(StringToks[i].getLocation());
1299 // The string could be shorter than this if it needs cleaning, but this is a
1300 // reasonable bound, which is all we need.
1301 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1302 SizeBound += StringToks[i].getLength()-2; // -2 for "".
1304 // Remember maximum string piece length.
1305 if (StringToks[i].getLength() > MaxTokenLength)
1306 MaxTokenLength = StringToks[i].getLength();
1308 // Remember if we see any wide or utf-8/16/32 strings.
1309 // Also check for illegal concatenations.
1310 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1312 Kind = StringToks[i].getKind();
1315 Diags->Report(StringToks[i].getLocation(),
1316 diag::err_unsupported_string_concat);
1322 // Include space for the null terminator.
1325 // TODO: K&R warning: "traditional C rejects string constant concatenation"
1327 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1328 CharByteWidth = getCharWidth(Kind, Target);
1329 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1332 // The output buffer size needs to be large enough to hold wide characters.
1333 // This is a worst-case assumption which basically corresponds to L"" "long".
1334 SizeBound *= CharByteWidth;
1336 // Size the temporary buffer to hold the result string data.
1337 ResultBuf.resize(SizeBound);
1339 // Likewise, but for each string piece.
1340 SmallString<512> TokenBuf;
1341 TokenBuf.resize(MaxTokenLength);
1343 // Loop over all the strings, getting their spelling, and expanding them to
1344 // wide strings as appropriate.
1345 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
1349 SourceLocation UDSuffixTokLoc;
1351 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
1352 const char *ThisTokBuf = &TokenBuf[0];
1353 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1354 // that ThisTokBuf points to a buffer that is big enough for the whole token
1355 // and 'spelled' tokens can only shrink.
1356 bool StringInvalid = false;
1357 unsigned ThisTokLen =
1358 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1361 return DiagnoseLexingError(StringToks[i].getLocation());
1363 const char *ThisTokBegin = ThisTokBuf;
1364 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1366 // Remove an optional ud-suffix.
1367 if (ThisTokEnd[-1] != '"') {
1368 const char *UDSuffixEnd = ThisTokEnd;
1371 } while (ThisTokEnd[-1] != '"');
1373 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1375 if (UDSuffixBuf.empty()) {
1376 if (StringToks[i].hasUCN())
1377 expandUCNs(UDSuffixBuf, UDSuffix);
1379 UDSuffixBuf.assign(UDSuffix);
1381 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1382 UDSuffixTokLoc = StringToks[i].getLocation();
1384 SmallString<32> ExpandedUDSuffix;
1385 if (StringToks[i].hasUCN()) {
1386 expandUCNs(ExpandedUDSuffix, UDSuffix);
1387 UDSuffix = ExpandedUDSuffix;
1390 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1391 // result of a concatenation involving at least one user-defined-string-
1392 // literal, all the participating user-defined-string-literals shall
1393 // have the same ud-suffix.
1394 if (UDSuffixBuf != UDSuffix) {
1396 SourceLocation TokLoc = StringToks[i].getLocation();
1397 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1398 << UDSuffixBuf << UDSuffix
1399 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1400 << SourceRange(TokLoc, TokLoc);
1407 // Strip the end quote.
1410 // TODO: Input character set mapping support.
1412 // Skip marker for wide or unicode strings.
1413 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1415 // Skip 8 of u8 marker for utf8 strings.
1416 if (ThisTokBuf[0] == '8')
1420 // Check for raw string
1421 if (ThisTokBuf[0] == 'R') {
1422 ThisTokBuf += 2; // skip R"
1424 const char *Prefix = ThisTokBuf;
1425 while (ThisTokBuf[0] != '(')
1427 ++ThisTokBuf; // skip '('
1429 // Remove same number of characters from the end
1430 ThisTokEnd -= ThisTokBuf - Prefix;
1431 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1433 // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1434 // results in a new-line in the resulting execution string-literal.
1435 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1436 while (!RemainingTokenSpan.empty()) {
1437 // Split the string literal on \r\n boundaries.
1438 size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1439 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1440 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1442 // Copy everything before the \r\n sequence into the string literal.
1443 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1446 // Point into the \n inside the \r\n sequence and operate on the
1447 // remaining portion of the literal.
1448 RemainingTokenSpan = AfterCRLF.substr(1);
1451 if (ThisTokBuf[0] != '"') {
1452 // The file may have come from PCH and then changed after loading the
1453 // PCH; Fail gracefully.
1454 return DiagnoseLexingError(StringToks[i].getLocation());
1456 ++ThisTokBuf; // skip "
1458 // Check if this is a pascal string
1459 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1460 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1462 // If the \p sequence is found in the first token, we have a pascal string
1463 // Otherwise, if we already have a pascal string, ignore the first \p
1471 while (ThisTokBuf != ThisTokEnd) {
1472 // Is this a span of non-escape characters?
1473 if (ThisTokBuf[0] != '\\') {
1474 const char *InStart = ThisTokBuf;
1477 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1479 // Copy the character span over.
1480 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1481 StringRef(InStart, ThisTokBuf - InStart)))
1485 // Is this a Universal Character Name escape?
1486 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1487 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1488 ResultPtr, hadError,
1489 FullSourceLoc(StringToks[i].getLocation(), SM),
1490 CharByteWidth, Diags, Features);
1493 // Otherwise, this is a non-UCN escape character. Process it.
1494 unsigned ResultChar =
1495 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1496 FullSourceLoc(StringToks[i].getLocation(), SM),
1497 CharByteWidth*8, Diags, Features);
1499 if (CharByteWidth == 4) {
1500 // FIXME: Make the type of the result buffer correct instead of
1501 // using reinterpret_cast.
1502 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1503 *ResultWidePtr = ResultChar;
1505 } else if (CharByteWidth == 2) {
1506 // FIXME: Make the type of the result buffer correct instead of
1507 // using reinterpret_cast.
1508 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1509 *ResultWidePtr = ResultChar & 0xFFFF;
1512 assert(CharByteWidth == 1 && "Unexpected char width");
1513 *ResultPtr++ = ResultChar & 0xFF;
1520 if (CharByteWidth == 4) {
1521 // FIXME: Make the type of the result buffer correct instead of
1522 // using reinterpret_cast.
1523 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1524 ResultWidePtr[0] = GetNumStringChars() - 1;
1525 } else if (CharByteWidth == 2) {
1526 // FIXME: Make the type of the result buffer correct instead of
1527 // using reinterpret_cast.
1528 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1529 ResultWidePtr[0] = GetNumStringChars() - 1;
1531 assert(CharByteWidth == 1 && "Unexpected char width");
1532 ResultBuf[0] = GetNumStringChars() - 1;
1535 // Verify that pascal strings aren't too large.
1536 if (GetStringLength() > 256) {
1538 Diags->Report(StringToks.front().getLocation(),
1539 diag::err_pascal_string_too_long)
1540 << SourceRange(StringToks.front().getLocation(),
1541 StringToks.back().getLocation());
1546 // Complain if this string literal has too many characters.
1547 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1549 if (GetNumStringChars() > MaxChars)
1550 Diags->Report(StringToks.front().getLocation(),
1551 diag::ext_string_too_long)
1552 << GetNumStringChars() << MaxChars
1553 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1554 << SourceRange(StringToks.front().getLocation(),
1555 StringToks.back().getLocation());
1559 static const char *resyncUTF8(const char *Err, const char *End) {
1562 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1563 while (++Err != End && (*Err & 0xC0) == 0x80)
1568 /// \brief This function copies from Fragment, which is a sequence of bytes
1569 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1570 /// Performs widening for multi-byte characters.
1571 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1572 const char *TokBegin,
1573 StringRef Fragment) {
1574 const UTF8 *ErrorPtrTmp;
1575 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1578 // If we see bad encoding for unprefixed string literals, warn and
1579 // simply copy the byte values, for compatibility with gcc and older
1580 // versions of clang.
1581 bool NoErrorOnBadEncoding = isAscii();
1582 if (NoErrorOnBadEncoding) {
1583 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1584 ResultPtr += Fragment.size();
1588 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1590 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1591 const DiagnosticBuilder &Builder =
1592 Diag(Diags, Features, SourceLoc, TokBegin,
1593 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1594 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1595 : diag::err_bad_string_encoding);
1597 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1598 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1600 // Decode into a dummy buffer.
1601 SmallString<512> Dummy;
1602 Dummy.reserve(Fragment.size() * CharByteWidth);
1603 char *Ptr = Dummy.data();
1605 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1606 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1607 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1608 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1609 ErrorPtr, NextStart);
1610 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1613 return !NoErrorOnBadEncoding;
1616 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1619 Diags->Report(Loc, diag::err_lexing_string);
1622 /// getOffsetOfStringByte - This function returns the offset of the
1623 /// specified byte of the string data represented by Token. This handles
1624 /// advancing over escape sequences in the string.
1625 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1626 unsigned ByteNo) const {
1627 // Get the spelling of the token.
1628 SmallString<32> SpellingBuffer;
1629 SpellingBuffer.resize(Tok.getLength());
1631 bool StringInvalid = false;
1632 const char *SpellingPtr = &SpellingBuffer[0];
1633 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1638 const char *SpellingStart = SpellingPtr;
1639 const char *SpellingEnd = SpellingPtr+TokLen;
1641 // Handle UTF-8 strings just like narrow strings.
1642 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1645 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1646 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1648 // For raw string literals, this is easy.
1649 if (SpellingPtr[0] == 'R') {
1650 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1653 while (*SpellingPtr != '(') {
1655 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1659 return SpellingPtr - SpellingStart + ByteNo;
1662 // Skip over the leading quote
1663 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1666 // Skip over bytes until we find the offset we're looking for.
1668 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1670 // Step over non-escapes simply.
1671 if (*SpellingPtr != '\\') {
1677 // Otherwise, this is an escape character. Advance over it.
1678 bool HadError = false;
1679 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1680 const char *EscapePtr = SpellingPtr;
1681 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1682 1, Features, HadError);
1684 // ByteNo is somewhere within the escape sequence.
1685 SpellingPtr = EscapePtr;
1690 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1691 FullSourceLoc(Tok.getLocation(), SM),
1692 CharByteWidth*8, Diags, Features);
1695 assert(!HadError && "This method isn't valid on erroneous strings");
1698 return SpellingPtr-SpellingStart;