blob: a40908bd9f0d7ae3c811df374ecf95e238be96f4 [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
Douglas Gregor5cee1192011-07-27 05:40:30 +000031static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
32 switch (kind) {
33 default: assert(0 && "Unknown token type!");
34 case tok::char_constant:
35 case tok::string_literal:
36 case tok::utf8_string_literal:
37 return Target.getCharWidth();
38 case tok::wide_char_constant:
39 case tok::wide_string_literal:
40 return Target.getWCharWidth();
41 case tok::utf16_char_constant:
42 case tok::utf16_string_literal:
43 return Target.getChar16Width();
44 case tok::utf32_char_constant:
45 case tok::utf32_string_literal:
46 return Target.getChar32Width();
47 }
48}
49
Reid Spencer5f016e22007-07-11 17:01:13 +000050/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
51/// either a character or a string literal.
52static unsigned ProcessCharEscape(const char *&ThisTokBuf,
53 const char *ThisTokEnd, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +000054 FullSourceLoc Loc, unsigned CharWidth,
55 Diagnostic *Diags) {
Reid Spencer5f016e22007-07-11 17:01:13 +000056 // Skip the '\' char.
57 ++ThisTokBuf;
58
59 // We know that this character can't be off the end of the buffer, because
60 // that would have been \", which would not have been the end of string.
61 unsigned ResultChar = *ThisTokBuf++;
62 switch (ResultChar) {
63 // These map to themselves.
64 case '\\': case '\'': case '"': case '?': break;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Reid Spencer5f016e22007-07-11 17:01:13 +000066 // These have fixed mappings.
67 case 'a':
68 // TODO: K&R: the meaning of '\\a' is different in traditional C
69 ResultChar = 7;
70 break;
71 case 'b':
72 ResultChar = 8;
73 break;
74 case 'e':
Chris Lattner91f54ce2010-11-17 06:26:08 +000075 if (Diags)
76 Diags->Report(Loc, diag::ext_nonstandard_escape) << "e";
Reid Spencer5f016e22007-07-11 17:01:13 +000077 ResultChar = 27;
78 break;
Eli Friedman3c548012009-06-10 01:32:39 +000079 case 'E':
Chris Lattner91f54ce2010-11-17 06:26:08 +000080 if (Diags)
81 Diags->Report(Loc, diag::ext_nonstandard_escape) << "E";
Eli Friedman3c548012009-06-10 01:32:39 +000082 ResultChar = 27;
83 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000084 case 'f':
85 ResultChar = 12;
86 break;
87 case 'n':
88 ResultChar = 10;
89 break;
90 case 'r':
91 ResultChar = 13;
92 break;
93 case 't':
94 ResultChar = 9;
95 break;
96 case 'v':
97 ResultChar = 11;
98 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000099 case 'x': { // Hex escape.
100 ResultChar = 0;
101 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner91f54ce2010-11-17 06:26:08 +0000102 if (Diags)
103 Diags->Report(Loc, diag::err_hex_escape_no_digits);
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 HadError = 1;
105 break;
106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 // Hex escapes are a maximal series of hex digits.
109 bool Overflow = false;
110 for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
111 int CharVal = HexDigitValue(ThisTokBuf[0]);
112 if (CharVal == -1) break;
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000113 // About to shift out a digit?
114 Overflow |= (ResultChar & 0xF0000000) ? true : false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 ResultChar <<= 4;
116 ResultChar |= CharVal;
117 }
118
119 // See if any bits will be truncated when evaluated as a character.
Reid Spencer5f016e22007-07-11 17:01:13 +0000120 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
121 Overflow = true;
122 ResultChar &= ~0U >> (32-CharWidth);
123 }
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 // Check for overflow.
Chris Lattner91f54ce2010-11-17 06:26:08 +0000126 if (Overflow && Diags) // Too many digits to fit in
127 Diags->Report(Loc, diag::warn_hex_escape_too_large);
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 break;
129 }
130 case '0': case '1': case '2': case '3':
131 case '4': case '5': case '6': case '7': {
132 // Octal escapes.
133 --ThisTokBuf;
134 ResultChar = 0;
135
136 // Octal escapes are a series of octal digits with maximum length 3.
137 // "\0123" is a two digit sequence equal to "\012" "3".
138 unsigned NumDigits = 0;
139 do {
140 ResultChar <<= 3;
141 ResultChar |= *ThisTokBuf++ - '0';
142 ++NumDigits;
143 } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
144 ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 // Check for overflow. Reject '\777', but not L'\777'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Chris Lattner91f54ce2010-11-17 06:26:08 +0000148 if (Diags)
149 Diags->Report(Loc, diag::warn_octal_escape_too_large);
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 ResultChar &= ~0U >> (32-CharWidth);
151 }
152 break;
153 }
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 // Otherwise, these are not valid escapes.
156 case '(': case '{': case '[': case '%':
157 // GCC accepts these as extensions. We warn about them as such though.
Chris Lattner91f54ce2010-11-17 06:26:08 +0000158 if (Diags)
159 Diags->Report(Loc, diag::ext_nonstandard_escape)
Douglas Gregorb90f4b32010-05-26 05:35:51 +0000160 << std::string()+(char)ResultChar;
Eli Friedmanf01fdff2009-04-28 00:51:18 +0000161 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 default:
Chris Lattner91f54ce2010-11-17 06:26:08 +0000163 if (Diags == 0)
Douglas Gregorb90f4b32010-05-26 05:35:51 +0000164 break;
165
Ted Kremenek23ef69d2010-12-03 00:09:56 +0000166 if (isgraph(ResultChar))
Chris Lattner91f54ce2010-11-17 06:26:08 +0000167 Diags->Report(Loc, diag::ext_unknown_escape)
168 << std::string()+(char)ResultChar;
Chris Lattnerac92d822008-11-22 07:23:31 +0000169 else
Chris Lattner91f54ce2010-11-17 06:26:08 +0000170 Diags->Report(Loc, diag::ext_unknown_escape)
171 << "x"+llvm::utohexstr(ResultChar);
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 break;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 return ResultChar;
176}
177
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000178/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
Nico Weber59705ae2010-10-09 00:27:47 +0000179/// return the UTF32.
180static bool ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
181 uint32_t &UcnVal, unsigned short &UcnLen,
Chris Lattner872a45e2010-11-17 06:55:10 +0000182 FullSourceLoc Loc, Diagnostic *Diags,
Chris Lattner6c66f072010-11-17 06:46:14 +0000183 const LangOptions &Features) {
184 if (!Features.CPlusPlus && !Features.C99 && Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000185 Diags->Report(Loc, diag::warn_ucn_not_valid_in_c89);
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Steve Naroff4e93b342009-04-01 11:09:15 +0000187 // Save the beginning of the string (for error diagnostics).
188 const char *ThisTokBegin = ThisTokBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000190 // Skip the '\u' char's.
191 ThisTokBuf += 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000192
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000193 if (ThisTokBuf == ThisTokEnd || !isxdigit(*ThisTokBuf)) {
Chris Lattner6c66f072010-11-17 06:46:14 +0000194 if (Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000195 Diags->Report(Loc, diag::err_ucn_escape_no_digits);
Nico Weber59705ae2010-10-09 00:27:47 +0000196 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000197 }
Nico Weber59705ae2010-10-09 00:27:47 +0000198 UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000199 unsigned short UcnLenSave = UcnLen;
Nico Weber59705ae2010-10-09 00:27:47 +0000200 for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000201 int CharVal = HexDigitValue(ThisTokBuf[0]);
202 if (CharVal == -1) break;
203 UcnVal <<= 4;
204 UcnVal |= CharVal;
205 }
206 // If we didn't consume the proper number of digits, there is a problem.
Nico Weber59705ae2010-10-09 00:27:47 +0000207 if (UcnLenSave) {
Chris Lattner872a45e2010-11-17 06:55:10 +0000208 if (Diags) {
Chris Lattner7ef5c272010-11-17 07:05:50 +0000209 SourceLocation L =
210 Lexer::AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin,
211 Loc.getManager(), Features);
212 Diags->Report(FullSourceLoc(L, Loc.getManager()),
213 diag::err_ucn_escape_incomplete);
Chris Lattner872a45e2010-11-17 06:55:10 +0000214 }
Nico Weber59705ae2010-10-09 00:27:47 +0000215 return false;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000216 }
Mike Stump1eb44332009-09-09 15:08:12 +0000217 // Check UCN constraints (C99 6.4.3p2).
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000218 if ((UcnVal < 0xa0 &&
219 (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60 )) // $, @, `
Mike Stump1eb44332009-09-09 15:08:12 +0000220 || (UcnVal >= 0xD800 && UcnVal <= 0xDFFF)
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000221 || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
Chris Lattner6c66f072010-11-17 06:46:14 +0000222 if (Diags)
Chris Lattner872a45e2010-11-17 06:55:10 +0000223 Diags->Report(Loc, diag::err_ucn_escape_invalid);
Nico Weber59705ae2010-10-09 00:27:47 +0000224 return false;
225 }
226 return true;
227}
228
229/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
230/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
231/// StringLiteralParser. When we decide to implement UCN's for identifiers,
232/// we will likely rework our support for UCN's.
233static void EncodeUCNEscape(const char *&ThisTokBuf, const char *ThisTokEnd,
Chris Lattnera95880d2010-11-17 07:12:42 +0000234 char *&ResultBuf, bool &HadError,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000235 FullSourceLoc Loc, unsigned CharByteWidth,
236 Diagnostic *Diags, const LangOptions &Features) {
Nico Weber59705ae2010-10-09 00:27:47 +0000237 typedef uint32_t UTF32;
238 UTF32 UcnVal = 0;
239 unsigned short UcnLen = 0;
Chris Lattnera95880d2010-11-17 07:12:42 +0000240 if (!ProcessUCNEscape(ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, Diags,
241 Features)) {
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000242 HadError = 1;
243 return;
244 }
Nico Weber59705ae2010-10-09 00:27:47 +0000245
Douglas Gregor5cee1192011-07-27 05:40:30 +0000246 assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth) &&
247 "only character widths of 1, 2, or 4 bytes supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000248
Douglas Gregor5cee1192011-07-27 05:40:30 +0000249 (void)UcnLen;
250 assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
Nico Webera0f15b02010-10-06 04:57:26 +0000251
Douglas Gregor5cee1192011-07-27 05:40:30 +0000252 if (CharByteWidth == 4) {
253 // Note: our internal rep of wide char tokens is always little-endian.
254 *ResultBuf++ = (UcnVal & 0x000000FF);
255 *ResultBuf++ = (UcnVal & 0x0000FF00) >> 8;
256 *ResultBuf++ = (UcnVal & 0x00FF0000) >> 16;
257 *ResultBuf++ = (UcnVal & 0xFF000000) >> 24;
258 return;
259 }
260
261 if (CharByteWidth == 2) {
Nico Webera0f15b02010-10-06 04:57:26 +0000262 // Convert to UTF16.
263 if (UcnVal < (UTF32)0xFFFF) {
264 *ResultBuf++ = (UcnVal & 0x000000FF);
265 *ResultBuf++ = (UcnVal & 0x0000FF00) >> 8;
266 return;
267 }
Chris Lattnera95880d2010-11-17 07:12:42 +0000268 if (Diags) Diags->Report(Loc, diag::warn_ucn_escape_too_large);
Nico Webera0f15b02010-10-06 04:57:26 +0000269
270 typedef uint16_t UTF16;
271 UcnVal -= 0x10000;
272 UTF16 surrogate1 = 0xD800 + (UcnVal >> 10);
273 UTF16 surrogate2 = 0xDC00 + (UcnVal & 0x3FF);
274 *ResultBuf++ = (surrogate1 & 0x000000FF);
275 *ResultBuf++ = (surrogate1 & 0x0000FF00) >> 8;
276 *ResultBuf++ = (surrogate2 & 0x000000FF);
277 *ResultBuf++ = (surrogate2 & 0x0000FF00) >> 8;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000278 return;
279 }
Douglas Gregor5cee1192011-07-27 05:40:30 +0000280
281 assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
282
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000283 // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
284 // The conversion below was inspired by:
285 // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
Mike Stump1eb44332009-09-09 15:08:12 +0000286 // First, we determine how many bytes the result will require.
Steve Naroff4e93b342009-04-01 11:09:15 +0000287 typedef uint8_t UTF8;
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000288
289 unsigned short bytesToWrite = 0;
290 if (UcnVal < (UTF32)0x80)
291 bytesToWrite = 1;
292 else if (UcnVal < (UTF32)0x800)
293 bytesToWrite = 2;
294 else if (UcnVal < (UTF32)0x10000)
295 bytesToWrite = 3;
296 else
297 bytesToWrite = 4;
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000299 const unsigned byteMask = 0xBF;
300 const unsigned byteMark = 0x80;
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000302 // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000303 // into the first byte, depending on how many bytes follow.
Mike Stump1eb44332009-09-09 15:08:12 +0000304 static const UTF8 firstByteMark[5] = {
Steve Naroff8a5c0cd2009-03-31 10:29:45 +0000305 0x00, 0x00, 0xC0, 0xE0, 0xF0
Steve Naroff0e3e3eb2009-03-30 23:46:03 +0000306 };
307 // Finally, we write the bytes into ResultBuf.
308 ResultBuf += bytesToWrite;
309 switch (bytesToWrite) { // note: everything falls through.
310 case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
311 case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
312 case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
313 case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
314 }
315 // Update the buffer.
316 ResultBuf += bytesToWrite;
317}
Reid Spencer5f016e22007-07-11 17:01:13 +0000318
319
320/// integer-constant: [C99 6.4.4.1]
321/// decimal-constant integer-suffix
322/// octal-constant integer-suffix
323/// hexadecimal-constant integer-suffix
Mike Stump1eb44332009-09-09 15:08:12 +0000324/// decimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000325/// nonzero-digit
326/// decimal-constant digit
Mike Stump1eb44332009-09-09 15:08:12 +0000327/// octal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000328/// 0
329/// octal-constant octal-digit
Mike Stump1eb44332009-09-09 15:08:12 +0000330/// hexadecimal-constant:
Reid Spencer5f016e22007-07-11 17:01:13 +0000331/// hexadecimal-prefix hexadecimal-digit
332/// hexadecimal-constant hexadecimal-digit
333/// hexadecimal-prefix: one of
334/// 0x 0X
335/// integer-suffix:
336/// unsigned-suffix [long-suffix]
337/// unsigned-suffix [long-long-suffix]
338/// long-suffix [unsigned-suffix]
339/// long-long-suffix [unsigned-sufix]
340/// nonzero-digit:
341/// 1 2 3 4 5 6 7 8 9
342/// octal-digit:
343/// 0 1 2 3 4 5 6 7
344/// hexadecimal-digit:
345/// 0 1 2 3 4 5 6 7 8 9
346/// a b c d e f
347/// A B C D E F
348/// unsigned-suffix: one of
349/// u U
350/// long-suffix: one of
351/// l L
Mike Stump1eb44332009-09-09 15:08:12 +0000352/// long-long-suffix: one of
Reid Spencer5f016e22007-07-11 17:01:13 +0000353/// ll LL
354///
355/// floating-constant: [C99 6.4.4.2]
356/// TODO: add rules...
357///
Reid Spencer5f016e22007-07-11 17:01:13 +0000358NumericLiteralParser::
359NumericLiteralParser(const char *begin, const char *end,
360 SourceLocation TokLoc, Preprocessor &pp)
361 : PP(pp), ThisTokBegin(begin), ThisTokEnd(end) {
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattnerc29bbde2008-09-30 20:45:40 +0000363 // This routine assumes that the range begin/end matches the regex for integer
364 // and FP constants (specifically, the 'pp-number' regex), and assumes that
365 // the byte at "*end" is both valid and not part of the regex. Because of
366 // this, it doesn't have to check for 'overscan' in various places.
367 assert(!isalnum(*end) && *end != '.' && *end != '_' &&
368 "Lexer didn't maximally munch?");
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 s = DigitsBegin = begin;
371 saw_exponent = false;
372 saw_period = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 isLong = false;
374 isUnsigned = false;
375 isLongLong = false;
Chris Lattner6e400c22007-08-26 03:29:23 +0000376 isFloat = false;
Chris Lattner506b8de2007-08-26 01:58:14 +0000377 isImaginary = false;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000378 isMicrosoftInteger = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 hadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 if (*s == '0') { // parse radix
Chris Lattner368328c2008-06-30 06:39:54 +0000382 ParseNumberStartingWithZero(TokLoc);
383 if (hadError)
384 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 } else { // the first digit is non-zero
386 radix = 10;
387 s = SkipDigits(s);
388 if (s == ThisTokEnd) {
389 // Done.
Christopher Lamb016765e2007-11-29 06:06:27 +0000390 } else if (isxdigit(*s) && !(*s == 'e' || *s == 'E')) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000391 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000392 diag::err_invalid_decimal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000393 hadError = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 return;
395 } else if (*s == '.') {
396 s++;
397 saw_period = true;
398 s = SkipDigits(s);
Mike Stump1eb44332009-09-09 15:08:12 +0000399 }
Chris Lattner4411f462008-09-29 23:12:31 +0000400 if ((*s == 'e' || *s == 'E')) { // exponent
Chris Lattner70f66ab2008-04-20 18:47:55 +0000401 const char *Exponent = s;
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 s++;
403 saw_exponent = true;
404 if (*s == '+' || *s == '-') s++; // sign
405 const char *first_non_digit = SkipDigits(s);
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000406 if (first_non_digit != s) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 s = first_non_digit;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000408 } else {
Chris Lattnerac92d822008-11-22 07:23:31 +0000409 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-begin),
410 diag::err_exponent_has_no_digits);
411 hadError = true;
Chris Lattner0b7f69d2008-04-20 18:41:46 +0000412 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 }
414 }
415 }
416
417 SuffixBegin = s;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner506b8de2007-08-26 01:58:14 +0000419 // Parse the suffix. At this point we can classify whether we have an FP or
420 // integer constant.
421 bool isFPConstant = isFloatingLiteral();
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner506b8de2007-08-26 01:58:14 +0000423 // Loop over all of the characters of the suffix. If we see something bad,
424 // we break out of the loop.
425 for (; s != ThisTokEnd; ++s) {
426 switch (*s) {
427 case 'f': // FP Suffix for "float"
428 case 'F':
429 if (!isFPConstant) break; // Error for integer constant.
Chris Lattner6e400c22007-08-26 03:29:23 +0000430 if (isFloat || isLong) break; // FF, LF invalid.
431 isFloat = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000432 continue; // Success.
433 case 'u':
434 case 'U':
435 if (isFPConstant) break; // Error for floating constant.
436 if (isUnsigned) break; // Cannot be repeated.
437 isUnsigned = true;
438 continue; // Success.
439 case 'l':
440 case 'L':
441 if (isLong || isLongLong) break; // Cannot be repeated.
Chris Lattner6e400c22007-08-26 03:29:23 +0000442 if (isFloat) break; // LF invalid.
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner506b8de2007-08-26 01:58:14 +0000444 // Check for long long. The L's need to be adjacent and the same case.
445 if (s+1 != ThisTokEnd && s[1] == s[0]) {
446 if (isFPConstant) break; // long long invalid for floats.
447 isLongLong = true;
448 ++s; // Eat both of them.
449 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 isLong = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000452 continue; // Success.
453 case 'i':
Chris Lattnerc6374152010-10-14 00:24:10 +0000454 case 'I':
Steve Naroff0c29b222008-04-04 21:02:54 +0000455 if (PP.getLangOptions().Microsoft) {
Fariborz Jahaniana8be02b2010-01-22 21:36:53 +0000456 if (isFPConstant || isLong || isLongLong) break;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000457
Steve Naroff0c29b222008-04-04 21:02:54 +0000458 // Allow i8, i16, i32, i64, and i128.
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000459 if (s + 1 != ThisTokEnd) {
460 switch (s[1]) {
461 case '8':
462 s += 2; // i8 suffix
463 isMicrosoftInteger = true;
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000464 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000465 case '1':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000466 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000467 if (s[2] == '6') {
468 s += 3; // i16 suffix
469 isMicrosoftInteger = true;
470 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000471 else if (s[2] == '2') {
472 if (s + 3 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000473 if (s[3] == '8') {
474 s += 4; // i128 suffix
475 isMicrosoftInteger = true;
476 }
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000477 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000478 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000479 case '3':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000480 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000481 if (s[2] == '2') {
482 s += 3; // i32 suffix
483 isLong = true;
484 isMicrosoftInteger = true;
485 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000486 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000487 case '6':
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000488 if (s + 2 == ThisTokEnd) break;
Francois Pichetd062b602011-01-11 11:57:53 +0000489 if (s[2] == '4') {
490 s += 3; // i64 suffix
491 isLongLong = true;
492 isMicrosoftInteger = true;
493 }
Nuno Lopes6e8c7ac2009-11-28 13:37:52 +0000494 break;
Mike Stumpb79fe2d2009-10-08 22:55:36 +0000495 default:
496 break;
497 }
498 break;
Steve Naroff0c29b222008-04-04 21:02:54 +0000499 }
Steve Naroff0c29b222008-04-04 21:02:54 +0000500 }
501 // fall through.
Chris Lattner506b8de2007-08-26 01:58:14 +0000502 case 'j':
503 case 'J':
504 if (isImaginary) break; // Cannot be repeated.
505 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
506 diag::ext_imaginary_constant);
507 isImaginary = true;
508 continue; // Success.
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 }
Chris Lattner506b8de2007-08-26 01:58:14 +0000510 // If we reached here, there was an error.
511 break;
512 }
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chris Lattner506b8de2007-08-26 01:58:14 +0000514 // Report an error if there are any.
515 if (s != ThisTokEnd) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000516 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
517 isFPConstant ? diag::err_invalid_suffix_float_constant :
518 diag::err_invalid_suffix_integer_constant)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000519 << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
Chris Lattnerac92d822008-11-22 07:23:31 +0000520 hadError = true;
Chris Lattner506b8de2007-08-26 01:58:14 +0000521 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 }
523}
524
Chris Lattner368328c2008-06-30 06:39:54 +0000525/// ParseNumberStartingWithZero - This method is called when the first character
526/// of the number is found to be a zero. This means it is either an octal
527/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
Mike Stump1eb44332009-09-09 15:08:12 +0000528/// a floating point number (01239.123e4). Eat the prefix, determining the
Chris Lattner368328c2008-06-30 06:39:54 +0000529/// radix etc.
530void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
531 assert(s[0] == '0' && "Invalid method call");
532 s++;
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Chris Lattner368328c2008-06-30 06:39:54 +0000534 // Handle a hex number like 0x1234.
535 if ((*s == 'x' || *s == 'X') && (isxdigit(s[1]) || s[1] == '.')) {
536 s++;
537 radix = 16;
538 DigitsBegin = s;
539 s = SkipHexDigits(s);
540 if (s == ThisTokEnd) {
541 // Done.
542 } else if (*s == '.') {
543 s++;
544 saw_period = true;
545 s = SkipHexDigits(s);
546 }
547 // A binary exponent can appear with or with a '.'. If dotted, the
Mike Stump1eb44332009-09-09 15:08:12 +0000548 // binary exponent is required.
Sean Hunt8c723402010-01-10 23:37:56 +0000549 if ((*s == 'p' || *s == 'P') && !PP.getLangOptions().CPlusPlus0x) {
Chris Lattner368328c2008-06-30 06:39:54 +0000550 const char *Exponent = s;
551 s++;
552 saw_exponent = true;
553 if (*s == '+' || *s == '-') s++; // sign
554 const char *first_non_digit = SkipDigits(s);
Chris Lattner6ea62382008-07-25 18:18:34 +0000555 if (first_non_digit == s) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000556 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
557 diag::err_exponent_has_no_digits);
558 hadError = true;
Chris Lattner6ea62382008-07-25 18:18:34 +0000559 return;
Chris Lattner368328c2008-06-30 06:39:54 +0000560 }
Chris Lattner6ea62382008-07-25 18:18:34 +0000561 s = first_non_digit;
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Sean Hunt8c723402010-01-10 23:37:56 +0000563 // In C++0x, we cannot support hexadecmial floating literals because
564 // they conflict with user-defined literals, so we warn in previous
565 // versions of C++ by default.
566 if (PP.getLangOptions().CPlusPlus)
567 PP.Diag(TokLoc, diag::ext_hexconstant_cplusplus);
568 else if (!PP.getLangOptions().HexFloats)
Chris Lattnerac92d822008-11-22 07:23:31 +0000569 PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
Chris Lattner368328c2008-06-30 06:39:54 +0000570 } else if (saw_period) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000571 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
572 diag::err_hexconstant_requires_exponent);
573 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000574 }
575 return;
576 }
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner368328c2008-06-30 06:39:54 +0000578 // Handle simple binary numbers 0b01010
579 if (*s == 'b' || *s == 'B') {
580 // 0b101010 is a GCC extension.
Chris Lattner413d3552008-06-30 06:44:49 +0000581 PP.Diag(TokLoc, diag::ext_binary_literal);
Chris Lattner368328c2008-06-30 06:39:54 +0000582 ++s;
583 radix = 2;
584 DigitsBegin = s;
585 s = SkipBinaryDigits(s);
586 if (s == ThisTokEnd) {
587 // Done.
588 } else if (isxdigit(*s)) {
Chris Lattnerac92d822008-11-22 07:23:31 +0000589 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000590 diag::err_invalid_binary_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000591 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000592 }
Chris Lattner413d3552008-06-30 06:44:49 +0000593 // Other suffixes will be diagnosed by the caller.
Chris Lattner368328c2008-06-30 06:39:54 +0000594 return;
595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chris Lattner368328c2008-06-30 06:39:54 +0000597 // For now, the radix is set to 8. If we discover that we have a
598 // floating point constant, the radix will change to 10. Octal floating
Mike Stump1eb44332009-09-09 15:08:12 +0000599 // point constants are not permitted (only decimal and hexadecimal).
Chris Lattner368328c2008-06-30 06:39:54 +0000600 radix = 8;
601 DigitsBegin = s;
602 s = SkipOctalDigits(s);
603 if (s == ThisTokEnd)
604 return; // Done, simple octal number like 01234
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Chris Lattner413d3552008-06-30 06:44:49 +0000606 // If we have some other non-octal digit that *is* a decimal digit, see if
607 // this is part of a floating point number like 094.123 or 09e1.
608 if (isdigit(*s)) {
609 const char *EndDecimal = SkipDigits(s);
610 if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
611 s = EndDecimal;
612 radix = 10;
613 }
614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattner413d3552008-06-30 06:44:49 +0000616 // If we have a hex digit other than 'e' (which denotes a FP exponent) then
617 // the code is using an incorrect base.
Chris Lattner368328c2008-06-30 06:39:54 +0000618 if (isxdigit(*s) && *s != 'e' && *s != 'E') {
Chris Lattnerac92d822008-11-22 07:23:31 +0000619 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
Chris Lattner5f9e2722011-07-23 10:55:15 +0000620 diag::err_invalid_octal_digit) << StringRef(s, 1);
Chris Lattnerac92d822008-11-22 07:23:31 +0000621 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000622 return;
623 }
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Chris Lattner368328c2008-06-30 06:39:54 +0000625 if (*s == '.') {
626 s++;
627 radix = 10;
628 saw_period = true;
Chris Lattner413d3552008-06-30 06:44:49 +0000629 s = SkipDigits(s); // Skip suffix.
Chris Lattner368328c2008-06-30 06:39:54 +0000630 }
631 if (*s == 'e' || *s == 'E') { // exponent
632 const char *Exponent = s;
633 s++;
634 radix = 10;
635 saw_exponent = true;
636 if (*s == '+' || *s == '-') s++; // sign
637 const char *first_non_digit = SkipDigits(s);
638 if (first_non_digit != s) {
639 s = first_non_digit;
640 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000641 PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
Chris Lattnerac92d822008-11-22 07:23:31 +0000642 diag::err_exponent_has_no_digits);
643 hadError = true;
Chris Lattner368328c2008-06-30 06:39:54 +0000644 return;
645 }
646 }
647}
648
649
Reid Spencer5f016e22007-07-11 17:01:13 +0000650/// GetIntegerValue - Convert this numeric literal value to an APInt that
651/// matches Val's input width. If there is an overflow, set Val to the low bits
652/// of the result and return true. Otherwise, return false.
653bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
Daniel Dunbara179be32008-10-16 07:32:01 +0000654 // Fast path: Compute a conservative bound on the maximum number of
655 // bits per digit in this radix. If we can't possibly overflow a
656 // uint64 based on that bound then do the simple conversion to
657 // integer. This avoids the expensive overflow checking below, and
658 // handles the common cases that matter (small decimal integers and
659 // hex/octal values which don't overflow).
660 unsigned MaxBitsPerDigit = 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000661 while ((1U << MaxBitsPerDigit) < radix)
Daniel Dunbara179be32008-10-16 07:32:01 +0000662 MaxBitsPerDigit += 1;
663 if ((SuffixBegin - DigitsBegin) * MaxBitsPerDigit <= 64) {
664 uint64_t N = 0;
665 for (s = DigitsBegin; s != SuffixBegin; ++s)
666 N = N*radix + HexDigitValue(*s);
667
668 // This will truncate the value to Val's input width. Simply check
669 // for overflow by comparing.
670 Val = N;
671 return Val.getZExtValue() != N;
672 }
673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 Val = 0;
675 s = DigitsBegin;
676
677 llvm::APInt RadixVal(Val.getBitWidth(), radix);
678 llvm::APInt CharVal(Val.getBitWidth(), 0);
679 llvm::APInt OldVal = Val;
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Reid Spencer5f016e22007-07-11 17:01:13 +0000681 bool OverflowOccurred = false;
682 while (s < SuffixBegin) {
683 unsigned C = HexDigitValue(*s++);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Reid Spencer5f016e22007-07-11 17:01:13 +0000685 // If this letter is out of bound for this radix, reject it.
686 assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 CharVal = C;
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 // Add the digit to the value in the appropriate radix. If adding in digits
691 // made the value smaller, then this overflowed.
692 OldVal = Val;
693
694 // Multiply by radix, did overflow occur on the multiply?
695 Val *= RadixVal;
696 OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
697
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 // Add value, did overflow occur on the value?
Daniel Dunbard70cb642008-10-16 06:39:30 +0000699 // (a + b) ult b <=> overflow
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 Val += CharVal;
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 OverflowOccurred |= Val.ult(CharVal);
702 }
703 return OverflowOccurred;
704}
705
John McCall94c939d2009-12-24 09:08:04 +0000706llvm::APFloat::opStatus
707NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
Ted Kremenek427d5af2007-11-26 23:12:30 +0000708 using llvm::APFloat;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Erick Tryzelaare9f195f2009-08-16 23:36:28 +0000710 unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
John McCall94c939d2009-12-24 09:08:04 +0000711 return Result.convertFromString(StringRef(ThisTokBegin, n),
712 APFloat::rmNearestTiesToEven);
Reid Spencer5f016e22007-07-11 17:01:13 +0000713}
714
Reid Spencer5f016e22007-07-11 17:01:13 +0000715
716CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
Douglas Gregor5cee1192011-07-27 05:40:30 +0000717 SourceLocation Loc, Preprocessor &PP,
718 tok::TokenKind kind) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 // At this point we know that the character matches the regex "L?'.*'".
720 HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Douglas Gregor5cee1192011-07-27 05:40:30 +0000722 Kind = kind;
723
724 // Determine if this is a wide or UTF character.
725 if (Kind == tok::wide_char_constant || Kind == tok::utf16_char_constant ||
726 Kind == tok::utf32_char_constant) {
727 ++begin;
728 }
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // Skip over the entry quote.
731 assert(begin[0] == '\'' && "Invalid token lexed");
732 ++begin;
733
Mike Stump1eb44332009-09-09 15:08:12 +0000734 // FIXME: The "Value" is an uint64_t so we can handle char literals of
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000735 // up to 64-bits.
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // FIXME: This extensively assumes that 'char' is 8-bits.
Chris Lattner98be4942008-03-05 18:54:05 +0000737 assert(PP.getTargetInfo().getCharWidth() == 8 &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 "Assumes char is 8 bits");
Chris Lattnere3ad8812009-04-28 21:51:46 +0000739 assert(PP.getTargetInfo().getIntWidth() <= 64 &&
740 (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
741 "Assumes sizeof(int) on target is <= 64 and a multiple of char");
742 assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
743 "Assumes sizeof(wchar) on target is <= 64");
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000744
Mike Stump1eb44332009-09-09 15:08:12 +0000745 // This is what we will use for overflow detection
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000746 llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattnere3ad8812009-04-28 21:51:46 +0000748 unsigned NumCharsSoFar = 0;
Chris Lattner1c6c64b2010-04-16 23:44:05 +0000749 bool Warned = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 while (begin[0] != '\'') {
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000751 uint64_t ResultChar;
Nico Weber59705ae2010-10-09 00:27:47 +0000752
753 // Is this a Universal Character Name escape?
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 if (begin[0] != '\\') // If this is a normal character, consume it.
755 ResultChar = *begin++;
Nico Weber59705ae2010-10-09 00:27:47 +0000756 else { // Otherwise, this is an escape character.
757 // Check for UCN.
758 if (begin[1] == 'u' || begin[1] == 'U') {
759 uint32_t utf32 = 0;
760 unsigned short UcnLen = 0;
Chris Lattner872a45e2010-11-17 06:55:10 +0000761 if (!ProcessUCNEscape(begin, end, utf32, UcnLen,
762 FullSourceLoc(Loc, PP.getSourceManager()),
Chris Lattner6c66f072010-11-17 06:46:14 +0000763 &PP.getDiagnostics(), PP.getLangOptions())) {
Nico Weber59705ae2010-10-09 00:27:47 +0000764 HadError = 1;
765 }
766 ResultChar = utf32;
767 } else {
768 // Otherwise, this is a non-UCN escape character. Process it.
Douglas Gregor5cee1192011-07-27 05:40:30 +0000769 unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
Chris Lattner91f54ce2010-11-17 06:26:08 +0000770 ResultChar = ProcessCharEscape(begin, end, HadError,
771 FullSourceLoc(Loc,PP.getSourceManager()),
Douglas Gregor5cee1192011-07-27 05:40:30 +0000772 CharWidth, &PP.getDiagnostics());
Nico Weber59705ae2010-10-09 00:27:47 +0000773 }
774 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000775
776 // If this is a multi-character constant (e.g. 'abc'), handle it. These are
777 // implementation defined (C99 6.4.4.4p10).
Chris Lattnere3ad8812009-04-28 21:51:46 +0000778 if (NumCharsSoFar) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000779 if (!isAscii()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000781 LitVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 } else {
783 // Narrow character literals act as though their value is concatenated
Chris Lattnere3ad8812009-04-28 21:51:46 +0000784 // in this implementation, but warn on overflow.
Chris Lattner1c6c64b2010-04-16 23:44:05 +0000785 if (LitVal.countLeadingZeros() < 8 && !Warned) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 PP.Diag(Loc, diag::warn_char_constant_too_large);
Chris Lattner1c6c64b2010-04-16 23:44:05 +0000787 Warned = true;
788 }
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000789 LitVal <<= 8;
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 }
791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000793 LitVal = LitVal + ResultChar;
Chris Lattnere3ad8812009-04-28 21:51:46 +0000794 ++NumCharsSoFar;
795 }
796
797 // If this is the second character being processed, do special handling.
798 if (NumCharsSoFar > 1) {
799 // Warn about discarding the top bits for multi-char wide-character
800 // constants (L'abcd').
Douglas Gregor5cee1192011-07-27 05:40:30 +0000801 if (!isAscii())
802 PP.Diag(Loc, diag::warn_extraneous_char_constant);
Chris Lattnere3ad8812009-04-28 21:51:46 +0000803 else if (NumCharsSoFar != 4)
804 PP.Diag(Loc, diag::ext_multichar_character_literal);
805 else
806 PP.Diag(Loc, diag::ext_four_char_character_literal);
Eli Friedman2a1c3632009-06-01 05:25:02 +0000807 IsMultiChar = true;
Daniel Dunbar930b71a2009-07-29 01:46:05 +0000808 } else
809 IsMultiChar = false;
Sanjiv Gupta4bc11af2009-04-21 02:21:29 +0000810
811 // Transfer the value from APInt to uint64_t
812 Value = LitVal.getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Douglas Gregor5cee1192011-07-27 05:40:30 +0000814 if (((isWide() && PP.getLangOptions().ShortWChar) || isUTF16()) &&
815 Value > 0xFFFF)
Nico Weber59705ae2010-10-09 00:27:47 +0000816 PP.Diag(Loc, diag::warn_ucn_escape_too_large);
817
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
819 // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
820 // character constants are not sign extended in the this implementation:
821 // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
Douglas Gregor5cee1192011-07-27 05:40:30 +0000822 if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
Eli Friedman15b91762009-06-05 07:05:05 +0000823 PP.getLangOptions().CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 Value = (signed char)Value;
825}
826
827
828/// string-literal: [C99 6.4.5]
829/// " [s-char-sequence] "
830/// L" [s-char-sequence] "
831/// s-char-sequence:
832/// s-char
833/// s-char-sequence s-char
834/// s-char:
835/// any source character except the double quote ",
836/// backslash \, or newline character
837/// escape-character
838/// universal-character-name
839/// escape-character: [C99 6.4.4.4]
840/// \ escape-code
841/// universal-character-name
842/// escape-code:
843/// character-escape-code
844/// octal-escape-code
845/// hex-escape-code
846/// character-escape-code: one of
847/// n t b r f v a
848/// \ ' " ?
849/// octal-escape-code:
850/// octal-digit
851/// octal-digit octal-digit
852/// octal-digit octal-digit octal-digit
853/// hex-escape-code:
854/// x hex-digit
855/// hex-escape-code hex-digit
856/// universal-character-name:
857/// \u hex-quad
858/// \U hex-quad hex-quad
859/// hex-quad:
860/// hex-digit hex-digit hex-digit hex-digit
861///
862StringLiteralParser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000863StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
Chris Lattner0833dd02010-11-17 07:21:13 +0000864 Preprocessor &PP, bool Complain)
865 : SM(PP.getSourceManager()), Features(PP.getLangOptions()),
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +0000866 Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
Douglas Gregor5cee1192011-07-27 05:40:30 +0000867 MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
868 ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
Chris Lattner0833dd02010-11-17 07:21:13 +0000869 init(StringToks, NumStringToks);
870}
871
872void StringLiteralParser::init(const Token *StringToks, unsigned NumStringToks){
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +0000873 // The literal token may have come from an invalid source location (e.g. due
874 // to a PCH error), in which case the token length will be 0.
875 if (NumStringToks == 0 || StringToks[0].getLength() < 2) {
876 hadError = true;
877 return;
878 }
879
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 // Scan all of the string portions, remember the max individual token length,
881 // computing a bound on the concatenated string length, and see whether any
882 // piece is a wide-string. If any of the string portions is a wide-string
883 // literal, the result is a wide-string literal [C99 6.4.5p4].
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +0000884 assert(NumStringToks && "expected at least one token");
Sean Hunt6cf75022010-08-30 17:47:05 +0000885 MaxTokenLength = StringToks[0].getLength();
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +0000886 assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +0000887 SizeBound = StringToks[0].getLength()-2; // -2 for "".
Douglas Gregor5cee1192011-07-27 05:40:30 +0000888 Kind = StringToks[0].getKind();
Sean Hunt6cf75022010-08-30 17:47:05 +0000889
890 hadError = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891
892 // Implement Translation Phase #6: concatenation of string literals
893 /// (C99 5.1.1.2p1). The common case is only one string fragment.
894 for (unsigned i = 1; i != NumStringToks; ++i) {
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +0000895 if (StringToks[i].getLength() < 2) {
896 hadError = true;
897 return;
898 }
899
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 // The string could be shorter than this if it needs cleaning, but this is a
901 // reasonable bound, which is all we need.
Argyrios Kyrtzidis403de3f2011-05-17 22:09:56 +0000902 assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
Sean Hunt6cf75022010-08-30 17:47:05 +0000903 SizeBound += StringToks[i].getLength()-2; // -2 for "".
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 // Remember maximum string piece length.
Sean Hunt6cf75022010-08-30 17:47:05 +0000906 if (StringToks[i].getLength() > MaxTokenLength)
907 MaxTokenLength = StringToks[i].getLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Douglas Gregor5cee1192011-07-27 05:40:30 +0000909 // Remember if we see any wide or utf-8/16/32 strings.
910 // Also check for illegal concatenations.
911 if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
912 if (isAscii()) {
913 Kind = StringToks[i].getKind();
914 } else {
915 if (Diags)
916 Diags->Report(FullSourceLoc(StringToks[i].getLocation(), SM),
917 diag::err_unsupported_string_concat);
918 hadError = true;
919 }
920 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 }
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000922
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 // Include space for the null terminator.
924 ++SizeBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 // TODO: K&R warning: "traditional C rejects string constant concatenation"
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregor5cee1192011-07-27 05:40:30 +0000928 // Get the width in bytes of char/wchar_t/char16_t/char32_t
929 CharByteWidth = getCharWidth(Kind, Target);
930 assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
931 CharByteWidth /= 8;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 // The output buffer size needs to be large enough to hold wide characters.
934 // This is a worst-case assumption which basically corresponds to L"" "long".
Douglas Gregor5cee1192011-07-27 05:40:30 +0000935 SizeBound *= CharByteWidth;
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 // Size the temporary buffer to hold the result string data.
938 ResultBuf.resize(SizeBound);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 // Likewise, but for each string piece.
941 llvm::SmallString<512> TokenBuf;
942 TokenBuf.resize(MaxTokenLength);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 // Loop over all the strings, getting their spelling, and expanding them to
945 // wide strings as appropriate.
946 ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlssonee98ac52007-10-15 02:50:23 +0000948 Pascal = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 for (unsigned i = 0, e = NumStringToks; i != e; ++i) {
951 const char *ThisTokBuf = &TokenBuf[0];
952 // Get the spelling of the token, which eliminates trigraphs, etc. We know
953 // that ThisTokBuf points to a buffer that is big enough for the whole token
954 // and 'spelled' tokens can only shrink.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000955 bool StringInvalid = false;
Chris Lattner0833dd02010-11-17 07:21:13 +0000956 unsigned ThisTokLen =
Chris Lattnerb0607272010-11-17 07:26:20 +0000957 Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
958 &StringInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000959 if (StringInvalid) {
Douglas Gregor5cee1192011-07-27 05:40:30 +0000960 hadError = true;
Douglas Gregor50f6af72010-03-16 05:20:39 +0000961 continue;
962 }
963
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 const char *ThisTokEnd = ThisTokBuf+ThisTokLen-1; // Skip end quote.
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 // TODO: Input character set mapping support.
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Craig Topper1661d712011-08-08 06:10:39 +0000967 // Skip marker for wide or unicode strings.
Douglas Gregor5cee1192011-07-27 05:40:30 +0000968 if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 ++ThisTokBuf;
Douglas Gregor5cee1192011-07-27 05:40:30 +0000970 // Skip 8 of u8 marker for utf8 strings.
971 if (ThisTokBuf[0] == '8')
972 ++ThisTokBuf;
Fariborz Jahanian56bedef2010-08-31 23:34:27 +0000973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 assert(ThisTokBuf[0] == '"' && "Expected quote, lexer broken?");
976 ++ThisTokBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Anders Carlssonee98ac52007-10-15 02:50:23 +0000978 // Check if this is a pascal string
Chris Lattnera95880d2010-11-17 07:12:42 +0000979 if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
Anders Carlssonee98ac52007-10-15 02:50:23 +0000980 ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Anders Carlssonee98ac52007-10-15 02:50:23 +0000982 // If the \p sequence is found in the first token, we have a pascal string
983 // Otherwise, if we already have a pascal string, ignore the first \p
984 if (i == 0) {
985 ++ThisTokBuf;
986 Pascal = true;
987 } else if (Pascal)
988 ThisTokBuf += 2;
989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 while (ThisTokBuf != ThisTokEnd) {
992 // Is this a span of non-escape characters?
993 if (ThisTokBuf[0] != '\\') {
994 const char *InStart = ThisTokBuf;
995 do {
996 ++ThisTokBuf;
997 } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 // Copy the character span over.
1000 unsigned Len = ThisTokBuf-InStart;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001001 if (CharByteWidth == 1) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 memcpy(ResultPtr, InStart, Len);
1003 ResultPtr += Len;
1004 } else {
1005 // Note: our internal rep of wide char tokens is always little-endian.
1006 for (; Len; --Len, ++InStart) {
1007 *ResultPtr++ = InStart[0];
1008 // Add zeros at the end.
Douglas Gregor5cee1192011-07-27 05:40:30 +00001009 for (unsigned i = 1, e = CharByteWidth; i != e; ++i)
Steve Naroff0e3e3eb2009-03-30 23:46:03 +00001010 *ResultPtr++ = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 }
1012 }
1013 continue;
1014 }
Steve Naroff4e93b342009-04-01 11:09:15 +00001015 // Is this a Universal Character Name escape?
Steve Naroff0e3e3eb2009-03-30 23:46:03 +00001016 if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
Nico Weber59705ae2010-10-09 00:27:47 +00001017 EncodeUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
Chris Lattnera95880d2010-11-17 07:12:42 +00001018 hadError, FullSourceLoc(StringToks[i].getLocation(),SM),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001019 CharByteWidth, Diags, Features);
Steve Naroff4e93b342009-04-01 11:09:15 +00001020 continue;
1021 }
1022 // Otherwise, this is a non-UCN escape character. Process it.
Chris Lattner91f54ce2010-11-17 06:26:08 +00001023 unsigned ResultChar =
1024 ProcessCharEscape(ThisTokBuf, ThisTokEnd, hadError,
Chris Lattner6c66f072010-11-17 06:46:14 +00001025 FullSourceLoc(StringToks[i].getLocation(), SM),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001026 CharByteWidth*8, Diags);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Steve Naroff4e93b342009-04-01 11:09:15 +00001028 // Note: our internal rep of wide char tokens is always little-endian.
1029 *ResultPtr++ = ResultChar & 0xFF;
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Douglas Gregor5cee1192011-07-27 05:40:30 +00001031 for (unsigned i = 1, e = CharByteWidth; i != e; ++i)
1032 *ResultPtr++ = ResultChar >> i*8;
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 }
1034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001036 if (Pascal) {
Anders Carlssonee98ac52007-10-15 02:50:23 +00001037 ResultBuf[0] = ResultPtr-&ResultBuf[0]-1;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001038 ResultBuf[0] /= CharByteWidth;
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001039
1040 // Verify that pascal strings aren't too large.
Chris Lattner0833dd02010-11-17 07:21:13 +00001041 if (GetStringLength() > 256) {
1042 if (Diags)
1043 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1044 diag::err_pascal_string_too_long)
1045 << SourceRange(StringToks[0].getLocation(),
1046 StringToks[NumStringToks-1].getLocation());
Douglas Gregor5cee1192011-07-27 05:40:30 +00001047 hadError = true;
Eli Friedman57d7dde2009-04-01 03:17:08 +00001048 return;
1049 }
Chris Lattner0833dd02010-11-17 07:21:13 +00001050 } else if (Diags) {
Douglas Gregor427c4922010-07-20 14:33:20 +00001051 // Complain if this string literal has too many characters.
Chris Lattnera95880d2010-11-17 07:12:42 +00001052 unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
Douglas Gregor427c4922010-07-20 14:33:20 +00001053
1054 if (GetNumStringChars() > MaxChars)
Chris Lattner0833dd02010-11-17 07:21:13 +00001055 Diags->Report(FullSourceLoc(StringToks[0].getLocation(), SM),
1056 diag::ext_string_too_long)
Douglas Gregor427c4922010-07-20 14:33:20 +00001057 << GetNumStringChars() << MaxChars
Chris Lattnera95880d2010-11-17 07:12:42 +00001058 << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
Douglas Gregor427c4922010-07-20 14:33:20 +00001059 << SourceRange(StringToks[0].getLocation(),
1060 StringToks[NumStringToks-1].getLocation());
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001061 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001062}
Chris Lattner719e6152009-02-18 19:21:10 +00001063
1064
1065/// getOffsetOfStringByte - This function returns the offset of the
1066/// specified byte of the string data represented by Token. This handles
1067/// advancing over escape sequences in the string.
1068unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
Chris Lattner6c66f072010-11-17 06:46:14 +00001069 unsigned ByteNo) const {
Chris Lattner719e6152009-02-18 19:21:10 +00001070 // Get the spelling of the token.
Chris Lattnerca1475e2010-11-17 06:35:43 +00001071 llvm::SmallString<32> SpellingBuffer;
Sean Hunt6cf75022010-08-30 17:47:05 +00001072 SpellingBuffer.resize(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Douglas Gregor50f6af72010-03-16 05:20:39 +00001074 bool StringInvalid = false;
Chris Lattner719e6152009-02-18 19:21:10 +00001075 const char *SpellingPtr = &SpellingBuffer[0];
Chris Lattnerb0607272010-11-17 07:26:20 +00001076 unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1077 &StringInvalid);
Chris Lattner91f54ce2010-11-17 06:26:08 +00001078 if (StringInvalid)
Douglas Gregor50f6af72010-03-16 05:20:39 +00001079 return 0;
Chris Lattner719e6152009-02-18 19:21:10 +00001080
Douglas Gregor5cee1192011-07-27 05:40:30 +00001081 assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1082 SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
Chris Lattner719e6152009-02-18 19:21:10 +00001083
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner719e6152009-02-18 19:21:10 +00001085 const char *SpellingStart = SpellingPtr;
1086 const char *SpellingEnd = SpellingPtr+TokLen;
1087
1088 // Skip over the leading quote.
1089 assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1090 ++SpellingPtr;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Chris Lattner719e6152009-02-18 19:21:10 +00001092 // Skip over bytes until we find the offset we're looking for.
1093 while (ByteNo) {
1094 assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Chris Lattner719e6152009-02-18 19:21:10 +00001096 // Step over non-escapes simply.
1097 if (*SpellingPtr != '\\') {
1098 ++SpellingPtr;
1099 --ByteNo;
1100 continue;
1101 }
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Chris Lattner719e6152009-02-18 19:21:10 +00001103 // Otherwise, this is an escape character. Advance over it.
1104 bool HadError = false;
1105 ProcessCharEscape(SpellingPtr, SpellingEnd, HadError,
Chris Lattnerca1475e2010-11-17 06:35:43 +00001106 FullSourceLoc(Tok.getLocation(), SM),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001107 CharByteWidth*8, Diags);
Chris Lattner719e6152009-02-18 19:21:10 +00001108 assert(!HadError && "This method isn't valid on erroneous strings");
1109 --ByteNo;
1110 }
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Chris Lattner719e6152009-02-18 19:21:10 +00001112 return SpellingPtr-SpellingStart;
1113}