blob: 345291382da600d78d34002db41ae461b9cdadf7 [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
163 // Skip the '\u' char's.
164 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000165
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000166 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
167 PP.Diag(Loc, diag::err_ucn_escape_no_digits);
168 HadError = 1;
169 return;
170 }
171 typedef unsigned int UTF32;
172
173 UTF32 UcnVal = 0;
174 unsigned short UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
175 for (; ThisTokBuf != ThisTokEnd && UcnLen; ++ThisTokBuf, UcnLen--) {
176 int CharVal = HexDigitValue(ThisTokBuf[0]);
177 if (CharVal == -1) break;
178 UcnVal <<= 4;
179 UcnVal |= CharVal;
180 }
181 // If we didn't consume the proper number of digits, there is a problem.
182 if (UcnLen) {
183 PP.Diag(Loc, diag::err_ucn_escape_incomplete);
184 HadError = 1;
185 return;
186 }
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000187 // Check UCN constraints (C99 6.4.3p2).
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000188 if ((UcnVal < 0xa0 &&
189 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000190 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)
191 || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000192 PP.Diag(Loc, diag::err_ucn_escape_invalid);
193 HadError = 1;
194 return;
195 }
196 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
197 // The conversion below was inspired by:
198 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
199 // First, we determine how many bytes the result will require.
200 typedef unsigned char UTF8;
201
202 unsigned short bytesToWrite = 0;
203 if (UcnVal < (UTF32)0x80)
204 bytesToWrite = 1;
205 else if (UcnVal < (UTF32)0x800)
206 bytesToWrite = 2;
207 else if (UcnVal < (UTF32)0x10000)
208 bytesToWrite = 3;
209 else
210 bytesToWrite = 4;
211
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000212 const unsigned byteMask = 0xBF;
213 const unsigned byteMark = 0x80;
214
215 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000216 // into the first byte, depending on how many bytes follow.
217 static const UTF8 firstByteMark[5] = {
218 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000219 };
220 // Finally, we write the bytes into ResultBuf.
221 ResultBuf += bytesToWrite;
222 switch (bytesToWrite) { // note: everything falls through.
223 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
224 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
225 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
226 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
227 }
228 // Update the buffer.
229 ResultBuf += bytesToWrite;
230}
Reid Spencer5f016e22007-07-11 17:01:13 +0000231
232
233/// integer-constant: [C99 6.4.4.1]
234/// decimal-constant integer-suffix
235/// octal-constant integer-suffix
236/// hexadecimal-constant integer-suffix
237/// decimal-constant:
238/// nonzero-digit
239/// decimal-constant digit
240/// octal-constant:
241/// 0
242/// octal-constant octal-digit
243/// hexadecimal-constant:
244/// hexadecimal-prefix hexadecimal-digit
245/// hexadecimal-constant hexadecimal-digit
246/// hexadecimal-prefix: one of
247/// 0x 0X
248/// integer-suffix:
249/// unsigned-suffix [long-suffix]
250/// unsigned-suffix [long-long-suffix]
251/// long-suffix [unsigned-suffix]
252/// long-long-suffix [unsigned-sufix]
253/// nonzero-digit:
254/// 1 2 3 4 5 6 7 8 9
255/// octal-digit:
256/// 0 1 2 3 4 5 6 7
257/// hexadecimal-digit:
258/// 0 1 2 3 4 5 6 7 8 9
259/// a b c d e f
260/// A B C D E F
261/// unsigned-suffix: one of
262/// u U
263/// long-suffix: one of
264/// l L
265/// long-long-suffix: one of
266/// ll LL
267///
268/// floating-constant: [C99 6.4.4.2]
269/// TODO: add rules...
270///
Reid Spencer5f016e22007-07-11 17:01:13 +0000271NumericLiteralParser::
272NumericLiteralParser(const char *begin, const char *end,
273 SourceLocation TokLoc, Preprocessor &pp)
274 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000275
276 // This routine assumes that the range begin/end matches the regex for integer
277 // and FP constants (specifically, the 'pp-number' regex), and assumes that
278 // the byte at "*end" is both valid and not part of the regex. Because of
279 // this, it doesn't have to check for 'overscan' in various places.
280 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
281 "Lexer didn't maximally munch?");
282
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 s = DigitsBegin = begin;
284 saw_exponent = false;
285 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 isLong = false;
287 isUnsigned = false;
288 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000289 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000290 isImaginary = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 hadError = false;
292
293 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000294 ParseNumberStartingWithZero(TokLoc);
295 if (hadError)
296 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 } else { // the first digit is non-zero
298 radix = 10;
299 s = SkipDigits(s);
300 if (s == ThisTokEnd) {
301 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000302 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000303 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
304 diag::err_invalid_decimal_digit) << std::string(s, s+1);
305 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 return;
307 } else if (*s == '.') {
308 s++;
309 saw_period = true;
310 s = SkipDigits(s);
311 }
Chris Lattner4411f462008-09-29 23:12:31 +0000312 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000313 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 s++;
315 saw_exponent = true;
316 if (*s == '+' || *s == '-') s++; // sign
317 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000318 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000320 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000321 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
322 diag::err_exponent_has_no_digits);
323 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000324 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 }
326 }
327 }
328
329 SuffixBegin = s;
Chris Lattner506b8de2007-08-26 01:58:14 +0000330
331 // Parse the suffix. At this point we can classify whether we have an FP or
332 // integer constant.
333 bool isFPConstant = isFloatingLiteral();
334
335 // Loop over all of the characters of the suffix. If we see something bad,
336 // we break out of the loop.
337 for (; s != ThisTokEnd; ++s) {
338 switch (*s) {
339 case 'f': // FP Suffix for "float"
340 case 'F':
341 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000342 if (isFloat || isLong) break; // FF, LF invalid.
343 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000344 continue; // Success.
345 case 'u':
346 case 'U':
347 if (isFPConstant) break; // Error for floating constant.
348 if (isUnsigned) break; // Cannot be repeated.
349 isUnsigned = true;
350 continue; // Success.
351 case 'l':
352 case 'L':
353 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000354 if (isFloat) break; // LF invalid.
Chris Lattner506b8de2007-08-26 01:58:14 +0000355
356 // Check for long long. The L's need to be adjacent and the same case.
357 if (s+1 != ThisTokEnd && s[1] == s[0]) {
358 if (isFPConstant) break; // long long invalid for floats.
359 isLongLong = true;
360 ++s; // Eat both of them.
361 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000364 continue; // Success.
365 case 'i':
Steve Naroff0c29b222008-04-04 21:02:54 +0000366 if (PP.getLangOptions().Microsoft) {
367 // Allow i8, i16, i32, i64, and i128.
368 if (++s == ThisTokEnd) break;
369 switch (*s) {
370 case '8':
371 s++; // i8 suffix
372 break;
373 case '1':
374 if (++s == ThisTokEnd) break;
375 if (*s == '6') s++; // i16 suffix
376 else if (*s == '2') {
377 if (++s == ThisTokEnd) break;
378 if (*s == '8') s++; // i128 suffix
379 }
380 break;
381 case '3':
382 if (++s == ThisTokEnd) break;
383 if (*s == '2') s++; // i32 suffix
384 break;
385 case '6':
386 if (++s == ThisTokEnd) break;
387 if (*s == '4') s++; // i64 suffix
388 break;
389 default:
390 break;
391 }
392 break;
393 }
394 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000395 case 'I':
396 case 'j':
397 case 'J':
398 if (isImaginary) break; // Cannot be repeated.
399 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
400 diag::ext_imaginary_constant);
401 isImaginary = true;
402 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000404 // If we reached here, there was an error.
405 break;
406 }
407
408 // Report an error if there are any.
409 if (s != ThisTokEnd) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000410 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
411 isFPConstant ? diag::err_invalid_suffix_float_constant :
412 diag::err_invalid_suffix_integer_constant)
413 << std::string(SuffixBegin, ThisTokEnd);
414 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000415 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 }
417}
418
Chris Lattner368328c2008-06-30 06:39:54 +0000419/// ParseNumberStartingWithZero - This method is called when the first character
420/// of the number is found to be a zero. This means it is either an octal
421/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
422/// a floating point number (01239.123e4). Eat the prefix, determining the
423/// radix etc.
424void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
425 assert(s[0] == '0' && "Invalid method call");
426 s++;
427
428 // Handle a hex number like 0x1234.
429 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
430 s++;
431 radix = 16;
432 DigitsBegin = s;
433 s = SkipHexDigits(s);
434 if (s == ThisTokEnd) {
435 // Done.
436 } else if (*s == '.') {
437 s++;
438 saw_period = true;
439 s = SkipHexDigits(s);
440 }
441 // A binary exponent can appear with or with a '.'. If dotted, the
442 // binary exponent is required.
Chris Lattner6ea62382008-07-25 18:18:34 +0000443 if (*s == 'p' || *s == 'P') {
Chris Lattner368328c2008-06-30 06:39:54 +0000444 const char *Exponent = s;
445 s++;
446 saw_exponent = true;
447 if (*s == '+' || *s == '-') s++; // sign
448 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000449 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000450 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
451 diag::err_exponent_has_no_digits);
452 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000453 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000454 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000455 s = first_non_digit;
456
Chris Lattner49842122008-11-22 07:39:03 +0000457 if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000458 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000459 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000460 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
461 diag::err_hexconstant_requires_exponent);
462 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000463 }
464 return;
465 }
466
467 // Handle simple binary numbers 0b01010
468 if (*s == 'b' || *s == 'B') {
469 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000470 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000471 ++s;
472 radix = 2;
473 DigitsBegin = s;
474 s = SkipBinaryDigits(s);
475 if (s == ThisTokEnd) {
476 // Done.
477 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000478 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
479 diag::err_invalid_binary_digit) << std::string(s, s+1);
480 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000481 }
Chris Lattner413d3552008-06-30 06:44:49 +0000482 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000483 return;
484 }
485
486 // For now, the radix is set to 8. If we discover that we have a
487 // floating point constant, the radix will change to 10. Octal floating
488 // point constants are not permitted (only decimal and hexadecimal).
489 radix = 8;
490 DigitsBegin = s;
491 s = SkipOctalDigits(s);
492 if (s == ThisTokEnd)
493 return; // Done, simple octal number like 01234
494
Chris Lattner413d3552008-06-30 06:44:49 +0000495 // If we have some other non-octal digit that *is* a decimal digit, see if
496 // this is part of a floating point number like 094.123 or 09e1.
497 if (isdigit(*s)) {
498 const char *EndDecimal = SkipDigits(s);
499 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
500 s = EndDecimal;
501 radix = 10;
502 }
503 }
504
505 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
506 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000507 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000508 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
509 diag::err_invalid_octal_digit) << std::string(s, s+1);
510 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000511 return;
512 }
513
514 if (*s == '.') {
515 s++;
516 radix = 10;
517 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000518 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000519 }
520 if (*s == 'e' || *s == 'E') { // exponent
521 const char *Exponent = s;
522 s++;
523 radix = 10;
524 saw_exponent = true;
525 if (*s == '+' || *s == '-') s++; // sign
526 const char *first_non_digit = SkipDigits(s);
527 if (first_non_digit != s) {
528 s = first_non_digit;
529 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000530 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
531 diag::err_exponent_has_no_digits);
532 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000533 return;
534 }
535 }
536}
537
538
Reid Spencer5f016e22007-07-11 17:01:13 +0000539/// GetIntegerValue - Convert this numeric literal value to an APInt that
540/// matches Val's input width. If there is an overflow, set Val to the low bits
541/// of the result and return true. Otherwise, return false.
542bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000543 // Fast path: Compute a conservative bound on the maximum number of
544 // bits per digit in this radix. If we can't possibly overflow a
545 // uint64 based on that bound then do the simple conversion to
546 // integer. This avoids the expensive overflow checking below, and
547 // handles the common cases that matter (small decimal integers and
548 // hex/octal values which don't overflow).
549 unsigned MaxBitsPerDigit = 1;
550 while ((1U << MaxBitsPerDigit) < radix)
551 MaxBitsPerDigit += 1;
552 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
553 uint64_t N = 0;
554 for (s = DigitsBegin; s != SuffixBegin; ++s)
555 N = N*radix + HexDigitValue(*s);
556
557 // This will truncate the value to Val's input width. Simply check
558 // for overflow by comparing.
559 Val = N;
560 return Val.getZExtValue() != N;
561 }
562
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 Val = 0;
564 s = DigitsBegin;
565
566 llvm::APInt RadixVal(Val.getBitWidth(), radix);
567 llvm::APInt CharVal(Val.getBitWidth(), 0);
568 llvm::APInt OldVal = Val;
569
570 bool OverflowOccurred = false;
571 while (s < SuffixBegin) {
572 unsigned C = HexDigitValue(*s++);
573
574 // If this letter is out of bound for this radix, reject it.
575 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
576
577 CharVal = C;
578
579 // Add the digit to the value in the appropriate radix. If adding in digits
580 // made the value smaller, then this overflowed.
581 OldVal = Val;
582
583 // Multiply by radix, did overflow occur on the multiply?
584 Val *= RadixVal;
585 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
586
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000588 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 OverflowOccurred |= Val.ult(CharVal);
591 }
592 return OverflowOccurred;
593}
594
Chris Lattner525a0502007-09-22 18:29:59 +0000595llvm::APFloat NumericLiteralParser::
Ted Kremenek427d5af2007-11-26 23:12:30 +0000596GetFloatValue(const llvm::fltSemantics &Format, bool* isExact) {
597 using llvm::APFloat;
598
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000599 llvm::SmallVector<char,256> floatChars;
600 for (unsigned i = 0, n = ThisTokEnd-ThisTokBegin; i != n; ++i)
601 floatChars.push_back(ThisTokBegin[i]);
602
603 floatChars.push_back('\0');
604
Ted Kremenek427d5af2007-11-26 23:12:30 +0000605 APFloat V (Format, APFloat::fcZero, false);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000606 APFloat::opStatus status;
Ted Kremenek32e61bf2007-11-29 00:54:29 +0000607
608 status = V.convertFromString(&floatChars[0],APFloat::rmNearestTiesToEven);
Ted Kremenek427d5af2007-11-26 23:12:30 +0000609
610 if (isExact)
611 *isExact = status == APFloat::opOK;
612
613 return V;
Reid Spencer5f016e22007-07-11 17:01:13 +0000614}
615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616
617CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
618 SourceLocation Loc, Preprocessor &PP) {
619 // At this point we know that the character matches the regex "L?'.*'".
620 HadError = false;
621 Value = 0;
622
623 // Determine if this is a wide character.
624 IsWide = begin[0] == 'L';
625 if (IsWide) ++begin;
626
627 // Skip over the entry quote.
628 assert(begin[0] == '\'' && "Invalid token lexed");
629 ++begin;
630
631 // FIXME: This assumes that 'int' is 32-bits in overflow calculation, and the
632 // size of "value".
Chris Lattner98be4942008-03-05 18:54:05 +0000633 assert(PP.getTargetInfo().getIntWidth() == 32 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 "Assumes sizeof(int) == 4 for now");
635 // FIXME: This assumes that wchar_t is 32-bits for now.
Chris Lattner98be4942008-03-05 18:54:05 +0000636 assert(PP.getTargetInfo().getWCharWidth() == 32 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 "Assumes sizeof(wchar_t) == 4 for now");
638 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000639 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 "Assumes char is 8 bits");
641
642 bool isFirstChar = true;
643 bool isMultiChar = false;
644 while (begin[0] != '\'') {
645 unsigned ResultChar;
646 if (begin[0] != '\\') // If this is a normal character, consume it.
647 ResultChar = *begin++;
648 else // Otherwise, this is an escape character.
649 ResultChar = ProcessCharEscape(begin, end, HadError, Loc, IsWide, PP);
650
651 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
652 // implementation defined (C99 6.4.4.4p10).
653 if (!isFirstChar) {
654 // If this is the second character being processed, do special handling.
655 if (!isMultiChar) {
656 isMultiChar = true;
657
658 // Warn about discarding the top bits for multi-char wide-character
659 // constants (L'abcd').
660 if (IsWide)
661 PP.Diag(Loc, diag::warn_extraneous_wide_char_constant);
662 }
663
664 if (IsWide) {
665 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
666 Value = 0;
667 } else {
668 // Narrow character literals act as though their value is concatenated
669 // in this implementation.
670 if (((Value << 8) >> 8) != Value)
671 PP.Diag(Loc, diag::warn_char_constant_too_large);
672 Value <<= 8;
673 }
674 }
675
676 Value += ResultChar;
677 isFirstChar = false;
678 }
679
680 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
681 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
682 // character constants are not sign extended in the this implementation:
683 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
684 if (!IsWide && !isMultiChar && (Value & 128) &&
Chris Lattner98be4942008-03-05 18:54:05 +0000685 PP.getTargetInfo().isCharSigned())
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 Value = (signed char)Value;
687}
688
689
690/// string-literal: [C99 6.4.5]
691/// " [s-char-sequence] "
692/// L" [s-char-sequence] "
693/// s-char-sequence:
694/// s-char
695/// s-char-sequence s-char
696/// s-char:
697/// any source character except the double quote ",
698/// backslash \, or newline character
699/// escape-character
700/// universal-character-name
701/// escape-character: [C99 6.4.4.4]
702/// \ escape-code
703/// universal-character-name
704/// escape-code:
705/// character-escape-code
706/// octal-escape-code
707/// hex-escape-code
708/// character-escape-code: one of
709/// n t b r f v a
710/// \ ' " ?
711/// octal-escape-code:
712/// octal-digit
713/// octal-digit octal-digit
714/// octal-digit octal-digit octal-digit
715/// hex-escape-code:
716/// x hex-digit
717/// hex-escape-code hex-digit
718/// universal-character-name:
719/// \u hex-quad
720/// \U hex-quad hex-quad
721/// hex-quad:
722/// hex-digit hex-digit hex-digit hex-digit
723///
724StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000725StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000726 Preprocessor &pp) : PP(pp) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // Scan all of the string portions, remember the max individual token length,
728 // computing a bound on the concatenated string length, and see whether any
729 // piece is a wide-string. If any of the string portions is a wide-string
730 // literal, the result is a wide-string literal [C99 6.4.5p4].
731 MaxTokenLength = StringToks[0].getLength();
732 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000733 AnyWide = StringToks[0].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000734
735 hadError = false;
736
737 // Implement Translation Phase #6: concatenation of string literals
738 /// (C99 5.1.1.2p1). The common case is only one string fragment.
739 for (unsigned i = 1; i != NumStringToks; ++i) {
740 // The string could be shorter than this if it needs cleaning, but this is a
741 // reasonable bound, which is all we need.
742 SizeBound += StringToks[i].getLength()-2; // -2 for "".
743
744 // Remember maximum string piece length.
745 if (StringToks[i].getLength() > MaxTokenLength)
746 MaxTokenLength = StringToks[i].getLength();
747
748 // Remember if we see any wide strings.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000749 AnyWide |= StringToks[i].is(tok::wide_string_literal);
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000751
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 // Include space for the null terminator.
753 ++SizeBound;
754
755 // TODO: K&R warning: "traditional C rejects string constant concatenation"
756
757 // Get the width in bytes of wchar_t. If no wchar_t strings are used, do not
758 // query the target. As such, wchar_tByteWidth is only valid if AnyWide=true.
759 wchar_tByteWidth = ~0U;
760 if (AnyWide) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000761 wchar_tByteWidth = PP.getTargetInfo().getWCharWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 assert((wchar_tByteWidth & 7) == 0 && "Assumes wchar_t is byte multiple!");
763 wchar_tByteWidth /= 8;
764 }
765
766 // The output buffer size needs to be large enough to hold wide characters.
767 // This is a worst-case assumption which basically corresponds to L"" "long".
768 if (AnyWide)
769 SizeBound *= wchar_tByteWidth;
770
771 // Size the temporary buffer to hold the result string data.
772 ResultBuf.resize(SizeBound);
773
774 // Likewise, but for each string piece.
775 llvm::SmallString<512> TokenBuf;
776 TokenBuf.resize(MaxTokenLength);
777
778 // Loop over all the strings, getting their spelling, and expanding them to
779 // wide strings as appropriate.
780 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
781
Anders Carlssonee98ac52007-10-15 02:50:23 +0000782 Pascal = false;
783
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
785 const char *ThisTokBuf = &TokenBuf[0];
786 // Get the spelling of the token, which eliminates trigraphs, etc. We know
787 // that ThisTokBuf points to a buffer that is big enough for the whole token
788 // and 'spelled' tokens can only shrink.
789 unsigned ThisTokLen = PP.getSpelling(StringToks[i], ThisTokBuf);
790 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
791
792 // TODO: Input character set mapping support.
793
794 // Skip L marker for wide strings.
795 bool ThisIsWide = false;
796 if (ThisTokBuf[0] == 'L') {
797 ++ThisTokBuf;
798 ThisIsWide = true;
799 }
800
801 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
802 ++ThisTokBuf;
803
Anders Carlssonee98ac52007-10-15 02:50:23 +0000804 // Check if this is a pascal string
805 if (pp.getLangOptions().PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
806 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
807
808 // If the \p sequence is found in the first token, we have a pascal string
809 // Otherwise, if we already have a pascal string, ignore the first \p
810 if (i == 0) {
811 ++ThisTokBuf;
812 Pascal = true;
813 } else if (Pascal)
814 ThisTokBuf += 2;
815 }
816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 while (ThisTokBuf != ThisTokEnd) {
818 // Is this a span of non-escape characters?
819 if (ThisTokBuf[0] != '\\') {
820 const char *InStart = ThisTokBuf;
821 do {
822 ++ThisTokBuf;
823 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
824
825 // Copy the character span over.
826 unsigned Len = ThisTokBuf-InStart;
827 if (!AnyWide) {
828 memcpy(ResultPtr, InStart, Len);
829 ResultPtr += Len;
830 } else {
831 // Note: our internal rep of wide char tokens is always little-endian.
832 for (; Len; --Len, ++InStart) {
833 *ResultPtr++ = InStart[0];
834 // Add zeros at the end.
835 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000836 *ResultPtr++ = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 }
838 }
839 continue;
840 }
841
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000842 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
843 ProcessUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000844 hadError, StringToks[i].getLocation(), ThisIsWide, PP);
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000845 } else {
846 // Otherwise, this is a non-UCN escape character. Process it.
847 unsigned ResultChar = ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
848 StringToks[i].getLocation(),
849 ThisIsWide, PP);
850
851 // Note: our internal rep of wide char tokens is always little-endian.
852 *ResultPtr++ = ResultChar & 0xFF;
853
854 if (AnyWide) {
855 for (unsigned i = 1, e = wchar_tByteWidth; i != e; ++i)
856 *ResultPtr++ = ResultChar >> i*8;
857 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 }
859 }
860 }
861
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000862 if (Pascal) {
Anders Carlssonee98ac52007-10-15 02:50:23 +0000863 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000864
865 // Verify that pascal strings aren't too large.
Eli Friedman57d7dde2009-04-01 03:17:08 +0000866 if (GetStringLength() > 256) {
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000867 PP.Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
868 << SourceRange(StringToks[0].getLocation(),
869 StringToks[NumStringToks-1].getLocation());
Eli Friedman57d7dde2009-04-01 03:17:08 +0000870 hadError = 1;
871 return;
872 }
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000873 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000874}
Chris Lattner719e6152009-02-18 19:21:10 +0000875
876
877/// getOffsetOfStringByte - This function returns the offset of the
878/// specified byte of the string data represented by Token. This handles
879/// advancing over escape sequences in the string.
880unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
881 unsigned ByteNo,
882 Preprocessor &PP) {
883 // Get the spelling of the token.
884 llvm::SmallString<16> SpellingBuffer;
885 SpellingBuffer.resize(Tok.getLength());
886
887 const char *SpellingPtr = &SpellingBuffer[0];
888 unsigned TokLen = PP.getSpelling(Tok, SpellingPtr);
889
890 assert(SpellingPtr[0] != 'L' && "Doesn't handle wide strings yet");
891
892
893 const char *SpellingStart = SpellingPtr;
894 const char *SpellingEnd = SpellingPtr+TokLen;
895
896 // Skip over the leading quote.
897 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
898 ++SpellingPtr;
899
900 // Skip over bytes until we find the offset we're looking for.
901 while (ByteNo) {
902 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
903
904 // Step over non-escapes simply.
905 if (*SpellingPtr != '\\') {
906 ++SpellingPtr;
907 --ByteNo;
908 continue;
909 }
910
911 // Otherwise, this is an escape character. Advance over it.
912 bool HadError = false;
913 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
914 Tok.getLocation(), false, PP);
915 assert(!HadError && "This method isn't valid on erroneous strings");
916 --ByteNo;
917 }
918
919 return SpellingPtr-SpellingStart;
920}