blob: 1b86ba5def85f8741b3700661eb434f8071dd46e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/Diagnostic.h"
Chris Lattner136f93a2007-07-16 06:55:01 +000018#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/ADT/StringExtras.h"
20using namespace clang;
21
22/// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
23/// not valid.
24static 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.
33static 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 'f':
60 ResultChar = 12;
61 break;
62 case 'n':
63 ResultChar = 10;
64 break;
65 case 'r':
66 ResultChar = 13;
67 break;
68 case 't':
69 ResultChar = 9;
70 break;
71 case 'v':
72 ResultChar = 11;
73 break;
74
75 //case 'u': case 'U': // FIXME: UCNs.
76 case 'x': { // Hex escape.
77 ResultChar = 0;
78 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
79 PP.Diag(Loc, diag::err_hex_escape_no_digits);
80 HadError = 1;
81 break;
82 }
83
84 // Hex escapes are a maximal series of hex digits.
85 bool Overflow = false;
86 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
87 int CharVal = HexDigitValue(ThisTokBuf[0]);
88 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +000089 // About to shift out a digit?
90 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +000091 ResultChar <<= 4;
92 ResultChar |= CharVal;
93 }
94
95 // See if any bits will be truncated when evaluated as a character.
Chris Lattner98be4942008-03-05 18:54:05 +000096 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide);
Ted Kremenek9c728dc2007-12-12 22:39:36 +000097
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner98be4942008-03-05 18:54:05 +0000125 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide);
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000126
Reid Spencer5f016e22007-07-11 17:01:13 +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///
Reid Spencer5f016e22007-07-11 17:01:13 +0000196NumericLiteralParser::
197NumericLiteralParser(const char *begin, const char *end,
198 SourceLocation TokLoc, Preprocessor &pp)
199 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000200
201 // This routine assumes that the range begin/end matches the regex for integer
202 // and FP constants (specifically, the 'pp-number' regex), and assumes that
203 // the byte at "*end" is both valid and not part of the regex. Because of
204 // this, it doesn't have to check for 'overscan' in various places.
205 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
206 "Lexer didn't maximally munch?");
207
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 s = DigitsBegin = begin;
209 saw_exponent = false;
210 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 isLong = false;
212 isUnsigned = false;
213 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000214 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000215 isImaginary = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 hadError = false;
217
218 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000219 ParseNumberStartingWithZero(TokLoc);
220 if (hadError)
221 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 } else { // the first digit is non-zero
223 radix = 10;
224 s = SkipDigits(s);
225 if (s == ThisTokEnd) {
226 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000227 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000228 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
229 diag::err_invalid_decimal_digit, std::string(s, s+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 return;
231 } else if (*s == '.') {
232 s++;
233 saw_period = true;
234 s = SkipDigits(s);
235 }
Chris Lattner4411f462008-09-29 23:12:31 +0000236 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000237 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 s++;
239 saw_exponent = true;
240 if (*s == '+' || *s == '-') s++; // sign
241 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000242 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000244 } else {
Chris Lattner70f66ab2008-04-20 18:47:55 +0000245 Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000246 diag::err_exponent_has_no_digits);
247 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 }
249 }
250 }
251
252 SuffixBegin = s;
Chris Lattner506b8de2007-08-26 01:58:14 +0000253
254 // Parse the suffix. At this point we can classify whether we have an FP or
255 // integer constant.
256 bool isFPConstant = isFloatingLiteral();
257
258 // Loop over all of the characters of the suffix. If we see something bad,
259 // we break out of the loop.
260 for (; s != ThisTokEnd; ++s) {
261 switch (*s) {
262 case 'f': // FP Suffix for "float"
263 case 'F':
264 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000265 if (isFloat || isLong) break; // FF, LF invalid.
266 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000267 continue; // Success.
268 case 'u':
269 case 'U':
270 if (isFPConstant) break; // Error for floating constant.
271 if (isUnsigned) break; // Cannot be repeated.
272 isUnsigned = true;
273 continue; // Success.
274 case 'l':
275 case 'L':
276 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000277 if (isFloat) break; // LF invalid.
Chris Lattner506b8de2007-08-26 01:58:14 +0000278
279 // Check for long long. The L's need to be adjacent and the same case.
280 if (s+1 != ThisTokEnd && s[1] == s[0]) {
281 if (isFPConstant) break; // long long invalid for floats.
282 isLongLong = true;
283 ++s; // Eat both of them.
284 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000287 continue; // Success.
288 case 'i':
Steve Naroff0c29b222008-04-04 21:02:54 +0000289 if (PP.getLangOptions().Microsoft) {
290 // Allow i8, i16, i32, i64, and i128.
291 if (++s == ThisTokEnd) break;
292 switch (*s) {
293 case '8':
294 s++; // i8 suffix
295 break;
296 case '1':
297 if (++s == ThisTokEnd) break;
298 if (*s == '6') s++; // i16 suffix
299 else if (*s == '2') {
300 if (++s == ThisTokEnd) break;
301 if (*s == '8') s++; // i128 suffix
302 }
303 break;
304 case '3':
305 if (++s == ThisTokEnd) break;
306 if (*s == '2') s++; // i32 suffix
307 break;
308 case '6':
309 if (++s == ThisTokEnd) break;
310 if (*s == '4') s++; // i64 suffix
311 break;
312 default:
313 break;
314 }
315 break;
316 }
317 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000318 case 'I':
319 case 'j':
320 case 'J':
321 if (isImaginary) break; // Cannot be repeated.
322 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
323 diag::ext_imaginary_constant);
324 isImaginary = true;
325 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000326 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000327 // If we reached here, there was an error.
328 break;
329 }
330
331 // Report an error if there are any.
332 if (s != ThisTokEnd) {
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000333 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
334 isFPConstant ? diag::err_invalid_suffix_float_constant :
335 diag::err_invalid_suffix_integer_constant,
Chris Lattner506b8de2007-08-26 01:58:14 +0000336 std::string(SuffixBegin, ThisTokEnd));
337 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 }
339}
340
Chris Lattner368328c2008-06-30 06:39:54 +0000341/// ParseNumberStartingWithZero - This method is called when the first character
342/// of the number is found to be a zero. This means it is either an octal
343/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
344/// a floating point number (01239.123e4). Eat the prefix, determining the
345/// radix etc.
346void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
347 assert(s[0] == '0' && "Invalid method call");
348 s++;
349
350 // Handle a hex number like 0x1234.
351 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
352 s++;
353 radix = 16;
354 DigitsBegin = s;
355 s = SkipHexDigits(s);
356 if (s == ThisTokEnd) {
357 // Done.
358 } else if (*s == '.') {
359 s++;
360 saw_period = true;
361 s = SkipHexDigits(s);
362 }
363 // A binary exponent can appear with or with a '.'. If dotted, the
364 // binary exponent is required.
Chris Lattner6ea62382008-07-25 18:18:34 +0000365 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000366 const char *Exponent = s;
367 s++;
368 saw_exponent = true;
369 if (*s == '+' || *s == '-') s++; // sign
370 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000371 if (first_non_digit == s) {
Chris Lattner368328c2008-06-30 06:39:54 +0000372 Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
373 diag::err_exponent_has_no_digits);
Chris Lattner6ea62382008-07-25 18:18:34 +0000374 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000375 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000376 s = first_non_digit;
377
378 if (!PP.getLangOptions().HexFloats)
379 Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000380 } else if (saw_period) {
381 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
382 diag::err_hexconstant_requires_exponent);
383 }
384 return;
385 }
386
387 // Handle simple binary numbers 0b01010
388 if (*s == 'b' || *s == 'B') {
389 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000390 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000391 ++s;
392 radix = 2;
393 DigitsBegin = s;
394 s = SkipBinaryDigits(s);
395 if (s == ThisTokEnd) {
396 // Done.
397 } else if (isxdigit(*s)) {
398 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
399 diag::err_invalid_binary_digit, std::string(s, s+1));
Chris Lattner368328c2008-06-30 06:39:54 +0000400 }
Chris Lattner413d3552008-06-30 06:44:49 +0000401 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000402 return;
403 }
404
405 // For now, the radix is set to 8. If we discover that we have a
406 // floating point constant, the radix will change to 10. Octal floating
407 // point constants are not permitted (only decimal and hexadecimal).
408 radix = 8;
409 DigitsBegin = s;
410 s = SkipOctalDigits(s);
411 if (s == ThisTokEnd)
412 return; // Done, simple octal number like 01234
413
Chris Lattner413d3552008-06-30 06:44:49 +0000414 // If we have some other non-octal digit that *is* a decimal digit, see if
415 // this is part of a floating point number like 094.123 or 09e1.
416 if (isdigit(*s)) {
417 const char *EndDecimal = SkipDigits(s);
418 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
419 s = EndDecimal;
420 radix = 10;
421 }
422 }
423
424 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
425 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000426 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
427 Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
428 diag::err_invalid_octal_digit, std::string(s, s+1));
429 return;
430 }
431
432 if (*s == '.') {
433 s++;
434 radix = 10;
435 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000436 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000437 }
438 if (*s == 'e' || *s == 'E') { // exponent
439 const char *Exponent = s;
440 s++;
441 radix = 10;
442 saw_exponent = true;
443 if (*s == '+' || *s == '-') s++; // sign
444 const char *first_non_digit = SkipDigits(s);
445 if (first_non_digit != s) {
446 s = first_non_digit;
447 } else {
448 Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
449 diag::err_exponent_has_no_digits);
450 return;
451 }
452 }
453}
454
455
Reid Spencer5f016e22007-07-11 17:01:13 +0000456/// GetIntegerValue - Convert this numeric literal value to an APInt that
457/// matches Val's input width. If there is an overflow, set Val to the low bits
458/// of the result and return true. Otherwise, return false.
459bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
460 Val = 0;
461 s = DigitsBegin;
462
463 llvm::APInt RadixVal(Val.getBitWidth(), radix);
464 llvm::APInt CharVal(Val.getBitWidth(), 0);
465 llvm::APInt OldVal = Val;
466
467 bool OverflowOccurred = false;
468 while (s < SuffixBegin) {
469 unsigned C = HexDigitValue(*s++);
470
471 // If this letter is out of bound for this radix, reject it.
472 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
473
474 CharVal = C;
475
476 // Add the digit to the value in the appropriate radix. If adding in digits
477 // made the value smaller, then this overflowed.
478 OldVal = Val;
479
480 // Multiply by radix, did overflow occur on the multiply?
481 Val *= RadixVal;
482 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000485 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 OverflowOccurred |= Val.ult(CharVal);
488 }
489 return OverflowOccurred;
490}
491
Chris Lattner525a0502007-09-22 18:29:59 +0000492llvm::APFloat NumericLiteralParser::
Ted Kremenek427d5af2007-11-26 23:12:30 +0000493GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
494 using llvm::APFloat;
495
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000496 llvm::SmallVector<char,256> floatChars;
497 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
498 floatChars.push_back(ThisTokBegin[i]);
499
500 floatChars.push_back('\0');
501
Ted Kremenek427d5af2007-11-26 23:12:30 +0000502 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000503 APFloat::opStatus status;
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000504
505 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000506
507 if (isExact)
508 *isExact = status == APFloat::opOK;
509
510 return V;
Reid Spencer5f016e22007-07-11 17:01:13 +0000511}
512
513void NumericLiteralParser::Diag(SourceLocation Loc, unsigned DiagID,
514 const std::string &M) {
515 PP.Diag(Loc, DiagID, M);
516 hadError = true;
517}
518
519
520CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
521 SourceLocation Loc, Preprocessor &PP) {
522 // At this point we know that the character matches the regex "L?'.*'".
523 HadError = false;
524 Value = 0;
525
526 // Determine if this is a wide character.
527 IsWide = begin[0] == 'L';
528 if (IsWide) ++begin;
529
530 // Skip over the entry quote.
531 assert(begin[0] == '\'' && "Invalid token lexed");
532 ++begin;
533
534 // FIXME: This assumes that 'int' is 32-bits in overflow calculation, and the
535 // size of "value".
Chris Lattner98be4942008-03-05 18:54:05 +0000536 assert(PP.getTargetInfo().getIntWidth() == 32 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 "Assumes sizeof(int) == 4 for now");
538 // FIXME: This assumes that wchar_t is 32-bits for now.
Chris Lattner98be4942008-03-05 18:54:05 +0000539 assert(PP.getTargetInfo().getWCharWidth() == 32 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000540 "Assumes sizeof(wchar_t) == 4 for now");
541 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000542 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 "Assumes char is 8 bits");
544
545 bool isFirstChar = true;
546 bool isMultiChar = false;
547 while (begin[0] != '\'') {
548 unsigned ResultChar;
549 if (begin[0] != '\\') // If this is a normal character, consume it.
550 ResultChar = *begin++;
551 else // Otherwise, this is an escape character.
552 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
553
554 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
555 // implementation defined (C99 6.4.4.4p10).
556 if (!isFirstChar) {
557 // If this is the second character being processed, do special handling.
558 if (!isMultiChar) {
559 isMultiChar = true;
560
561 // Warn about discarding the top bits for multi-char wide-character
562 // constants (L'abcd').
563 if (IsWide)
564 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
565 }
566
567 if (IsWide) {
568 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
569 Value = 0;
570 } else {
571 // Narrow character literals act as though their value is concatenated
572 // in this implementation.
573 if (((Value << 8) >> 8) != Value)
574 PP.Diag(Loc, diag::warn_char_constant_too_large);
575 Value <<= 8;
576 }
577 }
578
579 Value += ResultChar;
580 isFirstChar = false;
581 }
582
583 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
584 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
585 // character constants are not sign extended in the this implementation:
586 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
587 if (!IsWide && !isMultiChar && (Value & 128) &&
Chris Lattner98be4942008-03-05 18:54:05 +0000588 PP.getTargetInfo().isCharSigned())
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 Value = (signed char)Value;
590}
591
592
593/// string-literal: [C99 6.4.5]
594/// " [s-char-sequence] "
595/// L" [s-char-sequence] "
596/// s-char-sequence:
597/// s-char
598/// s-char-sequence s-char
599/// s-char:
600/// any source character except the double quote ",
601/// backslash \, or newline character
602/// escape-character
603/// universal-character-name
604/// escape-character: [C99 6.4.4.4]
605/// \ escape-code
606/// universal-character-name
607/// escape-code:
608/// character-escape-code
609/// octal-escape-code
610/// hex-escape-code
611/// character-escape-code: one of
612/// n t b r f v a
613/// \ ' " ?
614/// octal-escape-code:
615/// octal-digit
616/// octal-digit octal-digit
617/// octal-digit octal-digit octal-digit
618/// hex-escape-code:
619/// x hex-digit
620/// hex-escape-code hex-digit
621/// universal-character-name:
622/// \u hex-quad
623/// \U hex-quad hex-quad
624/// hex-quad:
625/// hex-digit hex-digit hex-digit hex-digit
626///
627StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000628StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 Preprocessor &pp, TargetInfo &t)
630 : PP(pp), Target(t) {
631 // Scan all of the string portions, remember the max individual token length,
632 // computing a bound on the concatenated string length, and see whether any
633 // piece is a wide-string. If any of the string portions is a wide-string
634 // literal, the result is a wide-string literal [C99 6.4.5p4].
635 MaxTokenLength = StringToks[0].getLength();
636 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000637 AnyWide = StringToks[0].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000638
639 hadError = false;
640
641 // Implement Translation Phase #6: concatenation of string literals
642 /// (C99 5.1.1.2p1). The common case is only one string fragment.
643 for (unsigned i = 1; i != NumStringToks; ++i) {
644 // The string could be shorter than this if it needs cleaning, but this is a
645 // reasonable bound, which is all we need.
646 SizeBound += StringToks[i].getLength()-2; // -2 for "".
647
648 // Remember maximum string piece length.
649 if (StringToks[i].getLength() > MaxTokenLength)
650 MaxTokenLength = StringToks[i].getLength();
651
652 // Remember if we see any wide strings.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000653 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 }
655
656
657 // Include space for the null terminator.
658 ++SizeBound;
659
660 // TODO: K&R warning: "traditional C rejects string constant concatenation"
661
662 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
663 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
664 wchar_tByteWidth = ~0U;
665 if (AnyWide) {
Chris Lattner98be4942008-03-05 18:54:05 +0000666 wchar_tByteWidth = Target.getWCharWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
668 wchar_tByteWidth /= 8;
669 }
670
671 // The output buffer size needs to be large enough to hold wide characters.
672 // This is a worst-case assumption which basically corresponds to L"" "long".
673 if (AnyWide)
674 SizeBound *= wchar_tByteWidth;
675
676 // Size the temporary buffer to hold the result string data.
677 ResultBuf.resize(SizeBound);
678
679 // Likewise, but for each string piece.
680 llvm::SmallString<512> TokenBuf;
681 TokenBuf.resize(MaxTokenLength);
682
683 // Loop over all the strings, getting their spelling, and expanding them to
684 // wide strings as appropriate.
685 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
686
Anders Carlssonee98ac52007-10-15 02:50:23 +0000687 Pascal = false;
688
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
690 const char *ThisTokBuf = &TokenBuf[0];
691 // Get the spelling of the token, which eliminates trigraphs, etc. We know
692 // that ThisTokBuf points to a buffer that is big enough for the whole token
693 // and 'spelled' tokens can only shrink.
694 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
695 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
696
697 // TODO: Input character set mapping support.
698
699 // Skip L marker for wide strings.
700 bool ThisIsWide = false;
701 if (ThisTokBuf[0] == 'L') {
702 ++ThisTokBuf;
703 ThisIsWide = true;
704 }
705
706 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
707 ++ThisTokBuf;
708
Anders Carlssonee98ac52007-10-15 02:50:23 +0000709 // Check if this is a pascal string
710 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
711 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
712
713 // If the \p sequence is found in the first token, we have a pascal string
714 // Otherwise, if we already have a pascal string, ignore the first \p
715 if (i == 0) {
716 ++ThisTokBuf;
717 Pascal = true;
718 } else if (Pascal)
719 ThisTokBuf += 2;
720 }
721
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 while (ThisTokBuf != ThisTokEnd) {
723 // Is this a span of non-escape characters?
724 if (ThisTokBuf[0] != '\\') {
725 const char *InStart = ThisTokBuf;
726 do {
727 ++ThisTokBuf;
728 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
729
730 // Copy the character span over.
731 unsigned Len = ThisTokBuf-InStart;
732 if (!AnyWide) {
733 memcpy(ResultPtr, InStart, Len);
734 ResultPtr += Len;
735 } else {
736 // Note: our internal rep of wide char tokens is always little-endian.
737 for (; Len; --Len, ++InStart) {
738 *ResultPtr++ = InStart[0];
739 // Add zeros at the end.
740 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
741 *ResultPtr++ = 0;
742 }
743 }
744 continue;
745 }
746
747 // Otherwise, this is an escape character. Process it.
748 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
749 StringToks[i].getLocation(),
750 ThisIsWide, PP);
751
752 // Note: our internal rep of wide char tokens is always little-endian.
753 *ResultPtr++ = ResultChar & 0xFF;
754
755 if (AnyWide) {
756 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
757 *ResultPtr++ = ResultChar >> i*8;
758 }
759 }
760 }
761
762 // Add zero terminator.
763 *ResultPtr = 0;
764 if (AnyWide) {
765 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
766 *ResultPtr++ = 0;
767 }
Anders Carlssonee98ac52007-10-15 02:50:23 +0000768
769 if (Pascal)
770 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000771}