blob: 9b0bc70345420b6a47469a66b2f0966733618938 [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
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000792/// user-defined-character-literal: [C++11 lex.ext]
793/// character-literal ud-suffix
794/// ud-suffix:
795/// identifier
796/// character-literal: [C++11 lex.ccon]
Craig Topper2fa4e862011-08-11 04:06:15 +0000797/// ' c-char-sequence '
798/// u' c-char-sequence '
799/// U' c-char-sequence '
800/// L' c-char-sequence '
801/// c-char-sequence:
802/// c-char
803/// c-char-sequence c-char
804/// c-char:
805/// any member of the source character set except the single-quote ',
806/// backslash \, or new-line character
807/// escape-sequence
808/// universal-character-name
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000809/// escape-sequence:
Craig Topper2fa4e862011-08-11 04:06:15 +0000810/// simple-escape-sequence
811/// octal-escape-sequence
812/// hexadecimal-escape-sequence
813/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +0000814/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +0000815/// octal-escape-sequence:
816/// \ octal-digit
817/// \ octal-digit octal-digit
818/// \ octal-digit octal-digit octal-digit
819/// hexadecimal-escape-sequence:
820/// \x hexadecimal-digit
821/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000822/// universal-character-name: [C++11 lex.charset]
Craig Topper2fa4e862011-08-11 04:06:15 +0000823/// \u hex-quad
824/// \U hex-quad hex-quad
825/// hex-quad:
826/// hex-digit hex-digit hex-digit hex-digit
827///
Reid Spencer5f016e22007-07-11 17:01:13 +0000828CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000829 SourceLocation Loc, Preprocessor &PP,
830 tok::TokenKind kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000831 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregor5cee1192011-07-27 05:40:30 +0000834 Kind = kind;
835
Richard Smith26b75c02012-03-09 22:27:51 +0000836 const char *TokBegin = begin;
837
Seth Cantrellbe773522012-01-18 12:27:04 +0000838 // Skip over wide character determinant.
839 if (Kind != tok::char_constant) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000840 ++begin;
841 }
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 // Skip over the entry quote.
844 assert(begin[0] == '\'' && "Invalid token lexed");
845 ++begin;
846
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000847 // Remove an optional ud-suffix.
848 if (end[-1] != '\'') {
849 const char *UDSuffixEnd = end;
850 do {
851 --end;
852 } while (end[-1] != '\'');
853 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith26b75c02012-03-09 22:27:51 +0000854 UDSuffixOffset = end - TokBegin;
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000855 }
856
Seth Cantrellbe773522012-01-18 12:27:04 +0000857 // Trim the ending quote.
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000858 assert(end != begin && "Invalid token lexed");
Seth Cantrellbe773522012-01-18 12:27:04 +0000859 --end;
860
Mike Stump1eb44332009-09-09 15:08:12 +0000861 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000862 // up to 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000864 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000866 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
867 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
868 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
869 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
870 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000871
Seth Cantrellbe773522012-01-18 12:27:04 +0000872 SmallVector<uint32_t,4> codepoint_buffer;
873 codepoint_buffer.resize(end-begin);
874 uint32_t *buffer_begin = &codepoint_buffer.front();
875 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Seth Cantrellbe773522012-01-18 12:27:04 +0000877 // Unicode escapes representing characters that cannot be correctly
878 // represented in a single code unit are disallowed in character literals
879 // by this implementation.
880 uint32_t largest_character_for_kind;
881 if (tok::wide_char_constant == Kind) {
882 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
883 } else if (tok::utf16_char_constant == Kind) {
884 largest_character_for_kind = 0xFFFF;
885 } else if (tok::utf32_char_constant == Kind) {
886 largest_character_for_kind = 0x10FFFF;
887 } else {
888 largest_character_for_kind = 0x7Fu;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000889 }
890
Seth Cantrellbe773522012-01-18 12:27:04 +0000891 while (begin!=end) {
892 // Is this a span of non-escape characters?
893 if (begin[0] != '\\') {
894 char const *start = begin;
895 do {
896 ++begin;
897 } while (begin != end && *begin != '\\');
898
Eli Friedman91359302012-02-11 05:08:10 +0000899 char const *tmp_in_start = start;
900 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrellbe773522012-01-18 12:27:04 +0000901 ConversionResult res =
902 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
903 reinterpret_cast<UTF8 const *>(begin),
904 &buffer_begin,buffer_end,strictConversion);
905 if (res!=conversionOK) {
Eli Friedman91359302012-02-11 05:08:10 +0000906 // If we see bad encoding for unprefixed character literals, warn and
907 // simply copy the byte values, for compatibility with gcc and
908 // older versions of clang.
909 bool NoErrorOnBadEncoding = isAscii();
910 unsigned Msg = diag::err_bad_character_encoding;
911 if (NoErrorOnBadEncoding)
912 Msg = diag::warn_bad_character_encoding;
913 PP.Diag(Loc, Msg);
914 if (NoErrorOnBadEncoding) {
915 start = tmp_in_start;
916 buffer_begin = tmp_out_start;
917 for ( ; start != begin; ++start, ++buffer_begin)
918 *buffer_begin = static_cast<uint8_t>(*start);
919 } else {
920 HadError = true;
921 }
Seth Cantrellbe773522012-01-18 12:27:04 +0000922 } else {
Eli Friedman91359302012-02-11 05:08:10 +0000923 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
924 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000925 HadError = true;
926 PP.Diag(Loc, diag::err_character_too_large);
927 }
928 }
929 }
930
931 continue;
932 }
933 // Is this a Universal Character Name excape?
934 if (begin[1] == 'u' || begin[1] == 'U') {
935 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000936 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrellbe773522012-01-18 12:27:04 +0000937 FullSourceLoc(Loc, PP.getSourceManager()),
David Blaikie4e4d0842012-03-11 07:00:24 +0000938 &PP.getDiagnostics(), PP.getLangOpts(),
Seth Cantrellbe773522012-01-18 12:27:04 +0000939 true))
940 {
941 HadError = true;
942 } else if (*buffer_begin > largest_character_for_kind) {
943 HadError = true;
944 PP.Diag(Loc,diag::err_character_too_large);
945 }
946
947 ++buffer_begin;
948 continue;
949 }
950 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
951 uint64_t result =
952 ProcessCharEscape(begin, end, HadError,
953 FullSourceLoc(Loc,PP.getSourceManager()),
954 CharWidth, &PP.getDiagnostics());
955 *buffer_begin++ = result;
956 }
957
958 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
959
Chris Lattnere3ad8812009-04-28 21:51:46 +0000960 if (NumCharsSoFar > 1) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000961 if (isWide())
Douglas Gregor5cee1192011-07-27 05:40:30 +0000962 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrellbe773522012-01-18 12:27:04 +0000963 else if (isAscii() && NumCharsSoFar == 4)
964 PP.Diag(Loc, diag::ext_four_char_character_literal);
965 else if (isAscii())
Chris Lattnere3ad8812009-04-28 21:51:46 +0000966 PP.Diag(Loc, diag::ext_multichar_character_literal);
967 else
Seth Cantrellbe773522012-01-18 12:27:04 +0000968 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000969 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000970 } else
971 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000972
Seth Cantrellbe773522012-01-18 12:27:04 +0000973 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
974
975 // Narrow character literals act as though their value is concatenated
976 // in this implementation, but warn on overflow.
977 bool multi_char_too_long = false;
978 if (isAscii() && isMultiChar()) {
979 LitVal = 0;
980 for (size_t i=0;i<NumCharsSoFar;++i) {
981 // check for enough leading zeros to shift into
982 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
983 LitVal <<= 8;
984 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
985 }
986 } else if (NumCharsSoFar > 0) {
987 // otherwise just take the last character
988 LitVal = buffer_begin[-1];
989 }
990
991 if (!HadError && multi_char_too_long) {
992 PP.Diag(Loc,diag::warn_char_constant_too_large);
993 }
994
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000995 // Transfer the value from APInt to uint64_t
996 Value = LitVal.getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Reid Spencer5f016e22007-07-11 17:01:13 +0000998 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
999 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1000 // character constants are not sign extended in the this implementation:
1001 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001002 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001003 PP.getLangOpts().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 Value = (signed char)Value;
1005}
1006
1007
Craig Topper2fa4e862011-08-11 04:06:15 +00001008/// string-literal: [C++0x lex.string]
1009/// encoding-prefix " [s-char-sequence] "
1010/// encoding-prefix R raw-string
1011/// encoding-prefix:
1012/// u8
1013/// u
1014/// U
1015/// L
Reid Spencer5f016e22007-07-11 17:01:13 +00001016/// s-char-sequence:
1017/// s-char
1018/// s-char-sequence s-char
1019/// s-char:
Craig Topper2fa4e862011-08-11 04:06:15 +00001020/// any member of the source character set except the double-quote ",
1021/// backslash \, or new-line character
1022/// escape-sequence
Reid Spencer5f016e22007-07-11 17:01:13 +00001023/// universal-character-name
Craig Topper2fa4e862011-08-11 04:06:15 +00001024/// raw-string:
1025/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1026/// r-char-sequence:
1027/// r-char
1028/// r-char-sequence r-char
1029/// r-char:
1030/// any member of the source character set, except a right parenthesis )
1031/// followed by the initial d-char-sequence (which may be empty)
1032/// followed by a double quote ".
1033/// d-char-sequence:
1034/// d-char
1035/// d-char-sequence d-char
1036/// d-char:
1037/// any member of the basic source character set except:
1038/// space, the left parenthesis (, the right parenthesis ),
1039/// the backslash \, and the control characters representing horizontal
1040/// tab, vertical tab, form feed, and newline.
1041/// escape-sequence: [C++0x lex.ccon]
1042/// simple-escape-sequence
1043/// octal-escape-sequence
1044/// hexadecimal-escape-sequence
1045/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +00001046/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +00001047/// octal-escape-sequence:
1048/// \ octal-digit
1049/// \ octal-digit octal-digit
1050/// \ octal-digit octal-digit octal-digit
1051/// hexadecimal-escape-sequence:
1052/// \x hexadecimal-digit
1053/// hexadecimal-escape-sequence hexadecimal-digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001054/// universal-character-name:
1055/// \u hex-quad
1056/// \U hex-quad hex-quad
1057/// hex-quad:
1058/// hex-digit hex-digit hex-digit hex-digit
1059///
1060StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +00001061StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner0833dd02010-11-17 07:21:13 +00001062 Preprocessor &PP, bool Complain)
David Blaikie4e4d0842012-03-11 07:00:24 +00001063 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001064 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001065 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1066 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner0833dd02010-11-17 07:21:13 +00001067 init(StringToks, NumStringToks);
1068}
1069
1070void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001071 // The literal token may have come from an invalid source location (e.g. due
1072 // to a PCH error), in which case the token length will be 0.
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001073 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1074 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 // Scan all of the string portions, remember the max individual token length,
1077 // computing a bound on the concatenated string length, and see whether any
1078 // piece is a wide-string. If any of the string portions is a wide-string
1079 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001080 assert(NumStringToks && "expected at least one token");
Sean Hunt6cf75022010-08-30 17:47:05 +00001081 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001082 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001083 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001084 Kind = StringToks[0].getKind();
Sean Hunt6cf75022010-08-30 17:47:05 +00001085
1086 hadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001087
1088 // Implement Translation Phase #6: concatenation of string literals
1089 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1090 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001091 if (StringToks[i].getLength() < 2)
1092 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 // The string could be shorter than this if it needs cleaning, but this is a
1095 // reasonable bound, which is all we need.
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001096 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001097 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 // Remember maximum string piece length.
Sean Hunt6cf75022010-08-30 17:47:05 +00001100 if (StringToks[i].getLength() > MaxTokenLength)
1101 MaxTokenLength = StringToks[i].getLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregor5cee1192011-07-27 05:40:30 +00001103 // Remember if we see any wide or utf-8/16/32 strings.
1104 // Also check for illegal concatenations.
1105 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1106 if (isAscii()) {
1107 Kind = StringToks[i].getKind();
1108 } else {
1109 if (Diags)
1110 Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
1111 diag::err_unsupported_string_concat);
1112 hadError = true;
1113 }
1114 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001116
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 // Include space for the null terminator.
1118 ++SizeBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Douglas Gregor5cee1192011-07-27 05:40:30 +00001122 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1123 CharByteWidth = getCharWidth(Kind, Target);
1124 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1125 CharByteWidth /= 8;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 // The output buffer size needs to be large enough to hold wide characters.
1128 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001129 SizeBound *= CharByteWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 // Size the temporary buffer to hold the result string data.
1132 ResultBuf.resize(SizeBound);
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 // Likewise, but for each string piece.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001135 SmallString<512> TokenBuf;
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 TokenBuf.resize(MaxTokenLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 // Loop over all the strings, getting their spelling, and expanding them to
1139 // wide strings as appropriate.
1140 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Anders Carlssonee98ac52007-10-15 02:50:23 +00001142 Pascal = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001144 SourceLocation UDSuffixTokLoc;
1145
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1147 const char *ThisTokBuf = &TokenBuf[0];
1148 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1149 // that ThisTokBuf points to a buffer that is big enough for the whole token
1150 // and 'spelled' tokens can only shrink.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001151 bool StringInvalid = false;
Chris Lattner0833dd02010-11-17 07:21:13 +00001152 unsigned ThisTokLen =
Chris Lattnerb0607272010-11-17 07:26:20 +00001153 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1154 &StringInvalid);
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001155 if (StringInvalid)
1156 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor50f6af72010-03-16 05:20:39 +00001157
Richard Smith26b75c02012-03-09 22:27:51 +00001158 const char *ThisTokBegin = ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001159 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1160
1161 // Remove an optional ud-suffix.
1162 if (ThisTokEnd[-1] != '"') {
1163 const char *UDSuffixEnd = ThisTokEnd;
1164 do {
1165 --ThisTokEnd;
1166 } while (ThisTokEnd[-1] != '"');
1167
1168 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1169
1170 if (UDSuffixBuf.empty()) {
1171 UDSuffixBuf.assign(UDSuffix);
Richard Smithdd66be72012-03-08 01:34:56 +00001172 UDSuffixToken = i;
1173 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001174 UDSuffixTokLoc = StringToks[i].getLocation();
1175 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1176 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1177 // result of a concatenation involving at least one user-defined-string-
1178 // literal, all the participating user-defined-string-literals shall
1179 // have the same ud-suffix.
1180 if (Diags) {
1181 SourceLocation TokLoc = StringToks[i].getLocation();
1182 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1183 << UDSuffixBuf << UDSuffix
1184 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1185 << SourceRange(TokLoc, TokLoc);
1186 }
1187 hadError = true;
1188 }
1189 }
1190
1191 // Strip the end quote.
1192 --ThisTokEnd;
1193
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 // TODO: Input character set mapping support.
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Craig Topper1661d712011-08-08 06:10:39 +00001196 // Skip marker for wide or unicode strings.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001197 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 ++ThisTokBuf;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001199 // Skip 8 of u8 marker for utf8 strings.
1200 if (ThisTokBuf[0] == '8')
1201 ++ThisTokBuf;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +00001202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Craig Topper2fa4e862011-08-11 04:06:15 +00001204 // Check for raw string
1205 if (ThisTokBuf[0] == 'R') {
1206 ThisTokBuf += 2; // skip R"
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Craig Topper2fa4e862011-08-11 04:06:15 +00001208 const char *Prefix = ThisTokBuf;
1209 while (ThisTokBuf[0] != '(')
Anders Carlssonee98ac52007-10-15 02:50:23 +00001210 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001211 ++ThisTokBuf; // skip '('
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Richard Smith49d51742012-03-08 21:59:28 +00001213 // Remove same number of characters from the end
1214 ThisTokEnd -= ThisTokBuf - Prefix;
1215 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper2fa4e862011-08-11 04:06:15 +00001216
1217 // Copy the string over
Richard Smith49d51742012-03-08 21:59:28 +00001218 if (CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
Eli Friedman91359302012-02-11 05:08:10 +00001219 if (DiagnoseBadString(StringToks[i]))
1220 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001221 } else {
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001222 if (ThisTokBuf[0] != '"') {
1223 // The file may have come from PCH and then changed after loading the
1224 // PCH; Fail gracefully.
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001225 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001226 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001227 ++ThisTokBuf; // skip "
1228
1229 // Check if this is a pascal string
1230 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1231 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1232
1233 // If the \p sequence is found in the first token, we have a pascal string
1234 // Otherwise, if we already have a pascal string, ignore the first \p
1235 if (i == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001237 Pascal = true;
1238 } else if (Pascal)
1239 ThisTokBuf += 2;
1240 }
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Craig Topper2fa4e862011-08-11 04:06:15 +00001242 while (ThisTokBuf != ThisTokEnd) {
1243 // Is this a span of non-escape characters?
1244 if (ThisTokBuf[0] != '\\') {
1245 const char *InStart = ThisTokBuf;
1246 do {
1247 ++ThisTokBuf;
1248 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1249
1250 // Copy the character span over.
Richard Smith49d51742012-03-08 21:59:28 +00001251 if (CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart)))
Eli Friedman91359302012-02-11 05:08:10 +00001252 if (DiagnoseBadString(StringToks[i]))
1253 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001254 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001255 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001256 // Is this a Universal Character Name escape?
1257 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith26b75c02012-03-09 22:27:51 +00001258 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1259 ResultPtr, hadError,
1260 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper2fa4e862011-08-11 04:06:15 +00001261 CharByteWidth, Diags, Features);
1262 continue;
1263 }
1264 // Otherwise, this is a non-UCN escape character. Process it.
1265 unsigned ResultChar =
1266 ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
1267 FullSourceLoc(StringToks[i].getLocation(), SM),
1268 CharByteWidth*8, Diags);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Eli Friedmancaf1f262011-11-02 23:06:23 +00001270 if (CharByteWidth == 4) {
1271 // FIXME: Make the type of the result buffer correct instead of
1272 // using reinterpret_cast.
1273 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001274 *ResultWidePtr = ResultChar;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001275 ResultPtr += 4;
1276 } else if (CharByteWidth == 2) {
1277 // FIXME: Make the type of the result buffer correct instead of
1278 // using reinterpret_cast.
1279 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001280 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001281 ResultPtr += 2;
1282 } else {
1283 assert(CharByteWidth == 1 && "Unexpected char width");
1284 *ResultPtr++ = ResultChar & 0xFF;
1285 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001286 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 }
1288 }
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001290 if (Pascal) {
Eli Friedman22508f42011-11-05 00:41:04 +00001291 if (CharByteWidth == 4) {
1292 // FIXME: Make the type of the result buffer correct instead of
1293 // using reinterpret_cast.
1294 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1295 ResultWidePtr[0] = GetNumStringChars() - 1;
1296 } else if (CharByteWidth == 2) {
1297 // FIXME: Make the type of the result buffer correct instead of
1298 // using reinterpret_cast.
1299 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1300 ResultWidePtr[0] = GetNumStringChars() - 1;
1301 } else {
1302 assert(CharByteWidth == 1 && "Unexpected char width");
1303 ResultBuf[0] = GetNumStringChars() - 1;
1304 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001305
1306 // Verify that pascal strings aren't too large.
Chris Lattner0833dd02010-11-17 07:21:13 +00001307 if (GetStringLength() > 256) {
1308 if (Diags)
1309 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1310 diag::err_pascal_string_too_long)
1311 << SourceRange(StringToks[0].getLocation(),
1312 StringToks[NumStringToks-1].getLocation());
Douglas Gregor5cee1192011-07-27 05:40:30 +00001313 hadError = true;
Eli Friedman57d7dde2009-04-01 03:17:08 +00001314 return;
1315 }
Chris Lattner0833dd02010-11-17 07:21:13 +00001316 } else if (Diags) {
Douglas Gregor427c4922010-07-20 14:33:20 +00001317 // Complain if this string literal has too many characters.
Chris Lattnera95880d2010-11-17 07:12:42 +00001318 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Douglas Gregor427c4922010-07-20 14:33:20 +00001319
1320 if (GetNumStringChars() > MaxChars)
Chris Lattner0833dd02010-11-17 07:21:13 +00001321 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1322 diag::ext_string_too_long)
Douglas Gregor427c4922010-07-20 14:33:20 +00001323 << GetNumStringChars() << MaxChars
Chris Lattnera95880d2010-11-17 07:12:42 +00001324 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregor427c4922010-07-20 14:33:20 +00001325 << SourceRange(StringToks[0].getLocation(),
1326 StringToks[NumStringToks-1].getLocation());
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001327 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001328}
Chris Lattner719e6152009-02-18 19:21:10 +00001329
1330
Craig Topper2fa4e862011-08-11 04:06:15 +00001331/// copyStringFragment - This function copies from Start to End into ResultPtr.
1332/// Performs widening for multi-byte characters.
Eli Friedmanf74a4582011-11-01 02:14:50 +00001333bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
1334 assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
1335 ConversionResult result = conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001336 // Copy the character span over.
1337 if (CharByteWidth == 1) {
Richard Smith49d51742012-03-08 21:59:28 +00001338 if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(Fragment.begin()),
1339 reinterpret_cast<const UTF8*>(Fragment.end())))
Eli Friedman91359302012-02-11 05:08:10 +00001340 result = sourceIllegal;
Craig Topper2fa4e862011-08-11 04:06:15 +00001341 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1342 ResultPtr += Fragment.size();
Eli Friedmanf74a4582011-11-01 02:14:50 +00001343 } else if (CharByteWidth == 2) {
1344 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1345 // FIXME: Make the type of the result buffer correct instead of
1346 // using reinterpret_cast.
1347 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001348 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001349 result = ConvertUTF8toUTF16(
1350 &sourceStart,sourceStart + Fragment.size(),
1351 &targetStart,targetStart + 2*Fragment.size(),flags);
1352 if (result==conversionOK)
1353 ResultPtr = reinterpret_cast<char*>(targetStart);
1354 } else if (CharByteWidth == 4) {
1355 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1356 // FIXME: Make the type of the result buffer correct instead of
1357 // using reinterpret_cast.
1358 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001359 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001360 result = ConvertUTF8toUTF32(
1361 &sourceStart,sourceStart + Fragment.size(),
1362 &targetStart,targetStart + 4*Fragment.size(),flags);
1363 if (result==conversionOK)
1364 ResultPtr = reinterpret_cast<char*>(targetStart);
Craig Topper2fa4e862011-08-11 04:06:15 +00001365 }
Eli Friedmanf74a4582011-11-01 02:14:50 +00001366 assert((result != targetExhausted)
1367 && "ConvertUTF8toUTFXX exhausted target buffer");
1368 return result != conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001369}
1370
Eli Friedman91359302012-02-11 05:08:10 +00001371bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
1372 // If we see bad encoding for unprefixed string literals, warn and
1373 // simply copy the byte values, for compatibility with gcc and older
1374 // versions of clang.
1375 bool NoErrorOnBadEncoding = isAscii();
1376 unsigned Msg = NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
1377 diag::err_bad_string_encoding;
1378 if (Diags)
1379 Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
1380 return !NoErrorOnBadEncoding;
1381}
Craig Topper2fa4e862011-08-11 04:06:15 +00001382
Argyrios Kyrtzidis31447492012-05-03 17:50:32 +00001383void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1384 hadError = true;
1385 if (Diags)
1386 Diags->Report(Loc, diag::err_lexing_string);
1387}
1388
Chris Lattner719e6152009-02-18 19:21:10 +00001389/// getOffsetOfStringByte - This function returns the offset of the
1390/// specified byte of the string data represented by Token. This handles
1391/// advancing over escape sequences in the string.
1392unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattner6c66f072010-11-17 06:46:14 +00001393 unsigned ByteNo) const {
Chris Lattner719e6152009-02-18 19:21:10 +00001394 // Get the spelling of the token.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001395 SmallString<32> SpellingBuffer;
Sean Hunt6cf75022010-08-30 17:47:05 +00001396 SpellingBuffer.resize(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Douglas Gregor50f6af72010-03-16 05:20:39 +00001398 bool StringInvalid = false;
Chris Lattner719e6152009-02-18 19:21:10 +00001399 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattnerb0607272010-11-17 07:26:20 +00001400 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1401 &StringInvalid);
Chris Lattner91f54ce2010-11-17 06:26:08 +00001402 if (StringInvalid)
Douglas Gregor50f6af72010-03-16 05:20:39 +00001403 return 0;
Chris Lattner719e6152009-02-18 19:21:10 +00001404
Chris Lattner719e6152009-02-18 19:21:10 +00001405 const char *SpellingStart = SpellingPtr;
1406 const char *SpellingEnd = SpellingPtr+TokLen;
1407
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001408 // Handle UTF-8 strings just like narrow strings.
1409 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1410 SpellingPtr += 2;
1411
1412 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1413 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1414
1415 // For raw string literals, this is easy.
1416 if (SpellingPtr[0] == 'R') {
1417 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1418 // Skip 'R"'.
1419 SpellingPtr += 2;
1420 while (*SpellingPtr != '(') {
1421 ++SpellingPtr;
1422 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1423 }
1424 // Skip '('.
1425 ++SpellingPtr;
1426 return SpellingPtr - SpellingStart + ByteNo;
1427 }
1428
1429 // Skip over the leading quote
Chris Lattner719e6152009-02-18 19:21:10 +00001430 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1431 ++SpellingPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Chris Lattner719e6152009-02-18 19:21:10 +00001433 // Skip over bytes until we find the offset we're looking for.
1434 while (ByteNo) {
1435 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Chris Lattner719e6152009-02-18 19:21:10 +00001437 // Step over non-escapes simply.
1438 if (*SpellingPtr != '\\') {
1439 ++SpellingPtr;
1440 --ByteNo;
1441 continue;
1442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Chris Lattner719e6152009-02-18 19:21:10 +00001444 // Otherwise, this is an escape character. Advance over it.
1445 bool HadError = false;
Richard Smithdf9ef1b2012-06-13 05:37:23 +00001446 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1447 const char *EscapePtr = SpellingPtr;
1448 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1449 1, Features, HadError);
1450 if (Len > ByteNo) {
1451 // ByteNo is somewhere within the escape sequence.
1452 SpellingPtr = EscapePtr;
1453 break;
1454 }
1455 ByteNo -= Len;
1456 } else {
1457 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
1458 FullSourceLoc(Tok.getLocation(), SM),
1459 CharByteWidth*8, Diags);
1460 --ByteNo;
1461 }
Chris Lattner719e6152009-02-18 19:21:10 +00001462 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattner719e6152009-02-18 19:21:10 +00001463 }
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattner719e6152009-02-18 19:21:10 +00001465 return SpellingPtr-SpellingStart;
1466}