blob: c637c3881927e3c6549f15e93b26054f35282a6f [file] [log] [blame]
Chris Lattner2f5add62007-04-05 06:57:15 +00001//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
Steve Naroff09ef4742007-03-09 23:16:33 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Steve Naroff09ef4742007-03-09 23:16:33 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner2f5add62007-04-05 06:57:15 +000010// This file implements the NumericLiteralParser, CharLiteralParser, and
11// StringLiteralParser interfaces.
Steve Naroff09ef4742007-03-09 23:16:33 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/LiteralSupport.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000016#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Basic/TargetInfo.h"
18#include "clang/Lex/LexDiagnostic.h"
19#include "clang/Lex/Preprocessor.h"
Steve Naroff4f88b312007-03-13 22:37:02 +000020#include "llvm/ADT/StringExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000021#include "llvm/Support/ConvertUTF.h"
David Blaikie76bd3c82011-09-23 05:35:21 +000022#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000023
Steve Naroff09ef4742007-03-09 23:16:33 +000024using namespace clang;
25
Douglas Gregorfb65e592011-07-27 05:40:30 +000026static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
27 switch (kind) {
David Blaikie83d382b2011-09-23 05:06:16 +000028 default: llvm_unreachable("Unknown token type!");
Douglas Gregorfb65e592011-07-27 05:40:30 +000029 case tok::char_constant:
30 case tok::string_literal:
31 case tok::utf8_string_literal:
32 return Target.getCharWidth();
33 case tok::wide_char_constant:
34 case tok::wide_string_literal:
35 return Target.getWCharWidth();
36 case tok::utf16_char_constant:
37 case tok::utf16_string_literal:
38 return Target.getChar16Width();
39 case tok::utf32_char_constant:
40 case tok::utf32_string_literal:
41 return Target.getChar32Width();
42 }
43}
44
Seth Cantrell4cfc8172012-10-28 18:24:46 +000045static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
46 FullSourceLoc TokLoc,
47 const char *TokBegin,
48 const char *TokRangeBegin,
49 const char *TokRangeEnd) {
50 SourceLocation Begin =
51 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
52 TokLoc.getManager(), Features);
53 SourceLocation End =
54 Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
55 TokLoc.getManager(), Features);
56 return CharSourceRange::getCharRange(Begin, End);
57}
58
Richard Smith639b8d02012-09-08 07:16:20 +000059/// \brief Produce a diagnostic highlighting some portion of a literal.
60///
61/// Emits the diagnostic \p DiagID, highlighting the range of characters from
62/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
63/// a substring of a spelling buffer for the token beginning at \p TokBegin.
64static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
65 const LangOptions &Features, FullSourceLoc TokLoc,
66 const char *TokBegin, const char *TokRangeBegin,
67 const char *TokRangeEnd, unsigned DiagID) {
68 SourceLocation Begin =
69 Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
70 TokLoc.getManager(), Features);
Seth Cantrell4cfc8172012-10-28 18:24:46 +000071 return Diags->Report(Begin, DiagID) <<
72 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
Richard Smith639b8d02012-09-08 07:16:20 +000073}
74
Chris Lattner2f5add62007-04-05 06:57:15 +000075/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
76/// either a character or a string literal.
Richard Smith639b8d02012-09-08 07:16:20 +000077static unsigned ProcessCharEscape(const char *ThisTokBegin,
78 const char *&ThisTokBuf,
Chris Lattner2f5add62007-04-05 06:57:15 +000079 const char *ThisTokEnd, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +000080 FullSourceLoc Loc, unsigned CharWidth,
Richard Smith639b8d02012-09-08 07:16:20 +000081 DiagnosticsEngine *Diags,
82 const LangOptions &Features) {
83 const char *EscapeBegin = ThisTokBuf;
84
Chris Lattner2f5add62007-04-05 06:57:15 +000085 // Skip the '\' char.
86 ++ThisTokBuf;
87
88 // We know that this character can't be off the end of the buffer, because
89 // that would have been \", which would not have been the end of string.
90 unsigned ResultChar = *ThisTokBuf++;
91 switch (ResultChar) {
92 // These map to themselves.
93 case '\\': case '\'': case '"': case '?': break;
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattner2f5add62007-04-05 06:57:15 +000095 // These have fixed mappings.
96 case 'a':
97 // TODO: K&R: the meaning of '\\a' is different in traditional C
98 ResultChar = 7;
99 break;
100 case 'b':
101 ResultChar = 8;
102 break;
103 case 'e':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000104 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000105 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
106 diag::ext_nonstandard_escape) << "e";
Chris Lattner2f5add62007-04-05 06:57:15 +0000107 ResultChar = 27;
108 break;
Eli Friedman28a00aa2009-06-10 01:32:39 +0000109 case 'E':
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000110 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000111 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
112 diag::ext_nonstandard_escape) << "E";
Eli Friedman28a00aa2009-06-10 01:32:39 +0000113 ResultChar = 27;
114 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000115 case 'f':
116 ResultChar = 12;
117 break;
118 case 'n':
119 ResultChar = 10;
120 break;
121 case 'r':
122 ResultChar = 13;
123 break;
124 case 't':
125 ResultChar = 9;
126 break;
127 case 'v':
128 ResultChar = 11;
129 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000130 case 'x': { // Hex escape.
131 ResultChar = 0;
Jordan Rosea7d03842013-02-08 22:30:41 +0000132 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000133 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000134 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000135 diag::err_hex_escape_no_digits) << "x";
Chris Lattner2f5add62007-04-05 06:57:15 +0000136 HadError = 1;
Chris Lattner2f5add62007-04-05 06:57:15 +0000137 break;
138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattner812eda82007-05-20 05:17:04 +0000140 // Hex escapes are a maximal series of hex digits.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000141 bool Overflow = false;
142 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000143 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Chris Lattnerc10adde2007-05-20 05:00:58 +0000144 if (CharVal == -1) break;
Chris Lattner59f09b62008-09-30 20:45:40 +0000145 // About to shift out a digit?
146 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000147 ResultChar <<= 4;
148 ResultChar |= CharVal;
149 }
150
151 // See if any bits will be truncated when evaluated as a character.
Chris Lattnerc10adde2007-05-20 05:00:58 +0000152 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
153 Overflow = true;
154 ResultChar &= ~0U >> (32-CharWidth);
155 }
Mike Stump11289f42009-09-09 15:08:12 +0000156
Chris Lattnerc10adde2007-05-20 05:00:58 +0000157 // Check for overflow.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000158 if (Overflow && Diags) // Too many digits to fit in
Richard Smith639b8d02012-09-08 07:16:20 +0000159 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Eli Friedman088d39a2013-07-23 00:25:18 +0000160 diag::err_hex_escape_too_large);
Chris Lattner2f5add62007-04-05 06:57:15 +0000161 break;
Chris Lattnerc10adde2007-05-20 05:00:58 +0000162 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000163 case '0': case '1': case '2': case '3':
Chris Lattner812eda82007-05-20 05:17:04 +0000164 case '4': case '5': case '6': case '7': {
Chris Lattner2f5add62007-04-05 06:57:15 +0000165 // Octal escapes.
Chris Lattner3f4b6e32007-06-09 06:20:47 +0000166 --ThisTokBuf;
Chris Lattner812eda82007-05-20 05:17:04 +0000167 ResultChar = 0;
168
169 // Octal escapes are a series of octal digits with maximum length 3.
170 // "\0123" is a two digit sequence equal to "\012" "3".
171 unsigned NumDigits = 0;
172 do {
173 ResultChar <<= 3;
174 ResultChar |= *ThisTokBuf++ - '0';
175 ++NumDigits;
176 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
177 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner812eda82007-05-20 05:17:04 +0000179 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner812eda82007-05-20 05:17:04 +0000180 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000181 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000182 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
Eli Friedman088d39a2013-07-23 00:25:18 +0000183 diag::err_octal_escape_too_large);
Chris Lattner812eda82007-05-20 05:17:04 +0000184 ResultChar &= ~0U >> (32-CharWidth);
185 }
Chris Lattner2f5add62007-04-05 06:57:15 +0000186 break;
Chris Lattner812eda82007-05-20 05:17:04 +0000187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner2f5add62007-04-05 06:57:15 +0000189 // Otherwise, these are not valid escapes.
190 case '(': case '{': case '[': case '%':
191 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000192 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000193 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
194 diag::ext_nonstandard_escape)
195 << std::string(1, ResultChar);
Eli Friedman5d72d412009-04-28 00:51:18 +0000196 break;
Chris Lattner2f5add62007-04-05 06:57:15 +0000197 default:
Chris Lattner7a02bfd2010-11-17 06:26:08 +0000198 if (Diags == 0)
Douglas Gregor9af03022010-05-26 05:35:51 +0000199 break;
Richard Smith639b8d02012-09-08 07:16:20 +0000200
Jordan Rosea7d03842013-02-08 22:30:41 +0000201 if (isPrintable(ResultChar))
Richard Smith639b8d02012-09-08 07:16:20 +0000202 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
203 diag::ext_unknown_escape)
204 << std::string(1, ResultChar);
Chris Lattner59acca52008-11-22 07:23:31 +0000205 else
Richard Smith639b8d02012-09-08 07:16:20 +0000206 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
207 diag::ext_unknown_escape)
208 << "x" + llvm::utohexstr(ResultChar);
Chris Lattner2f5add62007-04-05 06:57:15 +0000209 break;
210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner2f5add62007-04-05 06:57:15 +0000212 return ResultChar;
213}
214
Steve Naroff7b753d22009-03-30 23:46:03 +0000215/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Webera6bde812010-10-09 00:27:47 +0000216/// return the UTF32.
Richard Smith2a70e652012-03-09 22:27:51 +0000217static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
218 const char *ThisTokEnd,
Nico Webera6bde812010-10-09 00:27:47 +0000219 uint32_t &UcnVal, unsigned short &UcnLen,
David Blaikie9c902b52011-09-25 23:23:43 +0000220 FullSourceLoc Loc, DiagnosticsEngine *Diags,
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000221 const LangOptions &Features,
222 bool in_char_string_literal = false) {
Richard Smith2a70e652012-03-09 22:27:51 +0000223 const char *UcnBegin = ThisTokBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000224
Steve Naroff7b753d22009-03-30 23:46:03 +0000225 // Skip the '\u' char's.
226 ThisTokBuf += 2;
Chris Lattner2f5add62007-04-05 06:57:15 +0000227
Jordan Rosea7d03842013-02-08 22:30:41 +0000228 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
Chris Lattnerbde1b812010-11-17 06:46:14 +0000229 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000230 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Roseaa89cf12013-01-24 20:50:13 +0000231 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
Nico Webera6bde812010-10-09 00:27:47 +0000232 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000233 }
Nico Webera6bde812010-10-09 00:27:47 +0000234 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000235 unsigned short UcnLenSave = UcnLen;
Nico Webera6bde812010-10-09 00:27:47 +0000236 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000237 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000238 if (CharVal == -1) break;
239 UcnVal <<= 4;
240 UcnVal |= CharVal;
241 }
242 // If we didn't consume the proper number of digits, there is a problem.
Nico Webera6bde812010-10-09 00:27:47 +0000243 if (UcnLenSave) {
Richard Smith639b8d02012-09-08 07:16:20 +0000244 if (Diags)
245 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
246 diag::err_ucn_escape_incomplete);
Nico Webera6bde812010-10-09 00:27:47 +0000247 return false;
Steve Naroff7b753d22009-03-30 23:46:03 +0000248 }
Richard Smith2a70e652012-03-09 22:27:51 +0000249
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000250 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
Richard Smith2a70e652012-03-09 22:27:51 +0000251 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
252 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
Chris Lattnerbde1b812010-11-17 06:46:14 +0000253 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +0000254 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
255 diag::err_ucn_escape_invalid);
Nico Webera6bde812010-10-09 00:27:47 +0000256 return false;
257 }
Richard Smith2a70e652012-03-09 22:27:51 +0000258
259 // C++11 allows UCNs that refer to control characters and basic source
260 // characters inside character and string literals
261 if (UcnVal < 0xa0 &&
262 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000263 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
Richard Smith2a70e652012-03-09 22:27:51 +0000264 if (Diags) {
Richard Smith2a70e652012-03-09 22:27:51 +0000265 char BasicSCSChar = UcnVal;
266 if (UcnVal >= 0x20 && UcnVal < 0x7f)
Richard Smith639b8d02012-09-08 07:16:20 +0000267 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
268 IsError ? diag::err_ucn_escape_basic_scs :
269 diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
270 << StringRef(&BasicSCSChar, 1);
Richard Smith2a70e652012-03-09 22:27:51 +0000271 else
Richard Smith639b8d02012-09-08 07:16:20 +0000272 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
273 IsError ? diag::err_ucn_control_character :
274 diag::warn_cxx98_compat_literal_ucn_control_character);
Richard Smith2a70e652012-03-09 22:27:51 +0000275 }
276 if (IsError)
277 return false;
278 }
279
Richard Smith639b8d02012-09-08 07:16:20 +0000280 if (!Features.CPlusPlus && !Features.C99 && Diags)
281 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
Jordan Rosec0cba272013-01-27 20:12:04 +0000282 diag::warn_ucn_not_valid_in_c89_literal);
Richard Smith639b8d02012-09-08 07:16:20 +0000283
Nico Webera6bde812010-10-09 00:27:47 +0000284 return true;
285}
286
Richard Smith4060f772012-06-13 05:37:23 +0000287/// MeasureUCNEscape - Determine the number of bytes within the resulting string
288/// which this UCN will occupy.
289static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
290 const char *ThisTokEnd, unsigned CharByteWidth,
291 const LangOptions &Features, bool &HadError) {
292 // UTF-32: 4 bytes per escape.
293 if (CharByteWidth == 4)
294 return 4;
295
296 uint32_t UcnVal = 0;
297 unsigned short UcnLen = 0;
298 FullSourceLoc Loc;
299
300 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
301 UcnLen, Loc, 0, Features, true)) {
302 HadError = true;
303 return 0;
304 }
305
306 // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
307 if (CharByteWidth == 2)
308 return UcnVal <= 0xFFFF ? 2 : 4;
309
310 // UTF-8.
311 if (UcnVal < 0x80)
312 return 1;
313 if (UcnVal < 0x800)
314 return 2;
315 if (UcnVal < 0x10000)
316 return 3;
317 return 4;
318}
319
Nico Webera6bde812010-10-09 00:27:47 +0000320/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
321/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
322/// StringLiteralParser. When we decide to implement UCN's for identifiers,
323/// we will likely rework our support for UCN's.
Richard Smith2a70e652012-03-09 22:27:51 +0000324static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
325 const char *ThisTokEnd,
Chris Lattner2be8aa92010-11-17 07:12:42 +0000326 char *&ResultBuf, bool &HadError,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000327 FullSourceLoc Loc, unsigned CharByteWidth,
David Blaikie9c902b52011-09-25 23:23:43 +0000328 DiagnosticsEngine *Diags,
329 const LangOptions &Features) {
Nico Webera6bde812010-10-09 00:27:47 +0000330 typedef uint32_t UTF32;
331 UTF32 UcnVal = 0;
332 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +0000333 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
334 Loc, Diags, Features, true)) {
Richard Smith4060f772012-06-13 05:37:23 +0000335 HadError = true;
Steve Naroff7b753d22009-03-30 23:46:03 +0000336 return;
337 }
Nico Webera6bde812010-10-09 00:27:47 +0000338
Eli Friedmanf9edb002013-09-18 23:23:13 +0000339 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
Douglas Gregorfb65e592011-07-27 05:40:30 +0000340 "only character widths of 1, 2, or 4 bytes supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000341
Douglas Gregorfb65e592011-07-27 05:40:30 +0000342 (void)UcnLen;
343 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Weber9762e0a2010-10-06 04:57:26 +0000344
Douglas Gregorfb65e592011-07-27 05:40:30 +0000345 if (CharByteWidth == 4) {
Eli Friedmand1370792011-11-02 23:06:23 +0000346 // FIXME: Make the type of the result buffer correct instead of
347 // using reinterpret_cast.
348 UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf);
349 *ResultPtr = UcnVal;
350 ResultBuf += 4;
Douglas Gregorfb65e592011-07-27 05:40:30 +0000351 return;
352 }
353
354 if (CharByteWidth == 2) {
Eli Friedmand1370792011-11-02 23:06:23 +0000355 // FIXME: Make the type of the result buffer correct instead of
356 // using reinterpret_cast.
357 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
358
Richard Smith0948d932012-06-13 05:41:29 +0000359 if (UcnVal <= (UTF32)0xFFFF) {
Eli Friedmand1370792011-11-02 23:06:23 +0000360 *ResultPtr = UcnVal;
361 ResultBuf += 2;
Nico Weber9762e0a2010-10-06 04:57:26 +0000362 return;
363 }
Nico Weber9762e0a2010-10-06 04:57:26 +0000364
Eli Friedmand1370792011-11-02 23:06:23 +0000365 // Convert to UTF16.
Nico Weber9762e0a2010-10-06 04:57:26 +0000366 UcnVal -= 0x10000;
Eli Friedmand1370792011-11-02 23:06:23 +0000367 *ResultPtr = 0xD800 + (UcnVal >> 10);
368 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
369 ResultBuf += 4;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +0000370 return;
371 }
Douglas Gregorfb65e592011-07-27 05:40:30 +0000372
373 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
374
Steve Naroff7b753d22009-03-30 23:46:03 +0000375 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
376 // The conversion below was inspired by:
377 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump11289f42009-09-09 15:08:12 +0000378 // First, we determine how many bytes the result will require.
Steve Naroffc94adda2009-04-01 11:09:15 +0000379 typedef uint8_t UTF8;
Steve Naroff7b753d22009-03-30 23:46:03 +0000380
381 unsigned short bytesToWrite = 0;
382 if (UcnVal < (UTF32)0x80)
383 bytesToWrite = 1;
384 else if (UcnVal < (UTF32)0x800)
385 bytesToWrite = 2;
386 else if (UcnVal < (UTF32)0x10000)
387 bytesToWrite = 3;
388 else
389 bytesToWrite = 4;
Mike Stump11289f42009-09-09 15:08:12 +0000390
Steve Naroff7b753d22009-03-30 23:46:03 +0000391 const unsigned byteMask = 0xBF;
392 const unsigned byteMark = 0x80;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Steve Naroff7b753d22009-03-30 23:46:03 +0000394 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Narofff2a880c2009-03-31 10:29:45 +0000395 // into the first byte, depending on how many bytes follow.
Mike Stump11289f42009-09-09 15:08:12 +0000396 static const UTF8 firstByteMark[5] = {
Steve Narofff2a880c2009-03-31 10:29:45 +0000397 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff7b753d22009-03-30 23:46:03 +0000398 };
399 // Finally, we write the bytes into ResultBuf.
400 ResultBuf += bytesToWrite;
401 switch (bytesToWrite) { // note: everything falls through.
Benjamin Kramerf23a6e62012-11-08 19:22:26 +0000402 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
403 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
404 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
405 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
Steve Naroff7b753d22009-03-30 23:46:03 +0000406 }
407 // Update the buffer.
408 ResultBuf += bytesToWrite;
409}
Chris Lattner2f5add62007-04-05 06:57:15 +0000410
411
Steve Naroff09ef4742007-03-09 23:16:33 +0000412/// integer-constant: [C99 6.4.4.1]
413/// decimal-constant integer-suffix
414/// octal-constant integer-suffix
415/// hexadecimal-constant integer-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000416/// binary-literal integer-suffix [GNU, C++1y]
Richard Smith81292452012-03-08 21:59:28 +0000417/// user-defined-integer-literal: [C++11 lex.ext]
Richard Smith39570d002012-03-08 08:45:32 +0000418/// decimal-literal ud-suffix
419/// octal-literal ud-suffix
420/// hexadecimal-literal ud-suffix
Richard Smithf4198b72013-07-23 08:14:48 +0000421/// binary-literal ud-suffix [GNU, C++1y]
Mike Stump11289f42009-09-09 15:08:12 +0000422/// decimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000423/// nonzero-digit
424/// decimal-constant digit
Mike Stump11289f42009-09-09 15:08:12 +0000425/// octal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000426/// 0
427/// octal-constant octal-digit
Mike Stump11289f42009-09-09 15:08:12 +0000428/// hexadecimal-constant:
Steve Naroff09ef4742007-03-09 23:16:33 +0000429/// hexadecimal-prefix hexadecimal-digit
430/// hexadecimal-constant hexadecimal-digit
431/// hexadecimal-prefix: one of
432/// 0x 0X
Richard Smithf4198b72013-07-23 08:14:48 +0000433/// binary-literal:
434/// 0b binary-digit
435/// 0B binary-digit
436/// binary-literal binary-digit
Steve Naroff09ef4742007-03-09 23:16:33 +0000437/// integer-suffix:
438/// unsigned-suffix [long-suffix]
439/// unsigned-suffix [long-long-suffix]
440/// long-suffix [unsigned-suffix]
441/// long-long-suffix [unsigned-sufix]
442/// nonzero-digit:
443/// 1 2 3 4 5 6 7 8 9
444/// octal-digit:
445/// 0 1 2 3 4 5 6 7
446/// hexadecimal-digit:
447/// 0 1 2 3 4 5 6 7 8 9
448/// a b c d e f
449/// A B C D E F
Richard Smithf4198b72013-07-23 08:14:48 +0000450/// binary-digit:
451/// 0
452/// 1
Steve Naroff09ef4742007-03-09 23:16:33 +0000453/// unsigned-suffix: one of
454/// u U
455/// long-suffix: one of
456/// l L
Mike Stump11289f42009-09-09 15:08:12 +0000457/// long-long-suffix: one of
Steve Naroff09ef4742007-03-09 23:16:33 +0000458/// ll LL
459///
460/// floating-constant: [C99 6.4.4.2]
461/// TODO: add rules...
462///
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000463NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
464 SourceLocation TokLoc,
465 Preprocessor &PP)
466 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
Mike Stump11289f42009-09-09 15:08:12 +0000467
Chris Lattner59f09b62008-09-30 20:45:40 +0000468 // This routine assumes that the range begin/end matches the regex for integer
469 // and FP constants (specifically, the 'pp-number' regex), and assumes that
470 // the byte at "*end" is both valid and not part of the regex. Because of
471 // this, it doesn't have to check for 'overscan' in various places.
Jordan Rosea7d03842013-02-08 22:30:41 +0000472 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
Mike Stump11289f42009-09-09 15:08:12 +0000473
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000474 s = DigitsBegin = ThisTokBegin;
Steve Naroff09ef4742007-03-09 23:16:33 +0000475 saw_exponent = false;
476 saw_period = false;
Richard Smith39570d002012-03-08 08:45:32 +0000477 saw_ud_suffix = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000478 isLong = false;
479 isUnsigned = false;
480 isLongLong = false;
Chris Lattnered045422007-08-26 03:29:23 +0000481 isFloat = false;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000482 isImaginary = false;
Mike Stumpc99c0222009-10-08 22:55:36 +0000483 isMicrosoftInteger = false;
Steve Naroff09ef4742007-03-09 23:16:33 +0000484 hadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000485
Steve Naroff09ef4742007-03-09 23:16:33 +0000486 if (*s == '0') { // parse radix
Chris Lattner6016a512008-06-30 06:39:54 +0000487 ParseNumberStartingWithZero(TokLoc);
488 if (hadError)
489 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000490 } else { // the first digit is non-zero
491 radix = 10;
492 s = SkipDigits(s);
493 if (s == ThisTokEnd) {
Chris Lattner328fa5c2007-06-08 17:12:06 +0000494 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000495 } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000496 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000498 hadError = true;
Chris Lattner328fa5c2007-06-08 17:12:06 +0000499 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000500 } else if (*s == '.') {
501 s++;
502 saw_period = true;
503 s = SkipDigits(s);
Mike Stump11289f42009-09-09 15:08:12 +0000504 }
Chris Lattnerfb8b8f22008-09-29 23:12:31 +0000505 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner4885b972008-04-20 18:47:55 +0000506 const char *Exponent = s;
Steve Naroff09ef4742007-03-09 23:16:33 +0000507 s++;
508 saw_exponent = true;
509 if (*s == '+' || *s == '-') s++; // sign
510 const char *first_non_digit = SkipDigits(s);
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000511 if (first_non_digit != s) {
Steve Naroff09ef4742007-03-09 23:16:33 +0000512 s = first_non_digit;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000513 } else {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000514 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000515 diag::err_exponent_has_no_digits);
516 hadError = true;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000517 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000518 }
519 }
520 }
521
522 SuffixBegin = s;
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattnerf55ab182007-08-26 01:58:14 +0000524 // Parse the suffix. At this point we can classify whether we have an FP or
525 // integer constant.
526 bool isFPConstant = isFloatingLiteral();
Richard Smithf4198b72013-07-23 08:14:48 +0000527 const char *ImaginarySuffixLoc = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf55ab182007-08-26 01:58:14 +0000529 // Loop over all of the characters of the suffix. If we see something bad,
530 // we break out of the loop.
531 for (; s != ThisTokEnd; ++s) {
532 switch (*s) {
533 case 'f': // FP Suffix for "float"
534 case 'F':
535 if (!isFPConstant) break; // Error for integer constant.
Chris Lattnered045422007-08-26 03:29:23 +0000536 if (isFloat || isLong) break; // FF, LF invalid.
537 isFloat = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000538 continue; // Success.
539 case 'u':
540 case 'U':
541 if (isFPConstant) break; // Error for floating constant.
542 if (isUnsigned) break; // Cannot be repeated.
543 isUnsigned = true;
544 continue; // Success.
545 case 'l':
546 case 'L':
547 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattnered045422007-08-26 03:29:23 +0000548 if (isFloat) break; // LF invalid.
Mike Stump11289f42009-09-09 15:08:12 +0000549
Chris Lattnerf55ab182007-08-26 01:58:14 +0000550 // Check for long long. The L's need to be adjacent and the same case.
551 if (s+1 != ThisTokEnd && s[1] == s[0]) {
552 if (isFPConstant) break; // long long invalid for floats.
553 isLongLong = true;
554 ++s; // Eat both of them.
555 } else {
Steve Naroff09ef4742007-03-09 23:16:33 +0000556 isLong = true;
Steve Naroff09ef4742007-03-09 23:16:33 +0000557 }
Chris Lattnerf55ab182007-08-26 01:58:14 +0000558 continue; // Success.
559 case 'i':
Chris Lattner26f6c222010-10-14 00:24:10 +0000560 case 'I':
David Blaikiebbafb8a2012-03-11 07:00:24 +0000561 if (PP.getLangOpts().MicrosoftExt) {
Fariborz Jahanian8c6c0b62010-01-22 21:36:53 +0000562 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000563
Steve Naroffa1f41452008-04-04 21:02:54 +0000564 // Allow i8, i16, i32, i64, and i128.
Mike Stumpc99c0222009-10-08 22:55:36 +0000565 if (s + 1 != ThisTokEnd) {
566 switch (s[1]) {
567 case '8':
568 s += 2; // i8 suffix
569 isMicrosoftInteger = true;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000570 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000571 case '1':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000572 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000573 if (s[2] == '6') {
574 s += 3; // i16 suffix
575 isMicrosoftInteger = true;
576 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000577 else if (s[2] == '2') {
578 if (s + 3 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000579 if (s[3] == '8') {
580 s += 4; // i128 suffix
581 isMicrosoftInteger = true;
582 }
Mike Stumpc99c0222009-10-08 22:55:36 +0000583 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000584 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000585 case '3':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000586 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000587 if (s[2] == '2') {
588 s += 3; // i32 suffix
589 isLong = true;
590 isMicrosoftInteger = true;
591 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000592 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000593 case '6':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000594 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000595 if (s[2] == '4') {
596 s += 3; // i64 suffix
597 isLongLong = true;
598 isMicrosoftInteger = true;
599 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000600 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000601 default:
602 break;
603 }
604 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000605 }
Steve Naroffa1f41452008-04-04 21:02:54 +0000606 }
607 // fall through.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000608 case 'j':
609 case 'J':
610 if (isImaginary) break; // Cannot be repeated.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000611 isImaginary = true;
Richard Smithf4198b72013-07-23 08:14:48 +0000612 ImaginarySuffixLoc = s;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000613 continue; // Success.
Steve Naroff09ef4742007-03-09 23:16:33 +0000614 }
Richard Smith39570d002012-03-08 08:45:32 +0000615 // If we reached here, there was an error or a ud-suffix.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000616 break;
617 }
Mike Stump11289f42009-09-09 15:08:12 +0000618
Chris Lattnerf55ab182007-08-26 01:58:14 +0000619 if (s != ThisTokEnd) {
Richard Smithf4198b72013-07-23 08:14:48 +0000620 if (isValidUDSuffix(PP.getLangOpts(),
621 StringRef(SuffixBegin, ThisTokEnd - SuffixBegin))) {
622 // Any suffix pieces we might have parsed are actually part of the
623 // ud-suffix.
624 isLong = false;
625 isUnsigned = false;
626 isLongLong = false;
627 isFloat = false;
628 isImaginary = false;
629 isMicrosoftInteger = false;
630
Richard Smith39570d002012-03-08 08:45:32 +0000631 saw_ud_suffix = true;
632 return;
633 }
634
635 // Report an error if there are any.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000636 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000637 isFPConstant ? diag::err_invalid_suffix_float_constant :
638 diag::err_invalid_suffix_integer_constant)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000639 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattner59acca52008-11-22 07:23:31 +0000640 hadError = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000641 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000642 }
Richard Smithf4198b72013-07-23 08:14:48 +0000643
644 if (isImaginary) {
645 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
646 ImaginarySuffixLoc - ThisTokBegin),
647 diag::ext_imaginary_constant);
648 }
649}
650
651/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
652/// suffixes as ud-suffixes, because the diagnostic experience is better if we
653/// treat it as an invalid suffix.
654bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
655 StringRef Suffix) {
656 if (!LangOpts.CPlusPlus11 || Suffix.empty())
657 return false;
658
659 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
660 if (Suffix[0] == '_')
661 return true;
662
663 // In C++11, there are no library suffixes.
664 if (!LangOpts.CPlusPlus1y)
665 return false;
666
667 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
668 return llvm::StringSwitch<bool>(Suffix)
669 .Cases("h", "min", "s", true)
670 .Cases("ms", "us", "ns", true)
671 .Default(false);
Steve Naroff09ef4742007-03-09 23:16:33 +0000672}
673
Chris Lattner6016a512008-06-30 06:39:54 +0000674/// ParseNumberStartingWithZero - This method is called when the first character
675/// of the number is found to be a zero. This means it is either an octal
676/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump11289f42009-09-09 15:08:12 +0000677/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner6016a512008-06-30 06:39:54 +0000678/// radix etc.
679void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
680 assert(s[0] == '0' && "Invalid method call");
681 s++;
Mike Stump11289f42009-09-09 15:08:12 +0000682
Chris Lattner6016a512008-06-30 06:39:54 +0000683 // Handle a hex number like 0x1234.
Jordan Rosea7d03842013-02-08 22:30:41 +0000684 if ((*s == 'x' || *s == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
Chris Lattner6016a512008-06-30 06:39:54 +0000685 s++;
686 radix = 16;
687 DigitsBegin = s;
688 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000689 bool noSignificand = (s == DigitsBegin);
Chris Lattner6016a512008-06-30 06:39:54 +0000690 if (s == ThisTokEnd) {
691 // Done.
692 } else if (*s == '.') {
693 s++;
694 saw_period = true;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000695 const char *floatDigitsBegin = s;
Chris Lattner6016a512008-06-30 06:39:54 +0000696 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000697 noSignificand &= (floatDigitsBegin == s);
Chris Lattner6016a512008-06-30 06:39:54 +0000698 }
Aaron Ballmane1224a52012-02-08 13:36:33 +0000699
700 if (noSignificand) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000701 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Aaron Ballmane1224a52012-02-08 13:36:33 +0000702 diag::err_hexconstant_requires_digits);
703 hadError = true;
704 return;
705 }
706
Chris Lattner6016a512008-06-30 06:39:54 +0000707 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump11289f42009-09-09 15:08:12 +0000708 // binary exponent is required.
Douglas Gregor86325ad2011-08-30 22:40:35 +0000709 if (*s == 'p' || *s == 'P') {
Chris Lattner6016a512008-06-30 06:39:54 +0000710 const char *Exponent = s;
711 s++;
712 saw_exponent = true;
713 if (*s == '+' || *s == '-') s++; // sign
714 const char *first_non_digit = SkipDigits(s);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000715 if (first_non_digit == s) {
Chris Lattner59acca52008-11-22 07:23:31 +0000716 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
717 diag::err_exponent_has_no_digits);
718 hadError = true;
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000719 return;
Chris Lattner6016a512008-06-30 06:39:54 +0000720 }
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000721 s = first_non_digit;
Mike Stump11289f42009-09-09 15:08:12 +0000722
David Blaikiebbafb8a2012-03-11 07:00:24 +0000723 if (!PP.getLangOpts().HexFloats)
Chris Lattner59acca52008-11-22 07:23:31 +0000724 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner6016a512008-06-30 06:39:54 +0000725 } else if (saw_period) {
Chris Lattner59acca52008-11-22 07:23:31 +0000726 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
727 diag::err_hexconstant_requires_exponent);
728 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000729 }
730 return;
731 }
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner6016a512008-06-30 06:39:54 +0000733 // Handle simple binary numbers 0b01010
734 if (*s == 'b' || *s == 'B') {
Richard Smithc5c27f22013-04-19 20:47:20 +0000735 // 0b101010 is a C++1y / GCC extension.
736 PP.Diag(TokLoc,
737 PP.getLangOpts().CPlusPlus1y
738 ? diag::warn_cxx11_compat_binary_literal
739 : PP.getLangOpts().CPlusPlus
740 ? diag::ext_binary_literal_cxx1y
741 : diag::ext_binary_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000742 ++s;
743 radix = 2;
744 DigitsBegin = s;
745 s = SkipBinaryDigits(s);
746 if (s == ThisTokEnd) {
747 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000748 } else if (isHexDigit(*s)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000749 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000750 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000751 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000752 }
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000753 // Other suffixes will be diagnosed by the caller.
Chris Lattner6016a512008-06-30 06:39:54 +0000754 return;
755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Chris Lattner6016a512008-06-30 06:39:54 +0000757 // For now, the radix is set to 8. If we discover that we have a
758 // floating point constant, the radix will change to 10. Octal floating
Mike Stump11289f42009-09-09 15:08:12 +0000759 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner6016a512008-06-30 06:39:54 +0000760 radix = 8;
761 DigitsBegin = s;
762 s = SkipOctalDigits(s);
763 if (s == ThisTokEnd)
764 return; // Done, simple octal number like 01234
Mike Stump11289f42009-09-09 15:08:12 +0000765
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000766 // If we have some other non-octal digit that *is* a decimal digit, see if
767 // this is part of a floating point number like 094.123 or 09e1.
Jordan Rosea7d03842013-02-08 22:30:41 +0000768 if (isDigit(*s)) {
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000769 const char *EndDecimal = SkipDigits(s);
770 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
771 s = EndDecimal;
772 radix = 10;
773 }
774 }
Mike Stump11289f42009-09-09 15:08:12 +0000775
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000776 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
777 // the code is using an incorrect base.
Jordan Rosea7d03842013-02-08 22:30:41 +0000778 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattner59acca52008-11-22 07:23:31 +0000779 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000780 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000781 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000782 return;
783 }
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattner6016a512008-06-30 06:39:54 +0000785 if (*s == '.') {
786 s++;
787 radix = 10;
788 saw_period = true;
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000789 s = SkipDigits(s); // Skip suffix.
Chris Lattner6016a512008-06-30 06:39:54 +0000790 }
791 if (*s == 'e' || *s == 'E') { // exponent
792 const char *Exponent = s;
793 s++;
794 radix = 10;
795 saw_exponent = true;
796 if (*s == '+' || *s == '-') s++; // sign
797 const char *first_non_digit = SkipDigits(s);
798 if (first_non_digit != s) {
799 s = first_non_digit;
800 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000801 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000802 diag::err_exponent_has_no_digits);
803 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000804 return;
805 }
806 }
807}
808
Jordan Rosede584de2012-09-25 22:32:51 +0000809static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000810 switch (Radix) {
811 case 2:
812 return NumDigits <= 64;
813 case 8:
814 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
815 case 10:
816 return NumDigits <= 19; // floor(log10(2^64))
817 case 16:
818 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
819 default:
820 llvm_unreachable("impossible Radix");
821 }
822}
Chris Lattner6016a512008-06-30 06:39:54 +0000823
Chris Lattner5b743d32007-04-04 05:52:58 +0000824/// GetIntegerValue - Convert this numeric literal value to an APInt that
Chris Lattner871b4e12007-04-04 06:36:34 +0000825/// matches Val's input width. If there is an overflow, set Val to the low bits
826/// of the result and return true. Otherwise, return false.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000827bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000828 // Fast path: Compute a conservative bound on the maximum number of
829 // bits per digit in this radix. If we can't possibly overflow a
830 // uint64 based on that bound then do the simple conversion to
831 // integer. This avoids the expensive overflow checking below, and
832 // handles the common cases that matter (small decimal integers and
833 // hex/octal values which don't overflow).
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000834 const unsigned NumDigits = SuffixBegin - DigitsBegin;
Jordan Rosede584de2012-09-25 22:32:51 +0000835 if (alwaysFitsInto64Bits(radix, NumDigits)) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000836 uint64_t N = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000837 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
Jordan Rose78ed86a2013-01-18 22:33:58 +0000838 N = N * radix + llvm::hexDigitValue(*Ptr);
Daniel Dunbarbe947082008-10-16 07:32:01 +0000839
840 // This will truncate the value to Val's input width. Simply check
841 // for overflow by comparing.
842 Val = N;
843 return Val.getZExtValue() != N;
844 }
845
Chris Lattner5b743d32007-04-04 05:52:58 +0000846 Val = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000847 const char *Ptr = DigitsBegin;
Chris Lattner5b743d32007-04-04 05:52:58 +0000848
Chris Lattner23b7eb62007-06-15 23:05:46 +0000849 llvm::APInt RadixVal(Val.getBitWidth(), radix);
850 llvm::APInt CharVal(Val.getBitWidth(), 0);
851 llvm::APInt OldVal = Val;
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chris Lattner871b4e12007-04-04 06:36:34 +0000853 bool OverflowOccurred = false;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000854 while (Ptr < SuffixBegin) {
Jordan Rose78ed86a2013-01-18 22:33:58 +0000855 unsigned C = llvm::hexDigitValue(*Ptr++);
Mike Stump11289f42009-09-09 15:08:12 +0000856
Chris Lattner5b743d32007-04-04 05:52:58 +0000857 // If this letter is out of bound for this radix, reject it.
Chris Lattner531efa42007-04-04 06:49:26 +0000858 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump11289f42009-09-09 15:08:12 +0000859
Chris Lattner5b743d32007-04-04 05:52:58 +0000860 CharVal = C;
Mike Stump11289f42009-09-09 15:08:12 +0000861
Chris Lattner871b4e12007-04-04 06:36:34 +0000862 // Add the digit to the value in the appropriate radix. If adding in digits
863 // made the value smaller, then this overflowed.
Chris Lattner5b743d32007-04-04 05:52:58 +0000864 OldVal = Val;
Chris Lattner871b4e12007-04-04 06:36:34 +0000865
866 // Multiply by radix, did overflow occur on the multiply?
Chris Lattner5b743d32007-04-04 05:52:58 +0000867 Val *= RadixVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000868 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
869
Chris Lattner871b4e12007-04-04 06:36:34 +0000870 // Add value, did overflow occur on the value?
Daniel Dunbarb1f64422008-10-16 06:39:30 +0000871 // (a + b) ult b <=> overflow
Chris Lattner5b743d32007-04-04 05:52:58 +0000872 Val += CharVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000873 OverflowOccurred |= Val.ult(CharVal);
Chris Lattner5b743d32007-04-04 05:52:58 +0000874 }
Chris Lattner871b4e12007-04-04 06:36:34 +0000875 return OverflowOccurred;
Chris Lattner5b743d32007-04-04 05:52:58 +0000876}
877
John McCall53b93a02009-12-24 09:08:04 +0000878llvm::APFloat::opStatus
879NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenekfbb08bc2007-11-26 23:12:30 +0000880 using llvm::APFloat;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Erick Tryzelaarb9073112009-08-16 23:36:28 +0000882 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall53b93a02009-12-24 09:08:04 +0000883 return Result.convertFromString(StringRef(ThisTokBegin, n),
884 APFloat::rmNearestTiesToEven);
Steve Naroff97b9e912007-07-09 23:53:58 +0000885}
Chris Lattner5b743d32007-04-04 05:52:58 +0000886
Chris Lattner2f5add62007-04-05 06:57:15 +0000887
James Dennett1cc22032012-06-17 03:34:42 +0000888/// \verbatim
Richard Smithe18f0fa2012-03-05 04:02:15 +0000889/// user-defined-character-literal: [C++11 lex.ext]
890/// character-literal ud-suffix
891/// ud-suffix:
892/// identifier
893/// character-literal: [C++11 lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +0000894/// ' c-char-sequence '
895/// u' c-char-sequence '
896/// U' c-char-sequence '
897/// L' c-char-sequence '
898/// c-char-sequence:
899/// c-char
900/// c-char-sequence c-char
901/// c-char:
902/// any member of the source character set except the single-quote ',
903/// backslash \, or new-line character
904/// escape-sequence
905/// universal-character-name
Richard Smithe18f0fa2012-03-05 04:02:15 +0000906/// escape-sequence:
Craig Topper54edcca2011-08-11 04:06:15 +0000907/// simple-escape-sequence
908/// octal-escape-sequence
909/// hexadecimal-escape-sequence
910/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +0000911/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +0000912/// octal-escape-sequence:
913/// \ octal-digit
914/// \ octal-digit octal-digit
915/// \ octal-digit octal-digit octal-digit
916/// hexadecimal-escape-sequence:
917/// \x hexadecimal-digit
918/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smithe18f0fa2012-03-05 04:02:15 +0000919/// universal-character-name: [C++11 lex.charset]
Craig Topper54edcca2011-08-11 04:06:15 +0000920/// \u hex-quad
921/// \U hex-quad hex-quad
922/// hex-quad:
923/// hex-digit hex-digit hex-digit hex-digit
James Dennett1cc22032012-06-17 03:34:42 +0000924/// \endverbatim
Craig Topper54edcca2011-08-11 04:06:15 +0000925///
Chris Lattner2f5add62007-04-05 06:57:15 +0000926CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000927 SourceLocation Loc, Preprocessor &PP,
928 tok::TokenKind kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000929 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Chris Lattner2f5add62007-04-05 06:57:15 +0000930 HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregorfb65e592011-07-27 05:40:30 +0000932 Kind = kind;
933
Richard Smith2a70e652012-03-09 22:27:51 +0000934 const char *TokBegin = begin;
935
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000936 // Skip over wide character determinant.
937 if (Kind != tok::char_constant) {
Douglas Gregorfb65e592011-07-27 05:40:30 +0000938 ++begin;
939 }
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattner2f5add62007-04-05 06:57:15 +0000941 // Skip over the entry quote.
942 assert(begin[0] == '\'' && "Invalid token lexed");
943 ++begin;
944
Richard Smithe18f0fa2012-03-05 04:02:15 +0000945 // Remove an optional ud-suffix.
946 if (end[-1] != '\'') {
947 const char *UDSuffixEnd = end;
948 do {
949 --end;
950 } while (end[-1] != '\'');
951 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith2a70e652012-03-09 22:27:51 +0000952 UDSuffixOffset = end - TokBegin;
Richard Smithe18f0fa2012-03-05 04:02:15 +0000953 }
954
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000955 // Trim the ending quote.
Richard Smithe18f0fa2012-03-05 04:02:15 +0000956 assert(end != begin && "Invalid token lexed");
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000957 --end;
958
Mike Stump11289f42009-09-09 15:08:12 +0000959 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattner57540c52011-04-15 05:22:18 +0000960 // up to 64-bits.
Chris Lattner2f5add62007-04-05 06:57:15 +0000961 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner37e05872008-03-05 18:54:05 +0000962 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner2f5add62007-04-05 06:57:15 +0000963 "Assumes char is 8 bits");
Chris Lattner8577f622009-04-28 21:51:46 +0000964 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
965 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
966 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
967 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
968 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Guptaf09cb952009-04-21 02:21:29 +0000969
Nick Lewycky63cc55b2013-08-21 02:40:19 +0000970 SmallVector<uint32_t, 4> codepoint_buffer;
971 codepoint_buffer.resize(end - begin);
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000972 uint32_t *buffer_begin = &codepoint_buffer.front();
973 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump11289f42009-09-09 15:08:12 +0000974
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000975 // Unicode escapes representing characters that cannot be correctly
976 // represented in a single code unit are disallowed in character literals
977 // by this implementation.
978 uint32_t largest_character_for_kind;
979 if (tok::wide_char_constant == Kind) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +0000980 largest_character_for_kind =
Nick Lewycky8054f1d2013-08-21 18:57:51 +0000981 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000982 } else if (tok::utf16_char_constant == Kind) {
983 largest_character_for_kind = 0xFFFF;
984 } else if (tok::utf32_char_constant == Kind) {
985 largest_character_for_kind = 0x10FFFF;
986 } else {
987 largest_character_for_kind = 0x7Fu;
Chris Lattner8577f622009-04-28 21:51:46 +0000988 }
989
Nick Lewycky63cc55b2013-08-21 02:40:19 +0000990 while (begin != end) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000991 // Is this a span of non-escape characters?
992 if (begin[0] != '\\') {
993 char const *start = begin;
994 do {
995 ++begin;
996 } while (begin != end && *begin != '\\');
997
Eli Friedman94363522012-02-11 05:08:10 +0000998 char const *tmp_in_start = start;
999 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001000 ConversionResult res =
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001001 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1002 reinterpret_cast<UTF8 const *>(begin),
1003 &buffer_begin, buffer_end, strictConversion);
1004 if (res != conversionOK) {
1005 // If we see bad encoding for unprefixed character literals, warn and
1006 // simply copy the byte values, for compatibility with gcc and
Eli Friedman94363522012-02-11 05:08:10 +00001007 // older versions of clang.
1008 bool NoErrorOnBadEncoding = isAscii();
1009 unsigned Msg = diag::err_bad_character_encoding;
1010 if (NoErrorOnBadEncoding)
1011 Msg = diag::warn_bad_character_encoding;
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001012 PP.Diag(Loc, Msg);
Eli Friedman94363522012-02-11 05:08:10 +00001013 if (NoErrorOnBadEncoding) {
1014 start = tmp_in_start;
1015 buffer_begin = tmp_out_start;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001016 for (; start != begin; ++start, ++buffer_begin)
Eli Friedman94363522012-02-11 05:08:10 +00001017 *buffer_begin = static_cast<uint8_t>(*start);
1018 } else {
1019 HadError = true;
1020 }
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001021 } else {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001022 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
Eli Friedman94363522012-02-11 05:08:10 +00001023 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001024 HadError = true;
1025 PP.Diag(Loc, diag::err_character_too_large);
1026 }
1027 }
1028 }
1029
1030 continue;
1031 }
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001032 // Is this a Universal Character Name escape?
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001033 if (begin[1] == 'u' || begin[1] == 'U') {
1034 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +00001035 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001036 FullSourceLoc(Loc, PP.getSourceManager()),
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001037 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001038 HadError = true;
1039 } else if (*buffer_begin > largest_character_for_kind) {
1040 HadError = true;
Richard Smith639b8d02012-09-08 07:16:20 +00001041 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001042 }
1043
1044 ++buffer_begin;
1045 continue;
1046 }
1047 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1048 uint64_t result =
Richard Smith639b8d02012-09-08 07:16:20 +00001049 ProcessCharEscape(TokBegin, begin, end, HadError,
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001050 FullSourceLoc(Loc,PP.getSourceManager()),
Richard Smith639b8d02012-09-08 07:16:20 +00001051 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001052 *buffer_begin++ = result;
1053 }
1054
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001055 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001056
Chris Lattner8577f622009-04-28 21:51:46 +00001057 if (NumCharsSoFar > 1) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001058 if (isWide())
Douglas Gregorfb65e592011-07-27 05:40:30 +00001059 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001060 else if (isAscii() && NumCharsSoFar == 4)
1061 PP.Diag(Loc, diag::ext_four_char_character_literal);
1062 else if (isAscii())
Chris Lattner8577f622009-04-28 21:51:46 +00001063 PP.Diag(Loc, diag::ext_multichar_character_literal);
1064 else
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001065 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedmand8cec572009-06-01 05:25:02 +00001066 IsMultiChar = true;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001067 } else {
Daniel Dunbara444cc22009-07-29 01:46:05 +00001068 IsMultiChar = false;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001069 }
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001070
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001071 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1072
1073 // Narrow character literals act as though their value is concatenated
1074 // in this implementation, but warn on overflow.
1075 bool multi_char_too_long = false;
1076 if (isAscii() && isMultiChar()) {
1077 LitVal = 0;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001078 for (size_t i = 0; i < NumCharsSoFar; ++i) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001079 // check for enough leading zeros to shift into
1080 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1081 LitVal <<= 8;
1082 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1083 }
1084 } else if (NumCharsSoFar > 0) {
1085 // otherwise just take the last character
1086 LitVal = buffer_begin[-1];
1087 }
1088
1089 if (!HadError && multi_char_too_long) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001090 PP.Diag(Loc, diag::warn_char_constant_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001091 }
1092
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001093 // Transfer the value from APInt to uint64_t
1094 Value = LitVal.getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001095
Chris Lattner2f5add62007-04-05 06:57:15 +00001096 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1097 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1098 // character constants are not sign extended in the this implementation:
1099 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001100 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001101 PP.getLangOpts().CharIsSigned)
Chris Lattner2f5add62007-04-05 06:57:15 +00001102 Value = (signed char)Value;
1103}
1104
James Dennett99c193b2012-06-19 21:04:25 +00001105/// \verbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001106/// string-literal: [C++0x lex.string]
1107/// encoding-prefix " [s-char-sequence] "
1108/// encoding-prefix R raw-string
1109/// encoding-prefix:
1110/// u8
1111/// u
1112/// U
1113/// L
Steve Naroff4f88b312007-03-13 22:37:02 +00001114/// s-char-sequence:
1115/// s-char
1116/// s-char-sequence s-char
1117/// s-char:
Craig Topper54edcca2011-08-11 04:06:15 +00001118/// any member of the source character set except the double-quote ",
1119/// backslash \, or new-line character
1120/// escape-sequence
Steve Naroff4f88b312007-03-13 22:37:02 +00001121/// universal-character-name
Craig Topper54edcca2011-08-11 04:06:15 +00001122/// raw-string:
1123/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1124/// r-char-sequence:
1125/// r-char
1126/// r-char-sequence r-char
1127/// r-char:
1128/// any member of the source character set, except a right parenthesis )
1129/// followed by the initial d-char-sequence (which may be empty)
1130/// followed by a double quote ".
1131/// d-char-sequence:
1132/// d-char
1133/// d-char-sequence d-char
1134/// d-char:
1135/// any member of the basic source character set except:
1136/// space, the left parenthesis (, the right parenthesis ),
1137/// the backslash \, and the control characters representing horizontal
1138/// tab, vertical tab, form feed, and newline.
1139/// escape-sequence: [C++0x lex.ccon]
1140/// simple-escape-sequence
1141/// octal-escape-sequence
1142/// hexadecimal-escape-sequence
1143/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001144/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001145/// octal-escape-sequence:
1146/// \ octal-digit
1147/// \ octal-digit octal-digit
1148/// \ octal-digit octal-digit octal-digit
1149/// hexadecimal-escape-sequence:
1150/// \x hexadecimal-digit
1151/// hexadecimal-escape-sequence hexadecimal-digit
Steve Naroff4f88b312007-03-13 22:37:02 +00001152/// universal-character-name:
1153/// \u hex-quad
1154/// \U hex-quad hex-quad
1155/// hex-quad:
1156/// hex-digit hex-digit hex-digit hex-digit
James Dennett99c193b2012-06-19 21:04:25 +00001157/// \endverbatim
Chris Lattner2f5add62007-04-05 06:57:15 +00001158///
Steve Naroff4f88b312007-03-13 22:37:02 +00001159StringLiteralParser::
Chris Lattner146762e2007-07-20 16:59:19 +00001160StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner6bab4352010-11-17 07:21:13 +00001161 Preprocessor &PP, bool Complain)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001162 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001163 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001164 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1165 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner6bab4352010-11-17 07:21:13 +00001166 init(StringToks, NumStringToks);
1167}
1168
1169void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001170 // The literal token may have come from an invalid source location (e.g. due
1171 // to a PCH error), in which case the token length will be 0.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001172 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1173 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001174
Steve Naroff4f88b312007-03-13 22:37:02 +00001175 // Scan all of the string portions, remember the max individual token length,
1176 // computing a bound on the concatenated string length, and see whether any
1177 // piece is a wide-string. If any of the string portions is a wide-string
1178 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001179 assert(NumStringToks && "expected at least one token");
Alexis Hunt3b791862010-08-30 17:47:05 +00001180 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001181 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001182 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001183 Kind = StringToks[0].getKind();
Alexis Hunt3b791862010-08-30 17:47:05 +00001184
1185 hadError = false;
Chris Lattner2f5add62007-04-05 06:57:15 +00001186
1187 // Implement Translation Phase #6: concatenation of string literals
1188 /// (C99 5.1.1.2p1). The common case is only one string fragment.
Steve Naroff4f88b312007-03-13 22:37:02 +00001189 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001190 if (StringToks[i].getLength() < 2)
1191 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001192
Steve Naroff4f88b312007-03-13 22:37:02 +00001193 // The string could be shorter than this if it needs cleaning, but this is a
1194 // reasonable bound, which is all we need.
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001195 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001196 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump11289f42009-09-09 15:08:12 +00001197
Steve Naroff4f88b312007-03-13 22:37:02 +00001198 // Remember maximum string piece length.
Alexis Hunt3b791862010-08-30 17:47:05 +00001199 if (StringToks[i].getLength() > MaxTokenLength)
1200 MaxTokenLength = StringToks[i].getLength();
Mike Stump11289f42009-09-09 15:08:12 +00001201
Douglas Gregorfb65e592011-07-27 05:40:30 +00001202 // Remember if we see any wide or utf-8/16/32 strings.
1203 // Also check for illegal concatenations.
1204 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1205 if (isAscii()) {
1206 Kind = StringToks[i].getKind();
1207 } else {
1208 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +00001209 Diags->Report(StringToks[i].getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001210 diag::err_unsupported_string_concat);
1211 hadError = true;
1212 }
1213 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001214 }
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001215
Steve Naroff4f88b312007-03-13 22:37:02 +00001216 // Include space for the null terminator.
1217 ++SizeBound;
Mike Stump11289f42009-09-09 15:08:12 +00001218
Steve Naroff4f88b312007-03-13 22:37:02 +00001219 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump11289f42009-09-09 15:08:12 +00001220
Douglas Gregorfb65e592011-07-27 05:40:30 +00001221 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1222 CharByteWidth = getCharWidth(Kind, Target);
1223 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1224 CharByteWidth /= 8;
Mike Stump11289f42009-09-09 15:08:12 +00001225
Steve Naroff4f88b312007-03-13 22:37:02 +00001226 // The output buffer size needs to be large enough to hold wide characters.
1227 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001228 SizeBound *= CharByteWidth;
Mike Stump11289f42009-09-09 15:08:12 +00001229
Steve Naroff4f88b312007-03-13 22:37:02 +00001230 // Size the temporary buffer to hold the result string data.
1231 ResultBuf.resize(SizeBound);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Steve Naroff4f88b312007-03-13 22:37:02 +00001233 // Likewise, but for each string piece.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001234 SmallString<512> TokenBuf;
Steve Naroff4f88b312007-03-13 22:37:02 +00001235 TokenBuf.resize(MaxTokenLength);
Mike Stump11289f42009-09-09 15:08:12 +00001236
Steve Naroff4f88b312007-03-13 22:37:02 +00001237 // Loop over all the strings, getting their spelling, and expanding them to
1238 // wide strings as appropriate.
1239 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump11289f42009-09-09 15:08:12 +00001240
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001241 Pascal = false;
Mike Stump11289f42009-09-09 15:08:12 +00001242
Richard Smithe18f0fa2012-03-05 04:02:15 +00001243 SourceLocation UDSuffixTokLoc;
1244
Steve Naroff4f88b312007-03-13 22:37:02 +00001245 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1246 const char *ThisTokBuf = &TokenBuf[0];
1247 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1248 // that ThisTokBuf points to a buffer that is big enough for the whole token
1249 // and 'spelled' tokens can only shrink.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001250 bool StringInvalid = false;
Chris Lattner6bab4352010-11-17 07:21:13 +00001251 unsigned ThisTokLen =
Chris Lattner39720112010-11-17 07:26:20 +00001252 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1253 &StringInvalid);
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001254 if (StringInvalid)
1255 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001256
Richard Smith2a70e652012-03-09 22:27:51 +00001257 const char *ThisTokBegin = ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001258 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1259
1260 // Remove an optional ud-suffix.
1261 if (ThisTokEnd[-1] != '"') {
1262 const char *UDSuffixEnd = ThisTokEnd;
1263 do {
1264 --ThisTokEnd;
1265 } while (ThisTokEnd[-1] != '"');
1266
1267 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1268
1269 if (UDSuffixBuf.empty()) {
1270 UDSuffixBuf.assign(UDSuffix);
Richard Smith75b67d62012-03-08 01:34:56 +00001271 UDSuffixToken = i;
1272 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001273 UDSuffixTokLoc = StringToks[i].getLocation();
1274 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1275 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1276 // result of a concatenation involving at least one user-defined-string-
1277 // literal, all the participating user-defined-string-literals shall
1278 // have the same ud-suffix.
1279 if (Diags) {
1280 SourceLocation TokLoc = StringToks[i].getLocation();
1281 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1282 << UDSuffixBuf << UDSuffix
1283 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1284 << SourceRange(TokLoc, TokLoc);
1285 }
1286 hadError = true;
1287 }
1288 }
1289
1290 // Strip the end quote.
1291 --ThisTokEnd;
1292
Steve Naroff4f88b312007-03-13 22:37:02 +00001293 // TODO: Input character set mapping support.
Mike Stump11289f42009-09-09 15:08:12 +00001294
Craig Topper61147ed2011-08-08 06:10:39 +00001295 // Skip marker for wide or unicode strings.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001296 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Chris Lattnerc10adde2007-05-20 05:00:58 +00001297 ++ThisTokBuf;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001298 // Skip 8 of u8 marker for utf8 strings.
1299 if (ThisTokBuf[0] == '8')
1300 ++ThisTokBuf;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +00001301 }
Mike Stump11289f42009-09-09 15:08:12 +00001302
Craig Topper54edcca2011-08-11 04:06:15 +00001303 // Check for raw string
1304 if (ThisTokBuf[0] == 'R') {
1305 ThisTokBuf += 2; // skip R"
Mike Stump11289f42009-09-09 15:08:12 +00001306
Craig Topper54edcca2011-08-11 04:06:15 +00001307 const char *Prefix = ThisTokBuf;
1308 while (ThisTokBuf[0] != '(')
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001309 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001310 ++ThisTokBuf; // skip '('
Mike Stump11289f42009-09-09 15:08:12 +00001311
Richard Smith81292452012-03-08 21:59:28 +00001312 // Remove same number of characters from the end
1313 ThisTokEnd -= ThisTokBuf - Prefix;
1314 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper54edcca2011-08-11 04:06:15 +00001315
1316 // Copy the string over
Richard Smith639b8d02012-09-08 07:16:20 +00001317 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1318 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1319 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001320 } else {
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001321 if (ThisTokBuf[0] != '"') {
1322 // The file may have come from PCH and then changed after loading the
1323 // PCH; Fail gracefully.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001324 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001325 }
Craig Topper54edcca2011-08-11 04:06:15 +00001326 ++ThisTokBuf; // skip "
1327
1328 // Check if this is a pascal string
1329 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1330 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1331
1332 // If the \p sequence is found in the first token, we have a pascal string
1333 // Otherwise, if we already have a pascal string, ignore the first \p
1334 if (i == 0) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001335 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001336 Pascal = true;
1337 } else if (Pascal)
1338 ThisTokBuf += 2;
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Craig Topper54edcca2011-08-11 04:06:15 +00001341 while (ThisTokBuf != ThisTokEnd) {
1342 // Is this a span of non-escape characters?
1343 if (ThisTokBuf[0] != '\\') {
1344 const char *InStart = ThisTokBuf;
1345 do {
1346 ++ThisTokBuf;
1347 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1348
1349 // Copy the character span over.
Richard Smith639b8d02012-09-08 07:16:20 +00001350 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1351 StringRef(InStart, ThisTokBuf - InStart)))
1352 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001353 continue;
Steve Naroff4f88b312007-03-13 22:37:02 +00001354 }
Craig Topper54edcca2011-08-11 04:06:15 +00001355 // Is this a Universal Character Name escape?
1356 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith2a70e652012-03-09 22:27:51 +00001357 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1358 ResultPtr, hadError,
1359 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper54edcca2011-08-11 04:06:15 +00001360 CharByteWidth, Diags, Features);
1361 continue;
1362 }
1363 // Otherwise, this is a non-UCN escape character. Process it.
1364 unsigned ResultChar =
Richard Smith639b8d02012-09-08 07:16:20 +00001365 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper54edcca2011-08-11 04:06:15 +00001366 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001367 CharByteWidth*8, Diags, Features);
Mike Stump11289f42009-09-09 15:08:12 +00001368
Eli Friedmand1370792011-11-02 23:06:23 +00001369 if (CharByteWidth == 4) {
1370 // FIXME: Make the type of the result buffer correct instead of
1371 // using reinterpret_cast.
1372 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001373 *ResultWidePtr = ResultChar;
Eli Friedmand1370792011-11-02 23:06:23 +00001374 ResultPtr += 4;
1375 } else if (CharByteWidth == 2) {
1376 // FIXME: Make the type of the result buffer correct instead of
1377 // using reinterpret_cast.
1378 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001379 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmand1370792011-11-02 23:06:23 +00001380 ResultPtr += 2;
1381 } else {
1382 assert(CharByteWidth == 1 && "Unexpected char width");
1383 *ResultPtr++ = ResultChar & 0xFF;
1384 }
Craig Topper54edcca2011-08-11 04:06:15 +00001385 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001386 }
1387 }
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner8a24e582009-01-16 18:51:42 +00001389 if (Pascal) {
Eli Friedman20554702011-11-05 00:41:04 +00001390 if (CharByteWidth == 4) {
1391 // FIXME: Make the type of the result buffer correct instead of
1392 // using reinterpret_cast.
1393 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1394 ResultWidePtr[0] = GetNumStringChars() - 1;
1395 } else if (CharByteWidth == 2) {
1396 // FIXME: Make the type of the result buffer correct instead of
1397 // using reinterpret_cast.
1398 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1399 ResultWidePtr[0] = GetNumStringChars() - 1;
1400 } else {
1401 assert(CharByteWidth == 1 && "Unexpected char width");
1402 ResultBuf[0] = GetNumStringChars() - 1;
1403 }
Chris Lattner8a24e582009-01-16 18:51:42 +00001404
1405 // Verify that pascal strings aren't too large.
Chris Lattner6bab4352010-11-17 07:21:13 +00001406 if (GetStringLength() > 256) {
Richard Smith639b8d02012-09-08 07:16:20 +00001407 if (Diags)
1408 Diags->Report(StringToks[0].getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001409 diag::err_pascal_string_too_long)
1410 << SourceRange(StringToks[0].getLocation(),
1411 StringToks[NumStringToks-1].getLocation());
Douglas Gregorfb65e592011-07-27 05:40:30 +00001412 hadError = true;
Eli Friedman1c3fb222009-04-01 03:17:08 +00001413 return;
1414 }
Chris Lattner6bab4352010-11-17 07:21:13 +00001415 } else if (Diags) {
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001416 // Complain if this string literal has too many characters.
Chris Lattner2be8aa92010-11-17 07:12:42 +00001417 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001418
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001419 if (GetNumStringChars() > MaxChars)
Richard Smith639b8d02012-09-08 07:16:20 +00001420 Diags->Report(StringToks[0].getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001421 diag::ext_string_too_long)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001422 << GetNumStringChars() << MaxChars
Chris Lattner2be8aa92010-11-17 07:12:42 +00001423 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001424 << SourceRange(StringToks[0].getLocation(),
1425 StringToks[NumStringToks-1].getLocation());
Chris Lattner8a24e582009-01-16 18:51:42 +00001426 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001427}
Chris Lattnerddb71912009-02-18 19:21:10 +00001428
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001429static const char *resyncUTF8(const char *Err, const char *End) {
1430 if (Err == End)
1431 return End;
1432 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1433 while (++Err != End && (*Err & 0xC0) == 0x80)
1434 ;
1435 return Err;
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001436}
1437
Richard Smith639b8d02012-09-08 07:16:20 +00001438/// \brief This function copies from Fragment, which is a sequence of bytes
1439/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper54edcca2011-08-11 04:06:15 +00001440/// Performs widening for multi-byte characters.
Richard Smith639b8d02012-09-08 07:16:20 +00001441bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1442 const char *TokBegin,
1443 StringRef Fragment) {
1444 const UTF8 *ErrorPtrTmp;
1445 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1446 return false;
Craig Topper54edcca2011-08-11 04:06:15 +00001447
Eli Friedman94363522012-02-11 05:08:10 +00001448 // If we see bad encoding for unprefixed string literals, warn and
1449 // simply copy the byte values, for compatibility with gcc and older
1450 // versions of clang.
1451 bool NoErrorOnBadEncoding = isAscii();
Richard Smith639b8d02012-09-08 07:16:20 +00001452 if (NoErrorOnBadEncoding) {
1453 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1454 ResultPtr += Fragment.size();
1455 }
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001456
Richard Smith639b8d02012-09-08 07:16:20 +00001457 if (Diags) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001458 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1459
1460 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1461 const DiagnosticBuilder &Builder =
1462 Diag(Diags, Features, SourceLoc, TokBegin,
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001463 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001464 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1465 : diag::err_bad_string_encoding);
1466
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001467 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001468 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1469
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001470 // Decode into a dummy buffer.
1471 SmallString<512> Dummy;
1472 Dummy.reserve(Fragment.size() * CharByteWidth);
1473 char *Ptr = Dummy.data();
1474
David Blaikiea0613172012-10-30 23:22:22 +00001475 while (!Builder.hasMaxRanges() &&
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001476 !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001477 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001478 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001479 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1480 ErrorPtr, NextStart);
1481 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1482 }
Richard Smith639b8d02012-09-08 07:16:20 +00001483 }
Eli Friedman94363522012-02-11 05:08:10 +00001484 return !NoErrorOnBadEncoding;
1485}
Craig Topper54edcca2011-08-11 04:06:15 +00001486
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001487void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1488 hadError = true;
1489 if (Diags)
1490 Diags->Report(Loc, diag::err_lexing_string);
1491}
1492
Chris Lattnerddb71912009-02-18 19:21:10 +00001493/// getOffsetOfStringByte - This function returns the offset of the
1494/// specified byte of the string data represented by Token. This handles
1495/// advancing over escape sequences in the string.
1496unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattnerbde1b812010-11-17 06:46:14 +00001497 unsigned ByteNo) const {
Chris Lattnerddb71912009-02-18 19:21:10 +00001498 // Get the spelling of the token.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001499 SmallString<32> SpellingBuffer;
Alexis Hunt3b791862010-08-30 17:47:05 +00001500 SpellingBuffer.resize(Tok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001502 bool StringInvalid = false;
Chris Lattnerddb71912009-02-18 19:21:10 +00001503 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattner39720112010-11-17 07:26:20 +00001504 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1505 &StringInvalid);
Chris Lattner7a02bfd2010-11-17 06:26:08 +00001506 if (StringInvalid)
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001507 return 0;
Chris Lattnerddb71912009-02-18 19:21:10 +00001508
Chris Lattnerddb71912009-02-18 19:21:10 +00001509 const char *SpellingStart = SpellingPtr;
1510 const char *SpellingEnd = SpellingPtr+TokLen;
1511
Richard Smith4060f772012-06-13 05:37:23 +00001512 // Handle UTF-8 strings just like narrow strings.
1513 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1514 SpellingPtr += 2;
1515
1516 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1517 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1518
1519 // For raw string literals, this is easy.
1520 if (SpellingPtr[0] == 'R') {
1521 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1522 // Skip 'R"'.
1523 SpellingPtr += 2;
1524 while (*SpellingPtr != '(') {
1525 ++SpellingPtr;
1526 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1527 }
1528 // Skip '('.
1529 ++SpellingPtr;
1530 return SpellingPtr - SpellingStart + ByteNo;
1531 }
1532
1533 // Skip over the leading quote
Chris Lattnerddb71912009-02-18 19:21:10 +00001534 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1535 ++SpellingPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001536
Chris Lattnerddb71912009-02-18 19:21:10 +00001537 // Skip over bytes until we find the offset we're looking for.
1538 while (ByteNo) {
1539 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerddb71912009-02-18 19:21:10 +00001541 // Step over non-escapes simply.
1542 if (*SpellingPtr != '\\') {
1543 ++SpellingPtr;
1544 --ByteNo;
1545 continue;
1546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Chris Lattnerddb71912009-02-18 19:21:10 +00001548 // Otherwise, this is an escape character. Advance over it.
1549 bool HadError = false;
Richard Smith4060f772012-06-13 05:37:23 +00001550 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1551 const char *EscapePtr = SpellingPtr;
1552 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1553 1, Features, HadError);
1554 if (Len > ByteNo) {
1555 // ByteNo is somewhere within the escape sequence.
1556 SpellingPtr = EscapePtr;
1557 break;
1558 }
1559 ByteNo -= Len;
1560 } else {
Richard Smith639b8d02012-09-08 07:16:20 +00001561 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smith4060f772012-06-13 05:37:23 +00001562 FullSourceLoc(Tok.getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001563 CharByteWidth*8, Diags, Features);
Richard Smith4060f772012-06-13 05:37:23 +00001564 --ByteNo;
1565 }
Chris Lattnerddb71912009-02-18 19:21:10 +00001566 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattnerddb71912009-02-18 19:21:10 +00001567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Chris Lattnerddb71912009-02-18 19:21:10 +00001569 return SpellingPtr-SpellingStart;
1570}