blob: 27c80b93015873168809b26107b342e91310eeb0 [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:
Richard Smith3e3a7052014-11-08 06:08:42 +000031 case tok::utf8_char_constant:
Douglas Gregorfb65e592011-07-27 05:40:30 +000032 case tok::utf8_string_literal:
33 return Target.getCharWidth();
34 case tok::wide_char_constant:
35 case tok::wide_string_literal:
36 return Target.getWCharWidth();
37 case tok::utf16_char_constant:
38 case tok::utf16_string_literal:
39 return Target.getChar16Width();
40 case tok::utf32_char_constant:
41 case tok::utf32_string_literal:
42 return Target.getChar32Width();
43 }
44}
45
Seth Cantrell4cfc8172012-10-28 18:24:46 +000046static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
47 FullSourceLoc TokLoc,
48 const char *TokBegin,
49 const char *TokRangeBegin,
50 const char *TokRangeEnd) {
51 SourceLocation Begin =
52 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
53 TokLoc.getManager(), Features);
54 SourceLocation End =
55 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
56 TokLoc.getManager(), Features);
57 return CharSourceRange::getCharRange(Begin, End);
58}
59
Richard Smith639b8d02012-09-08 07:16:20 +000060/// \brief Produce a diagnostic highlighting some portion of a literal.
61///
62/// Emits the diagnostic \p DiagID, highlighting the range of characters from
63/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
64/// a substring of a spelling buffer for the token beginning at \p TokBegin.
65static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
66 const LangOptions &Features, FullSourceLoc TokLoc,
67 const char *TokBegin, const char *TokRangeBegin,
68 const char *TokRangeEnd, unsigned DiagID) {
69 SourceLocation Begin =
70 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
71 TokLoc.getManager(), Features);
Seth Cantrell4cfc8172012-10-28 18:24:46 +000072 return Diags->Report(Begin, DiagID) <<
73 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
Richard Smith639b8d02012-09-08 07:16:20 +000074}
75
Chris Lattner2f5add62007-04-05 06:57:15 +000076/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
77/// either a character or a string literal.
Richard Smith639b8d02012-09-08 07:16:20 +000078static unsigned ProcessCharEscape(const char *ThisTokBegin,
79 const char *&ThisTokBuf,
Chris Lattner2f5add62007-04-05 06:57:15 +000080 const char *ThisTokEnd, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +000081 FullSourceLoc Loc, unsigned CharWidth,
Richard Smith639b8d02012-09-08 07:16:20 +000082 DiagnosticsEngine *Diags,
83 const LangOptions &Features) {
84 const char *EscapeBegin = ThisTokBuf;
85
Chris Lattner2f5add62007-04-05 06:57:15 +000086 // Skip the '\' char.
87 ++ThisTokBuf;
88
89 // We know that this character can't be off the end of the buffer, because
90 // that would have been \", which would not have been the end of string.
91 unsigned ResultChar = *ThisTokBuf++;
92 switch (ResultChar) {
93 // These map to themselves.
94 case '\\': case '\'': case '"': case '?': break;
Mike Stump11289f42009-09-09 15:08:12 +000095
Chris Lattner2f5add62007-04-05 06:57:15 +000096 // These have fixed mappings.
97 case 'a':
98 // TODO: K&R: the meaning of '\\a' is different in traditional C
99 ResultChar = 7;
100 break;
101 case 'b':
102 ResultChar = 8;
103 break;
104 case 'e':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000105 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000106 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
107 diag::ext_nonstandard_escape) << "e";
Chris Lattner2f5add62007-04-05 06:57:15 +0000108 ResultChar = 27;
109 break;
Eli Friedman28a00aa2009-06-10 01:32:39 +0000110 case 'E':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000111 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000112 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
113 diag::ext_nonstandard_escape) << "E";
Eli Friedman28a00aa2009-06-10 01:32:39 +0000114 ResultChar = 27;
115 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000116 case 'f':
117 ResultChar = 12;
118 break;
119 case 'n':
120 ResultChar = 10;
121 break;
122 case 'r':
123 ResultChar = 13;
124 break;
125 case 't':
126 ResultChar = 9;
127 break;
128 case 'v':
129 ResultChar = 11;
130 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000131 case 'x': { // Hex escape.
132 ResultChar = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000133 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000134 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000135 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000136 diag::err_hex_escape_no_digits) << "x";
Chris Lattner2f5add62007-04-05 06:57:15 +0000137 HadError = 1;
Chris Lattner2f5add62007-04-05 06:57:15 +0000138 break;
139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Chris Lattner812eda82007-05-20 05:17:04 +0000141 // Hex escapes are a maximal series of hex digits.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000142 bool Overflow = false;
143 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000144 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Chris Lattnerc10adde2007-05-20 05:00:58 +0000145 if (CharVal == -1) break;
Chris Lattner59f09b62008-09-30 20:45:40 +0000146 // About to shift out a digit?
David Blaikie96cedb52015-03-23 19:54:44 +0000147 if (ResultChar & 0xF0000000)
148 Overflow = true;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000149 ResultChar <<= 4;
150 ResultChar |= CharVal;
151 }
152
153 // See if any bits will be truncated when evaluated as a character.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000154 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
155 Overflow = true;
156 ResultChar &= ~0U >> (32-CharWidth);
157 }
Mike Stump11289f42009-09-09 15:08:12 +0000158
Chris Lattnerc10adde2007-05-20 05:00:58 +0000159 // Check for overflow.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000160 if (Overflow && Diags) // Too many digits to fit in
Richard Smith639b8d02012-09-08 07:16:20 +0000161 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Craig Topper7f5ff212015-11-14 02:09:55 +0000162 diag::err_escape_too_large) << 0;
Chris Lattner2f5add62007-04-05 06:57:15 +0000163 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000164 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000165 case '0': case '1': case '2': case '3':
Chris Lattner812eda82007-05-20 05:17:04 +0000166 case '4': case '5': case '6': case '7': {
Chris Lattner2f5add62007-04-05 06:57:15 +0000167 // Octal escapes.
Chris Lattner3f4b6e32007-06-09 06:20:47 +0000168 --ThisTokBuf;
Chris Lattner812eda82007-05-20 05:17:04 +0000169 ResultChar = 0;
170
171 // Octal escapes are a series of octal digits with maximum length 3.
172 // "\0123" is a two digit sequence equal to "\012" "3".
173 unsigned NumDigits = 0;
174 do {
175 ResultChar <<= 3;
176 ResultChar |= *ThisTokBuf++ - '0';
177 ++NumDigits;
178 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
179 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner812eda82007-05-20 05:17:04 +0000181 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner812eda82007-05-20 05:17:04 +0000182 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000183 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000184 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Craig Topper7f5ff212015-11-14 02:09:55 +0000185 diag::err_escape_too_large) << 1;
Chris Lattner812eda82007-05-20 05:17:04 +0000186 ResultChar &= ~0U >> (32-CharWidth);
187 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000188 break;
Chris Lattner812eda82007-05-20 05:17:04 +0000189 }
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattner2f5add62007-04-05 06:57:15 +0000191 // Otherwise, these are not valid escapes.
192 case '(': case '{': case '[': case '%':
193 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000194 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000195 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
196 diag::ext_nonstandard_escape)
197 << std::string(1, ResultChar);
Eli Friedman5d72d412009-04-28 00:51:18 +0000198 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000199 default:
Craig Topperd2d442c2014-05-17 23:10:59 +0000200 if (!Diags)
Douglas Gregor9af03022010-05-26 05:35:51 +0000201 break;
Richard Smith639b8d02012-09-08 07:16:20 +0000202
Jordan Rosea7d03842013-02-08 22:30:41 +0000203 if (isPrintable(ResultChar))
Richard Smith639b8d02012-09-08 07:16:20 +0000204 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
205 diag::ext_unknown_escape)
206 << std::string(1, ResultChar);
Chris Lattner59acca52008-11-22 07:23:31 +0000207 else
Richard Smith639b8d02012-09-08 07:16:20 +0000208 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
209 diag::ext_unknown_escape)
210 << "x" + llvm::utohexstr(ResultChar);
Chris Lattner2f5add62007-04-05 06:57:15 +0000211 break;
212 }
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner2f5add62007-04-05 06:57:15 +0000214 return ResultChar;
215}
216
Richard Smith8b7258b2014-02-17 21:52:30 +0000217static void appendCodePoint(unsigned Codepoint,
218 llvm::SmallVectorImpl<char> &Str) {
219 char ResultBuf[4];
220 char *ResultPtr = ResultBuf;
221 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
222 (void)Res;
223 assert(Res && "Unexpected conversion failure");
224 Str.append(ResultBuf, ResultPtr);
225}
226
227void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
228 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
229 if (*I != '\\') {
230 Buf.push_back(*I);
231 continue;
232 }
233
234 ++I;
235 assert(*I == 'u' || *I == 'U');
236
237 unsigned NumHexDigits;
238 if (*I == 'u')
239 NumHexDigits = 4;
240 else
241 NumHexDigits = 8;
242
243 assert(I + NumHexDigits <= E);
244
245 uint32_t CodePoint = 0;
246 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
247 unsigned Value = llvm::hexDigitValue(*I);
248 assert(Value != -1U);
249
250 CodePoint <<= 4;
251 CodePoint += Value;
252 }
253
254 appendCodePoint(CodePoint, Buf);
255 --I;
256 }
257}
258
Steve Naroff7b753d22009-03-30 23:46:03 +0000259/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Webera6bde812010-10-09 00:27:47 +0000260/// return the UTF32.
Richard Smith2a70e652012-03-09 22:27:51 +0000261static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
262 const char *ThisTokEnd,
Nico Webera6bde812010-10-09 00:27:47 +0000263 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000264 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000265 const LangOptions &Features,
266 bool in_char_string_literal = false) {
Richard Smith2a70e652012-03-09 22:27:51 +0000267 const char *UcnBegin = ThisTokBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000268
Steve Naroff7b753d22009-03-30 23:46:03 +0000269 // Skip the '\u' char's.
270 ThisTokBuf += 2;
Chris Lattner2f5add62007-04-05 06:57:15 +0000271
Jordan Rosea7d03842013-02-08 22:30:41 +0000272 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattnerbde1b812010-11-17 06:46:14 +0000273 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000274 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000275 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
Nico Webera6bde812010-10-09 00:27:47 +0000276 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000277 }
Nico Webera6bde812010-10-09 00:27:47 +0000278 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000279 unsigned short UcnLenSave = UcnLen;
Nico Webera6bde812010-10-09 00:27:47 +0000280 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000281 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000282 if (CharVal == -1) break;
283 UcnVal <<= 4;
284 UcnVal |= CharVal;
285 }
286 // If we didn't consume the proper number of digits, there is a problem.
Nico Webera6bde812010-10-09 00:27:47 +0000287 if (UcnLenSave) {
Richard Smith639b8d02012-09-08 07:16:20 +0000288 if (Diags)
289 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
290 diag::err_ucn_escape_incomplete);
Nico Webera6bde812010-10-09 00:27:47 +0000291 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000292 }
Richard Smith2a70e652012-03-09 22:27:51 +0000293
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000294 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith2a70e652012-03-09 22:27:51 +0000295 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
296 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattnerbde1b812010-11-17 06:46:14 +0000297 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000298 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
299 diag::err_ucn_escape_invalid);
Nico Webera6bde812010-10-09 00:27:47 +0000300 return false;
301 }
Richard Smith2a70e652012-03-09 22:27:51 +0000302
303 // C++11 allows UCNs that refer to control characters and basic source
304 // characters inside character and string literals
305 if (UcnVal < 0xa0 &&
306 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000307 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
Richard Smith2a70e652012-03-09 22:27:51 +0000308 if (Diags) {
Richard Smith2a70e652012-03-09 22:27:51 +0000309 char BasicSCSChar = UcnVal;
310 if (UcnVal >= 0x20 && UcnVal < 0x7f)
Richard Smith639b8d02012-09-08 07:16:20 +0000311 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
312 IsError ? diag::err_ucn_escape_basic_scs :
313 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
314 << StringRef(&BasicSCSChar, 1);
Richard Smith2a70e652012-03-09 22:27:51 +0000315 else
Richard Smith639b8d02012-09-08 07:16:20 +0000316 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
317 IsError ? diag::err_ucn_control_character :
318 diag::warn_cxx98_compat_literal_ucn_control_character);
Richard Smith2a70e652012-03-09 22:27:51 +0000319 }
320 if (IsError)
321 return false;
322 }
323
Richard Smith639b8d02012-09-08 07:16:20 +0000324 if (!Features.CPlusPlus && !Features.C99 && Diags)
325 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Rosec0cba272013-01-27 20:12:04 +0000326 diag::warn_ucn_not_valid_in_c89_literal);
Richard Smith639b8d02012-09-08 07:16:20 +0000327
Nico Webera6bde812010-10-09 00:27:47 +0000328 return true;
329}
330
Richard Smith4060f772012-06-13 05:37:23 +0000331/// MeasureUCNEscape - Determine the number of bytes within the resulting string
332/// which this UCN will occupy.
333static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
334 const char *ThisTokEnd, unsigned CharByteWidth,
335 const LangOptions &Features, bool &HadError) {
336 // UTF-32: 4 bytes per escape.
337 if (CharByteWidth == 4)
338 return 4;
339
340 uint32_t UcnVal = 0;
341 unsigned short UcnLen = 0;
342 FullSourceLoc Loc;
343
344 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
Craig Topperd2d442c2014-05-17 23:10:59 +0000345 UcnLen, Loc, nullptr, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000346 HadError = true;
347 return 0;
348 }
349
350 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
351 if (CharByteWidth == 2)
352 return UcnVal <= 0xFFFF ? 2 : 4;
353
354 // UTF-8.
355 if (UcnVal < 0x80)
356 return 1;
357 if (UcnVal < 0x800)
358 return 2;
359 if (UcnVal < 0x10000)
360 return 3;
361 return 4;
362}
363
Nico Webera6bde812010-10-09 00:27:47 +0000364/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
365/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
366/// StringLiteralParser. When we decide to implement UCN's for identifiers,
367/// we will likely rework our support for UCN's.
Richard Smith2a70e652012-03-09 22:27:51 +0000368static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
369 const char *ThisTokEnd,
Chris Lattner2be8aa92010-11-17 07:12:42 +0000370 char *&ResultBuf, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000371 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikie9c902b52011-09-25 23:23:43 +0000372 DiagnosticsEngine *Diags,
373 const LangOptions &Features) {
Nico Webera6bde812010-10-09 00:27:47 +0000374 typedef uint32_t UTF32;
375 UTF32 UcnVal = 0;
376 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +0000377 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
378 Loc, Diags, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000379 HadError = true;
Steve Naroff7b753d22009-03-30 23:46:03 +0000380 return;
381 }
Nico Webera6bde812010-10-09 00:27:47 +0000382
Eli Friedmanf9edb002013-09-18 23:23:13 +0000383 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
Douglas Gregorfb65e592011-07-27 05:40:30 +0000384 "only character widths of 1, 2, or 4 bytes supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000385
Douglas Gregorfb65e592011-07-27 05:40:30 +0000386 (void)UcnLen;
387 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000388
Douglas Gregorfb65e592011-07-27 05:40:30 +0000389 if (CharByteWidth == 4) {
Eli Friedmand1370792011-11-02 23:06:23 +0000390 // FIXME: Make the type of the result buffer correct instead of
391 // using reinterpret_cast.
392 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
393 *ResultPtr = UcnVal;
394 ResultBuf += 4;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000395 return;
396 }
397
398 if (CharByteWidth == 2) {
Eli Friedmand1370792011-11-02 23:06:23 +0000399 // FIXME: Make the type of the result buffer correct instead of
400 // using reinterpret_cast.
401 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
402
Richard Smith0948d932012-06-13 05:41:29 +0000403 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmand1370792011-11-02 23:06:23 +0000404 *ResultPtr = UcnVal;
405 ResultBuf += 2;
Nico Weber9762e0a2010-10-06 04:57:26 +0000406 return;
407 }
Nico Weber9762e0a2010-10-06 04:57:26 +0000408
Eli Friedmand1370792011-11-02 23:06:23 +0000409 // Convert to UTF16.
Nico Weber9762e0a2010-10-06 04:57:26 +0000410 UcnVal -= 0x10000;
Eli Friedmand1370792011-11-02 23:06:23 +0000411 *ResultPtr = 0xD800 + (UcnVal >> 10);
412 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
413 ResultBuf += 4;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000414 return;
415 }
Douglas Gregorfb65e592011-07-27 05:40:30 +0000416
417 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
418
Steve Naroff7b753d22009-03-30 23:46:03 +0000419 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
420 // The conversion below was inspired by:
421 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump11289f42009-09-09 15:08:12 +0000422 // First, we determine how many bytes the result will require.
Steve Naroffc94adda2009-04-01 11:09:15 +0000423 typedef uint8_t UTF8;
Steve Naroff7b753d22009-03-30 23:46:03 +0000424
425 unsigned short bytesToWrite = 0;
426 if (UcnVal < (UTF32)0x80)
427 bytesToWrite = 1;
428 else if (UcnVal < (UTF32)0x800)
429 bytesToWrite = 2;
430 else if (UcnVal < (UTF32)0x10000)
431 bytesToWrite = 3;
432 else
433 bytesToWrite = 4;
Mike Stump11289f42009-09-09 15:08:12 +0000434
Steve Naroff7b753d22009-03-30 23:46:03 +0000435 const unsigned byteMask = 0xBF;
436 const unsigned byteMark = 0x80;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Steve Naroff7b753d22009-03-30 23:46:03 +0000438 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Narofff2a880c2009-03-31 10:29:45 +0000439 // into the first byte, depending on how many bytes follow.
Mike Stump11289f42009-09-09 15:08:12 +0000440 static const UTF8 firstByteMark[5] = {
Steve Narofff2a880c2009-03-31 10:29:45 +0000441 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff7b753d22009-03-30 23:46:03 +0000442 };
443 // Finally, we write the bytes into ResultBuf.
444 ResultBuf += bytesToWrite;
445 switch (bytesToWrite) { // note: everything falls through.
Benjamin Kramerf23a6e62012-11-08 19:22:26 +0000446 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
447 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
448 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
449 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000450 }
451 // Update the buffer.
452 ResultBuf += bytesToWrite;
453}
Chris Lattner2f5add62007-04-05 06:57:15 +0000454
455
Steve Naroff09ef4742007-03-09 23:16:33 +0000456/// integer-constant: [C99 6.4.4.1]
457/// decimal-constant integer-suffix
458/// octal-constant integer-suffix
459/// hexadecimal-constant integer-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000460/// binary-literal integer-suffix [GNU, C++1y]
Richard Smith81292452012-03-08 21:59:28 +0000461/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smith39570d002012-03-08 08:45:32 +0000462/// decimal-literal ud-suffix
463/// octal-literal ud-suffix
464/// hexadecimal-literal ud-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000465/// binary-literal ud-suffix [GNU, C++1y]
Mike Stump11289f42009-09-09 15:08:12 +0000466/// decimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000467/// nonzero-digit
468/// decimal-constant digit
Mike Stump11289f42009-09-09 15:08:12 +0000469/// octal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000470/// 0
471/// octal-constant octal-digit
Mike Stump11289f42009-09-09 15:08:12 +0000472/// hexadecimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000473/// hexadecimal-prefix hexadecimal-digit
474/// hexadecimal-constant hexadecimal-digit
475/// hexadecimal-prefix: one of
476/// 0x 0X
Richard Smithf4198b72013-07-23 08:14:48 +0000477/// binary-literal:
478/// 0b binary-digit
479/// 0B binary-digit
480/// binary-literal binary-digit
Steve Naroff09ef4742007-03-09 23:16:33 +0000481/// integer-suffix:
482/// unsigned-suffix [long-suffix]
483/// unsigned-suffix [long-long-suffix]
484/// long-suffix [unsigned-suffix]
485/// long-long-suffix [unsigned-sufix]
486/// nonzero-digit:
487/// 1 2 3 4 5 6 7 8 9
488/// octal-digit:
489/// 0 1 2 3 4 5 6 7
490/// hexadecimal-digit:
491/// 0 1 2 3 4 5 6 7 8 9
492/// a b c d e f
493/// A B C D E F
Richard Smithf4198b72013-07-23 08:14:48 +0000494/// binary-digit:
495/// 0
496/// 1
Steve Naroff09ef4742007-03-09 23:16:33 +0000497/// unsigned-suffix: one of
498/// u U
499/// long-suffix: one of
500/// l L
Mike Stump11289f42009-09-09 15:08:12 +0000501/// long-long-suffix: one of
Steve Naroff09ef4742007-03-09 23:16:33 +0000502/// ll LL
503///
504/// floating-constant: [C99 6.4.4.2]
505/// TODO: add rules...
506///
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000507NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
508 SourceLocation TokLoc,
509 Preprocessor &PP)
510 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
Mike Stump11289f42009-09-09 15:08:12 +0000511
Chris Lattner59f09b62008-09-30 20:45:40 +0000512 // This routine assumes that the range begin/end matches the regex for integer
513 // and FP constants (specifically, the 'pp-number' regex), and assumes that
514 // the byte at "*end" is both valid and not part of the regex. Because of
515 // this, it doesn't have to check for 'overscan' in various places.
Jordan Rosea7d03842013-02-08 22:30:41 +0000516 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
Mike Stump11289f42009-09-09 15:08:12 +0000517
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000518 s = DigitsBegin = ThisTokBegin;
Steve Naroff09ef4742007-03-09 23:16:33 +0000519 saw_exponent = false;
520 saw_period = false;
Richard Smith39570d002012-03-08 08:45:32 +0000521 saw_ud_suffix = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000522 isLong = false;
523 isUnsigned = false;
524 isLongLong = false;
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +0000525 isHalf = false;
Chris Lattnered045422007-08-26 03:29:23 +0000526 isFloat = false;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000527 isImaginary = false;
David Majnemer65a407c2014-06-21 18:46:07 +0000528 MicrosoftInteger = 0;
Steve Naroff09ef4742007-03-09 23:16:33 +0000529 hadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000530
Steve Naroff09ef4742007-03-09 23:16:33 +0000531 if (*s == '0') { // parse radix
Chris Lattner6016a512008-06-30 06:39:54 +0000532 ParseNumberStartingWithZero(TokLoc);
533 if (hadError)
534 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000535 } else { // the first digit is non-zero
536 radix = 10;
537 s = SkipDigits(s);
538 if (s == ThisTokEnd) {
Chris Lattner328fa5c2007-06-08 17:12:06 +0000539 // Done.
Craig Topper3efc7c02016-01-28 05:22:54 +0000540 } else {
541 ParseDecimalOrOctalCommon(TokLoc);
542 if (hadError)
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000543 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000544 }
545 }
546
547 SuffixBegin = s;
Richard Smith1e130482013-09-26 04:19:11 +0000548 checkSeparator(TokLoc, s, CSK_AfterDigits);
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattnerf55ab182007-08-26 01:58:14 +0000550 // Parse the suffix. At this point we can classify whether we have an FP or
551 // integer constant.
552 bool isFPConstant = isFloatingLiteral();
Craig Topperd2d442c2014-05-17 23:10:59 +0000553 const char *ImaginarySuffixLoc = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerf55ab182007-08-26 01:58:14 +0000555 // Loop over all of the characters of the suffix. If we see something bad,
556 // we break out of the loop.
557 for (; s != ThisTokEnd; ++s) {
558 switch (*s) {
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +0000559 case 'h': // FP Suffix for "half".
560 case 'H':
561 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
562 if (!PP.getLangOpts().Half) break;
563 if (!isFPConstant) break; // Error for integer constant.
564 if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
565 isHalf = true;
566 continue; // Success.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000567 case 'f': // FP Suffix for "float"
568 case 'F':
569 if (!isFPConstant) break; // Error for integer constant.
Nemanja Ivanovicd7d45bf2016-04-15 18:04:13 +0000570 if (isHalf || isFloat || isLong) break; // HF, FF, LF invalid.
Chris Lattnered045422007-08-26 03:29:23 +0000571 isFloat = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000572 continue; // Success.
573 case 'u':
574 case 'U':
575 if (isFPConstant) break; // Error for floating constant.
576 if (isUnsigned) break; // Cannot be repeated.
577 isUnsigned = true;
578 continue; // Success.
579 case 'l':
580 case 'L':
581 if (isLong || isLongLong) break; // Cannot be repeated.
Nemanja Ivanovicd7d45bf2016-04-15 18:04:13 +0000582 if (isHalf || isFloat) break; // LH, LF invalid.
Mike Stump11289f42009-09-09 15:08:12 +0000583
Chris Lattnerf55ab182007-08-26 01:58:14 +0000584 // Check for long long. The L's need to be adjacent and the same case.
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000585 if (s[1] == s[0]) {
586 assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
Chris Lattnerf55ab182007-08-26 01:58:14 +0000587 if (isFPConstant) break; // long long invalid for floats.
588 isLongLong = true;
589 ++s; // Eat both of them.
590 } else {
Steve Naroff09ef4742007-03-09 23:16:33 +0000591 isLong = true;
Steve Naroff09ef4742007-03-09 23:16:33 +0000592 }
Chris Lattnerf55ab182007-08-26 01:58:14 +0000593 continue; // Success.
594 case 'i':
Chris Lattner26f6c222010-10-14 00:24:10 +0000595 case 'I':
David Blaikiebbafb8a2012-03-11 07:00:24 +0000596 if (PP.getLangOpts().MicrosoftExt) {
David Majnemer65a407c2014-06-21 18:46:07 +0000597 if (isLong || isLongLong || MicrosoftInteger)
598 break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000599
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000600 if (!isFPConstant) {
David Majnemer5055dfc2015-07-26 09:02:26 +0000601 // Allow i8, i16, i32, and i64.
Mike Stumpc99c0222009-10-08 22:55:36 +0000602 switch (s[1]) {
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000603 case '8':
604 s += 2; // i8 suffix
605 MicrosoftInteger = 8;
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000606 break;
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000607 case '1':
608 if (s[2] == '6') {
609 s += 3; // i16 suffix
610 MicrosoftInteger = 16;
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000611 }
612 break;
613 case '3':
614 if (s[2] == '2') {
615 s += 3; // i32 suffix
616 MicrosoftInteger = 32;
617 }
618 break;
619 case '6':
620 if (s[2] == '4') {
621 s += 3; // i64 suffix
622 MicrosoftInteger = 64;
623 }
624 break;
625 default:
626 break;
627 }
628 }
629 if (MicrosoftInteger) {
630 assert(s <= ThisTokEnd && "didn't maximally munch?");
631 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000632 }
Steve Naroffa1f41452008-04-04 21:02:54 +0000633 }
Richard Smith2a988622013-09-24 04:06:10 +0000634 // "i", "if", and "il" are user-defined suffixes in C++1y.
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000635 if (*s == 'i' && PP.getLangOpts().CPlusPlus14)
Richard Smith2a988622013-09-24 04:06:10 +0000636 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000637 // fall through.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000638 case 'j':
639 case 'J':
640 if (isImaginary) break; // Cannot be repeated.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000641 isImaginary = true;
Richard Smithf4198b72013-07-23 08:14:48 +0000642 ImaginarySuffixLoc = s;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000643 continue; // Success.
Steve Naroff09ef4742007-03-09 23:16:33 +0000644 }
Richard Smith39570d002012-03-08 08:45:32 +0000645 // If we reached here, there was an error or a ud-suffix.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000646 break;
647 }
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattnerf55ab182007-08-26 01:58:14 +0000649 if (s != ThisTokEnd) {
Richard Smith8b7258b2014-02-17 21:52:30 +0000650 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
651 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
652 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
Richard Smithf4198b72013-07-23 08:14:48 +0000653 // Any suffix pieces we might have parsed are actually part of the
654 // ud-suffix.
655 isLong = false;
656 isUnsigned = false;
657 isLongLong = false;
658 isFloat = false;
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +0000659 isHalf = false;
Richard Smithf4198b72013-07-23 08:14:48 +0000660 isImaginary = false;
David Majnemer65a407c2014-06-21 18:46:07 +0000661 MicrosoftInteger = 0;
Richard Smithf4198b72013-07-23 08:14:48 +0000662
Richard Smith39570d002012-03-08 08:45:32 +0000663 saw_ud_suffix = true;
664 return;
665 }
666
667 // Report an error if there are any.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000668 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Craig Topper71a51ff2015-11-12 07:36:50 +0000669 diag::err_invalid_suffix_constant)
670 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin) << isFPConstant;
Chris Lattner59acca52008-11-22 07:23:31 +0000671 hadError = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000672 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000673 }
Richard Smithf4198b72013-07-23 08:14:48 +0000674
675 if (isImaginary) {
676 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
677 ImaginarySuffixLoc - ThisTokBegin),
678 diag::ext_imaginary_constant);
679 }
680}
681
Craig Topper3efc7c02016-01-28 05:22:54 +0000682/// ParseDecimalOrOctalCommon - This method is called for decimal or octal
683/// numbers. It issues an error for illegal digits, and handles floating point
684/// parsing. If it detects a floating point number, the radix is set to 10.
685void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
686 assert((radix == 8 || radix == 10) && "Unexpected radix");
687
688 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
689 // the code is using an incorrect base.
690 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
691 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
692 diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
693 hadError = true;
694 return;
695 }
696
697 if (*s == '.') {
698 checkSeparator(TokLoc, s, CSK_AfterDigits);
699 s++;
700 radix = 10;
701 saw_period = true;
702 checkSeparator(TokLoc, s, CSK_BeforeDigits);
703 s = SkipDigits(s); // Skip suffix.
704 }
705 if (*s == 'e' || *s == 'E') { // exponent
706 checkSeparator(TokLoc, s, CSK_AfterDigits);
707 const char *Exponent = s;
708 s++;
709 radix = 10;
710 saw_exponent = true;
711 if (*s == '+' || *s == '-') s++; // sign
712 const char *first_non_digit = SkipDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000713 if (containsDigits(s, first_non_digit)) {
Craig Topper3efc7c02016-01-28 05:22:54 +0000714 checkSeparator(TokLoc, s, CSK_BeforeDigits);
715 s = first_non_digit;
716 } else {
717 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
718 diag::err_exponent_has_no_digits);
719 hadError = true;
720 return;
721 }
722 }
723}
724
Richard Smithf4198b72013-07-23 08:14:48 +0000725/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
726/// suffixes as ud-suffixes, because the diagnostic experience is better if we
727/// treat it as an invalid suffix.
728bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
729 StringRef Suffix) {
730 if (!LangOpts.CPlusPlus11 || Suffix.empty())
731 return false;
732
733 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
734 if (Suffix[0] == '_')
735 return true;
736
737 // In C++11, there are no library suffixes.
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000738 if (!LangOpts.CPlusPlus14)
Richard Smithf4198b72013-07-23 08:14:48 +0000739 return false;
740
741 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
Richard Smith2a988622013-09-24 04:06:10 +0000742 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
Richard Smithf4198b72013-07-23 08:14:48 +0000743 return llvm::StringSwitch<bool>(Suffix)
744 .Cases("h", "min", "s", true)
745 .Cases("ms", "us", "ns", true)
Richard Smith2a988622013-09-24 04:06:10 +0000746 .Cases("il", "i", "if", true)
Richard Smithf4198b72013-07-23 08:14:48 +0000747 .Default(false);
Steve Naroff09ef4742007-03-09 23:16:33 +0000748}
749
Richard Smithfde94852013-09-26 03:33:06 +0000750void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
Richard Smith1e130482013-09-26 04:19:11 +0000751 const char *Pos,
752 CheckSeparatorKind IsAfterDigits) {
753 if (IsAfterDigits == CSK_AfterDigits) {
Richard Smith99dc0712013-09-26 05:57:03 +0000754 if (Pos == ThisTokBegin)
755 return;
Richard Smithfde94852013-09-26 03:33:06 +0000756 --Pos;
Richard Smith99dc0712013-09-26 05:57:03 +0000757 } else if (Pos == ThisTokEnd)
758 return;
Richard Smithfde94852013-09-26 03:33:06 +0000759
760 if (isDigitSeparator(*Pos))
761 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
762 diag::err_digit_separator_not_between_digits)
763 << IsAfterDigits;
764}
765
Chris Lattner6016a512008-06-30 06:39:54 +0000766/// ParseNumberStartingWithZero - This method is called when the first character
767/// of the number is found to be a zero. This means it is either an octal
768/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump11289f42009-09-09 15:08:12 +0000769/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner6016a512008-06-30 06:39:54 +0000770/// radix etc.
771void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
772 assert(s[0] == '0' && "Invalid method call");
773 s++;
Mike Stump11289f42009-09-09 15:08:12 +0000774
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000775 int c1 = s[0];
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000776
Chris Lattner6016a512008-06-30 06:39:54 +0000777 // Handle a hex number like 0x1234.
Benjamin Kramer86710282015-03-29 14:11:37 +0000778 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
Chris Lattner6016a512008-06-30 06:39:54 +0000779 s++;
Benjamin Kramer86710282015-03-29 14:11:37 +0000780 assert(s < ThisTokEnd && "didn't maximally munch?");
Chris Lattner6016a512008-06-30 06:39:54 +0000781 radix = 16;
782 DigitsBegin = s;
783 s = SkipHexDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000784 bool HasSignificandDigits = containsDigits(DigitsBegin, s);
Chris Lattner6016a512008-06-30 06:39:54 +0000785 if (s == ThisTokEnd) {
786 // Done.
787 } else if (*s == '.') {
788 s++;
789 saw_period = true;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000790 const char *floatDigitsBegin = s;
Chris Lattner6016a512008-06-30 06:39:54 +0000791 s = SkipHexDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000792 if (containsDigits(floatDigitsBegin, s))
793 HasSignificandDigits = true;
794 if (HasSignificandDigits)
795 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000796 }
Aaron Ballmane1224a52012-02-08 13:36:33 +0000797
Richard Smithb1cba3e2016-02-09 22:34:35 +0000798 if (!HasSignificandDigits) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000799 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Richard Smith560a3572016-03-04 22:32:06 +0000800 diag::err_hex_constant_requires)
801 << PP.getLangOpts().CPlusPlus << 1;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000802 hadError = true;
803 return;
804 }
805
Chris Lattner6016a512008-06-30 06:39:54 +0000806 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump11289f42009-09-09 15:08:12 +0000807 // binary exponent is required.
Douglas Gregor86325ad2011-08-30 22:40:35 +0000808 if (*s == 'p' || *s == 'P') {
Richard Smith70ee92f2014-04-22 23:50:25 +0000809 checkSeparator(TokLoc, s, CSK_AfterDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000810 const char *Exponent = s;
811 s++;
812 saw_exponent = true;
813 if (*s == '+' || *s == '-') s++; // sign
814 const char *first_non_digit = SkipDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000815 if (!containsDigits(s, first_non_digit)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000816 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
817 diag::err_exponent_has_no_digits);
818 hadError = true;
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000819 return;
Chris Lattner6016a512008-06-30 06:39:54 +0000820 }
Richard Smith70ee92f2014-04-22 23:50:25 +0000821 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000822 s = first_non_digit;
Mike Stump11289f42009-09-09 15:08:12 +0000823
David Blaikiebbafb8a2012-03-11 07:00:24 +0000824 if (!PP.getLangOpts().HexFloats)
Richard Smith560a3572016-03-04 22:32:06 +0000825 PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
826 ? diag::ext_hex_literal_invalid
827 : diag::ext_hex_constant_invalid);
828 else if (PP.getLangOpts().CPlusPlus1z)
829 PP.Diag(TokLoc, diag::warn_cxx1z_hex_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000830 } else if (saw_period) {
Richard Smith560a3572016-03-04 22:32:06 +0000831 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
832 diag::err_hex_constant_requires)
833 << PP.getLangOpts().CPlusPlus << 0;
Chris Lattner59acca52008-11-22 07:23:31 +0000834 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000835 }
836 return;
837 }
Mike Stump11289f42009-09-09 15:08:12 +0000838
Chris Lattner6016a512008-06-30 06:39:54 +0000839 // Handle simple binary numbers 0b01010
Benjamin Kramer86710282015-03-29 14:11:37 +0000840 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
Richard Smithc5c27f22013-04-19 20:47:20 +0000841 // 0b101010 is a C++1y / GCC extension.
842 PP.Diag(TokLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000843 PP.getLangOpts().CPlusPlus14
Richard Smithc5c27f22013-04-19 20:47:20 +0000844 ? diag::warn_cxx11_compat_binary_literal
845 : PP.getLangOpts().CPlusPlus
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000846 ? diag::ext_binary_literal_cxx14
Richard Smithc5c27f22013-04-19 20:47:20 +0000847 : diag::ext_binary_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000848 ++s;
Benjamin Kramer86710282015-03-29 14:11:37 +0000849 assert(s < ThisTokEnd && "didn't maximally munch?");
Chris Lattner6016a512008-06-30 06:39:54 +0000850 radix = 2;
851 DigitsBegin = s;
852 s = SkipBinaryDigits(s);
853 if (s == ThisTokEnd) {
854 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000855 } else if (isHexDigit(*s)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000856 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Craig Topper7f5ff212015-11-14 02:09:55 +0000857 diag::err_invalid_digit) << StringRef(s, 1) << 2;
Chris Lattner59acca52008-11-22 07:23:31 +0000858 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000859 }
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000860 // Other suffixes will be diagnosed by the caller.
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 // For now, the radix is set to 8. If we discover that we have a
865 // floating point constant, the radix will change to 10. Octal floating
Mike Stump11289f42009-09-09 15:08:12 +0000866 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner6016a512008-06-30 06:39:54 +0000867 radix = 8;
868 DigitsBegin = s;
869 s = SkipOctalDigits(s);
870 if (s == ThisTokEnd)
871 return; // Done, simple octal number like 01234
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000873 // If we have some other non-octal digit that *is* a decimal digit, see if
874 // this is part of a floating point number like 094.123 or 09e1.
Jordan Rosea7d03842013-02-08 22:30:41 +0000875 if (isDigit(*s)) {
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000876 const char *EndDecimal = SkipDigits(s);
877 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
878 s = EndDecimal;
879 radix = 10;
880 }
881 }
Mike Stump11289f42009-09-09 15:08:12 +0000882
Craig Topper3efc7c02016-01-28 05:22:54 +0000883 ParseDecimalOrOctalCommon(TokLoc);
Chris Lattner6016a512008-06-30 06:39:54 +0000884}
885
Jordan Rosede584de2012-09-25 22:32:51 +0000886static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000887 switch (Radix) {
888 case 2:
889 return NumDigits <= 64;
890 case 8:
891 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
892 case 10:
893 return NumDigits <= 19; // floor(log10(2^64))
894 case 16:
895 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
896 default:
897 llvm_unreachable("impossible Radix");
898 }
899}
Chris Lattner6016a512008-06-30 06:39:54 +0000900
Chris Lattner5b743d32007-04-04 05:52:58 +0000901/// GetIntegerValue - Convert this numeric literal value to an APInt that
Chris Lattner871b4e12007-04-04 06:36:34 +0000902/// matches Val's input width. If there is an overflow, set Val to the low bits
903/// of the result and return true. Otherwise, return false.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000904bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000905 // Fast path: Compute a conservative bound on the maximum number of
906 // bits per digit in this radix. If we can't possibly overflow a
907 // uint64 based on that bound then do the simple conversion to
908 // integer. This avoids the expensive overflow checking below, and
909 // handles the common cases that matter (small decimal integers and
910 // hex/octal values which don't overflow).
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000911 const unsigned NumDigits = SuffixBegin - DigitsBegin;
Jordan Rosede584de2012-09-25 22:32:51 +0000912 if (alwaysFitsInto64Bits(radix, NumDigits)) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000913 uint64_t N = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000914 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
Richard Smithfde94852013-09-26 03:33:06 +0000915 if (!isDigitSeparator(*Ptr))
916 N = N * radix + llvm::hexDigitValue(*Ptr);
Daniel Dunbarbe947082008-10-16 07:32:01 +0000917
918 // This will truncate the value to Val's input width. Simply check
919 // for overflow by comparing.
920 Val = N;
921 return Val.getZExtValue() != N;
922 }
923
Chris Lattner5b743d32007-04-04 05:52:58 +0000924 Val = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000925 const char *Ptr = DigitsBegin;
Chris Lattner5b743d32007-04-04 05:52:58 +0000926
Chris Lattner23b7eb62007-06-15 23:05:46 +0000927 llvm::APInt RadixVal(Val.getBitWidth(), radix);
928 llvm::APInt CharVal(Val.getBitWidth(), 0);
929 llvm::APInt OldVal = Val;
Mike Stump11289f42009-09-09 15:08:12 +0000930
Chris Lattner871b4e12007-04-04 06:36:34 +0000931 bool OverflowOccurred = false;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000932 while (Ptr < SuffixBegin) {
Richard Smithfde94852013-09-26 03:33:06 +0000933 if (isDigitSeparator(*Ptr)) {
934 ++Ptr;
935 continue;
936 }
937
Jordan Rose78ed86a2013-01-18 22:33:58 +0000938 unsigned C = llvm::hexDigitValue(*Ptr++);
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattner5b743d32007-04-04 05:52:58 +0000940 // If this letter is out of bound for this radix, reject it.
Chris Lattner531efa42007-04-04 06:49:26 +0000941 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner5b743d32007-04-04 05:52:58 +0000943 CharVal = C;
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattner871b4e12007-04-04 06:36:34 +0000945 // Add the digit to the value in the appropriate radix. If adding in digits
946 // made the value smaller, then this overflowed.
Chris Lattner5b743d32007-04-04 05:52:58 +0000947 OldVal = Val;
Chris Lattner871b4e12007-04-04 06:36:34 +0000948
949 // Multiply by radix, did overflow occur on the multiply?
Chris Lattner5b743d32007-04-04 05:52:58 +0000950 Val *= RadixVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000951 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
952
Chris Lattner871b4e12007-04-04 06:36:34 +0000953 // Add value, did overflow occur on the value?
Daniel Dunbarb1f64422008-10-16 06:39:30 +0000954 // (a + b) ult b <=> overflow
Chris Lattner5b743d32007-04-04 05:52:58 +0000955 Val += CharVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000956 OverflowOccurred |= Val.ult(CharVal);
Chris Lattner5b743d32007-04-04 05:52:58 +0000957 }
Chris Lattner871b4e12007-04-04 06:36:34 +0000958 return OverflowOccurred;
Chris Lattner5b743d32007-04-04 05:52:58 +0000959}
960
John McCall53b93a02009-12-24 09:08:04 +0000961llvm::APFloat::opStatus
962NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenekfbb08bc2007-11-26 23:12:30 +0000963 using llvm::APFloat;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Erick Tryzelaarb9073112009-08-16 23:36:28 +0000965 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
Richard Smithfde94852013-09-26 03:33:06 +0000966
967 llvm::SmallString<16> Buffer;
968 StringRef Str(ThisTokBegin, n);
969 if (Str.find('\'') != StringRef::npos) {
970 Buffer.reserve(n);
971 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
972 &isDigitSeparator);
973 Str = Buffer;
974 }
975
976 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
Steve Naroff97b9e912007-07-09 23:53:58 +0000977}
Chris Lattner5b743d32007-04-04 05:52:58 +0000978
Chris Lattner2f5add62007-04-05 06:57:15 +0000979
James Dennett1cc22032012-06-17 03:34:42 +0000980/// \verbatim
Richard Smithe18f0fa2012-03-05 04:02:15 +0000981/// user-defined-character-literal: [C++11 lex.ext]
982/// character-literal ud-suffix
983/// ud-suffix:
984/// identifier
985/// character-literal: [C++11 lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +0000986/// ' c-char-sequence '
987/// u' c-char-sequence '
988/// U' c-char-sequence '
989/// L' c-char-sequence '
Aaron Ballman9a17c852016-01-07 20:59:26 +0000990/// u8' c-char-sequence ' [C++1z lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +0000991/// c-char-sequence:
992/// c-char
993/// c-char-sequence c-char
994/// c-char:
995/// any member of the source character set except the single-quote ',
996/// backslash \, or new-line character
997/// escape-sequence
998/// universal-character-name
Richard Smithe18f0fa2012-03-05 04:02:15 +0000999/// escape-sequence:
Craig Topper54edcca2011-08-11 04:06:15 +00001000/// simple-escape-sequence
1001/// octal-escape-sequence
1002/// hexadecimal-escape-sequence
1003/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001004/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001005/// octal-escape-sequence:
1006/// \ octal-digit
1007/// \ octal-digit octal-digit
1008/// \ octal-digit octal-digit octal-digit
1009/// hexadecimal-escape-sequence:
1010/// \x hexadecimal-digit
1011/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smithe18f0fa2012-03-05 04:02:15 +00001012/// universal-character-name: [C++11 lex.charset]
Craig Topper54edcca2011-08-11 04:06:15 +00001013/// \u hex-quad
1014/// \U hex-quad hex-quad
1015/// hex-quad:
1016/// hex-digit hex-digit hex-digit hex-digit
James Dennett1cc22032012-06-17 03:34:42 +00001017/// \endverbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001018///
Chris Lattner2f5add62007-04-05 06:57:15 +00001019CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001020 SourceLocation Loc, Preprocessor &PP,
1021 tok::TokenKind kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001022 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Chris Lattner2f5add62007-04-05 06:57:15 +00001023 HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregorfb65e592011-07-27 05:40:30 +00001025 Kind = kind;
1026
Richard Smith2a70e652012-03-09 22:27:51 +00001027 const char *TokBegin = begin;
1028
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001029 // Skip over wide character determinant.
Richard Smith3e3a7052014-11-08 06:08:42 +00001030 if (Kind != tok::char_constant)
Douglas Gregorfb65e592011-07-27 05:40:30 +00001031 ++begin;
Richard Smith3e3a7052014-11-08 06:08:42 +00001032 if (Kind == tok::utf8_char_constant)
1033 ++begin;
Mike Stump11289f42009-09-09 15:08:12 +00001034
Chris Lattner2f5add62007-04-05 06:57:15 +00001035 // Skip over the entry quote.
1036 assert(begin[0] == '\'' && "Invalid token lexed");
1037 ++begin;
1038
Richard Smithe18f0fa2012-03-05 04:02:15 +00001039 // Remove an optional ud-suffix.
1040 if (end[-1] != '\'') {
1041 const char *UDSuffixEnd = end;
1042 do {
1043 --end;
1044 } while (end[-1] != '\'');
Richard Smith8b7258b2014-02-17 21:52:30 +00001045 // FIXME: Don't bother with this if !tok.hasUCN().
1046 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
Richard Smith2a70e652012-03-09 22:27:51 +00001047 UDSuffixOffset = end - TokBegin;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001048 }
1049
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001050 // Trim the ending quote.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001051 assert(end != begin && "Invalid token lexed");
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001052 --end;
1053
Mike Stump11289f42009-09-09 15:08:12 +00001054 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattner57540c52011-04-15 05:22:18 +00001055 // up to 64-bits.
Chris Lattner2f5add62007-04-05 06:57:15 +00001056 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner37e05872008-03-05 18:54:05 +00001057 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner2f5add62007-04-05 06:57:15 +00001058 "Assumes char is 8 bits");
Chris Lattner8577f622009-04-28 21:51:46 +00001059 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1060 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1061 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1062 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1063 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001064
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001065 SmallVector<uint32_t, 4> codepoint_buffer;
1066 codepoint_buffer.resize(end - begin);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001067 uint32_t *buffer_begin = &codepoint_buffer.front();
1068 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump11289f42009-09-09 15:08:12 +00001069
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001070 // Unicode escapes representing characters that cannot be correctly
1071 // represented in a single code unit are disallowed in character literals
1072 // by this implementation.
1073 uint32_t largest_character_for_kind;
1074 if (tok::wide_char_constant == Kind) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001075 largest_character_for_kind =
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001076 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
Richard Smith3e3a7052014-11-08 06:08:42 +00001077 } else if (tok::utf8_char_constant == Kind) {
1078 largest_character_for_kind = 0x7F;
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001079 } else if (tok::utf16_char_constant == Kind) {
1080 largest_character_for_kind = 0xFFFF;
1081 } else if (tok::utf32_char_constant == Kind) {
1082 largest_character_for_kind = 0x10FFFF;
1083 } else {
1084 largest_character_for_kind = 0x7Fu;
Chris Lattner8577f622009-04-28 21:51:46 +00001085 }
1086
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001087 while (begin != end) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001088 // Is this a span of non-escape characters?
1089 if (begin[0] != '\\') {
1090 char const *start = begin;
1091 do {
1092 ++begin;
1093 } while (begin != end && *begin != '\\');
1094
Eli Friedman94363522012-02-11 05:08:10 +00001095 char const *tmp_in_start = start;
1096 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001097 ConversionResult res =
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001098 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1099 reinterpret_cast<UTF8 const *>(begin),
1100 &buffer_begin, buffer_end, strictConversion);
1101 if (res != conversionOK) {
1102 // If we see bad encoding for unprefixed character literals, warn and
1103 // simply copy the byte values, for compatibility with gcc and
Eli Friedman94363522012-02-11 05:08:10 +00001104 // older versions of clang.
1105 bool NoErrorOnBadEncoding = isAscii();
1106 unsigned Msg = diag::err_bad_character_encoding;
1107 if (NoErrorOnBadEncoding)
1108 Msg = diag::warn_bad_character_encoding;
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001109 PP.Diag(Loc, Msg);
Eli Friedman94363522012-02-11 05:08:10 +00001110 if (NoErrorOnBadEncoding) {
1111 start = tmp_in_start;
1112 buffer_begin = tmp_out_start;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001113 for (; start != begin; ++start, ++buffer_begin)
Eli Friedman94363522012-02-11 05:08:10 +00001114 *buffer_begin = static_cast<uint8_t>(*start);
1115 } else {
1116 HadError = true;
1117 }
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001118 } else {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001119 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
Eli Friedman94363522012-02-11 05:08:10 +00001120 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001121 HadError = true;
1122 PP.Diag(Loc, diag::err_character_too_large);
1123 }
1124 }
1125 }
1126
1127 continue;
1128 }
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001129 // Is this a Universal Character Name escape?
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001130 if (begin[1] == 'u' || begin[1] == 'U') {
1131 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +00001132 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001133 FullSourceLoc(Loc, PP.getSourceManager()),
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001134 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001135 HadError = true;
1136 } else if (*buffer_begin > largest_character_for_kind) {
1137 HadError = true;
Richard Smith639b8d02012-09-08 07:16:20 +00001138 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001139 }
1140
1141 ++buffer_begin;
1142 continue;
1143 }
1144 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1145 uint64_t result =
Richard Smith639b8d02012-09-08 07:16:20 +00001146 ProcessCharEscape(TokBegin, begin, end, HadError,
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001147 FullSourceLoc(Loc,PP.getSourceManager()),
Richard Smith639b8d02012-09-08 07:16:20 +00001148 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001149 *buffer_begin++ = result;
1150 }
1151
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001152 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001153
Chris Lattner8577f622009-04-28 21:51:46 +00001154 if (NumCharsSoFar > 1) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001155 if (isWide())
Douglas Gregorfb65e592011-07-27 05:40:30 +00001156 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001157 else if (isAscii() && NumCharsSoFar == 4)
1158 PP.Diag(Loc, diag::ext_four_char_character_literal);
1159 else if (isAscii())
Chris Lattner8577f622009-04-28 21:51:46 +00001160 PP.Diag(Loc, diag::ext_multichar_character_literal);
1161 else
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001162 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedmand8cec572009-06-01 05:25:02 +00001163 IsMultiChar = true;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001164 } else {
Daniel Dunbara444cc22009-07-29 01:46:05 +00001165 IsMultiChar = false;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001166 }
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001167
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001168 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1169
1170 // Narrow character literals act as though their value is concatenated
1171 // in this implementation, but warn on overflow.
1172 bool multi_char_too_long = false;
1173 if (isAscii() && isMultiChar()) {
1174 LitVal = 0;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001175 for (size_t i = 0; i < NumCharsSoFar; ++i) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001176 // check for enough leading zeros to shift into
1177 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1178 LitVal <<= 8;
1179 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1180 }
1181 } else if (NumCharsSoFar > 0) {
1182 // otherwise just take the last character
1183 LitVal = buffer_begin[-1];
1184 }
1185
1186 if (!HadError && multi_char_too_long) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001187 PP.Diag(Loc, diag::warn_char_constant_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001188 }
1189
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001190 // Transfer the value from APInt to uint64_t
1191 Value = LitVal.getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001192
Chris Lattner2f5add62007-04-05 06:57:15 +00001193 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1194 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1195 // character constants are not sign extended in the this implementation:
1196 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001197 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001198 PP.getLangOpts().CharIsSigned)
Chris Lattner2f5add62007-04-05 06:57:15 +00001199 Value = (signed char)Value;
1200}
1201
James Dennett99c193b2012-06-19 21:04:25 +00001202/// \verbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001203/// string-literal: [C++0x lex.string]
1204/// encoding-prefix " [s-char-sequence] "
1205/// encoding-prefix R raw-string
1206/// encoding-prefix:
1207/// u8
1208/// u
1209/// U
1210/// L
Steve Naroff4f88b312007-03-13 22:37:02 +00001211/// s-char-sequence:
1212/// s-char
1213/// s-char-sequence s-char
1214/// s-char:
Craig Topper54edcca2011-08-11 04:06:15 +00001215/// any member of the source character set except the double-quote ",
1216/// backslash \, or new-line character
1217/// escape-sequence
Steve Naroff4f88b312007-03-13 22:37:02 +00001218/// universal-character-name
Craig Topper54edcca2011-08-11 04:06:15 +00001219/// raw-string:
1220/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1221/// r-char-sequence:
1222/// r-char
1223/// r-char-sequence r-char
1224/// r-char:
1225/// any member of the source character set, except a right parenthesis )
1226/// followed by the initial d-char-sequence (which may be empty)
1227/// followed by a double quote ".
1228/// d-char-sequence:
1229/// d-char
1230/// d-char-sequence d-char
1231/// d-char:
1232/// any member of the basic source character set except:
1233/// space, the left parenthesis (, the right parenthesis ),
1234/// the backslash \, and the control characters representing horizontal
1235/// tab, vertical tab, form feed, and newline.
1236/// escape-sequence: [C++0x lex.ccon]
1237/// simple-escape-sequence
1238/// octal-escape-sequence
1239/// hexadecimal-escape-sequence
1240/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001241/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001242/// octal-escape-sequence:
1243/// \ octal-digit
1244/// \ octal-digit octal-digit
1245/// \ octal-digit octal-digit octal-digit
1246/// hexadecimal-escape-sequence:
1247/// \x hexadecimal-digit
1248/// hexadecimal-escape-sequence hexadecimal-digit
Steve Naroff4f88b312007-03-13 22:37:02 +00001249/// universal-character-name:
1250/// \u hex-quad
1251/// \U hex-quad hex-quad
1252/// hex-quad:
1253/// hex-digit hex-digit hex-digit hex-digit
James Dennett99c193b2012-06-19 21:04:25 +00001254/// \endverbatim
Chris Lattner2f5add62007-04-05 06:57:15 +00001255///
Steve Naroff4f88b312007-03-13 22:37:02 +00001256StringLiteralParser::
Craig Topper9d5583e2014-06-26 04:58:39 +00001257StringLiteralParser(ArrayRef<Token> StringToks,
Chris Lattner6bab4352010-11-17 07:21:13 +00001258 Preprocessor &PP, bool Complain)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001259 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Craig Topperd2d442c2014-05-17 23:10:59 +00001260 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001261 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1262 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Craig Topper9d5583e2014-06-26 04:58:39 +00001263 init(StringToks);
Chris Lattner6bab4352010-11-17 07:21:13 +00001264}
1265
Craig Topper9d5583e2014-06-26 04:58:39 +00001266void StringLiteralParser::init(ArrayRef<Token> StringToks){
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001267 // The literal token may have come from an invalid source location (e.g. due
1268 // to a PCH error), in which case the token length will be 0.
Craig Topper9d5583e2014-06-26 04:58:39 +00001269 if (StringToks.empty() || StringToks[0].getLength() < 2)
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001270 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001271
Steve Naroff4f88b312007-03-13 22:37:02 +00001272 // Scan all of the string portions, remember the max individual token length,
1273 // computing a bound on the concatenated string length, and see whether any
1274 // piece is a wide-string. If any of the string portions is a wide-string
1275 // literal, the result is a wide-string literal [C99 6.4.5p4].
Craig Topper9d5583e2014-06-26 04:58:39 +00001276 assert(!StringToks.empty() && "expected at least one token");
Alexis Hunt3b791862010-08-30 17:47:05 +00001277 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001278 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001279 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001280 Kind = StringToks[0].getKind();
Alexis Hunt3b791862010-08-30 17:47:05 +00001281
1282 hadError = false;
Chris Lattner2f5add62007-04-05 06:57:15 +00001283
1284 // Implement Translation Phase #6: concatenation of string literals
1285 /// (C99 5.1.1.2p1). The common case is only one string fragment.
Craig Topper9d5583e2014-06-26 04:58:39 +00001286 for (unsigned i = 1; i != StringToks.size(); ++i) {
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001287 if (StringToks[i].getLength() < 2)
1288 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001289
Steve Naroff4f88b312007-03-13 22:37:02 +00001290 // The string could be shorter than this if it needs cleaning, but this is a
1291 // reasonable bound, which is all we need.
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001292 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001293 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump11289f42009-09-09 15:08:12 +00001294
Steve Naroff4f88b312007-03-13 22:37:02 +00001295 // Remember maximum string piece length.
Alexis Hunt3b791862010-08-30 17:47:05 +00001296 if (StringToks[i].getLength() > MaxTokenLength)
1297 MaxTokenLength = StringToks[i].getLength();
Mike Stump11289f42009-09-09 15:08:12 +00001298
Douglas Gregorfb65e592011-07-27 05:40:30 +00001299 // Remember if we see any wide or utf-8/16/32 strings.
1300 // Also check for illegal concatenations.
1301 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1302 if (isAscii()) {
1303 Kind = StringToks[i].getKind();
1304 } else {
1305 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +00001306 Diags->Report(StringToks[i].getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001307 diag::err_unsupported_string_concat);
1308 hadError = true;
1309 }
1310 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001311 }
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001312
Steve Naroff4f88b312007-03-13 22:37:02 +00001313 // Include space for the null terminator.
1314 ++SizeBound;
Mike Stump11289f42009-09-09 15:08:12 +00001315
Steve Naroff4f88b312007-03-13 22:37:02 +00001316 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump11289f42009-09-09 15:08:12 +00001317
Douglas Gregorfb65e592011-07-27 05:40:30 +00001318 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1319 CharByteWidth = getCharWidth(Kind, Target);
1320 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1321 CharByteWidth /= 8;
Mike Stump11289f42009-09-09 15:08:12 +00001322
Steve Naroff4f88b312007-03-13 22:37:02 +00001323 // The output buffer size needs to be large enough to hold wide characters.
1324 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001325 SizeBound *= CharByteWidth;
Mike Stump11289f42009-09-09 15:08:12 +00001326
Steve Naroff4f88b312007-03-13 22:37:02 +00001327 // Size the temporary buffer to hold the result string data.
1328 ResultBuf.resize(SizeBound);
Mike Stump11289f42009-09-09 15:08:12 +00001329
Steve Naroff4f88b312007-03-13 22:37:02 +00001330 // Likewise, but for each string piece.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001331 SmallString<512> TokenBuf;
Steve Naroff4f88b312007-03-13 22:37:02 +00001332 TokenBuf.resize(MaxTokenLength);
Mike Stump11289f42009-09-09 15:08:12 +00001333
Steve Naroff4f88b312007-03-13 22:37:02 +00001334 // Loop over all the strings, getting their spelling, and expanding them to
1335 // wide strings as appropriate.
1336 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump11289f42009-09-09 15:08:12 +00001337
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001338 Pascal = false;
Mike Stump11289f42009-09-09 15:08:12 +00001339
Richard Smithe18f0fa2012-03-05 04:02:15 +00001340 SourceLocation UDSuffixTokLoc;
1341
Craig Topper9d5583e2014-06-26 04:58:39 +00001342 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001343 const char *ThisTokBuf = &TokenBuf[0];
1344 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1345 // that ThisTokBuf points to a buffer that is big enough for the whole token
1346 // and 'spelled' tokens can only shrink.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001347 bool StringInvalid = false;
Chris Lattner6bab4352010-11-17 07:21:13 +00001348 unsigned ThisTokLen =
Chris Lattner39720112010-11-17 07:26:20 +00001349 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1350 &StringInvalid);
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001351 if (StringInvalid)
1352 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001353
Richard Smith2a70e652012-03-09 22:27:51 +00001354 const char *ThisTokBegin = ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001355 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1356
1357 // Remove an optional ud-suffix.
1358 if (ThisTokEnd[-1] != '"') {
1359 const char *UDSuffixEnd = ThisTokEnd;
1360 do {
1361 --ThisTokEnd;
1362 } while (ThisTokEnd[-1] != '"');
1363
1364 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1365
1366 if (UDSuffixBuf.empty()) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001367 if (StringToks[i].hasUCN())
1368 expandUCNs(UDSuffixBuf, UDSuffix);
1369 else
1370 UDSuffixBuf.assign(UDSuffix);
Richard Smith75b67d62012-03-08 01:34:56 +00001371 UDSuffixToken = i;
1372 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001373 UDSuffixTokLoc = StringToks[i].getLocation();
Richard Smith8b7258b2014-02-17 21:52:30 +00001374 } else {
1375 SmallString<32> ExpandedUDSuffix;
1376 if (StringToks[i].hasUCN()) {
1377 expandUCNs(ExpandedUDSuffix, UDSuffix);
1378 UDSuffix = ExpandedUDSuffix;
1379 }
1380
Richard Smithe18f0fa2012-03-05 04:02:15 +00001381 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1382 // result of a concatenation involving at least one user-defined-string-
1383 // literal, all the participating user-defined-string-literals shall
1384 // have the same ud-suffix.
David Blaikiedcb72d72014-03-09 05:18:27 +00001385 if (UDSuffixBuf != UDSuffix) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001386 if (Diags) {
1387 SourceLocation TokLoc = StringToks[i].getLocation();
1388 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1389 << UDSuffixBuf << UDSuffix
1390 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1391 << SourceRange(TokLoc, TokLoc);
1392 }
1393 hadError = true;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001394 }
Richard Smithe18f0fa2012-03-05 04:02:15 +00001395 }
1396 }
1397
1398 // Strip the end quote.
1399 --ThisTokEnd;
1400
Steve Naroff4f88b312007-03-13 22:37:02 +00001401 // TODO: Input character set mapping support.
Mike Stump11289f42009-09-09 15:08:12 +00001402
Craig Topper61147ed2011-08-08 06:10:39 +00001403 // Skip marker for wide or unicode strings.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001404 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Chris Lattnerc10adde2007-05-20 05:00:58 +00001405 ++ThisTokBuf;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001406 // Skip 8 of u8 marker for utf8 strings.
1407 if (ThisTokBuf[0] == '8')
1408 ++ThisTokBuf;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +00001409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Craig Topper54edcca2011-08-11 04:06:15 +00001411 // Check for raw string
1412 if (ThisTokBuf[0] == 'R') {
1413 ThisTokBuf += 2; // skip R"
Mike Stump11289f42009-09-09 15:08:12 +00001414
Craig Topper54edcca2011-08-11 04:06:15 +00001415 const char *Prefix = ThisTokBuf;
1416 while (ThisTokBuf[0] != '(')
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001417 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001418 ++ThisTokBuf; // skip '('
Mike Stump11289f42009-09-09 15:08:12 +00001419
Richard Smith81292452012-03-08 21:59:28 +00001420 // Remove same number of characters from the end
1421 ThisTokEnd -= ThisTokBuf - Prefix;
1422 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper54edcca2011-08-11 04:06:15 +00001423
David Majnemer54bbae52015-09-23 16:04:47 +00001424 // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1425 // results in a new-line in the resulting execution string-literal.
1426 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1427 while (!RemainingTokenSpan.empty()) {
1428 // Split the string literal on \r\n boundaries.
1429 size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1430 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1431 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1432
1433 // Copy everything before the \r\n sequence into the string literal.
1434 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1435 hadError = true;
1436
1437 // Point into the \n inside the \r\n sequence and operate on the
1438 // remaining portion of the literal.
1439 RemainingTokenSpan = AfterCRLF.substr(1);
1440 }
Craig Topper54edcca2011-08-11 04:06:15 +00001441 } else {
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001442 if (ThisTokBuf[0] != '"') {
1443 // The file may have come from PCH and then changed after loading the
1444 // PCH; Fail gracefully.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001445 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001446 }
Craig Topper54edcca2011-08-11 04:06:15 +00001447 ++ThisTokBuf; // skip "
1448
1449 // Check if this is a pascal string
1450 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1451 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1452
1453 // If the \p sequence is found in the first token, we have a pascal string
1454 // Otherwise, if we already have a pascal string, ignore the first \p
1455 if (i == 0) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001456 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001457 Pascal = true;
1458 } else if (Pascal)
1459 ThisTokBuf += 2;
1460 }
Mike Stump11289f42009-09-09 15:08:12 +00001461
Craig Topper54edcca2011-08-11 04:06:15 +00001462 while (ThisTokBuf != ThisTokEnd) {
1463 // Is this a span of non-escape characters?
1464 if (ThisTokBuf[0] != '\\') {
1465 const char *InStart = ThisTokBuf;
1466 do {
1467 ++ThisTokBuf;
1468 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1469
1470 // Copy the character span over.
Richard Smith639b8d02012-09-08 07:16:20 +00001471 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1472 StringRef(InStart, ThisTokBuf - InStart)))
1473 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001474 continue;
Steve Naroff4f88b312007-03-13 22:37:02 +00001475 }
Craig Topper54edcca2011-08-11 04:06:15 +00001476 // Is this a Universal Character Name escape?
1477 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith2a70e652012-03-09 22:27:51 +00001478 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1479 ResultPtr, hadError,
1480 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper54edcca2011-08-11 04:06:15 +00001481 CharByteWidth, Diags, Features);
1482 continue;
1483 }
1484 // Otherwise, this is a non-UCN escape character. Process it.
1485 unsigned ResultChar =
Richard Smith639b8d02012-09-08 07:16:20 +00001486 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper54edcca2011-08-11 04:06:15 +00001487 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001488 CharByteWidth*8, Diags, Features);
Mike Stump11289f42009-09-09 15:08:12 +00001489
Eli Friedmand1370792011-11-02 23:06:23 +00001490 if (CharByteWidth == 4) {
1491 // FIXME: Make the type of the result buffer correct instead of
1492 // using reinterpret_cast.
1493 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001494 *ResultWidePtr = ResultChar;
Eli Friedmand1370792011-11-02 23:06:23 +00001495 ResultPtr += 4;
1496 } else if (CharByteWidth == 2) {
1497 // FIXME: Make the type of the result buffer correct instead of
1498 // using reinterpret_cast.
1499 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001500 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmand1370792011-11-02 23:06:23 +00001501 ResultPtr += 2;
1502 } else {
1503 assert(CharByteWidth == 1 && "Unexpected char width");
1504 *ResultPtr++ = ResultChar & 0xFF;
1505 }
Craig Topper54edcca2011-08-11 04:06:15 +00001506 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001507 }
1508 }
Mike Stump11289f42009-09-09 15:08:12 +00001509
Chris Lattner8a24e582009-01-16 18:51:42 +00001510 if (Pascal) {
Eli Friedman20554702011-11-05 00:41:04 +00001511 if (CharByteWidth == 4) {
1512 // FIXME: Make the type of the result buffer correct instead of
1513 // using reinterpret_cast.
1514 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1515 ResultWidePtr[0] = GetNumStringChars() - 1;
1516 } else if (CharByteWidth == 2) {
1517 // FIXME: Make the type of the result buffer correct instead of
1518 // using reinterpret_cast.
1519 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1520 ResultWidePtr[0] = GetNumStringChars() - 1;
1521 } else {
1522 assert(CharByteWidth == 1 && "Unexpected char width");
1523 ResultBuf[0] = GetNumStringChars() - 1;
1524 }
Chris Lattner8a24e582009-01-16 18:51:42 +00001525
1526 // Verify that pascal strings aren't too large.
Chris Lattner6bab4352010-11-17 07:21:13 +00001527 if (GetStringLength() > 256) {
Richard Smith639b8d02012-09-08 07:16:20 +00001528 if (Diags)
Craig Topper9d5583e2014-06-26 04:58:39 +00001529 Diags->Report(StringToks.front().getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001530 diag::err_pascal_string_too_long)
Craig Topper9d5583e2014-06-26 04:58:39 +00001531 << SourceRange(StringToks.front().getLocation(),
1532 StringToks.back().getLocation());
Douglas Gregorfb65e592011-07-27 05:40:30 +00001533 hadError = true;
Eli Friedman1c3fb222009-04-01 03:17:08 +00001534 return;
1535 }
Chris Lattner6bab4352010-11-17 07:21:13 +00001536 } else if (Diags) {
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001537 // Complain if this string literal has too many characters.
Chris Lattner2be8aa92010-11-17 07:12:42 +00001538 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001539
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001540 if (GetNumStringChars() > MaxChars)
Craig Topper9d5583e2014-06-26 04:58:39 +00001541 Diags->Report(StringToks.front().getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001542 diag::ext_string_too_long)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001543 << GetNumStringChars() << MaxChars
Chris Lattner2be8aa92010-11-17 07:12:42 +00001544 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Craig Topper9d5583e2014-06-26 04:58:39 +00001545 << SourceRange(StringToks.front().getLocation(),
1546 StringToks.back().getLocation());
Chris Lattner8a24e582009-01-16 18:51:42 +00001547 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001548}
Chris Lattnerddb71912009-02-18 19:21:10 +00001549
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001550static const char *resyncUTF8(const char *Err, const char *End) {
1551 if (Err == End)
1552 return End;
1553 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1554 while (++Err != End && (*Err & 0xC0) == 0x80)
1555 ;
1556 return Err;
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001557}
1558
Richard Smith639b8d02012-09-08 07:16:20 +00001559/// \brief This function copies from Fragment, which is a sequence of bytes
1560/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper54edcca2011-08-11 04:06:15 +00001561/// Performs widening for multi-byte characters.
Richard Smith639b8d02012-09-08 07:16:20 +00001562bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1563 const char *TokBegin,
1564 StringRef Fragment) {
1565 const UTF8 *ErrorPtrTmp;
1566 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1567 return false;
Craig Topper54edcca2011-08-11 04:06:15 +00001568
Eli Friedman94363522012-02-11 05:08:10 +00001569 // If we see bad encoding for unprefixed string literals, warn and
1570 // simply copy the byte values, for compatibility with gcc and older
1571 // versions of clang.
1572 bool NoErrorOnBadEncoding = isAscii();
Richard Smith639b8d02012-09-08 07:16:20 +00001573 if (NoErrorOnBadEncoding) {
1574 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1575 ResultPtr += Fragment.size();
1576 }
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001577
Richard Smith639b8d02012-09-08 07:16:20 +00001578 if (Diags) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001579 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1580
1581 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1582 const DiagnosticBuilder &Builder =
1583 Diag(Diags, Features, SourceLoc, TokBegin,
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001584 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001585 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1586 : diag::err_bad_string_encoding);
1587
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001588 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001589 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1590
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001591 // Decode into a dummy buffer.
1592 SmallString<512> Dummy;
1593 Dummy.reserve(Fragment.size() * CharByteWidth);
1594 char *Ptr = Dummy.data();
1595
Alexander Kornienkod3b4e082014-05-22 19:56:11 +00001596 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001597 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001598 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001599 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1600 ErrorPtr, NextStart);
1601 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1602 }
Richard Smith639b8d02012-09-08 07:16:20 +00001603 }
Eli Friedman94363522012-02-11 05:08:10 +00001604 return !NoErrorOnBadEncoding;
1605}
Craig Topper54edcca2011-08-11 04:06:15 +00001606
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001607void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1608 hadError = true;
1609 if (Diags)
1610 Diags->Report(Loc, diag::err_lexing_string);
1611}
1612
Chris Lattnerddb71912009-02-18 19:21:10 +00001613/// getOffsetOfStringByte - This function returns the offset of the
1614/// specified byte of the string data represented by Token. This handles
1615/// advancing over escape sequences in the string.
1616unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattnerbde1b812010-11-17 06:46:14 +00001617 unsigned ByteNo) const {
Chris Lattnerddb71912009-02-18 19:21:10 +00001618 // Get the spelling of the token.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001619 SmallString<32> SpellingBuffer;
Alexis Hunt3b791862010-08-30 17:47:05 +00001620 SpellingBuffer.resize(Tok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001621
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001622 bool StringInvalid = false;
Chris Lattnerddb71912009-02-18 19:21:10 +00001623 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattner39720112010-11-17 07:26:20 +00001624 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1625 &StringInvalid);
Chris Lattner7a02bfd2010-11-17 06:26:08 +00001626 if (StringInvalid)
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001627 return 0;
Chris Lattnerddb71912009-02-18 19:21:10 +00001628
Chris Lattnerddb71912009-02-18 19:21:10 +00001629 const char *SpellingStart = SpellingPtr;
1630 const char *SpellingEnd = SpellingPtr+TokLen;
1631
Richard Smith4060f772012-06-13 05:37:23 +00001632 // Handle UTF-8 strings just like narrow strings.
1633 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1634 SpellingPtr += 2;
1635
1636 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1637 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1638
1639 // For raw string literals, this is easy.
1640 if (SpellingPtr[0] == 'R') {
1641 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1642 // Skip 'R"'.
1643 SpellingPtr += 2;
1644 while (*SpellingPtr != '(') {
1645 ++SpellingPtr;
1646 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1647 }
1648 // Skip '('.
1649 ++SpellingPtr;
1650 return SpellingPtr - SpellingStart + ByteNo;
1651 }
1652
1653 // Skip over the leading quote
Chris Lattnerddb71912009-02-18 19:21:10 +00001654 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1655 ++SpellingPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattnerddb71912009-02-18 19:21:10 +00001657 // Skip over bytes until we find the offset we're looking for.
1658 while (ByteNo) {
1659 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump11289f42009-09-09 15:08:12 +00001660
Chris Lattnerddb71912009-02-18 19:21:10 +00001661 // Step over non-escapes simply.
1662 if (*SpellingPtr != '\\') {
1663 ++SpellingPtr;
1664 --ByteNo;
1665 continue;
1666 }
Mike Stump11289f42009-09-09 15:08:12 +00001667
Chris Lattnerddb71912009-02-18 19:21:10 +00001668 // Otherwise, this is an escape character. Advance over it.
1669 bool HadError = false;
Richard Smith4060f772012-06-13 05:37:23 +00001670 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1671 const char *EscapePtr = SpellingPtr;
1672 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1673 1, Features, HadError);
1674 if (Len > ByteNo) {
1675 // ByteNo is somewhere within the escape sequence.
1676 SpellingPtr = EscapePtr;
1677 break;
1678 }
1679 ByteNo -= Len;
1680 } else {
Richard Smith639b8d02012-09-08 07:16:20 +00001681 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smith4060f772012-06-13 05:37:23 +00001682 FullSourceLoc(Tok.getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001683 CharByteWidth*8, Diags, Features);
Richard Smith4060f772012-06-13 05:37:23 +00001684 --ByteNo;
1685 }
Chris Lattnerddb71912009-02-18 19:21:10 +00001686 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattnerddb71912009-02-18 19:21:10 +00001687 }
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattnerddb71912009-02-18 19:21:10 +00001689 return SpellingPtr-SpellingStart;
1690}