1193326Sed//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the NumericLiteralParser, CharLiteralParser, and
11193326Sed// StringLiteralParser interfaces.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15193326Sed#include "clang/Lex/LiteralSupport.h"
16252723Sdim#include "clang/Basic/CharInfo.h"
17252723Sdim#include "clang/Basic/TargetInfo.h"
18252723Sdim#include "clang/Lex/LexDiagnostic.h"
19193326Sed#include "clang/Lex/Preprocessor.h"
20193326Sed#include "llvm/ADT/StringExtras.h"
21252723Sdim#include "llvm/Support/ConvertUTF.h"
22226890Sdim#include "llvm/Support/ErrorHandling.h"
23252723Sdim
24193326Sedusing namespace clang;
25193326Sed
26226890Sdimstatic unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
27226890Sdim  switch (kind) {
28226890Sdim  default: llvm_unreachable("Unknown token type!");
29226890Sdim  case tok::char_constant:
30226890Sdim  case tok::string_literal:
31226890Sdim  case tok::utf8_string_literal:
32226890Sdim    return Target.getCharWidth();
33226890Sdim  case tok::wide_char_constant:
34226890Sdim  case tok::wide_string_literal:
35226890Sdim    return Target.getWCharWidth();
36226890Sdim  case tok::utf16_char_constant:
37226890Sdim  case tok::utf16_string_literal:
38226890Sdim    return Target.getChar16Width();
39226890Sdim  case tok::utf32_char_constant:
40226890Sdim  case tok::utf32_string_literal:
41226890Sdim    return Target.getChar32Width();
42226890Sdim  }
43226890Sdim}
44226890Sdim
45245431Sdimstatic CharSourceRange MakeCharSourceRange(const LangOptions &Features,
46245431Sdim                                           FullSourceLoc TokLoc,
47245431Sdim                                           const char *TokBegin,
48245431Sdim                                           const char *TokRangeBegin,
49245431Sdim                                           const char *TokRangeEnd) {
50245431Sdim  SourceLocation Begin =
51245431Sdim    Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
52245431Sdim                                   TokLoc.getManager(), Features);
53245431Sdim  SourceLocation End =
54245431Sdim    Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
55245431Sdim                                   TokLoc.getManager(), Features);
56245431Sdim  return CharSourceRange::getCharRange(Begin, End);
57245431Sdim}
58245431Sdim
59245431Sdim/// \brief Produce a diagnostic highlighting some portion of a literal.
60245431Sdim///
61245431Sdim/// Emits the diagnostic \p DiagID, highlighting the range of characters from
62245431Sdim/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
63245431Sdim/// a substring of a spelling buffer for the token beginning at \p TokBegin.
64245431Sdimstatic DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
65245431Sdim                              const LangOptions &Features, FullSourceLoc TokLoc,
66245431Sdim                              const char *TokBegin, const char *TokRangeBegin,
67245431Sdim                              const char *TokRangeEnd, unsigned DiagID) {
68245431Sdim  SourceLocation Begin =
69245431Sdim    Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
70245431Sdim                                   TokLoc.getManager(), Features);
71245431Sdim  return Diags->Report(Begin, DiagID) <<
72245431Sdim    MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
73245431Sdim}
74245431Sdim
75193326Sed/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
76193326Sed/// either a character or a string literal.
77245431Sdimstatic unsigned ProcessCharEscape(const char *ThisTokBegin,
78245431Sdim                                  const char *&ThisTokBuf,
79193326Sed                                  const char *ThisTokEnd, bool &HadError,
80226890Sdim                                  FullSourceLoc Loc, unsigned CharWidth,
81245431Sdim                                  DiagnosticsEngine *Diags,
82245431Sdim                                  const LangOptions &Features) {
83245431Sdim  const char *EscapeBegin = ThisTokBuf;
84245431Sdim
85193326Sed  // Skip the '\' char.
86193326Sed  ++ThisTokBuf;
87193326Sed
88193326Sed  // We know that this character can't be off the end of the buffer, because
89193326Sed  // that would have been \", which would not have been the end of string.
90193326Sed  unsigned ResultChar = *ThisTokBuf++;
91193326Sed  switch (ResultChar) {
92193326Sed  // These map to themselves.
93193326Sed  case '\\': case '\'': case '"': case '?': break;
94198092Srdivacky
95193326Sed    // These have fixed mappings.
96193326Sed  case 'a':
97193326Sed    // TODO: K&R: the meaning of '\\a' is different in traditional C
98193326Sed    ResultChar = 7;
99193326Sed    break;
100193326Sed  case 'b':
101193326Sed    ResultChar = 8;
102193326Sed    break;
103193326Sed  case 'e':
104218893Sdim    if (Diags)
105245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
106245431Sdim           diag::ext_nonstandard_escape) << "e";
107193326Sed    ResultChar = 27;
108193326Sed    break;
109194179Sed  case 'E':
110218893Sdim    if (Diags)
111245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
112245431Sdim           diag::ext_nonstandard_escape) << "E";
113194179Sed    ResultChar = 27;
114194179Sed    break;
115193326Sed  case 'f':
116193326Sed    ResultChar = 12;
117193326Sed    break;
118193326Sed  case 'n':
119193326Sed    ResultChar = 10;
120193326Sed    break;
121193326Sed  case 'r':
122193326Sed    ResultChar = 13;
123193326Sed    break;
124193326Sed  case 't':
125193326Sed    ResultChar = 9;
126193326Sed    break;
127193326Sed  case 'v':
128193326Sed    ResultChar = 11;
129193326Sed    break;
130193326Sed  case 'x': { // Hex escape.
131193326Sed    ResultChar = 0;
132252723Sdim    if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
133218893Sdim      if (Diags)
134245431Sdim        Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
135252723Sdim             diag::err_hex_escape_no_digits) << "x";
136193326Sed      HadError = 1;
137193326Sed      break;
138193326Sed    }
139198092Srdivacky
140193326Sed    // Hex escapes are a maximal series of hex digits.
141193326Sed    bool Overflow = false;
142193326Sed    for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
143252723Sdim      int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
144193326Sed      if (CharVal == -1) break;
145193326Sed      // About to shift out a digit?
146193326Sed      Overflow |= (ResultChar & 0xF0000000) ? true : false;
147193326Sed      ResultChar <<= 4;
148193326Sed      ResultChar |= CharVal;
149193326Sed    }
150193326Sed
151193326Sed    // See if any bits will be truncated when evaluated as a character.
152193326Sed    if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
153193326Sed      Overflow = true;
154193326Sed      ResultChar &= ~0U >> (32-CharWidth);
155193326Sed    }
156198092Srdivacky
157193326Sed    // Check for overflow.
158218893Sdim    if (Overflow && Diags)   // Too many digits to fit in
159245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
160263509Sdim           diag::err_hex_escape_too_large);
161193326Sed    break;
162193326Sed  }
163193326Sed  case '0': case '1': case '2': case '3':
164193326Sed  case '4': case '5': case '6': case '7': {
165193326Sed    // Octal escapes.
166193326Sed    --ThisTokBuf;
167193326Sed    ResultChar = 0;
168193326Sed
169193326Sed    // Octal escapes are a series of octal digits with maximum length 3.
170193326Sed    // "\0123" is a two digit sequence equal to "\012" "3".
171193326Sed    unsigned NumDigits = 0;
172193326Sed    do {
173193326Sed      ResultChar <<= 3;
174193326Sed      ResultChar |= *ThisTokBuf++ - '0';
175193326Sed      ++NumDigits;
176193326Sed    } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
177193326Sed             ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
178198092Srdivacky
179193326Sed    // Check for overflow.  Reject '\777', but not L'\777'.
180193326Sed    if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
181218893Sdim      if (Diags)
182245431Sdim        Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
183263509Sdim             diag::err_octal_escape_too_large);
184193326Sed      ResultChar &= ~0U >> (32-CharWidth);
185193326Sed    }
186193326Sed    break;
187193326Sed  }
188198092Srdivacky
189193326Sed    // Otherwise, these are not valid escapes.
190193326Sed  case '(': case '{': case '[': case '%':
191193326Sed    // GCC accepts these as extensions.  We warn about them as such though.
192218893Sdim    if (Diags)
193245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
194245431Sdim           diag::ext_nonstandard_escape)
195245431Sdim        << std::string(1, ResultChar);
196193326Sed    break;
197193326Sed  default:
198218893Sdim    if (Diags == 0)
199208600Srdivacky      break;
200245431Sdim
201252723Sdim    if (isPrintable(ResultChar))
202245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
203245431Sdim           diag::ext_unknown_escape)
204245431Sdim        << std::string(1, ResultChar);
205193326Sed    else
206245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
207245431Sdim           diag::ext_unknown_escape)
208245431Sdim        << "x" + llvm::utohexstr(ResultChar);
209193326Sed    break;
210193326Sed  }
211198092Srdivacky
212193326Sed  return ResultChar;
213193326Sed}
214193326Sed
215193326Sed/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
216218893Sdim/// return the UTF32.
217235633Sdimstatic bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
218235633Sdim                             const char *ThisTokEnd,
219218893Sdim                             uint32_t &UcnVal, unsigned short &UcnLen,
220226890Sdim                             FullSourceLoc Loc, DiagnosticsEngine *Diags,
221235633Sdim                             const LangOptions &Features,
222235633Sdim                             bool in_char_string_literal = false) {
223235633Sdim  const char *UcnBegin = ThisTokBuf;
224198092Srdivacky
225193326Sed  // Skip the '\u' char's.
226193326Sed  ThisTokBuf += 2;
227193326Sed
228252723Sdim  if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
229218893Sdim    if (Diags)
230245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
231252723Sdim           diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
232218893Sdim    return false;
233193326Sed  }
234218893Sdim  UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
235212904Sdim  unsigned short UcnLenSave = UcnLen;
236218893Sdim  for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
237252723Sdim    int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
238193326Sed    if (CharVal == -1) break;
239193326Sed    UcnVal <<= 4;
240193326Sed    UcnVal |= CharVal;
241193326Sed  }
242193326Sed  // If we didn't consume the proper number of digits, there is a problem.
243218893Sdim  if (UcnLenSave) {
244245431Sdim    if (Diags)
245245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
246245431Sdim           diag::err_ucn_escape_incomplete);
247218893Sdim    return false;
248193326Sed  }
249235633Sdim
250235633Sdim  // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
251235633Sdim  if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
252235633Sdim      UcnVal > 0x10FFFF) {                      // maximum legal UTF32 value
253218893Sdim    if (Diags)
254245431Sdim      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
255245431Sdim           diag::err_ucn_escape_invalid);
256218893Sdim    return false;
257218893Sdim  }
258235633Sdim
259235633Sdim  // C++11 allows UCNs that refer to control characters and basic source
260235633Sdim  // characters inside character and string literals
261235633Sdim  if (UcnVal < 0xa0 &&
262235633Sdim      (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) {  // $, @, `
263252723Sdim    bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
264235633Sdim    if (Diags) {
265235633Sdim      char BasicSCSChar = UcnVal;
266235633Sdim      if (UcnVal >= 0x20 && UcnVal < 0x7f)
267245431Sdim        Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
268245431Sdim             IsError ? diag::err_ucn_escape_basic_scs :
269245431Sdim                       diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
270245431Sdim            << StringRef(&BasicSCSChar, 1);
271235633Sdim      else
272245431Sdim        Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
273245431Sdim             IsError ? diag::err_ucn_control_character :
274245431Sdim                       diag::warn_cxx98_compat_literal_ucn_control_character);
275235633Sdim    }
276235633Sdim    if (IsError)
277235633Sdim      return false;
278235633Sdim  }
279235633Sdim
280245431Sdim  if (!Features.CPlusPlus && !Features.C99 && Diags)
281245431Sdim    Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
282252723Sdim         diag::warn_ucn_not_valid_in_c89_literal);
283245431Sdim
284218893Sdim  return true;
285218893Sdim}
286218893Sdim
287245431Sdim/// MeasureUCNEscape - Determine the number of bytes within the resulting string
288245431Sdim/// which this UCN will occupy.
289245431Sdimstatic int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
290245431Sdim                            const char *ThisTokEnd, unsigned CharByteWidth,
291245431Sdim                            const LangOptions &Features, bool &HadError) {
292245431Sdim  // UTF-32: 4 bytes per escape.
293245431Sdim  if (CharByteWidth == 4)
294245431Sdim    return 4;
295245431Sdim
296245431Sdim  uint32_t UcnVal = 0;
297245431Sdim  unsigned short UcnLen = 0;
298245431Sdim  FullSourceLoc Loc;
299245431Sdim
300245431Sdim  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
301245431Sdim                        UcnLen, Loc, 0, Features, true)) {
302245431Sdim    HadError = true;
303245431Sdim    return 0;
304245431Sdim  }
305245431Sdim
306245431Sdim  // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
307245431Sdim  if (CharByteWidth == 2)
308245431Sdim    return UcnVal <= 0xFFFF ? 2 : 4;
309245431Sdim
310245431Sdim  // UTF-8.
311245431Sdim  if (UcnVal < 0x80)
312245431Sdim    return 1;
313245431Sdim  if (UcnVal < 0x800)
314245431Sdim    return 2;
315245431Sdim  if (UcnVal < 0x10000)
316245431Sdim    return 3;
317245431Sdim  return 4;
318245431Sdim}
319245431Sdim
320218893Sdim/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
321218893Sdim/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
322218893Sdim/// StringLiteralParser. When we decide to implement UCN's for identifiers,
323218893Sdim/// we will likely rework our support for UCN's.
324235633Sdimstatic void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
325235633Sdim                            const char *ThisTokEnd,
326218893Sdim                            char *&ResultBuf, bool &HadError,
327226890Sdim                            FullSourceLoc Loc, unsigned CharByteWidth,
328226890Sdim                            DiagnosticsEngine *Diags,
329218893Sdim                            const LangOptions &Features) {
330218893Sdim  typedef uint32_t UTF32;
331218893Sdim  UTF32 UcnVal = 0;
332218893Sdim  unsigned short UcnLen = 0;
333235633Sdim  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
334235633Sdim                        Loc, Diags, Features, true)) {
335245431Sdim    HadError = true;
336193326Sed    return;
337193326Sed  }
338218893Sdim
339263509Sdim  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
340226890Sdim         "only character widths of 1, 2, or 4 bytes supported");
341218893Sdim
342226890Sdim  (void)UcnLen;
343226890Sdim  assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
344218893Sdim
345226890Sdim  if (CharByteWidth == 4) {
346235633Sdim    // FIXME: Make the type of the result buffer correct instead of
347235633Sdim    // using reinterpret_cast.
348235633Sdim    UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
349235633Sdim    *ResultPtr = UcnVal;
350235633Sdim    ResultBuf += 4;
351226890Sdim    return;
352226890Sdim  }
353226890Sdim
354226890Sdim  if (CharByteWidth == 2) {
355235633Sdim    // FIXME: Make the type of the result buffer correct instead of
356235633Sdim    // using reinterpret_cast.
357235633Sdim    UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
358235633Sdim
359245431Sdim    if (UcnVal <= (UTF32)0xFFFF) {
360235633Sdim      *ResultPtr = UcnVal;
361235633Sdim      ResultBuf += 2;
362218893Sdim      return;
363218893Sdim    }
364218893Sdim
365235633Sdim    // Convert to UTF16.
366218893Sdim    UcnVal -= 0x10000;
367235633Sdim    *ResultPtr     = 0xD800 + (UcnVal >> 10);
368235633Sdim    *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
369235633Sdim    ResultBuf += 4;
370212904Sdim    return;
371212904Sdim  }
372226890Sdim
373226890Sdim  assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
374226890Sdim
375193326Sed  // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
376193326Sed  // The conversion below was inspired by:
377193326Sed  //   http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
378198092Srdivacky  // First, we determine how many bytes the result will require.
379193326Sed  typedef uint8_t UTF8;
380193326Sed
381193326Sed  unsigned short bytesToWrite = 0;
382193326Sed  if (UcnVal < (UTF32)0x80)
383193326Sed    bytesToWrite = 1;
384193326Sed  else if (UcnVal < (UTF32)0x800)
385193326Sed    bytesToWrite = 2;
386193326Sed  else if (UcnVal < (UTF32)0x10000)
387193326Sed    bytesToWrite = 3;
388193326Sed  else
389193326Sed    bytesToWrite = 4;
390198092Srdivacky
391193326Sed  const unsigned byteMask = 0xBF;
392193326Sed  const unsigned byteMark = 0x80;
393198092Srdivacky
394193326Sed  // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
395193326Sed  // into the first byte, depending on how many bytes follow.
396198092Srdivacky  static const UTF8 firstByteMark[5] = {
397193326Sed    0x00, 0x00, 0xC0, 0xE0, 0xF0
398193326Sed  };
399193326Sed  // Finally, we write the bytes into ResultBuf.
400193326Sed  ResultBuf += bytesToWrite;
401193326Sed  switch (bytesToWrite) { // note: everything falls through.
402245431Sdim  case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
403245431Sdim  case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
404245431Sdim  case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
405245431Sdim  case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
406193326Sed  }
407193326Sed  // Update the buffer.
408193326Sed  ResultBuf += bytesToWrite;
409193326Sed}
410193326Sed
411193326Sed
412193326Sed///       integer-constant: [C99 6.4.4.1]
413193326Sed///         decimal-constant integer-suffix
414193326Sed///         octal-constant integer-suffix
415193326Sed///         hexadecimal-constant integer-suffix
416263509Sdim///         binary-literal integer-suffix [GNU, C++1y]
417235633Sdim///       user-defined-integer-literal: [C++11 lex.ext]
418235633Sdim///         decimal-literal ud-suffix
419235633Sdim///         octal-literal ud-suffix
420235633Sdim///         hexadecimal-literal ud-suffix
421263509Sdim///         binary-literal ud-suffix [GNU, C++1y]
422198092Srdivacky///       decimal-constant:
423193326Sed///         nonzero-digit
424193326Sed///         decimal-constant digit
425198092Srdivacky///       octal-constant:
426193326Sed///         0
427193326Sed///         octal-constant octal-digit
428198092Srdivacky///       hexadecimal-constant:
429193326Sed///         hexadecimal-prefix hexadecimal-digit
430193326Sed///         hexadecimal-constant hexadecimal-digit
431193326Sed///       hexadecimal-prefix: one of
432193326Sed///         0x 0X
433263509Sdim///       binary-literal:
434263509Sdim///         0b binary-digit
435263509Sdim///         0B binary-digit
436263509Sdim///         binary-literal binary-digit
437193326Sed///       integer-suffix:
438193326Sed///         unsigned-suffix [long-suffix]
439193326Sed///         unsigned-suffix [long-long-suffix]
440193326Sed///         long-suffix [unsigned-suffix]
441193326Sed///         long-long-suffix [unsigned-sufix]
442193326Sed///       nonzero-digit:
443193326Sed///         1 2 3 4 5 6 7 8 9
444193326Sed///       octal-digit:
445193326Sed///         0 1 2 3 4 5 6 7
446193326Sed///       hexadecimal-digit:
447193326Sed///         0 1 2 3 4 5 6 7 8 9
448193326Sed///         a b c d e f
449193326Sed///         A B C D E F
450263509Sdim///       binary-digit:
451263509Sdim///         0
452263509Sdim///         1
453193326Sed///       unsigned-suffix: one of
454193326Sed///         u U
455193326Sed///       long-suffix: one of
456193326Sed///         l L
457198092Srdivacky///       long-long-suffix: one of
458193326Sed///         ll LL
459193326Sed///
460193326Sed///       floating-constant: [C99 6.4.4.2]
461193326Sed///         TODO: add rules...
462193326Sed///
463245431SdimNumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
464245431Sdim                                           SourceLocation TokLoc,
465245431Sdim                                           Preprocessor &PP)
466245431Sdim  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
467198092Srdivacky
468193326Sed  // This routine assumes that the range begin/end matches the regex for integer
469193326Sed  // and FP constants (specifically, the 'pp-number' regex), and assumes that
470193326Sed  // the byte at "*end" is both valid and not part of the regex.  Because of
471193326Sed  // this, it doesn't have to check for 'overscan' in various places.
472252723Sdim  assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
473198092Srdivacky
474245431Sdim  s = DigitsBegin = ThisTokBegin;
475193326Sed  saw_exponent = false;
476193326Sed  saw_period = false;
477235633Sdim  saw_ud_suffix = false;
478193326Sed  isLong = false;
479193326Sed  isUnsigned = false;
480193326Sed  isLongLong = false;
481193326Sed  isFloat = false;
482193326Sed  isImaginary = false;
483198092Srdivacky  isMicrosoftInteger = false;
484193326Sed  hadError = false;
485198092Srdivacky
486193326Sed  if (*s == '0') { // parse radix
487193326Sed    ParseNumberStartingWithZero(TokLoc);
488193326Sed    if (hadError)
489193326Sed      return;
490193326Sed  } else { // the first digit is non-zero
491193326Sed    radix = 10;
492193326Sed    s = SkipDigits(s);
493193326Sed    if (s == ThisTokEnd) {
494193326Sed      // Done.
495252723Sdim    } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) {
496245431Sdim      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
497226890Sdim              diag::err_invalid_decimal_digit) << StringRef(s, 1);
498193326Sed      hadError = true;
499193326Sed      return;
500193326Sed    } else if (*s == '.') {
501263509Sdim      checkSeparator(TokLoc, s, CSK_AfterDigits);
502193326Sed      s++;
503193326Sed      saw_period = true;
504263509Sdim      checkSeparator(TokLoc, s, CSK_BeforeDigits);
505193326Sed      s = SkipDigits(s);
506198092Srdivacky    }
507193326Sed    if ((*s == 'e' || *s == 'E')) { // exponent
508263509Sdim      checkSeparator(TokLoc, s, CSK_AfterDigits);
509193326Sed      const char *Exponent = s;
510193326Sed      s++;
511193326Sed      saw_exponent = true;
512193326Sed      if (*s == '+' || *s == '-')  s++; // sign
513263509Sdim      checkSeparator(TokLoc, s, CSK_BeforeDigits);
514193326Sed      const char *first_non_digit = SkipDigits(s);
515193326Sed      if (first_non_digit != s) {
516193326Sed        s = first_non_digit;
517193326Sed      } else {
518245431Sdim        PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
519193326Sed                diag::err_exponent_has_no_digits);
520193326Sed        hadError = true;
521193326Sed        return;
522193326Sed      }
523193326Sed    }
524193326Sed  }
525193326Sed
526193326Sed  SuffixBegin = s;
527263509Sdim  checkSeparator(TokLoc, s, CSK_AfterDigits);
528198092Srdivacky
529193326Sed  // Parse the suffix.  At this point we can classify whether we have an FP or
530193326Sed  // integer constant.
531193326Sed  bool isFPConstant = isFloatingLiteral();
532263509Sdim  const char *ImaginarySuffixLoc = 0;
533198092Srdivacky
534193326Sed  // Loop over all of the characters of the suffix.  If we see something bad,
535193326Sed  // we break out of the loop.
536193326Sed  for (; s != ThisTokEnd; ++s) {
537193326Sed    switch (*s) {
538193326Sed    case 'f':      // FP Suffix for "float"
539193326Sed    case 'F':
540193326Sed      if (!isFPConstant) break;  // Error for integer constant.
541193326Sed      if (isFloat || isLong) break; // FF, LF invalid.
542193326Sed      isFloat = true;
543193326Sed      continue;  // Success.
544193326Sed    case 'u':
545193326Sed    case 'U':
546193326Sed      if (isFPConstant) break;  // Error for floating constant.
547193326Sed      if (isUnsigned) break;    // Cannot be repeated.
548193326Sed      isUnsigned = true;
549193326Sed      continue;  // Success.
550193326Sed    case 'l':
551193326Sed    case 'L':
552193326Sed      if (isLong || isLongLong) break;  // Cannot be repeated.
553193326Sed      if (isFloat) break;               // LF invalid.
554198092Srdivacky
555193326Sed      // Check for long long.  The L's need to be adjacent and the same case.
556193326Sed      if (s+1 != ThisTokEnd && s[1] == s[0]) {
557193326Sed        if (isFPConstant) break;        // long long invalid for floats.
558193326Sed        isLongLong = true;
559193326Sed        ++s;  // Eat both of them.
560193326Sed      } else {
561193326Sed        isLong = true;
562193326Sed      }
563193326Sed      continue;  // Success.
564193326Sed    case 'i':
565218893Sdim    case 'I':
566235633Sdim      if (PP.getLangOpts().MicrosoftExt) {
567202879Srdivacky        if (isFPConstant || isLong || isLongLong) break;
568199990Srdivacky
569193326Sed        // Allow i8, i16, i32, i64, and i128.
570198092Srdivacky        if (s + 1 != ThisTokEnd) {
571198092Srdivacky          switch (s[1]) {
572198092Srdivacky            case '8':
573198092Srdivacky              s += 2; // i8 suffix
574198092Srdivacky              isMicrosoftInteger = true;
575199990Srdivacky              break;
576198092Srdivacky            case '1':
577199990Srdivacky              if (s + 2 == ThisTokEnd) break;
578218893Sdim              if (s[2] == '6') {
579218893Sdim                s += 3; // i16 suffix
580218893Sdim                isMicrosoftInteger = true;
581218893Sdim              }
582199990Srdivacky              else if (s[2] == '2') {
583199990Srdivacky                if (s + 3 == ThisTokEnd) break;
584218893Sdim                if (s[3] == '8') {
585218893Sdim                  s += 4; // i128 suffix
586218893Sdim                  isMicrosoftInteger = true;
587218893Sdim                }
588198092Srdivacky              }
589199990Srdivacky              break;
590198092Srdivacky            case '3':
591199990Srdivacky              if (s + 2 == ThisTokEnd) break;
592218893Sdim              if (s[2] == '2') {
593218893Sdim                s += 3; // i32 suffix
594218893Sdim                isLong = true;
595218893Sdim                isMicrosoftInteger = true;
596218893Sdim              }
597199990Srdivacky              break;
598198092Srdivacky            case '6':
599199990Srdivacky              if (s + 2 == ThisTokEnd) break;
600218893Sdim              if (s[2] == '4') {
601218893Sdim                s += 3; // i64 suffix
602218893Sdim                isLongLong = true;
603218893Sdim                isMicrosoftInteger = true;
604218893Sdim              }
605199990Srdivacky              break;
606198092Srdivacky            default:
607198092Srdivacky              break;
608198092Srdivacky          }
609198092Srdivacky          break;
610193326Sed        }
611193326Sed      }
612263509Sdim      // "i", "if", and "il" are user-defined suffixes in C++1y.
613263509Sdim      if (PP.getLangOpts().CPlusPlus1y && *s == 'i')
614263509Sdim        break;
615193326Sed      // fall through.
616193326Sed    case 'j':
617193326Sed    case 'J':
618193326Sed      if (isImaginary) break;   // Cannot be repeated.
619193326Sed      isImaginary = true;
620263509Sdim      ImaginarySuffixLoc = s;
621193326Sed      continue;  // Success.
622193326Sed    }
623235633Sdim    // If we reached here, there was an error or a ud-suffix.
624193326Sed    break;
625193326Sed  }
626198092Srdivacky
627193326Sed  if (s != ThisTokEnd) {
628263509Sdim    if (isValidUDSuffix(PP.getLangOpts(),
629263509Sdim                        StringRef(SuffixBegin, ThisTokEnd - SuffixBegin))) {
630263509Sdim      // Any suffix pieces we might have parsed are actually part of the
631263509Sdim      // ud-suffix.
632263509Sdim      isLong = false;
633263509Sdim      isUnsigned = false;
634263509Sdim      isLongLong = false;
635263509Sdim      isFloat = false;
636263509Sdim      isImaginary = false;
637263509Sdim      isMicrosoftInteger = false;
638263509Sdim
639235633Sdim      saw_ud_suffix = true;
640235633Sdim      return;
641235633Sdim    }
642235633Sdim
643235633Sdim    // Report an error if there are any.
644245431Sdim    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
645193326Sed            isFPConstant ? diag::err_invalid_suffix_float_constant :
646193326Sed                           diag::err_invalid_suffix_integer_constant)
647226890Sdim      << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
648193326Sed    hadError = true;
649193326Sed    return;
650193326Sed  }
651263509Sdim
652263509Sdim  if (isImaginary) {
653263509Sdim    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
654263509Sdim                                       ImaginarySuffixLoc - ThisTokBegin),
655263509Sdim            diag::ext_imaginary_constant);
656263509Sdim  }
657193326Sed}
658193326Sed
659263509Sdim/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
660263509Sdim/// suffixes as ud-suffixes, because the diagnostic experience is better if we
661263509Sdim/// treat it as an invalid suffix.
662263509Sdimbool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
663263509Sdim                                           StringRef Suffix) {
664263509Sdim  if (!LangOpts.CPlusPlus11 || Suffix.empty())
665263509Sdim    return false;
666263509Sdim
667263509Sdim  // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
668263509Sdim  if (Suffix[0] == '_')
669263509Sdim    return true;
670263509Sdim
671263509Sdim  // In C++11, there are no library suffixes.
672263509Sdim  if (!LangOpts.CPlusPlus1y)
673263509Sdim    return false;
674263509Sdim
675263509Sdim  // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
676263509Sdim  // Per tweaked N3660, "il", "i", and "if" are also used in the library.
677263509Sdim  return llvm::StringSwitch<bool>(Suffix)
678263509Sdim      .Cases("h", "min", "s", true)
679263509Sdim      .Cases("ms", "us", "ns", true)
680263509Sdim      .Cases("il", "i", "if", true)
681263509Sdim      .Default(false);
682263509Sdim}
683263509Sdim
684263509Sdimvoid NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
685263509Sdim                                          const char *Pos,
686263509Sdim                                          CheckSeparatorKind IsAfterDigits) {
687263509Sdim  if (IsAfterDigits == CSK_AfterDigits) {
688263509Sdim    if (Pos == ThisTokBegin)
689263509Sdim      return;
690263509Sdim    --Pos;
691263509Sdim  } else if (Pos == ThisTokEnd)
692263509Sdim    return;
693263509Sdim
694263509Sdim  if (isDigitSeparator(*Pos))
695263509Sdim    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
696263509Sdim            diag::err_digit_separator_not_between_digits)
697263509Sdim      << IsAfterDigits;
698263509Sdim}
699263509Sdim
700193326Sed/// ParseNumberStartingWithZero - This method is called when the first character
701193326Sed/// of the number is found to be a zero.  This means it is either an octal
702193326Sed/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
703198092Srdivacky/// a floating point number (01239.123e4).  Eat the prefix, determining the
704193326Sed/// radix etc.
705193326Sedvoid NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
706193326Sed  assert(s[0] == '0' && "Invalid method call");
707193326Sed  s++;
708198092Srdivacky
709263509Sdim  int c1 = s[0];
710263509Sdim  int c2 = s[1];
711263509Sdim
712193326Sed  // Handle a hex number like 0x1234.
713263509Sdim  if ((c1 == 'x' || c1 == 'X') && (isHexDigit(c2) || c2 == '.')) {
714193326Sed    s++;
715193326Sed    radix = 16;
716193326Sed    DigitsBegin = s;
717193326Sed    s = SkipHexDigits(s);
718235633Sdim    bool noSignificand = (s == DigitsBegin);
719193326Sed    if (s == ThisTokEnd) {
720193326Sed      // Done.
721193326Sed    } else if (*s == '.') {
722193326Sed      s++;
723193326Sed      saw_period = true;
724235633Sdim      const char *floatDigitsBegin = s;
725193326Sed      s = SkipHexDigits(s);
726235633Sdim      noSignificand &= (floatDigitsBegin == s);
727193326Sed    }
728235633Sdim
729235633Sdim    if (noSignificand) {
730245431Sdim      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
731235633Sdim        diag::err_hexconstant_requires_digits);
732235633Sdim      hadError = true;
733235633Sdim      return;
734235633Sdim    }
735235633Sdim
736193326Sed    // A binary exponent can appear with or with a '.'. If dotted, the
737198092Srdivacky    // binary exponent is required.
738226890Sdim    if (*s == 'p' || *s == 'P') {
739193326Sed      const char *Exponent = s;
740193326Sed      s++;
741193326Sed      saw_exponent = true;
742193326Sed      if (*s == '+' || *s == '-')  s++; // sign
743193326Sed      const char *first_non_digit = SkipDigits(s);
744193326Sed      if (first_non_digit == s) {
745193326Sed        PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
746193326Sed                diag::err_exponent_has_no_digits);
747193326Sed        hadError = true;
748193326Sed        return;
749193326Sed      }
750193326Sed      s = first_non_digit;
751198092Srdivacky
752235633Sdim      if (!PP.getLangOpts().HexFloats)
753193326Sed        PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
754193326Sed    } else if (saw_period) {
755193326Sed      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
756193326Sed              diag::err_hexconstant_requires_exponent);
757193326Sed      hadError = true;
758193326Sed    }
759193326Sed    return;
760193326Sed  }
761198092Srdivacky
762193326Sed  // Handle simple binary numbers 0b01010
763263509Sdim  if ((c1 == 'b' || c1 == 'B') && (c2 == '0' || c2 == '1')) {
764252723Sdim    // 0b101010 is a C++1y / GCC extension.
765252723Sdim    PP.Diag(TokLoc,
766252723Sdim            PP.getLangOpts().CPlusPlus1y
767252723Sdim              ? diag::warn_cxx11_compat_binary_literal
768252723Sdim              : PP.getLangOpts().CPlusPlus
769252723Sdim                ? diag::ext_binary_literal_cxx1y
770252723Sdim                : diag::ext_binary_literal);
771193326Sed    ++s;
772193326Sed    radix = 2;
773193326Sed    DigitsBegin = s;
774193326Sed    s = SkipBinaryDigits(s);
775193326Sed    if (s == ThisTokEnd) {
776193326Sed      // Done.
777252723Sdim    } else if (isHexDigit(*s)) {
778193326Sed      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
779226890Sdim              diag::err_invalid_binary_digit) << StringRef(s, 1);
780193326Sed      hadError = true;
781193326Sed    }
782193326Sed    // Other suffixes will be diagnosed by the caller.
783193326Sed    return;
784193326Sed  }
785198092Srdivacky
786193326Sed  // For now, the radix is set to 8. If we discover that we have a
787193326Sed  // floating point constant, the radix will change to 10. Octal floating
788198092Srdivacky  // point constants are not permitted (only decimal and hexadecimal).
789193326Sed  radix = 8;
790193326Sed  DigitsBegin = s;
791193326Sed  s = SkipOctalDigits(s);
792193326Sed  if (s == ThisTokEnd)
793193326Sed    return; // Done, simple octal number like 01234
794198092Srdivacky
795193326Sed  // If we have some other non-octal digit that *is* a decimal digit, see if
796193326Sed  // this is part of a floating point number like 094.123 or 09e1.
797252723Sdim  if (isDigit(*s)) {
798193326Sed    const char *EndDecimal = SkipDigits(s);
799193326Sed    if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
800193326Sed      s = EndDecimal;
801193326Sed      radix = 10;
802193326Sed    }
803193326Sed  }
804198092Srdivacky
805193326Sed  // If we have a hex digit other than 'e' (which denotes a FP exponent) then
806193326Sed  // the code is using an incorrect base.
807252723Sdim  if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
808193326Sed    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
809226890Sdim            diag::err_invalid_octal_digit) << StringRef(s, 1);
810193326Sed    hadError = true;
811193326Sed    return;
812193326Sed  }
813198092Srdivacky
814193326Sed  if (*s == '.') {
815193326Sed    s++;
816193326Sed    radix = 10;
817193326Sed    saw_period = true;
818193326Sed    s = SkipDigits(s); // Skip suffix.
819193326Sed  }
820193326Sed  if (*s == 'e' || *s == 'E') { // exponent
821193326Sed    const char *Exponent = s;
822193326Sed    s++;
823193326Sed    radix = 10;
824193326Sed    saw_exponent = true;
825193326Sed    if (*s == '+' || *s == '-')  s++; // sign
826193326Sed    const char *first_non_digit = SkipDigits(s);
827193326Sed    if (first_non_digit != s) {
828193326Sed      s = first_non_digit;
829193326Sed    } else {
830198092Srdivacky      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
831193326Sed              diag::err_exponent_has_no_digits);
832193326Sed      hadError = true;
833193326Sed      return;
834193326Sed    }
835193326Sed  }
836193326Sed}
837193326Sed
838245431Sdimstatic bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
839245431Sdim  switch (Radix) {
840245431Sdim  case 2:
841245431Sdim    return NumDigits <= 64;
842245431Sdim  case 8:
843245431Sdim    return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
844245431Sdim  case 10:
845245431Sdim    return NumDigits <= 19; // floor(log10(2^64))
846245431Sdim  case 16:
847245431Sdim    return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
848245431Sdim  default:
849245431Sdim    llvm_unreachable("impossible Radix");
850245431Sdim  }
851245431Sdim}
852193326Sed
853193326Sed/// GetIntegerValue - Convert this numeric literal value to an APInt that
854193326Sed/// matches Val's input width.  If there is an overflow, set Val to the low bits
855193326Sed/// of the result and return true.  Otherwise, return false.
856193326Sedbool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
857193326Sed  // Fast path: Compute a conservative bound on the maximum number of
858193326Sed  // bits per digit in this radix. If we can't possibly overflow a
859193326Sed  // uint64 based on that bound then do the simple conversion to
860193326Sed  // integer. This avoids the expensive overflow checking below, and
861193326Sed  // handles the common cases that matter (small decimal integers and
862193326Sed  // hex/octal values which don't overflow).
863245431Sdim  const unsigned NumDigits = SuffixBegin - DigitsBegin;
864245431Sdim  if (alwaysFitsInto64Bits(radix, NumDigits)) {
865193326Sed    uint64_t N = 0;
866245431Sdim    for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
867263509Sdim      if (!isDigitSeparator(*Ptr))
868263509Sdim        N = N * radix + llvm::hexDigitValue(*Ptr);
869193326Sed
870193326Sed    // This will truncate the value to Val's input width. Simply check
871193326Sed    // for overflow by comparing.
872193326Sed    Val = N;
873193326Sed    return Val.getZExtValue() != N;
874193326Sed  }
875193326Sed
876193326Sed  Val = 0;
877245431Sdim  const char *Ptr = DigitsBegin;
878193326Sed
879193326Sed  llvm::APInt RadixVal(Val.getBitWidth(), radix);
880193326Sed  llvm::APInt CharVal(Val.getBitWidth(), 0);
881193326Sed  llvm::APInt OldVal = Val;
882198092Srdivacky
883193326Sed  bool OverflowOccurred = false;
884245431Sdim  while (Ptr < SuffixBegin) {
885263509Sdim    if (isDigitSeparator(*Ptr)) {
886263509Sdim      ++Ptr;
887263509Sdim      continue;
888263509Sdim    }
889263509Sdim
890252723Sdim    unsigned C = llvm::hexDigitValue(*Ptr++);
891198092Srdivacky
892193326Sed    // If this letter is out of bound for this radix, reject it.
893193326Sed    assert(C < radix && "NumericLiteralParser ctor should have rejected this");
894198092Srdivacky
895193326Sed    CharVal = C;
896198092Srdivacky
897193326Sed    // Add the digit to the value in the appropriate radix.  If adding in digits
898193326Sed    // made the value smaller, then this overflowed.
899193326Sed    OldVal = Val;
900193326Sed
901193326Sed    // Multiply by radix, did overflow occur on the multiply?
902193326Sed    Val *= RadixVal;
903193326Sed    OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
904193326Sed
905193326Sed    // Add value, did overflow occur on the value?
906193326Sed    //   (a + b) ult b  <=> overflow
907193326Sed    Val += CharVal;
908193326Sed    OverflowOccurred |= Val.ult(CharVal);
909193326Sed  }
910193326Sed  return OverflowOccurred;
911193326Sed}
912193326Sed
913201361Srdivackyllvm::APFloat::opStatus
914201361SrdivackyNumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
915193326Sed  using llvm::APFloat;
916198092Srdivacky
917198092Srdivacky  unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
918263509Sdim
919263509Sdim  llvm::SmallString<16> Buffer;
920263509Sdim  StringRef Str(ThisTokBegin, n);
921263509Sdim  if (Str.find('\'') != StringRef::npos) {
922263509Sdim    Buffer.reserve(n);
923263509Sdim    std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
924263509Sdim                        &isDigitSeparator);
925263509Sdim    Str = Buffer;
926263509Sdim  }
927263509Sdim
928263509Sdim  return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
929193326Sed}
930193326Sed
931193326Sed
932245431Sdim/// \verbatim
933235633Sdim///       user-defined-character-literal: [C++11 lex.ext]
934235633Sdim///         character-literal ud-suffix
935235633Sdim///       ud-suffix:
936235633Sdim///         identifier
937235633Sdim///       character-literal: [C++11 lex.ccon]
938226890Sdim///         ' c-char-sequence '
939226890Sdim///         u' c-char-sequence '
940226890Sdim///         U' c-char-sequence '
941226890Sdim///         L' c-char-sequence '
942226890Sdim///       c-char-sequence:
943226890Sdim///         c-char
944226890Sdim///         c-char-sequence c-char
945226890Sdim///       c-char:
946226890Sdim///         any member of the source character set except the single-quote ',
947226890Sdim///           backslash \, or new-line character
948226890Sdim///         escape-sequence
949226890Sdim///         universal-character-name
950235633Sdim///       escape-sequence:
951226890Sdim///         simple-escape-sequence
952226890Sdim///         octal-escape-sequence
953226890Sdim///         hexadecimal-escape-sequence
954226890Sdim///       simple-escape-sequence:
955226890Sdim///         one of \' \" \? \\ \a \b \f \n \r \t \v
956226890Sdim///       octal-escape-sequence:
957226890Sdim///         \ octal-digit
958226890Sdim///         \ octal-digit octal-digit
959226890Sdim///         \ octal-digit octal-digit octal-digit
960226890Sdim///       hexadecimal-escape-sequence:
961226890Sdim///         \x hexadecimal-digit
962226890Sdim///         hexadecimal-escape-sequence hexadecimal-digit
963235633Sdim///       universal-character-name: [C++11 lex.charset]
964226890Sdim///         \u hex-quad
965226890Sdim///         \U hex-quad hex-quad
966226890Sdim///       hex-quad:
967226890Sdim///         hex-digit hex-digit hex-digit hex-digit
968245431Sdim/// \endverbatim
969226890Sdim///
970193326SedCharLiteralParser::CharLiteralParser(const char *begin, const char *end,
971226890Sdim                                     SourceLocation Loc, Preprocessor &PP,
972226890Sdim                                     tok::TokenKind kind) {
973235633Sdim  // At this point we know that the character matches the regex "(L|u|U)?'.*'".
974193326Sed  HadError = false;
975198092Srdivacky
976226890Sdim  Kind = kind;
977198092Srdivacky
978235633Sdim  const char *TokBegin = begin;
979235633Sdim
980235633Sdim  // Skip over wide character determinant.
981235633Sdim  if (Kind != tok::char_constant) {
982226890Sdim    ++begin;
983226890Sdim  }
984226890Sdim
985193326Sed  // Skip over the entry quote.
986193326Sed  assert(begin[0] == '\'' && "Invalid token lexed");
987193326Sed  ++begin;
988193326Sed
989235633Sdim  // Remove an optional ud-suffix.
990235633Sdim  if (end[-1] != '\'') {
991235633Sdim    const char *UDSuffixEnd = end;
992235633Sdim    do {
993235633Sdim      --end;
994235633Sdim    } while (end[-1] != '\'');
995235633Sdim    UDSuffixBuf.assign(end, UDSuffixEnd);
996235633Sdim    UDSuffixOffset = end - TokBegin;
997235633Sdim  }
998235633Sdim
999235633Sdim  // Trim the ending quote.
1000235633Sdim  assert(end != begin && "Invalid token lexed");
1001235633Sdim  --end;
1002235633Sdim
1003198092Srdivacky  // FIXME: The "Value" is an uint64_t so we can handle char literals of
1004221345Sdim  // up to 64-bits.
1005193326Sed  // FIXME: This extensively assumes that 'char' is 8-bits.
1006193326Sed  assert(PP.getTargetInfo().getCharWidth() == 8 &&
1007193326Sed         "Assumes char is 8 bits");
1008193326Sed  assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1009193326Sed         (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1010193326Sed         "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1011193326Sed  assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1012193326Sed         "Assumes sizeof(wchar) on target is <= 64");
1013193326Sed
1014263509Sdim  SmallVector<uint32_t, 4> codepoint_buffer;
1015263509Sdim  codepoint_buffer.resize(end - begin);
1016235633Sdim  uint32_t *buffer_begin = &codepoint_buffer.front();
1017235633Sdim  uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1018198092Srdivacky
1019235633Sdim  // Unicode escapes representing characters that cannot be correctly
1020235633Sdim  // represented in a single code unit are disallowed in character literals
1021235633Sdim  // by this implementation.
1022235633Sdim  uint32_t largest_character_for_kind;
1023235633Sdim  if (tok::wide_char_constant == Kind) {
1024263509Sdim    largest_character_for_kind =
1025263509Sdim        0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1026235633Sdim  } else if (tok::utf16_char_constant == Kind) {
1027235633Sdim    largest_character_for_kind = 0xFFFF;
1028235633Sdim  } else if (tok::utf32_char_constant == Kind) {
1029235633Sdim    largest_character_for_kind = 0x10FFFF;
1030235633Sdim  } else {
1031235633Sdim    largest_character_for_kind = 0x7Fu;
1032235633Sdim  }
1033218893Sdim
1034263509Sdim  while (begin != end) {
1035235633Sdim    // Is this a span of non-escape characters?
1036235633Sdim    if (begin[0] != '\\') {
1037235633Sdim      char const *start = begin;
1038235633Sdim      do {
1039235633Sdim        ++begin;
1040235633Sdim      } while (begin != end && *begin != '\\');
1041235633Sdim
1042235633Sdim      char const *tmp_in_start = start;
1043235633Sdim      uint32_t *tmp_out_start = buffer_begin;
1044235633Sdim      ConversionResult res =
1045263509Sdim          ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1046263509Sdim                             reinterpret_cast<UTF8 const *>(begin),
1047263509Sdim                             &buffer_begin, buffer_end, strictConversion);
1048263509Sdim      if (res != conversionOK) {
1049263509Sdim        // If we see bad encoding for unprefixed character literals, warn and
1050263509Sdim        // simply copy the byte values, for compatibility with gcc and
1051235633Sdim        // older versions of clang.
1052235633Sdim        bool NoErrorOnBadEncoding = isAscii();
1053235633Sdim        unsigned Msg = diag::err_bad_character_encoding;
1054235633Sdim        if (NoErrorOnBadEncoding)
1055235633Sdim          Msg = diag::warn_bad_character_encoding;
1056235633Sdim        PP.Diag(Loc, Msg);
1057235633Sdim        if (NoErrorOnBadEncoding) {
1058235633Sdim          start = tmp_in_start;
1059235633Sdim          buffer_begin = tmp_out_start;
1060263509Sdim          for (; start != begin; ++start, ++buffer_begin)
1061235633Sdim            *buffer_begin = static_cast<uint8_t>(*start);
1062235633Sdim        } else {
1063235633Sdim          HadError = true;
1064218893Sdim        }
1065235633Sdim      } else {
1066263509Sdim        for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1067235633Sdim          if (*tmp_out_start > largest_character_for_kind) {
1068235633Sdim            HadError = true;
1069235633Sdim            PP.Diag(Loc, diag::err_character_too_large);
1070235633Sdim          }
1071226890Sdim        }
1072218893Sdim      }
1073235633Sdim
1074235633Sdim      continue;
1075218893Sdim    }
1076263509Sdim    // Is this a Universal Character Name escape?
1077235633Sdim    if (begin[1] == 'u' || begin[1] == 'U') {
1078235633Sdim      unsigned short UcnLen = 0;
1079235633Sdim      if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1080235633Sdim                            FullSourceLoc(Loc, PP.getSourceManager()),
1081263509Sdim                            &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1082235633Sdim        HadError = true;
1083235633Sdim      } else if (*buffer_begin > largest_character_for_kind) {
1084235633Sdim        HadError = true;
1085245431Sdim        PP.Diag(Loc, diag::err_character_too_large);
1086235633Sdim      }
1087193326Sed
1088235633Sdim      ++buffer_begin;
1089235633Sdim      continue;
1090193326Sed    }
1091235633Sdim    unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1092235633Sdim    uint64_t result =
1093245431Sdim      ProcessCharEscape(TokBegin, begin, end, HadError,
1094245431Sdim                        FullSourceLoc(Loc,PP.getSourceManager()),
1095245431Sdim                        CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1096235633Sdim    *buffer_begin++ = result;
1097193326Sed  }
1098193326Sed
1099263509Sdim  unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1100235633Sdim
1101193326Sed  if (NumCharsSoFar > 1) {
1102235633Sdim    if (isWide())
1103226890Sdim      PP.Diag(Loc, diag::warn_extraneous_char_constant);
1104235633Sdim    else if (isAscii() && NumCharsSoFar == 4)
1105235633Sdim      PP.Diag(Loc, diag::ext_four_char_character_literal);
1106235633Sdim    else if (isAscii())
1107193326Sed      PP.Diag(Loc, diag::ext_multichar_character_literal);
1108193326Sed    else
1109235633Sdim      PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1110193326Sed    IsMultiChar = true;
1111263509Sdim  } else {
1112198092Srdivacky    IsMultiChar = false;
1113263509Sdim  }
1114193326Sed
1115235633Sdim  llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1116235633Sdim
1117235633Sdim  // Narrow character literals act as though their value is concatenated
1118235633Sdim  // in this implementation, but warn on overflow.
1119235633Sdim  bool multi_char_too_long = false;
1120235633Sdim  if (isAscii() && isMultiChar()) {
1121235633Sdim    LitVal = 0;
1122263509Sdim    for (size_t i = 0; i < NumCharsSoFar; ++i) {
1123235633Sdim      // check for enough leading zeros to shift into
1124235633Sdim      multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1125235633Sdim      LitVal <<= 8;
1126235633Sdim      LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1127235633Sdim    }
1128235633Sdim  } else if (NumCharsSoFar > 0) {
1129235633Sdim    // otherwise just take the last character
1130235633Sdim    LitVal = buffer_begin[-1];
1131235633Sdim  }
1132235633Sdim
1133235633Sdim  if (!HadError && multi_char_too_long) {
1134263509Sdim    PP.Diag(Loc, diag::warn_char_constant_too_large);
1135235633Sdim  }
1136235633Sdim
1137193326Sed  // Transfer the value from APInt to uint64_t
1138193326Sed  Value = LitVal.getZExtValue();
1139198092Srdivacky
1140193326Sed  // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1141193326Sed  // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
1142193326Sed  // character constants are not sign extended in the this implementation:
1143193326Sed  // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1144226890Sdim  if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1145235633Sdim      PP.getLangOpts().CharIsSigned)
1146193326Sed    Value = (signed char)Value;
1147193326Sed}
1148193326Sed
1149245431Sdim/// \verbatim
1150226890Sdim///       string-literal: [C++0x lex.string]
1151226890Sdim///         encoding-prefix " [s-char-sequence] "
1152226890Sdim///         encoding-prefix R raw-string
1153226890Sdim///       encoding-prefix:
1154226890Sdim///         u8
1155226890Sdim///         u
1156226890Sdim///         U
1157226890Sdim///         L
1158193326Sed///       s-char-sequence:
1159193326Sed///         s-char
1160193326Sed///         s-char-sequence s-char
1161193326Sed///       s-char:
1162226890Sdim///         any member of the source character set except the double-quote ",
1163226890Sdim///           backslash \, or new-line character
1164226890Sdim///         escape-sequence
1165193326Sed///         universal-character-name
1166226890Sdim///       raw-string:
1167226890Sdim///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
1168226890Sdim///       r-char-sequence:
1169226890Sdim///         r-char
1170226890Sdim///         r-char-sequence r-char
1171226890Sdim///       r-char:
1172226890Sdim///         any member of the source character set, except a right parenthesis )
1173226890Sdim///           followed by the initial d-char-sequence (which may be empty)
1174226890Sdim///           followed by a double quote ".
1175226890Sdim///       d-char-sequence:
1176226890Sdim///         d-char
1177226890Sdim///         d-char-sequence d-char
1178226890Sdim///       d-char:
1179226890Sdim///         any member of the basic source character set except:
1180226890Sdim///           space, the left parenthesis (, the right parenthesis ),
1181226890Sdim///           the backslash \, and the control characters representing horizontal
1182226890Sdim///           tab, vertical tab, form feed, and newline.
1183226890Sdim///       escape-sequence: [C++0x lex.ccon]
1184226890Sdim///         simple-escape-sequence
1185226890Sdim///         octal-escape-sequence
1186226890Sdim///         hexadecimal-escape-sequence
1187226890Sdim///       simple-escape-sequence:
1188226890Sdim///         one of \' \" \? \\ \a \b \f \n \r \t \v
1189226890Sdim///       octal-escape-sequence:
1190226890Sdim///         \ octal-digit
1191226890Sdim///         \ octal-digit octal-digit
1192226890Sdim///         \ octal-digit octal-digit octal-digit
1193226890Sdim///       hexadecimal-escape-sequence:
1194226890Sdim///         \x hexadecimal-digit
1195226890Sdim///         hexadecimal-escape-sequence hexadecimal-digit
1196193326Sed///       universal-character-name:
1197193326Sed///         \u hex-quad
1198193326Sed///         \U hex-quad hex-quad
1199193326Sed///       hex-quad:
1200193326Sed///         hex-digit hex-digit hex-digit hex-digit
1201245431Sdim/// \endverbatim
1202193326Sed///
1203193326SedStringLiteralParser::
1204193326SedStringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1205218893Sdim                    Preprocessor &PP, bool Complain)
1206235633Sdim  : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1207223017Sdim    Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1208226890Sdim    MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1209226890Sdim    ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1210218893Sdim  init(StringToks, NumStringToks);
1211218893Sdim}
1212218893Sdim
1213218893Sdimvoid StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1214223017Sdim  // The literal token may have come from an invalid source location (e.g. due
1215223017Sdim  // to a PCH error), in which case the token length will be 0.
1216245431Sdim  if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1217245431Sdim    return DiagnoseLexingError(SourceLocation());
1218223017Sdim
1219193326Sed  // Scan all of the string portions, remember the max individual token length,
1220193326Sed  // computing a bound on the concatenated string length, and see whether any
1221193326Sed  // piece is a wide-string.  If any of the string portions is a wide-string
1222193326Sed  // literal, the result is a wide-string literal [C99 6.4.5p4].
1223223017Sdim  assert(NumStringToks && "expected at least one token");
1224193326Sed  MaxTokenLength = StringToks[0].getLength();
1225223017Sdim  assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1226193326Sed  SizeBound = StringToks[0].getLength()-2;  // -2 for "".
1227226890Sdim  Kind = StringToks[0].getKind();
1228198092Srdivacky
1229193326Sed  hadError = false;
1230193326Sed
1231193326Sed  // Implement Translation Phase #6: concatenation of string literals
1232193326Sed  /// (C99 5.1.1.2p1).  The common case is only one string fragment.
1233193326Sed  for (unsigned i = 1; i != NumStringToks; ++i) {
1234245431Sdim    if (StringToks[i].getLength() < 2)
1235245431Sdim      return DiagnoseLexingError(StringToks[i].getLocation());
1236223017Sdim
1237193326Sed    // The string could be shorter than this if it needs cleaning, but this is a
1238193326Sed    // reasonable bound, which is all we need.
1239223017Sdim    assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1240193326Sed    SizeBound += StringToks[i].getLength()-2;  // -2 for "".
1241198092Srdivacky
1242193326Sed    // Remember maximum string piece length.
1243198092Srdivacky    if (StringToks[i].getLength() > MaxTokenLength)
1244193326Sed      MaxTokenLength = StringToks[i].getLength();
1245198092Srdivacky
1246226890Sdim    // Remember if we see any wide or utf-8/16/32 strings.
1247226890Sdim    // Also check for illegal concatenations.
1248226890Sdim    if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1249226890Sdim      if (isAscii()) {
1250226890Sdim        Kind = StringToks[i].getKind();
1251226890Sdim      } else {
1252226890Sdim        if (Diags)
1253245431Sdim          Diags->Report(StringToks[i].getLocation(),
1254226890Sdim                        diag::err_unsupported_string_concat);
1255226890Sdim        hadError = true;
1256226890Sdim      }
1257226890Sdim    }
1258193326Sed  }
1259193326Sed
1260193326Sed  // Include space for the null terminator.
1261193326Sed  ++SizeBound;
1262198092Srdivacky
1263193326Sed  // TODO: K&R warning: "traditional C rejects string constant concatenation"
1264198092Srdivacky
1265226890Sdim  // Get the width in bytes of char/wchar_t/char16_t/char32_t
1266226890Sdim  CharByteWidth = getCharWidth(Kind, Target);
1267226890Sdim  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1268226890Sdim  CharByteWidth /= 8;
1269198092Srdivacky
1270193326Sed  // The output buffer size needs to be large enough to hold wide characters.
1271193326Sed  // This is a worst-case assumption which basically corresponds to L"" "long".
1272226890Sdim  SizeBound *= CharByteWidth;
1273198092Srdivacky
1274193326Sed  // Size the temporary buffer to hold the result string data.
1275193326Sed  ResultBuf.resize(SizeBound);
1276198092Srdivacky
1277193326Sed  // Likewise, but for each string piece.
1278235633Sdim  SmallString<512> TokenBuf;
1279193326Sed  TokenBuf.resize(MaxTokenLength);
1280198092Srdivacky
1281193326Sed  // Loop over all the strings, getting their spelling, and expanding them to
1282193326Sed  // wide strings as appropriate.
1283193326Sed  ResultPtr = &ResultBuf[0];   // Next byte to fill in.
1284198092Srdivacky
1285193326Sed  Pascal = false;
1286198092Srdivacky
1287235633Sdim  SourceLocation UDSuffixTokLoc;
1288235633Sdim
1289193326Sed  for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1290193326Sed    const char *ThisTokBuf = &TokenBuf[0];
1291193326Sed    // Get the spelling of the token, which eliminates trigraphs, etc.  We know
1292193326Sed    // that ThisTokBuf points to a buffer that is big enough for the whole token
1293193326Sed    // and 'spelled' tokens can only shrink.
1294205219Srdivacky    bool StringInvalid = false;
1295218893Sdim    unsigned ThisTokLen =
1296218893Sdim      Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1297218893Sdim                         &StringInvalid);
1298245431Sdim    if (StringInvalid)
1299245431Sdim      return DiagnoseLexingError(StringToks[i].getLocation());
1300205219Srdivacky
1301235633Sdim    const char *ThisTokBegin = ThisTokBuf;
1302235633Sdim    const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1303235633Sdim
1304235633Sdim    // Remove an optional ud-suffix.
1305235633Sdim    if (ThisTokEnd[-1] != '"') {
1306235633Sdim      const char *UDSuffixEnd = ThisTokEnd;
1307235633Sdim      do {
1308235633Sdim        --ThisTokEnd;
1309235633Sdim      } while (ThisTokEnd[-1] != '"');
1310235633Sdim
1311235633Sdim      StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1312235633Sdim
1313235633Sdim      if (UDSuffixBuf.empty()) {
1314235633Sdim        UDSuffixBuf.assign(UDSuffix);
1315235633Sdim        UDSuffixToken = i;
1316235633Sdim        UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1317235633Sdim        UDSuffixTokLoc = StringToks[i].getLocation();
1318235633Sdim      } else if (!UDSuffixBuf.equals(UDSuffix)) {
1319235633Sdim        // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1320235633Sdim        // result of a concatenation involving at least one user-defined-string-
1321235633Sdim        // literal, all the participating user-defined-string-literals shall
1322235633Sdim        // have the same ud-suffix.
1323235633Sdim        if (Diags) {
1324235633Sdim          SourceLocation TokLoc = StringToks[i].getLocation();
1325235633Sdim          Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1326235633Sdim            << UDSuffixBuf << UDSuffix
1327235633Sdim            << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1328235633Sdim            << SourceRange(TokLoc, TokLoc);
1329235633Sdim        }
1330235633Sdim        hadError = true;
1331235633Sdim      }
1332235633Sdim    }
1333235633Sdim
1334235633Sdim    // Strip the end quote.
1335235633Sdim    --ThisTokEnd;
1336235633Sdim
1337193326Sed    // TODO: Input character set mapping support.
1338198092Srdivacky
1339226890Sdim    // Skip marker for wide or unicode strings.
1340226890Sdim    if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1341193326Sed      ++ThisTokBuf;
1342226890Sdim      // Skip 8 of u8 marker for utf8 strings.
1343226890Sdim      if (ThisTokBuf[0] == '8')
1344226890Sdim        ++ThisTokBuf;
1345212904Sdim    }
1346198092Srdivacky
1347226890Sdim    // Check for raw string
1348226890Sdim    if (ThisTokBuf[0] == 'R') {
1349226890Sdim      ThisTokBuf += 2; // skip R"
1350198092Srdivacky
1351226890Sdim      const char *Prefix = ThisTokBuf;
1352226890Sdim      while (ThisTokBuf[0] != '(')
1353193326Sed        ++ThisTokBuf;
1354226890Sdim      ++ThisTokBuf; // skip '('
1355198092Srdivacky
1356235633Sdim      // Remove same number of characters from the end
1357235633Sdim      ThisTokEnd -= ThisTokBuf - Prefix;
1358235633Sdim      assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1359226890Sdim
1360226890Sdim      // Copy the string over
1361245431Sdim      if (CopyStringFragment(StringToks[i], ThisTokBegin,
1362245431Sdim                             StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1363245431Sdim        hadError = true;
1364226890Sdim    } else {
1365245431Sdim      if (ThisTokBuf[0] != '"') {
1366245431Sdim        // The file may have come from PCH and then changed after loading the
1367245431Sdim        // PCH; Fail gracefully.
1368245431Sdim        return DiagnoseLexingError(StringToks[i].getLocation());
1369245431Sdim      }
1370226890Sdim      ++ThisTokBuf; // skip "
1371226890Sdim
1372226890Sdim      // Check if this is a pascal string
1373226890Sdim      if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1374226890Sdim          ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1375226890Sdim
1376226890Sdim        // If the \p sequence is found in the first token, we have a pascal string
1377226890Sdim        // Otherwise, if we already have a pascal string, ignore the first \p
1378226890Sdim        if (i == 0) {
1379193326Sed          ++ThisTokBuf;
1380226890Sdim          Pascal = true;
1381226890Sdim        } else if (Pascal)
1382226890Sdim          ThisTokBuf += 2;
1383226890Sdim      }
1384198092Srdivacky
1385226890Sdim      while (ThisTokBuf != ThisTokEnd) {
1386226890Sdim        // Is this a span of non-escape characters?
1387226890Sdim        if (ThisTokBuf[0] != '\\') {
1388226890Sdim          const char *InStart = ThisTokBuf;
1389226890Sdim          do {
1390226890Sdim            ++ThisTokBuf;
1391226890Sdim          } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1392226890Sdim
1393226890Sdim          // Copy the character span over.
1394245431Sdim          if (CopyStringFragment(StringToks[i], ThisTokBegin,
1395245431Sdim                                 StringRef(InStart, ThisTokBuf - InStart)))
1396245431Sdim            hadError = true;
1397226890Sdim          continue;
1398193326Sed        }
1399226890Sdim        // Is this a Universal Character Name escape?
1400226890Sdim        if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1401235633Sdim          EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1402235633Sdim                          ResultPtr, hadError,
1403235633Sdim                          FullSourceLoc(StringToks[i].getLocation(), SM),
1404226890Sdim                          CharByteWidth, Diags, Features);
1405226890Sdim          continue;
1406226890Sdim        }
1407226890Sdim        // Otherwise, this is a non-UCN escape character.  Process it.
1408226890Sdim        unsigned ResultChar =
1409245431Sdim          ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1410226890Sdim                            FullSourceLoc(StringToks[i].getLocation(), SM),
1411245431Sdim                            CharByteWidth*8, Diags, Features);
1412198092Srdivacky
1413235633Sdim        if (CharByteWidth == 4) {
1414235633Sdim          // FIXME: Make the type of the result buffer correct instead of
1415235633Sdim          // using reinterpret_cast.
1416235633Sdim          UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1417235633Sdim          *ResultWidePtr = ResultChar;
1418235633Sdim          ResultPtr += 4;
1419235633Sdim        } else if (CharByteWidth == 2) {
1420235633Sdim          // FIXME: Make the type of the result buffer correct instead of
1421235633Sdim          // using reinterpret_cast.
1422235633Sdim          UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1423235633Sdim          *ResultWidePtr = ResultChar & 0xFFFF;
1424235633Sdim          ResultPtr += 2;
1425235633Sdim        } else {
1426235633Sdim          assert(CharByteWidth == 1 && "Unexpected char width");
1427235633Sdim          *ResultPtr++ = ResultChar & 0xFF;
1428235633Sdim        }
1429193326Sed      }
1430193326Sed    }
1431193326Sed  }
1432198092Srdivacky
1433193326Sed  if (Pascal) {
1434235633Sdim    if (CharByteWidth == 4) {
1435235633Sdim      // FIXME: Make the type of the result buffer correct instead of
1436235633Sdim      // using reinterpret_cast.
1437235633Sdim      UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1438235633Sdim      ResultWidePtr[0] = GetNumStringChars() - 1;
1439235633Sdim    } else if (CharByteWidth == 2) {
1440235633Sdim      // FIXME: Make the type of the result buffer correct instead of
1441235633Sdim      // using reinterpret_cast.
1442235633Sdim      UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1443235633Sdim      ResultWidePtr[0] = GetNumStringChars() - 1;
1444235633Sdim    } else {
1445235633Sdim      assert(CharByteWidth == 1 && "Unexpected char width");
1446235633Sdim      ResultBuf[0] = GetNumStringChars() - 1;
1447235633Sdim    }
1448193326Sed
1449193326Sed    // Verify that pascal strings aren't too large.
1450218893Sdim    if (GetStringLength() > 256) {
1451245431Sdim      if (Diags)
1452245431Sdim        Diags->Report(StringToks[0].getLocation(),
1453218893Sdim                      diag::err_pascal_string_too_long)
1454218893Sdim          << SourceRange(StringToks[0].getLocation(),
1455218893Sdim                         StringToks[NumStringToks-1].getLocation());
1456226890Sdim      hadError = true;
1457193326Sed      return;
1458193326Sed    }
1459218893Sdim  } else if (Diags) {
1460212904Sdim    // Complain if this string literal has too many characters.
1461218893Sdim    unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1462245431Sdim
1463212904Sdim    if (GetNumStringChars() > MaxChars)
1464245431Sdim      Diags->Report(StringToks[0].getLocation(),
1465218893Sdim                    diag::ext_string_too_long)
1466212904Sdim        << GetNumStringChars() << MaxChars
1467218893Sdim        << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1468212904Sdim        << SourceRange(StringToks[0].getLocation(),
1469212904Sdim                       StringToks[NumStringToks-1].getLocation());
1470193326Sed  }
1471193326Sed}
1472193326Sed
1473245431Sdimstatic const char *resyncUTF8(const char *Err, const char *End) {
1474245431Sdim  if (Err == End)
1475245431Sdim    return End;
1476245431Sdim  End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1477245431Sdim  while (++Err != End && (*Err & 0xC0) == 0x80)
1478245431Sdim    ;
1479245431Sdim  return Err;
1480245431Sdim}
1481193326Sed
1482245431Sdim/// \brief This function copies from Fragment, which is a sequence of bytes
1483245431Sdim/// within Tok's contents (which begin at TokBegin) into ResultPtr.
1484226890Sdim/// Performs widening for multi-byte characters.
1485245431Sdimbool StringLiteralParser::CopyStringFragment(const Token &Tok,
1486245431Sdim                                             const char *TokBegin,
1487245431Sdim                                             StringRef Fragment) {
1488245431Sdim  const UTF8 *ErrorPtrTmp;
1489245431Sdim  if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1490245431Sdim    return false;
1491226890Sdim
1492235633Sdim  // If we see bad encoding for unprefixed string literals, warn and
1493235633Sdim  // simply copy the byte values, for compatibility with gcc and older
1494235633Sdim  // versions of clang.
1495235633Sdim  bool NoErrorOnBadEncoding = isAscii();
1496245431Sdim  if (NoErrorOnBadEncoding) {
1497245431Sdim    memcpy(ResultPtr, Fragment.data(), Fragment.size());
1498245431Sdim    ResultPtr += Fragment.size();
1499245431Sdim  }
1500245431Sdim
1501245431Sdim  if (Diags) {
1502245431Sdim    const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1503245431Sdim
1504245431Sdim    FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1505245431Sdim    const DiagnosticBuilder &Builder =
1506245431Sdim      Diag(Diags, Features, SourceLoc, TokBegin,
1507245431Sdim           ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1508245431Sdim           NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1509245431Sdim                                : diag::err_bad_string_encoding);
1510245431Sdim
1511245431Sdim    const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1512245431Sdim    StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1513245431Sdim
1514245431Sdim    // Decode into a dummy buffer.
1515245431Sdim    SmallString<512> Dummy;
1516245431Sdim    Dummy.reserve(Fragment.size() * CharByteWidth);
1517245431Sdim    char *Ptr = Dummy.data();
1518245431Sdim
1519245431Sdim    while (!Builder.hasMaxRanges() &&
1520245431Sdim           !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1521245431Sdim      const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1522245431Sdim      NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1523245431Sdim      Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1524245431Sdim                                     ErrorPtr, NextStart);
1525245431Sdim      NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1526245431Sdim    }
1527245431Sdim  }
1528235633Sdim  return !NoErrorOnBadEncoding;
1529235633Sdim}
1530226890Sdim
1531245431Sdimvoid StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1532245431Sdim  hadError = true;
1533245431Sdim  if (Diags)
1534245431Sdim    Diags->Report(Loc, diag::err_lexing_string);
1535245431Sdim}
1536245431Sdim
1537193326Sed/// getOffsetOfStringByte - This function returns the offset of the
1538193326Sed/// specified byte of the string data represented by Token.  This handles
1539193326Sed/// advancing over escape sequences in the string.
1540193326Sedunsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1541218893Sdim                                                    unsigned ByteNo) const {
1542193326Sed  // Get the spelling of the token.
1543235633Sdim  SmallString<32> SpellingBuffer;
1544193326Sed  SpellingBuffer.resize(Tok.getLength());
1545198092Srdivacky
1546205219Srdivacky  bool StringInvalid = false;
1547193326Sed  const char *SpellingPtr = &SpellingBuffer[0];
1548218893Sdim  unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1549218893Sdim                                       &StringInvalid);
1550218893Sdim  if (StringInvalid)
1551205219Srdivacky    return 0;
1552193326Sed
1553245431Sdim  const char *SpellingStart = SpellingPtr;
1554245431Sdim  const char *SpellingEnd = SpellingPtr+TokLen;
1555245431Sdim
1556245431Sdim  // Handle UTF-8 strings just like narrow strings.
1557245431Sdim  if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1558245431Sdim    SpellingPtr += 2;
1559245431Sdim
1560226890Sdim  assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1561226890Sdim         SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1562193326Sed
1563245431Sdim  // For raw string literals, this is easy.
1564245431Sdim  if (SpellingPtr[0] == 'R') {
1565245431Sdim    assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1566245431Sdim    // Skip 'R"'.
1567245431Sdim    SpellingPtr += 2;
1568245431Sdim    while (*SpellingPtr != '(') {
1569245431Sdim      ++SpellingPtr;
1570245431Sdim      assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1571245431Sdim    }
1572245431Sdim    // Skip '('.
1573245431Sdim    ++SpellingPtr;
1574245431Sdim    return SpellingPtr - SpellingStart + ByteNo;
1575245431Sdim  }
1576198092Srdivacky
1577245431Sdim  // Skip over the leading quote
1578193326Sed  assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1579193326Sed  ++SpellingPtr;
1580198092Srdivacky
1581193326Sed  // Skip over bytes until we find the offset we're looking for.
1582193326Sed  while (ByteNo) {
1583193326Sed    assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1584198092Srdivacky
1585193326Sed    // Step over non-escapes simply.
1586193326Sed    if (*SpellingPtr != '\\') {
1587193326Sed      ++SpellingPtr;
1588193326Sed      --ByteNo;
1589193326Sed      continue;
1590193326Sed    }
1591198092Srdivacky
1592193326Sed    // Otherwise, this is an escape character.  Advance over it.
1593193326Sed    bool HadError = false;
1594245431Sdim    if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1595245431Sdim      const char *EscapePtr = SpellingPtr;
1596245431Sdim      unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1597245431Sdim                                      1, Features, HadError);
1598245431Sdim      if (Len > ByteNo) {
1599245431Sdim        // ByteNo is somewhere within the escape sequence.
1600245431Sdim        SpellingPtr = EscapePtr;
1601245431Sdim        break;
1602245431Sdim      }
1603245431Sdim      ByteNo -= Len;
1604245431Sdim    } else {
1605245431Sdim      ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1606245431Sdim                        FullSourceLoc(Tok.getLocation(), SM),
1607245431Sdim                        CharByteWidth*8, Diags, Features);
1608245431Sdim      --ByteNo;
1609245431Sdim    }
1610193326Sed    assert(!HadError && "This method isn't valid on erroneous strings");
1611193326Sed  }
1612198092Srdivacky
1613193326Sed  return SpellingPtr-SpellingStart;
1614193326Sed}
1615