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