LiteralSupport.cpp revision 263509
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"
16193326Sed#include "clang/Basic/CharInfo.h"
17193326Sed#include "clang/Basic/TargetInfo.h"
18193326Sed#include "clang/Lex/LexDiagnostic.h"
19198092Srdivacky#include "clang/Lex/Preprocessor.h"
20193326Sed#include "llvm/ADT/StringExtras.h"
21193326Sed#include "llvm/Support/ConvertUTF.h"
22193326Sed#include "llvm/Support/ErrorHandling.h"
23193326Sed
24193326Sedusing namespace clang;
25193326Sed
26193326Sedstatic unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
27193326Sed  switch (kind) {
28193326Sed  default: llvm_unreachable("Unknown token type!");
29193326Sed  case tok::char_constant:
30193326Sed  case tok::string_literal:
31193326Sed  case tok::utf8_string_literal:
32193326Sed    return Target.getCharWidth();
33193326Sed  case tok::wide_char_constant:
34193326Sed  case tok::wide_string_literal:
35193326Sed    return Target.getWCharWidth();
36218893Sdim  case tok::utf16_char_constant:
37218893Sdim  case tok::utf16_string_literal:
38193326Sed    return Target.getChar16Width();
39193326Sed  case tok::utf32_char_constant:
40193326Sed  case tok::utf32_string_literal:
41193326Sed    return Target.getChar32Width();
42193326Sed  }
43193326Sed}
44193326Sed
45193326Sedstatic CharSourceRange MakeCharSourceRange(const LangOptions &Features,
46193326Sed                                           FullSourceLoc TokLoc,
47198092Srdivacky                                           const char *TokBegin,
48193326Sed                                           const char *TokRangeBegin,
49193326Sed                                           const char *TokRangeEnd) {
50193326Sed  SourceLocation Begin =
51193326Sed    Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
52193326Sed                                   TokLoc.getManager(), Features);
53193326Sed  SourceLocation End =
54193326Sed    Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
55193326Sed                                   TokLoc.getManager(), Features);
56193326Sed  return CharSourceRange::getCharRange(Begin, End);
57218893Sdim}
58218893Sdim
59193326Sed/// \brief Produce a diagnostic highlighting some portion of a literal.
60193326Sed///
61194179Sed/// Emits the diagnostic \p DiagID, highlighting the range of characters from
62218893Sdim/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
63218893Sdim/// a substring of a spelling buffer for the token beginning at \p TokBegin.
64194179Sedstatic DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
65194179Sed                              const LangOptions &Features, FullSourceLoc TokLoc,
66193326Sed                              const char *TokBegin, const char *TokRangeBegin,
67193326Sed                              const char *TokRangeEnd, unsigned DiagID) {
68193326Sed  SourceLocation Begin =
69193326Sed    Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
70193326Sed                                   TokLoc.getManager(), Features);
71193326Sed  return Diags->Report(Begin, DiagID) <<
72193326Sed    MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
73193326Sed}
74193326Sed
75193326Sed/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
76193326Sed/// either a character or a string literal.
77193326Sedstatic unsigned ProcessCharEscape(const char *ThisTokBegin,
78193326Sed                                  const char *&ThisTokBuf,
79193326Sed                                  const char *ThisTokEnd, bool &HadError,
80193326Sed                                  FullSourceLoc Loc, unsigned CharWidth,
81193326Sed                                  DiagnosticsEngine *Diags,
82193326Sed                                  const LangOptions &Features) {
83193326Sed  const char *EscapeBegin = ThisTokBuf;
84218893Sdim
85218893Sdim  // Skip the '\' char.
86193326Sed  ++ThisTokBuf;
87193326Sed
88193326Sed  // We know that this character can't be off the end of the buffer, because
89198092Srdivacky  // 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;
94193326Sed
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;
102218893Sdim    break;
103218893Sdim  case 'e':
104198092Srdivacky    if (Diags)
105193326Sed      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
106193326Sed           diag::ext_nonstandard_escape) << "e";
107193326Sed    ResultChar = 27;
108193326Sed    break;
109198092Srdivacky  case 'E':
110193326Sed    if (Diags)
111218893Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
112218893Sdim           diag::ext_nonstandard_escape) << "E";
113193326Sed    ResultChar = 27;
114193326Sed    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;
130198092Srdivacky  case 'x': { // Hex escape.
131193326Sed    ResultChar = 0;
132218893Sdim    if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
133218893Sdim      if (Diags)
134198092Srdivacky        Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
135193326Sed             diag::err_hex_escape_no_digits) << "x";
136218893Sdim      HadError = 1;
137218893Sdim      break;
138193326Sed    }
139193326Sed
140193326Sed    // Hex escapes are a maximal series of hex digits.
141193326Sed    bool Overflow = false;
142198092Srdivacky    for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
143193326Sed      int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
144193326Sed      if (CharVal == -1) break;
145193326Sed      // About to shift out a digit?
146218893Sdim      Overflow |= (ResultChar & 0xF0000000) ? true : false;
147218893Sdim      ResultChar <<= 4;
148208600Srdivacky      ResultChar |= CharVal;
149193326Sed    }
150193326Sed
151218893Sdim    // See if any bits will be truncated when evaluated as a character.
152208600Srdivacky    if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
153208600Srdivacky      Overflow = true;
154218893Sdim      ResultChar &= ~0U >> (32-CharWidth);
155218893Sdim    }
156218893Sdim
157193326Sed    // Check for overflow.
158218893Sdim    if (Overflow && Diags)   // Too many digits to fit in
159218893Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
160193326Sed           diag::err_hex_escape_too_large);
161193326Sed    break;
162198092Srdivacky  }
163193326Sed  case '0': case '1': case '2': case '3':
164193326Sed  case '4': case '5': case '6': case '7': {
165193326Sed    // Octal escapes.
166193326Sed    --ThisTokBuf;
167218893Sdim    ResultChar = 0;
168218893Sdim
169218893Sdim    // Octal escapes are a series of octal digits with maximum length 3.
170218893Sdim    // "\0123" is a two digit sequence equal to "\012" "3".
171218893Sdim    unsigned NumDigits = 0;
172218893Sdim    do {
173218893Sdim      ResultChar <<= 3;
174198092Srdivacky      ResultChar |= *ThisTokBuf++ - '0';
175193326Sed      ++NumDigits;
176193326Sed    } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
177198092Srdivacky             ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
178193326Sed
179193326Sed    // Check for overflow.  Reject '\777', but not L'\777'.
180193326Sed    if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
181193326Sed      if (Diags)
182218893Sdim        Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
183218893Sdim             diag::err_octal_escape_too_large);
184218893Sdim      ResultChar &= ~0U >> (32-CharWidth);
185193326Sed    }
186218893Sdim    break;
187212904Sdim  }
188218893Sdim
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.
192193326Sed    if (Diags)
193193326Sed      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
194193326Sed           diag::ext_nonstandard_escape)
195218893Sdim        << std::string(1, ResultChar);
196218893Sdim    break;
197218893Sdim  default:
198218893Sdim    if (Diags == 0)
199218893Sdim      break;
200218893Sdim
201218893Sdim    if (isPrintable(ResultChar))
202218893Sdim      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
203218893Sdim           diag::ext_unknown_escape)
204193326Sed        << std::string(1, ResultChar);
205198092Srdivacky    else
206193326Sed      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
207193326Sed           diag::ext_unknown_escape)
208198092Srdivacky        << "x" + llvm::utohexstr(ResultChar);
209193326Sed    break;
210218893Sdim  }
211218893Sdim
212218893Sdim  return ResultChar;
213218893Sdim}
214218893Sdim
215218893Sdim/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
216218893Sdim/// return the UTF32.
217218893Sdimstatic bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
218218893Sdim                             const char *ThisTokEnd,
219218893Sdim                             uint32_t &UcnVal, unsigned short &UcnLen,
220218893Sdim                             FullSourceLoc Loc, DiagnosticsEngine *Diags,
221218893Sdim                             const LangOptions &Features,
222218893Sdim                             bool in_char_string_literal = false) {
223218893Sdim  const char *UcnBegin = ThisTokBuf;
224218893Sdim
225218893Sdim  // Skip the '\u' char's.
226218893Sdim  ThisTokBuf += 2;
227218893Sdim
228218893Sdim  if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
229218893Sdim    if (Diags)
230193326Sed      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
231193326Sed           diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
232193326Sed    return false;
233218893Sdim  }
234212904Sdim  UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
235218893Sdim  unsigned short UcnLenSave = UcnLen;
236218893Sdim  for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
237218893Sdim    int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
238218893Sdim    if (CharVal == -1) break;
239218893Sdim    UcnVal <<= 4;
240218893Sdim    UcnVal |= CharVal;
241218893Sdim  }
242218893Sdim  // If we didn't consume the proper number of digits, there is a problem.
243218893Sdim  if (UcnLenSave) {
244218893Sdim    if (Diags)
245218893Sdim      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
246218893Sdim           diag::err_ucn_escape_incomplete);
247218893Sdim    return false;
248218893Sdim  }
249218893Sdim
250218893Sdim  // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
251218893Sdim  if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
252218893Sdim      UcnVal > 0x10FFFF) {                      // maximum legal UTF32 value
253218893Sdim    if (Diags)
254218893Sdim      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
255218893Sdim           diag::err_ucn_escape_invalid);
256218893Sdim    return false;
257218893Sdim  }
258218893Sdim
259218893Sdim  // C++11 allows UCNs that refer to control characters and basic source
260218893Sdim  // characters inside character and string literals
261218893Sdim  if (UcnVal < 0xa0 &&
262218893Sdim      (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) {  // $, @, `
263212904Sdim    bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
264212904Sdim    if (Diags) {
265193326Sed      char BasicSCSChar = UcnVal;
266193326Sed      if (UcnVal >= 0x20 && UcnVal < 0x7f)
267193326Sed        Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
268198092Srdivacky             IsError ? diag::err_ucn_escape_basic_scs :
269193326Sed                       diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
270193326Sed            << StringRef(&BasicSCSChar, 1);
271193326Sed      else
272193326Sed        Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
273193326Sed             IsError ? diag::err_ucn_control_character :
274193326Sed                       diag::warn_cxx98_compat_literal_ucn_control_character);
275193326Sed    }
276193326Sed    if (IsError)
277193326Sed      return false;
278193326Sed  }
279193326Sed
280198092Srdivacky  if (!Features.CPlusPlus && !Features.C99 && Diags)
281193326Sed    Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
282193326Sed         diag::warn_ucn_not_valid_in_c89_literal);
283198092Srdivacky
284193326Sed  return true;
285193326Sed}
286198092Srdivacky
287193326Sed/// MeasureUCNEscape - Determine the number of bytes within the resulting string
288193326Sed/// which this UCN will occupy.
289193326Sedstatic int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
290193326Sed                            const char *ThisTokEnd, unsigned CharByteWidth,
291193326Sed                            const LangOptions &Features, bool &HadError) {
292193326Sed  // UTF-32: 4 bytes per escape.
293193326Sed  if (CharByteWidth == 4)
294193326Sed    return 4;
295193326Sed
296193326Sed  uint32_t UcnVal = 0;
297193326Sed  unsigned short UcnLen = 0;
298193326Sed  FullSourceLoc Loc;
299193326Sed
300193326Sed  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
301193326Sed                        UcnLen, Loc, 0, Features, true)) {
302193326Sed    HadError = true;
303193326Sed    return 0;
304193326Sed  }
305193326Sed
306198092Srdivacky  // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
307193326Sed  if (CharByteWidth == 2)
308193326Sed    return UcnVal <= 0xFFFF ? 2 : 4;
309198092Srdivacky
310193326Sed  // UTF-8.
311193326Sed  if (UcnVal < 0x80)
312198092Srdivacky    return 1;
313193326Sed  if (UcnVal < 0x800)
314193326Sed    return 2;
315193326Sed  if (UcnVal < 0x10000)
316193326Sed    return 3;
317193326Sed  return 4;
318193326Sed}
319193326Sed
320193326Sed/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
321193326Sed/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
322193326Sed/// StringLiteralParser. When we decide to implement UCN's for identifiers,
323193326Sed/// we will likely rework our support for UCN's.
324193326Sedstatic void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
325193326Sed                            const char *ThisTokEnd,
326193326Sed                            char *&ResultBuf, bool &HadError,
327193326Sed                            FullSourceLoc Loc, unsigned CharByteWidth,
328193326Sed                            DiagnosticsEngine *Diags,
329193326Sed                            const LangOptions &Features) {
330193326Sed  typedef uint32_t UTF32;
331193326Sed  UTF32 UcnVal = 0;
332193326Sed  unsigned short UcnLen = 0;
333193326Sed  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
334198092Srdivacky                        Loc, Diags, Features, true)) {
335193326Sed    HadError = true;
336193326Sed    return;
337193326Sed  }
338193326Sed
339193326Sed  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
340193326Sed         "only character widths of 1, 2, or 4 bytes supported");
341193326Sed
342193326Sed  (void)UcnLen;
343193326Sed  assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
344198092Srdivacky
345193326Sed  if (CharByteWidth == 4) {
346193326Sed    // FIXME: Make the type of the result buffer correct instead of
347193326Sed    // using reinterpret_cast.
348193326Sed    UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
349193326Sed    *ResultPtr = UcnVal;
350193326Sed    ResultBuf += 4;
351198092Srdivacky    return;
352193326Sed  }
353193326Sed
354193326Sed  if (CharByteWidth == 2) {
355193326Sed    // FIXME: Make the type of the result buffer correct instead of
356193326Sed    // using reinterpret_cast.
357193326Sed    UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
358193326Sed
359193326Sed    if (UcnVal <= (UTF32)0xFFFF) {
360198092Srdivacky      *ResultPtr = UcnVal;
361193326Sed      ResultBuf += 2;
362198092Srdivacky      return;
363193326Sed    }
364193326Sed
365193326Sed    // Convert to UTF16.
366193326Sed    UcnVal -= 0x10000;
367193326Sed    *ResultPtr     = 0xD800 + (UcnVal >> 10);
368193326Sed    *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
369193326Sed    ResultBuf += 4;
370193326Sed    return;
371193326Sed  }
372193326Sed
373193326Sed  assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
374212904Sdim
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
378193326Sed  // First, we determine how many bytes the result will require.
379193326Sed  typedef uint8_t UTF8;
380193326Sed
381198092Srdivacky  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;
390193326Sed
391193326Sed  const unsigned byteMask = 0xBF;
392193326Sed  const unsigned byteMark = 0x80;
393193326Sed
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.
396193326Sed  static const UTF8 firstByteMark[5] = {
397193326Sed    0x00, 0x00, 0xC0, 0xE0, 0xF0
398193326Sed  };
399193326Sed  // Finally, we write the bytes into ResultBuf.
400198092Srdivacky  ResultBuf += bytesToWrite;
401193326Sed  switch (bytesToWrite) { // note: everything falls through.
402193326Sed  case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
403193326Sed  case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
404198092Srdivacky  case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
405193326Sed  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
416193326Sed///         binary-literal integer-suffix [GNU, C++1y]
417193326Sed///       user-defined-integer-literal: [C++11 lex.ext]
418193326Sed///         decimal-literal ud-suffix
419193326Sed///         octal-literal ud-suffix
420193326Sed///         hexadecimal-literal ud-suffix
421193326Sed///         binary-literal ud-suffix [GNU, C++1y]
422193326Sed///       decimal-constant:
423193326Sed///         nonzero-digit
424193326Sed///         decimal-constant digit
425198092Srdivacky///       octal-constant:
426193326Sed///         0
427193326Sed///         octal-constant octal-digit
428193326Sed///       hexadecimal-constant:
429193326Sed///         hexadecimal-prefix hexadecimal-digit
430193326Sed///         hexadecimal-constant hexadecimal-digit
431193326Sed///       hexadecimal-prefix: one of
432193326Sed///         0x 0X
433193326Sed///       binary-literal:
434193326Sed///         0b binary-digit
435193326Sed///         0B binary-digit
436218893Sdim///         binary-literal binary-digit
437193326Sed///       integer-suffix:
438202879Srdivacky///         unsigned-suffix [long-suffix]
439199990Srdivacky///         unsigned-suffix [long-long-suffix]
440193326Sed///         long-suffix [unsigned-suffix]
441198092Srdivacky///         long-long-suffix [unsigned-sufix]
442198092Srdivacky///       nonzero-digit:
443198092Srdivacky///         1 2 3 4 5 6 7 8 9
444198092Srdivacky///       octal-digit:
445198092Srdivacky///         0 1 2 3 4 5 6 7
446199990Srdivacky///       hexadecimal-digit:
447198092Srdivacky///         0 1 2 3 4 5 6 7 8 9
448199990Srdivacky///         a b c d e f
449218893Sdim///         A B C D E F
450218893Sdim///       binary-digit:
451218893Sdim///         0
452218893Sdim///         1
453199990Srdivacky///       unsigned-suffix: one of
454199990Srdivacky///         u U
455218893Sdim///       long-suffix: one of
456218893Sdim///         l L
457218893Sdim///       long-long-suffix: one of
458218893Sdim///         ll LL
459198092Srdivacky///
460199990Srdivacky///       floating-constant: [C99 6.4.4.2]
461198092Srdivacky///         TODO: add rules...
462199990Srdivacky///
463218893SdimNumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
464218893Sdim                                           SourceLocation TokLoc,
465218893Sdim                                           Preprocessor &PP)
466218893Sdim  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
467218893Sdim
468199990Srdivacky  // This routine assumes that the range begin/end matches the regex for integer
469198092Srdivacky  // and FP constants (specifically, the 'pp-number' regex), and assumes that
470199990Srdivacky  // the byte at "*end" is both valid and not part of the regex.  Because of
471218893Sdim  // this, it doesn't have to check for 'overscan' in various places.
472218893Sdim  assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
473218893Sdim
474218893Sdim  s = DigitsBegin = ThisTokBegin;
475218893Sdim  saw_exponent = false;
476199990Srdivacky  saw_period = false;
477198092Srdivacky  saw_ud_suffix = false;
478198092Srdivacky  isLong = false;
479198092Srdivacky  isUnsigned = false;
480198092Srdivacky  isLongLong = false;
481193326Sed  isFloat = false;
482193326Sed  isImaginary = false;
483193326Sed  isMicrosoftInteger = false;
484193326Sed  hadError = false;
485193326Sed
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.
495198092Srdivacky    } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) {
496193326Sed      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
497193326Sed              diag::err_invalid_decimal_digit) << StringRef(s, 1);
498193326Sed      hadError = true;
499193326Sed      return;
500193326Sed    } else if (*s == '.') {
501212904Sdim      checkSeparator(TokLoc, s, CSK_AfterDigits);
502193326Sed      s++;
503193326Sed      saw_period = true;
504193326Sed      checkSeparator(TokLoc, s, CSK_BeforeDigits);
505193326Sed      s = SkipDigits(s);
506193326Sed    }
507193326Sed    if ((*s == 'e' || *s == 'E')) { // exponent
508193326Sed      checkSeparator(TokLoc, s, CSK_AfterDigits);
509193326Sed      const char *Exponent = s;
510198092Srdivacky      s++;
511193326Sed      saw_exponent = true;
512193326Sed      if (*s == '+' || *s == '-')  s++; // sign
513193326Sed      checkSeparator(TokLoc, s, CSK_BeforeDigits);
514193326Sed      const char *first_non_digit = SkipDigits(s);
515198092Srdivacky      if (first_non_digit != s) {
516193326Sed        s = first_non_digit;
517193326Sed      } else {
518193326Sed        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;
527193326Sed  checkSeparator(TokLoc, s, CSK_AfterDigits);
528193326Sed
529193326Sed  // Parse the suffix.  At this point we can classify whether we have an FP or
530198092Srdivacky  // integer constant.
531202379Srdivacky  bool isFPConstant = isFloatingLiteral();
532193326Sed  const char *ImaginarySuffixLoc = 0;
533193326Sed
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.
544198092Srdivacky    case 'u':
545202379Srdivacky    case 'U':
546202379Srdivacky      if (isFPConstant) break;  // Error for floating constant.
547202379Srdivacky      if (isUnsigned) break;    // Cannot be repeated.
548202379Srdivacky      isUnsigned = true;
549202379Srdivacky      continue;  // Success.
550202379Srdivacky    case 'l':
551193326Sed    case 'L':
552193326Sed      if (isLong || isLongLong) break;  // Cannot be repeated.
553193326Sed      if (isFloat) break;               // LF invalid.
554193326Sed
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;
559198092Srdivacky        ++s;  // Eat both of them.
560193326Sed      } else {
561193326Sed        isLong = true;
562193326Sed      }
563193326Sed      continue;  // Success.
564193326Sed    case 'i':
565193326Sed    case 'I':
566193326Sed      if (PP.getLangOpts().MicrosoftExt) {
567193326Sed        if (isFPConstant || isLong || isLongLong) break;
568193326Sed
569193326Sed        // Allow i8, i16, i32, i64, and i128.
570193326Sed        if (s + 1 != ThisTokEnd) {
571193326Sed          switch (s[1]) {
572212904Sdim            case '8':
573193326Sed              s += 2; // i8 suffix
574193326Sed              isMicrosoftInteger = true;
575193326Sed              break;
576193326Sed            case '1':
577193326Sed              if (s + 2 == ThisTokEnd) break;
578198092Srdivacky              if (s[2] == '6') {
579193326Sed                s += 3; // i16 suffix
580193326Sed                isMicrosoftInteger = true;
581198092Srdivacky              }
582193326Sed              else if (s[2] == '2') {
583193326Sed                if (s + 3 == ThisTokEnd) break;
584193326Sed                if (s[3] == '8') {
585193326Sed                  s += 4; // i128 suffix
586193326Sed                  isMicrosoftInteger = true;
587198092Srdivacky                }
588193326Sed              }
589193326Sed              break;
590193326Sed            case '3':
591193326Sed              if (s + 2 == ThisTokEnd) break;
592193326Sed              if (s[2] == '2') {
593193326Sed                s += 3; // i32 suffix
594193326Sed                isLong = true;
595193326Sed                isMicrosoftInteger = true;
596193326Sed              }
597198092Srdivacky              break;
598193326Sed            case '6':
599193326Sed              if (s + 2 == ThisTokEnd) break;
600193326Sed              if (s[2] == '4') {
601193326Sed                s += 3; // i64 suffix
602212904Sdim                isLongLong = true;
603193326Sed                isMicrosoftInteger = true;
604193326Sed              }
605193326Sed              break;
606198092Srdivacky            default:
607193326Sed              break;
608193326Sed          }
609193326Sed          break;
610193326Sed        }
611193326Sed      }
612193326Sed      // "i", "if", and "il" are user-defined suffixes in C++1y.
613193326Sed      if (PP.getLangOpts().CPlusPlus1y && *s == 'i')
614193326Sed        break;
615193326Sed      // fall through.
616193326Sed    case 'j':
617193326Sed    case 'J':
618193326Sed      if (isImaginary) break;   // Cannot be repeated.
619193326Sed      isImaginary = true;
620193326Sed      ImaginarySuffixLoc = s;
621193326Sed      continue;  // Success.
622193326Sed    }
623198092Srdivacky    // If we reached here, there was an error or a ud-suffix.
624193326Sed    break;
625193326Sed  }
626193326Sed
627193326Sed  if (s != ThisTokEnd) {
628193326Sed    if (isValidUDSuffix(PP.getLangOpts(),
629193326Sed                        StringRef(SuffixBegin, ThisTokEnd - SuffixBegin))) {
630193326Sed      // Any suffix pieces we might have parsed are actually part of the
631193326Sed      // ud-suffix.
632193326Sed      isLong = false;
633193326Sed      isUnsigned = false;
634193326Sed      isLongLong = false;
635193326Sed      isFloat = false;
636193326Sed      isImaginary = false;
637193326Sed      isMicrosoftInteger = false;
638193326Sed
639193326Sed      saw_ud_suffix = true;
640193326Sed      return;
641193326Sed    }
642193326Sed
643198092Srdivacky    // Report an error if there are any.
644193326Sed    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
645193326Sed            isFPConstant ? diag::err_invalid_suffix_float_constant :
646193326Sed                           diag::err_invalid_suffix_integer_constant)
647193326Sed      << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
648193326Sed    hadError = true;
649193326Sed    return;
650193326Sed  }
651193326Sed
652193326Sed  if (isImaginary) {
653193326Sed    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
654193326Sed                                       ImaginarySuffixLoc - ThisTokBegin),
655193326Sed            diag::ext_imaginary_constant);
656193326Sed  }
657193326Sed}
658193326Sed
659193326Sed/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
660193326Sed/// suffixes as ud-suffixes, because the diagnostic experience is better if we
661193326Sed/// treat it as an invalid suffix.
662198092Srdivackybool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
663193326Sed                                           StringRef Suffix) {
664193326Sed  if (!LangOpts.CPlusPlus11 || Suffix.empty())
665193326Sed    return false;
666198092Srdivacky
667193326Sed  // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
668193326Sed  if (Suffix[0] == '_')
669198092Srdivacky    return true;
670193326Sed
671198092Srdivacky  // In C++11, there are no library suffixes.
672193326Sed  if (!LangOpts.CPlusPlus1y)
673193326Sed    return false;
674193326Sed
675193326Sed  // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
676193326Sed  // Per tweaked N3660, "il", "i", and "if" are also used in the library.
677193326Sed  return llvm::StringSwitch<bool>(Suffix)
678193326Sed      .Cases("h", "min", "s", true)
679193326Sed      .Cases("ms", "us", "ns", true)
680193326Sed      .Cases("il", "i", "if", true)
681193326Sed      .Default(false);
682193326Sed}
683193326Sed
684193326Sedvoid NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
685193326Sed                                          const char *Pos,
686193326Sed                                          CheckSeparatorKind IsAfterDigits) {
687193326Sed  if (IsAfterDigits == CSK_AfterDigits) {
688201361Srdivacky    if (Pos == ThisTokBegin)
689201361Srdivacky      return;
690193326Sed    --Pos;
691198092Srdivacky  } else if (Pos == ThisTokEnd)
692198092Srdivacky    return;
693198092Srdivacky
694201361Srdivacky  if (isDigitSeparator(*Pos))
695201361Srdivacky    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
696193326Sed            diag::err_digit_separator_not_between_digits)
697193326Sed      << IsAfterDigits;
698193326Sed}
699193326Sed
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");
707198092Srdivacky  s++;
708193326Sed
709193326Sed  int c1 = s[0];
710193326Sed  int c2 = s[1];
711193326Sed
712198092Srdivacky  // Handle a hex number like 0x1234.
713221345Sdim  if ((c1 == 'x' || c1 == 'X') && (isHexDigit(c2) || c2 == '.')) {
714193326Sed    s++;
715193326Sed    radix = 16;
716193326Sed    DigitsBegin = s;
717193326Sed    s = SkipHexDigits(s);
718193326Sed    bool noSignificand = (s == DigitsBegin);
719193326Sed    if (s == ThisTokEnd) {
720193326Sed      // Done.
721193326Sed    } else if (*s == '.') {
722193326Sed      s++;
723198092Srdivacky      saw_period = true;
724193326Sed      const char *floatDigitsBegin = s;
725198092Srdivacky      s = SkipHexDigits(s);
726193326Sed      noSignificand &= (floatDigitsBegin == s);
727207619Srdivacky    }
728193326Sed
729193326Sed    if (noSignificand) {
730218893Sdim      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
731218893Sdim        diag::err_hexconstant_requires_digits);
732193326Sed      hadError = true;
733193326Sed      return;
734218893Sdim    }
735218893Sdim
736218893Sdim    // A binary exponent can appear with or with a '.'. If dotted, the
737218893Sdim    // binary exponent is required.
738218893Sdim    if (*s == 'p' || *s == 'P') {
739218893Sdim      const char *Exponent = s;
740218893Sdim      s++;
741218893Sdim      saw_exponent = true;
742218893Sdim      if (*s == '+' || *s == '-')  s++; // sign
743218893Sdim      const char *first_non_digit = SkipDigits(s);
744218893Sdim      if (first_non_digit == s) {
745218893Sdim        PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
746218893Sdim                diag::err_exponent_has_no_digits);
747218893Sdim        hadError = true;
748218893Sdim        return;
749218893Sdim      }
750218893Sdim      s = first_non_digit;
751218893Sdim
752218893Sdim      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  }
761193326Sed
762193326Sed  // Handle simple binary numbers 0b01010
763207619Srdivacky  if ((c1 == 'b' || c1 == 'B') && (c2 == '0' || c2 == '1')) {
764193326Sed    // 0b101010 is a C++1y / GCC extension.
765207619Srdivacky    PP.Diag(TokLoc,
766207619Srdivacky            PP.getLangOpts().CPlusPlus1y
767193326Sed              ? diag::warn_cxx11_compat_binary_literal
768193326Sed              : PP.getLangOpts().CPlusPlus
769193326Sed                ? diag::ext_binary_literal_cxx1y
770198092Srdivacky                : diag::ext_binary_literal);
771193326Sed    ++s;
772193326Sed    radix = 2;
773193326Sed    DigitsBegin = s;
774193326Sed    s = SkipBinaryDigits(s);
775193326Sed    if (s == ThisTokEnd) {
776193326Sed      // Done.
777193326Sed    } else if (isHexDigit(*s)) {
778193326Sed      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
779193326Sed              diag::err_invalid_binary_digit) << StringRef(s, 1);
780193326Sed      hadError = true;
781193326Sed    }
782193326Sed    // Other suffixes will be diagnosed by the caller.
783193326Sed    return;
784193326Sed  }
785193326Sed
786198092Srdivacky  // For now, the radix is set to 8. If we discover that we have a
787198092Srdivacky  // floating point constant, the radix will change to 10. Octal floating
788193326Sed  // point constants are not permitted (only decimal and hexadecimal).
789193326Sed  radix = 8;
790193326Sed  DigitsBegin = s;
791198092Srdivacky  s = SkipOctalDigits(s);
792218893Sdim  if (s == ThisTokEnd)
793218893Sdim    return; // Done, simple octal number like 01234
794218893Sdim
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.
797193326Sed  if (isDigit(*s)) {
798193326Sed    const char *EndDecimal = SkipDigits(s);
799193326Sed    if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
800193576Sed      s = EndDecimal;
801193326Sed      radix = 10;
802193326Sed    }
803193326Sed  }
804193326Sed
805193326Sed  // If we have a hex digit other than 'e' (which denotes a FP exponent) then
806193326Sed  // the code is using an incorrect base.
807193326Sed  if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
808193326Sed    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
809193326Sed            diag::err_invalid_octal_digit) << StringRef(s, 1);
810193326Sed    hadError = true;
811193326Sed    return;
812193326Sed  }
813193326Sed
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 {
830193326Sed      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
831193326Sed              diag::err_exponent_has_no_digits);
832193326Sed      hadError = true;
833193326Sed      return;
834193326Sed    }
835193326Sed  }
836193326Sed}
837193326Sed
838193326Sedstatic bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
839193326Sed  switch (Radix) {
840193326Sed  case 2:
841218893Sdim    return NumDigits <= 64;
842218893Sdim  case 8:
843218893Sdim    return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
844218893Sdim  case 10:
845218893Sdim    return NumDigits <= 19; // floor(log10(2^64))
846218893Sdim  case 16:
847218893Sdim    return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
848193326Sed  default:
849193326Sed    llvm_unreachable("impossible Radix");
850193326Sed  }
851193326Sed}
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
855198092Srdivacky/// 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).
863193326Sed  const unsigned NumDigits = SuffixBegin - DigitsBegin;
864198092Srdivacky  if (alwaysFitsInto64Bits(radix, NumDigits)) {
865193326Sed    uint64_t N = 0;
866198092Srdivacky    for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
867193326Sed      if (!isDigitSeparator(*Ptr))
868198092Srdivacky        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  }
875198092Srdivacky
876193326Sed  Val = 0;
877198092Srdivacky  const char *Ptr = DigitsBegin;
878193326Sed
879193326Sed  llvm::APInt RadixVal(Val.getBitWidth(), radix);
880193326Sed  llvm::APInt CharVal(Val.getBitWidth(), 0);
881193326Sed  llvm::APInt OldVal = Val;
882218893Sdim
883193326Sed  bool OverflowOccurred = false;
884193326Sed  while (Ptr < SuffixBegin) {
885193326Sed    if (isDigitSeparator(*Ptr)) {
886198092Srdivacky      ++Ptr;
887193326Sed      continue;
888193326Sed    }
889193326Sed
890193326Sed    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;
896193326Sed
897193326Sed    // Add the digit to the value in the appropriate radix.  If adding in digits
898198092Srdivacky    // made the value smaller, then this overflowed.
899193326Sed    OldVal = Val;
900193326Sed
901193326Sed    // Multiply by radix, did overflow occur on the multiply?
902198092Srdivacky    Val *= RadixVal;
903193326Sed    OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
904198092Srdivacky
905193326Sed    // Add value, did overflow occur on the value?
906193326Sed    //   (a + b) ult b  <=> overflow
907193326Sed    Val += CharVal;
908193326Sed    OverflowOccurred |= Val.ult(CharVal);
909193326Sed  }
910205219Srdivacky  return OverflowOccurred;
911218893Sdim}
912218893Sdim
913218893Sdimllvm::APFloat::opStatus
914205219SrdivackyNumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
915205219Srdivacky  using llvm::APFloat;
916205219Srdivacky
917205219Srdivacky  unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
918205219Srdivacky
919193326Sed  llvm::SmallString<16> Buffer;
920212904Sdim  StringRef Str(ThisTokBegin, n);
921193326Sed  if (Str.find('\'') != StringRef::npos) {
922198092Srdivacky    Buffer.reserve(n);
923193326Sed    std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
924212904Sdim                        &isDigitSeparator);
925212904Sdim    Str = Buffer;
926193326Sed  }
927212904Sdim
928198092Srdivacky  return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
929193326Sed}
930193326Sed
931198092Srdivacky
932193326Sed/// \verbatim
933218893Sdim///       user-defined-character-literal: [C++11 lex.ext]
934193326Sed///         character-literal ud-suffix
935198092Srdivacky///       ud-suffix:
936193326Sed///         identifier
937193326Sed///       character-literal: [C++11 lex.ccon]
938193326Sed///         ' c-char-sequence '
939193326Sed///         u' c-char-sequence '
940193326Sed///         U' c-char-sequence '
941193326Sed///         L' c-char-sequence '
942193326Sed///       c-char-sequence:
943193326Sed///         c-char
944198092Srdivacky///         c-char-sequence c-char
945193326Sed///       c-char:
946193326Sed///         any member of the source character set except the single-quote ',
947193326Sed///           backslash \, or new-line character
948193326Sed///         escape-sequence
949193326Sed///         universal-character-name
950193326Sed///       escape-sequence:
951193326Sed///         simple-escape-sequence
952198092Srdivacky///         octal-escape-sequence
953193326Sed///         hexadecimal-escape-sequence
954193326Sed///       simple-escape-sequence:
955193326Sed///         one of \' \" \? \\ \a \b \f \n \r \t \v
956193326Sed///       octal-escape-sequence:
957193326Sed///         \ octal-digit
958193326Sed///         \ octal-digit octal-digit
959193326Sed///         \ octal-digit octal-digit octal-digit
960193326Sed///       hexadecimal-escape-sequence:
961193326Sed///         \x hexadecimal-digit
962193326Sed///         hexadecimal-escape-sequence hexadecimal-digit
963193326Sed///       universal-character-name: [C++11 lex.charset]
964193326Sed///         \u hex-quad
965193326Sed///         \U hex-quad hex-quad
966193326Sed///       hex-quad:
967193326Sed///         hex-digit hex-digit hex-digit hex-digit
968193326Sed/// \endverbatim
969193326Sed///
970193326SedCharLiteralParser::CharLiteralParser(const char *begin, const char *end,
971218893Sdim                                     SourceLocation Loc, Preprocessor &PP,
972218893Sdim                                     tok::TokenKind kind) {
973218893Sdim  // At this point we know that the character matches the regex "(L|u|U)?'.*'".
974193326Sed  HadError = false;
975193326Sed
976193326Sed  Kind = kind;
977218893Sdim
978218893Sdim  const char *TokBegin = begin;
979218893Sdim
980218893Sdim  // Skip over wide character determinant.
981198092Srdivacky  if (Kind != tok::char_constant) {
982193326Sed    ++begin;
983193326Sed  }
984198092Srdivacky
985193326Sed  // Skip over the entry quote.
986193326Sed  assert(begin[0] == '\'' && "Invalid token lexed");
987193326Sed  ++begin;
988193326Sed
989193326Sed  // Remove an optional ud-suffix.
990193326Sed  if (end[-1] != '\'') {
991198092Srdivacky    const char *UDSuffixEnd = end;
992193326Sed    do {
993193326Sed      --end;
994210299Sed    } while (end[-1] != '\'');
995210299Sed    UDSuffixBuf.assign(end, UDSuffixEnd);
996193326Sed    UDSuffixOffset = end - TokBegin;
997193326Sed  }
998218893Sdim
999218893Sdim  // Trim the ending quote.
1000218893Sdim  assert(end != begin && "Invalid token lexed");
1001218893Sdim  --end;
1002218893Sdim
1003218893Sdim  // FIXME: The "Value" is an uint64_t so we can handle char literals of
1004193326Sed  // up to 64-bits.
1005193326Sed  // FIXME: This extensively assumes that 'char' is 8-bits.
1006193326Sed  assert(PP.getTargetInfo().getCharWidth() == 8 &&
1007218893Sdim         "Assumes char is 8 bits");
1008212904Sdim  assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1009218893Sdim         (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1010212904Sdim         "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1011212904Sdim  assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1012218893Sdim         "Assumes sizeof(wchar) on target is <= 64");
1013218893Sdim
1014212904Sdim  SmallVector<uint32_t, 4> codepoint_buffer;
1015218893Sdim  codepoint_buffer.resize(end - begin);
1016212904Sdim  uint32_t *buffer_begin = &codepoint_buffer.front();
1017212904Sdim  uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1018193326Sed
1019193326Sed  // Unicode escapes representing characters that cannot be correctly
1020193326Sed  // represented in a single code unit are disallowed in character literals
1021193326Sed  // by this implementation.
1022193326Sed  uint32_t largest_character_for_kind;
1023193326Sed  if (tok::wide_char_constant == Kind) {
1024193326Sed    largest_character_for_kind =
1025193326Sed        0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1026218893Sdim  } else if (tok::utf16_char_constant == Kind) {
1027193326Sed    largest_character_for_kind = 0xFFFF;
1028218893Sdim  } else if (tok::utf32_char_constant == Kind) {
1029193326Sed    largest_character_for_kind = 0x10FFFF;
1030198092Srdivacky  } else {
1031205219Srdivacky    largest_character_for_kind = 0x7Fu;
1032193326Sed  }
1033218893Sdim
1034218893Sdim  while (begin != end) {
1035218893Sdim    // Is this a span of non-escape characters?
1036205219Srdivacky    if (begin[0] != '\\') {
1037193326Sed      char const *start = begin;
1038193326Sed      do {
1039193326Sed        ++begin;
1040198092Srdivacky      } while (begin != end && *begin != '\\');
1041193326Sed
1042193326Sed      char const *tmp_in_start = start;
1043193326Sed      uint32_t *tmp_out_start = buffer_begin;
1044193326Sed      ConversionResult res =
1045193326Sed          ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1046193326Sed                             reinterpret_cast<UTF8 const *>(begin),
1047198092Srdivacky                             &buffer_begin, buffer_end, strictConversion);
1048193326Sed      if (res != conversionOK) {
1049193326Sed        // If we see bad encoding for unprefixed character literals, warn and
1050193326Sed        // simply copy the byte values, for compatibility with gcc and
1051198092Srdivacky        // older versions of clang.
1052193326Sed        bool NoErrorOnBadEncoding = isAscii();
1053193326Sed        unsigned Msg = diag::err_bad_character_encoding;
1054193326Sed        if (NoErrorOnBadEncoding)
1055193326Sed          Msg = diag::warn_bad_character_encoding;
1056193326Sed        PP.Diag(Loc, Msg);
1057193326Sed        if (NoErrorOnBadEncoding) {
1058198092Srdivacky          start = tmp_in_start;
1059193326Sed          buffer_begin = tmp_out_start;
1060193326Sed          for (; start != begin; ++start, ++buffer_begin)
1061193326Sed            *buffer_begin = static_cast<uint8_t>(*start);
1062218893Sdim        } else {
1063218893Sdim          HadError = true;
1064193326Sed        }
1065193326Sed      } else {
1066193326Sed        for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1067198092Srdivacky          if (*tmp_out_start > largest_character_for_kind) {
1068193326Sed            HadError = true;
1069193326Sed            PP.Diag(Loc, diag::err_character_too_large);
1070          }
1071        }
1072      }
1073
1074      continue;
1075    }
1076    // Is this a Universal Character Name escape?
1077    if (begin[1] == 'u' || begin[1] == 'U') {
1078      unsigned short UcnLen = 0;
1079      if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1080                            FullSourceLoc(Loc, PP.getSourceManager()),
1081                            &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1082        HadError = true;
1083      } else if (*buffer_begin > largest_character_for_kind) {
1084        HadError = true;
1085        PP.Diag(Loc, diag::err_character_too_large);
1086      }
1087
1088      ++buffer_begin;
1089      continue;
1090    }
1091    unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1092    uint64_t result =
1093      ProcessCharEscape(TokBegin, begin, end, HadError,
1094                        FullSourceLoc(Loc,PP.getSourceManager()),
1095                        CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1096    *buffer_begin++ = result;
1097  }
1098
1099  unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1100
1101  if (NumCharsSoFar > 1) {
1102    if (isWide())
1103      PP.Diag(Loc, diag::warn_extraneous_char_constant);
1104    else if (isAscii() && NumCharsSoFar == 4)
1105      PP.Diag(Loc, diag::ext_four_char_character_literal);
1106    else if (isAscii())
1107      PP.Diag(Loc, diag::ext_multichar_character_literal);
1108    else
1109      PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1110    IsMultiChar = true;
1111  } else {
1112    IsMultiChar = false;
1113  }
1114
1115  llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1116
1117  // Narrow character literals act as though their value is concatenated
1118  // in this implementation, but warn on overflow.
1119  bool multi_char_too_long = false;
1120  if (isAscii() && isMultiChar()) {
1121    LitVal = 0;
1122    for (size_t i = 0; i < NumCharsSoFar; ++i) {
1123      // check for enough leading zeros to shift into
1124      multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1125      LitVal <<= 8;
1126      LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1127    }
1128  } else if (NumCharsSoFar > 0) {
1129    // otherwise just take the last character
1130    LitVal = buffer_begin[-1];
1131  }
1132
1133  if (!HadError && multi_char_too_long) {
1134    PP.Diag(Loc, diag::warn_char_constant_too_large);
1135  }
1136
1137  // Transfer the value from APInt to uint64_t
1138  Value = LitVal.getZExtValue();
1139
1140  // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1141  // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
1142  // character constants are not sign extended in the this implementation:
1143  // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1144  if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1145      PP.getLangOpts().CharIsSigned)
1146    Value = (signed char)Value;
1147}
1148
1149/// \verbatim
1150///       string-literal: [C++0x lex.string]
1151///         encoding-prefix " [s-char-sequence] "
1152///         encoding-prefix R raw-string
1153///       encoding-prefix:
1154///         u8
1155///         u
1156///         U
1157///         L
1158///       s-char-sequence:
1159///         s-char
1160///         s-char-sequence s-char
1161///       s-char:
1162///         any member of the source character set except the double-quote ",
1163///           backslash \, or new-line character
1164///         escape-sequence
1165///         universal-character-name
1166///       raw-string:
1167///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
1168///       r-char-sequence:
1169///         r-char
1170///         r-char-sequence r-char
1171///       r-char:
1172///         any member of the source character set, except a right parenthesis )
1173///           followed by the initial d-char-sequence (which may be empty)
1174///           followed by a double quote ".
1175///       d-char-sequence:
1176///         d-char
1177///         d-char-sequence d-char
1178///       d-char:
1179///         any member of the basic source character set except:
1180///           space, the left parenthesis (, the right parenthesis ),
1181///           the backslash \, and the control characters representing horizontal
1182///           tab, vertical tab, form feed, and newline.
1183///       escape-sequence: [C++0x lex.ccon]
1184///         simple-escape-sequence
1185///         octal-escape-sequence
1186///         hexadecimal-escape-sequence
1187///       simple-escape-sequence:
1188///         one of \' \" \? \\ \a \b \f \n \r \t \v
1189///       octal-escape-sequence:
1190///         \ octal-digit
1191///         \ octal-digit octal-digit
1192///         \ octal-digit octal-digit octal-digit
1193///       hexadecimal-escape-sequence:
1194///         \x hexadecimal-digit
1195///         hexadecimal-escape-sequence hexadecimal-digit
1196///       universal-character-name:
1197///         \u hex-quad
1198///         \U hex-quad hex-quad
1199///       hex-quad:
1200///         hex-digit hex-digit hex-digit hex-digit
1201/// \endverbatim
1202///
1203StringLiteralParser::
1204StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1205                    Preprocessor &PP, bool Complain)
1206  : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1207    Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1208    MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1209    ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1210  init(StringToks, NumStringToks);
1211}
1212
1213void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1214  // The literal token may have come from an invalid source location (e.g. due
1215  // to a PCH error), in which case the token length will be 0.
1216  if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1217    return DiagnoseLexingError(SourceLocation());
1218
1219  // Scan all of the string portions, remember the max individual token length,
1220  // computing a bound on the concatenated string length, and see whether any
1221  // piece is a wide-string.  If any of the string portions is a wide-string
1222  // literal, the result is a wide-string literal [C99 6.4.5p4].
1223  assert(NumStringToks && "expected at least one token");
1224  MaxTokenLength = StringToks[0].getLength();
1225  assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1226  SizeBound = StringToks[0].getLength()-2;  // -2 for "".
1227  Kind = StringToks[0].getKind();
1228
1229  hadError = false;
1230
1231  // Implement Translation Phase #6: concatenation of string literals
1232  /// (C99 5.1.1.2p1).  The common case is only one string fragment.
1233  for (unsigned i = 1; i != NumStringToks; ++i) {
1234    if (StringToks[i].getLength() < 2)
1235      return DiagnoseLexingError(StringToks[i].getLocation());
1236
1237    // The string could be shorter than this if it needs cleaning, but this is a
1238    // reasonable bound, which is all we need.
1239    assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1240    SizeBound += StringToks[i].getLength()-2;  // -2 for "".
1241
1242    // Remember maximum string piece length.
1243    if (StringToks[i].getLength() > MaxTokenLength)
1244      MaxTokenLength = StringToks[i].getLength();
1245
1246    // Remember if we see any wide or utf-8/16/32 strings.
1247    // Also check for illegal concatenations.
1248    if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1249      if (isAscii()) {
1250        Kind = StringToks[i].getKind();
1251      } else {
1252        if (Diags)
1253          Diags->Report(StringToks[i].getLocation(),
1254                        diag::err_unsupported_string_concat);
1255        hadError = true;
1256      }
1257    }
1258  }
1259
1260  // Include space for the null terminator.
1261  ++SizeBound;
1262
1263  // TODO: K&R warning: "traditional C rejects string constant concatenation"
1264
1265  // Get the width in bytes of char/wchar_t/char16_t/char32_t
1266  CharByteWidth = getCharWidth(Kind, Target);
1267  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1268  CharByteWidth /= 8;
1269
1270  // The output buffer size needs to be large enough to hold wide characters.
1271  // This is a worst-case assumption which basically corresponds to L"" "long".
1272  SizeBound *= CharByteWidth;
1273
1274  // Size the temporary buffer to hold the result string data.
1275  ResultBuf.resize(SizeBound);
1276
1277  // Likewise, but for each string piece.
1278  SmallString<512> TokenBuf;
1279  TokenBuf.resize(MaxTokenLength);
1280
1281  // Loop over all the strings, getting their spelling, and expanding them to
1282  // wide strings as appropriate.
1283  ResultPtr = &ResultBuf[0];   // Next byte to fill in.
1284
1285  Pascal = false;
1286
1287  SourceLocation UDSuffixTokLoc;
1288
1289  for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1290    const char *ThisTokBuf = &TokenBuf[0];
1291    // Get the spelling of the token, which eliminates trigraphs, etc.  We know
1292    // that ThisTokBuf points to a buffer that is big enough for the whole token
1293    // and 'spelled' tokens can only shrink.
1294    bool StringInvalid = false;
1295    unsigned ThisTokLen =
1296      Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1297                         &StringInvalid);
1298    if (StringInvalid)
1299      return DiagnoseLexingError(StringToks[i].getLocation());
1300
1301    const char *ThisTokBegin = ThisTokBuf;
1302    const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1303
1304    // Remove an optional ud-suffix.
1305    if (ThisTokEnd[-1] != '"') {
1306      const char *UDSuffixEnd = ThisTokEnd;
1307      do {
1308        --ThisTokEnd;
1309      } while (ThisTokEnd[-1] != '"');
1310
1311      StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1312
1313      if (UDSuffixBuf.empty()) {
1314        UDSuffixBuf.assign(UDSuffix);
1315        UDSuffixToken = i;
1316        UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1317        UDSuffixTokLoc = StringToks[i].getLocation();
1318      } else if (!UDSuffixBuf.equals(UDSuffix)) {
1319        // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1320        // result of a concatenation involving at least one user-defined-string-
1321        // literal, all the participating user-defined-string-literals shall
1322        // have the same ud-suffix.
1323        if (Diags) {
1324          SourceLocation TokLoc = StringToks[i].getLocation();
1325          Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1326            << UDSuffixBuf << UDSuffix
1327            << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1328            << SourceRange(TokLoc, TokLoc);
1329        }
1330        hadError = true;
1331      }
1332    }
1333
1334    // Strip the end quote.
1335    --ThisTokEnd;
1336
1337    // TODO: Input character set mapping support.
1338
1339    // Skip marker for wide or unicode strings.
1340    if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1341      ++ThisTokBuf;
1342      // Skip 8 of u8 marker for utf8 strings.
1343      if (ThisTokBuf[0] == '8')
1344        ++ThisTokBuf;
1345    }
1346
1347    // Check for raw string
1348    if (ThisTokBuf[0] == 'R') {
1349      ThisTokBuf += 2; // skip R"
1350
1351      const char *Prefix = ThisTokBuf;
1352      while (ThisTokBuf[0] != '(')
1353        ++ThisTokBuf;
1354      ++ThisTokBuf; // skip '('
1355
1356      // Remove same number of characters from the end
1357      ThisTokEnd -= ThisTokBuf - Prefix;
1358      assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1359
1360      // Copy the string over
1361      if (CopyStringFragment(StringToks[i], ThisTokBegin,
1362                             StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1363        hadError = true;
1364    } else {
1365      if (ThisTokBuf[0] != '"') {
1366        // The file may have come from PCH and then changed after loading the
1367        // PCH; Fail gracefully.
1368        return DiagnoseLexingError(StringToks[i].getLocation());
1369      }
1370      ++ThisTokBuf; // skip "
1371
1372      // Check if this is a pascal string
1373      if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1374          ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1375
1376        // If the \p sequence is found in the first token, we have a pascal string
1377        // Otherwise, if we already have a pascal string, ignore the first \p
1378        if (i == 0) {
1379          ++ThisTokBuf;
1380          Pascal = true;
1381        } else if (Pascal)
1382          ThisTokBuf += 2;
1383      }
1384
1385      while (ThisTokBuf != ThisTokEnd) {
1386        // Is this a span of non-escape characters?
1387        if (ThisTokBuf[0] != '\\') {
1388          const char *InStart = ThisTokBuf;
1389          do {
1390            ++ThisTokBuf;
1391          } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1392
1393          // Copy the character span over.
1394          if (CopyStringFragment(StringToks[i], ThisTokBegin,
1395                                 StringRef(InStart, ThisTokBuf - InStart)))
1396            hadError = true;
1397          continue;
1398        }
1399        // Is this a Universal Character Name escape?
1400        if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1401          EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1402                          ResultPtr, hadError,
1403                          FullSourceLoc(StringToks[i].getLocation(), SM),
1404                          CharByteWidth, Diags, Features);
1405          continue;
1406        }
1407        // Otherwise, this is a non-UCN escape character.  Process it.
1408        unsigned ResultChar =
1409          ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1410                            FullSourceLoc(StringToks[i].getLocation(), SM),
1411                            CharByteWidth*8, Diags, Features);
1412
1413        if (CharByteWidth == 4) {
1414          // FIXME: Make the type of the result buffer correct instead of
1415          // using reinterpret_cast.
1416          UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1417          *ResultWidePtr = ResultChar;
1418          ResultPtr += 4;
1419        } else if (CharByteWidth == 2) {
1420          // FIXME: Make the type of the result buffer correct instead of
1421          // using reinterpret_cast.
1422          UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1423          *ResultWidePtr = ResultChar & 0xFFFF;
1424          ResultPtr += 2;
1425        } else {
1426          assert(CharByteWidth == 1 && "Unexpected char width");
1427          *ResultPtr++ = ResultChar & 0xFF;
1428        }
1429      }
1430    }
1431  }
1432
1433  if (Pascal) {
1434    if (CharByteWidth == 4) {
1435      // FIXME: Make the type of the result buffer correct instead of
1436      // using reinterpret_cast.
1437      UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1438      ResultWidePtr[0] = GetNumStringChars() - 1;
1439    } else if (CharByteWidth == 2) {
1440      // FIXME: Make the type of the result buffer correct instead of
1441      // using reinterpret_cast.
1442      UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1443      ResultWidePtr[0] = GetNumStringChars() - 1;
1444    } else {
1445      assert(CharByteWidth == 1 && "Unexpected char width");
1446      ResultBuf[0] = GetNumStringChars() - 1;
1447    }
1448
1449    // Verify that pascal strings aren't too large.
1450    if (GetStringLength() > 256) {
1451      if (Diags)
1452        Diags->Report(StringToks[0].getLocation(),
1453                      diag::err_pascal_string_too_long)
1454          << SourceRange(StringToks[0].getLocation(),
1455                         StringToks[NumStringToks-1].getLocation());
1456      hadError = true;
1457      return;
1458    }
1459  } else if (Diags) {
1460    // Complain if this string literal has too many characters.
1461    unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1462
1463    if (GetNumStringChars() > MaxChars)
1464      Diags->Report(StringToks[0].getLocation(),
1465                    diag::ext_string_too_long)
1466        << GetNumStringChars() << MaxChars
1467        << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1468        << SourceRange(StringToks[0].getLocation(),
1469                       StringToks[NumStringToks-1].getLocation());
1470  }
1471}
1472
1473static const char *resyncUTF8(const char *Err, const char *End) {
1474  if (Err == End)
1475    return End;
1476  End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1477  while (++Err != End && (*Err & 0xC0) == 0x80)
1478    ;
1479  return Err;
1480}
1481
1482/// \brief This function copies from Fragment, which is a sequence of bytes
1483/// within Tok's contents (which begin at TokBegin) into ResultPtr.
1484/// Performs widening for multi-byte characters.
1485bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1486                                             const char *TokBegin,
1487                                             StringRef Fragment) {
1488  const UTF8 *ErrorPtrTmp;
1489  if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1490    return false;
1491
1492  // If we see bad encoding for unprefixed string literals, warn and
1493  // simply copy the byte values, for compatibility with gcc and older
1494  // versions of clang.
1495  bool NoErrorOnBadEncoding = isAscii();
1496  if (NoErrorOnBadEncoding) {
1497    memcpy(ResultPtr, Fragment.data(), Fragment.size());
1498    ResultPtr += Fragment.size();
1499  }
1500
1501  if (Diags) {
1502    const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1503
1504    FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1505    const DiagnosticBuilder &Builder =
1506      Diag(Diags, Features, SourceLoc, TokBegin,
1507           ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1508           NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1509                                : diag::err_bad_string_encoding);
1510
1511    const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1512    StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1513
1514    // Decode into a dummy buffer.
1515    SmallString<512> Dummy;
1516    Dummy.reserve(Fragment.size() * CharByteWidth);
1517    char *Ptr = Dummy.data();
1518
1519    while (!Builder.hasMaxRanges() &&
1520           !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1521      const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1522      NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1523      Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1524                                     ErrorPtr, NextStart);
1525      NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1526    }
1527  }
1528  return !NoErrorOnBadEncoding;
1529}
1530
1531void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1532  hadError = true;
1533  if (Diags)
1534    Diags->Report(Loc, diag::err_lexing_string);
1535}
1536
1537/// getOffsetOfStringByte - This function returns the offset of the
1538/// specified byte of the string data represented by Token.  This handles
1539/// advancing over escape sequences in the string.
1540unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1541                                                    unsigned ByteNo) const {
1542  // Get the spelling of the token.
1543  SmallString<32> SpellingBuffer;
1544  SpellingBuffer.resize(Tok.getLength());
1545
1546  bool StringInvalid = false;
1547  const char *SpellingPtr = &SpellingBuffer[0];
1548  unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1549                                       &StringInvalid);
1550  if (StringInvalid)
1551    return 0;
1552
1553  const char *SpellingStart = SpellingPtr;
1554  const char *SpellingEnd = SpellingPtr+TokLen;
1555
1556  // Handle UTF-8 strings just like narrow strings.
1557  if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1558    SpellingPtr += 2;
1559
1560  assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1561         SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1562
1563  // For raw string literals, this is easy.
1564  if (SpellingPtr[0] == 'R') {
1565    assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1566    // Skip 'R"'.
1567    SpellingPtr += 2;
1568    while (*SpellingPtr != '(') {
1569      ++SpellingPtr;
1570      assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1571    }
1572    // Skip '('.
1573    ++SpellingPtr;
1574    return SpellingPtr - SpellingStart + ByteNo;
1575  }
1576
1577  // Skip over the leading quote
1578  assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1579  ++SpellingPtr;
1580
1581  // Skip over bytes until we find the offset we're looking for.
1582  while (ByteNo) {
1583    assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1584
1585    // Step over non-escapes simply.
1586    if (*SpellingPtr != '\\') {
1587      ++SpellingPtr;
1588      --ByteNo;
1589      continue;
1590    }
1591
1592    // Otherwise, this is an escape character.  Advance over it.
1593    bool HadError = false;
1594    if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1595      const char *EscapePtr = SpellingPtr;
1596      unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1597                                      1, Features, HadError);
1598      if (Len > ByteNo) {
1599        // ByteNo is somewhere within the escape sequence.
1600        SpellingPtr = EscapePtr;
1601        break;
1602      }
1603      ByteNo -= Len;
1604    } else {
1605      ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1606                        FullSourceLoc(Tok.getLocation(), SM),
1607                        CharByteWidth*8, Diags, Features);
1608      --ByteNo;
1609    }
1610    assert(!HadError && "This method isn't valid on erroneous strings");
1611  }
1612
1613  return SpellingPtr-SpellingStart;
1614}
1615