blob: b2290b3187c6c43969a7a0c29fb5c40be9c4ddea [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
Reid Spencer5f016e22007-07-11 17:01:13 +000052/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
53/// either a character or a string literal.
54static unsigned ProcessCharEscape(const char *&ThisTokBuf,
55 const char *ThisTokEnd, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +000056 FullSourceLoc Loc, unsigned CharWidth,
David Blaikied6471f72011-09-25 23:23:43 +000057 DiagnosticsEngine *Diags) {
Reid Spencer5f016e22007-07-11 17:01:13 +000058 // Skip the '\' char.
59 ++ThisTokBuf;
60
61 // We know that this character can't be off the end of the buffer, because
62 // that would have been \", which would not have been the end of string.
63 unsigned ResultChar = *ThisTokBuf++;
64 switch (ResultChar) {
65 // These map to themselves.
66 case '\\': case '\'': case '"': case '?': break;
Mike Stump1eb44332009-09-09 15:08:12 +000067
Reid Spencer5f016e22007-07-11 17:01:13 +000068 // These have fixed mappings.
69 case 'a':
70 // TODO: K&R: the meaning of '\\a' is different in traditional C
71 ResultChar = 7;
72 break;
73 case 'b':
74 ResultChar = 8;
75 break;
76 case 'e':
Chris Lattner91f54ce2010-11-17 06:26:08 +000077 if (Diags)
78 Diags->Report(Loc, diag::ext_nonstandard_escape) << "e";
Reid Spencer5f016e22007-07-11 17:01:13 +000079 ResultChar = 27;
80 break;
Eli Friedman3c548012009-06-10 01:32:39 +000081 case 'E':
Chris Lattner91f54ce2010-11-17 06:26:08 +000082 if (Diags)
83 Diags->Report(Loc, diag::ext_nonstandard_escape) << "E";
Eli Friedman3c548012009-06-10 01:32:39 +000084 ResultChar = 27;
85 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000086 case 'f':
87 ResultChar = 12;
88 break;
89 case 'n':
90 ResultChar = 10;
91 break;
92 case 'r':
93 ResultChar = 13;
94 break;
95 case 't':
96 ResultChar = 9;
97 break;
98 case 'v':
99 ResultChar = 11;
100 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 case 'x': { // Hex escape.
102 ResultChar = 0;
103 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner91f54ce2010-11-17 06:26:08 +0000104 if (Diags)
105 Diags->Report(Loc, diag::err_hex_escape_no_digits);
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 HadError = 1;
107 break;
108 }
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 // Hex escapes are a maximal series of hex digits.
111 bool Overflow = false;
112 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
113 int CharVal = HexDigitValue(ThisTokBuf[0]);
114 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000115 // About to shift out a digit?
116 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 ResultChar <<= 4;
118 ResultChar |= CharVal;
119 }
120
121 // See if any bits will be truncated when evaluated as a character.
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
123 Overflow = true;
124 ResultChar &= ~0U >> (32-CharWidth);
125 }
Mike Stump1eb44332009-09-09 15:08:12 +0000126
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 // Check for overflow.
Chris Lattner91f54ce2010-11-17 06:26:08 +0000128 if (Overflow && Diags) // Too many digits to fit in
129 Diags->Report(Loc, diag::warn_hex_escape_too_large);
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 break;
131 }
132 case '0': case '1': case '2': case '3':
133 case '4': case '5': case '6': case '7': {
134 // Octal escapes.
135 --ThisTokBuf;
136 ResultChar = 0;
137
138 // Octal escapes are a series of octal digits with maximum length 3.
139 // "\0123" is a two digit sequence equal to "\012" "3".
140 unsigned NumDigits = 0;
141 do {
142 ResultChar <<= 3;
143 ResultChar |= *ThisTokBuf++ - '0';
144 ++NumDigits;
145 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
146 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 // Check for overflow. Reject '\777', but not L'\777'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner91f54ce2010-11-17 06:26:08 +0000150 if (Diags)
151 Diags->Report(Loc, diag::warn_octal_escape_too_large);
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 ResultChar &= ~0U >> (32-CharWidth);
153 }
154 break;
155 }
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 // Otherwise, these are not valid escapes.
158 case '(': case '{': case '[': case '%':
159 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner91f54ce2010-11-17 06:26:08 +0000160 if (Diags)
161 Diags->Report(Loc, diag::ext_nonstandard_escape)
Douglas Gregorb90f4b32010-05-26 05:35:51 +0000162 << std::string()+(char)ResultChar;
Eli Friedmanf01fdff2009-04-28 00:51:18 +0000163 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 default:
Chris Lattner91f54ce2010-11-17 06:26:08 +0000165 if (Diags == 0)
Douglas Gregorb90f4b32010-05-26 05:35:51 +0000166 break;
167
Ted Kremenek23ef69d2010-12-03 00:09:56 +0000168 if (isgraph(ResultChar))
Chris Lattner91f54ce2010-11-17 06:26:08 +0000169 Diags->Report(Loc, diag::ext_unknown_escape)
170 << std::string()+(char)ResultChar;
Chris Lattnerac92d822008-11-22 07:23:31 +0000171 else
Chris Lattner91f54ce2010-11-17 06:26:08 +0000172 Diags->Report(Loc, diag::ext_unknown_escape)
173 << "x"+llvm::utohexstr(ResultChar);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 break;
175 }
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 return ResultChar;
178}
179
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000180/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Weber59705ae2010-10-09 00:27:47 +0000181/// return the UTF32.
Richard Smith26b75c02012-03-09 22:27:51 +0000182static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
183 const char *ThisTokEnd,
Nico Weber59705ae2010-10-09 00:27:47 +0000184 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikied6471f72011-09-25 23:23:43 +0000185 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrellbe773522012-01-18 12:27:04 +0000186 const LangOptions &Features,
187 bool in_char_string_literal = false) {
Chris Lattner6c66f072010-11-17 06:46:14 +0000188 if (!Features.CPlusPlus && !Features.C99 && Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000189 Diags->Report(Loc, diag::warn_ucn_not_valid_in_c89);
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Richard Smith26b75c02012-03-09 22:27:51 +0000191 const char *UcnBegin = ThisTokBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000193 // Skip the '\u' char's.
194 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000195
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000196 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner6c66f072010-11-17 06:46:14 +0000197 if (Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000198 Diags->Report(Loc, diag::err_ucn_escape_no_digits);
Nico Weber59705ae2010-10-09 00:27:47 +0000199 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000200 }
Nico Weber59705ae2010-10-09 00:27:47 +0000201 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000202 unsigned short UcnLenSave = UcnLen;
Nico Weber59705ae2010-10-09 00:27:47 +0000203 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000204 int CharVal = HexDigitValue(ThisTokBuf[0]);
205 if (CharVal == -1) break;
206 UcnVal <<= 4;
207 UcnVal |= CharVal;
208 }
209 // If we didn't consume the proper number of digits, there is a problem.
Nico Weber59705ae2010-10-09 00:27:47 +0000210 if (UcnLenSave) {
Chris Lattner872a45e2010-11-17 06:55:10 +0000211 if (Diags) {
Chris Lattner7ef5c272010-11-17 07:05:50 +0000212 SourceLocation L =
Richard Smith26b75c02012-03-09 22:27:51 +0000213 Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
Chris Lattner7ef5c272010-11-17 07:05:50 +0000214 Loc.getManager(), Features);
Richard Smith26b75c02012-03-09 22:27:51 +0000215 Diags->Report(L, diag::err_ucn_escape_incomplete);
Chris Lattner872a45e2010-11-17 06:55:10 +0000216 }
Nico Weber59705ae2010-10-09 00:27:47 +0000217 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000218 }
Richard Smith26b75c02012-03-09 22:27:51 +0000219
Seth Cantrellbe773522012-01-18 12:27:04 +0000220 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith26b75c02012-03-09 22:27:51 +0000221 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
222 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattner6c66f072010-11-17 06:46:14 +0000223 if (Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000224 Diags->Report(Loc, diag::err_ucn_escape_invalid);
Nico Weber59705ae2010-10-09 00:27:47 +0000225 return false;
226 }
Richard Smith26b75c02012-03-09 22:27:51 +0000227
228 // C++11 allows UCNs that refer to control characters and basic source
229 // characters inside character and string literals
230 if (UcnVal < 0xa0 &&
231 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
232 bool IsError = (!Features.CPlusPlus0x || !in_char_string_literal);
233 if (Diags) {
234 SourceLocation UcnBeginLoc =
235 Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
236 Loc.getManager(), Features);
237 char BasicSCSChar = UcnVal;
238 if (UcnVal >= 0x20 && UcnVal < 0x7f)
239 Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_escape_basic_scs :
240 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
241 << StringRef(&BasicSCSChar, 1);
242 else
243 Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_control_character :
244 diag::warn_cxx98_compat_literal_ucn_control_character);
245 }
246 if (IsError)
247 return false;
248 }
249
Nico Weber59705ae2010-10-09 00:27:47 +0000250 return true;
251}
252
Richard Smithdf9ef1b2012-06-13 05:37:23 +0000253/// MeasureUCNEscape - Determine the number of bytes within the resulting string
254/// which this UCN will occupy.
255static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
256 const char *ThisTokEnd, unsigned CharByteWidth,
257 const LangOptions &Features, bool &HadError) {
258 // UTF-32: 4 bytes per escape.
259 if (CharByteWidth == 4)
260 return 4;
261
262 uint32_t UcnVal = 0;
263 unsigned short UcnLen = 0;
264 FullSourceLoc Loc;
265
266 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
267 UcnLen, Loc, 0, Features, true)) {
268 HadError = true;
269 return 0;
270 }
271
272 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
273 if (CharByteWidth == 2)
274 return UcnVal <= 0xFFFF ? 2 : 4;
275
276 // UTF-8.
277 if (UcnVal < 0x80)
278 return 1;
279 if (UcnVal < 0x800)
280 return 2;
281 if (UcnVal < 0x10000)
282 return 3;
283 return 4;
284}
285
Nico Weber59705ae2010-10-09 00:27:47 +0000286/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
287/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
288/// StringLiteralParser. When we decide to implement UCN's for identifiers,
289/// we will likely rework our support for UCN's.
Richard Smith26b75c02012-03-09 22:27:51 +0000290static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
291 const char *ThisTokEnd,
Chris Lattnera95880d2010-11-17 07:12:42 +0000292 char *&ResultBuf, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000293 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikied6471f72011-09-25 23:23:43 +0000294 DiagnosticsEngine *Diags,
295 const LangOptions &Features) {
Nico Weber59705ae2010-10-09 00:27:47 +0000296 typedef uint32_t UTF32;
297 UTF32 UcnVal = 0;
298 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000299 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
300 Loc, Diags, Features, true)) {
Richard Smithdf9ef1b2012-06-13 05:37:23 +0000301 HadError = true;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000302 return;
303 }
Nico Weber59705ae2010-10-09 00:27:47 +0000304
Douglas Gregor5cee1192011-07-27 05:40:30 +0000305 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
306 "only character widths of 1, 2, or 4 bytes supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000307
Douglas Gregor5cee1192011-07-27 05:40:30 +0000308 (void)UcnLen;
309 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000310
Douglas Gregor5cee1192011-07-27 05:40:30 +0000311 if (CharByteWidth == 4) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000312 // FIXME: Make the type of the result buffer correct instead of
313 // using reinterpret_cast.
314 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
315 *ResultPtr = UcnVal;
316 ResultBuf += 4;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000317 return;
318 }
319
320 if (CharByteWidth == 2) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000321 // FIXME: Make the type of the result buffer correct instead of
322 // using reinterpret_cast.
323 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
324
Richard Smith59b26d82012-06-13 05:41:29 +0000325 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000326 *ResultPtr = UcnVal;
327 ResultBuf += 2;
Nico Webera0f15b02010-10-06 04:57:26 +0000328 return;
329 }
Nico Webera0f15b02010-10-06 04:57:26 +0000330
Eli Friedmancaf1f262011-11-02 23:06:23 +0000331 // Convert to UTF16.
Nico Webera0f15b02010-10-06 04:57:26 +0000332 UcnVal -= 0x10000;
Eli Friedmancaf1f262011-11-02 23:06:23 +0000333 *ResultPtr = 0xD800 + (UcnVal >> 10);
334 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
335 ResultBuf += 4;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000336 return;
337 }
Douglas Gregor5cee1192011-07-27 05:40:30 +0000338
339 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
340
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000341 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
342 // The conversion below was inspired by:
343 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump1eb44332009-09-09 15:08:12 +0000344 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000345 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000346
347 unsigned short bytesToWrite = 0;
348 if (UcnVal < (UTF32)0x80)
349 bytesToWrite = 1;
350 else if (UcnVal < (UTF32)0x800)
351 bytesToWrite = 2;
352 else if (UcnVal < (UTF32)0x10000)
353 bytesToWrite = 3;
354 else
355 bytesToWrite = 4;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000357 const unsigned byteMask = 0xBF;
358 const unsigned byteMark = 0x80;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000360 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000361 // into the first byte, depending on how many bytes follow.
Mike Stump1eb44332009-09-09 15:08:12 +0000362 static const UTF8 firstByteMark[5] = {
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000363 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000364 };
365 // Finally, we write the bytes into ResultBuf.
366 ResultBuf += bytesToWrite;
367 switch (bytesToWrite) { // note: everything falls through.
368 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
369 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
370 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
371 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
372 }
373 // Update the buffer.
374 ResultBuf += bytesToWrite;
375}
Reid Spencer5f016e22007-07-11 17:01:13 +0000376
377
378/// integer-constant: [C99 6.4.4.1]
379/// decimal-constant integer-suffix
380/// octal-constant integer-suffix
381/// hexadecimal-constant integer-suffix
Richard Smith49d51742012-03-08 21:59:28 +0000382/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smithb453ad32012-03-08 08:45:32 +0000383/// decimal-literal ud-suffix
384/// octal-literal ud-suffix
385/// hexadecimal-literal ud-suffix
Mike Stump1eb44332009-09-09 15:08:12 +0000386/// decimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000387/// nonzero-digit
388/// decimal-constant digit
Mike Stump1eb44332009-09-09 15:08:12 +0000389/// octal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000390/// 0
391/// octal-constant octal-digit
Mike Stump1eb44332009-09-09 15:08:12 +0000392/// hexadecimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000393/// hexadecimal-prefix hexadecimal-digit
394/// hexadecimal-constant hexadecimal-digit
395/// hexadecimal-prefix: one of
396/// 0x 0X
397/// integer-suffix:
398/// unsigned-suffix [long-suffix]
399/// unsigned-suffix [long-long-suffix]
400/// long-suffix [unsigned-suffix]
401/// long-long-suffix [unsigned-sufix]
402/// nonzero-digit:
403/// 1 2 3 4 5 6 7 8 9
404/// octal-digit:
405/// 0 1 2 3 4 5 6 7
406/// hexadecimal-digit:
407/// 0 1 2 3 4 5 6 7 8 9
408/// a b c d e f
409/// A B C D E F
410/// unsigned-suffix: one of
411/// u U
412/// long-suffix: one of
413/// l L
Mike Stump1eb44332009-09-09 15:08:12 +0000414/// long-long-suffix: one of
Reid Spencer5f016e22007-07-11 17:01:13 +0000415/// ll LL
416///
417/// floating-constant: [C99 6.4.4.2]
418/// TODO: add rules...
419///
Reid Spencer5f016e22007-07-11 17:01:13 +0000420NumericLiteralParser::
421NumericLiteralParser(const char *begin, const char *end,
422 SourceLocation TokLoc, Preprocessor &pp)
423 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000425 // This routine assumes that the range begin/end matches the regex for integer
426 // and FP constants (specifically, the 'pp-number' regex), and assumes that
427 // the byte at "*end" is both valid and not part of the regex. Because of
428 // this, it doesn't have to check for 'overscan' in various places.
429 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
430 "Lexer didn't maximally munch?");
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 s = DigitsBegin = begin;
433 saw_exponent = false;
434 saw_period = false;
Richard Smithb453ad32012-03-08 08:45:32 +0000435 saw_ud_suffix = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 isLong = false;
437 isUnsigned = false;
438 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000439 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000440 isImaginary = false;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000441 isMicrosoftInteger = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 hadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000445 ParseNumberStartingWithZero(TokLoc);
446 if (hadError)
447 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 } else { // the first digit is non-zero
449 radix = 10;
450 s = SkipDigits(s);
451 if (s == ThisTokEnd) {
452 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000453 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000454 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000455 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000456 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 return;
458 } else if (*s == '.') {
459 s++;
460 saw_period = true;
461 s = SkipDigits(s);
Mike Stump1eb44332009-09-09 15:08:12 +0000462 }
Chris Lattner4411f462008-09-29 23:12:31 +0000463 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000464 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 s++;
466 saw_exponent = true;
467 if (*s == '+' || *s == '-') s++; // sign
468 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000469 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000471 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000472 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
473 diag::err_exponent_has_no_digits);
474 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000475 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 }
477 }
478 }
479
480 SuffixBegin = s;
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner506b8de2007-08-26 01:58:14 +0000482 // Parse the suffix. At this point we can classify whether we have an FP or
483 // integer constant.
484 bool isFPConstant = isFloatingLiteral();
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Chris Lattner506b8de2007-08-26 01:58:14 +0000486 // Loop over all of the characters of the suffix. If we see something bad,
487 // we break out of the loop.
488 for (; s != ThisTokEnd; ++s) {
489 switch (*s) {
490 case 'f': // FP Suffix for "float"
491 case 'F':
492 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000493 if (isFloat || isLong) break; // FF, LF invalid.
494 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000495 continue; // Success.
496 case 'u':
497 case 'U':
498 if (isFPConstant) break; // Error for floating constant.
499 if (isUnsigned) break; // Cannot be repeated.
500 isUnsigned = true;
501 continue; // Success.
502 case 'l':
503 case 'L':
504 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000505 if (isFloat) break; // LF invalid.
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattner506b8de2007-08-26 01:58:14 +0000507 // Check for long long. The L's need to be adjacent and the same case.
508 if (s+1 != ThisTokEnd && s[1] == s[0]) {
509 if (isFPConstant) break; // long long invalid for floats.
510 isLongLong = true;
511 ++s; // Eat both of them.
512 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000515 continue; // Success.
516 case 'i':
Chris Lattnerc6374152010-10-14 00:24:10 +0000517 case 'I':
David Blaikie4e4d0842012-03-11 07:00:24 +0000518 if (PP.getLangOpts().MicrosoftExt) {
Fariborz Jahaniana8be02b2010-01-22 21:36:53 +0000519 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000520
Steve Naroff0c29b222008-04-04 21:02:54 +0000521 // Allow i8, i16, i32, i64, and i128.
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000522 if (s + 1 != ThisTokEnd) {
523 switch (s[1]) {
524 case '8':
525 s += 2; // i8 suffix
526 isMicrosoftInteger = true;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000527 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000528 case '1':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000529 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000530 if (s[2] == '6') {
531 s += 3; // i16 suffix
532 isMicrosoftInteger = true;
533 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000534 else if (s[2] == '2') {
535 if (s + 3 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000536 if (s[3] == '8') {
537 s += 4; // i128 suffix
538 isMicrosoftInteger = true;
539 }
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000540 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000541 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000542 case '3':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000543 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000544 if (s[2] == '2') {
545 s += 3; // i32 suffix
546 isLong = true;
547 isMicrosoftInteger = true;
548 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000549 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000550 case '6':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000551 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000552 if (s[2] == '4') {
553 s += 3; // i64 suffix
554 isLongLong = true;
555 isMicrosoftInteger = true;
556 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000557 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000558 default:
559 break;
560 }
561 break;
Steve Naroff0c29b222008-04-04 21:02:54 +0000562 }
Steve Naroff0c29b222008-04-04 21:02:54 +0000563 }
564 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000565 case 'j':
566 case 'J':
567 if (isImaginary) break; // Cannot be repeated.
568 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
569 diag::ext_imaginary_constant);
570 isImaginary = true;
571 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 }
Richard Smithb453ad32012-03-08 08:45:32 +0000573 // If we reached here, there was an error or a ud-suffix.
Chris Lattner506b8de2007-08-26 01:58:14 +0000574 break;
575 }
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner506b8de2007-08-26 01:58:14 +0000577 if (s != ThisTokEnd) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000578 if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
Richard Smithb453ad32012-03-08 08:45:32 +0000579 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
580 // with an '_' are ill-formed.
581 saw_ud_suffix = true;
582 return;
583 }
584
585 // Report an error if there are any.
586 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin-begin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000587 isFPConstant ? diag::err_invalid_suffix_float_constant :
588 diag::err_invalid_suffix_integer_constant)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattnerac92d822008-11-22 07:23:31 +0000590 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000591 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 }
593}
594
Chris Lattner368328c2008-06-30 06:39:54 +0000595/// ParseNumberStartingWithZero - This method is called when the first character
596/// of the number is found to be a zero. This means it is either an octal
597/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump1eb44332009-09-09 15:08:12 +0000598/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner368328c2008-06-30 06:39:54 +0000599/// radix etc.
600void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
601 assert(s[0] == '0' && "Invalid method call");
602 s++;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattner368328c2008-06-30 06:39:54 +0000604 // Handle a hex number like 0x1234.
605 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
606 s++;
607 radix = 16;
608 DigitsBegin = s;
609 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000610 bool noSignificand = (s == DigitsBegin);
Chris Lattner368328c2008-06-30 06:39:54 +0000611 if (s == ThisTokEnd) {
612 // Done.
613 } else if (*s == '.') {
614 s++;
615 saw_period = true;
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000616 const char *floatDigitsBegin = s;
Chris Lattner368328c2008-06-30 06:39:54 +0000617 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000618 noSignificand &= (floatDigitsBegin == s);
Chris Lattner368328c2008-06-30 06:39:54 +0000619 }
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000620
621 if (noSignificand) {
622 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), \
623 diag::err_hexconstant_requires_digits);
624 hadError = true;
625 return;
626 }
627
Chris Lattner368328c2008-06-30 06:39:54 +0000628 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump1eb44332009-09-09 15:08:12 +0000629 // binary exponent is required.
Douglas Gregor1155c422011-08-30 22:40:35 +0000630 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000631 const char *Exponent = s;
632 s++;
633 saw_exponent = true;
634 if (*s == '+' || *s == '-') s++; // sign
635 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000636 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000637 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
638 diag::err_exponent_has_no_digits);
639 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000640 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000641 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000642 s = first_non_digit;
Mike Stump1eb44332009-09-09 15:08:12 +0000643
David Blaikie4e4d0842012-03-11 07:00:24 +0000644 if (!PP.getLangOpts().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000645 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000646 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000647 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
648 diag::err_hexconstant_requires_exponent);
649 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000650 }
651 return;
652 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattner368328c2008-06-30 06:39:54 +0000654 // Handle simple binary numbers 0b01010
655 if (*s == 'b' || *s == 'B') {
656 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000657 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000658 ++s;
659 radix = 2;
660 DigitsBegin = s;
661 s = SkipBinaryDigits(s);
662 if (s == ThisTokEnd) {
663 // Done.
664 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000665 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000666 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000667 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000668 }
Chris Lattner413d3552008-06-30 06:44:49 +0000669 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000670 return;
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner368328c2008-06-30 06:39:54 +0000673 // For now, the radix is set to 8. If we discover that we have a
674 // floating point constant, the radix will change to 10. Octal floating
Mike Stump1eb44332009-09-09 15:08:12 +0000675 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner368328c2008-06-30 06:39:54 +0000676 radix = 8;
677 DigitsBegin = s;
678 s = SkipOctalDigits(s);
679 if (s == ThisTokEnd)
680 return; // Done, simple octal number like 01234
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Chris Lattner413d3552008-06-30 06:44:49 +0000682 // If we have some other non-octal digit that *is* a decimal digit, see if
683 // this is part of a floating point number like 094.123 or 09e1.
684 if (isdigit(*s)) {
685 const char *EndDecimal = SkipDigits(s);
686 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
687 s = EndDecimal;
688 radix = 10;
689 }
690 }
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner413d3552008-06-30 06:44:49 +0000692 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
693 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000694 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
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_octal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000697 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000698 return;
699 }
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner368328c2008-06-30 06:39:54 +0000701 if (*s == '.') {
702 s++;
703 radix = 10;
704 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000705 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000706 }
707 if (*s == 'e' || *s == 'E') { // exponent
708 const char *Exponent = s;
709 s++;
710 radix = 10;
711 saw_exponent = true;
712 if (*s == '+' || *s == '-') s++; // sign
713 const char *first_non_digit = SkipDigits(s);
714 if (first_non_digit != s) {
715 s = first_non_digit;
716 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000717 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000718 diag::err_exponent_has_no_digits);
719 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000720 return;
721 }
722 }
723}
724
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726/// GetIntegerValue - Convert this numeric literal value to an APInt that
727/// matches Val's input width. If there is an overflow, set Val to the low bits
728/// of the result and return true. Otherwise, return false.
729bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000730 // Fast path: Compute a conservative bound on the maximum number of
731 // bits per digit in this radix. If we can't possibly overflow a
732 // uint64 based on that bound then do the simple conversion to
733 // integer. This avoids the expensive overflow checking below, and
734 // handles the common cases that matter (small decimal integers and
735 // hex/octal values which don't overflow).
736 unsigned MaxBitsPerDigit = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000737 while ((1U << MaxBitsPerDigit) < radix)
Daniel Dunbara179be32008-10-16 07:32:01 +0000738 MaxBitsPerDigit += 1;
739 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
740 uint64_t N = 0;
741 for (s = DigitsBegin; s != SuffixBegin; ++s)
742 N = N*radix + HexDigitValue(*s);
743
744 // This will truncate the value to Val's input width. Simply check
745 // for overflow by comparing.
746 Val = N;
747 return Val.getZExtValue() != N;
748 }
749
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 Val = 0;
751 s = DigitsBegin;
752
753 llvm::APInt RadixVal(Val.getBitWidth(), radix);
754 llvm::APInt CharVal(Val.getBitWidth(), 0);
755 llvm::APInt OldVal = Val;
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 bool OverflowOccurred = false;
758 while (s < SuffixBegin) {
759 unsigned C = HexDigitValue(*s++);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // If this letter is out of bound for this radix, reject it.
762 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 CharVal = C;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 // Add the digit to the value in the appropriate radix. If adding in digits
767 // made the value smaller, then this overflowed.
768 OldVal = Val;
769
770 // Multiply by radix, did overflow occur on the multiply?
771 Val *= RadixVal;
772 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
773
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000775 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 OverflowOccurred |= Val.ult(CharVal);
778 }
779 return OverflowOccurred;
780}
781
John McCall94c939d2009-12-24 09:08:04 +0000782llvm::APFloat::opStatus
783NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenek427d5af2007-11-26 23:12:30 +0000784 using llvm::APFloat;
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000786 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall94c939d2009-12-24 09:08:04 +0000787 return Result.convertFromString(StringRef(ThisTokBegin, n),
788 APFloat::rmNearestTiesToEven);
Reid Spencer5f016e22007-07-11 17:01:13 +0000789}
790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791
James Dennett58f9ce12012-06-17 03:34:42 +0000792/// \verbatim
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000793/// user-defined-character-literal: [C++11 lex.ext]
794/// character-literal ud-suffix
795/// ud-suffix:
796/// identifier
797/// character-literal: [C++11 lex.ccon]
Craig Topper2fa4e862011-08-11 04:06:15 +0000798/// ' c-char-sequence '
799/// u' c-char-sequence '
800/// U' c-char-sequence '
801/// L' c-char-sequence '
802/// c-char-sequence:
803/// c-char
804/// c-char-sequence c-char
805/// c-char:
806/// any member of the source character set except the single-quote ',
807/// backslash \, or new-line character
808/// escape-sequence
809/// universal-character-name
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000810/// escape-sequence:
Craig Topper2fa4e862011-08-11 04:06:15 +0000811/// simple-escape-sequence
812/// octal-escape-sequence
813/// hexadecimal-escape-sequence
814/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +0000815/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +0000816/// octal-escape-sequence:
817/// \ octal-digit
818/// \ octal-digit octal-digit
819/// \ octal-digit octal-digit octal-digit
820/// hexadecimal-escape-sequence:
821/// \x hexadecimal-digit
822/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000823/// universal-character-name: [C++11 lex.charset]
Craig Topper2fa4e862011-08-11 04:06:15 +0000824/// \u hex-quad
825/// \U hex-quad hex-quad
826/// hex-quad:
827/// hex-digit hex-digit hex-digit hex-digit
James Dennett58f9ce12012-06-17 03:34:42 +0000828/// \endverbatim
Craig Topper2fa4e862011-08-11 04:06:15 +0000829///
Reid Spencer5f016e22007-07-11 17:01:13 +0000830CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000831 SourceLocation Loc, Preprocessor &PP,
832 tok::TokenKind kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000833 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Douglas Gregor5cee1192011-07-27 05:40:30 +0000836 Kind = kind;
837
Richard Smith26b75c02012-03-09 22:27:51 +0000838 const char *TokBegin = begin;
839
Seth Cantrellbe773522012-01-18 12:27:04 +0000840 // Skip over wide character determinant.
841 if (Kind != tok::char_constant) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000842 ++begin;
843 }
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 // Skip over the entry quote.
846 assert(begin[0] == '\'' && "Invalid token lexed");
847 ++begin;
848
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000849 // Remove an optional ud-suffix.
850 if (end[-1] != '\'') {
851 const char *UDSuffixEnd = end;
852 do {
853 --end;
854 } while (end[-1] != '\'');
855 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith26b75c02012-03-09 22:27:51 +0000856 UDSuffixOffset = end - TokBegin;
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000857 }
858
Seth Cantrellbe773522012-01-18 12:27:04 +0000859 // Trim the ending quote.
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000860 assert(end != begin && "Invalid token lexed");
Seth Cantrellbe773522012-01-18 12:27:04 +0000861 --end;
862
Mike Stump1eb44332009-09-09 15:08:12 +0000863 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000864 // up to 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000866 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000868 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
869 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
870 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
871 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
872 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000873
Seth Cantrellbe773522012-01-18 12:27:04 +0000874 SmallVector<uint32_t,4> codepoint_buffer;
875 codepoint_buffer.resize(end-begin);
876 uint32_t *buffer_begin = &codepoint_buffer.front();
877 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Seth Cantrellbe773522012-01-18 12:27:04 +0000879 // Unicode escapes representing characters that cannot be correctly
880 // represented in a single code unit are disallowed in character literals
881 // by this implementation.
882 uint32_t largest_character_for_kind;
883 if (tok::wide_char_constant == Kind) {
884 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
885 } else if (tok::utf16_char_constant == Kind) {
886 largest_character_for_kind = 0xFFFF;
887 } else if (tok::utf32_char_constant == Kind) {
888 largest_character_for_kind = 0x10FFFF;
889 } else {
890 largest_character_for_kind = 0x7Fu;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000891 }
892
Seth Cantrellbe773522012-01-18 12:27:04 +0000893 while (begin!=end) {
894 // Is this a span of non-escape characters?
895 if (begin[0] != '\\') {
896 char const *start = begin;
897 do {
898 ++begin;
899 } while (begin != end && *begin != '\\');
900
Eli Friedman91359302012-02-11 05:08:10 +0000901 char const *tmp_in_start = start;
902 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrellbe773522012-01-18 12:27:04 +0000903 ConversionResult res =
904 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
905 reinterpret_cast<UTF8 const *>(begin),
906 &buffer_begin,buffer_end,strictConversion);
907 if (res!=conversionOK) {
Eli Friedman91359302012-02-11 05:08:10 +0000908 // If we see bad encoding for unprefixed character literals, warn and
909 // simply copy the byte values, for compatibility with gcc and
910 // older versions of clang.
911 bool NoErrorOnBadEncoding = isAscii();
912 unsigned Msg = diag::err_bad_character_encoding;
913 if (NoErrorOnBadEncoding)
914 Msg = diag::warn_bad_character_encoding;
915 PP.Diag(Loc, Msg);
916 if (NoErrorOnBadEncoding) {
917 start = tmp_in_start;
918 buffer_begin = tmp_out_start;
919 for ( ; start != begin; ++start, ++buffer_begin)
920 *buffer_begin = static_cast<uint8_t>(*start);
921 } else {
922 HadError = true;
923 }
Seth Cantrellbe773522012-01-18 12:27:04 +0000924 } else {
Eli Friedman91359302012-02-11 05:08:10 +0000925 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
926 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000927 HadError = true;
928 PP.Diag(Loc, diag::err_character_too_large);
929 }
930 }
931 }
932
933 continue;
934 }
935 // Is this a Universal Character Name excape?
936 if (begin[1] == 'u' || begin[1] == 'U') {
937 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000938 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrellbe773522012-01-18 12:27:04 +0000939 FullSourceLoc(Loc, PP.getSourceManager()),
David Blaikie4e4d0842012-03-11 07:00:24 +0000940 &PP.getDiagnostics(), PP.getLangOpts(),
Seth Cantrellbe773522012-01-18 12:27:04 +0000941 true))
942 {
943 HadError = true;
944 } else if (*buffer_begin > largest_character_for_kind) {
945 HadError = true;
946 PP.Diag(Loc,diag::err_character_too_large);
947 }
948
949 ++buffer_begin;
950 continue;
951 }
952 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
953 uint64_t result =
954 ProcessCharEscape(begin, end, HadError,
955 FullSourceLoc(Loc,PP.getSourceManager()),
956 CharWidth, &PP.getDiagnostics());
957 *buffer_begin++ = result;
958 }
959
960 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
961
Chris Lattnere3ad8812009-04-28 21:51:46 +0000962 if (NumCharsSoFar > 1) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000963 if (isWide())
Douglas Gregor5cee1192011-07-27 05:40:30 +0000964 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrellbe773522012-01-18 12:27:04 +0000965 else if (isAscii() && NumCharsSoFar == 4)
966 PP.Diag(Loc, diag::ext_four_char_character_literal);
967 else if (isAscii())
Chris Lattnere3ad8812009-04-28 21:51:46 +0000968 PP.Diag(Loc, diag::ext_multichar_character_literal);
969 else
Seth Cantrellbe773522012-01-18 12:27:04 +0000970 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000971 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000972 } else
973 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000974
Seth Cantrellbe773522012-01-18 12:27:04 +0000975 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
976
977 // Narrow character literals act as though their value is concatenated
978 // in this implementation, but warn on overflow.
979 bool multi_char_too_long = false;
980 if (isAscii() && isMultiChar()) {
981 LitVal = 0;
982 for (size_t i=0;i<NumCharsSoFar;++i) {
983 // check for enough leading zeros to shift into
984 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
985 LitVal <<= 8;
986 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
987 }
988 } else if (NumCharsSoFar > 0) {
989 // otherwise just take the last character
990 LitVal = buffer_begin[-1];
991 }
992
993 if (!HadError && multi_char_too_long) {
994 PP.Diag(Loc,diag::warn_char_constant_too_large);
995 }
996
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000997 // Transfer the value from APInt to uint64_t
998 Value = LitVal.getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1001 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1002 // character constants are not sign extended in the this implementation:
1003 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001004 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001005 PP.getLangOpts().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 Value = (signed char)Value;
1007}
1008
James Dennetta1263cf2012-06-19 21:04:25 +00001009/// \verbatim
Craig Topper2fa4e862011-08-11 04:06:15 +00001010/// string-literal: [C++0x lex.string]
1011/// encoding-prefix " [s-char-sequence] "
1012/// encoding-prefix R raw-string
1013/// encoding-prefix:
1014/// u8
1015/// u
1016/// U
1017/// L
Reid Spencer5f016e22007-07-11 17:01:13 +00001018/// s-char-sequence:
1019/// s-char
1020/// s-char-sequence s-char
1021/// s-char:
Craig Topper2fa4e862011-08-11 04:06:15 +00001022/// any member of the source character set except the double-quote ",
1023/// backslash \, or new-line character
1024/// escape-sequence
Reid Spencer5f016e22007-07-11 17:01:13 +00001025/// universal-character-name
Craig Topper2fa4e862011-08-11 04:06:15 +00001026/// raw-string:
1027/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1028/// r-char-sequence:
1029/// r-char
1030/// r-char-sequence r-char
1031/// r-char:
1032/// any member of the source character set, except a right parenthesis )
1033/// followed by the initial d-char-sequence (which may be empty)
1034/// followed by a double quote ".
1035/// d-char-sequence:
1036/// d-char
1037/// d-char-sequence d-char
1038/// d-char:
1039/// any member of the basic source character set except:
1040/// space, the left parenthesis (, the right parenthesis ),
1041/// the backslash \, and the control characters representing horizontal
1042/// tab, vertical tab, form feed, and newline.
1043/// escape-sequence: [C++0x lex.ccon]
1044/// simple-escape-sequence
1045/// octal-escape-sequence
1046/// hexadecimal-escape-sequence
1047/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +00001048/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +00001049/// octal-escape-sequence:
1050/// \ octal-digit
1051/// \ octal-digit octal-digit
1052/// \ octal-digit octal-digit octal-digit
1053/// hexadecimal-escape-sequence:
1054/// \x hexadecimal-digit
1055/// hexadecimal-escape-sequence hexadecimal-digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001056/// universal-character-name:
1057/// \u hex-quad
1058/// \U hex-quad hex-quad
1059/// hex-quad:
1060/// hex-digit hex-digit hex-digit hex-digit
James Dennetta1263cf2012-06-19 21:04:25 +00001061/// \endverbatim
Reid Spencer5f016e22007-07-11 17:01:13 +00001062///
1063StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +00001064StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner0833dd02010-11-17 07:21:13 +00001065 Preprocessor &PP, bool Complain)
David Blaikie4e4d0842012-03-11 07:00:24 +00001066 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001067 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001068 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1069 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner0833dd02010-11-17 07:21:13 +00001070 init(StringToks, NumStringToks);
1071}
1072
1073void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001074 // The literal token may have come from an invalid source location (e.g. due
1075 // to a PCH error), in which case the token length will be 0.
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001076 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1077 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001078
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 // Scan all of the string portions, remember the max individual token length,
1080 // computing a bound on the concatenated string length, and see whether any
1081 // piece is a wide-string. If any of the string portions is a wide-string
1082 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001083 assert(NumStringToks && "expected at least one token");
Sean Hunt6cf75022010-08-30 17:47:05 +00001084 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001085 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001086 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001087 Kind = StringToks[0].getKind();
Sean Hunt6cf75022010-08-30 17:47:05 +00001088
1089 hadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001090
1091 // Implement Translation Phase #6: concatenation of string literals
1092 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1093 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001094 if (StringToks[i].getLength() < 2)
1095 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001096
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 // The string could be shorter than this if it needs cleaning, but this is a
1098 // reasonable bound, which is all we need.
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001099 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001100 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 // Remember maximum string piece length.
Sean Hunt6cf75022010-08-30 17:47:05 +00001103 if (StringToks[i].getLength() > MaxTokenLength)
1104 MaxTokenLength = StringToks[i].getLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Douglas Gregor5cee1192011-07-27 05:40:30 +00001106 // Remember if we see any wide or utf-8/16/32 strings.
1107 // Also check for illegal concatenations.
1108 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1109 if (isAscii()) {
1110 Kind = StringToks[i].getKind();
1111 } else {
1112 if (Diags)
1113 Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
1114 diag::err_unsupported_string_concat);
1115 hadError = true;
1116 }
1117 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // Include space for the null terminator.
1121 ++SizeBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Douglas Gregor5cee1192011-07-27 05:40:30 +00001125 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1126 CharByteWidth = getCharWidth(Kind, Target);
1127 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1128 CharByteWidth /= 8;
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 // The output buffer size needs to be large enough to hold wide characters.
1131 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001132 SizeBound *= CharByteWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 // Size the temporary buffer to hold the result string data.
1135 ResultBuf.resize(SizeBound);
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // Likewise, but for each string piece.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001138 SmallString<512> TokenBuf;
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 TokenBuf.resize(MaxTokenLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 // Loop over all the strings, getting their spelling, and expanding them to
1142 // wide strings as appropriate.
1143 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Anders Carlssonee98ac52007-10-15 02:50:23 +00001145 Pascal = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001147 SourceLocation UDSuffixTokLoc;
1148
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1150 const char *ThisTokBuf = &TokenBuf[0];
1151 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1152 // that ThisTokBuf points to a buffer that is big enough for the whole token
1153 // and 'spelled' tokens can only shrink.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001154 bool StringInvalid = false;
Chris Lattner0833dd02010-11-17 07:21:13 +00001155 unsigned ThisTokLen =
Chris Lattnerb0607272010-11-17 07:26:20 +00001156 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1157 &StringInvalid);
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001158 if (StringInvalid)
1159 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor50f6af72010-03-16 05:20:39 +00001160
Richard Smith26b75c02012-03-09 22:27:51 +00001161 const char *ThisTokBegin = ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001162 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1163
1164 // Remove an optional ud-suffix.
1165 if (ThisTokEnd[-1] != '"') {
1166 const char *UDSuffixEnd = ThisTokEnd;
1167 do {
1168 --ThisTokEnd;
1169 } while (ThisTokEnd[-1] != '"');
1170
1171 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1172
1173 if (UDSuffixBuf.empty()) {
1174 UDSuffixBuf.assign(UDSuffix);
Richard Smithdd66be72012-03-08 01:34:56 +00001175 UDSuffixToken = i;
1176 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001177 UDSuffixTokLoc = StringToks[i].getLocation();
1178 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1179 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1180 // result of a concatenation involving at least one user-defined-string-
1181 // literal, all the participating user-defined-string-literals shall
1182 // have the same ud-suffix.
1183 if (Diags) {
1184 SourceLocation TokLoc = StringToks[i].getLocation();
1185 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1186 << UDSuffixBuf << UDSuffix
1187 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1188 << SourceRange(TokLoc, TokLoc);
1189 }
1190 hadError = true;
1191 }
1192 }
1193
1194 // Strip the end quote.
1195 --ThisTokEnd;
1196
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 // TODO: Input character set mapping support.
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Craig Topper1661d712011-08-08 06:10:39 +00001199 // Skip marker for wide or unicode strings.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001200 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 ++ThisTokBuf;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001202 // Skip 8 of u8 marker for utf8 strings.
1203 if (ThisTokBuf[0] == '8')
1204 ++ThisTokBuf;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +00001205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Craig Topper2fa4e862011-08-11 04:06:15 +00001207 // Check for raw string
1208 if (ThisTokBuf[0] == 'R') {
1209 ThisTokBuf += 2; // skip R"
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Craig Topper2fa4e862011-08-11 04:06:15 +00001211 const char *Prefix = ThisTokBuf;
1212 while (ThisTokBuf[0] != '(')
Anders Carlssonee98ac52007-10-15 02:50:23 +00001213 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001214 ++ThisTokBuf; // skip '('
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Richard Smith49d51742012-03-08 21:59:28 +00001216 // Remove same number of characters from the end
1217 ThisTokEnd -= ThisTokBuf - Prefix;
1218 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper2fa4e862011-08-11 04:06:15 +00001219
1220 // Copy the string over
Richard Smith49d51742012-03-08 21:59:28 +00001221 if (CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
Eli Friedman91359302012-02-11 05:08:10 +00001222 if (DiagnoseBadString(StringToks[i]))
1223 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001224 } else {
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001225 if (ThisTokBuf[0] != '"') {
1226 // The file may have come from PCH and then changed after loading the
1227 // PCH; Fail gracefully.
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001228 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001229 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001230 ++ThisTokBuf; // skip "
1231
1232 // Check if this is a pascal string
1233 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1234 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1235
1236 // If the \p sequence is found in the first token, we have a pascal string
1237 // Otherwise, if we already have a pascal string, ignore the first \p
1238 if (i == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001240 Pascal = true;
1241 } else if (Pascal)
1242 ThisTokBuf += 2;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Craig Topper2fa4e862011-08-11 04:06:15 +00001245 while (ThisTokBuf != ThisTokEnd) {
1246 // Is this a span of non-escape characters?
1247 if (ThisTokBuf[0] != '\\') {
1248 const char *InStart = ThisTokBuf;
1249 do {
1250 ++ThisTokBuf;
1251 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1252
1253 // Copy the character span over.
Richard Smith49d51742012-03-08 21:59:28 +00001254 if (CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart)))
Eli Friedman91359302012-02-11 05:08:10 +00001255 if (DiagnoseBadString(StringToks[i]))
1256 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001257 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001259 // Is this a Universal Character Name escape?
1260 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith26b75c02012-03-09 22:27:51 +00001261 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1262 ResultPtr, hadError,
1263 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper2fa4e862011-08-11 04:06:15 +00001264 CharByteWidth, Diags, Features);
1265 continue;
1266 }
1267 // Otherwise, this is a non-UCN escape character. Process it.
1268 unsigned ResultChar =
1269 ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
1270 FullSourceLoc(StringToks[i].getLocation(), SM),
1271 CharByteWidth*8, Diags);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Eli Friedmancaf1f262011-11-02 23:06:23 +00001273 if (CharByteWidth == 4) {
1274 // FIXME: Make the type of the result buffer correct instead of
1275 // using reinterpret_cast.
1276 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001277 *ResultWidePtr = ResultChar;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001278 ResultPtr += 4;
1279 } else if (CharByteWidth == 2) {
1280 // FIXME: Make the type of the result buffer correct instead of
1281 // using reinterpret_cast.
1282 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001283 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001284 ResultPtr += 2;
1285 } else {
1286 assert(CharByteWidth == 1 && "Unexpected char width");
1287 *ResultPtr++ = ResultChar & 0xFF;
1288 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001289 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 }
1291 }
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001293 if (Pascal) {
Eli Friedman22508f42011-11-05 00:41:04 +00001294 if (CharByteWidth == 4) {
1295 // FIXME: Make the type of the result buffer correct instead of
1296 // using reinterpret_cast.
1297 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1298 ResultWidePtr[0] = GetNumStringChars() - 1;
1299 } else if (CharByteWidth == 2) {
1300 // FIXME: Make the type of the result buffer correct instead of
1301 // using reinterpret_cast.
1302 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1303 ResultWidePtr[0] = GetNumStringChars() - 1;
1304 } else {
1305 assert(CharByteWidth == 1 && "Unexpected char width");
1306 ResultBuf[0] = GetNumStringChars() - 1;
1307 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001308
1309 // Verify that pascal strings aren't too large.
Chris Lattner0833dd02010-11-17 07:21:13 +00001310 if (GetStringLength() > 256) {
1311 if (Diags)
1312 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1313 diag::err_pascal_string_too_long)
1314 << SourceRange(StringToks[0].getLocation(),
1315 StringToks[NumStringToks-1].getLocation());
Douglas Gregor5cee1192011-07-27 05:40:30 +00001316 hadError = true;
Eli Friedman57d7dde2009-04-01 03:17:08 +00001317 return;
1318 }
Chris Lattner0833dd02010-11-17 07:21:13 +00001319 } else if (Diags) {
Douglas Gregor427c4922010-07-20 14:33:20 +00001320 // Complain if this string literal has too many characters.
Chris Lattnera95880d2010-11-17 07:12:42 +00001321 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Douglas Gregor427c4922010-07-20 14:33:20 +00001322
1323 if (GetNumStringChars() > MaxChars)
Chris Lattner0833dd02010-11-17 07:21:13 +00001324 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1325 diag::ext_string_too_long)
Douglas Gregor427c4922010-07-20 14:33:20 +00001326 << GetNumStringChars() << MaxChars
Chris Lattnera95880d2010-11-17 07:12:42 +00001327 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregor427c4922010-07-20 14:33:20 +00001328 << SourceRange(StringToks[0].getLocation(),
1329 StringToks[NumStringToks-1].getLocation());
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001330 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001331}
Chris Lattner719e6152009-02-18 19:21:10 +00001332
1333
Craig Topper2fa4e862011-08-11 04:06:15 +00001334/// copyStringFragment - This function copies from Start to End into ResultPtr.
1335/// Performs widening for multi-byte characters.
Eli Friedmanf74a4582011-11-01 02:14:50 +00001336bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
1337 assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
1338 ConversionResult result = conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001339 // Copy the character span over.
1340 if (CharByteWidth == 1) {
Richard Smith49d51742012-03-08 21:59:28 +00001341 if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(Fragment.begin()),
1342 reinterpret_cast<const UTF8*>(Fragment.end())))
Eli Friedman91359302012-02-11 05:08:10 +00001343 result = sourceIllegal;
Craig Topper2fa4e862011-08-11 04:06:15 +00001344 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1345 ResultPtr += Fragment.size();
Eli Friedmanf74a4582011-11-01 02:14:50 +00001346 } else if (CharByteWidth == 2) {
1347 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1348 // FIXME: Make the type of the result buffer correct instead of
1349 // using reinterpret_cast.
1350 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001351 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001352 result = ConvertUTF8toUTF16(
1353 &sourceStart,sourceStart + Fragment.size(),
1354 &targetStart,targetStart + 2*Fragment.size(),flags);
1355 if (result==conversionOK)
1356 ResultPtr = reinterpret_cast<char*>(targetStart);
1357 } else if (CharByteWidth == 4) {
1358 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1359 // FIXME: Make the type of the result buffer correct instead of
1360 // using reinterpret_cast.
1361 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001362 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001363 result = ConvertUTF8toUTF32(
1364 &sourceStart,sourceStart + Fragment.size(),
1365 &targetStart,targetStart + 4*Fragment.size(),flags);
1366 if (result==conversionOK)
1367 ResultPtr = reinterpret_cast<char*>(targetStart);
Craig Topper2fa4e862011-08-11 04:06:15 +00001368 }
Eli Friedmanf74a4582011-11-01 02:14:50 +00001369 assert((result != targetExhausted)
1370 && "ConvertUTF8toUTFXX exhausted target buffer");
1371 return result != conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001372}
1373
Eli Friedman91359302012-02-11 05:08:10 +00001374bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
1375 // If we see bad encoding for unprefixed string literals, warn and
1376 // simply copy the byte values, for compatibility with gcc and older
1377 // versions of clang.
1378 bool NoErrorOnBadEncoding = isAscii();
1379 unsigned Msg = NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
1380 diag::err_bad_string_encoding;
1381 if (Diags)
1382 Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
1383 return !NoErrorOnBadEncoding;
1384}
Craig Topper2fa4e862011-08-11 04:06:15 +00001385
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001386void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1387 hadError = true;
1388 if (Diags)
1389 Diags->Report(Loc, diag::err_lexing_string);
1390}
1391
Chris Lattner719e6152009-02-18 19:21:10 +00001392/// getOffsetOfStringByte - This function returns the offset of the
1393/// specified byte of the string data represented by Token. This handles
1394/// advancing over escape sequences in the string.
1395unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattner6c66f072010-11-17 06:46:14 +00001396 unsigned ByteNo) const {
Chris Lattner719e6152009-02-18 19:21:10 +00001397 // Get the spelling of the token.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001398 SmallString<32> SpellingBuffer;
Sean Hunt6cf75022010-08-30 17:47:05 +00001399 SpellingBuffer.resize(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregor50f6af72010-03-16 05:20:39 +00001401 bool StringInvalid = false;
Chris Lattner719e6152009-02-18 19:21:10 +00001402 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattnerb0607272010-11-17 07:26:20 +00001403 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1404 &StringInvalid);
Chris Lattner91f54ce2010-11-17 06:26:08 +00001405 if (StringInvalid)
Douglas Gregor50f6af72010-03-16 05:20:39 +00001406 return 0;
Chris Lattner719e6152009-02-18 19:21:10 +00001407
Chris Lattner719e6152009-02-18 19:21:10 +00001408 const char *SpellingStart = SpellingPtr;
1409 const char *SpellingEnd = SpellingPtr+TokLen;
1410
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001411 // Handle UTF-8 strings just like narrow strings.
1412 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1413 SpellingPtr += 2;
1414
1415 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1416 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1417
1418 // For raw string literals, this is easy.
1419 if (SpellingPtr[0] == 'R') {
1420 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1421 // Skip 'R"'.
1422 SpellingPtr += 2;
1423 while (*SpellingPtr != '(') {
1424 ++SpellingPtr;
1425 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1426 }
1427 // Skip '('.
1428 ++SpellingPtr;
1429 return SpellingPtr - SpellingStart + ByteNo;
1430 }
1431
1432 // Skip over the leading quote
Chris Lattner719e6152009-02-18 19:21:10 +00001433 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1434 ++SpellingPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Chris Lattner719e6152009-02-18 19:21:10 +00001436 // Skip over bytes until we find the offset we're looking for.
1437 while (ByteNo) {
1438 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattner719e6152009-02-18 19:21:10 +00001440 // Step over non-escapes simply.
1441 if (*SpellingPtr != '\\') {
1442 ++SpellingPtr;
1443 --ByteNo;
1444 continue;
1445 }
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Chris Lattner719e6152009-02-18 19:21:10 +00001447 // Otherwise, this is an escape character. Advance over it.
1448 bool HadError = false;
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001449 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1450 const char *EscapePtr = SpellingPtr;
1451 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1452 1, Features, HadError);
1453 if (Len > ByteNo) {
1454 // ByteNo is somewhere within the escape sequence.
1455 SpellingPtr = EscapePtr;
1456 break;
1457 }
1458 ByteNo -= Len;
1459 } else {
1460 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
1461 FullSourceLoc(Tok.getLocation(), SM),
1462 CharByteWidth*8, Diags);
1463 --ByteNo;
1464 }
Chris Lattner719e6152009-02-18 19:21:10 +00001465 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattner719e6152009-02-18 19:21:10 +00001466 }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Chris Lattner719e6152009-02-18 19:21:10 +00001468 return SpellingPtr-SpellingStart;
1469}