1 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the NumericLiteralParser, CharLiteralParser, and
11 // StringLiteralParser interfaces.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/LiteralSupport.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/Lex/LexDiagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Basic/ConvertUTF.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/ErrorHandling.h"
22 using namespace clang;
24 /// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
26 static int HexDigitValue(char C) {
27 if (C >= '0' && C <= '9') return C-'0';
28 if (C >= 'a' && C <= 'f') return C-'a'+10;
29 if (C >= 'A' && C <= 'F') return C-'A'+10;
33 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
35 default: llvm_unreachable("Unknown token type!");
36 case tok::char_constant:
37 case tok::string_literal:
38 case tok::utf8_string_literal:
39 return Target.getCharWidth();
40 case tok::wide_char_constant:
41 case tok::wide_string_literal:
42 return Target.getWCharWidth();
43 case tok::utf16_char_constant:
44 case tok::utf16_string_literal:
45 return Target.getChar16Width();
46 case tok::utf32_char_constant:
47 case tok::utf32_string_literal:
48 return Target.getChar32Width();
52 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
53 /// either a character or a string literal.
54 static unsigned ProcessCharEscape(const char *&ThisTokBuf,
55 const char *ThisTokEnd, bool &HadError,
56 FullSourceLoc Loc, unsigned CharWidth,
57 DiagnosticsEngine *Diags) {
61 // We know that this character can't be off the end of the buffer, because
62 // that would have been \", which would not have been the end of string.
63 unsigned ResultChar = *ThisTokBuf++;
65 // These map to themselves.
66 case '\\': case '\'': case '"': case '?': break;
68 // These have fixed mappings.
70 // TODO: K&R: the meaning of '\\a' is different in traditional C
78 Diags->Report(Loc, diag::ext_nonstandard_escape) << "e";
83 Diags->Report(Loc, diag::ext_nonstandard_escape) << "E";
101 case 'x': { // Hex escape.
103 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
105 Diags->Report(Loc, diag::err_hex_escape_no_digits);
110 // Hex escapes are a maximal series of hex digits.
111 bool Overflow = false;
112 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
113 int CharVal = HexDigitValue(ThisTokBuf[0]);
114 if (CharVal == -1) break;
115 // About to shift out a digit?
116 Overflow |= (ResultChar & 0xF0000000) ? true : false;
118 ResultChar |= CharVal;
121 // See if any bits will be truncated when evaluated as a character.
122 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
124 ResultChar &= ~0U >> (32-CharWidth);
127 // Check for overflow.
128 if (Overflow && Diags) // Too many digits to fit in
129 Diags->Report(Loc, diag::warn_hex_escape_too_large);
132 case '0': case '1': case '2': case '3':
133 case '4': case '5': case '6': case '7': {
138 // Octal escapes are a series of octal digits with maximum length 3.
139 // "\0123" is a two digit sequence equal to "\012" "3".
140 unsigned NumDigits = 0;
143 ResultChar |= *ThisTokBuf++ - '0';
145 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
146 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
148 // Check for overflow. Reject '\777', but not L'\777'.
149 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
151 Diags->Report(Loc, diag::warn_octal_escape_too_large);
152 ResultChar &= ~0U >> (32-CharWidth);
157 // Otherwise, these are not valid escapes.
158 case '(': case '{': case '[': case '%':
159 // GCC accepts these as extensions. We warn about them as such though.
161 Diags->Report(Loc, diag::ext_nonstandard_escape)
162 << std::string()+(char)ResultChar;
168 if (isgraph(ResultChar))
169 Diags->Report(Loc, diag::ext_unknown_escape)
170 << std::string()+(char)ResultChar;
172 Diags->Report(Loc, diag::ext_unknown_escape)
173 << "x"+llvm::utohexstr(ResultChar);
180 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
181 /// return the UTF32.
182 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
183 const char *ThisTokEnd,
184 uint32_t &UcnVal, unsigned short &UcnLen,
185 FullSourceLoc Loc, DiagnosticsEngine *Diags,
186 const LangOptions &Features,
187 bool in_char_string_literal = false) {
188 if (!Features.CPlusPlus && !Features.C99 && Diags)
189 Diags->Report(Loc, diag::warn_ucn_not_valid_in_c89);
191 const char *UcnBegin = ThisTokBuf;
193 // Skip the '\u' char's.
196 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
198 Diags->Report(Loc, diag::err_ucn_escape_no_digits);
201 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
202 unsigned short UcnLenSave = UcnLen;
203 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
204 int CharVal = HexDigitValue(ThisTokBuf[0]);
205 if (CharVal == -1) break;
209 // If we didn't consume the proper number of digits, there is a problem.
213 Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
214 Loc.getManager(), Features);
215 Diags->Report(L, diag::err_ucn_escape_incomplete);
220 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
221 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
222 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
224 Diags->Report(Loc, diag::err_ucn_escape_invalid);
228 // C++11 allows UCNs that refer to control characters and basic source
229 // characters inside character and string literals
231 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
232 bool IsError = (!Features.CPlusPlus0x || !in_char_string_literal);
234 SourceLocation UcnBeginLoc =
235 Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
236 Loc.getManager(), Features);
237 char BasicSCSChar = UcnVal;
238 if (UcnVal >= 0x20 && UcnVal < 0x7f)
239 Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_escape_basic_scs :
240 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
241 << StringRef(&BasicSCSChar, 1);
243 Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_control_character :
244 diag::warn_cxx98_compat_literal_ucn_control_character);
253 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
254 /// which this UCN will occupy.
255 static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
256 const char *ThisTokEnd, unsigned CharByteWidth,
257 const LangOptions &Features, bool &HadError) {
258 // UTF-32: 4 bytes per escape.
259 if (CharByteWidth == 4)
263 unsigned short UcnLen = 0;
266 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
267 UcnLen, Loc, 0, Features, true)) {
272 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
273 if (CharByteWidth == 2)
274 return UcnVal <= 0xFFFF ? 2 : 4;
281 if (UcnVal < 0x10000)
286 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
287 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
288 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
289 /// we will likely rework our support for UCN's.
290 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
291 const char *ThisTokEnd,
292 char *&ResultBuf, bool &HadError,
293 FullSourceLoc Loc, unsigned CharByteWidth,
294 DiagnosticsEngine *Diags,
295 const LangOptions &Features) {
296 typedef uint32_t UTF32;
298 unsigned short UcnLen = 0;
299 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
300 Loc, Diags, Features, true)) {
305 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
306 "only character widths of 1, 2, or 4 bytes supported");
309 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
311 if (CharByteWidth == 4) {
312 // FIXME: Make the type of the result buffer correct instead of
313 // using reinterpret_cast.
314 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
320 if (CharByteWidth == 2) {
321 // FIXME: Make the type of the result buffer correct instead of
322 // using reinterpret_cast.
323 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
325 if (UcnVal <= (UTF32)0xFFFF) {
333 *ResultPtr = 0xD800 + (UcnVal >> 10);
334 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
339 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
341 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
342 // The conversion below was inspired by:
343 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
344 // First, we determine how many bytes the result will require.
345 typedef uint8_t UTF8;
347 unsigned short bytesToWrite = 0;
348 if (UcnVal < (UTF32)0x80)
350 else if (UcnVal < (UTF32)0x800)
352 else if (UcnVal < (UTF32)0x10000)
357 const unsigned byteMask = 0xBF;
358 const unsigned byteMark = 0x80;
360 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
361 // into the first byte, depending on how many bytes follow.
362 static const UTF8 firstByteMark[5] = {
363 0x00, 0x00, 0xC0, 0xE0, 0xF0
365 // Finally, we write the bytes into ResultBuf.
366 ResultBuf += bytesToWrite;
367 switch (bytesToWrite) { // note: everything falls through.
368 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
369 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
370 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
371 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
373 // Update the buffer.
374 ResultBuf += bytesToWrite;
378 /// integer-constant: [C99 6.4.4.1]
379 /// decimal-constant integer-suffix
380 /// octal-constant integer-suffix
381 /// hexadecimal-constant integer-suffix
382 /// user-defined-integer-literal: [C++11 lex.ext]
383 /// decimal-literal ud-suffix
384 /// octal-literal ud-suffix
385 /// hexadecimal-literal ud-suffix
386 /// decimal-constant:
388 /// decimal-constant digit
391 /// octal-constant octal-digit
392 /// hexadecimal-constant:
393 /// hexadecimal-prefix hexadecimal-digit
394 /// hexadecimal-constant hexadecimal-digit
395 /// hexadecimal-prefix: one of
398 /// unsigned-suffix [long-suffix]
399 /// unsigned-suffix [long-long-suffix]
400 /// long-suffix [unsigned-suffix]
401 /// long-long-suffix [unsigned-sufix]
403 /// 1 2 3 4 5 6 7 8 9
406 /// hexadecimal-digit:
407 /// 0 1 2 3 4 5 6 7 8 9
410 /// unsigned-suffix: one of
412 /// long-suffix: one of
414 /// long-long-suffix: one of
417 /// floating-constant: [C99 6.4.4.2]
418 /// TODO: add rules...
420 NumericLiteralParser::
421 NumericLiteralParser(const char *begin, const char *end,
422 SourceLocation TokLoc, Preprocessor &pp)
423 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
425 // This routine assumes that the range begin/end matches the regex for integer
426 // and FP constants (specifically, the 'pp-number' regex), and assumes that
427 // the byte at "*end" is both valid and not part of the regex. Because of
428 // this, it doesn't have to check for 'overscan' in various places.
429 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
430 "Lexer didn't maximally munch?");
432 s = DigitsBegin = begin;
433 saw_exponent = false;
435 saw_ud_suffix = false;
441 isMicrosoftInteger = false;
444 if (*s == '0') { // parse radix
445 ParseNumberStartingWithZero(TokLoc);
448 } else { // the first digit is non-zero
451 if (s == ThisTokEnd) {
453 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
454 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
455 diag::err_invalid_decimal_digit) << StringRef(s, 1);
458 } else if (*s == '.') {
463 if ((*s == 'e' || *s == 'E')) { // exponent
464 const char *Exponent = s;
467 if (*s == '+' || *s == '-') s++; // sign
468 const char *first_non_digit = SkipDigits(s);
469 if (first_non_digit != s) {
472 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
473 diag::err_exponent_has_no_digits);
482 // Parse the suffix. At this point we can classify whether we have an FP or
484 bool isFPConstant = isFloatingLiteral();
486 // Loop over all of the characters of the suffix. If we see something bad,
487 // we break out of the loop.
488 for (; s != ThisTokEnd; ++s) {
490 case 'f': // FP Suffix for "float"
492 if (!isFPConstant) break; // Error for integer constant.
493 if (isFloat || isLong) break; // FF, LF invalid.
495 continue; // Success.
498 if (isFPConstant) break; // Error for floating constant.
499 if (isUnsigned) break; // Cannot be repeated.
501 continue; // Success.
504 if (isLong || isLongLong) break; // Cannot be repeated.
505 if (isFloat) break; // LF invalid.
507 // Check for long long. The L's need to be adjacent and the same case.
508 if (s+1 != ThisTokEnd && s[1] == s[0]) {
509 if (isFPConstant) break; // long long invalid for floats.
511 ++s; // Eat both of them.
515 continue; // Success.
518 if (PP.getLangOpts().MicrosoftExt) {
519 if (isFPConstant || isLong || isLongLong) break;
521 // Allow i8, i16, i32, i64, and i128.
522 if (s + 1 != ThisTokEnd) {
526 isMicrosoftInteger = true;
529 if (s + 2 == ThisTokEnd) break;
531 s += 3; // i16 suffix
532 isMicrosoftInteger = true;
534 else if (s[2] == '2') {
535 if (s + 3 == ThisTokEnd) break;
537 s += 4; // i128 suffix
538 isMicrosoftInteger = true;
543 if (s + 2 == ThisTokEnd) break;
545 s += 3; // i32 suffix
547 isMicrosoftInteger = true;
551 if (s + 2 == ThisTokEnd) break;
553 s += 3; // i64 suffix
555 isMicrosoftInteger = true;
567 if (isImaginary) break; // Cannot be repeated.
568 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
569 diag::ext_imaginary_constant);
571 continue; // Success.
573 // If we reached here, there was an error or a ud-suffix.
577 if (s != ThisTokEnd) {
578 if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
579 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
580 // with an '_' are ill-formed.
581 saw_ud_suffix = true;
585 // Report an error if there are any.
586 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin-begin),
587 isFPConstant ? diag::err_invalid_suffix_float_constant :
588 diag::err_invalid_suffix_integer_constant)
589 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
595 /// ParseNumberStartingWithZero - This method is called when the first character
596 /// of the number is found to be a zero. This means it is either an octal
597 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
598 /// a floating point number (01239.123e4). Eat the prefix, determining the
600 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
601 assert(s[0] == '0' && "Invalid method call");
604 // Handle a hex number like 0x1234.
605 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
609 s = SkipHexDigits(s);
610 bool noSignificand = (s == DigitsBegin);
611 if (s == ThisTokEnd) {
613 } else if (*s == '.') {
616 const char *floatDigitsBegin = s;
617 s = SkipHexDigits(s);
618 noSignificand &= (floatDigitsBegin == s);
622 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), \
623 diag::err_hexconstant_requires_digits);
628 // A binary exponent can appear with or with a '.'. If dotted, the
629 // binary exponent is required.
630 if (*s == 'p' || *s == 'P') {
631 const char *Exponent = s;
634 if (*s == '+' || *s == '-') s++; // sign
635 const char *first_non_digit = SkipDigits(s);
636 if (first_non_digit == s) {
637 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
638 diag::err_exponent_has_no_digits);
644 if (!PP.getLangOpts().HexFloats)
645 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
646 } else if (saw_period) {
647 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
648 diag::err_hexconstant_requires_exponent);
654 // Handle simple binary numbers 0b01010
655 if (*s == 'b' || *s == 'B') {
656 // 0b101010 is a GCC extension.
657 PP.Diag(TokLoc, diag::ext_binary_literal);
661 s = SkipBinaryDigits(s);
662 if (s == ThisTokEnd) {
664 } else if (isxdigit(*s)) {
665 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
666 diag::err_invalid_binary_digit) << StringRef(s, 1);
669 // Other suffixes will be diagnosed by the caller.
673 // For now, the radix is set to 8. If we discover that we have a
674 // floating point constant, the radix will change to 10. Octal floating
675 // point constants are not permitted (only decimal and hexadecimal).
678 s = SkipOctalDigits(s);
680 return; // Done, simple octal number like 01234
682 // If we have some other non-octal digit that *is* a decimal digit, see if
683 // this is part of a floating point number like 094.123 or 09e1.
685 const char *EndDecimal = SkipDigits(s);
686 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
692 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
693 // the code is using an incorrect base.
694 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
695 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
696 diag::err_invalid_octal_digit) << StringRef(s, 1);
705 s = SkipDigits(s); // Skip suffix.
707 if (*s == 'e' || *s == 'E') { // exponent
708 const char *Exponent = s;
712 if (*s == '+' || *s == '-') s++; // sign
713 const char *first_non_digit = SkipDigits(s);
714 if (first_non_digit != s) {
717 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
718 diag::err_exponent_has_no_digits);
726 /// GetIntegerValue - Convert this numeric literal value to an APInt that
727 /// matches Val's input width. If there is an overflow, set Val to the low bits
728 /// of the result and return true. Otherwise, return false.
729 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
730 // Fast path: Compute a conservative bound on the maximum number of
731 // bits per digit in this radix. If we can't possibly overflow a
732 // uint64 based on that bound then do the simple conversion to
733 // integer. This avoids the expensive overflow checking below, and
734 // handles the common cases that matter (small decimal integers and
735 // hex/octal values which don't overflow).
736 unsigned MaxBitsPerDigit = 1;
737 while ((1U << MaxBitsPerDigit) < radix)
738 MaxBitsPerDigit += 1;
739 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
741 for (s = DigitsBegin; s != SuffixBegin; ++s)
742 N = N*radix + HexDigitValue(*s);
744 // This will truncate the value to Val's input width. Simply check
745 // for overflow by comparing.
747 return Val.getZExtValue() != N;
753 llvm::APInt RadixVal(Val.getBitWidth(), radix);
754 llvm::APInt CharVal(Val.getBitWidth(), 0);
755 llvm::APInt OldVal = Val;
757 bool OverflowOccurred = false;
758 while (s < SuffixBegin) {
759 unsigned C = HexDigitValue(*s++);
761 // If this letter is out of bound for this radix, reject it.
762 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
766 // Add the digit to the value in the appropriate radix. If adding in digits
767 // made the value smaller, then this overflowed.
770 // Multiply by radix, did overflow occur on the multiply?
772 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
774 // Add value, did overflow occur on the value?
775 // (a + b) ult b <=> overflow
777 OverflowOccurred |= Val.ult(CharVal);
779 return OverflowOccurred;
782 llvm::APFloat::opStatus
783 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
786 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
787 return Result.convertFromString(StringRef(ThisTokBegin, n),
788 APFloat::rmNearestTiesToEven);
793 /// user-defined-character-literal: [C++11 lex.ext]
794 /// character-literal ud-suffix
797 /// character-literal: [C++11 lex.ccon]
798 /// ' c-char-sequence '
799 /// u' c-char-sequence '
800 /// U' c-char-sequence '
801 /// L' c-char-sequence '
804 /// c-char-sequence c-char
806 /// any member of the source character set except the single-quote ',
807 /// backslash \, or new-line character
809 /// universal-character-name
811 /// simple-escape-sequence
812 /// octal-escape-sequence
813 /// hexadecimal-escape-sequence
814 /// simple-escape-sequence:
815 /// one of \' \" \? \\ \a \b \f \n \r \t \v
816 /// octal-escape-sequence:
818 /// \ octal-digit octal-digit
819 /// \ octal-digit octal-digit octal-digit
820 /// hexadecimal-escape-sequence:
821 /// \x hexadecimal-digit
822 /// hexadecimal-escape-sequence hexadecimal-digit
823 /// universal-character-name: [C++11 lex.charset]
825 /// \U hex-quad hex-quad
827 /// hex-digit hex-digit hex-digit hex-digit
830 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
831 SourceLocation Loc, Preprocessor &PP,
832 tok::TokenKind kind) {
833 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
838 const char *TokBegin = begin;
840 // Skip over wide character determinant.
841 if (Kind != tok::char_constant) {
845 // Skip over the entry quote.
846 assert(begin[0] == '\'' && "Invalid token lexed");
849 // Remove an optional ud-suffix.
850 if (end[-1] != '\'') {
851 const char *UDSuffixEnd = end;
854 } while (end[-1] != '\'');
855 UDSuffixBuf.assign(end, UDSuffixEnd);
856 UDSuffixOffset = end - TokBegin;
859 // Trim the ending quote.
860 assert(end != begin && "Invalid token lexed");
863 // FIXME: The "Value" is an uint64_t so we can handle char literals of
865 // FIXME: This extensively assumes that 'char' is 8-bits.
866 assert(PP.getTargetInfo().getCharWidth() == 8 &&
867 "Assumes char is 8 bits");
868 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
869 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
870 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
871 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
872 "Assumes sizeof(wchar) on target is <= 64");
874 SmallVector<uint32_t,4> codepoint_buffer;
875 codepoint_buffer.resize(end-begin);
876 uint32_t *buffer_begin = &codepoint_buffer.front();
877 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
879 // Unicode escapes representing characters that cannot be correctly
880 // represented in a single code unit are disallowed in character literals
881 // by this implementation.
882 uint32_t largest_character_for_kind;
883 if (tok::wide_char_constant == Kind) {
884 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
885 } else if (tok::utf16_char_constant == Kind) {
886 largest_character_for_kind = 0xFFFF;
887 } else if (tok::utf32_char_constant == Kind) {
888 largest_character_for_kind = 0x10FFFF;
890 largest_character_for_kind = 0x7Fu;
894 // Is this a span of non-escape characters?
895 if (begin[0] != '\\') {
896 char const *start = begin;
899 } while (begin != end && *begin != '\\');
901 char const *tmp_in_start = start;
902 uint32_t *tmp_out_start = buffer_begin;
903 ConversionResult res =
904 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
905 reinterpret_cast<UTF8 const *>(begin),
906 &buffer_begin,buffer_end,strictConversion);
907 if (res!=conversionOK) {
908 // If we see bad encoding for unprefixed character literals, warn and
909 // simply copy the byte values, for compatibility with gcc and
910 // older versions of clang.
911 bool NoErrorOnBadEncoding = isAscii();
912 unsigned Msg = diag::err_bad_character_encoding;
913 if (NoErrorOnBadEncoding)
914 Msg = diag::warn_bad_character_encoding;
916 if (NoErrorOnBadEncoding) {
917 start = tmp_in_start;
918 buffer_begin = tmp_out_start;
919 for ( ; start != begin; ++start, ++buffer_begin)
920 *buffer_begin = static_cast<uint8_t>(*start);
925 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
926 if (*tmp_out_start > largest_character_for_kind) {
928 PP.Diag(Loc, diag::err_character_too_large);
935 // Is this a Universal Character Name excape?
936 if (begin[1] == 'u' || begin[1] == 'U') {
937 unsigned short UcnLen = 0;
938 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
939 FullSourceLoc(Loc, PP.getSourceManager()),
940 &PP.getDiagnostics(), PP.getLangOpts(),
944 } else if (*buffer_begin > largest_character_for_kind) {
946 PP.Diag(Loc,diag::err_character_too_large);
952 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
954 ProcessCharEscape(begin, end, HadError,
955 FullSourceLoc(Loc,PP.getSourceManager()),
956 CharWidth, &PP.getDiagnostics());
957 *buffer_begin++ = result;
960 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
962 if (NumCharsSoFar > 1) {
964 PP.Diag(Loc, diag::warn_extraneous_char_constant);
965 else if (isAscii() && NumCharsSoFar == 4)
966 PP.Diag(Loc, diag::ext_four_char_character_literal);
968 PP.Diag(Loc, diag::ext_multichar_character_literal);
970 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
975 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
977 // Narrow character literals act as though their value is concatenated
978 // in this implementation, but warn on overflow.
979 bool multi_char_too_long = false;
980 if (isAscii() && isMultiChar()) {
982 for (size_t i=0;i<NumCharsSoFar;++i) {
983 // check for enough leading zeros to shift into
984 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
986 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
988 } else if (NumCharsSoFar > 0) {
989 // otherwise just take the last character
990 LitVal = buffer_begin[-1];
993 if (!HadError && multi_char_too_long) {
994 PP.Diag(Loc,diag::warn_char_constant_too_large);
997 // Transfer the value from APInt to uint64_t
998 Value = LitVal.getZExtValue();
1000 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1001 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1002 // character constants are not sign extended in the this implementation:
1003 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1004 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1005 PP.getLangOpts().CharIsSigned)
1006 Value = (signed char)Value;
1010 /// string-literal: [C++0x lex.string]
1011 /// encoding-prefix " [s-char-sequence] "
1012 /// encoding-prefix R raw-string
1013 /// encoding-prefix:
1018 /// s-char-sequence:
1020 /// s-char-sequence s-char
1022 /// any member of the source character set except the double-quote ",
1023 /// backslash \, or new-line character
1025 /// universal-character-name
1027 /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1028 /// r-char-sequence:
1030 /// r-char-sequence r-char
1032 /// any member of the source character set, except a right parenthesis )
1033 /// followed by the initial d-char-sequence (which may be empty)
1034 /// followed by a double quote ".
1035 /// d-char-sequence:
1037 /// d-char-sequence d-char
1039 /// any member of the basic source character set except:
1040 /// space, the left parenthesis (, the right parenthesis ),
1041 /// the backslash \, and the control characters representing horizontal
1042 /// tab, vertical tab, form feed, and newline.
1043 /// escape-sequence: [C++0x lex.ccon]
1044 /// simple-escape-sequence
1045 /// octal-escape-sequence
1046 /// hexadecimal-escape-sequence
1047 /// simple-escape-sequence:
1048 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1049 /// octal-escape-sequence:
1051 /// \ octal-digit octal-digit
1052 /// \ octal-digit octal-digit octal-digit
1053 /// hexadecimal-escape-sequence:
1054 /// \x hexadecimal-digit
1055 /// hexadecimal-escape-sequence hexadecimal-digit
1056 /// universal-character-name:
1058 /// \U hex-quad hex-quad
1060 /// hex-digit hex-digit hex-digit hex-digit
1063 StringLiteralParser::
1064 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1065 Preprocessor &PP, bool Complain)
1066 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1067 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1068 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1069 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1070 init(StringToks, NumStringToks);
1073 void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1074 // The literal token may have come from an invalid source location (e.g. due
1075 // to a PCH error), in which case the token length will be 0.
1076 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1077 return DiagnoseLexingError(SourceLocation());
1079 // Scan all of the string portions, remember the max individual token length,
1080 // computing a bound on the concatenated string length, and see whether any
1081 // piece is a wide-string. If any of the string portions is a wide-string
1082 // literal, the result is a wide-string literal [C99 6.4.5p4].
1083 assert(NumStringToks && "expected at least one token");
1084 MaxTokenLength = StringToks[0].getLength();
1085 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1086 SizeBound = StringToks[0].getLength()-2; // -2 for "".
1087 Kind = StringToks[0].getKind();
1091 // Implement Translation Phase #6: concatenation of string literals
1092 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1093 for (unsigned i = 1; i != NumStringToks; ++i) {
1094 if (StringToks[i].getLength() < 2)
1095 return DiagnoseLexingError(StringToks[i].getLocation());
1097 // The string could be shorter than this if it needs cleaning, but this is a
1098 // reasonable bound, which is all we need.
1099 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1100 SizeBound += StringToks[i].getLength()-2; // -2 for "".
1102 // Remember maximum string piece length.
1103 if (StringToks[i].getLength() > MaxTokenLength)
1104 MaxTokenLength = StringToks[i].getLength();
1106 // Remember if we see any wide or utf-8/16/32 strings.
1107 // Also check for illegal concatenations.
1108 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1110 Kind = StringToks[i].getKind();
1113 Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
1114 diag::err_unsupported_string_concat);
1120 // Include space for the null terminator.
1123 // TODO: K&R warning: "traditional C rejects string constant concatenation"
1125 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1126 CharByteWidth = getCharWidth(Kind, Target);
1127 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1130 // The output buffer size needs to be large enough to hold wide characters.
1131 // This is a worst-case assumption which basically corresponds to L"" "long".
1132 SizeBound *= CharByteWidth;
1134 // Size the temporary buffer to hold the result string data.
1135 ResultBuf.resize(SizeBound);
1137 // Likewise, but for each string piece.
1138 SmallString<512> TokenBuf;
1139 TokenBuf.resize(MaxTokenLength);
1141 // Loop over all the strings, getting their spelling, and expanding them to
1142 // wide strings as appropriate.
1143 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
1147 SourceLocation UDSuffixTokLoc;
1149 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1150 const char *ThisTokBuf = &TokenBuf[0];
1151 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1152 // that ThisTokBuf points to a buffer that is big enough for the whole token
1153 // and 'spelled' tokens can only shrink.
1154 bool StringInvalid = false;
1155 unsigned ThisTokLen =
1156 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1159 return DiagnoseLexingError(StringToks[i].getLocation());
1161 const char *ThisTokBegin = ThisTokBuf;
1162 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1164 // Remove an optional ud-suffix.
1165 if (ThisTokEnd[-1] != '"') {
1166 const char *UDSuffixEnd = ThisTokEnd;
1169 } while (ThisTokEnd[-1] != '"');
1171 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1173 if (UDSuffixBuf.empty()) {
1174 UDSuffixBuf.assign(UDSuffix);
1176 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1177 UDSuffixTokLoc = StringToks[i].getLocation();
1178 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1179 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1180 // result of a concatenation involving at least one user-defined-string-
1181 // literal, all the participating user-defined-string-literals shall
1182 // have the same ud-suffix.
1184 SourceLocation TokLoc = StringToks[i].getLocation();
1185 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1186 << UDSuffixBuf << UDSuffix
1187 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1188 << SourceRange(TokLoc, TokLoc);
1194 // Strip the end quote.
1197 // TODO: Input character set mapping support.
1199 // Skip marker for wide or unicode strings.
1200 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1202 // Skip 8 of u8 marker for utf8 strings.
1203 if (ThisTokBuf[0] == '8')
1207 // Check for raw string
1208 if (ThisTokBuf[0] == 'R') {
1209 ThisTokBuf += 2; // skip R"
1211 const char *Prefix = ThisTokBuf;
1212 while (ThisTokBuf[0] != '(')
1214 ++ThisTokBuf; // skip '('
1216 // Remove same number of characters from the end
1217 ThisTokEnd -= ThisTokBuf - Prefix;
1218 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1220 // Copy the string over
1221 if (CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1222 if (DiagnoseBadString(StringToks[i]))
1225 if (ThisTokBuf[0] != '"') {
1226 // The file may have come from PCH and then changed after loading the
1227 // PCH; Fail gracefully.
1228 return DiagnoseLexingError(StringToks[i].getLocation());
1230 ++ThisTokBuf; // skip "
1232 // Check if this is a pascal string
1233 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1234 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1236 // If the \p sequence is found in the first token, we have a pascal string
1237 // Otherwise, if we already have a pascal string, ignore the first \p
1245 while (ThisTokBuf != ThisTokEnd) {
1246 // Is this a span of non-escape characters?
1247 if (ThisTokBuf[0] != '\\') {
1248 const char *InStart = ThisTokBuf;
1251 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1253 // Copy the character span over.
1254 if (CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart)))
1255 if (DiagnoseBadString(StringToks[i]))
1259 // Is this a Universal Character Name escape?
1260 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1261 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1262 ResultPtr, hadError,
1263 FullSourceLoc(StringToks[i].getLocation(), SM),
1264 CharByteWidth, Diags, Features);
1267 // Otherwise, this is a non-UCN escape character. Process it.
1268 unsigned ResultChar =
1269 ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
1270 FullSourceLoc(StringToks[i].getLocation(), SM),
1271 CharByteWidth*8, Diags);
1273 if (CharByteWidth == 4) {
1274 // FIXME: Make the type of the result buffer correct instead of
1275 // using reinterpret_cast.
1276 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1277 *ResultWidePtr = ResultChar;
1279 } else if (CharByteWidth == 2) {
1280 // FIXME: Make the type of the result buffer correct instead of
1281 // using reinterpret_cast.
1282 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1283 *ResultWidePtr = ResultChar & 0xFFFF;
1286 assert(CharByteWidth == 1 && "Unexpected char width");
1287 *ResultPtr++ = ResultChar & 0xFF;
1294 if (CharByteWidth == 4) {
1295 // FIXME: Make the type of the result buffer correct instead of
1296 // using reinterpret_cast.
1297 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1298 ResultWidePtr[0] = GetNumStringChars() - 1;
1299 } else if (CharByteWidth == 2) {
1300 // FIXME: Make the type of the result buffer correct instead of
1301 // using reinterpret_cast.
1302 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1303 ResultWidePtr[0] = GetNumStringChars() - 1;
1305 assert(CharByteWidth == 1 && "Unexpected char width");
1306 ResultBuf[0] = GetNumStringChars() - 1;
1309 // Verify that pascal strings aren't too large.
1310 if (GetStringLength() > 256) {
1312 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1313 diag::err_pascal_string_too_long)
1314 << SourceRange(StringToks[0].getLocation(),
1315 StringToks[NumStringToks-1].getLocation());
1320 // Complain if this string literal has too many characters.
1321 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1323 if (GetNumStringChars() > MaxChars)
1324 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1325 diag::ext_string_too_long)
1326 << GetNumStringChars() << MaxChars
1327 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1328 << SourceRange(StringToks[0].getLocation(),
1329 StringToks[NumStringToks-1].getLocation());
1333 /// copyStringFragment - This function copies from Start to End into ResultPtr.
1334 /// Performs widening for multi-byte characters.
1335 bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
1336 return !ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr);
1339 bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
1340 // If we see bad encoding for unprefixed string literals, warn and
1341 // simply copy the byte values, for compatibility with gcc and older
1342 // versions of clang.
1343 bool NoErrorOnBadEncoding = isAscii();
1344 unsigned Msg = NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
1345 diag::err_bad_string_encoding;
1347 Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
1348 return !NoErrorOnBadEncoding;
1351 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1354 Diags->Report(Loc, diag::err_lexing_string);
1357 /// getOffsetOfStringByte - This function returns the offset of the
1358 /// specified byte of the string data represented by Token. This handles
1359 /// advancing over escape sequences in the string.
1360 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1361 unsigned ByteNo) const {
1362 // Get the spelling of the token.
1363 SmallString<32> SpellingBuffer;
1364 SpellingBuffer.resize(Tok.getLength());
1366 bool StringInvalid = false;
1367 const char *SpellingPtr = &SpellingBuffer[0];
1368 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1373 const char *SpellingStart = SpellingPtr;
1374 const char *SpellingEnd = SpellingPtr+TokLen;
1376 // Handle UTF-8 strings just like narrow strings.
1377 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1380 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1381 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1383 // For raw string literals, this is easy.
1384 if (SpellingPtr[0] == 'R') {
1385 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1388 while (*SpellingPtr != '(') {
1390 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1394 return SpellingPtr - SpellingStart + ByteNo;
1397 // Skip over the leading quote
1398 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1401 // Skip over bytes until we find the offset we're looking for.
1403 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1405 // Step over non-escapes simply.
1406 if (*SpellingPtr != '\\') {
1412 // Otherwise, this is an escape character. Advance over it.
1413 bool HadError = false;
1414 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1415 const char *EscapePtr = SpellingPtr;
1416 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1417 1, Features, HadError);
1419 // ByteNo is somewhere within the escape sequence.
1420 SpellingPtr = EscapePtr;
1425 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
1426 FullSourceLoc(Tok.getLocation(), SM),
1427 CharByteWidth*8, Diags);
1430 assert(!HadError && "This method isn't valid on erroneous strings");
1433 return SpellingPtr-SpellingStart;