blob: b6cc5996fdfcaf6c871e6634af73372beadfc5a1 [file] [log] [blame]
Chris Lattner2f5add62007-04-05 06:57:15 +00001//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
Steve Naroff09ef4742007-03-09 23:16:33 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Steve Naroff09ef4742007-03-09 23:16:33 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner2f5add62007-04-05 06:57:15 +000010// This file implements the NumericLiteralParser, CharLiteralParser, and
11// StringLiteralParser interfaces.
Steve Naroff09ef4742007-03-09 23:16:33 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/Basic/TargetInfo.h"
17#include "clang/Lex/LexDiagnostic.h"
18#include "clang/Lex/Preprocessor.h"
Steve Naroff4f88b312007-03-13 22:37:02 +000019#include "llvm/ADT/StringExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000020#include "llvm/Support/ConvertUTF.h"
David Blaikie76bd3c82011-09-23 05:35:21 +000021#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000022
Steve Naroff09ef4742007-03-09 23:16:33 +000023using namespace clang;
24
Douglas Gregorfb65e592011-07-27 05:40:30 +000025static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
26 switch (kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000027 default: llvm_unreachable("Unknown token type!");
Douglas Gregorfb65e592011-07-27 05:40:30 +000028 case tok::char_constant:
29 case tok::string_literal:
30 case tok::utf8_string_literal:
31 return Target.getCharWidth();
32 case tok::wide_char_constant:
33 case tok::wide_string_literal:
34 return Target.getWCharWidth();
35 case tok::utf16_char_constant:
36 case tok::utf16_string_literal:
37 return Target.getChar16Width();
38 case tok::utf32_char_constant:
39 case tok::utf32_string_literal:
40 return Target.getChar32Width();
41 }
42}
43
Seth Cantrell4cfc8172012-10-28 18:24:46 +000044static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
45 FullSourceLoc TokLoc,
46 const char *TokBegin,
47 const char *TokRangeBegin,
48 const char *TokRangeEnd) {
49 SourceLocation Begin =
50 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
51 TokLoc.getManager(), Features);
52 SourceLocation End =
53 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
54 TokLoc.getManager(), Features);
55 return CharSourceRange::getCharRange(Begin, End);
56}
57
Richard Smith639b8d02012-09-08 07:16:20 +000058/// \brief Produce a diagnostic highlighting some portion of a literal.
59///
60/// Emits the diagnostic \p DiagID, highlighting the range of characters from
61/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
62/// a substring of a spelling buffer for the token beginning at \p TokBegin.
63static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
64 const LangOptions &Features, FullSourceLoc TokLoc,
65 const char *TokBegin, const char *TokRangeBegin,
66 const char *TokRangeEnd, unsigned DiagID) {
67 SourceLocation Begin =
68 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
69 TokLoc.getManager(), Features);
Seth Cantrell4cfc8172012-10-28 18:24:46 +000070 return Diags->Report(Begin, DiagID) <<
71 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
Richard Smith639b8d02012-09-08 07:16:20 +000072}
73
Chris Lattner2f5add62007-04-05 06:57:15 +000074/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
75/// either a character or a string literal.
Richard Smith639b8d02012-09-08 07:16:20 +000076static unsigned ProcessCharEscape(const char *ThisTokBegin,
77 const char *&ThisTokBuf,
Chris Lattner2f5add62007-04-05 06:57:15 +000078 const char *ThisTokEnd, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +000079 FullSourceLoc Loc, unsigned CharWidth,
Richard Smith639b8d02012-09-08 07:16:20 +000080 DiagnosticsEngine *Diags,
81 const LangOptions &Features) {
82 const char *EscapeBegin = ThisTokBuf;
83
Chris Lattner2f5add62007-04-05 06:57:15 +000084 // Skip the '\' char.
85 ++ThisTokBuf;
86
87 // We know that this character can't be off the end of the buffer, because
88 // that would have been \", which would not have been the end of string.
89 unsigned ResultChar = *ThisTokBuf++;
90 switch (ResultChar) {
91 // These map to themselves.
92 case '\\': case '\'': case '"': case '?': break;
Mike Stump11289f42009-09-09 15:08:12 +000093
Chris Lattner2f5add62007-04-05 06:57:15 +000094 // These have fixed mappings.
95 case 'a':
96 // TODO: K&R: the meaning of '\\a' is different in traditional C
97 ResultChar = 7;
98 break;
99 case 'b':
100 ResultChar = 8;
101 break;
102 case 'e':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000103 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000104 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
105 diag::ext_nonstandard_escape) << "e";
Chris Lattner2f5add62007-04-05 06:57:15 +0000106 ResultChar = 27;
107 break;
Eli Friedman28a00aa2009-06-10 01:32:39 +0000108 case 'E':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000109 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000110 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
111 diag::ext_nonstandard_escape) << "E";
Eli Friedman28a00aa2009-06-10 01:32:39 +0000112 ResultChar = 27;
113 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000114 case 'f':
115 ResultChar = 12;
116 break;
117 case 'n':
118 ResultChar = 10;
119 break;
120 case 'r':
121 ResultChar = 13;
122 break;
123 case 't':
124 ResultChar = 9;
125 break;
126 case 'v':
127 ResultChar = 11;
128 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000129 case 'x': { // Hex escape.
130 ResultChar = 0;
131 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000132 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000133 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000134 diag::err_hex_escape_no_digits) << "x";
Chris Lattner2f5add62007-04-05 06:57:15 +0000135 HadError = 1;
Chris Lattner2f5add62007-04-05 06:57:15 +0000136 break;
137 }
Mike Stump11289f42009-09-09 15:08:12 +0000138
Chris Lattner812eda82007-05-20 05:17:04 +0000139 // Hex escapes are a maximal series of hex digits.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000140 bool Overflow = false;
141 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000142 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Chris Lattnerc10adde2007-05-20 05:00:58 +0000143 if (CharVal == -1) break;
Chris Lattner59f09b62008-09-30 20:45:40 +0000144 // About to shift out a digit?
145 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000146 ResultChar <<= 4;
147 ResultChar |= CharVal;
148 }
149
150 // See if any bits will be truncated when evaluated as a character.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000151 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
152 Overflow = true;
153 ResultChar &= ~0U >> (32-CharWidth);
154 }
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattnerc10adde2007-05-20 05:00:58 +0000156 // Check for overflow.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000157 if (Overflow && Diags) // Too many digits to fit in
Richard Smith639b8d02012-09-08 07:16:20 +0000158 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
159 diag::warn_hex_escape_too_large);
Chris Lattner2f5add62007-04-05 06:57:15 +0000160 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000161 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000162 case '0': case '1': case '2': case '3':
Chris Lattner812eda82007-05-20 05:17:04 +0000163 case '4': case '5': case '6': case '7': {
Chris Lattner2f5add62007-04-05 06:57:15 +0000164 // Octal escapes.
Chris Lattner3f4b6e32007-06-09 06:20:47 +0000165 --ThisTokBuf;
Chris Lattner812eda82007-05-20 05:17:04 +0000166 ResultChar = 0;
167
168 // Octal escapes are a series of octal digits with maximum length 3.
169 // "\0123" is a two digit sequence equal to "\012" "3".
170 unsigned NumDigits = 0;
171 do {
172 ResultChar <<= 3;
173 ResultChar |= *ThisTokBuf++ - '0';
174 ++NumDigits;
175 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
176 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump11289f42009-09-09 15:08:12 +0000177
Chris Lattner812eda82007-05-20 05:17:04 +0000178 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner812eda82007-05-20 05:17:04 +0000179 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000180 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000181 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
182 diag::warn_octal_escape_too_large);
Chris Lattner812eda82007-05-20 05:17:04 +0000183 ResultChar &= ~0U >> (32-CharWidth);
184 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000185 break;
Chris Lattner812eda82007-05-20 05:17:04 +0000186 }
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattner2f5add62007-04-05 06:57:15 +0000188 // Otherwise, these are not valid escapes.
189 case '(': case '{': case '[': case '%':
190 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000191 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000192 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
193 diag::ext_nonstandard_escape)
194 << std::string(1, ResultChar);
Eli Friedman5d72d412009-04-28 00:51:18 +0000195 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000196 default:
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000197 if (Diags == 0)
Douglas Gregor9af03022010-05-26 05:35:51 +0000198 break;
Richard Smith639b8d02012-09-08 07:16:20 +0000199
Ted Kremenek8c4c74f2010-12-03 00:09:56 +0000200 if (isgraph(ResultChar))
Richard Smith639b8d02012-09-08 07:16:20 +0000201 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
202 diag::ext_unknown_escape)
203 << std::string(1, ResultChar);
Chris Lattner59acca52008-11-22 07:23:31 +0000204 else
Richard Smith639b8d02012-09-08 07:16:20 +0000205 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
206 diag::ext_unknown_escape)
207 << "x" + llvm::utohexstr(ResultChar);
Chris Lattner2f5add62007-04-05 06:57:15 +0000208 break;
209 }
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner2f5add62007-04-05 06:57:15 +0000211 return ResultChar;
212}
213
Steve Naroff7b753d22009-03-30 23:46:03 +0000214/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Webera6bde812010-10-09 00:27:47 +0000215/// return the UTF32.
Richard Smith2a70e652012-03-09 22:27:51 +0000216static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
217 const char *ThisTokEnd,
Nico Webera6bde812010-10-09 00:27:47 +0000218 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000219 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000220 const LangOptions &Features,
221 bool in_char_string_literal = false) {
Richard Smith2a70e652012-03-09 22:27:51 +0000222 const char *UcnBegin = ThisTokBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000223
Steve Naroff7b753d22009-03-30 23:46:03 +0000224 // Skip the '\u' char's.
225 ThisTokBuf += 2;
Chris Lattner2f5add62007-04-05 06:57:15 +0000226
Steve Naroff7b753d22009-03-30 23:46:03 +0000227 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattnerbde1b812010-11-17 06:46:14 +0000228 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000229 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000230 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
Nico Webera6bde812010-10-09 00:27:47 +0000231 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000232 }
Nico Webera6bde812010-10-09 00:27:47 +0000233 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000234 unsigned short UcnLenSave = UcnLen;
Nico Webera6bde812010-10-09 00:27:47 +0000235 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000236 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000237 if (CharVal == -1) break;
238 UcnVal <<= 4;
239 UcnVal |= CharVal;
240 }
241 // If we didn't consume the proper number of digits, there is a problem.
Nico Webera6bde812010-10-09 00:27:47 +0000242 if (UcnLenSave) {
Richard Smith639b8d02012-09-08 07:16:20 +0000243 if (Diags)
244 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
245 diag::err_ucn_escape_incomplete);
Nico Webera6bde812010-10-09 00:27:47 +0000246 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000247 }
Richard Smith2a70e652012-03-09 22:27:51 +0000248
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000249 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith2a70e652012-03-09 22:27:51 +0000250 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
251 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattnerbde1b812010-11-17 06:46:14 +0000252 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000253 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
254 diag::err_ucn_escape_invalid);
Nico Webera6bde812010-10-09 00:27:47 +0000255 return false;
256 }
Richard Smith2a70e652012-03-09 22:27:51 +0000257
258 // C++11 allows UCNs that refer to control characters and basic source
259 // characters inside character and string literals
260 if (UcnVal < 0xa0 &&
261 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000262 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
Richard Smith2a70e652012-03-09 22:27:51 +0000263 if (Diags) {
Richard Smith2a70e652012-03-09 22:27:51 +0000264 char BasicSCSChar = UcnVal;
265 if (UcnVal >= 0x20 && UcnVal < 0x7f)
Richard Smith639b8d02012-09-08 07:16:20 +0000266 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
267 IsError ? diag::err_ucn_escape_basic_scs :
268 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
269 << StringRef(&BasicSCSChar, 1);
Richard Smith2a70e652012-03-09 22:27:51 +0000270 else
Richard Smith639b8d02012-09-08 07:16:20 +0000271 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
272 IsError ? diag::err_ucn_control_character :
273 diag::warn_cxx98_compat_literal_ucn_control_character);
Richard Smith2a70e652012-03-09 22:27:51 +0000274 }
275 if (IsError)
276 return false;
277 }
278
Richard Smith639b8d02012-09-08 07:16:20 +0000279 if (!Features.CPlusPlus && !Features.C99 && Diags)
280 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Rosec0cba272013-01-27 20:12:04 +0000281 diag::warn_ucn_not_valid_in_c89_literal);
Richard Smith639b8d02012-09-08 07:16:20 +0000282
Nico Webera6bde812010-10-09 00:27:47 +0000283 return true;
284}
285
Richard Smith4060f772012-06-13 05:37:23 +0000286/// MeasureUCNEscape - Determine the number of bytes within the resulting string
287/// which this UCN will occupy.
288static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
289 const char *ThisTokEnd, unsigned CharByteWidth,
290 const LangOptions &Features, bool &HadError) {
291 // UTF-32: 4 bytes per escape.
292 if (CharByteWidth == 4)
293 return 4;
294
295 uint32_t UcnVal = 0;
296 unsigned short UcnLen = 0;
297 FullSourceLoc Loc;
298
299 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
300 UcnLen, Loc, 0, Features, true)) {
301 HadError = true;
302 return 0;
303 }
304
305 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
306 if (CharByteWidth == 2)
307 return UcnVal <= 0xFFFF ? 2 : 4;
308
309 // UTF-8.
310 if (UcnVal < 0x80)
311 return 1;
312 if (UcnVal < 0x800)
313 return 2;
314 if (UcnVal < 0x10000)
315 return 3;
316 return 4;
317}
318
Nico Webera6bde812010-10-09 00:27:47 +0000319/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
320/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
321/// StringLiteralParser. When we decide to implement UCN's for identifiers,
322/// we will likely rework our support for UCN's.
Richard Smith2a70e652012-03-09 22:27:51 +0000323static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
324 const char *ThisTokEnd,
Chris Lattner2be8aa92010-11-17 07:12:42 +0000325 char *&ResultBuf, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000326 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikie9c902b52011-09-25 23:23:43 +0000327 DiagnosticsEngine *Diags,
328 const LangOptions &Features) {
Nico Webera6bde812010-10-09 00:27:47 +0000329 typedef uint32_t UTF32;
330 UTF32 UcnVal = 0;
331 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +0000332 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
333 Loc, Diags, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000334 HadError = true;
Steve Naroff7b753d22009-03-30 23:46:03 +0000335 return;
336 }
Nico Webera6bde812010-10-09 00:27:47 +0000337
Douglas Gregorfb65e592011-07-27 05:40:30 +0000338 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
339 "only character widths of 1, 2, or 4 bytes supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000340
Douglas Gregorfb65e592011-07-27 05:40:30 +0000341 (void)UcnLen;
342 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000343
Douglas Gregorfb65e592011-07-27 05:40:30 +0000344 if (CharByteWidth == 4) {
Eli Friedmand1370792011-11-02 23:06:23 +0000345 // FIXME: Make the type of the result buffer correct instead of
346 // using reinterpret_cast.
347 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
348 *ResultPtr = UcnVal;
349 ResultBuf += 4;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000350 return;
351 }
352
353 if (CharByteWidth == 2) {
Eli Friedmand1370792011-11-02 23:06:23 +0000354 // FIXME: Make the type of the result buffer correct instead of
355 // using reinterpret_cast.
356 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
357
Richard Smith0948d932012-06-13 05:41:29 +0000358 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmand1370792011-11-02 23:06:23 +0000359 *ResultPtr = UcnVal;
360 ResultBuf += 2;
Nico Weber9762e0a2010-10-06 04:57:26 +0000361 return;
362 }
Nico Weber9762e0a2010-10-06 04:57:26 +0000363
Eli Friedmand1370792011-11-02 23:06:23 +0000364 // Convert to UTF16.
Nico Weber9762e0a2010-10-06 04:57:26 +0000365 UcnVal -= 0x10000;
Eli Friedmand1370792011-11-02 23:06:23 +0000366 *ResultPtr = 0xD800 + (UcnVal >> 10);
367 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
368 ResultBuf += 4;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000369 return;
370 }
Douglas Gregorfb65e592011-07-27 05:40:30 +0000371
372 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
373
Steve Naroff7b753d22009-03-30 23:46:03 +0000374 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
375 // The conversion below was inspired by:
376 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump11289f42009-09-09 15:08:12 +0000377 // First, we determine how many bytes the result will require.
Steve Naroffc94adda2009-04-01 11:09:15 +0000378 typedef uint8_t UTF8;
Steve Naroff7b753d22009-03-30 23:46:03 +0000379
380 unsigned short bytesToWrite = 0;
381 if (UcnVal < (UTF32)0x80)
382 bytesToWrite = 1;
383 else if (UcnVal < (UTF32)0x800)
384 bytesToWrite = 2;
385 else if (UcnVal < (UTF32)0x10000)
386 bytesToWrite = 3;
387 else
388 bytesToWrite = 4;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff7b753d22009-03-30 23:46:03 +0000390 const unsigned byteMask = 0xBF;
391 const unsigned byteMark = 0x80;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Steve Naroff7b753d22009-03-30 23:46:03 +0000393 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Narofff2a880c2009-03-31 10:29:45 +0000394 // into the first byte, depending on how many bytes follow.
Mike Stump11289f42009-09-09 15:08:12 +0000395 static const UTF8 firstByteMark[5] = {
Steve Narofff2a880c2009-03-31 10:29:45 +0000396 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff7b753d22009-03-30 23:46:03 +0000397 };
398 // Finally, we write the bytes into ResultBuf.
399 ResultBuf += bytesToWrite;
400 switch (bytesToWrite) { // note: everything falls through.
Benjamin Kramerf23a6e62012-11-08 19:22:26 +0000401 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
402 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
403 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
404 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000405 }
406 // Update the buffer.
407 ResultBuf += bytesToWrite;
408}
Chris Lattner2f5add62007-04-05 06:57:15 +0000409
410
Steve Naroff09ef4742007-03-09 23:16:33 +0000411/// integer-constant: [C99 6.4.4.1]
412/// decimal-constant integer-suffix
413/// octal-constant integer-suffix
414/// hexadecimal-constant integer-suffix
Richard Smith81292452012-03-08 21:59:28 +0000415/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smith39570d002012-03-08 08:45:32 +0000416/// decimal-literal ud-suffix
417/// octal-literal ud-suffix
418/// hexadecimal-literal ud-suffix
Mike Stump11289f42009-09-09 15:08:12 +0000419/// decimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000420/// nonzero-digit
421/// decimal-constant digit
Mike Stump11289f42009-09-09 15:08:12 +0000422/// octal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000423/// 0
424/// octal-constant octal-digit
Mike Stump11289f42009-09-09 15:08:12 +0000425/// hexadecimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000426/// hexadecimal-prefix hexadecimal-digit
427/// hexadecimal-constant hexadecimal-digit
428/// hexadecimal-prefix: one of
429/// 0x 0X
430/// integer-suffix:
431/// unsigned-suffix [long-suffix]
432/// unsigned-suffix [long-long-suffix]
433/// long-suffix [unsigned-suffix]
434/// long-long-suffix [unsigned-sufix]
435/// nonzero-digit:
436/// 1 2 3 4 5 6 7 8 9
437/// octal-digit:
438/// 0 1 2 3 4 5 6 7
439/// hexadecimal-digit:
440/// 0 1 2 3 4 5 6 7 8 9
441/// a b c d e f
442/// A B C D E F
443/// unsigned-suffix: one of
444/// u U
445/// long-suffix: one of
446/// l L
Mike Stump11289f42009-09-09 15:08:12 +0000447/// long-long-suffix: one of
Steve Naroff09ef4742007-03-09 23:16:33 +0000448/// ll LL
449///
450/// floating-constant: [C99 6.4.4.2]
451/// TODO: add rules...
452///
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000453NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
454 SourceLocation TokLoc,
455 Preprocessor &PP)
456 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattner59f09b62008-09-30 20:45:40 +0000458 // This routine assumes that the range begin/end matches the regex for integer
459 // and FP constants (specifically, the 'pp-number' regex), and assumes that
460 // the byte at "*end" is both valid and not part of the regex. Because of
461 // this, it doesn't have to check for 'overscan' in various places.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000462 assert(!isalnum(*ThisTokEnd) && *ThisTokEnd != '.' && *ThisTokEnd != '_' &&
Chris Lattner59f09b62008-09-30 20:45:40 +0000463 "Lexer didn't maximally munch?");
Mike Stump11289f42009-09-09 15:08:12 +0000464
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000465 s = DigitsBegin = ThisTokBegin;
Steve Naroff09ef4742007-03-09 23:16:33 +0000466 saw_exponent = false;
467 saw_period = false;
Richard Smith39570d002012-03-08 08:45:32 +0000468 saw_ud_suffix = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000469 isLong = false;
470 isUnsigned = false;
471 isLongLong = false;
Chris Lattnered045422007-08-26 03:29:23 +0000472 isFloat = false;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000473 isImaginary = false;
Mike Stumpc99c0222009-10-08 22:55:36 +0000474 isMicrosoftInteger = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000475 hadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000476
Steve Naroff09ef4742007-03-09 23:16:33 +0000477 if (*s == '0') { // parse radix
Chris Lattner6016a512008-06-30 06:39:54 +0000478 ParseNumberStartingWithZero(TokLoc);
479 if (hadError)
480 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000481 } else { // the first digit is non-zero
482 radix = 10;
483 s = SkipDigits(s);
484 if (s == ThisTokEnd) {
Chris Lattner328fa5c2007-06-08 17:12:06 +0000485 // Done.
Christopher Lamb42e69f22007-11-29 06:06:27 +0000486 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000487 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000488 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000489 hadError = true;
Chris Lattner328fa5c2007-06-08 17:12:06 +0000490 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000491 } else if (*s == '.') {
492 s++;
493 saw_period = true;
494 s = SkipDigits(s);
Mike Stump11289f42009-09-09 15:08:12 +0000495 }
Chris Lattnerfb8b8f22008-09-29 23:12:31 +0000496 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner4885b972008-04-20 18:47:55 +0000497 const char *Exponent = s;
Steve Naroff09ef4742007-03-09 23:16:33 +0000498 s++;
499 saw_exponent = true;
500 if (*s == '+' || *s == '-') s++; // sign
501 const char *first_non_digit = SkipDigits(s);
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000502 if (first_non_digit != s) {
Steve Naroff09ef4742007-03-09 23:16:33 +0000503 s = first_non_digit;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000504 } else {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000505 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000506 diag::err_exponent_has_no_digits);
507 hadError = true;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000508 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000509 }
510 }
511 }
512
513 SuffixBegin = s;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattnerf55ab182007-08-26 01:58:14 +0000515 // Parse the suffix. At this point we can classify whether we have an FP or
516 // integer constant.
517 bool isFPConstant = isFloatingLiteral();
Mike Stump11289f42009-09-09 15:08:12 +0000518
Chris Lattnerf55ab182007-08-26 01:58:14 +0000519 // Loop over all of the characters of the suffix. If we see something bad,
520 // we break out of the loop.
521 for (; s != ThisTokEnd; ++s) {
522 switch (*s) {
523 case 'f': // FP Suffix for "float"
524 case 'F':
525 if (!isFPConstant) break; // Error for integer constant.
Chris Lattnered045422007-08-26 03:29:23 +0000526 if (isFloat || isLong) break; // FF, LF invalid.
527 isFloat = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000528 continue; // Success.
529 case 'u':
530 case 'U':
531 if (isFPConstant) break; // Error for floating constant.
532 if (isUnsigned) break; // Cannot be repeated.
533 isUnsigned = true;
534 continue; // Success.
535 case 'l':
536 case 'L':
537 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattnered045422007-08-26 03:29:23 +0000538 if (isFloat) break; // LF invalid.
Mike Stump11289f42009-09-09 15:08:12 +0000539
Chris Lattnerf55ab182007-08-26 01:58:14 +0000540 // Check for long long. The L's need to be adjacent and the same case.
541 if (s+1 != ThisTokEnd && s[1] == s[0]) {
542 if (isFPConstant) break; // long long invalid for floats.
543 isLongLong = true;
544 ++s; // Eat both of them.
545 } else {
Steve Naroff09ef4742007-03-09 23:16:33 +0000546 isLong = true;
Steve Naroff09ef4742007-03-09 23:16:33 +0000547 }
Chris Lattnerf55ab182007-08-26 01:58:14 +0000548 continue; // Success.
549 case 'i':
Chris Lattner26f6c222010-10-14 00:24:10 +0000550 case 'I':
David Blaikiebbafb8a2012-03-11 07:00:24 +0000551 if (PP.getLangOpts().MicrosoftExt) {
Fariborz Jahanian8c6c0b62010-01-22 21:36:53 +0000552 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000553
Steve Naroffa1f41452008-04-04 21:02:54 +0000554 // Allow i8, i16, i32, i64, and i128.
Mike Stumpc99c0222009-10-08 22:55:36 +0000555 if (s + 1 != ThisTokEnd) {
556 switch (s[1]) {
557 case '8':
558 s += 2; // i8 suffix
559 isMicrosoftInteger = true;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000560 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000561 case '1':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000562 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000563 if (s[2] == '6') {
564 s += 3; // i16 suffix
565 isMicrosoftInteger = true;
566 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000567 else if (s[2] == '2') {
568 if (s + 3 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000569 if (s[3] == '8') {
570 s += 4; // i128 suffix
571 isMicrosoftInteger = true;
572 }
Mike Stumpc99c0222009-10-08 22:55:36 +0000573 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000574 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000575 case '3':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000576 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000577 if (s[2] == '2') {
578 s += 3; // i32 suffix
579 isLong = true;
580 isMicrosoftInteger = true;
581 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000582 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000583 case '6':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000584 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000585 if (s[2] == '4') {
586 s += 3; // i64 suffix
587 isLongLong = true;
588 isMicrosoftInteger = true;
589 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000590 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000591 default:
592 break;
593 }
594 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000595 }
Steve Naroffa1f41452008-04-04 21:02:54 +0000596 }
597 // fall through.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000598 case 'j':
599 case 'J':
600 if (isImaginary) break; // Cannot be repeated.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000601 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Chris Lattnerf55ab182007-08-26 01:58:14 +0000602 diag::ext_imaginary_constant);
603 isImaginary = true;
604 continue; // Success.
Steve Naroff09ef4742007-03-09 23:16:33 +0000605 }
Richard Smith39570d002012-03-08 08:45:32 +0000606 // If we reached here, there was an error or a ud-suffix.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000607 break;
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Chris Lattnerf55ab182007-08-26 01:58:14 +0000610 if (s != ThisTokEnd) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000611 if (PP.getLangOpts().CPlusPlus11 && s == SuffixBegin && *s == '_') {
Richard Smith39570d002012-03-08 08:45:32 +0000612 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
613 // with an '_' are ill-formed.
614 saw_ud_suffix = true;
615 return;
616 }
617
618 // Report an error if there are any.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000619 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000620 isFPConstant ? diag::err_invalid_suffix_float_constant :
621 diag::err_invalid_suffix_integer_constant)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000622 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattner59acca52008-11-22 07:23:31 +0000623 hadError = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000624 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000625 }
626}
627
Chris Lattner6016a512008-06-30 06:39:54 +0000628/// ParseNumberStartingWithZero - This method is called when the first character
629/// of the number is found to be a zero. This means it is either an octal
630/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump11289f42009-09-09 15:08:12 +0000631/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner6016a512008-06-30 06:39:54 +0000632/// radix etc.
633void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
634 assert(s[0] == '0' && "Invalid method call");
635 s++;
Mike Stump11289f42009-09-09 15:08:12 +0000636
Chris Lattner6016a512008-06-30 06:39:54 +0000637 // Handle a hex number like 0x1234.
638 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
639 s++;
640 radix = 16;
641 DigitsBegin = s;
642 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000643 bool noSignificand = (s == DigitsBegin);
Chris Lattner6016a512008-06-30 06:39:54 +0000644 if (s == ThisTokEnd) {
645 // Done.
646 } else if (*s == '.') {
647 s++;
648 saw_period = true;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000649 const char *floatDigitsBegin = s;
Chris Lattner6016a512008-06-30 06:39:54 +0000650 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000651 noSignificand &= (floatDigitsBegin == s);
Chris Lattner6016a512008-06-30 06:39:54 +0000652 }
Aaron Ballmane1224a52012-02-08 13:36:33 +0000653
654 if (noSignificand) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000655 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Aaron Ballmane1224a52012-02-08 13:36:33 +0000656 diag::err_hexconstant_requires_digits);
657 hadError = true;
658 return;
659 }
660
Chris Lattner6016a512008-06-30 06:39:54 +0000661 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump11289f42009-09-09 15:08:12 +0000662 // binary exponent is required.
Douglas Gregor86325ad2011-08-30 22:40:35 +0000663 if (*s == 'p' || *s == 'P') {
Chris Lattner6016a512008-06-30 06:39:54 +0000664 const char *Exponent = s;
665 s++;
666 saw_exponent = true;
667 if (*s == '+' || *s == '-') s++; // sign
668 const char *first_non_digit = SkipDigits(s);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000669 if (first_non_digit == s) {
Chris Lattner59acca52008-11-22 07:23:31 +0000670 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
671 diag::err_exponent_has_no_digits);
672 hadError = true;
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000673 return;
Chris Lattner6016a512008-06-30 06:39:54 +0000674 }
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000675 s = first_non_digit;
Mike Stump11289f42009-09-09 15:08:12 +0000676
David Blaikiebbafb8a2012-03-11 07:00:24 +0000677 if (!PP.getLangOpts().HexFloats)
Chris Lattner59acca52008-11-22 07:23:31 +0000678 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner6016a512008-06-30 06:39:54 +0000679 } else if (saw_period) {
Chris Lattner59acca52008-11-22 07:23:31 +0000680 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
681 diag::err_hexconstant_requires_exponent);
682 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000683 }
684 return;
685 }
Mike Stump11289f42009-09-09 15:08:12 +0000686
Chris Lattner6016a512008-06-30 06:39:54 +0000687 // Handle simple binary numbers 0b01010
688 if (*s == 'b' || *s == 'B') {
689 // 0b101010 is a GCC extension.
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000690 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000691 ++s;
692 radix = 2;
693 DigitsBegin = s;
694 s = SkipBinaryDigits(s);
695 if (s == ThisTokEnd) {
696 // Done.
697 } else if (isxdigit(*s)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000698 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000699 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000700 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000701 }
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000702 // Other suffixes will be diagnosed by the caller.
Chris Lattner6016a512008-06-30 06:39:54 +0000703 return;
704 }
Mike Stump11289f42009-09-09 15:08:12 +0000705
Chris Lattner6016a512008-06-30 06:39:54 +0000706 // For now, the radix is set to 8. If we discover that we have a
707 // floating point constant, the radix will change to 10. Octal floating
Mike Stump11289f42009-09-09 15:08:12 +0000708 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner6016a512008-06-30 06:39:54 +0000709 radix = 8;
710 DigitsBegin = s;
711 s = SkipOctalDigits(s);
712 if (s == ThisTokEnd)
713 return; // Done, simple octal number like 01234
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000715 // If we have some other non-octal digit that *is* a decimal digit, see if
716 // this is part of a floating point number like 094.123 or 09e1.
717 if (isdigit(*s)) {
718 const char *EndDecimal = SkipDigits(s);
719 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
720 s = EndDecimal;
721 radix = 10;
722 }
723 }
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000725 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
726 // the code is using an incorrect base.
Chris Lattner6016a512008-06-30 06:39:54 +0000727 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattner59acca52008-11-22 07:23:31 +0000728 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000729 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000730 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000731 return;
732 }
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattner6016a512008-06-30 06:39:54 +0000734 if (*s == '.') {
735 s++;
736 radix = 10;
737 saw_period = true;
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000738 s = SkipDigits(s); // Skip suffix.
Chris Lattner6016a512008-06-30 06:39:54 +0000739 }
740 if (*s == 'e' || *s == 'E') { // exponent
741 const char *Exponent = s;
742 s++;
743 radix = 10;
744 saw_exponent = true;
745 if (*s == '+' || *s == '-') s++; // sign
746 const char *first_non_digit = SkipDigits(s);
747 if (first_non_digit != s) {
748 s = first_non_digit;
749 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000750 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000751 diag::err_exponent_has_no_digits);
752 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000753 return;
754 }
755 }
756}
757
Jordan Rosede584de2012-09-25 22:32:51 +0000758static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000759 switch (Radix) {
760 case 2:
761 return NumDigits <= 64;
762 case 8:
763 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
764 case 10:
765 return NumDigits <= 19; // floor(log10(2^64))
766 case 16:
767 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
768 default:
769 llvm_unreachable("impossible Radix");
770 }
771}
Chris Lattner6016a512008-06-30 06:39:54 +0000772
Chris Lattner5b743d32007-04-04 05:52:58 +0000773/// GetIntegerValue - Convert this numeric literal value to an APInt that
Chris Lattner871b4e12007-04-04 06:36:34 +0000774/// matches Val's input width. If there is an overflow, set Val to the low bits
775/// of the result and return true. Otherwise, return false.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000776bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000777 // Fast path: Compute a conservative bound on the maximum number of
778 // bits per digit in this radix. If we can't possibly overflow a
779 // uint64 based on that bound then do the simple conversion to
780 // integer. This avoids the expensive overflow checking below, and
781 // handles the common cases that matter (small decimal integers and
782 // hex/octal values which don't overflow).
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000783 const unsigned NumDigits = SuffixBegin - DigitsBegin;
Jordan Rosede584de2012-09-25 22:32:51 +0000784 if (alwaysFitsInto64Bits(radix, NumDigits)) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000785 uint64_t N = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000786 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
Jordan Rose78ed86a2013-01-18 22:33:58 +0000787 N = N * radix + llvm::hexDigitValue(*Ptr);
Daniel Dunbarbe947082008-10-16 07:32:01 +0000788
789 // This will truncate the value to Val's input width. Simply check
790 // for overflow by comparing.
791 Val = N;
792 return Val.getZExtValue() != N;
793 }
794
Chris Lattner5b743d32007-04-04 05:52:58 +0000795 Val = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000796 const char *Ptr = DigitsBegin;
Chris Lattner5b743d32007-04-04 05:52:58 +0000797
Chris Lattner23b7eb62007-06-15 23:05:46 +0000798 llvm::APInt RadixVal(Val.getBitWidth(), radix);
799 llvm::APInt CharVal(Val.getBitWidth(), 0);
800 llvm::APInt OldVal = Val;
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattner871b4e12007-04-04 06:36:34 +0000802 bool OverflowOccurred = false;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000803 while (Ptr < SuffixBegin) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000804 unsigned C = llvm::hexDigitValue(*Ptr++);
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattner5b743d32007-04-04 05:52:58 +0000806 // If this letter is out of bound for this radix, reject it.
Chris Lattner531efa42007-04-04 06:49:26 +0000807 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattner5b743d32007-04-04 05:52:58 +0000809 CharVal = C;
Mike Stump11289f42009-09-09 15:08:12 +0000810
Chris Lattner871b4e12007-04-04 06:36:34 +0000811 // Add the digit to the value in the appropriate radix. If adding in digits
812 // made the value smaller, then this overflowed.
Chris Lattner5b743d32007-04-04 05:52:58 +0000813 OldVal = Val;
Chris Lattner871b4e12007-04-04 06:36:34 +0000814
815 // Multiply by radix, did overflow occur on the multiply?
Chris Lattner5b743d32007-04-04 05:52:58 +0000816 Val *= RadixVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000817 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
818
Chris Lattner871b4e12007-04-04 06:36:34 +0000819 // Add value, did overflow occur on the value?
Daniel Dunbarb1f64422008-10-16 06:39:30 +0000820 // (a + b) ult b <=> overflow
Chris Lattner5b743d32007-04-04 05:52:58 +0000821 Val += CharVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000822 OverflowOccurred |= Val.ult(CharVal);
Chris Lattner5b743d32007-04-04 05:52:58 +0000823 }
Chris Lattner871b4e12007-04-04 06:36:34 +0000824 return OverflowOccurred;
Chris Lattner5b743d32007-04-04 05:52:58 +0000825}
826
John McCall53b93a02009-12-24 09:08:04 +0000827llvm::APFloat::opStatus
828NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenekfbb08bc2007-11-26 23:12:30 +0000829 using llvm::APFloat;
Mike Stump11289f42009-09-09 15:08:12 +0000830
Erick Tryzelaarb9073112009-08-16 23:36:28 +0000831 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall53b93a02009-12-24 09:08:04 +0000832 return Result.convertFromString(StringRef(ThisTokBegin, n),
833 APFloat::rmNearestTiesToEven);
Steve Naroff97b9e912007-07-09 23:53:58 +0000834}
Chris Lattner5b743d32007-04-04 05:52:58 +0000835
Chris Lattner2f5add62007-04-05 06:57:15 +0000836
James Dennett1cc22032012-06-17 03:34:42 +0000837/// \verbatim
Richard Smithe18f0fa2012-03-05 04:02:15 +0000838/// user-defined-character-literal: [C++11 lex.ext]
839/// character-literal ud-suffix
840/// ud-suffix:
841/// identifier
842/// character-literal: [C++11 lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +0000843/// ' c-char-sequence '
844/// u' c-char-sequence '
845/// U' c-char-sequence '
846/// L' c-char-sequence '
847/// c-char-sequence:
848/// c-char
849/// c-char-sequence c-char
850/// c-char:
851/// any member of the source character set except the single-quote ',
852/// backslash \, or new-line character
853/// escape-sequence
854/// universal-character-name
Richard Smithe18f0fa2012-03-05 04:02:15 +0000855/// escape-sequence:
Craig Topper54edcca2011-08-11 04:06:15 +0000856/// simple-escape-sequence
857/// octal-escape-sequence
858/// hexadecimal-escape-sequence
859/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +0000860/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +0000861/// octal-escape-sequence:
862/// \ octal-digit
863/// \ octal-digit octal-digit
864/// \ octal-digit octal-digit octal-digit
865/// hexadecimal-escape-sequence:
866/// \x hexadecimal-digit
867/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smithe18f0fa2012-03-05 04:02:15 +0000868/// universal-character-name: [C++11 lex.charset]
Craig Topper54edcca2011-08-11 04:06:15 +0000869/// \u hex-quad
870/// \U hex-quad hex-quad
871/// hex-quad:
872/// hex-digit hex-digit hex-digit hex-digit
James Dennett1cc22032012-06-17 03:34:42 +0000873/// \endverbatim
Craig Topper54edcca2011-08-11 04:06:15 +0000874///
Chris Lattner2f5add62007-04-05 06:57:15 +0000875CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000876 SourceLocation Loc, Preprocessor &PP,
877 tok::TokenKind kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000878 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Chris Lattner2f5add62007-04-05 06:57:15 +0000879 HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000880
Douglas Gregorfb65e592011-07-27 05:40:30 +0000881 Kind = kind;
882
Richard Smith2a70e652012-03-09 22:27:51 +0000883 const char *TokBegin = begin;
884
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000885 // Skip over wide character determinant.
886 if (Kind != tok::char_constant) {
Douglas Gregorfb65e592011-07-27 05:40:30 +0000887 ++begin;
888 }
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattner2f5add62007-04-05 06:57:15 +0000890 // Skip over the entry quote.
891 assert(begin[0] == '\'' && "Invalid token lexed");
892 ++begin;
893
Richard Smithe18f0fa2012-03-05 04:02:15 +0000894 // Remove an optional ud-suffix.
895 if (end[-1] != '\'') {
896 const char *UDSuffixEnd = end;
897 do {
898 --end;
899 } while (end[-1] != '\'');
900 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith2a70e652012-03-09 22:27:51 +0000901 UDSuffixOffset = end - TokBegin;
Richard Smithe18f0fa2012-03-05 04:02:15 +0000902 }
903
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000904 // Trim the ending quote.
Richard Smithe18f0fa2012-03-05 04:02:15 +0000905 assert(end != begin && "Invalid token lexed");
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000906 --end;
907
Mike Stump11289f42009-09-09 15:08:12 +0000908 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattner57540c52011-04-15 05:22:18 +0000909 // up to 64-bits.
Chris Lattner2f5add62007-04-05 06:57:15 +0000910 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner37e05872008-03-05 18:54:05 +0000911 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner2f5add62007-04-05 06:57:15 +0000912 "Assumes char is 8 bits");
Chris Lattner8577f622009-04-28 21:51:46 +0000913 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
914 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
915 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
916 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
917 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Guptaf09cb952009-04-21 02:21:29 +0000918
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000919 SmallVector<uint32_t,4> codepoint_buffer;
920 codepoint_buffer.resize(end-begin);
921 uint32_t *buffer_begin = &codepoint_buffer.front();
922 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump11289f42009-09-09 15:08:12 +0000923
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000924 // Unicode escapes representing characters that cannot be correctly
925 // represented in a single code unit are disallowed in character literals
926 // by this implementation.
927 uint32_t largest_character_for_kind;
928 if (tok::wide_char_constant == Kind) {
929 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
930 } else if (tok::utf16_char_constant == Kind) {
931 largest_character_for_kind = 0xFFFF;
932 } else if (tok::utf32_char_constant == Kind) {
933 largest_character_for_kind = 0x10FFFF;
934 } else {
935 largest_character_for_kind = 0x7Fu;
Chris Lattner8577f622009-04-28 21:51:46 +0000936 }
937
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000938 while (begin!=end) {
939 // Is this a span of non-escape characters?
940 if (begin[0] != '\\') {
941 char const *start = begin;
942 do {
943 ++begin;
944 } while (begin != end && *begin != '\\');
945
Eli Friedman94363522012-02-11 05:08:10 +0000946 char const *tmp_in_start = start;
947 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000948 ConversionResult res =
949 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
950 reinterpret_cast<UTF8 const *>(begin),
951 &buffer_begin,buffer_end,strictConversion);
952 if (res!=conversionOK) {
Eli Friedman94363522012-02-11 05:08:10 +0000953 // If we see bad encoding for unprefixed character literals, warn and
954 // simply copy the byte values, for compatibility with gcc and
955 // older versions of clang.
956 bool NoErrorOnBadEncoding = isAscii();
957 unsigned Msg = diag::err_bad_character_encoding;
958 if (NoErrorOnBadEncoding)
959 Msg = diag::warn_bad_character_encoding;
960 PP.Diag(Loc, Msg);
961 if (NoErrorOnBadEncoding) {
962 start = tmp_in_start;
963 buffer_begin = tmp_out_start;
964 for ( ; start != begin; ++start, ++buffer_begin)
965 *buffer_begin = static_cast<uint8_t>(*start);
966 } else {
967 HadError = true;
968 }
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000969 } else {
Eli Friedman94363522012-02-11 05:08:10 +0000970 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
971 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000972 HadError = true;
973 PP.Diag(Loc, diag::err_character_too_large);
974 }
975 }
976 }
977
978 continue;
979 }
980 // Is this a Universal Character Name excape?
981 if (begin[1] == 'u' || begin[1] == 'U') {
982 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +0000983 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000984 FullSourceLoc(Loc, PP.getSourceManager()),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000985 &PP.getDiagnostics(), PP.getLangOpts(),
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000986 true))
987 {
988 HadError = true;
989 } else if (*buffer_begin > largest_character_for_kind) {
990 HadError = true;
Richard Smith639b8d02012-09-08 07:16:20 +0000991 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000992 }
993
994 ++buffer_begin;
995 continue;
996 }
997 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
998 uint64_t result =
Richard Smith639b8d02012-09-08 07:16:20 +0000999 ProcessCharEscape(TokBegin, begin, end, HadError,
1000 FullSourceLoc(Loc,PP.getSourceManager()),
1001 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001002 *buffer_begin++ = result;
1003 }
1004
1005 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
1006
Chris Lattner8577f622009-04-28 21:51:46 +00001007 if (NumCharsSoFar > 1) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001008 if (isWide())
Douglas Gregorfb65e592011-07-27 05:40:30 +00001009 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001010 else if (isAscii() && NumCharsSoFar == 4)
1011 PP.Diag(Loc, diag::ext_four_char_character_literal);
1012 else if (isAscii())
Chris Lattner8577f622009-04-28 21:51:46 +00001013 PP.Diag(Loc, diag::ext_multichar_character_literal);
1014 else
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001015 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedmand8cec572009-06-01 05:25:02 +00001016 IsMultiChar = true;
Daniel Dunbara444cc22009-07-29 01:46:05 +00001017 } else
1018 IsMultiChar = false;
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001019
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001020 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1021
1022 // Narrow character literals act as though their value is concatenated
1023 // in this implementation, but warn on overflow.
1024 bool multi_char_too_long = false;
1025 if (isAscii() && isMultiChar()) {
1026 LitVal = 0;
1027 for (size_t i=0;i<NumCharsSoFar;++i) {
1028 // check for enough leading zeros to shift into
1029 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1030 LitVal <<= 8;
1031 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1032 }
1033 } else if (NumCharsSoFar > 0) {
1034 // otherwise just take the last character
1035 LitVal = buffer_begin[-1];
1036 }
1037
1038 if (!HadError && multi_char_too_long) {
1039 PP.Diag(Loc,diag::warn_char_constant_too_large);
1040 }
1041
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001042 // Transfer the value from APInt to uint64_t
1043 Value = LitVal.getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001044
Chris Lattner2f5add62007-04-05 06:57:15 +00001045 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1046 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1047 // character constants are not sign extended in the this implementation:
1048 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001049 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001050 PP.getLangOpts().CharIsSigned)
Chris Lattner2f5add62007-04-05 06:57:15 +00001051 Value = (signed char)Value;
1052}
1053
James Dennett99c193b2012-06-19 21:04:25 +00001054/// \verbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001055/// string-literal: [C++0x lex.string]
1056/// encoding-prefix " [s-char-sequence] "
1057/// encoding-prefix R raw-string
1058/// encoding-prefix:
1059/// u8
1060/// u
1061/// U
1062/// L
Steve Naroff4f88b312007-03-13 22:37:02 +00001063/// s-char-sequence:
1064/// s-char
1065/// s-char-sequence s-char
1066/// s-char:
Craig Topper54edcca2011-08-11 04:06:15 +00001067/// any member of the source character set except the double-quote ",
1068/// backslash \, or new-line character
1069/// escape-sequence
Steve Naroff4f88b312007-03-13 22:37:02 +00001070/// universal-character-name
Craig Topper54edcca2011-08-11 04:06:15 +00001071/// raw-string:
1072/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1073/// r-char-sequence:
1074/// r-char
1075/// r-char-sequence r-char
1076/// r-char:
1077/// any member of the source character set, except a right parenthesis )
1078/// followed by the initial d-char-sequence (which may be empty)
1079/// followed by a double quote ".
1080/// d-char-sequence:
1081/// d-char
1082/// d-char-sequence d-char
1083/// d-char:
1084/// any member of the basic source character set except:
1085/// space, the left parenthesis (, the right parenthesis ),
1086/// the backslash \, and the control characters representing horizontal
1087/// tab, vertical tab, form feed, and newline.
1088/// escape-sequence: [C++0x lex.ccon]
1089/// simple-escape-sequence
1090/// octal-escape-sequence
1091/// hexadecimal-escape-sequence
1092/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001093/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001094/// octal-escape-sequence:
1095/// \ octal-digit
1096/// \ octal-digit octal-digit
1097/// \ octal-digit octal-digit octal-digit
1098/// hexadecimal-escape-sequence:
1099/// \x hexadecimal-digit
1100/// hexadecimal-escape-sequence hexadecimal-digit
Steve Naroff4f88b312007-03-13 22:37:02 +00001101/// universal-character-name:
1102/// \u hex-quad
1103/// \U hex-quad hex-quad
1104/// hex-quad:
1105/// hex-digit hex-digit hex-digit hex-digit
James Dennett99c193b2012-06-19 21:04:25 +00001106/// \endverbatim
Chris Lattner2f5add62007-04-05 06:57:15 +00001107///
Steve Naroff4f88b312007-03-13 22:37:02 +00001108StringLiteralParser::
Chris Lattner146762e2007-07-20 16:59:19 +00001109StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner6bab4352010-11-17 07:21:13 +00001110 Preprocessor &PP, bool Complain)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001111 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001112 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001113 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1114 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner6bab4352010-11-17 07:21:13 +00001115 init(StringToks, NumStringToks);
1116}
1117
1118void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001119 // The literal token may have come from an invalid source location (e.g. due
1120 // to a PCH error), in which case the token length will be 0.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001121 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1122 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001123
Steve Naroff4f88b312007-03-13 22:37:02 +00001124 // Scan all of the string portions, remember the max individual token length,
1125 // computing a bound on the concatenated string length, and see whether any
1126 // piece is a wide-string. If any of the string portions is a wide-string
1127 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001128 assert(NumStringToks && "expected at least one token");
Alexis Hunt3b791862010-08-30 17:47:05 +00001129 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001130 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001131 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001132 Kind = StringToks[0].getKind();
Alexis Hunt3b791862010-08-30 17:47:05 +00001133
1134 hadError = false;
Chris Lattner2f5add62007-04-05 06:57:15 +00001135
1136 // Implement Translation Phase #6: concatenation of string literals
1137 /// (C99 5.1.1.2p1). The common case is only one string fragment.
Steve Naroff4f88b312007-03-13 22:37:02 +00001138 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001139 if (StringToks[i].getLength() < 2)
1140 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001141
Steve Naroff4f88b312007-03-13 22:37:02 +00001142 // The string could be shorter than this if it needs cleaning, but this is a
1143 // reasonable bound, which is all we need.
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001144 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001145 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump11289f42009-09-09 15:08:12 +00001146
Steve Naroff4f88b312007-03-13 22:37:02 +00001147 // Remember maximum string piece length.
Alexis Hunt3b791862010-08-30 17:47:05 +00001148 if (StringToks[i].getLength() > MaxTokenLength)
1149 MaxTokenLength = StringToks[i].getLength();
Mike Stump11289f42009-09-09 15:08:12 +00001150
Douglas Gregorfb65e592011-07-27 05:40:30 +00001151 // Remember if we see any wide or utf-8/16/32 strings.
1152 // Also check for illegal concatenations.
1153 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1154 if (isAscii()) {
1155 Kind = StringToks[i].getKind();
1156 } else {
1157 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +00001158 Diags->Report(StringToks[i].getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001159 diag::err_unsupported_string_concat);
1160 hadError = true;
1161 }
1162 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001163 }
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001164
Steve Naroff4f88b312007-03-13 22:37:02 +00001165 // Include space for the null terminator.
1166 ++SizeBound;
Mike Stump11289f42009-09-09 15:08:12 +00001167
Steve Naroff4f88b312007-03-13 22:37:02 +00001168 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump11289f42009-09-09 15:08:12 +00001169
Douglas Gregorfb65e592011-07-27 05:40:30 +00001170 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1171 CharByteWidth = getCharWidth(Kind, Target);
1172 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1173 CharByteWidth /= 8;
Mike Stump11289f42009-09-09 15:08:12 +00001174
Steve Naroff4f88b312007-03-13 22:37:02 +00001175 // The output buffer size needs to be large enough to hold wide characters.
1176 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001177 SizeBound *= CharByteWidth;
Mike Stump11289f42009-09-09 15:08:12 +00001178
Steve Naroff4f88b312007-03-13 22:37:02 +00001179 // Size the temporary buffer to hold the result string data.
1180 ResultBuf.resize(SizeBound);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Steve Naroff4f88b312007-03-13 22:37:02 +00001182 // Likewise, but for each string piece.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001183 SmallString<512> TokenBuf;
Steve Naroff4f88b312007-03-13 22:37:02 +00001184 TokenBuf.resize(MaxTokenLength);
Mike Stump11289f42009-09-09 15:08:12 +00001185
Steve Naroff4f88b312007-03-13 22:37:02 +00001186 // Loop over all the strings, getting their spelling, and expanding them to
1187 // wide strings as appropriate.
1188 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump11289f42009-09-09 15:08:12 +00001189
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001190 Pascal = false;
Mike Stump11289f42009-09-09 15:08:12 +00001191
Richard Smithe18f0fa2012-03-05 04:02:15 +00001192 SourceLocation UDSuffixTokLoc;
1193
Steve Naroff4f88b312007-03-13 22:37:02 +00001194 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1195 const char *ThisTokBuf = &TokenBuf[0];
1196 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1197 // that ThisTokBuf points to a buffer that is big enough for the whole token
1198 // and 'spelled' tokens can only shrink.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001199 bool StringInvalid = false;
Chris Lattner6bab4352010-11-17 07:21:13 +00001200 unsigned ThisTokLen =
Chris Lattner39720112010-11-17 07:26:20 +00001201 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1202 &StringInvalid);
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001203 if (StringInvalid)
1204 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001205
Richard Smith2a70e652012-03-09 22:27:51 +00001206 const char *ThisTokBegin = ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001207 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1208
1209 // Remove an optional ud-suffix.
1210 if (ThisTokEnd[-1] != '"') {
1211 const char *UDSuffixEnd = ThisTokEnd;
1212 do {
1213 --ThisTokEnd;
1214 } while (ThisTokEnd[-1] != '"');
1215
1216 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1217
1218 if (UDSuffixBuf.empty()) {
1219 UDSuffixBuf.assign(UDSuffix);
Richard Smith75b67d62012-03-08 01:34:56 +00001220 UDSuffixToken = i;
1221 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001222 UDSuffixTokLoc = StringToks[i].getLocation();
1223 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1224 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1225 // result of a concatenation involving at least one user-defined-string-
1226 // literal, all the participating user-defined-string-literals shall
1227 // have the same ud-suffix.
1228 if (Diags) {
1229 SourceLocation TokLoc = StringToks[i].getLocation();
1230 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1231 << UDSuffixBuf << UDSuffix
1232 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1233 << SourceRange(TokLoc, TokLoc);
1234 }
1235 hadError = true;
1236 }
1237 }
1238
1239 // Strip the end quote.
1240 --ThisTokEnd;
1241
Steve Naroff4f88b312007-03-13 22:37:02 +00001242 // TODO: Input character set mapping support.
Mike Stump11289f42009-09-09 15:08:12 +00001243
Craig Topper61147ed2011-08-08 06:10:39 +00001244 // Skip marker for wide or unicode strings.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001245 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Chris Lattnerc10adde2007-05-20 05:00:58 +00001246 ++ThisTokBuf;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001247 // Skip 8 of u8 marker for utf8 strings.
1248 if (ThisTokBuf[0] == '8')
1249 ++ThisTokBuf;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +00001250 }
Mike Stump11289f42009-09-09 15:08:12 +00001251
Craig Topper54edcca2011-08-11 04:06:15 +00001252 // Check for raw string
1253 if (ThisTokBuf[0] == 'R') {
1254 ThisTokBuf += 2; // skip R"
Mike Stump11289f42009-09-09 15:08:12 +00001255
Craig Topper54edcca2011-08-11 04:06:15 +00001256 const char *Prefix = ThisTokBuf;
1257 while (ThisTokBuf[0] != '(')
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001258 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001259 ++ThisTokBuf; // skip '('
Mike Stump11289f42009-09-09 15:08:12 +00001260
Richard Smith81292452012-03-08 21:59:28 +00001261 // Remove same number of characters from the end
1262 ThisTokEnd -= ThisTokBuf - Prefix;
1263 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper54edcca2011-08-11 04:06:15 +00001264
1265 // Copy the string over
Richard Smith639b8d02012-09-08 07:16:20 +00001266 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1267 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1268 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001269 } else {
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001270 if (ThisTokBuf[0] != '"') {
1271 // The file may have come from PCH and then changed after loading the
1272 // PCH; Fail gracefully.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001273 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001274 }
Craig Topper54edcca2011-08-11 04:06:15 +00001275 ++ThisTokBuf; // skip "
1276
1277 // Check if this is a pascal string
1278 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1279 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1280
1281 // If the \p sequence is found in the first token, we have a pascal string
1282 // Otherwise, if we already have a pascal string, ignore the first \p
1283 if (i == 0) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001284 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001285 Pascal = true;
1286 } else if (Pascal)
1287 ThisTokBuf += 2;
1288 }
Mike Stump11289f42009-09-09 15:08:12 +00001289
Craig Topper54edcca2011-08-11 04:06:15 +00001290 while (ThisTokBuf != ThisTokEnd) {
1291 // Is this a span of non-escape characters?
1292 if (ThisTokBuf[0] != '\\') {
1293 const char *InStart = ThisTokBuf;
1294 do {
1295 ++ThisTokBuf;
1296 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1297
1298 // Copy the character span over.
Richard Smith639b8d02012-09-08 07:16:20 +00001299 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1300 StringRef(InStart, ThisTokBuf - InStart)))
1301 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001302 continue;
Steve Naroff4f88b312007-03-13 22:37:02 +00001303 }
Craig Topper54edcca2011-08-11 04:06:15 +00001304 // Is this a Universal Character Name escape?
1305 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith2a70e652012-03-09 22:27:51 +00001306 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1307 ResultPtr, hadError,
1308 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper54edcca2011-08-11 04:06:15 +00001309 CharByteWidth, Diags, Features);
1310 continue;
1311 }
1312 // Otherwise, this is a non-UCN escape character. Process it.
1313 unsigned ResultChar =
Richard Smith639b8d02012-09-08 07:16:20 +00001314 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper54edcca2011-08-11 04:06:15 +00001315 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001316 CharByteWidth*8, Diags, Features);
Mike Stump11289f42009-09-09 15:08:12 +00001317
Eli Friedmand1370792011-11-02 23:06:23 +00001318 if (CharByteWidth == 4) {
1319 // FIXME: Make the type of the result buffer correct instead of
1320 // using reinterpret_cast.
1321 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001322 *ResultWidePtr = ResultChar;
Eli Friedmand1370792011-11-02 23:06:23 +00001323 ResultPtr += 4;
1324 } else if (CharByteWidth == 2) {
1325 // FIXME: Make the type of the result buffer correct instead of
1326 // using reinterpret_cast.
1327 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001328 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmand1370792011-11-02 23:06:23 +00001329 ResultPtr += 2;
1330 } else {
1331 assert(CharByteWidth == 1 && "Unexpected char width");
1332 *ResultPtr++ = ResultChar & 0xFF;
1333 }
Craig Topper54edcca2011-08-11 04:06:15 +00001334 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001335 }
1336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattner8a24e582009-01-16 18:51:42 +00001338 if (Pascal) {
Eli Friedman20554702011-11-05 00:41:04 +00001339 if (CharByteWidth == 4) {
1340 // FIXME: Make the type of the result buffer correct instead of
1341 // using reinterpret_cast.
1342 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1343 ResultWidePtr[0] = GetNumStringChars() - 1;
1344 } else if (CharByteWidth == 2) {
1345 // FIXME: Make the type of the result buffer correct instead of
1346 // using reinterpret_cast.
1347 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1348 ResultWidePtr[0] = GetNumStringChars() - 1;
1349 } else {
1350 assert(CharByteWidth == 1 && "Unexpected char width");
1351 ResultBuf[0] = GetNumStringChars() - 1;
1352 }
Chris Lattner8a24e582009-01-16 18:51:42 +00001353
1354 // Verify that pascal strings aren't too large.
Chris Lattner6bab4352010-11-17 07:21:13 +00001355 if (GetStringLength() > 256) {
Richard Smith639b8d02012-09-08 07:16:20 +00001356 if (Diags)
1357 Diags->Report(StringToks[0].getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001358 diag::err_pascal_string_too_long)
1359 << SourceRange(StringToks[0].getLocation(),
1360 StringToks[NumStringToks-1].getLocation());
Douglas Gregorfb65e592011-07-27 05:40:30 +00001361 hadError = true;
Eli Friedman1c3fb222009-04-01 03:17:08 +00001362 return;
1363 }
Chris Lattner6bab4352010-11-17 07:21:13 +00001364 } else if (Diags) {
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001365 // Complain if this string literal has too many characters.
Chris Lattner2be8aa92010-11-17 07:12:42 +00001366 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001367
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001368 if (GetNumStringChars() > MaxChars)
Richard Smith639b8d02012-09-08 07:16:20 +00001369 Diags->Report(StringToks[0].getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001370 diag::ext_string_too_long)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001371 << GetNumStringChars() << MaxChars
Chris Lattner2be8aa92010-11-17 07:12:42 +00001372 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001373 << SourceRange(StringToks[0].getLocation(),
1374 StringToks[NumStringToks-1].getLocation());
Chris Lattner8a24e582009-01-16 18:51:42 +00001375 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001376}
Chris Lattnerddb71912009-02-18 19:21:10 +00001377
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001378static const char *resyncUTF8(const char *Err, const char *End) {
1379 if (Err == End)
1380 return End;
1381 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1382 while (++Err != End && (*Err & 0xC0) == 0x80)
1383 ;
1384 return Err;
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001385}
1386
Richard Smith639b8d02012-09-08 07:16:20 +00001387/// \brief This function copies from Fragment, which is a sequence of bytes
1388/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper54edcca2011-08-11 04:06:15 +00001389/// Performs widening for multi-byte characters.
Richard Smith639b8d02012-09-08 07:16:20 +00001390bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1391 const char *TokBegin,
1392 StringRef Fragment) {
1393 const UTF8 *ErrorPtrTmp;
1394 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1395 return false;
Craig Topper54edcca2011-08-11 04:06:15 +00001396
Eli Friedman94363522012-02-11 05:08:10 +00001397 // If we see bad encoding for unprefixed string literals, warn and
1398 // simply copy the byte values, for compatibility with gcc and older
1399 // versions of clang.
1400 bool NoErrorOnBadEncoding = isAscii();
Richard Smith639b8d02012-09-08 07:16:20 +00001401 if (NoErrorOnBadEncoding) {
1402 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1403 ResultPtr += Fragment.size();
1404 }
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001405
Richard Smith639b8d02012-09-08 07:16:20 +00001406 if (Diags) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001407 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1408
1409 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1410 const DiagnosticBuilder &Builder =
1411 Diag(Diags, Features, SourceLoc, TokBegin,
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001412 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001413 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1414 : diag::err_bad_string_encoding);
1415
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001416 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001417 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1418
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001419 // Decode into a dummy buffer.
1420 SmallString<512> Dummy;
1421 Dummy.reserve(Fragment.size() * CharByteWidth);
1422 char *Ptr = Dummy.data();
1423
David Blaikiea0613172012-10-30 23:22:22 +00001424 while (!Builder.hasMaxRanges() &&
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001425 !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001426 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001427 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001428 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1429 ErrorPtr, NextStart);
1430 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1431 }
Richard Smith639b8d02012-09-08 07:16:20 +00001432 }
Eli Friedman94363522012-02-11 05:08:10 +00001433 return !NoErrorOnBadEncoding;
1434}
Craig Topper54edcca2011-08-11 04:06:15 +00001435
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001436void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1437 hadError = true;
1438 if (Diags)
1439 Diags->Report(Loc, diag::err_lexing_string);
1440}
1441
Chris Lattnerddb71912009-02-18 19:21:10 +00001442/// getOffsetOfStringByte - This function returns the offset of the
1443/// specified byte of the string data represented by Token. This handles
1444/// advancing over escape sequences in the string.
1445unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattnerbde1b812010-11-17 06:46:14 +00001446 unsigned ByteNo) const {
Chris Lattnerddb71912009-02-18 19:21:10 +00001447 // Get the spelling of the token.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001448 SmallString<32> SpellingBuffer;
Alexis Hunt3b791862010-08-30 17:47:05 +00001449 SpellingBuffer.resize(Tok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001450
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001451 bool StringInvalid = false;
Chris Lattnerddb71912009-02-18 19:21:10 +00001452 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattner39720112010-11-17 07:26:20 +00001453 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1454 &StringInvalid);
Chris Lattner7a02bfd2010-11-17 06:26:08 +00001455 if (StringInvalid)
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001456 return 0;
Chris Lattnerddb71912009-02-18 19:21:10 +00001457
Chris Lattnerddb71912009-02-18 19:21:10 +00001458 const char *SpellingStart = SpellingPtr;
1459 const char *SpellingEnd = SpellingPtr+TokLen;
1460
Richard Smith4060f772012-06-13 05:37:23 +00001461 // Handle UTF-8 strings just like narrow strings.
1462 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1463 SpellingPtr += 2;
1464
1465 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1466 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1467
1468 // For raw string literals, this is easy.
1469 if (SpellingPtr[0] == 'R') {
1470 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1471 // Skip 'R"'.
1472 SpellingPtr += 2;
1473 while (*SpellingPtr != '(') {
1474 ++SpellingPtr;
1475 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1476 }
1477 // Skip '('.
1478 ++SpellingPtr;
1479 return SpellingPtr - SpellingStart + ByteNo;
1480 }
1481
1482 // Skip over the leading quote
Chris Lattnerddb71912009-02-18 19:21:10 +00001483 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1484 ++SpellingPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001485
Chris Lattnerddb71912009-02-18 19:21:10 +00001486 // Skip over bytes until we find the offset we're looking for.
1487 while (ByteNo) {
1488 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump11289f42009-09-09 15:08:12 +00001489
Chris Lattnerddb71912009-02-18 19:21:10 +00001490 // Step over non-escapes simply.
1491 if (*SpellingPtr != '\\') {
1492 ++SpellingPtr;
1493 --ByteNo;
1494 continue;
1495 }
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattnerddb71912009-02-18 19:21:10 +00001497 // Otherwise, this is an escape character. Advance over it.
1498 bool HadError = false;
Richard Smith4060f772012-06-13 05:37:23 +00001499 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1500 const char *EscapePtr = SpellingPtr;
1501 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1502 1, Features, HadError);
1503 if (Len > ByteNo) {
1504 // ByteNo is somewhere within the escape sequence.
1505 SpellingPtr = EscapePtr;
1506 break;
1507 }
1508 ByteNo -= Len;
1509 } else {
Richard Smith639b8d02012-09-08 07:16:20 +00001510 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smith4060f772012-06-13 05:37:23 +00001511 FullSourceLoc(Tok.getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001512 CharByteWidth*8, Diags, Features);
Richard Smith4060f772012-06-13 05:37:23 +00001513 --ByteNo;
1514 }
Chris Lattnerddb71912009-02-18 19:21:10 +00001515 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattnerddb71912009-02-18 19:21:10 +00001516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Chris Lattnerddb71912009-02-18 19:21:10 +00001518 return SpellingPtr-SpellingStart;
1519}