blob: 61f1d55a0edfb536e09933da435bf654c9d298d8 [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 == '.') {
Richard Smith1e130482013-09-26 04:19:11 +0000501 checkSeparator(TokLoc, s, CSK_AfterDigits);
Steve Naroff09ef4742007-03-09 23:16:33 +0000502 s++;
503 saw_period = true;
Richard Smith1e130482013-09-26 04:19:11 +0000504 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Steve Naroff09ef4742007-03-09 23:16:33 +0000505 s = SkipDigits(s);
Mike Stump11289f42009-09-09 15:08:12 +0000506 }
Chris Lattnerfb8b8f22008-09-29 23:12:31 +0000507 if ((*s == 'e' || *s == 'E')) { // exponent
Richard Smith1e130482013-09-26 04:19:11 +0000508 checkSeparator(TokLoc, s, CSK_AfterDigits);
Chris Lattner4885b972008-04-20 18:47:55 +0000509 const char *Exponent = s;
Steve Naroff09ef4742007-03-09 23:16:33 +0000510 s++;
511 saw_exponent = true;
512 if (*s == '+' || *s == '-') s++; // sign
Richard Smith1e130482013-09-26 04:19:11 +0000513 checkSeparator(TokLoc, s, CSK_BeforeDigits);
Steve Naroff09ef4742007-03-09 23:16:33 +0000514 const char *first_non_digit = SkipDigits(s);
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000515 if (first_non_digit != s) {
Steve Naroff09ef4742007-03-09 23:16:33 +0000516 s = first_non_digit;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000517 } else {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000518 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000519 diag::err_exponent_has_no_digits);
520 hadError = true;
Chris Lattner48a9b9b2008-04-20 18:41:46 +0000521 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000522 }
523 }
524 }
525
526 SuffixBegin = s;
Richard Smith1e130482013-09-26 04:19:11 +0000527 checkSeparator(TokLoc, s, CSK_AfterDigits);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattnerf55ab182007-08-26 01:58:14 +0000529 // Parse the suffix. At this point we can classify whether we have an FP or
530 // integer constant.
531 bool isFPConstant = isFloatingLiteral();
Richard Smithf4198b72013-07-23 08:14:48 +0000532 const char *ImaginarySuffixLoc = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000533
Chris Lattnerf55ab182007-08-26 01:58:14 +0000534 // Loop over all of the characters of the suffix. If we see something bad,
535 // we break out of the loop.
536 for (; s != ThisTokEnd; ++s) {
537 switch (*s) {
538 case 'f': // FP Suffix for "float"
539 case 'F':
540 if (!isFPConstant) break; // Error for integer constant.
Chris Lattnered045422007-08-26 03:29:23 +0000541 if (isFloat || isLong) break; // FF, LF invalid.
542 isFloat = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000543 continue; // Success.
544 case 'u':
545 case 'U':
546 if (isFPConstant) break; // Error for floating constant.
547 if (isUnsigned) break; // Cannot be repeated.
548 isUnsigned = true;
549 continue; // Success.
550 case 'l':
551 case 'L':
552 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattnered045422007-08-26 03:29:23 +0000553 if (isFloat) break; // LF invalid.
Mike Stump11289f42009-09-09 15:08:12 +0000554
Chris Lattnerf55ab182007-08-26 01:58:14 +0000555 // Check for long long. The L's need to be adjacent and the same case.
556 if (s+1 != ThisTokEnd && s[1] == s[0]) {
557 if (isFPConstant) break; // long long invalid for floats.
558 isLongLong = true;
559 ++s; // Eat both of them.
560 } else {
Steve Naroff09ef4742007-03-09 23:16:33 +0000561 isLong = true;
Steve Naroff09ef4742007-03-09 23:16:33 +0000562 }
Chris Lattnerf55ab182007-08-26 01:58:14 +0000563 continue; // Success.
564 case 'i':
Chris Lattner26f6c222010-10-14 00:24:10 +0000565 case 'I':
David Blaikiebbafb8a2012-03-11 07:00:24 +0000566 if (PP.getLangOpts().MicrosoftExt) {
Fariborz Jahanian8c6c0b62010-01-22 21:36:53 +0000567 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000568
Steve Naroffa1f41452008-04-04 21:02:54 +0000569 // Allow i8, i16, i32, i64, and i128.
Mike Stumpc99c0222009-10-08 22:55:36 +0000570 if (s + 1 != ThisTokEnd) {
571 switch (s[1]) {
572 case '8':
573 s += 2; // i8 suffix
574 isMicrosoftInteger = true;
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000575 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000576 case '1':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000577 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000578 if (s[2] == '6') {
579 s += 3; // i16 suffix
580 isMicrosoftInteger = true;
581 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000582 else if (s[2] == '2') {
583 if (s + 3 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000584 if (s[3] == '8') {
585 s += 4; // i128 suffix
586 isMicrosoftInteger = true;
587 }
Mike Stumpc99c0222009-10-08 22:55:36 +0000588 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000589 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000590 case '3':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000591 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000592 if (s[2] == '2') {
593 s += 3; // i32 suffix
594 isLong = true;
595 isMicrosoftInteger = true;
596 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000597 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000598 case '6':
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000599 if (s + 2 == ThisTokEnd) break;
Francois Pichet12df1dc2011-01-11 11:57:53 +0000600 if (s[2] == '4') {
601 s += 3; // i64 suffix
602 isLongLong = true;
603 isMicrosoftInteger = true;
604 }
Nuno Lopesbaa1bc42009-11-28 13:37:52 +0000605 break;
Mike Stumpc99c0222009-10-08 22:55:36 +0000606 default:
607 break;
608 }
609 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000610 }
Steve Naroffa1f41452008-04-04 21:02:54 +0000611 }
Richard Smith2a988622013-09-24 04:06:10 +0000612 // "i", "if", and "il" are user-defined suffixes in C++1y.
613 if (PP.getLangOpts().CPlusPlus1y && *s == 'i')
614 break;
Steve Naroffa1f41452008-04-04 21:02:54 +0000615 // fall through.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000616 case 'j':
617 case 'J':
618 if (isImaginary) break; // Cannot be repeated.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000619 isImaginary = true;
Richard Smithf4198b72013-07-23 08:14:48 +0000620 ImaginarySuffixLoc = s;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000621 continue; // Success.
Steve Naroff09ef4742007-03-09 23:16:33 +0000622 }
Richard Smith39570d002012-03-08 08:45:32 +0000623 // If we reached here, there was an error or a ud-suffix.
Chris Lattnerf55ab182007-08-26 01:58:14 +0000624 break;
625 }
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattnerf55ab182007-08-26 01:58:14 +0000627 if (s != ThisTokEnd) {
Richard Smithf4198b72013-07-23 08:14:48 +0000628 if (isValidUDSuffix(PP.getLangOpts(),
629 StringRef(SuffixBegin, ThisTokEnd - SuffixBegin))) {
630 // Any suffix pieces we might have parsed are actually part of the
631 // ud-suffix.
632 isLong = false;
633 isUnsigned = false;
634 isLongLong = false;
635 isFloat = false;
636 isImaginary = false;
637 isMicrosoftInteger = false;
638
Richard Smith39570d002012-03-08 08:45:32 +0000639 saw_ud_suffix = true;
640 return;
641 }
642
643 // Report an error if there are any.
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000644 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000645 isFPConstant ? diag::err_invalid_suffix_float_constant :
646 diag::err_invalid_suffix_integer_constant)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000647 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattner59acca52008-11-22 07:23:31 +0000648 hadError = true;
Chris Lattnerf55ab182007-08-26 01:58:14 +0000649 return;
Steve Naroff09ef4742007-03-09 23:16:33 +0000650 }
Richard Smithf4198b72013-07-23 08:14:48 +0000651
652 if (isImaginary) {
653 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc,
654 ImaginarySuffixLoc - ThisTokBegin),
655 diag::ext_imaginary_constant);
656 }
657}
658
659/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
660/// suffixes as ud-suffixes, because the diagnostic experience is better if we
661/// treat it as an invalid suffix.
662bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
663 StringRef Suffix) {
664 if (!LangOpts.CPlusPlus11 || Suffix.empty())
665 return false;
666
667 // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
668 if (Suffix[0] == '_')
669 return true;
670
671 // In C++11, there are no library suffixes.
672 if (!LangOpts.CPlusPlus1y)
673 return false;
674
675 // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library.
Richard Smith2a988622013-09-24 04:06:10 +0000676 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
Richard Smithf4198b72013-07-23 08:14:48 +0000677 return llvm::StringSwitch<bool>(Suffix)
678 .Cases("h", "min", "s", true)
679 .Cases("ms", "us", "ns", true)
Richard Smith2a988622013-09-24 04:06:10 +0000680 .Cases("il", "i", "if", true)
Richard Smithf4198b72013-07-23 08:14:48 +0000681 .Default(false);
Steve Naroff09ef4742007-03-09 23:16:33 +0000682}
683
Richard Smithfde94852013-09-26 03:33:06 +0000684void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
Richard Smith1e130482013-09-26 04:19:11 +0000685 const char *Pos,
686 CheckSeparatorKind IsAfterDigits) {
687 if (IsAfterDigits == CSK_AfterDigits) {
Richard Smith99dc0712013-09-26 05:57:03 +0000688 if (Pos == ThisTokBegin)
689 return;
Richard Smithfde94852013-09-26 03:33:06 +0000690 --Pos;
Richard Smith99dc0712013-09-26 05:57:03 +0000691 } else if (Pos == ThisTokEnd)
692 return;
Richard Smithfde94852013-09-26 03:33:06 +0000693
694 if (isDigitSeparator(*Pos))
695 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
696 diag::err_digit_separator_not_between_digits)
697 << IsAfterDigits;
698}
699
Chris Lattner6016a512008-06-30 06:39:54 +0000700/// ParseNumberStartingWithZero - This method is called when the first character
701/// of the number is found to be a zero. This means it is either an octal
702/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump11289f42009-09-09 15:08:12 +0000703/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner6016a512008-06-30 06:39:54 +0000704/// radix etc.
705void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
706 assert(s[0] == '0' && "Invalid method call");
707 s++;
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattner6016a512008-06-30 06:39:54 +0000709 // Handle a hex number like 0x1234.
Jordan Rosea7d03842013-02-08 22:30:41 +0000710 if ((*s == 'x' || *s == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
Chris Lattner6016a512008-06-30 06:39:54 +0000711 s++;
712 radix = 16;
713 DigitsBegin = s;
714 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000715 bool noSignificand = (s == DigitsBegin);
Chris Lattner6016a512008-06-30 06:39:54 +0000716 if (s == ThisTokEnd) {
717 // Done.
718 } else if (*s == '.') {
719 s++;
720 saw_period = true;
Aaron Ballmane1224a52012-02-08 13:36:33 +0000721 const char *floatDigitsBegin = s;
Chris Lattner6016a512008-06-30 06:39:54 +0000722 s = SkipHexDigits(s);
Aaron Ballmane1224a52012-02-08 13:36:33 +0000723 noSignificand &= (floatDigitsBegin == s);
Chris Lattner6016a512008-06-30 06:39:54 +0000724 }
Aaron Ballmane1224a52012-02-08 13:36:33 +0000725
726 if (noSignificand) {
Dmitri Gribenko7ba91722012-09-24 09:53:54 +0000727 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
Aaron Ballmane1224a52012-02-08 13:36:33 +0000728 diag::err_hexconstant_requires_digits);
729 hadError = true;
730 return;
731 }
732
Chris Lattner6016a512008-06-30 06:39:54 +0000733 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump11289f42009-09-09 15:08:12 +0000734 // binary exponent is required.
Douglas Gregor86325ad2011-08-30 22:40:35 +0000735 if (*s == 'p' || *s == 'P') {
Chris Lattner6016a512008-06-30 06:39:54 +0000736 const char *Exponent = s;
737 s++;
738 saw_exponent = true;
739 if (*s == '+' || *s == '-') s++; // sign
740 const char *first_non_digit = SkipDigits(s);
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000741 if (first_non_digit == s) {
Chris Lattner59acca52008-11-22 07:23:31 +0000742 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
743 diag::err_exponent_has_no_digits);
744 hadError = true;
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000745 return;
Chris Lattner6016a512008-06-30 06:39:54 +0000746 }
Chris Lattnerc94ad4a2008-07-25 18:18:34 +0000747 s = first_non_digit;
Mike Stump11289f42009-09-09 15:08:12 +0000748
David Blaikiebbafb8a2012-03-11 07:00:24 +0000749 if (!PP.getLangOpts().HexFloats)
Chris Lattner59acca52008-11-22 07:23:31 +0000750 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner6016a512008-06-30 06:39:54 +0000751 } else if (saw_period) {
Chris Lattner59acca52008-11-22 07:23:31 +0000752 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
753 diag::err_hexconstant_requires_exponent);
754 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000755 }
756 return;
757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Chris Lattner6016a512008-06-30 06:39:54 +0000759 // Handle simple binary numbers 0b01010
Richard Smithfde94852013-09-26 03:33:06 +0000760 if ((*s == 'b' || *s == 'B') && (s[1] == '0' || s[1] == '1')) {
Richard Smithc5c27f22013-04-19 20:47:20 +0000761 // 0b101010 is a C++1y / GCC extension.
762 PP.Diag(TokLoc,
763 PP.getLangOpts().CPlusPlus1y
764 ? diag::warn_cxx11_compat_binary_literal
765 : PP.getLangOpts().CPlusPlus
766 ? diag::ext_binary_literal_cxx1y
767 : diag::ext_binary_literal);
Chris Lattner6016a512008-06-30 06:39:54 +0000768 ++s;
769 radix = 2;
770 DigitsBegin = s;
771 s = SkipBinaryDigits(s);
772 if (s == ThisTokEnd) {
773 // Done.
Jordan Rosea7d03842013-02-08 22:30:41 +0000774 } else if (isHexDigit(*s)) {
Chris Lattner59acca52008-11-22 07:23:31 +0000775 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000776 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000777 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000778 }
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000779 // Other suffixes will be diagnosed by the caller.
Chris Lattner6016a512008-06-30 06:39:54 +0000780 return;
781 }
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattner6016a512008-06-30 06:39:54 +0000783 // For now, the radix is set to 8. If we discover that we have a
784 // floating point constant, the radix will change to 10. Octal floating
Mike Stump11289f42009-09-09 15:08:12 +0000785 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner6016a512008-06-30 06:39:54 +0000786 radix = 8;
787 DigitsBegin = s;
788 s = SkipOctalDigits(s);
789 if (s == ThisTokEnd)
790 return; // Done, simple octal number like 01234
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000792 // If we have some other non-octal digit that *is* a decimal digit, see if
793 // this is part of a floating point number like 094.123 or 09e1.
Jordan Rosea7d03842013-02-08 22:30:41 +0000794 if (isDigit(*s)) {
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000795 const char *EndDecimal = SkipDigits(s);
796 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
797 s = EndDecimal;
798 radix = 10;
799 }
800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000802 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
803 // the code is using an incorrect base.
Jordan Rosea7d03842013-02-08 22:30:41 +0000804 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattner59acca52008-11-22 07:23:31 +0000805 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000806 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattner59acca52008-11-22 07:23:31 +0000807 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000808 return;
809 }
Mike Stump11289f42009-09-09 15:08:12 +0000810
Chris Lattner6016a512008-06-30 06:39:54 +0000811 if (*s == '.') {
812 s++;
813 radix = 10;
814 saw_period = true;
Chris Lattnerd68c04f2008-06-30 06:44:49 +0000815 s = SkipDigits(s); // Skip suffix.
Chris Lattner6016a512008-06-30 06:39:54 +0000816 }
817 if (*s == 'e' || *s == 'E') { // exponent
818 const char *Exponent = s;
819 s++;
820 radix = 10;
821 saw_exponent = true;
822 if (*s == '+' || *s == '-') s++; // sign
823 const char *first_non_digit = SkipDigits(s);
824 if (first_non_digit != s) {
825 s = first_non_digit;
826 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000827 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattner59acca52008-11-22 07:23:31 +0000828 diag::err_exponent_has_no_digits);
829 hadError = true;
Chris Lattner6016a512008-06-30 06:39:54 +0000830 return;
831 }
832 }
833}
834
Jordan Rosede584de2012-09-25 22:32:51 +0000835static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000836 switch (Radix) {
837 case 2:
838 return NumDigits <= 64;
839 case 8:
840 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
841 case 10:
842 return NumDigits <= 19; // floor(log10(2^64))
843 case 16:
844 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
845 default:
846 llvm_unreachable("impossible Radix");
847 }
848}
Chris Lattner6016a512008-06-30 06:39:54 +0000849
Chris Lattner5b743d32007-04-04 05:52:58 +0000850/// GetIntegerValue - Convert this numeric literal value to an APInt that
Chris Lattner871b4e12007-04-04 06:36:34 +0000851/// matches Val's input width. If there is an overflow, set Val to the low bits
852/// of the result and return true. Otherwise, return false.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000853bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000854 // Fast path: Compute a conservative bound on the maximum number of
855 // bits per digit in this radix. If we can't possibly overflow a
856 // uint64 based on that bound then do the simple conversion to
857 // integer. This avoids the expensive overflow checking below, and
858 // handles the common cases that matter (small decimal integers and
859 // hex/octal values which don't overflow).
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000860 const unsigned NumDigits = SuffixBegin - DigitsBegin;
Jordan Rosede584de2012-09-25 22:32:51 +0000861 if (alwaysFitsInto64Bits(radix, NumDigits)) {
Daniel Dunbarbe947082008-10-16 07:32:01 +0000862 uint64_t N = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000863 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
Richard Smithfde94852013-09-26 03:33:06 +0000864 if (!isDigitSeparator(*Ptr))
865 N = N * radix + llvm::hexDigitValue(*Ptr);
Daniel Dunbarbe947082008-10-16 07:32:01 +0000866
867 // This will truncate the value to Val's input width. Simply check
868 // for overflow by comparing.
869 Val = N;
870 return Val.getZExtValue() != N;
871 }
872
Chris Lattner5b743d32007-04-04 05:52:58 +0000873 Val = 0;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000874 const char *Ptr = DigitsBegin;
Chris Lattner5b743d32007-04-04 05:52:58 +0000875
Chris Lattner23b7eb62007-06-15 23:05:46 +0000876 llvm::APInt RadixVal(Val.getBitWidth(), radix);
877 llvm::APInt CharVal(Val.getBitWidth(), 0);
878 llvm::APInt OldVal = Val;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner871b4e12007-04-04 06:36:34 +0000880 bool OverflowOccurred = false;
Dmitri Gribenko511288b2012-09-25 19:09:15 +0000881 while (Ptr < SuffixBegin) {
Richard Smithfde94852013-09-26 03:33:06 +0000882 if (isDigitSeparator(*Ptr)) {
883 ++Ptr;
884 continue;
885 }
886
Jordan Rose78ed86a2013-01-18 22:33:58 +0000887 unsigned C = llvm::hexDigitValue(*Ptr++);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattner5b743d32007-04-04 05:52:58 +0000889 // If this letter is out of bound for this radix, reject it.
Chris Lattner531efa42007-04-04 06:49:26 +0000890 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump11289f42009-09-09 15:08:12 +0000891
Chris Lattner5b743d32007-04-04 05:52:58 +0000892 CharVal = C;
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chris Lattner871b4e12007-04-04 06:36:34 +0000894 // Add the digit to the value in the appropriate radix. If adding in digits
895 // made the value smaller, then this overflowed.
Chris Lattner5b743d32007-04-04 05:52:58 +0000896 OldVal = Val;
Chris Lattner871b4e12007-04-04 06:36:34 +0000897
898 // Multiply by radix, did overflow occur on the multiply?
Chris Lattner5b743d32007-04-04 05:52:58 +0000899 Val *= RadixVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000900 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
901
Chris Lattner871b4e12007-04-04 06:36:34 +0000902 // Add value, did overflow occur on the value?
Daniel Dunbarb1f64422008-10-16 06:39:30 +0000903 // (a + b) ult b <=> overflow
Chris Lattner5b743d32007-04-04 05:52:58 +0000904 Val += CharVal;
Chris Lattner871b4e12007-04-04 06:36:34 +0000905 OverflowOccurred |= Val.ult(CharVal);
Chris Lattner5b743d32007-04-04 05:52:58 +0000906 }
Chris Lattner871b4e12007-04-04 06:36:34 +0000907 return OverflowOccurred;
Chris Lattner5b743d32007-04-04 05:52:58 +0000908}
909
John McCall53b93a02009-12-24 09:08:04 +0000910llvm::APFloat::opStatus
911NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenekfbb08bc2007-11-26 23:12:30 +0000912 using llvm::APFloat;
Mike Stump11289f42009-09-09 15:08:12 +0000913
Erick Tryzelaarb9073112009-08-16 23:36:28 +0000914 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
Richard Smithfde94852013-09-26 03:33:06 +0000915
916 llvm::SmallString<16> Buffer;
917 StringRef Str(ThisTokBegin, n);
918 if (Str.find('\'') != StringRef::npos) {
919 Buffer.reserve(n);
920 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
921 &isDigitSeparator);
922 Str = Buffer;
923 }
924
925 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
Steve Naroff97b9e912007-07-09 23:53:58 +0000926}
Chris Lattner5b743d32007-04-04 05:52:58 +0000927
Chris Lattner2f5add62007-04-05 06:57:15 +0000928
James Dennett1cc22032012-06-17 03:34:42 +0000929/// \verbatim
Richard Smithe18f0fa2012-03-05 04:02:15 +0000930/// user-defined-character-literal: [C++11 lex.ext]
931/// character-literal ud-suffix
932/// ud-suffix:
933/// identifier
934/// character-literal: [C++11 lex.ccon]
Craig Topper54edcca2011-08-11 04:06:15 +0000935/// ' c-char-sequence '
936/// u' c-char-sequence '
937/// U' c-char-sequence '
938/// L' c-char-sequence '
939/// c-char-sequence:
940/// c-char
941/// c-char-sequence c-char
942/// c-char:
943/// any member of the source character set except the single-quote ',
944/// backslash \, or new-line character
945/// escape-sequence
946/// universal-character-name
Richard Smithe18f0fa2012-03-05 04:02:15 +0000947/// escape-sequence:
Craig Topper54edcca2011-08-11 04:06:15 +0000948/// simple-escape-sequence
949/// octal-escape-sequence
950/// hexadecimal-escape-sequence
951/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +0000952/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +0000953/// octal-escape-sequence:
954/// \ octal-digit
955/// \ octal-digit octal-digit
956/// \ octal-digit octal-digit octal-digit
957/// hexadecimal-escape-sequence:
958/// \x hexadecimal-digit
959/// hexadecimal-escape-sequence hexadecimal-digit
Richard Smithe18f0fa2012-03-05 04:02:15 +0000960/// universal-character-name: [C++11 lex.charset]
Craig Topper54edcca2011-08-11 04:06:15 +0000961/// \u hex-quad
962/// \U hex-quad hex-quad
963/// hex-quad:
964/// hex-digit hex-digit hex-digit hex-digit
James Dennett1cc22032012-06-17 03:34:42 +0000965/// \endverbatim
Craig Topper54edcca2011-08-11 04:06:15 +0000966///
Chris Lattner2f5add62007-04-05 06:57:15 +0000967CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregorfb65e592011-07-27 05:40:30 +0000968 SourceLocation Loc, Preprocessor &PP,
969 tok::TokenKind kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000970 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
Chris Lattner2f5add62007-04-05 06:57:15 +0000971 HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +0000972
Douglas Gregorfb65e592011-07-27 05:40:30 +0000973 Kind = kind;
974
Richard Smith2a70e652012-03-09 22:27:51 +0000975 const char *TokBegin = begin;
976
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000977 // Skip over wide character determinant.
978 if (Kind != tok::char_constant) {
Douglas Gregorfb65e592011-07-27 05:40:30 +0000979 ++begin;
980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Chris Lattner2f5add62007-04-05 06:57:15 +0000982 // Skip over the entry quote.
983 assert(begin[0] == '\'' && "Invalid token lexed");
984 ++begin;
985
Richard Smithe18f0fa2012-03-05 04:02:15 +0000986 // Remove an optional ud-suffix.
987 if (end[-1] != '\'') {
988 const char *UDSuffixEnd = end;
989 do {
990 --end;
991 } while (end[-1] != '\'');
992 UDSuffixBuf.assign(end, UDSuffixEnd);
Richard Smith2a70e652012-03-09 22:27:51 +0000993 UDSuffixOffset = end - TokBegin;
Richard Smithe18f0fa2012-03-05 04:02:15 +0000994 }
995
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000996 // Trim the ending quote.
Richard Smithe18f0fa2012-03-05 04:02:15 +0000997 assert(end != begin && "Invalid token lexed");
Seth Cantrell8b2b6772012-01-18 12:27:04 +0000998 --end;
999
Mike Stump11289f42009-09-09 15:08:12 +00001000 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattner57540c52011-04-15 05:22:18 +00001001 // up to 64-bits.
Chris Lattner2f5add62007-04-05 06:57:15 +00001002 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner37e05872008-03-05 18:54:05 +00001003 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner2f5add62007-04-05 06:57:15 +00001004 "Assumes char is 8 bits");
Chris Lattner8577f622009-04-28 21:51:46 +00001005 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1006 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1007 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1008 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1009 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001010
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001011 SmallVector<uint32_t, 4> codepoint_buffer;
1012 codepoint_buffer.resize(end - begin);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001013 uint32_t *buffer_begin = &codepoint_buffer.front();
1014 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
Mike Stump11289f42009-09-09 15:08:12 +00001015
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001016 // Unicode escapes representing characters that cannot be correctly
1017 // represented in a single code unit are disallowed in character literals
1018 // by this implementation.
1019 uint32_t largest_character_for_kind;
1020 if (tok::wide_char_constant == Kind) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001021 largest_character_for_kind =
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001022 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001023 } else if (tok::utf16_char_constant == Kind) {
1024 largest_character_for_kind = 0xFFFF;
1025 } else if (tok::utf32_char_constant == Kind) {
1026 largest_character_for_kind = 0x10FFFF;
1027 } else {
1028 largest_character_for_kind = 0x7Fu;
Chris Lattner8577f622009-04-28 21:51:46 +00001029 }
1030
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001031 while (begin != end) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001032 // Is this a span of non-escape characters?
1033 if (begin[0] != '\\') {
1034 char const *start = begin;
1035 do {
1036 ++begin;
1037 } while (begin != end && *begin != '\\');
1038
Eli Friedman94363522012-02-11 05:08:10 +00001039 char const *tmp_in_start = start;
1040 uint32_t *tmp_out_start = buffer_begin;
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001041 ConversionResult res =
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001042 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1043 reinterpret_cast<UTF8 const *>(begin),
1044 &buffer_begin, buffer_end, strictConversion);
1045 if (res != conversionOK) {
1046 // If we see bad encoding for unprefixed character literals, warn and
1047 // simply copy the byte values, for compatibility with gcc and
Eli Friedman94363522012-02-11 05:08:10 +00001048 // older versions of clang.
1049 bool NoErrorOnBadEncoding = isAscii();
1050 unsigned Msg = diag::err_bad_character_encoding;
1051 if (NoErrorOnBadEncoding)
1052 Msg = diag::warn_bad_character_encoding;
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001053 PP.Diag(Loc, Msg);
Eli Friedman94363522012-02-11 05:08:10 +00001054 if (NoErrorOnBadEncoding) {
1055 start = tmp_in_start;
1056 buffer_begin = tmp_out_start;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001057 for (; start != begin; ++start, ++buffer_begin)
Eli Friedman94363522012-02-11 05:08:10 +00001058 *buffer_begin = static_cast<uint8_t>(*start);
1059 } else {
1060 HadError = true;
1061 }
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001062 } else {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001063 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
Eli Friedman94363522012-02-11 05:08:10 +00001064 if (*tmp_out_start > largest_character_for_kind) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001065 HadError = true;
1066 PP.Diag(Loc, diag::err_character_too_large);
1067 }
1068 }
1069 }
1070
1071 continue;
1072 }
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001073 // Is this a Universal Character Name escape?
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001074 if (begin[1] == 'u' || begin[1] == 'U') {
1075 unsigned short UcnLen = 0;
Richard Smith2a70e652012-03-09 22:27:51 +00001076 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001077 FullSourceLoc(Loc, PP.getSourceManager()),
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001078 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001079 HadError = true;
1080 } else if (*buffer_begin > largest_character_for_kind) {
1081 HadError = true;
Richard Smith639b8d02012-09-08 07:16:20 +00001082 PP.Diag(Loc, diag::err_character_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001083 }
1084
1085 ++buffer_begin;
1086 continue;
1087 }
1088 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1089 uint64_t result =
Richard Smith639b8d02012-09-08 07:16:20 +00001090 ProcessCharEscape(TokBegin, begin, end, HadError,
Nick Lewycky8054f1d2013-08-21 18:57:51 +00001091 FullSourceLoc(Loc,PP.getSourceManager()),
Richard Smith639b8d02012-09-08 07:16:20 +00001092 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001093 *buffer_begin++ = result;
1094 }
1095
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001096 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001097
Chris Lattner8577f622009-04-28 21:51:46 +00001098 if (NumCharsSoFar > 1) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001099 if (isWide())
Douglas Gregorfb65e592011-07-27 05:40:30 +00001100 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001101 else if (isAscii() && NumCharsSoFar == 4)
1102 PP.Diag(Loc, diag::ext_four_char_character_literal);
1103 else if (isAscii())
Chris Lattner8577f622009-04-28 21:51:46 +00001104 PP.Diag(Loc, diag::ext_multichar_character_literal);
1105 else
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001106 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
Eli Friedmand8cec572009-06-01 05:25:02 +00001107 IsMultiChar = true;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001108 } else {
Daniel Dunbara444cc22009-07-29 01:46:05 +00001109 IsMultiChar = false;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001110 }
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001111
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001112 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1113
1114 // Narrow character literals act as though their value is concatenated
1115 // in this implementation, but warn on overflow.
1116 bool multi_char_too_long = false;
1117 if (isAscii() && isMultiChar()) {
1118 LitVal = 0;
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001119 for (size_t i = 0; i < NumCharsSoFar; ++i) {
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001120 // check for enough leading zeros to shift into
1121 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1122 LitVal <<= 8;
1123 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1124 }
1125 } else if (NumCharsSoFar > 0) {
1126 // otherwise just take the last character
1127 LitVal = buffer_begin[-1];
1128 }
1129
1130 if (!HadError && multi_char_too_long) {
Nick Lewycky63cc55b2013-08-21 02:40:19 +00001131 PP.Diag(Loc, diag::warn_char_constant_too_large);
Seth Cantrell8b2b6772012-01-18 12:27:04 +00001132 }
1133
Sanjiv Guptaf09cb952009-04-21 02:21:29 +00001134 // Transfer the value from APInt to uint64_t
1135 Value = LitVal.getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattner2f5add62007-04-05 06:57:15 +00001137 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1138 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1139 // character constants are not sign extended in the this implementation:
1140 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001141 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001142 PP.getLangOpts().CharIsSigned)
Chris Lattner2f5add62007-04-05 06:57:15 +00001143 Value = (signed char)Value;
1144}
1145
James Dennett99c193b2012-06-19 21:04:25 +00001146/// \verbatim
Craig Topper54edcca2011-08-11 04:06:15 +00001147/// string-literal: [C++0x lex.string]
1148/// encoding-prefix " [s-char-sequence] "
1149/// encoding-prefix R raw-string
1150/// encoding-prefix:
1151/// u8
1152/// u
1153/// U
1154/// L
Steve Naroff4f88b312007-03-13 22:37:02 +00001155/// s-char-sequence:
1156/// s-char
1157/// s-char-sequence s-char
1158/// s-char:
Craig Topper54edcca2011-08-11 04:06:15 +00001159/// any member of the source character set except the double-quote ",
1160/// backslash \, or new-line character
1161/// escape-sequence
Steve Naroff4f88b312007-03-13 22:37:02 +00001162/// universal-character-name
Craig Topper54edcca2011-08-11 04:06:15 +00001163/// raw-string:
1164/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1165/// r-char-sequence:
1166/// r-char
1167/// r-char-sequence r-char
1168/// r-char:
1169/// any member of the source character set, except a right parenthesis )
1170/// followed by the initial d-char-sequence (which may be empty)
1171/// followed by a double quote ".
1172/// d-char-sequence:
1173/// d-char
1174/// d-char-sequence d-char
1175/// d-char:
1176/// any member of the basic source character set except:
1177/// space, the left parenthesis (, the right parenthesis ),
1178/// the backslash \, and the control characters representing horizontal
1179/// tab, vertical tab, form feed, and newline.
1180/// escape-sequence: [C++0x lex.ccon]
1181/// simple-escape-sequence
1182/// octal-escape-sequence
1183/// hexadecimal-escape-sequence
1184/// simple-escape-sequence:
NAKAMURA Takumi9f8a02d2011-08-12 05:49:51 +00001185/// one of \' \" \? \\ \a \b \f \n \r \t \v
Craig Topper54edcca2011-08-11 04:06:15 +00001186/// octal-escape-sequence:
1187/// \ octal-digit
1188/// \ octal-digit octal-digit
1189/// \ octal-digit octal-digit octal-digit
1190/// hexadecimal-escape-sequence:
1191/// \x hexadecimal-digit
1192/// hexadecimal-escape-sequence hexadecimal-digit
Steve Naroff4f88b312007-03-13 22:37:02 +00001193/// universal-character-name:
1194/// \u hex-quad
1195/// \U hex-quad hex-quad
1196/// hex-quad:
1197/// hex-digit hex-digit hex-digit hex-digit
James Dennett99c193b2012-06-19 21:04:25 +00001198/// \endverbatim
Chris Lattner2f5add62007-04-05 06:57:15 +00001199///
Steve Naroff4f88b312007-03-13 22:37:02 +00001200StringLiteralParser::
Chris Lattner146762e2007-07-20 16:59:19 +00001201StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner6bab4352010-11-17 07:21:13 +00001202 Preprocessor &PP, bool Complain)
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001204 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001205 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1206 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner6bab4352010-11-17 07:21:13 +00001207 init(StringToks, NumStringToks);
1208}
1209
1210void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001211 // The literal token may have come from an invalid source location (e.g. due
1212 // to a PCH error), in which case the token length will be 0.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001213 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1214 return DiagnoseLexingError(SourceLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001215
Steve Naroff4f88b312007-03-13 22:37:02 +00001216 // Scan all of the string portions, remember the max individual token length,
1217 // computing a bound on the concatenated string length, and see whether any
1218 // piece is a wide-string. If any of the string portions is a wide-string
1219 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001220 assert(NumStringToks && "expected at least one token");
Alexis Hunt3b791862010-08-30 17:47:05 +00001221 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001222 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001223 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001224 Kind = StringToks[0].getKind();
Alexis Hunt3b791862010-08-30 17:47:05 +00001225
1226 hadError = false;
Chris Lattner2f5add62007-04-05 06:57:15 +00001227
1228 // Implement Translation Phase #6: concatenation of string literals
1229 /// (C99 5.1.1.2p1). The common case is only one string fragment.
Steve Naroff4f88b312007-03-13 22:37:02 +00001230 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001231 if (StringToks[i].getLength() < 2)
1232 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001233
Steve Naroff4f88b312007-03-13 22:37:02 +00001234 // The string could be shorter than this if it needs cleaning, but this is a
1235 // reasonable bound, which is all we need.
Argyrios Kyrtzidis8b7252a2011-05-17 22:09:56 +00001236 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Alexis Hunt3b791862010-08-30 17:47:05 +00001237 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump11289f42009-09-09 15:08:12 +00001238
Steve Naroff4f88b312007-03-13 22:37:02 +00001239 // Remember maximum string piece length.
Alexis Hunt3b791862010-08-30 17:47:05 +00001240 if (StringToks[i].getLength() > MaxTokenLength)
1241 MaxTokenLength = StringToks[i].getLength();
Mike Stump11289f42009-09-09 15:08:12 +00001242
Douglas Gregorfb65e592011-07-27 05:40:30 +00001243 // Remember if we see any wide or utf-8/16/32 strings.
1244 // Also check for illegal concatenations.
1245 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1246 if (isAscii()) {
1247 Kind = StringToks[i].getKind();
1248 } else {
1249 if (Diags)
Richard Smith639b8d02012-09-08 07:16:20 +00001250 Diags->Report(StringToks[i].getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001251 diag::err_unsupported_string_concat);
1252 hadError = true;
1253 }
1254 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001255 }
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001256
Steve Naroff4f88b312007-03-13 22:37:02 +00001257 // Include space for the null terminator.
1258 ++SizeBound;
Mike Stump11289f42009-09-09 15:08:12 +00001259
Steve Naroff4f88b312007-03-13 22:37:02 +00001260 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump11289f42009-09-09 15:08:12 +00001261
Douglas Gregorfb65e592011-07-27 05:40:30 +00001262 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1263 CharByteWidth = getCharWidth(Kind, Target);
1264 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1265 CharByteWidth /= 8;
Mike Stump11289f42009-09-09 15:08:12 +00001266
Steve Naroff4f88b312007-03-13 22:37:02 +00001267 // The output buffer size needs to be large enough to hold wide characters.
1268 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregorfb65e592011-07-27 05:40:30 +00001269 SizeBound *= CharByteWidth;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Steve Naroff4f88b312007-03-13 22:37:02 +00001271 // Size the temporary buffer to hold the result string data.
1272 ResultBuf.resize(SizeBound);
Mike Stump11289f42009-09-09 15:08:12 +00001273
Steve Naroff4f88b312007-03-13 22:37:02 +00001274 // Likewise, but for each string piece.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001275 SmallString<512> TokenBuf;
Steve Naroff4f88b312007-03-13 22:37:02 +00001276 TokenBuf.resize(MaxTokenLength);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Steve Naroff4f88b312007-03-13 22:37:02 +00001278 // Loop over all the strings, getting their spelling, and expanding them to
1279 // wide strings as appropriate.
1280 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump11289f42009-09-09 15:08:12 +00001281
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001282 Pascal = false;
Mike Stump11289f42009-09-09 15:08:12 +00001283
Richard Smithe18f0fa2012-03-05 04:02:15 +00001284 SourceLocation UDSuffixTokLoc;
1285
Steve Naroff4f88b312007-03-13 22:37:02 +00001286 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1287 const char *ThisTokBuf = &TokenBuf[0];
1288 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1289 // that ThisTokBuf points to a buffer that is big enough for the whole token
1290 // and 'spelled' tokens can only shrink.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001291 bool StringInvalid = false;
Chris Lattner6bab4352010-11-17 07:21:13 +00001292 unsigned ThisTokLen =
Chris Lattner39720112010-11-17 07:26:20 +00001293 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1294 &StringInvalid);
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001295 if (StringInvalid)
1296 return DiagnoseLexingError(StringToks[i].getLocation());
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001297
Richard Smith2a70e652012-03-09 22:27:51 +00001298 const char *ThisTokBegin = ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001299 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1300
1301 // Remove an optional ud-suffix.
1302 if (ThisTokEnd[-1] != '"') {
1303 const char *UDSuffixEnd = ThisTokEnd;
1304 do {
1305 --ThisTokEnd;
1306 } while (ThisTokEnd[-1] != '"');
1307
1308 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1309
1310 if (UDSuffixBuf.empty()) {
1311 UDSuffixBuf.assign(UDSuffix);
Richard Smith75b67d62012-03-08 01:34:56 +00001312 UDSuffixToken = i;
1313 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
Richard Smithe18f0fa2012-03-05 04:02:15 +00001314 UDSuffixTokLoc = StringToks[i].getLocation();
1315 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1316 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1317 // result of a concatenation involving at least one user-defined-string-
1318 // literal, all the participating user-defined-string-literals shall
1319 // have the same ud-suffix.
1320 if (Diags) {
1321 SourceLocation TokLoc = StringToks[i].getLocation();
1322 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1323 << UDSuffixBuf << UDSuffix
1324 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1325 << SourceRange(TokLoc, TokLoc);
1326 }
1327 hadError = true;
1328 }
1329 }
1330
1331 // Strip the end quote.
1332 --ThisTokEnd;
1333
Steve Naroff4f88b312007-03-13 22:37:02 +00001334 // TODO: Input character set mapping support.
Mike Stump11289f42009-09-09 15:08:12 +00001335
Craig Topper61147ed2011-08-08 06:10:39 +00001336 // Skip marker for wide or unicode strings.
Douglas Gregorfb65e592011-07-27 05:40:30 +00001337 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Chris Lattnerc10adde2007-05-20 05:00:58 +00001338 ++ThisTokBuf;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001339 // Skip 8 of u8 marker for utf8 strings.
1340 if (ThisTokBuf[0] == '8')
1341 ++ThisTokBuf;
Fariborz Jahanianabaae2b2010-08-31 23:34:27 +00001342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Craig Topper54edcca2011-08-11 04:06:15 +00001344 // Check for raw string
1345 if (ThisTokBuf[0] == 'R') {
1346 ThisTokBuf += 2; // skip R"
Mike Stump11289f42009-09-09 15:08:12 +00001347
Craig Topper54edcca2011-08-11 04:06:15 +00001348 const char *Prefix = ThisTokBuf;
1349 while (ThisTokBuf[0] != '(')
Anders Carlssoncbfc4b82007-10-15 02:50:23 +00001350 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001351 ++ThisTokBuf; // skip '('
Mike Stump11289f42009-09-09 15:08:12 +00001352
Richard Smith81292452012-03-08 21:59:28 +00001353 // Remove same number of characters from the end
1354 ThisTokEnd -= ThisTokBuf - Prefix;
1355 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
Craig Topper54edcca2011-08-11 04:06:15 +00001356
1357 // Copy the string over
Richard Smith639b8d02012-09-08 07:16:20 +00001358 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1359 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1360 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001361 } else {
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001362 if (ThisTokBuf[0] != '"') {
1363 // The file may have come from PCH and then changed after loading the
1364 // PCH; Fail gracefully.
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001365 return DiagnoseLexingError(StringToks[i].getLocation());
Argyrios Kyrtzidis4e5b5c32012-05-03 01:01:56 +00001366 }
Craig Topper54edcca2011-08-11 04:06:15 +00001367 ++ThisTokBuf; // skip "
1368
1369 // Check if this is a pascal string
1370 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1371 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1372
1373 // If the \p sequence is found in the first token, we have a pascal string
1374 // Otherwise, if we already have a pascal string, ignore the first \p
1375 if (i == 0) {
Steve Naroff4f88b312007-03-13 22:37:02 +00001376 ++ThisTokBuf;
Craig Topper54edcca2011-08-11 04:06:15 +00001377 Pascal = true;
1378 } else if (Pascal)
1379 ThisTokBuf += 2;
1380 }
Mike Stump11289f42009-09-09 15:08:12 +00001381
Craig Topper54edcca2011-08-11 04:06:15 +00001382 while (ThisTokBuf != ThisTokEnd) {
1383 // Is this a span of non-escape characters?
1384 if (ThisTokBuf[0] != '\\') {
1385 const char *InStart = ThisTokBuf;
1386 do {
1387 ++ThisTokBuf;
1388 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1389
1390 // Copy the character span over.
Richard Smith639b8d02012-09-08 07:16:20 +00001391 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1392 StringRef(InStart, ThisTokBuf - InStart)))
1393 hadError = true;
Craig Topper54edcca2011-08-11 04:06:15 +00001394 continue;
Steve Naroff4f88b312007-03-13 22:37:02 +00001395 }
Craig Topper54edcca2011-08-11 04:06:15 +00001396 // Is this a Universal Character Name escape?
1397 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Richard Smith2a70e652012-03-09 22:27:51 +00001398 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1399 ResultPtr, hadError,
1400 FullSourceLoc(StringToks[i].getLocation(), SM),
Craig Topper54edcca2011-08-11 04:06:15 +00001401 CharByteWidth, Diags, Features);
1402 continue;
1403 }
1404 // Otherwise, this is a non-UCN escape character. Process it.
1405 unsigned ResultChar =
Richard Smith639b8d02012-09-08 07:16:20 +00001406 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
Craig Topper54edcca2011-08-11 04:06:15 +00001407 FullSourceLoc(StringToks[i].getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001408 CharByteWidth*8, Diags, Features);
Mike Stump11289f42009-09-09 15:08:12 +00001409
Eli Friedmand1370792011-11-02 23:06:23 +00001410 if (CharByteWidth == 4) {
1411 // FIXME: Make the type of the result buffer correct instead of
1412 // using reinterpret_cast.
1413 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001414 *ResultWidePtr = ResultChar;
Eli Friedmand1370792011-11-02 23:06:23 +00001415 ResultPtr += 4;
1416 } else if (CharByteWidth == 2) {
1417 // FIXME: Make the type of the result buffer correct instead of
1418 // using reinterpret_cast.
1419 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
Nico Weberd60b72f2011-11-14 05:17:37 +00001420 *ResultWidePtr = ResultChar & 0xFFFF;
Eli Friedmand1370792011-11-02 23:06:23 +00001421 ResultPtr += 2;
1422 } else {
1423 assert(CharByteWidth == 1 && "Unexpected char width");
1424 *ResultPtr++ = ResultChar & 0xFF;
1425 }
Craig Topper54edcca2011-08-11 04:06:15 +00001426 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001427 }
1428 }
Mike Stump11289f42009-09-09 15:08:12 +00001429
Chris Lattner8a24e582009-01-16 18:51:42 +00001430 if (Pascal) {
Eli Friedman20554702011-11-05 00:41:04 +00001431 if (CharByteWidth == 4) {
1432 // FIXME: Make the type of the result buffer correct instead of
1433 // using reinterpret_cast.
1434 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1435 ResultWidePtr[0] = GetNumStringChars() - 1;
1436 } else if (CharByteWidth == 2) {
1437 // FIXME: Make the type of the result buffer correct instead of
1438 // using reinterpret_cast.
1439 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1440 ResultWidePtr[0] = GetNumStringChars() - 1;
1441 } else {
1442 assert(CharByteWidth == 1 && "Unexpected char width");
1443 ResultBuf[0] = GetNumStringChars() - 1;
1444 }
Chris Lattner8a24e582009-01-16 18:51:42 +00001445
1446 // Verify that pascal strings aren't too large.
Chris Lattner6bab4352010-11-17 07:21:13 +00001447 if (GetStringLength() > 256) {
Richard Smith639b8d02012-09-08 07:16:20 +00001448 if (Diags)
1449 Diags->Report(StringToks[0].getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001450 diag::err_pascal_string_too_long)
1451 << SourceRange(StringToks[0].getLocation(),
1452 StringToks[NumStringToks-1].getLocation());
Douglas Gregorfb65e592011-07-27 05:40:30 +00001453 hadError = true;
Eli Friedman1c3fb222009-04-01 03:17:08 +00001454 return;
1455 }
Chris Lattner6bab4352010-11-17 07:21:13 +00001456 } else if (Diags) {
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001457 // Complain if this string literal has too many characters.
Chris Lattner2be8aa92010-11-17 07:12:42 +00001458 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001459
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001460 if (GetNumStringChars() > MaxChars)
Richard Smith639b8d02012-09-08 07:16:20 +00001461 Diags->Report(StringToks[0].getLocation(),
Chris Lattner6bab4352010-11-17 07:21:13 +00001462 diag::ext_string_too_long)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001463 << GetNumStringChars() << MaxChars
Chris Lattner2be8aa92010-11-17 07:12:42 +00001464 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregorb37b46e2010-07-20 14:33:20 +00001465 << SourceRange(StringToks[0].getLocation(),
1466 StringToks[NumStringToks-1].getLocation());
Chris Lattner8a24e582009-01-16 18:51:42 +00001467 }
Steve Naroff4f88b312007-03-13 22:37:02 +00001468}
Chris Lattnerddb71912009-02-18 19:21:10 +00001469
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001470static const char *resyncUTF8(const char *Err, const char *End) {
1471 if (Err == End)
1472 return End;
1473 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1474 while (++Err != End && (*Err & 0xC0) == 0x80)
1475 ;
1476 return Err;
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001477}
1478
Richard Smith639b8d02012-09-08 07:16:20 +00001479/// \brief This function copies from Fragment, which is a sequence of bytes
1480/// within Tok's contents (which begin at TokBegin) into ResultPtr.
Craig Topper54edcca2011-08-11 04:06:15 +00001481/// Performs widening for multi-byte characters.
Richard Smith639b8d02012-09-08 07:16:20 +00001482bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1483 const char *TokBegin,
1484 StringRef Fragment) {
1485 const UTF8 *ErrorPtrTmp;
1486 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1487 return false;
Craig Topper54edcca2011-08-11 04:06:15 +00001488
Eli Friedman94363522012-02-11 05:08:10 +00001489 // If we see bad encoding for unprefixed string literals, warn and
1490 // simply copy the byte values, for compatibility with gcc and older
1491 // versions of clang.
1492 bool NoErrorOnBadEncoding = isAscii();
Richard Smith639b8d02012-09-08 07:16:20 +00001493 if (NoErrorOnBadEncoding) {
1494 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1495 ResultPtr += Fragment.size();
1496 }
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001497
Richard Smith639b8d02012-09-08 07:16:20 +00001498 if (Diags) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001499 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1500
1501 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1502 const DiagnosticBuilder &Builder =
1503 Diag(Diags, Features, SourceLoc, TokBegin,
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001504 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001505 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1506 : diag::err_bad_string_encoding);
1507
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001508 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001509 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1510
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001511 // Decode into a dummy buffer.
1512 SmallString<512> Dummy;
1513 Dummy.reserve(Fragment.size() * CharByteWidth);
1514 char *Ptr = Dummy.data();
1515
David Blaikiea0613172012-10-30 23:22:22 +00001516 while (!Builder.hasMaxRanges() &&
Benjamin Kramer7d574e22012-11-08 19:22:31 +00001517 !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001518 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
Benjamin Kramerf23a6e62012-11-08 19:22:26 +00001519 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Seth Cantrell4cfc8172012-10-28 18:24:46 +00001520 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1521 ErrorPtr, NextStart);
1522 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1523 }
Richard Smith639b8d02012-09-08 07:16:20 +00001524 }
Eli Friedman94363522012-02-11 05:08:10 +00001525 return !NoErrorOnBadEncoding;
1526}
Craig Topper54edcca2011-08-11 04:06:15 +00001527
Argyrios Kyrtzidis9933e3a2012-05-03 17:50:32 +00001528void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1529 hadError = true;
1530 if (Diags)
1531 Diags->Report(Loc, diag::err_lexing_string);
1532}
1533
Chris Lattnerddb71912009-02-18 19:21:10 +00001534/// getOffsetOfStringByte - This function returns the offset of the
1535/// specified byte of the string data represented by Token. This handles
1536/// advancing over escape sequences in the string.
1537unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattnerbde1b812010-11-17 06:46:14 +00001538 unsigned ByteNo) const {
Chris Lattnerddb71912009-02-18 19:21:10 +00001539 // Get the spelling of the token.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001540 SmallString<32> SpellingBuffer;
Alexis Hunt3b791862010-08-30 17:47:05 +00001541 SpellingBuffer.resize(Tok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001542
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001543 bool StringInvalid = false;
Chris Lattnerddb71912009-02-18 19:21:10 +00001544 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattner39720112010-11-17 07:26:20 +00001545 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1546 &StringInvalid);
Chris Lattner7a02bfd2010-11-17 06:26:08 +00001547 if (StringInvalid)
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001548 return 0;
Chris Lattnerddb71912009-02-18 19:21:10 +00001549
Chris Lattnerddb71912009-02-18 19:21:10 +00001550 const char *SpellingStart = SpellingPtr;
1551 const char *SpellingEnd = SpellingPtr+TokLen;
1552
Richard Smith4060f772012-06-13 05:37:23 +00001553 // Handle UTF-8 strings just like narrow strings.
1554 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1555 SpellingPtr += 2;
1556
1557 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1558 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1559
1560 // For raw string literals, this is easy.
1561 if (SpellingPtr[0] == 'R') {
1562 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1563 // Skip 'R"'.
1564 SpellingPtr += 2;
1565 while (*SpellingPtr != '(') {
1566 ++SpellingPtr;
1567 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1568 }
1569 // Skip '('.
1570 ++SpellingPtr;
1571 return SpellingPtr - SpellingStart + ByteNo;
1572 }
1573
1574 // Skip over the leading quote
Chris Lattnerddb71912009-02-18 19:21:10 +00001575 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1576 ++SpellingPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001577
Chris Lattnerddb71912009-02-18 19:21:10 +00001578 // Skip over bytes until we find the offset we're looking for.
1579 while (ByteNo) {
1580 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump11289f42009-09-09 15:08:12 +00001581
Chris Lattnerddb71912009-02-18 19:21:10 +00001582 // Step over non-escapes simply.
1583 if (*SpellingPtr != '\\') {
1584 ++SpellingPtr;
1585 --ByteNo;
1586 continue;
1587 }
Mike Stump11289f42009-09-09 15:08:12 +00001588
Chris Lattnerddb71912009-02-18 19:21:10 +00001589 // Otherwise, this is an escape character. Advance over it.
1590 bool HadError = false;
Richard Smith4060f772012-06-13 05:37:23 +00001591 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1592 const char *EscapePtr = SpellingPtr;
1593 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1594 1, Features, HadError);
1595 if (Len > ByteNo) {
1596 // ByteNo is somewhere within the escape sequence.
1597 SpellingPtr = EscapePtr;
1598 break;
1599 }
1600 ByteNo -= Len;
1601 } else {
Richard Smith639b8d02012-09-08 07:16:20 +00001602 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
Richard Smith4060f772012-06-13 05:37:23 +00001603 FullSourceLoc(Tok.getLocation(), SM),
Richard Smith639b8d02012-09-08 07:16:20 +00001604 CharByteWidth*8, Diags, Features);
Richard Smith4060f772012-06-13 05:37:23 +00001605 --ByteNo;
1606 }
Chris Lattnerddb71912009-02-18 19:21:10 +00001607 assert(!HadError && "This method isn't valid on erroneous strings");
Chris Lattnerddb71912009-02-18 19:21:10 +00001608 }
Mike Stump11289f42009-09-09 15:08:12 +00001609
Chris Lattnerddb71912009-02-18 19:21:10 +00001610 return SpellingPtr-SpellingStart;
1611}