clang API Documentation

LiteralSupport.cpp
Go to the documentation of this file.
00001 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the NumericLiteralParser, CharLiteralParser, and
00011 // StringLiteralParser interfaces.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Lex/LiteralSupport.h"
00016 #include "clang/Lex/Preprocessor.h"
00017 #include "clang/Lex/LexDiagnostic.h"
00018 #include "clang/Basic/TargetInfo.h"
00019 #include "clang/Basic/ConvertUTF.h"
00020 #include "llvm/ADT/StringExtras.h"
00021 #include "llvm/Support/ErrorHandling.h"
00022 using namespace clang;
00023 
00024 /// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
00025 /// not valid.
00026 static int HexDigitValue(char C) {
00027   if (C >= '0' && C <= '9') return C-'0';
00028   if (C >= 'a' && C <= 'f') return C-'a'+10;
00029   if (C >= 'A' && C <= 'F') return C-'A'+10;
00030   return -1;
00031 }
00032 
00033 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
00034   switch (kind) {
00035   default: llvm_unreachable("Unknown token type!");
00036   case tok::char_constant:
00037   case tok::string_literal:
00038   case tok::utf8_string_literal:
00039     return Target.getCharWidth();
00040   case tok::wide_char_constant:
00041   case tok::wide_string_literal:
00042     return Target.getWCharWidth();
00043   case tok::utf16_char_constant:
00044   case tok::utf16_string_literal:
00045     return Target.getChar16Width();
00046   case tok::utf32_char_constant:
00047   case tok::utf32_string_literal:
00048     return Target.getChar32Width();
00049   }
00050 }
00051 
00052 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
00053 /// either a character or a string literal.
00054 static unsigned ProcessCharEscape(const char *&ThisTokBuf,
00055                                   const char *ThisTokEnd, bool &HadError,
00056                                   FullSourceLoc Loc, unsigned CharWidth,
00057                                   DiagnosticsEngine *Diags) {
00058   // Skip the '\' char.
00059   ++ThisTokBuf;
00060 
00061   // We know that this character can't be off the end of the buffer, because
00062   // that would have been \", which would not have been the end of string.
00063   unsigned ResultChar = *ThisTokBuf++;
00064   switch (ResultChar) {
00065   // These map to themselves.
00066   case '\\': case '\'': case '"': case '?': break;
00067 
00068     // These have fixed mappings.
00069   case 'a':
00070     // TODO: K&R: the meaning of '\\a' is different in traditional C
00071     ResultChar = 7;
00072     break;
00073   case 'b':
00074     ResultChar = 8;
00075     break;
00076   case 'e':
00077     if (Diags)
00078       Diags->Report(Loc, diag::ext_nonstandard_escape) << "e";
00079     ResultChar = 27;
00080     break;
00081   case 'E':
00082     if (Diags)
00083       Diags->Report(Loc, diag::ext_nonstandard_escape) << "E";
00084     ResultChar = 27;
00085     break;
00086   case 'f':
00087     ResultChar = 12;
00088     break;
00089   case 'n':
00090     ResultChar = 10;
00091     break;
00092   case 'r':
00093     ResultChar = 13;
00094     break;
00095   case 't':
00096     ResultChar = 9;
00097     break;
00098   case 'v':
00099     ResultChar = 11;
00100     break;
00101   case 'x': { // Hex escape.
00102     ResultChar = 0;
00103     if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
00104       if (Diags)
00105         Diags->Report(Loc, diag::err_hex_escape_no_digits);
00106       HadError = 1;
00107       break;
00108     }
00109 
00110     // Hex escapes are a maximal series of hex digits.
00111     bool Overflow = false;
00112     for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
00113       int CharVal = HexDigitValue(ThisTokBuf[0]);
00114       if (CharVal == -1) break;
00115       // About to shift out a digit?
00116       Overflow |= (ResultChar & 0xF0000000) ? true : false;
00117       ResultChar <<= 4;
00118       ResultChar |= CharVal;
00119     }
00120 
00121     // See if any bits will be truncated when evaluated as a character.
00122     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
00123       Overflow = true;
00124       ResultChar &= ~0U >> (32-CharWidth);
00125     }
00126 
00127     // Check for overflow.
00128     if (Overflow && Diags)   // Too many digits to fit in
00129       Diags->Report(Loc, diag::warn_hex_escape_too_large);
00130     break;
00131   }
00132   case '0': case '1': case '2': case '3':
00133   case '4': case '5': case '6': case '7': {
00134     // Octal escapes.
00135     --ThisTokBuf;
00136     ResultChar = 0;
00137 
00138     // Octal escapes are a series of octal digits with maximum length 3.
00139     // "\0123" is a two digit sequence equal to "\012" "3".
00140     unsigned NumDigits = 0;
00141     do {
00142       ResultChar <<= 3;
00143       ResultChar |= *ThisTokBuf++ - '0';
00144       ++NumDigits;
00145     } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
00146              ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
00147 
00148     // Check for overflow.  Reject '\777', but not L'\777'.
00149     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
00150       if (Diags)
00151         Diags->Report(Loc, diag::warn_octal_escape_too_large);
00152       ResultChar &= ~0U >> (32-CharWidth);
00153     }
00154     break;
00155   }
00156 
00157     // Otherwise, these are not valid escapes.
00158   case '(': case '{': case '[': case '%':
00159     // GCC accepts these as extensions.  We warn about them as such though.
00160     if (Diags)
00161       Diags->Report(Loc, diag::ext_nonstandard_escape)
00162         << std::string()+(char)ResultChar;
00163     break;
00164   default:
00165     if (Diags == 0)
00166       break;
00167       
00168     if (isgraph(ResultChar))
00169       Diags->Report(Loc, diag::ext_unknown_escape)
00170         << std::string()+(char)ResultChar;
00171     else
00172       Diags->Report(Loc, diag::ext_unknown_escape)
00173         << "x"+llvm::utohexstr(ResultChar);
00174     break;
00175   }
00176 
00177   return ResultChar;
00178 }
00179 
00180 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
00181 /// return the UTF32.
00182 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
00183                              const char *ThisTokEnd,
00184                              uint32_t &UcnVal, unsigned short &UcnLen,
00185                              FullSourceLoc Loc, DiagnosticsEngine *Diags, 
00186                              const LangOptions &Features,
00187                              bool in_char_string_literal = false) {
00188   if (!Features.CPlusPlus && !Features.C99 && Diags)
00189     Diags->Report(Loc, diag::warn_ucn_not_valid_in_c89);
00190 
00191   const char *UcnBegin = ThisTokBuf;
00192 
00193   // Skip the '\u' char's.
00194   ThisTokBuf += 2;
00195 
00196   if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
00197     if (Diags)
00198       Diags->Report(Loc, diag::err_ucn_escape_no_digits);
00199     return false;
00200   }
00201   UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
00202   unsigned short UcnLenSave = UcnLen;
00203   for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
00204     int CharVal = HexDigitValue(ThisTokBuf[0]);
00205     if (CharVal == -1) break;
00206     UcnVal <<= 4;
00207     UcnVal |= CharVal;
00208   }
00209   // If we didn't consume the proper number of digits, there is a problem.
00210   if (UcnLenSave) {
00211     if (Diags) {
00212       SourceLocation L =
00213         Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
00214                                        Loc.getManager(), Features);
00215       Diags->Report(L, diag::err_ucn_escape_incomplete);
00216     }
00217     return false;
00218   }
00219 
00220   // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
00221   if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
00222       UcnVal > 0x10FFFF) {                      // maximum legal UTF32 value
00223     if (Diags)
00224       Diags->Report(Loc, diag::err_ucn_escape_invalid);
00225     return false;
00226   }
00227 
00228   // C++11 allows UCNs that refer to control characters and basic source
00229   // characters inside character and string literals
00230   if (UcnVal < 0xa0 &&
00231       (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) {  // $, @, `
00232     bool IsError = (!Features.CPlusPlus0x || !in_char_string_literal);
00233     if (Diags) {
00234       SourceLocation UcnBeginLoc =
00235         Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
00236                                        Loc.getManager(), Features);
00237       char BasicSCSChar = UcnVal;
00238       if (UcnVal >= 0x20 && UcnVal < 0x7f)
00239         Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_escape_basic_scs :
00240                       diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
00241           << StringRef(&BasicSCSChar, 1);
00242       else
00243         Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_control_character :
00244                       diag::warn_cxx98_compat_literal_ucn_control_character);
00245     }
00246     if (IsError)
00247       return false;
00248   }
00249 
00250   return true;
00251 }
00252 
00253 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
00254 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
00255 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
00256 /// we will likely rework our support for UCN's.
00257 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
00258                             const char *ThisTokEnd,
00259                             char *&ResultBuf, bool &HadError,
00260                             FullSourceLoc Loc, unsigned CharByteWidth,
00261                             DiagnosticsEngine *Diags,
00262                             const LangOptions &Features) {
00263   typedef uint32_t UTF32;
00264   UTF32 UcnVal = 0;
00265   unsigned short UcnLen = 0;
00266   if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
00267                         Loc, Diags, Features, true)) {
00268     HadError = 1;
00269     return;
00270   }
00271 
00272   assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
00273          "only character widths of 1, 2, or 4 bytes supported");
00274 
00275   (void)UcnLen;
00276   assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
00277 
00278   if (CharByteWidth == 4) {
00279     // FIXME: Make the type of the result buffer correct instead of
00280     // using reinterpret_cast.
00281     UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
00282     *ResultPtr = UcnVal;
00283     ResultBuf += 4;
00284     return;
00285   }
00286 
00287   if (CharByteWidth == 2) {
00288     // FIXME: Make the type of the result buffer correct instead of
00289     // using reinterpret_cast.
00290     UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
00291 
00292     if (UcnVal < (UTF32)0xFFFF) {
00293       *ResultPtr = UcnVal;
00294       ResultBuf += 2;
00295       return;
00296     }
00297 
00298     // Convert to UTF16.
00299     UcnVal -= 0x10000;
00300     *ResultPtr     = 0xD800 + (UcnVal >> 10);
00301     *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
00302     ResultBuf += 4;
00303     return;
00304   }
00305 
00306   assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
00307 
00308   // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
00309   // The conversion below was inspired by:
00310   //   http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
00311   // First, we determine how many bytes the result will require.
00312   typedef uint8_t UTF8;
00313 
00314   unsigned short bytesToWrite = 0;
00315   if (UcnVal < (UTF32)0x80)
00316     bytesToWrite = 1;
00317   else if (UcnVal < (UTF32)0x800)
00318     bytesToWrite = 2;
00319   else if (UcnVal < (UTF32)0x10000)
00320     bytesToWrite = 3;
00321   else
00322     bytesToWrite = 4;
00323 
00324   const unsigned byteMask = 0xBF;
00325   const unsigned byteMark = 0x80;
00326 
00327   // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
00328   // into the first byte, depending on how many bytes follow.
00329   static const UTF8 firstByteMark[5] = {
00330     0x00, 0x00, 0xC0, 0xE0, 0xF0
00331   };
00332   // Finally, we write the bytes into ResultBuf.
00333   ResultBuf += bytesToWrite;
00334   switch (bytesToWrite) { // note: everything falls through.
00335     case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
00336     case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
00337     case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
00338     case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
00339   }
00340   // Update the buffer.
00341   ResultBuf += bytesToWrite;
00342 }
00343 
00344 
00345 ///       integer-constant: [C99 6.4.4.1]
00346 ///         decimal-constant integer-suffix
00347 ///         octal-constant integer-suffix
00348 ///         hexadecimal-constant integer-suffix
00349 ///       user-defined-integer-literal: [C++11 lex.ext]
00350 ///         decimal-literal ud-suffix
00351 ///         octal-literal ud-suffix
00352 ///         hexadecimal-literal ud-suffix
00353 ///       decimal-constant:
00354 ///         nonzero-digit
00355 ///         decimal-constant digit
00356 ///       octal-constant:
00357 ///         0
00358 ///         octal-constant octal-digit
00359 ///       hexadecimal-constant:
00360 ///         hexadecimal-prefix hexadecimal-digit
00361 ///         hexadecimal-constant hexadecimal-digit
00362 ///       hexadecimal-prefix: one of
00363 ///         0x 0X
00364 ///       integer-suffix:
00365 ///         unsigned-suffix [long-suffix]
00366 ///         unsigned-suffix [long-long-suffix]
00367 ///         long-suffix [unsigned-suffix]
00368 ///         long-long-suffix [unsigned-sufix]
00369 ///       nonzero-digit:
00370 ///         1 2 3 4 5 6 7 8 9
00371 ///       octal-digit:
00372 ///         0 1 2 3 4 5 6 7
00373 ///       hexadecimal-digit:
00374 ///         0 1 2 3 4 5 6 7 8 9
00375 ///         a b c d e f
00376 ///         A B C D E F
00377 ///       unsigned-suffix: one of
00378 ///         u U
00379 ///       long-suffix: one of
00380 ///         l L
00381 ///       long-long-suffix: one of
00382 ///         ll LL
00383 ///
00384 ///       floating-constant: [C99 6.4.4.2]
00385 ///         TODO: add rules...
00386 ///
00387 NumericLiteralParser::
00388 NumericLiteralParser(const char *begin, const char *end,
00389                      SourceLocation TokLoc, Preprocessor &pp)
00390   : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
00391 
00392   // This routine assumes that the range begin/end matches the regex for integer
00393   // and FP constants (specifically, the 'pp-number' regex), and assumes that
00394   // the byte at "*end" is both valid and not part of the regex.  Because of
00395   // this, it doesn't have to check for 'overscan' in various places.
00396   assert(!isalnum(*end) && *end != '.' && *end != '_' &&
00397          "Lexer didn't maximally munch?");
00398 
00399   s = DigitsBegin = begin;
00400   saw_exponent = false;
00401   saw_period = false;
00402   saw_ud_suffix = false;
00403   isLong = false;
00404   isUnsigned = false;
00405   isLongLong = false;
00406   isFloat = false;
00407   isImaginary = false;
00408   isMicrosoftInteger = false;
00409   hadError = false;
00410 
00411   if (*s == '0') { // parse radix
00412     ParseNumberStartingWithZero(TokLoc);
00413     if (hadError)
00414       return;
00415   } else { // the first digit is non-zero
00416     radix = 10;
00417     s = SkipDigits(s);
00418     if (s == ThisTokEnd) {
00419       // Done.
00420     } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
00421       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
00422               diag::err_invalid_decimal_digit) << StringRef(s, 1);
00423       hadError = true;
00424       return;
00425     } else if (*s == '.') {
00426       s++;
00427       saw_period = true;
00428       s = SkipDigits(s);
00429     }
00430     if ((*s == 'e' || *s == 'E')) { // exponent
00431       const char *Exponent = s;
00432       s++;
00433       saw_exponent = true;
00434       if (*s == '+' || *s == '-')  s++; // sign
00435       const char *first_non_digit = SkipDigits(s);
00436       if (first_non_digit != s) {
00437         s = first_non_digit;
00438       } else {
00439         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
00440                 diag::err_exponent_has_no_digits);
00441         hadError = true;
00442         return;
00443       }
00444     }
00445   }
00446 
00447   SuffixBegin = s;
00448 
00449   // Parse the suffix.  At this point we can classify whether we have an FP or
00450   // integer constant.
00451   bool isFPConstant = isFloatingLiteral();
00452 
00453   // Loop over all of the characters of the suffix.  If we see something bad,
00454   // we break out of the loop.
00455   for (; s != ThisTokEnd; ++s) {
00456     switch (*s) {
00457     case 'f':      // FP Suffix for "float"
00458     case 'F':
00459       if (!isFPConstant) break;  // Error for integer constant.
00460       if (isFloat || isLong) break; // FF, LF invalid.
00461       isFloat = true;
00462       continue;  // Success.
00463     case 'u':
00464     case 'U':
00465       if (isFPConstant) break;  // Error for floating constant.
00466       if (isUnsigned) break;    // Cannot be repeated.
00467       isUnsigned = true;
00468       continue;  // Success.
00469     case 'l':
00470     case 'L':
00471       if (isLong || isLongLong) break;  // Cannot be repeated.
00472       if (isFloat) break;               // LF invalid.
00473 
00474       // Check for long long.  The L's need to be adjacent and the same case.
00475       if (s+1 != ThisTokEnd && s[1] == s[0]) {
00476         if (isFPConstant) break;        // long long invalid for floats.
00477         isLongLong = true;
00478         ++s;  // Eat both of them.
00479       } else {
00480         isLong = true;
00481       }
00482       continue;  // Success.
00483     case 'i':
00484     case 'I':
00485       if (PP.getLangOpts().MicrosoftExt) {
00486         if (isFPConstant || isLong || isLongLong) break;
00487 
00488         // Allow i8, i16, i32, i64, and i128.
00489         if (s + 1 != ThisTokEnd) {
00490           switch (s[1]) {
00491             case '8':
00492               s += 2; // i8 suffix
00493               isMicrosoftInteger = true;
00494               break;
00495             case '1':
00496               if (s + 2 == ThisTokEnd) break;
00497               if (s[2] == '6') {
00498                 s += 3; // i16 suffix
00499                 isMicrosoftInteger = true;
00500               }
00501               else if (s[2] == '2') {
00502                 if (s + 3 == ThisTokEnd) break;
00503                 if (s[3] == '8') {
00504                   s += 4; // i128 suffix
00505                   isMicrosoftInteger = true;
00506                 }
00507               }
00508               break;
00509             case '3':
00510               if (s + 2 == ThisTokEnd) break;
00511               if (s[2] == '2') {
00512                 s += 3; // i32 suffix
00513                 isLong = true;
00514                 isMicrosoftInteger = true;
00515               }
00516               break;
00517             case '6':
00518               if (s + 2 == ThisTokEnd) break;
00519               if (s[2] == '4') {
00520                 s += 3; // i64 suffix
00521                 isLongLong = true;
00522                 isMicrosoftInteger = true;
00523               }
00524               break;
00525             default:
00526               break;
00527           }
00528           break;
00529         }
00530       }
00531       // fall through.
00532     case 'j':
00533     case 'J':
00534       if (isImaginary) break;   // Cannot be repeated.
00535       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
00536               diag::ext_imaginary_constant);
00537       isImaginary = true;
00538       continue;  // Success.
00539     }
00540     // If we reached here, there was an error or a ud-suffix.
00541     break;
00542   }
00543 
00544   if (s != ThisTokEnd) {
00545     if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
00546       // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
00547       // with an '_' are ill-formed.
00548       saw_ud_suffix = true;
00549       return;
00550     }
00551 
00552     // Report an error if there are any.
00553     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin-begin),
00554             isFPConstant ? diag::err_invalid_suffix_float_constant :
00555                            diag::err_invalid_suffix_integer_constant)
00556       << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
00557     hadError = true;
00558     return;
00559   }
00560 }
00561 
00562 /// ParseNumberStartingWithZero - This method is called when the first character
00563 /// of the number is found to be a zero.  This means it is either an octal
00564 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
00565 /// a floating point number (01239.123e4).  Eat the prefix, determining the
00566 /// radix etc.
00567 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
00568   assert(s[0] == '0' && "Invalid method call");
00569   s++;
00570 
00571   // Handle a hex number like 0x1234.
00572   if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
00573     s++;
00574     radix = 16;
00575     DigitsBegin = s;
00576     s = SkipHexDigits(s);
00577     bool noSignificand = (s == DigitsBegin);
00578     if (s == ThisTokEnd) {
00579       // Done.
00580     } else if (*s == '.') {
00581       s++;
00582       saw_period = true;
00583       const char *floatDigitsBegin = s;
00584       s = SkipHexDigits(s);
00585       noSignificand &= (floatDigitsBegin == s);
00586     }
00587 
00588     if (noSignificand) {
00589       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), \
00590         diag::err_hexconstant_requires_digits);
00591       hadError = true;
00592       return;
00593     }
00594 
00595     // A binary exponent can appear with or with a '.'. If dotted, the
00596     // binary exponent is required.
00597     if (*s == 'p' || *s == 'P') {
00598       const char *Exponent = s;
00599       s++;
00600       saw_exponent = true;
00601       if (*s == '+' || *s == '-')  s++; // sign
00602       const char *first_non_digit = SkipDigits(s);
00603       if (first_non_digit == s) {
00604         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
00605                 diag::err_exponent_has_no_digits);
00606         hadError = true;
00607         return;
00608       }
00609       s = first_non_digit;
00610 
00611       if (!PP.getLangOpts().HexFloats)
00612         PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
00613     } else if (saw_period) {
00614       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
00615               diag::err_hexconstant_requires_exponent);
00616       hadError = true;
00617     }
00618     return;
00619   }
00620 
00621   // Handle simple binary numbers 0b01010
00622   if (*s == 'b' || *s == 'B') {
00623     // 0b101010 is a GCC extension.
00624     PP.Diag(TokLoc, diag::ext_binary_literal);
00625     ++s;
00626     radix = 2;
00627     DigitsBegin = s;
00628     s = SkipBinaryDigits(s);
00629     if (s == ThisTokEnd) {
00630       // Done.
00631     } else if (isxdigit(*s)) {
00632       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
00633               diag::err_invalid_binary_digit) << StringRef(s, 1);
00634       hadError = true;
00635     }
00636     // Other suffixes will be diagnosed by the caller.
00637     return;
00638   }
00639 
00640   // For now, the radix is set to 8. If we discover that we have a
00641   // floating point constant, the radix will change to 10. Octal floating
00642   // point constants are not permitted (only decimal and hexadecimal).
00643   radix = 8;
00644   DigitsBegin = s;
00645   s = SkipOctalDigits(s);
00646   if (s == ThisTokEnd)
00647     return; // Done, simple octal number like 01234
00648 
00649   // If we have some other non-octal digit that *is* a decimal digit, see if
00650   // this is part of a floating point number like 094.123 or 09e1.
00651   if (isdigit(*s)) {
00652     const char *EndDecimal = SkipDigits(s);
00653     if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
00654       s = EndDecimal;
00655       radix = 10;
00656     }
00657   }
00658 
00659   // If we have a hex digit other than 'e' (which denotes a FP exponent) then
00660   // the code is using an incorrect base.
00661   if (isxdigit(*s) && *s != 'e' && *s != 'E') {
00662     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
00663             diag::err_invalid_octal_digit) << StringRef(s, 1);
00664     hadError = true;
00665     return;
00666   }
00667 
00668   if (*s == '.') {
00669     s++;
00670     radix = 10;
00671     saw_period = true;
00672     s = SkipDigits(s); // Skip suffix.
00673   }
00674   if (*s == 'e' || *s == 'E') { // exponent
00675     const char *Exponent = s;
00676     s++;
00677     radix = 10;
00678     saw_exponent = true;
00679     if (*s == '+' || *s == '-')  s++; // sign
00680     const char *first_non_digit = SkipDigits(s);
00681     if (first_non_digit != s) {
00682       s = first_non_digit;
00683     } else {
00684       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
00685               diag::err_exponent_has_no_digits);
00686       hadError = true;
00687       return;
00688     }
00689   }
00690 }
00691 
00692 
00693 /// GetIntegerValue - Convert this numeric literal value to an APInt that
00694 /// matches Val's input width.  If there is an overflow, set Val to the low bits
00695 /// of the result and return true.  Otherwise, return false.
00696 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
00697   // Fast path: Compute a conservative bound on the maximum number of
00698   // bits per digit in this radix. If we can't possibly overflow a
00699   // uint64 based on that bound then do the simple conversion to
00700   // integer. This avoids the expensive overflow checking below, and
00701   // handles the common cases that matter (small decimal integers and
00702   // hex/octal values which don't overflow).
00703   unsigned MaxBitsPerDigit = 1;
00704   while ((1U << MaxBitsPerDigit) < radix)
00705     MaxBitsPerDigit += 1;
00706   if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
00707     uint64_t N = 0;
00708     for (s = DigitsBegin; s != SuffixBegin; ++s)
00709       N = N*radix + HexDigitValue(*s);
00710 
00711     // This will truncate the value to Val's input width. Simply check
00712     // for overflow by comparing.
00713     Val = N;
00714     return Val.getZExtValue() != N;
00715   }
00716 
00717   Val = 0;
00718   s = DigitsBegin;
00719 
00720   llvm::APInt RadixVal(Val.getBitWidth(), radix);
00721   llvm::APInt CharVal(Val.getBitWidth(), 0);
00722   llvm::APInt OldVal = Val;
00723 
00724   bool OverflowOccurred = false;
00725   while (s < SuffixBegin) {
00726     unsigned C = HexDigitValue(*s++);
00727 
00728     // If this letter is out of bound for this radix, reject it.
00729     assert(C < radix && "NumericLiteralParser ctor should have rejected this");
00730 
00731     CharVal = C;
00732 
00733     // Add the digit to the value in the appropriate radix.  If adding in digits
00734     // made the value smaller, then this overflowed.
00735     OldVal = Val;
00736 
00737     // Multiply by radix, did overflow occur on the multiply?
00738     Val *= RadixVal;
00739     OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
00740 
00741     // Add value, did overflow occur on the value?
00742     //   (a + b) ult b  <=> overflow
00743     Val += CharVal;
00744     OverflowOccurred |= Val.ult(CharVal);
00745   }
00746   return OverflowOccurred;
00747 }
00748 
00749 llvm::APFloat::opStatus
00750 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
00751   using llvm::APFloat;
00752 
00753   unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
00754   return Result.convertFromString(StringRef(ThisTokBegin, n),
00755                                   APFloat::rmNearestTiesToEven);
00756 }
00757 
00758 
00759 ///       user-defined-character-literal: [C++11 lex.ext]
00760 ///         character-literal ud-suffix
00761 ///       ud-suffix:
00762 ///         identifier
00763 ///       character-literal: [C++11 lex.ccon]
00764 ///         ' c-char-sequence '
00765 ///         u' c-char-sequence '
00766 ///         U' c-char-sequence '
00767 ///         L' c-char-sequence '
00768 ///       c-char-sequence:
00769 ///         c-char
00770 ///         c-char-sequence c-char
00771 ///       c-char:
00772 ///         any member of the source character set except the single-quote ',
00773 ///           backslash \, or new-line character
00774 ///         escape-sequence
00775 ///         universal-character-name
00776 ///       escape-sequence:
00777 ///         simple-escape-sequence
00778 ///         octal-escape-sequence
00779 ///         hexadecimal-escape-sequence
00780 ///       simple-escape-sequence:
00781 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
00782 ///       octal-escape-sequence:
00783 ///         \ octal-digit
00784 ///         \ octal-digit octal-digit
00785 ///         \ octal-digit octal-digit octal-digit
00786 ///       hexadecimal-escape-sequence:
00787 ///         \x hexadecimal-digit
00788 ///         hexadecimal-escape-sequence hexadecimal-digit
00789 ///       universal-character-name: [C++11 lex.charset]
00790 ///         \u hex-quad
00791 ///         \U hex-quad hex-quad
00792 ///       hex-quad:
00793 ///         hex-digit hex-digit hex-digit hex-digit
00794 ///
00795 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
00796                                      SourceLocation Loc, Preprocessor &PP,
00797                                      tok::TokenKind kind) {
00798   // At this point we know that the character matches the regex "(L|u|U)?'.*'".
00799   HadError = false;
00800 
00801   Kind = kind;
00802 
00803   const char *TokBegin = begin;
00804 
00805   // Skip over wide character determinant.
00806   if (Kind != tok::char_constant) {
00807     ++begin;
00808   }
00809 
00810   // Skip over the entry quote.
00811   assert(begin[0] == '\'' && "Invalid token lexed");
00812   ++begin;
00813 
00814   // Remove an optional ud-suffix.
00815   if (end[-1] != '\'') {
00816     const char *UDSuffixEnd = end;
00817     do {
00818       --end;
00819     } while (end[-1] != '\'');
00820     UDSuffixBuf.assign(end, UDSuffixEnd);
00821     UDSuffixOffset = end - TokBegin;
00822   }
00823 
00824   // Trim the ending quote.
00825   assert(end != begin && "Invalid token lexed");
00826   --end;
00827 
00828   // FIXME: The "Value" is an uint64_t so we can handle char literals of
00829   // up to 64-bits.
00830   // FIXME: This extensively assumes that 'char' is 8-bits.
00831   assert(PP.getTargetInfo().getCharWidth() == 8 &&
00832          "Assumes char is 8 bits");
00833   assert(PP.getTargetInfo().getIntWidth() <= 64 &&
00834          (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
00835          "Assumes sizeof(int) on target is <= 64 and a multiple of char");
00836   assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
00837          "Assumes sizeof(wchar) on target is <= 64");
00838 
00839   SmallVector<uint32_t,4> codepoint_buffer;
00840   codepoint_buffer.resize(end-begin);
00841   uint32_t *buffer_begin = &codepoint_buffer.front();
00842   uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
00843 
00844   // Unicode escapes representing characters that cannot be correctly
00845   // represented in a single code unit are disallowed in character literals
00846   // by this implementation.
00847   uint32_t largest_character_for_kind;
00848   if (tok::wide_char_constant == Kind) {
00849     largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
00850   } else if (tok::utf16_char_constant == Kind) {
00851     largest_character_for_kind = 0xFFFF;
00852   } else if (tok::utf32_char_constant == Kind) {
00853     largest_character_for_kind = 0x10FFFF;
00854   } else {
00855     largest_character_for_kind = 0x7Fu;
00856   }
00857 
00858   while (begin!=end) {
00859     // Is this a span of non-escape characters?
00860     if (begin[0] != '\\') {
00861       char const *start = begin;
00862       do {
00863         ++begin;
00864       } while (begin != end && *begin != '\\');
00865 
00866       char const *tmp_in_start = start;
00867       uint32_t *tmp_out_start = buffer_begin;
00868       ConversionResult res =
00869       ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
00870                          reinterpret_cast<UTF8 const *>(begin),
00871                          &buffer_begin,buffer_end,strictConversion);
00872       if (res!=conversionOK) {
00873         // If we see bad encoding for unprefixed character literals, warn and 
00874         // simply copy the byte values, for compatibility with gcc and 
00875         // older versions of clang.
00876         bool NoErrorOnBadEncoding = isAscii();
00877         unsigned Msg = diag::err_bad_character_encoding;
00878         if (NoErrorOnBadEncoding)
00879           Msg = diag::warn_bad_character_encoding;
00880         PP.Diag(Loc, Msg);
00881         if (NoErrorOnBadEncoding) {
00882           start = tmp_in_start;
00883           buffer_begin = tmp_out_start;
00884           for ( ; start != begin; ++start, ++buffer_begin)
00885             *buffer_begin = static_cast<uint8_t>(*start);
00886         } else {
00887           HadError = true;
00888         }
00889       } else {
00890         for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
00891           if (*tmp_out_start > largest_character_for_kind) {
00892             HadError = true;
00893             PP.Diag(Loc, diag::err_character_too_large);
00894           }
00895         }
00896       }
00897 
00898       continue;
00899     }
00900     // Is this a Universal Character Name excape?
00901     if (begin[1] == 'u' || begin[1] == 'U') {
00902       unsigned short UcnLen = 0;
00903       if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
00904                             FullSourceLoc(Loc, PP.getSourceManager()),
00905                             &PP.getDiagnostics(), PP.getLangOpts(),
00906                             true))
00907       {
00908         HadError = true;
00909       } else if (*buffer_begin > largest_character_for_kind) {
00910         HadError = true;
00911         PP.Diag(Loc,diag::err_character_too_large);
00912       }
00913 
00914       ++buffer_begin;
00915       continue;
00916     }
00917     unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
00918     uint64_t result =
00919     ProcessCharEscape(begin, end, HadError,
00920                       FullSourceLoc(Loc,PP.getSourceManager()),
00921                       CharWidth, &PP.getDiagnostics());
00922     *buffer_begin++ = result;
00923   }
00924 
00925   unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
00926 
00927   if (NumCharsSoFar > 1) {
00928     if (isWide())
00929       PP.Diag(Loc, diag::warn_extraneous_char_constant);
00930     else if (isAscii() && NumCharsSoFar == 4)
00931       PP.Diag(Loc, diag::ext_four_char_character_literal);
00932     else if (isAscii())
00933       PP.Diag(Loc, diag::ext_multichar_character_literal);
00934     else
00935       PP.Diag(Loc, diag::err_multichar_utf_character_literal);
00936     IsMultiChar = true;
00937   } else
00938     IsMultiChar = false;
00939 
00940   llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
00941 
00942   // Narrow character literals act as though their value is concatenated
00943   // in this implementation, but warn on overflow.
00944   bool multi_char_too_long = false;
00945   if (isAscii() && isMultiChar()) {
00946     LitVal = 0;
00947     for (size_t i=0;i<NumCharsSoFar;++i) {
00948       // check for enough leading zeros to shift into
00949       multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
00950       LitVal <<= 8;
00951       LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
00952     }
00953   } else if (NumCharsSoFar > 0) {
00954     // otherwise just take the last character
00955     LitVal = buffer_begin[-1];
00956   }
00957 
00958   if (!HadError && multi_char_too_long) {
00959     PP.Diag(Loc,diag::warn_char_constant_too_large);
00960   }
00961 
00962   // Transfer the value from APInt to uint64_t
00963   Value = LitVal.getZExtValue();
00964 
00965   // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
00966   // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
00967   // character constants are not sign extended in the this implementation:
00968   // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
00969   if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
00970       PP.getLangOpts().CharIsSigned)
00971     Value = (signed char)Value;
00972 }
00973 
00974 
00975 ///       string-literal: [C++0x lex.string]
00976 ///         encoding-prefix " [s-char-sequence] "
00977 ///         encoding-prefix R raw-string
00978 ///       encoding-prefix:
00979 ///         u8
00980 ///         u
00981 ///         U
00982 ///         L
00983 ///       s-char-sequence:
00984 ///         s-char
00985 ///         s-char-sequence s-char
00986 ///       s-char:
00987 ///         any member of the source character set except the double-quote ",
00988 ///           backslash \, or new-line character
00989 ///         escape-sequence
00990 ///         universal-character-name
00991 ///       raw-string:
00992 ///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
00993 ///       r-char-sequence:
00994 ///         r-char
00995 ///         r-char-sequence r-char
00996 ///       r-char:
00997 ///         any member of the source character set, except a right parenthesis )
00998 ///           followed by the initial d-char-sequence (which may be empty)
00999 ///           followed by a double quote ".
01000 ///       d-char-sequence:
01001 ///         d-char
01002 ///         d-char-sequence d-char
01003 ///       d-char:
01004 ///         any member of the basic source character set except:
01005 ///           space, the left parenthesis (, the right parenthesis ),
01006 ///           the backslash \, and the control characters representing horizontal
01007 ///           tab, vertical tab, form feed, and newline.
01008 ///       escape-sequence: [C++0x lex.ccon]
01009 ///         simple-escape-sequence
01010 ///         octal-escape-sequence
01011 ///         hexadecimal-escape-sequence
01012 ///       simple-escape-sequence:
01013 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
01014 ///       octal-escape-sequence:
01015 ///         \ octal-digit
01016 ///         \ octal-digit octal-digit
01017 ///         \ octal-digit octal-digit octal-digit
01018 ///       hexadecimal-escape-sequence:
01019 ///         \x hexadecimal-digit
01020 ///         hexadecimal-escape-sequence hexadecimal-digit
01021 ///       universal-character-name:
01022 ///         \u hex-quad
01023 ///         \U hex-quad hex-quad
01024 ///       hex-quad:
01025 ///         hex-digit hex-digit hex-digit hex-digit
01026 ///
01027 StringLiteralParser::
01028 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
01029                     Preprocessor &PP, bool Complain)
01030   : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
01031     Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
01032     MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
01033     ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
01034   init(StringToks, NumStringToks);
01035 }
01036 
01037 void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
01038   // The literal token may have come from an invalid source location (e.g. due
01039   // to a PCH error), in which case the token length will be 0.
01040   if (NumStringToks == 0 || StringToks[0].getLength() < 2)
01041     return DiagnoseLexingError(SourceLocation());
01042 
01043   // Scan all of the string portions, remember the max individual token length,
01044   // computing a bound on the concatenated string length, and see whether any
01045   // piece is a wide-string.  If any of the string portions is a wide-string
01046   // literal, the result is a wide-string literal [C99 6.4.5p4].
01047   assert(NumStringToks && "expected at least one token");
01048   MaxTokenLength = StringToks[0].getLength();
01049   assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
01050   SizeBound = StringToks[0].getLength()-2;  // -2 for "".
01051   Kind = StringToks[0].getKind();
01052 
01053   hadError = false;
01054 
01055   // Implement Translation Phase #6: concatenation of string literals
01056   /// (C99 5.1.1.2p1).  The common case is only one string fragment.
01057   for (unsigned i = 1; i != NumStringToks; ++i) {
01058     if (StringToks[i].getLength() < 2)
01059       return DiagnoseLexingError(StringToks[i].getLocation());
01060 
01061     // The string could be shorter than this if it needs cleaning, but this is a
01062     // reasonable bound, which is all we need.
01063     assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
01064     SizeBound += StringToks[i].getLength()-2;  // -2 for "".
01065 
01066     // Remember maximum string piece length.
01067     if (StringToks[i].getLength() > MaxTokenLength)
01068       MaxTokenLength = StringToks[i].getLength();
01069 
01070     // Remember if we see any wide or utf-8/16/32 strings.
01071     // Also check for illegal concatenations.
01072     if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
01073       if (isAscii()) {
01074         Kind = StringToks[i].getKind();
01075       } else {
01076         if (Diags)
01077           Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
01078                         diag::err_unsupported_string_concat);
01079         hadError = true;
01080       }
01081     }
01082   }
01083 
01084   // Include space for the null terminator.
01085   ++SizeBound;
01086 
01087   // TODO: K&R warning: "traditional C rejects string constant concatenation"
01088 
01089   // Get the width in bytes of char/wchar_t/char16_t/char32_t
01090   CharByteWidth = getCharWidth(Kind, Target);
01091   assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
01092   CharByteWidth /= 8;
01093 
01094   // The output buffer size needs to be large enough to hold wide characters.
01095   // This is a worst-case assumption which basically corresponds to L"" "long".
01096   SizeBound *= CharByteWidth;
01097 
01098   // Size the temporary buffer to hold the result string data.
01099   ResultBuf.resize(SizeBound);
01100 
01101   // Likewise, but for each string piece.
01102   SmallString<512> TokenBuf;
01103   TokenBuf.resize(MaxTokenLength);
01104 
01105   // Loop over all the strings, getting their spelling, and expanding them to
01106   // wide strings as appropriate.
01107   ResultPtr = &ResultBuf[0];   // Next byte to fill in.
01108 
01109   Pascal = false;
01110 
01111   SourceLocation UDSuffixTokLoc;
01112 
01113   for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
01114     const char *ThisTokBuf = &TokenBuf[0];
01115     // Get the spelling of the token, which eliminates trigraphs, etc.  We know
01116     // that ThisTokBuf points to a buffer that is big enough for the whole token
01117     // and 'spelled' tokens can only shrink.
01118     bool StringInvalid = false;
01119     unsigned ThisTokLen = 
01120       Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
01121                          &StringInvalid);
01122     if (StringInvalid)
01123       return DiagnoseLexingError(StringToks[i].getLocation());
01124 
01125     const char *ThisTokBegin = ThisTokBuf;
01126     const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
01127 
01128     // Remove an optional ud-suffix.
01129     if (ThisTokEnd[-1] != '"') {
01130       const char *UDSuffixEnd = ThisTokEnd;
01131       do {
01132         --ThisTokEnd;
01133       } while (ThisTokEnd[-1] != '"');
01134 
01135       StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
01136 
01137       if (UDSuffixBuf.empty()) {
01138         UDSuffixBuf.assign(UDSuffix);
01139         UDSuffixToken = i;
01140         UDSuffixOffset = ThisTokEnd - ThisTokBuf;
01141         UDSuffixTokLoc = StringToks[i].getLocation();
01142       } else if (!UDSuffixBuf.equals(UDSuffix)) {
01143         // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
01144         // result of a concatenation involving at least one user-defined-string-
01145         // literal, all the participating user-defined-string-literals shall
01146         // have the same ud-suffix.
01147         if (Diags) {
01148           SourceLocation TokLoc = StringToks[i].getLocation();
01149           Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
01150             << UDSuffixBuf << UDSuffix
01151             << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
01152             << SourceRange(TokLoc, TokLoc);
01153         }
01154         hadError = true;
01155       }
01156     }
01157 
01158     // Strip the end quote.
01159     --ThisTokEnd;
01160 
01161     // TODO: Input character set mapping support.
01162 
01163     // Skip marker for wide or unicode strings.
01164     if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
01165       ++ThisTokBuf;
01166       // Skip 8 of u8 marker for utf8 strings.
01167       if (ThisTokBuf[0] == '8')
01168         ++ThisTokBuf;
01169     }
01170 
01171     // Check for raw string
01172     if (ThisTokBuf[0] == 'R') {
01173       ThisTokBuf += 2; // skip R"
01174 
01175       const char *Prefix = ThisTokBuf;
01176       while (ThisTokBuf[0] != '(')
01177         ++ThisTokBuf;
01178       ++ThisTokBuf; // skip '('
01179 
01180       // Remove same number of characters from the end
01181       ThisTokEnd -= ThisTokBuf - Prefix;
01182       assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
01183 
01184       // Copy the string over
01185       if (CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
01186         if (DiagnoseBadString(StringToks[i]))
01187           hadError = true;
01188     } else {
01189       if (ThisTokBuf[0] != '"') {
01190         // The file may have come from PCH and then changed after loading the
01191         // PCH; Fail gracefully.
01192         return DiagnoseLexingError(StringToks[i].getLocation());
01193       }
01194       ++ThisTokBuf; // skip "
01195 
01196       // Check if this is a pascal string
01197       if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
01198           ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
01199 
01200         // If the \p sequence is found in the first token, we have a pascal string
01201         // Otherwise, if we already have a pascal string, ignore the first \p
01202         if (i == 0) {
01203           ++ThisTokBuf;
01204           Pascal = true;
01205         } else if (Pascal)
01206           ThisTokBuf += 2;
01207       }
01208 
01209       while (ThisTokBuf != ThisTokEnd) {
01210         // Is this a span of non-escape characters?
01211         if (ThisTokBuf[0] != '\\') {
01212           const char *InStart = ThisTokBuf;
01213           do {
01214             ++ThisTokBuf;
01215           } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
01216 
01217           // Copy the character span over.
01218           if (CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart)))
01219             if (DiagnoseBadString(StringToks[i]))
01220               hadError = true;
01221           continue;
01222         }
01223         // Is this a Universal Character Name escape?
01224         if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
01225           EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
01226                           ResultPtr, hadError,
01227                           FullSourceLoc(StringToks[i].getLocation(), SM),
01228                           CharByteWidth, Diags, Features);
01229           continue;
01230         }
01231         // Otherwise, this is a non-UCN escape character.  Process it.
01232         unsigned ResultChar =
01233           ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
01234                             FullSourceLoc(StringToks[i].getLocation(), SM),
01235                             CharByteWidth*8, Diags);
01236 
01237         if (CharByteWidth == 4) {
01238           // FIXME: Make the type of the result buffer correct instead of
01239           // using reinterpret_cast.
01240           UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
01241           *ResultWidePtr = ResultChar;
01242           ResultPtr += 4;
01243         } else if (CharByteWidth == 2) {
01244           // FIXME: Make the type of the result buffer correct instead of
01245           // using reinterpret_cast.
01246           UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
01247           *ResultWidePtr = ResultChar & 0xFFFF;
01248           ResultPtr += 2;
01249         } else {
01250           assert(CharByteWidth == 1 && "Unexpected char width");
01251           *ResultPtr++ = ResultChar & 0xFF;
01252         }
01253       }
01254     }
01255   }
01256 
01257   if (Pascal) {
01258     if (CharByteWidth == 4) {
01259       // FIXME: Make the type of the result buffer correct instead of
01260       // using reinterpret_cast.
01261       UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
01262       ResultWidePtr[0] = GetNumStringChars() - 1;
01263     } else if (CharByteWidth == 2) {
01264       // FIXME: Make the type of the result buffer correct instead of
01265       // using reinterpret_cast.
01266       UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
01267       ResultWidePtr[0] = GetNumStringChars() - 1;
01268     } else {
01269       assert(CharByteWidth == 1 && "Unexpected char width");
01270       ResultBuf[0] = GetNumStringChars() - 1;
01271     }
01272 
01273     // Verify that pascal strings aren't too large.
01274     if (GetStringLength() > 256) {
01275       if (Diags) 
01276         Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
01277                       diag::err_pascal_string_too_long)
01278           << SourceRange(StringToks[0].getLocation(),
01279                          StringToks[NumStringToks-1].getLocation());
01280       hadError = true;
01281       return;
01282     }
01283   } else if (Diags) {
01284     // Complain if this string literal has too many characters.
01285     unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
01286     
01287     if (GetNumStringChars() > MaxChars)
01288       Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
01289                     diag::ext_string_too_long)
01290         << GetNumStringChars() << MaxChars
01291         << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
01292         << SourceRange(StringToks[0].getLocation(),
01293                        StringToks[NumStringToks-1].getLocation());
01294   }
01295 }
01296 
01297 
01298 /// copyStringFragment - This function copies from Start to End into ResultPtr.
01299 /// Performs widening for multi-byte characters.
01300 bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
01301   assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
01302   ConversionResult result = conversionOK;
01303   // Copy the character span over.
01304   if (CharByteWidth == 1) {
01305     if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(Fragment.begin()),
01306                            reinterpret_cast<const UTF8*>(Fragment.end())))
01307       result = sourceIllegal;
01308     memcpy(ResultPtr, Fragment.data(), Fragment.size());
01309     ResultPtr += Fragment.size();
01310   } else if (CharByteWidth == 2) {
01311     UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
01312     // FIXME: Make the type of the result buffer correct instead of
01313     // using reinterpret_cast.
01314     UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
01315     ConversionFlags flags = strictConversion;
01316     result = ConvertUTF8toUTF16(
01317       &sourceStart,sourceStart + Fragment.size(),
01318         &targetStart,targetStart + 2*Fragment.size(),flags);
01319     if (result==conversionOK)
01320       ResultPtr = reinterpret_cast<char*>(targetStart);
01321   } else if (CharByteWidth == 4) {
01322     UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
01323     // FIXME: Make the type of the result buffer correct instead of
01324     // using reinterpret_cast.
01325     UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
01326     ConversionFlags flags = strictConversion;
01327     result = ConvertUTF8toUTF32(
01328         &sourceStart,sourceStart + Fragment.size(),
01329         &targetStart,targetStart + 4*Fragment.size(),flags);
01330     if (result==conversionOK)
01331       ResultPtr = reinterpret_cast<char*>(targetStart);
01332   }
01333   assert((result != targetExhausted)
01334          && "ConvertUTF8toUTFXX exhausted target buffer");
01335   return result != conversionOK;
01336 }
01337 
01338 bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
01339   // If we see bad encoding for unprefixed string literals, warn and
01340   // simply copy the byte values, for compatibility with gcc and older
01341   // versions of clang.
01342   bool NoErrorOnBadEncoding = isAscii();
01343   unsigned Msg = NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
01344                                         diag::err_bad_string_encoding;
01345   if (Diags)
01346     Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
01347   return !NoErrorOnBadEncoding;
01348 }
01349 
01350 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
01351   hadError = true;
01352   if (Diags)
01353     Diags->Report(Loc, diag::err_lexing_string);
01354 }
01355 
01356 /// getOffsetOfStringByte - This function returns the offset of the
01357 /// specified byte of the string data represented by Token.  This handles
01358 /// advancing over escape sequences in the string.
01359 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
01360                                                     unsigned ByteNo) const {
01361   // Get the spelling of the token.
01362   SmallString<32> SpellingBuffer;
01363   SpellingBuffer.resize(Tok.getLength());
01364 
01365   bool StringInvalid = false;
01366   const char *SpellingPtr = &SpellingBuffer[0];
01367   unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
01368                                        &StringInvalid);
01369   if (StringInvalid)
01370     return 0;
01371 
01372   assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
01373          SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
01374 
01375 
01376   const char *SpellingStart = SpellingPtr;
01377   const char *SpellingEnd = SpellingPtr+TokLen;
01378 
01379   // Skip over the leading quote.
01380   assert(SpellingPtr[0] == '"' && "Should be a string literal!");
01381   ++SpellingPtr;
01382 
01383   // Skip over bytes until we find the offset we're looking for.
01384   while (ByteNo) {
01385     assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
01386 
01387     // Step over non-escapes simply.
01388     if (*SpellingPtr != '\\') {
01389       ++SpellingPtr;
01390       --ByteNo;
01391       continue;
01392     }
01393 
01394     // Otherwise, this is an escape character.  Advance over it.
01395     bool HadError = false;
01396     ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
01397                       FullSourceLoc(Tok.getLocation(), SM),
01398                       CharByteWidth*8, Diags);
01399     assert(!HadError && "This method isn't valid on erroneous strings");
01400     --ByteNo;
01401   }
01402 
01403   return SpellingPtr-SpellingStart;
01404 }