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