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::err_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::err_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 == 4) &&
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 ///         binary-literal integer-suffix [GNU, C++1y]
417 ///       user-defined-integer-literal: [C++11 lex.ext]
418 ///         decimal-literal ud-suffix
419 ///         octal-literal ud-suffix
420 ///         hexadecimal-literal ud-suffix
421 ///         binary-literal ud-suffix [GNU, C++1y]
422 ///       decimal-constant:
423 ///         nonzero-digit
424 ///         decimal-constant digit
425 ///       octal-constant:
426 ///         0
427 ///         octal-constant octal-digit
428 ///       hexadecimal-constant:
429 ///         hexadecimal-prefix hexadecimal-digit
430 ///         hexadecimal-constant hexadecimal-digit
431 ///       hexadecimal-prefix: one of
432 ///         0x 0X
433 ///       binary-literal:
434 ///         0b binary-digit
435 ///         0B binary-digit
436 ///         binary-literal binary-digit
437 ///       integer-suffix:
438 ///         unsigned-suffix [long-suffix]
439 ///         unsigned-suffix [long-long-suffix]
440 ///         long-suffix [unsigned-suffix]
441 ///         long-long-suffix [unsigned-sufix]
442 ///       nonzero-digit:
443 ///         1 2 3 4 5 6 7 8 9
444 ///       octal-digit:
445 ///         0 1 2 3 4 5 6 7
446 ///       hexadecimal-digit:
447 ///         0 1 2 3 4 5 6 7 8 9
448 ///         a b c d e f
449 ///         A B C D E F
450 ///       binary-digit:
451 ///         0
452 ///         1
453 ///       unsigned-suffix: one of
454 ///         u U
455 ///       long-suffix: one of
456 ///         l L
457 ///       long-long-suffix: one of
458 ///         ll LL
459 ///
460 ///       floating-constant: [C99 6.4.4.2]
461 ///         TODO: add rules...
462 ///
463 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
464                                            SourceLocation TokLoc,
465                                            Preprocessor &PP)
466   : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
467 
468   // This routine assumes that the range begin/end matches the regex for integer
469   // and FP constants (specifically, the 'pp-number' regex), and assumes that
470   // the byte at "*end" is both valid and not part of the regex.  Because of
471   // this, it doesn't have to check for 'overscan' in various places.
472   assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
473 
474   s = DigitsBegin = ThisTokBegin;
475   saw_exponent = false;
476   saw_period = false;
477   saw_ud_suffix = false;
478   isLong = false;
479   isUnsigned = false;
480   isLongLong = false;
481   isFloat = false;
482   isImaginary = false;
483   isMicrosoftInteger = false;
484   hadError = false;
485 
486   if (*s == '0') { // parse radix
487     ParseNumberStartingWithZero(TokLoc);
488     if (hadError)
489       return;
490   } else { // the first digit is non-zero
491     radix = 10;
492     s = SkipDigits(s);
493     if (s == ThisTokEnd) {
494       // Done.
495     } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) {
496       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
497               diag::err_invalid_decimal_digit) << StringRef(s, 1);
498       hadError = true;
499       return;
500     } else if (*s == '.') {
501       checkSeparator(TokLoc, s, CSK_AfterDigits);
502       s++;
503       saw_period = true;
504       checkSeparator(TokLoc, s, CSK_BeforeDigits);
505       s = SkipDigits(s);
506     }
507     if ((*s == 'e' || *s == 'E')) { // exponent
508       checkSeparator(TokLoc, s, CSK_AfterDigits);
509       const char *Exponent = s;
510       s++;
511       saw_exponent = true;
512       if (*s == '+' || *s == '-')  s++; // sign
513       checkSeparator(TokLoc, s, CSK_BeforeDigits);
514       const char *first_non_digit = SkipDigits(s);
515       if (first_non_digit != s) {
516         s = first_non_digit;
517       } else {
518         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
519                 diag::err_exponent_has_no_digits);
520         hadError = true;
521         return;
522       }
523     }
524   }
525 
526   SuffixBegin = s;
527   checkSeparator(TokLoc, s, CSK_AfterDigits);
528 
529   // Parse the suffix.  At this point we can classify whether we have an FP or
530   // integer constant.
531   bool isFPConstant = isFloatingLiteral();
532   const char *ImaginarySuffixLoc = 0;
533 
534   // Loop over all of the characters of the suffix.  If we see something bad,
535   // we break out of the loop.
536   for (; s != ThisTokEnd; ++s) {
537     switch (*s) {
538     case 'f':      // FP Suffix for "float"
539     case 'F':
540       if (!isFPConstant) break;  // Error for integer constant.
541       if (isFloat || isLong) break; // FF, LF invalid.
542       isFloat = true;
543       continue;  // Success.
544     case 'u':
545     case 'U':
546       if (isFPConstant) break;  // Error for floating constant.
547       if (isUnsigned) break;    // Cannot be repeated.
548       isUnsigned = true;
549       continue;  // Success.
550     case 'l':
551     case 'L':
552       if (isLong || isLongLong) break;  // Cannot be repeated.
553       if (isFloat) break;               // LF invalid.
554 
555       // Check for long long.  The L's need to be adjacent and the same case.
556       if (s+1 != ThisTokEnd && s[1] == s[0]) {
557         if (isFPConstant) break;        // long long invalid for floats.
558         isLongLong = true;
559         ++s;  // Eat both of them.
560       } else {
561         isLong = true;
562       }
563       continue;  // Success.
564     case 'i':
565     case 'I':
566       if (PP.getLangOpts().MicrosoftExt) {
567         if (isFPConstant || isLong || isLongLong) break;
568 
569         // Allow i8, i16, i32, i64, and i128.
570         if (s + 1 != ThisTokEnd) {
571           switch (s[1]) {
572             case '8':
573               s += 2; // i8 suffix
574               isMicrosoftInteger = true;
575               break;
576             case '1':
577               if (s + 2 == ThisTokEnd) break;
578               if (s[2] == '6') {
579                 s += 3; // i16 suffix
580                 isMicrosoftInteger = true;
581               }
582               else if (s[2] == '2') {
583                 if (s + 3 == ThisTokEnd) break;
584                 if (s[3] == '8') {
585                   s += 4; // i128 suffix
586                   isMicrosoftInteger = true;
587                 }
588               }
589               break;
590             case '3':
591               if (s + 2 == ThisTokEnd) break;
592               if (s[2] == '2') {
593                 s += 3; // i32 suffix
594                 isLong = true;
595                 isMicrosoftInteger = true;
596               }
597               break;
598             case '6':
599               if (s + 2 == ThisTokEnd) break;
600               if (s[2] == '4') {
601                 s += 3; // i64 suffix
602                 isLongLong = true;
603                 isMicrosoftInteger = true;
604               }
605               break;
606             default:
607               break;
608           }
609           break;
610         }
611       }
612       // "i", "if", and "il" are user-defined suffixes in C++1y.
613       if (PP.getLangOpts().CPlusPlus1y && *s == 'i')
614         break;
615       // fall through.
616     case 'j':
617     case 'J':
618       if (isImaginary) break;   // Cannot be repeated.
619       isImaginary = true;
620       ImaginarySuffixLoc = s;
621       continue;  // Success.
622     }
623     // If we reached here, there was an error or a ud-suffix.
624     break;
625   }
626 
627   if (s != ThisTokEnd) {
628     if (isValidUDSuffix(PP.getLangOpts(),
629                         StringRef(SuffixBegin, ThisTokEnd - SuffixBegin))) {
630       // Any suffix pieces we might have parsed are actually part of the
631       // ud-suffix.
632       isLong = false;
633       isUnsigned = false;
634       isLongLong = false;
635       isFloat = false;
636       isImaginary = false;
637       isMicrosoftInteger = false;
638 
639       saw_ud_suffix = true;
640       return;
641     }
642 
643     // Report an error if there are any.
644     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
645             isFPConstant ? diag::err_invalid_suffix_float_constant :
646                            diag::err_invalid_suffix_integer_constant)
647       << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
648     hadError = true;
649     return;
650   }
651 
652   if (isImaginary) {
653     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
654                                        ImaginarySuffixLoc - ThisTokBegin),
655             diag::ext_imaginary_constant);
656   }
657 }
658 
659 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
660 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
661 /// treat it as an invalid suffix.
662 bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
663                                            StringRef Suffix) {
664   if (!LangOpts.CPlusPlus11 || Suffix.empty())
665     return false;
666 
667   // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
668   if (Suffix[0] == '_')
669     return true;
670 
671   // In C++11, there are no library suffixes.
672   if (!LangOpts.CPlusPlus1y)
673     return false;
674 
675   // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
676   // Per tweaked N3660, "il", "i", and "if" are also used in the library.
677   return llvm::StringSwitch<bool>(Suffix)
678       .Cases("h", "min", "s", true)
679       .Cases("ms", "us", "ns", true)
680       .Cases("il", "i", "if", true)
681       .Default(false);
682 }
683 
684 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
685                                           const char *Pos,
686                                           CheckSeparatorKind IsAfterDigits) {
687   if (IsAfterDigits == CSK_AfterDigits) {
688     if (Pos == ThisTokBegin)
689       return;
690     --Pos;
691   } else if (Pos == ThisTokEnd)
692     return;
693 
694   if (isDigitSeparator(*Pos))
695     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
696             diag::err_digit_separator_not_between_digits)
697       << IsAfterDigits;
698 }
699 
700 /// ParseNumberStartingWithZero - This method is called when the first character
701 /// of the number is found to be a zero.  This means it is either an octal
702 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
703 /// a floating point number (01239.123e4).  Eat the prefix, determining the
704 /// radix etc.
705 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
706   assert(s[0] == '0' && "Invalid method call");
707   s++;
708 
709   // Handle a hex number like 0x1234.
710   if ((*s == 'x' || *s == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
711     s++;
712     radix = 16;
713     DigitsBegin = s;
714     s = SkipHexDigits(s);
715     bool noSignificand = (s == DigitsBegin);
716     if (s == ThisTokEnd) {
717       // Done.
718     } else if (*s == '.') {
719       s++;
720       saw_period = true;
721       const char *floatDigitsBegin = s;
722       s = SkipHexDigits(s);
723       noSignificand &= (floatDigitsBegin == s);
724     }
725 
726     if (noSignificand) {
727       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
728         diag::err_hexconstant_requires_digits);
729       hadError = true;
730       return;
731     }
732 
733     // A binary exponent can appear with or with a '.'. If dotted, the
734     // binary exponent is required.
735     if (*s == 'p' || *s == 'P') {
736       const char *Exponent = s;
737       s++;
738       saw_exponent = true;
739       if (*s == '+' || *s == '-')  s++; // sign
740       const char *first_non_digit = SkipDigits(s);
741       if (first_non_digit == s) {
742         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
743                 diag::err_exponent_has_no_digits);
744         hadError = true;
745         return;
746       }
747       s = first_non_digit;
748 
749       if (!PP.getLangOpts().HexFloats)
750         PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
751     } else if (saw_period) {
752       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
753               diag::err_hexconstant_requires_exponent);
754       hadError = true;
755     }
756     return;
757   }
758 
759   // Handle simple binary numbers 0b01010
760   if ((*s == 'b' || *s == 'B') && (s[1] == '0' || s[1] == '1')) {
761     // 0b101010 is a C++1y / GCC extension.
762     PP.Diag(TokLoc,
763             PP.getLangOpts().CPlusPlus1y
764               ? diag::warn_cxx11_compat_binary_literal
765               : PP.getLangOpts().CPlusPlus
766                 ? diag::ext_binary_literal_cxx1y
767                 : diag::ext_binary_literal);
768     ++s;
769     radix = 2;
770     DigitsBegin = s;
771     s = SkipBinaryDigits(s);
772     if (s == ThisTokEnd) {
773       // Done.
774     } else if (isHexDigit(*s)) {
775       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
776               diag::err_invalid_binary_digit) << StringRef(s, 1);
777       hadError = true;
778     }
779     // Other suffixes will be diagnosed by the caller.
780     return;
781   }
782 
783   // For now, the radix is set to 8. If we discover that we have a
784   // floating point constant, the radix will change to 10. Octal floating
785   // point constants are not permitted (only decimal and hexadecimal).
786   radix = 8;
787   DigitsBegin = s;
788   s = SkipOctalDigits(s);
789   if (s == ThisTokEnd)
790     return; // Done, simple octal number like 01234
791 
792   // If we have some other non-octal digit that *is* a decimal digit, see if
793   // this is part of a floating point number like 094.123 or 09e1.
794   if (isDigit(*s)) {
795     const char *EndDecimal = SkipDigits(s);
796     if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
797       s = EndDecimal;
798       radix = 10;
799     }
800   }
801 
802   // If we have a hex digit other than 'e' (which denotes a FP exponent) then
803   // the code is using an incorrect base.
804   if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
805     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
806             diag::err_invalid_octal_digit) << StringRef(s, 1);
807     hadError = true;
808     return;
809   }
810 
811   if (*s == '.') {
812     s++;
813     radix = 10;
814     saw_period = true;
815     s = SkipDigits(s); // Skip suffix.
816   }
817   if (*s == 'e' || *s == 'E') { // exponent
818     const char *Exponent = s;
819     s++;
820     radix = 10;
821     saw_exponent = true;
822     if (*s == '+' || *s == '-')  s++; // sign
823     const char *first_non_digit = SkipDigits(s);
824     if (first_non_digit != s) {
825       s = first_non_digit;
826     } else {
827       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
828               diag::err_exponent_has_no_digits);
829       hadError = true;
830       return;
831     }
832   }
833 }
834 
835 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
836   switch (Radix) {
837   case 2:
838     return NumDigits <= 64;
839   case 8:
840     return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
841   case 10:
842     return NumDigits <= 19; // floor(log10(2^64))
843   case 16:
844     return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
845   default:
846     llvm_unreachable("impossible Radix");
847   }
848 }
849 
850 /// GetIntegerValue - Convert this numeric literal value to an APInt that
851 /// matches Val's input width.  If there is an overflow, set Val to the low bits
852 /// of the result and return true.  Otherwise, return false.
853 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
854   // Fast path: Compute a conservative bound on the maximum number of
855   // bits per digit in this radix. If we can't possibly overflow a
856   // uint64 based on that bound then do the simple conversion to
857   // integer. This avoids the expensive overflow checking below, and
858   // handles the common cases that matter (small decimal integers and
859   // hex/octal values which don't overflow).
860   const unsigned NumDigits = SuffixBegin - DigitsBegin;
861   if (alwaysFitsInto64Bits(radix, NumDigits)) {
862     uint64_t N = 0;
863     for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
864       if (!isDigitSeparator(*Ptr))
865         N = N * radix + llvm::hexDigitValue(*Ptr);
866 
867     // This will truncate the value to Val's input width. Simply check
868     // for overflow by comparing.
869     Val = N;
870     return Val.getZExtValue() != N;
871   }
872 
873   Val = 0;
874   const char *Ptr = DigitsBegin;
875 
876   llvm::APInt RadixVal(Val.getBitWidth(), radix);
877   llvm::APInt CharVal(Val.getBitWidth(), 0);
878   llvm::APInt OldVal = Val;
879 
880   bool OverflowOccurred = false;
881   while (Ptr < SuffixBegin) {
882     if (isDigitSeparator(*Ptr)) {
883       ++Ptr;
884       continue;
885     }
886 
887     unsigned C = llvm::hexDigitValue(*Ptr++);
888 
889     // If this letter is out of bound for this radix, reject it.
890     assert(C < radix && "NumericLiteralParser ctor should have rejected this");
891 
892     CharVal = C;
893 
894     // Add the digit to the value in the appropriate radix.  If adding in digits
895     // made the value smaller, then this overflowed.
896     OldVal = Val;
897 
898     // Multiply by radix, did overflow occur on the multiply?
899     Val *= RadixVal;
900     OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
901 
902     // Add value, did overflow occur on the value?
903     //   (a + b) ult b  <=> overflow
904     Val += CharVal;
905     OverflowOccurred |= Val.ult(CharVal);
906   }
907   return OverflowOccurred;
908 }
909 
910 llvm::APFloat::opStatus
911 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
912   using llvm::APFloat;
913 
914   unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
915 
916   llvm::SmallString<16> Buffer;
917   StringRef Str(ThisTokBegin, n);
918   if (Str.find('\'') != StringRef::npos) {
919     Buffer.reserve(n);
920     std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
921                         &isDigitSeparator);
922     Str = Buffer;
923   }
924 
925   return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
926 }
927 
928 
929 /// \verbatim
930 ///       user-defined-character-literal: [C++11 lex.ext]
931 ///         character-literal ud-suffix
932 ///       ud-suffix:
933 ///         identifier
934 ///       character-literal: [C++11 lex.ccon]
935 ///         ' c-char-sequence '
936 ///         u' c-char-sequence '
937 ///         U' c-char-sequence '
938 ///         L' c-char-sequence '
939 ///       c-char-sequence:
940 ///         c-char
941 ///         c-char-sequence c-char
942 ///       c-char:
943 ///         any member of the source character set except the single-quote ',
944 ///           backslash \, or new-line character
945 ///         escape-sequence
946 ///         universal-character-name
947 ///       escape-sequence:
948 ///         simple-escape-sequence
949 ///         octal-escape-sequence
950 ///         hexadecimal-escape-sequence
951 ///       simple-escape-sequence:
952 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
953 ///       octal-escape-sequence:
954 ///         \ octal-digit
955 ///         \ octal-digit octal-digit
956 ///         \ octal-digit octal-digit octal-digit
957 ///       hexadecimal-escape-sequence:
958 ///         \x hexadecimal-digit
959 ///         hexadecimal-escape-sequence hexadecimal-digit
960 ///       universal-character-name: [C++11 lex.charset]
961 ///         \u hex-quad
962 ///         \U hex-quad hex-quad
963 ///       hex-quad:
964 ///         hex-digit hex-digit hex-digit hex-digit
965 /// \endverbatim
966 ///
967 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
968                                      SourceLocation Loc, Preprocessor &PP,
969                                      tok::TokenKind kind) {
970   // At this point we know that the character matches the regex "(L|u|U)?'.*'".
971   HadError = false;
972 
973   Kind = kind;
974 
975   const char *TokBegin = begin;
976 
977   // Skip over wide character determinant.
978   if (Kind != tok::char_constant) {
979     ++begin;
980   }
981 
982   // Skip over the entry quote.
983   assert(begin[0] == '\'' && "Invalid token lexed");
984   ++begin;
985 
986   // Remove an optional ud-suffix.
987   if (end[-1] != '\'') {
988     const char *UDSuffixEnd = end;
989     do {
990       --end;
991     } while (end[-1] != '\'');
992     UDSuffixBuf.assign(end, UDSuffixEnd);
993     UDSuffixOffset = end - TokBegin;
994   }
995 
996   // Trim the ending quote.
997   assert(end != begin && "Invalid token lexed");
998   --end;
999 
1000   // FIXME: The "Value" is an uint64_t so we can handle char literals of
1001   // up to 64-bits.
1002   // FIXME: This extensively assumes that 'char' is 8-bits.
1003   assert(PP.getTargetInfo().getCharWidth() == 8 &&
1004          "Assumes char is 8 bits");
1005   assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1006          (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1007          "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1008   assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1009          "Assumes sizeof(wchar) on target is <= 64");
1010 
1011   SmallVector<uint32_t, 4> codepoint_buffer;
1012   codepoint_buffer.resize(end - begin);
1013   uint32_t *buffer_begin = &codepoint_buffer.front();
1014   uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1015 
1016   // Unicode escapes representing characters that cannot be correctly
1017   // represented in a single code unit are disallowed in character literals
1018   // by this implementation.
1019   uint32_t largest_character_for_kind;
1020   if (tok::wide_char_constant == Kind) {
1021     largest_character_for_kind =
1022         0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1023   } else if (tok::utf16_char_constant == Kind) {
1024     largest_character_for_kind = 0xFFFF;
1025   } else if (tok::utf32_char_constant == Kind) {
1026     largest_character_for_kind = 0x10FFFF;
1027   } else {
1028     largest_character_for_kind = 0x7Fu;
1029   }
1030 
1031   while (begin != end) {
1032     // Is this a span of non-escape characters?
1033     if (begin[0] != '\\') {
1034       char const *start = begin;
1035       do {
1036         ++begin;
1037       } while (begin != end && *begin != '\\');
1038 
1039       char const *tmp_in_start = start;
1040       uint32_t *tmp_out_start = buffer_begin;
1041       ConversionResult res =
1042           ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1043                              reinterpret_cast<UTF8 const *>(begin),
1044                              &buffer_begin, buffer_end, strictConversion);
1045       if (res != conversionOK) {
1046         // If we see bad encoding for unprefixed character literals, warn and
1047         // simply copy the byte values, for compatibility with gcc and
1048         // older versions of clang.
1049         bool NoErrorOnBadEncoding = isAscii();
1050         unsigned Msg = diag::err_bad_character_encoding;
1051         if (NoErrorOnBadEncoding)
1052           Msg = diag::warn_bad_character_encoding;
1053         PP.Diag(Loc, Msg);
1054         if (NoErrorOnBadEncoding) {
1055           start = tmp_in_start;
1056           buffer_begin = tmp_out_start;
1057           for (; start != begin; ++start, ++buffer_begin)
1058             *buffer_begin = static_cast<uint8_t>(*start);
1059         } else {
1060           HadError = true;
1061         }
1062       } else {
1063         for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1064           if (*tmp_out_start > largest_character_for_kind) {
1065             HadError = true;
1066             PP.Diag(Loc, diag::err_character_too_large);
1067           }
1068         }
1069       }
1070 
1071       continue;
1072     }
1073     // Is this a Universal Character Name escape?
1074     if (begin[1] == 'u' || begin[1] == 'U') {
1075       unsigned short UcnLen = 0;
1076       if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1077                             FullSourceLoc(Loc, PP.getSourceManager()),
1078                             &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1079         HadError = true;
1080       } else if (*buffer_begin > largest_character_for_kind) {
1081         HadError = true;
1082         PP.Diag(Loc, diag::err_character_too_large);
1083       }
1084 
1085       ++buffer_begin;
1086       continue;
1087     }
1088     unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1089     uint64_t result =
1090       ProcessCharEscape(TokBegin, begin, end, HadError,
1091                         FullSourceLoc(Loc,PP.getSourceManager()),
1092                         CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1093     *buffer_begin++ = result;
1094   }
1095 
1096   unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1097 
1098   if (NumCharsSoFar > 1) {
1099     if (isWide())
1100       PP.Diag(Loc, diag::warn_extraneous_char_constant);
1101     else if (isAscii() && NumCharsSoFar == 4)
1102       PP.Diag(Loc, diag::ext_four_char_character_literal);
1103     else if (isAscii())
1104       PP.Diag(Loc, diag::ext_multichar_character_literal);
1105     else
1106       PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1107     IsMultiChar = true;
1108   } else {
1109     IsMultiChar = false;
1110   }
1111 
1112   llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1113 
1114   // Narrow character literals act as though their value is concatenated
1115   // in this implementation, but warn on overflow.
1116   bool multi_char_too_long = false;
1117   if (isAscii() && isMultiChar()) {
1118     LitVal = 0;
1119     for (size_t i = 0; i < NumCharsSoFar; ++i) {
1120       // check for enough leading zeros to shift into
1121       multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1122       LitVal <<= 8;
1123       LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1124     }
1125   } else if (NumCharsSoFar > 0) {
1126     // otherwise just take the last character
1127     LitVal = buffer_begin[-1];
1128   }
1129 
1130   if (!HadError && multi_char_too_long) {
1131     PP.Diag(Loc, diag::warn_char_constant_too_large);
1132   }
1133 
1134   // Transfer the value from APInt to uint64_t
1135   Value = LitVal.getZExtValue();
1136 
1137   // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1138   // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
1139   // character constants are not sign extended in the this implementation:
1140   // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1141   if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1142       PP.getLangOpts().CharIsSigned)
1143     Value = (signed char)Value;
1144 }
1145 
1146 /// \verbatim
1147 ///       string-literal: [C++0x lex.string]
1148 ///         encoding-prefix " [s-char-sequence] "
1149 ///         encoding-prefix R raw-string
1150 ///       encoding-prefix:
1151 ///         u8
1152 ///         u
1153 ///         U
1154 ///         L
1155 ///       s-char-sequence:
1156 ///         s-char
1157 ///         s-char-sequence s-char
1158 ///       s-char:
1159 ///         any member of the source character set except the double-quote ",
1160 ///           backslash \, or new-line character
1161 ///         escape-sequence
1162 ///         universal-character-name
1163 ///       raw-string:
1164 ///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
1165 ///       r-char-sequence:
1166 ///         r-char
1167 ///         r-char-sequence r-char
1168 ///       r-char:
1169 ///         any member of the source character set, except a right parenthesis )
1170 ///           followed by the initial d-char-sequence (which may be empty)
1171 ///           followed by a double quote ".
1172 ///       d-char-sequence:
1173 ///         d-char
1174 ///         d-char-sequence d-char
1175 ///       d-char:
1176 ///         any member of the basic source character set except:
1177 ///           space, the left parenthesis (, the right parenthesis ),
1178 ///           the backslash \, and the control characters representing horizontal
1179 ///           tab, vertical tab, form feed, and newline.
1180 ///       escape-sequence: [C++0x lex.ccon]
1181 ///         simple-escape-sequence
1182 ///         octal-escape-sequence
1183 ///         hexadecimal-escape-sequence
1184 ///       simple-escape-sequence:
1185 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
1186 ///       octal-escape-sequence:
1187 ///         \ octal-digit
1188 ///         \ octal-digit octal-digit
1189 ///         \ octal-digit octal-digit octal-digit
1190 ///       hexadecimal-escape-sequence:
1191 ///         \x hexadecimal-digit
1192 ///         hexadecimal-escape-sequence hexadecimal-digit
1193 ///       universal-character-name:
1194 ///         \u hex-quad
1195 ///         \U hex-quad hex-quad
1196 ///       hex-quad:
1197 ///         hex-digit hex-digit hex-digit hex-digit
1198 /// \endverbatim
1199 ///
1200 StringLiteralParser::
1201 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1202                     Preprocessor &PP, bool Complain)
1203   : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1204     Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1205     MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1206     ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1207   init(StringToks, NumStringToks);
1208 }
1209 
1210 void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1211   // The literal token may have come from an invalid source location (e.g. due
1212   // to a PCH error), in which case the token length will be 0.
1213   if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1214     return DiagnoseLexingError(SourceLocation());
1215 
1216   // Scan all of the string portions, remember the max individual token length,
1217   // computing a bound on the concatenated string length, and see whether any
1218   // piece is a wide-string.  If any of the string portions is a wide-string
1219   // literal, the result is a wide-string literal [C99 6.4.5p4].
1220   assert(NumStringToks && "expected at least one token");
1221   MaxTokenLength = StringToks[0].getLength();
1222   assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1223   SizeBound = StringToks[0].getLength()-2;  // -2 for "".
1224   Kind = StringToks[0].getKind();
1225 
1226   hadError = false;
1227 
1228   // Implement Translation Phase #6: concatenation of string literals
1229   /// (C99 5.1.1.2p1).  The common case is only one string fragment.
1230   for (unsigned i = 1; i != NumStringToks; ++i) {
1231     if (StringToks[i].getLength() < 2)
1232       return DiagnoseLexingError(StringToks[i].getLocation());
1233 
1234     // The string could be shorter than this if it needs cleaning, but this is a
1235     // reasonable bound, which is all we need.
1236     assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1237     SizeBound += StringToks[i].getLength()-2;  // -2 for "".
1238 
1239     // Remember maximum string piece length.
1240     if (StringToks[i].getLength() > MaxTokenLength)
1241       MaxTokenLength = StringToks[i].getLength();
1242 
1243     // Remember if we see any wide or utf-8/16/32 strings.
1244     // Also check for illegal concatenations.
1245     if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1246       if (isAscii()) {
1247         Kind = StringToks[i].getKind();
1248       } else {
1249         if (Diags)
1250           Diags->Report(StringToks[i].getLocation(),
1251                         diag::err_unsupported_string_concat);
1252         hadError = true;
1253       }
1254     }
1255   }
1256 
1257   // Include space for the null terminator.
1258   ++SizeBound;
1259 
1260   // TODO: K&R warning: "traditional C rejects string constant concatenation"
1261 
1262   // Get the width in bytes of char/wchar_t/char16_t/char32_t
1263   CharByteWidth = getCharWidth(Kind, Target);
1264   assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1265   CharByteWidth /= 8;
1266 
1267   // The output buffer size needs to be large enough to hold wide characters.
1268   // This is a worst-case assumption which basically corresponds to L"" "long".
1269   SizeBound *= CharByteWidth;
1270 
1271   // Size the temporary buffer to hold the result string data.
1272   ResultBuf.resize(SizeBound);
1273 
1274   // Likewise, but for each string piece.
1275   SmallString<512> TokenBuf;
1276   TokenBuf.resize(MaxTokenLength);
1277 
1278   // Loop over all the strings, getting their spelling, and expanding them to
1279   // wide strings as appropriate.
1280   ResultPtr = &ResultBuf[0];   // Next byte to fill in.
1281 
1282   Pascal = false;
1283 
1284   SourceLocation UDSuffixTokLoc;
1285 
1286   for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1287     const char *ThisTokBuf = &TokenBuf[0];
1288     // Get the spelling of the token, which eliminates trigraphs, etc.  We know
1289     // that ThisTokBuf points to a buffer that is big enough for the whole token
1290     // and 'spelled' tokens can only shrink.
1291     bool StringInvalid = false;
1292     unsigned ThisTokLen =
1293       Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1294                          &StringInvalid);
1295     if (StringInvalid)
1296       return DiagnoseLexingError(StringToks[i].getLocation());
1297 
1298     const char *ThisTokBegin = ThisTokBuf;
1299     const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1300 
1301     // Remove an optional ud-suffix.
1302     if (ThisTokEnd[-1] != '"') {
1303       const char *UDSuffixEnd = ThisTokEnd;
1304       do {
1305         --ThisTokEnd;
1306       } while (ThisTokEnd[-1] != '"');
1307 
1308       StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1309 
1310       if (UDSuffixBuf.empty()) {
1311         UDSuffixBuf.assign(UDSuffix);
1312         UDSuffixToken = i;
1313         UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1314         UDSuffixTokLoc = StringToks[i].getLocation();
1315       } else if (!UDSuffixBuf.equals(UDSuffix)) {
1316         // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1317         // result of a concatenation involving at least one user-defined-string-
1318         // literal, all the participating user-defined-string-literals shall
1319         // have the same ud-suffix.
1320         if (Diags) {
1321           SourceLocation TokLoc = StringToks[i].getLocation();
1322           Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1323             << UDSuffixBuf << UDSuffix
1324             << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1325             << SourceRange(TokLoc, TokLoc);
1326         }
1327         hadError = true;
1328       }
1329     }
1330 
1331     // Strip the end quote.
1332     --ThisTokEnd;
1333 
1334     // TODO: Input character set mapping support.
1335 
1336     // Skip marker for wide or unicode strings.
1337     if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1338       ++ThisTokBuf;
1339       // Skip 8 of u8 marker for utf8 strings.
1340       if (ThisTokBuf[0] == '8')
1341         ++ThisTokBuf;
1342     }
1343 
1344     // Check for raw string
1345     if (ThisTokBuf[0] == 'R') {
1346       ThisTokBuf += 2; // skip R"
1347 
1348       const char *Prefix = ThisTokBuf;
1349       while (ThisTokBuf[0] != '(')
1350         ++ThisTokBuf;
1351       ++ThisTokBuf; // skip '('
1352 
1353       // Remove same number of characters from the end
1354       ThisTokEnd -= ThisTokBuf - Prefix;
1355       assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1356 
1357       // Copy the string over
1358       if (CopyStringFragment(StringToks[i], ThisTokBegin,
1359                              StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1360         hadError = true;
1361     } else {
1362       if (ThisTokBuf[0] != '"') {
1363         // The file may have come from PCH and then changed after loading the
1364         // PCH; Fail gracefully.
1365         return DiagnoseLexingError(StringToks[i].getLocation());
1366       }
1367       ++ThisTokBuf; // skip "
1368 
1369       // Check if this is a pascal string
1370       if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1371           ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1372 
1373         // If the \p sequence is found in the first token, we have a pascal string
1374         // Otherwise, if we already have a pascal string, ignore the first \p
1375         if (i == 0) {
1376           ++ThisTokBuf;
1377           Pascal = true;
1378         } else if (Pascal)
1379           ThisTokBuf += 2;
1380       }
1381 
1382       while (ThisTokBuf != ThisTokEnd) {
1383         // Is this a span of non-escape characters?
1384         if (ThisTokBuf[0] != '\\') {
1385           const char *InStart = ThisTokBuf;
1386           do {
1387             ++ThisTokBuf;
1388           } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1389 
1390           // Copy the character span over.
1391           if (CopyStringFragment(StringToks[i], ThisTokBegin,
1392                                  StringRef(InStart, ThisTokBuf - InStart)))
1393             hadError = true;
1394           continue;
1395         }
1396         // Is this a Universal Character Name escape?
1397         if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1398           EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1399                           ResultPtr, hadError,
1400                           FullSourceLoc(StringToks[i].getLocation(), SM),
1401                           CharByteWidth, Diags, Features);
1402           continue;
1403         }
1404         // Otherwise, this is a non-UCN escape character.  Process it.
1405         unsigned ResultChar =
1406           ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1407                             FullSourceLoc(StringToks[i].getLocation(), SM),
1408                             CharByteWidth*8, Diags, Features);
1409 
1410         if (CharByteWidth == 4) {
1411           // FIXME: Make the type of the result buffer correct instead of
1412           // using reinterpret_cast.
1413           UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1414           *ResultWidePtr = ResultChar;
1415           ResultPtr += 4;
1416         } else if (CharByteWidth == 2) {
1417           // FIXME: Make the type of the result buffer correct instead of
1418           // using reinterpret_cast.
1419           UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1420           *ResultWidePtr = ResultChar & 0xFFFF;
1421           ResultPtr += 2;
1422         } else {
1423           assert(CharByteWidth == 1 && "Unexpected char width");
1424           *ResultPtr++ = ResultChar & 0xFF;
1425         }
1426       }
1427     }
1428   }
1429 
1430   if (Pascal) {
1431     if (CharByteWidth == 4) {
1432       // FIXME: Make the type of the result buffer correct instead of
1433       // using reinterpret_cast.
1434       UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1435       ResultWidePtr[0] = GetNumStringChars() - 1;
1436     } else if (CharByteWidth == 2) {
1437       // FIXME: Make the type of the result buffer correct instead of
1438       // using reinterpret_cast.
1439       UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1440       ResultWidePtr[0] = GetNumStringChars() - 1;
1441     } else {
1442       assert(CharByteWidth == 1 && "Unexpected char width");
1443       ResultBuf[0] = GetNumStringChars() - 1;
1444     }
1445 
1446     // Verify that pascal strings aren't too large.
1447     if (GetStringLength() > 256) {
1448       if (Diags)
1449         Diags->Report(StringToks[0].getLocation(),
1450                       diag::err_pascal_string_too_long)
1451           << SourceRange(StringToks[0].getLocation(),
1452                          StringToks[NumStringToks-1].getLocation());
1453       hadError = true;
1454       return;
1455     }
1456   } else if (Diags) {
1457     // Complain if this string literal has too many characters.
1458     unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1459 
1460     if (GetNumStringChars() > MaxChars)
1461       Diags->Report(StringToks[0].getLocation(),
1462                     diag::ext_string_too_long)
1463         << GetNumStringChars() << MaxChars
1464         << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1465         << SourceRange(StringToks[0].getLocation(),
1466                        StringToks[NumStringToks-1].getLocation());
1467   }
1468 }
1469 
1470 static const char *resyncUTF8(const char *Err, const char *End) {
1471   if (Err == End)
1472     return End;
1473   End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1474   while (++Err != End && (*Err & 0xC0) == 0x80)
1475     ;
1476   return Err;
1477 }
1478 
1479 /// \brief This function copies from Fragment, which is a sequence of bytes
1480 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1481 /// Performs widening for multi-byte characters.
1482 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1483                                              const char *TokBegin,
1484                                              StringRef Fragment) {
1485   const UTF8 *ErrorPtrTmp;
1486   if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1487     return false;
1488 
1489   // If we see bad encoding for unprefixed string literals, warn and
1490   // simply copy the byte values, for compatibility with gcc and older
1491   // versions of clang.
1492   bool NoErrorOnBadEncoding = isAscii();
1493   if (NoErrorOnBadEncoding) {
1494     memcpy(ResultPtr, Fragment.data(), Fragment.size());
1495     ResultPtr += Fragment.size();
1496   }
1497 
1498   if (Diags) {
1499     const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1500 
1501     FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1502     const DiagnosticBuilder &Builder =
1503       Diag(Diags, Features, SourceLoc, TokBegin,
1504            ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1505            NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1506                                 : diag::err_bad_string_encoding);
1507 
1508     const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1509     StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1510 
1511     // Decode into a dummy buffer.
1512     SmallString<512> Dummy;
1513     Dummy.reserve(Fragment.size() * CharByteWidth);
1514     char *Ptr = Dummy.data();
1515 
1516     while (!Builder.hasMaxRanges() &&
1517            !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1518       const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1519       NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1520       Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1521                                      ErrorPtr, NextStart);
1522       NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1523     }
1524   }
1525   return !NoErrorOnBadEncoding;
1526 }
1527 
1528 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1529   hadError = true;
1530   if (Diags)
1531     Diags->Report(Loc, diag::err_lexing_string);
1532 }
1533 
1534 /// getOffsetOfStringByte - This function returns the offset of the
1535 /// specified byte of the string data represented by Token.  This handles
1536 /// advancing over escape sequences in the string.
1537 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1538                                                     unsigned ByteNo) const {
1539   // Get the spelling of the token.
1540   SmallString<32> SpellingBuffer;
1541   SpellingBuffer.resize(Tok.getLength());
1542 
1543   bool StringInvalid = false;
1544   const char *SpellingPtr = &SpellingBuffer[0];
1545   unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1546                                        &StringInvalid);
1547   if (StringInvalid)
1548     return 0;
1549 
1550   const char *SpellingStart = SpellingPtr;
1551   const char *SpellingEnd = SpellingPtr+TokLen;
1552 
1553   // Handle UTF-8 strings just like narrow strings.
1554   if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1555     SpellingPtr += 2;
1556 
1557   assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1558          SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1559 
1560   // For raw string literals, this is easy.
1561   if (SpellingPtr[0] == 'R') {
1562     assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1563     // Skip 'R"'.
1564     SpellingPtr += 2;
1565     while (*SpellingPtr != '(') {
1566       ++SpellingPtr;
1567       assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1568     }
1569     // Skip '('.
1570     ++SpellingPtr;
1571     return SpellingPtr - SpellingStart + ByteNo;
1572   }
1573 
1574   // Skip over the leading quote
1575   assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1576   ++SpellingPtr;
1577 
1578   // Skip over bytes until we find the offset we're looking for.
1579   while (ByteNo) {
1580     assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1581 
1582     // Step over non-escapes simply.
1583     if (*SpellingPtr != '\\') {
1584       ++SpellingPtr;
1585       --ByteNo;
1586       continue;
1587     }
1588 
1589     // Otherwise, this is an escape character.  Advance over it.
1590     bool HadError = false;
1591     if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1592       const char *EscapePtr = SpellingPtr;
1593       unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1594                                       1, Features, HadError);
1595       if (Len > ByteNo) {
1596         // ByteNo is somewhere within the escape sequence.
1597         SpellingPtr = EscapePtr;
1598         break;
1599       }
1600       ByteNo -= Len;
1601     } else {
1602       ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1603                         FullSourceLoc(Tok.getLocation(), SM),
1604                         CharByteWidth*8, Diags, Features);
1605       --ByteNo;
1606     }
1607     assert(!HadError && "This method isn't valid on erroneous strings");
1608   }
1609 
1610   return SpellingPtr-SpellingStart;
1611 }
1612