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