blob: cb04e0030542c686c58643c22f0b2f0c4167e795 [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"
Erick Tryzelaare9f195f2009-08-16 23:36:28 +000019#include "llvm/ADT/StringRef.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "llvm/ADT/StringExtras.h"
21using namespace clang;
22
23/// HexDigitValue - Return the value of the specified hex digit, or -1 if it's
24/// not valid.
25static int HexDigitValue(char C) {
26 if (C >= '0' && C <= '9') return C-'0';
27 if (C >= 'a' && C <= 'f') return C-'a'+10;
28 if (C >= 'A' && C <= 'F') return C-'A'+10;
29 return -1;
30}
31
32/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
33/// either a character or a string literal.
34static unsigned ProcessCharEscape(const char *&ThisTokBuf,
35 const char *ThisTokEnd, bool &HadError,
36 SourceLocation Loc, bool IsWide,
37 Preprocessor &PP) {
38 // Skip the '\' char.
39 ++ThisTokBuf;
40
41 // We know that this character can't be off the end of the buffer, because
42 // that would have been \", which would not have been the end of string.
43 unsigned ResultChar = *ThisTokBuf++;
44 switch (ResultChar) {
45 // These map to themselves.
46 case '\\': case '\'': case '"': case '?': break;
47
48 // These have fixed mappings.
49 case 'a':
50 // TODO: K&R: the meaning of '\\a' is different in traditional C
51 ResultChar = 7;
52 break;
53 case 'b':
54 ResultChar = 8;
55 break;
56 case 'e':
Chris Lattner204b2fe2008-11-18 21:48:13 +000057 PP.Diag(Loc, diag::ext_nonstandard_escape) << "e";
Reid Spencer5f016e22007-07-11 17:01:13 +000058 ResultChar = 27;
59 break;
Eli Friedman3c548012009-06-10 01:32:39 +000060 case 'E':
61 PP.Diag(Loc, diag::ext_nonstandard_escape) << "E";
62 ResultChar = 27;
63 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000064 case 'f':
65 ResultChar = 12;
66 break;
67 case 'n':
68 ResultChar = 10;
69 break;
70 case 'r':
71 ResultChar = 13;
72 break;
73 case 't':
74 ResultChar = 9;
75 break;
76 case 'v':
77 ResultChar = 11;
78 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000079 case 'x': { // Hex escape.
80 ResultChar = 0;
81 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
82 PP.Diag(Loc, diag::err_hex_escape_no_digits);
83 HadError = 1;
84 break;
85 }
86
87 // Hex escapes are a maximal series of hex digits.
88 bool Overflow = false;
89 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
90 int CharVal = HexDigitValue(ThisTokBuf[0]);
91 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +000092 // About to shift out a digit?
93 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +000094 ResultChar <<= 4;
95 ResultChar |= CharVal;
96 }
97
98 // See if any bits will be truncated when evaluated as a character.
Alisdair Meredith1a75ee22009-07-14 08:10:06 +000099 unsigned CharWidth = IsWide
100 ? PP.getTargetInfo().getWCharWidth()
101 : PP.getTargetInfo().getCharWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
104 Overflow = true;
105 ResultChar &= ~0U >> (32-CharWidth);
106 }
107
108 // Check for overflow.
109 if (Overflow) // Too many digits to fit in
110 PP.Diag(Loc, diag::warn_hex_escape_too_large);
111 break;
112 }
113 case '0': case '1': case '2': case '3':
114 case '4': case '5': case '6': case '7': {
115 // Octal escapes.
116 --ThisTokBuf;
117 ResultChar = 0;
118
119 // Octal escapes are a series of octal digits with maximum length 3.
120 // "\0123" is a two digit sequence equal to "\012" "3".
121 unsigned NumDigits = 0;
122 do {
123 ResultChar <<= 3;
124 ResultChar |= *ThisTokBuf++ - '0';
125 ++NumDigits;
126 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
127 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
128
129 // Check for overflow. Reject '\777', but not L'\777'.
Alisdair Meredith1a75ee22009-07-14 08:10:06 +0000130 unsigned CharWidth = IsWide
131 ? PP.getTargetInfo().getWCharWidth()
132 : PP.getTargetInfo().getCharWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000133
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
135 PP.Diag(Loc, diag::warn_octal_escape_too_large);
136 ResultChar &= ~0U >> (32-CharWidth);
137 }
138 break;
139 }
140
141 // Otherwise, these are not valid escapes.
142 case '(': case '{': case '[': case '%':
143 // GCC accepts these as extensions. We warn about them as such though.
Eli Friedmanf01fdff2009-04-28 00:51:18 +0000144 PP.Diag(Loc, diag::ext_nonstandard_escape)
145 << std::string()+(char)ResultChar;
146 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 default:
Chris Lattnerac92d822008-11-22 07:23:31 +0000148 if (isgraph(ThisTokBuf[0]))
Chris Lattner204b2fe2008-11-18 21:48:13 +0000149 PP.Diag(Loc, diag::ext_unknown_escape) << std::string()+(char)ResultChar;
Chris Lattnerac92d822008-11-22 07:23:31 +0000150 else
Chris Lattner204b2fe2008-11-18 21:48:13 +0000151 PP.Diag(Loc, diag::ext_unknown_escape) << "x"+llvm::utohexstr(ResultChar);
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 break;
153 }
154
155 return ResultChar;
156}
157
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000158/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
159/// convert the UTF32 to UTF8. This is a subroutine of StringLiteralParser.
160/// When we decide to implement UCN's for character constants and identifiers,
161/// we will likely rework our support for UCN's.
162static void ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000163 char *&ResultBuf, bool &HadError,
164 SourceLocation Loc, bool IsWide, Preprocessor &PP)
165{
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000166 // FIXME: Add a warning - UCN's are only valid in C++ & C99.
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000167 // FIXME: Handle wide strings.
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000168
Steve Naroff4e93b342009-04-01 11:09:15 +0000169 // Save the beginning of the string (for error diagnostics).
170 const char *ThisTokBegin = ThisTokBuf;
171
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000172 // Skip the '\u' char's.
173 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000174
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000175 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
176 PP.Diag(Loc, diag::err_ucn_escape_no_digits);
177 HadError = 1;
178 return;
179 }
Steve Naroff4e93b342009-04-01 11:09:15 +0000180 typedef uint32_t UTF32;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000181
182 UTF32 UcnVal = 0;
183 unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
184 for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) {
185 int CharVal = HexDigitValue(ThisTokBuf[0]);
186 if (CharVal == -1) break;
187 UcnVal <<= 4;
188 UcnVal |= CharVal;
189 }
190 // If we didn't consume the proper number of digits, there is a problem.
191 if (UcnLen) {
Steve Naroff4e93b342009-04-01 11:09:15 +0000192 PP.Diag(PP.AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin),
193 diag::err_ucn_escape_incomplete);
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000194 HadError = 1;
195 return;
196 }
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000197 // Check UCN constraints (C99 6.4.3p2).
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000198 if ((UcnVal < 0xa0 &&
199 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000200 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)
201 || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000202 PP.Diag(Loc, diag::err_ucn_escape_invalid);
203 HadError = 1;
204 return;
205 }
206 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
207 // The conversion below was inspired by:
208 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
209 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000210 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000211
212 unsigned short bytesToWrite = 0;
213 if (UcnVal < (UTF32)0x80)
214 bytesToWrite = 1;
215 else if (UcnVal < (UTF32)0x800)
216 bytesToWrite = 2;
217 else if (UcnVal < (UTF32)0x10000)
218 bytesToWrite = 3;
219 else
220 bytesToWrite = 4;
221
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000222 const unsigned byteMask = 0xBF;
223 const unsigned byteMark = 0x80;
224
225 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000226 // into the first byte, depending on how many bytes follow.
227 static const UTF8 firstByteMark[5] = {
228 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000229 };
230 // Finally, we write the bytes into ResultBuf.
231 ResultBuf += bytesToWrite;
232 switch (bytesToWrite) { // note: everything falls through.
233 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
234 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
235 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
236 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
237 }
238 // Update the buffer.
239 ResultBuf += bytesToWrite;
240}
Reid Spencer5f016e22007-07-11 17:01:13 +0000241
242
243/// integer-constant: [C99 6.4.4.1]
244/// decimal-constant integer-suffix
245/// octal-constant integer-suffix
246/// hexadecimal-constant integer-suffix
247/// decimal-constant:
248/// nonzero-digit
249/// decimal-constant digit
250/// octal-constant:
251/// 0
252/// octal-constant octal-digit
253/// hexadecimal-constant:
254/// hexadecimal-prefix hexadecimal-digit
255/// hexadecimal-constant hexadecimal-digit
256/// hexadecimal-prefix: one of
257/// 0x 0X
258/// integer-suffix:
259/// unsigned-suffix [long-suffix]
260/// unsigned-suffix [long-long-suffix]
261/// long-suffix [unsigned-suffix]
262/// long-long-suffix [unsigned-sufix]
263/// nonzero-digit:
264/// 1 2 3 4 5 6 7 8 9
265/// octal-digit:
266/// 0 1 2 3 4 5 6 7
267/// hexadecimal-digit:
268/// 0 1 2 3 4 5 6 7 8 9
269/// a b c d e f
270/// A B C D E F
271/// unsigned-suffix: one of
272/// u U
273/// long-suffix: one of
274/// l L
275/// long-long-suffix: one of
276/// ll LL
277///
278/// floating-constant: [C99 6.4.4.2]
279/// TODO: add rules...
280///
Reid Spencer5f016e22007-07-11 17:01:13 +0000281NumericLiteralParser::
282NumericLiteralParser(const char *begin, const char *end,
283 SourceLocation TokLoc, Preprocessor &pp)
284 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000285
286 // This routine assumes that the range begin/end matches the regex for integer
287 // and FP constants (specifically, the 'pp-number' regex), and assumes that
288 // the byte at "*end" is both valid and not part of the regex. Because of
289 // this, it doesn't have to check for 'overscan' in various places.
290 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
291 "Lexer didn't maximally munch?");
292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 s = DigitsBegin = begin;
294 saw_exponent = false;
295 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 isLong = false;
297 isUnsigned = false;
298 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000299 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000300 isImaginary = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 hadError = false;
302
303 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000304 ParseNumberStartingWithZero(TokLoc);
305 if (hadError)
306 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 } else { // the first digit is non-zero
308 radix = 10;
309 s = SkipDigits(s);
310 if (s == ThisTokEnd) {
311 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000312 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000313 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
314 diag::err_invalid_decimal_digit) << std::string(s, s+1);
315 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 return;
317 } else if (*s == '.') {
318 s++;
319 saw_period = true;
320 s = SkipDigits(s);
321 }
Chris Lattner4411f462008-09-29 23:12:31 +0000322 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000323 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 s++;
325 saw_exponent = true;
326 if (*s == '+' || *s == '-') s++; // sign
327 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000328 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000330 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000331 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
332 diag::err_exponent_has_no_digits);
333 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000334 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 }
336 }
337 }
338
339 SuffixBegin = s;
Chris Lattner506b8de2007-08-26 01:58:14 +0000340
341 // Parse the suffix. At this point we can classify whether we have an FP or
342 // integer constant.
343 bool isFPConstant = isFloatingLiteral();
344
345 // Loop over all of the characters of the suffix. If we see something bad,
346 // we break out of the loop.
347 for (; s != ThisTokEnd; ++s) {
348 switch (*s) {
349 case 'f': // FP Suffix for "float"
350 case 'F':
351 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000352 if (isFloat || isLong) break; // FF, LF invalid.
353 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000354 continue; // Success.
355 case 'u':
356 case 'U':
357 if (isFPConstant) break; // Error for floating constant.
358 if (isUnsigned) break; // Cannot be repeated.
359 isUnsigned = true;
360 continue; // Success.
361 case 'l':
362 case 'L':
363 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000364 if (isFloat) break; // LF invalid.
Chris Lattner506b8de2007-08-26 01:58:14 +0000365
366 // Check for long long. The L's need to be adjacent and the same case.
367 if (s+1 != ThisTokEnd && s[1] == s[0]) {
368 if (isFPConstant) break; // long long invalid for floats.
369 isLongLong = true;
370 ++s; // Eat both of them.
371 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000374 continue; // Success.
375 case 'i':
Steve Naroff0c29b222008-04-04 21:02:54 +0000376 if (PP.getLangOptions().Microsoft) {
377 // Allow i8, i16, i32, i64, and i128.
378 if (++s == ThisTokEnd) break;
379 switch (*s) {
380 case '8':
381 s++; // i8 suffix
382 break;
383 case '1':
384 if (++s == ThisTokEnd) break;
385 if (*s == '6') s++; // i16 suffix
386 else if (*s == '2') {
387 if (++s == ThisTokEnd) break;
388 if (*s == '8') s++; // i128 suffix
389 }
390 break;
391 case '3':
392 if (++s == ThisTokEnd) break;
393 if (*s == '2') s++; // i32 suffix
394 break;
395 case '6':
396 if (++s == ThisTokEnd) break;
397 if (*s == '4') s++; // i64 suffix
398 break;
399 default:
400 break;
401 }
402 break;
403 }
404 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000405 case 'I':
406 case 'j':
407 case 'J':
408 if (isImaginary) break; // Cannot be repeated.
409 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
410 diag::ext_imaginary_constant);
411 isImaginary = true;
412 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000414 // If we reached here, there was an error.
415 break;
416 }
417
418 // Report an error if there are any.
419 if (s != ThisTokEnd) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000420 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
421 isFPConstant ? diag::err_invalid_suffix_float_constant :
422 diag::err_invalid_suffix_integer_constant)
423 << std::string(SuffixBegin, ThisTokEnd);
424 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000425 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 }
427}
428
Chris Lattner368328c2008-06-30 06:39:54 +0000429/// ParseNumberStartingWithZero - This method is called when the first character
430/// of the number is found to be a zero. This means it is either an octal
431/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
432/// a floating point number (01239.123e4). Eat the prefix, determining the
433/// radix etc.
434void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
435 assert(s[0] == '0' && "Invalid method call");
436 s++;
437
438 // Handle a hex number like 0x1234.
439 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
440 s++;
441 radix = 16;
442 DigitsBegin = s;
443 s = SkipHexDigits(s);
444 if (s == ThisTokEnd) {
445 // Done.
446 } else if (*s == '.') {
447 s++;
448 saw_period = true;
449 s = SkipHexDigits(s);
450 }
451 // A binary exponent can appear with or with a '.'. If dotted, the
452 // binary exponent is required.
Chris Lattner6ea62382008-07-25 18:18:34 +0000453 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000454 const char *Exponent = s;
455 s++;
456 saw_exponent = true;
457 if (*s == '+' || *s == '-') s++; // sign
458 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000459 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000460 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
461 diag::err_exponent_has_no_digits);
462 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000463 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000464 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000465 s = first_non_digit;
466
Chris Lattner49842122008-11-22 07:39:03 +0000467 if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000468 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000469 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000470 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
471 diag::err_hexconstant_requires_exponent);
472 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000473 }
474 return;
475 }
476
477 // Handle simple binary numbers 0b01010
478 if (*s == 'b' || *s == 'B') {
479 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000480 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000481 ++s;
482 radix = 2;
483 DigitsBegin = s;
484 s = SkipBinaryDigits(s);
485 if (s == ThisTokEnd) {
486 // Done.
487 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000488 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
489 diag::err_invalid_binary_digit) << std::string(s, s+1);
490 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000491 }
Chris Lattner413d3552008-06-30 06:44:49 +0000492 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000493 return;
494 }
495
496 // For now, the radix is set to 8. If we discover that we have a
497 // floating point constant, the radix will change to 10. Octal floating
498 // point constants are not permitted (only decimal and hexadecimal).
499 radix = 8;
500 DigitsBegin = s;
501 s = SkipOctalDigits(s);
502 if (s == ThisTokEnd)
503 return; // Done, simple octal number like 01234
504
Chris Lattner413d3552008-06-30 06:44:49 +0000505 // If we have some other non-octal digit that *is* a decimal digit, see if
506 // this is part of a floating point number like 094.123 or 09e1.
507 if (isdigit(*s)) {
508 const char *EndDecimal = SkipDigits(s);
509 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
510 s = EndDecimal;
511 radix = 10;
512 }
513 }
514
515 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
516 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000517 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000518 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
519 diag::err_invalid_octal_digit) << std::string(s, s+1);
520 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000521 return;
522 }
523
524 if (*s == '.') {
525 s++;
526 radix = 10;
527 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000528 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000529 }
530 if (*s == 'e' || *s == 'E') { // exponent
531 const char *Exponent = s;
532 s++;
533 radix = 10;
534 saw_exponent = true;
535 if (*s == '+' || *s == '-') s++; // sign
536 const char *first_non_digit = SkipDigits(s);
537 if (first_non_digit != s) {
538 s = first_non_digit;
539 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000540 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
541 diag::err_exponent_has_no_digits);
542 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000543 return;
544 }
545 }
546}
547
548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549/// GetIntegerValue - Convert this numeric literal value to an APInt that
550/// matches Val's input width. If there is an overflow, set Val to the low bits
551/// of the result and return true. Otherwise, return false.
552bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000553 // Fast path: Compute a conservative bound on the maximum number of
554 // bits per digit in this radix. If we can't possibly overflow a
555 // uint64 based on that bound then do the simple conversion to
556 // integer. This avoids the expensive overflow checking below, and
557 // handles the common cases that matter (small decimal integers and
558 // hex/octal values which don't overflow).
559 unsigned MaxBitsPerDigit = 1;
560 while ((1U << MaxBitsPerDigit) < radix)
561 MaxBitsPerDigit += 1;
562 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
563 uint64_t N = 0;
564 for (s = DigitsBegin; s != SuffixBegin; ++s)
565 N = N*radix + HexDigitValue(*s);
566
567 // This will truncate the value to Val's input width. Simply check
568 // for overflow by comparing.
569 Val = N;
570 return Val.getZExtValue() != N;
571 }
572
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 Val = 0;
574 s = DigitsBegin;
575
576 llvm::APInt RadixVal(Val.getBitWidth(), radix);
577 llvm::APInt CharVal(Val.getBitWidth(), 0);
578 llvm::APInt OldVal = Val;
579
580 bool OverflowOccurred = false;
581 while (s < SuffixBegin) {
582 unsigned C = HexDigitValue(*s++);
583
584 // If this letter is out of bound for this radix, reject it.
585 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
586
587 CharVal = C;
588
589 // Add the digit to the value in the appropriate radix. If adding in digits
590 // made the value smaller, then this overflowed.
591 OldVal = Val;
592
593 // Multiply by radix, did overflow occur on the multiply?
594 Val *= RadixVal;
595 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
596
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000598 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 OverflowOccurred |= Val.ult(CharVal);
601 }
602 return OverflowOccurred;
603}
604
Chris Lattner525a0502007-09-22 18:29:59 +0000605llvm::APFloat NumericLiteralParser::
Ted Kremenek427d5af2007-11-26 23:12:30 +0000606GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
607 using llvm::APFloat;
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000608 using llvm::StringRef;
Ted Kremenek427d5af2007-11-26 23:12:30 +0000609
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000610 llvm::SmallVector<char,256> floatChars;
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000611 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
612 for (unsigned i = 0; i != n; ++i)
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000613 floatChars.push_back(ThisTokBegin[i]);
614
615 floatChars.push_back('\0');
616
Ted Kremenek427d5af2007-11-26 23:12:30 +0000617 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000618 APFloat::opStatus status;
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000619
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000620 status = V.convertFromString(StringRef(&floatChars[0], n),
621 APFloat::rmNearestTiesToEven);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000622
623 if (isExact)
624 *isExact = status == APFloat::opOK;
625
626 return V;
Reid Spencer5f016e22007-07-11 17:01:13 +0000627}
628
Reid Spencer5f016e22007-07-11 17:01:13 +0000629
630CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
631 SourceLocation Loc, Preprocessor &PP) {
632 // At this point we know that the character matches the regex "L?'.*'".
633 HadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634
635 // Determine if this is a wide character.
636 IsWide = begin[0] == 'L';
637 if (IsWide) ++begin;
638
639 // Skip over the entry quote.
640 assert(begin[0] == '\'' && "Invalid token lexed");
641 ++begin;
642
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000643 // FIXME: The "Value" is an uint64_t so we can handle char literals of
644 // upto 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000646 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000648 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
649 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
650 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
651 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
652 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000653
654 // This is what we will use for overflow detection
655 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000656
Chris Lattnere3ad8812009-04-28 21:51:46 +0000657 unsigned NumCharsSoFar = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 while (begin[0] != '\'') {
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000659 uint64_t ResultChar;
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 if (begin[0] != '\\') // If this is a normal character, consume it.
661 ResultChar = *begin++;
662 else // Otherwise, this is an escape character.
663 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
664
665 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
666 // implementation defined (C99 6.4.4.4p10).
Chris Lattnere3ad8812009-04-28 21:51:46 +0000667 if (NumCharsSoFar) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 if (IsWide) {
669 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000670 LitVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 } else {
672 // Narrow character literals act as though their value is concatenated
Chris Lattnere3ad8812009-04-28 21:51:46 +0000673 // in this implementation, but warn on overflow.
674 if (LitVal.countLeadingZeros() < 8)
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 PP.Diag(Loc, diag::warn_char_constant_too_large);
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000676 LitVal <<= 8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 }
678 }
679
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000680 LitVal = LitVal + ResultChar;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000681 ++NumCharsSoFar;
682 }
683
684 // If this is the second character being processed, do special handling.
685 if (NumCharsSoFar > 1) {
686 // Warn about discarding the top bits for multi-char wide-character
687 // constants (L'abcd').
688 if (IsWide)
689 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
690 else if (NumCharsSoFar != 4)
691 PP.Diag(Loc, diag::ext_multichar_character_literal);
692 else
693 PP.Diag(Loc, diag::ext_four_char_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000694 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000695 } else
696 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000697
698 // Transfer the value from APInt to uint64_t
699 Value = LitVal.getZExtValue();
Reid Spencer5f016e22007-07-11 17:01:13 +0000700
701 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
702 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
703 // character constants are not sign extended in the this implementation:
704 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Chris Lattnere3ad8812009-04-28 21:51:46 +0000705 if (!IsWide && NumCharsSoFar == 1 && (Value & 128) &&
Eli Friedman15b91762009-06-05 07:05:05 +0000706 PP.getLangOptions().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 Value = (signed char)Value;
708}
709
710
711/// string-literal: [C99 6.4.5]
712/// " [s-char-sequence] "
713/// L" [s-char-sequence] "
714/// s-char-sequence:
715/// s-char
716/// s-char-sequence s-char
717/// s-char:
718/// any source character except the double quote ",
719/// backslash \, or newline character
720/// escape-character
721/// universal-character-name
722/// escape-character: [C99 6.4.4.4]
723/// \ escape-code
724/// universal-character-name
725/// escape-code:
726/// character-escape-code
727/// octal-escape-code
728/// hex-escape-code
729/// character-escape-code: one of
730/// n t b r f v a
731/// \ ' " ?
732/// octal-escape-code:
733/// octal-digit
734/// octal-digit octal-digit
735/// octal-digit octal-digit octal-digit
736/// hex-escape-code:
737/// x hex-digit
738/// hex-escape-code hex-digit
739/// universal-character-name:
740/// \u hex-quad
741/// \U hex-quad hex-quad
742/// hex-quad:
743/// hex-digit hex-digit hex-digit hex-digit
744///
745StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000746StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000747 Preprocessor &pp) : PP(pp) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 // Scan all of the string portions, remember the max individual token length,
749 // computing a bound on the concatenated string length, and see whether any
750 // piece is a wide-string. If any of the string portions is a wide-string
751 // literal, the result is a wide-string literal [C99 6.4.5p4].
752 MaxTokenLength = StringToks[0].getLength();
753 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000754 AnyWide = StringToks[0].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000755
756 hadError = false;
757
758 // Implement Translation Phase #6: concatenation of string literals
759 /// (C99 5.1.1.2p1). The common case is only one string fragment.
760 for (unsigned i = 1; i != NumStringToks; ++i) {
761 // The string could be shorter than this if it needs cleaning, but this is a
762 // reasonable bound, which is all we need.
763 SizeBound += StringToks[i].getLength()-2; // -2 for "".
764
765 // Remember maximum string piece length.
766 if (StringToks[i].getLength() > MaxTokenLength)
767 MaxTokenLength = StringToks[i].getLength();
768
769 // Remember if we see any wide strings.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000770 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 // Include space for the null terminator.
774 ++SizeBound;
775
776 // TODO: K&R warning: "traditional C rejects string constant concatenation"
777
778 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
779 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
780 wchar_tByteWidth = ~0U;
781 if (AnyWide) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000782 wchar_tByteWidth = PP.getTargetInfo().getWCharWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
784 wchar_tByteWidth /= 8;
785 }
786
787 // The output buffer size needs to be large enough to hold wide characters.
788 // This is a worst-case assumption which basically corresponds to L"" "long".
789 if (AnyWide)
790 SizeBound *= wchar_tByteWidth;
791
792 // Size the temporary buffer to hold the result string data.
793 ResultBuf.resize(SizeBound);
794
795 // Likewise, but for each string piece.
796 llvm::SmallString<512> TokenBuf;
797 TokenBuf.resize(MaxTokenLength);
798
799 // Loop over all the strings, getting their spelling, and expanding them to
800 // wide strings as appropriate.
801 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
802
Anders Carlssonee98ac52007-10-15 02:50:23 +0000803 Pascal = false;
804
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
806 const char *ThisTokBuf = &TokenBuf[0];
807 // Get the spelling of the token, which eliminates trigraphs, etc. We know
808 // that ThisTokBuf points to a buffer that is big enough for the whole token
809 // and 'spelled' tokens can only shrink.
810 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
811 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
812
813 // TODO: Input character set mapping support.
814
815 // Skip L marker for wide strings.
816 bool ThisIsWide = false;
817 if (ThisTokBuf[0] == 'L') {
818 ++ThisTokBuf;
819 ThisIsWide = true;
820 }
821
822 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
823 ++ThisTokBuf;
824
Anders Carlssonee98ac52007-10-15 02:50:23 +0000825 // Check if this is a pascal string
826 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
827 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
828
829 // If the \p sequence is found in the first token, we have a pascal string
830 // Otherwise, if we already have a pascal string, ignore the first \p
831 if (i == 0) {
832 ++ThisTokBuf;
833 Pascal = true;
834 } else if (Pascal)
835 ThisTokBuf += 2;
836 }
837
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 while (ThisTokBuf != ThisTokEnd) {
839 // Is this a span of non-escape characters?
840 if (ThisTokBuf[0] != '\\') {
841 const char *InStart = ThisTokBuf;
842 do {
843 ++ThisTokBuf;
844 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
845
846 // Copy the character span over.
847 unsigned Len = ThisTokBuf-InStart;
848 if (!AnyWide) {
849 memcpy(ResultPtr, InStart, Len);
850 ResultPtr += Len;
851 } else {
852 // Note: our internal rep of wide char tokens is always little-endian.
853 for (; Len; --Len, ++InStart) {
854 *ResultPtr++ = InStart[0];
855 // Add zeros at the end.
856 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000857 *ResultPtr++ = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 }
859 }
860 continue;
861 }
Steve Naroff4e93b342009-04-01 11:09:15 +0000862 // Is this a Universal Character Name escape?
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000863 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
864 ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000865 hadError, StringToks[i].getLocation(), ThisIsWide, PP);
Steve Naroff4e93b342009-04-01 11:09:15 +0000866 continue;
867 }
868 // Otherwise, this is a non-UCN escape character. Process it.
869 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
870 StringToks[i].getLocation(),
871 ThisIsWide, PP);
872
873 // Note: our internal rep of wide char tokens is always little-endian.
874 *ResultPtr++ = ResultChar & 0xFF;
875
876 if (AnyWide) {
877 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
878 *ResultPtr++ = ResultChar >> i*8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 }
880 }
881 }
882
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000883 if (Pascal) {
Anders Carlssonee98ac52007-10-15 02:50:23 +0000884 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000885
886 // Verify that pascal strings aren't too large.
Eli Friedman57d7dde2009-04-01 03:17:08 +0000887 if (GetStringLength() > 256) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000888 PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
889 << SourceRange(StringToks[0].getLocation(),
890 StringToks[NumStringToks-1].getLocation());
Eli Friedman57d7dde2009-04-01 03:17:08 +0000891 hadError = 1;
892 return;
893 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000894 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000895}
Chris Lattner719e6152009-02-18 19:21:10 +0000896
897
898/// getOffsetOfStringByte - This function returns the offset of the
899/// specified byte of the string data represented by Token. This handles
900/// advancing over escape sequences in the string.
901unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
902 unsigned ByteNo,
903 Preprocessor &PP) {
904 // Get the spelling of the token.
905 llvm::SmallString<16> SpellingBuffer;
906 SpellingBuffer.resize(Tok.getLength());
907
908 const char *SpellingPtr = &SpellingBuffer[0];
909 unsigned TokLen = PP.getSpelling(Tok, SpellingPtr);
910
911 assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet");
912
913
914 const char *SpellingStart = SpellingPtr;
915 const char *SpellingEnd = SpellingPtr+TokLen;
916
917 // Skip over the leading quote.
918 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
919 ++SpellingPtr;
920
921 // Skip over bytes until we find the offset we're looking for.
922 while (ByteNo) {
923 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
924
925 // Step over non-escapes simply.
926 if (*SpellingPtr != '\\') {
927 ++SpellingPtr;
928 --ByteNo;
929 continue;
930 }
931
932 // Otherwise, this is an escape character. Advance over it.
933 bool HadError = false;
934 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
935 Tok.getLocation(), false, PP);
936 assert(!HadError && "This method isn't valid on erroneous strings");
937 --ByteNo;
938 }
939
940 return SpellingPtr-SpellingStart;
941}