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