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