1 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the NumericLiteralParser, CharLiteralParser, and
11 // StringLiteralParser interfaces.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Lex/LiteralSupport.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/LexDiagnostic.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/ConvertUTF.h"
22 #include "llvm/Support/ErrorHandling.h"
23
24 using namespace clang;
25
getCharWidth(tok::TokenKind kind,const TargetInfo & Target)26 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
27 switch (kind) {
28 default: llvm_unreachable("Unknown token type!");
29 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
MakeCharSourceRange(const LangOptions & Features,FullSourceLoc TokLoc,const char * TokBegin,const char * TokRangeBegin,const char * TokRangeEnd)45 static 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
59 /// \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.
Diag(DiagnosticsEngine * Diags,const LangOptions & Features,FullSourceLoc TokLoc,const char * TokBegin,const char * TokRangeBegin,const char * TokRangeEnd,unsigned DiagID)64 static 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);
71 return Diags->Report(Begin, DiagID) <<
72 MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
73 }
74
75 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
76 /// either a character or a string literal.
ProcessCharEscape(const char * ThisTokBegin,const char * & ThisTokBuf,const char * ThisTokEnd,bool & HadError,FullSourceLoc Loc,unsigned CharWidth,DiagnosticsEngine * Diags,const LangOptions & Features)77 static unsigned ProcessCharEscape(const char *ThisTokBegin,
78 const char *&ThisTokBuf,
79 const char *ThisTokEnd, bool &HadError,
80 FullSourceLoc Loc, unsigned CharWidth,
81 DiagnosticsEngine *Diags,
82 const LangOptions &Features) {
83 const char *EscapeBegin = ThisTokBuf;
84
85 // 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;
94
95 // 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':
104 if (Diags)
105 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
106 diag::ext_nonstandard_escape) << "e";
107 ResultChar = 27;
108 break;
109 case 'E':
110 if (Diags)
111 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
112 diag::ext_nonstandard_escape) << "E";
113 ResultChar = 27;
114 break;
115 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;
130 case 'x': { // Hex escape.
131 ResultChar = 0;
132 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
133 if (Diags)
134 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
135 diag::err_hex_escape_no_digits) << "x";
136 HadError = 1;
137 break;
138 }
139
140 // Hex escapes are a maximal series of hex digits.
141 bool Overflow = false;
142 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
143 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
144 if (CharVal == -1) break;
145 // About to shift out a digit?
146 Overflow |= (ResultChar & 0xF0000000) ? true : false;
147 ResultChar <<= 4;
148 ResultChar |= CharVal;
149 }
150
151 // See if any bits will be truncated when evaluated as a character.
152 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
153 Overflow = true;
154 ResultChar &= ~0U >> (32-CharWidth);
155 }
156
157 // Check for overflow.
158 if (Overflow && Diags) // Too many digits to fit in
159 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
160 diag::err_hex_escape_too_large);
161 break;
162 }
163 case '0': case '1': case '2': case '3':
164 case '4': case '5': case '6': case '7': {
165 // Octal escapes.
166 --ThisTokBuf;
167 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');
178
179 // Check for overflow. Reject '\777', but not L'\777'.
180 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
181 if (Diags)
182 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
183 diag::err_octal_escape_too_large);
184 ResultChar &= ~0U >> (32-CharWidth);
185 }
186 break;
187 }
188
189 // Otherwise, these are not valid escapes.
190 case '(': case '{': case '[': case '%':
191 // GCC accepts these as extensions. We warn about them as such though.
192 if (Diags)
193 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
194 diag::ext_nonstandard_escape)
195 << std::string(1, ResultChar);
196 break;
197 default:
198 if (Diags == 0)
199 break;
200
201 if (isPrintable(ResultChar))
202 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
203 diag::ext_unknown_escape)
204 << std::string(1, ResultChar);
205 else
206 Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
207 diag::ext_unknown_escape)
208 << "x" + llvm::utohexstr(ResultChar);
209 break;
210 }
211
212 return ResultChar;
213 }
214
215 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
216 /// return the UTF32.
ProcessUCNEscape(const char * ThisTokBegin,const char * & ThisTokBuf,const char * ThisTokEnd,uint32_t & UcnVal,unsigned short & UcnLen,FullSourceLoc Loc,DiagnosticsEngine * Diags,const LangOptions & Features,bool in_char_string_literal=false)217 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
218 const char *ThisTokEnd,
219 uint32_t &UcnVal, unsigned short &UcnLen,
220 FullSourceLoc Loc, DiagnosticsEngine *Diags,
221 const LangOptions &Features,
222 bool in_char_string_literal = false) {
223 const char *UcnBegin = ThisTokBuf;
224
225 // Skip the '\u' char's.
226 ThisTokBuf += 2;
227
228 if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
229 if (Diags)
230 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
231 diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
232 return false;
233 }
234 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
235 unsigned short UcnLenSave = UcnLen;
236 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
237 int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
238 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.
243 if (UcnLenSave) {
244 if (Diags)
245 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
246 diag::err_ucn_escape_incomplete);
247 return false;
248 }
249
250 // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
251 if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
252 UcnVal > 0x10FFFF) { // maximum legal UTF32 value
253 if (Diags)
254 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
255 diag::err_ucn_escape_invalid);
256 return false;
257 }
258
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)) { // $, @, `
263 bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
264 if (Diags) {
265 char BasicSCSChar = UcnVal;
266 if (UcnVal >= 0x20 && UcnVal < 0x7f)
267 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);
271 else
272 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
273 IsError ? diag::err_ucn_control_character :
274 diag::warn_cxx98_compat_literal_ucn_control_character);
275 }
276 if (IsError)
277 return false;
278 }
279
280 if (!Features.CPlusPlus && !Features.C99 && Diags)
281 Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
282 diag::warn_ucn_not_valid_in_c89_literal);
283
284 return true;
285 }
286
287 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
288 /// which this UCN will occupy.
MeasureUCNEscape(const char * ThisTokBegin,const char * & ThisTokBuf,const char * ThisTokEnd,unsigned CharByteWidth,const LangOptions & Features,bool & HadError)289 static 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
320 /// 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.
EncodeUCNEscape(const char * ThisTokBegin,const char * & ThisTokBuf,const char * ThisTokEnd,char * & ResultBuf,bool & HadError,FullSourceLoc Loc,unsigned CharByteWidth,DiagnosticsEngine * Diags,const LangOptions & Features)324 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
325 const char *ThisTokEnd,
326 char *&ResultBuf, bool &HadError,
327 FullSourceLoc Loc, unsigned CharByteWidth,
328 DiagnosticsEngine *Diags,
329 const LangOptions &Features) {
330 typedef uint32_t UTF32;
331 UTF32 UcnVal = 0;
332 unsigned short UcnLen = 0;
333 if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
334 Loc, Diags, Features, true)) {
335 HadError = true;
336 return;
337 }
338
339 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
340 "only character widths of 1, 2, or 4 bytes supported");
341
342 (void)UcnLen;
343 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
344
345 if (CharByteWidth == 4) {
346 // 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;
351 return;
352 }
353
354 if (CharByteWidth == 2) {
355 // FIXME: Make the type of the result buffer correct instead of
356 // using reinterpret_cast.
357 UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf);
358
359 if (UcnVal <= (UTF32)0xFFFF) {
360 *ResultPtr = UcnVal;
361 ResultBuf += 2;
362 return;
363 }
364
365 // Convert to UTF16.
366 UcnVal -= 0x10000;
367 *ResultPtr = 0xD800 + (UcnVal >> 10);
368 *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
369 ResultBuf += 4;
370 return;
371 }
372
373 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
374
375 // 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
378 // First, we determine how many bytes the result will require.
379 typedef uint8_t UTF8;
380
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;
390
391 const unsigned byteMask = 0xBF;
392 const unsigned byteMark = 0x80;
393
394 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
395 // into the first byte, depending on how many bytes follow.
396 static const UTF8 firstByteMark[5] = {
397 0x00, 0x00, 0xC0, 0xE0, 0xF0
398 };
399 // Finally, we write the bytes into ResultBuf.
400 ResultBuf += bytesToWrite;
401 switch (bytesToWrite) { // note: everything falls through.
402 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]);
406 }
407 // Update the buffer.
408 ResultBuf += bytesToWrite;
409 }
410
411
412 /// integer-constant: [C99 6.4.4.1]
413 /// decimal-constant integer-suffix
414 /// octal-constant integer-suffix
415 /// hexadecimal-constant integer-suffix
416 /// binary-literal integer-suffix [GNU, C++1y]
417 /// user-defined-integer-literal: [C++11 lex.ext]
418 /// decimal-literal ud-suffix
419 /// octal-literal ud-suffix
420 /// hexadecimal-literal ud-suffix
421 /// binary-literal ud-suffix [GNU, C++1y]
422 /// decimal-constant:
423 /// nonzero-digit
424 /// decimal-constant digit
425 /// octal-constant:
426 /// 0
427 /// octal-constant octal-digit
428 /// hexadecimal-constant:
429 /// hexadecimal-prefix hexadecimal-digit
430 /// hexadecimal-constant hexadecimal-digit
431 /// hexadecimal-prefix: one of
432 /// 0x 0X
433 /// binary-literal:
434 /// 0b binary-digit
435 /// 0B binary-digit
436 /// binary-literal binary-digit
437 /// 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
450 /// binary-digit:
451 /// 0
452 /// 1
453 /// unsigned-suffix: one of
454 /// u U
455 /// long-suffix: one of
456 /// l L
457 /// long-long-suffix: one of
458 /// ll LL
459 ///
460 /// floating-constant: [C99 6.4.4.2]
461 /// TODO: add rules...
462 ///
NumericLiteralParser(StringRef TokSpelling,SourceLocation TokLoc,Preprocessor & PP)463 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
464 SourceLocation TokLoc,
465 Preprocessor &PP)
466 : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
467
468 // 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.
472 assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
473
474 s = DigitsBegin = ThisTokBegin;
475 saw_exponent = false;
476 saw_period = false;
477 saw_ud_suffix = false;
478 isLong = false;
479 isUnsigned = false;
480 isLongLong = false;
481 isFloat = false;
482 isImaginary = false;
483 isMicrosoftInteger = false;
484 hadError = false;
485
486 if (*s == '0') { // parse radix
487 ParseNumberStartingWithZero(TokLoc);
488 if (hadError)
489 return;
490 } else { // the first digit is non-zero
491 radix = 10;
492 s = SkipDigits(s);
493 if (s == ThisTokEnd) {
494 // Done.
495 } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) {
496 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
497 diag::err_invalid_decimal_digit) << StringRef(s, 1);
498 hadError = true;
499 return;
500 } else if (*s == '.') {
501 checkSeparator(TokLoc, s, CSK_AfterDigits);
502 s++;
503 saw_period = true;
504 checkSeparator(TokLoc, s, CSK_BeforeDigits);
505 s = SkipDigits(s);
506 }
507 if ((*s == 'e' || *s == 'E')) { // exponent
508 checkSeparator(TokLoc, s, CSK_AfterDigits);
509 const char *Exponent = s;
510 s++;
511 saw_exponent = true;
512 if (*s == '+' || *s == '-') s++; // sign
513 checkSeparator(TokLoc, s, CSK_BeforeDigits);
514 const char *first_non_digit = SkipDigits(s);
515 if (first_non_digit != s) {
516 s = first_non_digit;
517 } else {
518 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin),
519 diag::err_exponent_has_no_digits);
520 hadError = true;
521 return;
522 }
523 }
524 }
525
526 SuffixBegin = s;
527 checkSeparator(TokLoc, s, CSK_AfterDigits);
528
529 // Parse the suffix. At this point we can classify whether we have an FP or
530 // integer constant.
531 bool isFPConstant = isFloatingLiteral();
532 const char *ImaginarySuffixLoc = 0;
533
534 // 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.
541 if (isFloat || isLong) break; // FF, LF invalid.
542 isFloat = true;
543 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.
553 if (isFloat) break; // LF invalid.
554
555 // 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 {
561 isLong = true;
562 }
563 continue; // Success.
564 case 'i':
565 case 'I':
566 if (PP.getLangOpts().MicrosoftExt) {
567 if (isFPConstant || isLong || isLongLong) break;
568
569 // Allow i8, i16, i32, i64, and i128.
570 if (s + 1 != ThisTokEnd) {
571 switch (s[1]) {
572 case '8':
573 s += 2; // i8 suffix
574 isMicrosoftInteger = true;
575 break;
576 case '1':
577 if (s + 2 == ThisTokEnd) break;
578 if (s[2] == '6') {
579 s += 3; // i16 suffix
580 isMicrosoftInteger = true;
581 }
582 else if (s[2] == '2') {
583 if (s + 3 == ThisTokEnd) break;
584 if (s[3] == '8') {
585 s += 4; // i128 suffix
586 isMicrosoftInteger = true;
587 }
588 }
589 break;
590 case '3':
591 if (s + 2 == ThisTokEnd) break;
592 if (s[2] == '2') {
593 s += 3; // i32 suffix
594 isLong = true;
595 isMicrosoftInteger = true;
596 }
597 break;
598 case '6':
599 if (s + 2 == ThisTokEnd) break;
600 if (s[2] == '4') {
601 s += 3; // i64 suffix
602 isLongLong = true;
603 isMicrosoftInteger = true;
604 }
605 break;
606 default:
607 break;
608 }
609 break;
610 }
611 }
612 // "i", "if", and "il" are user-defined suffixes in C++1y.
613 if (PP.getLangOpts().CPlusPlus1y && *s == 'i')
614 break;
615 // fall through.
616 case 'j':
617 case 'J':
618 if (isImaginary) break; // Cannot be repeated.
619 isImaginary = true;
620 ImaginarySuffixLoc = s;
621 continue; // Success.
622 }
623 // If we reached here, there was an error or a ud-suffix.
624 break;
625 }
626
627 if (s != ThisTokEnd) {
628 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
639 saw_ud_suffix = true;
640 return;
641 }
642
643 // Report an error if there are any.
644 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
645 isFPConstant ? diag::err_invalid_suffix_float_constant :
646 diag::err_invalid_suffix_integer_constant)
647 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
648 hadError = true;
649 return;
650 }
651
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.
isValidUDSuffix(const LangOptions & LangOpts,StringRef Suffix)662 bool 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.
676 // Per tweaked N3660, "il", "i", and "if" are also used in the library.
677 return llvm::StringSwitch<bool>(Suffix)
678 .Cases("h", "min", "s", true)
679 .Cases("ms", "us", "ns", true)
680 .Cases("il", "i", "if", true)
681 .Default(false);
682 }
683
checkSeparator(SourceLocation TokLoc,const char * Pos,CheckSeparatorKind IsAfterDigits)684 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
685 const char *Pos,
686 CheckSeparatorKind IsAfterDigits) {
687 if (IsAfterDigits == CSK_AfterDigits) {
688 if (Pos == ThisTokBegin)
689 return;
690 --Pos;
691 } else if (Pos == ThisTokEnd)
692 return;
693
694 if (isDigitSeparator(*Pos))
695 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
696 diag::err_digit_separator_not_between_digits)
697 << IsAfterDigits;
698 }
699
700 /// 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
703 /// a floating point number (01239.123e4). Eat the prefix, determining the
704 /// radix etc.
ParseNumberStartingWithZero(SourceLocation TokLoc)705 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
706 assert(s[0] == '0' && "Invalid method call");
707 s++;
708
709 int c1 = s[0];
710 int c2 = s[1];
711
712 // Handle a hex number like 0x1234.
713 if ((c1 == 'x' || c1 == 'X') && (isHexDigit(c2) || c2 == '.')) {
714 s++;
715 radix = 16;
716 DigitsBegin = s;
717 s = SkipHexDigits(s);
718 bool noSignificand = (s == DigitsBegin);
719 if (s == ThisTokEnd) {
720 // Done.
721 } else if (*s == '.') {
722 s++;
723 saw_period = true;
724 const char *floatDigitsBegin = s;
725 s = SkipHexDigits(s);
726 noSignificand &= (floatDigitsBegin == s);
727 }
728
729 if (noSignificand) {
730 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
731 diag::err_hexconstant_requires_digits);
732 hadError = true;
733 return;
734 }
735
736 // A binary exponent can appear with or with a '.'. If dotted, the
737 // binary exponent is required.
738 if (*s == 'p' || *s == 'P') {
739 const char *Exponent = s;
740 s++;
741 saw_exponent = true;
742 if (*s == '+' || *s == '-') s++; // sign
743 const char *first_non_digit = SkipDigits(s);
744 if (first_non_digit == s) {
745 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
746 diag::err_exponent_has_no_digits);
747 hadError = true;
748 return;
749 }
750 s = first_non_digit;
751
752 if (!PP.getLangOpts().HexFloats)
753 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
754 } else if (saw_period) {
755 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
756 diag::err_hexconstant_requires_exponent);
757 hadError = true;
758 }
759 return;
760 }
761
762 // Handle simple binary numbers 0b01010
763 if ((c1 == 'b' || c1 == 'B') && (c2 == '0' || c2 == '1')) {
764 // 0b101010 is a C++1y / GCC extension.
765 PP.Diag(TokLoc,
766 PP.getLangOpts().CPlusPlus1y
767 ? diag::warn_cxx11_compat_binary_literal
768 : PP.getLangOpts().CPlusPlus
769 ? diag::ext_binary_literal_cxx1y
770 : diag::ext_binary_literal);
771 ++s;
772 radix = 2;
773 DigitsBegin = s;
774 s = SkipBinaryDigits(s);
775 if (s == ThisTokEnd) {
776 // Done.
777 } else if (isHexDigit(*s)) {
778 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
779 diag::err_invalid_binary_digit) << StringRef(s, 1);
780 hadError = true;
781 }
782 // Other suffixes will be diagnosed by the caller.
783 return;
784 }
785
786 // For now, the radix is set to 8. If we discover that we have a
787 // floating point constant, the radix will change to 10. Octal floating
788 // point constants are not permitted (only decimal and hexadecimal).
789 radix = 8;
790 DigitsBegin = s;
791 s = SkipOctalDigits(s);
792 if (s == ThisTokEnd)
793 return; // Done, simple octal number like 01234
794
795 // If we have some other non-octal digit that *is* a decimal digit, see if
796 // this is part of a floating point number like 094.123 or 09e1.
797 if (isDigit(*s)) {
798 const char *EndDecimal = SkipDigits(s);
799 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
800 s = EndDecimal;
801 radix = 10;
802 }
803 }
804
805 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
806 // the code is using an incorrect base.
807 if (isHexDigit(*s) && *s != 'e' && *s != 'E') {
808 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
809 diag::err_invalid_octal_digit) << StringRef(s, 1);
810 hadError = true;
811 return;
812 }
813
814 if (*s == '.') {
815 s++;
816 radix = 10;
817 saw_period = true;
818 s = SkipDigits(s); // Skip suffix.
819 }
820 if (*s == 'e' || *s == 'E') { // exponent
821 const char *Exponent = s;
822 s++;
823 radix = 10;
824 saw_exponent = true;
825 if (*s == '+' || *s == '-') s++; // sign
826 const char *first_non_digit = SkipDigits(s);
827 if (first_non_digit != s) {
828 s = first_non_digit;
829 } else {
830 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
831 diag::err_exponent_has_no_digits);
832 hadError = true;
833 return;
834 }
835 }
836 }
837
alwaysFitsInto64Bits(unsigned Radix,unsigned NumDigits)838 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
839 switch (Radix) {
840 case 2:
841 return NumDigits <= 64;
842 case 8:
843 return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
844 case 10:
845 return NumDigits <= 19; // floor(log10(2^64))
846 case 16:
847 return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
848 default:
849 llvm_unreachable("impossible Radix");
850 }
851 }
852
853 /// GetIntegerValue - Convert this numeric literal value to an APInt that
854 /// matches Val's input width. If there is an overflow, set Val to the low bits
855 /// of the result and return true. Otherwise, return false.
GetIntegerValue(llvm::APInt & Val)856 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
857 // Fast path: Compute a conservative bound on the maximum number of
858 // bits per digit in this radix. If we can't possibly overflow a
859 // uint64 based on that bound then do the simple conversion to
860 // integer. This avoids the expensive overflow checking below, and
861 // handles the common cases that matter (small decimal integers and
862 // hex/octal values which don't overflow).
863 const unsigned NumDigits = SuffixBegin - DigitsBegin;
864 if (alwaysFitsInto64Bits(radix, NumDigits)) {
865 uint64_t N = 0;
866 for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
867 if (!isDigitSeparator(*Ptr))
868 N = N * radix + llvm::hexDigitValue(*Ptr);
869
870 // This will truncate the value to Val's input width. Simply check
871 // for overflow by comparing.
872 Val = N;
873 return Val.getZExtValue() != N;
874 }
875
876 Val = 0;
877 const char *Ptr = DigitsBegin;
878
879 llvm::APInt RadixVal(Val.getBitWidth(), radix);
880 llvm::APInt CharVal(Val.getBitWidth(), 0);
881 llvm::APInt OldVal = Val;
882
883 bool OverflowOccurred = false;
884 while (Ptr < SuffixBegin) {
885 if (isDigitSeparator(*Ptr)) {
886 ++Ptr;
887 continue;
888 }
889
890 unsigned C = llvm::hexDigitValue(*Ptr++);
891
892 // If this letter is out of bound for this radix, reject it.
893 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
894
895 CharVal = C;
896
897 // Add the digit to the value in the appropriate radix. If adding in digits
898 // made the value smaller, then this overflowed.
899 OldVal = Val;
900
901 // Multiply by radix, did overflow occur on the multiply?
902 Val *= RadixVal;
903 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
904
905 // Add value, did overflow occur on the value?
906 // (a + b) ult b <=> overflow
907 Val += CharVal;
908 OverflowOccurred |= Val.ult(CharVal);
909 }
910 return OverflowOccurred;
911 }
912
913 llvm::APFloat::opStatus
GetFloatValue(llvm::APFloat & Result)914 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
915 using llvm::APFloat;
916
917 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
918
919 llvm::SmallString<16> Buffer;
920 StringRef Str(ThisTokBegin, n);
921 if (Str.find('\'') != StringRef::npos) {
922 Buffer.reserve(n);
923 std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
924 &isDigitSeparator);
925 Str = Buffer;
926 }
927
928 return Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
929 }
930
931
932 /// \verbatim
933 /// user-defined-character-literal: [C++11 lex.ext]
934 /// character-literal ud-suffix
935 /// ud-suffix:
936 /// identifier
937 /// character-literal: [C++11 lex.ccon]
938 /// ' c-char-sequence '
939 /// u' c-char-sequence '
940 /// U' c-char-sequence '
941 /// L' c-char-sequence '
942 /// c-char-sequence:
943 /// c-char
944 /// c-char-sequence c-char
945 /// c-char:
946 /// any member of the source character set except the single-quote ',
947 /// backslash \, or new-line character
948 /// escape-sequence
949 /// universal-character-name
950 /// escape-sequence:
951 /// simple-escape-sequence
952 /// octal-escape-sequence
953 /// hexadecimal-escape-sequence
954 /// simple-escape-sequence:
955 /// one of \' \" \? \\ \a \b \f \n \r \t \v
956 /// octal-escape-sequence:
957 /// \ octal-digit
958 /// \ octal-digit octal-digit
959 /// \ octal-digit octal-digit octal-digit
960 /// hexadecimal-escape-sequence:
961 /// \x hexadecimal-digit
962 /// hexadecimal-escape-sequence hexadecimal-digit
963 /// universal-character-name: [C++11 lex.charset]
964 /// \u hex-quad
965 /// \U hex-quad hex-quad
966 /// hex-quad:
967 /// hex-digit hex-digit hex-digit hex-digit
968 /// \endverbatim
969 ///
CharLiteralParser(const char * begin,const char * end,SourceLocation Loc,Preprocessor & PP,tok::TokenKind kind)970 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
971 SourceLocation Loc, Preprocessor &PP,
972 tok::TokenKind kind) {
973 // At this point we know that the character matches the regex "(L|u|U)?'.*'".
974 HadError = false;
975
976 Kind = kind;
977
978 const char *TokBegin = begin;
979
980 // Skip over wide character determinant.
981 if (Kind != tok::char_constant) {
982 ++begin;
983 }
984
985 // Skip over the entry quote.
986 assert(begin[0] == '\'' && "Invalid token lexed");
987 ++begin;
988
989 // Remove an optional ud-suffix.
990 if (end[-1] != '\'') {
991 const char *UDSuffixEnd = end;
992 do {
993 --end;
994 } while (end[-1] != '\'');
995 UDSuffixBuf.assign(end, UDSuffixEnd);
996 UDSuffixOffset = end - TokBegin;
997 }
998
999 // Trim the ending quote.
1000 assert(end != begin && "Invalid token lexed");
1001 --end;
1002
1003 // FIXME: The "Value" is an uint64_t so we can handle char literals of
1004 // up to 64-bits.
1005 // FIXME: This extensively assumes that 'char' is 8-bits.
1006 assert(PP.getTargetInfo().getCharWidth() == 8 &&
1007 "Assumes char is 8 bits");
1008 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1009 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1010 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1011 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1012 "Assumes sizeof(wchar) on target is <= 64");
1013
1014 SmallVector<uint32_t, 4> codepoint_buffer;
1015 codepoint_buffer.resize(end - begin);
1016 uint32_t *buffer_begin = &codepoint_buffer.front();
1017 uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1018
1019 // Unicode escapes representing characters that cannot be correctly
1020 // represented in a single code unit are disallowed in character literals
1021 // by this implementation.
1022 uint32_t largest_character_for_kind;
1023 if (tok::wide_char_constant == Kind) {
1024 largest_character_for_kind =
1025 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1026 } else if (tok::utf16_char_constant == Kind) {
1027 largest_character_for_kind = 0xFFFF;
1028 } else if (tok::utf32_char_constant == Kind) {
1029 largest_character_for_kind = 0x10FFFF;
1030 } else {
1031 largest_character_for_kind = 0x7Fu;
1032 }
1033
1034 while (begin != end) {
1035 // Is this a span of non-escape characters?
1036 if (begin[0] != '\\') {
1037 char const *start = begin;
1038 do {
1039 ++begin;
1040 } while (begin != end && *begin != '\\');
1041
1042 char const *tmp_in_start = start;
1043 uint32_t *tmp_out_start = buffer_begin;
1044 ConversionResult res =
1045 ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
1046 reinterpret_cast<UTF8 const *>(begin),
1047 &buffer_begin, buffer_end, strictConversion);
1048 if (res != conversionOK) {
1049 // If we see bad encoding for unprefixed character literals, warn and
1050 // simply copy the byte values, for compatibility with gcc and
1051 // older versions of clang.
1052 bool NoErrorOnBadEncoding = isAscii();
1053 unsigned Msg = diag::err_bad_character_encoding;
1054 if (NoErrorOnBadEncoding)
1055 Msg = diag::warn_bad_character_encoding;
1056 PP.Diag(Loc, Msg);
1057 if (NoErrorOnBadEncoding) {
1058 start = tmp_in_start;
1059 buffer_begin = tmp_out_start;
1060 for (; start != begin; ++start, ++buffer_begin)
1061 *buffer_begin = static_cast<uint8_t>(*start);
1062 } else {
1063 HadError = true;
1064 }
1065 } else {
1066 for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1067 if (*tmp_out_start > largest_character_for_kind) {
1068 HadError = true;
1069 PP.Diag(Loc, diag::err_character_too_large);
1070 }
1071 }
1072 }
1073
1074 continue;
1075 }
1076 // Is this a Universal Character Name escape?
1077 if (begin[1] == 'u' || begin[1] == 'U') {
1078 unsigned short UcnLen = 0;
1079 if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1080 FullSourceLoc(Loc, PP.getSourceManager()),
1081 &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1082 HadError = true;
1083 } else if (*buffer_begin > largest_character_for_kind) {
1084 HadError = true;
1085 PP.Diag(Loc, diag::err_character_too_large);
1086 }
1087
1088 ++buffer_begin;
1089 continue;
1090 }
1091 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1092 uint64_t result =
1093 ProcessCharEscape(TokBegin, begin, end, HadError,
1094 FullSourceLoc(Loc,PP.getSourceManager()),
1095 CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1096 *buffer_begin++ = result;
1097 }
1098
1099 unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1100
1101 if (NumCharsSoFar > 1) {
1102 if (isWide())
1103 PP.Diag(Loc, diag::warn_extraneous_char_constant);
1104 else if (isAscii() && NumCharsSoFar == 4)
1105 PP.Diag(Loc, diag::ext_four_char_character_literal);
1106 else if (isAscii())
1107 PP.Diag(Loc, diag::ext_multichar_character_literal);
1108 else
1109 PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1110 IsMultiChar = true;
1111 } else {
1112 IsMultiChar = false;
1113 }
1114
1115 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1116
1117 // Narrow character literals act as though their value is concatenated
1118 // in this implementation, but warn on overflow.
1119 bool multi_char_too_long = false;
1120 if (isAscii() && isMultiChar()) {
1121 LitVal = 0;
1122 for (size_t i = 0; i < NumCharsSoFar; ++i) {
1123 // check for enough leading zeros to shift into
1124 multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1125 LitVal <<= 8;
1126 LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1127 }
1128 } else if (NumCharsSoFar > 0) {
1129 // otherwise just take the last character
1130 LitVal = buffer_begin[-1];
1131 }
1132
1133 if (!HadError && multi_char_too_long) {
1134 PP.Diag(Loc, diag::warn_char_constant_too_large);
1135 }
1136
1137 // Transfer the value from APInt to uint64_t
1138 Value = LitVal.getZExtValue();
1139
1140 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1141 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
1142 // character constants are not sign extended in the this implementation:
1143 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1144 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1145 PP.getLangOpts().CharIsSigned)
1146 Value = (signed char)Value;
1147 }
1148
1149 /// \verbatim
1150 /// string-literal: [C++0x lex.string]
1151 /// encoding-prefix " [s-char-sequence] "
1152 /// encoding-prefix R raw-string
1153 /// encoding-prefix:
1154 /// u8
1155 /// u
1156 /// U
1157 /// L
1158 /// s-char-sequence:
1159 /// s-char
1160 /// s-char-sequence s-char
1161 /// s-char:
1162 /// any member of the source character set except the double-quote ",
1163 /// backslash \, or new-line character
1164 /// escape-sequence
1165 /// universal-character-name
1166 /// raw-string:
1167 /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
1168 /// r-char-sequence:
1169 /// r-char
1170 /// r-char-sequence r-char
1171 /// r-char:
1172 /// any member of the source character set, except a right parenthesis )
1173 /// followed by the initial d-char-sequence (which may be empty)
1174 /// followed by a double quote ".
1175 /// d-char-sequence:
1176 /// d-char
1177 /// d-char-sequence d-char
1178 /// d-char:
1179 /// any member of the basic source character set except:
1180 /// space, the left parenthesis (, the right parenthesis ),
1181 /// the backslash \, and the control characters representing horizontal
1182 /// tab, vertical tab, form feed, and newline.
1183 /// escape-sequence: [C++0x lex.ccon]
1184 /// simple-escape-sequence
1185 /// octal-escape-sequence
1186 /// hexadecimal-escape-sequence
1187 /// simple-escape-sequence:
1188 /// one of \' \" \? \\ \a \b \f \n \r \t \v
1189 /// octal-escape-sequence:
1190 /// \ octal-digit
1191 /// \ octal-digit octal-digit
1192 /// \ octal-digit octal-digit octal-digit
1193 /// hexadecimal-escape-sequence:
1194 /// \x hexadecimal-digit
1195 /// hexadecimal-escape-sequence hexadecimal-digit
1196 /// universal-character-name:
1197 /// \u hex-quad
1198 /// \U hex-quad hex-quad
1199 /// hex-quad:
1200 /// hex-digit hex-digit hex-digit hex-digit
1201 /// \endverbatim
1202 ///
1203 StringLiteralParser::
StringLiteralParser(const Token * StringToks,unsigned NumStringToks,Preprocessor & PP,bool Complain)1204 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
1205 Preprocessor &PP, bool Complain)
1206 : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1207 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
1208 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1209 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1210 init(StringToks, NumStringToks);
1211 }
1212
init(const Token * StringToks,unsigned NumStringToks)1213 void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
1214 // The literal token may have come from an invalid source location (e.g. due
1215 // to a PCH error), in which case the token length will be 0.
1216 if (NumStringToks == 0 || StringToks[0].getLength() < 2)
1217 return DiagnoseLexingError(SourceLocation());
1218
1219 // Scan all of the string portions, remember the max individual token length,
1220 // computing a bound on the concatenated string length, and see whether any
1221 // piece is a wide-string. If any of the string portions is a wide-string
1222 // literal, the result is a wide-string literal [C99 6.4.5p4].
1223 assert(NumStringToks && "expected at least one token");
1224 MaxTokenLength = StringToks[0].getLength();
1225 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1226 SizeBound = StringToks[0].getLength()-2; // -2 for "".
1227 Kind = StringToks[0].getKind();
1228
1229 hadError = false;
1230
1231 // Implement Translation Phase #6: concatenation of string literals
1232 /// (C99 5.1.1.2p1). The common case is only one string fragment.
1233 for (unsigned i = 1; i != NumStringToks; ++i) {
1234 if (StringToks[i].getLength() < 2)
1235 return DiagnoseLexingError(StringToks[i].getLocation());
1236
1237 // The string could be shorter than this if it needs cleaning, but this is a
1238 // reasonable bound, which is all we need.
1239 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1240 SizeBound += StringToks[i].getLength()-2; // -2 for "".
1241
1242 // Remember maximum string piece length.
1243 if (StringToks[i].getLength() > MaxTokenLength)
1244 MaxTokenLength = StringToks[i].getLength();
1245
1246 // Remember if we see any wide or utf-8/16/32 strings.
1247 // Also check for illegal concatenations.
1248 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1249 if (isAscii()) {
1250 Kind = StringToks[i].getKind();
1251 } else {
1252 if (Diags)
1253 Diags->Report(StringToks[i].getLocation(),
1254 diag::err_unsupported_string_concat);
1255 hadError = true;
1256 }
1257 }
1258 }
1259
1260 // Include space for the null terminator.
1261 ++SizeBound;
1262
1263 // TODO: K&R warning: "traditional C rejects string constant concatenation"
1264
1265 // Get the width in bytes of char/wchar_t/char16_t/char32_t
1266 CharByteWidth = getCharWidth(Kind, Target);
1267 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1268 CharByteWidth /= 8;
1269
1270 // The output buffer size needs to be large enough to hold wide characters.
1271 // This is a worst-case assumption which basically corresponds to L"" "long".
1272 SizeBound *= CharByteWidth;
1273
1274 // Size the temporary buffer to hold the result string data.
1275 ResultBuf.resize(SizeBound);
1276
1277 // Likewise, but for each string piece.
1278 SmallString<512> TokenBuf;
1279 TokenBuf.resize(MaxTokenLength);
1280
1281 // Loop over all the strings, getting their spelling, and expanding them to
1282 // wide strings as appropriate.
1283 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
1284
1285 Pascal = false;
1286
1287 SourceLocation UDSuffixTokLoc;
1288
1289 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
1290 const char *ThisTokBuf = &TokenBuf[0];
1291 // Get the spelling of the token, which eliminates trigraphs, etc. We know
1292 // that ThisTokBuf points to a buffer that is big enough for the whole token
1293 // and 'spelled' tokens can only shrink.
1294 bool StringInvalid = false;
1295 unsigned ThisTokLen =
1296 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1297 &StringInvalid);
1298 if (StringInvalid)
1299 return DiagnoseLexingError(StringToks[i].getLocation());
1300
1301 const char *ThisTokBegin = ThisTokBuf;
1302 const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1303
1304 // Remove an optional ud-suffix.
1305 if (ThisTokEnd[-1] != '"') {
1306 const char *UDSuffixEnd = ThisTokEnd;
1307 do {
1308 --ThisTokEnd;
1309 } while (ThisTokEnd[-1] != '"');
1310
1311 StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1312
1313 if (UDSuffixBuf.empty()) {
1314 UDSuffixBuf.assign(UDSuffix);
1315 UDSuffixToken = i;
1316 UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1317 UDSuffixTokLoc = StringToks[i].getLocation();
1318 } else if (!UDSuffixBuf.equals(UDSuffix)) {
1319 // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1320 // result of a concatenation involving at least one user-defined-string-
1321 // literal, all the participating user-defined-string-literals shall
1322 // have the same ud-suffix.
1323 if (Diags) {
1324 SourceLocation TokLoc = StringToks[i].getLocation();
1325 Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1326 << UDSuffixBuf << UDSuffix
1327 << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1328 << SourceRange(TokLoc, TokLoc);
1329 }
1330 hadError = true;
1331 }
1332 }
1333
1334 // Strip the end quote.
1335 --ThisTokEnd;
1336
1337 // TODO: Input character set mapping support.
1338
1339 // Skip marker for wide or unicode strings.
1340 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1341 ++ThisTokBuf;
1342 // Skip 8 of u8 marker for utf8 strings.
1343 if (ThisTokBuf[0] == '8')
1344 ++ThisTokBuf;
1345 }
1346
1347 // Check for raw string
1348 if (ThisTokBuf[0] == 'R') {
1349 ThisTokBuf += 2; // skip R"
1350
1351 const char *Prefix = ThisTokBuf;
1352 while (ThisTokBuf[0] != '(')
1353 ++ThisTokBuf;
1354 ++ThisTokBuf; // skip '('
1355
1356 // Remove same number of characters from the end
1357 ThisTokEnd -= ThisTokBuf - Prefix;
1358 assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1359
1360 // Copy the string over
1361 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1362 StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf)))
1363 hadError = true;
1364 } else {
1365 if (ThisTokBuf[0] != '"') {
1366 // The file may have come from PCH and then changed after loading the
1367 // PCH; Fail gracefully.
1368 return DiagnoseLexingError(StringToks[i].getLocation());
1369 }
1370 ++ThisTokBuf; // skip "
1371
1372 // Check if this is a pascal string
1373 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1374 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1375
1376 // If the \p sequence is found in the first token, we have a pascal string
1377 // Otherwise, if we already have a pascal string, ignore the first \p
1378 if (i == 0) {
1379 ++ThisTokBuf;
1380 Pascal = true;
1381 } else if (Pascal)
1382 ThisTokBuf += 2;
1383 }
1384
1385 while (ThisTokBuf != ThisTokEnd) {
1386 // Is this a span of non-escape characters?
1387 if (ThisTokBuf[0] != '\\') {
1388 const char *InStart = ThisTokBuf;
1389 do {
1390 ++ThisTokBuf;
1391 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1392
1393 // Copy the character span over.
1394 if (CopyStringFragment(StringToks[i], ThisTokBegin,
1395 StringRef(InStart, ThisTokBuf - InStart)))
1396 hadError = true;
1397 continue;
1398 }
1399 // Is this a Universal Character Name escape?
1400 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1401 EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1402 ResultPtr, hadError,
1403 FullSourceLoc(StringToks[i].getLocation(), SM),
1404 CharByteWidth, Diags, Features);
1405 continue;
1406 }
1407 // Otherwise, this is a non-UCN escape character. Process it.
1408 unsigned ResultChar =
1409 ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1410 FullSourceLoc(StringToks[i].getLocation(), SM),
1411 CharByteWidth*8, Diags, Features);
1412
1413 if (CharByteWidth == 4) {
1414 // FIXME: Make the type of the result buffer correct instead of
1415 // using reinterpret_cast.
1416 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr);
1417 *ResultWidePtr = ResultChar;
1418 ResultPtr += 4;
1419 } else if (CharByteWidth == 2) {
1420 // FIXME: Make the type of the result buffer correct instead of
1421 // using reinterpret_cast.
1422 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr);
1423 *ResultWidePtr = ResultChar & 0xFFFF;
1424 ResultPtr += 2;
1425 } else {
1426 assert(CharByteWidth == 1 && "Unexpected char width");
1427 *ResultPtr++ = ResultChar & 0xFF;
1428 }
1429 }
1430 }
1431 }
1432
1433 if (Pascal) {
1434 if (CharByteWidth == 4) {
1435 // FIXME: Make the type of the result buffer correct instead of
1436 // using reinterpret_cast.
1437 UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data());
1438 ResultWidePtr[0] = GetNumStringChars() - 1;
1439 } else if (CharByteWidth == 2) {
1440 // FIXME: Make the type of the result buffer correct instead of
1441 // using reinterpret_cast.
1442 UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data());
1443 ResultWidePtr[0] = GetNumStringChars() - 1;
1444 } else {
1445 assert(CharByteWidth == 1 && "Unexpected char width");
1446 ResultBuf[0] = GetNumStringChars() - 1;
1447 }
1448
1449 // Verify that pascal strings aren't too large.
1450 if (GetStringLength() > 256) {
1451 if (Diags)
1452 Diags->Report(StringToks[0].getLocation(),
1453 diag::err_pascal_string_too_long)
1454 << SourceRange(StringToks[0].getLocation(),
1455 StringToks[NumStringToks-1].getLocation());
1456 hadError = true;
1457 return;
1458 }
1459 } else if (Diags) {
1460 // Complain if this string literal has too many characters.
1461 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1462
1463 if (GetNumStringChars() > MaxChars)
1464 Diags->Report(StringToks[0].getLocation(),
1465 diag::ext_string_too_long)
1466 << GetNumStringChars() << MaxChars
1467 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1468 << SourceRange(StringToks[0].getLocation(),
1469 StringToks[NumStringToks-1].getLocation());
1470 }
1471 }
1472
resyncUTF8(const char * Err,const char * End)1473 static const char *resyncUTF8(const char *Err, const char *End) {
1474 if (Err == End)
1475 return End;
1476 End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err);
1477 while (++Err != End && (*Err & 0xC0) == 0x80)
1478 ;
1479 return Err;
1480 }
1481
1482 /// \brief This function copies from Fragment, which is a sequence of bytes
1483 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
1484 /// Performs widening for multi-byte characters.
CopyStringFragment(const Token & Tok,const char * TokBegin,StringRef Fragment)1485 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1486 const char *TokBegin,
1487 StringRef Fragment) {
1488 const UTF8 *ErrorPtrTmp;
1489 if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1490 return false;
1491
1492 // If we see bad encoding for unprefixed string literals, warn and
1493 // simply copy the byte values, for compatibility with gcc and older
1494 // versions of clang.
1495 bool NoErrorOnBadEncoding = isAscii();
1496 if (NoErrorOnBadEncoding) {
1497 memcpy(ResultPtr, Fragment.data(), Fragment.size());
1498 ResultPtr += Fragment.size();
1499 }
1500
1501 if (Diags) {
1502 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1503
1504 FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1505 const DiagnosticBuilder &Builder =
1506 Diag(Diags, Features, SourceLoc, TokBegin,
1507 ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1508 NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
1509 : diag::err_bad_string_encoding);
1510
1511 const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1512 StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1513
1514 // Decode into a dummy buffer.
1515 SmallString<512> Dummy;
1516 Dummy.reserve(Fragment.size() * CharByteWidth);
1517 char *Ptr = Dummy.data();
1518
1519 while (!Builder.hasMaxRanges() &&
1520 !ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1521 const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1522 NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1523 Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1524 ErrorPtr, NextStart);
1525 NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1526 }
1527 }
1528 return !NoErrorOnBadEncoding;
1529 }
1530
DiagnoseLexingError(SourceLocation Loc)1531 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1532 hadError = true;
1533 if (Diags)
1534 Diags->Report(Loc, diag::err_lexing_string);
1535 }
1536
1537 /// getOffsetOfStringByte - This function returns the offset of the
1538 /// specified byte of the string data represented by Token. This handles
1539 /// advancing over escape sequences in the string.
getOffsetOfStringByte(const Token & Tok,unsigned ByteNo) const1540 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1541 unsigned ByteNo) const {
1542 // Get the spelling of the token.
1543 SmallString<32> SpellingBuffer;
1544 SpellingBuffer.resize(Tok.getLength());
1545
1546 bool StringInvalid = false;
1547 const char *SpellingPtr = &SpellingBuffer[0];
1548 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1549 &StringInvalid);
1550 if (StringInvalid)
1551 return 0;
1552
1553 const char *SpellingStart = SpellingPtr;
1554 const char *SpellingEnd = SpellingPtr+TokLen;
1555
1556 // Handle UTF-8 strings just like narrow strings.
1557 if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
1558 SpellingPtr += 2;
1559
1560 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1561 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1562
1563 // For raw string literals, this is easy.
1564 if (SpellingPtr[0] == 'R') {
1565 assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1566 // Skip 'R"'.
1567 SpellingPtr += 2;
1568 while (*SpellingPtr != '(') {
1569 ++SpellingPtr;
1570 assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1571 }
1572 // Skip '('.
1573 ++SpellingPtr;
1574 return SpellingPtr - SpellingStart + ByteNo;
1575 }
1576
1577 // Skip over the leading quote
1578 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1579 ++SpellingPtr;
1580
1581 // Skip over bytes until we find the offset we're looking for.
1582 while (ByteNo) {
1583 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1584
1585 // Step over non-escapes simply.
1586 if (*SpellingPtr != '\\') {
1587 ++SpellingPtr;
1588 --ByteNo;
1589 continue;
1590 }
1591
1592 // Otherwise, this is an escape character. Advance over it.
1593 bool HadError = false;
1594 if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
1595 const char *EscapePtr = SpellingPtr;
1596 unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1597 1, Features, HadError);
1598 if (Len > ByteNo) {
1599 // ByteNo is somewhere within the escape sequence.
1600 SpellingPtr = EscapePtr;
1601 break;
1602 }
1603 ByteNo -= Len;
1604 } else {
1605 ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1606 FullSourceLoc(Tok.getLocation(), SM),
1607 CharByteWidth*8, Diags, Features);
1608 --ByteNo;
1609 }
1610 assert(!HadError && "This method isn't valid on erroneous strings");
1611 }
1612
1613 return SpellingPtr-SpellingStart;
1614 }
1615