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