blob: 5041a29419850f6efefb84198f25799f53128de1 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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/Basic/Diagnostic.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/TargetInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#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 'f':
61 ResultChar = 12;
62 break;
63 case 'n':
64 ResultChar = 10;
65 break;
66 case 'r':
67 ResultChar = 13;
68 break;
69 case 't':
70 ResultChar = 9;
71 break;
72 case 'v':
73 ResultChar = 11;
74 break;
75
76 //case 'u': case 'U': // FIXME: UCNs.
77 case 'x': { // Hex escape.
78 ResultChar = 0;
79 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
80 PP.Diag(Loc, diag::err_hex_escape_no_digits);
81 HadError = 1;
82 break;
83 }
84
85 // Hex escapes are a maximal series of hex digits.
86 bool Overflow = false;
87 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
88 int CharVal = HexDigitValue(ThisTokBuf[0]);
89 if (CharVal == -1) break;
Chris Lattnerc75ccff2007-09-03 18:28:41 +000090 Overflow |= (ResultChar & 0xF0000000) ? true : false; // About to shift out a digit?
Chris Lattner4b009652007-07-25 00:24:17 +000091 ResultChar <<= 4;
92 ResultChar |= CharVal;
93 }
94
95 // See if any bits will be truncated when evaluated as a character.
Chris Lattner8cd0e932008-03-05 18:54:05 +000096 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000097
Chris Lattner4b009652007-07-25 00:24:17 +000098 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
99 Overflow = true;
100 ResultChar &= ~0U >> (32-CharWidth);
101 }
102
103 // Check for overflow.
104 if (Overflow) // Too many digits to fit in
105 PP.Diag(Loc, diag::warn_hex_escape_too_large);
106 break;
107 }
108 case '0': case '1': case '2': case '3':
109 case '4': case '5': case '6': case '7': {
110 // Octal escapes.
111 --ThisTokBuf;
112 ResultChar = 0;
113
114 // Octal escapes are a series of octal digits with maximum length 3.
115 // "\0123" is a two digit sequence equal to "\012" "3".
116 unsigned NumDigits = 0;
117 do {
118 ResultChar <<= 3;
119 ResultChar |= *ThisTokBuf++ - '0';
120 ++NumDigits;
121 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
122 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
123
124 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000125 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000126
Chris Lattner4b009652007-07-25 00:24:17 +0000127 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
128 PP.Diag(Loc, diag::warn_octal_escape_too_large);
129 ResultChar &= ~0U >> (32-CharWidth);
130 }
131 break;
132 }
133
134 // Otherwise, these are not valid escapes.
135 case '(': case '{': case '[': case '%':
136 // GCC accepts these as extensions. We warn about them as such though.
137 if (!PP.getLangOptions().NoExtensions) {
138 PP.Diag(Loc, diag::ext_nonstandard_escape,
139 std::string()+(char)ResultChar);
140 break;
141 }
142 // FALL THROUGH.
143 default:
144 if (isgraph(ThisTokBuf[0])) {
145 PP.Diag(Loc, diag::ext_unknown_escape, std::string()+(char)ResultChar);
146 } else {
147 PP.Diag(Loc, diag::ext_unknown_escape, "x"+llvm::utohexstr(ResultChar));
148 }
149 break;
150 }
151
152 return ResultChar;
153}
154
155
156
157
158/// integer-constant: [C99 6.4.4.1]
159/// decimal-constant integer-suffix
160/// octal-constant integer-suffix
161/// hexadecimal-constant integer-suffix
162/// decimal-constant:
163/// nonzero-digit
164/// decimal-constant digit
165/// octal-constant:
166/// 0
167/// octal-constant octal-digit
168/// hexadecimal-constant:
169/// hexadecimal-prefix hexadecimal-digit
170/// hexadecimal-constant hexadecimal-digit
171/// hexadecimal-prefix: one of
172/// 0x 0X
173/// integer-suffix:
174/// unsigned-suffix [long-suffix]
175/// unsigned-suffix [long-long-suffix]
176/// long-suffix [unsigned-suffix]
177/// long-long-suffix [unsigned-sufix]
178/// nonzero-digit:
179/// 1 2 3 4 5 6 7 8 9
180/// octal-digit:
181/// 0 1 2 3 4 5 6 7
182/// hexadecimal-digit:
183/// 0 1 2 3 4 5 6 7 8 9
184/// a b c d e f
185/// A B C D E F
186/// unsigned-suffix: one of
187/// u U
188/// long-suffix: one of
189/// l L
190/// long-long-suffix: one of
191/// ll LL
192///
193/// floating-constant: [C99 6.4.4.2]
194/// TODO: add rules...
195///
Chris Lattner4b009652007-07-25 00:24:17 +0000196NumericLiteralParser::
197NumericLiteralParser(const char *begin, const char *end,
198 SourceLocation TokLoc, Preprocessor &pp)
199 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
200 s = DigitsBegin = begin;
201 saw_exponent = false;
202 saw_period = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000203 isLong = false;
204 isUnsigned = false;
205 isLongLong = false;
Chris Lattnerc04a0bd2007-08-26 03:29:23 +0000206 isFloat = false;
Chris Lattnerae71e482007-08-26 01:58:14 +0000207 isImaginary = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000208 hadError = false;
209
210 if (*s == '0') { // parse radix
Chris Lattnerca8dbca2008-06-30 06:39:54 +0000211 ParseNumberStartingWithZero(TokLoc);
212 if (hadError)
213 return;
Chris Lattner4b009652007-07-25 00:24:17 +0000214 } else { // the first digit is non-zero
215 radix = 10;
216 s = SkipDigits(s);
217 if (s == ThisTokEnd) {
218 // Done.
Christopher Lambd763e3f2007-11-29 06:06:27 +0000219 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattner40f43dd2008-04-20 18:41:46 +0000220 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
221 diag::err_invalid_decimal_digit, std::string(s, s+1));
Chris Lattner4b009652007-07-25 00:24:17 +0000222 return;
223 } else if (*s == '.') {
224 s++;
225 saw_period = true;
226 s = SkipDigits(s);
227 }
228 if (*s == 'e' || *s == 'E') { // exponent
Chris Lattner68c3db92008-04-20 18:47:55 +0000229 const char *Exponent = s;
Chris Lattner4b009652007-07-25 00:24:17 +0000230 s++;
231 saw_exponent = true;
232 if (*s == '+' || *s == '-') s++; // sign
233 const char *first_non_digit = SkipDigits(s);
Chris Lattner40f43dd2008-04-20 18:41:46 +0000234 if (first_non_digit != s) {
Chris Lattner4b009652007-07-25 00:24:17 +0000235 s = first_non_digit;
Chris Lattner40f43dd2008-04-20 18:41:46 +0000236 } else {
Chris Lattner68c3db92008-04-20 18:47:55 +0000237 Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
Chris Lattner40f43dd2008-04-20 18:41:46 +0000238 diag::err_exponent_has_no_digits);
239 return;
Chris Lattner4b009652007-07-25 00:24:17 +0000240 }
241 }
242 }
243
244 SuffixBegin = s;
Chris Lattnerae71e482007-08-26 01:58:14 +0000245
246 // Parse the suffix. At this point we can classify whether we have an FP or
247 // integer constant.
248 bool isFPConstant = isFloatingLiteral();
249
250 // Loop over all of the characters of the suffix. If we see something bad,
251 // we break out of the loop.
252 for (; s != ThisTokEnd; ++s) {
253 switch (*s) {
254 case 'f': // FP Suffix for "float"
255 case 'F':
256 if (!isFPConstant) break; // Error for integer constant.
Chris Lattnerc04a0bd2007-08-26 03:29:23 +0000257 if (isFloat || isLong) break; // FF, LF invalid.
258 isFloat = true;
Chris Lattnerae71e482007-08-26 01:58:14 +0000259 continue; // Success.
260 case 'u':
261 case 'U':
262 if (isFPConstant) break; // Error for floating constant.
263 if (isUnsigned) break; // Cannot be repeated.
264 isUnsigned = true;
265 continue; // Success.
266 case 'l':
267 case 'L':
268 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattnerc04a0bd2007-08-26 03:29:23 +0000269 if (isFloat) break; // LF invalid.
Chris Lattnerae71e482007-08-26 01:58:14 +0000270
271 // Check for long long. The L's need to be adjacent and the same case.
272 if (s+1 != ThisTokEnd && s[1] == s[0]) {
273 if (isFPConstant) break; // long long invalid for floats.
274 isLongLong = true;
275 ++s; // Eat both of them.
276 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000277 isLong = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000278 }
Chris Lattnerae71e482007-08-26 01:58:14 +0000279 continue; // Success.
280 case 'i':
Steve Naroffc6e7fef2008-04-04 21:02:54 +0000281 if (PP.getLangOptions().Microsoft) {
282 // Allow i8, i16, i32, i64, and i128.
283 if (++s == ThisTokEnd) break;
284 switch (*s) {
285 case '8':
286 s++; // i8 suffix
287 break;
288 case '1':
289 if (++s == ThisTokEnd) break;
290 if (*s == '6') s++; // i16 suffix
291 else if (*s == '2') {
292 if (++s == ThisTokEnd) break;
293 if (*s == '8') s++; // i128 suffix
294 }
295 break;
296 case '3':
297 if (++s == ThisTokEnd) break;
298 if (*s == '2') s++; // i32 suffix
299 break;
300 case '6':
301 if (++s == ThisTokEnd) break;
302 if (*s == '4') s++; // i64 suffix
303 break;
304 default:
305 break;
306 }
307 break;
308 }
309 // fall through.
Chris Lattnerae71e482007-08-26 01:58:14 +0000310 case 'I':
311 case 'j':
312 case 'J':
313 if (isImaginary) break; // Cannot be repeated.
314 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
315 diag::ext_imaginary_constant);
316 isImaginary = true;
317 continue; // Success.
Chris Lattner4b009652007-07-25 00:24:17 +0000318 }
Chris Lattnerae71e482007-08-26 01:58:14 +0000319 // If we reached here, there was an error.
320 break;
321 }
322
323 // Report an error if there are any.
324 if (s != ThisTokEnd) {
Chris Lattner40f43dd2008-04-20 18:41:46 +0000325 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
326 isFPConstant ? diag::err_invalid_suffix_float_constant :
327 diag::err_invalid_suffix_integer_constant,
Chris Lattnerae71e482007-08-26 01:58:14 +0000328 std::string(SuffixBegin, ThisTokEnd));
329 return;
Chris Lattner4b009652007-07-25 00:24:17 +0000330 }
331}
332
Chris Lattnerca8dbca2008-06-30 06:39:54 +0000333/// ParseNumberStartingWithZero - This method is called when the first character
334/// of the number is found to be a zero. This means it is either an octal
335/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
336/// a floating point number (01239.123e4). Eat the prefix, determining the
337/// radix etc.
338void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
339 assert(s[0] == '0' && "Invalid method call");
340 s++;
341
342 // Handle a hex number like 0x1234.
343 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
344 s++;
345 radix = 16;
346 DigitsBegin = s;
347 s = SkipHexDigits(s);
348 if (s == ThisTokEnd) {
349 // Done.
350 } else if (*s == '.') {
351 s++;
352 saw_period = true;
353 s = SkipHexDigits(s);
354 }
355 // A binary exponent can appear with or with a '.'. If dotted, the
356 // binary exponent is required.
357 if ((*s == 'p' || *s == 'P') && PP.getLangOptions().HexFloats) {
358 const char *Exponent = s;
359 s++;
360 saw_exponent = true;
361 if (*s == '+' || *s == '-') s++; // sign
362 const char *first_non_digit = SkipDigits(s);
363 if (first_non_digit != s) {
364 s = first_non_digit;
365 } else {
366 Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
367 diag::err_exponent_has_no_digits);
368 }
369 } else if (saw_period) {
370 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
371 diag::err_hexconstant_requires_exponent);
372 }
373 return;
374 }
375
376 // Handle simple binary numbers 0b01010
377 if (*s == 'b' || *s == 'B') {
378 // 0b101010 is a GCC extension.
379 ++s;
380 radix = 2;
381 DigitsBegin = s;
382 s = SkipBinaryDigits(s);
383 if (s == ThisTokEnd) {
384 // Done.
385 } else if (isxdigit(*s)) {
386 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
387 diag::err_invalid_binary_digit, std::string(s, s+1));
388 return;
389 }
390 // Otherwise suffixes will be diagnosed by the caller.
391 PP.Diag(TokLoc, diag::ext_binary_literal);
392 return;
393 }
394
395 // For now, the radix is set to 8. If we discover that we have a
396 // floating point constant, the radix will change to 10. Octal floating
397 // point constants are not permitted (only decimal and hexadecimal).
398 radix = 8;
399 DigitsBegin = s;
400 s = SkipOctalDigits(s);
401 if (s == ThisTokEnd)
402 return; // Done, simple octal number like 01234
403
404 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
405 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
406 diag::err_invalid_octal_digit, std::string(s, s+1));
407 return;
408 }
409
410 if (*s == '.') {
411 s++;
412 radix = 10;
413 saw_period = true;
414 s = SkipDigits(s);
415 }
416 if (*s == 'e' || *s == 'E') { // exponent
417 const char *Exponent = s;
418 s++;
419 radix = 10;
420 saw_exponent = true;
421 if (*s == '+' || *s == '-') s++; // sign
422 const char *first_non_digit = SkipDigits(s);
423 if (first_non_digit != s) {
424 s = first_non_digit;
425 } else {
426 Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
427 diag::err_exponent_has_no_digits);
428 return;
429 }
430 }
431}
432
433
Chris Lattner4b009652007-07-25 00:24:17 +0000434/// GetIntegerValue - Convert this numeric literal value to an APInt that
435/// matches Val's input width. If there is an overflow, set Val to the low bits
436/// of the result and return true. Otherwise, return false.
437bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
438 Val = 0;
439 s = DigitsBegin;
440
441 llvm::APInt RadixVal(Val.getBitWidth(), radix);
442 llvm::APInt CharVal(Val.getBitWidth(), 0);
443 llvm::APInt OldVal = Val;
444
445 bool OverflowOccurred = false;
446 while (s < SuffixBegin) {
447 unsigned C = HexDigitValue(*s++);
448
449 // If this letter is out of bound for this radix, reject it.
450 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
451
452 CharVal = C;
453
454 // Add the digit to the value in the appropriate radix. If adding in digits
455 // made the value smaller, then this overflowed.
456 OldVal = Val;
457
458 // Multiply by radix, did overflow occur on the multiply?
459 Val *= RadixVal;
460 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
461
462 OldVal = Val;
463 // Add value, did overflow occur on the value?
464 Val += CharVal;
465 OverflowOccurred |= Val.ult(OldVal);
466 OverflowOccurred |= Val.ult(CharVal);
467 }
468 return OverflowOccurred;
469}
470
Chris Lattner858eece2007-09-22 18:29:59 +0000471llvm::APFloat NumericLiteralParser::
Ted Kremenekfc2ebeb2007-11-26 23:12:30 +0000472GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
473 using llvm::APFloat;
474
Ted Kremenekf2dbd2b2007-11-29 00:54:29 +0000475 llvm::SmallVector<char,256> floatChars;
476 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
477 floatChars.push_back(ThisTokBegin[i]);
478
479 floatChars.push_back('\0');
480
Ted Kremenekfc2ebeb2007-11-26 23:12:30 +0000481 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenekfc2ebeb2007-11-26 23:12:30 +0000482 APFloat::opStatus status;
Ted Kremenekf2dbd2b2007-11-29 00:54:29 +0000483
484 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
Ted Kremenekfc2ebeb2007-11-26 23:12:30 +0000485
486 if (isExact)
487 *isExact = status == APFloat::opOK;
488
489 return V;
Chris Lattner4b009652007-07-25 00:24:17 +0000490}
491
492void NumericLiteralParser::Diag(SourceLocation Loc, unsigned DiagID,
493 const std::string &M) {
494 PP.Diag(Loc, DiagID, M);
495 hadError = true;
496}
497
498
499CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
500 SourceLocation Loc, Preprocessor &PP) {
501 // At this point we know that the character matches the regex "L?'.*'".
502 HadError = false;
503 Value = 0;
504
505 // Determine if this is a wide character.
506 IsWide = begin[0] == 'L';
507 if (IsWide) ++begin;
508
509 // Skip over the entry quote.
510 assert(begin[0] == '\'' && "Invalid token lexed");
511 ++begin;
512
513 // FIXME: This assumes that 'int' is 32-bits in overflow calculation, and the
514 // size of "value".
Chris Lattner8cd0e932008-03-05 18:54:05 +0000515 assert(PP.getTargetInfo().getIntWidth() == 32 &&
Chris Lattner4b009652007-07-25 00:24:17 +0000516 "Assumes sizeof(int) == 4 for now");
517 // FIXME: This assumes that wchar_t is 32-bits for now.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000518 assert(PP.getTargetInfo().getWCharWidth() == 32 &&
Chris Lattner4b009652007-07-25 00:24:17 +0000519 "Assumes sizeof(wchar_t) == 4 for now");
520 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000521 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Chris Lattner4b009652007-07-25 00:24:17 +0000522 "Assumes char is 8 bits");
523
524 bool isFirstChar = true;
525 bool isMultiChar = false;
526 while (begin[0] != '\'') {
527 unsigned ResultChar;
528 if (begin[0] != '\\') // If this is a normal character, consume it.
529 ResultChar = *begin++;
530 else // Otherwise, this is an escape character.
531 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
532
533 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
534 // implementation defined (C99 6.4.4.4p10).
535 if (!isFirstChar) {
536 // If this is the second character being processed, do special handling.
537 if (!isMultiChar) {
538 isMultiChar = true;
539
540 // Warn about discarding the top bits for multi-char wide-character
541 // constants (L'abcd').
542 if (IsWide)
543 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
544 }
545
546 if (IsWide) {
547 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
548 Value = 0;
549 } else {
550 // Narrow character literals act as though their value is concatenated
551 // in this implementation.
552 if (((Value << 8) >> 8) != Value)
553 PP.Diag(Loc, diag::warn_char_constant_too_large);
554 Value <<= 8;
555 }
556 }
557
558 Value += ResultChar;
559 isFirstChar = false;
560 }
561
562 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
563 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
564 // character constants are not sign extended in the this implementation:
565 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
566 if (!IsWide && !isMultiChar && (Value & 128) &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000567 PP.getTargetInfo().isCharSigned())
Chris Lattner4b009652007-07-25 00:24:17 +0000568 Value = (signed char)Value;
569}
570
571
572/// string-literal: [C99 6.4.5]
573/// " [s-char-sequence] "
574/// L" [s-char-sequence] "
575/// s-char-sequence:
576/// s-char
577/// s-char-sequence s-char
578/// s-char:
579/// any source character except the double quote ",
580/// backslash \, or newline character
581/// escape-character
582/// universal-character-name
583/// escape-character: [C99 6.4.4.4]
584/// \ escape-code
585/// universal-character-name
586/// escape-code:
587/// character-escape-code
588/// octal-escape-code
589/// hex-escape-code
590/// character-escape-code: one of
591/// n t b r f v a
592/// \ ' " ?
593/// octal-escape-code:
594/// octal-digit
595/// octal-digit octal-digit
596/// octal-digit octal-digit octal-digit
597/// hex-escape-code:
598/// x hex-digit
599/// hex-escape-code hex-digit
600/// universal-character-name:
601/// \u hex-quad
602/// \U hex-quad hex-quad
603/// hex-quad:
604/// hex-digit hex-digit hex-digit hex-digit
605///
606StringLiteralParser::
607StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
608 Preprocessor &pp, TargetInfo &t)
609 : PP(pp), Target(t) {
610 // Scan all of the string portions, remember the max individual token length,
611 // computing a bound on the concatenated string length, and see whether any
612 // piece is a wide-string. If any of the string portions is a wide-string
613 // literal, the result is a wide-string literal [C99 6.4.5p4].
614 MaxTokenLength = StringToks[0].getLength();
615 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000616 AnyWide = StringToks[0].is(tok::wide_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000617
618 hadError = false;
619
620 // Implement Translation Phase #6: concatenation of string literals
621 /// (C99 5.1.1.2p1). The common case is only one string fragment.
622 for (unsigned i = 1; i != NumStringToks; ++i) {
623 // The string could be shorter than this if it needs cleaning, but this is a
624 // reasonable bound, which is all we need.
625 SizeBound += StringToks[i].getLength()-2; // -2 for "".
626
627 // Remember maximum string piece length.
628 if (StringToks[i].getLength() > MaxTokenLength)
629 MaxTokenLength = StringToks[i].getLength();
630
631 // Remember if we see any wide strings.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000632 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Chris Lattner4b009652007-07-25 00:24:17 +0000633 }
634
635
636 // Include space for the null terminator.
637 ++SizeBound;
638
639 // TODO: K&R warning: "traditional C rejects string constant concatenation"
640
641 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
642 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
643 wchar_tByteWidth = ~0U;
644 if (AnyWide) {
Chris Lattner8cd0e932008-03-05 18:54:05 +0000645 wchar_tByteWidth = Target.getWCharWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000646 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
647 wchar_tByteWidth /= 8;
648 }
649
650 // The output buffer size needs to be large enough to hold wide characters.
651 // This is a worst-case assumption which basically corresponds to L"" "long".
652 if (AnyWide)
653 SizeBound *= wchar_tByteWidth;
654
655 // Size the temporary buffer to hold the result string data.
656 ResultBuf.resize(SizeBound);
657
658 // Likewise, but for each string piece.
659 llvm::SmallString<512> TokenBuf;
660 TokenBuf.resize(MaxTokenLength);
661
662 // Loop over all the strings, getting their spelling, and expanding them to
663 // wide strings as appropriate.
664 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
665
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000666 Pascal = false;
667
Chris Lattner4b009652007-07-25 00:24:17 +0000668 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
669 const char *ThisTokBuf = &TokenBuf[0];
670 // Get the spelling of the token, which eliminates trigraphs, etc. We know
671 // that ThisTokBuf points to a buffer that is big enough for the whole token
672 // and 'spelled' tokens can only shrink.
673 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
674 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
675
676 // TODO: Input character set mapping support.
677
678 // Skip L marker for wide strings.
679 bool ThisIsWide = false;
680 if (ThisTokBuf[0] == 'L') {
681 ++ThisTokBuf;
682 ThisIsWide = true;
683 }
684
685 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
686 ++ThisTokBuf;
687
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000688 // Check if this is a pascal string
689 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
690 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
691
692 // If the \p sequence is found in the first token, we have a pascal string
693 // Otherwise, if we already have a pascal string, ignore the first \p
694 if (i == 0) {
695 ++ThisTokBuf;
696 Pascal = true;
697 } else if (Pascal)
698 ThisTokBuf += 2;
699 }
700
Chris Lattner4b009652007-07-25 00:24:17 +0000701 while (ThisTokBuf != ThisTokEnd) {
702 // Is this a span of non-escape characters?
703 if (ThisTokBuf[0] != '\\') {
704 const char *InStart = ThisTokBuf;
705 do {
706 ++ThisTokBuf;
707 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
708
709 // Copy the character span over.
710 unsigned Len = ThisTokBuf-InStart;
711 if (!AnyWide) {
712 memcpy(ResultPtr, InStart, Len);
713 ResultPtr += Len;
714 } else {
715 // Note: our internal rep of wide char tokens is always little-endian.
716 for (; Len; --Len, ++InStart) {
717 *ResultPtr++ = InStart[0];
718 // Add zeros at the end.
719 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
720 *ResultPtr++ = 0;
721 }
722 }
723 continue;
724 }
725
726 // Otherwise, this is an escape character. Process it.
727 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
728 StringToks[i].getLocation(),
729 ThisIsWide, PP);
730
731 // Note: our internal rep of wide char tokens is always little-endian.
732 *ResultPtr++ = ResultChar & 0xFF;
733
734 if (AnyWide) {
735 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
736 *ResultPtr++ = ResultChar >> i*8;
737 }
738 }
739 }
740
741 // Add zero terminator.
742 *ResultPtr = 0;
743 if (AnyWide) {
744 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
745 *ResultPtr++ = 0;
746 }
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000747
748 if (Pascal)
749 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Chris Lattner4b009652007-07-25 00:24:17 +0000750}