blob: 901d96d21ae38adc1f6b2c3bfafe4c36dfa6f617 [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.
182static bool ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
183 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikied6471f72011-09-25 23:23:43 +0000184 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrellbe773522012-01-18 12:27:04 +0000185 const LangOptions &Features,
186 bool in_char_string_literal = false) {
Chris Lattner6c66f072010-11-17 06:46:14 +0000187 if (!Features.CPlusPlus && !Features.C99 && Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000188 Diags->Report(Loc, diag::warn_ucn_not_valid_in_c89);
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Steve Naroff4e93b342009-04-01 11:09:15 +0000190 // Save the beginning of the string (for error diagnostics).
191 const char *ThisTokBegin = 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 =
213 Lexer::AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin,
214 Loc.getManager(), Features);
215 Diags->Report(FullSourceLoc(L, Loc.getManager()),
216 diag::err_ucn_escape_incomplete);
Chris Lattner872a45e2010-11-17 06:55:10 +0000217 }
Nico Weber59705ae2010-10-09 00:27:47 +0000218 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000219 }
Seth Cantrellbe773522012-01-18 12:27:04 +0000220 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
221 bool invalid_ucn = (0xD800<=UcnVal && UcnVal<=0xDFFF) // surrogate codepoints
222 || 0x10FFFF < UcnVal; // maximum legal UTF32 value
223
224 // C++11 allows UCNs that refer to control characters and basic source
225 // characters inside character and string literals
226 if (!Features.CPlusPlus0x || !in_char_string_literal) {
227 if ((UcnVal < 0xa0 &&
228 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 ))) { // $, @, `
229 invalid_ucn = true;
230 }
231 }
232
233 if (invalid_ucn) {
Chris Lattner6c66f072010-11-17 06:46:14 +0000234 if (Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000235 Diags->Report(Loc, diag::err_ucn_escape_invalid);
Nico Weber59705ae2010-10-09 00:27:47 +0000236 return false;
237 }
238 return true;
239}
240
241/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
242/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
243/// StringLiteralParser. When we decide to implement UCN's for identifiers,
244/// we will likely rework our support for UCN's.
245static void EncodeUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
Chris Lattnera95880d2010-11-17 07:12:42 +0000246 char *&ResultBuf, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000247 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikied6471f72011-09-25 23:23:43 +0000248 DiagnosticsEngine *Diags,
249 const LangOptions &Features) {
Nico Weber59705ae2010-10-09 00:27:47 +0000250 typedef uint32_t UTF32;
251 UTF32 UcnVal = 0;
252 unsigned short UcnLen = 0;
Chris Lattnera95880d2010-11-17 07:12:42 +0000253 if (!ProcessUCNEscape(ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, Diags,
254 Features)) {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000255 HadError = 1;
256 return;
257 }
Nico Weber59705ae2010-10-09 00:27:47 +0000258
Douglas Gregor5cee1192011-07-27 05:40:30 +0000259 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
260 "only character widths of 1, 2, or 4 bytes supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000261
Douglas Gregor5cee1192011-07-27 05:40:30 +0000262 (void)UcnLen;
263 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000264
Douglas Gregor5cee1192011-07-27 05:40:30 +0000265 if (CharByteWidth == 4) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000266 // FIXME: Make the type of the result buffer correct instead of
267 // using reinterpret_cast.
268 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
269 *ResultPtr = UcnVal;
270 ResultBuf += 4;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000271 return;
272 }
273
274 if (CharByteWidth == 2) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000275 // FIXME: Make the type of the result buffer correct instead of
276 // using reinterpret_cast.
277 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
278
Nico Webera0f15b02010-10-06 04:57:26 +0000279 if (UcnVal < (UTF32)0xFFFF) {
Eli Friedmancaf1f262011-11-02 23:06:23 +0000280 *ResultPtr = UcnVal;
281 ResultBuf += 2;
Nico Webera0f15b02010-10-06 04:57:26 +0000282 return;
283 }
Nico Webera0f15b02010-10-06 04:57:26 +0000284
Eli Friedmancaf1f262011-11-02 23:06:23 +0000285 // Convert to UTF16.
Nico Webera0f15b02010-10-06 04:57:26 +0000286 UcnVal -= 0x10000;
Eli Friedmancaf1f262011-11-02 23:06:23 +0000287 *ResultPtr = 0xD800 + (UcnVal >> 10);
288 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
289 ResultBuf += 4;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000290 return;
291 }
Douglas Gregor5cee1192011-07-27 05:40:30 +0000292
293 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
294
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000295 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
296 // The conversion below was inspired by:
297 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump1eb44332009-09-09 15:08:12 +0000298 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000299 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000300
301 unsigned short bytesToWrite = 0;
302 if (UcnVal < (UTF32)0x80)
303 bytesToWrite = 1;
304 else if (UcnVal < (UTF32)0x800)
305 bytesToWrite = 2;
306 else if (UcnVal < (UTF32)0x10000)
307 bytesToWrite = 3;
308 else
309 bytesToWrite = 4;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000311 const unsigned byteMask = 0xBF;
312 const unsigned byteMark = 0x80;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000314 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000315 // into the first byte, depending on how many bytes follow.
Mike Stump1eb44332009-09-09 15:08:12 +0000316 static const UTF8 firstByteMark[5] = {
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000317 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000318 };
319 // Finally, we write the bytes into ResultBuf.
320 ResultBuf += bytesToWrite;
321 switch (bytesToWrite) { // note: everything falls through.
322 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
323 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
324 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
325 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
326 }
327 // Update the buffer.
328 ResultBuf += bytesToWrite;
329}
Reid Spencer5f016e22007-07-11 17:01:13 +0000330
331
332/// integer-constant: [C99 6.4.4.1]
333/// decimal-constant integer-suffix
334/// octal-constant integer-suffix
335/// hexadecimal-constant integer-suffix
Richard Smithb453ad32012-03-08 08:45:32 +0000336/// user-defiend-integer-literal: [C++11 lex.ext]
337/// decimal-literal ud-suffix
338/// octal-literal ud-suffix
339/// hexadecimal-literal ud-suffix
Mike Stump1eb44332009-09-09 15:08:12 +0000340/// decimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000341/// nonzero-digit
342/// decimal-constant digit
Mike Stump1eb44332009-09-09 15:08:12 +0000343/// octal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000344/// 0
345/// octal-constant octal-digit
Mike Stump1eb44332009-09-09 15:08:12 +0000346/// hexadecimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000347/// hexadecimal-prefix hexadecimal-digit
348/// hexadecimal-constant hexadecimal-digit
349/// hexadecimal-prefix: one of
350/// 0x 0X
351/// integer-suffix:
352/// unsigned-suffix [long-suffix]
353/// unsigned-suffix [long-long-suffix]
354/// long-suffix [unsigned-suffix]
355/// long-long-suffix [unsigned-sufix]
356/// nonzero-digit:
357/// 1 2 3 4 5 6 7 8 9
358/// octal-digit:
359/// 0 1 2 3 4 5 6 7
360/// hexadecimal-digit:
361/// 0 1 2 3 4 5 6 7 8 9
362/// a b c d e f
363/// A B C D E F
364/// unsigned-suffix: one of
365/// u U
366/// long-suffix: one of
367/// l L
Mike Stump1eb44332009-09-09 15:08:12 +0000368/// long-long-suffix: one of
Reid Spencer5f016e22007-07-11 17:01:13 +0000369/// ll LL
370///
371/// floating-constant: [C99 6.4.4.2]
372/// TODO: add rules...
373///
Reid Spencer5f016e22007-07-11 17:01:13 +0000374NumericLiteralParser::
375NumericLiteralParser(const char *begin, const char *end,
376 SourceLocation TokLoc, Preprocessor &pp)
377 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000379 // This routine assumes that the range begin/end matches the regex for integer
380 // and FP constants (specifically, the 'pp-number' regex), and assumes that
381 // the byte at "*end" is both valid and not part of the regex. Because of
382 // this, it doesn't have to check for 'overscan' in various places.
383 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
384 "Lexer didn't maximally munch?");
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 s = DigitsBegin = begin;
387 saw_exponent = false;
388 saw_period = false;
Richard Smithb453ad32012-03-08 08:45:32 +0000389 saw_ud_suffix = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 isLong = false;
391 isUnsigned = false;
392 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000393 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000394 isImaginary = false;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000395 isMicrosoftInteger = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 hadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000399 ParseNumberStartingWithZero(TokLoc);
400 if (hadError)
401 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 } else { // the first digit is non-zero
403 radix = 10;
404 s = SkipDigits(s);
405 if (s == ThisTokEnd) {
406 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000407 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000408 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000409 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000410 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 return;
412 } else if (*s == '.') {
413 s++;
414 saw_period = true;
415 s = SkipDigits(s);
Mike Stump1eb44332009-09-09 15:08:12 +0000416 }
Chris Lattner4411f462008-09-29 23:12:31 +0000417 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000418 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 s++;
420 saw_exponent = true;
421 if (*s == '+' || *s == '-') s++; // sign
422 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000423 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000425 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000426 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
427 diag::err_exponent_has_no_digits);
428 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000429 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 }
431 }
432 }
433
434 SuffixBegin = s;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner506b8de2007-08-26 01:58:14 +0000436 // Parse the suffix. At this point we can classify whether we have an FP or
437 // integer constant.
438 bool isFPConstant = isFloatingLiteral();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner506b8de2007-08-26 01:58:14 +0000440 // Loop over all of the characters of the suffix. If we see something bad,
441 // we break out of the loop.
442 for (; s != ThisTokEnd; ++s) {
443 switch (*s) {
444 case 'f': // FP Suffix for "float"
445 case 'F':
446 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000447 if (isFloat || isLong) break; // FF, LF invalid.
448 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000449 continue; // Success.
450 case 'u':
451 case 'U':
452 if (isFPConstant) break; // Error for floating constant.
453 if (isUnsigned) break; // Cannot be repeated.
454 isUnsigned = true;
455 continue; // Success.
456 case 'l':
457 case 'L':
458 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000459 if (isFloat) break; // LF invalid.
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner506b8de2007-08-26 01:58:14 +0000461 // Check for long long. The L's need to be adjacent and the same case.
462 if (s+1 != ThisTokEnd && s[1] == s[0]) {
463 if (isFPConstant) break; // long long invalid for floats.
464 isLongLong = true;
465 ++s; // Eat both of them.
466 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000469 continue; // Success.
470 case 'i':
Chris Lattnerc6374152010-10-14 00:24:10 +0000471 case 'I':
Francois Pichet62ec1f22011-09-17 17:15:52 +0000472 if (PP.getLangOptions().MicrosoftExt) {
Fariborz Jahaniana8be02b2010-01-22 21:36:53 +0000473 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000474
Steve Naroff0c29b222008-04-04 21:02:54 +0000475 // Allow i8, i16, i32, i64, and i128.
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000476 if (s + 1 != ThisTokEnd) {
477 switch (s[1]) {
478 case '8':
479 s += 2; // i8 suffix
480 isMicrosoftInteger = true;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000481 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000482 case '1':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000483 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000484 if (s[2] == '6') {
485 s += 3; // i16 suffix
486 isMicrosoftInteger = true;
487 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000488 else if (s[2] == '2') {
489 if (s + 3 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000490 if (s[3] == '8') {
491 s += 4; // i128 suffix
492 isMicrosoftInteger = true;
493 }
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000494 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000495 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000496 case '3':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000497 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000498 if (s[2] == '2') {
499 s += 3; // i32 suffix
500 isLong = true;
501 isMicrosoftInteger = true;
502 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000503 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000504 case '6':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000505 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000506 if (s[2] == '4') {
507 s += 3; // i64 suffix
508 isLongLong = true;
509 isMicrosoftInteger = true;
510 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000511 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000512 default:
513 break;
514 }
515 break;
Steve Naroff0c29b222008-04-04 21:02:54 +0000516 }
Steve Naroff0c29b222008-04-04 21:02:54 +0000517 }
518 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000519 case 'j':
520 case 'J':
521 if (isImaginary) break; // Cannot be repeated.
522 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
523 diag::ext_imaginary_constant);
524 isImaginary = true;
525 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 }
Richard Smithb453ad32012-03-08 08:45:32 +0000527 // If we reached here, there was an error or a ud-suffix.
Chris Lattner506b8de2007-08-26 01:58:14 +0000528 break;
529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner506b8de2007-08-26 01:58:14 +0000531 if (s != ThisTokEnd) {
Richard Smithb453ad32012-03-08 08:45:32 +0000532 if (PP.getLangOptions().CPlusPlus0x && s == SuffixBegin && *s == '_') {
533 // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not starting
534 // with an '_' are ill-formed.
535 saw_ud_suffix = true;
536 return;
537 }
538
539 // Report an error if there are any.
540 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin-begin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000541 isFPConstant ? diag::err_invalid_suffix_float_constant :
542 diag::err_invalid_suffix_integer_constant)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000543 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattnerac92d822008-11-22 07:23:31 +0000544 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000545 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 }
547}
548
Chris Lattner368328c2008-06-30 06:39:54 +0000549/// ParseNumberStartingWithZero - This method is called when the first character
550/// of the number is found to be a zero. This means it is either an octal
551/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump1eb44332009-09-09 15:08:12 +0000552/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner368328c2008-06-30 06:39:54 +0000553/// radix etc.
554void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
555 assert(s[0] == '0' && "Invalid method call");
556 s++;
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner368328c2008-06-30 06:39:54 +0000558 // Handle a hex number like 0x1234.
559 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
560 s++;
561 radix = 16;
562 DigitsBegin = s;
563 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000564 bool noSignificand = (s == DigitsBegin);
Chris Lattner368328c2008-06-30 06:39:54 +0000565 if (s == ThisTokEnd) {
566 // Done.
567 } else if (*s == '.') {
568 s++;
569 saw_period = true;
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000570 const char *floatDigitsBegin = s;
Chris Lattner368328c2008-06-30 06:39:54 +0000571 s = SkipHexDigits(s);
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000572 noSignificand &= (floatDigitsBegin == s);
Chris Lattner368328c2008-06-30 06:39:54 +0000573 }
Aaron Ballman66b0eba2012-02-08 13:36:33 +0000574
575 if (noSignificand) {
576 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), \
577 diag::err_hexconstant_requires_digits);
578 hadError = true;
579 return;
580 }
581
Chris Lattner368328c2008-06-30 06:39:54 +0000582 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump1eb44332009-09-09 15:08:12 +0000583 // binary exponent is required.
Douglas Gregor1155c422011-08-30 22:40:35 +0000584 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000585 const char *Exponent = s;
586 s++;
587 saw_exponent = true;
588 if (*s == '+' || *s == '-') s++; // sign
589 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000590 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000591 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
592 diag::err_exponent_has_no_digits);
593 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000594 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000595 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000596 s = first_non_digit;
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Douglas Gregor1155c422011-08-30 22:40:35 +0000598 if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000599 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000600 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000601 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
602 diag::err_hexconstant_requires_exponent);
603 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000604 }
605 return;
606 }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Chris Lattner368328c2008-06-30 06:39:54 +0000608 // Handle simple binary numbers 0b01010
609 if (*s == 'b' || *s == 'B') {
610 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000611 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000612 ++s;
613 radix = 2;
614 DigitsBegin = s;
615 s = SkipBinaryDigits(s);
616 if (s == ThisTokEnd) {
617 // Done.
618 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000619 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000620 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000621 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000622 }
Chris Lattner413d3552008-06-30 06:44:49 +0000623 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000624 return;
625 }
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattner368328c2008-06-30 06:39:54 +0000627 // For now, the radix is set to 8. If we discover that we have a
628 // floating point constant, the radix will change to 10. Octal floating
Mike Stump1eb44332009-09-09 15:08:12 +0000629 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner368328c2008-06-30 06:39:54 +0000630 radix = 8;
631 DigitsBegin = s;
632 s = SkipOctalDigits(s);
633 if (s == ThisTokEnd)
634 return; // Done, simple octal number like 01234
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Chris Lattner413d3552008-06-30 06:44:49 +0000636 // If we have some other non-octal digit that *is* a decimal digit, see if
637 // this is part of a floating point number like 094.123 or 09e1.
638 if (isdigit(*s)) {
639 const char *EndDecimal = SkipDigits(s);
640 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
641 s = EndDecimal;
642 radix = 10;
643 }
644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattner413d3552008-06-30 06:44:49 +0000646 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
647 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000648 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000649 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000650 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000651 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000652 return;
653 }
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Chris Lattner368328c2008-06-30 06:39:54 +0000655 if (*s == '.') {
656 s++;
657 radix = 10;
658 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000659 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000660 }
661 if (*s == 'e' || *s == 'E') { // exponent
662 const char *Exponent = s;
663 s++;
664 radix = 10;
665 saw_exponent = true;
666 if (*s == '+' || *s == '-') s++; // sign
667 const char *first_non_digit = SkipDigits(s);
668 if (first_non_digit != s) {
669 s = first_non_digit;
670 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000671 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000672 diag::err_exponent_has_no_digits);
673 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000674 return;
675 }
676 }
677}
678
679
Reid Spencer5f016e22007-07-11 17:01:13 +0000680/// GetIntegerValue - Convert this numeric literal value to an APInt that
681/// matches Val's input width. If there is an overflow, set Val to the low bits
682/// of the result and return true. Otherwise, return false.
683bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000684 // Fast path: Compute a conservative bound on the maximum number of
685 // bits per digit in this radix. If we can't possibly overflow a
686 // uint64 based on that bound then do the simple conversion to
687 // integer. This avoids the expensive overflow checking below, and
688 // handles the common cases that matter (small decimal integers and
689 // hex/octal values which don't overflow).
690 unsigned MaxBitsPerDigit = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000691 while ((1U << MaxBitsPerDigit) < radix)
Daniel Dunbara179be32008-10-16 07:32:01 +0000692 MaxBitsPerDigit += 1;
693 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
694 uint64_t N = 0;
695 for (s = DigitsBegin; s != SuffixBegin; ++s)
696 N = N*radix + HexDigitValue(*s);
697
698 // This will truncate the value to Val's input width. Simply check
699 // for overflow by comparing.
700 Val = N;
701 return Val.getZExtValue() != N;
702 }
703
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 Val = 0;
705 s = DigitsBegin;
706
707 llvm::APInt RadixVal(Val.getBitWidth(), radix);
708 llvm::APInt CharVal(Val.getBitWidth(), 0);
709 llvm::APInt OldVal = Val;
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 bool OverflowOccurred = false;
712 while (s < SuffixBegin) {
713 unsigned C = HexDigitValue(*s++);
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 // If this letter is out of bound for this radix, reject it.
716 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 CharVal = C;
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 // Add the digit to the value in the appropriate radix. If adding in digits
721 // made the value smaller, then this overflowed.
722 OldVal = Val;
723
724 // Multiply by radix, did overflow occur on the multiply?
725 Val *= RadixVal;
726 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
727
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000729 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 OverflowOccurred |= Val.ult(CharVal);
732 }
733 return OverflowOccurred;
734}
735
John McCall94c939d2009-12-24 09:08:04 +0000736llvm::APFloat::opStatus
737NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenek427d5af2007-11-26 23:12:30 +0000738 using llvm::APFloat;
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000740 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall94c939d2009-12-24 09:08:04 +0000741 return Result.convertFromString(StringRef(ThisTokBegin, n),
742 APFloat::rmNearestTiesToEven);
Reid Spencer5f016e22007-07-11 17:01:13 +0000743}
744
Reid Spencer5f016e22007-07-11 17:01:13 +0000745
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000746/// user-defined-character-literal: [C++11 lex.ext]
747/// character-literal ud-suffix
748/// ud-suffix:
749/// identifier
750/// character-literal: [C++11 lex.ccon]
Craig Topper2fa4e862011-08-11 04:06:15 +0000751/// ' c-char-sequence '
752/// u' c-char-sequence '
753/// U' c-char-sequence '
754/// L' c-char-sequence '
755/// c-char-sequence:
756/// c-char
757/// c-char-sequence c-char
758/// c-char:
759/// any member of the source character set except the single-quote ',
760/// backslash \, or new-line character
761/// escape-sequence
762/// universal-character-name
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000763/// escape-sequence:
Craig Topper2fa4e862011-08-11 04:06:15 +0000764/// simple-escape-sequence
765/// octal-escape-sequence
766/// hexadecimal-escape-sequence
767/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +0000768/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +0000769/// octal-escape-sequence:
770/// \ octal-digit
771/// \ octal-digit octal-digit
772/// \ octal-digit octal-digit octal-digit
773/// hexadecimal-escape-sequence:
774/// \x hexadecimal-digit
775/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000776/// universal-character-name: [C++11 lex.charset]
Craig Topper2fa4e862011-08-11 04:06:15 +0000777/// \u hex-quad
778/// \U hex-quad hex-quad
779/// hex-quad:
780/// hex-digit hex-digit hex-digit hex-digit
781///
Reid Spencer5f016e22007-07-11 17:01:13 +0000782CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000783 SourceLocation Loc, Preprocessor &PP,
784 tok::TokenKind kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000785 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Douglas Gregor5cee1192011-07-27 05:40:30 +0000788 Kind = kind;
789
Seth Cantrellbe773522012-01-18 12:27:04 +0000790 // Skip over wide character determinant.
791 if (Kind != tok::char_constant) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000792 ++begin;
793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 // Skip over the entry quote.
796 assert(begin[0] == '\'' && "Invalid token lexed");
797 ++begin;
798
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000799 // Remove an optional ud-suffix.
800 if (end[-1] != '\'') {
801 const char *UDSuffixEnd = end;
802 do {
803 --end;
804 } while (end[-1] != '\'');
805 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smithdd66be72012-03-08 01:34:56 +0000806 UDSuffixOffset = end - begin + 1;
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000807 }
808
Seth Cantrellbe773522012-01-18 12:27:04 +0000809 // Trim the ending quote.
Richard Smith5cc2c6e2012-03-05 04:02:15 +0000810 assert(end != begin && "Invalid token lexed");
Seth Cantrellbe773522012-01-18 12:27:04 +0000811 --end;
812
Mike Stump1eb44332009-09-09 15:08:12 +0000813 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000814 // up to 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000816 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000818 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
819 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
820 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
821 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
822 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000823
Seth Cantrellbe773522012-01-18 12:27:04 +0000824 SmallVector<uint32_t,4> codepoint_buffer;
825 codepoint_buffer.resize(end-begin);
826 uint32_t *buffer_begin = &codepoint_buffer.front();
827 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Seth Cantrellbe773522012-01-18 12:27:04 +0000829 // Unicode escapes representing characters that cannot be correctly
830 // represented in a single code unit are disallowed in character literals
831 // by this implementation.
832 uint32_t largest_character_for_kind;
833 if (tok::wide_char_constant == Kind) {
834 largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
835 } else if (tok::utf16_char_constant == Kind) {
836 largest_character_for_kind = 0xFFFF;
837 } else if (tok::utf32_char_constant == Kind) {
838 largest_character_for_kind = 0x10FFFF;
839 } else {
840 largest_character_for_kind = 0x7Fu;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000841 }
842
Seth Cantrellbe773522012-01-18 12:27:04 +0000843 while (begin!=end) {
844 // Is this a span of non-escape characters?
845 if (begin[0] != '\\') {
846 char const *start = begin;
847 do {
848 ++begin;
849 } while (begin != end && *begin != '\\');
850
Eli Friedman91359302012-02-11 05:08:10 +0000851 char const *tmp_in_start = start;
852 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrellbe773522012-01-18 12:27:04 +0000853 ConversionResult res =
854 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
855 reinterpret_cast<UTF8 const *>(begin),
856 &buffer_begin,buffer_end,strictConversion);
857 if (res!=conversionOK) {
Eli Friedman91359302012-02-11 05:08:10 +0000858 // If we see bad encoding for unprefixed character literals, warn and
859 // simply copy the byte values, for compatibility with gcc and
860 // older versions of clang.
861 bool NoErrorOnBadEncoding = isAscii();
862 unsigned Msg = diag::err_bad_character_encoding;
863 if (NoErrorOnBadEncoding)
864 Msg = diag::warn_bad_character_encoding;
865 PP.Diag(Loc, Msg);
866 if (NoErrorOnBadEncoding) {
867 start = tmp_in_start;
868 buffer_begin = tmp_out_start;
869 for ( ; start != begin; ++start, ++buffer_begin)
870 *buffer_begin = static_cast<uint8_t>(*start);
871 } else {
872 HadError = true;
873 }
Seth Cantrellbe773522012-01-18 12:27:04 +0000874 } else {
Eli Friedman91359302012-02-11 05:08:10 +0000875 for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
876 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000877 HadError = true;
878 PP.Diag(Loc, diag::err_character_too_large);
879 }
880 }
881 }
882
883 continue;
884 }
885 // Is this a Universal Character Name excape?
886 if (begin[1] == 'u' || begin[1] == 'U') {
887 unsigned short UcnLen = 0;
888 if (!ProcessUCNEscape(begin, end, *buffer_begin, UcnLen,
889 FullSourceLoc(Loc, PP.getSourceManager()),
890 &PP.getDiagnostics(), PP.getLangOptions(),
891 true))
892 {
893 HadError = true;
894 } else if (*buffer_begin > largest_character_for_kind) {
895 HadError = true;
896 PP.Diag(Loc,diag::err_character_too_large);
897 }
898
899 ++buffer_begin;
900 continue;
901 }
902 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
903 uint64_t result =
904 ProcessCharEscape(begin, end, HadError,
905 FullSourceLoc(Loc,PP.getSourceManager()),
906 CharWidth, &PP.getDiagnostics());
907 *buffer_begin++ = result;
908 }
909
910 unsigned NumCharsSoFar = buffer_begin-&codepoint_buffer.front();
911
Chris Lattnere3ad8812009-04-28 21:51:46 +0000912 if (NumCharsSoFar > 1) {
Seth Cantrellbe773522012-01-18 12:27:04 +0000913 if (isWide())
Douglas Gregor5cee1192011-07-27 05:40:30 +0000914 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrellbe773522012-01-18 12:27:04 +0000915 else if (isAscii() && NumCharsSoFar == 4)
916 PP.Diag(Loc, diag::ext_four_char_character_literal);
917 else if (isAscii())
Chris Lattnere3ad8812009-04-28 21:51:46 +0000918 PP.Diag(Loc, diag::ext_multichar_character_literal);
919 else
Seth Cantrellbe773522012-01-18 12:27:04 +0000920 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000921 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000922 } else
923 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000924
Seth Cantrellbe773522012-01-18 12:27:04 +0000925 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
926
927 // Narrow character literals act as though their value is concatenated
928 // in this implementation, but warn on overflow.
929 bool multi_char_too_long = false;
930 if (isAscii() && isMultiChar()) {
931 LitVal = 0;
932 for (size_t i=0;i<NumCharsSoFar;++i) {
933 // check for enough leading zeros to shift into
934 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
935 LitVal <<= 8;
936 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
937 }
938 } else if (NumCharsSoFar > 0) {
939 // otherwise just take the last character
940 LitVal = buffer_begin[-1];
941 }
942
943 if (!HadError && multi_char_too_long) {
944 PP.Diag(Loc,diag::warn_char_constant_too_large);
945 }
946
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000947 // Transfer the value from APInt to uint64_t
948 Value = LitVal.getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
951 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
952 // character constants are not sign extended in the this implementation:
953 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregor5cee1192011-07-27 05:40:30 +0000954 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
Eli Friedman15b91762009-06-05 07:05:05 +0000955 PP.getLangOptions().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 Value = (signed char)Value;
957}
958
959
Craig Topper2fa4e862011-08-11 04:06:15 +0000960/// string-literal: [C++0x lex.string]
961/// encoding-prefix " [s-char-sequence] "
962/// encoding-prefix R raw-string
963/// encoding-prefix:
964/// u8
965/// u
966/// U
967/// L
Reid Spencer5f016e22007-07-11 17:01:13 +0000968/// s-char-sequence:
969/// s-char
970/// s-char-sequence s-char
971/// s-char:
Craig Topper2fa4e862011-08-11 04:06:15 +0000972/// any member of the source character set except the double-quote ",
973/// backslash \, or new-line character
974/// escape-sequence
Reid Spencer5f016e22007-07-11 17:01:13 +0000975/// universal-character-name
Craig Topper2fa4e862011-08-11 04:06:15 +0000976/// raw-string:
977/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
978/// r-char-sequence:
979/// r-char
980/// r-char-sequence r-char
981/// r-char:
982/// any member of the source character set, except a right parenthesis )
983/// followed by the initial d-char-sequence (which may be empty)
984/// followed by a double quote ".
985/// d-char-sequence:
986/// d-char
987/// d-char-sequence d-char
988/// d-char:
989/// any member of the basic source character set except:
990/// space, the left parenthesis (, the right parenthesis ),
991/// the backslash \, and the control characters representing horizontal
992/// tab, vertical tab, form feed, and newline.
993/// escape-sequence: [C++0x lex.ccon]
994/// simple-escape-sequence
995/// octal-escape-sequence
996/// hexadecimal-escape-sequence
997/// simple-escape-sequence:
NAKAMURA Takumiddddd482011-08-12 05:49:51 +0000998/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper2fa4e862011-08-11 04:06:15 +0000999/// octal-escape-sequence:
1000/// \ octal-digit
1001/// \ octal-digit octal-digit
1002/// \ octal-digit octal-digit octal-digit
1003/// hexadecimal-escape-sequence:
1004/// \x hexadecimal-digit
1005/// hexadecimal-escape-sequence hexadecimal-digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001006/// universal-character-name:
1007/// \u hex-quad
1008/// \U hex-quad hex-quad
1009/// hex-quad:
1010/// hex-digit hex-digit hex-digit hex-digit
1011///
1012StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +00001013StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner0833dd02010-11-17 07:21:13 +00001014 Preprocessor &PP, bool Complain)
1015 : SM(PP.getSourceManager()), Features(PP.getLangOptions()),
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001016 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001017 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1018 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner0833dd02010-11-17 07:21:13 +00001019 init(StringToks, NumStringToks);
1020}
1021
1022void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001023 // The literal token may have come from an invalid source location (e.g. due
1024 // to a PCH error), in which case the token length will be 0.
1025 if (NumStringToks == 0 || StringToks[0].getLength() < 2) {
1026 hadError = true;
1027 return;
1028 }
1029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // Scan all of the string portions, remember the max individual token length,
1031 // computing a bound on the concatenated string length, and see whether any
1032 // piece is a wide-string. If any of the string portions is a wide-string
1033 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001034 assert(NumStringToks && "expected at least one token");
Sean Hunt6cf75022010-08-30 17:47:05 +00001035 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001036 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001037 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001038 Kind = StringToks[0].getKind();
Sean Hunt6cf75022010-08-30 17:47:05 +00001039
1040 hadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001041
1042 // Implement Translation Phase #6: concatenation of string literals
1043 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1044 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001045 if (StringToks[i].getLength() < 2) {
1046 hadError = true;
1047 return;
1048 }
1049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 // The string could be shorter than this if it needs cleaning, but this is a
1051 // reasonable bound, which is all we need.
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +00001052 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +00001053 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // Remember maximum string piece length.
Sean Hunt6cf75022010-08-30 17:47:05 +00001056 if (StringToks[i].getLength() > MaxTokenLength)
1057 MaxTokenLength = StringToks[i].getLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Douglas Gregor5cee1192011-07-27 05:40:30 +00001059 // Remember if we see any wide or utf-8/16/32 strings.
1060 // Also check for illegal concatenations.
1061 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1062 if (isAscii()) {
1063 Kind = StringToks[i].getKind();
1064 } else {
1065 if (Diags)
1066 Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
1067 diag::err_unsupported_string_concat);
1068 hadError = true;
1069 }
1070 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001072
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 // Include space for the null terminator.
1074 ++SizeBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Douglas Gregor5cee1192011-07-27 05:40:30 +00001078 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1079 CharByteWidth = getCharWidth(Kind, Target);
1080 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1081 CharByteWidth /= 8;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 // The output buffer size needs to be large enough to hold wide characters.
1084 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregor5cee1192011-07-27 05:40:30 +00001085 SizeBound *= CharByteWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 // Size the temporary buffer to hold the result string data.
1088 ResultBuf.resize(SizeBound);
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 // Likewise, but for each string piece.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001091 SmallString<512> TokenBuf;
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 TokenBuf.resize(MaxTokenLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 // Loop over all the strings, getting their spelling, and expanding them to
1095 // wide strings as appropriate.
1096 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Anders Carlssonee98ac52007-10-15 02:50:23 +00001098 Pascal = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001100 SourceLocation UDSuffixTokLoc;
1101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1103 const char *ThisTokBuf = &TokenBuf[0];
1104 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1105 // that ThisTokBuf points to a buffer that is big enough for the whole token
1106 // and 'spelled' tokens can only shrink.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001107 bool StringInvalid = false;
Chris Lattner0833dd02010-11-17 07:21:13 +00001108 unsigned ThisTokLen =
Chris Lattnerb0607272010-11-17 07:26:20 +00001109 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1110 &StringInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001111 if (StringInvalid) {
Douglas Gregor5cee1192011-07-27 05:40:30 +00001112 hadError = true;
Douglas Gregor50f6af72010-03-16 05:20:39 +00001113 continue;
1114 }
1115
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001116 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1117
1118 // Remove an optional ud-suffix.
1119 if (ThisTokEnd[-1] != '"') {
1120 const char *UDSuffixEnd = ThisTokEnd;
1121 do {
1122 --ThisTokEnd;
1123 } while (ThisTokEnd[-1] != '"');
1124
1125 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1126
1127 if (UDSuffixBuf.empty()) {
1128 UDSuffixBuf.assign(UDSuffix);
Richard Smithdd66be72012-03-08 01:34:56 +00001129 UDSuffixToken = i;
1130 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smith5cc2c6e2012-03-05 04:02:15 +00001131 UDSuffixTokLoc = StringToks[i].getLocation();
1132 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1133 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1134 // result of a concatenation involving at least one user-defined-string-
1135 // literal, all the participating user-defined-string-literals shall
1136 // have the same ud-suffix.
1137 if (Diags) {
1138 SourceLocation TokLoc = StringToks[i].getLocation();
1139 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1140 << UDSuffixBuf << UDSuffix
1141 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1142 << SourceRange(TokLoc, TokLoc);
1143 }
1144 hadError = true;
1145 }
1146 }
1147
1148 // Strip the end quote.
1149 --ThisTokEnd;
1150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 // TODO: Input character set mapping support.
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Craig Topper1661d712011-08-08 06:10:39 +00001153 // Skip marker for wide or unicode strings.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001154 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 ++ThisTokBuf;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001156 // Skip 8 of u8 marker for utf8 strings.
1157 if (ThisTokBuf[0] == '8')
1158 ++ThisTokBuf;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +00001159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Craig Topper2fa4e862011-08-11 04:06:15 +00001161 // Check for raw string
1162 if (ThisTokBuf[0] == 'R') {
1163 ThisTokBuf += 2; // skip R"
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Craig Topper2fa4e862011-08-11 04:06:15 +00001165 const char *Prefix = ThisTokBuf;
1166 while (ThisTokBuf[0] != '(')
Anders Carlssonee98ac52007-10-15 02:50:23 +00001167 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001168 ++ThisTokBuf; // skip '('
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Craig Topper2fa4e862011-08-11 04:06:15 +00001170 // remove same number of characters from the end
1171 if (ThisTokEnd >= ThisTokBuf + (ThisTokBuf - Prefix))
1172 ThisTokEnd -= (ThisTokBuf - Prefix);
1173
1174 // Copy the string over
Eli Friedmanf74a4582011-11-01 02:14:50 +00001175 if (CopyStringFragment(StringRef(ThisTokBuf,ThisTokEnd-ThisTokBuf)))
1176 {
Eli Friedman91359302012-02-11 05:08:10 +00001177 if (DiagnoseBadString(StringToks[i]))
1178 hadError = true;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001179 }
1180
Craig Topper2fa4e862011-08-11 04:06:15 +00001181 } else {
1182 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
1183 ++ThisTokBuf; // skip "
1184
1185 // Check if this is a pascal string
1186 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1187 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1188
1189 // If the \p sequence is found in the first token, we have a pascal string
1190 // Otherwise, if we already have a pascal string, ignore the first \p
1191 if (i == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 ++ThisTokBuf;
Craig Topper2fa4e862011-08-11 04:06:15 +00001193 Pascal = true;
1194 } else if (Pascal)
1195 ThisTokBuf += 2;
1196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Craig Topper2fa4e862011-08-11 04:06:15 +00001198 while (ThisTokBuf != ThisTokEnd) {
1199 // Is this a span of non-escape characters?
1200 if (ThisTokBuf[0] != '\\') {
1201 const char *InStart = ThisTokBuf;
1202 do {
1203 ++ThisTokBuf;
1204 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1205
1206 // Copy the character span over.
Eli Friedmanf74a4582011-11-01 02:14:50 +00001207 if (CopyStringFragment(StringRef(InStart,ThisTokBuf-InStart)))
1208 {
Eli Friedman91359302012-02-11 05:08:10 +00001209 if (DiagnoseBadString(StringToks[i]))
1210 hadError = true;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001211 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001212 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00001213 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001214 // Is this a Universal Character Name escape?
1215 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1216 EncodeUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
1217 hadError, FullSourceLoc(StringToks[i].getLocation(),SM),
1218 CharByteWidth, Diags, Features);
1219 continue;
1220 }
1221 // Otherwise, this is a non-UCN escape character. Process it.
1222 unsigned ResultChar =
1223 ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
1224 FullSourceLoc(StringToks[i].getLocation(), SM),
1225 CharByteWidth*8, Diags);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Eli Friedmancaf1f262011-11-02 23:06:23 +00001227 if (CharByteWidth == 4) {
1228 // FIXME: Make the type of the result buffer correct instead of
1229 // using reinterpret_cast.
1230 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001231 *ResultWidePtr = ResultChar;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001232 ResultPtr += 4;
1233 } else if (CharByteWidth == 2) {
1234 // FIXME: Make the type of the result buffer correct instead of
1235 // using reinterpret_cast.
1236 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weber9b483df2011-11-14 05:17:37 +00001237 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmancaf1f262011-11-02 23:06:23 +00001238 ResultPtr += 2;
1239 } else {
1240 assert(CharByteWidth == 1 && "Unexpected char width");
1241 *ResultPtr++ = ResultChar & 0xFF;
1242 }
Craig Topper2fa4e862011-08-11 04:06:15 +00001243 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 }
1245 }
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001247 if (Pascal) {
Eli Friedman22508f42011-11-05 00:41:04 +00001248 if (CharByteWidth == 4) {
1249 // FIXME: Make the type of the result buffer correct instead of
1250 // using reinterpret_cast.
1251 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1252 ResultWidePtr[0] = GetNumStringChars() - 1;
1253 } else if (CharByteWidth == 2) {
1254 // FIXME: Make the type of the result buffer correct instead of
1255 // using reinterpret_cast.
1256 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1257 ResultWidePtr[0] = GetNumStringChars() - 1;
1258 } else {
1259 assert(CharByteWidth == 1 && "Unexpected char width");
1260 ResultBuf[0] = GetNumStringChars() - 1;
1261 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001262
1263 // Verify that pascal strings aren't too large.
Chris Lattner0833dd02010-11-17 07:21:13 +00001264 if (GetStringLength() > 256) {
1265 if (Diags)
1266 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1267 diag::err_pascal_string_too_long)
1268 << SourceRange(StringToks[0].getLocation(),
1269 StringToks[NumStringToks-1].getLocation());
Douglas Gregor5cee1192011-07-27 05:40:30 +00001270 hadError = true;
Eli Friedman57d7dde2009-04-01 03:17:08 +00001271 return;
1272 }
Chris Lattner0833dd02010-11-17 07:21:13 +00001273 } else if (Diags) {
Douglas Gregor427c4922010-07-20 14:33:20 +00001274 // Complain if this string literal has too many characters.
Chris Lattnera95880d2010-11-17 07:12:42 +00001275 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Douglas Gregor427c4922010-07-20 14:33:20 +00001276
1277 if (GetNumStringChars() > MaxChars)
Chris Lattner0833dd02010-11-17 07:21:13 +00001278 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1279 diag::ext_string_too_long)
Douglas Gregor427c4922010-07-20 14:33:20 +00001280 << GetNumStringChars() << MaxChars
Chris Lattnera95880d2010-11-17 07:12:42 +00001281 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregor427c4922010-07-20 14:33:20 +00001282 << SourceRange(StringToks[0].getLocation(),
1283 StringToks[NumStringToks-1].getLocation());
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001284 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001285}
Chris Lattner719e6152009-02-18 19:21:10 +00001286
1287
Craig Topper2fa4e862011-08-11 04:06:15 +00001288/// copyStringFragment - This function copies from Start to End into ResultPtr.
1289/// Performs widening for multi-byte characters.
Eli Friedmanf74a4582011-11-01 02:14:50 +00001290bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
1291 assert(CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4);
1292 ConversionResult result = conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001293 // Copy the character span over.
1294 if (CharByteWidth == 1) {
Eli Friedman91359302012-02-11 05:08:10 +00001295 if (!isLegalUTF8Sequence(reinterpret_cast<const UTF8*>(Fragment.begin()),
1296 reinterpret_cast<const UTF8*>(Fragment.end())))
1297 result = sourceIllegal;
Craig Topper2fa4e862011-08-11 04:06:15 +00001298 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1299 ResultPtr += Fragment.size();
Eli Friedmanf74a4582011-11-01 02:14:50 +00001300 } else if (CharByteWidth == 2) {
1301 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1302 // FIXME: Make the type of the result buffer correct instead of
1303 // using reinterpret_cast.
1304 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001305 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001306 result = ConvertUTF8toUTF16(
1307 &sourceStart,sourceStart + Fragment.size(),
1308 &targetStart,targetStart + 2*Fragment.size(),flags);
1309 if (result==conversionOK)
1310 ResultPtr = reinterpret_cast<char*>(targetStart);
1311 } else if (CharByteWidth == 4) {
1312 UTF8 const *sourceStart = (UTF8 const *)Fragment.data();
1313 // FIXME: Make the type of the result buffer correct instead of
1314 // using reinterpret_cast.
1315 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
Eli Friedman91359302012-02-11 05:08:10 +00001316 ConversionFlags flags = strictConversion;
Eli Friedmanf74a4582011-11-01 02:14:50 +00001317 result = ConvertUTF8toUTF32(
1318 &sourceStart,sourceStart + Fragment.size(),
1319 &targetStart,targetStart + 4*Fragment.size(),flags);
1320 if (result==conversionOK)
1321 ResultPtr = reinterpret_cast<char*>(targetStart);
Craig Topper2fa4e862011-08-11 04:06:15 +00001322 }
Eli Friedmanf74a4582011-11-01 02:14:50 +00001323 assert((result != targetExhausted)
1324 && "ConvertUTF8toUTFXX exhausted target buffer");
1325 return result != conversionOK;
Craig Topper2fa4e862011-08-11 04:06:15 +00001326}
1327
Eli Friedman91359302012-02-11 05:08:10 +00001328bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
1329 // If we see bad encoding for unprefixed string literals, warn and
1330 // simply copy the byte values, for compatibility with gcc and older
1331 // versions of clang.
1332 bool NoErrorOnBadEncoding = isAscii();
1333 unsigned Msg = NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
1334 diag::err_bad_string_encoding;
1335 if (Diags)
1336 Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
1337 return !NoErrorOnBadEncoding;
1338}
Craig Topper2fa4e862011-08-11 04:06:15 +00001339
Chris Lattner719e6152009-02-18 19:21:10 +00001340/// getOffsetOfStringByte - This function returns the offset of the
1341/// specified byte of the string data represented by Token. This handles
1342/// advancing over escape sequences in the string.
1343unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattner6c66f072010-11-17 06:46:14 +00001344 unsigned ByteNo) const {
Chris Lattner719e6152009-02-18 19:21:10 +00001345 // Get the spelling of the token.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001346 SmallString<32> SpellingBuffer;
Sean Hunt6cf75022010-08-30 17:47:05 +00001347 SpellingBuffer.resize(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Douglas Gregor50f6af72010-03-16 05:20:39 +00001349 bool StringInvalid = false;
Chris Lattner719e6152009-02-18 19:21:10 +00001350 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattnerb0607272010-11-17 07:26:20 +00001351 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1352 &StringInvalid);
Chris Lattner91f54ce2010-11-17 06:26:08 +00001353 if (StringInvalid)
Douglas Gregor50f6af72010-03-16 05:20:39 +00001354 return 0;
Chris Lattner719e6152009-02-18 19:21:10 +00001355
Douglas Gregor5cee1192011-07-27 05:40:30 +00001356 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1357 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
Chris Lattner719e6152009-02-18 19:21:10 +00001358
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Chris Lattner719e6152009-02-18 19:21:10 +00001360 const char *SpellingStart = SpellingPtr;
1361 const char *SpellingEnd = SpellingPtr+TokLen;
1362
1363 // Skip over the leading quote.
1364 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1365 ++SpellingPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattner719e6152009-02-18 19:21:10 +00001367 // Skip over bytes until we find the offset we're looking for.
1368 while (ByteNo) {
1369 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Chris Lattner719e6152009-02-18 19:21:10 +00001371 // Step over non-escapes simply.
1372 if (*SpellingPtr != '\\') {
1373 ++SpellingPtr;
1374 --ByteNo;
1375 continue;
1376 }
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Chris Lattner719e6152009-02-18 19:21:10 +00001378 // Otherwise, this is an escape character. Advance over it.
1379 bool HadError = false;
1380 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
Chris Lattnerca1475e2010-11-17 06:35:43 +00001381 FullSourceLoc(Tok.getLocation(), SM),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001382 CharByteWidth*8, Diags);
Chris Lattner719e6152009-02-18 19:21:10 +00001383 assert(!HadError && "This method isn't valid on erroneous strings");
1384 --ByteNo;
1385 }
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Chris Lattner719e6152009-02-18 19:21:10 +00001387 return SpellingPtr-SpellingStart;
1388}