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/LangOptions.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Lex/Token.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/Support/ErrorHandling.h"
37 using namespace clang;
39 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
41 default: llvm_unreachable("Unknown token type!");
42 case tok::char_constant:
43 case tok::string_literal:
44 case tok::utf8_char_constant:
45 case tok::utf8_string_literal:
46 return Target.getCharWidth();
47 case tok::wide_char_constant:
48 case tok::wide_string_literal:
49 return Target.getWCharWidth();
50 case tok::utf16_char_constant:
51 case tok::utf16_string_literal:
52 return Target.getChar16Width();
53 case tok::utf32_char_constant:
54 case tok::utf32_string_literal:
55 return Target.getChar32Width();
59 static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
62 const char *TokRangeBegin,
63 const char *TokRangeEnd) {
64 SourceLocation Begin =
65 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
66 TokLoc.getManager(), Features);
68 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
69 TokLoc.getManager(), Features);
70 return CharSourceRange::getCharRange(Begin, End);
73 /// \brief Produce a diagnostic highlighting some portion of a literal.
75 /// Emits the diagnostic \p DiagID, highlighting the range of characters from
76 /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
77 /// a substring of a spelling buffer for the token beginning at \p TokBegin.
78 static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
79 const LangOptions &Features, FullSourceLoc TokLoc,
80 const char *TokBegin, const char *TokRangeBegin,
81 const char *TokRangeEnd, unsigned DiagID) {
82 SourceLocation Begin =
83 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
84 TokLoc.getManager(), Features);
85 return Diags->Report(Begin, DiagID) <<
86 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
89 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
90 /// either a character or a string literal.
91 static unsigned ProcessCharEscape(const char *ThisTokBegin,
92 const char *&ThisTokBuf,
93 const char *ThisTokEnd, bool &HadError,
94 FullSourceLoc Loc, unsigned CharWidth,
95 DiagnosticsEngine *Diags,
96 const LangOptions &Features) {
97 const char *EscapeBegin = ThisTokBuf;
102 // We know that this character can't be off the end of the buffer, because
103 // that would have been \", which would not have been the end of string.
104 unsigned ResultChar = *ThisTokBuf++;
105 switch (ResultChar) {
106 // These map to themselves.
107 case '\\': case '\'': case '"': case '?': break;
109 // These have fixed mappings.
111 // TODO: K&R: the meaning of '\\a' is different in traditional C
119 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
120 diag::ext_nonstandard_escape) << "e";
125 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
126 diag::ext_nonstandard_escape) << "E";
144 case 'x': { // Hex escape.
146 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
148 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
149 diag::err_hex_escape_no_digits) << "x";
154 // Hex escapes are a maximal series of hex digits.
155 bool Overflow = false;
156 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
157 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
158 if (CharVal == -1) break;
159 // About to shift out a digit?
160 if (ResultChar & 0xF0000000)
163 ResultChar |= CharVal;
166 // See if any bits will be truncated when evaluated as a character.
167 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
169 ResultChar &= ~0U >> (32-CharWidth);
172 // Check for overflow.
173 if (Overflow && Diags) // Too many digits to fit in
174 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
175 diag::err_escape_too_large) << 0;
178 case '0': case '1': case '2': case '3':
179 case '4': case '5': case '6': case '7': {
184 // Octal escapes are a series of octal digits with maximum length 3.
185 // "\0123" is a two digit sequence equal to "\012" "3".
186 unsigned NumDigits = 0;
189 ResultChar |= *ThisTokBuf++ - '0';
191 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
192 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
194 // Check for overflow. Reject '\777', but not L'\777'.
195 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
197 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
198 diag::err_escape_too_large) << 1;
199 ResultChar &= ~0U >> (32-CharWidth);
204 // Otherwise, these are not valid escapes.
205 case '(': case '{': case '[': case '%':
206 // GCC accepts these as extensions. We warn about them as such though.
208 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
209 diag::ext_nonstandard_escape)
210 << std::string(1, ResultChar);
216 if (isPrintable(ResultChar))
217 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
218 diag::ext_unknown_escape)
219 << std::string(1, ResultChar);
221 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
222 diag::ext_unknown_escape)
223 << "x" + llvm::utohexstr(ResultChar);
230 static void appendCodePoint(unsigned Codepoint,
231 llvm::SmallVectorImpl<char> &Str) {
233 char *ResultPtr = ResultBuf;
234 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
236 assert(Res && "Unexpected conversion failure");
237 Str.append(ResultBuf, ResultPtr);
240 void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
241 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
248 assert(*I == 'u' || *I == 'U');
250 unsigned NumHexDigits;
256 assert(I + NumHexDigits <= E);
258 uint32_t CodePoint = 0;
259 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
260 unsigned Value = llvm::hexDigitValue(*I);
261 assert(Value != -1U);
267 appendCodePoint(CodePoint, Buf);
272 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
273 /// return the UTF32.
274 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
275 const char *ThisTokEnd,
276 uint32_t &UcnVal, unsigned short &UcnLen,
277 FullSourceLoc Loc, DiagnosticsEngine *Diags,
278 const LangOptions &Features,
279 bool in_char_string_literal = false) {
280 const char *UcnBegin = ThisTokBuf;
282 // Skip the '\u' char's.
285 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
287 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
288 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
291 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
292 unsigned short UcnLenSave = UcnLen;
293 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
294 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
295 if (CharVal == -1) break;
299 // If we didn't consume the proper number of digits, there is a problem.
302 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
303 diag::err_ucn_escape_incomplete);
307 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
308 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
309 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
311 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
312 diag::err_ucn_escape_invalid);
316 // C++11 allows UCNs that refer to control characters and basic source
317 // characters inside character and string literals
319 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
320 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
322 char BasicSCSChar = UcnVal;
323 if (UcnVal >= 0x20 && UcnVal < 0x7f)
324 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
325 IsError ? diag::err_ucn_escape_basic_scs :
326 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
327 << StringRef(&BasicSCSChar, 1);
329 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
330 IsError ? diag::err_ucn_control_character :
331 diag::warn_cxx98_compat_literal_ucn_control_character);
337 if (!Features.CPlusPlus && !Features.C99 && Diags)
338 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
339 diag::warn_ucn_not_valid_in_c89_literal);
344 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
345 /// which this UCN will occupy.
346 static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
347 const char *ThisTokEnd, unsigned CharByteWidth,
348 const LangOptions &Features, bool &HadError) {
349 // UTF-32: 4 bytes per escape.
350 if (CharByteWidth == 4)
354 unsigned short UcnLen = 0;
357 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
358 UcnLen, Loc, nullptr, Features, true)) {
363 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
364 if (CharByteWidth == 2)
365 return UcnVal <= 0xFFFF ? 2 : 4;
372 if (UcnVal < 0x10000)
377 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
378 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
379 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
380 /// we will likely rework our support for UCN's.
381 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
382 const char *ThisTokEnd,
383 char *&ResultBuf, bool &HadError,
384 FullSourceLoc Loc, unsigned CharByteWidth,
385 DiagnosticsEngine *Diags,
386 const LangOptions &Features) {
387 typedef uint32_t UTF32;
389 unsigned short UcnLen = 0;
390 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
391 Loc, Diags, Features, true)) {
396 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
397 "only character widths of 1, 2, or 4 bytes supported");
400 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
402 if (CharByteWidth == 4) {
403 // FIXME: Make the type of the result buffer correct instead of
404 // using reinterpret_cast.
405 llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
411 if (CharByteWidth == 2) {
412 // FIXME: Make the type of the result buffer correct instead of
413 // using reinterpret_cast.
414 llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
416 if (UcnVal <= (UTF32)0xFFFF) {
424 *ResultPtr = 0xD800 + (UcnVal >> 10);
425 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
430 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
432 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
433 // The conversion below was inspired by:
434 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
435 // First, we determine how many bytes the result will require.
436 typedef uint8_t UTF8;
438 unsigned short bytesToWrite = 0;
439 if (UcnVal < (UTF32)0x80)
441 else if (UcnVal < (UTF32)0x800)
443 else if (UcnVal < (UTF32)0x10000)
448 const unsigned byteMask = 0xBF;
449 const unsigned byteMark = 0x80;
451 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
452 // into the first byte, depending on how many bytes follow.
453 static const UTF8 firstByteMark[5] = {
454 0x00, 0x00, 0xC0, 0xE0, 0xF0
456 // Finally, we write the bytes into ResultBuf.
457 ResultBuf += bytesToWrite;
458 switch (bytesToWrite) { // note: everything falls through.
459 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
460 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
461 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
462 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
464 // Update the buffer.
465 ResultBuf += bytesToWrite;
468 /// integer-constant: [C99 6.4.4.1]
469 /// decimal-constant integer-suffix
470 /// octal-constant integer-suffix
471 /// hexadecimal-constant integer-suffix
472 /// binary-literal integer-suffix [GNU, C++1y]
473 /// user-defined-integer-literal: [C++11 lex.ext]
474 /// decimal-literal ud-suffix
475 /// octal-literal ud-suffix
476 /// hexadecimal-literal ud-suffix
477 /// binary-literal ud-suffix [GNU, C++1y]
478 /// decimal-constant:
480 /// decimal-constant digit
483 /// octal-constant octal-digit
484 /// hexadecimal-constant:
485 /// hexadecimal-prefix hexadecimal-digit
486 /// hexadecimal-constant hexadecimal-digit
487 /// hexadecimal-prefix: one of
492 /// binary-literal binary-digit
494 /// unsigned-suffix [long-suffix]
495 /// unsigned-suffix [long-long-suffix]
496 /// long-suffix [unsigned-suffix]
497 /// long-long-suffix [unsigned-sufix]
499 /// 1 2 3 4 5 6 7 8 9
502 /// hexadecimal-digit:
503 /// 0 1 2 3 4 5 6 7 8 9
509 /// unsigned-suffix: one of
511 /// long-suffix: one of
513 /// long-long-suffix: one of
516 /// floating-constant: [C99 6.4.4.2]
517 /// TODO: add rules...
519 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
520 SourceLocation TokLoc,
522 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
524 // This routine assumes that the range begin/end matches the regex for integer
525 // and FP constants (specifically, the 'pp-number' regex), and assumes that
526 // the byte at "*end" is both valid and not part of the regex. Because of
527 // this, it doesn't have to check for 'overscan' in various places.
528 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
530 s = DigitsBegin = ThisTokBegin;
531 saw_exponent = false;
533 saw_ud_suffix = false;
541 MicrosoftInteger = 0;
544 if (*s == '0') { // parse radix
545 ParseNumberStartingWithZero(TokLoc);
548 } else { // the first digit is non-zero
551 if (s == ThisTokEnd) {
554 ParseDecimalOrOctalCommon(TokLoc);
561 checkSeparator(TokLoc, s, CSK_AfterDigits);
563 // Parse the suffix. At this point we can classify whether we have an FP or
565 bool isFPConstant = isFloatingLiteral();
566 const char *ImaginarySuffixLoc = nullptr;
568 // Loop over all of the characters of the suffix. If we see something bad,
569 // we break out of the loop.
570 for (; s != ThisTokEnd; ++s) {
572 case 'h': // FP Suffix for "half".
574 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
575 if (!PP.getLangOpts().Half) break;
576 if (!isFPConstant) break; // Error for integer constant.
577 if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
579 continue; // Success.
580 case 'f': // FP Suffix for "float"
582 if (!isFPConstant) break; // Error for integer constant.
583 if (isHalf || isFloat || isLong || isFloat128)
584 break; // HF, FF, LF, QF invalid.
586 continue; // Success.
587 case 'q': // FP Suffix for "__float128"
589 if (!isFPConstant) break; // Error for integer constant.
590 if (isHalf || isFloat || isLong || isFloat128)
591 break; // HQ, FQ, LQ, QQ invalid.
593 continue; // Success.
596 if (isFPConstant) break; // Error for floating constant.
597 if (isUnsigned) break; // Cannot be repeated.
599 continue; // Success.
602 if (isLong || isLongLong) break; // Cannot be repeated.
603 if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid.
605 // Check for long long. The L's need to be adjacent and the same case.
607 assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
608 if (isFPConstant) break; // long long invalid for floats.
610 ++s; // Eat both of them.
614 continue; // Success.
617 if (PP.getLangOpts().MicrosoftExt) {
618 if (isLong || isLongLong || MicrosoftInteger)
622 // Allow i8, i16, i32, and i64.
626 MicrosoftInteger = 8;
630 s += 3; // i16 suffix
631 MicrosoftInteger = 16;
636 s += 3; // i32 suffix
637 MicrosoftInteger = 32;
642 s += 3; // i64 suffix
643 MicrosoftInteger = 64;
650 if (MicrosoftInteger) {
651 assert(s <= ThisTokEnd && "didn't maximally munch?");
655 // "i", "if", and "il" are user-defined suffixes in C++1y.
656 if (*s == 'i' && PP.getLangOpts().CPlusPlus14)
661 if (isImaginary) break; // Cannot be repeated.
663 ImaginarySuffixLoc = s;
664 continue; // Success.
666 // If we reached here, there was an error or a ud-suffix.
670 if (s != ThisTokEnd) {
671 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
672 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
673 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
674 // Any suffix pieces we might have parsed are actually part of the
682 MicrosoftInteger = 0;
684 saw_ud_suffix = true;
688 // Report an error if there are any.
689 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
690 diag::err_invalid_suffix_constant)
691 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin) << isFPConstant;
697 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
698 ImaginarySuffixLoc - ThisTokBegin),
699 diag::ext_imaginary_constant);
703 /// ParseDecimalOrOctalCommon - This method is called for decimal or octal
704 /// numbers. It issues an error for illegal digits, and handles floating point
705 /// parsing. If it detects a floating point number, the radix is set to 10.
706 void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
707 assert((radix == 8 || radix == 10) && "Unexpected radix");
709 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
710 // the code is using an incorrect base.
711 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
712 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
713 diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
719 checkSeparator(TokLoc, s, CSK_AfterDigits);
723 checkSeparator(TokLoc, s, CSK_BeforeDigits);
724 s = SkipDigits(s); // Skip suffix.
726 if (*s == 'e' || *s == 'E') { // exponent
727 checkSeparator(TokLoc, s, CSK_AfterDigits);
728 const char *Exponent = s;
732 if (*s == '+' || *s == '-') s++; // sign
733 const char *first_non_digit = SkipDigits(s);
734 if (containsDigits(s, first_non_digit)) {
735 checkSeparator(TokLoc, s, CSK_BeforeDigits);
738 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
739 diag::err_exponent_has_no_digits);
746 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
747 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
748 /// treat it as an invalid suffix.
749 bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
751 if (!LangOpts.CPlusPlus11 || Suffix.empty())
754 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
755 if (Suffix[0] == '_')
758 // In C++11, there are no library suffixes.
759 if (!LangOpts.CPlusPlus14)
762 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
763 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
764 return llvm::StringSwitch<bool>(Suffix)
765 .Cases("h", "min", "s", true)
766 .Cases("ms", "us", "ns", true)
767 .Cases("il", "i", "if", true)
771 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
773 CheckSeparatorKind IsAfterDigits) {
774 if (IsAfterDigits == CSK_AfterDigits) {
775 if (Pos == ThisTokBegin)
778 } else if (Pos == ThisTokEnd)
781 if (isDigitSeparator(*Pos))
782 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
783 diag::err_digit_separator_not_between_digits)
787 /// ParseNumberStartingWithZero - This method is called when the first character
788 /// of the number is found to be a zero. This means it is either an octal
789 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
790 /// a floating point number (01239.123e4). Eat the prefix, determining the
792 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
793 assert(s[0] == '0' && "Invalid method call");
798 // Handle a hex number like 0x1234.
799 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
801 assert(s < ThisTokEnd && "didn't maximally munch?");
804 s = SkipHexDigits(s);
805 bool HasSignificandDigits = containsDigits(DigitsBegin, s);
806 if (s == ThisTokEnd) {
808 } else if (*s == '.') {
811 const char *floatDigitsBegin = s;
812 s = SkipHexDigits(s);
813 if (containsDigits(floatDigitsBegin, s))
814 HasSignificandDigits = true;
815 if (HasSignificandDigits)
816 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
819 if (!HasSignificandDigits) {
820 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
821 diag::err_hex_constant_requires)
822 << PP.getLangOpts().CPlusPlus << 1;
827 // A binary exponent can appear with or with a '.'. If dotted, the
828 // binary exponent is required.
829 if (*s == 'p' || *s == 'P') {
830 checkSeparator(TokLoc, s, CSK_AfterDigits);
831 const char *Exponent = s;
834 if (*s == '+' || *s == '-') s++; // sign
835 const char *first_non_digit = SkipDigits(s);
836 if (!containsDigits(s, first_non_digit)) {
837 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
838 diag::err_exponent_has_no_digits);
842 checkSeparator(TokLoc, s, CSK_BeforeDigits);
845 if (!PP.getLangOpts().HexFloats)
846 PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
847 ? diag::ext_hex_literal_invalid
848 : diag::ext_hex_constant_invalid);
849 else if (PP.getLangOpts().CPlusPlus1z)
850 PP.Diag(TokLoc, diag::warn_cxx1z_hex_literal);
851 } else if (saw_period) {
852 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
853 diag::err_hex_constant_requires)
854 << PP.getLangOpts().CPlusPlus << 0;
860 // Handle simple binary numbers 0b01010
861 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
862 // 0b101010 is a C++1y / GCC extension.
864 PP.getLangOpts().CPlusPlus14
865 ? diag::warn_cxx11_compat_binary_literal
866 : PP.getLangOpts().CPlusPlus
867 ? diag::ext_binary_literal_cxx14
868 : diag::ext_binary_literal);
870 assert(s < ThisTokEnd && "didn't maximally munch?");
873 s = SkipBinaryDigits(s);
874 if (s == ThisTokEnd) {
876 } else if (isHexDigit(*s)) {
877 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
878 diag::err_invalid_digit) << StringRef(s, 1) << 2;
881 // Other suffixes will be diagnosed by the caller.
885 // For now, the radix is set to 8. If we discover that we have a
886 // floating point constant, the radix will change to 10. Octal floating
887 // point constants are not permitted (only decimal and hexadecimal).
890 s = SkipOctalDigits(s);
892 return; // Done, simple octal number like 01234
894 // If we have some other non-octal digit that *is* a decimal digit, see if
895 // this is part of a floating point number like 094.123 or 09e1.
897 const char *EndDecimal = SkipDigits(s);
898 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
904 ParseDecimalOrOctalCommon(TokLoc);
907 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
910 return NumDigits <= 64;
912 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
914 return NumDigits <= 19; // floor(log10(2^64))
916 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
918 llvm_unreachable("impossible Radix");
922 /// GetIntegerValue - Convert this numeric literal value to an APInt that
923 /// matches Val's input width. If there is an overflow, set Val to the low bits
924 /// of the result and return true. Otherwise, return false.
925 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
926 // Fast path: Compute a conservative bound on the maximum number of
927 // bits per digit in this radix. If we can't possibly overflow a
928 // uint64 based on that bound then do the simple conversion to
929 // integer. This avoids the expensive overflow checking below, and
930 // handles the common cases that matter (small decimal integers and
931 // hex/octal values which don't overflow).
932 const unsigned NumDigits = SuffixBegin - DigitsBegin;
933 if (alwaysFitsInto64Bits(radix, NumDigits)) {
935 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
936 if (!isDigitSeparator(*Ptr))
937 N = N * radix + llvm::hexDigitValue(*Ptr);
939 // This will truncate the value to Val's input width. Simply check
940 // for overflow by comparing.
942 return Val.getZExtValue() != N;
946 const char *Ptr = DigitsBegin;
948 llvm::APInt RadixVal(Val.getBitWidth(), radix);
949 llvm::APInt CharVal(Val.getBitWidth(), 0);
950 llvm::APInt OldVal = Val;
952 bool OverflowOccurred = false;
953 while (Ptr < SuffixBegin) {
954 if (isDigitSeparator(*Ptr)) {
959 unsigned C = llvm::hexDigitValue(*Ptr++);
961 // If this letter is out of bound for this radix, reject it.
962 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
966 // Add the digit to the value in the appropriate radix. If adding in digits
967 // made the value smaller, then this overflowed.
970 // Multiply by radix, did overflow occur on the multiply?
972 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
974 // Add value, did overflow occur on the value?
975 // (a + b) ult b <=> overflow
977 OverflowOccurred |= Val.ult(CharVal);
979 return OverflowOccurred;
982 llvm::APFloat::opStatus
983 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
986 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
988 llvm::SmallString<16> Buffer;
989 StringRef Str(ThisTokBegin, n);
990 if (Str.find('\'') != StringRef::npos) {
992 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
997 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
1001 /// user-defined-character-literal: [C++11 lex.ext]
1002 /// character-literal ud-suffix
1005 /// character-literal: [C++11 lex.ccon]
1006 /// ' c-char-sequence '
1007 /// u' c-char-sequence '
1008 /// U' c-char-sequence '
1009 /// L' c-char-sequence '
1010 /// u8' c-char-sequence ' [C++1z lex.ccon]
1011 /// c-char-sequence:
1013 /// c-char-sequence c-char
1015 /// any member of the source character set except the single-quote ',
1016 /// backslash \, or new-line character
1018 /// universal-character-name
1019 /// escape-sequence:
1020 /// simple-escape-sequence
1021 /// octal-escape-sequence
1022 /// hexadecimal-escape-sequence
1023 /// simple-escape-sequence:
1024 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1025 /// octal-escape-sequence:
1027 /// \ octal-digit octal-digit
1028 /// \ octal-digit octal-digit octal-digit
1029 /// hexadecimal-escape-sequence:
1030 /// \x hexadecimal-digit
1031 /// hexadecimal-escape-sequence hexadecimal-digit
1032 /// universal-character-name: [C++11 lex.charset]
1034 /// \U hex-quad hex-quad
1036 /// hex-digit hex-digit hex-digit hex-digit
1039 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
1040 SourceLocation Loc, Preprocessor &PP,
1041 tok::TokenKind kind) {
1042 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
1047 const char *TokBegin = begin;
1049 // Skip over wide character determinant.
1050 if (Kind != tok::char_constant)
1052 if (Kind == tok::utf8_char_constant)
1055 // Skip over the entry quote.
1056 assert(begin[0] == '\'' && "Invalid token lexed");
1059 // Remove an optional ud-suffix.
1060 if (end[-1] != '\'') {
1061 const char *UDSuffixEnd = end;
1064 } while (end[-1] != '\'');
1065 // FIXME: Don't bother with this if !tok.hasUCN().
1066 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
1067 UDSuffixOffset = end - TokBegin;
1070 // Trim the ending quote.
1071 assert(end != begin && "Invalid token lexed");
1074 // FIXME: The "Value" is an uint64_t so we can handle char literals of
1076 // FIXME: This extensively assumes that 'char' is 8-bits.
1077 assert(PP.getTargetInfo().getCharWidth() == 8 &&
1078 "Assumes char is 8 bits");
1079 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1080 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1081 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1082 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1083 "Assumes sizeof(wchar) on target is <= 64");
1085 SmallVector<uint32_t, 4> codepoint_buffer;
1086 codepoint_buffer.resize(end - begin);
1087 uint32_t *buffer_begin = &codepoint_buffer.front();
1088 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1090 // Unicode escapes representing characters that cannot be correctly
1091 // represented in a single code unit are disallowed in character literals
1092 // by this implementation.
1093 uint32_t largest_character_for_kind;
1094 if (tok::wide_char_constant == Kind) {
1095 largest_character_for_kind =
1096 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1097 } else if (tok::utf8_char_constant == Kind) {
1098 largest_character_for_kind = 0x7F;
1099 } else if (tok::utf16_char_constant == Kind) {
1100 largest_character_for_kind = 0xFFFF;
1101 } else if (tok::utf32_char_constant == Kind) {
1102 largest_character_for_kind = 0x10FFFF;
1104 largest_character_for_kind = 0x7Fu;
1107 while (begin != end) {
1108 // Is this a span of non-escape characters?
1109 if (begin[0] != '\\') {
1110 char const *start = begin;
1113 } while (begin != end && *begin != '\\');
1115 char const *tmp_in_start = start;
1116 uint32_t *tmp_out_start = buffer_begin;
1117 llvm::ConversionResult res =
1118 llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
1119 reinterpret_cast<llvm::UTF8 const *>(begin),
1120 &buffer_begin, buffer_end, llvm::strictConversion);
1121 if (res != llvm::conversionOK) {
1122 // If we see bad encoding for unprefixed character literals, warn and
1123 // simply copy the byte values, for compatibility with gcc and
1124 // older versions of clang.
1125 bool NoErrorOnBadEncoding = isAscii();
1126 unsigned Msg = diag::err_bad_character_encoding;
1127 if (NoErrorOnBadEncoding)
1128 Msg = diag::warn_bad_character_encoding;
1130 if (NoErrorOnBadEncoding) {
1131 start = tmp_in_start;
1132 buffer_begin = tmp_out_start;
1133 for (; start != begin; ++start, ++buffer_begin)
1134 *buffer_begin = static_cast<uint8_t>(*start);
1139 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1140 if (*tmp_out_start > largest_character_for_kind) {
1142 PP.Diag(Loc, diag::err_character_too_large);
1149 // Is this a Universal Character Name escape?
1150 if (begin[1] == 'u' || begin[1] == 'U') {
1151 unsigned short UcnLen = 0;
1152 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1153 FullSourceLoc(Loc, PP.getSourceManager()),
1154 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1156 } else if (*buffer_begin > largest_character_for_kind) {
1158 PP.Diag(Loc, diag::err_character_too_large);
1164 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1166 ProcessCharEscape(TokBegin, begin, end, HadError,
1167 FullSourceLoc(Loc,PP.getSourceManager()),
1168 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1169 *buffer_begin++ = result;
1172 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1174 if (NumCharsSoFar > 1) {
1176 PP.Diag(Loc, diag::warn_extraneous_char_constant);
1177 else if (isAscii() && NumCharsSoFar == 4)
1178 PP.Diag(Loc, diag::ext_four_char_character_literal);
1180 PP.Diag(Loc, diag::ext_multichar_character_literal);
1182 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1185 IsMultiChar = false;
1188 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1190 // Narrow character literals act as though their value is concatenated
1191 // in this implementation, but warn on overflow.
1192 bool multi_char_too_long = false;
1193 if (isAscii() && isMultiChar()) {
1195 for (size_t i = 0; i < NumCharsSoFar; ++i) {
1196 // check for enough leading zeros to shift into
1197 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1199 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1201 } else if (NumCharsSoFar > 0) {
1202 // otherwise just take the last character
1203 LitVal = buffer_begin[-1];
1206 if (!HadError && multi_char_too_long) {
1207 PP.Diag(Loc, diag::warn_char_constant_too_large);
1210 // Transfer the value from APInt to uint64_t
1211 Value = LitVal.getZExtValue();
1213 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1214 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1215 // character constants are not sign extended in the this implementation:
1216 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1217 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1218 PP.getLangOpts().CharIsSigned)
1219 Value = (signed char)Value;
1223 /// string-literal: [C++0x lex.string]
1224 /// encoding-prefix " [s-char-sequence] "
1225 /// encoding-prefix R raw-string
1226 /// encoding-prefix:
1231 /// s-char-sequence:
1233 /// s-char-sequence s-char
1235 /// any member of the source character set except the double-quote ",
1236 /// backslash \, or new-line character
1238 /// universal-character-name
1240 /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1241 /// r-char-sequence:
1243 /// r-char-sequence r-char
1245 /// any member of the source character set, except a right parenthesis )
1246 /// followed by the initial d-char-sequence (which may be empty)
1247 /// followed by a double quote ".
1248 /// d-char-sequence:
1250 /// d-char-sequence d-char
1252 /// any member of the basic source character set except:
1253 /// space, the left parenthesis (, the right parenthesis ),
1254 /// the backslash \, and the control characters representing horizontal
1255 /// tab, vertical tab, form feed, and newline.
1256 /// escape-sequence: [C++0x lex.ccon]
1257 /// simple-escape-sequence
1258 /// octal-escape-sequence
1259 /// hexadecimal-escape-sequence
1260 /// simple-escape-sequence:
1261 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1262 /// octal-escape-sequence:
1264 /// \ octal-digit octal-digit
1265 /// \ octal-digit octal-digit octal-digit
1266 /// hexadecimal-escape-sequence:
1267 /// \x hexadecimal-digit
1268 /// hexadecimal-escape-sequence hexadecimal-digit
1269 /// universal-character-name:
1271 /// \U hex-quad hex-quad
1273 /// hex-digit hex-digit hex-digit hex-digit
1276 StringLiteralParser::
1277 StringLiteralParser(ArrayRef<Token> StringToks,
1278 Preprocessor &PP, bool Complain)
1279 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1280 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
1281 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1282 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1286 void StringLiteralParser::init(ArrayRef<Token> StringToks){
1287 // The literal token may have come from an invalid source location (e.g. due
1288 // to a PCH error), in which case the token length will be 0.
1289 if (StringToks.empty() || StringToks[0].getLength() < 2)
1290 return DiagnoseLexingError(SourceLocation());
1292 // Scan all of the string portions, remember the max individual token length,
1293 // computing a bound on the concatenated string length, and see whether any
1294 // piece is a wide-string. If any of the string portions is a wide-string
1295 // literal, the result is a wide-string literal [C99 6.4.5p4].
1296 assert(!StringToks.empty() && "expected at least one token");
1297 MaxTokenLength = StringToks[0].getLength();
1298 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1299 SizeBound = StringToks[0].getLength()-2; // -2 for "".
1300 Kind = StringToks[0].getKind();
1304 // Implement Translation Phase #6: concatenation of string literals
1305 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1306 for (unsigned i = 1; i != StringToks.size(); ++i) {
1307 if (StringToks[i].getLength() < 2)
1308 return DiagnoseLexingError(StringToks[i].getLocation());
1310 // The string could be shorter than this if it needs cleaning, but this is a
1311 // reasonable bound, which is all we need.
1312 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1313 SizeBound += StringToks[i].getLength()-2; // -2 for "".
1315 // Remember maximum string piece length.
1316 if (StringToks[i].getLength() > MaxTokenLength)
1317 MaxTokenLength = StringToks[i].getLength();
1319 // Remember if we see any wide or utf-8/16/32 strings.
1320 // Also check for illegal concatenations.
1321 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1323 Kind = StringToks[i].getKind();
1326 Diags->Report(StringToks[i].getLocation(),
1327 diag::err_unsupported_string_concat);
1333 // Include space for the null terminator.
1336 // TODO: K&R warning: "traditional C rejects string constant concatenation"
1338 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1339 CharByteWidth = getCharWidth(Kind, Target);
1340 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1343 // The output buffer size needs to be large enough to hold wide characters.
1344 // This is a worst-case assumption which basically corresponds to L"" "long".
1345 SizeBound *= CharByteWidth;
1347 // Size the temporary buffer to hold the result string data.
1348 ResultBuf.resize(SizeBound);
1350 // Likewise, but for each string piece.
1351 SmallString<512> TokenBuf;
1352 TokenBuf.resize(MaxTokenLength);
1354 // Loop over all the strings, getting their spelling, and expanding them to
1355 // wide strings as appropriate.
1356 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
1360 SourceLocation UDSuffixTokLoc;
1362 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
1363 const char *ThisTokBuf = &TokenBuf[0];
1364 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1365 // that ThisTokBuf points to a buffer that is big enough for the whole token
1366 // and 'spelled' tokens can only shrink.
1367 bool StringInvalid = false;
1368 unsigned ThisTokLen =
1369 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1372 return DiagnoseLexingError(StringToks[i].getLocation());
1374 const char *ThisTokBegin = ThisTokBuf;
1375 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1377 // Remove an optional ud-suffix.
1378 if (ThisTokEnd[-1] != '"') {
1379 const char *UDSuffixEnd = ThisTokEnd;
1382 } while (ThisTokEnd[-1] != '"');
1384 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1386 if (UDSuffixBuf.empty()) {
1387 if (StringToks[i].hasUCN())
1388 expandUCNs(UDSuffixBuf, UDSuffix);
1390 UDSuffixBuf.assign(UDSuffix);
1392 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1393 UDSuffixTokLoc = StringToks[i].getLocation();
1395 SmallString<32> ExpandedUDSuffix;
1396 if (StringToks[i].hasUCN()) {
1397 expandUCNs(ExpandedUDSuffix, UDSuffix);
1398 UDSuffix = ExpandedUDSuffix;
1401 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1402 // result of a concatenation involving at least one user-defined-string-
1403 // literal, all the participating user-defined-string-literals shall
1404 // have the same ud-suffix.
1405 if (UDSuffixBuf != UDSuffix) {
1407 SourceLocation TokLoc = StringToks[i].getLocation();
1408 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1409 << UDSuffixBuf << UDSuffix
1410 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1411 << SourceRange(TokLoc, TokLoc);
1418 // Strip the end quote.
1421 // TODO: Input character set mapping support.
1423 // Skip marker for wide or unicode strings.
1424 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1426 // Skip 8 of u8 marker for utf8 strings.
1427 if (ThisTokBuf[0] == '8')
1431 // Check for raw string
1432 if (ThisTokBuf[0] == 'R') {
1433 ThisTokBuf += 2; // skip R"
1435 const char *Prefix = ThisTokBuf;
1436 while (ThisTokBuf[0] != '(')
1438 ++ThisTokBuf; // skip '('
1440 // Remove same number of characters from the end
1441 ThisTokEnd -= ThisTokBuf - Prefix;
1442 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1444 // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1445 // results in a new-line in the resulting execution string-literal.
1446 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1447 while (!RemainingTokenSpan.empty()) {
1448 // Split the string literal on \r\n boundaries.
1449 size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1450 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1451 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1453 // Copy everything before the \r\n sequence into the string literal.
1454 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1457 // Point into the \n inside the \r\n sequence and operate on the
1458 // remaining portion of the literal.
1459 RemainingTokenSpan = AfterCRLF.substr(1);
1462 if (ThisTokBuf[0] != '"') {
1463 // The file may have come from PCH and then changed after loading the
1464 // PCH; Fail gracefully.
1465 return DiagnoseLexingError(StringToks[i].getLocation());
1467 ++ThisTokBuf; // skip "
1469 // Check if this is a pascal string
1470 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1471 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1473 // If the \p sequence is found in the first token, we have a pascal string
1474 // Otherwise, if we already have a pascal string, ignore the first \p
1482 while (ThisTokBuf != ThisTokEnd) {
1483 // Is this a span of non-escape characters?
1484 if (ThisTokBuf[0] != '\\') {
1485 const char *InStart = ThisTokBuf;
1488 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1490 // Copy the character span over.
1491 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1492 StringRef(InStart, ThisTokBuf - InStart)))
1496 // Is this a Universal Character Name escape?
1497 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1498 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1499 ResultPtr, hadError,
1500 FullSourceLoc(StringToks[i].getLocation(), SM),
1501 CharByteWidth, Diags, Features);
1504 // Otherwise, this is a non-UCN escape character. Process it.
1505 unsigned ResultChar =
1506 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1507 FullSourceLoc(StringToks[i].getLocation(), SM),
1508 CharByteWidth*8, Diags, Features);
1510 if (CharByteWidth == 4) {
1511 // FIXME: Make the type of the result buffer correct instead of
1512 // using reinterpret_cast.
1513 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
1514 *ResultWidePtr = ResultChar;
1516 } else if (CharByteWidth == 2) {
1517 // FIXME: Make the type of the result buffer correct instead of
1518 // using reinterpret_cast.
1519 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
1520 *ResultWidePtr = ResultChar & 0xFFFF;
1523 assert(CharByteWidth == 1 && "Unexpected char width");
1524 *ResultPtr++ = ResultChar & 0xFF;
1531 if (CharByteWidth == 4) {
1532 // FIXME: Make the type of the result buffer correct instead of
1533 // using reinterpret_cast.
1534 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
1535 ResultWidePtr[0] = GetNumStringChars() - 1;
1536 } else if (CharByteWidth == 2) {
1537 // FIXME: Make the type of the result buffer correct instead of
1538 // using reinterpret_cast.
1539 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
1540 ResultWidePtr[0] = GetNumStringChars() - 1;
1542 assert(CharByteWidth == 1 && "Unexpected char width");
1543 ResultBuf[0] = GetNumStringChars() - 1;
1546 // Verify that pascal strings aren't too large.
1547 if (GetStringLength() > 256) {
1549 Diags->Report(StringToks.front().getLocation(),
1550 diag::err_pascal_string_too_long)
1551 << SourceRange(StringToks.front().getLocation(),
1552 StringToks.back().getLocation());
1557 // Complain if this string literal has too many characters.
1558 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1560 if (GetNumStringChars() > MaxChars)
1561 Diags->Report(StringToks.front().getLocation(),
1562 diag::ext_string_too_long)
1563 << GetNumStringChars() << MaxChars
1564 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1565 << SourceRange(StringToks.front().getLocation(),
1566 StringToks.back().getLocation());
1570 static const char *resyncUTF8(const char *Err, const char *End) {
1573 End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
1574 while (++Err != End && (*Err & 0xC0) == 0x80)
1579 /// \brief This function copies from Fragment, which is a sequence of bytes
1580 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1581 /// Performs widening for multi-byte characters.
1582 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1583 const char *TokBegin,
1584 StringRef Fragment) {
1585 const llvm::UTF8 *ErrorPtrTmp;
1586 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1589 // If we see bad encoding for unprefixed string literals, warn and
1590 // simply copy the byte values, for compatibility with gcc and older
1591 // versions of clang.
1592 bool NoErrorOnBadEncoding = isAscii();
1593 if (NoErrorOnBadEncoding) {
1594 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1595 ResultPtr += Fragment.size();
1599 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1601 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1602 const DiagnosticBuilder &Builder =
1603 Diag(Diags, Features, SourceLoc, TokBegin,
1604 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1605 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1606 : diag::err_bad_string_encoding);
1608 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1609 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1611 // Decode into a dummy buffer.
1612 SmallString<512> Dummy;
1613 Dummy.reserve(Fragment.size() * CharByteWidth);
1614 char *Ptr = Dummy.data();
1616 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1617 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1618 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1619 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1620 ErrorPtr, NextStart);
1621 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1624 return !NoErrorOnBadEncoding;
1627 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1630 Diags->Report(Loc, diag::err_lexing_string);
1633 /// getOffsetOfStringByte - This function returns the offset of the
1634 /// specified byte of the string data represented by Token. This handles
1635 /// advancing over escape sequences in the string.
1636 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1637 unsigned ByteNo) const {
1638 // Get the spelling of the token.
1639 SmallString<32> SpellingBuffer;
1640 SpellingBuffer.resize(Tok.getLength());
1642 bool StringInvalid = false;
1643 const char *SpellingPtr = &SpellingBuffer[0];
1644 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1649 const char *SpellingStart = SpellingPtr;
1650 const char *SpellingEnd = SpellingPtr+TokLen;
1652 // Handle UTF-8 strings just like narrow strings.
1653 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1656 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1657 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1659 // For raw string literals, this is easy.
1660 if (SpellingPtr[0] == 'R') {
1661 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1664 while (*SpellingPtr != '(') {
1666 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1670 return SpellingPtr - SpellingStart + ByteNo;
1673 // Skip over the leading quote
1674 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1677 // Skip over bytes until we find the offset we're looking for.
1679 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1681 // Step over non-escapes simply.
1682 if (*SpellingPtr != '\\') {
1688 // Otherwise, this is an escape character. Advance over it.
1689 bool HadError = false;
1690 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1691 const char *EscapePtr = SpellingPtr;
1692 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1693 1, Features, HadError);
1695 // ByteNo is somewhere within the escape sequence.
1696 SpellingPtr = EscapePtr;
1701 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1702 FullSourceLoc(Tok.getLocation(), SM),
1703 CharByteWidth*8, Diags, Features);
1706 assert(!HadError && "This method isn't valid on erroneous strings");
1709 return SpellingPtr-SpellingStart;
1712 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
1713 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
1714 /// treat it as an invalid suffix.
1715 bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
1717 return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||