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 /// 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.
460 *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
463 *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
466 *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
469 *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
471 // Update the buffer.
472 ResultBuf += bytesToWrite;
475 /// integer-constant: [C99 6.4.4.1]
476 /// decimal-constant integer-suffix
477 /// octal-constant integer-suffix
478 /// hexadecimal-constant integer-suffix
479 /// binary-literal integer-suffix [GNU, C++1y]
480 /// user-defined-integer-literal: [C++11 lex.ext]
481 /// decimal-literal ud-suffix
482 /// octal-literal ud-suffix
483 /// hexadecimal-literal ud-suffix
484 /// binary-literal ud-suffix [GNU, C++1y]
485 /// decimal-constant:
487 /// decimal-constant digit
490 /// octal-constant octal-digit
491 /// hexadecimal-constant:
492 /// hexadecimal-prefix hexadecimal-digit
493 /// hexadecimal-constant hexadecimal-digit
494 /// hexadecimal-prefix: one of
499 /// binary-literal binary-digit
501 /// unsigned-suffix [long-suffix]
502 /// unsigned-suffix [long-long-suffix]
503 /// long-suffix [unsigned-suffix]
504 /// long-long-suffix [unsigned-sufix]
506 /// 1 2 3 4 5 6 7 8 9
509 /// hexadecimal-digit:
510 /// 0 1 2 3 4 5 6 7 8 9
516 /// unsigned-suffix: one of
518 /// long-suffix: one of
520 /// long-long-suffix: one of
523 /// floating-constant: [C99 6.4.4.2]
524 /// TODO: add rules...
526 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
527 SourceLocation TokLoc,
529 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
531 // This routine assumes that the range begin/end matches the regex for integer
532 // and FP constants (specifically, the 'pp-number' regex), and assumes that
533 // the byte at "*end" is both valid and not part of the regex. Because of
534 // this, it doesn't have to check for 'overscan' in various places.
535 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
537 s = DigitsBegin = ThisTokBegin;
538 saw_exponent = false;
540 saw_ud_suffix = false;
541 saw_fixed_point_suffix = false;
550 MicrosoftInteger = 0;
555 if (*s == '0') { // parse radix
556 ParseNumberStartingWithZero(TokLoc);
559 } else { // the first digit is non-zero
562 if (s == ThisTokEnd) {
565 ParseDecimalOrOctalCommon(TokLoc);
572 checkSeparator(TokLoc, s, CSK_AfterDigits);
574 // Initial scan to lookahead for fixed point suffix.
575 if (PP.getLangOpts().FixedPoint) {
576 for (const char *c = s; c != ThisTokEnd; ++c) {
577 if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
578 saw_fixed_point_suffix = true;
584 // Parse the suffix. At this point we can classify whether we have an FP or
586 bool isFPConstant = isFloatingLiteral();
588 // Loop over all of the characters of the suffix. If we see something bad,
589 // we break out of the loop.
590 for (; s != ThisTokEnd; ++s) {
594 if (!PP.getLangOpts().FixedPoint) break;
595 if (isFract || isAccum) break;
596 if (!(saw_period || saw_exponent)) break;
601 if (!PP.getLangOpts().FixedPoint) break;
602 if (isFract || isAccum) break;
603 if (!(saw_period || saw_exponent)) break;
606 case 'h': // FP Suffix for "half".
608 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
609 if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
610 if (isIntegerLiteral()) break; // Error for integer constant.
611 if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
613 continue; // Success.
614 case 'f': // FP Suffix for "float"
616 if (!isFPConstant) break; // Error for integer constant.
617 if (isHalf || isFloat || isLong || isFloat128)
618 break; // HF, FF, LF, QF invalid.
620 if (s + 2 < ThisTokEnd && s[1] == '1' && s[2] == '6') {
621 s += 2; // success, eat up 2 characters.
627 continue; // Success.
628 case 'q': // FP Suffix for "__float128"
630 if (!isFPConstant) break; // Error for integer constant.
631 if (isHalf || isFloat || isLong || isFloat128)
632 break; // HQ, FQ, LQ, QQ invalid.
634 continue; // Success.
637 if (isFPConstant) break; // Error for floating constant.
638 if (isUnsigned) break; // Cannot be repeated.
640 continue; // Success.
643 if (isLong || isLongLong) break; // Cannot be repeated.
644 if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid.
646 // Check for long long. The L's need to be adjacent and the same case.
648 assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
649 if (isFPConstant) break; // long long invalid for floats.
651 ++s; // Eat both of them.
655 continue; // Success.
658 if (PP.getLangOpts().MicrosoftExt) {
659 if (isLong || isLongLong || MicrosoftInteger)
663 // Allow i8, i16, i32, and i64.
667 MicrosoftInteger = 8;
671 s += 3; // i16 suffix
672 MicrosoftInteger = 16;
677 s += 3; // i32 suffix
678 MicrosoftInteger = 32;
683 s += 3; // i64 suffix
684 MicrosoftInteger = 64;
691 if (MicrosoftInteger) {
692 assert(s <= ThisTokEnd && "didn't maximally munch?");
699 if (isImaginary) break; // Cannot be repeated.
701 continue; // Success.
703 // If we reached here, there was an error or a ud-suffix.
707 // "i", "if", and "il" are user-defined suffixes in C++1y.
708 if (s != ThisTokEnd || isImaginary) {
709 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
710 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
711 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
713 // Any suffix pieces we might have parsed are actually part of the
722 MicrosoftInteger = 0;
723 saw_fixed_point_suffix = false;
728 saw_ud_suffix = true;
732 if (s != ThisTokEnd) {
733 // Report an error if there are any.
734 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
735 diag::err_invalid_suffix_constant)
736 << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant;
741 if (!hadError && saw_fixed_point_suffix) {
742 assert(isFract || isAccum);
746 /// ParseDecimalOrOctalCommon - This method is called for decimal or octal
747 /// numbers. It issues an error for illegal digits, and handles floating point
748 /// parsing. If it detects a floating point number, the radix is set to 10.
749 void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
750 assert((radix == 8 || radix == 10) && "Unexpected radix");
752 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
753 // the code is using an incorrect base.
754 if (isHexDigit(*s) && *s != 'e' && *s != 'E' &&
755 !isValidUDSuffix(PP.getLangOpts(), StringRef(s, ThisTokEnd - s))) {
756 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
757 diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
763 checkSeparator(TokLoc, s, CSK_AfterDigits);
767 checkSeparator(TokLoc, s, CSK_BeforeDigits);
768 s = SkipDigits(s); // Skip suffix.
770 if (*s == 'e' || *s == 'E') { // exponent
771 checkSeparator(TokLoc, s, CSK_AfterDigits);
772 const char *Exponent = s;
776 if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
777 const char *first_non_digit = SkipDigits(s);
778 if (containsDigits(s, first_non_digit)) {
779 checkSeparator(TokLoc, s, CSK_BeforeDigits);
783 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
784 diag::err_exponent_has_no_digits);
792 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
793 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
794 /// treat it as an invalid suffix.
795 bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
797 if (!LangOpts.CPlusPlus11 || Suffix.empty())
800 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
801 if (Suffix[0] == '_')
804 // In C++11, there are no library suffixes.
805 if (!LangOpts.CPlusPlus14)
808 // In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
809 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
810 // In C++2a "d" and "y" are used in the library.
811 return llvm::StringSwitch<bool>(Suffix)
812 .Cases("h", "min", "s", true)
813 .Cases("ms", "us", "ns", true)
814 .Cases("il", "i", "if", true)
815 .Cases("d", "y", LangOpts.CPlusPlus2a)
819 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
821 CheckSeparatorKind IsAfterDigits) {
822 if (IsAfterDigits == CSK_AfterDigits) {
823 if (Pos == ThisTokBegin)
826 } else if (Pos == ThisTokEnd)
829 if (isDigitSeparator(*Pos)) {
830 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
831 diag::err_digit_separator_not_between_digits)
837 /// ParseNumberStartingWithZero - This method is called when the first character
838 /// of the number is found to be a zero. This means it is either an octal
839 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
840 /// a floating point number (01239.123e4). Eat the prefix, determining the
842 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
843 assert(s[0] == '0' && "Invalid method call");
848 // Handle a hex number like 0x1234.
849 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
851 assert(s < ThisTokEnd && "didn't maximally munch?");
854 s = SkipHexDigits(s);
855 bool HasSignificandDigits = containsDigits(DigitsBegin, s);
856 if (s == ThisTokEnd) {
858 } else if (*s == '.') {
861 const char *floatDigitsBegin = s;
862 s = SkipHexDigits(s);
863 if (containsDigits(floatDigitsBegin, s))
864 HasSignificandDigits = true;
865 if (HasSignificandDigits)
866 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
869 if (!HasSignificandDigits) {
870 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
871 diag::err_hex_constant_requires)
872 << PP.getLangOpts().CPlusPlus << 1;
877 // A binary exponent can appear with or with a '.'. If dotted, the
878 // binary exponent is required.
879 if (*s == 'p' || *s == 'P') {
880 checkSeparator(TokLoc, s, CSK_AfterDigits);
881 const char *Exponent = s;
884 if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
885 const char *first_non_digit = SkipDigits(s);
886 if (!containsDigits(s, first_non_digit)) {
888 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
889 diag::err_exponent_has_no_digits);
894 checkSeparator(TokLoc, s, CSK_BeforeDigits);
897 if (!PP.getLangOpts().HexFloats)
898 PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
899 ? diag::ext_hex_literal_invalid
900 : diag::ext_hex_constant_invalid);
901 else if (PP.getLangOpts().CPlusPlus17)
902 PP.Diag(TokLoc, diag::warn_cxx17_hex_literal);
903 } else if (saw_period) {
904 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
905 diag::err_hex_constant_requires)
906 << PP.getLangOpts().CPlusPlus << 0;
912 // Handle simple binary numbers 0b01010
913 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
914 // 0b101010 is a C++1y / GCC extension.
916 PP.getLangOpts().CPlusPlus14
917 ? diag::warn_cxx11_compat_binary_literal
918 : PP.getLangOpts().CPlusPlus
919 ? diag::ext_binary_literal_cxx14
920 : diag::ext_binary_literal);
922 assert(s < ThisTokEnd && "didn't maximally munch?");
925 s = SkipBinaryDigits(s);
926 if (s == ThisTokEnd) {
928 } else if (isHexDigit(*s) &&
929 !isValidUDSuffix(PP.getLangOpts(),
930 StringRef(s, ThisTokEnd - s))) {
931 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
932 diag::err_invalid_digit) << StringRef(s, 1) << 2;
935 // Other suffixes will be diagnosed by the caller.
939 // For now, the radix is set to 8. If we discover that we have a
940 // floating point constant, the radix will change to 10. Octal floating
941 // point constants are not permitted (only decimal and hexadecimal).
944 s = SkipOctalDigits(s);
946 return; // Done, simple octal number like 01234
948 // If we have some other non-octal digit that *is* a decimal digit, see if
949 // this is part of a floating point number like 094.123 or 09e1.
951 const char *EndDecimal = SkipDigits(s);
952 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
958 ParseDecimalOrOctalCommon(TokLoc);
961 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
964 return NumDigits <= 64;
966 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
968 return NumDigits <= 19; // floor(log10(2^64))
970 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
972 llvm_unreachable("impossible Radix");
976 /// GetIntegerValue - Convert this numeric literal value to an APInt that
977 /// matches Val's input width. If there is an overflow, set Val to the low bits
978 /// of the result and return true. Otherwise, return false.
979 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
980 // Fast path: Compute a conservative bound on the maximum number of
981 // bits per digit in this radix. If we can't possibly overflow a
982 // uint64 based on that bound then do the simple conversion to
983 // integer. This avoids the expensive overflow checking below, and
984 // handles the common cases that matter (small decimal integers and
985 // hex/octal values which don't overflow).
986 const unsigned NumDigits = SuffixBegin - DigitsBegin;
987 if (alwaysFitsInto64Bits(radix, NumDigits)) {
989 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
990 if (!isDigitSeparator(*Ptr))
991 N = N * radix + llvm::hexDigitValue(*Ptr);
993 // This will truncate the value to Val's input width. Simply check
994 // for overflow by comparing.
996 return Val.getZExtValue() != N;
1000 const char *Ptr = DigitsBegin;
1002 llvm::APInt RadixVal(Val.getBitWidth(), radix);
1003 llvm::APInt CharVal(Val.getBitWidth(), 0);
1004 llvm::APInt OldVal = Val;
1006 bool OverflowOccurred = false;
1007 while (Ptr < SuffixBegin) {
1008 if (isDigitSeparator(*Ptr)) {
1013 unsigned C = llvm::hexDigitValue(*Ptr++);
1015 // If this letter is out of bound for this radix, reject it.
1016 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1020 // Add the digit to the value in the appropriate radix. If adding in digits
1021 // made the value smaller, then this overflowed.
1024 // Multiply by radix, did overflow occur on the multiply?
1026 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
1028 // Add value, did overflow occur on the value?
1029 // (a + b) ult b <=> overflow
1031 OverflowOccurred |= Val.ult(CharVal);
1033 return OverflowOccurred;
1036 llvm::APFloat::opStatus
1037 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
1038 using llvm::APFloat;
1040 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
1042 llvm::SmallString<16> Buffer;
1043 StringRef Str(ThisTokBegin, n);
1044 if (Str.find('\'') != StringRef::npos) {
1046 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
1051 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
1054 static inline bool IsExponentPart(char c) {
1055 return c == 'p' || c == 'P' || c == 'e' || c == 'E';
1058 bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
1059 assert(radix == 16 || radix == 10);
1061 // Find how many digits are needed to store the whole literal.
1062 unsigned NumDigits = SuffixBegin - DigitsBegin;
1063 if (saw_period) --NumDigits;
1065 // Initial scan of the exponent if it exists
1066 bool ExpOverflowOccurred = false;
1067 bool NegativeExponent = false;
1068 const char *ExponentBegin;
1069 uint64_t Exponent = 0;
1070 int64_t BaseShift = 0;
1072 const char *Ptr = DigitsBegin;
1074 while (!IsExponentPart(*Ptr)) ++Ptr;
1075 ExponentBegin = Ptr;
1077 NegativeExponent = *Ptr == '-';
1078 if (NegativeExponent) ++Ptr;
1080 unsigned NumExpDigits = SuffixBegin - Ptr;
1081 if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
1082 llvm::StringRef ExpStr(Ptr, NumExpDigits);
1083 llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
1084 Exponent = ExpInt.getZExtValue();
1086 ExpOverflowOccurred = true;
1089 if (NegativeExponent) BaseShift -= Exponent;
1090 else BaseShift += Exponent;
1093 // Number of bits needed for decimal literal is
1094 // ceil(NumDigits * log2(10)) Integral part
1095 // + Scale Fractional part
1096 // + ceil(Exponent * log2(10)) Exponent
1097 // --------------------------------------------------
1098 // ceil((NumDigits + Exponent) * log2(10)) + Scale
1100 // But for simplicity in handling integers, we can round up log2(10) to 4,
1102 // 4 * (NumDigits + Exponent) + Scale
1104 // Number of digits needed for hexadecimal literal is
1105 // 4 * NumDigits Integral part
1106 // + Scale Fractional part
1107 // + Exponent Exponent
1108 // --------------------------------------------------
1109 // (4 * NumDigits) + Scale + Exponent
1110 uint64_t NumBitsNeeded;
1112 NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
1114 NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
1116 if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
1117 ExpOverflowOccurred = true;
1118 llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
1120 bool FoundDecimal = false;
1122 int64_t FractBaseShift = 0;
1123 const char *End = saw_exponent ? ExponentBegin : SuffixBegin;
1124 for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) {
1126 FoundDecimal = true;
1130 // Normal reading of an integer
1131 unsigned C = llvm::hexDigitValue(*Ptr);
1132 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1138 // Keep track of how much we will need to adjust this value by from the
1139 // number of digits past the radix point.
1143 // For a radix of 16, we will be multiplying by 2 instead of 16.
1144 if (radix == 16) FractBaseShift *= 4;
1145 BaseShift += FractBaseShift;
1149 uint64_t Base = (radix == 16) ? 2 : 10;
1150 if (BaseShift > 0) {
1151 for (int64_t i = 0; i < BaseShift; ++i) {
1154 } else if (BaseShift < 0) {
1155 for (int64_t i = BaseShift; i < 0 && !Val.isNullValue(); ++i)
1156 Val = Val.udiv(Base);
1159 bool IntOverflowOccurred = false;
1160 auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
1161 if (Val.getBitWidth() > StoreVal.getBitWidth()) {
1162 IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
1163 StoreVal = Val.trunc(StoreVal.getBitWidth());
1164 } else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
1165 IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
1166 StoreVal = Val.zext(StoreVal.getBitWidth());
1171 return IntOverflowOccurred || ExpOverflowOccurred;
1175 /// user-defined-character-literal: [C++11 lex.ext]
1176 /// character-literal ud-suffix
1179 /// character-literal: [C++11 lex.ccon]
1180 /// ' c-char-sequence '
1181 /// u' c-char-sequence '
1182 /// U' c-char-sequence '
1183 /// L' c-char-sequence '
1184 /// u8' c-char-sequence ' [C++1z lex.ccon]
1185 /// c-char-sequence:
1187 /// c-char-sequence c-char
1189 /// any member of the source character set except the single-quote ',
1190 /// backslash \, or new-line character
1192 /// universal-character-name
1193 /// escape-sequence:
1194 /// simple-escape-sequence
1195 /// octal-escape-sequence
1196 /// hexadecimal-escape-sequence
1197 /// simple-escape-sequence:
1198 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1199 /// octal-escape-sequence:
1201 /// \ octal-digit octal-digit
1202 /// \ octal-digit octal-digit octal-digit
1203 /// hexadecimal-escape-sequence:
1204 /// \x hexadecimal-digit
1205 /// hexadecimal-escape-sequence hexadecimal-digit
1206 /// universal-character-name: [C++11 lex.charset]
1208 /// \U hex-quad hex-quad
1210 /// hex-digit hex-digit hex-digit hex-digit
1213 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
1214 SourceLocation Loc, Preprocessor &PP,
1215 tok::TokenKind kind) {
1216 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
1221 const char *TokBegin = begin;
1223 // Skip over wide character determinant.
1224 if (Kind != tok::char_constant)
1226 if (Kind == tok::utf8_char_constant)
1229 // Skip over the entry quote.
1230 assert(begin[0] == '\'' && "Invalid token lexed");
1233 // Remove an optional ud-suffix.
1234 if (end[-1] != '\'') {
1235 const char *UDSuffixEnd = end;
1238 } while (end[-1] != '\'');
1239 // FIXME: Don't bother with this if !tok.hasUCN().
1240 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
1241 UDSuffixOffset = end - TokBegin;
1244 // Trim the ending quote.
1245 assert(end != begin && "Invalid token lexed");
1248 // FIXME: The "Value" is an uint64_t so we can handle char literals of
1250 // FIXME: This extensively assumes that 'char' is 8-bits.
1251 assert(PP.getTargetInfo().getCharWidth() == 8 &&
1252 "Assumes char is 8 bits");
1253 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1254 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1255 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1256 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1257 "Assumes sizeof(wchar) on target is <= 64");
1259 SmallVector<uint32_t, 4> codepoint_buffer;
1260 codepoint_buffer.resize(end - begin);
1261 uint32_t *buffer_begin = &codepoint_buffer.front();
1262 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1264 // Unicode escapes representing characters that cannot be correctly
1265 // represented in a single code unit are disallowed in character literals
1266 // by this implementation.
1267 uint32_t largest_character_for_kind;
1268 if (tok::wide_char_constant == Kind) {
1269 largest_character_for_kind =
1270 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1271 } else if (tok::utf8_char_constant == Kind) {
1272 largest_character_for_kind = 0x7F;
1273 } else if (tok::utf16_char_constant == Kind) {
1274 largest_character_for_kind = 0xFFFF;
1275 } else if (tok::utf32_char_constant == Kind) {
1276 largest_character_for_kind = 0x10FFFF;
1278 largest_character_for_kind = 0x7Fu;
1281 while (begin != end) {
1282 // Is this a span of non-escape characters?
1283 if (begin[0] != '\\') {
1284 char const *start = begin;
1287 } while (begin != end && *begin != '\\');
1289 char const *tmp_in_start = start;
1290 uint32_t *tmp_out_start = buffer_begin;
1291 llvm::ConversionResult res =
1292 llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
1293 reinterpret_cast<llvm::UTF8 const *>(begin),
1294 &buffer_begin, buffer_end, llvm::strictConversion);
1295 if (res != llvm::conversionOK) {
1296 // If we see bad encoding for unprefixed character literals, warn and
1297 // simply copy the byte values, for compatibility with gcc and
1298 // older versions of clang.
1299 bool NoErrorOnBadEncoding = isAscii();
1300 unsigned Msg = diag::err_bad_character_encoding;
1301 if (NoErrorOnBadEncoding)
1302 Msg = diag::warn_bad_character_encoding;
1304 if (NoErrorOnBadEncoding) {
1305 start = tmp_in_start;
1306 buffer_begin = tmp_out_start;
1307 for (; start != begin; ++start, ++buffer_begin)
1308 *buffer_begin = static_cast<uint8_t>(*start);
1313 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1314 if (*tmp_out_start > largest_character_for_kind) {
1316 PP.Diag(Loc, diag::err_character_too_large);
1323 // Is this a Universal Character Name escape?
1324 if (begin[1] == 'u' || begin[1] == 'U') {
1325 unsigned short UcnLen = 0;
1326 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1327 FullSourceLoc(Loc, PP.getSourceManager()),
1328 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1330 } else if (*buffer_begin > largest_character_for_kind) {
1332 PP.Diag(Loc, diag::err_character_too_large);
1338 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1340 ProcessCharEscape(TokBegin, begin, end, HadError,
1341 FullSourceLoc(Loc,PP.getSourceManager()),
1342 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1343 *buffer_begin++ = result;
1346 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1348 if (NumCharsSoFar > 1) {
1350 PP.Diag(Loc, diag::warn_extraneous_char_constant);
1351 else if (isAscii() && NumCharsSoFar == 4)
1352 PP.Diag(Loc, diag::ext_four_char_character_literal);
1354 PP.Diag(Loc, diag::ext_multichar_character_literal);
1356 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1359 IsMultiChar = false;
1362 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1364 // Narrow character literals act as though their value is concatenated
1365 // in this implementation, but warn on overflow.
1366 bool multi_char_too_long = false;
1367 if (isAscii() && isMultiChar()) {
1369 for (size_t i = 0; i < NumCharsSoFar; ++i) {
1370 // check for enough leading zeros to shift into
1371 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1373 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1375 } else if (NumCharsSoFar > 0) {
1376 // otherwise just take the last character
1377 LitVal = buffer_begin[-1];
1380 if (!HadError && multi_char_too_long) {
1381 PP.Diag(Loc, diag::warn_char_constant_too_large);
1384 // Transfer the value from APInt to uint64_t
1385 Value = LitVal.getZExtValue();
1387 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1388 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1389 // character constants are not sign extended in the this implementation:
1390 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1391 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1392 PP.getLangOpts().CharIsSigned)
1393 Value = (signed char)Value;
1397 /// string-literal: [C++0x lex.string]
1398 /// encoding-prefix " [s-char-sequence] "
1399 /// encoding-prefix R raw-string
1400 /// encoding-prefix:
1405 /// s-char-sequence:
1407 /// s-char-sequence s-char
1409 /// any member of the source character set except the double-quote ",
1410 /// backslash \, or new-line character
1412 /// universal-character-name
1414 /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1415 /// r-char-sequence:
1417 /// r-char-sequence r-char
1419 /// any member of the source character set, except a right parenthesis )
1420 /// followed by the initial d-char-sequence (which may be empty)
1421 /// followed by a double quote ".
1422 /// d-char-sequence:
1424 /// d-char-sequence d-char
1426 /// any member of the basic source character set except:
1427 /// space, the left parenthesis (, the right parenthesis ),
1428 /// the backslash \, and the control characters representing horizontal
1429 /// tab, vertical tab, form feed, and newline.
1430 /// escape-sequence: [C++0x lex.ccon]
1431 /// simple-escape-sequence
1432 /// octal-escape-sequence
1433 /// hexadecimal-escape-sequence
1434 /// simple-escape-sequence:
1435 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1436 /// octal-escape-sequence:
1438 /// \ octal-digit octal-digit
1439 /// \ octal-digit octal-digit octal-digit
1440 /// hexadecimal-escape-sequence:
1441 /// \x hexadecimal-digit
1442 /// hexadecimal-escape-sequence hexadecimal-digit
1443 /// universal-character-name:
1445 /// \U hex-quad hex-quad
1447 /// hex-digit hex-digit hex-digit hex-digit
1450 StringLiteralParser::
1451 StringLiteralParser(ArrayRef<Token> StringToks,
1452 Preprocessor &PP, bool Complain)
1453 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1454 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
1455 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1456 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1460 void StringLiteralParser::init(ArrayRef<Token> StringToks){
1461 // The literal token may have come from an invalid source location (e.g. due
1462 // to a PCH error), in which case the token length will be 0.
1463 if (StringToks.empty() || StringToks[0].getLength() < 2)
1464 return DiagnoseLexingError(SourceLocation());
1466 // Scan all of the string portions, remember the max individual token length,
1467 // computing a bound on the concatenated string length, and see whether any
1468 // piece is a wide-string. If any of the string portions is a wide-string
1469 // literal, the result is a wide-string literal [C99 6.4.5p4].
1470 assert(!StringToks.empty() && "expected at least one token");
1471 MaxTokenLength = StringToks[0].getLength();
1472 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1473 SizeBound = StringToks[0].getLength()-2; // -2 for "".
1474 Kind = StringToks[0].getKind();
1478 // Implement Translation Phase #6: concatenation of string literals
1479 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1480 for (unsigned i = 1; i != StringToks.size(); ++i) {
1481 if (StringToks[i].getLength() < 2)
1482 return DiagnoseLexingError(StringToks[i].getLocation());
1484 // The string could be shorter than this if it needs cleaning, but this is a
1485 // reasonable bound, which is all we need.
1486 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1487 SizeBound += StringToks[i].getLength()-2; // -2 for "".
1489 // Remember maximum string piece length.
1490 if (StringToks[i].getLength() > MaxTokenLength)
1491 MaxTokenLength = StringToks[i].getLength();
1493 // Remember if we see any wide or utf-8/16/32 strings.
1494 // Also check for illegal concatenations.
1495 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1497 Kind = StringToks[i].getKind();
1500 Diags->Report(StringToks[i].getLocation(),
1501 diag::err_unsupported_string_concat);
1507 // Include space for the null terminator.
1510 // TODO: K&R warning: "traditional C rejects string constant concatenation"
1512 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1513 CharByteWidth = getCharWidth(Kind, Target);
1514 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1517 // The output buffer size needs to be large enough to hold wide characters.
1518 // This is a worst-case assumption which basically corresponds to L"" "long".
1519 SizeBound *= CharByteWidth;
1521 // Size the temporary buffer to hold the result string data.
1522 ResultBuf.resize(SizeBound);
1524 // Likewise, but for each string piece.
1525 SmallString<512> TokenBuf;
1526 TokenBuf.resize(MaxTokenLength);
1528 // Loop over all the strings, getting their spelling, and expanding them to
1529 // wide strings as appropriate.
1530 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
1534 SourceLocation UDSuffixTokLoc;
1536 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
1537 const char *ThisTokBuf = &TokenBuf[0];
1538 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1539 // that ThisTokBuf points to a buffer that is big enough for the whole token
1540 // and 'spelled' tokens can only shrink.
1541 bool StringInvalid = false;
1542 unsigned ThisTokLen =
1543 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1546 return DiagnoseLexingError(StringToks[i].getLocation());
1548 const char *ThisTokBegin = ThisTokBuf;
1549 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1551 // Remove an optional ud-suffix.
1552 if (ThisTokEnd[-1] != '"') {
1553 const char *UDSuffixEnd = ThisTokEnd;
1556 } while (ThisTokEnd[-1] != '"');
1558 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1560 if (UDSuffixBuf.empty()) {
1561 if (StringToks[i].hasUCN())
1562 expandUCNs(UDSuffixBuf, UDSuffix);
1564 UDSuffixBuf.assign(UDSuffix);
1566 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1567 UDSuffixTokLoc = StringToks[i].getLocation();
1569 SmallString<32> ExpandedUDSuffix;
1570 if (StringToks[i].hasUCN()) {
1571 expandUCNs(ExpandedUDSuffix, UDSuffix);
1572 UDSuffix = ExpandedUDSuffix;
1575 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1576 // result of a concatenation involving at least one user-defined-string-
1577 // literal, all the participating user-defined-string-literals shall
1578 // have the same ud-suffix.
1579 if (UDSuffixBuf != UDSuffix) {
1581 SourceLocation TokLoc = StringToks[i].getLocation();
1582 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1583 << UDSuffixBuf << UDSuffix
1584 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1585 << SourceRange(TokLoc, TokLoc);
1592 // Strip the end quote.
1595 // TODO: Input character set mapping support.
1597 // Skip marker for wide or unicode strings.
1598 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1600 // Skip 8 of u8 marker for utf8 strings.
1601 if (ThisTokBuf[0] == '8')
1605 // Check for raw string
1606 if (ThisTokBuf[0] == 'R') {
1607 ThisTokBuf += 2; // skip R"
1609 const char *Prefix = ThisTokBuf;
1610 while (ThisTokBuf[0] != '(')
1612 ++ThisTokBuf; // skip '('
1614 // Remove same number of characters from the end
1615 ThisTokEnd -= ThisTokBuf - Prefix;
1616 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1618 // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1619 // results in a new-line in the resulting execution string-literal.
1620 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1621 while (!RemainingTokenSpan.empty()) {
1622 // Split the string literal on \r\n boundaries.
1623 size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1624 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1625 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1627 // Copy everything before the \r\n sequence into the string literal.
1628 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1631 // Point into the \n inside the \r\n sequence and operate on the
1632 // remaining portion of the literal.
1633 RemainingTokenSpan = AfterCRLF.substr(1);
1636 if (ThisTokBuf[0] != '"') {
1637 // The file may have come from PCH and then changed after loading the
1638 // PCH; Fail gracefully.
1639 return DiagnoseLexingError(StringToks[i].getLocation());
1641 ++ThisTokBuf; // skip "
1643 // Check if this is a pascal string
1644 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1645 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1647 // If the \p sequence is found in the first token, we have a pascal string
1648 // Otherwise, if we already have a pascal string, ignore the first \p
1656 while (ThisTokBuf != ThisTokEnd) {
1657 // Is this a span of non-escape characters?
1658 if (ThisTokBuf[0] != '\\') {
1659 const char *InStart = ThisTokBuf;
1662 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1664 // Copy the character span over.
1665 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1666 StringRef(InStart, ThisTokBuf - InStart)))
1670 // Is this a Universal Character Name escape?
1671 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1672 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1673 ResultPtr, hadError,
1674 FullSourceLoc(StringToks[i].getLocation(), SM),
1675 CharByteWidth, Diags, Features);
1678 // Otherwise, this is a non-UCN escape character. Process it.
1679 unsigned ResultChar =
1680 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1681 FullSourceLoc(StringToks[i].getLocation(), SM),
1682 CharByteWidth*8, Diags, Features);
1684 if (CharByteWidth == 4) {
1685 // FIXME: Make the type of the result buffer correct instead of
1686 // using reinterpret_cast.
1687 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
1688 *ResultWidePtr = ResultChar;
1690 } else if (CharByteWidth == 2) {
1691 // FIXME: Make the type of the result buffer correct instead of
1692 // using reinterpret_cast.
1693 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
1694 *ResultWidePtr = ResultChar & 0xFFFF;
1697 assert(CharByteWidth == 1 && "Unexpected char width");
1698 *ResultPtr++ = ResultChar & 0xFF;
1705 if (CharByteWidth == 4) {
1706 // FIXME: Make the type of the result buffer correct instead of
1707 // using reinterpret_cast.
1708 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
1709 ResultWidePtr[0] = GetNumStringChars() - 1;
1710 } else if (CharByteWidth == 2) {
1711 // FIXME: Make the type of the result buffer correct instead of
1712 // using reinterpret_cast.
1713 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
1714 ResultWidePtr[0] = GetNumStringChars() - 1;
1716 assert(CharByteWidth == 1 && "Unexpected char width");
1717 ResultBuf[0] = GetNumStringChars() - 1;
1720 // Verify that pascal strings aren't too large.
1721 if (GetStringLength() > 256) {
1723 Diags->Report(StringToks.front().getLocation(),
1724 diag::err_pascal_string_too_long)
1725 << SourceRange(StringToks.front().getLocation(),
1726 StringToks.back().getLocation());
1731 // Complain if this string literal has too many characters.
1732 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1734 if (GetNumStringChars() > MaxChars)
1735 Diags->Report(StringToks.front().getLocation(),
1736 diag::ext_string_too_long)
1737 << GetNumStringChars() << MaxChars
1738 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1739 << SourceRange(StringToks.front().getLocation(),
1740 StringToks.back().getLocation());
1744 static const char *resyncUTF8(const char *Err, const char *End) {
1747 End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
1748 while (++Err != End && (*Err & 0xC0) == 0x80)
1753 /// This function copies from Fragment, which is a sequence of bytes
1754 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1755 /// Performs widening for multi-byte characters.
1756 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1757 const char *TokBegin,
1758 StringRef Fragment) {
1759 const llvm::UTF8 *ErrorPtrTmp;
1760 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1763 // If we see bad encoding for unprefixed string literals, warn and
1764 // simply copy the byte values, for compatibility with gcc and older
1765 // versions of clang.
1766 bool NoErrorOnBadEncoding = isAscii();
1767 if (NoErrorOnBadEncoding) {
1768 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1769 ResultPtr += Fragment.size();
1773 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1775 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1776 const DiagnosticBuilder &Builder =
1777 Diag(Diags, Features, SourceLoc, TokBegin,
1778 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1779 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1780 : diag::err_bad_string_encoding);
1782 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1783 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1785 // Decode into a dummy buffer.
1786 SmallString<512> Dummy;
1787 Dummy.reserve(Fragment.size() * CharByteWidth);
1788 char *Ptr = Dummy.data();
1790 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1791 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1792 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1793 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1794 ErrorPtr, NextStart);
1795 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1798 return !NoErrorOnBadEncoding;
1801 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1804 Diags->Report(Loc, diag::err_lexing_string);
1807 /// getOffsetOfStringByte - This function returns the offset of the
1808 /// specified byte of the string data represented by Token. This handles
1809 /// advancing over escape sequences in the string.
1810 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1811 unsigned ByteNo) const {
1812 // Get the spelling of the token.
1813 SmallString<32> SpellingBuffer;
1814 SpellingBuffer.resize(Tok.getLength());
1816 bool StringInvalid = false;
1817 const char *SpellingPtr = &SpellingBuffer[0];
1818 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1823 const char *SpellingStart = SpellingPtr;
1824 const char *SpellingEnd = SpellingPtr+TokLen;
1826 // Handle UTF-8 strings just like narrow strings.
1827 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1830 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1831 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1833 // For raw string literals, this is easy.
1834 if (SpellingPtr[0] == 'R') {
1835 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1838 while (*SpellingPtr != '(') {
1840 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1844 return SpellingPtr - SpellingStart + ByteNo;
1847 // Skip over the leading quote
1848 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1851 // Skip over bytes until we find the offset we're looking for.
1853 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1855 // Step over non-escapes simply.
1856 if (*SpellingPtr != '\\') {
1862 // Otherwise, this is an escape character. Advance over it.
1863 bool HadError = false;
1864 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1865 const char *EscapePtr = SpellingPtr;
1866 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1867 1, Features, HadError);
1869 // ByteNo is somewhere within the escape sequence.
1870 SpellingPtr = EscapePtr;
1875 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1876 FullSourceLoc(Tok.getLocation(), SM),
1877 CharByteWidth*8, Diags, Features);
1880 assert(!HadError && "This method isn't valid on erroneous strings");
1883 return SpellingPtr-SpellingStart;
1886 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
1887 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
1888 /// treat it as an invalid suffix.
1889 bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
1891 return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||