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