]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Lex/LiteralSupport.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Lex / LiteralSupport.cpp
1 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the NumericLiteralParser, CharLiteralParser, and
11 // StringLiteralParser interfaces.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Lex/LiteralSupport.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/Lex/LexDiagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Basic/ConvertUTF.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/ErrorHandling.h"
22 using namespace clang;
23
24 /// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
25 /// not valid.
26 static int HexDigitValue(char C) {
27   if (C >= '0' && C <= '9') return C-'0';
28   if (C >= 'a' && C <= 'f') return C-'a'+10;
29   if (C >= 'A' && C <= 'F') return C-'A'+10;
30   return -1;
31 }
32
33 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
34   switch (kind) {
35   default: llvm_unreachable("Unknown token type!");
36   case tok::char_constant:
37   case tok::string_literal:
38   case tok::utf8_string_literal:
39     return Target.getCharWidth();
40   case tok::wide_char_constant:
41   case tok::wide_string_literal:
42     return Target.getWCharWidth();
43   case tok::utf16_char_constant:
44   case tok::utf16_string_literal:
45     return Target.getChar16Width();
46   case tok::utf32_char_constant:
47   case tok::utf32_string_literal:
48     return Target.getChar32Width();
49   }
50 }
51
52 static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
53                                            FullSourceLoc TokLoc,
54                                            const char *TokBegin,
55                                            const char *TokRangeBegin,
56                                            const char *TokRangeEnd) {
57   SourceLocation Begin =
58     Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
59                                    TokLoc.getManager(), Features);
60   SourceLocation End =
61     Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
62                                    TokLoc.getManager(), Features);
63   return CharSourceRange::getCharRange(Begin, End);
64 }
65
66 /// \brief Produce a diagnostic highlighting some portion of a literal.
67 ///
68 /// Emits the diagnostic \p DiagID, highlighting the range of characters from
69 /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
70 /// a substring of a spelling buffer for the token beginning at \p TokBegin.
71 static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
72                               const LangOptions &Features, FullSourceLoc TokLoc,
73                               const char *TokBegin, const char *TokRangeBegin,
74                               const char *TokRangeEnd, unsigned DiagID) {
75   SourceLocation Begin =
76     Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
77                                    TokLoc.getManager(), Features);
78   return Diags->Report(Begin, DiagID) <<
79     MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
80 }
81
82 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
83 /// either a character or a string literal.
84 static unsigned ProcessCharEscape(const char *ThisTokBegin,
85                                   const char *&ThisTokBuf,
86                                   const char *ThisTokEnd, bool &HadError,
87                                   FullSourceLoc Loc, unsigned CharWidth,
88                                   DiagnosticsEngine *Diags,
89                                   const LangOptions &Features) {
90   const char *EscapeBegin = ThisTokBuf;
91
92   // Skip the '\' char.
93   ++ThisTokBuf;
94
95   // We know that this character can't be off the end of the buffer, because
96   // that would have been \", which would not have been the end of string.
97   unsigned ResultChar = *ThisTokBuf++;
98   switch (ResultChar) {
99   // These map to themselves.
100   case '\\': case '\'': case '"': case '?': break;
101
102     // These have fixed mappings.
103   case 'a':
104     // TODO: K&R: the meaning of '\\a' is different in traditional C
105     ResultChar = 7;
106     break;
107   case 'b':
108     ResultChar = 8;
109     break;
110   case 'e':
111     if (Diags)
112       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
113            diag::ext_nonstandard_escape) << "e";
114     ResultChar = 27;
115     break;
116   case 'E':
117     if (Diags)
118       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
119            diag::ext_nonstandard_escape) << "E";
120     ResultChar = 27;
121     break;
122   case 'f':
123     ResultChar = 12;
124     break;
125   case 'n':
126     ResultChar = 10;
127     break;
128   case 'r':
129     ResultChar = 13;
130     break;
131   case 't':
132     ResultChar = 9;
133     break;
134   case 'v':
135     ResultChar = 11;
136     break;
137   case 'x': { // Hex escape.
138     ResultChar = 0;
139     if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
140       if (Diags)
141         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
142              diag::err_hex_escape_no_digits);
143       HadError = 1;
144       break;
145     }
146
147     // Hex escapes are a maximal series of hex digits.
148     bool Overflow = false;
149     for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
150       int CharVal = HexDigitValue(ThisTokBuf[0]);
151       if (CharVal == -1) break;
152       // About to shift out a digit?
153       Overflow |= (ResultChar & 0xF0000000) ? true : false;
154       ResultChar <<= 4;
155       ResultChar |= CharVal;
156     }
157
158     // See if any bits will be truncated when evaluated as a character.
159     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
160       Overflow = true;
161       ResultChar &= ~0U >> (32-CharWidth);
162     }
163
164     // Check for overflow.
165     if (Overflow && Diags)   // Too many digits to fit in
166       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
167            diag::warn_hex_escape_too_large);
168     break;
169   }
170   case '0': case '1': case '2': case '3':
171   case '4': case '5': case '6': case '7': {
172     // Octal escapes.
173     --ThisTokBuf;
174     ResultChar = 0;
175
176     // Octal escapes are a series of octal digits with maximum length 3.
177     // "\0123" is a two digit sequence equal to "\012" "3".
178     unsigned NumDigits = 0;
179     do {
180       ResultChar <<= 3;
181       ResultChar |= *ThisTokBuf++ - '0';
182       ++NumDigits;
183     } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
184              ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
185
186     // Check for overflow.  Reject '\777', but not L'\777'.
187     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
188       if (Diags)
189         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
190              diag::warn_octal_escape_too_large);
191       ResultChar &= ~0U >> (32-CharWidth);
192     }
193     break;
194   }
195
196     // Otherwise, these are not valid escapes.
197   case '(': case '{': case '[': case '%':
198     // GCC accepts these as extensions.  We warn about them as such though.
199     if (Diags)
200       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
201            diag::ext_nonstandard_escape)
202         << std::string(1, ResultChar);
203     break;
204   default:
205     if (Diags == 0)
206       break;
207
208     if (isgraph(ResultChar))
209       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
210            diag::ext_unknown_escape)
211         << std::string(1, ResultChar);
212     else
213       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
214            diag::ext_unknown_escape)
215         << "x" + llvm::utohexstr(ResultChar);
216     break;
217   }
218
219   return ResultChar;
220 }
221
222 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
223 /// return the UTF32.
224 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
225                              const char *ThisTokEnd,
226                              uint32_t &UcnVal, unsigned short &UcnLen,
227                              FullSourceLoc Loc, DiagnosticsEngine *Diags, 
228                              const LangOptions &Features,
229                              bool in_char_string_literal = false) {
230   const char *UcnBegin = ThisTokBuf;
231
232   // Skip the '\u' char's.
233   ThisTokBuf += 2;
234
235   if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
236     if (Diags)
237       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
238            diag::err_ucn_escape_no_digits);
239     return false;
240   }
241   UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
242   unsigned short UcnLenSave = UcnLen;
243   for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
244     int CharVal = HexDigitValue(ThisTokBuf[0]);
245     if (CharVal == -1) break;
246     UcnVal <<= 4;
247     UcnVal |= CharVal;
248   }
249   // If we didn't consume the proper number of digits, there is a problem.
250   if (UcnLenSave) {
251     if (Diags)
252       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
253            diag::err_ucn_escape_incomplete);
254     return false;
255   }
256
257   // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
258   if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
259       UcnVal > 0x10FFFF) {                      // maximum legal UTF32 value
260     if (Diags)
261       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
262            diag::err_ucn_escape_invalid);
263     return false;
264   }
265
266   // C++11 allows UCNs that refer to control characters and basic source
267   // characters inside character and string literals
268   if (UcnVal < 0xa0 &&
269       (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) {  // $, @, `
270     bool IsError = (!Features.CPlusPlus0x || !in_char_string_literal);
271     if (Diags) {
272       char BasicSCSChar = UcnVal;
273       if (UcnVal >= 0x20 && UcnVal < 0x7f)
274         Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
275              IsError ? diag::err_ucn_escape_basic_scs :
276                        diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
277             << StringRef(&BasicSCSChar, 1);
278       else
279         Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
280              IsError ? diag::err_ucn_control_character :
281                        diag::warn_cxx98_compat_literal_ucn_control_character);
282     }
283     if (IsError)
284       return false;
285   }
286
287   if (!Features.CPlusPlus && !Features.C99 && Diags)
288     Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
289          diag::warn_ucn_not_valid_in_c89);
290
291   return true;
292 }
293
294 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
295 /// which this UCN will occupy.
296 static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
297                             const char *ThisTokEnd, unsigned CharByteWidth,
298                             const LangOptions &Features, bool &HadError) {
299   // UTF-32: 4 bytes per escape.
300   if (CharByteWidth == 4)
301     return 4;
302
303   uint32_t UcnVal = 0;
304   unsigned short UcnLen = 0;
305   FullSourceLoc Loc;
306
307   if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
308                         UcnLen, Loc, 0, Features, true)) {
309     HadError = true;
310     return 0;
311   }
312
313   // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
314   if (CharByteWidth == 2)
315     return UcnVal <= 0xFFFF ? 2 : 4;
316
317   // UTF-8.
318   if (UcnVal < 0x80)
319     return 1;
320   if (UcnVal < 0x800)
321     return 2;
322   if (UcnVal < 0x10000)
323     return 3;
324   return 4;
325 }
326
327 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
328 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
329 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
330 /// we will likely rework our support for UCN's.
331 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
332                             const char *ThisTokEnd,
333                             char *&ResultBuf, bool &HadError,
334                             FullSourceLoc Loc, unsigned CharByteWidth,
335                             DiagnosticsEngine *Diags,
336                             const LangOptions &Features) {
337   typedef uint32_t UTF32;
338   UTF32 UcnVal = 0;
339   unsigned short UcnLen = 0;
340   if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
341                         Loc, Diags, Features, true)) {
342     HadError = true;
343     return;
344   }
345
346   assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
347          "only character widths of 1, 2, or 4 bytes supported");
348
349   (void)UcnLen;
350   assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
351
352   if (CharByteWidth == 4) {
353     // FIXME: Make the type of the result buffer correct instead of
354     // using reinterpret_cast.
355     UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
356     *ResultPtr = UcnVal;
357     ResultBuf += 4;
358     return;
359   }
360
361   if (CharByteWidth == 2) {
362     // FIXME: Make the type of the result buffer correct instead of
363     // using reinterpret_cast.
364     UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
365
366     if (UcnVal <= (UTF32)0xFFFF) {
367       *ResultPtr = UcnVal;
368       ResultBuf += 2;
369       return;
370     }
371
372     // Convert to UTF16.
373     UcnVal -= 0x10000;
374     *ResultPtr     = 0xD800 + (UcnVal >> 10);
375     *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
376     ResultBuf += 4;
377     return;
378   }
379
380   assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
381
382   // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
383   // The conversion below was inspired by:
384   //   http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
385   // First, we determine how many bytes the result will require.
386   typedef uint8_t UTF8;
387
388   unsigned short bytesToWrite = 0;
389   if (UcnVal < (UTF32)0x80)
390     bytesToWrite = 1;
391   else if (UcnVal < (UTF32)0x800)
392     bytesToWrite = 2;
393   else if (UcnVal < (UTF32)0x10000)
394     bytesToWrite = 3;
395   else
396     bytesToWrite = 4;
397
398   const unsigned byteMask = 0xBF;
399   const unsigned byteMark = 0x80;
400
401   // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
402   // into the first byte, depending on how many bytes follow.
403   static const UTF8 firstByteMark[5] = {
404     0x00, 0x00, 0xC0, 0xE0, 0xF0
405   };
406   // Finally, we write the bytes into ResultBuf.
407   ResultBuf += bytesToWrite;
408   switch (bytesToWrite) { // note: everything falls through.
409   case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
410   case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
411   case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
412   case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
413   }
414   // Update the buffer.
415   ResultBuf += bytesToWrite;
416 }
417
418
419 ///       integer-constant: [C99 6.4.4.1]
420 ///         decimal-constant integer-suffix
421 ///         octal-constant integer-suffix
422 ///         hexadecimal-constant integer-suffix
423 ///       user-defined-integer-literal: [C++11 lex.ext]
424 ///         decimal-literal ud-suffix
425 ///         octal-literal ud-suffix
426 ///         hexadecimal-literal ud-suffix
427 ///       decimal-constant:
428 ///         nonzero-digit
429 ///         decimal-constant digit
430 ///       octal-constant:
431 ///         0
432 ///         octal-constant octal-digit
433 ///       hexadecimal-constant:
434 ///         hexadecimal-prefix hexadecimal-digit
435 ///         hexadecimal-constant hexadecimal-digit
436 ///       hexadecimal-prefix: one of
437 ///         0x 0X
438 ///       integer-suffix:
439 ///         unsigned-suffix [long-suffix]
440 ///         unsigned-suffix [long-long-suffix]
441 ///         long-suffix [unsigned-suffix]
442 ///         long-long-suffix [unsigned-sufix]
443 ///       nonzero-digit:
444 ///         1 2 3 4 5 6 7 8 9
445 ///       octal-digit:
446 ///         0 1 2 3 4 5 6 7
447 ///       hexadecimal-digit:
448 ///         0 1 2 3 4 5 6 7 8 9
449 ///         a b c d e f
450 ///         A B C D E F
451 ///       unsigned-suffix: one of
452 ///         u U
453 ///       long-suffix: one of
454 ///         l L
455 ///       long-long-suffix: one of
456 ///         ll LL
457 ///
458 ///       floating-constant: [C99 6.4.4.2]
459 ///         TODO: add rules...
460 ///
461 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
462                                            SourceLocation TokLoc,
463                                            Preprocessor &PP)
464   : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
465
466   // This routine assumes that the range begin/end matches the regex for integer
467   // and FP constants (specifically, the 'pp-number' regex), and assumes that
468   // the byte at "*end" is both valid and not part of the regex.  Because of
469   // this, it doesn't have to check for 'overscan' in various places.
470   assert(!isalnum(*ThisTokEnd) && *ThisTokEnd != '.' && *ThisTokEnd != '_' &&
471          "Lexer didn't maximally munch?");
472
473   s = DigitsBegin = ThisTokBegin;
474   saw_exponent = false;
475   saw_period = false;
476   saw_ud_suffix = false;
477   isLong = false;
478   isUnsigned = false;
479   isLongLong = false;
480   isFloat = false;
481   isImaginary = false;
482   isMicrosoftInteger = false;
483   hadError = false;
484
485   if (*s == '0') { // parse radix
486     ParseNumberStartingWithZero(TokLoc);
487     if (hadError)
488       return;
489   } else { // the first digit is non-zero
490     radix = 10;
491     s = SkipDigits(s);
492     if (s == ThisTokEnd) {
493       // Done.
494     } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
495       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
496               diag::err_invalid_decimal_digit) << StringRef(s, 1);
497       hadError = true;
498       return;
499     } else if (*s == '.') {
500       s++;
501       saw_period = true;
502       s = SkipDigits(s);
503     }
504     if ((*s == 'e' || *s == 'E')) { // exponent
505       const char *Exponent = s;
506       s++;
507       saw_exponent = true;
508       if (*s == '+' || *s == '-')  s++; // sign
509       const char *first_non_digit = SkipDigits(s);
510       if (first_non_digit != s) {
511         s = first_non_digit;
512       } else {
513         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
514                 diag::err_exponent_has_no_digits);
515         hadError = true;
516         return;
517       }
518     }
519   }
520
521   SuffixBegin = s;
522
523   // Parse the suffix.  At this point we can classify whether we have an FP or
524   // integer constant.
525   bool isFPConstant = isFloatingLiteral();
526
527   // Loop over all of the characters of the suffix.  If we see something bad,
528   // we break out of the loop.
529   for (; s != ThisTokEnd; ++s) {
530     switch (*s) {
531     case 'f':      // FP Suffix for "float"
532     case 'F':
533       if (!isFPConstant) break;  // Error for integer constant.
534       if (isFloat || isLong) break; // FF, LF invalid.
535       isFloat = true;
536       continue;  // Success.
537     case 'u':
538     case 'U':
539       if (isFPConstant) break;  // Error for floating constant.
540       if (isUnsigned) break;    // Cannot be repeated.
541       isUnsigned = true;
542       continue;  // Success.
543     case 'l':
544     case 'L':
545       if (isLong || isLongLong) break;  // Cannot be repeated.
546       if (isFloat) break;               // LF invalid.
547
548       // Check for long long.  The L's need to be adjacent and the same case.
549       if (s+1 != ThisTokEnd && s[1] == s[0]) {
550         if (isFPConstant) break;        // long long invalid for floats.
551         isLongLong = true;
552         ++s;  // Eat both of them.
553       } else {
554         isLong = true;
555       }
556       continue;  // Success.
557     case 'i':
558     case 'I':
559       if (PP.getLangOpts().MicrosoftExt) {
560         if (isFPConstant || isLong || isLongLong) break;
561
562         // Allow i8, i16, i32, i64, and i128.
563         if (s + 1 != ThisTokEnd) {
564           switch (s[1]) {
565             case '8':
566               s += 2; // i8 suffix
567               isMicrosoftInteger = true;
568               break;
569             case '1':
570               if (s + 2 == ThisTokEnd) break;
571               if (s[2] == '6') {
572                 s += 3; // i16 suffix
573                 isMicrosoftInteger = true;
574               }
575               else if (s[2] == '2') {
576                 if (s + 3 == ThisTokEnd) break;
577                 if (s[3] == '8') {
578                   s += 4; // i128 suffix
579                   isMicrosoftInteger = true;
580                 }
581               }
582               break;
583             case '3':
584               if (s + 2 == ThisTokEnd) break;
585               if (s[2] == '2') {
586                 s += 3; // i32 suffix
587                 isLong = true;
588                 isMicrosoftInteger = true;
589               }
590               break;
591             case '6':
592               if (s + 2 == ThisTokEnd) break;
593               if (s[2] == '4') {
594                 s += 3; // i64 suffix
595                 isLongLong = true;
596                 isMicrosoftInteger = true;
597               }
598               break;
599             default:
600               break;
601           }
602           break;
603         }
604       }
605       // fall through.
606     case 'j':
607     case 'J':
608       if (isImaginary) break;   // Cannot be repeated.
609       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
610               diag::ext_imaginary_constant);
611       isImaginary = true;
612       continue;  // Success.
613     }
614     // If we reached here, there was an error or a ud-suffix.
615     break;
616   }
617
618   if (s != ThisTokEnd) {
619     if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
620       // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
621       // with an '_' are ill-formed.
622       saw_ud_suffix = true;
623       return;
624     }
625
626     // Report an error if there are any.
627     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
628             isFPConstant ? diag::err_invalid_suffix_float_constant :
629                            diag::err_invalid_suffix_integer_constant)
630       << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
631     hadError = true;
632     return;
633   }
634 }
635
636 /// ParseNumberStartingWithZero - This method is called when the first character
637 /// of the number is found to be a zero.  This means it is either an octal
638 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
639 /// a floating point number (01239.123e4).  Eat the prefix, determining the
640 /// radix etc.
641 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
642   assert(s[0] == '0' && "Invalid method call");
643   s++;
644
645   // Handle a hex number like 0x1234.
646   if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
647     s++;
648     radix = 16;
649     DigitsBegin = s;
650     s = SkipHexDigits(s);
651     bool noSignificand = (s == DigitsBegin);
652     if (s == ThisTokEnd) {
653       // Done.
654     } else if (*s == '.') {
655       s++;
656       saw_period = true;
657       const char *floatDigitsBegin = s;
658       s = SkipHexDigits(s);
659       noSignificand &= (floatDigitsBegin == s);
660     }
661
662     if (noSignificand) {
663       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
664         diag::err_hexconstant_requires_digits);
665       hadError = true;
666       return;
667     }
668
669     // A binary exponent can appear with or with a '.'. If dotted, the
670     // binary exponent is required.
671     if (*s == 'p' || *s == 'P') {
672       const char *Exponent = s;
673       s++;
674       saw_exponent = true;
675       if (*s == '+' || *s == '-')  s++; // sign
676       const char *first_non_digit = SkipDigits(s);
677       if (first_non_digit == s) {
678         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
679                 diag::err_exponent_has_no_digits);
680         hadError = true;
681         return;
682       }
683       s = first_non_digit;
684
685       if (!PP.getLangOpts().HexFloats)
686         PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
687     } else if (saw_period) {
688       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
689               diag::err_hexconstant_requires_exponent);
690       hadError = true;
691     }
692     return;
693   }
694
695   // Handle simple binary numbers 0b01010
696   if (*s == 'b' || *s == 'B') {
697     // 0b101010 is a GCC extension.
698     PP.Diag(TokLoc, diag::ext_binary_literal);
699     ++s;
700     radix = 2;
701     DigitsBegin = s;
702     s = SkipBinaryDigits(s);
703     if (s == ThisTokEnd) {
704       // Done.
705     } else if (isxdigit(*s)) {
706       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
707               diag::err_invalid_binary_digit) << StringRef(s, 1);
708       hadError = true;
709     }
710     // Other suffixes will be diagnosed by the caller.
711     return;
712   }
713
714   // For now, the radix is set to 8. If we discover that we have a
715   // floating point constant, the radix will change to 10. Octal floating
716   // point constants are not permitted (only decimal and hexadecimal).
717   radix = 8;
718   DigitsBegin = s;
719   s = SkipOctalDigits(s);
720   if (s == ThisTokEnd)
721     return; // Done, simple octal number like 01234
722
723   // If we have some other non-octal digit that *is* a decimal digit, see if
724   // this is part of a floating point number like 094.123 or 09e1.
725   if (isdigit(*s)) {
726     const char *EndDecimal = SkipDigits(s);
727     if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
728       s = EndDecimal;
729       radix = 10;
730     }
731   }
732
733   // If we have a hex digit other than 'e' (which denotes a FP exponent) then
734   // the code is using an incorrect base.
735   if (isxdigit(*s) && *s != 'e' && *s != 'E') {
736     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
737             diag::err_invalid_octal_digit) << StringRef(s, 1);
738     hadError = true;
739     return;
740   }
741
742   if (*s == '.') {
743     s++;
744     radix = 10;
745     saw_period = true;
746     s = SkipDigits(s); // Skip suffix.
747   }
748   if (*s == 'e' || *s == 'E') { // exponent
749     const char *Exponent = s;
750     s++;
751     radix = 10;
752     saw_exponent = true;
753     if (*s == '+' || *s == '-')  s++; // sign
754     const char *first_non_digit = SkipDigits(s);
755     if (first_non_digit != s) {
756       s = first_non_digit;
757     } else {
758       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
759               diag::err_exponent_has_no_digits);
760       hadError = true;
761       return;
762     }
763   }
764 }
765
766 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
767   switch (Radix) {
768   case 2:
769     return NumDigits <= 64;
770   case 8:
771     return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
772   case 10:
773     return NumDigits <= 19; // floor(log10(2^64))
774   case 16:
775     return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
776   default:
777     llvm_unreachable("impossible Radix");
778   }
779 }
780
781 /// GetIntegerValue - Convert this numeric literal value to an APInt that
782 /// matches Val's input width.  If there is an overflow, set Val to the low bits
783 /// of the result and return true.  Otherwise, return false.
784 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
785   // Fast path: Compute a conservative bound on the maximum number of
786   // bits per digit in this radix. If we can't possibly overflow a
787   // uint64 based on that bound then do the simple conversion to
788   // integer. This avoids the expensive overflow checking below, and
789   // handles the common cases that matter (small decimal integers and
790   // hex/octal values which don't overflow).
791   const unsigned NumDigits = SuffixBegin - DigitsBegin;
792   if (alwaysFitsInto64Bits(radix, NumDigits)) {
793     uint64_t N = 0;
794     for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
795       N = N * radix + HexDigitValue(*Ptr);
796
797     // This will truncate the value to Val's input width. Simply check
798     // for overflow by comparing.
799     Val = N;
800     return Val.getZExtValue() != N;
801   }
802
803   Val = 0;
804   const char *Ptr = DigitsBegin;
805
806   llvm::APInt RadixVal(Val.getBitWidth(), radix);
807   llvm::APInt CharVal(Val.getBitWidth(), 0);
808   llvm::APInt OldVal = Val;
809
810   bool OverflowOccurred = false;
811   while (Ptr < SuffixBegin) {
812     unsigned C = HexDigitValue(*Ptr++);
813
814     // If this letter is out of bound for this radix, reject it.
815     assert(C < radix && "NumericLiteralParser ctor should have rejected this");
816
817     CharVal = C;
818
819     // Add the digit to the value in the appropriate radix.  If adding in digits
820     // made the value smaller, then this overflowed.
821     OldVal = Val;
822
823     // Multiply by radix, did overflow occur on the multiply?
824     Val *= RadixVal;
825     OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
826
827     // Add value, did overflow occur on the value?
828     //   (a + b) ult b  <=> overflow
829     Val += CharVal;
830     OverflowOccurred |= Val.ult(CharVal);
831   }
832   return OverflowOccurred;
833 }
834
835 llvm::APFloat::opStatus
836 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
837   using llvm::APFloat;
838
839   unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
840   return Result.convertFromString(StringRef(ThisTokBegin, n),
841                                   APFloat::rmNearestTiesToEven);
842 }
843
844
845 /// \verbatim
846 ///       user-defined-character-literal: [C++11 lex.ext]
847 ///         character-literal ud-suffix
848 ///       ud-suffix:
849 ///         identifier
850 ///       character-literal: [C++11 lex.ccon]
851 ///         ' c-char-sequence '
852 ///         u' c-char-sequence '
853 ///         U' c-char-sequence '
854 ///         L' c-char-sequence '
855 ///       c-char-sequence:
856 ///         c-char
857 ///         c-char-sequence c-char
858 ///       c-char:
859 ///         any member of the source character set except the single-quote ',
860 ///           backslash \, or new-line character
861 ///         escape-sequence
862 ///         universal-character-name
863 ///       escape-sequence:
864 ///         simple-escape-sequence
865 ///         octal-escape-sequence
866 ///         hexadecimal-escape-sequence
867 ///       simple-escape-sequence:
868 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
869 ///       octal-escape-sequence:
870 ///         \ octal-digit
871 ///         \ octal-digit octal-digit
872 ///         \ octal-digit octal-digit octal-digit
873 ///       hexadecimal-escape-sequence:
874 ///         \x hexadecimal-digit
875 ///         hexadecimal-escape-sequence hexadecimal-digit
876 ///       universal-character-name: [C++11 lex.charset]
877 ///         \u hex-quad
878 ///         \U hex-quad hex-quad
879 ///       hex-quad:
880 ///         hex-digit hex-digit hex-digit hex-digit
881 /// \endverbatim
882 ///
883 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
884                                      SourceLocation Loc, Preprocessor &PP,
885                                      tok::TokenKind kind) {
886   // At this point we know that the character matches the regex "(L|u|U)?'.*'".
887   HadError = false;
888
889   Kind = kind;
890
891   const char *TokBegin = begin;
892
893   // Skip over wide character determinant.
894   if (Kind != tok::char_constant) {
895     ++begin;
896   }
897
898   // Skip over the entry quote.
899   assert(begin[0] == '\'' && "Invalid token lexed");
900   ++begin;
901
902   // Remove an optional ud-suffix.
903   if (end[-1] != '\'') {
904     const char *UDSuffixEnd = end;
905     do {
906       --end;
907     } while (end[-1] != '\'');
908     UDSuffixBuf.assign(end, UDSuffixEnd);
909     UDSuffixOffset = end - TokBegin;
910   }
911
912   // Trim the ending quote.
913   assert(end != begin && "Invalid token lexed");
914   --end;
915
916   // FIXME: The "Value" is an uint64_t so we can handle char literals of
917   // up to 64-bits.
918   // FIXME: This extensively assumes that 'char' is 8-bits.
919   assert(PP.getTargetInfo().getCharWidth() == 8 &&
920          "Assumes char is 8 bits");
921   assert(PP.getTargetInfo().getIntWidth() <= 64 &&
922          (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
923          "Assumes sizeof(int) on target is <= 64 and a multiple of char");
924   assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
925          "Assumes sizeof(wchar) on target is <= 64");
926
927   SmallVector<uint32_t,4> codepoint_buffer;
928   codepoint_buffer.resize(end-begin);
929   uint32_t *buffer_begin = &codepoint_buffer.front();
930   uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
931
932   // Unicode escapes representing characters that cannot be correctly
933   // represented in a single code unit are disallowed in character literals
934   // by this implementation.
935   uint32_t largest_character_for_kind;
936   if (tok::wide_char_constant == Kind) {
937     largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
938   } else if (tok::utf16_char_constant == Kind) {
939     largest_character_for_kind = 0xFFFF;
940   } else if (tok::utf32_char_constant == Kind) {
941     largest_character_for_kind = 0x10FFFF;
942   } else {
943     largest_character_for_kind = 0x7Fu;
944   }
945
946   while (begin!=end) {
947     // Is this a span of non-escape characters?
948     if (begin[0] != '\\') {
949       char const *start = begin;
950       do {
951         ++begin;
952       } while (begin != end && *begin != '\\');
953
954       char const *tmp_in_start = start;
955       uint32_t *tmp_out_start = buffer_begin;
956       ConversionResult res =
957       ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
958                          reinterpret_cast<UTF8 const *>(begin),
959                          &buffer_begin,buffer_end,strictConversion);
960       if (res!=conversionOK) {
961         // If we see bad encoding for unprefixed character literals, warn and 
962         // simply copy the byte values, for compatibility with gcc and 
963         // older versions of clang.
964         bool NoErrorOnBadEncoding = isAscii();
965         unsigned Msg = diag::err_bad_character_encoding;
966         if (NoErrorOnBadEncoding)
967           Msg = diag::warn_bad_character_encoding;
968         PP.Diag(Loc, Msg);
969         if (NoErrorOnBadEncoding) {
970           start = tmp_in_start;
971           buffer_begin = tmp_out_start;
972           for ( ; start != begin; ++start, ++buffer_begin)
973             *buffer_begin = static_cast<uint8_t>(*start);
974         } else {
975           HadError = true;
976         }
977       } else {
978         for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
979           if (*tmp_out_start > largest_character_for_kind) {
980             HadError = true;
981             PP.Diag(Loc, diag::err_character_too_large);
982           }
983         }
984       }
985
986       continue;
987     }
988     // Is this a Universal Character Name excape?
989     if (begin[1] == 'u' || begin[1] == 'U') {
990       unsigned short UcnLen = 0;
991       if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
992                             FullSourceLoc(Loc, PP.getSourceManager()),
993                             &PP.getDiagnostics(), PP.getLangOpts(),
994                             true))
995       {
996         HadError = true;
997       } else if (*buffer_begin > largest_character_for_kind) {
998         HadError = true;
999         PP.Diag(Loc, diag::err_character_too_large);
1000       }
1001
1002       ++buffer_begin;
1003       continue;
1004     }
1005     unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1006     uint64_t result =
1007       ProcessCharEscape(TokBegin, begin, end, HadError,
1008                         FullSourceLoc(Loc,PP.getSourceManager()),
1009                         CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1010     *buffer_begin++ = result;
1011   }
1012
1013   unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
1014
1015   if (NumCharsSoFar > 1) {
1016     if (isWide())
1017       PP.Diag(Loc, diag::warn_extraneous_char_constant);
1018     else if (isAscii() && NumCharsSoFar == 4)
1019       PP.Diag(Loc, diag::ext_four_char_character_literal);
1020     else if (isAscii())
1021       PP.Diag(Loc, diag::ext_multichar_character_literal);
1022     else
1023       PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1024     IsMultiChar = true;
1025   } else
1026     IsMultiChar = false;
1027
1028   llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1029
1030   // Narrow character literals act as though their value is concatenated
1031   // in this implementation, but warn on overflow.
1032   bool multi_char_too_long = false;
1033   if (isAscii() && isMultiChar()) {
1034     LitVal = 0;
1035     for (size_t i=0;i<NumCharsSoFar;++i) {
1036       // check for enough leading zeros to shift into
1037       multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1038       LitVal <<= 8;
1039       LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1040     }
1041   } else if (NumCharsSoFar > 0) {
1042     // otherwise just take the last character
1043     LitVal = buffer_begin[-1];
1044   }
1045
1046   if (!HadError && multi_char_too_long) {
1047     PP.Diag(Loc,diag::warn_char_constant_too_large);
1048   }
1049
1050   // Transfer the value from APInt to uint64_t
1051   Value = LitVal.getZExtValue();
1052
1053   // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1054   // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
1055   // character constants are not sign extended in the this implementation:
1056   // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1057   if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1058       PP.getLangOpts().CharIsSigned)
1059     Value = (signed char)Value;
1060 }
1061
1062 /// \verbatim
1063 ///       string-literal: [C++0x lex.string]
1064 ///         encoding-prefix " [s-char-sequence] "
1065 ///         encoding-prefix R raw-string
1066 ///       encoding-prefix:
1067 ///         u8
1068 ///         u
1069 ///         U
1070 ///         L
1071 ///       s-char-sequence:
1072 ///         s-char
1073 ///         s-char-sequence s-char
1074 ///       s-char:
1075 ///         any member of the source character set except the double-quote ",
1076 ///           backslash \, or new-line character
1077 ///         escape-sequence
1078 ///         universal-character-name
1079 ///       raw-string:
1080 ///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
1081 ///       r-char-sequence:
1082 ///         r-char
1083 ///         r-char-sequence r-char
1084 ///       r-char:
1085 ///         any member of the source character set, except a right parenthesis )
1086 ///           followed by the initial d-char-sequence (which may be empty)
1087 ///           followed by a double quote ".
1088 ///       d-char-sequence:
1089 ///         d-char
1090 ///         d-char-sequence d-char
1091 ///       d-char:
1092 ///         any member of the basic source character set except:
1093 ///           space, the left parenthesis (, the right parenthesis ),
1094 ///           the backslash \, and the control characters representing horizontal
1095 ///           tab, vertical tab, form feed, and newline.
1096 ///       escape-sequence: [C++0x lex.ccon]
1097 ///         simple-escape-sequence
1098 ///         octal-escape-sequence
1099 ///         hexadecimal-escape-sequence
1100 ///       simple-escape-sequence:
1101 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
1102 ///       octal-escape-sequence:
1103 ///         \ octal-digit
1104 ///         \ octal-digit octal-digit
1105 ///         \ octal-digit octal-digit octal-digit
1106 ///       hexadecimal-escape-sequence:
1107 ///         \x hexadecimal-digit
1108 ///         hexadecimal-escape-sequence hexadecimal-digit
1109 ///       universal-character-name:
1110 ///         \u hex-quad
1111 ///         \U hex-quad hex-quad
1112 ///       hex-quad:
1113 ///         hex-digit hex-digit hex-digit hex-digit
1114 /// \endverbatim
1115 ///
1116 StringLiteralParser::
1117 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1118                     Preprocessor &PP, bool Complain)
1119   : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1120     Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1121     MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1122     ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1123   init(StringToks, NumStringToks);
1124 }
1125
1126 void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1127   // The literal token may have come from an invalid source location (e.g. due
1128   // to a PCH error), in which case the token length will be 0.
1129   if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1130     return DiagnoseLexingError(SourceLocation());
1131
1132   // Scan all of the string portions, remember the max individual token length,
1133   // computing a bound on the concatenated string length, and see whether any
1134   // piece is a wide-string.  If any of the string portions is a wide-string
1135   // literal, the result is a wide-string literal [C99 6.4.5p4].
1136   assert(NumStringToks && "expected at least one token");
1137   MaxTokenLength = StringToks[0].getLength();
1138   assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1139   SizeBound = StringToks[0].getLength()-2;  // -2 for "".
1140   Kind = StringToks[0].getKind();
1141
1142   hadError = false;
1143
1144   // Implement Translation Phase #6: concatenation of string literals
1145   /// (C99 5.1.1.2p1).  The common case is only one string fragment.
1146   for (unsigned i = 1; i != NumStringToks; ++i) {
1147     if (StringToks[i].getLength() < 2)
1148       return DiagnoseLexingError(StringToks[i].getLocation());
1149
1150     // The string could be shorter than this if it needs cleaning, but this is a
1151     // reasonable bound, which is all we need.
1152     assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1153     SizeBound += StringToks[i].getLength()-2;  // -2 for "".
1154
1155     // Remember maximum string piece length.
1156     if (StringToks[i].getLength() > MaxTokenLength)
1157       MaxTokenLength = StringToks[i].getLength();
1158
1159     // Remember if we see any wide or utf-8/16/32 strings.
1160     // Also check for illegal concatenations.
1161     if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1162       if (isAscii()) {
1163         Kind = StringToks[i].getKind();
1164       } else {
1165         if (Diags)
1166           Diags->Report(StringToks[i].getLocation(),
1167                         diag::err_unsupported_string_concat);
1168         hadError = true;
1169       }
1170     }
1171   }
1172
1173   // Include space for the null terminator.
1174   ++SizeBound;
1175
1176   // TODO: K&R warning: "traditional C rejects string constant concatenation"
1177
1178   // Get the width in bytes of char/wchar_t/char16_t/char32_t
1179   CharByteWidth = getCharWidth(Kind, Target);
1180   assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1181   CharByteWidth /= 8;
1182
1183   // The output buffer size needs to be large enough to hold wide characters.
1184   // This is a worst-case assumption which basically corresponds to L"" "long".
1185   SizeBound *= CharByteWidth;
1186
1187   // Size the temporary buffer to hold the result string data.
1188   ResultBuf.resize(SizeBound);
1189
1190   // Likewise, but for each string piece.
1191   SmallString<512> TokenBuf;
1192   TokenBuf.resize(MaxTokenLength);
1193
1194   // Loop over all the strings, getting their spelling, and expanding them to
1195   // wide strings as appropriate.
1196   ResultPtr = &ResultBuf[0];   // Next byte to fill in.
1197
1198   Pascal = false;
1199
1200   SourceLocation UDSuffixTokLoc;
1201
1202   for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1203     const char *ThisTokBuf = &TokenBuf[0];
1204     // Get the spelling of the token, which eliminates trigraphs, etc.  We know
1205     // that ThisTokBuf points to a buffer that is big enough for the whole token
1206     // and 'spelled' tokens can only shrink.
1207     bool StringInvalid = false;
1208     unsigned ThisTokLen = 
1209       Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1210                          &StringInvalid);
1211     if (StringInvalid)
1212       return DiagnoseLexingError(StringToks[i].getLocation());
1213
1214     const char *ThisTokBegin = ThisTokBuf;
1215     const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1216
1217     // Remove an optional ud-suffix.
1218     if (ThisTokEnd[-1] != '"') {
1219       const char *UDSuffixEnd = ThisTokEnd;
1220       do {
1221         --ThisTokEnd;
1222       } while (ThisTokEnd[-1] != '"');
1223
1224       StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1225
1226       if (UDSuffixBuf.empty()) {
1227         UDSuffixBuf.assign(UDSuffix);
1228         UDSuffixToken = i;
1229         UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1230         UDSuffixTokLoc = StringToks[i].getLocation();
1231       } else if (!UDSuffixBuf.equals(UDSuffix)) {
1232         // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1233         // result of a concatenation involving at least one user-defined-string-
1234         // literal, all the participating user-defined-string-literals shall
1235         // have the same ud-suffix.
1236         if (Diags) {
1237           SourceLocation TokLoc = StringToks[i].getLocation();
1238           Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1239             << UDSuffixBuf << UDSuffix
1240             << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1241             << SourceRange(TokLoc, TokLoc);
1242         }
1243         hadError = true;
1244       }
1245     }
1246
1247     // Strip the end quote.
1248     --ThisTokEnd;
1249
1250     // TODO: Input character set mapping support.
1251
1252     // Skip marker for wide or unicode strings.
1253     if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1254       ++ThisTokBuf;
1255       // Skip 8 of u8 marker for utf8 strings.
1256       if (ThisTokBuf[0] == '8')
1257         ++ThisTokBuf;
1258     }
1259
1260     // Check for raw string
1261     if (ThisTokBuf[0] == 'R') {
1262       ThisTokBuf += 2; // skip R"
1263
1264       const char *Prefix = ThisTokBuf;
1265       while (ThisTokBuf[0] != '(')
1266         ++ThisTokBuf;
1267       ++ThisTokBuf; // skip '('
1268
1269       // Remove same number of characters from the end
1270       ThisTokEnd -= ThisTokBuf - Prefix;
1271       assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1272
1273       // Copy the string over
1274       if (CopyStringFragment(StringToks[i], ThisTokBegin,
1275                              StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1276         hadError = true;
1277     } else {
1278       if (ThisTokBuf[0] != '"') {
1279         // The file may have come from PCH and then changed after loading the
1280         // PCH; Fail gracefully.
1281         return DiagnoseLexingError(StringToks[i].getLocation());
1282       }
1283       ++ThisTokBuf; // skip "
1284
1285       // Check if this is a pascal string
1286       if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1287           ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1288
1289         // If the \p sequence is found in the first token, we have a pascal string
1290         // Otherwise, if we already have a pascal string, ignore the first \p
1291         if (i == 0) {
1292           ++ThisTokBuf;
1293           Pascal = true;
1294         } else if (Pascal)
1295           ThisTokBuf += 2;
1296       }
1297
1298       while (ThisTokBuf != ThisTokEnd) {
1299         // Is this a span of non-escape characters?
1300         if (ThisTokBuf[0] != '\\') {
1301           const char *InStart = ThisTokBuf;
1302           do {
1303             ++ThisTokBuf;
1304           } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1305
1306           // Copy the character span over.
1307           if (CopyStringFragment(StringToks[i], ThisTokBegin,
1308                                  StringRef(InStart, ThisTokBuf - InStart)))
1309             hadError = true;
1310           continue;
1311         }
1312         // Is this a Universal Character Name escape?
1313         if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1314           EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1315                           ResultPtr, hadError,
1316                           FullSourceLoc(StringToks[i].getLocation(), SM),
1317                           CharByteWidth, Diags, Features);
1318           continue;
1319         }
1320         // Otherwise, this is a non-UCN escape character.  Process it.
1321         unsigned ResultChar =
1322           ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1323                             FullSourceLoc(StringToks[i].getLocation(), SM),
1324                             CharByteWidth*8, Diags, Features);
1325
1326         if (CharByteWidth == 4) {
1327           // FIXME: Make the type of the result buffer correct instead of
1328           // using reinterpret_cast.
1329           UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1330           *ResultWidePtr = ResultChar;
1331           ResultPtr += 4;
1332         } else if (CharByteWidth == 2) {
1333           // FIXME: Make the type of the result buffer correct instead of
1334           // using reinterpret_cast.
1335           UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1336           *ResultWidePtr = ResultChar & 0xFFFF;
1337           ResultPtr += 2;
1338         } else {
1339           assert(CharByteWidth == 1 && "Unexpected char width");
1340           *ResultPtr++ = ResultChar & 0xFF;
1341         }
1342       }
1343     }
1344   }
1345
1346   if (Pascal) {
1347     if (CharByteWidth == 4) {
1348       // FIXME: Make the type of the result buffer correct instead of
1349       // using reinterpret_cast.
1350       UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1351       ResultWidePtr[0] = GetNumStringChars() - 1;
1352     } else if (CharByteWidth == 2) {
1353       // FIXME: Make the type of the result buffer correct instead of
1354       // using reinterpret_cast.
1355       UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1356       ResultWidePtr[0] = GetNumStringChars() - 1;
1357     } else {
1358       assert(CharByteWidth == 1 && "Unexpected char width");
1359       ResultBuf[0] = GetNumStringChars() - 1;
1360     }
1361
1362     // Verify that pascal strings aren't too large.
1363     if (GetStringLength() > 256) {
1364       if (Diags)
1365         Diags->Report(StringToks[0].getLocation(),
1366                       diag::err_pascal_string_too_long)
1367           << SourceRange(StringToks[0].getLocation(),
1368                          StringToks[NumStringToks-1].getLocation());
1369       hadError = true;
1370       return;
1371     }
1372   } else if (Diags) {
1373     // Complain if this string literal has too many characters.
1374     unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1375
1376     if (GetNumStringChars() > MaxChars)
1377       Diags->Report(StringToks[0].getLocation(),
1378                     diag::ext_string_too_long)
1379         << GetNumStringChars() << MaxChars
1380         << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1381         << SourceRange(StringToks[0].getLocation(),
1382                        StringToks[NumStringToks-1].getLocation());
1383   }
1384 }
1385
1386 static const char *resyncUTF8(const char *Err, const char *End) {
1387   if (Err == End)
1388     return End;
1389   End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1390   while (++Err != End && (*Err & 0xC0) == 0x80)
1391     ;
1392   return Err;
1393 }
1394
1395 /// \brief This function copies from Fragment, which is a sequence of bytes
1396 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1397 /// Performs widening for multi-byte characters.
1398 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1399                                              const char *TokBegin,
1400                                              StringRef Fragment) {
1401   const UTF8 *ErrorPtrTmp;
1402   if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1403     return false;
1404
1405   // If we see bad encoding for unprefixed string literals, warn and
1406   // simply copy the byte values, for compatibility with gcc and older
1407   // versions of clang.
1408   bool NoErrorOnBadEncoding = isAscii();
1409   if (NoErrorOnBadEncoding) {
1410     memcpy(ResultPtr, Fragment.data(), Fragment.size());
1411     ResultPtr += Fragment.size();
1412   }
1413
1414   if (Diags) {
1415     const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1416
1417     FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1418     const DiagnosticBuilder &Builder =
1419       Diag(Diags, Features, SourceLoc, TokBegin,
1420            ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1421            NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1422                                 : diag::err_bad_string_encoding);
1423
1424     const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1425     StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1426
1427     // Decode into a dummy buffer.
1428     SmallString<512> Dummy;
1429     Dummy.reserve(Fragment.size() * CharByteWidth);
1430     char *Ptr = Dummy.data();
1431
1432     while (!Builder.hasMaxRanges() &&
1433            !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1434       const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1435       NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1436       Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1437                                      ErrorPtr, NextStart);
1438       NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1439     }
1440   }
1441   return !NoErrorOnBadEncoding;
1442 }
1443
1444 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1445   hadError = true;
1446   if (Diags)
1447     Diags->Report(Loc, diag::err_lexing_string);
1448 }
1449
1450 /// getOffsetOfStringByte - This function returns the offset of the
1451 /// specified byte of the string data represented by Token.  This handles
1452 /// advancing over escape sequences in the string.
1453 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1454                                                     unsigned ByteNo) const {
1455   // Get the spelling of the token.
1456   SmallString<32> SpellingBuffer;
1457   SpellingBuffer.resize(Tok.getLength());
1458
1459   bool StringInvalid = false;
1460   const char *SpellingPtr = &SpellingBuffer[0];
1461   unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1462                                        &StringInvalid);
1463   if (StringInvalid)
1464     return 0;
1465
1466   const char *SpellingStart = SpellingPtr;
1467   const char *SpellingEnd = SpellingPtr+TokLen;
1468
1469   // Handle UTF-8 strings just like narrow strings.
1470   if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1471     SpellingPtr += 2;
1472
1473   assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1474          SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1475
1476   // For raw string literals, this is easy.
1477   if (SpellingPtr[0] == 'R') {
1478     assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1479     // Skip 'R"'.
1480     SpellingPtr += 2;
1481     while (*SpellingPtr != '(') {
1482       ++SpellingPtr;
1483       assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1484     }
1485     // Skip '('.
1486     ++SpellingPtr;
1487     return SpellingPtr - SpellingStart + ByteNo;
1488   }
1489
1490   // Skip over the leading quote
1491   assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1492   ++SpellingPtr;
1493
1494   // Skip over bytes until we find the offset we're looking for.
1495   while (ByteNo) {
1496     assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1497
1498     // Step over non-escapes simply.
1499     if (*SpellingPtr != '\\') {
1500       ++SpellingPtr;
1501       --ByteNo;
1502       continue;
1503     }
1504
1505     // Otherwise, this is an escape character.  Advance over it.
1506     bool HadError = false;
1507     if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1508       const char *EscapePtr = SpellingPtr;
1509       unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1510                                       1, Features, HadError);
1511       if (Len > ByteNo) {
1512         // ByteNo is somewhere within the escape sequence.
1513         SpellingPtr = EscapePtr;
1514         break;
1515       }
1516       ByteNo -= Len;
1517     } else {
1518       ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1519                         FullSourceLoc(Tok.getLocation(), SM),
1520                         CharByteWidth*8, Diags, Features);
1521       --ByteNo;
1522     }
1523     assert(!HadError && "This method isn't valid on erroneous strings");
1524   }
1525
1526   return SpellingPtr-SpellingStart;
1527 }