blob: dcd239d5abd41235658536c90135656e3d50fb88 [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"
Chris Lattner500d3292009-01-29 05:15:15 +000017#include "clang/Lex/LexDiagnostic.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':
Chris Lattner204b2fe2008-11-18 21:48:13 +000056 PP.Diag(Loc, diag::ext_nonstandard_escape) << "e";
Reid Spencer5f016e22007-07-11 17:01:13 +000057 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;
Reid Spencer5f016e22007-07-11 17:01:13 +000074 case 'x': { // Hex escape.
75 ResultChar = 0;
76 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
77 PP.Diag(Loc, diag::err_hex_escape_no_digits);
78 HadError = 1;
79 break;
80 }
81
82 // Hex escapes are a maximal series of hex digits.
83 bool Overflow = false;
84 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
85 int CharVal = HexDigitValue(ThisTokBuf[0]);
86 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +000087 // About to shift out a digit?
88 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +000089 ResultChar <<= 4;
90 ResultChar |= CharVal;
91 }
92
93 // See if any bits will be truncated when evaluated as a character.
Chris Lattner98be4942008-03-05 18:54:05 +000094 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide);
Ted Kremenek9c728dc2007-12-12 22:39:36 +000095
Reid Spencer5f016e22007-07-11 17:01:13 +000096 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
97 Overflow = true;
98 ResultChar &= ~0U >> (32-CharWidth);
99 }
100
101 // Check for overflow.
102 if (Overflow) // Too many digits to fit in
103 PP.Diag(Loc, diag::warn_hex_escape_too_large);
104 break;
105 }
106 case '0': case '1': case '2': case '3':
107 case '4': case '5': case '6': case '7': {
108 // Octal escapes.
109 --ThisTokBuf;
110 ResultChar = 0;
111
112 // Octal escapes are a series of octal digits with maximum length 3.
113 // "\0123" is a two digit sequence equal to "\012" "3".
114 unsigned NumDigits = 0;
115 do {
116 ResultChar <<= 3;
117 ResultChar |= *ThisTokBuf++ - '0';
118 ++NumDigits;
119 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
120 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
121
122 // Check for overflow. Reject '\777', but not L'\777'.
Chris Lattner98be4942008-03-05 18:54:05 +0000123 unsigned CharWidth = PP.getTargetInfo().getCharWidth(IsWide);
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000124
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
126 PP.Diag(Loc, diag::warn_octal_escape_too_large);
127 ResultChar &= ~0U >> (32-CharWidth);
128 }
129 break;
130 }
131
132 // Otherwise, these are not valid escapes.
133 case '(': case '{': case '[': case '%':
134 // GCC accepts these as extensions. We warn about them as such though.
135 if (!PP.getLangOptions().NoExtensions) {
Chris Lattner204b2fe2008-11-18 21:48:13 +0000136 PP.Diag(Loc, diag::ext_nonstandard_escape)
137 << std::string()+(char)ResultChar;
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 break;
139 }
140 // FALL THROUGH.
141 default:
Chris Lattnerac92d822008-11-22 07:23:31 +0000142 if (isgraph(ThisTokBuf[0]))
Chris Lattner204b2fe2008-11-18 21:48:13 +0000143 PP.Diag(Loc, diag::ext_unknown_escape) << std::string()+(char)ResultChar;
Chris Lattnerac92d822008-11-22 07:23:31 +0000144 else
Chris Lattner204b2fe2008-11-18 21:48:13 +0000145 PP.Diag(Loc, diag::ext_unknown_escape) << "x"+llvm::utohexstr(ResultChar);
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 break;
147 }
148
149 return ResultChar;
150}
151
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000152/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
153/// convert the UTF32 to UTF8. This is a subroutine of StringLiteralParser.
154/// When we decide to implement UCN's for character constants and identifiers,
155/// we will likely rework our support for UCN's.
156static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
157 char *&ResultBuf, const char *ResultBufEnd,
158 bool &HadError,
159 SourceLocation Loc, Preprocessor &PP) {
160 // FIXME: Add a warning - UCN's are only valid in C++ & C99.
161
162 // Skip the '\u' char's.
163 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000164
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000165 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
166 PP.Diag(Loc, diag::err_ucn_escape_no_digits);
167 HadError = 1;
168 return;
169 }
170 typedef unsigned int UTF32;
171
172 UTF32 UcnVal = 0;
173 unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
174 for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) {
175 int CharVal = HexDigitValue(ThisTokBuf[0]);
176 if (CharVal == -1) break;
177 UcnVal <<= 4;
178 UcnVal |= CharVal;
179 }
180 // If we didn't consume the proper number of digits, there is a problem.
181 if (UcnLen) {
182 PP.Diag(Loc, diag::err_ucn_escape_incomplete);
183 HadError = 1;
184 return;
185 }
186 // Check UCN constraints (C99 6.4.3p2)
187 if ((UcnVal < 0xa0 &&
188 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
189 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)) {
190 PP.Diag(Loc, diag::err_ucn_escape_invalid);
191 HadError = 1;
192 return;
193 }
194 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
195 // The conversion below was inspired by:
196 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
197 // First, we determine how many bytes the result will require.
198 typedef unsigned char UTF8;
199
200 unsigned short bytesToWrite = 0;
201 if (UcnVal < (UTF32)0x80)
202 bytesToWrite = 1;
203 else if (UcnVal < (UTF32)0x800)
204 bytesToWrite = 2;
205 else if (UcnVal < (UTF32)0x10000)
206 bytesToWrite = 3;
207 else
208 bytesToWrite = 4;
209
210 // If the buffer isn't big enough, bail.
211 if ((ResultBuf + bytesToWrite) >= ResultBufEnd) {
212 PP.Diag(Loc, diag::err_ucn_escape_too_big);
213 HadError = 1;
214 return;
215 }
216 const unsigned byteMask = 0xBF;
217 const unsigned byteMark = 0x80;
218
219 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
220 // into the first byte, depending on how many bytes follow. There are
221 // as many entries in this table as there are UTF8 sequence types.
222 static const UTF8 firstByteMark[7] = {
223 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
224 };
225 // Finally, we write the bytes into ResultBuf.
226 ResultBuf += bytesToWrite;
227 switch (bytesToWrite) { // note: everything falls through.
228 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
229 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
230 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
231 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
232 }
233 // Update the buffer.
234 ResultBuf += bytesToWrite;
235}
Reid Spencer5f016e22007-07-11 17:01:13 +0000236
237
238/// integer-constant: [C99 6.4.4.1]
239/// decimal-constant integer-suffix
240/// octal-constant integer-suffix
241/// hexadecimal-constant integer-suffix
242/// decimal-constant:
243/// nonzero-digit
244/// decimal-constant digit
245/// octal-constant:
246/// 0
247/// octal-constant octal-digit
248/// hexadecimal-constant:
249/// hexadecimal-prefix hexadecimal-digit
250/// hexadecimal-constant hexadecimal-digit
251/// hexadecimal-prefix: one of
252/// 0x 0X
253/// integer-suffix:
254/// unsigned-suffix [long-suffix]
255/// unsigned-suffix [long-long-suffix]
256/// long-suffix [unsigned-suffix]
257/// long-long-suffix [unsigned-sufix]
258/// nonzero-digit:
259/// 1 2 3 4 5 6 7 8 9
260/// octal-digit:
261/// 0 1 2 3 4 5 6 7
262/// hexadecimal-digit:
263/// 0 1 2 3 4 5 6 7 8 9
264/// a b c d e f
265/// A B C D E F
266/// unsigned-suffix: one of
267/// u U
268/// long-suffix: one of
269/// l L
270/// long-long-suffix: one of
271/// ll LL
272///
273/// floating-constant: [C99 6.4.4.2]
274/// TODO: add rules...
275///
Reid Spencer5f016e22007-07-11 17:01:13 +0000276NumericLiteralParser::
277NumericLiteralParser(const char *begin, const char *end,
278 SourceLocation TokLoc, Preprocessor &pp)
279 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000280
281 // This routine assumes that the range begin/end matches the regex for integer
282 // and FP constants (specifically, the 'pp-number' regex), and assumes that
283 // the byte at "*end" is both valid and not part of the regex. Because of
284 // this, it doesn't have to check for 'overscan' in various places.
285 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
286 "Lexer didn't maximally munch?");
287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 s = DigitsBegin = begin;
289 saw_exponent = false;
290 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 isLong = false;
292 isUnsigned = false;
293 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000294 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000295 isImaginary = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 hadError = false;
297
298 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000299 ParseNumberStartingWithZero(TokLoc);
300 if (hadError)
301 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 } else { // the first digit is non-zero
303 radix = 10;
304 s = SkipDigits(s);
305 if (s == ThisTokEnd) {
306 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000307 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000308 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
309 diag::err_invalid_decimal_digit) << std::string(s, s+1);
310 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 return;
312 } else if (*s == '.') {
313 s++;
314 saw_period = true;
315 s = SkipDigits(s);
316 }
Chris Lattner4411f462008-09-29 23:12:31 +0000317 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000318 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 s++;
320 saw_exponent = true;
321 if (*s == '+' || *s == '-') s++; // sign
322 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000323 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000325 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000326 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
327 diag::err_exponent_has_no_digits);
328 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000329 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 }
331 }
332 }
333
334 SuffixBegin = s;
Chris Lattner506b8de2007-08-26 01:58:14 +0000335
336 // Parse the suffix. At this point we can classify whether we have an FP or
337 // integer constant.
338 bool isFPConstant = isFloatingLiteral();
339
340 // Loop over all of the characters of the suffix. If we see something bad,
341 // we break out of the loop.
342 for (; s != ThisTokEnd; ++s) {
343 switch (*s) {
344 case 'f': // FP Suffix for "float"
345 case 'F':
346 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000347 if (isFloat || isLong) break; // FF, LF invalid.
348 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000349 continue; // Success.
350 case 'u':
351 case 'U':
352 if (isFPConstant) break; // Error for floating constant.
353 if (isUnsigned) break; // Cannot be repeated.
354 isUnsigned = true;
355 continue; // Success.
356 case 'l':
357 case 'L':
358 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000359 if (isFloat) break; // LF invalid.
Chris Lattner506b8de2007-08-26 01:58:14 +0000360
361 // Check for long long. The L's need to be adjacent and the same case.
362 if (s+1 != ThisTokEnd && s[1] == s[0]) {
363 if (isFPConstant) break; // long long invalid for floats.
364 isLongLong = true;
365 ++s; // Eat both of them.
366 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000369 continue; // Success.
370 case 'i':
Steve Naroff0c29b222008-04-04 21:02:54 +0000371 if (PP.getLangOptions().Microsoft) {
372 // Allow i8, i16, i32, i64, and i128.
373 if (++s == ThisTokEnd) break;
374 switch (*s) {
375 case '8':
376 s++; // i8 suffix
377 break;
378 case '1':
379 if (++s == ThisTokEnd) break;
380 if (*s == '6') s++; // i16 suffix
381 else if (*s == '2') {
382 if (++s == ThisTokEnd) break;
383 if (*s == '8') s++; // i128 suffix
384 }
385 break;
386 case '3':
387 if (++s == ThisTokEnd) break;
388 if (*s == '2') s++; // i32 suffix
389 break;
390 case '6':
391 if (++s == ThisTokEnd) break;
392 if (*s == '4') s++; // i64 suffix
393 break;
394 default:
395 break;
396 }
397 break;
398 }
399 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000400 case 'I':
401 case 'j':
402 case 'J':
403 if (isImaginary) break; // Cannot be repeated.
404 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
405 diag::ext_imaginary_constant);
406 isImaginary = true;
407 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000409 // If we reached here, there was an error.
410 break;
411 }
412
413 // Report an error if there are any.
414 if (s != ThisTokEnd) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000415 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
416 isFPConstant ? diag::err_invalid_suffix_float_constant :
417 diag::err_invalid_suffix_integer_constant)
418 << std::string(SuffixBegin, ThisTokEnd);
419 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000420 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 }
422}
423
Chris Lattner368328c2008-06-30 06:39:54 +0000424/// ParseNumberStartingWithZero - This method is called when the first character
425/// of the number is found to be a zero. This means it is either an octal
426/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
427/// a floating point number (01239.123e4). Eat the prefix, determining the
428/// radix etc.
429void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
430 assert(s[0] == '0' && "Invalid method call");
431 s++;
432
433 // Handle a hex number like 0x1234.
434 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
435 s++;
436 radix = 16;
437 DigitsBegin = s;
438 s = SkipHexDigits(s);
439 if (s == ThisTokEnd) {
440 // Done.
441 } else if (*s == '.') {
442 s++;
443 saw_period = true;
444 s = SkipHexDigits(s);
445 }
446 // A binary exponent can appear with or with a '.'. If dotted, the
447 // binary exponent is required.
Chris Lattner6ea62382008-07-25 18:18:34 +0000448 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000449 const char *Exponent = s;
450 s++;
451 saw_exponent = true;
452 if (*s == '+' || *s == '-') s++; // sign
453 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000454 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000455 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
456 diag::err_exponent_has_no_digits);
457 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000458 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000459 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000460 s = first_non_digit;
461
Chris Lattner49842122008-11-22 07:39:03 +0000462 if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000463 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000464 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000465 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
466 diag::err_hexconstant_requires_exponent);
467 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000468 }
469 return;
470 }
471
472 // Handle simple binary numbers 0b01010
473 if (*s == 'b' || *s == 'B') {
474 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000475 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000476 ++s;
477 radix = 2;
478 DigitsBegin = s;
479 s = SkipBinaryDigits(s);
480 if (s == ThisTokEnd) {
481 // Done.
482 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000483 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
484 diag::err_invalid_binary_digit) << std::string(s, s+1);
485 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000486 }
Chris Lattner413d3552008-06-30 06:44:49 +0000487 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000488 return;
489 }
490
491 // For now, the radix is set to 8. If we discover that we have a
492 // floating point constant, the radix will change to 10. Octal floating
493 // point constants are not permitted (only decimal and hexadecimal).
494 radix = 8;
495 DigitsBegin = s;
496 s = SkipOctalDigits(s);
497 if (s == ThisTokEnd)
498 return; // Done, simple octal number like 01234
499
Chris Lattner413d3552008-06-30 06:44:49 +0000500 // If we have some other non-octal digit that *is* a decimal digit, see if
501 // this is part of a floating point number like 094.123 or 09e1.
502 if (isdigit(*s)) {
503 const char *EndDecimal = SkipDigits(s);
504 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
505 s = EndDecimal;
506 radix = 10;
507 }
508 }
509
510 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
511 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000512 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000513 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
514 diag::err_invalid_octal_digit) << std::string(s, s+1);
515 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000516 return;
517 }
518
519 if (*s == '.') {
520 s++;
521 radix = 10;
522 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000523 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000524 }
525 if (*s == 'e' || *s == 'E') { // exponent
526 const char *Exponent = s;
527 s++;
528 radix = 10;
529 saw_exponent = true;
530 if (*s == '+' || *s == '-') s++; // sign
531 const char *first_non_digit = SkipDigits(s);
532 if (first_non_digit != s) {
533 s = first_non_digit;
534 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000535 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
536 diag::err_exponent_has_no_digits);
537 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000538 return;
539 }
540 }
541}
542
543
Reid Spencer5f016e22007-07-11 17:01:13 +0000544/// GetIntegerValue - Convert this numeric literal value to an APInt that
545/// matches Val's input width. If there is an overflow, set Val to the low bits
546/// of the result and return true. Otherwise, return false.
547bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000548 // Fast path: Compute a conservative bound on the maximum number of
549 // bits per digit in this radix. If we can't possibly overflow a
550 // uint64 based on that bound then do the simple conversion to
551 // integer. This avoids the expensive overflow checking below, and
552 // handles the common cases that matter (small decimal integers and
553 // hex/octal values which don't overflow).
554 unsigned MaxBitsPerDigit = 1;
555 while ((1U << MaxBitsPerDigit) < radix)
556 MaxBitsPerDigit += 1;
557 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
558 uint64_t N = 0;
559 for (s = DigitsBegin; s != SuffixBegin; ++s)
560 N = N*radix + HexDigitValue(*s);
561
562 // This will truncate the value to Val's input width. Simply check
563 // for overflow by comparing.
564 Val = N;
565 return Val.getZExtValue() != N;
566 }
567
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 Val = 0;
569 s = DigitsBegin;
570
571 llvm::APInt RadixVal(Val.getBitWidth(), radix);
572 llvm::APInt CharVal(Val.getBitWidth(), 0);
573 llvm::APInt OldVal = Val;
574
575 bool OverflowOccurred = false;
576 while (s < SuffixBegin) {
577 unsigned C = HexDigitValue(*s++);
578
579 // If this letter is out of bound for this radix, reject it.
580 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
581
582 CharVal = C;
583
584 // Add the digit to the value in the appropriate radix. If adding in digits
585 // made the value smaller, then this overflowed.
586 OldVal = Val;
587
588 // Multiply by radix, did overflow occur on the multiply?
589 Val *= RadixVal;
590 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
591
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000593 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 OverflowOccurred |= Val.ult(CharVal);
596 }
597 return OverflowOccurred;
598}
599
Chris Lattner525a0502007-09-22 18:29:59 +0000600llvm::APFloat NumericLiteralParser::
Ted Kremenek427d5af2007-11-26 23:12:30 +0000601GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
602 using llvm::APFloat;
603
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000604 llvm::SmallVector<char,256> floatChars;
605 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
606 floatChars.push_back(ThisTokBegin[i]);
607
608 floatChars.push_back('\0');
609
Ted Kremenek427d5af2007-11-26 23:12:30 +0000610 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000611 APFloat::opStatus status;
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000612
613 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000614
615 if (isExact)
616 *isExact = status == APFloat::opOK;
617
618 return V;
Reid Spencer5f016e22007-07-11 17:01:13 +0000619}
620
Reid Spencer5f016e22007-07-11 17:01:13 +0000621
622CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
623 SourceLocation Loc, Preprocessor &PP) {
624 // At this point we know that the character matches the regex "L?'.*'".
625 HadError = false;
626 Value = 0;
627
628 // Determine if this is a wide character.
629 IsWide = begin[0] == 'L';
630 if (IsWide) ++begin;
631
632 // Skip over the entry quote.
633 assert(begin[0] == '\'' && "Invalid token lexed");
634 ++begin;
635
636 // FIXME: This assumes that 'int' is 32-bits in overflow calculation, and the
637 // size of "value".
Chris Lattner98be4942008-03-05 18:54:05 +0000638 assert(PP.getTargetInfo().getIntWidth() == 32 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 "Assumes sizeof(int) == 4 for now");
640 // FIXME: This assumes that wchar_t is 32-bits for now.
Chris Lattner98be4942008-03-05 18:54:05 +0000641 assert(PP.getTargetInfo().getWCharWidth() == 32 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 "Assumes sizeof(wchar_t) == 4 for now");
643 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000644 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 "Assumes char is 8 bits");
646
647 bool isFirstChar = true;
648 bool isMultiChar = false;
649 while (begin[0] != '\'') {
650 unsigned ResultChar;
651 if (begin[0] != '\\') // If this is a normal character, consume it.
652 ResultChar = *begin++;
653 else // Otherwise, this is an escape character.
654 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
655
656 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
657 // implementation defined (C99 6.4.4.4p10).
658 if (!isFirstChar) {
659 // If this is the second character being processed, do special handling.
660 if (!isMultiChar) {
661 isMultiChar = true;
662
663 // Warn about discarding the top bits for multi-char wide-character
664 // constants (L'abcd').
665 if (IsWide)
666 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
667 }
668
669 if (IsWide) {
670 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
671 Value = 0;
672 } else {
673 // Narrow character literals act as though their value is concatenated
674 // in this implementation.
675 if (((Value << 8) >> 8) != Value)
676 PP.Diag(Loc, diag::warn_char_constant_too_large);
677 Value <<= 8;
678 }
679 }
680
681 Value += ResultChar;
682 isFirstChar = false;
683 }
684
685 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
686 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
687 // character constants are not sign extended in the this implementation:
688 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
689 if (!IsWide && !isMultiChar && (Value & 128) &&
Chris Lattner98be4942008-03-05 18:54:05 +0000690 PP.getTargetInfo().isCharSigned())
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 Value = (signed char)Value;
692}
693
694
695/// string-literal: [C99 6.4.5]
696/// " [s-char-sequence] "
697/// L" [s-char-sequence] "
698/// s-char-sequence:
699/// s-char
700/// s-char-sequence s-char
701/// s-char:
702/// any source character except the double quote ",
703/// backslash \, or newline character
704/// escape-character
705/// universal-character-name
706/// escape-character: [C99 6.4.4.4]
707/// \ escape-code
708/// universal-character-name
709/// escape-code:
710/// character-escape-code
711/// octal-escape-code
712/// hex-escape-code
713/// character-escape-code: one of
714/// n t b r f v a
715/// \ ' " ?
716/// octal-escape-code:
717/// octal-digit
718/// octal-digit octal-digit
719/// octal-digit octal-digit octal-digit
720/// hex-escape-code:
721/// x hex-digit
722/// hex-escape-code hex-digit
723/// universal-character-name:
724/// \u hex-quad
725/// \U hex-quad hex-quad
726/// hex-quad:
727/// hex-digit hex-digit hex-digit hex-digit
728///
729StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000730StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000731 Preprocessor &pp) : PP(pp) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 // Scan all of the string portions, remember the max individual token length,
733 // computing a bound on the concatenated string length, and see whether any
734 // piece is a wide-string. If any of the string portions is a wide-string
735 // literal, the result is a wide-string literal [C99 6.4.5p4].
736 MaxTokenLength = StringToks[0].getLength();
737 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000738 AnyWide = StringToks[0].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000739
740 hadError = false;
741
742 // Implement Translation Phase #6: concatenation of string literals
743 /// (C99 5.1.1.2p1). The common case is only one string fragment.
744 for (unsigned i = 1; i != NumStringToks; ++i) {
745 // The string could be shorter than this if it needs cleaning, but this is a
746 // reasonable bound, which is all we need.
747 SizeBound += StringToks[i].getLength()-2; // -2 for "".
748
749 // Remember maximum string piece length.
750 if (StringToks[i].getLength() > MaxTokenLength)
751 MaxTokenLength = StringToks[i].getLength();
752
753 // Remember if we see any wide strings.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000754 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000756
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 // Include space for the null terminator.
758 ++SizeBound;
759
760 // TODO: K&R warning: "traditional C rejects string constant concatenation"
761
762 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
763 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
764 wchar_tByteWidth = ~0U;
765 if (AnyWide) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000766 wchar_tByteWidth = PP.getTargetInfo().getWCharWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
768 wchar_tByteWidth /= 8;
769 }
770
771 // The output buffer size needs to be large enough to hold wide characters.
772 // This is a worst-case assumption which basically corresponds to L"" "long".
773 if (AnyWide)
774 SizeBound *= wchar_tByteWidth;
775
776 // Size the temporary buffer to hold the result string data.
777 ResultBuf.resize(SizeBound);
778
779 // Likewise, but for each string piece.
780 llvm::SmallString<512> TokenBuf;
781 TokenBuf.resize(MaxTokenLength);
782
783 // Loop over all the strings, getting their spelling, and expanding them to
784 // wide strings as appropriate.
785 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
786
Anders Carlssonee98ac52007-10-15 02:50:23 +0000787 Pascal = false;
788
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
790 const char *ThisTokBuf = &TokenBuf[0];
791 // Get the spelling of the token, which eliminates trigraphs, etc. We know
792 // that ThisTokBuf points to a buffer that is big enough for the whole token
793 // and 'spelled' tokens can only shrink.
794 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
795 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
796
797 // TODO: Input character set mapping support.
798
799 // Skip L marker for wide strings.
800 bool ThisIsWide = false;
801 if (ThisTokBuf[0] == 'L') {
802 ++ThisTokBuf;
803 ThisIsWide = true;
804 }
805
806 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
807 ++ThisTokBuf;
808
Anders Carlssonee98ac52007-10-15 02:50:23 +0000809 // Check if this is a pascal string
810 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
811 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
812
813 // If the \p sequence is found in the first token, we have a pascal string
814 // Otherwise, if we already have a pascal string, ignore the first \p
815 if (i == 0) {
816 ++ThisTokBuf;
817 Pascal = true;
818 } else if (Pascal)
819 ThisTokBuf += 2;
820 }
821
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 while (ThisTokBuf != ThisTokEnd) {
823 // Is this a span of non-escape characters?
824 if (ThisTokBuf[0] != '\\') {
825 const char *InStart = ThisTokBuf;
826 do {
827 ++ThisTokBuf;
828 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
829
830 // Copy the character span over.
831 unsigned Len = ThisTokBuf-InStart;
832 if (!AnyWide) {
833 memcpy(ResultPtr, InStart, Len);
834 ResultPtr += Len;
835 } else {
836 // Note: our internal rep of wide char tokens is always little-endian.
837 for (; Len; --Len, ++InStart) {
838 *ResultPtr++ = InStart[0];
839 // Add zeros at the end.
840 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000841 *ResultPtr++ = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 }
843 }
844 continue;
845 }
846
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000847 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
848 ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
849 GetString() + ResultBuf.size(),
850 hadError, StringToks[i].getLocation(), PP);
851 } else {
852 // Otherwise, this is a non-UCN escape character. Process it.
853 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
854 StringToks[i].getLocation(),
855 ThisIsWide, PP);
856
857 // Note: our internal rep of wide char tokens is always little-endian.
858 *ResultPtr++ = ResultChar & 0xFF;
859
860 if (AnyWide) {
861 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
862 *ResultPtr++ = ResultChar >> i*8;
863 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 }
865 }
866 }
867
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000868 if (Pascal) {
Anders Carlssonee98ac52007-10-15 02:50:23 +0000869 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000870
871 // Verify that pascal strings aren't too large.
872 if (GetStringLength() > 256)
873 PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
874 << SourceRange(StringToks[0].getLocation(),
875 StringToks[NumStringToks-1].getLocation());
876 hadError = 1;
877 return;
878 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000879}
Chris Lattner719e6152009-02-18 19:21:10 +0000880
881
882/// getOffsetOfStringByte - This function returns the offset of the
883/// specified byte of the string data represented by Token. This handles
884/// advancing over escape sequences in the string.
885unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
886 unsigned ByteNo,
887 Preprocessor &PP) {
888 // Get the spelling of the token.
889 llvm::SmallString<16> SpellingBuffer;
890 SpellingBuffer.resize(Tok.getLength());
891
892 const char *SpellingPtr = &SpellingBuffer[0];
893 unsigned TokLen = PP.getSpelling(Tok, SpellingPtr);
894
895 assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet");
896
897
898 const char *SpellingStart = SpellingPtr;
899 const char *SpellingEnd = SpellingPtr+TokLen;
900
901 // Skip over the leading quote.
902 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
903 ++SpellingPtr;
904
905 // Skip over bytes until we find the offset we're looking for.
906 while (ByteNo) {
907 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
908
909 // Step over non-escapes simply.
910 if (*SpellingPtr != '\\') {
911 ++SpellingPtr;
912 --ByteNo;
913 continue;
914 }
915
916 // Otherwise, this is an escape character. Advance over it.
917 bool HadError = false;
918 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
919 Tok.getLocation(), false, PP);
920 assert(!HadError && "This method isn't valid on erroneous strings");
921 --ByteNo;
922 }
923
924 return SpellingPtr-SpellingStart;
925}