blob: 582ed3ff4721603ae591bc46b776274aa5ee509d [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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/LangOptions.h"
18#include "clang/Basic/SourceLocation.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/TargetInfo.h"
20#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000021#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/Lex/Token.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/SmallVector.h"
Steve Naroff4f88b312007-03-13 22:37:02 +000026#include "llvm/ADT/StringExtras.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000027#include "llvm/ADT/StringSwitch.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000028#include "llvm/Support/ConvertUTF.h"
David Blaikie76bd3c82011-09-23 05:35:21 +000029#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include <algorithm>
31#include <cassert>
32#include <cstddef>
33#include <cstdint>
34#include <cstring>
35#include <string>
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000036
Steve Naroff09ef4742007-03-09 23:16:33 +000037using namespace clang;
38
Douglas Gregorfb65e592011-07-27 05:40:30 +000039static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
40 switch (kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000041 default: llvm_unreachable("Unknown token type!");
Douglas Gregorfb65e592011-07-27 05:40:30 +000042 case tok::char_constant:
43 case tok::string_literal:
Richard Smith3e3a7052014-11-08 06:08:42 +000044 case tok::utf8_char_constant:
Douglas Gregorfb65e592011-07-27 05:40:30 +000045 case tok::utf8_string_literal:
46 return Target.getCharWidth();
47 case tok::wide_char_constant:
48 case tok::wide_string_literal:
49 return Target.getWCharWidth();
50 case tok::utf16_char_constant:
51 case tok::utf16_string_literal:
52 return Target.getChar16Width();
53 case tok::utf32_char_constant:
54 case tok::utf32_string_literal:
55 return Target.getChar32Width();
56 }
57}
58
Seth Cantrell4cfc8172012-10-28 18:24:46 +000059static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
60 FullSourceLoc TokLoc,
61 const char *TokBegin,
62 const char *TokRangeBegin,
63 const char *TokRangeEnd) {
64 SourceLocation Begin =
65 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
66 TokLoc.getManager(), Features);
67 SourceLocation End =
68 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
69 TokLoc.getManager(), Features);
70 return CharSourceRange::getCharRange(Begin, End);
71}
72
Richard Smith639b8d02012-09-08 07:16:20 +000073/// \brief Produce a diagnostic highlighting some portion of a literal.
74///
75/// Emits the diagnostic \p DiagID, highlighting the range of characters from
76/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
77/// a substring of a spelling buffer for the token beginning at \p TokBegin.
78static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
79 const LangOptions &Features, FullSourceLoc TokLoc,
80 const char *TokBegin, const char *TokRangeBegin,
81 const char *TokRangeEnd, unsigned DiagID) {
82 SourceLocation Begin =
83 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
84 TokLoc.getManager(), Features);
Seth Cantrell4cfc8172012-10-28 18:24:46 +000085 return Diags->Report(Begin, DiagID) <<
86 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
Richard Smith639b8d02012-09-08 07:16:20 +000087}
88
Chris Lattner2f5add62007-04-05 06:57:15 +000089/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
90/// either a character or a string literal.
Richard Smith639b8d02012-09-08 07:16:20 +000091static unsigned ProcessCharEscape(const char *ThisTokBegin,
92 const char *&ThisTokBuf,
Chris Lattner2f5add62007-04-05 06:57:15 +000093 const char *ThisTokEnd, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +000094 FullSourceLoc Loc, unsigned CharWidth,
Richard Smith639b8d02012-09-08 07:16:20 +000095 DiagnosticsEngine *Diags,
96 const LangOptions &Features) {
97 const char *EscapeBegin = ThisTokBuf;
98
Chris Lattner2f5add62007-04-05 06:57:15 +000099 // Skip the '\' char.
100 ++ThisTokBuf;
101
102 // We know that this character can't be off the end of the buffer, because
103 // that would have been \", which would not have been the end of string.
104 unsigned ResultChar = *ThisTokBuf++;
105 switch (ResultChar) {
106 // These map to themselves.
107 case '\\': case '\'': case '"': case '?': break;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattner2f5add62007-04-05 06:57:15 +0000109 // These have fixed mappings.
110 case 'a':
111 // TODO: K&R: the meaning of '\\a' is different in traditional C
112 ResultChar = 7;
113 break;
114 case 'b':
115 ResultChar = 8;
116 break;
117 case 'e':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000118 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000119 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
120 diag::ext_nonstandard_escape) << "e";
Chris Lattner2f5add62007-04-05 06:57:15 +0000121 ResultChar = 27;
122 break;
Eli Friedman28a00aa2009-06-10 01:32:39 +0000123 case 'E':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000124 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000125 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
126 diag::ext_nonstandard_escape) << "E";
Eli Friedman28a00aa2009-06-10 01:32:39 +0000127 ResultChar = 27;
128 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000129 case 'f':
130 ResultChar = 12;
131 break;
132 case 'n':
133 ResultChar = 10;
134 break;
135 case 'r':
136 ResultChar = 13;
137 break;
138 case 't':
139 ResultChar = 9;
140 break;
141 case 'v':
142 ResultChar = 11;
143 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000144 case 'x': { // Hex escape.
145 ResultChar = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000146 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000147 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000148 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000149 diag::err_hex_escape_no_digits) << "x";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000150 HadError = true;
Chris Lattner2f5add62007-04-05 06:57:15 +0000151 break;
152 }
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattner812eda82007-05-20 05:17:04 +0000154 // Hex escapes are a maximal series of hex digits.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000155 bool Overflow = false;
156 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000157 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Chris Lattnerc10adde2007-05-20 05:00:58 +0000158 if (CharVal == -1) break;
Chris Lattner59f09b62008-09-30 20:45:40 +0000159 // About to shift out a digit?
David Blaikie96cedb52015-03-23 19:54:44 +0000160 if (ResultChar & 0xF0000000)
161 Overflow = true;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000162 ResultChar <<= 4;
163 ResultChar |= CharVal;
164 }
165
166 // See if any bits will be truncated when evaluated as a character.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000167 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
168 Overflow = true;
169 ResultChar &= ~0U >> (32-CharWidth);
170 }
Mike Stump11289f42009-09-09 15:08:12 +0000171
Chris Lattnerc10adde2007-05-20 05:00:58 +0000172 // Check for overflow.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000173 if (Overflow && Diags) // Too many digits to fit in
Richard Smith639b8d02012-09-08 07:16:20 +0000174 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Craig Topper7f5ff212015-11-14 02:09:55 +0000175 diag::err_escape_too_large) << 0;
Chris Lattner2f5add62007-04-05 06:57:15 +0000176 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000177 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000178 case '0': case '1': case '2': case '3':
Chris Lattner812eda82007-05-20 05:17:04 +0000179 case '4': case '5': case '6': case '7': {
Chris Lattner2f5add62007-04-05 06:57:15 +0000180 // Octal escapes.
Chris Lattner3f4b6e32007-06-09 06:20:47 +0000181 --ThisTokBuf;
Chris Lattner812eda82007-05-20 05:17:04 +0000182 ResultChar = 0;
183
184 // Octal escapes are a series of octal digits with maximum length 3.
185 // "\0123" is a two digit sequence equal to "\012" "3".
186 unsigned NumDigits = 0;
187 do {
188 ResultChar <<= 3;
189 ResultChar |= *ThisTokBuf++ - '0';
190 ++NumDigits;
191 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
192 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner812eda82007-05-20 05:17:04 +0000194 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner812eda82007-05-20 05:17:04 +0000195 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000196 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000197 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Craig Topper7f5ff212015-11-14 02:09:55 +0000198 diag::err_escape_too_large) << 1;
Chris Lattner812eda82007-05-20 05:17:04 +0000199 ResultChar &= ~0U >> (32-CharWidth);
200 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000201 break;
Chris Lattner812eda82007-05-20 05:17:04 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner2f5add62007-04-05 06:57:15 +0000204 // Otherwise, these are not valid escapes.
205 case '(': case '{': case '[': case '%':
206 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000207 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000208 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
209 diag::ext_nonstandard_escape)
210 << std::string(1, ResultChar);
Eli Friedman5d72d412009-04-28 00:51:18 +0000211 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000212 default:
Craig Topperd2d442c2014-05-17 23:10:59 +0000213 if (!Diags)
Douglas Gregor9af03022010-05-26 05:35:51 +0000214 break;
Richard Smith639b8d02012-09-08 07:16:20 +0000215
Jordan Rosea7d03842013-02-08 22:30:41 +0000216 if (isPrintable(ResultChar))
Richard Smith639b8d02012-09-08 07:16:20 +0000217 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
218 diag::ext_unknown_escape)
219 << std::string(1, ResultChar);
Chris Lattner59acca52008-11-22 07:23:31 +0000220 else
Richard Smith639b8d02012-09-08 07:16:20 +0000221 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
222 diag::ext_unknown_escape)
223 << "x" + llvm::utohexstr(ResultChar);
Chris Lattner2f5add62007-04-05 06:57:15 +0000224 break;
225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner2f5add62007-04-05 06:57:15 +0000227 return ResultChar;
228}
229
Richard Smith8b7258b2014-02-17 21:52:30 +0000230static void appendCodePoint(unsigned Codepoint,
231 llvm::SmallVectorImpl<char> &Str) {
232 char ResultBuf[4];
233 char *ResultPtr = ResultBuf;
234 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
235 (void)Res;
236 assert(Res && "Unexpected conversion failure");
237 Str.append(ResultBuf, ResultPtr);
238}
239
240void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
241 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
242 if (*I != '\\') {
243 Buf.push_back(*I);
244 continue;
245 }
246
247 ++I;
248 assert(*I == 'u' || *I == 'U');
249
250 unsigned NumHexDigits;
251 if (*I == 'u')
252 NumHexDigits = 4;
253 else
254 NumHexDigits = 8;
255
256 assert(I + NumHexDigits <= E);
257
258 uint32_t CodePoint = 0;
259 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
260 unsigned Value = llvm::hexDigitValue(*I);
261 assert(Value != -1U);
262
263 CodePoint <<= 4;
264 CodePoint += Value;
265 }
266
267 appendCodePoint(CodePoint, Buf);
268 --I;
269 }
270}
271
Steve Naroff7b753d22009-03-30 23:46:03 +0000272/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Webera6bde812010-10-09 00:27:47 +0000273/// return the UTF32.
Richard Smith2a70e652012-03-09 22:27:51 +0000274static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
275 const char *ThisTokEnd,
Nico Webera6bde812010-10-09 00:27:47 +0000276 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000277 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000278 const LangOptions &Features,
279 bool in_char_string_literal = false) {
Richard Smith2a70e652012-03-09 22:27:51 +0000280 const char *UcnBegin = ThisTokBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000281
Steve Naroff7b753d22009-03-30 23:46:03 +0000282 // Skip the '\u' char's.
283 ThisTokBuf += 2;
Chris Lattner2f5add62007-04-05 06:57:15 +0000284
Jordan Rosea7d03842013-02-08 22:30:41 +0000285 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattnerbde1b812010-11-17 06:46:14 +0000286 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000287 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000288 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
Nico Webera6bde812010-10-09 00:27:47 +0000289 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000290 }
Nico Webera6bde812010-10-09 00:27:47 +0000291 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000292 unsigned short UcnLenSave = UcnLen;
Nico Webera6bde812010-10-09 00:27:47 +0000293 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000294 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000295 if (CharVal == -1) break;
296 UcnVal <<= 4;
297 UcnVal |= CharVal;
298 }
299 // If we didn't consume the proper number of digits, there is a problem.
Nico Webera6bde812010-10-09 00:27:47 +0000300 if (UcnLenSave) {
Richard Smith639b8d02012-09-08 07:16:20 +0000301 if (Diags)
302 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
303 diag::err_ucn_escape_incomplete);
Nico Webera6bde812010-10-09 00:27:47 +0000304 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000305 }
Richard Smith2a70e652012-03-09 22:27:51 +0000306
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000307 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith2a70e652012-03-09 22:27:51 +0000308 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
309 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattnerbde1b812010-11-17 06:46:14 +0000310 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000311 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
312 diag::err_ucn_escape_invalid);
Nico Webera6bde812010-10-09 00:27:47 +0000313 return false;
314 }
Richard Smith2a70e652012-03-09 22:27:51 +0000315
316 // C++11 allows UCNs that refer to control characters and basic source
317 // characters inside character and string literals
318 if (UcnVal < 0xa0 &&
319 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000320 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
Richard Smith2a70e652012-03-09 22:27:51 +0000321 if (Diags) {
Richard Smith2a70e652012-03-09 22:27:51 +0000322 char BasicSCSChar = UcnVal;
323 if (UcnVal >= 0x20 && UcnVal < 0x7f)
Richard Smith639b8d02012-09-08 07:16:20 +0000324 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
325 IsError ? diag::err_ucn_escape_basic_scs :
326 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
327 << StringRef(&BasicSCSChar, 1);
Richard Smith2a70e652012-03-09 22:27:51 +0000328 else
Richard Smith639b8d02012-09-08 07:16:20 +0000329 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
330 IsError ? diag::err_ucn_control_character :
331 diag::warn_cxx98_compat_literal_ucn_control_character);
Richard Smith2a70e652012-03-09 22:27:51 +0000332 }
333 if (IsError)
334 return false;
335 }
336
Richard Smith639b8d02012-09-08 07:16:20 +0000337 if (!Features.CPlusPlus && !Features.C99 && Diags)
338 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Rosec0cba272013-01-27 20:12:04 +0000339 diag::warn_ucn_not_valid_in_c89_literal);
Richard Smith639b8d02012-09-08 07:16:20 +0000340
Nico Webera6bde812010-10-09 00:27:47 +0000341 return true;
342}
343
Richard Smith4060f772012-06-13 05:37:23 +0000344/// MeasureUCNEscape - Determine the number of bytes within the resulting string
345/// which this UCN will occupy.
346static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
347 const char *ThisTokEnd, unsigned CharByteWidth,
348 const LangOptions &Features, bool &HadError) {
349 // UTF-32: 4 bytes per escape.
350 if (CharByteWidth == 4)
351 return 4;
352
353 uint32_t UcnVal = 0;
354 unsigned short UcnLen = 0;
355 FullSourceLoc Loc;
356
357 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
Craig Topperd2d442c2014-05-17 23:10:59 +0000358 UcnLen, Loc, nullptr, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000359 HadError = true;
360 return 0;
361 }
362
363 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
364 if (CharByteWidth == 2)
365 return UcnVal <= 0xFFFF ? 2 : 4;
366
367 // UTF-8.
368 if (UcnVal < 0x80)
369 return 1;
370 if (UcnVal < 0x800)
371 return 2;
372 if (UcnVal < 0x10000)
373 return 3;
374 return 4;
375}
376
Nico Webera6bde812010-10-09 00:27:47 +0000377/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
378/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
379/// StringLiteralParser. When we decide to implement UCN's for identifiers,
380/// we will likely rework our support for UCN's.
Richard Smith2a70e652012-03-09 22:27:51 +0000381static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
382 const char *ThisTokEnd,
Chris Lattner2be8aa92010-11-17 07:12:42 +0000383 char *&ResultBuf, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000384 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikie9c902b52011-09-25 23:23:43 +0000385 DiagnosticsEngine *Diags,
386 const LangOptions &Features) {
Nico Webera6bde812010-10-09 00:27:47 +0000387 typedef uint32_t UTF32;
388 UTF32 UcnVal = 0;
389 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +0000390 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
391 Loc, Diags, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000392 HadError = true;
Steve Naroff7b753d22009-03-30 23:46:03 +0000393 return;
394 }
Nico Webera6bde812010-10-09 00:27:47 +0000395
Eli Friedmanf9edb002013-09-18 23:23:13 +0000396 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
Douglas Gregorfb65e592011-07-27 05:40:30 +0000397 "only character widths of 1, 2, or 4 bytes supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000398
Douglas Gregorfb65e592011-07-27 05:40:30 +0000399 (void)UcnLen;
400 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000401
Douglas Gregorfb65e592011-07-27 05:40:30 +0000402 if (CharByteWidth == 4) {
Eli Friedmand1370792011-11-02 23:06:23 +0000403 // FIXME: Make the type of the result buffer correct instead of
404 // using reinterpret_cast.
Justin Lebar90910552016-09-30 00:38:45 +0000405 llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
Eli Friedmand1370792011-11-02 23:06:23 +0000406 *ResultPtr = UcnVal;
407 ResultBuf += 4;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000408 return;
409 }
410
411 if (CharByteWidth == 2) {
Eli Friedmand1370792011-11-02 23:06:23 +0000412 // FIXME: Make the type of the result buffer correct instead of
413 // using reinterpret_cast.
Justin Lebar90910552016-09-30 00:38:45 +0000414 llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
Eli Friedmand1370792011-11-02 23:06:23 +0000415
Richard Smith0948d932012-06-13 05:41:29 +0000416 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmand1370792011-11-02 23:06:23 +0000417 *ResultPtr = UcnVal;
418 ResultBuf += 2;
Nico Weber9762e0a2010-10-06 04:57:26 +0000419 return;
420 }
Nico Weber9762e0a2010-10-06 04:57:26 +0000421
Eli Friedmand1370792011-11-02 23:06:23 +0000422 // Convert to UTF16.
Nico Weber9762e0a2010-10-06 04:57:26 +0000423 UcnVal -= 0x10000;
Eli Friedmand1370792011-11-02 23:06:23 +0000424 *ResultPtr = 0xD800 + (UcnVal >> 10);
425 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
426 ResultBuf += 4;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000427 return;
428 }
Douglas Gregorfb65e592011-07-27 05:40:30 +0000429
430 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
431
Steve Naroff7b753d22009-03-30 23:46:03 +0000432 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
433 // The conversion below was inspired by:
434 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump11289f42009-09-09 15:08:12 +0000435 // First, we determine how many bytes the result will require.
Steve Naroffc94adda2009-04-01 11:09:15 +0000436 typedef uint8_t UTF8;
Steve Naroff7b753d22009-03-30 23:46:03 +0000437
438 unsigned short bytesToWrite = 0;
439 if (UcnVal < (UTF32)0x80)
440 bytesToWrite = 1;
441 else if (UcnVal < (UTF32)0x800)
442 bytesToWrite = 2;
443 else if (UcnVal < (UTF32)0x10000)
444 bytesToWrite = 3;
445 else
446 bytesToWrite = 4;
Mike Stump11289f42009-09-09 15:08:12 +0000447
Steve Naroff7b753d22009-03-30 23:46:03 +0000448 const unsigned byteMask = 0xBF;
449 const unsigned byteMark = 0x80;
Mike Stump11289f42009-09-09 15:08:12 +0000450
Steve Naroff7b753d22009-03-30 23:46:03 +0000451 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Narofff2a880c2009-03-31 10:29:45 +0000452 // into the first byte, depending on how many bytes follow.
Mike Stump11289f42009-09-09 15:08:12 +0000453 static const UTF8 firstByteMark[5] = {
Steve Narofff2a880c2009-03-31 10:29:45 +0000454 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff7b753d22009-03-30 23:46:03 +0000455 };
456 // Finally, we write the bytes into ResultBuf.
457 ResultBuf += bytesToWrite;
458 switch (bytesToWrite) { // note: everything falls through.
Benjamin Kramerf23a6e62012-11-08 19:22:26 +0000459 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
460 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
461 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
462 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000463 }
464 // Update the buffer.
465 ResultBuf += bytesToWrite;
466}
Chris Lattner2f5add62007-04-05 06:57:15 +0000467
Steve Naroff09ef4742007-03-09 23:16:33 +0000468/// integer-constant: [C99 6.4.4.1]
469/// decimal-constant integer-suffix
470/// octal-constant integer-suffix
471/// hexadecimal-constant integer-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000472/// binary-literal integer-suffix [GNU, C++1y]
Richard Smith81292452012-03-08 21:59:28 +0000473/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smith39570d002012-03-08 08:45:32 +0000474/// decimal-literal ud-suffix
475/// octal-literal ud-suffix
476/// hexadecimal-literal ud-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000477/// binary-literal ud-suffix [GNU, C++1y]
Mike Stump11289f42009-09-09 15:08:12 +0000478/// decimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000479/// nonzero-digit
480/// decimal-constant digit
Mike Stump11289f42009-09-09 15:08:12 +0000481/// octal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000482/// 0
483/// octal-constant octal-digit
Mike Stump11289f42009-09-09 15:08:12 +0000484/// hexadecimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000485/// hexadecimal-prefix hexadecimal-digit
486/// hexadecimal-constant hexadecimal-digit
487/// hexadecimal-prefix: one of
488/// 0x 0X
Richard Smithf4198b72013-07-23 08:14:48 +0000489/// binary-literal:
490/// 0b binary-digit
491/// 0B binary-digit
492/// binary-literal binary-digit
Steve Naroff09ef4742007-03-09 23:16:33 +0000493/// integer-suffix:
494/// unsigned-suffix [long-suffix]
495/// unsigned-suffix [long-long-suffix]
496/// long-suffix [unsigned-suffix]
497/// long-long-suffix [unsigned-sufix]
498/// nonzero-digit:
499/// 1 2 3 4 5 6 7 8 9
500/// octal-digit:
501/// 0 1 2 3 4 5 6 7
502/// hexadecimal-digit:
503/// 0 1 2 3 4 5 6 7 8 9
504/// a b c d e f
505/// A B C D E F
Richard Smithf4198b72013-07-23 08:14:48 +0000506/// binary-digit:
507/// 0
508/// 1
Steve Naroff09ef4742007-03-09 23:16:33 +0000509/// unsigned-suffix: one of
510/// u U
511/// long-suffix: one of
512/// l L
Mike Stump11289f42009-09-09 15:08:12 +0000513/// long-long-suffix: one of
Steve Naroff09ef4742007-03-09 23:16:33 +0000514/// ll LL
515///
516/// floating-constant: [C99 6.4.4.2]
517/// TODO: add rules...
518///
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000519NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
520 SourceLocation TokLoc,
521 Preprocessor &PP)
522 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattner59f09b62008-09-30 20:45:40 +0000524 // This routine assumes that the range begin/end matches the regex for integer
525 // and FP constants (specifically, the 'pp-number' regex), and assumes that
526 // the byte at "*end" is both valid and not part of the regex. Because of
527 // this, it doesn't have to check for 'overscan' in various places.
Jordan Rosea7d03842013-02-08 22:30:41 +0000528 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
Mike Stump11289f42009-09-09 15:08:12 +0000529
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000530 s = DigitsBegin = ThisTokBegin;
Steve Naroff09ef4742007-03-09 23:16:33 +0000531 saw_exponent = false;
532 saw_period = false;
Richard Smith39570d002012-03-08 08:45:32 +0000533 saw_ud_suffix = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000534 isLong = false;
535 isUnsigned = false;
536 isLongLong = false;
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +0000537 isHalf = false;
Chris Lattnered045422007-08-26 03:29:23 +0000538 isFloat = false;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000539 isImaginary = false;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000540 isFloat128 = false;
David Majnemer65a407c2014-06-21 18:46:07 +0000541 MicrosoftInteger = 0;
Steve Naroff09ef4742007-03-09 23:16:33 +0000542 hadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000543
Steve Naroff09ef4742007-03-09 23:16:33 +0000544 if (*s == '0') { // parse radix
Chris Lattner6016a512008-06-30 06:39:54 +0000545 ParseNumberStartingWithZero(TokLoc);
546 if (hadError)
547 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000548 } else { // the first digit is non-zero
549 radix = 10;
550 s = SkipDigits(s);
551 if (s == ThisTokEnd) {
Chris Lattner328fa5c2007-06-08 17:12:06 +0000552 // Done.
Craig Topper3efc7c02016-01-28 05:22:54 +0000553 } else {
554 ParseDecimalOrOctalCommon(TokLoc);
555 if (hadError)
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000556 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000557 }
558 }
559
560 SuffixBegin = s;
Richard Smith1e130482013-09-26 04:19:11 +0000561 checkSeparator(TokLoc, s, CSK_AfterDigits);
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattnerf55ab182007-08-26 01:58:14 +0000563 // Parse the suffix. At this point we can classify whether we have an FP or
564 // integer constant.
565 bool isFPConstant = isFloatingLiteral();
Craig Topperd2d442c2014-05-17 23:10:59 +0000566 const char *ImaginarySuffixLoc = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Chris Lattnerf55ab182007-08-26 01:58:14 +0000568 // Loop over all of the characters of the suffix. If we see something bad,
569 // we break out of the loop.
570 for (; s != ThisTokEnd; ++s) {
571 switch (*s) {
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +0000572 case 'h': // FP Suffix for "half".
573 case 'H':
574 // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
575 if (!PP.getLangOpts().Half) break;
576 if (!isFPConstant) break; // Error for integer constant.
577 if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
578 isHalf = true;
579 continue; // Success.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000580 case 'f': // FP Suffix for "float"
581 case 'F':
582 if (!isFPConstant) break; // Error for integer constant.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000583 if (isHalf || isFloat || isLong || isFloat128)
584 break; // HF, FF, LF, QF invalid.
Chris Lattnered045422007-08-26 03:29:23 +0000585 isFloat = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000586 continue; // Success.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000587 case 'q': // FP Suffix for "__float128"
588 case 'Q':
589 if (!isFPConstant) break; // Error for integer constant.
590 if (isHalf || isFloat || isLong || isFloat128)
591 break; // HQ, FQ, LQ, QQ invalid.
592 isFloat128 = true;
593 continue; // Success.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000594 case 'u':
595 case 'U':
596 if (isFPConstant) break; // Error for floating constant.
597 if (isUnsigned) break; // Cannot be repeated.
598 isUnsigned = true;
599 continue; // Success.
600 case 'l':
601 case 'L':
602 if (isLong || isLongLong) break; // Cannot be repeated.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000603 if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid.
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattnerf55ab182007-08-26 01:58:14 +0000605 // Check for long long. The L's need to be adjacent and the same case.
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000606 if (s[1] == s[0]) {
607 assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
Chris Lattnerf55ab182007-08-26 01:58:14 +0000608 if (isFPConstant) break; // long long invalid for floats.
609 isLongLong = true;
610 ++s; // Eat both of them.
611 } else {
Steve Naroff09ef4742007-03-09 23:16:33 +0000612 isLong = true;
Steve Naroff09ef4742007-03-09 23:16:33 +0000613 }
Chris Lattnerf55ab182007-08-26 01:58:14 +0000614 continue; // Success.
615 case 'i':
Chris Lattner26f6c222010-10-14 00:24:10 +0000616 case 'I':
David Blaikiebbafb8a2012-03-11 07:00:24 +0000617 if (PP.getLangOpts().MicrosoftExt) {
David Majnemer65a407c2014-06-21 18:46:07 +0000618 if (isLong || isLongLong || MicrosoftInteger)
619 break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000620
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000621 if (!isFPConstant) {
David Majnemer5055dfc2015-07-26 09:02:26 +0000622 // Allow i8, i16, i32, and i64.
Mike Stumpc99c0222009-10-08 22:55:36 +0000623 switch (s[1]) {
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000624 case '8':
625 s += 2; // i8 suffix
626 MicrosoftInteger = 8;
Peter Collingbourneefe09b42014-05-29 23:10:15 +0000627 break;
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000628 case '1':
629 if (s[2] == '6') {
630 s += 3; // i16 suffix
631 MicrosoftInteger = 16;
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000632 }
633 break;
634 case '3':
635 if (s[2] == '2') {
636 s += 3; // i32 suffix
637 MicrosoftInteger = 32;
638 }
639 break;
640 case '6':
641 if (s[2] == '4') {
642 s += 3; // i64 suffix
643 MicrosoftInteger = 64;
644 }
645 break;
646 default:
647 break;
648 }
649 }
650 if (MicrosoftInteger) {
651 assert(s <= ThisTokEnd && "didn't maximally munch?");
652 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000653 }
Steve Naroffa1f41452008-04-04 21:02:54 +0000654 }
Richard Smith2a988622013-09-24 04:06:10 +0000655 // "i", "if", and "il" are user-defined suffixes in C++1y.
Benjamin Kramer7fd88382015-03-29 14:11:22 +0000656 if (*s == 'i' && PP.getLangOpts().CPlusPlus14)
Richard Smith2a988622013-09-24 04:06:10 +0000657 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000658 // fall through.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000659 case 'j':
660 case 'J':
661 if (isImaginary) break; // Cannot be repeated.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000662 isImaginary = true;
Richard Smithf4198b72013-07-23 08:14:48 +0000663 ImaginarySuffixLoc = s;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000664 continue; // Success.
Steve Naroff09ef4742007-03-09 23:16:33 +0000665 }
Richard Smith39570d002012-03-08 08:45:32 +0000666 // If we reached here, there was an error or a ud-suffix.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000667 break;
668 }
Mike Stump11289f42009-09-09 15:08:12 +0000669
Chris Lattnerf55ab182007-08-26 01:58:14 +0000670 if (s != ThisTokEnd) {
Richard Smith8b7258b2014-02-17 21:52:30 +0000671 // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
672 expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
673 if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
Richard Smithf4198b72013-07-23 08:14:48 +0000674 // Any suffix pieces we might have parsed are actually part of the
675 // ud-suffix.
676 isLong = false;
677 isUnsigned = false;
678 isLongLong = false;
679 isFloat = false;
Anastasia Stulova5c1a2c52016-02-17 11:34:37 +0000680 isHalf = false;
Richard Smithf4198b72013-07-23 08:14:48 +0000681 isImaginary = false;
David Majnemer65a407c2014-06-21 18:46:07 +0000682 MicrosoftInteger = 0;
Richard Smithf4198b72013-07-23 08:14:48 +0000683
Richard Smith39570d002012-03-08 08:45:32 +0000684 saw_ud_suffix = true;
685 return;
686 }
687
688 // Report an error if there are any.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000689 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Craig Topper71a51ff2015-11-12 07:36:50 +0000690 diag::err_invalid_suffix_constant)
691 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin) << isFPConstant;
Chris Lattner59acca52008-11-22 07:23:31 +0000692 hadError = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000693 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000694 }
Richard Smithf4198b72013-07-23 08:14:48 +0000695
696 if (isImaginary) {
697 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
698 ImaginarySuffixLoc - ThisTokBegin),
699 diag::ext_imaginary_constant);
700 }
701}
702
Craig Topper3efc7c02016-01-28 05:22:54 +0000703/// ParseDecimalOrOctalCommon - This method is called for decimal or octal
704/// numbers. It issues an error for illegal digits, and handles floating point
705/// parsing. If it detects a floating point number, the radix is set to 10.
706void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
707 assert((radix == 8 || radix == 10) && "Unexpected radix");
708
709 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
710 // the code is using an incorrect base.
711 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
712 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
713 diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
714 hadError = true;
715 return;
716 }
717
718 if (*s == '.') {
719 checkSeparator(TokLoc, s, CSK_AfterDigits);
720 s++;
721 radix = 10;
722 saw_period = true;
723 checkSeparator(TokLoc, s, CSK_BeforeDigits);
724 s = SkipDigits(s); // Skip suffix.
725 }
726 if (*s == 'e' || *s == 'E') { // exponent
727 checkSeparator(TokLoc, s, CSK_AfterDigits);
728 const char *Exponent = s;
729 s++;
730 radix = 10;
731 saw_exponent = true;
732 if (*s == '+' || *s == '-') s++; // sign
733 const char *first_non_digit = SkipDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000734 if (containsDigits(s, first_non_digit)) {
Craig Topper3efc7c02016-01-28 05:22:54 +0000735 checkSeparator(TokLoc, s, CSK_BeforeDigits);
736 s = first_non_digit;
737 } else {
738 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
739 diag::err_exponent_has_no_digits);
740 hadError = true;
741 return;
742 }
743 }
744}
745
Richard Smithf4198b72013-07-23 08:14:48 +0000746/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
747/// suffixes as ud-suffixes, because the diagnostic experience is better if we
748/// treat it as an invalid suffix.
749bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
750 StringRef Suffix) {
751 if (!LangOpts.CPlusPlus11 || Suffix.empty())
752 return false;
753
754 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
755 if (Suffix[0] == '_')
756 return true;
757
758 // In C++11, there are no library suffixes.
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000759 if (!LangOpts.CPlusPlus14)
Richard Smithf4198b72013-07-23 08:14:48 +0000760 return false;
761
762 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
Richard Smith2a988622013-09-24 04:06:10 +0000763 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
Richard Smithf4198b72013-07-23 08:14:48 +0000764 return llvm::StringSwitch<bool>(Suffix)
765 .Cases("h", "min", "s", true)
766 .Cases("ms", "us", "ns", true)
Richard Smith2a988622013-09-24 04:06:10 +0000767 .Cases("il", "i", "if", true)
Richard Smithf4198b72013-07-23 08:14:48 +0000768 .Default(false);
Steve Naroff09ef4742007-03-09 23:16:33 +0000769}
770
Richard Smithfde94852013-09-26 03:33:06 +0000771void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
Richard Smith1e130482013-09-26 04:19:11 +0000772 const char *Pos,
773 CheckSeparatorKind IsAfterDigits) {
774 if (IsAfterDigits == CSK_AfterDigits) {
Richard Smith99dc0712013-09-26 05:57:03 +0000775 if (Pos == ThisTokBegin)
776 return;
Richard Smithfde94852013-09-26 03:33:06 +0000777 --Pos;
Richard Smith99dc0712013-09-26 05:57:03 +0000778 } else if (Pos == ThisTokEnd)
779 return;
Richard Smithfde94852013-09-26 03:33:06 +0000780
781 if (isDigitSeparator(*Pos))
782 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
783 diag::err_digit_separator_not_between_digits)
784 << IsAfterDigits;
785}
786
Chris Lattner6016a512008-06-30 06:39:54 +0000787/// ParseNumberStartingWithZero - This method is called when the first character
788/// of the number is found to be a zero. This means it is either an octal
789/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump11289f42009-09-09 15:08:12 +0000790/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner6016a512008-06-30 06:39:54 +0000791/// radix etc.
792void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
793 assert(s[0] == '0' && "Invalid method call");
794 s++;
Mike Stump11289f42009-09-09 15:08:12 +0000795
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000796 int c1 = s[0];
NAKAMURA Takumif2bc8f32013-09-27 04:42:28 +0000797
Chris Lattner6016a512008-06-30 06:39:54 +0000798 // Handle a hex number like 0x1234.
Benjamin Kramer86710282015-03-29 14:11:37 +0000799 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
Chris Lattner6016a512008-06-30 06:39:54 +0000800 s++;
Benjamin Kramer86710282015-03-29 14:11:37 +0000801 assert(s < ThisTokEnd && "didn't maximally munch?");
Chris Lattner6016a512008-06-30 06:39:54 +0000802 radix = 16;
803 DigitsBegin = s;
804 s = SkipHexDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000805 bool HasSignificandDigits = containsDigits(DigitsBegin, s);
Chris Lattner6016a512008-06-30 06:39:54 +0000806 if (s == ThisTokEnd) {
807 // Done.
808 } else if (*s == '.') {
809 s++;
810 saw_period = true;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000811 const char *floatDigitsBegin = s;
Chris Lattner6016a512008-06-30 06:39:54 +0000812 s = SkipHexDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000813 if (containsDigits(floatDigitsBegin, s))
814 HasSignificandDigits = true;
815 if (HasSignificandDigits)
816 checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000817 }
Aaron Ballmane1224a52012-02-08 13:36:33 +0000818
Richard Smithb1cba3e2016-02-09 22:34:35 +0000819 if (!HasSignificandDigits) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000820 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Richard Smith560a3572016-03-04 22:32:06 +0000821 diag::err_hex_constant_requires)
822 << PP.getLangOpts().CPlusPlus << 1;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000823 hadError = true;
824 return;
825 }
826
Chris Lattner6016a512008-06-30 06:39:54 +0000827 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump11289f42009-09-09 15:08:12 +0000828 // binary exponent is required.
Douglas Gregor86325ad2011-08-30 22:40:35 +0000829 if (*s == 'p' || *s == 'P') {
Richard Smith70ee92f2014-04-22 23:50:25 +0000830 checkSeparator(TokLoc, s, CSK_AfterDigits);
Chris Lattner6016a512008-06-30 06:39:54 +0000831 const char *Exponent = s;
832 s++;
833 saw_exponent = true;
834 if (*s == '+' || *s == '-') s++; // sign
835 const char *first_non_digit = SkipDigits(s);
Richard Smithb1cba3e2016-02-09 22:34:35 +0000836 if (!containsDigits(s, first_non_digit)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000837 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
838 diag::err_exponent_has_no_digits);
839 hadError = true;
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000840 return;
Chris Lattner6016a512008-06-30 06:39:54 +0000841 }
Richard Smith70ee92f2014-04-22 23:50:25 +0000842 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000843 s = first_non_digit;
Mike Stump11289f42009-09-09 15:08:12 +0000844
David Blaikiebbafb8a2012-03-11 07:00:24 +0000845 if (!PP.getLangOpts().HexFloats)
Richard Smith560a3572016-03-04 22:32:06 +0000846 PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
847 ? diag::ext_hex_literal_invalid
848 : diag::ext_hex_constant_invalid);
849 else if (PP.getLangOpts().CPlusPlus1z)
850 PP.Diag(TokLoc, diag::warn_cxx1z_hex_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000851 } else if (saw_period) {
Richard Smith560a3572016-03-04 22:32:06 +0000852 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
853 diag::err_hex_constant_requires)
854 << PP.getLangOpts().CPlusPlus << 0;
Chris Lattner59acca52008-11-22 07:23:31 +0000855 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000856 }
857 return;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattner6016a512008-06-30 06:39:54 +0000860 // Handle simple binary numbers 0b01010
Benjamin Kramer86710282015-03-29 14:11:37 +0000861 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
Richard Smithc5c27f22013-04-19 20:47:20 +0000862 // 0b101010 is a C++1y / GCC extension.
863 PP.Diag(TokLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000864 PP.getLangOpts().CPlusPlus14
Richard Smithc5c27f22013-04-19 20:47:20 +0000865 ? diag::warn_cxx11_compat_binary_literal
866 : PP.getLangOpts().CPlusPlus
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000867 ? diag::ext_binary_literal_cxx14
Richard Smithc5c27f22013-04-19 20:47:20 +0000868 : diag::ext_binary_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000869 ++s;
Benjamin Kramer86710282015-03-29 14:11:37 +0000870 assert(s < ThisTokEnd && "didn't maximally munch?");
Chris Lattner6016a512008-06-30 06:39:54 +0000871 radix = 2;
872 DigitsBegin = s;
873 s = SkipBinaryDigits(s);
874 if (s == ThisTokEnd) {
875 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000876 } else if (isHexDigit(*s)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000877 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Craig Topper7f5ff212015-11-14 02:09:55 +0000878 diag::err_invalid_digit) << StringRef(s, 1) << 2;
Chris Lattner59acca52008-11-22 07:23:31 +0000879 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000880 }
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000881 // Other suffixes will be diagnosed by the caller.
Chris Lattner6016a512008-06-30 06:39:54 +0000882 return;
883 }
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattner6016a512008-06-30 06:39:54 +0000885 // For now, the radix is set to 8. If we discover that we have a
886 // floating point constant, the radix will change to 10. Octal floating
Mike Stump11289f42009-09-09 15:08:12 +0000887 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner6016a512008-06-30 06:39:54 +0000888 radix = 8;
889 DigitsBegin = s;
890 s = SkipOctalDigits(s);
891 if (s == ThisTokEnd)
892 return; // Done, simple octal number like 01234
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000894 // If we have some other non-octal digit that *is* a decimal digit, see if
895 // this is part of a floating point number like 094.123 or 09e1.
Jordan Rosea7d03842013-02-08 22:30:41 +0000896 if (isDigit(*s)) {
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000897 const char *EndDecimal = SkipDigits(s);
898 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
899 s = EndDecimal;
900 radix = 10;
901 }
902 }
Mike Stump11289f42009-09-09 15:08:12 +0000903
Craig Topper3efc7c02016-01-28 05:22:54 +0000904 ParseDecimalOrOctalCommon(TokLoc);
Chris Lattner6016a512008-06-30 06:39:54 +0000905}
906
Jordan Rosede584de2012-09-25 22:32:51 +0000907static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000908 switch (Radix) {
909 case 2:
910 return NumDigits <= 64;
911 case 8:
912 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
913 case 10:
914 return NumDigits <= 19; // floor(log10(2^64))
915 case 16:
916 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
917 default:
918 llvm_unreachable("impossible Radix");
919 }
920}
Chris Lattner6016a512008-06-30 06:39:54 +0000921
Chris Lattner5b743d32007-04-04 05:52:58 +0000922/// GetIntegerValue - Convert this numeric literal value to an APInt that
Chris Lattner871b4e12007-04-04 06:36:34 +0000923/// matches Val's input width. If there is an overflow, set Val to the low bits
924/// of the result and return true. Otherwise, return false.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000925bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000926 // Fast path: Compute a conservative bound on the maximum number of
927 // bits per digit in this radix. If we can't possibly overflow a
928 // uint64 based on that bound then do the simple conversion to
929 // integer. This avoids the expensive overflow checking below, and
930 // handles the common cases that matter (small decimal integers and
931 // hex/octal values which don't overflow).
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000932 const unsigned NumDigits = SuffixBegin - DigitsBegin;
Jordan Rosede584de2012-09-25 22:32:51 +0000933 if (alwaysFitsInto64Bits(radix, NumDigits)) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000934 uint64_t N = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000935 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
Richard Smithfde94852013-09-26 03:33:06 +0000936 if (!isDigitSeparator(*Ptr))
937 N = N * radix + llvm::hexDigitValue(*Ptr);
Daniel Dunbarbe947082008-10-16 07:32:01 +0000938
939 // This will truncate the value to Val's input width. Simply check
940 // for overflow by comparing.
941 Val = N;
942 return Val.getZExtValue() != N;
943 }
944
Chris Lattner5b743d32007-04-04 05:52:58 +0000945 Val = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000946 const char *Ptr = DigitsBegin;
Chris Lattner5b743d32007-04-04 05:52:58 +0000947
Chris Lattner23b7eb62007-06-15 23:05:46 +0000948 llvm::APInt RadixVal(Val.getBitWidth(), radix);
949 llvm::APInt CharVal(Val.getBitWidth(), 0);
950 llvm::APInt OldVal = Val;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner871b4e12007-04-04 06:36:34 +0000952 bool OverflowOccurred = false;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000953 while (Ptr < SuffixBegin) {
Richard Smithfde94852013-09-26 03:33:06 +0000954 if (isDigitSeparator(*Ptr)) {
955 ++Ptr;
956 continue;
957 }
958
Jordan Rose78ed86a2013-01-18 22:33:58 +0000959 unsigned C = llvm::hexDigitValue(*Ptr++);
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chris Lattner5b743d32007-04-04 05:52:58 +0000961 // If this letter is out of bound for this radix, reject it.
Chris Lattner531efa42007-04-04 06:49:26 +0000962 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump11289f42009-09-09 15:08:12 +0000963
Chris Lattner5b743d32007-04-04 05:52:58 +0000964 CharVal = C;
Mike Stump11289f42009-09-09 15:08:12 +0000965
Chris Lattner871b4e12007-04-04 06:36:34 +0000966 // Add the digit to the value in the appropriate radix. If adding in digits
967 // made the value smaller, then this overflowed.
Chris Lattner5b743d32007-04-04 05:52:58 +0000968 OldVal = Val;
Chris Lattner871b4e12007-04-04 06:36:34 +0000969
970 // Multiply by radix, did overflow occur on the multiply?
Chris Lattner5b743d32007-04-04 05:52:58 +0000971 Val *= RadixVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000972 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
973
Chris Lattner871b4e12007-04-04 06:36:34 +0000974 // Add value, did overflow occur on the value?
Daniel Dunbarb1f64422008-10-16 06:39:30 +0000975 // (a + b) ult b <=> overflow
Chris Lattner5b743d32007-04-04 05:52:58 +0000976 Val += CharVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000977 OverflowOccurred |= Val.ult(CharVal);
Chris Lattner5b743d32007-04-04 05:52:58 +0000978 }
Chris Lattner871b4e12007-04-04 06:36:34 +0000979 return OverflowOccurred;
Chris Lattner5b743d32007-04-04 05:52:58 +0000980}
981
John McCall53b93a02009-12-24 09:08:04 +0000982llvm::APFloat::opStatus
983NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenekfbb08bc2007-11-26 23:12:30 +0000984 using llvm::APFloat;
Mike Stump11289f42009-09-09 15:08:12 +0000985
Erick Tryzelaarb9073112009-08-16 23:36:28 +0000986 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
Richard Smithfde94852013-09-26 03:33:06 +0000987
988 llvm::SmallString<16> Buffer;
989 StringRef Str(ThisTokBegin, n);
990 if (Str.find('\'') != StringRef::npos) {
991 Buffer.reserve(n);
992 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
993 &isDigitSeparator);
994 Str = Buffer;
995 }
996
997 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
Steve Naroff97b9e912007-07-09 23:53:58 +0000998}
Chris Lattner5b743d32007-04-04 05:52:58 +0000999
James Dennett1cc22032012-06-17 03:34:42 +00001000/// \verbatim
Richard Smithe18f0fa2012-03-05 04:02:15 +00001001/// user-defined-character-literal: [C++11 lex.ext]
1002/// character-literal ud-suffix
1003/// ud-suffix:
1004/// identifier
1005/// character-literal: [C++11 lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +00001006/// ' c-char-sequence '
1007/// u' c-char-sequence '
1008/// U' c-char-sequence '
1009/// L' c-char-sequence '
Aaron Ballman9a17c852016-01-07 20:59:26 +00001010/// u8' c-char-sequence ' [C++1z lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +00001011/// c-char-sequence:
1012/// c-char
1013/// c-char-sequence c-char
1014/// c-char:
1015/// any member of the source character set except the single-quote ',
1016/// backslash \, or new-line character
1017/// escape-sequence
1018/// universal-character-name
Richard Smithe18f0fa2012-03-05 04:02:15 +00001019/// escape-sequence:
Craig Topper54edcca2011-08-11 04:06:15 +00001020/// simple-escape-sequence
1021/// octal-escape-sequence
1022/// hexadecimal-escape-sequence
1023/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001024/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001025/// octal-escape-sequence:
1026/// \ octal-digit
1027/// \ octal-digit octal-digit
1028/// \ octal-digit octal-digit octal-digit
1029/// hexadecimal-escape-sequence:
1030/// \x hexadecimal-digit
1031/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smithe18f0fa2012-03-05 04:02:15 +00001032/// universal-character-name: [C++11 lex.charset]
Craig Topper54edcca2011-08-11 04:06:15 +00001033/// \u hex-quad
1034/// \U hex-quad hex-quad
1035/// hex-quad:
1036/// hex-digit hex-digit hex-digit hex-digit
James Dennett1cc22032012-06-17 03:34:42 +00001037/// \endverbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001038///
Chris Lattner2f5add62007-04-05 06:57:15 +00001039CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001040 SourceLocation Loc, Preprocessor &PP,
1041 tok::TokenKind kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001042 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Chris Lattner2f5add62007-04-05 06:57:15 +00001043 HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001044
Douglas Gregorfb65e592011-07-27 05:40:30 +00001045 Kind = kind;
1046
Richard Smith2a70e652012-03-09 22:27:51 +00001047 const char *TokBegin = begin;
1048
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001049 // Skip over wide character determinant.
Richard Smith3e3a7052014-11-08 06:08:42 +00001050 if (Kind != tok::char_constant)
Douglas Gregorfb65e592011-07-27 05:40:30 +00001051 ++begin;
Richard Smith3e3a7052014-11-08 06:08:42 +00001052 if (Kind == tok::utf8_char_constant)
1053 ++begin;
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chris Lattner2f5add62007-04-05 06:57:15 +00001055 // Skip over the entry quote.
1056 assert(begin[0] == '\'' && "Invalid token lexed");
1057 ++begin;
1058
Richard Smithe18f0fa2012-03-05 04:02:15 +00001059 // Remove an optional ud-suffix.
1060 if (end[-1] != '\'') {
1061 const char *UDSuffixEnd = end;
1062 do {
1063 --end;
1064 } while (end[-1] != '\'');
Richard Smith8b7258b2014-02-17 21:52:30 +00001065 // FIXME: Don't bother with this if !tok.hasUCN().
1066 expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
Richard Smith2a70e652012-03-09 22:27:51 +00001067 UDSuffixOffset = end - TokBegin;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001068 }
1069
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001070 // Trim the ending quote.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001071 assert(end != begin && "Invalid token lexed");
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001072 --end;
1073
Mike Stump11289f42009-09-09 15:08:12 +00001074 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattner57540c52011-04-15 05:22:18 +00001075 // up to 64-bits.
Chris Lattner2f5add62007-04-05 06:57:15 +00001076 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner37e05872008-03-05 18:54:05 +00001077 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner2f5add62007-04-05 06:57:15 +00001078 "Assumes char is 8 bits");
Chris Lattner8577f622009-04-28 21:51:46 +00001079 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1080 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1081 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1082 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1083 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001084
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001085 SmallVector<uint32_t, 4> codepoint_buffer;
1086 codepoint_buffer.resize(end - begin);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001087 uint32_t *buffer_begin = &codepoint_buffer.front();
1088 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump11289f42009-09-09 15:08:12 +00001089
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001090 // Unicode escapes representing characters that cannot be correctly
1091 // represented in a single code unit are disallowed in character literals
1092 // by this implementation.
1093 uint32_t largest_character_for_kind;
1094 if (tok::wide_char_constant == Kind) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001095 largest_character_for_kind =
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001096 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
Richard Smith3e3a7052014-11-08 06:08:42 +00001097 } else if (tok::utf8_char_constant == Kind) {
1098 largest_character_for_kind = 0x7F;
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001099 } else if (tok::utf16_char_constant == Kind) {
1100 largest_character_for_kind = 0xFFFF;
1101 } else if (tok::utf32_char_constant == Kind) {
1102 largest_character_for_kind = 0x10FFFF;
1103 } else {
1104 largest_character_for_kind = 0x7Fu;
Chris Lattner8577f622009-04-28 21:51:46 +00001105 }
1106
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001107 while (begin != end) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001108 // Is this a span of non-escape characters?
1109 if (begin[0] != '\\') {
1110 char const *start = begin;
1111 do {
1112 ++begin;
1113 } while (begin != end && *begin != '\\');
1114
Eli Friedman94363522012-02-11 05:08:10 +00001115 char const *tmp_in_start = start;
1116 uint32_t *tmp_out_start = buffer_begin;
Justin Lebar90910552016-09-30 00:38:45 +00001117 llvm::ConversionResult res =
1118 llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
1119 reinterpret_cast<llvm::UTF8 const *>(begin),
1120 &buffer_begin, buffer_end, llvm::strictConversion);
1121 if (res != llvm::conversionOK) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001122 // If we see bad encoding for unprefixed character literals, warn and
1123 // simply copy the byte values, for compatibility with gcc and
Eli Friedman94363522012-02-11 05:08:10 +00001124 // older versions of clang.
1125 bool NoErrorOnBadEncoding = isAscii();
1126 unsigned Msg = diag::err_bad_character_encoding;
1127 if (NoErrorOnBadEncoding)
1128 Msg = diag::warn_bad_character_encoding;
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001129 PP.Diag(Loc, Msg);
Eli Friedman94363522012-02-11 05:08:10 +00001130 if (NoErrorOnBadEncoding) {
1131 start = tmp_in_start;
1132 buffer_begin = tmp_out_start;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001133 for (; start != begin; ++start, ++buffer_begin)
Eli Friedman94363522012-02-11 05:08:10 +00001134 *buffer_begin = static_cast<uint8_t>(*start);
1135 } else {
1136 HadError = true;
1137 }
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001138 } else {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001139 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
Eli Friedman94363522012-02-11 05:08:10 +00001140 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001141 HadError = true;
1142 PP.Diag(Loc, diag::err_character_too_large);
1143 }
1144 }
1145 }
1146
1147 continue;
1148 }
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001149 // Is this a Universal Character Name escape?
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001150 if (begin[1] == 'u' || begin[1] == 'U') {
1151 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +00001152 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001153 FullSourceLoc(Loc, PP.getSourceManager()),
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001154 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001155 HadError = true;
1156 } else if (*buffer_begin > largest_character_for_kind) {
1157 HadError = true;
Richard Smith639b8d02012-09-08 07:16:20 +00001158 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001159 }
1160
1161 ++buffer_begin;
1162 continue;
1163 }
1164 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1165 uint64_t result =
Richard Smith639b8d02012-09-08 07:16:20 +00001166 ProcessCharEscape(TokBegin, begin, end, HadError,
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001167 FullSourceLoc(Loc,PP.getSourceManager()),
Richard Smith639b8d02012-09-08 07:16:20 +00001168 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001169 *buffer_begin++ = result;
1170 }
1171
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001172 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001173
Chris Lattner8577f622009-04-28 21:51:46 +00001174 if (NumCharsSoFar > 1) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001175 if (isWide())
Douglas Gregorfb65e592011-07-27 05:40:30 +00001176 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001177 else if (isAscii() && NumCharsSoFar == 4)
1178 PP.Diag(Loc, diag::ext_four_char_character_literal);
1179 else if (isAscii())
Chris Lattner8577f622009-04-28 21:51:46 +00001180 PP.Diag(Loc, diag::ext_multichar_character_literal);
1181 else
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001182 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedmand8cec572009-06-01 05:25:02 +00001183 IsMultiChar = true;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001184 } else {
Daniel Dunbara444cc22009-07-29 01:46:05 +00001185 IsMultiChar = false;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001186 }
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001187
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001188 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1189
1190 // Narrow character literals act as though their value is concatenated
1191 // in this implementation, but warn on overflow.
1192 bool multi_char_too_long = false;
1193 if (isAscii() && isMultiChar()) {
1194 LitVal = 0;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001195 for (size_t i = 0; i < NumCharsSoFar; ++i) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001196 // check for enough leading zeros to shift into
1197 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1198 LitVal <<= 8;
1199 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1200 }
1201 } else if (NumCharsSoFar > 0) {
1202 // otherwise just take the last character
1203 LitVal = buffer_begin[-1];
1204 }
1205
1206 if (!HadError && multi_char_too_long) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001207 PP.Diag(Loc, diag::warn_char_constant_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001208 }
1209
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001210 // Transfer the value from APInt to uint64_t
1211 Value = LitVal.getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner2f5add62007-04-05 06:57:15 +00001213 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1214 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1215 // character constants are not sign extended in the this implementation:
1216 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001217 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001218 PP.getLangOpts().CharIsSigned)
Chris Lattner2f5add62007-04-05 06:57:15 +00001219 Value = (signed char)Value;
1220}
1221
James Dennett99c193b2012-06-19 21:04:25 +00001222/// \verbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001223/// string-literal: [C++0x lex.string]
1224/// encoding-prefix " [s-char-sequence] "
1225/// encoding-prefix R raw-string
1226/// encoding-prefix:
1227/// u8
1228/// u
1229/// U
1230/// L
Steve Naroff4f88b312007-03-13 22:37:02 +00001231/// s-char-sequence:
1232/// s-char
1233/// s-char-sequence s-char
1234/// s-char:
Craig Topper54edcca2011-08-11 04:06:15 +00001235/// any member of the source character set except the double-quote ",
1236/// backslash \, or new-line character
1237/// escape-sequence
Steve Naroff4f88b312007-03-13 22:37:02 +00001238/// universal-character-name
Craig Topper54edcca2011-08-11 04:06:15 +00001239/// raw-string:
1240/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1241/// r-char-sequence:
1242/// r-char
1243/// r-char-sequence r-char
1244/// r-char:
1245/// any member of the source character set, except a right parenthesis )
1246/// followed by the initial d-char-sequence (which may be empty)
1247/// followed by a double quote ".
1248/// d-char-sequence:
1249/// d-char
1250/// d-char-sequence d-char
1251/// d-char:
1252/// any member of the basic source character set except:
1253/// space, the left parenthesis (, the right parenthesis ),
1254/// the backslash \, and the control characters representing horizontal
1255/// tab, vertical tab, form feed, and newline.
1256/// escape-sequence: [C++0x lex.ccon]
1257/// simple-escape-sequence
1258/// octal-escape-sequence
1259/// hexadecimal-escape-sequence
1260/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001261/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001262/// octal-escape-sequence:
1263/// \ octal-digit
1264/// \ octal-digit octal-digit
1265/// \ octal-digit octal-digit octal-digit
1266/// hexadecimal-escape-sequence:
1267/// \x hexadecimal-digit
1268/// hexadecimal-escape-sequence hexadecimal-digit
Steve Naroff4f88b312007-03-13 22:37:02 +00001269/// universal-character-name:
1270/// \u hex-quad
1271/// \U hex-quad hex-quad
1272/// hex-quad:
1273/// hex-digit hex-digit hex-digit hex-digit
James Dennett99c193b2012-06-19 21:04:25 +00001274/// \endverbatim
Chris Lattner2f5add62007-04-05 06:57:15 +00001275///
Steve Naroff4f88b312007-03-13 22:37:02 +00001276StringLiteralParser::
Craig Topper9d5583e2014-06-26 04:58:39 +00001277StringLiteralParser(ArrayRef<Token> StringToks,
Chris Lattner6bab4352010-11-17 07:21:13 +00001278 Preprocessor &PP, bool Complain)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001279 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Craig Topperd2d442c2014-05-17 23:10:59 +00001280 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001281 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1282 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Craig Topper9d5583e2014-06-26 04:58:39 +00001283 init(StringToks);
Chris Lattner6bab4352010-11-17 07:21:13 +00001284}
1285
Craig Topper9d5583e2014-06-26 04:58:39 +00001286void StringLiteralParser::init(ArrayRef<Token> StringToks){
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001287 // The literal token may have come from an invalid source location (e.g. due
1288 // to a PCH error), in which case the token length will be 0.
Craig Topper9d5583e2014-06-26 04:58:39 +00001289 if (StringToks.empty() || StringToks[0].getLength() < 2)
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001290 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001291
Steve Naroff4f88b312007-03-13 22:37:02 +00001292 // Scan all of the string portions, remember the max individual token length,
1293 // computing a bound on the concatenated string length, and see whether any
1294 // piece is a wide-string. If any of the string portions is a wide-string
1295 // literal, the result is a wide-string literal [C99 6.4.5p4].
Craig Topper9d5583e2014-06-26 04:58:39 +00001296 assert(!StringToks.empty() && "expected at least one token");
Alexis Hunt3b791862010-08-30 17:47:05 +00001297 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001298 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001299 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001300 Kind = StringToks[0].getKind();
Alexis Hunt3b791862010-08-30 17:47:05 +00001301
1302 hadError = false;
Chris Lattner2f5add62007-04-05 06:57:15 +00001303
1304 // Implement Translation Phase #6: concatenation of string literals
1305 /// (C99 5.1.1.2p1). The common case is only one string fragment.
Craig Topper9d5583e2014-06-26 04:58:39 +00001306 for (unsigned i = 1; i != StringToks.size(); ++i) {
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001307 if (StringToks[i].getLength() < 2)
1308 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001309
Steve Naroff4f88b312007-03-13 22:37:02 +00001310 // The string could be shorter than this if it needs cleaning, but this is a
1311 // reasonable bound, which is all we need.
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001312 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001313 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump11289f42009-09-09 15:08:12 +00001314
Steve Naroff4f88b312007-03-13 22:37:02 +00001315 // Remember maximum string piece length.
Alexis Hunt3b791862010-08-30 17:47:05 +00001316 if (StringToks[i].getLength() > MaxTokenLength)
1317 MaxTokenLength = StringToks[i].getLength();
Mike Stump11289f42009-09-09 15:08:12 +00001318
Douglas Gregorfb65e592011-07-27 05:40:30 +00001319 // Remember if we see any wide or utf-8/16/32 strings.
1320 // Also check for illegal concatenations.
1321 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1322 if (isAscii()) {
1323 Kind = StringToks[i].getKind();
1324 } else {
1325 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +00001326 Diags->Report(StringToks[i].getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001327 diag::err_unsupported_string_concat);
1328 hadError = true;
1329 }
1330 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001331 }
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001332
Steve Naroff4f88b312007-03-13 22:37:02 +00001333 // Include space for the null terminator.
1334 ++SizeBound;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Steve Naroff4f88b312007-03-13 22:37:02 +00001336 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregorfb65e592011-07-27 05:40:30 +00001338 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1339 CharByteWidth = getCharWidth(Kind, Target);
1340 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1341 CharByteWidth /= 8;
Mike Stump11289f42009-09-09 15:08:12 +00001342
Steve Naroff4f88b312007-03-13 22:37:02 +00001343 // The output buffer size needs to be large enough to hold wide characters.
1344 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001345 SizeBound *= CharByteWidth;
Mike Stump11289f42009-09-09 15:08:12 +00001346
Steve Naroff4f88b312007-03-13 22:37:02 +00001347 // Size the temporary buffer to hold the result string data.
1348 ResultBuf.resize(SizeBound);
Mike Stump11289f42009-09-09 15:08:12 +00001349
Steve Naroff4f88b312007-03-13 22:37:02 +00001350 // Likewise, but for each string piece.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001351 SmallString<512> TokenBuf;
Steve Naroff4f88b312007-03-13 22:37:02 +00001352 TokenBuf.resize(MaxTokenLength);
Mike Stump11289f42009-09-09 15:08:12 +00001353
Steve Naroff4f88b312007-03-13 22:37:02 +00001354 // Loop over all the strings, getting their spelling, and expanding them to
1355 // wide strings as appropriate.
1356 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump11289f42009-09-09 15:08:12 +00001357
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001358 Pascal = false;
Mike Stump11289f42009-09-09 15:08:12 +00001359
Richard Smithe18f0fa2012-03-05 04:02:15 +00001360 SourceLocation UDSuffixTokLoc;
1361
Craig Topper9d5583e2014-06-26 04:58:39 +00001362 for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001363 const char *ThisTokBuf = &TokenBuf[0];
1364 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1365 // that ThisTokBuf points to a buffer that is big enough for the whole token
1366 // and 'spelled' tokens can only shrink.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001367 bool StringInvalid = false;
Chris Lattner6bab4352010-11-17 07:21:13 +00001368 unsigned ThisTokLen =
Chris Lattner39720112010-11-17 07:26:20 +00001369 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1370 &StringInvalid);
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001371 if (StringInvalid)
1372 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001373
Richard Smith2a70e652012-03-09 22:27:51 +00001374 const char *ThisTokBegin = ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001375 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1376
1377 // Remove an optional ud-suffix.
1378 if (ThisTokEnd[-1] != '"') {
1379 const char *UDSuffixEnd = ThisTokEnd;
1380 do {
1381 --ThisTokEnd;
1382 } while (ThisTokEnd[-1] != '"');
1383
1384 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1385
1386 if (UDSuffixBuf.empty()) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001387 if (StringToks[i].hasUCN())
1388 expandUCNs(UDSuffixBuf, UDSuffix);
1389 else
1390 UDSuffixBuf.assign(UDSuffix);
Richard Smith75b67d62012-03-08 01:34:56 +00001391 UDSuffixToken = i;
1392 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001393 UDSuffixTokLoc = StringToks[i].getLocation();
Richard Smith8b7258b2014-02-17 21:52:30 +00001394 } else {
1395 SmallString<32> ExpandedUDSuffix;
1396 if (StringToks[i].hasUCN()) {
1397 expandUCNs(ExpandedUDSuffix, UDSuffix);
1398 UDSuffix = ExpandedUDSuffix;
1399 }
1400
Richard Smithe18f0fa2012-03-05 04:02:15 +00001401 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1402 // result of a concatenation involving at least one user-defined-string-
1403 // literal, all the participating user-defined-string-literals shall
1404 // have the same ud-suffix.
David Blaikiedcb72d72014-03-09 05:18:27 +00001405 if (UDSuffixBuf != UDSuffix) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001406 if (Diags) {
1407 SourceLocation TokLoc = StringToks[i].getLocation();
1408 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1409 << UDSuffixBuf << UDSuffix
1410 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1411 << SourceRange(TokLoc, TokLoc);
1412 }
1413 hadError = true;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001414 }
Richard Smithe18f0fa2012-03-05 04:02:15 +00001415 }
1416 }
1417
1418 // Strip the end quote.
1419 --ThisTokEnd;
1420
Steve Naroff4f88b312007-03-13 22:37:02 +00001421 // TODO: Input character set mapping support.
Mike Stump11289f42009-09-09 15:08:12 +00001422
Craig Topper61147ed2011-08-08 06:10:39 +00001423 // Skip marker for wide or unicode strings.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001424 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Chris Lattnerc10adde2007-05-20 05:00:58 +00001425 ++ThisTokBuf;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001426 // Skip 8 of u8 marker for utf8 strings.
1427 if (ThisTokBuf[0] == '8')
1428 ++ThisTokBuf;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +00001429 }
Mike Stump11289f42009-09-09 15:08:12 +00001430
Craig Topper54edcca2011-08-11 04:06:15 +00001431 // Check for raw string
1432 if (ThisTokBuf[0] == 'R') {
1433 ThisTokBuf += 2; // skip R"
Mike Stump11289f42009-09-09 15:08:12 +00001434
Craig Topper54edcca2011-08-11 04:06:15 +00001435 const char *Prefix = ThisTokBuf;
1436 while (ThisTokBuf[0] != '(')
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001437 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001438 ++ThisTokBuf; // skip '('
Mike Stump11289f42009-09-09 15:08:12 +00001439
Richard Smith81292452012-03-08 21:59:28 +00001440 // Remove same number of characters from the end
1441 ThisTokEnd -= ThisTokBuf - Prefix;
1442 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper54edcca2011-08-11 04:06:15 +00001443
David Majnemer54bbae52015-09-23 16:04:47 +00001444 // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1445 // results in a new-line in the resulting execution string-literal.
1446 StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1447 while (!RemainingTokenSpan.empty()) {
1448 // Split the string literal on \r\n boundaries.
1449 size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1450 StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1451 StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1452
1453 // Copy everything before the \r\n sequence into the string literal.
1454 if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1455 hadError = true;
1456
1457 // Point into the \n inside the \r\n sequence and operate on the
1458 // remaining portion of the literal.
1459 RemainingTokenSpan = AfterCRLF.substr(1);
1460 }
Craig Topper54edcca2011-08-11 04:06:15 +00001461 } else {
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001462 if (ThisTokBuf[0] != '"') {
1463 // The file may have come from PCH and then changed after loading the
1464 // PCH; Fail gracefully.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001465 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001466 }
Craig Topper54edcca2011-08-11 04:06:15 +00001467 ++ThisTokBuf; // skip "
1468
1469 // Check if this is a pascal string
1470 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1471 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1472
1473 // If the \p sequence is found in the first token, we have a pascal string
1474 // Otherwise, if we already have a pascal string, ignore the first \p
1475 if (i == 0) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001476 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001477 Pascal = true;
1478 } else if (Pascal)
1479 ThisTokBuf += 2;
1480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
Craig Topper54edcca2011-08-11 04:06:15 +00001482 while (ThisTokBuf != ThisTokEnd) {
1483 // Is this a span of non-escape characters?
1484 if (ThisTokBuf[0] != '\\') {
1485 const char *InStart = ThisTokBuf;
1486 do {
1487 ++ThisTokBuf;
1488 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1489
1490 // Copy the character span over.
Richard Smith639b8d02012-09-08 07:16:20 +00001491 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1492 StringRef(InStart, ThisTokBuf - InStart)))
1493 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001494 continue;
Steve Naroff4f88b312007-03-13 22:37:02 +00001495 }
Craig Topper54edcca2011-08-11 04:06:15 +00001496 // Is this a Universal Character Name escape?
1497 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith2a70e652012-03-09 22:27:51 +00001498 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1499 ResultPtr, hadError,
1500 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper54edcca2011-08-11 04:06:15 +00001501 CharByteWidth, Diags, Features);
1502 continue;
1503 }
1504 // Otherwise, this is a non-UCN escape character. Process it.
1505 unsigned ResultChar =
Richard Smith639b8d02012-09-08 07:16:20 +00001506 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper54edcca2011-08-11 04:06:15 +00001507 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001508 CharByteWidth*8, Diags, Features);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Eli Friedmand1370792011-11-02 23:06:23 +00001510 if (CharByteWidth == 4) {
1511 // FIXME: Make the type of the result buffer correct instead of
1512 // using reinterpret_cast.
Justin Lebar90910552016-09-30 00:38:45 +00001513 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001514 *ResultWidePtr = ResultChar;
Eli Friedmand1370792011-11-02 23:06:23 +00001515 ResultPtr += 4;
1516 } else if (CharByteWidth == 2) {
1517 // FIXME: Make the type of the result buffer correct instead of
1518 // using reinterpret_cast.
Justin Lebar90910552016-09-30 00:38:45 +00001519 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001520 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmand1370792011-11-02 23:06:23 +00001521 ResultPtr += 2;
1522 } else {
1523 assert(CharByteWidth == 1 && "Unexpected char width");
1524 *ResultPtr++ = ResultChar & 0xFF;
1525 }
Craig Topper54edcca2011-08-11 04:06:15 +00001526 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001527 }
1528 }
Mike Stump11289f42009-09-09 15:08:12 +00001529
Chris Lattner8a24e582009-01-16 18:51:42 +00001530 if (Pascal) {
Eli Friedman20554702011-11-05 00:41:04 +00001531 if (CharByteWidth == 4) {
1532 // FIXME: Make the type of the result buffer correct instead of
1533 // using reinterpret_cast.
Justin Lebar90910552016-09-30 00:38:45 +00001534 llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
Eli Friedman20554702011-11-05 00:41:04 +00001535 ResultWidePtr[0] = GetNumStringChars() - 1;
1536 } else if (CharByteWidth == 2) {
1537 // FIXME: Make the type of the result buffer correct instead of
1538 // using reinterpret_cast.
Justin Lebar90910552016-09-30 00:38:45 +00001539 llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
Eli Friedman20554702011-11-05 00:41:04 +00001540 ResultWidePtr[0] = GetNumStringChars() - 1;
1541 } else {
1542 assert(CharByteWidth == 1 && "Unexpected char width");
1543 ResultBuf[0] = GetNumStringChars() - 1;
1544 }
Chris Lattner8a24e582009-01-16 18:51:42 +00001545
1546 // Verify that pascal strings aren't too large.
Chris Lattner6bab4352010-11-17 07:21:13 +00001547 if (GetStringLength() > 256) {
Richard Smith639b8d02012-09-08 07:16:20 +00001548 if (Diags)
Craig Topper9d5583e2014-06-26 04:58:39 +00001549 Diags->Report(StringToks.front().getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001550 diag::err_pascal_string_too_long)
Craig Topper9d5583e2014-06-26 04:58:39 +00001551 << SourceRange(StringToks.front().getLocation(),
1552 StringToks.back().getLocation());
Douglas Gregorfb65e592011-07-27 05:40:30 +00001553 hadError = true;
Eli Friedman1c3fb222009-04-01 03:17:08 +00001554 return;
1555 }
Chris Lattner6bab4352010-11-17 07:21:13 +00001556 } else if (Diags) {
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001557 // Complain if this string literal has too many characters.
Chris Lattner2be8aa92010-11-17 07:12:42 +00001558 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001559
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001560 if (GetNumStringChars() > MaxChars)
Craig Topper9d5583e2014-06-26 04:58:39 +00001561 Diags->Report(StringToks.front().getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001562 diag::ext_string_too_long)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001563 << GetNumStringChars() << MaxChars
Chris Lattner2be8aa92010-11-17 07:12:42 +00001564 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Craig Topper9d5583e2014-06-26 04:58:39 +00001565 << SourceRange(StringToks.front().getLocation(),
1566 StringToks.back().getLocation());
Chris Lattner8a24e582009-01-16 18:51:42 +00001567 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001568}
Chris Lattnerddb71912009-02-18 19:21:10 +00001569
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001570static const char *resyncUTF8(const char *Err, const char *End) {
1571 if (Err == End)
1572 return End;
Justin Lebar90910552016-09-30 00:38:45 +00001573 End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001574 while (++Err != End && (*Err & 0xC0) == 0x80)
1575 ;
1576 return Err;
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001577}
1578
Richard Smith639b8d02012-09-08 07:16:20 +00001579/// \brief This function copies from Fragment, which is a sequence of bytes
1580/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper54edcca2011-08-11 04:06:15 +00001581/// Performs widening for multi-byte characters.
Richard Smith639b8d02012-09-08 07:16:20 +00001582bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1583 const char *TokBegin,
1584 StringRef Fragment) {
Justin Lebar90910552016-09-30 00:38:45 +00001585 const llvm::UTF8 *ErrorPtrTmp;
Richard Smith639b8d02012-09-08 07:16:20 +00001586 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1587 return false;
Craig Topper54edcca2011-08-11 04:06:15 +00001588
Eli Friedman94363522012-02-11 05:08:10 +00001589 // If we see bad encoding for unprefixed string literals, warn and
1590 // simply copy the byte values, for compatibility with gcc and older
1591 // versions of clang.
1592 bool NoErrorOnBadEncoding = isAscii();
Richard Smith639b8d02012-09-08 07:16:20 +00001593 if (NoErrorOnBadEncoding) {
1594 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1595 ResultPtr += Fragment.size();
1596 }
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001597
Richard Smith639b8d02012-09-08 07:16:20 +00001598 if (Diags) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001599 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1600
1601 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1602 const DiagnosticBuilder &Builder =
1603 Diag(Diags, Features, SourceLoc, TokBegin,
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001604 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001605 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1606 : diag::err_bad_string_encoding);
1607
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001608 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001609 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1610
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001611 // Decode into a dummy buffer.
1612 SmallString<512> Dummy;
1613 Dummy.reserve(Fragment.size() * CharByteWidth);
1614 char *Ptr = Dummy.data();
1615
Alexander Kornienkod3b4e082014-05-22 19:56:11 +00001616 while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001617 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001618 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001619 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1620 ErrorPtr, NextStart);
1621 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1622 }
Richard Smith639b8d02012-09-08 07:16:20 +00001623 }
Eli Friedman94363522012-02-11 05:08:10 +00001624 return !NoErrorOnBadEncoding;
1625}
Craig Topper54edcca2011-08-11 04:06:15 +00001626
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001627void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1628 hadError = true;
1629 if (Diags)
1630 Diags->Report(Loc, diag::err_lexing_string);
1631}
1632
Chris Lattnerddb71912009-02-18 19:21:10 +00001633/// getOffsetOfStringByte - This function returns the offset of the
1634/// specified byte of the string data represented by Token. This handles
1635/// advancing over escape sequences in the string.
1636unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattnerbde1b812010-11-17 06:46:14 +00001637 unsigned ByteNo) const {
Chris Lattnerddb71912009-02-18 19:21:10 +00001638 // Get the spelling of the token.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001639 SmallString<32> SpellingBuffer;
Alexis Hunt3b791862010-08-30 17:47:05 +00001640 SpellingBuffer.resize(Tok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001641
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001642 bool StringInvalid = false;
Chris Lattnerddb71912009-02-18 19:21:10 +00001643 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattner39720112010-11-17 07:26:20 +00001644 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1645 &StringInvalid);
Chris Lattner7a02bfd2010-11-17 06:26:08 +00001646 if (StringInvalid)
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001647 return 0;
Chris Lattnerddb71912009-02-18 19:21:10 +00001648
Chris Lattnerddb71912009-02-18 19:21:10 +00001649 const char *SpellingStart = SpellingPtr;
1650 const char *SpellingEnd = SpellingPtr+TokLen;
1651
Richard Smith4060f772012-06-13 05:37:23 +00001652 // Handle UTF-8 strings just like narrow strings.
1653 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1654 SpellingPtr += 2;
1655
1656 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1657 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1658
1659 // For raw string literals, this is easy.
1660 if (SpellingPtr[0] == 'R') {
1661 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1662 // Skip 'R"'.
1663 SpellingPtr += 2;
1664 while (*SpellingPtr != '(') {
1665 ++SpellingPtr;
1666 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1667 }
1668 // Skip '('.
1669 ++SpellingPtr;
1670 return SpellingPtr - SpellingStart + ByteNo;
1671 }
1672
1673 // Skip over the leading quote
Chris Lattnerddb71912009-02-18 19:21:10 +00001674 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1675 ++SpellingPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattnerddb71912009-02-18 19:21:10 +00001677 // Skip over bytes until we find the offset we're looking for.
1678 while (ByteNo) {
1679 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnerddb71912009-02-18 19:21:10 +00001681 // Step over non-escapes simply.
1682 if (*SpellingPtr != '\\') {
1683 ++SpellingPtr;
1684 --ByteNo;
1685 continue;
1686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Chris Lattnerddb71912009-02-18 19:21:10 +00001688 // Otherwise, this is an escape character. Advance over it.
1689 bool HadError = false;
Richard Smith4060f772012-06-13 05:37:23 +00001690 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1691 const char *EscapePtr = SpellingPtr;
1692 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1693 1, Features, HadError);
1694 if (Len > ByteNo) {
1695 // ByteNo is somewhere within the escape sequence.
1696 SpellingPtr = EscapePtr;
1697 break;
1698 }
1699 ByteNo -= Len;
1700 } else {
Richard Smith639b8d02012-09-08 07:16:20 +00001701 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smith4060f772012-06-13 05:37:23 +00001702 FullSourceLoc(Tok.getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001703 CharByteWidth*8, Diags, Features);
Richard Smith4060f772012-06-13 05:37:23 +00001704 --ByteNo;
1705 }
Chris Lattnerddb71912009-02-18 19:21:10 +00001706 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattnerddb71912009-02-18 19:21:10 +00001707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Chris Lattnerddb71912009-02-18 19:21:10 +00001709 return SpellingPtr-SpellingStart;
1710}