1193326Sed//===--- LiteralSupport.cpp - Code to parse and process literals ----------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9193326Sed// 10193326Sed// This file implements the NumericLiteralParser, CharLiteralParser, and 11193326Sed// StringLiteralParser interfaces. 12193326Sed// 13193326Sed//===----------------------------------------------------------------------===// 14193326Sed 15193326Sed#include "clang/Lex/LiteralSupport.h" 16249423Sdim#include "clang/Basic/CharInfo.h" 17249423Sdim#include "clang/Basic/TargetInfo.h" 18249423Sdim#include "clang/Lex/LexDiagnostic.h" 19193326Sed#include "clang/Lex/Preprocessor.h" 20193326Sed#include "llvm/ADT/StringExtras.h" 21249423Sdim#include "llvm/Support/ConvertUTF.h" 22226633Sdim#include "llvm/Support/ErrorHandling.h" 23249423Sdim 24193326Sedusing namespace clang; 25193326Sed 26226633Sdimstatic unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) { 27226633Sdim switch (kind) { 28226633Sdim default: llvm_unreachable("Unknown token type!"); 29226633Sdim case tok::char_constant: 30226633Sdim case tok::string_literal: 31226633Sdim case tok::utf8_string_literal: 32226633Sdim return Target.getCharWidth(); 33226633Sdim case tok::wide_char_constant: 34226633Sdim case tok::wide_string_literal: 35226633Sdim return Target.getWCharWidth(); 36226633Sdim case tok::utf16_char_constant: 37226633Sdim case tok::utf16_string_literal: 38226633Sdim return Target.getChar16Width(); 39226633Sdim case tok::utf32_char_constant: 40226633Sdim case tok::utf32_string_literal: 41226633Sdim return Target.getChar32Width(); 42226633Sdim } 43226633Sdim} 44226633Sdim 45243830Sdimstatic CharSourceRange MakeCharSourceRange(const LangOptions &Features, 46243830Sdim FullSourceLoc TokLoc, 47243830Sdim const char *TokBegin, 48243830Sdim const char *TokRangeBegin, 49243830Sdim const char *TokRangeEnd) { 50243830Sdim SourceLocation Begin = 51243830Sdim Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin, 52243830Sdim TokLoc.getManager(), Features); 53243830Sdim SourceLocation End = 54243830Sdim Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin, 55243830Sdim TokLoc.getManager(), Features); 56243830Sdim return CharSourceRange::getCharRange(Begin, End); 57243830Sdim} 58243830Sdim 59243830Sdim/// \brief Produce a diagnostic highlighting some portion of a literal. 60243830Sdim/// 61243830Sdim/// Emits the diagnostic \p DiagID, highlighting the range of characters from 62243830Sdim/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be 63243830Sdim/// a substring of a spelling buffer for the token beginning at \p TokBegin. 64243830Sdimstatic DiagnosticBuilder Diag(DiagnosticsEngine *Diags, 65243830Sdim const LangOptions &Features, FullSourceLoc TokLoc, 66243830Sdim const char *TokBegin, const char *TokRangeBegin, 67243830Sdim const char *TokRangeEnd, unsigned DiagID) { 68243830Sdim SourceLocation Begin = 69243830Sdim Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin, 70243830Sdim TokLoc.getManager(), Features); 71243830Sdim return Diags->Report(Begin, DiagID) << 72243830Sdim MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd); 73243830Sdim} 74243830Sdim 75193326Sed/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in 76193326Sed/// either a character or a string literal. 77243830Sdimstatic unsigned ProcessCharEscape(const char *ThisTokBegin, 78243830Sdim const char *&ThisTokBuf, 79193326Sed const char *ThisTokEnd, bool &HadError, 80226633Sdim FullSourceLoc Loc, unsigned CharWidth, 81243830Sdim DiagnosticsEngine *Diags, 82243830Sdim const LangOptions &Features) { 83243830Sdim const char *EscapeBegin = ThisTokBuf; 84243830Sdim 85193326Sed // Skip the '\' char. 86193326Sed ++ThisTokBuf; 87193326Sed 88193326Sed // We know that this character can't be off the end of the buffer, because 89193326Sed // that would have been \", which would not have been the end of string. 90193326Sed unsigned ResultChar = *ThisTokBuf++; 91193326Sed switch (ResultChar) { 92193326Sed // These map to themselves. 93193326Sed case '\\': case '\'': case '"': case '?': break; 94198092Srdivacky 95193326Sed // These have fixed mappings. 96193326Sed case 'a': 97193326Sed // TODO: K&R: the meaning of '\\a' is different in traditional C 98193326Sed ResultChar = 7; 99193326Sed break; 100193326Sed case 'b': 101193326Sed ResultChar = 8; 102193326Sed break; 103193326Sed case 'e': 104218893Sdim if (Diags) 105243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 106243830Sdim diag::ext_nonstandard_escape) << "e"; 107193326Sed ResultChar = 27; 108193326Sed break; 109194179Sed case 'E': 110218893Sdim if (Diags) 111243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 112243830Sdim diag::ext_nonstandard_escape) << "E"; 113194179Sed ResultChar = 27; 114194179Sed break; 115193326Sed case 'f': 116193326Sed ResultChar = 12; 117193326Sed break; 118193326Sed case 'n': 119193326Sed ResultChar = 10; 120193326Sed break; 121193326Sed case 'r': 122193326Sed ResultChar = 13; 123193326Sed break; 124193326Sed case 't': 125193326Sed ResultChar = 9; 126193326Sed break; 127193326Sed case 'v': 128193326Sed ResultChar = 11; 129193326Sed break; 130193326Sed case 'x': { // Hex escape. 131193326Sed ResultChar = 0; 132249423Sdim if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) { 133218893Sdim if (Diags) 134243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 135249423Sdim diag::err_hex_escape_no_digits) << "x"; 136193326Sed HadError = 1; 137193326Sed break; 138193326Sed } 139198092Srdivacky 140193326Sed // Hex escapes are a maximal series of hex digits. 141193326Sed bool Overflow = false; 142193326Sed for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) { 143249423Sdim int CharVal = llvm::hexDigitValue(ThisTokBuf[0]); 144193326Sed if (CharVal == -1) break; 145193326Sed // About to shift out a digit? 146193326Sed Overflow |= (ResultChar & 0xF0000000) ? true : false; 147193326Sed ResultChar <<= 4; 148193326Sed ResultChar |= CharVal; 149193326Sed } 150193326Sed 151193326Sed // See if any bits will be truncated when evaluated as a character. 152193326Sed if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { 153193326Sed Overflow = true; 154193326Sed ResultChar &= ~0U >> (32-CharWidth); 155193326Sed } 156198092Srdivacky 157193326Sed // Check for overflow. 158218893Sdim if (Overflow && Diags) // Too many digits to fit in 159243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 160263508Sdim diag::err_hex_escape_too_large); 161193326Sed break; 162193326Sed } 163193326Sed case '0': case '1': case '2': case '3': 164193326Sed case '4': case '5': case '6': case '7': { 165193326Sed // Octal escapes. 166193326Sed --ThisTokBuf; 167193326Sed ResultChar = 0; 168193326Sed 169193326Sed // Octal escapes are a series of octal digits with maximum length 3. 170193326Sed // "\0123" is a two digit sequence equal to "\012" "3". 171193326Sed unsigned NumDigits = 0; 172193326Sed do { 173193326Sed ResultChar <<= 3; 174193326Sed ResultChar |= *ThisTokBuf++ - '0'; 175193326Sed ++NumDigits; 176193326Sed } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 && 177193326Sed ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7'); 178198092Srdivacky 179193326Sed // Check for overflow. Reject '\777', but not L'\777'. 180193326Sed if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { 181218893Sdim if (Diags) 182243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 183263508Sdim diag::err_octal_escape_too_large); 184193326Sed ResultChar &= ~0U >> (32-CharWidth); 185193326Sed } 186193326Sed break; 187193326Sed } 188198092Srdivacky 189193326Sed // Otherwise, these are not valid escapes. 190193326Sed case '(': case '{': case '[': case '%': 191193326Sed // GCC accepts these as extensions. We warn about them as such though. 192218893Sdim if (Diags) 193243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 194243830Sdim diag::ext_nonstandard_escape) 195243830Sdim << std::string(1, ResultChar); 196193326Sed break; 197193326Sed default: 198218893Sdim if (Diags == 0) 199208600Srdivacky break; 200243830Sdim 201249423Sdim if (isPrintable(ResultChar)) 202243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 203243830Sdim diag::ext_unknown_escape) 204243830Sdim << std::string(1, ResultChar); 205193326Sed else 206243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, 207243830Sdim diag::ext_unknown_escape) 208243830Sdim << "x" + llvm::utohexstr(ResultChar); 209193326Sed break; 210193326Sed } 211198092Srdivacky 212193326Sed return ResultChar; 213193326Sed} 214193326Sed 215193326Sed/// ProcessUCNEscape - Read the Universal Character Name, check constraints and 216218893Sdim/// return the UTF32. 217234353Sdimstatic bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, 218234353Sdim const char *ThisTokEnd, 219218893Sdim uint32_t &UcnVal, unsigned short &UcnLen, 220226633Sdim FullSourceLoc Loc, DiagnosticsEngine *Diags, 221234353Sdim const LangOptions &Features, 222234353Sdim bool in_char_string_literal = false) { 223234353Sdim const char *UcnBegin = ThisTokBuf; 224198092Srdivacky 225193326Sed // Skip the '\u' char's. 226193326Sed ThisTokBuf += 2; 227193326Sed 228249423Sdim if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) { 229218893Sdim if (Diags) 230243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, 231249423Sdim diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1); 232218893Sdim return false; 233193326Sed } 234218893Sdim UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8); 235212904Sdim unsigned short UcnLenSave = UcnLen; 236218893Sdim for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) { 237249423Sdim int CharVal = llvm::hexDigitValue(ThisTokBuf[0]); 238193326Sed if (CharVal == -1) break; 239193326Sed UcnVal <<= 4; 240193326Sed UcnVal |= CharVal; 241193326Sed } 242193326Sed // If we didn't consume the proper number of digits, there is a problem. 243218893Sdim if (UcnLenSave) { 244243830Sdim if (Diags) 245243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, 246243830Sdim diag::err_ucn_escape_incomplete); 247218893Sdim return false; 248193326Sed } 249234353Sdim 250234353Sdim // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2] 251234353Sdim if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints 252234353Sdim UcnVal > 0x10FFFF) { // maximum legal UTF32 value 253218893Sdim if (Diags) 254243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, 255243830Sdim diag::err_ucn_escape_invalid); 256218893Sdim return false; 257218893Sdim } 258234353Sdim 259234353Sdim // C++11 allows UCNs that refer to control characters and basic source 260234353Sdim // characters inside character and string literals 261234353Sdim if (UcnVal < 0xa0 && 262234353Sdim (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, ` 263249423Sdim bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal); 264234353Sdim if (Diags) { 265234353Sdim char BasicSCSChar = UcnVal; 266234353Sdim if (UcnVal >= 0x20 && UcnVal < 0x7f) 267243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, 268243830Sdim IsError ? diag::err_ucn_escape_basic_scs : 269243830Sdim diag::warn_cxx98_compat_literal_ucn_escape_basic_scs) 270243830Sdim << StringRef(&BasicSCSChar, 1); 271234353Sdim else 272243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, 273243830Sdim IsError ? diag::err_ucn_control_character : 274243830Sdim diag::warn_cxx98_compat_literal_ucn_control_character); 275234353Sdim } 276234353Sdim if (IsError) 277234353Sdim return false; 278234353Sdim } 279234353Sdim 280243830Sdim if (!Features.CPlusPlus && !Features.C99 && Diags) 281243830Sdim Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, 282249423Sdim diag::warn_ucn_not_valid_in_c89_literal); 283243830Sdim 284218893Sdim return true; 285218893Sdim} 286218893Sdim 287239462Sdim/// MeasureUCNEscape - Determine the number of bytes within the resulting string 288239462Sdim/// which this UCN will occupy. 289239462Sdimstatic int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, 290239462Sdim const char *ThisTokEnd, unsigned CharByteWidth, 291239462Sdim const LangOptions &Features, bool &HadError) { 292239462Sdim // UTF-32: 4 bytes per escape. 293239462Sdim if (CharByteWidth == 4) 294239462Sdim return 4; 295239462Sdim 296239462Sdim uint32_t UcnVal = 0; 297239462Sdim unsigned short UcnLen = 0; 298239462Sdim FullSourceLoc Loc; 299239462Sdim 300239462Sdim if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, 301239462Sdim UcnLen, Loc, 0, Features, true)) { 302239462Sdim HadError = true; 303239462Sdim return 0; 304239462Sdim } 305239462Sdim 306239462Sdim // UTF-16: 2 bytes for BMP, 4 bytes otherwise. 307239462Sdim if (CharByteWidth == 2) 308239462Sdim return UcnVal <= 0xFFFF ? 2 : 4; 309239462Sdim 310239462Sdim // UTF-8. 311239462Sdim if (UcnVal < 0x80) 312239462Sdim return 1; 313239462Sdim if (UcnVal < 0x800) 314239462Sdim return 2; 315239462Sdim if (UcnVal < 0x10000) 316239462Sdim return 3; 317239462Sdim return 4; 318239462Sdim} 319239462Sdim 320218893Sdim/// EncodeUCNEscape - Read the Universal Character Name, check constraints and 321218893Sdim/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of 322218893Sdim/// StringLiteralParser. When we decide to implement UCN's for identifiers, 323218893Sdim/// we will likely rework our support for UCN's. 324234353Sdimstatic void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, 325234353Sdim const char *ThisTokEnd, 326218893Sdim char *&ResultBuf, bool &HadError, 327226633Sdim FullSourceLoc Loc, unsigned CharByteWidth, 328226633Sdim DiagnosticsEngine *Diags, 329218893Sdim const LangOptions &Features) { 330218893Sdim typedef uint32_t UTF32; 331218893Sdim UTF32 UcnVal = 0; 332218893Sdim unsigned short UcnLen = 0; 333234353Sdim if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, 334234353Sdim Loc, Diags, Features, true)) { 335239462Sdim HadError = true; 336193326Sed return; 337193326Sed } 338218893Sdim 339263508Sdim assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && 340226633Sdim "only character widths of 1, 2, or 4 bytes supported"); 341218893Sdim 342226633Sdim (void)UcnLen; 343226633Sdim assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported"); 344218893Sdim 345226633Sdim if (CharByteWidth == 4) { 346234353Sdim // FIXME: Make the type of the result buffer correct instead of 347234353Sdim // using reinterpret_cast. 348234353Sdim UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf); 349234353Sdim *ResultPtr = UcnVal; 350234353Sdim ResultBuf += 4; 351226633Sdim return; 352226633Sdim } 353226633Sdim 354226633Sdim if (CharByteWidth == 2) { 355234353Sdim // FIXME: Make the type of the result buffer correct instead of 356234353Sdim // using reinterpret_cast. 357234353Sdim UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf); 358234353Sdim 359239462Sdim if (UcnVal <= (UTF32)0xFFFF) { 360234353Sdim *ResultPtr = UcnVal; 361234353Sdim ResultBuf += 2; 362218893Sdim return; 363218893Sdim } 364218893Sdim 365234353Sdim // Convert to UTF16. 366218893Sdim UcnVal -= 0x10000; 367234353Sdim *ResultPtr = 0xD800 + (UcnVal >> 10); 368234353Sdim *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF); 369234353Sdim ResultBuf += 4; 370212904Sdim return; 371212904Sdim } 372226633Sdim 373226633Sdim assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters"); 374226633Sdim 375193326Sed // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8. 376193326Sed // The conversion below was inspired by: 377193326Sed // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c 378198092Srdivacky // First, we determine how many bytes the result will require. 379193326Sed typedef uint8_t UTF8; 380193326Sed 381193326Sed unsigned short bytesToWrite = 0; 382193326Sed if (UcnVal < (UTF32)0x80) 383193326Sed bytesToWrite = 1; 384193326Sed else if (UcnVal < (UTF32)0x800) 385193326Sed bytesToWrite = 2; 386193326Sed else if (UcnVal < (UTF32)0x10000) 387193326Sed bytesToWrite = 3; 388193326Sed else 389193326Sed bytesToWrite = 4; 390198092Srdivacky 391193326Sed const unsigned byteMask = 0xBF; 392193326Sed const unsigned byteMark = 0x80; 393198092Srdivacky 394193326Sed // Once the bits are split out into bytes of UTF8, this is a mask OR-ed 395193326Sed // into the first byte, depending on how many bytes follow. 396198092Srdivacky static const UTF8 firstByteMark[5] = { 397193326Sed 0x00, 0x00, 0xC0, 0xE0, 0xF0 398193326Sed }; 399193326Sed // Finally, we write the bytes into ResultBuf. 400193326Sed ResultBuf += bytesToWrite; 401193326Sed switch (bytesToWrite) { // note: everything falls through. 402243830Sdim case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; 403243830Sdim case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; 404243830Sdim case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; 405243830Sdim case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]); 406193326Sed } 407193326Sed // Update the buffer. 408193326Sed ResultBuf += bytesToWrite; 409193326Sed} 410193326Sed 411193326Sed 412193326Sed/// integer-constant: [C99 6.4.4.1] 413193326Sed/// decimal-constant integer-suffix 414193326Sed/// octal-constant integer-suffix 415193326Sed/// hexadecimal-constant integer-suffix 416263508Sdim/// binary-literal integer-suffix [GNU, C++1y] 417234353Sdim/// user-defined-integer-literal: [C++11 lex.ext] 418234353Sdim/// decimal-literal ud-suffix 419234353Sdim/// octal-literal ud-suffix 420234353Sdim/// hexadecimal-literal ud-suffix 421263508Sdim/// binary-literal ud-suffix [GNU, C++1y] 422198092Srdivacky/// decimal-constant: 423193326Sed/// nonzero-digit 424193326Sed/// decimal-constant digit 425198092Srdivacky/// octal-constant: 426193326Sed/// 0 427193326Sed/// octal-constant octal-digit 428198092Srdivacky/// hexadecimal-constant: 429193326Sed/// hexadecimal-prefix hexadecimal-digit 430193326Sed/// hexadecimal-constant hexadecimal-digit 431193326Sed/// hexadecimal-prefix: one of 432193326Sed/// 0x 0X 433263508Sdim/// binary-literal: 434263508Sdim/// 0b binary-digit 435263508Sdim/// 0B binary-digit 436263508Sdim/// binary-literal binary-digit 437193326Sed/// integer-suffix: 438193326Sed/// unsigned-suffix [long-suffix] 439193326Sed/// unsigned-suffix [long-long-suffix] 440193326Sed/// long-suffix [unsigned-suffix] 441193326Sed/// long-long-suffix [unsigned-sufix] 442193326Sed/// nonzero-digit: 443193326Sed/// 1 2 3 4 5 6 7 8 9 444193326Sed/// octal-digit: 445193326Sed/// 0 1 2 3 4 5 6 7 446193326Sed/// hexadecimal-digit: 447193326Sed/// 0 1 2 3 4 5 6 7 8 9 448193326Sed/// a b c d e f 449193326Sed/// A B C D E F 450263508Sdim/// binary-digit: 451263508Sdim/// 0 452263508Sdim/// 1 453193326Sed/// unsigned-suffix: one of 454193326Sed/// u U 455193326Sed/// long-suffix: one of 456193326Sed/// l L 457198092Srdivacky/// long-long-suffix: one of 458193326Sed/// ll LL 459193326Sed/// 460193326Sed/// floating-constant: [C99 6.4.4.2] 461193326Sed/// TODO: add rules... 462193326Sed/// 463243830SdimNumericLiteralParser::NumericLiteralParser(StringRef TokSpelling, 464243830Sdim SourceLocation TokLoc, 465243830Sdim Preprocessor &PP) 466243830Sdim : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) { 467198092Srdivacky 468193326Sed // This routine assumes that the range begin/end matches the regex for integer 469193326Sed // and FP constants (specifically, the 'pp-number' regex), and assumes that 470193326Sed // the byte at "*end" is both valid and not part of the regex. Because of 471193326Sed // this, it doesn't have to check for 'overscan' in various places. 472249423Sdim assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?"); 473198092Srdivacky 474243830Sdim s = DigitsBegin = ThisTokBegin; 475193326Sed saw_exponent = false; 476193326Sed saw_period = false; 477234353Sdim saw_ud_suffix = false; 478193326Sed isLong = false; 479193326Sed isUnsigned = false; 480193326Sed isLongLong = false; 481193326Sed isFloat = false; 482193326Sed isImaginary = false; 483198092Srdivacky isMicrosoftInteger = false; 484193326Sed hadError = false; 485198092Srdivacky 486193326Sed if (*s == '0') { // parse radix 487193326Sed ParseNumberStartingWithZero(TokLoc); 488193326Sed if (hadError) 489193326Sed return; 490193326Sed } else { // the first digit is non-zero 491193326Sed radix = 10; 492193326Sed s = SkipDigits(s); 493193326Sed if (s == ThisTokEnd) { 494193326Sed // Done. 495249423Sdim } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) { 496243830Sdim PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), 497226633Sdim diag::err_invalid_decimal_digit) << StringRef(s, 1); 498193326Sed hadError = true; 499193326Sed return; 500193326Sed } else if (*s == '.') { 501263508Sdim checkSeparator(TokLoc, s, CSK_AfterDigits); 502193326Sed s++; 503193326Sed saw_period = true; 504263508Sdim checkSeparator(TokLoc, s, CSK_BeforeDigits); 505193326Sed s = SkipDigits(s); 506198092Srdivacky } 507193326Sed if ((*s == 'e' || *s == 'E')) { // exponent 508263508Sdim checkSeparator(TokLoc, s, CSK_AfterDigits); 509193326Sed const char *Exponent = s; 510193326Sed s++; 511193326Sed saw_exponent = true; 512193326Sed if (*s == '+' || *s == '-') s++; // sign 513263508Sdim checkSeparator(TokLoc, s, CSK_BeforeDigits); 514193326Sed const char *first_non_digit = SkipDigits(s); 515193326Sed if (first_non_digit != s) { 516193326Sed s = first_non_digit; 517193326Sed } else { 518243830Sdim PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin), 519193326Sed diag::err_exponent_has_no_digits); 520193326Sed hadError = true; 521193326Sed return; 522193326Sed } 523193326Sed } 524193326Sed } 525193326Sed 526193326Sed SuffixBegin = s; 527263508Sdim checkSeparator(TokLoc, s, CSK_AfterDigits); 528198092Srdivacky 529193326Sed // Parse the suffix. At this point we can classify whether we have an FP or 530193326Sed // integer constant. 531193326Sed bool isFPConstant = isFloatingLiteral(); 532263508Sdim const char *ImaginarySuffixLoc = 0; 533198092Srdivacky 534193326Sed // Loop over all of the characters of the suffix. If we see something bad, 535193326Sed // we break out of the loop. 536193326Sed for (; s != ThisTokEnd; ++s) { 537193326Sed switch (*s) { 538193326Sed case 'f': // FP Suffix for "float" 539193326Sed case 'F': 540193326Sed if (!isFPConstant) break; // Error for integer constant. 541193326Sed if (isFloat || isLong) break; // FF, LF invalid. 542193326Sed isFloat = true; 543193326Sed continue; // Success. 544193326Sed case 'u': 545193326Sed case 'U': 546193326Sed if (isFPConstant) break; // Error for floating constant. 547193326Sed if (isUnsigned) break; // Cannot be repeated. 548193326Sed isUnsigned = true; 549193326Sed continue; // Success. 550193326Sed case 'l': 551193326Sed case 'L': 552193326Sed if (isLong || isLongLong) break; // Cannot be repeated. 553193326Sed if (isFloat) break; // LF invalid. 554198092Srdivacky 555193326Sed // Check for long long. The L's need to be adjacent and the same case. 556193326Sed if (s+1 != ThisTokEnd && s[1] == s[0]) { 557193326Sed if (isFPConstant) break; // long long invalid for floats. 558193326Sed isLongLong = true; 559193326Sed ++s; // Eat both of them. 560193326Sed } else { 561193326Sed isLong = true; 562193326Sed } 563193326Sed continue; // Success. 564193326Sed case 'i': 565218893Sdim case 'I': 566234353Sdim if (PP.getLangOpts().MicrosoftExt) { 567202879Srdivacky if (isFPConstant || isLong || isLongLong) break; 568199990Srdivacky 569193326Sed // Allow i8, i16, i32, i64, and i128. 570198092Srdivacky if (s + 1 != ThisTokEnd) { 571198092Srdivacky switch (s[1]) { 572198092Srdivacky case '8': 573198092Srdivacky s += 2; // i8 suffix 574198092Srdivacky isMicrosoftInteger = true; 575199990Srdivacky break; 576198092Srdivacky case '1': 577199990Srdivacky if (s + 2 == ThisTokEnd) break; 578218893Sdim if (s[2] == '6') { 579218893Sdim s += 3; // i16 suffix 580218893Sdim isMicrosoftInteger = true; 581218893Sdim } 582199990Srdivacky else if (s[2] == '2') { 583199990Srdivacky if (s + 3 == ThisTokEnd) break; 584218893Sdim if (s[3] == '8') { 585218893Sdim s += 4; // i128 suffix 586218893Sdim isMicrosoftInteger = true; 587218893Sdim } 588198092Srdivacky } 589199990Srdivacky break; 590198092Srdivacky case '3': 591199990Srdivacky if (s + 2 == ThisTokEnd) break; 592218893Sdim if (s[2] == '2') { 593218893Sdim s += 3; // i32 suffix 594218893Sdim isLong = true; 595218893Sdim isMicrosoftInteger = true; 596218893Sdim } 597199990Srdivacky break; 598198092Srdivacky case '6': 599199990Srdivacky if (s + 2 == ThisTokEnd) break; 600218893Sdim if (s[2] == '4') { 601218893Sdim s += 3; // i64 suffix 602218893Sdim isLongLong = true; 603218893Sdim isMicrosoftInteger = true; 604218893Sdim } 605199990Srdivacky break; 606198092Srdivacky default: 607198092Srdivacky break; 608198092Srdivacky } 609198092Srdivacky break; 610193326Sed } 611193326Sed } 612263508Sdim // "i", "if", and "il" are user-defined suffixes in C++1y. 613263508Sdim if (PP.getLangOpts().CPlusPlus1y && *s == 'i') 614263508Sdim break; 615193326Sed // fall through. 616193326Sed case 'j': 617193326Sed case 'J': 618193326Sed if (isImaginary) break; // Cannot be repeated. 619193326Sed isImaginary = true; 620263508Sdim ImaginarySuffixLoc = s; 621193326Sed continue; // Success. 622193326Sed } 623234353Sdim // If we reached here, there was an error or a ud-suffix. 624193326Sed break; 625193326Sed } 626198092Srdivacky 627193326Sed if (s != ThisTokEnd) { 628263508Sdim if (isValidUDSuffix(PP.getLangOpts(), 629263508Sdim StringRef(SuffixBegin, ThisTokEnd - SuffixBegin))) { 630263508Sdim // Any suffix pieces we might have parsed are actually part of the 631263508Sdim // ud-suffix. 632263508Sdim isLong = false; 633263508Sdim isUnsigned = false; 634263508Sdim isLongLong = false; 635263508Sdim isFloat = false; 636263508Sdim isImaginary = false; 637263508Sdim isMicrosoftInteger = false; 638263508Sdim 639234353Sdim saw_ud_suffix = true; 640234353Sdim return; 641234353Sdim } 642234353Sdim 643234353Sdim // Report an error if there are any. 644243830Sdim PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin), 645193326Sed isFPConstant ? diag::err_invalid_suffix_float_constant : 646193326Sed diag::err_invalid_suffix_integer_constant) 647226633Sdim << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin); 648193326Sed hadError = true; 649193326Sed return; 650193326Sed } 651263508Sdim 652263508Sdim if (isImaginary) { 653263508Sdim PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, 654263508Sdim ImaginarySuffixLoc - ThisTokBegin), 655263508Sdim diag::ext_imaginary_constant); 656263508Sdim } 657193326Sed} 658193326Sed 659263508Sdim/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved 660263508Sdim/// suffixes as ud-suffixes, because the diagnostic experience is better if we 661263508Sdim/// treat it as an invalid suffix. 662263508Sdimbool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts, 663263508Sdim StringRef Suffix) { 664263508Sdim if (!LangOpts.CPlusPlus11 || Suffix.empty()) 665263508Sdim return false; 666263508Sdim 667263508Sdim // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid. 668263508Sdim if (Suffix[0] == '_') 669263508Sdim return true; 670263508Sdim 671263508Sdim // In C++11, there are no library suffixes. 672263508Sdim if (!LangOpts.CPlusPlus1y) 673263508Sdim return false; 674263508Sdim 675263508Sdim // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library. 676263508Sdim // Per tweaked N3660, "il", "i", and "if" are also used in the library. 677263508Sdim return llvm::StringSwitch<bool>(Suffix) 678263508Sdim .Cases("h", "min", "s", true) 679263508Sdim .Cases("ms", "us", "ns", true) 680263508Sdim .Cases("il", "i", "if", true) 681263508Sdim .Default(false); 682263508Sdim} 683263508Sdim 684263508Sdimvoid NumericLiteralParser::checkSeparator(SourceLocation TokLoc, 685263508Sdim const char *Pos, 686263508Sdim CheckSeparatorKind IsAfterDigits) { 687263508Sdim if (IsAfterDigits == CSK_AfterDigits) { 688263508Sdim if (Pos == ThisTokBegin) 689263508Sdim return; 690263508Sdim --Pos; 691263508Sdim } else if (Pos == ThisTokEnd) 692263508Sdim return; 693263508Sdim 694263508Sdim if (isDigitSeparator(*Pos)) 695263508Sdim PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin), 696263508Sdim diag::err_digit_separator_not_between_digits) 697263508Sdim << IsAfterDigits; 698263508Sdim} 699263508Sdim 700193326Sed/// ParseNumberStartingWithZero - This method is called when the first character 701193326Sed/// of the number is found to be a zero. This means it is either an octal 702193326Sed/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or 703198092Srdivacky/// a floating point number (01239.123e4). Eat the prefix, determining the 704193326Sed/// radix etc. 705193326Sedvoid NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { 706193326Sed assert(s[0] == '0' && "Invalid method call"); 707193326Sed s++; 708198092Srdivacky 709263508Sdim int c1 = s[0]; 710263508Sdim int c2 = s[1]; 711263508Sdim 712193326Sed // Handle a hex number like 0x1234. 713263508Sdim if ((c1 == 'x' || c1 == 'X') && (isHexDigit(c2) || c2 == '.')) { 714193326Sed s++; 715193326Sed radix = 16; 716193326Sed DigitsBegin = s; 717193326Sed s = SkipHexDigits(s); 718234353Sdim bool noSignificand = (s == DigitsBegin); 719193326Sed if (s == ThisTokEnd) { 720193326Sed // Done. 721193326Sed } else if (*s == '.') { 722193326Sed s++; 723193326Sed saw_period = true; 724234353Sdim const char *floatDigitsBegin = s; 725193326Sed s = SkipHexDigits(s); 726234353Sdim noSignificand &= (floatDigitsBegin == s); 727193326Sed } 728234353Sdim 729234353Sdim if (noSignificand) { 730243830Sdim PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), 731234353Sdim diag::err_hexconstant_requires_digits); 732234353Sdim hadError = true; 733234353Sdim return; 734234353Sdim } 735234353Sdim 736193326Sed // A binary exponent can appear with or with a '.'. If dotted, the 737198092Srdivacky // binary exponent is required. 738226633Sdim if (*s == 'p' || *s == 'P') { 739193326Sed const char *Exponent = s; 740193326Sed s++; 741193326Sed saw_exponent = true; 742193326Sed if (*s == '+' || *s == '-') s++; // sign 743193326Sed const char *first_non_digit = SkipDigits(s); 744193326Sed if (first_non_digit == s) { 745193326Sed PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), 746193326Sed diag::err_exponent_has_no_digits); 747193326Sed hadError = true; 748193326Sed return; 749193326Sed } 750193326Sed s = first_non_digit; 751198092Srdivacky 752234353Sdim if (!PP.getLangOpts().HexFloats) 753193326Sed PP.Diag(TokLoc, diag::ext_hexconstant_invalid); 754193326Sed } else if (saw_period) { 755193326Sed PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 756193326Sed diag::err_hexconstant_requires_exponent); 757193326Sed hadError = true; 758193326Sed } 759193326Sed return; 760193326Sed } 761198092Srdivacky 762193326Sed // Handle simple binary numbers 0b01010 763263508Sdim if ((c1 == 'b' || c1 == 'B') && (c2 == '0' || c2 == '1')) { 764251662Sdim // 0b101010 is a C++1y / GCC extension. 765251662Sdim PP.Diag(TokLoc, 766251662Sdim PP.getLangOpts().CPlusPlus1y 767251662Sdim ? diag::warn_cxx11_compat_binary_literal 768251662Sdim : PP.getLangOpts().CPlusPlus 769251662Sdim ? diag::ext_binary_literal_cxx1y 770251662Sdim : diag::ext_binary_literal); 771193326Sed ++s; 772193326Sed radix = 2; 773193326Sed DigitsBegin = s; 774193326Sed s = SkipBinaryDigits(s); 775193326Sed if (s == ThisTokEnd) { 776193326Sed // Done. 777249423Sdim } else if (isHexDigit(*s)) { 778193326Sed PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 779226633Sdim diag::err_invalid_binary_digit) << StringRef(s, 1); 780193326Sed hadError = true; 781193326Sed } 782193326Sed // Other suffixes will be diagnosed by the caller. 783193326Sed return; 784193326Sed } 785198092Srdivacky 786193326Sed // For now, the radix is set to 8. If we discover that we have a 787193326Sed // floating point constant, the radix will change to 10. Octal floating 788198092Srdivacky // point constants are not permitted (only decimal and hexadecimal). 789193326Sed radix = 8; 790193326Sed DigitsBegin = s; 791193326Sed s = SkipOctalDigits(s); 792193326Sed if (s == ThisTokEnd) 793193326Sed return; // Done, simple octal number like 01234 794198092Srdivacky 795193326Sed // If we have some other non-octal digit that *is* a decimal digit, see if 796193326Sed // this is part of a floating point number like 094.123 or 09e1. 797249423Sdim if (isDigit(*s)) { 798193326Sed const char *EndDecimal = SkipDigits(s); 799193326Sed if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') { 800193326Sed s = EndDecimal; 801193326Sed radix = 10; 802193326Sed } 803193326Sed } 804198092Srdivacky 805193326Sed // If we have a hex digit other than 'e' (which denotes a FP exponent) then 806193326Sed // the code is using an incorrect base. 807249423Sdim if (isHexDigit(*s) && *s != 'e' && *s != 'E') { 808193326Sed PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), 809226633Sdim diag::err_invalid_octal_digit) << StringRef(s, 1); 810193326Sed hadError = true; 811193326Sed return; 812193326Sed } 813198092Srdivacky 814193326Sed if (*s == '.') { 815193326Sed s++; 816193326Sed radix = 10; 817193326Sed saw_period = true; 818193326Sed s = SkipDigits(s); // Skip suffix. 819193326Sed } 820193326Sed if (*s == 'e' || *s == 'E') { // exponent 821193326Sed const char *Exponent = s; 822193326Sed s++; 823193326Sed radix = 10; 824193326Sed saw_exponent = true; 825193326Sed if (*s == '+' || *s == '-') s++; // sign 826193326Sed const char *first_non_digit = SkipDigits(s); 827193326Sed if (first_non_digit != s) { 828193326Sed s = first_non_digit; 829193326Sed } else { 830198092Srdivacky PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), 831193326Sed diag::err_exponent_has_no_digits); 832193326Sed hadError = true; 833193326Sed return; 834193326Sed } 835193326Sed } 836193326Sed} 837193326Sed 838243830Sdimstatic bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) { 839243830Sdim switch (Radix) { 840243830Sdim case 2: 841243830Sdim return NumDigits <= 64; 842243830Sdim case 8: 843243830Sdim return NumDigits <= 64 / 3; // Digits are groups of 3 bits. 844243830Sdim case 10: 845243830Sdim return NumDigits <= 19; // floor(log10(2^64)) 846243830Sdim case 16: 847243830Sdim return NumDigits <= 64 / 4; // Digits are groups of 4 bits. 848243830Sdim default: 849243830Sdim llvm_unreachable("impossible Radix"); 850243830Sdim } 851243830Sdim} 852193326Sed 853193326Sed/// GetIntegerValue - Convert this numeric literal value to an APInt that 854193326Sed/// matches Val's input width. If there is an overflow, set Val to the low bits 855193326Sed/// of the result and return true. Otherwise, return false. 856193326Sedbool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { 857193326Sed // Fast path: Compute a conservative bound on the maximum number of 858193326Sed // bits per digit in this radix. If we can't possibly overflow a 859193326Sed // uint64 based on that bound then do the simple conversion to 860193326Sed // integer. This avoids the expensive overflow checking below, and 861193326Sed // handles the common cases that matter (small decimal integers and 862193326Sed // hex/octal values which don't overflow). 863243830Sdim const unsigned NumDigits = SuffixBegin - DigitsBegin; 864243830Sdim if (alwaysFitsInto64Bits(radix, NumDigits)) { 865193326Sed uint64_t N = 0; 866243830Sdim for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr) 867263508Sdim if (!isDigitSeparator(*Ptr)) 868263508Sdim N = N * radix + llvm::hexDigitValue(*Ptr); 869193326Sed 870193326Sed // This will truncate the value to Val's input width. Simply check 871193326Sed // for overflow by comparing. 872193326Sed Val = N; 873193326Sed return Val.getZExtValue() != N; 874193326Sed } 875193326Sed 876193326Sed Val = 0; 877243830Sdim const char *Ptr = DigitsBegin; 878193326Sed 879193326Sed llvm::APInt RadixVal(Val.getBitWidth(), radix); 880193326Sed llvm::APInt CharVal(Val.getBitWidth(), 0); 881193326Sed llvm::APInt OldVal = Val; 882198092Srdivacky 883193326Sed bool OverflowOccurred = false; 884243830Sdim while (Ptr < SuffixBegin) { 885263508Sdim if (isDigitSeparator(*Ptr)) { 886263508Sdim ++Ptr; 887263508Sdim continue; 888263508Sdim } 889263508Sdim 890249423Sdim unsigned C = llvm::hexDigitValue(*Ptr++); 891198092Srdivacky 892193326Sed // If this letter is out of bound for this radix, reject it. 893193326Sed assert(C < radix && "NumericLiteralParser ctor should have rejected this"); 894198092Srdivacky 895193326Sed CharVal = C; 896198092Srdivacky 897193326Sed // Add the digit to the value in the appropriate radix. If adding in digits 898193326Sed // made the value smaller, then this overflowed. 899193326Sed OldVal = Val; 900193326Sed 901193326Sed // Multiply by radix, did overflow occur on the multiply? 902193326Sed Val *= RadixVal; 903193326Sed OverflowOccurred |= Val.udiv(RadixVal) != OldVal; 904193326Sed 905193326Sed // Add value, did overflow occur on the value? 906193326Sed // (a + b) ult b <=> overflow 907193326Sed Val += CharVal; 908193326Sed OverflowOccurred |= Val.ult(CharVal); 909193326Sed } 910193326Sed return OverflowOccurred; 911193326Sed} 912193326Sed 913201361Srdivackyllvm::APFloat::opStatus 914201361SrdivackyNumericLiteralParser::GetFloatValue(llvm::APFloat &Result) { 915193326Sed using llvm::APFloat; 916198092Srdivacky 917198092Srdivacky unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin); 918263508Sdim 919263508Sdim llvm::SmallString<16> Buffer; 920263508Sdim StringRef Str(ThisTokBegin, n); 921263508Sdim if (Str.find('\'') != StringRef::npos) { 922263508Sdim Buffer.reserve(n); 923263508Sdim std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer), 924263508Sdim &isDigitSeparator); 925263508Sdim Str = Buffer; 926263508Sdim } 927263508Sdim 928263508Sdim return Result.convertFromString(Str, APFloat::rmNearestTiesToEven); 929193326Sed} 930193326Sed 931193326Sed 932239462Sdim/// \verbatim 933234353Sdim/// user-defined-character-literal: [C++11 lex.ext] 934234353Sdim/// character-literal ud-suffix 935234353Sdim/// ud-suffix: 936234353Sdim/// identifier 937234353Sdim/// character-literal: [C++11 lex.ccon] 938226633Sdim/// ' c-char-sequence ' 939226633Sdim/// u' c-char-sequence ' 940226633Sdim/// U' c-char-sequence ' 941226633Sdim/// L' c-char-sequence ' 942226633Sdim/// c-char-sequence: 943226633Sdim/// c-char 944226633Sdim/// c-char-sequence c-char 945226633Sdim/// c-char: 946226633Sdim/// any member of the source character set except the single-quote ', 947226633Sdim/// backslash \, or new-line character 948226633Sdim/// escape-sequence 949226633Sdim/// universal-character-name 950234353Sdim/// escape-sequence: 951226633Sdim/// simple-escape-sequence 952226633Sdim/// octal-escape-sequence 953226633Sdim/// hexadecimal-escape-sequence 954226633Sdim/// simple-escape-sequence: 955226633Sdim/// one of \' \" \? \\ \a \b \f \n \r \t \v 956226633Sdim/// octal-escape-sequence: 957226633Sdim/// \ octal-digit 958226633Sdim/// \ octal-digit octal-digit 959226633Sdim/// \ octal-digit octal-digit octal-digit 960226633Sdim/// hexadecimal-escape-sequence: 961226633Sdim/// \x hexadecimal-digit 962226633Sdim/// hexadecimal-escape-sequence hexadecimal-digit 963234353Sdim/// universal-character-name: [C++11 lex.charset] 964226633Sdim/// \u hex-quad 965226633Sdim/// \U hex-quad hex-quad 966226633Sdim/// hex-quad: 967226633Sdim/// hex-digit hex-digit hex-digit hex-digit 968239462Sdim/// \endverbatim 969226633Sdim/// 970193326SedCharLiteralParser::CharLiteralParser(const char *begin, const char *end, 971226633Sdim SourceLocation Loc, Preprocessor &PP, 972226633Sdim tok::TokenKind kind) { 973234353Sdim // At this point we know that the character matches the regex "(L|u|U)?'.*'". 974193326Sed HadError = false; 975198092Srdivacky 976226633Sdim Kind = kind; 977198092Srdivacky 978234353Sdim const char *TokBegin = begin; 979234353Sdim 980234353Sdim // Skip over wide character determinant. 981234353Sdim if (Kind != tok::char_constant) { 982226633Sdim ++begin; 983226633Sdim } 984226633Sdim 985193326Sed // Skip over the entry quote. 986193326Sed assert(begin[0] == '\'' && "Invalid token lexed"); 987193326Sed ++begin; 988193326Sed 989234353Sdim // Remove an optional ud-suffix. 990234353Sdim if (end[-1] != '\'') { 991234353Sdim const char *UDSuffixEnd = end; 992234353Sdim do { 993234353Sdim --end; 994234353Sdim } while (end[-1] != '\''); 995234353Sdim UDSuffixBuf.assign(end, UDSuffixEnd); 996234353Sdim UDSuffixOffset = end - TokBegin; 997234353Sdim } 998234353Sdim 999234353Sdim // Trim the ending quote. 1000234353Sdim assert(end != begin && "Invalid token lexed"); 1001234353Sdim --end; 1002234353Sdim 1003198092Srdivacky // FIXME: The "Value" is an uint64_t so we can handle char literals of 1004221345Sdim // up to 64-bits. 1005193326Sed // FIXME: This extensively assumes that 'char' is 8-bits. 1006193326Sed assert(PP.getTargetInfo().getCharWidth() == 8 && 1007193326Sed "Assumes char is 8 bits"); 1008193326Sed assert(PP.getTargetInfo().getIntWidth() <= 64 && 1009193326Sed (PP.getTargetInfo().getIntWidth() & 7) == 0 && 1010193326Sed "Assumes sizeof(int) on target is <= 64 and a multiple of char"); 1011193326Sed assert(PP.getTargetInfo().getWCharWidth() <= 64 && 1012193326Sed "Assumes sizeof(wchar) on target is <= 64"); 1013193326Sed 1014263508Sdim SmallVector<uint32_t, 4> codepoint_buffer; 1015263508Sdim codepoint_buffer.resize(end - begin); 1016234353Sdim uint32_t *buffer_begin = &codepoint_buffer.front(); 1017234353Sdim uint32_t *buffer_end = buffer_begin + codepoint_buffer.size(); 1018198092Srdivacky 1019234353Sdim // Unicode escapes representing characters that cannot be correctly 1020234353Sdim // represented in a single code unit are disallowed in character literals 1021234353Sdim // by this implementation. 1022234353Sdim uint32_t largest_character_for_kind; 1023234353Sdim if (tok::wide_char_constant == Kind) { 1024263508Sdim largest_character_for_kind = 1025263508Sdim 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth()); 1026234353Sdim } else if (tok::utf16_char_constant == Kind) { 1027234353Sdim largest_character_for_kind = 0xFFFF; 1028234353Sdim } else if (tok::utf32_char_constant == Kind) { 1029234353Sdim largest_character_for_kind = 0x10FFFF; 1030234353Sdim } else { 1031234353Sdim largest_character_for_kind = 0x7Fu; 1032234353Sdim } 1033218893Sdim 1034263508Sdim while (begin != end) { 1035234353Sdim // Is this a span of non-escape characters? 1036234353Sdim if (begin[0] != '\\') { 1037234353Sdim char const *start = begin; 1038234353Sdim do { 1039234353Sdim ++begin; 1040234353Sdim } while (begin != end && *begin != '\\'); 1041234353Sdim 1042234353Sdim char const *tmp_in_start = start; 1043234353Sdim uint32_t *tmp_out_start = buffer_begin; 1044234353Sdim ConversionResult res = 1045263508Sdim ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start), 1046263508Sdim reinterpret_cast<UTF8 const *>(begin), 1047263508Sdim &buffer_begin, buffer_end, strictConversion); 1048263508Sdim if (res != conversionOK) { 1049263508Sdim // If we see bad encoding for unprefixed character literals, warn and 1050263508Sdim // simply copy the byte values, for compatibility with gcc and 1051234353Sdim // older versions of clang. 1052234353Sdim bool NoErrorOnBadEncoding = isAscii(); 1053234353Sdim unsigned Msg = diag::err_bad_character_encoding; 1054234353Sdim if (NoErrorOnBadEncoding) 1055234353Sdim Msg = diag::warn_bad_character_encoding; 1056234353Sdim PP.Diag(Loc, Msg); 1057234353Sdim if (NoErrorOnBadEncoding) { 1058234353Sdim start = tmp_in_start; 1059234353Sdim buffer_begin = tmp_out_start; 1060263508Sdim for (; start != begin; ++start, ++buffer_begin) 1061234353Sdim *buffer_begin = static_cast<uint8_t>(*start); 1062234353Sdim } else { 1063234353Sdim HadError = true; 1064218893Sdim } 1065234353Sdim } else { 1066263508Sdim for (; tmp_out_start < buffer_begin; ++tmp_out_start) { 1067234353Sdim if (*tmp_out_start > largest_character_for_kind) { 1068234353Sdim HadError = true; 1069234353Sdim PP.Diag(Loc, diag::err_character_too_large); 1070234353Sdim } 1071226633Sdim } 1072218893Sdim } 1073234353Sdim 1074234353Sdim continue; 1075218893Sdim } 1076263508Sdim // Is this a Universal Character Name escape? 1077234353Sdim if (begin[1] == 'u' || begin[1] == 'U') { 1078234353Sdim unsigned short UcnLen = 0; 1079234353Sdim if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen, 1080234353Sdim FullSourceLoc(Loc, PP.getSourceManager()), 1081263508Sdim &PP.getDiagnostics(), PP.getLangOpts(), true)) { 1082234353Sdim HadError = true; 1083234353Sdim } else if (*buffer_begin > largest_character_for_kind) { 1084234353Sdim HadError = true; 1085243830Sdim PP.Diag(Loc, diag::err_character_too_large); 1086234353Sdim } 1087193326Sed 1088234353Sdim ++buffer_begin; 1089234353Sdim continue; 1090193326Sed } 1091234353Sdim unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo()); 1092234353Sdim uint64_t result = 1093243830Sdim ProcessCharEscape(TokBegin, begin, end, HadError, 1094243830Sdim FullSourceLoc(Loc,PP.getSourceManager()), 1095243830Sdim CharWidth, &PP.getDiagnostics(), PP.getLangOpts()); 1096234353Sdim *buffer_begin++ = result; 1097193326Sed } 1098193326Sed 1099263508Sdim unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front(); 1100234353Sdim 1101193326Sed if (NumCharsSoFar > 1) { 1102234353Sdim if (isWide()) 1103226633Sdim PP.Diag(Loc, diag::warn_extraneous_char_constant); 1104234353Sdim else if (isAscii() && NumCharsSoFar == 4) 1105234353Sdim PP.Diag(Loc, diag::ext_four_char_character_literal); 1106234353Sdim else if (isAscii()) 1107193326Sed PP.Diag(Loc, diag::ext_multichar_character_literal); 1108193326Sed else 1109234353Sdim PP.Diag(Loc, diag::err_multichar_utf_character_literal); 1110193326Sed IsMultiChar = true; 1111263508Sdim } else { 1112198092Srdivacky IsMultiChar = false; 1113263508Sdim } 1114193326Sed 1115234353Sdim llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0); 1116234353Sdim 1117234353Sdim // Narrow character literals act as though their value is concatenated 1118234353Sdim // in this implementation, but warn on overflow. 1119234353Sdim bool multi_char_too_long = false; 1120234353Sdim if (isAscii() && isMultiChar()) { 1121234353Sdim LitVal = 0; 1122263508Sdim for (size_t i = 0; i < NumCharsSoFar; ++i) { 1123234353Sdim // check for enough leading zeros to shift into 1124234353Sdim multi_char_too_long |= (LitVal.countLeadingZeros() < 8); 1125234353Sdim LitVal <<= 8; 1126234353Sdim LitVal = LitVal + (codepoint_buffer[i] & 0xFF); 1127234353Sdim } 1128234353Sdim } else if (NumCharsSoFar > 0) { 1129234353Sdim // otherwise just take the last character 1130234353Sdim LitVal = buffer_begin[-1]; 1131234353Sdim } 1132234353Sdim 1133234353Sdim if (!HadError && multi_char_too_long) { 1134263508Sdim PP.Diag(Loc, diag::warn_char_constant_too_large); 1135234353Sdim } 1136234353Sdim 1137193326Sed // Transfer the value from APInt to uint64_t 1138193326Sed Value = LitVal.getZExtValue(); 1139198092Srdivacky 1140193326Sed // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1") 1141193326Sed // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple 1142193326Sed // character constants are not sign extended in the this implementation: 1143193326Sed // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC. 1144226633Sdim if (isAscii() && NumCharsSoFar == 1 && (Value & 128) && 1145234353Sdim PP.getLangOpts().CharIsSigned) 1146193326Sed Value = (signed char)Value; 1147193326Sed} 1148193326Sed 1149239462Sdim/// \verbatim 1150226633Sdim/// string-literal: [C++0x lex.string] 1151226633Sdim/// encoding-prefix " [s-char-sequence] " 1152226633Sdim/// encoding-prefix R raw-string 1153226633Sdim/// encoding-prefix: 1154226633Sdim/// u8 1155226633Sdim/// u 1156226633Sdim/// U 1157226633Sdim/// L 1158193326Sed/// s-char-sequence: 1159193326Sed/// s-char 1160193326Sed/// s-char-sequence s-char 1161193326Sed/// s-char: 1162226633Sdim/// any member of the source character set except the double-quote ", 1163226633Sdim/// backslash \, or new-line character 1164226633Sdim/// escape-sequence 1165193326Sed/// universal-character-name 1166226633Sdim/// raw-string: 1167226633Sdim/// " d-char-sequence ( r-char-sequence ) d-char-sequence " 1168226633Sdim/// r-char-sequence: 1169226633Sdim/// r-char 1170226633Sdim/// r-char-sequence r-char 1171226633Sdim/// r-char: 1172226633Sdim/// any member of the source character set, except a right parenthesis ) 1173226633Sdim/// followed by the initial d-char-sequence (which may be empty) 1174226633Sdim/// followed by a double quote ". 1175226633Sdim/// d-char-sequence: 1176226633Sdim/// d-char 1177226633Sdim/// d-char-sequence d-char 1178226633Sdim/// d-char: 1179226633Sdim/// any member of the basic source character set except: 1180226633Sdim/// space, the left parenthesis (, the right parenthesis ), 1181226633Sdim/// the backslash \, and the control characters representing horizontal 1182226633Sdim/// tab, vertical tab, form feed, and newline. 1183226633Sdim/// escape-sequence: [C++0x lex.ccon] 1184226633Sdim/// simple-escape-sequence 1185226633Sdim/// octal-escape-sequence 1186226633Sdim/// hexadecimal-escape-sequence 1187226633Sdim/// simple-escape-sequence: 1188226633Sdim/// one of \' \" \? \\ \a \b \f \n \r \t \v 1189226633Sdim/// octal-escape-sequence: 1190226633Sdim/// \ octal-digit 1191226633Sdim/// \ octal-digit octal-digit 1192226633Sdim/// \ octal-digit octal-digit octal-digit 1193226633Sdim/// hexadecimal-escape-sequence: 1194226633Sdim/// \x hexadecimal-digit 1195226633Sdim/// hexadecimal-escape-sequence hexadecimal-digit 1196193326Sed/// universal-character-name: 1197193326Sed/// \u hex-quad 1198193326Sed/// \U hex-quad hex-quad 1199193326Sed/// hex-quad: 1200193326Sed/// hex-digit hex-digit hex-digit hex-digit 1201239462Sdim/// \endverbatim 1202193326Sed/// 1203193326SedStringLiteralParser:: 1204193326SedStringLiteralParser(const Token *StringToks, unsigned NumStringToks, 1205218893Sdim Preprocessor &PP, bool Complain) 1206234353Sdim : SM(PP.getSourceManager()), Features(PP.getLangOpts()), 1207223017Sdim Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0), 1208226633Sdim MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown), 1209226633Sdim ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) { 1210218893Sdim init(StringToks, NumStringToks); 1211218893Sdim} 1212218893Sdim 1213218893Sdimvoid StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){ 1214223017Sdim // The literal token may have come from an invalid source location (e.g. due 1215223017Sdim // to a PCH error), in which case the token length will be 0. 1216239462Sdim if (NumStringToks == 0 || StringToks[0].getLength() < 2) 1217239462Sdim return DiagnoseLexingError(SourceLocation()); 1218223017Sdim 1219193326Sed // Scan all of the string portions, remember the max individual token length, 1220193326Sed // computing a bound on the concatenated string length, and see whether any 1221193326Sed // piece is a wide-string. If any of the string portions is a wide-string 1222193326Sed // literal, the result is a wide-string literal [C99 6.4.5p4]. 1223223017Sdim assert(NumStringToks && "expected at least one token"); 1224193326Sed MaxTokenLength = StringToks[0].getLength(); 1225223017Sdim assert(StringToks[0].getLength() >= 2 && "literal token is invalid!"); 1226193326Sed SizeBound = StringToks[0].getLength()-2; // -2 for "". 1227226633Sdim Kind = StringToks[0].getKind(); 1228198092Srdivacky 1229193326Sed hadError = false; 1230193326Sed 1231193326Sed // Implement Translation Phase #6: concatenation of string literals 1232193326Sed /// (C99 5.1.1.2p1). The common case is only one string fragment. 1233193326Sed for (unsigned i = 1; i != NumStringToks; ++i) { 1234239462Sdim if (StringToks[i].getLength() < 2) 1235239462Sdim return DiagnoseLexingError(StringToks[i].getLocation()); 1236223017Sdim 1237193326Sed // The string could be shorter than this if it needs cleaning, but this is a 1238193326Sed // reasonable bound, which is all we need. 1239223017Sdim assert(StringToks[i].getLength() >= 2 && "literal token is invalid!"); 1240193326Sed SizeBound += StringToks[i].getLength()-2; // -2 for "". 1241198092Srdivacky 1242193326Sed // Remember maximum string piece length. 1243198092Srdivacky if (StringToks[i].getLength() > MaxTokenLength) 1244193326Sed MaxTokenLength = StringToks[i].getLength(); 1245198092Srdivacky 1246226633Sdim // Remember if we see any wide or utf-8/16/32 strings. 1247226633Sdim // Also check for illegal concatenations. 1248226633Sdim if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) { 1249226633Sdim if (isAscii()) { 1250226633Sdim Kind = StringToks[i].getKind(); 1251226633Sdim } else { 1252226633Sdim if (Diags) 1253243830Sdim Diags->Report(StringToks[i].getLocation(), 1254226633Sdim diag::err_unsupported_string_concat); 1255226633Sdim hadError = true; 1256226633Sdim } 1257226633Sdim } 1258193326Sed } 1259193326Sed 1260193326Sed // Include space for the null terminator. 1261193326Sed ++SizeBound; 1262198092Srdivacky 1263193326Sed // TODO: K&R warning: "traditional C rejects string constant concatenation" 1264198092Srdivacky 1265226633Sdim // Get the width in bytes of char/wchar_t/char16_t/char32_t 1266226633Sdim CharByteWidth = getCharWidth(Kind, Target); 1267226633Sdim assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); 1268226633Sdim CharByteWidth /= 8; 1269198092Srdivacky 1270193326Sed // The output buffer size needs to be large enough to hold wide characters. 1271193326Sed // This is a worst-case assumption which basically corresponds to L"" "long". 1272226633Sdim SizeBound *= CharByteWidth; 1273198092Srdivacky 1274193326Sed // Size the temporary buffer to hold the result string data. 1275193326Sed ResultBuf.resize(SizeBound); 1276198092Srdivacky 1277193326Sed // Likewise, but for each string piece. 1278234353Sdim SmallString<512> TokenBuf; 1279193326Sed TokenBuf.resize(MaxTokenLength); 1280198092Srdivacky 1281193326Sed // Loop over all the strings, getting their spelling, and expanding them to 1282193326Sed // wide strings as appropriate. 1283193326Sed ResultPtr = &ResultBuf[0]; // Next byte to fill in. 1284198092Srdivacky 1285193326Sed Pascal = false; 1286198092Srdivacky 1287234353Sdim SourceLocation UDSuffixTokLoc; 1288234353Sdim 1289193326Sed for (unsigned i = 0, e = NumStringToks; i != e; ++i) { 1290193326Sed const char *ThisTokBuf = &TokenBuf[0]; 1291193326Sed // Get the spelling of the token, which eliminates trigraphs, etc. We know 1292193326Sed // that ThisTokBuf points to a buffer that is big enough for the whole token 1293193326Sed // and 'spelled' tokens can only shrink. 1294205219Srdivacky bool StringInvalid = false; 1295218893Sdim unsigned ThisTokLen = 1296218893Sdim Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features, 1297218893Sdim &StringInvalid); 1298239462Sdim if (StringInvalid) 1299239462Sdim return DiagnoseLexingError(StringToks[i].getLocation()); 1300205219Srdivacky 1301234353Sdim const char *ThisTokBegin = ThisTokBuf; 1302234353Sdim const char *ThisTokEnd = ThisTokBuf+ThisTokLen; 1303234353Sdim 1304234353Sdim // Remove an optional ud-suffix. 1305234353Sdim if (ThisTokEnd[-1] != '"') { 1306234353Sdim const char *UDSuffixEnd = ThisTokEnd; 1307234353Sdim do { 1308234353Sdim --ThisTokEnd; 1309234353Sdim } while (ThisTokEnd[-1] != '"'); 1310234353Sdim 1311234353Sdim StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd); 1312234353Sdim 1313234353Sdim if (UDSuffixBuf.empty()) { 1314234353Sdim UDSuffixBuf.assign(UDSuffix); 1315234353Sdim UDSuffixToken = i; 1316234353Sdim UDSuffixOffset = ThisTokEnd - ThisTokBuf; 1317234353Sdim UDSuffixTokLoc = StringToks[i].getLocation(); 1318234353Sdim } else if (!UDSuffixBuf.equals(UDSuffix)) { 1319234353Sdim // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the 1320234353Sdim // result of a concatenation involving at least one user-defined-string- 1321234353Sdim // literal, all the participating user-defined-string-literals shall 1322234353Sdim // have the same ud-suffix. 1323234353Sdim if (Diags) { 1324234353Sdim SourceLocation TokLoc = StringToks[i].getLocation(); 1325234353Sdim Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix) 1326234353Sdim << UDSuffixBuf << UDSuffix 1327234353Sdim << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc) 1328234353Sdim << SourceRange(TokLoc, TokLoc); 1329234353Sdim } 1330234353Sdim hadError = true; 1331234353Sdim } 1332234353Sdim } 1333234353Sdim 1334234353Sdim // Strip the end quote. 1335234353Sdim --ThisTokEnd; 1336234353Sdim 1337193326Sed // TODO: Input character set mapping support. 1338198092Srdivacky 1339226633Sdim // Skip marker for wide or unicode strings. 1340226633Sdim if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') { 1341193326Sed ++ThisTokBuf; 1342226633Sdim // Skip 8 of u8 marker for utf8 strings. 1343226633Sdim if (ThisTokBuf[0] == '8') 1344226633Sdim ++ThisTokBuf; 1345212904Sdim } 1346198092Srdivacky 1347226633Sdim // Check for raw string 1348226633Sdim if (ThisTokBuf[0] == 'R') { 1349226633Sdim ThisTokBuf += 2; // skip R" 1350198092Srdivacky 1351226633Sdim const char *Prefix = ThisTokBuf; 1352226633Sdim while (ThisTokBuf[0] != '(') 1353193326Sed ++ThisTokBuf; 1354226633Sdim ++ThisTokBuf; // skip '(' 1355198092Srdivacky 1356234353Sdim // Remove same number of characters from the end 1357234353Sdim ThisTokEnd -= ThisTokBuf - Prefix; 1358234353Sdim assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal"); 1359226633Sdim 1360226633Sdim // Copy the string over 1361243830Sdim if (CopyStringFragment(StringToks[i], ThisTokBegin, 1362243830Sdim StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf))) 1363243830Sdim hadError = true; 1364226633Sdim } else { 1365239462Sdim if (ThisTokBuf[0] != '"') { 1366239462Sdim // The file may have come from PCH and then changed after loading the 1367239462Sdim // PCH; Fail gracefully. 1368239462Sdim return DiagnoseLexingError(StringToks[i].getLocation()); 1369239462Sdim } 1370226633Sdim ++ThisTokBuf; // skip " 1371226633Sdim 1372226633Sdim // Check if this is a pascal string 1373226633Sdim if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd && 1374226633Sdim ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') { 1375226633Sdim 1376226633Sdim // If the \p sequence is found in the first token, we have a pascal string 1377226633Sdim // Otherwise, if we already have a pascal string, ignore the first \p 1378226633Sdim if (i == 0) { 1379193326Sed ++ThisTokBuf; 1380226633Sdim Pascal = true; 1381226633Sdim } else if (Pascal) 1382226633Sdim ThisTokBuf += 2; 1383226633Sdim } 1384198092Srdivacky 1385226633Sdim while (ThisTokBuf != ThisTokEnd) { 1386226633Sdim // Is this a span of non-escape characters? 1387226633Sdim if (ThisTokBuf[0] != '\\') { 1388226633Sdim const char *InStart = ThisTokBuf; 1389226633Sdim do { 1390226633Sdim ++ThisTokBuf; 1391226633Sdim } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\'); 1392226633Sdim 1393226633Sdim // Copy the character span over. 1394243830Sdim if (CopyStringFragment(StringToks[i], ThisTokBegin, 1395243830Sdim StringRef(InStart, ThisTokBuf - InStart))) 1396243830Sdim hadError = true; 1397226633Sdim continue; 1398193326Sed } 1399226633Sdim // Is this a Universal Character Name escape? 1400226633Sdim if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') { 1401234353Sdim EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, 1402234353Sdim ResultPtr, hadError, 1403234353Sdim FullSourceLoc(StringToks[i].getLocation(), SM), 1404226633Sdim CharByteWidth, Diags, Features); 1405226633Sdim continue; 1406226633Sdim } 1407226633Sdim // Otherwise, this is a non-UCN escape character. Process it. 1408226633Sdim unsigned ResultChar = 1409243830Sdim ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError, 1410226633Sdim FullSourceLoc(StringToks[i].getLocation(), SM), 1411243830Sdim CharByteWidth*8, Diags, Features); 1412198092Srdivacky 1413234353Sdim if (CharByteWidth == 4) { 1414234353Sdim // FIXME: Make the type of the result buffer correct instead of 1415234353Sdim // using reinterpret_cast. 1416234353Sdim UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr); 1417234353Sdim *ResultWidePtr = ResultChar; 1418234353Sdim ResultPtr += 4; 1419234353Sdim } else if (CharByteWidth == 2) { 1420234353Sdim // FIXME: Make the type of the result buffer correct instead of 1421234353Sdim // using reinterpret_cast. 1422234353Sdim UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr); 1423234353Sdim *ResultWidePtr = ResultChar & 0xFFFF; 1424234353Sdim ResultPtr += 2; 1425234353Sdim } else { 1426234353Sdim assert(CharByteWidth == 1 && "Unexpected char width"); 1427234353Sdim *ResultPtr++ = ResultChar & 0xFF; 1428234353Sdim } 1429193326Sed } 1430193326Sed } 1431193326Sed } 1432198092Srdivacky 1433193326Sed if (Pascal) { 1434234353Sdim if (CharByteWidth == 4) { 1435234353Sdim // FIXME: Make the type of the result buffer correct instead of 1436234353Sdim // using reinterpret_cast. 1437234353Sdim UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data()); 1438234353Sdim ResultWidePtr[0] = GetNumStringChars() - 1; 1439234353Sdim } else if (CharByteWidth == 2) { 1440234353Sdim // FIXME: Make the type of the result buffer correct instead of 1441234353Sdim // using reinterpret_cast. 1442234353Sdim UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data()); 1443234353Sdim ResultWidePtr[0] = GetNumStringChars() - 1; 1444234353Sdim } else { 1445234353Sdim assert(CharByteWidth == 1 && "Unexpected char width"); 1446234353Sdim ResultBuf[0] = GetNumStringChars() - 1; 1447234353Sdim } 1448193326Sed 1449193326Sed // Verify that pascal strings aren't too large. 1450218893Sdim if (GetStringLength() > 256) { 1451243830Sdim if (Diags) 1452243830Sdim Diags->Report(StringToks[0].getLocation(), 1453218893Sdim diag::err_pascal_string_too_long) 1454218893Sdim << SourceRange(StringToks[0].getLocation(), 1455218893Sdim StringToks[NumStringToks-1].getLocation()); 1456226633Sdim hadError = true; 1457193326Sed return; 1458193326Sed } 1459218893Sdim } else if (Diags) { 1460212904Sdim // Complain if this string literal has too many characters. 1461218893Sdim unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509; 1462243830Sdim 1463212904Sdim if (GetNumStringChars() > MaxChars) 1464243830Sdim Diags->Report(StringToks[0].getLocation(), 1465218893Sdim diag::ext_string_too_long) 1466212904Sdim << GetNumStringChars() << MaxChars 1467218893Sdim << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0) 1468212904Sdim << SourceRange(StringToks[0].getLocation(), 1469212904Sdim StringToks[NumStringToks-1].getLocation()); 1470193326Sed } 1471193326Sed} 1472193326Sed 1473243830Sdimstatic const char *resyncUTF8(const char *Err, const char *End) { 1474243830Sdim if (Err == End) 1475243830Sdim return End; 1476243830Sdim End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err); 1477243830Sdim while (++Err != End && (*Err & 0xC0) == 0x80) 1478243830Sdim ; 1479243830Sdim return Err; 1480226633Sdim} 1481226633Sdim 1482243830Sdim/// \brief This function copies from Fragment, which is a sequence of bytes 1483243830Sdim/// within Tok's contents (which begin at TokBegin) into ResultPtr. 1484243830Sdim/// Performs widening for multi-byte characters. 1485243830Sdimbool StringLiteralParser::CopyStringFragment(const Token &Tok, 1486243830Sdim const char *TokBegin, 1487243830Sdim StringRef Fragment) { 1488243830Sdim const UTF8 *ErrorPtrTmp; 1489243830Sdim if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp)) 1490243830Sdim return false; 1491243830Sdim 1492234353Sdim // If we see bad encoding for unprefixed string literals, warn and 1493234353Sdim // simply copy the byte values, for compatibility with gcc and older 1494234353Sdim // versions of clang. 1495234353Sdim bool NoErrorOnBadEncoding = isAscii(); 1496243830Sdim if (NoErrorOnBadEncoding) { 1497243830Sdim memcpy(ResultPtr, Fragment.data(), Fragment.size()); 1498243830Sdim ResultPtr += Fragment.size(); 1499243830Sdim } 1500243830Sdim 1501243830Sdim if (Diags) { 1502243830Sdim const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp); 1503243830Sdim 1504243830Sdim FullSourceLoc SourceLoc(Tok.getLocation(), SM); 1505243830Sdim const DiagnosticBuilder &Builder = 1506243830Sdim Diag(Diags, Features, SourceLoc, TokBegin, 1507243830Sdim ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()), 1508243830Sdim NoErrorOnBadEncoding ? diag::warn_bad_string_encoding 1509243830Sdim : diag::err_bad_string_encoding); 1510243830Sdim 1511243830Sdim const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end()); 1512243830Sdim StringRef NextFragment(NextStart, Fragment.end()-NextStart); 1513243830Sdim 1514243830Sdim // Decode into a dummy buffer. 1515243830Sdim SmallString<512> Dummy; 1516243830Sdim Dummy.reserve(Fragment.size() * CharByteWidth); 1517243830Sdim char *Ptr = Dummy.data(); 1518243830Sdim 1519243830Sdim while (!Builder.hasMaxRanges() && 1520243830Sdim !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) { 1521243830Sdim const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp); 1522243830Sdim NextStart = resyncUTF8(ErrorPtr, Fragment.end()); 1523243830Sdim Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin, 1524243830Sdim ErrorPtr, NextStart); 1525243830Sdim NextFragment = StringRef(NextStart, Fragment.end()-NextStart); 1526243830Sdim } 1527243830Sdim } 1528234353Sdim return !NoErrorOnBadEncoding; 1529234353Sdim} 1530226633Sdim 1531239462Sdimvoid StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) { 1532239462Sdim hadError = true; 1533239462Sdim if (Diags) 1534239462Sdim Diags->Report(Loc, diag::err_lexing_string); 1535239462Sdim} 1536239462Sdim 1537193326Sed/// getOffsetOfStringByte - This function returns the offset of the 1538193326Sed/// specified byte of the string data represented by Token. This handles 1539193326Sed/// advancing over escape sequences in the string. 1540193326Sedunsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, 1541218893Sdim unsigned ByteNo) const { 1542193326Sed // Get the spelling of the token. 1543234353Sdim SmallString<32> SpellingBuffer; 1544193326Sed SpellingBuffer.resize(Tok.getLength()); 1545198092Srdivacky 1546205219Srdivacky bool StringInvalid = false; 1547193326Sed const char *SpellingPtr = &SpellingBuffer[0]; 1548218893Sdim unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features, 1549218893Sdim &StringInvalid); 1550218893Sdim if (StringInvalid) 1551205219Srdivacky return 0; 1552193326Sed 1553239462Sdim const char *SpellingStart = SpellingPtr; 1554239462Sdim const char *SpellingEnd = SpellingPtr+TokLen; 1555239462Sdim 1556239462Sdim // Handle UTF-8 strings just like narrow strings. 1557239462Sdim if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8') 1558239462Sdim SpellingPtr += 2; 1559239462Sdim 1560226633Sdim assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' && 1561226633Sdim SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet"); 1562193326Sed 1563239462Sdim // For raw string literals, this is easy. 1564239462Sdim if (SpellingPtr[0] == 'R') { 1565239462Sdim assert(SpellingPtr[1] == '"' && "Should be a raw string literal!"); 1566239462Sdim // Skip 'R"'. 1567239462Sdim SpellingPtr += 2; 1568239462Sdim while (*SpellingPtr != '(') { 1569239462Sdim ++SpellingPtr; 1570239462Sdim assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal"); 1571239462Sdim } 1572239462Sdim // Skip '('. 1573239462Sdim ++SpellingPtr; 1574239462Sdim return SpellingPtr - SpellingStart + ByteNo; 1575239462Sdim } 1576198092Srdivacky 1577239462Sdim // Skip over the leading quote 1578193326Sed assert(SpellingPtr[0] == '"' && "Should be a string literal!"); 1579193326Sed ++SpellingPtr; 1580198092Srdivacky 1581193326Sed // Skip over bytes until we find the offset we're looking for. 1582193326Sed while (ByteNo) { 1583193326Sed assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!"); 1584198092Srdivacky 1585193326Sed // Step over non-escapes simply. 1586193326Sed if (*SpellingPtr != '\\') { 1587193326Sed ++SpellingPtr; 1588193326Sed --ByteNo; 1589193326Sed continue; 1590193326Sed } 1591198092Srdivacky 1592193326Sed // Otherwise, this is an escape character. Advance over it. 1593193326Sed bool HadError = false; 1594239462Sdim if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') { 1595239462Sdim const char *EscapePtr = SpellingPtr; 1596239462Sdim unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd, 1597239462Sdim 1, Features, HadError); 1598239462Sdim if (Len > ByteNo) { 1599239462Sdim // ByteNo is somewhere within the escape sequence. 1600239462Sdim SpellingPtr = EscapePtr; 1601239462Sdim break; 1602239462Sdim } 1603239462Sdim ByteNo -= Len; 1604239462Sdim } else { 1605243830Sdim ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError, 1606239462Sdim FullSourceLoc(Tok.getLocation(), SM), 1607243830Sdim CharByteWidth*8, Diags, Features); 1608239462Sdim --ByteNo; 1609239462Sdim } 1610193326Sed assert(!HadError && "This method isn't valid on erroneous strings"); 1611193326Sed } 1612198092Srdivacky 1613193326Sed return SpellingPtr-SpellingStart; 1614193326Sed} 1615