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