blob: a3184e90ad8d1185f81f6a933c14a73ce94b23d4 [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,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000157 char *&ResultBuf, bool &HadError,
158 SourceLocation Loc, bool IsWide, Preprocessor &PP)
159{
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000160 // FIXME: Add a warning - UCN's are only valid in C++ & C99.
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000161 // FIXME: Handle wide strings.
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000162
Steve Naroff4e93b342009-04-01 11:09:15 +0000163 // Save the beginning of the string (for error diagnostics).
164 const char *ThisTokBegin = ThisTokBuf;
165
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000166 // Skip the '\u' char's.
167 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000168
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000169 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
170 PP.Diag(Loc, diag::err_ucn_escape_no_digits);
171 HadError = 1;
172 return;
173 }
Steve Naroff4e93b342009-04-01 11:09:15 +0000174 typedef uint32_t UTF32;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000175
176 UTF32 UcnVal = 0;
177 unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
178 for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) {
179 int CharVal = HexDigitValue(ThisTokBuf[0]);
180 if (CharVal == -1) break;
181 UcnVal <<= 4;
182 UcnVal |= CharVal;
183 }
184 // If we didn't consume the proper number of digits, there is a problem.
185 if (UcnLen) {
Steve Naroff4e93b342009-04-01 11:09:15 +0000186 PP.Diag(PP.AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin),
187 diag::err_ucn_escape_incomplete);
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000188 HadError = 1;
189 return;
190 }
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000191 // Check UCN constraints (C99 6.4.3p2).
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000192 if ((UcnVal < 0xa0 &&
193 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000194 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)
195 || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000196 PP.Diag(Loc, diag::err_ucn_escape_invalid);
197 HadError = 1;
198 return;
199 }
200 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
201 // The conversion below was inspired by:
202 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
203 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000204 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000205
206 unsigned short bytesToWrite = 0;
207 if (UcnVal < (UTF32)0x80)
208 bytesToWrite = 1;
209 else if (UcnVal < (UTF32)0x800)
210 bytesToWrite = 2;
211 else if (UcnVal < (UTF32)0x10000)
212 bytesToWrite = 3;
213 else
214 bytesToWrite = 4;
215
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000216 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
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000220 // into the first byte, depending on how many bytes follow.
221 static const UTF8 firstByteMark[5] = {
222 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000223 };
224 // Finally, we write the bytes into ResultBuf.
225 ResultBuf += bytesToWrite;
226 switch (bytesToWrite) { // note: everything falls through.
227 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
228 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
229 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
230 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
231 }
232 // Update the buffer.
233 ResultBuf += bytesToWrite;
234}
Reid Spencer5f016e22007-07-11 17:01:13 +0000235
236
237/// integer-constant: [C99 6.4.4.1]
238/// decimal-constant integer-suffix
239/// octal-constant integer-suffix
240/// hexadecimal-constant integer-suffix
241/// decimal-constant:
242/// nonzero-digit
243/// decimal-constant digit
244/// octal-constant:
245/// 0
246/// octal-constant octal-digit
247/// hexadecimal-constant:
248/// hexadecimal-prefix hexadecimal-digit
249/// hexadecimal-constant hexadecimal-digit
250/// hexadecimal-prefix: one of
251/// 0x 0X
252/// integer-suffix:
253/// unsigned-suffix [long-suffix]
254/// unsigned-suffix [long-long-suffix]
255/// long-suffix [unsigned-suffix]
256/// long-long-suffix [unsigned-sufix]
257/// nonzero-digit:
258/// 1 2 3 4 5 6 7 8 9
259/// octal-digit:
260/// 0 1 2 3 4 5 6 7
261/// hexadecimal-digit:
262/// 0 1 2 3 4 5 6 7 8 9
263/// a b c d e f
264/// A B C D E F
265/// unsigned-suffix: one of
266/// u U
267/// long-suffix: one of
268/// l L
269/// long-long-suffix: one of
270/// ll LL
271///
272/// floating-constant: [C99 6.4.4.2]
273/// TODO: add rules...
274///
Reid Spencer5f016e22007-07-11 17:01:13 +0000275NumericLiteralParser::
276NumericLiteralParser(const char *begin, const char *end,
277 SourceLocation TokLoc, Preprocessor &pp)
278 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000279
280 // This routine assumes that the range begin/end matches the regex for integer
281 // and FP constants (specifically, the 'pp-number' regex), and assumes that
282 // the byte at "*end" is both valid and not part of the regex. Because of
283 // this, it doesn't have to check for 'overscan' in various places.
284 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
285 "Lexer didn't maximally munch?");
286
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 s = DigitsBegin = begin;
288 saw_exponent = false;
289 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000290 isLong = false;
291 isUnsigned = false;
292 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000293 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000294 isImaginary = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 hadError = false;
296
297 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000298 ParseNumberStartingWithZero(TokLoc);
299 if (hadError)
300 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 } else { // the first digit is non-zero
302 radix = 10;
303 s = SkipDigits(s);
304 if (s == ThisTokEnd) {
305 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000306 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000307 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
308 diag::err_invalid_decimal_digit) << std::string(s, s+1);
309 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 return;
311 } else if (*s == '.') {
312 s++;
313 saw_period = true;
314 s = SkipDigits(s);
315 }
Chris Lattner4411f462008-09-29 23:12:31 +0000316 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000317 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 s++;
319 saw_exponent = true;
320 if (*s == '+' || *s == '-') s++; // sign
321 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000322 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000324 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000325 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
326 diag::err_exponent_has_no_digits);
327 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000328 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 }
330 }
331 }
332
333 SuffixBegin = s;
Chris Lattner506b8de2007-08-26 01:58:14 +0000334
335 // Parse the suffix. At this point we can classify whether we have an FP or
336 // integer constant.
337 bool isFPConstant = isFloatingLiteral();
338
339 // Loop over all of the characters of the suffix. If we see something bad,
340 // we break out of the loop.
341 for (; s != ThisTokEnd; ++s) {
342 switch (*s) {
343 case 'f': // FP Suffix for "float"
344 case 'F':
345 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000346 if (isFloat || isLong) break; // FF, LF invalid.
347 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000348 continue; // Success.
349 case 'u':
350 case 'U':
351 if (isFPConstant) break; // Error for floating constant.
352 if (isUnsigned) break; // Cannot be repeated.
353 isUnsigned = true;
354 continue; // Success.
355 case 'l':
356 case 'L':
357 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000358 if (isFloat) break; // LF invalid.
Chris Lattner506b8de2007-08-26 01:58:14 +0000359
360 // Check for long long. The L's need to be adjacent and the same case.
361 if (s+1 != ThisTokEnd && s[1] == s[0]) {
362 if (isFPConstant) break; // long long invalid for floats.
363 isLongLong = true;
364 ++s; // Eat both of them.
365 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000368 continue; // Success.
369 case 'i':
Steve Naroff0c29b222008-04-04 21:02:54 +0000370 if (PP.getLangOptions().Microsoft) {
371 // Allow i8, i16, i32, i64, and i128.
372 if (++s == ThisTokEnd) break;
373 switch (*s) {
374 case '8':
375 s++; // i8 suffix
376 break;
377 case '1':
378 if (++s == ThisTokEnd) break;
379 if (*s == '6') s++; // i16 suffix
380 else if (*s == '2') {
381 if (++s == ThisTokEnd) break;
382 if (*s == '8') s++; // i128 suffix
383 }
384 break;
385 case '3':
386 if (++s == ThisTokEnd) break;
387 if (*s == '2') s++; // i32 suffix
388 break;
389 case '6':
390 if (++s == ThisTokEnd) break;
391 if (*s == '4') s++; // i64 suffix
392 break;
393 default:
394 break;
395 }
396 break;
397 }
398 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000399 case 'I':
400 case 'j':
401 case 'J':
402 if (isImaginary) break; // Cannot be repeated.
403 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
404 diag::ext_imaginary_constant);
405 isImaginary = true;
406 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000408 // If we reached here, there was an error.
409 break;
410 }
411
412 // Report an error if there are any.
413 if (s != ThisTokEnd) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000414 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
415 isFPConstant ? diag::err_invalid_suffix_float_constant :
416 diag::err_invalid_suffix_integer_constant)
417 << std::string(SuffixBegin, ThisTokEnd);
418 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000419 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 }
421}
422
Chris Lattner368328c2008-06-30 06:39:54 +0000423/// ParseNumberStartingWithZero - This method is called when the first character
424/// of the number is found to be a zero. This means it is either an octal
425/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
426/// a floating point number (01239.123e4). Eat the prefix, determining the
427/// radix etc.
428void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
429 assert(s[0] == '0' && "Invalid method call");
430 s++;
431
432 // Handle a hex number like 0x1234.
433 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
434 s++;
435 radix = 16;
436 DigitsBegin = s;
437 s = SkipHexDigits(s);
438 if (s == ThisTokEnd) {
439 // Done.
440 } else if (*s == '.') {
441 s++;
442 saw_period = true;
443 s = SkipHexDigits(s);
444 }
445 // A binary exponent can appear with or with a '.'. If dotted, the
446 // binary exponent is required.
Chris Lattner6ea62382008-07-25 18:18:34 +0000447 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000448 const char *Exponent = s;
449 s++;
450 saw_exponent = true;
451 if (*s == '+' || *s == '-') s++; // sign
452 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000453 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000454 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
455 diag::err_exponent_has_no_digits);
456 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000457 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000458 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000459 s = first_non_digit;
460
Chris Lattner49842122008-11-22 07:39:03 +0000461 if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000462 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000463 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000464 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
465 diag::err_hexconstant_requires_exponent);
466 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000467 }
468 return;
469 }
470
471 // Handle simple binary numbers 0b01010
472 if (*s == 'b' || *s == 'B') {
473 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000474 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000475 ++s;
476 radix = 2;
477 DigitsBegin = s;
478 s = SkipBinaryDigits(s);
479 if (s == ThisTokEnd) {
480 // Done.
481 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000482 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
483 diag::err_invalid_binary_digit) << std::string(s, s+1);
484 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000485 }
Chris Lattner413d3552008-06-30 06:44:49 +0000486 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000487 return;
488 }
489
490 // For now, the radix is set to 8. If we discover that we have a
491 // floating point constant, the radix will change to 10. Octal floating
492 // point constants are not permitted (only decimal and hexadecimal).
493 radix = 8;
494 DigitsBegin = s;
495 s = SkipOctalDigits(s);
496 if (s == ThisTokEnd)
497 return; // Done, simple octal number like 01234
498
Chris Lattner413d3552008-06-30 06:44:49 +0000499 // If we have some other non-octal digit that *is* a decimal digit, see if
500 // this is part of a floating point number like 094.123 or 09e1.
501 if (isdigit(*s)) {
502 const char *EndDecimal = SkipDigits(s);
503 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
504 s = EndDecimal;
505 radix = 10;
506 }
507 }
508
509 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
510 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000511 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000512 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
513 diag::err_invalid_octal_digit) << std::string(s, s+1);
514 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000515 return;
516 }
517
518 if (*s == '.') {
519 s++;
520 radix = 10;
521 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000522 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000523 }
524 if (*s == 'e' || *s == 'E') { // exponent
525 const char *Exponent = s;
526 s++;
527 radix = 10;
528 saw_exponent = true;
529 if (*s == '+' || *s == '-') s++; // sign
530 const char *first_non_digit = SkipDigits(s);
531 if (first_non_digit != s) {
532 s = first_non_digit;
533 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000534 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
535 diag::err_exponent_has_no_digits);
536 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000537 return;
538 }
539 }
540}
541
542
Reid Spencer5f016e22007-07-11 17:01:13 +0000543/// GetIntegerValue - Convert this numeric literal value to an APInt that
544/// matches Val's input width. If there is an overflow, set Val to the low bits
545/// of the result and return true. Otherwise, return false.
546bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000547 // Fast path: Compute a conservative bound on the maximum number of
548 // bits per digit in this radix. If we can't possibly overflow a
549 // uint64 based on that bound then do the simple conversion to
550 // integer. This avoids the expensive overflow checking below, and
551 // handles the common cases that matter (small decimal integers and
552 // hex/octal values which don't overflow).
553 unsigned MaxBitsPerDigit = 1;
554 while ((1U << MaxBitsPerDigit) < radix)
555 MaxBitsPerDigit += 1;
556 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
557 uint64_t N = 0;
558 for (s = DigitsBegin; s != SuffixBegin; ++s)
559 N = N*radix + HexDigitValue(*s);
560
561 // This will truncate the value to Val's input width. Simply check
562 // for overflow by comparing.
563 Val = N;
564 return Val.getZExtValue() != N;
565 }
566
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 Val = 0;
568 s = DigitsBegin;
569
570 llvm::APInt RadixVal(Val.getBitWidth(), radix);
571 llvm::APInt CharVal(Val.getBitWidth(), 0);
572 llvm::APInt OldVal = Val;
573
574 bool OverflowOccurred = false;
575 while (s < SuffixBegin) {
576 unsigned C = HexDigitValue(*s++);
577
578 // If this letter is out of bound for this radix, reject it.
579 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
580
581 CharVal = C;
582
583 // Add the digit to the value in the appropriate radix. If adding in digits
584 // made the value smaller, then this overflowed.
585 OldVal = Val;
586
587 // Multiply by radix, did overflow occur on the multiply?
588 Val *= RadixVal;
589 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000592 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 OverflowOccurred |= Val.ult(CharVal);
595 }
596 return OverflowOccurred;
597}
598
Chris Lattner525a0502007-09-22 18:29:59 +0000599llvm::APFloat NumericLiteralParser::
Ted Kremenek427d5af2007-11-26 23:12:30 +0000600GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
601 using llvm::APFloat;
602
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000603 llvm::SmallVector<char,256> floatChars;
604 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
605 floatChars.push_back(ThisTokBegin[i]);
606
607 floatChars.push_back('\0');
608
Ted Kremenek427d5af2007-11-26 23:12:30 +0000609 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000610 APFloat::opStatus status;
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000611
612 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000613
614 if (isExact)
615 *isExact = status == APFloat::opOK;
616
617 return V;
Reid Spencer5f016e22007-07-11 17:01:13 +0000618}
619
Reid Spencer5f016e22007-07-11 17:01:13 +0000620
621CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
622 SourceLocation Loc, Preprocessor &PP) {
623 // At this point we know that the character matches the regex "L?'.*'".
624 HadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000625
626 // Determine if this is a wide character.
627 IsWide = begin[0] == 'L';
628 if (IsWide) ++begin;
629
630 // Skip over the entry quote.
631 assert(begin[0] == '\'' && "Invalid token lexed");
632 ++begin;
633
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000634 // FIXME: The "Value" is an uint64_t so we can handle char literals of
635 // upto 64-bits.
636 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
637 "Assumes sizeof(int) on target is <= 64");
638 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
639 "Assumes sizeof(wchar) on target is <= 64");
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000641 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 "Assumes char is 8 bits");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000643
644 // This is what we will use for overflow detection
645 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000646
647 bool isFirstChar = true;
648 bool isMultiChar = false;
649 while (begin[0] != '\'') {
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000650 uint64_t ResultChar;
Reid Spencer5f016e22007-07-11 17:01:13 +0000651 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'.
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000671 LitVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 } else {
673 // Narrow character literals act as though their value is concatenated
674 // in this implementation.
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000675 if ((LitVal.shl(8)).lshr(8) != LitVal)
676 // if (((LitVal << 8) >> 8) != LitVal)
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 PP.Diag(Loc, diag::warn_char_constant_too_large);
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000678 LitVal <<= 8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 }
680 }
681
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000682 LitVal = LitVal + ResultChar;
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 isFirstChar = false;
684 }
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000685
686 // Transfer the value from APInt to uint64_t
687 Value = LitVal.getZExtValue();
Reid Spencer5f016e22007-07-11 17:01:13 +0000688
689 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
690 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
691 // character constants are not sign extended in the this implementation:
692 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
693 if (!IsWide && !isMultiChar && (Value & 128) &&
Chris Lattner98be4942008-03-05 18:54:05 +0000694 PP.getTargetInfo().isCharSigned())
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 Value = (signed char)Value;
696}
697
698
699/// string-literal: [C99 6.4.5]
700/// " [s-char-sequence] "
701/// L" [s-char-sequence] "
702/// s-char-sequence:
703/// s-char
704/// s-char-sequence s-char
705/// s-char:
706/// any source character except the double quote ",
707/// backslash \, or newline character
708/// escape-character
709/// universal-character-name
710/// escape-character: [C99 6.4.4.4]
711/// \ escape-code
712/// universal-character-name
713/// escape-code:
714/// character-escape-code
715/// octal-escape-code
716/// hex-escape-code
717/// character-escape-code: one of
718/// n t b r f v a
719/// \ ' " ?
720/// octal-escape-code:
721/// octal-digit
722/// octal-digit octal-digit
723/// octal-digit octal-digit octal-digit
724/// hex-escape-code:
725/// x hex-digit
726/// hex-escape-code hex-digit
727/// universal-character-name:
728/// \u hex-quad
729/// \U hex-quad hex-quad
730/// hex-quad:
731/// hex-digit hex-digit hex-digit hex-digit
732///
733StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000734StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000735 Preprocessor &pp) : PP(pp) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // Scan all of the string portions, remember the max individual token length,
737 // computing a bound on the concatenated string length, and see whether any
738 // piece is a wide-string. If any of the string portions is a wide-string
739 // literal, the result is a wide-string literal [C99 6.4.5p4].
740 MaxTokenLength = StringToks[0].getLength();
741 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000742 AnyWide = StringToks[0].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000743
744 hadError = false;
745
746 // Implement Translation Phase #6: concatenation of string literals
747 /// (C99 5.1.1.2p1). The common case is only one string fragment.
748 for (unsigned i = 1; i != NumStringToks; ++i) {
749 // The string could be shorter than this if it needs cleaning, but this is a
750 // reasonable bound, which is all we need.
751 SizeBound += StringToks[i].getLength()-2; // -2 for "".
752
753 // Remember maximum string piece length.
754 if (StringToks[i].getLength() > MaxTokenLength)
755 MaxTokenLength = StringToks[i].getLength();
756
757 // Remember if we see any wide strings.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000758 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // Include space for the null terminator.
762 ++SizeBound;
763
764 // TODO: K&R warning: "traditional C rejects string constant concatenation"
765
766 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
767 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
768 wchar_tByteWidth = ~0U;
769 if (AnyWide) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000770 wchar_tByteWidth = PP.getTargetInfo().getWCharWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
772 wchar_tByteWidth /= 8;
773 }
774
775 // The output buffer size needs to be large enough to hold wide characters.
776 // This is a worst-case assumption which basically corresponds to L"" "long".
777 if (AnyWide)
778 SizeBound *= wchar_tByteWidth;
779
780 // Size the temporary buffer to hold the result string data.
781 ResultBuf.resize(SizeBound);
782
783 // Likewise, but for each string piece.
784 llvm::SmallString<512> TokenBuf;
785 TokenBuf.resize(MaxTokenLength);
786
787 // Loop over all the strings, getting their spelling, and expanding them to
788 // wide strings as appropriate.
789 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
790
Anders Carlssonee98ac52007-10-15 02:50:23 +0000791 Pascal = false;
792
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
794 const char *ThisTokBuf = &TokenBuf[0];
795 // Get the spelling of the token, which eliminates trigraphs, etc. We know
796 // that ThisTokBuf points to a buffer that is big enough for the whole token
797 // and 'spelled' tokens can only shrink.
798 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
799 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
800
801 // TODO: Input character set mapping support.
802
803 // Skip L marker for wide strings.
804 bool ThisIsWide = false;
805 if (ThisTokBuf[0] == 'L') {
806 ++ThisTokBuf;
807 ThisIsWide = true;
808 }
809
810 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
811 ++ThisTokBuf;
812
Anders Carlssonee98ac52007-10-15 02:50:23 +0000813 // Check if this is a pascal string
814 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
815 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
816
817 // If the \p sequence is found in the first token, we have a pascal string
818 // Otherwise, if we already have a pascal string, ignore the first \p
819 if (i == 0) {
820 ++ThisTokBuf;
821 Pascal = true;
822 } else if (Pascal)
823 ThisTokBuf += 2;
824 }
825
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 while (ThisTokBuf != ThisTokEnd) {
827 // Is this a span of non-escape characters?
828 if (ThisTokBuf[0] != '\\') {
829 const char *InStart = ThisTokBuf;
830 do {
831 ++ThisTokBuf;
832 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
833
834 // Copy the character span over.
835 unsigned Len = ThisTokBuf-InStart;
836 if (!AnyWide) {
837 memcpy(ResultPtr, InStart, Len);
838 ResultPtr += Len;
839 } else {
840 // Note: our internal rep of wide char tokens is always little-endian.
841 for (; Len; --Len, ++InStart) {
842 *ResultPtr++ = InStart[0];
843 // Add zeros at the end.
844 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000845 *ResultPtr++ = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 }
847 }
848 continue;
849 }
Steve Naroff4e93b342009-04-01 11:09:15 +0000850 // Is this a Universal Character Name escape?
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000851 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
852 ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000853 hadError, StringToks[i].getLocation(), ThisIsWide, PP);
Steve Naroff4e93b342009-04-01 11:09:15 +0000854 continue;
855 }
856 // Otherwise, this is a non-UCN escape character. Process it.
857 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
858 StringToks[i].getLocation(),
859 ThisIsWide, PP);
860
861 // Note: our internal rep of wide char tokens is always little-endian.
862 *ResultPtr++ = ResultChar & 0xFF;
863
864 if (AnyWide) {
865 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
866 *ResultPtr++ = ResultChar >> i*8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 }
868 }
869 }
870
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000871 if (Pascal) {
Anders Carlssonee98ac52007-10-15 02:50:23 +0000872 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000873
874 // Verify that pascal strings aren't too large.
Eli Friedman57d7dde2009-04-01 03:17:08 +0000875 if (GetStringLength() > 256) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000876 PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
877 << SourceRange(StringToks[0].getLocation(),
878 StringToks[NumStringToks-1].getLocation());
Eli Friedman57d7dde2009-04-01 03:17:08 +0000879 hadError = 1;
880 return;
881 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000882 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000883}
Chris Lattner719e6152009-02-18 19:21:10 +0000884
885
886/// getOffsetOfStringByte - This function returns the offset of the
887/// specified byte of the string data represented by Token. This handles
888/// advancing over escape sequences in the string.
889unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
890 unsigned ByteNo,
891 Preprocessor &PP) {
892 // Get the spelling of the token.
893 llvm::SmallString<16> SpellingBuffer;
894 SpellingBuffer.resize(Tok.getLength());
895
896 const char *SpellingPtr = &SpellingBuffer[0];
897 unsigned TokLen = PP.getSpelling(Tok, SpellingPtr);
898
899 assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet");
900
901
902 const char *SpellingStart = SpellingPtr;
903 const char *SpellingEnd = SpellingPtr+TokLen;
904
905 // Skip over the leading quote.
906 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
907 ++SpellingPtr;
908
909 // Skip over bytes until we find the offset we're looking for.
910 while (ByteNo) {
911 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
912
913 // Step over non-escapes simply.
914 if (*SpellingPtr != '\\') {
915 ++SpellingPtr;
916 --ByteNo;
917 continue;
918 }
919
920 // Otherwise, this is an escape character. Advance over it.
921 bool HadError = false;
922 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
923 Tok.getLocation(), false, PP);
924 assert(!HadError && "This method isn't valid on erroneous strings");
925 --ByteNo;
926 }
927
928 return SpellingPtr-SpellingStart;
929}