blob: e65d2edbd32ec0aa8652d8afde7b6fd752d817df [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the NumericLiteralParser, CharLiteralParser, and
11// StringLiteralParser interfaces.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/LiteralSupport.h"
16#include "clang/Lex/Preprocessor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000017#include "clang/Lex/LexDiagnostic.h"
Chris Lattner136f93a2007-07-16 06:55:01 +000018#include "clang/Basic/TargetInfo.h"
Eli Friedmanf74a4582011-11-01 02:14:50 +000019#include "clang/Basic/ConvertUTF.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "llvm/ADT/StringExtras.h"
David Blaikie9fe8c742011-09-23 05:35:21 +000021#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
24/// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
25/// not valid.
26static int HexDigitValue(char C) {
27 if (C >= '0' && C <= '9') return C-'0';
28 if (C >= 'a' && C <= 'f') return C-'a'+10;
29 if (C >= 'A' && C <= 'F') return C-'A'+10;
30 return -1;
31}
32
Douglas Gregor5cee1192011-07-27 05:40:30 +000033static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
34 switch (kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +000035 default: llvm_unreachable("Unknown token type!");
Douglas Gregor5cee1192011-07-27 05:40:30 +000036 case tok::char_constant:
37 case tok::string_literal:
38 case tok::utf8_string_literal:
39 return Target.getCharWidth();
40 case tok::wide_char_constant:
41 case tok::wide_string_literal:
42 return Target.getWCharWidth();
43 case tok::utf16_char_constant:
44 case tok::utf16_string_literal:
45 return Target.getChar16Width();
46 case tok::utf32_char_constant:
47 case tok::utf32_string_literal:
48 return Target.getChar32Width();
49 }
50}
51
Richard Smithe5f05882012-09-08 07:16:20 +000052/// \brief Produce a diagnostic highlighting some portion of a literal.
53///
54/// Emits the diagnostic \p DiagID, highlighting the range of characters from
55/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
56/// a substring of a spelling buffer for the token beginning at \p TokBegin.
57static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
58 const LangOptions &Features, FullSourceLoc TokLoc,
59 const char *TokBegin, const char *TokRangeBegin,
60 const char *TokRangeEnd, unsigned DiagID) {
61 SourceLocation Begin =
62 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
63 TokLoc.getManager(), Features);
64 SourceLocation End =
65 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
66 TokLoc.getManager(), Features);
67 return Diags->Report(Begin, DiagID)
68 << CharSourceRange::getCharRange(Begin, End);
69}
70
Reid Spencer5f016e22007-07-11 17:01:13 +000071/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
72/// either a character or a string literal.
Richard Smithe5f05882012-09-08 07:16:20 +000073static unsigned ProcessCharEscape(const char *ThisTokBegin,
74 const char *&ThisTokBuf,
Reid Spencer5f016e22007-07-11 17:01:13 +000075 const char *ThisTokEnd, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +000076 FullSourceLoc Loc, unsigned CharWidth,
Richard Smithe5f05882012-09-08 07:16:20 +000077 DiagnosticsEngine *Diags,
78 const LangOptions &Features) {
79 const char *EscapeBegin = ThisTokBuf;
80
Reid Spencer5f016e22007-07-11 17:01:13 +000081 // Skip the '\' char.
82 ++ThisTokBuf;
83
84 // We know that this character can't be off the end of the buffer, because
85 // that would have been \", which would not have been the end of string.
86 unsigned ResultChar = *ThisTokBuf++;
87 switch (ResultChar) {
88 // These map to themselves.
89 case '\\': case '\'': case '"': case '?': break;
Mike Stump1eb44332009-09-09 15:08:12 +000090
Reid Spencer5f016e22007-07-11 17:01:13 +000091 // These have fixed mappings.
92 case 'a':
93 // TODO: K&R: the meaning of '\\a' is different in traditional C
94 ResultChar = 7;
95 break;
96 case 'b':
97 ResultChar = 8;
98 break;
99 case 'e':
Chris Lattner91f54ce2010-11-17 06:26:08 +0000100 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000101 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
102 diag::ext_nonstandard_escape) << "e";
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 ResultChar = 27;
104 break;
Eli Friedman3c548012009-06-10 01:32:39 +0000105 case 'E':
Chris Lattner91f54ce2010-11-17 06:26:08 +0000106 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000107 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
108 diag::ext_nonstandard_escape) << "E";
Eli Friedman3c548012009-06-10 01:32:39 +0000109 ResultChar = 27;
110 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 case 'f':
112 ResultChar = 12;
113 break;
114 case 'n':
115 ResultChar = 10;
116 break;
117 case 'r':
118 ResultChar = 13;
119 break;
120 case 't':
121 ResultChar = 9;
122 break;
123 case 'v':
124 ResultChar = 11;
125 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 case 'x': { // Hex escape.
127 ResultChar = 0;
128 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner91f54ce2010-11-17 06:26:08 +0000129 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000130 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
131 diag::err_hex_escape_no_digits);
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 HadError = 1;
133 break;
134 }
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 // Hex escapes are a maximal series of hex digits.
137 bool Overflow = false;
138 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
139 int CharVal = HexDigitValue(ThisTokBuf[0]);
140 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000141 // About to shift out a digit?
142 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 ResultChar <<= 4;
144 ResultChar |= CharVal;
145 }
146
147 // See if any bits will be truncated when evaluated as a character.
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
149 Overflow = true;
150 ResultChar &= ~0U >> (32-CharWidth);
151 }
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // Check for overflow.
Chris Lattner91f54ce2010-11-17 06:26:08 +0000154 if (Overflow && Diags) // Too many digits to fit in
Richard Smithe5f05882012-09-08 07:16:20 +0000155 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
156 diag::warn_hex_escape_too_large);
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 break;
158 }
159 case '0': case '1': case '2': case '3':
160 case '4': case '5': case '6': case '7': {
161 // Octal escapes.
162 --ThisTokBuf;
163 ResultChar = 0;
164
165 // Octal escapes are a series of octal digits with maximum length 3.
166 // "\0123" is a two digit sequence equal to "\012" "3".
167 unsigned NumDigits = 0;
168 do {
169 ResultChar <<= 3;
170 ResultChar |= *ThisTokBuf++ - '0';
171 ++NumDigits;
172 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
173 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 // Check for overflow. Reject '\777', but not L'\777'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner91f54ce2010-11-17 06:26:08 +0000177 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000178 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
179 diag::warn_octal_escape_too_large);
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 ResultChar &= ~0U >> (32-CharWidth);
181 }
182 break;
183 }
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 // Otherwise, these are not valid escapes.
186 case '(': case '{': case '[': case '%':
187 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner91f54ce2010-11-17 06:26:08 +0000188 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000189 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
190 diag::ext_nonstandard_escape)
191 << std::string(1, ResultChar);
Eli Friedmanf01fdff2009-04-28 00:51:18 +0000192 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 default:
Chris Lattner91f54ce2010-11-17 06:26:08 +0000194 if (Diags == 0)
Douglas Gregorb90f4b32010-05-26 05:35:51 +0000195 break;
Richard Smithe5f05882012-09-08 07:16:20 +0000196
Ted Kremenek23ef69d2010-12-03 00:09:56 +0000197 if (isgraph(ResultChar))
Richard Smithe5f05882012-09-08 07:16:20 +0000198 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
199 diag::ext_unknown_escape)
200 << std::string(1, ResultChar);
Chris Lattnerac92d822008-11-22 07:23:31 +0000201 else
Richard Smithe5f05882012-09-08 07:16:20 +0000202 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
203 diag::ext_unknown_escape)
204 << "x" + llvm::utohexstr(ResultChar);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 break;
206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 return ResultChar;
209}
210
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000211/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Weber59705ae2010-10-09 00:27:47 +0000212/// return the UTF32.
Richard Smith26b75c02012-03-09 22:27:51 +0000213static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
214 const char *ThisTokEnd,
Nico Weber59705ae2010-10-09 00:27:47 +0000215 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikied6471f72011-09-25 23:23:43 +0000216 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrellbe773522012-01-18 12:27:04 +0000217 const LangOptions &Features,
218 bool in_char_string_literal = false) {
Richard Smith26b75c02012-03-09 22:27:51 +0000219 const char *UcnBegin = ThisTokBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000221 // Skip the '\u' char's.
222 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000223
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000224 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner6c66f072010-11-17 06:46:14 +0000225 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000226 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
227 diag::err_ucn_escape_no_digits);
Nico Weber59705ae2010-10-09 00:27:47 +0000228 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000229 }
Nico Weber59705ae2010-10-09 00:27:47 +0000230 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000231 unsigned short UcnLenSave = UcnLen;
Nico Weber59705ae2010-10-09 00:27:47 +0000232 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000233 int CharVal = HexDigitValue(ThisTokBuf[0]);
234 if (CharVal == -1) break;
235 UcnVal <<= 4;
236 UcnVal |= CharVal;
237 }
238 // If we didn't consume the proper number of digits, there is a problem.
Nico Weber59705ae2010-10-09 00:27:47 +0000239 if (UcnLenSave) {
Richard Smithe5f05882012-09-08 07:16:20 +0000240 if (Diags)
241 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
242 diag::err_ucn_escape_incomplete);
Nico Weber59705ae2010-10-09 00:27:47 +0000243 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000244 }
Richard Smith26b75c02012-03-09 22:27:51 +0000245
Seth Cantrellbe773522012-01-18 12:27:04 +0000246 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith26b75c02012-03-09 22:27:51 +0000247 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
248 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattner6c66f072010-11-17 06:46:14 +0000249 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +0000250 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
251 diag::err_ucn_escape_invalid);
Nico Weber59705ae2010-10-09 00:27:47 +0000252 return false;
253 }
Richard Smith26b75c02012-03-09 22:27:51 +0000254
255 // C++11 allows UCNs that refer to control characters and basic source
256 // characters inside character and string literals
257 if (UcnVal < 0xa0 &&
258 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
259 bool IsError = (!Features.CPlusPlus0x || !in_char_string_literal);
260 if (Diags) {
Richard Smith26b75c02012-03-09 22:27:51 +0000261 char BasicSCSChar = UcnVal;
262 if (UcnVal >= 0x20 && UcnVal < 0x7f)
Richard Smithe5f05882012-09-08 07:16:20 +0000263 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
264 IsError ? diag::err_ucn_escape_basic_scs :
265 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
266 << StringRef(&BasicSCSChar, 1);
Richard Smith26b75c02012-03-09 22:27:51 +0000267 else
Richard Smithe5f05882012-09-08 07:16:20 +0000268 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
269 IsError ? diag::err_ucn_control_character :
270 diag::warn_cxx98_compat_literal_ucn_control_character);
Richard Smith26b75c02012-03-09 22:27:51 +0000271 }
272 if (IsError)
273 return false;
274 }
275
Richard Smithe5f05882012-09-08 07:16:20 +0000276 if (!Features.CPlusPlus && !Features.C99 && Diags)
277 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
278 diag::warn_ucn_not_valid_in_c89);
279
Nico Weber59705ae2010-10-09 00:27:47 +0000280 return true;
281}
282
Richard Smithdf9ef1b2012-06-13 05:37:23 +0000283/// MeasureUCNEscape - Determine the number of bytes within the resulting string
284/// which this UCN will occupy.
285static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
286 const char *ThisTokEnd, unsigned CharByteWidth,
287 const LangOptions &Features, bool &HadError) {
288 // UTF-32: 4 bytes per escape.
289 if (CharByteWidth == 4)
290 return 4;
291
292 uint32_t UcnVal = 0;
293 unsigned short UcnLen = 0;
294 FullSourceLoc Loc;
295
296 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
297 UcnLen, Loc, 0, Features, true)) {
298 HadError = true;
299 return 0;
300 }
301
302 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
303 if (CharByteWidth == 2)
304 return UcnVal <= 0xFFFF ? 2 : 4;
305
306 // UTF-8.
307 if (UcnVal < 0x80)
308 return 1;
309 if (UcnVal < 0x800)
310 return 2;
311 if (UcnVal < 0x10000)
312 return 3;
313 return 4;
314}
315
Nico Weber59705ae2010-10-09 00:27:47 +0000316/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
317/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
318/// StringLiteralParser. When we decide to implement UCN's for identifiers,
319/// we will likely rework our support for UCN's.
Richard Smith26b75c02012-03-09 22:27:51 +0000320static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
321 const char *ThisTokEnd,
Chris Lattnera95880d2010-11-17 07:12:42 +0000322 char *&ResultBuf, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000323 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikied6471f72011-09-25 23:23:43 +0000324 DiagnosticsEngine *Diags,
325 const LangOptions &Features) {
Nico Weber59705ae2010-10-09 00:27:47 +0000326 typedef uint32_t UTF32;
327 UTF32 UcnVal = 0;
328 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000329 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
330 Loc, Diags, Features, true)) {
Richard Smithdf9ef1b2012-06-13 05:37:23 +0000331 HadError = true;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000332 return;
333 }
Nico Weber59705ae2010-10-09 00:27:47 +0000334
Douglas Gregor5cee1192011-07-27 05:40:30 +0000335 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
336 "only character widths of 1, 2, or 4 bytes supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000337
Douglas Gregor5cee1192011-07-27 05:40:30 +0000338 (void)UcnLen;
339 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000340
Douglas Gregor5cee1192011-07-27 05:40:30 +0000341 if (CharByteWidth == 4) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000342 // FIXME: Make the type of the result buffer correct instead of
343 // using reinterpret_cast.
344 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
345 *ResultPtr = UcnVal;
346 ResultBuf += 4;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000347 return;
348 }
349
350 if (CharByteWidth == 2) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000351 // FIXME: Make the type of the result buffer correct instead of
352 // using reinterpret_cast.
353 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
354
Richard Smith59b26d82012-06-13 05:41:29 +0000355 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000356 *ResultPtr = UcnVal;
357 ResultBuf += 2;
Nico Webera0f15b02010-10-06 04:57:26 +0000358 return;
359 }
Nico Webera0f15b02010-10-06 04:57:26 +0000360
Eli Friedmancaf1f262011-11-02 23:06:23 +0000361 // Convert to UTF16.
Nico Webera0f15b02010-10-06 04:57:26 +0000362 UcnVal -= 0x10000;
Eli Friedmancaf1f262011-11-02 23:06:23 +0000363 *ResultPtr = 0xD800 + (UcnVal >> 10);
364 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
365 ResultBuf += 4;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000366 return;
367 }
Douglas Gregor5cee1192011-07-27 05:40:30 +0000368
369 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
370
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000371 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
372 // The conversion below was inspired by:
373 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump1eb44332009-09-09 15:08:12 +0000374 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000375 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000376
377 unsigned short bytesToWrite = 0;
378 if (UcnVal < (UTF32)0x80)
379 bytesToWrite = 1;
380 else if (UcnVal < (UTF32)0x800)
381 bytesToWrite = 2;
382 else if (UcnVal < (UTF32)0x10000)
383 bytesToWrite = 3;
384 else
385 bytesToWrite = 4;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000387 const unsigned byteMask = 0xBF;
388 const unsigned byteMark = 0x80;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000390 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000391 // into the first byte, depending on how many bytes follow.
Mike Stump1eb44332009-09-09 15:08:12 +0000392 static const UTF8 firstByteMark[5] = {
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000393 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000394 };
395 // Finally, we write the bytes into ResultBuf.
396 ResultBuf += bytesToWrite;
397 switch (bytesToWrite) { // note: everything falls through.
398 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
399 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
400 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
401 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
402 }
403 // Update the buffer.
404 ResultBuf += bytesToWrite;
405}
Reid Spencer5f016e22007-07-11 17:01:13 +0000406
407
408/// integer-constant: [C99 6.4.4.1]
409/// decimal-constant integer-suffix
410/// octal-constant integer-suffix
411/// hexadecimal-constant integer-suffix
Richard Smith49d51742012-03-08 21:59:28 +0000412/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smithb453ad32012-03-08 08:45:32 +0000413/// decimal-literal ud-suffix
414/// octal-literal ud-suffix
415/// hexadecimal-literal ud-suffix
Mike Stump1eb44332009-09-09 15:08:12 +0000416/// decimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000417/// nonzero-digit
418/// decimal-constant digit
Mike Stump1eb44332009-09-09 15:08:12 +0000419/// octal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000420/// 0
421/// octal-constant octal-digit
Mike Stump1eb44332009-09-09 15:08:12 +0000422/// hexadecimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000423/// hexadecimal-prefix hexadecimal-digit
424/// hexadecimal-constant hexadecimal-digit
425/// hexadecimal-prefix: one of
426/// 0x 0X
427/// integer-suffix:
428/// unsigned-suffix [long-suffix]
429/// unsigned-suffix [long-long-suffix]
430/// long-suffix [unsigned-suffix]
431/// long-long-suffix [unsigned-sufix]
432/// nonzero-digit:
433/// 1 2 3 4 5 6 7 8 9
434/// octal-digit:
435/// 0 1 2 3 4 5 6 7
436/// hexadecimal-digit:
437/// 0 1 2 3 4 5 6 7 8 9
438/// a b c d e f
439/// A B C D E F
440/// unsigned-suffix: one of
441/// u U
442/// long-suffix: one of
443/// l L
Mike Stump1eb44332009-09-09 15:08:12 +0000444/// long-long-suffix: one of
Reid Spencer5f016e22007-07-11 17:01:13 +0000445/// ll LL
446///
447/// floating-constant: [C99 6.4.4.2]
448/// TODO: add rules...
449///
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000450NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
451 SourceLocation TokLoc,
452 Preprocessor &PP)
453 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000455 // This routine assumes that the range begin/end matches the regex for integer
456 // and FP constants (specifically, the 'pp-number' regex), and assumes that
457 // the byte at "*end" is both valid and not part of the regex. Because of
458 // this, it doesn't have to check for 'overscan' in various places.
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000459 assert(!isalnum(*ThisTokEnd) && *ThisTokEnd != '.' && *ThisTokEnd != '_' &&
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000460 "Lexer didn't maximally munch?");
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000462 s = DigitsBegin = ThisTokBegin;
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 saw_exponent = false;
464 saw_period = false;
Richard Smithb453ad32012-03-08 08:45:32 +0000465 saw_ud_suffix = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 isLong = false;
467 isUnsigned = false;
468 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000469 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000470 isImaginary = false;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000471 isMicrosoftInteger = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 hadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000475 ParseNumberStartingWithZero(TokLoc);
476 if (hadError)
477 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 } else { // the first digit is non-zero
479 radix = 10;
480 s = SkipDigits(s);
481 if (s == ThisTokEnd) {
482 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000483 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000484 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000486 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 return;
488 } else if (*s == '.') {
489 s++;
490 saw_period = true;
491 s = SkipDigits(s);
Mike Stump1eb44332009-09-09 15:08:12 +0000492 }
Chris Lattner4411f462008-09-29 23:12:31 +0000493 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000494 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 s++;
496 saw_exponent = true;
497 if (*s == '+' || *s == '-') s++; // sign
498 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000499 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000501 } else {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000502 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000503 diag::err_exponent_has_no_digits);
504 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000505 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 }
507 }
508 }
509
510 SuffixBegin = s;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner506b8de2007-08-26 01:58:14 +0000512 // Parse the suffix. At this point we can classify whether we have an FP or
513 // integer constant.
514 bool isFPConstant = isFloatingLiteral();
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattner506b8de2007-08-26 01:58:14 +0000516 // Loop over all of the characters of the suffix. If we see something bad,
517 // we break out of the loop.
518 for (; s != ThisTokEnd; ++s) {
519 switch (*s) {
520 case 'f': // FP Suffix for "float"
521 case 'F':
522 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000523 if (isFloat || isLong) break; // FF, LF invalid.
524 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000525 continue; // Success.
526 case 'u':
527 case 'U':
528 if (isFPConstant) break; // Error for floating constant.
529 if (isUnsigned) break; // Cannot be repeated.
530 isUnsigned = true;
531 continue; // Success.
532 case 'l':
533 case 'L':
534 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000535 if (isFloat) break; // LF invalid.
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner506b8de2007-08-26 01:58:14 +0000537 // Check for long long. The L's need to be adjacent and the same case.
538 if (s+1 != ThisTokEnd && s[1] == s[0]) {
539 if (isFPConstant) break; // long long invalid for floats.
540 isLongLong = true;
541 ++s; // Eat both of them.
542 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000545 continue; // Success.
546 case 'i':
Chris Lattnerc6374152010-10-14 00:24:10 +0000547 case 'I':
David Blaikie4e4d0842012-03-11 07:00:24 +0000548 if (PP.getLangOpts().MicrosoftExt) {
Fariborz Jahaniana8be02b2010-01-22 21:36:53 +0000549 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000550
Steve Naroff0c29b222008-04-04 21:02:54 +0000551 // Allow i8, i16, i32, i64, and i128.
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000552 if (s + 1 != ThisTokEnd) {
553 switch (s[1]) {
554 case '8':
555 s += 2; // i8 suffix
556 isMicrosoftInteger = true;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000557 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000558 case '1':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000559 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000560 if (s[2] == '6') {
561 s += 3; // i16 suffix
562 isMicrosoftInteger = true;
563 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000564 else if (s[2] == '2') {
565 if (s + 3 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000566 if (s[3] == '8') {
567 s += 4; // i128 suffix
568 isMicrosoftInteger = true;
569 }
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000570 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000571 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000572 case '3':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000573 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000574 if (s[2] == '2') {
575 s += 3; // i32 suffix
576 isLong = true;
577 isMicrosoftInteger = true;
578 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000579 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000580 case '6':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000581 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000582 if (s[2] == '4') {
583 s += 3; // i64 suffix
584 isLongLong = true;
585 isMicrosoftInteger = true;
586 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000587 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000588 default:
589 break;
590 }
591 break;
Steve Naroff0c29b222008-04-04 21:02:54 +0000592 }
Steve Naroff0c29b222008-04-04 21:02:54 +0000593 }
594 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000595 case 'j':
596 case 'J':
597 if (isImaginary) break; // Cannot be repeated.
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000598 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Chris Lattner506b8de2007-08-26 01:58:14 +0000599 diag::ext_imaginary_constant);
600 isImaginary = true;
601 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 }
Richard Smithb453ad32012-03-08 08:45:32 +0000603 // If we reached here, there was an error or a ud-suffix.
Chris Lattner506b8de2007-08-26 01:58:14 +0000604 break;
605 }
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Chris Lattner506b8de2007-08-26 01:58:14 +0000607 if (s != ThisTokEnd) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000608 if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
Richard Smithb453ad32012-03-08 08:45:32 +0000609 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
610 // with an '_' are ill-formed.
611 saw_ud_suffix = true;
612 return;
613 }
614
615 // Report an error if there are any.
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000616 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000617 isFPConstant ? diag::err_invalid_suffix_float_constant :
618 diag::err_invalid_suffix_integer_constant)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000619 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattnerac92d822008-11-22 07:23:31 +0000620 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000621 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 }
623}
624
Chris Lattner368328c2008-06-30 06:39:54 +0000625/// ParseNumberStartingWithZero - This method is called when the first character
626/// of the number is found to be a zero. This means it is either an octal
627/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump1eb44332009-09-09 15:08:12 +0000628/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner368328c2008-06-30 06:39:54 +0000629/// radix etc.
630void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
631 assert(s[0] == '0' && "Invalid method call");
632 s++;
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner368328c2008-06-30 06:39:54 +0000634 // Handle a hex number like 0x1234.
635 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
636 s++;
637 radix = 16;
638 DigitsBegin = s;
639 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000640 bool noSignificand = (s == DigitsBegin);
Chris Lattner368328c2008-06-30 06:39:54 +0000641 if (s == ThisTokEnd) {
642 // Done.
643 } else if (*s == '.') {
644 s++;
645 saw_period = true;
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000646 const char *floatDigitsBegin = s;
Chris Lattner368328c2008-06-30 06:39:54 +0000647 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000648 noSignificand &= (floatDigitsBegin == s);
Chris Lattner368328c2008-06-30 06:39:54 +0000649 }
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000650
651 if (noSignificand) {
Dmitri Gribenkofc97ea22012-09-24 09:53:54 +0000652 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000653 diag::err_hexconstant_requires_digits);
654 hadError = true;
655 return;
656 }
657
Chris Lattner368328c2008-06-30 06:39:54 +0000658 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump1eb44332009-09-09 15:08:12 +0000659 // binary exponent is required.
Douglas Gregor1155c422011-08-30 22:40:35 +0000660 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000661 const char *Exponent = s;
662 s++;
663 saw_exponent = true;
664 if (*s == '+' || *s == '-') s++; // sign
665 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000666 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000667 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
668 diag::err_exponent_has_no_digits);
669 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000670 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000671 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000672 s = first_non_digit;
Mike Stump1eb44332009-09-09 15:08:12 +0000673
David Blaikie4e4d0842012-03-11 07:00:24 +0000674 if (!PP.getLangOpts().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000675 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000676 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000677 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
678 diag::err_hexconstant_requires_exponent);
679 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000680 }
681 return;
682 }
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Chris Lattner368328c2008-06-30 06:39:54 +0000684 // Handle simple binary numbers 0b01010
685 if (*s == 'b' || *s == 'B') {
686 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000687 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000688 ++s;
689 radix = 2;
690 DigitsBegin = s;
691 s = SkipBinaryDigits(s);
692 if (s == ThisTokEnd) {
693 // Done.
694 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000695 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000696 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000697 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000698 }
Chris Lattner413d3552008-06-30 06:44:49 +0000699 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000700 return;
701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattner368328c2008-06-30 06:39:54 +0000703 // For now, the radix is set to 8. If we discover that we have a
704 // floating point constant, the radix will change to 10. Octal floating
Mike Stump1eb44332009-09-09 15:08:12 +0000705 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner368328c2008-06-30 06:39:54 +0000706 radix = 8;
707 DigitsBegin = s;
708 s = SkipOctalDigits(s);
709 if (s == ThisTokEnd)
710 return; // Done, simple octal number like 01234
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattner413d3552008-06-30 06:44:49 +0000712 // If we have some other non-octal digit that *is* a decimal digit, see if
713 // this is part of a floating point number like 094.123 or 09e1.
714 if (isdigit(*s)) {
715 const char *EndDecimal = SkipDigits(s);
716 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
717 s = EndDecimal;
718 radix = 10;
719 }
720 }
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattner413d3552008-06-30 06:44:49 +0000722 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
723 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000724 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000725 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000726 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000727 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000728 return;
729 }
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Chris Lattner368328c2008-06-30 06:39:54 +0000731 if (*s == '.') {
732 s++;
733 radix = 10;
734 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000735 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000736 }
737 if (*s == 'e' || *s == 'E') { // exponent
738 const char *Exponent = s;
739 s++;
740 radix = 10;
741 saw_exponent = true;
742 if (*s == '+' || *s == '-') s++; // sign
743 const char *first_non_digit = SkipDigits(s);
744 if (first_non_digit != s) {
745 s = first_non_digit;
746 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000747 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000748 diag::err_exponent_has_no_digits);
749 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000750 return;
751 }
752 }
753}
754
755
Reid Spencer5f016e22007-07-11 17:01:13 +0000756/// GetIntegerValue - Convert this numeric literal value to an APInt that
757/// matches Val's input width. If there is an overflow, set Val to the low bits
758/// of the result and return true. Otherwise, return false.
759bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000760 // Fast path: Compute a conservative bound on the maximum number of
761 // bits per digit in this radix. If we can't possibly overflow a
762 // uint64 based on that bound then do the simple conversion to
763 // integer. This avoids the expensive overflow checking below, and
764 // handles the common cases that matter (small decimal integers and
765 // hex/octal values which don't overflow).
766 unsigned MaxBitsPerDigit = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000767 while ((1U << MaxBitsPerDigit) < radix)
Daniel Dunbara179be32008-10-16 07:32:01 +0000768 MaxBitsPerDigit += 1;
769 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
770 uint64_t N = 0;
771 for (s = DigitsBegin; s != SuffixBegin; ++s)
772 N = N*radix + HexDigitValue(*s);
773
774 // This will truncate the value to Val's input width. Simply check
775 // for overflow by comparing.
776 Val = N;
777 return Val.getZExtValue() != N;
778 }
779
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 Val = 0;
781 s = DigitsBegin;
782
783 llvm::APInt RadixVal(Val.getBitWidth(), radix);
784 llvm::APInt CharVal(Val.getBitWidth(), 0);
785 llvm::APInt OldVal = Val;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 bool OverflowOccurred = false;
788 while (s < SuffixBegin) {
789 unsigned C = HexDigitValue(*s++);
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 // If this letter is out of bound for this radix, reject it.
792 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 CharVal = C;
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 // Add the digit to the value in the appropriate radix. If adding in digits
797 // made the value smaller, then this overflowed.
798 OldVal = Val;
799
800 // Multiply by radix, did overflow occur on the multiply?
801 Val *= RadixVal;
802 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
803
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000805 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 OverflowOccurred |= Val.ult(CharVal);
808 }
809 return OverflowOccurred;
810}
811
John McCall94c939d2009-12-24 09:08:04 +0000812llvm::APFloat::opStatus
813NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenek427d5af2007-11-26 23:12:30 +0000814 using llvm::APFloat;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000816 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall94c939d2009-12-24 09:08:04 +0000817 return Result.convertFromString(StringRef(ThisTokBegin, n),
818 APFloat::rmNearestTiesToEven);
Reid Spencer5f016e22007-07-11 17:01:13 +0000819}
820
Reid Spencer5f016e22007-07-11 17:01:13 +0000821
James Dennett58f9ce12012-06-17 03:34:42 +0000822/// \verbatim
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000823/// user-defined-character-literal: [C++11 lex.ext]
824/// character-literal ud-suffix
825/// ud-suffix:
826/// identifier
827/// character-literal: [C++11 lex.ccon]
Craig Topper2fa4e862011-08-11 04:06:15 +0000828/// ' c-char-sequence '
829/// u' c-char-sequence '
830/// U' c-char-sequence '
831/// L' c-char-sequence '
832/// c-char-sequence:
833/// c-char
834/// c-char-sequence c-char
835/// c-char:
836/// any member of the source character set except the single-quote ',
837/// backslash \, or new-line character
838/// escape-sequence
839/// universal-character-name
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000840/// escape-sequence:
Craig Topper2fa4e862011-08-11 04:06:15 +0000841/// simple-escape-sequence
842/// octal-escape-sequence
843/// hexadecimal-escape-sequence
844/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +0000845/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +0000846/// octal-escape-sequence:
847/// \ octal-digit
848/// \ octal-digit octal-digit
849/// \ octal-digit octal-digit octal-digit
850/// hexadecimal-escape-sequence:
851/// \x hexadecimal-digit
852/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000853/// universal-character-name: [C++11 lex.charset]
Craig Topper2fa4e862011-08-11 04:06:15 +0000854/// \u hex-quad
855/// \U hex-quad hex-quad
856/// hex-quad:
857/// hex-digit hex-digit hex-digit hex-digit
James Dennett58f9ce12012-06-17 03:34:42 +0000858/// \endverbatim
Craig Topper2fa4e862011-08-11 04:06:15 +0000859///
Reid Spencer5f016e22007-07-11 17:01:13 +0000860CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000861 SourceLocation Loc, Preprocessor &PP,
862 tok::TokenKind kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000863 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Douglas Gregor5cee1192011-07-27 05:40:30 +0000866 Kind = kind;
867
Richard Smith26b75c02012-03-09 22:27:51 +0000868 const char *TokBegin = begin;
869
Seth Cantrellbe773522012-01-18 12:27:04 +0000870 // Skip over wide character determinant.
871 if (Kind != tok::char_constant) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000872 ++begin;
873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 // Skip over the entry quote.
876 assert(begin[0] == '\'' && "Invalid token lexed");
877 ++begin;
878
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000879 // Remove an optional ud-suffix.
880 if (end[-1] != '\'') {
881 const char *UDSuffixEnd = end;
882 do {
883 --end;
884 } while (end[-1] != '\'');
885 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith26b75c02012-03-09 22:27:51 +0000886 UDSuffixOffset = end - TokBegin;
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000887 }
888
Seth Cantrellbe773522012-01-18 12:27:04 +0000889 // Trim the ending quote.
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000890 assert(end != begin && "Invalid token lexed");
Seth Cantrellbe773522012-01-18 12:27:04 +0000891 --end;
892
Mike Stump1eb44332009-09-09 15:08:12 +0000893 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000894 // up to 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000896 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000898 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
899 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
900 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
901 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
902 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000903
Seth Cantrellbe773522012-01-18 12:27:04 +0000904 SmallVector<uint32_t,4> codepoint_buffer;
905 codepoint_buffer.resize(end-begin);
906 uint32_t *buffer_begin = &codepoint_buffer.front();
907 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Seth Cantrellbe773522012-01-18 12:27:04 +0000909 // Unicode escapes representing characters that cannot be correctly
910 // represented in a single code unit are disallowed in character literals
911 // by this implementation.
912 uint32_t largest_character_for_kind;
913 if (tok::wide_char_constant == Kind) {
914 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
915 } else if (tok::utf16_char_constant == Kind) {
916 largest_character_for_kind = 0xFFFF;
917 } else if (tok::utf32_char_constant == Kind) {
918 largest_character_for_kind = 0x10FFFF;
919 } else {
920 largest_character_for_kind = 0x7Fu;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000921 }
922
Seth Cantrellbe773522012-01-18 12:27:04 +0000923 while (begin!=end) {
924 // Is this a span of non-escape characters?
925 if (begin[0] != '\\') {
926 char const *start = begin;
927 do {
928 ++begin;
929 } while (begin != end && *begin != '\\');
930
Eli Friedman91359302012-02-11 05:08:10 +0000931 char const *tmp_in_start = start;
932 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrellbe773522012-01-18 12:27:04 +0000933 ConversionResult res =
934 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
935 reinterpret_cast<UTF8 const *>(begin),
936 &buffer_begin,buffer_end,strictConversion);
937 if (res!=conversionOK) {
Eli Friedman91359302012-02-11 05:08:10 +0000938 // If we see bad encoding for unprefixed character literals, warn and
939 // simply copy the byte values, for compatibility with gcc and
940 // older versions of clang.
941 bool NoErrorOnBadEncoding = isAscii();
942 unsigned Msg = diag::err_bad_character_encoding;
943 if (NoErrorOnBadEncoding)
944 Msg = diag::warn_bad_character_encoding;
945 PP.Diag(Loc, Msg);
946 if (NoErrorOnBadEncoding) {
947 start = tmp_in_start;
948 buffer_begin = tmp_out_start;
949 for ( ; start != begin; ++start, ++buffer_begin)
950 *buffer_begin = static_cast<uint8_t>(*start);
951 } else {
952 HadError = true;
953 }
Seth Cantrellbe773522012-01-18 12:27:04 +0000954 } else {
Eli Friedman91359302012-02-11 05:08:10 +0000955 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
956 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000957 HadError = true;
958 PP.Diag(Loc, diag::err_character_too_large);
959 }
960 }
961 }
962
963 continue;
964 }
965 // Is this a Universal Character Name excape?
966 if (begin[1] == 'u' || begin[1] == 'U') {
967 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000968 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrellbe773522012-01-18 12:27:04 +0000969 FullSourceLoc(Loc, PP.getSourceManager()),
David Blaikie4e4d0842012-03-11 07:00:24 +0000970 &PP.getDiagnostics(), PP.getLangOpts(),
Seth Cantrellbe773522012-01-18 12:27:04 +0000971 true))
972 {
973 HadError = true;
974 } else if (*buffer_begin > largest_character_for_kind) {
975 HadError = true;
Richard Smithe5f05882012-09-08 07:16:20 +0000976 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrellbe773522012-01-18 12:27:04 +0000977 }
978
979 ++buffer_begin;
980 continue;
981 }
982 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
983 uint64_t result =
Richard Smithe5f05882012-09-08 07:16:20 +0000984 ProcessCharEscape(TokBegin, begin, end, HadError,
985 FullSourceLoc(Loc,PP.getSourceManager()),
986 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrellbe773522012-01-18 12:27:04 +0000987 *buffer_begin++ = result;
988 }
989
990 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
991
Chris Lattnere3ad8812009-04-28 21:51:46 +0000992 if (NumCharsSoFar > 1) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000993 if (isWide())
Douglas Gregor5cee1192011-07-27 05:40:30 +0000994 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrellbe773522012-01-18 12:27:04 +0000995 else if (isAscii() && NumCharsSoFar == 4)
996 PP.Diag(Loc, diag::ext_four_char_character_literal);
997 else if (isAscii())
Chris Lattnere3ad8812009-04-28 21:51:46 +0000998 PP.Diag(Loc, diag::ext_multichar_character_literal);
999 else
Seth Cantrellbe773522012-01-18 12:27:04 +00001000 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +00001001 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +00001002 } else
1003 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +00001004
Seth Cantrellbe773522012-01-18 12:27:04 +00001005 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1006
1007 // Narrow character literals act as though their value is concatenated
1008 // in this implementation, but warn on overflow.
1009 bool multi_char_too_long = false;
1010 if (isAscii() && isMultiChar()) {
1011 LitVal = 0;
1012 for (size_t i=0;i<NumCharsSoFar;++i) {
1013 // check for enough leading zeros to shift into
1014 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1015 LitVal <<= 8;
1016 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1017 }
1018 } else if (NumCharsSoFar > 0) {
1019 // otherwise just take the last character
1020 LitVal = buffer_begin[-1];
1021 }
1022
1023 if (!HadError && multi_char_too_long) {
1024 PP.Diag(Loc,diag::warn_char_constant_too_large);
1025 }
1026
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +00001027 // Transfer the value from APInt to uint64_t
1028 Value = LitVal.getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1031 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1032 // character constants are not sign extended in the this implementation:
1033 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001034 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001035 PP.getLangOpts().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 Value = (signed char)Value;
1037}
1038
James Dennetta1263cf2012-06-19 21:04:25 +00001039/// \verbatim
Craig Topper2fa4e862011-08-11 04:06:15 +00001040/// string-literal: [C++0x lex.string]
1041/// encoding-prefix " [s-char-sequence] "
1042/// encoding-prefix R raw-string
1043/// encoding-prefix:
1044/// u8
1045/// u
1046/// U
1047/// L
Reid Spencer5f016e22007-07-11 17:01:13 +00001048/// s-char-sequence:
1049/// s-char
1050/// s-char-sequence s-char
1051/// s-char:
Craig Topper2fa4e862011-08-11 04:06:15 +00001052/// any member of the source character set except the double-quote ",
1053/// backslash \, or new-line character
1054/// escape-sequence
Reid Spencer5f016e22007-07-11 17:01:13 +00001055/// universal-character-name
Craig Topper2fa4e862011-08-11 04:06:15 +00001056/// raw-string:
1057/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1058/// r-char-sequence:
1059/// r-char
1060/// r-char-sequence r-char
1061/// r-char:
1062/// any member of the source character set, except a right parenthesis )
1063/// followed by the initial d-char-sequence (which may be empty)
1064/// followed by a double quote ".
1065/// d-char-sequence:
1066/// d-char
1067/// d-char-sequence d-char
1068/// d-char:
1069/// any member of the basic source character set except:
1070/// space, the left parenthesis (, the right parenthesis ),
1071/// the backslash \, and the control characters representing horizontal
1072/// tab, vertical tab, form feed, and newline.
1073/// escape-sequence: [C++0x lex.ccon]
1074/// simple-escape-sequence
1075/// octal-escape-sequence
1076/// hexadecimal-escape-sequence
1077/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +00001078/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +00001079/// octal-escape-sequence:
1080/// \ octal-digit
1081/// \ octal-digit octal-digit
1082/// \ octal-digit octal-digit octal-digit
1083/// hexadecimal-escape-sequence:
1084/// \x hexadecimal-digit
1085/// hexadecimal-escape-sequence hexadecimal-digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001086/// universal-character-name:
1087/// \u hex-quad
1088/// \U hex-quad hex-quad
1089/// hex-quad:
1090/// hex-digit hex-digit hex-digit hex-digit
James Dennetta1263cf2012-06-19 21:04:25 +00001091/// \endverbatim
Reid Spencer5f016e22007-07-11 17:01:13 +00001092///
1093StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +00001094StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner0833dd02010-11-17 07:21:13 +00001095 Preprocessor &PP, bool Complain)
David Blaikie4e4d0842012-03-11 07:00:24 +00001096 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001097 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001098 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1099 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner0833dd02010-11-17 07:21:13 +00001100 init(StringToks, NumStringToks);
1101}
1102
1103void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001104 // The literal token may have come from an invalid source location (e.g. due
1105 // to a PCH error), in which case the token length will be 0.
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001106 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1107 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001108
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Scan all of the string portions, remember the max individual token length,
1110 // computing a bound on the concatenated string length, and see whether any
1111 // piece is a wide-string. If any of the string portions is a wide-string
1112 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001113 assert(NumStringToks && "expected at least one token");
Sean Hunt6cf75022010-08-30 17:47:05 +00001114 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001115 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001116 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001117 Kind = StringToks[0].getKind();
Sean Hunt6cf75022010-08-30 17:47:05 +00001118
1119 hadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001120
1121 // Implement Translation Phase #6: concatenation of string literals
1122 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1123 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001124 if (StringToks[i].getLength() < 2)
1125 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001126
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 // The string could be shorter than this if it needs cleaning, but this is a
1128 // reasonable bound, which is all we need.
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001129 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001130 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 // Remember maximum string piece length.
Sean Hunt6cf75022010-08-30 17:47:05 +00001133 if (StringToks[i].getLength() > MaxTokenLength)
1134 MaxTokenLength = StringToks[i].getLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Douglas Gregor5cee1192011-07-27 05:40:30 +00001136 // Remember if we see any wide or utf-8/16/32 strings.
1137 // Also check for illegal concatenations.
1138 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1139 if (isAscii()) {
1140 Kind = StringToks[i].getKind();
1141 } else {
1142 if (Diags)
Richard Smithe5f05882012-09-08 07:16:20 +00001143 Diags->Report(StringToks[i].getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001144 diag::err_unsupported_string_concat);
1145 hadError = true;
1146 }
1147 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 // Include space for the null terminator.
1151 ++SizeBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Douglas Gregor5cee1192011-07-27 05:40:30 +00001155 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1156 CharByteWidth = getCharWidth(Kind, Target);
1157 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1158 CharByteWidth /= 8;
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 // The output buffer size needs to be large enough to hold wide characters.
1161 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001162 SizeBound *= CharByteWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 // Size the temporary buffer to hold the result string data.
1165 ResultBuf.resize(SizeBound);
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // Likewise, but for each string piece.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001168 SmallString<512> TokenBuf;
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 TokenBuf.resize(MaxTokenLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 // Loop over all the strings, getting their spelling, and expanding them to
1172 // wide strings as appropriate.
1173 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Anders Carlssonee98ac52007-10-15 02:50:23 +00001175 Pascal = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001177 SourceLocation UDSuffixTokLoc;
1178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1180 const char *ThisTokBuf = &TokenBuf[0];
1181 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1182 // that ThisTokBuf points to a buffer that is big enough for the whole token
1183 // and 'spelled' tokens can only shrink.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001184 bool StringInvalid = false;
Chris Lattner0833dd02010-11-17 07:21:13 +00001185 unsigned ThisTokLen =
Chris Lattnerb0607272010-11-17 07:26:20 +00001186 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1187 &StringInvalid);
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001188 if (StringInvalid)
1189 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor50f6af72010-03-16 05:20:39 +00001190
Richard Smith26b75c02012-03-09 22:27:51 +00001191 const char *ThisTokBegin = ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001192 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1193
1194 // Remove an optional ud-suffix.
1195 if (ThisTokEnd[-1] != '"') {
1196 const char *UDSuffixEnd = ThisTokEnd;
1197 do {
1198 --ThisTokEnd;
1199 } while (ThisTokEnd[-1] != '"');
1200
1201 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1202
1203 if (UDSuffixBuf.empty()) {
1204 UDSuffixBuf.assign(UDSuffix);
Richard Smithdd66be72012-03-08 01:34:56 +00001205 UDSuffixToken = i;
1206 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001207 UDSuffixTokLoc = StringToks[i].getLocation();
1208 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1209 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1210 // result of a concatenation involving at least one user-defined-string-
1211 // literal, all the participating user-defined-string-literals shall
1212 // have the same ud-suffix.
1213 if (Diags) {
1214 SourceLocation TokLoc = StringToks[i].getLocation();
1215 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1216 << UDSuffixBuf << UDSuffix
1217 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1218 << SourceRange(TokLoc, TokLoc);
1219 }
1220 hadError = true;
1221 }
1222 }
1223
1224 // Strip the end quote.
1225 --ThisTokEnd;
1226
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 // TODO: Input character set mapping support.
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Craig Topper1661d712011-08-08 06:10:39 +00001229 // Skip marker for wide or unicode strings.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001230 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 ++ThisTokBuf;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001232 // Skip 8 of u8 marker for utf8 strings.
1233 if (ThisTokBuf[0] == '8')
1234 ++ThisTokBuf;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +00001235 }
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Craig Topper2fa4e862011-08-11 04:06:15 +00001237 // Check for raw string
1238 if (ThisTokBuf[0] == 'R') {
1239 ThisTokBuf += 2; // skip R"
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Craig Topper2fa4e862011-08-11 04:06:15 +00001241 const char *Prefix = ThisTokBuf;
1242 while (ThisTokBuf[0] != '(')
Anders Carlssonee98ac52007-10-15 02:50:23 +00001243 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001244 ++ThisTokBuf; // skip '('
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Richard Smith49d51742012-03-08 21:59:28 +00001246 // Remove same number of characters from the end
1247 ThisTokEnd -= ThisTokBuf - Prefix;
1248 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper2fa4e862011-08-11 04:06:15 +00001249
1250 // Copy the string over
Richard Smithe5f05882012-09-08 07:16:20 +00001251 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1252 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1253 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001254 } else {
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001255 if (ThisTokBuf[0] != '"') {
1256 // The file may have come from PCH and then changed after loading the
1257 // PCH; Fail gracefully.
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001258 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001259 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001260 ++ThisTokBuf; // skip "
1261
1262 // Check if this is a pascal string
1263 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1264 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1265
1266 // If the \p sequence is found in the first token, we have a pascal string
1267 // Otherwise, if we already have a pascal string, ignore the first \p
1268 if (i == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001270 Pascal = true;
1271 } else if (Pascal)
1272 ThisTokBuf += 2;
1273 }
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Craig Topper2fa4e862011-08-11 04:06:15 +00001275 while (ThisTokBuf != ThisTokEnd) {
1276 // Is this a span of non-escape characters?
1277 if (ThisTokBuf[0] != '\\') {
1278 const char *InStart = ThisTokBuf;
1279 do {
1280 ++ThisTokBuf;
1281 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1282
1283 // Copy the character span over.
Richard Smithe5f05882012-09-08 07:16:20 +00001284 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1285 StringRef(InStart, ThisTokBuf - InStart)))
1286 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001287 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001289 // Is this a Universal Character Name escape?
1290 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith26b75c02012-03-09 22:27:51 +00001291 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1292 ResultPtr, hadError,
1293 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper2fa4e862011-08-11 04:06:15 +00001294 CharByteWidth, Diags, Features);
1295 continue;
1296 }
1297 // Otherwise, this is a non-UCN escape character. Process it.
1298 unsigned ResultChar =
Richard Smithe5f05882012-09-08 07:16:20 +00001299 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper2fa4e862011-08-11 04:06:15 +00001300 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smithe5f05882012-09-08 07:16:20 +00001301 CharByteWidth*8, Diags, Features);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Eli Friedmancaf1f262011-11-02 23:06:23 +00001303 if (CharByteWidth == 4) {
1304 // FIXME: Make the type of the result buffer correct instead of
1305 // using reinterpret_cast.
1306 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001307 *ResultWidePtr = ResultChar;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001308 ResultPtr += 4;
1309 } else if (CharByteWidth == 2) {
1310 // FIXME: Make the type of the result buffer correct instead of
1311 // using reinterpret_cast.
1312 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001313 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001314 ResultPtr += 2;
1315 } else {
1316 assert(CharByteWidth == 1 && "Unexpected char width");
1317 *ResultPtr++ = ResultChar & 0xFF;
1318 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001319 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 }
1321 }
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001323 if (Pascal) {
Eli Friedman22508f42011-11-05 00:41:04 +00001324 if (CharByteWidth == 4) {
1325 // FIXME: Make the type of the result buffer correct instead of
1326 // using reinterpret_cast.
1327 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1328 ResultWidePtr[0] = GetNumStringChars() - 1;
1329 } else if (CharByteWidth == 2) {
1330 // FIXME: Make the type of the result buffer correct instead of
1331 // using reinterpret_cast.
1332 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1333 ResultWidePtr[0] = GetNumStringChars() - 1;
1334 } else {
1335 assert(CharByteWidth == 1 && "Unexpected char width");
1336 ResultBuf[0] = GetNumStringChars() - 1;
1337 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001338
1339 // Verify that pascal strings aren't too large.
Chris Lattner0833dd02010-11-17 07:21:13 +00001340 if (GetStringLength() > 256) {
Richard Smithe5f05882012-09-08 07:16:20 +00001341 if (Diags)
1342 Diags->Report(StringToks[0].getLocation(),
Chris Lattner0833dd02010-11-17 07:21:13 +00001343 diag::err_pascal_string_too_long)
1344 << SourceRange(StringToks[0].getLocation(),
1345 StringToks[NumStringToks-1].getLocation());
Douglas Gregor5cee1192011-07-27 05:40:30 +00001346 hadError = true;
Eli Friedman57d7dde2009-04-01 03:17:08 +00001347 return;
1348 }
Chris Lattner0833dd02010-11-17 07:21:13 +00001349 } else if (Diags) {
Douglas Gregor427c4922010-07-20 14:33:20 +00001350 // Complain if this string literal has too many characters.
Chris Lattnera95880d2010-11-17 07:12:42 +00001351 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Douglas Gregor427c4922010-07-20 14:33:20 +00001352
1353 if (GetNumStringChars() > MaxChars)
Richard Smithe5f05882012-09-08 07:16:20 +00001354 Diags->Report(StringToks[0].getLocation(),
Chris Lattner0833dd02010-11-17 07:21:13 +00001355 diag::ext_string_too_long)
Douglas Gregor427c4922010-07-20 14:33:20 +00001356 << GetNumStringChars() << MaxChars
Chris Lattnera95880d2010-11-17 07:12:42 +00001357 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregor427c4922010-07-20 14:33:20 +00001358 << SourceRange(StringToks[0].getLocation(),
1359 StringToks[NumStringToks-1].getLocation());
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001360 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001361}
Chris Lattner719e6152009-02-18 19:21:10 +00001362
Richard Smithe5f05882012-09-08 07:16:20 +00001363/// \brief This function copies from Fragment, which is a sequence of bytes
1364/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper2fa4e862011-08-11 04:06:15 +00001365/// Performs widening for multi-byte characters.
Richard Smithe5f05882012-09-08 07:16:20 +00001366bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1367 const char *TokBegin,
1368 StringRef Fragment) {
1369 const UTF8 *ErrorPtrTmp;
1370 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1371 return false;
1372 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Craig Topper2fa4e862011-08-11 04:06:15 +00001373
Eli Friedman91359302012-02-11 05:08:10 +00001374 // If we see bad encoding for unprefixed string literals, warn and
1375 // simply copy the byte values, for compatibility with gcc and older
1376 // versions of clang.
1377 bool NoErrorOnBadEncoding = isAscii();
Richard Smithe5f05882012-09-08 07:16:20 +00001378 if (NoErrorOnBadEncoding) {
1379 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1380 ResultPtr += Fragment.size();
1381 }
1382 if (Diags) {
1383 Diag(Diags, Features, FullSourceLoc(Tok.getLocation(), SM), TokBegin,
1384 ErrorPtr, ErrorPtr + std::min<unsigned>(getNumBytesForUTF8(*ErrorPtr),
1385 Fragment.end() - ErrorPtr),
1386 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1387 : diag::err_bad_string_encoding);
1388 }
Eli Friedman91359302012-02-11 05:08:10 +00001389 return !NoErrorOnBadEncoding;
1390}
Craig Topper2fa4e862011-08-11 04:06:15 +00001391
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001392void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1393 hadError = true;
1394 if (Diags)
1395 Diags->Report(Loc, diag::err_lexing_string);
1396}
1397
Chris Lattner719e6152009-02-18 19:21:10 +00001398/// getOffsetOfStringByte - This function returns the offset of the
1399/// specified byte of the string data represented by Token. This handles
1400/// advancing over escape sequences in the string.
1401unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattner6c66f072010-11-17 06:46:14 +00001402 unsigned ByteNo) const {
Chris Lattner719e6152009-02-18 19:21:10 +00001403 // Get the spelling of the token.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001404 SmallString<32> SpellingBuffer;
Sean Hunt6cf75022010-08-30 17:47:05 +00001405 SpellingBuffer.resize(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Douglas Gregor50f6af72010-03-16 05:20:39 +00001407 bool StringInvalid = false;
Chris Lattner719e6152009-02-18 19:21:10 +00001408 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattnerb0607272010-11-17 07:26:20 +00001409 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1410 &StringInvalid);
Chris Lattner91f54ce2010-11-17 06:26:08 +00001411 if (StringInvalid)
Douglas Gregor50f6af72010-03-16 05:20:39 +00001412 return 0;
Chris Lattner719e6152009-02-18 19:21:10 +00001413
Chris Lattner719e6152009-02-18 19:21:10 +00001414 const char *SpellingStart = SpellingPtr;
1415 const char *SpellingEnd = SpellingPtr+TokLen;
1416
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001417 // Handle UTF-8 strings just like narrow strings.
1418 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1419 SpellingPtr += 2;
1420
1421 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1422 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1423
1424 // For raw string literals, this is easy.
1425 if (SpellingPtr[0] == 'R') {
1426 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1427 // Skip 'R"'.
1428 SpellingPtr += 2;
1429 while (*SpellingPtr != '(') {
1430 ++SpellingPtr;
1431 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1432 }
1433 // Skip '('.
1434 ++SpellingPtr;
1435 return SpellingPtr - SpellingStart + ByteNo;
1436 }
1437
1438 // Skip over the leading quote
Chris Lattner719e6152009-02-18 19:21:10 +00001439 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1440 ++SpellingPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Chris Lattner719e6152009-02-18 19:21:10 +00001442 // Skip over bytes until we find the offset we're looking for.
1443 while (ByteNo) {
1444 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattner719e6152009-02-18 19:21:10 +00001446 // Step over non-escapes simply.
1447 if (*SpellingPtr != '\\') {
1448 ++SpellingPtr;
1449 --ByteNo;
1450 continue;
1451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Chris Lattner719e6152009-02-18 19:21:10 +00001453 // Otherwise, this is an escape character. Advance over it.
1454 bool HadError = false;
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001455 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1456 const char *EscapePtr = SpellingPtr;
1457 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1458 1, Features, HadError);
1459 if (Len > ByteNo) {
1460 // ByteNo is somewhere within the escape sequence.
1461 SpellingPtr = EscapePtr;
1462 break;
1463 }
1464 ByteNo -= Len;
1465 } else {
Richard Smithe5f05882012-09-08 07:16:20 +00001466 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001467 FullSourceLoc(Tok.getLocation(), SM),
Richard Smithe5f05882012-09-08 07:16:20 +00001468 CharByteWidth*8, Diags, Features);
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001469 --ByteNo;
1470 }
Chris Lattner719e6152009-02-18 19:21:10 +00001471 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattner719e6152009-02-18 19:21:10 +00001472 }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Chris Lattner719e6152009-02-18 19:21:10 +00001474 return SpellingPtr-SpellingStart;
1475}