blob: 5da0e9c3ef73c10d94eaed360c4ac43dac04f0ab [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;
Eli Friedman3c548012009-06-10 01:32:39 +000059 case 'E':
60 PP.Diag(Loc, diag::ext_nonstandard_escape) << "E";
61 ResultChar = 27;
62 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000063 case 'f':
64 ResultChar = 12;
65 break;
66 case 'n':
67 ResultChar = 10;
68 break;
69 case 'r':
70 ResultChar = 13;
71 break;
72 case 't':
73 ResultChar = 9;
74 break;
75 case 'v':
76 ResultChar = 11;
77 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000078 case 'x': { // Hex escape.
79 ResultChar = 0;
80 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
81 PP.Diag(Loc, diag::err_hex_escape_no_digits);
82 HadError = 1;
83 break;
84 }
85
86 // Hex escapes are a maximal series of hex digits.
87 bool Overflow = false;
88 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
89 int CharVal = HexDigitValue(ThisTokBuf[0]);
90 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +000091 // About to shift out a digit?
92 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +000093 ResultChar <<= 4;
94 ResultChar |= CharVal;
95 }
96
97 // See if any bits will be truncated when evaluated as a character.
Alisdair Meredith1a75ee22009-07-14 08:10:06 +000098 unsigned CharWidth = IsWide
99 ? PP.getTargetInfo().getWCharWidth()
100 : PP.getTargetInfo().getCharWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000101
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
103 Overflow = true;
104 ResultChar &= ~0U >> (32-CharWidth);
105 }
106
107 // Check for overflow.
108 if (Overflow) // Too many digits to fit in
109 PP.Diag(Loc, diag::warn_hex_escape_too_large);
110 break;
111 }
112 case '0': case '1': case '2': case '3':
113 case '4': case '5': case '6': case '7': {
114 // Octal escapes.
115 --ThisTokBuf;
116 ResultChar = 0;
117
118 // Octal escapes are a series of octal digits with maximum length 3.
119 // "\0123" is a two digit sequence equal to "\012" "3".
120 unsigned NumDigits = 0;
121 do {
122 ResultChar <<= 3;
123 ResultChar |= *ThisTokBuf++ - '0';
124 ++NumDigits;
125 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
126 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
127
128 // Check for overflow. Reject '\777', but not L'\777'.
Alisdair Meredith1a75ee22009-07-14 08:10:06 +0000129 unsigned CharWidth = IsWide
130 ? PP.getTargetInfo().getWCharWidth()
131 : PP.getTargetInfo().getCharWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000132
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
134 PP.Diag(Loc, diag::warn_octal_escape_too_large);
135 ResultChar &= ~0U >> (32-CharWidth);
136 }
137 break;
138 }
139
140 // Otherwise, these are not valid escapes.
141 case '(': case '{': case '[': case '%':
142 // GCC accepts these as extensions. We warn about them as such though.
Eli Friedmanf01fdff2009-04-28 00:51:18 +0000143 PP.Diag(Loc, diag::ext_nonstandard_escape)
144 << std::string()+(char)ResultChar;
145 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 default:
Chris Lattnerac92d822008-11-22 07:23:31 +0000147 if (isgraph(ThisTokBuf[0]))
Chris Lattner204b2fe2008-11-18 21:48:13 +0000148 PP.Diag(Loc, diag::ext_unknown_escape) << std::string()+(char)ResultChar;
Chris Lattnerac92d822008-11-22 07:23:31 +0000149 else
Chris Lattner204b2fe2008-11-18 21:48:13 +0000150 PP.Diag(Loc, diag::ext_unknown_escape) << "x"+llvm::utohexstr(ResultChar);
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 break;
152 }
153
154 return ResultChar;
155}
156
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000157/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
158/// convert the UTF32 to UTF8. This is a subroutine of StringLiteralParser.
159/// When we decide to implement UCN's for character constants and identifiers,
160/// we will likely rework our support for UCN's.
161static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000162 char *&ResultBuf, bool &HadError,
163 SourceLocation Loc, bool IsWide, Preprocessor &PP)
164{
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000165 // FIXME: Add a warning - UCN's are only valid in C++ & C99.
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000166 // FIXME: Handle wide strings.
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000167
Steve Naroff4e93b342009-04-01 11:09:15 +0000168 // Save the beginning of the string (for error diagnostics).
169 const char *ThisTokBegin = ThisTokBuf;
170
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000171 // Skip the '\u' char's.
172 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000174 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
175 PP.Diag(Loc, diag::err_ucn_escape_no_digits);
176 HadError = 1;
177 return;
178 }
Steve Naroff4e93b342009-04-01 11:09:15 +0000179 typedef uint32_t UTF32;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000180
181 UTF32 UcnVal = 0;
182 unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
183 for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) {
184 int CharVal = HexDigitValue(ThisTokBuf[0]);
185 if (CharVal == -1) break;
186 UcnVal <<= 4;
187 UcnVal |= CharVal;
188 }
189 // If we didn't consume the proper number of digits, there is a problem.
190 if (UcnLen) {
Steve Naroff4e93b342009-04-01 11:09:15 +0000191 PP.Diag(PP.AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin),
192 diag::err_ucn_escape_incomplete);
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000193 HadError = 1;
194 return;
195 }
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000196 // Check UCN constraints (C99 6.4.3p2).
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000197 if ((UcnVal < 0xa0 &&
198 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000199 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)
200 || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000201 PP.Diag(Loc, diag::err_ucn_escape_invalid);
202 HadError = 1;
203 return;
204 }
205 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
206 // The conversion below was inspired by:
207 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
208 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000209 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000210
211 unsigned short bytesToWrite = 0;
212 if (UcnVal < (UTF32)0x80)
213 bytesToWrite = 1;
214 else if (UcnVal < (UTF32)0x800)
215 bytesToWrite = 2;
216 else if (UcnVal < (UTF32)0x10000)
217 bytesToWrite = 3;
218 else
219 bytesToWrite = 4;
220
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000221 const unsigned byteMask = 0xBF;
222 const unsigned byteMark = 0x80;
223
224 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000225 // into the first byte, depending on how many bytes follow.
226 static const UTF8 firstByteMark[5] = {
227 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000228 };
229 // Finally, we write the bytes into ResultBuf.
230 ResultBuf += bytesToWrite;
231 switch (bytesToWrite) { // note: everything falls through.
232 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
233 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
234 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
235 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
236 }
237 // Update the buffer.
238 ResultBuf += bytesToWrite;
239}
Reid Spencer5f016e22007-07-11 17:01:13 +0000240
241
242/// integer-constant: [C99 6.4.4.1]
243/// decimal-constant integer-suffix
244/// octal-constant integer-suffix
245/// hexadecimal-constant integer-suffix
246/// decimal-constant:
247/// nonzero-digit
248/// decimal-constant digit
249/// octal-constant:
250/// 0
251/// octal-constant octal-digit
252/// hexadecimal-constant:
253/// hexadecimal-prefix hexadecimal-digit
254/// hexadecimal-constant hexadecimal-digit
255/// hexadecimal-prefix: one of
256/// 0x 0X
257/// integer-suffix:
258/// unsigned-suffix [long-suffix]
259/// unsigned-suffix [long-long-suffix]
260/// long-suffix [unsigned-suffix]
261/// long-long-suffix [unsigned-sufix]
262/// nonzero-digit:
263/// 1 2 3 4 5 6 7 8 9
264/// octal-digit:
265/// 0 1 2 3 4 5 6 7
266/// hexadecimal-digit:
267/// 0 1 2 3 4 5 6 7 8 9
268/// a b c d e f
269/// A B C D E F
270/// unsigned-suffix: one of
271/// u U
272/// long-suffix: one of
273/// l L
274/// long-long-suffix: one of
275/// ll LL
276///
277/// floating-constant: [C99 6.4.4.2]
278/// TODO: add rules...
279///
Reid Spencer5f016e22007-07-11 17:01:13 +0000280NumericLiteralParser::
281NumericLiteralParser(const char *begin, const char *end,
282 SourceLocation TokLoc, Preprocessor &pp)
283 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000284
285 // This routine assumes that the range begin/end matches the regex for integer
286 // and FP constants (specifically, the 'pp-number' regex), and assumes that
287 // the byte at "*end" is both valid and not part of the regex. Because of
288 // this, it doesn't have to check for 'overscan' in various places.
289 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
290 "Lexer didn't maximally munch?");
291
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 s = DigitsBegin = begin;
293 saw_exponent = false;
294 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 isLong = false;
296 isUnsigned = false;
297 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000298 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000299 isImaginary = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 hadError = false;
301
302 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000303 ParseNumberStartingWithZero(TokLoc);
304 if (hadError)
305 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 } else { // the first digit is non-zero
307 radix = 10;
308 s = SkipDigits(s);
309 if (s == ThisTokEnd) {
310 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000311 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000312 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
313 diag::err_invalid_decimal_digit) << std::string(s, s+1);
314 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 return;
316 } else if (*s == '.') {
317 s++;
318 saw_period = true;
319 s = SkipDigits(s);
320 }
Chris Lattner4411f462008-09-29 23:12:31 +0000321 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000322 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 s++;
324 saw_exponent = true;
325 if (*s == '+' || *s == '-') s++; // sign
326 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000327 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000329 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000330 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
331 diag::err_exponent_has_no_digits);
332 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000333 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 }
335 }
336 }
337
338 SuffixBegin = s;
Chris Lattner506b8de2007-08-26 01:58:14 +0000339
340 // Parse the suffix. At this point we can classify whether we have an FP or
341 // integer constant.
342 bool isFPConstant = isFloatingLiteral();
343
344 // Loop over all of the characters of the suffix. If we see something bad,
345 // we break out of the loop.
346 for (; s != ThisTokEnd; ++s) {
347 switch (*s) {
348 case 'f': // FP Suffix for "float"
349 case 'F':
350 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000351 if (isFloat || isLong) break; // FF, LF invalid.
352 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000353 continue; // Success.
354 case 'u':
355 case 'U':
356 if (isFPConstant) break; // Error for floating constant.
357 if (isUnsigned) break; // Cannot be repeated.
358 isUnsigned = true;
359 continue; // Success.
360 case 'l':
361 case 'L':
362 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000363 if (isFloat) break; // LF invalid.
Chris Lattner506b8de2007-08-26 01:58:14 +0000364
365 // Check for long long. The L's need to be adjacent and the same case.
366 if (s+1 != ThisTokEnd && s[1] == s[0]) {
367 if (isFPConstant) break; // long long invalid for floats.
368 isLongLong = true;
369 ++s; // Eat both of them.
370 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000373 continue; // Success.
374 case 'i':
Steve Naroff0c29b222008-04-04 21:02:54 +0000375 if (PP.getLangOptions().Microsoft) {
376 // Allow i8, i16, i32, i64, and i128.
377 if (++s == ThisTokEnd) break;
378 switch (*s) {
379 case '8':
380 s++; // i8 suffix
381 break;
382 case '1':
383 if (++s == ThisTokEnd) break;
384 if (*s == '6') s++; // i16 suffix
385 else if (*s == '2') {
386 if (++s == ThisTokEnd) break;
387 if (*s == '8') s++; // i128 suffix
388 }
389 break;
390 case '3':
391 if (++s == ThisTokEnd) break;
392 if (*s == '2') s++; // i32 suffix
393 break;
394 case '6':
395 if (++s == ThisTokEnd) break;
396 if (*s == '4') s++; // i64 suffix
397 break;
398 default:
399 break;
400 }
401 break;
402 }
403 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000404 case 'I':
405 case 'j':
406 case 'J':
407 if (isImaginary) break; // Cannot be repeated.
408 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
409 diag::ext_imaginary_constant);
410 isImaginary = true;
411 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000413 // If we reached here, there was an error.
414 break;
415 }
416
417 // Report an error if there are any.
418 if (s != ThisTokEnd) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000419 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
420 isFPConstant ? diag::err_invalid_suffix_float_constant :
421 diag::err_invalid_suffix_integer_constant)
422 << std::string(SuffixBegin, ThisTokEnd);
423 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000424 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 }
426}
427
Chris Lattner368328c2008-06-30 06:39:54 +0000428/// ParseNumberStartingWithZero - This method is called when the first character
429/// of the number is found to be a zero. This means it is either an octal
430/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
431/// a floating point number (01239.123e4). Eat the prefix, determining the
432/// radix etc.
433void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
434 assert(s[0] == '0' && "Invalid method call");
435 s++;
436
437 // Handle a hex number like 0x1234.
438 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
439 s++;
440 radix = 16;
441 DigitsBegin = s;
442 s = SkipHexDigits(s);
443 if (s == ThisTokEnd) {
444 // Done.
445 } else if (*s == '.') {
446 s++;
447 saw_period = true;
448 s = SkipHexDigits(s);
449 }
450 // A binary exponent can appear with or with a '.'. If dotted, the
451 // binary exponent is required.
Chris Lattner6ea62382008-07-25 18:18:34 +0000452 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000453 const char *Exponent = s;
454 s++;
455 saw_exponent = true;
456 if (*s == '+' || *s == '-') s++; // sign
457 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000458 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000459 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
460 diag::err_exponent_has_no_digits);
461 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000462 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000463 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000464 s = first_non_digit;
465
Chris Lattner49842122008-11-22 07:39:03 +0000466 if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000467 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000468 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000469 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
470 diag::err_hexconstant_requires_exponent);
471 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000472 }
473 return;
474 }
475
476 // Handle simple binary numbers 0b01010
477 if (*s == 'b' || *s == 'B') {
478 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000479 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000480 ++s;
481 radix = 2;
482 DigitsBegin = s;
483 s = SkipBinaryDigits(s);
484 if (s == ThisTokEnd) {
485 // Done.
486 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000487 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
488 diag::err_invalid_binary_digit) << std::string(s, s+1);
489 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000490 }
Chris Lattner413d3552008-06-30 06:44:49 +0000491 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000492 return;
493 }
494
495 // For now, the radix is set to 8. If we discover that we have a
496 // floating point constant, the radix will change to 10. Octal floating
497 // point constants are not permitted (only decimal and hexadecimal).
498 radix = 8;
499 DigitsBegin = s;
500 s = SkipOctalDigits(s);
501 if (s == ThisTokEnd)
502 return; // Done, simple octal number like 01234
503
Chris Lattner413d3552008-06-30 06:44:49 +0000504 // If we have some other non-octal digit that *is* a decimal digit, see if
505 // this is part of a floating point number like 094.123 or 09e1.
506 if (isdigit(*s)) {
507 const char *EndDecimal = SkipDigits(s);
508 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
509 s = EndDecimal;
510 radix = 10;
511 }
512 }
513
514 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
515 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000516 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000517 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
518 diag::err_invalid_octal_digit) << std::string(s, s+1);
519 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000520 return;
521 }
522
523 if (*s == '.') {
524 s++;
525 radix = 10;
526 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000527 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000528 }
529 if (*s == 'e' || *s == 'E') { // exponent
530 const char *Exponent = s;
531 s++;
532 radix = 10;
533 saw_exponent = true;
534 if (*s == '+' || *s == '-') s++; // sign
535 const char *first_non_digit = SkipDigits(s);
536 if (first_non_digit != s) {
537 s = first_non_digit;
538 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000539 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
540 diag::err_exponent_has_no_digits);
541 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000542 return;
543 }
544 }
545}
546
547
Reid Spencer5f016e22007-07-11 17:01:13 +0000548/// GetIntegerValue - Convert this numeric literal value to an APInt that
549/// matches Val's input width. If there is an overflow, set Val to the low bits
550/// of the result and return true. Otherwise, return false.
551bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000552 // Fast path: Compute a conservative bound on the maximum number of
553 // bits per digit in this radix. If we can't possibly overflow a
554 // uint64 based on that bound then do the simple conversion to
555 // integer. This avoids the expensive overflow checking below, and
556 // handles the common cases that matter (small decimal integers and
557 // hex/octal values which don't overflow).
558 unsigned MaxBitsPerDigit = 1;
559 while ((1U << MaxBitsPerDigit) < radix)
560 MaxBitsPerDigit += 1;
561 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
562 uint64_t N = 0;
563 for (s = DigitsBegin; s != SuffixBegin; ++s)
564 N = N*radix + HexDigitValue(*s);
565
566 // This will truncate the value to Val's input width. Simply check
567 // for overflow by comparing.
568 Val = N;
569 return Val.getZExtValue() != N;
570 }
571
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 Val = 0;
573 s = DigitsBegin;
574
575 llvm::APInt RadixVal(Val.getBitWidth(), radix);
576 llvm::APInt CharVal(Val.getBitWidth(), 0);
577 llvm::APInt OldVal = Val;
578
579 bool OverflowOccurred = false;
580 while (s < SuffixBegin) {
581 unsigned C = HexDigitValue(*s++);
582
583 // If this letter is out of bound for this radix, reject it.
584 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
585
586 CharVal = C;
587
588 // Add the digit to the value in the appropriate radix. If adding in digits
589 // made the value smaller, then this overflowed.
590 OldVal = Val;
591
592 // Multiply by radix, did overflow occur on the multiply?
593 Val *= RadixVal;
594 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
595
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000597 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 OverflowOccurred |= Val.ult(CharVal);
600 }
601 return OverflowOccurred;
602}
603
Chris Lattner525a0502007-09-22 18:29:59 +0000604llvm::APFloat NumericLiteralParser::
Ted Kremenek427d5af2007-11-26 23:12:30 +0000605GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
606 using llvm::APFloat;
607
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000608 llvm::SmallVector<char,256> floatChars;
609 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
610 floatChars.push_back(ThisTokBegin[i]);
611
612 floatChars.push_back('\0');
613
Ted Kremenek427d5af2007-11-26 23:12:30 +0000614 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000615 APFloat::opStatus status;
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000616
617 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000618
619 if (isExact)
620 *isExact = status == APFloat::opOK;
621
622 return V;
Reid Spencer5f016e22007-07-11 17:01:13 +0000623}
624
Reid Spencer5f016e22007-07-11 17:01:13 +0000625
626CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
627 SourceLocation Loc, Preprocessor &PP) {
628 // At this point we know that the character matches the regex "L?'.*'".
629 HadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000630
631 // Determine if this is a wide character.
632 IsWide = begin[0] == 'L';
633 if (IsWide) ++begin;
634
635 // Skip over the entry quote.
636 assert(begin[0] == '\'' && "Invalid token lexed");
637 ++begin;
638
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000639 // FIXME: The "Value" is an uint64_t so we can handle char literals of
640 // upto 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000642 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000644 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
645 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
646 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
647 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
648 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000649
650 // This is what we will use for overflow detection
651 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000652
Chris Lattnere3ad8812009-04-28 21:51:46 +0000653 unsigned NumCharsSoFar = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 while (begin[0] != '\'') {
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000655 uint64_t ResultChar;
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 if (begin[0] != '\\') // If this is a normal character, consume it.
657 ResultChar = *begin++;
658 else // Otherwise, this is an escape character.
659 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
660
661 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
662 // implementation defined (C99 6.4.4.4p10).
Chris Lattnere3ad8812009-04-28 21:51:46 +0000663 if (NumCharsSoFar) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 if (IsWide) {
665 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000666 LitVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 } else {
668 // Narrow character literals act as though their value is concatenated
Chris Lattnere3ad8812009-04-28 21:51:46 +0000669 // in this implementation, but warn on overflow.
670 if (LitVal.countLeadingZeros() < 8)
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 PP.Diag(Loc, diag::warn_char_constant_too_large);
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000672 LitVal <<= 8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 }
674 }
675
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000676 LitVal = LitVal + ResultChar;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000677 ++NumCharsSoFar;
678 }
679
680 // If this is the second character being processed, do special handling.
681 if (NumCharsSoFar > 1) {
682 // Warn about discarding the top bits for multi-char wide-character
683 // constants (L'abcd').
684 if (IsWide)
685 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
686 else if (NumCharsSoFar != 4)
687 PP.Diag(Loc, diag::ext_multichar_character_literal);
688 else
689 PP.Diag(Loc, diag::ext_four_char_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000690 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000691 } else
692 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000693
694 // Transfer the value from APInt to uint64_t
695 Value = LitVal.getZExtValue();
Reid Spencer5f016e22007-07-11 17:01:13 +0000696
697 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
698 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
699 // character constants are not sign extended in the this implementation:
700 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Chris Lattnere3ad8812009-04-28 21:51:46 +0000701 if (!IsWide && NumCharsSoFar == 1 && (Value & 128) &&
Eli Friedman15b91762009-06-05 07:05:05 +0000702 PP.getLangOptions().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 Value = (signed char)Value;
704}
705
706
707/// string-literal: [C99 6.4.5]
708/// " [s-char-sequence] "
709/// L" [s-char-sequence] "
710/// s-char-sequence:
711/// s-char
712/// s-char-sequence s-char
713/// s-char:
714/// any source character except the double quote ",
715/// backslash \, or newline character
716/// escape-character
717/// universal-character-name
718/// escape-character: [C99 6.4.4.4]
719/// \ escape-code
720/// universal-character-name
721/// escape-code:
722/// character-escape-code
723/// octal-escape-code
724/// hex-escape-code
725/// character-escape-code: one of
726/// n t b r f v a
727/// \ ' " ?
728/// octal-escape-code:
729/// octal-digit
730/// octal-digit octal-digit
731/// octal-digit octal-digit octal-digit
732/// hex-escape-code:
733/// x hex-digit
734/// hex-escape-code hex-digit
735/// universal-character-name:
736/// \u hex-quad
737/// \U hex-quad hex-quad
738/// hex-quad:
739/// hex-digit hex-digit hex-digit hex-digit
740///
741StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000742StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000743 Preprocessor &pp) : PP(pp) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 // Scan all of the string portions, remember the max individual token length,
745 // computing a bound on the concatenated string length, and see whether any
746 // piece is a wide-string. If any of the string portions is a wide-string
747 // literal, the result is a wide-string literal [C99 6.4.5p4].
748 MaxTokenLength = StringToks[0].getLength();
749 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000750 AnyWide = StringToks[0].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000751
752 hadError = false;
753
754 // Implement Translation Phase #6: concatenation of string literals
755 /// (C99 5.1.1.2p1). The common case is only one string fragment.
756 for (unsigned i = 1; i != NumStringToks; ++i) {
757 // The string could be shorter than this if it needs cleaning, but this is a
758 // reasonable bound, which is all we need.
759 SizeBound += StringToks[i].getLength()-2; // -2 for "".
760
761 // Remember maximum string piece length.
762 if (StringToks[i].getLength() > MaxTokenLength)
763 MaxTokenLength = StringToks[i].getLength();
764
765 // Remember if we see any wide strings.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000766 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000768
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 // Include space for the null terminator.
770 ++SizeBound;
771
772 // TODO: K&R warning: "traditional C rejects string constant concatenation"
773
774 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
775 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
776 wchar_tByteWidth = ~0U;
777 if (AnyWide) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000778 wchar_tByteWidth = PP.getTargetInfo().getWCharWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
780 wchar_tByteWidth /= 8;
781 }
782
783 // The output buffer size needs to be large enough to hold wide characters.
784 // This is a worst-case assumption which basically corresponds to L"" "long".
785 if (AnyWide)
786 SizeBound *= wchar_tByteWidth;
787
788 // Size the temporary buffer to hold the result string data.
789 ResultBuf.resize(SizeBound);
790
791 // Likewise, but for each string piece.
792 llvm::SmallString<512> TokenBuf;
793 TokenBuf.resize(MaxTokenLength);
794
795 // Loop over all the strings, getting their spelling, and expanding them to
796 // wide strings as appropriate.
797 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
798
Anders Carlssonee98ac52007-10-15 02:50:23 +0000799 Pascal = false;
800
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
802 const char *ThisTokBuf = &TokenBuf[0];
803 // Get the spelling of the token, which eliminates trigraphs, etc. We know
804 // that ThisTokBuf points to a buffer that is big enough for the whole token
805 // and 'spelled' tokens can only shrink.
806 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
807 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
808
809 // TODO: Input character set mapping support.
810
811 // Skip L marker for wide strings.
812 bool ThisIsWide = false;
813 if (ThisTokBuf[0] == 'L') {
814 ++ThisTokBuf;
815 ThisIsWide = true;
816 }
817
818 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
819 ++ThisTokBuf;
820
Anders Carlssonee98ac52007-10-15 02:50:23 +0000821 // Check if this is a pascal string
822 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
823 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
824
825 // If the \p sequence is found in the first token, we have a pascal string
826 // Otherwise, if we already have a pascal string, ignore the first \p
827 if (i == 0) {
828 ++ThisTokBuf;
829 Pascal = true;
830 } else if (Pascal)
831 ThisTokBuf += 2;
832 }
833
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 while (ThisTokBuf != ThisTokEnd) {
835 // Is this a span of non-escape characters?
836 if (ThisTokBuf[0] != '\\') {
837 const char *InStart = ThisTokBuf;
838 do {
839 ++ThisTokBuf;
840 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
841
842 // Copy the character span over.
843 unsigned Len = ThisTokBuf-InStart;
844 if (!AnyWide) {
845 memcpy(ResultPtr, InStart, Len);
846 ResultPtr += Len;
847 } else {
848 // Note: our internal rep of wide char tokens is always little-endian.
849 for (; Len; --Len, ++InStart) {
850 *ResultPtr++ = InStart[0];
851 // Add zeros at the end.
852 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000853 *ResultPtr++ = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 }
855 }
856 continue;
857 }
Steve Naroff4e93b342009-04-01 11:09:15 +0000858 // Is this a Universal Character Name escape?
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000859 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
860 ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000861 hadError, StringToks[i].getLocation(), ThisIsWide, PP);
Steve Naroff4e93b342009-04-01 11:09:15 +0000862 continue;
863 }
864 // Otherwise, this is a non-UCN escape character. Process it.
865 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
866 StringToks[i].getLocation(),
867 ThisIsWide, PP);
868
869 // Note: our internal rep of wide char tokens is always little-endian.
870 *ResultPtr++ = ResultChar & 0xFF;
871
872 if (AnyWide) {
873 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
874 *ResultPtr++ = ResultChar >> i*8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 }
876 }
877 }
878
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000879 if (Pascal) {
Anders Carlssonee98ac52007-10-15 02:50:23 +0000880 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000881
882 // Verify that pascal strings aren't too large.
Eli Friedman57d7dde2009-04-01 03:17:08 +0000883 if (GetStringLength() > 256) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000884 PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
885 << SourceRange(StringToks[0].getLocation(),
886 StringToks[NumStringToks-1].getLocation());
Eli Friedman57d7dde2009-04-01 03:17:08 +0000887 hadError = 1;
888 return;
889 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000890 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000891}
Chris Lattner719e6152009-02-18 19:21:10 +0000892
893
894/// getOffsetOfStringByte - This function returns the offset of the
895/// specified byte of the string data represented by Token. This handles
896/// advancing over escape sequences in the string.
897unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
898 unsigned ByteNo,
899 Preprocessor &PP) {
900 // Get the spelling of the token.
901 llvm::SmallString<16> SpellingBuffer;
902 SpellingBuffer.resize(Tok.getLength());
903
904 const char *SpellingPtr = &SpellingBuffer[0];
905 unsigned TokLen = PP.getSpelling(Tok, SpellingPtr);
906
907 assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet");
908
909
910 const char *SpellingStart = SpellingPtr;
911 const char *SpellingEnd = SpellingPtr+TokLen;
912
913 // Skip over the leading quote.
914 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
915 ++SpellingPtr;
916
917 // Skip over bytes until we find the offset we're looking for.
918 while (ByteNo) {
919 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
920
921 // Step over non-escapes simply.
922 if (*SpellingPtr != '\\') {
923 ++SpellingPtr;
924 --ByteNo;
925 continue;
926 }
927
928 // Otherwise, this is an escape character. Advance over it.
929 bool HadError = false;
930 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
931 Tok.getLocation(), false, PP);
932 assert(!HadError && "This method isn't valid on erroneous strings");
933 --ByteNo;
934 }
935
936 return SpellingPtr-SpellingStart;
937}