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