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/Lex/Preprocessor.h"
17 #include "clang/Lex/LexDiagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "llvm/ADT/StringExtras.h"
20 using namespace clang;
21 
22 /// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
23 /// not valid.
24 static int HexDigitValue(char C) {
25   if (C >= '0' && C <= '9') return C-'0';
26   if (C >= 'a' && C <= 'f') return C-'a'+10;
27   if (C >= 'A' && C <= 'F') return C-'A'+10;
28   return -1;
29 }
30 
31 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
32 /// either a character or a string literal.
33 static unsigned ProcessCharEscape(const char *&ThisTokBuf,
34                                   const char *ThisTokEnd, bool &HadError,
35                                   SourceLocation Loc, bool IsWide,
36                                   Preprocessor &PP) {
37   // Skip the '\' char.
38   ++ThisTokBuf;
39 
40   // We know that this character can't be off the end of the buffer, because
41   // that would have been \", which would not have been the end of string.
42   unsigned ResultChar = *ThisTokBuf++;
43   switch (ResultChar) {
44   // These map to themselves.
45   case '\\': case '\'': case '"': case '?': break;
46 
47     // These have fixed mappings.
48   case 'a':
49     // TODO: K&R: the meaning of '\\a' is different in traditional C
50     ResultChar = 7;
51     break;
52   case 'b':
53     ResultChar = 8;
54     break;
55   case 'e':
56     PP.Diag(Loc, diag::ext_nonstandard_escape) << "e";
57     ResultChar = 27;
58     break;
59   case 'E':
60     PP.Diag(Loc, diag::ext_nonstandard_escape) << "E";
61     ResultChar = 27;
62     break;
63   case 'f':
64     ResultChar = 12;
65     break;
66   case 'n':
67     ResultChar = 10;
68     break;
69   case 'r':
70     ResultChar = 13;
71     break;
72   case 't':
73     ResultChar = 9;
74     break;
75   case 'v':
76     ResultChar = 11;
77     break;
78   case 'x': { // Hex escape.
79     ResultChar = 0;
80     if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
81       PP.Diag(Loc, diag::err_hex_escape_no_digits);
82       HadError = 1;
83       break;
84     }
85 
86     // Hex escapes are a maximal series of hex digits.
87     bool Overflow = false;
88     for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
89       int CharVal = HexDigitValue(ThisTokBuf[0]);
90       if (CharVal == -1) break;
91       // About to shift out a digit?
92       Overflow |= (ResultChar & 0xF0000000) ? true : false;
93       ResultChar <<= 4;
94       ResultChar |= CharVal;
95     }
96 
97     // See if any bits will be truncated when evaluated as a character.
98     unsigned CharWidth = IsWide
99                        ? PP.getTargetInfo().getWCharWidth()
100                        : PP.getTargetInfo().getCharWidth();
101 
102     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
103       Overflow = true;
104       ResultChar &= ~0U >> (32-CharWidth);
105     }
106 
107     // Check for overflow.
108     if (Overflow)   // Too many digits to fit in
109       PP.Diag(Loc, diag::warn_hex_escape_too_large);
110     break;
111   }
112   case '0': case '1': case '2': case '3':
113   case '4': case '5': case '6': case '7': {
114     // Octal escapes.
115     --ThisTokBuf;
116     ResultChar = 0;
117 
118     // Octal escapes are a series of octal digits with maximum length 3.
119     // "\0123" is a two digit sequence equal to "\012" "3".
120     unsigned NumDigits = 0;
121     do {
122       ResultChar <<= 3;
123       ResultChar |= *ThisTokBuf++ - '0';
124       ++NumDigits;
125     } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
126              ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
127 
128     // Check for overflow.  Reject '\777', but not L'\777'.
129     unsigned CharWidth = IsWide
130                        ? PP.getTargetInfo().getWCharWidth()
131                        : PP.getTargetInfo().getCharWidth();
132 
133     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
134       PP.Diag(Loc, diag::warn_octal_escape_too_large);
135       ResultChar &= ~0U >> (32-CharWidth);
136     }
137     break;
138   }
139 
140     // Otherwise, these are not valid escapes.
141   case '(': case '{': case '[': case '%':
142     // GCC accepts these as extensions.  We warn about them as such though.
143     PP.Diag(Loc, diag::ext_nonstandard_escape)
144       << std::string()+(char)ResultChar;
145     break;
146   default:
147     if (isgraph(ThisTokBuf[0]))
148       PP.Diag(Loc, diag::ext_unknown_escape) << std::string()+(char)ResultChar;
149     else
150       PP.Diag(Loc, diag::ext_unknown_escape) << "x"+llvm::utohexstr(ResultChar);
151     break;
152   }
153 
154   return ResultChar;
155 }
156 
157 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
158 /// convert the UTF32 to UTF8. This is a subroutine of StringLiteralParser.
159 /// When we decide to implement UCN's for character constants and identifiers,
160 /// we will likely rework our support for UCN's.
161 static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
162                              char *&ResultBuf, bool &HadError,
163                              SourceLocation Loc, bool IsWide, Preprocessor &PP)
164 {
165   // FIXME: Add a warning - UCN's are only valid in C++ & C99.
166   // FIXME: Handle wide strings.
167 
168   // Save the beginning of the string (for error diagnostics).
169   const char *ThisTokBegin = ThisTokBuf;
170 
171   // Skip the '\u' char's.
172   ThisTokBuf += 2;
173 
174   if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
175     PP.Diag(Loc, diag::err_ucn_escape_no_digits);
176     HadError = 1;
177     return;
178   }
179   typedef uint32_t UTF32;
180 
181   UTF32 UcnVal = 0;
182   unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
183   for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) {
184     int CharVal = HexDigitValue(ThisTokBuf[0]);
185     if (CharVal == -1) break;
186     UcnVal <<= 4;
187     UcnVal |= CharVal;
188   }
189   // If we didn't consume the proper number of digits, there is a problem.
190   if (UcnLen) {
191     PP.Diag(PP.AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin),
192             diag::err_ucn_escape_incomplete);
193     HadError = 1;
194     return;
195   }
196   // Check UCN constraints (C99 6.4.3p2).
197   if ((UcnVal < 0xa0 &&
198       (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
199       || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)
200       || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
201     PP.Diag(Loc, diag::err_ucn_escape_invalid);
202     HadError = 1;
203     return;
204   }
205   // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
206   // The conversion below was inspired by:
207   //   http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
208   // First, we determine how many bytes the result will require.
209   typedef uint8_t UTF8;
210 
211   unsigned short bytesToWrite = 0;
212   if (UcnVal < (UTF32)0x80)
213     bytesToWrite = 1;
214   else if (UcnVal < (UTF32)0x800)
215     bytesToWrite = 2;
216   else if (UcnVal < (UTF32)0x10000)
217     bytesToWrite = 3;
218   else
219     bytesToWrite = 4;
220 
221   const unsigned byteMask = 0xBF;
222   const unsigned byteMark = 0x80;
223 
224   // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
225   // into the first byte, depending on how many bytes follow.
226   static const UTF8 firstByteMark[5] = {
227     0x00, 0x00, 0xC0, 0xE0, 0xF0
228   };
229   // Finally, we write the bytes into ResultBuf.
230   ResultBuf += bytesToWrite;
231   switch (bytesToWrite) { // note: everything falls through.
232     case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
233     case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
234     case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
235     case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
236   }
237   // Update the buffer.
238   ResultBuf += bytesToWrite;
239 }
240 
241 
242 ///       integer-constant: [C99 6.4.4.1]
243 ///         decimal-constant integer-suffix
244 ///         octal-constant integer-suffix
245 ///         hexadecimal-constant integer-suffix
246 ///       decimal-constant:
247 ///         nonzero-digit
248 ///         decimal-constant digit
249 ///       octal-constant:
250 ///         0
251 ///         octal-constant octal-digit
252 ///       hexadecimal-constant:
253 ///         hexadecimal-prefix hexadecimal-digit
254 ///         hexadecimal-constant hexadecimal-digit
255 ///       hexadecimal-prefix: one of
256 ///         0x 0X
257 ///       integer-suffix:
258 ///         unsigned-suffix [long-suffix]
259 ///         unsigned-suffix [long-long-suffix]
260 ///         long-suffix [unsigned-suffix]
261 ///         long-long-suffix [unsigned-sufix]
262 ///       nonzero-digit:
263 ///         1 2 3 4 5 6 7 8 9
264 ///       octal-digit:
265 ///         0 1 2 3 4 5 6 7
266 ///       hexadecimal-digit:
267 ///         0 1 2 3 4 5 6 7 8 9
268 ///         a b c d e f
269 ///         A B C D E F
270 ///       unsigned-suffix: one of
271 ///         u U
272 ///       long-suffix: one of
273 ///         l L
274 ///       long-long-suffix: one of
275 ///         ll LL
276 ///
277 ///       floating-constant: [C99 6.4.4.2]
278 ///         TODO: add rules...
279 ///
280 NumericLiteralParser::
281 NumericLiteralParser(const char *begin, const char *end,
282                      SourceLocation TokLoc, Preprocessor &pp)
283   : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
284 
285   // This routine assumes that the range begin/end matches the regex for integer
286   // and FP constants (specifically, the 'pp-number' regex), and assumes that
287   // the byte at "*end" is both valid and not part of the regex.  Because of
288   // this, it doesn't have to check for 'overscan' in various places.
289   assert(!isalnum(*end) && *end != '.' && *end != '_' &&
290          "Lexer didn't maximally munch?");
291 
292   s = DigitsBegin = begin;
293   saw_exponent = false;
294   saw_period = false;
295   isLong = false;
296   isUnsigned = false;
297   isLongLong = false;
298   isFloat = false;
299   isImaginary = false;
300   hadError = false;
301 
302   if (*s == '0') { // parse radix
303     ParseNumberStartingWithZero(TokLoc);
304     if (hadError)
305       return;
306   } else { // the first digit is non-zero
307     radix = 10;
308     s = SkipDigits(s);
309     if (s == ThisTokEnd) {
310       // Done.
311     } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
312       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
313               diag::err_invalid_decimal_digit) << std::string(s, s+1);
314       hadError = true;
315       return;
316     } else if (*s == '.') {
317       s++;
318       saw_period = true;
319       s = SkipDigits(s);
320     }
321     if ((*s == 'e' || *s == 'E')) { // exponent
322       const char *Exponent = s;
323       s++;
324       saw_exponent = true;
325       if (*s == '+' || *s == '-')  s++; // sign
326       const char *first_non_digit = SkipDigits(s);
327       if (first_non_digit != s) {
328         s = first_non_digit;
329       } else {
330         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
331                 diag::err_exponent_has_no_digits);
332         hadError = true;
333         return;
334       }
335     }
336   }
337 
338   SuffixBegin = s;
339 
340   // Parse the suffix.  At this point we can classify whether we have an FP or
341   // integer constant.
342   bool isFPConstant = isFloatingLiteral();
343 
344   // Loop over all of the characters of the suffix.  If we see something bad,
345   // we break out of the loop.
346   for (; s != ThisTokEnd; ++s) {
347     switch (*s) {
348     case 'f':      // FP Suffix for "float"
349     case 'F':
350       if (!isFPConstant) break;  // Error for integer constant.
351       if (isFloat || isLong) break; // FF, LF invalid.
352       isFloat = true;
353       continue;  // Success.
354     case 'u':
355     case 'U':
356       if (isFPConstant) break;  // Error for floating constant.
357       if (isUnsigned) break;    // Cannot be repeated.
358       isUnsigned = true;
359       continue;  // Success.
360     case 'l':
361     case 'L':
362       if (isLong || isLongLong) break;  // Cannot be repeated.
363       if (isFloat) break;               // LF invalid.
364 
365       // Check for long long.  The L's need to be adjacent and the same case.
366       if (s+1 != ThisTokEnd && s[1] == s[0]) {
367         if (isFPConstant) break;        // long long invalid for floats.
368         isLongLong = true;
369         ++s;  // Eat both of them.
370       } else {
371         isLong = true;
372       }
373       continue;  // Success.
374     case 'i':
375       if (PP.getLangOptions().Microsoft) {
376         // Allow i8, i16, i32, i64, and i128.
377         if (++s == ThisTokEnd) break;
378         switch (*s) {
379           case '8':
380             s++; // i8 suffix
381             break;
382           case '1':
383             if (++s == ThisTokEnd) break;
384             if (*s == '6') s++; // i16 suffix
385             else if (*s == '2') {
386               if (++s == ThisTokEnd) break;
387               if (*s == '8') s++; // i128 suffix
388             }
389             break;
390           case '3':
391             if (++s == ThisTokEnd) break;
392             if (*s == '2') s++; // i32 suffix
393             break;
394           case '6':
395             if (++s == ThisTokEnd) break;
396             if (*s == '4') s++; // i64 suffix
397             break;
398           default:
399             break;
400         }
401         break;
402       }
403       // fall through.
404     case 'I':
405     case 'j':
406     case 'J':
407       if (isImaginary) break;   // Cannot be repeated.
408       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
409               diag::ext_imaginary_constant);
410       isImaginary = true;
411       continue;  // Success.
412     }
413     // If we reached here, there was an error.
414     break;
415   }
416 
417   // Report an error if there are any.
418   if (s != ThisTokEnd) {
419     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
420             isFPConstant ? diag::err_invalid_suffix_float_constant :
421                            diag::err_invalid_suffix_integer_constant)
422       << std::string(SuffixBegin, ThisTokEnd);
423     hadError = true;
424     return;
425   }
426 }
427 
428 /// ParseNumberStartingWithZero - This method is called when the first character
429 /// of the number is found to be a zero.  This means it is either an octal
430 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
431 /// a floating point number (01239.123e4).  Eat the prefix, determining the
432 /// radix etc.
433 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
434   assert(s[0] == '0' && "Invalid method call");
435   s++;
436 
437   // Handle a hex number like 0x1234.
438   if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
439     s++;
440     radix = 16;
441     DigitsBegin = s;
442     s = SkipHexDigits(s);
443     if (s == ThisTokEnd) {
444       // Done.
445     } else if (*s == '.') {
446       s++;
447       saw_period = true;
448       s = SkipHexDigits(s);
449     }
450     // A binary exponent can appear with or with a '.'. If dotted, the
451     // binary exponent is required.
452     if (*s == 'p' || *s == 'P') {
453       const char *Exponent = s;
454       s++;
455       saw_exponent = true;
456       if (*s == '+' || *s == '-')  s++; // sign
457       const char *first_non_digit = SkipDigits(s);
458       if (first_non_digit == s) {
459         PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
460                 diag::err_exponent_has_no_digits);
461         hadError = true;
462         return;
463       }
464       s = first_non_digit;
465 
466       if (!PP.getLangOptions().HexFloats)
467         PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
468     } else if (saw_period) {
469       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
470               diag::err_hexconstant_requires_exponent);
471       hadError = true;
472     }
473     return;
474   }
475 
476   // Handle simple binary numbers 0b01010
477   if (*s == 'b' || *s == 'B') {
478     // 0b101010 is a GCC extension.
479     PP.Diag(TokLoc, diag::ext_binary_literal);
480     ++s;
481     radix = 2;
482     DigitsBegin = s;
483     s = SkipBinaryDigits(s);
484     if (s == ThisTokEnd) {
485       // Done.
486     } else if (isxdigit(*s)) {
487       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
488               diag::err_invalid_binary_digit) << std::string(s, s+1);
489       hadError = true;
490     }
491     // Other suffixes will be diagnosed by the caller.
492     return;
493   }
494 
495   // For now, the radix is set to 8. If we discover that we have a
496   // floating point constant, the radix will change to 10. Octal floating
497   // point constants are not permitted (only decimal and hexadecimal).
498   radix = 8;
499   DigitsBegin = s;
500   s = SkipOctalDigits(s);
501   if (s == ThisTokEnd)
502     return; // Done, simple octal number like 01234
503 
504   // If we have some other non-octal digit that *is* a decimal digit, see if
505   // this is part of a floating point number like 094.123 or 09e1.
506   if (isdigit(*s)) {
507     const char *EndDecimal = SkipDigits(s);
508     if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
509       s = EndDecimal;
510       radix = 10;
511     }
512   }
513 
514   // If we have a hex digit other than 'e' (which denotes a FP exponent) then
515   // the code is using an incorrect base.
516   if (isxdigit(*s) && *s != 'e' && *s != 'E') {
517     PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
518             diag::err_invalid_octal_digit) << std::string(s, s+1);
519     hadError = true;
520     return;
521   }
522 
523   if (*s == '.') {
524     s++;
525     radix = 10;
526     saw_period = true;
527     s = SkipDigits(s); // Skip suffix.
528   }
529   if (*s == 'e' || *s == 'E') { // exponent
530     const char *Exponent = s;
531     s++;
532     radix = 10;
533     saw_exponent = true;
534     if (*s == '+' || *s == '-')  s++; // sign
535     const char *first_non_digit = SkipDigits(s);
536     if (first_non_digit != s) {
537       s = first_non_digit;
538     } else {
539       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
540               diag::err_exponent_has_no_digits);
541       hadError = true;
542       return;
543     }
544   }
545 }
546 
547 
548 /// GetIntegerValue - Convert this numeric literal value to an APInt that
549 /// matches Val's input width.  If there is an overflow, set Val to the low bits
550 /// of the result and return true.  Otherwise, return false.
551 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
552   // Fast path: Compute a conservative bound on the maximum number of
553   // bits per digit in this radix. If we can't possibly overflow a
554   // uint64 based on that bound then do the simple conversion to
555   // integer. This avoids the expensive overflow checking below, and
556   // handles the common cases that matter (small decimal integers and
557   // hex/octal values which don't overflow).
558   unsigned MaxBitsPerDigit = 1;
559   while ((1U << MaxBitsPerDigit) < radix)
560     MaxBitsPerDigit += 1;
561   if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
562     uint64_t N = 0;
563     for (s = DigitsBegin; s != SuffixBegin; ++s)
564       N = N*radix + HexDigitValue(*s);
565 
566     // This will truncate the value to Val's input width. Simply check
567     // for overflow by comparing.
568     Val = N;
569     return Val.getZExtValue() != N;
570   }
571 
572   Val = 0;
573   s = DigitsBegin;
574 
575   llvm::APInt RadixVal(Val.getBitWidth(), radix);
576   llvm::APInt CharVal(Val.getBitWidth(), 0);
577   llvm::APInt OldVal = Val;
578 
579   bool OverflowOccurred = false;
580   while (s < SuffixBegin) {
581     unsigned C = HexDigitValue(*s++);
582 
583     // If this letter is out of bound for this radix, reject it.
584     assert(C < radix && "NumericLiteralParser ctor should have rejected this");
585 
586     CharVal = C;
587 
588     // Add the digit to the value in the appropriate radix.  If adding in digits
589     // made the value smaller, then this overflowed.
590     OldVal = Val;
591 
592     // Multiply by radix, did overflow occur on the multiply?
593     Val *= RadixVal;
594     OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
595 
596     // Add value, did overflow occur on the value?
597     //   (a + b) ult b  <=> overflow
598     Val += CharVal;
599     OverflowOccurred |= Val.ult(CharVal);
600   }
601   return OverflowOccurred;
602 }
603 
604 llvm::APFloat NumericLiteralParser::
605 GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
606   using llvm::APFloat;
607 
608   llvm::SmallVector<char,256> floatChars;
609   for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
610     floatChars.push_back(ThisTokBegin[i]);
611 
612   floatChars.push_back('\0');
613 
614   APFloat V (Format, APFloat::fcZero, false);
615   APFloat::opStatus status;
616 
617   status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
618 
619   if (isExact)
620     *isExact = status == APFloat::opOK;
621 
622   return V;
623 }
624 
625 
626 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
627                                      SourceLocation Loc, Preprocessor &PP) {
628   // At this point we know that the character matches the regex "L?'.*'".
629   HadError = false;
630 
631   // Determine if this is a wide character.
632   IsWide = begin[0] == 'L';
633   if (IsWide) ++begin;
634 
635   // Skip over the entry quote.
636   assert(begin[0] == '\'' && "Invalid token lexed");
637   ++begin;
638 
639   // FIXME: The "Value" is an uint64_t so we can handle char literals of
640   // upto 64-bits.
641   // FIXME: This extensively assumes that 'char' is 8-bits.
642   assert(PP.getTargetInfo().getCharWidth() == 8 &&
643          "Assumes char is 8 bits");
644   assert(PP.getTargetInfo().getIntWidth() <= 64 &&
645          (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
646          "Assumes sizeof(int) on target is <= 64 and a multiple of char");
647   assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
648          "Assumes sizeof(wchar) on target is <= 64");
649 
650   // This is what we will use for overflow detection
651   llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
652 
653   unsigned NumCharsSoFar = 0;
654   while (begin[0] != '\'') {
655     uint64_t ResultChar;
656     if (begin[0] != '\\')     // If this is a normal character, consume it.
657       ResultChar = *begin++;
658     else                      // Otherwise, this is an escape character.
659       ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
660 
661     // If this is a multi-character constant (e.g. 'abc'), handle it.  These are
662     // implementation defined (C99 6.4.4.4p10).
663     if (NumCharsSoFar) {
664       if (IsWide) {
665         // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
666         LitVal = 0;
667       } else {
668         // Narrow character literals act as though their value is concatenated
669         // in this implementation, but warn on overflow.
670         if (LitVal.countLeadingZeros() < 8)
671           PP.Diag(Loc, diag::warn_char_constant_too_large);
672         LitVal <<= 8;
673       }
674     }
675 
676     LitVal = LitVal + ResultChar;
677     ++NumCharsSoFar;
678   }
679 
680   // If this is the second character being processed, do special handling.
681   if (NumCharsSoFar > 1) {
682     // Warn about discarding the top bits for multi-char wide-character
683     // constants (L'abcd').
684     if (IsWide)
685       PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
686     else if (NumCharsSoFar != 4)
687       PP.Diag(Loc, diag::ext_multichar_character_literal);
688     else
689       PP.Diag(Loc, diag::ext_four_char_character_literal);
690     IsMultiChar = true;
691   } else
692     IsMultiChar = false;
693 
694   // Transfer the value from APInt to uint64_t
695   Value = LitVal.getZExtValue();
696 
697   // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
698   // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
699   // character constants are not sign extended in the this implementation:
700   // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
701   if (!IsWide && NumCharsSoFar == 1 && (Value & 128) &&
702       PP.getLangOptions().CharIsSigned)
703     Value = (signed char)Value;
704 }
705 
706 
707 ///       string-literal: [C99 6.4.5]
708 ///          " [s-char-sequence] "
709 ///         L" [s-char-sequence] "
710 ///       s-char-sequence:
711 ///         s-char
712 ///         s-char-sequence s-char
713 ///       s-char:
714 ///         any source character except the double quote ",
715 ///           backslash \, or newline character
716 ///         escape-character
717 ///         universal-character-name
718 ///       escape-character: [C99 6.4.4.4]
719 ///         \ escape-code
720 ///         universal-character-name
721 ///       escape-code:
722 ///         character-escape-code
723 ///         octal-escape-code
724 ///         hex-escape-code
725 ///       character-escape-code: one of
726 ///         n t b r f v a
727 ///         \ ' " ?
728 ///       octal-escape-code:
729 ///         octal-digit
730 ///         octal-digit octal-digit
731 ///         octal-digit octal-digit octal-digit
732 ///       hex-escape-code:
733 ///         x hex-digit
734 ///         hex-escape-code hex-digit
735 ///       universal-character-name:
736 ///         \u hex-quad
737 ///         \U hex-quad hex-quad
738 ///       hex-quad:
739 ///         hex-digit hex-digit hex-digit hex-digit
740 ///
741 StringLiteralParser::
742 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
743                     Preprocessor &pp) : PP(pp) {
744   // Scan all of the string portions, remember the max individual token length,
745   // computing a bound on the concatenated string length, and see whether any
746   // piece is a wide-string.  If any of the string portions is a wide-string
747   // literal, the result is a wide-string literal [C99 6.4.5p4].
748   MaxTokenLength = StringToks[0].getLength();
749   SizeBound = StringToks[0].getLength()-2;  // -2 for "".
750   AnyWide = StringToks[0].is(tok::wide_string_literal);
751 
752   hadError = false;
753 
754   // Implement Translation Phase #6: concatenation of string literals
755   /// (C99 5.1.1.2p1).  The common case is only one string fragment.
756   for (unsigned i = 1; i != NumStringToks; ++i) {
757     // The string could be shorter than this if it needs cleaning, but this is a
758     // reasonable bound, which is all we need.
759     SizeBound += StringToks[i].getLength()-2;  // -2 for "".
760 
761     // Remember maximum string piece length.
762     if (StringToks[i].getLength() > MaxTokenLength)
763       MaxTokenLength = StringToks[i].getLength();
764 
765     // Remember if we see any wide strings.
766     AnyWide |= StringToks[i].is(tok::wide_string_literal);
767   }
768 
769   // Include space for the null terminator.
770   ++SizeBound;
771 
772   // TODO: K&R warning: "traditional C rejects string constant concatenation"
773 
774   // Get the width in bytes of wchar_t.  If no wchar_t strings are used, do not
775   // query the target.  As such, wchar_tByteWidth is only valid if AnyWide=true.
776   wchar_tByteWidth = ~0U;
777   if (AnyWide) {
778     wchar_tByteWidth = PP.getTargetInfo().getWCharWidth();
779     assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
780     wchar_tByteWidth /= 8;
781   }
782 
783   // The output buffer size needs to be large enough to hold wide characters.
784   // This is a worst-case assumption which basically corresponds to L"" "long".
785   if (AnyWide)
786     SizeBound *= wchar_tByteWidth;
787 
788   // Size the temporary buffer to hold the result string data.
789   ResultBuf.resize(SizeBound);
790 
791   // Likewise, but for each string piece.
792   llvm::SmallString<512> TokenBuf;
793   TokenBuf.resize(MaxTokenLength);
794 
795   // Loop over all the strings, getting their spelling, and expanding them to
796   // wide strings as appropriate.
797   ResultPtr = &ResultBuf[0];   // Next byte to fill in.
798 
799   Pascal = false;
800 
801   for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
802     const char *ThisTokBuf = &TokenBuf[0];
803     // Get the spelling of the token, which eliminates trigraphs, etc.  We know
804     // that ThisTokBuf points to a buffer that is big enough for the whole token
805     // and 'spelled' tokens can only shrink.
806     unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
807     const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1;  // Skip end quote.
808 
809     // TODO: Input character set mapping support.
810 
811     // Skip L marker for wide strings.
812     bool ThisIsWide = false;
813     if (ThisTokBuf[0] == 'L') {
814       ++ThisTokBuf;
815       ThisIsWide = true;
816     }
817 
818     assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
819     ++ThisTokBuf;
820 
821     // Check if this is a pascal string
822     if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
823         ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
824 
825       // If the \p sequence is found in the first token, we have a pascal string
826       // Otherwise, if we already have a pascal string, ignore the first \p
827       if (i == 0) {
828         ++ThisTokBuf;
829         Pascal = true;
830       } else if (Pascal)
831         ThisTokBuf += 2;
832     }
833 
834     while (ThisTokBuf != ThisTokEnd) {
835       // Is this a span of non-escape characters?
836       if (ThisTokBuf[0] != '\\') {
837         const char *InStart = ThisTokBuf;
838         do {
839           ++ThisTokBuf;
840         } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
841 
842         // Copy the character span over.
843         unsigned Len = ThisTokBuf-InStart;
844         if (!AnyWide) {
845           memcpy(ResultPtr, InStart, Len);
846           ResultPtr += Len;
847         } else {
848           // Note: our internal rep of wide char tokens is always little-endian.
849           for (; Len; --Len, ++InStart) {
850             *ResultPtr++ = InStart[0];
851             // Add zeros at the end.
852             for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
853               *ResultPtr++ = 0;
854           }
855         }
856         continue;
857       }
858       // Is this a Universal Character Name escape?
859       if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
860         ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
861                          hadError, StringToks[i].getLocation(), ThisIsWide, PP);
862         continue;
863       }
864       // Otherwise, this is a non-UCN escape character.  Process it.
865       unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
866                                               StringToks[i].getLocation(),
867                                               ThisIsWide, PP);
868 
869       // Note: our internal rep of wide char tokens is always little-endian.
870       *ResultPtr++ = ResultChar & 0xFF;
871 
872       if (AnyWide) {
873         for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
874           *ResultPtr++ = ResultChar >> i*8;
875       }
876     }
877   }
878 
879   if (Pascal) {
880     ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
881 
882     // Verify that pascal strings aren't too large.
883     if (GetStringLength() > 256) {
884       PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
885         << SourceRange(StringToks[0].getLocation(),
886                        StringToks[NumStringToks-1].getLocation());
887       hadError = 1;
888       return;
889     }
890   }
891 }
892 
893 
894 /// getOffsetOfStringByte - This function returns the offset of the
895 /// specified byte of the string data represented by Token.  This handles
896 /// advancing over escape sequences in the string.
897 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
898                                                     unsigned ByteNo,
899                                                     Preprocessor &PP) {
900   // Get the spelling of the token.
901   llvm::SmallString<16> SpellingBuffer;
902   SpellingBuffer.resize(Tok.getLength());
903 
904   const char *SpellingPtr = &SpellingBuffer[0];
905   unsigned TokLen = PP.getSpelling(Tok, SpellingPtr);
906 
907   assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet");
908 
909 
910   const char *SpellingStart = SpellingPtr;
911   const char *SpellingEnd = SpellingPtr+TokLen;
912 
913   // Skip over the leading quote.
914   assert(SpellingPtr[0] == '"' && "Should be a string literal!");
915   ++SpellingPtr;
916 
917   // Skip over bytes until we find the offset we're looking for.
918   while (ByteNo) {
919     assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
920 
921     // Step over non-escapes simply.
922     if (*SpellingPtr != '\\') {
923       ++SpellingPtr;
924       --ByteNo;
925       continue;
926     }
927 
928     // Otherwise, this is an escape character.  Advance over it.
929     bool HadError = false;
930     ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
931                       Tok.getLocation(), false, PP);
932     assert(!HadError && "This method isn't valid on erroneous strings");
933     --ByteNo;
934   }
935 
936   return SpellingPtr-SpellingStart;
937 }
938