blob: b01fc1f8c6b3c286b137414282ef2b0f6b27ec6c [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
253/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
254/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
255/// StringLiteralParser. When we decide to implement UCN's for identifiers,
256/// we will likely rework our support for UCN's.
Richard Smith26b75c02012-03-09 22:27:51 +0000257static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
258 const char *ThisTokEnd,
Chris Lattnera95880d2010-11-17 07:12:42 +0000259 char *&ResultBuf, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000260 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikied6471f72011-09-25 23:23:43 +0000261 DiagnosticsEngine *Diags,
262 const LangOptions &Features) {
Nico Weber59705ae2010-10-09 00:27:47 +0000263 typedef uint32_t UTF32;
264 UTF32 UcnVal = 0;
265 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000266 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
267 Loc, Diags, Features, true)) {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000268 HadError = 1;
269 return;
270 }
Nico Weber59705ae2010-10-09 00:27:47 +0000271
Douglas Gregor5cee1192011-07-27 05:40:30 +0000272 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
273 "only character widths of 1, 2, or 4 bytes supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000274
Douglas Gregor5cee1192011-07-27 05:40:30 +0000275 (void)UcnLen;
276 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000277
Douglas Gregor5cee1192011-07-27 05:40:30 +0000278 if (CharByteWidth == 4) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000279 // FIXME: Make the type of the result buffer correct instead of
280 // using reinterpret_cast.
281 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
282 *ResultPtr = UcnVal;
283 ResultBuf += 4;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000284 return;
285 }
286
287 if (CharByteWidth == 2) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000288 // FIXME: Make the type of the result buffer correct instead of
289 // using reinterpret_cast.
290 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
291
Nico Webera0f15b02010-10-06 04:57:26 +0000292 if (UcnVal < (UTF32)0xFFFF) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000293 *ResultPtr = UcnVal;
294 ResultBuf += 2;
Nico Webera0f15b02010-10-06 04:57:26 +0000295 return;
296 }
Nico Webera0f15b02010-10-06 04:57:26 +0000297
Eli Friedmancaf1f262011-11-02 23:06:23 +0000298 // Convert to UTF16.
Nico Webera0f15b02010-10-06 04:57:26 +0000299 UcnVal -= 0x10000;
Eli Friedmancaf1f262011-11-02 23:06:23 +0000300 *ResultPtr = 0xD800 + (UcnVal >> 10);
301 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
302 ResultBuf += 4;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000303 return;
304 }
Douglas Gregor5cee1192011-07-27 05:40:30 +0000305
306 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
307
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000308 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
309 // The conversion below was inspired by:
310 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump1eb44332009-09-09 15:08:12 +0000311 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000312 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000313
314 unsigned short bytesToWrite = 0;
315 if (UcnVal < (UTF32)0x80)
316 bytesToWrite = 1;
317 else if (UcnVal < (UTF32)0x800)
318 bytesToWrite = 2;
319 else if (UcnVal < (UTF32)0x10000)
320 bytesToWrite = 3;
321 else
322 bytesToWrite = 4;
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000324 const unsigned byteMask = 0xBF;
325 const unsigned byteMark = 0x80;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000327 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000328 // into the first byte, depending on how many bytes follow.
Mike Stump1eb44332009-09-09 15:08:12 +0000329 static const UTF8 firstByteMark[5] = {
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000330 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000331 };
332 // Finally, we write the bytes into ResultBuf.
333 ResultBuf += bytesToWrite;
334 switch (bytesToWrite) { // note: everything falls through.
335 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
336 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
337 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
338 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
339 }
340 // Update the buffer.
341 ResultBuf += bytesToWrite;
342}
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
344
345/// integer-constant: [C99 6.4.4.1]
346/// decimal-constant integer-suffix
347/// octal-constant integer-suffix
348/// hexadecimal-constant integer-suffix
Richard Smith49d51742012-03-08 21:59:28 +0000349/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smithb453ad32012-03-08 08:45:32 +0000350/// decimal-literal ud-suffix
351/// octal-literal ud-suffix
352/// hexadecimal-literal ud-suffix
Mike Stump1eb44332009-09-09 15:08:12 +0000353/// decimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000354/// nonzero-digit
355/// decimal-constant digit
Mike Stump1eb44332009-09-09 15:08:12 +0000356/// octal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000357/// 0
358/// octal-constant octal-digit
Mike Stump1eb44332009-09-09 15:08:12 +0000359/// hexadecimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000360/// hexadecimal-prefix hexadecimal-digit
361/// hexadecimal-constant hexadecimal-digit
362/// hexadecimal-prefix: one of
363/// 0x 0X
364/// integer-suffix:
365/// unsigned-suffix [long-suffix]
366/// unsigned-suffix [long-long-suffix]
367/// long-suffix [unsigned-suffix]
368/// long-long-suffix [unsigned-sufix]
369/// nonzero-digit:
370/// 1 2 3 4 5 6 7 8 9
371/// octal-digit:
372/// 0 1 2 3 4 5 6 7
373/// hexadecimal-digit:
374/// 0 1 2 3 4 5 6 7 8 9
375/// a b c d e f
376/// A B C D E F
377/// unsigned-suffix: one of
378/// u U
379/// long-suffix: one of
380/// l L
Mike Stump1eb44332009-09-09 15:08:12 +0000381/// long-long-suffix: one of
Reid Spencer5f016e22007-07-11 17:01:13 +0000382/// ll LL
383///
384/// floating-constant: [C99 6.4.4.2]
385/// TODO: add rules...
386///
Reid Spencer5f016e22007-07-11 17:01:13 +0000387NumericLiteralParser::
388NumericLiteralParser(const char *begin, const char *end,
389 SourceLocation TokLoc, Preprocessor &pp)
390 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000392 // This routine assumes that the range begin/end matches the regex for integer
393 // and FP constants (specifically, the 'pp-number' regex), and assumes that
394 // the byte at "*end" is both valid and not part of the regex. Because of
395 // this, it doesn't have to check for 'overscan' in various places.
396 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
397 "Lexer didn't maximally munch?");
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 s = DigitsBegin = begin;
400 saw_exponent = false;
401 saw_period = false;
Richard Smithb453ad32012-03-08 08:45:32 +0000402 saw_ud_suffix = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 isLong = false;
404 isUnsigned = false;
405 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000406 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000407 isImaginary = false;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000408 isMicrosoftInteger = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 hadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000412 ParseNumberStartingWithZero(TokLoc);
413 if (hadError)
414 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 } else { // the first digit is non-zero
416 radix = 10;
417 s = SkipDigits(s);
418 if (s == ThisTokEnd) {
419 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000420 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000421 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000422 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000423 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 return;
425 } else if (*s == '.') {
426 s++;
427 saw_period = true;
428 s = SkipDigits(s);
Mike Stump1eb44332009-09-09 15:08:12 +0000429 }
Chris Lattner4411f462008-09-29 23:12:31 +0000430 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000431 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 s++;
433 saw_exponent = true;
434 if (*s == '+' || *s == '-') s++; // sign
435 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000436 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000438 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000439 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
440 diag::err_exponent_has_no_digits);
441 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000442 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 }
444 }
445 }
446
447 SuffixBegin = s;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Chris Lattner506b8de2007-08-26 01:58:14 +0000449 // Parse the suffix. At this point we can classify whether we have an FP or
450 // integer constant.
451 bool isFPConstant = isFloatingLiteral();
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner506b8de2007-08-26 01:58:14 +0000453 // Loop over all of the characters of the suffix. If we see something bad,
454 // we break out of the loop.
455 for (; s != ThisTokEnd; ++s) {
456 switch (*s) {
457 case 'f': // FP Suffix for "float"
458 case 'F':
459 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000460 if (isFloat || isLong) break; // FF, LF invalid.
461 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000462 continue; // Success.
463 case 'u':
464 case 'U':
465 if (isFPConstant) break; // Error for floating constant.
466 if (isUnsigned) break; // Cannot be repeated.
467 isUnsigned = true;
468 continue; // Success.
469 case 'l':
470 case 'L':
471 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000472 if (isFloat) break; // LF invalid.
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner506b8de2007-08-26 01:58:14 +0000474 // Check for long long. The L's need to be adjacent and the same case.
475 if (s+1 != ThisTokEnd && s[1] == s[0]) {
476 if (isFPConstant) break; // long long invalid for floats.
477 isLongLong = true;
478 ++s; // Eat both of them.
479 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000482 continue; // Success.
483 case 'i':
Chris Lattnerc6374152010-10-14 00:24:10 +0000484 case 'I':
David Blaikie4e4d0842012-03-11 07:00:24 +0000485 if (PP.getLangOpts().MicrosoftExt) {
Fariborz Jahaniana8be02b2010-01-22 21:36:53 +0000486 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000487
Steve Naroff0c29b222008-04-04 21:02:54 +0000488 // Allow i8, i16, i32, i64, and i128.
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000489 if (s + 1 != ThisTokEnd) {
490 switch (s[1]) {
491 case '8':
492 s += 2; // i8 suffix
493 isMicrosoftInteger = true;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000494 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000495 case '1':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000496 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000497 if (s[2] == '6') {
498 s += 3; // i16 suffix
499 isMicrosoftInteger = true;
500 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000501 else if (s[2] == '2') {
502 if (s + 3 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000503 if (s[3] == '8') {
504 s += 4; // i128 suffix
505 isMicrosoftInteger = true;
506 }
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000507 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000508 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000509 case '3':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000510 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000511 if (s[2] == '2') {
512 s += 3; // i32 suffix
513 isLong = true;
514 isMicrosoftInteger = true;
515 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000516 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000517 case '6':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000518 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000519 if (s[2] == '4') {
520 s += 3; // i64 suffix
521 isLongLong = true;
522 isMicrosoftInteger = true;
523 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000524 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000525 default:
526 break;
527 }
528 break;
Steve Naroff0c29b222008-04-04 21:02:54 +0000529 }
Steve Naroff0c29b222008-04-04 21:02:54 +0000530 }
531 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000532 case 'j':
533 case 'J':
534 if (isImaginary) break; // Cannot be repeated.
535 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
536 diag::ext_imaginary_constant);
537 isImaginary = true;
538 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 }
Richard Smithb453ad32012-03-08 08:45:32 +0000540 // If we reached here, there was an error or a ud-suffix.
Chris Lattner506b8de2007-08-26 01:58:14 +0000541 break;
542 }
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner506b8de2007-08-26 01:58:14 +0000544 if (s != ThisTokEnd) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000545 if (PP.getLangOpts().CPlusPlus0x && s == SuffixBegin && *s == '_') {
Richard Smithb453ad32012-03-08 08:45:32 +0000546 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
547 // with an '_' are ill-formed.
548 saw_ud_suffix = true;
549 return;
550 }
551
552 // Report an error if there are any.
553 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin-begin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000554 isFPConstant ? diag::err_invalid_suffix_float_constant :
555 diag::err_invalid_suffix_integer_constant)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000556 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattnerac92d822008-11-22 07:23:31 +0000557 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000558 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 }
560}
561
Chris Lattner368328c2008-06-30 06:39:54 +0000562/// ParseNumberStartingWithZero - This method is called when the first character
563/// of the number is found to be a zero. This means it is either an octal
564/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump1eb44332009-09-09 15:08:12 +0000565/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner368328c2008-06-30 06:39:54 +0000566/// radix etc.
567void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
568 assert(s[0] == '0' && "Invalid method call");
569 s++;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattner368328c2008-06-30 06:39:54 +0000571 // Handle a hex number like 0x1234.
572 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
573 s++;
574 radix = 16;
575 DigitsBegin = s;
576 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000577 bool noSignificand = (s == DigitsBegin);
Chris Lattner368328c2008-06-30 06:39:54 +0000578 if (s == ThisTokEnd) {
579 // Done.
580 } else if (*s == '.') {
581 s++;
582 saw_period = true;
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000583 const char *floatDigitsBegin = s;
Chris Lattner368328c2008-06-30 06:39:54 +0000584 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000585 noSignificand &= (floatDigitsBegin == s);
Chris Lattner368328c2008-06-30 06:39:54 +0000586 }
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000587
588 if (noSignificand) {
589 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), \
590 diag::err_hexconstant_requires_digits);
591 hadError = true;
592 return;
593 }
594
Chris Lattner368328c2008-06-30 06:39:54 +0000595 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump1eb44332009-09-09 15:08:12 +0000596 // binary exponent is required.
Douglas Gregor1155c422011-08-30 22:40:35 +0000597 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000598 const char *Exponent = s;
599 s++;
600 saw_exponent = true;
601 if (*s == '+' || *s == '-') s++; // sign
602 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000603 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000604 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
605 diag::err_exponent_has_no_digits);
606 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000607 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000608 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000609 s = first_non_digit;
Mike Stump1eb44332009-09-09 15:08:12 +0000610
David Blaikie4e4d0842012-03-11 07:00:24 +0000611 if (!PP.getLangOpts().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000612 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000613 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000614 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
615 diag::err_hexconstant_requires_exponent);
616 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000617 }
618 return;
619 }
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner368328c2008-06-30 06:39:54 +0000621 // Handle simple binary numbers 0b01010
622 if (*s == 'b' || *s == 'B') {
623 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000624 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000625 ++s;
626 radix = 2;
627 DigitsBegin = s;
628 s = SkipBinaryDigits(s);
629 if (s == ThisTokEnd) {
630 // Done.
631 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000632 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000633 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000634 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000635 }
Chris Lattner413d3552008-06-30 06:44:49 +0000636 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000637 return;
638 }
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner368328c2008-06-30 06:39:54 +0000640 // For now, the radix is set to 8. If we discover that we have a
641 // floating point constant, the radix will change to 10. Octal floating
Mike Stump1eb44332009-09-09 15:08:12 +0000642 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner368328c2008-06-30 06:39:54 +0000643 radix = 8;
644 DigitsBegin = s;
645 s = SkipOctalDigits(s);
646 if (s == ThisTokEnd)
647 return; // Done, simple octal number like 01234
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattner413d3552008-06-30 06:44:49 +0000649 // If we have some other non-octal digit that *is* a decimal digit, see if
650 // this is part of a floating point number like 094.123 or 09e1.
651 if (isdigit(*s)) {
652 const char *EndDecimal = SkipDigits(s);
653 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
654 s = EndDecimal;
655 radix = 10;
656 }
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattner413d3552008-06-30 06:44:49 +0000659 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
660 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000661 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000662 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000663 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000664 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000665 return;
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Chris Lattner368328c2008-06-30 06:39:54 +0000668 if (*s == '.') {
669 s++;
670 radix = 10;
671 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000672 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000673 }
674 if (*s == 'e' || *s == 'E') { // exponent
675 const char *Exponent = s;
676 s++;
677 radix = 10;
678 saw_exponent = true;
679 if (*s == '+' || *s == '-') s++; // sign
680 const char *first_non_digit = SkipDigits(s);
681 if (first_non_digit != s) {
682 s = first_non_digit;
683 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000684 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000685 diag::err_exponent_has_no_digits);
686 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000687 return;
688 }
689 }
690}
691
692
Reid Spencer5f016e22007-07-11 17:01:13 +0000693/// GetIntegerValue - Convert this numeric literal value to an APInt that
694/// matches Val's input width. If there is an overflow, set Val to the low bits
695/// of the result and return true. Otherwise, return false.
696bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000697 // Fast path: Compute a conservative bound on the maximum number of
698 // bits per digit in this radix. If we can't possibly overflow a
699 // uint64 based on that bound then do the simple conversion to
700 // integer. This avoids the expensive overflow checking below, and
701 // handles the common cases that matter (small decimal integers and
702 // hex/octal values which don't overflow).
703 unsigned MaxBitsPerDigit = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000704 while ((1U << MaxBitsPerDigit) < radix)
Daniel Dunbara179be32008-10-16 07:32:01 +0000705 MaxBitsPerDigit += 1;
706 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
707 uint64_t N = 0;
708 for (s = DigitsBegin; s != SuffixBegin; ++s)
709 N = N*radix + HexDigitValue(*s);
710
711 // This will truncate the value to Val's input width. Simply check
712 // for overflow by comparing.
713 Val = N;
714 return Val.getZExtValue() != N;
715 }
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 Val = 0;
718 s = DigitsBegin;
719
720 llvm::APInt RadixVal(Val.getBitWidth(), radix);
721 llvm::APInt CharVal(Val.getBitWidth(), 0);
722 llvm::APInt OldVal = Val;
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 bool OverflowOccurred = false;
725 while (s < SuffixBegin) {
726 unsigned C = HexDigitValue(*s++);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 // If this letter is out of bound for this radix, reject it.
729 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 CharVal = C;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 // Add the digit to the value in the appropriate radix. If adding in digits
734 // made the value smaller, then this overflowed.
735 OldVal = Val;
736
737 // Multiply by radix, did overflow occur on the multiply?
738 Val *= RadixVal;
739 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
740
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000742 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 OverflowOccurred |= Val.ult(CharVal);
745 }
746 return OverflowOccurred;
747}
748
John McCall94c939d2009-12-24 09:08:04 +0000749llvm::APFloat::opStatus
750NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenek427d5af2007-11-26 23:12:30 +0000751 using llvm::APFloat;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000753 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall94c939d2009-12-24 09:08:04 +0000754 return Result.convertFromString(StringRef(ThisTokBegin, n),
755 APFloat::rmNearestTiesToEven);
Reid Spencer5f016e22007-07-11 17:01:13 +0000756}
757
Reid Spencer5f016e22007-07-11 17:01:13 +0000758
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000759/// user-defined-character-literal: [C++11 lex.ext]
760/// character-literal ud-suffix
761/// ud-suffix:
762/// identifier
763/// character-literal: [C++11 lex.ccon]
Craig Topper2fa4e862011-08-11 04:06:15 +0000764/// ' c-char-sequence '
765/// u' c-char-sequence '
766/// U' c-char-sequence '
767/// L' c-char-sequence '
768/// c-char-sequence:
769/// c-char
770/// c-char-sequence c-char
771/// c-char:
772/// any member of the source character set except the single-quote ',
773/// backslash \, or new-line character
774/// escape-sequence
775/// universal-character-name
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000776/// escape-sequence:
Craig Topper2fa4e862011-08-11 04:06:15 +0000777/// simple-escape-sequence
778/// octal-escape-sequence
779/// hexadecimal-escape-sequence
780/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +0000781/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +0000782/// octal-escape-sequence:
783/// \ octal-digit
784/// \ octal-digit octal-digit
785/// \ octal-digit octal-digit octal-digit
786/// hexadecimal-escape-sequence:
787/// \x hexadecimal-digit
788/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000789/// universal-character-name: [C++11 lex.charset]
Craig Topper2fa4e862011-08-11 04:06:15 +0000790/// \u hex-quad
791/// \U hex-quad hex-quad
792/// hex-quad:
793/// hex-digit hex-digit hex-digit hex-digit
794///
Reid Spencer5f016e22007-07-11 17:01:13 +0000795CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000796 SourceLocation Loc, Preprocessor &PP,
797 tok::TokenKind kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000798 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Douglas Gregor5cee1192011-07-27 05:40:30 +0000801 Kind = kind;
802
Richard Smith26b75c02012-03-09 22:27:51 +0000803 const char *TokBegin = begin;
804
Seth Cantrellbe773522012-01-18 12:27:04 +0000805 // Skip over wide character determinant.
806 if (Kind != tok::char_constant) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000807 ++begin;
808 }
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 // Skip over the entry quote.
811 assert(begin[0] == '\'' && "Invalid token lexed");
812 ++begin;
813
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000814 // Remove an optional ud-suffix.
815 if (end[-1] != '\'') {
816 const char *UDSuffixEnd = end;
817 do {
818 --end;
819 } while (end[-1] != '\'');
820 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith26b75c02012-03-09 22:27:51 +0000821 UDSuffixOffset = end - TokBegin;
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000822 }
823
Seth Cantrellbe773522012-01-18 12:27:04 +0000824 // Trim the ending quote.
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000825 assert(end != begin && "Invalid token lexed");
Seth Cantrellbe773522012-01-18 12:27:04 +0000826 --end;
827
Mike Stump1eb44332009-09-09 15:08:12 +0000828 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000829 // up to 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000831 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000833 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
834 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
835 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
836 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
837 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000838
Seth Cantrellbe773522012-01-18 12:27:04 +0000839 SmallVector<uint32_t,4> codepoint_buffer;
840 codepoint_buffer.resize(end-begin);
841 uint32_t *buffer_begin = &codepoint_buffer.front();
842 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Seth Cantrellbe773522012-01-18 12:27:04 +0000844 // Unicode escapes representing characters that cannot be correctly
845 // represented in a single code unit are disallowed in character literals
846 // by this implementation.
847 uint32_t largest_character_for_kind;
848 if (tok::wide_char_constant == Kind) {
849 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
850 } else if (tok::utf16_char_constant == Kind) {
851 largest_character_for_kind = 0xFFFF;
852 } else if (tok::utf32_char_constant == Kind) {
853 largest_character_for_kind = 0x10FFFF;
854 } else {
855 largest_character_for_kind = 0x7Fu;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000856 }
857
Seth Cantrellbe773522012-01-18 12:27:04 +0000858 while (begin!=end) {
859 // Is this a span of non-escape characters?
860 if (begin[0] != '\\') {
861 char const *start = begin;
862 do {
863 ++begin;
864 } while (begin != end && *begin != '\\');
865
Eli Friedman91359302012-02-11 05:08:10 +0000866 char const *tmp_in_start = start;
867 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrellbe773522012-01-18 12:27:04 +0000868 ConversionResult res =
869 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
870 reinterpret_cast<UTF8 const *>(begin),
871 &buffer_begin,buffer_end,strictConversion);
872 if (res!=conversionOK) {
Eli Friedman91359302012-02-11 05:08:10 +0000873 // If we see bad encoding for unprefixed character literals, warn and
874 // simply copy the byte values, for compatibility with gcc and
875 // older versions of clang.
876 bool NoErrorOnBadEncoding = isAscii();
877 unsigned Msg = diag::err_bad_character_encoding;
878 if (NoErrorOnBadEncoding)
879 Msg = diag::warn_bad_character_encoding;
880 PP.Diag(Loc, Msg);
881 if (NoErrorOnBadEncoding) {
882 start = tmp_in_start;
883 buffer_begin = tmp_out_start;
884 for ( ; start != begin; ++start, ++buffer_begin)
885 *buffer_begin = static_cast<uint8_t>(*start);
886 } else {
887 HadError = true;
888 }
Seth Cantrellbe773522012-01-18 12:27:04 +0000889 } else {
Eli Friedman91359302012-02-11 05:08:10 +0000890 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
891 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000892 HadError = true;
893 PP.Diag(Loc, diag::err_character_too_large);
894 }
895 }
896 }
897
898 continue;
899 }
900 // Is this a Universal Character Name excape?
901 if (begin[1] == 'u' || begin[1] == 'U') {
902 unsigned short UcnLen = 0;
Richard Smith26b75c02012-03-09 22:27:51 +0000903 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrellbe773522012-01-18 12:27:04 +0000904 FullSourceLoc(Loc, PP.getSourceManager()),
David Blaikie4e4d0842012-03-11 07:00:24 +0000905 &PP.getDiagnostics(), PP.getLangOpts(),
Seth Cantrellbe773522012-01-18 12:27:04 +0000906 true))
907 {
908 HadError = true;
909 } else if (*buffer_begin > largest_character_for_kind) {
910 HadError = true;
911 PP.Diag(Loc,diag::err_character_too_large);
912 }
913
914 ++buffer_begin;
915 continue;
916 }
917 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
918 uint64_t result =
919 ProcessCharEscape(begin, end, HadError,
920 FullSourceLoc(Loc,PP.getSourceManager()),
921 CharWidth, &PP.getDiagnostics());
922 *buffer_begin++ = result;
923 }
924
925 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
926
Chris Lattnere3ad8812009-04-28 21:51:46 +0000927 if (NumCharsSoFar > 1) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000928 if (isWide())
Douglas Gregor5cee1192011-07-27 05:40:30 +0000929 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrellbe773522012-01-18 12:27:04 +0000930 else if (isAscii() && NumCharsSoFar == 4)
931 PP.Diag(Loc, diag::ext_four_char_character_literal);
932 else if (isAscii())
Chris Lattnere3ad8812009-04-28 21:51:46 +0000933 PP.Diag(Loc, diag::ext_multichar_character_literal);
934 else
Seth Cantrellbe773522012-01-18 12:27:04 +0000935 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000936 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000937 } else
938 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000939
Seth Cantrellbe773522012-01-18 12:27:04 +0000940 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
941
942 // Narrow character literals act as though their value is concatenated
943 // in this implementation, but warn on overflow.
944 bool multi_char_too_long = false;
945 if (isAscii() && isMultiChar()) {
946 LitVal = 0;
947 for (size_t i=0;i<NumCharsSoFar;++i) {
948 // check for enough leading zeros to shift into
949 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
950 LitVal <<= 8;
951 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
952 }
953 } else if (NumCharsSoFar > 0) {
954 // otherwise just take the last character
955 LitVal = buffer_begin[-1];
956 }
957
958 if (!HadError && multi_char_too_long) {
959 PP.Diag(Loc,diag::warn_char_constant_too_large);
960 }
961
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000962 // Transfer the value from APInt to uint64_t
963 Value = LitVal.getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
966 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
967 // character constants are not sign extended in the this implementation:
968 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregor5cee1192011-07-27 05:40:30 +0000969 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000970 PP.getLangOpts().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 Value = (signed char)Value;
972}
973
974
Craig Topper2fa4e862011-08-11 04:06:15 +0000975/// string-literal: [C++0x lex.string]
976/// encoding-prefix " [s-char-sequence] "
977/// encoding-prefix R raw-string
978/// encoding-prefix:
979/// u8
980/// u
981/// U
982/// L
Reid Spencer5f016e22007-07-11 17:01:13 +0000983/// s-char-sequence:
984/// s-char
985/// s-char-sequence s-char
986/// s-char:
Craig Topper2fa4e862011-08-11 04:06:15 +0000987/// any member of the source character set except the double-quote ",
988/// backslash \, or new-line character
989/// escape-sequence
Reid Spencer5f016e22007-07-11 17:01:13 +0000990/// universal-character-name
Craig Topper2fa4e862011-08-11 04:06:15 +0000991/// raw-string:
992/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
993/// r-char-sequence:
994/// r-char
995/// r-char-sequence r-char
996/// r-char:
997/// any member of the source character set, except a right parenthesis )
998/// followed by the initial d-char-sequence (which may be empty)
999/// followed by a double quote ".
1000/// d-char-sequence:
1001/// d-char
1002/// d-char-sequence d-char
1003/// d-char:
1004/// any member of the basic source character set except:
1005/// space, the left parenthesis (, the right parenthesis ),
1006/// the backslash \, and the control characters representing horizontal
1007/// tab, vertical tab, form feed, and newline.
1008/// escape-sequence: [C++0x lex.ccon]
1009/// simple-escape-sequence
1010/// octal-escape-sequence
1011/// hexadecimal-escape-sequence
1012/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +00001013/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +00001014/// octal-escape-sequence:
1015/// \ octal-digit
1016/// \ octal-digit octal-digit
1017/// \ octal-digit octal-digit octal-digit
1018/// hexadecimal-escape-sequence:
1019/// \x hexadecimal-digit
1020/// hexadecimal-escape-sequence hexadecimal-digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001021/// universal-character-name:
1022/// \u hex-quad
1023/// \U hex-quad hex-quad
1024/// hex-quad:
1025/// hex-digit hex-digit hex-digit hex-digit
1026///
1027StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +00001028StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner0833dd02010-11-17 07:21:13 +00001029 Preprocessor &PP, bool Complain)
David Blaikie4e4d0842012-03-11 07:00:24 +00001030 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001031 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001032 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1033 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner0833dd02010-11-17 07:21:13 +00001034 init(StringToks, NumStringToks);
1035}
1036
1037void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001038 // The literal token may have come from an invalid source location (e.g. due
1039 // to a PCH error), in which case the token length will be 0.
1040 if (NumStringToks == 0 || StringToks[0].getLength() < 2) {
1041 hadError = true;
1042 return;
1043 }
1044
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 // Scan all of the string portions, remember the max individual token length,
1046 // computing a bound on the concatenated string length, and see whether any
1047 // piece is a wide-string. If any of the string portions is a wide-string
1048 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001049 assert(NumStringToks && "expected at least one token");
Sean Hunt6cf75022010-08-30 17:47:05 +00001050 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001051 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001052 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001053 Kind = StringToks[0].getKind();
Sean Hunt6cf75022010-08-30 17:47:05 +00001054
1055 hadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001056
1057 // Implement Translation Phase #6: concatenation of string literals
1058 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1059 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001060 if (StringToks[i].getLength() < 2) {
1061 hadError = true;
1062 return;
1063 }
1064
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 // The string could be shorter than this if it needs cleaning, but this is a
1066 // reasonable bound, which is all we need.
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001067 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001068 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 // Remember maximum string piece length.
Sean Hunt6cf75022010-08-30 17:47:05 +00001071 if (StringToks[i].getLength() > MaxTokenLength)
1072 MaxTokenLength = StringToks[i].getLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Douglas Gregor5cee1192011-07-27 05:40:30 +00001074 // Remember if we see any wide or utf-8/16/32 strings.
1075 // Also check for illegal concatenations.
1076 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1077 if (isAscii()) {
1078 Kind = StringToks[i].getKind();
1079 } else {
1080 if (Diags)
1081 Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
1082 diag::err_unsupported_string_concat);
1083 hadError = true;
1084 }
1085 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001087
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 // Include space for the null terminator.
1089 ++SizeBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregor5cee1192011-07-27 05:40:30 +00001093 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1094 CharByteWidth = getCharWidth(Kind, Target);
1095 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1096 CharByteWidth /= 8;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 // The output buffer size needs to be large enough to hold wide characters.
1099 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001100 SizeBound *= CharByteWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 // Size the temporary buffer to hold the result string data.
1103 ResultBuf.resize(SizeBound);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Reid Spencer5f016e22007-07-11 17:01:13 +00001105 // Likewise, but for each string piece.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001106 SmallString<512> TokenBuf;
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 TokenBuf.resize(MaxTokenLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Loop over all the strings, getting their spelling, and expanding them to
1110 // wide strings as appropriate.
1111 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Anders Carlssonee98ac52007-10-15 02:50:23 +00001113 Pascal = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001115 SourceLocation UDSuffixTokLoc;
1116
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1118 const char *ThisTokBuf = &TokenBuf[0];
1119 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1120 // that ThisTokBuf points to a buffer that is big enough for the whole token
1121 // and 'spelled' tokens can only shrink.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001122 bool StringInvalid = false;
Chris Lattner0833dd02010-11-17 07:21:13 +00001123 unsigned ThisTokLen =
Chris Lattnerb0607272010-11-17 07:26:20 +00001124 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1125 &StringInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001126 if (StringInvalid) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00001127 hadError = true;
Douglas Gregor50f6af72010-03-16 05:20:39 +00001128 continue;
1129 }
1130
Richard Smith26b75c02012-03-09 22:27:51 +00001131 const char *ThisTokBegin = ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001132 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1133
1134 // Remove an optional ud-suffix.
1135 if (ThisTokEnd[-1] != '"') {
1136 const char *UDSuffixEnd = ThisTokEnd;
1137 do {
1138 --ThisTokEnd;
1139 } while (ThisTokEnd[-1] != '"');
1140
1141 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1142
1143 if (UDSuffixBuf.empty()) {
1144 UDSuffixBuf.assign(UDSuffix);
Richard Smithdd66be72012-03-08 01:34:56 +00001145 UDSuffixToken = i;
1146 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001147 UDSuffixTokLoc = StringToks[i].getLocation();
1148 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1149 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1150 // result of a concatenation involving at least one user-defined-string-
1151 // literal, all the participating user-defined-string-literals shall
1152 // have the same ud-suffix.
1153 if (Diags) {
1154 SourceLocation TokLoc = StringToks[i].getLocation();
1155 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1156 << UDSuffixBuf << UDSuffix
1157 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1158 << SourceRange(TokLoc, TokLoc);
1159 }
1160 hadError = true;
1161 }
1162 }
1163
1164 // Strip the end quote.
1165 --ThisTokEnd;
1166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // TODO: Input character set mapping support.
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Craig Topper1661d712011-08-08 06:10:39 +00001169 // Skip marker for wide or unicode strings.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001170 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 ++ThisTokBuf;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001172 // Skip 8 of u8 marker for utf8 strings.
1173 if (ThisTokBuf[0] == '8')
1174 ++ThisTokBuf;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +00001175 }
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Craig Topper2fa4e862011-08-11 04:06:15 +00001177 // Check for raw string
1178 if (ThisTokBuf[0] == 'R') {
1179 ThisTokBuf += 2; // skip R"
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Craig Topper2fa4e862011-08-11 04:06:15 +00001181 const char *Prefix = ThisTokBuf;
1182 while (ThisTokBuf[0] != '(')
Anders Carlssonee98ac52007-10-15 02:50:23 +00001183 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001184 ++ThisTokBuf; // skip '('
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Richard Smith49d51742012-03-08 21:59:28 +00001186 // Remove same number of characters from the end
1187 ThisTokEnd -= ThisTokBuf - Prefix;
1188 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper2fa4e862011-08-11 04:06:15 +00001189
1190 // Copy the string over
Richard Smith49d51742012-03-08 21:59:28 +00001191 if (CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
Eli Friedman91359302012-02-11 05:08:10 +00001192 if (DiagnoseBadString(StringToks[i]))
1193 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001194 } else {
Argyrios Kyrtzidis07a07582012-05-03 01:01:56 +00001195 if (ThisTokBuf[0] != '"') {
1196 // The file may have come from PCH and then changed after loading the
1197 // PCH; Fail gracefully.
1198 hadError = true;
1199 continue;
1200 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001201 ++ThisTokBuf; // skip "
1202
1203 // Check if this is a pascal string
1204 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1205 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1206
1207 // If the \p sequence is found in the first token, we have a pascal string
1208 // Otherwise, if we already have a pascal string, ignore the first \p
1209 if (i == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001210 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001211 Pascal = true;
1212 } else if (Pascal)
1213 ThisTokBuf += 2;
1214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Craig Topper2fa4e862011-08-11 04:06:15 +00001216 while (ThisTokBuf != ThisTokEnd) {
1217 // Is this a span of non-escape characters?
1218 if (ThisTokBuf[0] != '\\') {
1219 const char *InStart = ThisTokBuf;
1220 do {
1221 ++ThisTokBuf;
1222 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1223
1224 // Copy the character span over.
Richard Smith49d51742012-03-08 21:59:28 +00001225 if (CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart)))
Eli Friedman91359302012-02-11 05:08:10 +00001226 if (DiagnoseBadString(StringToks[i]))
1227 hadError = true;
Craig Topper2fa4e862011-08-11 04:06:15 +00001228 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001230 // Is this a Universal Character Name escape?
1231 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith26b75c02012-03-09 22:27:51 +00001232 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1233 ResultPtr, hadError,
1234 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper2fa4e862011-08-11 04:06:15 +00001235 CharByteWidth, Diags, Features);
1236 continue;
1237 }
1238 // Otherwise, this is a non-UCN escape character. Process it.
1239 unsigned ResultChar =
1240 ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
1241 FullSourceLoc(StringToks[i].getLocation(), SM),
1242 CharByteWidth*8, Diags);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Eli Friedmancaf1f262011-11-02 23:06:23 +00001244 if (CharByteWidth == 4) {
1245 // FIXME: Make the type of the result buffer correct instead of
1246 // using reinterpret_cast.
1247 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001248 *ResultWidePtr = ResultChar;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001249 ResultPtr += 4;
1250 } else if (CharByteWidth == 2) {
1251 // FIXME: Make the type of the result buffer correct instead of
1252 // using reinterpret_cast.
1253 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001254 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001255 ResultPtr += 2;
1256 } else {
1257 assert(CharByteWidth == 1 && "Unexpected char width");
1258 *ResultPtr++ = ResultChar & 0xFF;
1259 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001260 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 }
1262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001264 if (Pascal) {
Eli Friedman22508f42011-11-05 00:41:04 +00001265 if (CharByteWidth == 4) {
1266 // FIXME: Make the type of the result buffer correct instead of
1267 // using reinterpret_cast.
1268 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1269 ResultWidePtr[0] = GetNumStringChars() - 1;
1270 } else if (CharByteWidth == 2) {
1271 // FIXME: Make the type of the result buffer correct instead of
1272 // using reinterpret_cast.
1273 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1274 ResultWidePtr[0] = GetNumStringChars() - 1;
1275 } else {
1276 assert(CharByteWidth == 1 && "Unexpected char width");
1277 ResultBuf[0] = GetNumStringChars() - 1;
1278 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001279
1280 // Verify that pascal strings aren't too large.
Chris Lattner0833dd02010-11-17 07:21:13 +00001281 if (GetStringLength() > 256) {
1282 if (Diags)
1283 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1284 diag::err_pascal_string_too_long)
1285 << SourceRange(StringToks[0].getLocation(),
1286 StringToks[NumStringToks-1].getLocation());
Douglas Gregor5cee1192011-07-27 05:40:30 +00001287 hadError = true;
Eli Friedman57d7dde2009-04-01 03:17:08 +00001288 return;
1289 }
Chris Lattner0833dd02010-11-17 07:21:13 +00001290 } else if (Diags) {
Douglas Gregor427c4922010-07-20 14:33:20 +00001291 // Complain if this string literal has too many characters.
Chris Lattnera95880d2010-11-17 07:12:42 +00001292 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Douglas Gregor427c4922010-07-20 14:33:20 +00001293
1294 if (GetNumStringChars() > MaxChars)
Chris Lattner0833dd02010-11-17 07:21:13 +00001295 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1296 diag::ext_string_too_long)
Douglas Gregor427c4922010-07-20 14:33:20 +00001297 << GetNumStringChars() << MaxChars
Chris Lattnera95880d2010-11-17 07:12:42 +00001298 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregor427c4922010-07-20 14:33:20 +00001299 << SourceRange(StringToks[0].getLocation(),
1300 StringToks[NumStringToks-1].getLocation());
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001301 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001302}
Chris Lattner719e6152009-02-18 19:21:10 +00001303
1304
Craig Topper2fa4e862011-08-11 04:06:15 +00001305/// copyStringFragment - This function copies from Start to End into ResultPtr.
1306/// Performs widening for multi-byte characters.
Eli Friedmanf74a4582011-11-01 02:14:50 +00001307bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
1308 assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
1309 ConversionResult result = conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001310 // Copy the character span over.
1311 if (CharByteWidth == 1) {
Richard Smith49d51742012-03-08 21:59:28 +00001312 if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(Fragment.begin()),
1313 reinterpret_cast<const UTF8*>(Fragment.end())))
Eli Friedman91359302012-02-11 05:08:10 +00001314 result = sourceIllegal;
Craig Topper2fa4e862011-08-11 04:06:15 +00001315 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1316 ResultPtr += Fragment.size();
Eli Friedmanf74a4582011-11-01 02:14:50 +00001317 } else if (CharByteWidth == 2) {
1318 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1319 // FIXME: Make the type of the result buffer correct instead of
1320 // using reinterpret_cast.
1321 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001322 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001323 result = ConvertUTF8toUTF16(
1324 &sourceStart,sourceStart + Fragment.size(),
1325 &targetStart,targetStart + 2*Fragment.size(),flags);
1326 if (result==conversionOK)
1327 ResultPtr = reinterpret_cast<char*>(targetStart);
1328 } else if (CharByteWidth == 4) {
1329 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1330 // FIXME: Make the type of the result buffer correct instead of
1331 // using reinterpret_cast.
1332 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001333 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001334 result = ConvertUTF8toUTF32(
1335 &sourceStart,sourceStart + Fragment.size(),
1336 &targetStart,targetStart + 4*Fragment.size(),flags);
1337 if (result==conversionOK)
1338 ResultPtr = reinterpret_cast<char*>(targetStart);
Craig Topper2fa4e862011-08-11 04:06:15 +00001339 }
Eli Friedmanf74a4582011-11-01 02:14:50 +00001340 assert((result != targetExhausted)
1341 && "ConvertUTF8toUTFXX exhausted target buffer");
1342 return result != conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001343}
1344
Eli Friedman91359302012-02-11 05:08:10 +00001345bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
1346 // If we see bad encoding for unprefixed string literals, warn and
1347 // simply copy the byte values, for compatibility with gcc and older
1348 // versions of clang.
1349 bool NoErrorOnBadEncoding = isAscii();
1350 unsigned Msg = NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
1351 diag::err_bad_string_encoding;
1352 if (Diags)
1353 Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
1354 return !NoErrorOnBadEncoding;
1355}
Craig Topper2fa4e862011-08-11 04:06:15 +00001356
Chris Lattner719e6152009-02-18 19:21:10 +00001357/// getOffsetOfStringByte - This function returns the offset of the
1358/// specified byte of the string data represented by Token. This handles
1359/// advancing over escape sequences in the string.
1360unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattner6c66f072010-11-17 06:46:14 +00001361 unsigned ByteNo) const {
Chris Lattner719e6152009-02-18 19:21:10 +00001362 // Get the spelling of the token.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001363 SmallString<32> SpellingBuffer;
Sean Hunt6cf75022010-08-30 17:47:05 +00001364 SpellingBuffer.resize(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Douglas Gregor50f6af72010-03-16 05:20:39 +00001366 bool StringInvalid = false;
Chris Lattner719e6152009-02-18 19:21:10 +00001367 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattnerb0607272010-11-17 07:26:20 +00001368 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1369 &StringInvalid);
Chris Lattner91f54ce2010-11-17 06:26:08 +00001370 if (StringInvalid)
Douglas Gregor50f6af72010-03-16 05:20:39 +00001371 return 0;
Chris Lattner719e6152009-02-18 19:21:10 +00001372
Douglas Gregor5cee1192011-07-27 05:40:30 +00001373 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1374 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
Chris Lattner719e6152009-02-18 19:21:10 +00001375
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Chris Lattner719e6152009-02-18 19:21:10 +00001377 const char *SpellingStart = SpellingPtr;
1378 const char *SpellingEnd = SpellingPtr+TokLen;
1379
1380 // Skip over the leading quote.
1381 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1382 ++SpellingPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Chris Lattner719e6152009-02-18 19:21:10 +00001384 // Skip over bytes until we find the offset we're looking for.
1385 while (ByteNo) {
1386 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Chris Lattner719e6152009-02-18 19:21:10 +00001388 // Step over non-escapes simply.
1389 if (*SpellingPtr != '\\') {
1390 ++SpellingPtr;
1391 --ByteNo;
1392 continue;
1393 }
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Chris Lattner719e6152009-02-18 19:21:10 +00001395 // Otherwise, this is an escape character. Advance over it.
1396 bool HadError = false;
1397 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
Chris Lattnerca1475e2010-11-17 06:35:43 +00001398 FullSourceLoc(Tok.getLocation(), SM),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001399 CharByteWidth*8, Diags);
Chris Lattner719e6152009-02-18 19:21:10 +00001400 assert(!HadError && "This method isn't valid on erroneous strings");
1401 --ByteNo;
1402 }
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Chris Lattner719e6152009-02-18 19:21:10 +00001404 return SpellingPtr-SpellingStart;
1405}