blob: 6417d0f0f5f27ce0e5b8480fd79689ba7461f7e0 [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"
Jordan Rosea7d03842013-02-08 22:30:41 +000016#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Basic/TargetInfo.h"
18#include "clang/Lex/LexDiagnostic.h"
19#include "clang/Lex/Preprocessor.h"
Steve Naroff4f88b312007-03-13 22:37:02 +000020#include "llvm/ADT/StringExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000021#include "llvm/Support/ConvertUTF.h"
David Blaikie76bd3c82011-09-23 05:35:21 +000022#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000023
Steve Naroff09ef4742007-03-09 23:16:33 +000024using namespace clang;
25
Douglas Gregorfb65e592011-07-27 05:40:30 +000026static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
27 switch (kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000028 default: llvm_unreachable("Unknown token type!");
Douglas Gregorfb65e592011-07-27 05:40:30 +000029 case tok::char_constant:
30 case tok::string_literal:
31 case tok::utf8_string_literal:
32 return Target.getCharWidth();
33 case tok::wide_char_constant:
34 case tok::wide_string_literal:
35 return Target.getWCharWidth();
36 case tok::utf16_char_constant:
37 case tok::utf16_string_literal:
38 return Target.getChar16Width();
39 case tok::utf32_char_constant:
40 case tok::utf32_string_literal:
41 return Target.getChar32Width();
42 }
43}
44
Seth Cantrell4cfc8172012-10-28 18:24:46 +000045static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
46 FullSourceLoc TokLoc,
47 const char *TokBegin,
48 const char *TokRangeBegin,
49 const char *TokRangeEnd) {
50 SourceLocation Begin =
51 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
52 TokLoc.getManager(), Features);
53 SourceLocation End =
54 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
55 TokLoc.getManager(), Features);
56 return CharSourceRange::getCharRange(Begin, End);
57}
58
Richard Smith639b8d02012-09-08 07:16:20 +000059/// \brief Produce a diagnostic highlighting some portion of a literal.
60///
61/// Emits the diagnostic \p DiagID, highlighting the range of characters from
62/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
63/// a substring of a spelling buffer for the token beginning at \p TokBegin.
64static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
65 const LangOptions &Features, FullSourceLoc TokLoc,
66 const char *TokBegin, const char *TokRangeBegin,
67 const char *TokRangeEnd, unsigned DiagID) {
68 SourceLocation Begin =
69 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
70 TokLoc.getManager(), Features);
Seth Cantrell4cfc8172012-10-28 18:24:46 +000071 return Diags->Report(Begin, DiagID) <<
72 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
Richard Smith639b8d02012-09-08 07:16:20 +000073}
74
Chris Lattner2f5add62007-04-05 06:57:15 +000075/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
76/// either a character or a string literal.
Richard Smith639b8d02012-09-08 07:16:20 +000077static unsigned ProcessCharEscape(const char *ThisTokBegin,
78 const char *&ThisTokBuf,
Chris Lattner2f5add62007-04-05 06:57:15 +000079 const char *ThisTokEnd, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +000080 FullSourceLoc Loc, unsigned CharWidth,
Richard Smith639b8d02012-09-08 07:16:20 +000081 DiagnosticsEngine *Diags,
82 const LangOptions &Features) {
83 const char *EscapeBegin = ThisTokBuf;
84
Chris Lattner2f5add62007-04-05 06:57:15 +000085 // Skip the '\' char.
86 ++ThisTokBuf;
87
88 // We know that this character can't be off the end of the buffer, because
89 // that would have been \", which would not have been the end of string.
90 unsigned ResultChar = *ThisTokBuf++;
91 switch (ResultChar) {
92 // These map to themselves.
93 case '\\': case '\'': case '"': case '?': break;
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner2f5add62007-04-05 06:57:15 +000095 // These have fixed mappings.
96 case 'a':
97 // TODO: K&R: the meaning of '\\a' is different in traditional C
98 ResultChar = 7;
99 break;
100 case 'b':
101 ResultChar = 8;
102 break;
103 case 'e':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000104 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000105 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
106 diag::ext_nonstandard_escape) << "e";
Chris Lattner2f5add62007-04-05 06:57:15 +0000107 ResultChar = 27;
108 break;
Eli Friedman28a00aa2009-06-10 01:32:39 +0000109 case 'E':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000110 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000111 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
112 diag::ext_nonstandard_escape) << "E";
Eli Friedman28a00aa2009-06-10 01:32:39 +0000113 ResultChar = 27;
114 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000115 case 'f':
116 ResultChar = 12;
117 break;
118 case 'n':
119 ResultChar = 10;
120 break;
121 case 'r':
122 ResultChar = 13;
123 break;
124 case 't':
125 ResultChar = 9;
126 break;
127 case 'v':
128 ResultChar = 11;
129 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000130 case 'x': { // Hex escape.
131 ResultChar = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000132 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000133 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000134 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000135 diag::err_hex_escape_no_digits) << "x";
Chris Lattner2f5add62007-04-05 06:57:15 +0000136 HadError = 1;
Chris Lattner2f5add62007-04-05 06:57:15 +0000137 break;
138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattner812eda82007-05-20 05:17:04 +0000140 // Hex escapes are a maximal series of hex digits.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000141 bool Overflow = false;
142 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000143 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Chris Lattnerc10adde2007-05-20 05:00:58 +0000144 if (CharVal == -1) break;
Chris Lattner59f09b62008-09-30 20:45:40 +0000145 // About to shift out a digit?
146 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000147 ResultChar <<= 4;
148 ResultChar |= CharVal;
149 }
150
151 // See if any bits will be truncated when evaluated as a character.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000152 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
153 Overflow = true;
154 ResultChar &= ~0U >> (32-CharWidth);
155 }
Mike Stump11289f42009-09-09 15:08:12 +0000156
Chris Lattnerc10adde2007-05-20 05:00:58 +0000157 // Check for overflow.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000158 if (Overflow && Diags) // Too many digits to fit in
Richard Smith639b8d02012-09-08 07:16:20 +0000159 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Eli Friedman088d39a2013-07-23 00:25:18 +0000160 diag::err_hex_escape_too_large);
Chris Lattner2f5add62007-04-05 06:57:15 +0000161 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000162 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000163 case '0': case '1': case '2': case '3':
Chris Lattner812eda82007-05-20 05:17:04 +0000164 case '4': case '5': case '6': case '7': {
Chris Lattner2f5add62007-04-05 06:57:15 +0000165 // Octal escapes.
Chris Lattner3f4b6e32007-06-09 06:20:47 +0000166 --ThisTokBuf;
Chris Lattner812eda82007-05-20 05:17:04 +0000167 ResultChar = 0;
168
169 // Octal escapes are a series of octal digits with maximum length 3.
170 // "\0123" is a two digit sequence equal to "\012" "3".
171 unsigned NumDigits = 0;
172 do {
173 ResultChar <<= 3;
174 ResultChar |= *ThisTokBuf++ - '0';
175 ++NumDigits;
176 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
177 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner812eda82007-05-20 05:17:04 +0000179 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner812eda82007-05-20 05:17:04 +0000180 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000181 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000182 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Eli Friedman088d39a2013-07-23 00:25:18 +0000183 diag::err_octal_escape_too_large);
Chris Lattner812eda82007-05-20 05:17:04 +0000184 ResultChar &= ~0U >> (32-CharWidth);
185 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000186 break;
Chris Lattner812eda82007-05-20 05:17:04 +0000187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner2f5add62007-04-05 06:57:15 +0000189 // Otherwise, these are not valid escapes.
190 case '(': case '{': case '[': case '%':
191 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000192 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000193 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
194 diag::ext_nonstandard_escape)
195 << std::string(1, ResultChar);
Eli Friedman5d72d412009-04-28 00:51:18 +0000196 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000197 default:
Craig Topperd2d442c2014-05-17 23:10:59 +0000198 if (!Diags)
Douglas Gregor9af03022010-05-26 05:35:51 +0000199 break;
Richard Smith639b8d02012-09-08 07:16:20 +0000200
Jordan Rosea7d03842013-02-08 22:30:41 +0000201 if (isPrintable(ResultChar))
Richard Smith639b8d02012-09-08 07:16:20 +0000202 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
203 diag::ext_unknown_escape)
204 << std::string(1, ResultChar);
Chris Lattner59acca52008-11-22 07:23:31 +0000205 else
Richard Smith639b8d02012-09-08 07:16:20 +0000206 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
207 diag::ext_unknown_escape)
208 << "x" + llvm::utohexstr(ResultChar);
Chris Lattner2f5add62007-04-05 06:57:15 +0000209 break;
210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner2f5add62007-04-05 06:57:15 +0000212 return ResultChar;
213}
214
Richard Smith8b7258b2014-02-17 21:52:30 +0000215static void appendCodePoint(unsigned Codepoint,
216 llvm::SmallVectorImpl<char> &Str) {
217 char ResultBuf[4];
218 char *ResultPtr = ResultBuf;
219 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
220 (void)Res;
221 assert(Res && "Unexpected conversion failure");
222 Str.append(ResultBuf, ResultPtr);
223}
224
225void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
226 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
227 if (*I != '\\') {
228 Buf.push_back(*I);
229 continue;
230 }
231
232 ++I;
233 assert(*I == 'u' || *I == 'U');
234
235 unsigned NumHexDigits;
236 if (*I == 'u')
237 NumHexDigits = 4;
238 else
239 NumHexDigits = 8;
240
241 assert(I + NumHexDigits <= E);
242
243 uint32_t CodePoint = 0;
244 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
245 unsigned Value = llvm::hexDigitValue(*I);
246 assert(Value != -1U);
247
248 CodePoint <<= 4;
249 CodePoint += Value;
250 }
251
252 appendCodePoint(CodePoint, Buf);
253 --I;
254 }
255}
256
Steve Naroff7b753d22009-03-30 23:46:03 +0000257/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Webera6bde812010-10-09 00:27:47 +0000258/// return the UTF32.
Richard Smith2a70e652012-03-09 22:27:51 +0000259static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
260 const char *ThisTokEnd,
Nico Webera6bde812010-10-09 00:27:47 +0000261 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000262 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000263 const LangOptions &Features,
264 bool in_char_string_literal = false) {
Richard Smith2a70e652012-03-09 22:27:51 +0000265 const char *UcnBegin = ThisTokBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000266
Steve Naroff7b753d22009-03-30 23:46:03 +0000267 // Skip the '\u' char's.
268 ThisTokBuf += 2;
Chris Lattner2f5add62007-04-05 06:57:15 +0000269
Jordan Rosea7d03842013-02-08 22:30:41 +0000270 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattnerbde1b812010-11-17 06:46:14 +0000271 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000272 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000273 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
Nico Webera6bde812010-10-09 00:27:47 +0000274 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000275 }
Nico Webera6bde812010-10-09 00:27:47 +0000276 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000277 unsigned short UcnLenSave = UcnLen;
Nico Webera6bde812010-10-09 00:27:47 +0000278 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000279 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000280 if (CharVal == -1) break;
281 UcnVal <<= 4;
282 UcnVal |= CharVal;
283 }
284 // If we didn't consume the proper number of digits, there is a problem.
Nico Webera6bde812010-10-09 00:27:47 +0000285 if (UcnLenSave) {
Richard Smith639b8d02012-09-08 07:16:20 +0000286 if (Diags)
287 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
288 diag::err_ucn_escape_incomplete);
Nico Webera6bde812010-10-09 00:27:47 +0000289 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000290 }
Richard Smith2a70e652012-03-09 22:27:51 +0000291
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000292 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith2a70e652012-03-09 22:27:51 +0000293 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
294 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattnerbde1b812010-11-17 06:46:14 +0000295 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000296 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
297 diag::err_ucn_escape_invalid);
Nico Webera6bde812010-10-09 00:27:47 +0000298 return false;
299 }
Richard Smith2a70e652012-03-09 22:27:51 +0000300
301 // C++11 allows UCNs that refer to control characters and basic source
302 // characters inside character and string literals
303 if (UcnVal < 0xa0 &&
304 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000305 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
Richard Smith2a70e652012-03-09 22:27:51 +0000306 if (Diags) {
Richard Smith2a70e652012-03-09 22:27:51 +0000307 char BasicSCSChar = UcnVal;
308 if (UcnVal >= 0x20 && UcnVal < 0x7f)
Richard Smith639b8d02012-09-08 07:16:20 +0000309 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
310 IsError ? diag::err_ucn_escape_basic_scs :
311 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
312 << StringRef(&BasicSCSChar, 1);
Richard Smith2a70e652012-03-09 22:27:51 +0000313 else
Richard Smith639b8d02012-09-08 07:16:20 +0000314 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
315 IsError ? diag::err_ucn_control_character :
316 diag::warn_cxx98_compat_literal_ucn_control_character);
Richard Smith2a70e652012-03-09 22:27:51 +0000317 }
318 if (IsError)
319 return false;
320 }
321
Richard Smith639b8d02012-09-08 07:16:20 +0000322 if (!Features.CPlusPlus && !Features.C99 && Diags)
323 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Rosec0cba272013-01-27 20:12:04 +0000324 diag::warn_ucn_not_valid_in_c89_literal);
Richard Smith639b8d02012-09-08 07:16:20 +0000325
Nico Webera6bde812010-10-09 00:27:47 +0000326 return true;
327}
328
Richard Smith4060f772012-06-13 05:37:23 +0000329/// MeasureUCNEscape - Determine the number of bytes within the resulting string
330/// which this UCN will occupy.
331static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
332 const char *ThisTokEnd, unsigned CharByteWidth,
333 const LangOptions &Features, bool &HadError) {
334 // UTF-32: 4 bytes per escape.
335 if (CharByteWidth == 4)
336 return 4;
337
338 uint32_t UcnVal = 0;
339 unsigned short UcnLen = 0;
340 FullSourceLoc Loc;
341
342 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
Craig Topperd2d442c2014-05-17 23:10:59 +0000343 UcnLen, Loc, nullptr, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000344 HadError = true;
345 return 0;
346 }
347
348 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
349 if (CharByteWidth == 2)
350 return UcnVal <= 0xFFFF ? 2 : 4;
351
352 // UTF-8.
353 if (UcnVal < 0x80)
354 return 1;
355 if (UcnVal < 0x800)
356 return 2;
357 if (UcnVal < 0x10000)
358 return 3;
359 return 4;
360}
361
Nico Webera6bde812010-10-09 00:27:47 +0000362/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
363/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
364/// StringLiteralParser. When we decide to implement UCN's for identifiers,
365/// we will likely rework our support for UCN's.
Richard Smith2a70e652012-03-09 22:27:51 +0000366static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
367 const char *ThisTokEnd,
Chris Lattner2be8aa92010-11-17 07:12:42 +0000368 char *&ResultBuf, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000369 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikie9c902b52011-09-25 23:23:43 +0000370 DiagnosticsEngine *Diags,
371 const LangOptions &Features) {
Nico Webera6bde812010-10-09 00:27:47 +0000372 typedef uint32_t UTF32;
373 UTF32 UcnVal = 0;
374 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +0000375 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
376 Loc, Diags, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000377 HadError = true;
Steve Naroff7b753d22009-03-30 23:46:03 +0000378 return;
379 }
Nico Webera6bde812010-10-09 00:27:47 +0000380
Eli Friedmanf9edb002013-09-18 23:23:13 +0000381 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
Douglas Gregorfb65e592011-07-27 05:40:30 +0000382 "only character widths of 1, 2, or 4 bytes supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000383
Douglas Gregorfb65e592011-07-27 05:40:30 +0000384 (void)UcnLen;
385 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000386
Douglas Gregorfb65e592011-07-27 05:40:30 +0000387 if (CharByteWidth == 4) {
Eli Friedmand1370792011-11-02 23:06:23 +0000388 // FIXME: Make the type of the result buffer correct instead of
389 // using reinterpret_cast.
390 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
391 *ResultPtr = UcnVal;
392 ResultBuf += 4;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000393 return;
394 }
395
396 if (CharByteWidth == 2) {
Eli Friedmand1370792011-11-02 23:06:23 +0000397 // FIXME: Make the type of the result buffer correct instead of
398 // using reinterpret_cast.
399 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
400
Richard Smith0948d932012-06-13 05:41:29 +0000401 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmand1370792011-11-02 23:06:23 +0000402 *ResultPtr = UcnVal;
403 ResultBuf += 2;
Nico Weber9762e0a2010-10-06 04:57:26 +0000404 return;
405 }
Nico Weber9762e0a2010-10-06 04:57:26 +0000406
Eli Friedmand1370792011-11-02 23:06:23 +0000407 // Convert to UTF16.
Nico Weber9762e0a2010-10-06 04:57:26 +0000408 UcnVal -= 0x10000;
Eli Friedmand1370792011-11-02 23:06:23 +0000409 *ResultPtr = 0xD800 + (UcnVal >> 10);
410 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
411 ResultBuf += 4;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000412 return;
413 }
Douglas Gregorfb65e592011-07-27 05:40:30 +0000414
415 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
416
Steve Naroff7b753d22009-03-30 23:46:03 +0000417 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
418 // The conversion below was inspired by:
419 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump11289f42009-09-09 15:08:12 +0000420 // First, we determine how many bytes the result will require.
Steve Naroffc94adda2009-04-01 11:09:15 +0000421 typedef uint8_t UTF8;
Steve Naroff7b753d22009-03-30 23:46:03 +0000422
423 unsigned short bytesToWrite = 0;
424 if (UcnVal < (UTF32)0x80)
425 bytesToWrite = 1;
426 else if (UcnVal < (UTF32)0x800)
427 bytesToWrite = 2;
428 else if (UcnVal < (UTF32)0x10000)
429 bytesToWrite = 3;
430 else
431 bytesToWrite = 4;
Mike Stump11289f42009-09-09 15:08:12 +0000432
Steve Naroff7b753d22009-03-30 23:46:03 +0000433 const unsigned byteMask = 0xBF;
434 const unsigned byteMark = 0x80;
Mike Stump11289f42009-09-09 15:08:12 +0000435
Steve Naroff7b753d22009-03-30 23:46:03 +0000436 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Narofff2a880c2009-03-31 10:29:45 +0000437 // into the first byte, depending on how many bytes follow.
Mike Stump11289f42009-09-09 15:08:12 +0000438 static const UTF8 firstByteMark[5] = {
Steve Narofff2a880c2009-03-31 10:29:45 +0000439 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff7b753d22009-03-30 23:46:03 +0000440 };
441 // Finally, we write the bytes into ResultBuf.
442 ResultBuf += bytesToWrite;
443 switch (bytesToWrite) { // note: everything falls through.
Benjamin Kramerf23a6e62012-11-08 19:22:26 +0000444 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
445 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
446 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
447 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000448 }
449 // Update the buffer.
450 ResultBuf += bytesToWrite;
451}
Chris Lattner2f5add62007-04-05 06:57:15 +0000452
453
Steve Naroff09ef4742007-03-09 23:16:33 +0000454/// integer-constant: [C99 6.4.4.1]
455/// decimal-constant integer-suffix
456/// octal-constant integer-suffix
457/// hexadecimal-constant integer-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000458/// binary-literal integer-suffix [GNU, C++1y]
Richard Smith81292452012-03-08 21:59:28 +0000459/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smith39570d002012-03-08 08:45:32 +0000460/// decimal-literal ud-suffix
461/// octal-literal ud-suffix
462/// hexadecimal-literal ud-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000463/// binary-literal ud-suffix [GNU, C++1y]
Mike Stump11289f42009-09-09 15:08:12 +0000464/// decimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000465/// nonzero-digit
466/// decimal-constant digit
Mike Stump11289f42009-09-09 15:08:12 +0000467/// octal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000468/// 0
469/// octal-constant octal-digit
Mike Stump11289f42009-09-09 15:08:12 +0000470/// hexadecimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000471/// hexadecimal-prefix hexadecimal-digit
472/// hexadecimal-constant hexadecimal-digit
473/// hexadecimal-prefix: one of
474/// 0x 0X
Richard Smithf4198b72013-07-23 08:14:48 +0000475/// binary-literal:
476/// 0b binary-digit
477/// 0B binary-digit
478/// binary-literal binary-digit
Steve Naroff09ef4742007-03-09 23:16:33 +0000479/// integer-suffix:
480/// unsigned-suffix [long-suffix]
481/// unsigned-suffix [long-long-suffix]
482/// long-suffix [unsigned-suffix]
483/// long-long-suffix [unsigned-sufix]
484/// nonzero-digit:
485/// 1 2 3 4 5 6 7 8 9
486/// octal-digit:
487/// 0 1 2 3 4 5 6 7
488/// hexadecimal-digit:
489/// 0 1 2 3 4 5 6 7 8 9
490/// a b c d e f
491/// A B C D E F
Richard Smithf4198b72013-07-23 08:14:48 +0000492/// binary-digit:
493/// 0
494/// 1
Steve Naroff09ef4742007-03-09 23:16:33 +0000495/// unsigned-suffix: one of
496/// u U
497/// long-suffix: one of
498/// l L
Mike Stump11289f42009-09-09 15:08:12 +0000499/// long-long-suffix: one of
Steve Naroff09ef4742007-03-09 23:16:33 +0000500/// ll LL
501///
502/// floating-constant: [C99 6.4.4.2]
503/// TODO: add rules...
504///
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000505NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
506 SourceLocation TokLoc,
507 Preprocessor &PP)
508 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
Mike Stump11289f42009-09-09 15:08:12 +0000509
Chris Lattner59f09b62008-09-30 20:45:40 +0000510 // This routine assumes that the range begin/end matches the regex for integer
511 // and FP constants (specifically, the 'pp-number' regex), and assumes that
512 // the byte at "*end" is both valid and not part of the regex. Because of
513 // this, it doesn't have to check for 'overscan' in various places.
Jordan Rosea7d03842013-02-08 22:30:41 +0000514 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
Mike Stump11289f42009-09-09 15:08:12 +0000515
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000516 s = DigitsBegin = ThisTokBegin;
Steve Naroff09ef4742007-03-09 23:16:33 +0000517 saw_exponent = false;
518 saw_period = false;
Richard Smith39570d002012-03-08 08:45:32 +0000519 saw_ud_suffix = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000520 isLong = false;
521 isUnsigned = false;
522 isLongLong = false;
Chris Lattnered045422007-08-26 03:29:23 +0000523 isFloat = false;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000524 isImaginary = false;
David Majnemer65a407c2014-06-21 18:46:07 +0000525 MicrosoftInteger = 0;
Steve Naroff09ef4742007-03-09 23:16:33 +0000526 hadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Steve Naroff09ef4742007-03-09 23:16:33 +0000528 if (*s == '0') { // parse radix
Chris Lattner6016a512008-06-30 06:39:54 +0000529 ParseNumberStartingWithZero(TokLoc);
530 if (hadError)
531 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000532 } else { // the first digit is non-zero
533 radix = 10;
534 s = SkipDigits(s);
535 if (s == ThisTokEnd) {
Chris Lattner328fa5c2007-06-08 17:12:06 +0000536 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000537 } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000538 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000539 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000540 hadError = true;
Chris Lattner328fa5c2007-06-08 17:12:06 +0000541 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000542 } else if (*s == '.') {
Richard Smith1e130482013-09-26 04:19:11 +0000543 checkSeparator(TokLoc, s, CSK_AfterDigits);
Steve Naroff09ef4742007-03-09 23:16:33 +0000544 s++;
545 saw_period = true;
Richard Smith1e130482013-09-26 04:19:11 +0000546 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Steve Naroff09ef4742007-03-09 23:16:33 +0000547 s = SkipDigits(s);
Mike Stump11289f42009-09-09 15:08:12 +0000548 }
Chris Lattnerfb8b8f22008-09-29 23:12:31 +0000549 if ((*s == 'e' || *s == 'E')) { // exponent
Richard Smith1e130482013-09-26 04:19:11 +0000550 checkSeparator(TokLoc, s, CSK_AfterDigits);
Chris Lattner4885b972008-04-20 18:47:55 +0000551 const char *Exponent = s;
Steve Naroff09ef4742007-03-09 23:16:33 +0000552 s++;
553 saw_exponent = true;
554 if (*s == '+' || *s == '-') s++; // sign
Richard Smith1e130482013-09-26 04:19:11 +0000555 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Steve Naroff09ef4742007-03-09 23:16:33 +0000556 const char *first_non_digit = SkipDigits(s);
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000557 if (first_non_digit != s) {
Steve Naroff09ef4742007-03-09 23:16:33 +0000558 s = first_non_digit;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000559 } else {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000560 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000561 diag::err_exponent_has_no_digits);
562 hadError = true;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000563 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000564 }
565 }
566 }
567
568 SuffixBegin = s;
Richard Smith1e130482013-09-26 04:19:11 +0000569 checkSeparator(TokLoc, s, CSK_AfterDigits);
Mike Stump11289f42009-09-09 15:08:12 +0000570
Chris Lattnerf55ab182007-08-26 01:58:14 +0000571 // Parse the suffix. At this point we can classify whether we have an FP or
572 // integer constant.
573 bool isFPConstant = isFloatingLiteral();
Craig Topperd2d442c2014-05-17 23:10:59 +0000574 const char *ImaginarySuffixLoc = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000575
Chris Lattnerf55ab182007-08-26 01:58:14 +0000576 // Loop over all of the characters of the suffix. If we see something bad,
577 // we break out of the loop.
578 for (; s != ThisTokEnd; ++s) {
579 switch (*s) {
580 case 'f': // FP Suffix for "float"
581 case 'F':
582 if (!isFPConstant) break; // Error for integer constant.
Chris Lattnered045422007-08-26 03:29:23 +0000583 if (isFloat || isLong) break; // FF, LF invalid.
584 isFloat = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000585 continue; // Success.
586 case 'u':
587 case 'U':
588 if (isFPConstant) break; // Error for floating constant.
589 if (isUnsigned) break; // Cannot be repeated.
590 isUnsigned = true;
591 continue; // Success.
592 case 'l':
593 case 'L':
594 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattnered045422007-08-26 03:29:23 +0000595 if (isFloat) break; // LF invalid.
Mike Stump11289f42009-09-09 15:08:12 +0000596
Chris Lattnerf55ab182007-08-26 01:58:14 +0000597 // Check for long long. The L's need to be adjacent and the same case.
598 if (s+1 != ThisTokEnd && s[1] == s[0]) {
599 if (isFPConstant) break; // long long invalid for floats.
600 isLongLong = true;
601 ++s; // Eat both of them.
602 } else {
Steve Naroff09ef4742007-03-09 23:16:33 +0000603 isLong = true;
Steve Naroff09ef4742007-03-09 23:16:33 +0000604 }
Chris Lattnerf55ab182007-08-26 01:58:14 +0000605 continue; // Success.
606 case 'i':
Chris Lattner26f6c222010-10-14 00:24:10 +0000607 case 'I':
David Blaikiebbafb8a2012-03-11 07:00:24 +0000608 if (PP.getLangOpts().MicrosoftExt) {
David Majnemer65a407c2014-06-21 18:46:07 +0000609 if (isLong || isLongLong || MicrosoftInteger)
610 break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000611
Steve Naroffa1f41452008-04-04 21:02:54 +0000612 // Allow i8, i16, i32, i64, and i128.
Mike Stumpc99c0222009-10-08 22:55:36 +0000613 if (s + 1 != ThisTokEnd) {
614 switch (s[1]) {
615 case '8':
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000616 if (isFPConstant) break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000617 s += 2; // i8 suffix
David Majnemer65a407c2014-06-21 18:46:07 +0000618 MicrosoftInteger = 8;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000619 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000620 case '1':
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000621 if (isFPConstant) break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000622 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000623 if (s[2] == '6') {
624 s += 3; // i16 suffix
David Majnemer65a407c2014-06-21 18:46:07 +0000625 MicrosoftInteger = 16;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000626 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000627 else if (s[2] == '2') {
628 if (s + 3 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000629 if (s[3] == '8') {
630 s += 4; // i128 suffix
David Majnemer65a407c2014-06-21 18:46:07 +0000631 MicrosoftInteger = 128;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000632 }
Mike Stumpc99c0222009-10-08 22:55:36 +0000633 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000634 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000635 case '3':
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000636 if (isFPConstant) break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000637 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000638 if (s[2] == '2') {
639 s += 3; // i32 suffix
David Majnemer65a407c2014-06-21 18:46:07 +0000640 MicrosoftInteger = 32;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000641 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000642 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000643 case '6':
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000644 if (isFPConstant) break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000645 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000646 if (s[2] == '4') {
647 s += 3; // i64 suffix
David Majnemer65a407c2014-06-21 18:46:07 +0000648 MicrosoftInteger = 64;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000649 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000650 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000651 default:
652 break;
653 }
David Majnemer65a407c2014-06-21 18:46:07 +0000654 if (MicrosoftInteger)
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000655 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000656 }
Steve Naroffa1f41452008-04-04 21:02:54 +0000657 }
Richard Smith2a988622013-09-24 04:06:10 +0000658 // "i", "if", and "il" are user-defined suffixes in C++1y.
659 if (PP.getLangOpts().CPlusPlus1y && *s == 'i')
660 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000661 // fall through.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000662 case 'j':
663 case 'J':
664 if (isImaginary) break; // Cannot be repeated.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000665 isImaginary = true;
Richard Smithf4198b72013-07-23 08:14:48 +0000666 ImaginarySuffixLoc = s;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000667 continue; // Success.
Steve Naroff09ef4742007-03-09 23:16:33 +0000668 }
Richard Smith39570d002012-03-08 08:45:32 +0000669 // If we reached here, there was an error or a ud-suffix.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000670 break;
671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Chris Lattnerf55ab182007-08-26 01:58:14 +0000673 if (s != ThisTokEnd) {
Richard Smith8b7258b2014-02-17 21:52:30 +0000674 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
675 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
676 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
Richard Smithf4198b72013-07-23 08:14:48 +0000677 // Any suffix pieces we might have parsed are actually part of the
678 // ud-suffix.
679 isLong = false;
680 isUnsigned = false;
681 isLongLong = false;
682 isFloat = false;
683 isImaginary = false;
David Majnemer65a407c2014-06-21 18:46:07 +0000684 MicrosoftInteger = 0;
Richard Smithf4198b72013-07-23 08:14:48 +0000685
Richard Smith39570d002012-03-08 08:45:32 +0000686 saw_ud_suffix = true;
687 return;
688 }
689
690 // Report an error if there are any.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000691 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000692 isFPConstant ? diag::err_invalid_suffix_float_constant :
693 diag::err_invalid_suffix_integer_constant)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000694 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattner59acca52008-11-22 07:23:31 +0000695 hadError = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000696 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000697 }
Richard Smithf4198b72013-07-23 08:14:48 +0000698
699 if (isImaginary) {
700 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
701 ImaginarySuffixLoc - ThisTokBegin),
702 diag::ext_imaginary_constant);
703 }
704}
705
706/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
707/// suffixes as ud-suffixes, because the diagnostic experience is better if we
708/// treat it as an invalid suffix.
709bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
710 StringRef Suffix) {
711 if (!LangOpts.CPlusPlus11 || Suffix.empty())
712 return false;
713
714 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
715 if (Suffix[0] == '_')
716 return true;
717
718 // In C++11, there are no library suffixes.
719 if (!LangOpts.CPlusPlus1y)
720 return false;
721
722 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
Richard Smith2a988622013-09-24 04:06:10 +0000723 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
Richard Smithf4198b72013-07-23 08:14:48 +0000724 return llvm::StringSwitch<bool>(Suffix)
725 .Cases("h", "min", "s", true)
726 .Cases("ms", "us", "ns", true)
Richard Smith2a988622013-09-24 04:06:10 +0000727 .Cases("il", "i", "if", true)
Richard Smithf4198b72013-07-23 08:14:48 +0000728 .Default(false);
Steve Naroff09ef4742007-03-09 23:16:33 +0000729}
730
Richard Smithfde94852013-09-26 03:33:06 +0000731void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
Richard Smith1e130482013-09-26 04:19:11 +0000732 const char *Pos,
733 CheckSeparatorKind IsAfterDigits) {
734 if (IsAfterDigits == CSK_AfterDigits) {
Richard Smith99dc0712013-09-26 05:57:03 +0000735 if (Pos == ThisTokBegin)
736 return;
Richard Smithfde94852013-09-26 03:33:06 +0000737 --Pos;
Richard Smith99dc0712013-09-26 05:57:03 +0000738 } else if (Pos == ThisTokEnd)
739 return;
Richard Smithfde94852013-09-26 03:33:06 +0000740
741 if (isDigitSeparator(*Pos))
742 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
743 diag::err_digit_separator_not_between_digits)
744 << IsAfterDigits;
745}
746
Chris Lattner6016a512008-06-30 06:39:54 +0000747/// ParseNumberStartingWithZero - This method is called when the first character
748/// of the number is found to be a zero. This means it is either an octal
749/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump11289f42009-09-09 15:08:12 +0000750/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner6016a512008-06-30 06:39:54 +0000751/// radix etc.
752void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
753 assert(s[0] == '0' && "Invalid method call");
754 s++;
Mike Stump11289f42009-09-09 15:08:12 +0000755
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000756 int c1 = s[0];
757 int c2 = s[1];
758
Chris Lattner6016a512008-06-30 06:39:54 +0000759 // Handle a hex number like 0x1234.
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000760 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(c2) || c2 == '.')) {
Chris Lattner6016a512008-06-30 06:39:54 +0000761 s++;
762 radix = 16;
763 DigitsBegin = s;
764 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000765 bool noSignificand = (s == DigitsBegin);
Chris Lattner6016a512008-06-30 06:39:54 +0000766 if (s == ThisTokEnd) {
767 // Done.
768 } else if (*s == '.') {
769 s++;
770 saw_period = true;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000771 const char *floatDigitsBegin = s;
Richard Smith70ee92f2014-04-22 23:50:25 +0000772 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000773 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000774 noSignificand &= (floatDigitsBegin == s);
Chris Lattner6016a512008-06-30 06:39:54 +0000775 }
Aaron Ballmane1224a52012-02-08 13:36:33 +0000776
777 if (noSignificand) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000778 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Aaron Ballmane1224a52012-02-08 13:36:33 +0000779 diag::err_hexconstant_requires_digits);
780 hadError = true;
781 return;
782 }
783
Chris Lattner6016a512008-06-30 06:39:54 +0000784 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump11289f42009-09-09 15:08:12 +0000785 // binary exponent is required.
Douglas Gregor86325ad2011-08-30 22:40:35 +0000786 if (*s == 'p' || *s == 'P') {
Richard Smith70ee92f2014-04-22 23:50:25 +0000787 checkSeparator(TokLoc, s, CSK_AfterDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000788 const char *Exponent = s;
789 s++;
790 saw_exponent = true;
791 if (*s == '+' || *s == '-') s++; // sign
792 const char *first_non_digit = SkipDigits(s);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000793 if (first_non_digit == s) {
Chris Lattner59acca52008-11-22 07:23:31 +0000794 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
795 diag::err_exponent_has_no_digits);
796 hadError = true;
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000797 return;
Chris Lattner6016a512008-06-30 06:39:54 +0000798 }
Richard Smith70ee92f2014-04-22 23:50:25 +0000799 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000800 s = first_non_digit;
Mike Stump11289f42009-09-09 15:08:12 +0000801
David Blaikiebbafb8a2012-03-11 07:00:24 +0000802 if (!PP.getLangOpts().HexFloats)
Chris Lattner59acca52008-11-22 07:23:31 +0000803 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner6016a512008-06-30 06:39:54 +0000804 } else if (saw_period) {
Chris Lattner59acca52008-11-22 07:23:31 +0000805 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
806 diag::err_hexconstant_requires_exponent);
807 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000808 }
809 return;
810 }
Mike Stump11289f42009-09-09 15:08:12 +0000811
Chris Lattner6016a512008-06-30 06:39:54 +0000812 // Handle simple binary numbers 0b01010
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000813 if ((c1 == 'b' || c1 == 'B') && (c2 == '0' || c2 == '1')) {
Richard Smithc5c27f22013-04-19 20:47:20 +0000814 // 0b101010 is a C++1y / GCC extension.
815 PP.Diag(TokLoc,
816 PP.getLangOpts().CPlusPlus1y
817 ? diag::warn_cxx11_compat_binary_literal
818 : PP.getLangOpts().CPlusPlus
819 ? diag::ext_binary_literal_cxx1y
820 : diag::ext_binary_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000821 ++s;
822 radix = 2;
823 DigitsBegin = s;
824 s = SkipBinaryDigits(s);
825 if (s == ThisTokEnd) {
826 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000827 } else if (isHexDigit(*s)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000828 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000829 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000830 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000831 }
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000832 // Other suffixes will be diagnosed by the caller.
Chris Lattner6016a512008-06-30 06:39:54 +0000833 return;
834 }
Mike Stump11289f42009-09-09 15:08:12 +0000835
Chris Lattner6016a512008-06-30 06:39:54 +0000836 // For now, the radix is set to 8. If we discover that we have a
837 // floating point constant, the radix will change to 10. Octal floating
Mike Stump11289f42009-09-09 15:08:12 +0000838 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner6016a512008-06-30 06:39:54 +0000839 radix = 8;
840 DigitsBegin = s;
841 s = SkipOctalDigits(s);
842 if (s == ThisTokEnd)
843 return; // Done, simple octal number like 01234
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000845 // If we have some other non-octal digit that *is* a decimal digit, see if
846 // this is part of a floating point number like 094.123 or 09e1.
Jordan Rosea7d03842013-02-08 22:30:41 +0000847 if (isDigit(*s)) {
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000848 const char *EndDecimal = SkipDigits(s);
849 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
850 s = EndDecimal;
851 radix = 10;
852 }
853 }
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000855 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
856 // the code is using an incorrect base.
Jordan Rosea7d03842013-02-08 22:30:41 +0000857 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattner59acca52008-11-22 07:23:31 +0000858 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000859 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000860 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000861 return;
862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Chris Lattner6016a512008-06-30 06:39:54 +0000864 if (*s == '.') {
865 s++;
866 radix = 10;
867 saw_period = true;
Richard Smith70ee92f2014-04-22 23:50:25 +0000868 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000869 s = SkipDigits(s); // Skip suffix.
Chris Lattner6016a512008-06-30 06:39:54 +0000870 }
871 if (*s == 'e' || *s == 'E') { // exponent
Richard Smith70ee92f2014-04-22 23:50:25 +0000872 checkSeparator(TokLoc, s, CSK_AfterDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000873 const char *Exponent = s;
874 s++;
875 radix = 10;
876 saw_exponent = true;
877 if (*s == '+' || *s == '-') s++; // sign
878 const char *first_non_digit = SkipDigits(s);
879 if (first_non_digit != s) {
Richard Smith70ee92f2014-04-22 23:50:25 +0000880 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000881 s = first_non_digit;
882 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000883 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000884 diag::err_exponent_has_no_digits);
885 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000886 return;
887 }
888 }
889}
890
Jordan Rosede584de2012-09-25 22:32:51 +0000891static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000892 switch (Radix) {
893 case 2:
894 return NumDigits <= 64;
895 case 8:
896 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
897 case 10:
898 return NumDigits <= 19; // floor(log10(2^64))
899 case 16:
900 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
901 default:
902 llvm_unreachable("impossible Radix");
903 }
904}
Chris Lattner6016a512008-06-30 06:39:54 +0000905
Chris Lattner5b743d32007-04-04 05:52:58 +0000906/// GetIntegerValue - Convert this numeric literal value to an APInt that
Chris Lattner871b4e12007-04-04 06:36:34 +0000907/// matches Val's input width. If there is an overflow, set Val to the low bits
908/// of the result and return true. Otherwise, return false.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000909bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000910 // Fast path: Compute a conservative bound on the maximum number of
911 // bits per digit in this radix. If we can't possibly overflow a
912 // uint64 based on that bound then do the simple conversion to
913 // integer. This avoids the expensive overflow checking below, and
914 // handles the common cases that matter (small decimal integers and
915 // hex/octal values which don't overflow).
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000916 const unsigned NumDigits = SuffixBegin - DigitsBegin;
Jordan Rosede584de2012-09-25 22:32:51 +0000917 if (alwaysFitsInto64Bits(radix, NumDigits)) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000918 uint64_t N = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000919 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
Richard Smithfde94852013-09-26 03:33:06 +0000920 if (!isDigitSeparator(*Ptr))
921 N = N * radix + llvm::hexDigitValue(*Ptr);
Daniel Dunbarbe947082008-10-16 07:32:01 +0000922
923 // This will truncate the value to Val's input width. Simply check
924 // for overflow by comparing.
925 Val = N;
926 return Val.getZExtValue() != N;
927 }
928
Chris Lattner5b743d32007-04-04 05:52:58 +0000929 Val = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000930 const char *Ptr = DigitsBegin;
Chris Lattner5b743d32007-04-04 05:52:58 +0000931
Chris Lattner23b7eb62007-06-15 23:05:46 +0000932 llvm::APInt RadixVal(Val.getBitWidth(), radix);
933 llvm::APInt CharVal(Val.getBitWidth(), 0);
934 llvm::APInt OldVal = Val;
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner871b4e12007-04-04 06:36:34 +0000936 bool OverflowOccurred = false;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000937 while (Ptr < SuffixBegin) {
Richard Smithfde94852013-09-26 03:33:06 +0000938 if (isDigitSeparator(*Ptr)) {
939 ++Ptr;
940 continue;
941 }
942
Jordan Rose78ed86a2013-01-18 22:33:58 +0000943 unsigned C = llvm::hexDigitValue(*Ptr++);
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattner5b743d32007-04-04 05:52:58 +0000945 // If this letter is out of bound for this radix, reject it.
Chris Lattner531efa42007-04-04 06:49:26 +0000946 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chris Lattner5b743d32007-04-04 05:52:58 +0000948 CharVal = C;
Mike Stump11289f42009-09-09 15:08:12 +0000949
Chris Lattner871b4e12007-04-04 06:36:34 +0000950 // Add the digit to the value in the appropriate radix. If adding in digits
951 // made the value smaller, then this overflowed.
Chris Lattner5b743d32007-04-04 05:52:58 +0000952 OldVal = Val;
Chris Lattner871b4e12007-04-04 06:36:34 +0000953
954 // Multiply by radix, did overflow occur on the multiply?
Chris Lattner5b743d32007-04-04 05:52:58 +0000955 Val *= RadixVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000956 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
957
Chris Lattner871b4e12007-04-04 06:36:34 +0000958 // Add value, did overflow occur on the value?
Daniel Dunbarb1f64422008-10-16 06:39:30 +0000959 // (a + b) ult b <=> overflow
Chris Lattner5b743d32007-04-04 05:52:58 +0000960 Val += CharVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000961 OverflowOccurred |= Val.ult(CharVal);
Chris Lattner5b743d32007-04-04 05:52:58 +0000962 }
Chris Lattner871b4e12007-04-04 06:36:34 +0000963 return OverflowOccurred;
Chris Lattner5b743d32007-04-04 05:52:58 +0000964}
965
John McCall53b93a02009-12-24 09:08:04 +0000966llvm::APFloat::opStatus
967NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenekfbb08bc2007-11-26 23:12:30 +0000968 using llvm::APFloat;
Mike Stump11289f42009-09-09 15:08:12 +0000969
Erick Tryzelaarb9073112009-08-16 23:36:28 +0000970 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
Richard Smithfde94852013-09-26 03:33:06 +0000971
972 llvm::SmallString<16> Buffer;
973 StringRef Str(ThisTokBegin, n);
974 if (Str.find('\'') != StringRef::npos) {
975 Buffer.reserve(n);
976 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
977 &isDigitSeparator);
978 Str = Buffer;
979 }
980
981 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
Steve Naroff97b9e912007-07-09 23:53:58 +0000982}
Chris Lattner5b743d32007-04-04 05:52:58 +0000983
Chris Lattner2f5add62007-04-05 06:57:15 +0000984
James Dennett1cc22032012-06-17 03:34:42 +0000985/// \verbatim
Richard Smithe18f0fa2012-03-05 04:02:15 +0000986/// user-defined-character-literal: [C++11 lex.ext]
987/// character-literal ud-suffix
988/// ud-suffix:
989/// identifier
990/// character-literal: [C++11 lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +0000991/// ' c-char-sequence '
992/// u' c-char-sequence '
993/// U' c-char-sequence '
994/// L' c-char-sequence '
995/// c-char-sequence:
996/// c-char
997/// c-char-sequence c-char
998/// c-char:
999/// any member of the source character set except the single-quote ',
1000/// backslash \, or new-line character
1001/// escape-sequence
1002/// universal-character-name
Richard Smithe18f0fa2012-03-05 04:02:15 +00001003/// escape-sequence:
Craig Topper54edcca2011-08-11 04:06:15 +00001004/// simple-escape-sequence
1005/// octal-escape-sequence
1006/// hexadecimal-escape-sequence
1007/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001008/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001009/// octal-escape-sequence:
1010/// \ octal-digit
1011/// \ octal-digit octal-digit
1012/// \ octal-digit octal-digit octal-digit
1013/// hexadecimal-escape-sequence:
1014/// \x hexadecimal-digit
1015/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smithe18f0fa2012-03-05 04:02:15 +00001016/// universal-character-name: [C++11 lex.charset]
Craig Topper54edcca2011-08-11 04:06:15 +00001017/// \u hex-quad
1018/// \U hex-quad hex-quad
1019/// hex-quad:
1020/// hex-digit hex-digit hex-digit hex-digit
James Dennett1cc22032012-06-17 03:34:42 +00001021/// \endverbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001022///
Chris Lattner2f5add62007-04-05 06:57:15 +00001023CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001024 SourceLocation Loc, Preprocessor &PP,
1025 tok::TokenKind kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001026 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Chris Lattner2f5add62007-04-05 06:57:15 +00001027 HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001028
Douglas Gregorfb65e592011-07-27 05:40:30 +00001029 Kind = kind;
1030
Richard Smith2a70e652012-03-09 22:27:51 +00001031 const char *TokBegin = begin;
1032
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001033 // Skip over wide character determinant.
1034 if (Kind != tok::char_constant) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00001035 ++begin;
1036 }
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chris Lattner2f5add62007-04-05 06:57:15 +00001038 // Skip over the entry quote.
1039 assert(begin[0] == '\'' && "Invalid token lexed");
1040 ++begin;
1041
Richard Smithe18f0fa2012-03-05 04:02:15 +00001042 // Remove an optional ud-suffix.
1043 if (end[-1] != '\'') {
1044 const char *UDSuffixEnd = end;
1045 do {
1046 --end;
1047 } while (end[-1] != '\'');
Richard Smith8b7258b2014-02-17 21:52:30 +00001048 // FIXME: Don't bother with this if !tok.hasUCN().
1049 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
Richard Smith2a70e652012-03-09 22:27:51 +00001050 UDSuffixOffset = end - TokBegin;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001051 }
1052
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001053 // Trim the ending quote.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001054 assert(end != begin && "Invalid token lexed");
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001055 --end;
1056
Mike Stump11289f42009-09-09 15:08:12 +00001057 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattner57540c52011-04-15 05:22:18 +00001058 // up to 64-bits.
Chris Lattner2f5add62007-04-05 06:57:15 +00001059 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner37e05872008-03-05 18:54:05 +00001060 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner2f5add62007-04-05 06:57:15 +00001061 "Assumes char is 8 bits");
Chris Lattner8577f622009-04-28 21:51:46 +00001062 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1063 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1064 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1065 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1066 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001067
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001068 SmallVector<uint32_t, 4> codepoint_buffer;
1069 codepoint_buffer.resize(end - begin);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001070 uint32_t *buffer_begin = &codepoint_buffer.front();
1071 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump11289f42009-09-09 15:08:12 +00001072
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001073 // Unicode escapes representing characters that cannot be correctly
1074 // represented in a single code unit are disallowed in character literals
1075 // by this implementation.
1076 uint32_t largest_character_for_kind;
1077 if (tok::wide_char_constant == Kind) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001078 largest_character_for_kind =
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001079 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001080 } else if (tok::utf16_char_constant == Kind) {
1081 largest_character_for_kind = 0xFFFF;
1082 } else if (tok::utf32_char_constant == Kind) {
1083 largest_character_for_kind = 0x10FFFF;
1084 } else {
1085 largest_character_for_kind = 0x7Fu;
Chris Lattner8577f622009-04-28 21:51:46 +00001086 }
1087
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001088 while (begin != end) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001089 // Is this a span of non-escape characters?
1090 if (begin[0] != '\\') {
1091 char const *start = begin;
1092 do {
1093 ++begin;
1094 } while (begin != end && *begin != '\\');
1095
Eli Friedman94363522012-02-11 05:08:10 +00001096 char const *tmp_in_start = start;
1097 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001098 ConversionResult res =
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001099 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1100 reinterpret_cast<UTF8 const *>(begin),
1101 &buffer_begin, buffer_end, strictConversion);
1102 if (res != conversionOK) {
1103 // If we see bad encoding for unprefixed character literals, warn and
1104 // simply copy the byte values, for compatibility with gcc and
Eli Friedman94363522012-02-11 05:08:10 +00001105 // older versions of clang.
1106 bool NoErrorOnBadEncoding = isAscii();
1107 unsigned Msg = diag::err_bad_character_encoding;
1108 if (NoErrorOnBadEncoding)
1109 Msg = diag::warn_bad_character_encoding;
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001110 PP.Diag(Loc, Msg);
Eli Friedman94363522012-02-11 05:08:10 +00001111 if (NoErrorOnBadEncoding) {
1112 start = tmp_in_start;
1113 buffer_begin = tmp_out_start;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001114 for (; start != begin; ++start, ++buffer_begin)
Eli Friedman94363522012-02-11 05:08:10 +00001115 *buffer_begin = static_cast<uint8_t>(*start);
1116 } else {
1117 HadError = true;
1118 }
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001119 } else {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001120 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
Eli Friedman94363522012-02-11 05:08:10 +00001121 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001122 HadError = true;
1123 PP.Diag(Loc, diag::err_character_too_large);
1124 }
1125 }
1126 }
1127
1128 continue;
1129 }
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001130 // Is this a Universal Character Name escape?
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001131 if (begin[1] == 'u' || begin[1] == 'U') {
1132 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +00001133 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001134 FullSourceLoc(Loc, PP.getSourceManager()),
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001135 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001136 HadError = true;
1137 } else if (*buffer_begin > largest_character_for_kind) {
1138 HadError = true;
Richard Smith639b8d02012-09-08 07:16:20 +00001139 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001140 }
1141
1142 ++buffer_begin;
1143 continue;
1144 }
1145 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1146 uint64_t result =
Richard Smith639b8d02012-09-08 07:16:20 +00001147 ProcessCharEscape(TokBegin, begin, end, HadError,
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001148 FullSourceLoc(Loc,PP.getSourceManager()),
Richard Smith639b8d02012-09-08 07:16:20 +00001149 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001150 *buffer_begin++ = result;
1151 }
1152
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001153 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001154
Chris Lattner8577f622009-04-28 21:51:46 +00001155 if (NumCharsSoFar > 1) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001156 if (isWide())
Douglas Gregorfb65e592011-07-27 05:40:30 +00001157 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001158 else if (isAscii() && NumCharsSoFar == 4)
1159 PP.Diag(Loc, diag::ext_four_char_character_literal);
1160 else if (isAscii())
Chris Lattner8577f622009-04-28 21:51:46 +00001161 PP.Diag(Loc, diag::ext_multichar_character_literal);
1162 else
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001163 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedmand8cec572009-06-01 05:25:02 +00001164 IsMultiChar = true;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001165 } else {
Daniel Dunbara444cc22009-07-29 01:46:05 +00001166 IsMultiChar = false;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001167 }
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001168
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001169 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1170
1171 // Narrow character literals act as though their value is concatenated
1172 // in this implementation, but warn on overflow.
1173 bool multi_char_too_long = false;
1174 if (isAscii() && isMultiChar()) {
1175 LitVal = 0;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001176 for (size_t i = 0; i < NumCharsSoFar; ++i) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001177 // check for enough leading zeros to shift into
1178 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1179 LitVal <<= 8;
1180 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1181 }
1182 } else if (NumCharsSoFar > 0) {
1183 // otherwise just take the last character
1184 LitVal = buffer_begin[-1];
1185 }
1186
1187 if (!HadError && multi_char_too_long) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001188 PP.Diag(Loc, diag::warn_char_constant_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001189 }
1190
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001191 // Transfer the value from APInt to uint64_t
1192 Value = LitVal.getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattner2f5add62007-04-05 06:57:15 +00001194 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1195 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1196 // character constants are not sign extended in the this implementation:
1197 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001198 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001199 PP.getLangOpts().CharIsSigned)
Chris Lattner2f5add62007-04-05 06:57:15 +00001200 Value = (signed char)Value;
1201}
1202
James Dennett99c193b2012-06-19 21:04:25 +00001203/// \verbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001204/// string-literal: [C++0x lex.string]
1205/// encoding-prefix " [s-char-sequence] "
1206/// encoding-prefix R raw-string
1207/// encoding-prefix:
1208/// u8
1209/// u
1210/// U
1211/// L
Steve Naroff4f88b312007-03-13 22:37:02 +00001212/// s-char-sequence:
1213/// s-char
1214/// s-char-sequence s-char
1215/// s-char:
Craig Topper54edcca2011-08-11 04:06:15 +00001216/// any member of the source character set except the double-quote ",
1217/// backslash \, or new-line character
1218/// escape-sequence
Steve Naroff4f88b312007-03-13 22:37:02 +00001219/// universal-character-name
Craig Topper54edcca2011-08-11 04:06:15 +00001220/// raw-string:
1221/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1222/// r-char-sequence:
1223/// r-char
1224/// r-char-sequence r-char
1225/// r-char:
1226/// any member of the source character set, except a right parenthesis )
1227/// followed by the initial d-char-sequence (which may be empty)
1228/// followed by a double quote ".
1229/// d-char-sequence:
1230/// d-char
1231/// d-char-sequence d-char
1232/// d-char:
1233/// any member of the basic source character set except:
1234/// space, the left parenthesis (, the right parenthesis ),
1235/// the backslash \, and the control characters representing horizontal
1236/// tab, vertical tab, form feed, and newline.
1237/// escape-sequence: [C++0x lex.ccon]
1238/// simple-escape-sequence
1239/// octal-escape-sequence
1240/// hexadecimal-escape-sequence
1241/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001242/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001243/// octal-escape-sequence:
1244/// \ octal-digit
1245/// \ octal-digit octal-digit
1246/// \ octal-digit octal-digit octal-digit
1247/// hexadecimal-escape-sequence:
1248/// \x hexadecimal-digit
1249/// hexadecimal-escape-sequence hexadecimal-digit
Steve Naroff4f88b312007-03-13 22:37:02 +00001250/// universal-character-name:
1251/// \u hex-quad
1252/// \U hex-quad hex-quad
1253/// hex-quad:
1254/// hex-digit hex-digit hex-digit hex-digit
James Dennett99c193b2012-06-19 21:04:25 +00001255/// \endverbatim
Chris Lattner2f5add62007-04-05 06:57:15 +00001256///
Steve Naroff4f88b312007-03-13 22:37:02 +00001257StringLiteralParser::
Craig Topper9d5583e2014-06-26 04:58:39 +00001258StringLiteralParser(ArrayRef<Token> StringToks,
Chris Lattner6bab4352010-11-17 07:21:13 +00001259 Preprocessor &PP, bool Complain)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001260 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Craig Topperd2d442c2014-05-17 23:10:59 +00001261 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001262 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1263 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Craig Topper9d5583e2014-06-26 04:58:39 +00001264 init(StringToks);
Chris Lattner6bab4352010-11-17 07:21:13 +00001265}
1266
Craig Topper9d5583e2014-06-26 04:58:39 +00001267void StringLiteralParser::init(ArrayRef<Token> StringToks){
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001268 // The literal token may have come from an invalid source location (e.g. due
1269 // to a PCH error), in which case the token length will be 0.
Craig Topper9d5583e2014-06-26 04:58:39 +00001270 if (StringToks.empty() || StringToks[0].getLength() < 2)
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001271 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001272
Steve Naroff4f88b312007-03-13 22:37:02 +00001273 // Scan all of the string portions, remember the max individual token length,
1274 // computing a bound on the concatenated string length, and see whether any
1275 // piece is a wide-string. If any of the string portions is a wide-string
1276 // literal, the result is a wide-string literal [C99 6.4.5p4].
Craig Topper9d5583e2014-06-26 04:58:39 +00001277 assert(!StringToks.empty() && "expected at least one token");
Alexis Hunt3b791862010-08-30 17:47:05 +00001278 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001279 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001280 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001281 Kind = StringToks[0].getKind();
Alexis Hunt3b791862010-08-30 17:47:05 +00001282
1283 hadError = false;
Chris Lattner2f5add62007-04-05 06:57:15 +00001284
1285 // Implement Translation Phase #6: concatenation of string literals
1286 /// (C99 5.1.1.2p1). The common case is only one string fragment.
Craig Topper9d5583e2014-06-26 04:58:39 +00001287 for (unsigned i = 1; i != StringToks.size(); ++i) {
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001288 if (StringToks[i].getLength() < 2)
1289 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001290
Steve Naroff4f88b312007-03-13 22:37:02 +00001291 // The string could be shorter than this if it needs cleaning, but this is a
1292 // reasonable bound, which is all we need.
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001293 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001294 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump11289f42009-09-09 15:08:12 +00001295
Steve Naroff4f88b312007-03-13 22:37:02 +00001296 // Remember maximum string piece length.
Alexis Hunt3b791862010-08-30 17:47:05 +00001297 if (StringToks[i].getLength() > MaxTokenLength)
1298 MaxTokenLength = StringToks[i].getLength();
Mike Stump11289f42009-09-09 15:08:12 +00001299
Douglas Gregorfb65e592011-07-27 05:40:30 +00001300 // Remember if we see any wide or utf-8/16/32 strings.
1301 // Also check for illegal concatenations.
1302 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1303 if (isAscii()) {
1304 Kind = StringToks[i].getKind();
1305 } else {
1306 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +00001307 Diags->Report(StringToks[i].getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001308 diag::err_unsupported_string_concat);
1309 hadError = true;
1310 }
1311 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001312 }
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001313
Steve Naroff4f88b312007-03-13 22:37:02 +00001314 // Include space for the null terminator.
1315 ++SizeBound;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Steve Naroff4f88b312007-03-13 22:37:02 +00001317 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump11289f42009-09-09 15:08:12 +00001318
Douglas Gregorfb65e592011-07-27 05:40:30 +00001319 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1320 CharByteWidth = getCharWidth(Kind, Target);
1321 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1322 CharByteWidth /= 8;
Mike Stump11289f42009-09-09 15:08:12 +00001323
Steve Naroff4f88b312007-03-13 22:37:02 +00001324 // The output buffer size needs to be large enough to hold wide characters.
1325 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001326 SizeBound *= CharByteWidth;
Mike Stump11289f42009-09-09 15:08:12 +00001327
Steve Naroff4f88b312007-03-13 22:37:02 +00001328 // Size the temporary buffer to hold the result string data.
1329 ResultBuf.resize(SizeBound);
Mike Stump11289f42009-09-09 15:08:12 +00001330
Steve Naroff4f88b312007-03-13 22:37:02 +00001331 // Likewise, but for each string piece.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001332 SmallString<512> TokenBuf;
Steve Naroff4f88b312007-03-13 22:37:02 +00001333 TokenBuf.resize(MaxTokenLength);
Mike Stump11289f42009-09-09 15:08:12 +00001334
Steve Naroff4f88b312007-03-13 22:37:02 +00001335 // Loop over all the strings, getting their spelling, and expanding them to
1336 // wide strings as appropriate.
1337 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump11289f42009-09-09 15:08:12 +00001338
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001339 Pascal = false;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Richard Smithe18f0fa2012-03-05 04:02:15 +00001341 SourceLocation UDSuffixTokLoc;
1342
Craig Topper9d5583e2014-06-26 04:58:39 +00001343 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001344 const char *ThisTokBuf = &TokenBuf[0];
1345 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1346 // that ThisTokBuf points to a buffer that is big enough for the whole token
1347 // and 'spelled' tokens can only shrink.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001348 bool StringInvalid = false;
Chris Lattner6bab4352010-11-17 07:21:13 +00001349 unsigned ThisTokLen =
Chris Lattner39720112010-11-17 07:26:20 +00001350 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1351 &StringInvalid);
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001352 if (StringInvalid)
1353 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001354
Richard Smith2a70e652012-03-09 22:27:51 +00001355 const char *ThisTokBegin = ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001356 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1357
1358 // Remove an optional ud-suffix.
1359 if (ThisTokEnd[-1] != '"') {
1360 const char *UDSuffixEnd = ThisTokEnd;
1361 do {
1362 --ThisTokEnd;
1363 } while (ThisTokEnd[-1] != '"');
1364
1365 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1366
1367 if (UDSuffixBuf.empty()) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001368 if (StringToks[i].hasUCN())
1369 expandUCNs(UDSuffixBuf, UDSuffix);
1370 else
1371 UDSuffixBuf.assign(UDSuffix);
Richard Smith75b67d62012-03-08 01:34:56 +00001372 UDSuffixToken = i;
1373 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001374 UDSuffixTokLoc = StringToks[i].getLocation();
Richard Smith8b7258b2014-02-17 21:52:30 +00001375 } else {
1376 SmallString<32> ExpandedUDSuffix;
1377 if (StringToks[i].hasUCN()) {
1378 expandUCNs(ExpandedUDSuffix, UDSuffix);
1379 UDSuffix = ExpandedUDSuffix;
1380 }
1381
Richard Smithe18f0fa2012-03-05 04:02:15 +00001382 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1383 // result of a concatenation involving at least one user-defined-string-
1384 // literal, all the participating user-defined-string-literals shall
1385 // have the same ud-suffix.
David Blaikiedcb72d72014-03-09 05:18:27 +00001386 if (UDSuffixBuf != UDSuffix) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001387 if (Diags) {
1388 SourceLocation TokLoc = StringToks[i].getLocation();
1389 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1390 << UDSuffixBuf << UDSuffix
1391 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1392 << SourceRange(TokLoc, TokLoc);
1393 }
1394 hadError = true;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001395 }
Richard Smithe18f0fa2012-03-05 04:02:15 +00001396 }
1397 }
1398
1399 // Strip the end quote.
1400 --ThisTokEnd;
1401
Steve Naroff4f88b312007-03-13 22:37:02 +00001402 // TODO: Input character set mapping support.
Mike Stump11289f42009-09-09 15:08:12 +00001403
Craig Topper61147ed2011-08-08 06:10:39 +00001404 // Skip marker for wide or unicode strings.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001405 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Chris Lattnerc10adde2007-05-20 05:00:58 +00001406 ++ThisTokBuf;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001407 // Skip 8 of u8 marker for utf8 strings.
1408 if (ThisTokBuf[0] == '8')
1409 ++ThisTokBuf;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +00001410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
Craig Topper54edcca2011-08-11 04:06:15 +00001412 // Check for raw string
1413 if (ThisTokBuf[0] == 'R') {
1414 ThisTokBuf += 2; // skip R"
Mike Stump11289f42009-09-09 15:08:12 +00001415
Craig Topper54edcca2011-08-11 04:06:15 +00001416 const char *Prefix = ThisTokBuf;
1417 while (ThisTokBuf[0] != '(')
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001418 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001419 ++ThisTokBuf; // skip '('
Mike Stump11289f42009-09-09 15:08:12 +00001420
Richard Smith81292452012-03-08 21:59:28 +00001421 // Remove same number of characters from the end
1422 ThisTokEnd -= ThisTokBuf - Prefix;
1423 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper54edcca2011-08-11 04:06:15 +00001424
1425 // Copy the string over
Richard Smith639b8d02012-09-08 07:16:20 +00001426 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1427 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1428 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001429 } else {
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001430 if (ThisTokBuf[0] != '"') {
1431 // The file may have come from PCH and then changed after loading the
1432 // PCH; Fail gracefully.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001433 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001434 }
Craig Topper54edcca2011-08-11 04:06:15 +00001435 ++ThisTokBuf; // skip "
1436
1437 // Check if this is a pascal string
1438 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1439 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1440
1441 // If the \p sequence is found in the first token, we have a pascal string
1442 // Otherwise, if we already have a pascal string, ignore the first \p
1443 if (i == 0) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001444 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001445 Pascal = true;
1446 } else if (Pascal)
1447 ThisTokBuf += 2;
1448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
Craig Topper54edcca2011-08-11 04:06:15 +00001450 while (ThisTokBuf != ThisTokEnd) {
1451 // Is this a span of non-escape characters?
1452 if (ThisTokBuf[0] != '\\') {
1453 const char *InStart = ThisTokBuf;
1454 do {
1455 ++ThisTokBuf;
1456 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1457
1458 // Copy the character span over.
Richard Smith639b8d02012-09-08 07:16:20 +00001459 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1460 StringRef(InStart, ThisTokBuf - InStart)))
1461 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001462 continue;
Steve Naroff4f88b312007-03-13 22:37:02 +00001463 }
Craig Topper54edcca2011-08-11 04:06:15 +00001464 // Is this a Universal Character Name escape?
1465 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith2a70e652012-03-09 22:27:51 +00001466 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1467 ResultPtr, hadError,
1468 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper54edcca2011-08-11 04:06:15 +00001469 CharByteWidth, Diags, Features);
1470 continue;
1471 }
1472 // Otherwise, this is a non-UCN escape character. Process it.
1473 unsigned ResultChar =
Richard Smith639b8d02012-09-08 07:16:20 +00001474 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper54edcca2011-08-11 04:06:15 +00001475 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001476 CharByteWidth*8, Diags, Features);
Mike Stump11289f42009-09-09 15:08:12 +00001477
Eli Friedmand1370792011-11-02 23:06:23 +00001478 if (CharByteWidth == 4) {
1479 // FIXME: Make the type of the result buffer correct instead of
1480 // using reinterpret_cast.
1481 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001482 *ResultWidePtr = ResultChar;
Eli Friedmand1370792011-11-02 23:06:23 +00001483 ResultPtr += 4;
1484 } else if (CharByteWidth == 2) {
1485 // FIXME: Make the type of the result buffer correct instead of
1486 // using reinterpret_cast.
1487 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001488 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmand1370792011-11-02 23:06:23 +00001489 ResultPtr += 2;
1490 } else {
1491 assert(CharByteWidth == 1 && "Unexpected char width");
1492 *ResultPtr++ = ResultChar & 0xFF;
1493 }
Craig Topper54edcca2011-08-11 04:06:15 +00001494 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001495 }
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattner8a24e582009-01-16 18:51:42 +00001498 if (Pascal) {
Eli Friedman20554702011-11-05 00:41:04 +00001499 if (CharByteWidth == 4) {
1500 // FIXME: Make the type of the result buffer correct instead of
1501 // using reinterpret_cast.
1502 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1503 ResultWidePtr[0] = GetNumStringChars() - 1;
1504 } else if (CharByteWidth == 2) {
1505 // FIXME: Make the type of the result buffer correct instead of
1506 // using reinterpret_cast.
1507 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1508 ResultWidePtr[0] = GetNumStringChars() - 1;
1509 } else {
1510 assert(CharByteWidth == 1 && "Unexpected char width");
1511 ResultBuf[0] = GetNumStringChars() - 1;
1512 }
Chris Lattner8a24e582009-01-16 18:51:42 +00001513
1514 // Verify that pascal strings aren't too large.
Chris Lattner6bab4352010-11-17 07:21:13 +00001515 if (GetStringLength() > 256) {
Richard Smith639b8d02012-09-08 07:16:20 +00001516 if (Diags)
Craig Topper9d5583e2014-06-26 04:58:39 +00001517 Diags->Report(StringToks.front().getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001518 diag::err_pascal_string_too_long)
Craig Topper9d5583e2014-06-26 04:58:39 +00001519 << SourceRange(StringToks.front().getLocation(),
1520 StringToks.back().getLocation());
Douglas Gregorfb65e592011-07-27 05:40:30 +00001521 hadError = true;
Eli Friedman1c3fb222009-04-01 03:17:08 +00001522 return;
1523 }
Chris Lattner6bab4352010-11-17 07:21:13 +00001524 } else if (Diags) {
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001525 // Complain if this string literal has too many characters.
Chris Lattner2be8aa92010-11-17 07:12:42 +00001526 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001527
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001528 if (GetNumStringChars() > MaxChars)
Craig Topper9d5583e2014-06-26 04:58:39 +00001529 Diags->Report(StringToks.front().getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001530 diag::ext_string_too_long)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001531 << GetNumStringChars() << MaxChars
Chris Lattner2be8aa92010-11-17 07:12:42 +00001532 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Craig Topper9d5583e2014-06-26 04:58:39 +00001533 << SourceRange(StringToks.front().getLocation(),
1534 StringToks.back().getLocation());
Chris Lattner8a24e582009-01-16 18:51:42 +00001535 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001536}
Chris Lattnerddb71912009-02-18 19:21:10 +00001537
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001538static const char *resyncUTF8(const char *Err, const char *End) {
1539 if (Err == End)
1540 return End;
1541 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1542 while (++Err != End && (*Err & 0xC0) == 0x80)
1543 ;
1544 return Err;
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001545}
1546
Richard Smith639b8d02012-09-08 07:16:20 +00001547/// \brief This function copies from Fragment, which is a sequence of bytes
1548/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper54edcca2011-08-11 04:06:15 +00001549/// Performs widening for multi-byte characters.
Richard Smith639b8d02012-09-08 07:16:20 +00001550bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1551 const char *TokBegin,
1552 StringRef Fragment) {
1553 const UTF8 *ErrorPtrTmp;
1554 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1555 return false;
Craig Topper54edcca2011-08-11 04:06:15 +00001556
Eli Friedman94363522012-02-11 05:08:10 +00001557 // If we see bad encoding for unprefixed string literals, warn and
1558 // simply copy the byte values, for compatibility with gcc and older
1559 // versions of clang.
1560 bool NoErrorOnBadEncoding = isAscii();
Richard Smith639b8d02012-09-08 07:16:20 +00001561 if (NoErrorOnBadEncoding) {
1562 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1563 ResultPtr += Fragment.size();
1564 }
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001565
Richard Smith639b8d02012-09-08 07:16:20 +00001566 if (Diags) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001567 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1568
1569 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1570 const DiagnosticBuilder &Builder =
1571 Diag(Diags, Features, SourceLoc, TokBegin,
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001572 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001573 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1574 : diag::err_bad_string_encoding);
1575
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001576 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001577 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1578
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001579 // Decode into a dummy buffer.
1580 SmallString<512> Dummy;
1581 Dummy.reserve(Fragment.size() * CharByteWidth);
1582 char *Ptr = Dummy.data();
1583
Alexander Kornienkod3b4e082014-05-22 19:56:11 +00001584 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001585 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001586 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001587 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1588 ErrorPtr, NextStart);
1589 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1590 }
Richard Smith639b8d02012-09-08 07:16:20 +00001591 }
Eli Friedman94363522012-02-11 05:08:10 +00001592 return !NoErrorOnBadEncoding;
1593}
Craig Topper54edcca2011-08-11 04:06:15 +00001594
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001595void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1596 hadError = true;
1597 if (Diags)
1598 Diags->Report(Loc, diag::err_lexing_string);
1599}
1600
Chris Lattnerddb71912009-02-18 19:21:10 +00001601/// getOffsetOfStringByte - This function returns the offset of the
1602/// specified byte of the string data represented by Token. This handles
1603/// advancing over escape sequences in the string.
1604unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattnerbde1b812010-11-17 06:46:14 +00001605 unsigned ByteNo) const {
Chris Lattnerddb71912009-02-18 19:21:10 +00001606 // Get the spelling of the token.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001607 SmallString<32> SpellingBuffer;
Alexis Hunt3b791862010-08-30 17:47:05 +00001608 SpellingBuffer.resize(Tok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001609
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001610 bool StringInvalid = false;
Chris Lattnerddb71912009-02-18 19:21:10 +00001611 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattner39720112010-11-17 07:26:20 +00001612 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1613 &StringInvalid);
Chris Lattner7a02bfd2010-11-17 06:26:08 +00001614 if (StringInvalid)
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001615 return 0;
Chris Lattnerddb71912009-02-18 19:21:10 +00001616
Chris Lattnerddb71912009-02-18 19:21:10 +00001617 const char *SpellingStart = SpellingPtr;
1618 const char *SpellingEnd = SpellingPtr+TokLen;
1619
Richard Smith4060f772012-06-13 05:37:23 +00001620 // Handle UTF-8 strings just like narrow strings.
1621 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1622 SpellingPtr += 2;
1623
1624 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1625 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1626
1627 // For raw string literals, this is easy.
1628 if (SpellingPtr[0] == 'R') {
1629 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1630 // Skip 'R"'.
1631 SpellingPtr += 2;
1632 while (*SpellingPtr != '(') {
1633 ++SpellingPtr;
1634 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1635 }
1636 // Skip '('.
1637 ++SpellingPtr;
1638 return SpellingPtr - SpellingStart + ByteNo;
1639 }
1640
1641 // Skip over the leading quote
Chris Lattnerddb71912009-02-18 19:21:10 +00001642 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1643 ++SpellingPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001644
Chris Lattnerddb71912009-02-18 19:21:10 +00001645 // Skip over bytes until we find the offset we're looking for.
1646 while (ByteNo) {
1647 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump11289f42009-09-09 15:08:12 +00001648
Chris Lattnerddb71912009-02-18 19:21:10 +00001649 // Step over non-escapes simply.
1650 if (*SpellingPtr != '\\') {
1651 ++SpellingPtr;
1652 --ByteNo;
1653 continue;
1654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Chris Lattnerddb71912009-02-18 19:21:10 +00001656 // Otherwise, this is an escape character. Advance over it.
1657 bool HadError = false;
Richard Smith4060f772012-06-13 05:37:23 +00001658 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1659 const char *EscapePtr = SpellingPtr;
1660 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1661 1, Features, HadError);
1662 if (Len > ByteNo) {
1663 // ByteNo is somewhere within the escape sequence.
1664 SpellingPtr = EscapePtr;
1665 break;
1666 }
1667 ByteNo -= Len;
1668 } else {
Richard Smith639b8d02012-09-08 07:16:20 +00001669 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smith4060f772012-06-13 05:37:23 +00001670 FullSourceLoc(Tok.getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001671 CharByteWidth*8, Diags, Features);
Richard Smith4060f772012-06-13 05:37:23 +00001672 --ByteNo;
1673 }
Chris Lattnerddb71912009-02-18 19:21:10 +00001674 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattnerddb71912009-02-18 19:21:10 +00001675 }
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattnerddb71912009-02-18 19:21:10 +00001677 return SpellingPtr-SpellingStart;
1678}