blob: c28781dc5f2bef8e8739ae0bc355e8f8558fd71d [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000028#include "clang/Basic/CharInfo.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000029#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/CodeCompletionHandler.h"
31#include "clang/Lex/LexDiagnostic.h"
32#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +000033#include "llvm/ADT/STLExtras.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000034#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Chris Lattner739e7392007-04-29 07:12:06 +000038#include "llvm/Support/MemoryBuffer.h"
Jordan Rose58c61e02013-02-09 01:10:25 +000039#include "UnicodeCharSets.h"
Craig Topper54edcca2011-08-11 04:06:15 +000040#include <cstring>
Chris Lattner22eb9722006-06-18 05:43:12 +000041using namespace clang;
42
Chris Lattner4894f482007-10-07 08:47:24 +000043//===----------------------------------------------------------------------===//
44// Token Class Implementation
45//===----------------------------------------------------------------------===//
46
Mike Stump11289f42009-09-09 15:08:12 +000047/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000048bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000049 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
51 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000052}
53
54/// getObjCKeywordID - Return the ObjC keyword kind.
55tok::ObjCKeywordKind Token::getObjCKeywordID() const {
56 IdentifierInfo *specId = getIdentifierInfo();
57 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
58}
59
Chris Lattner67671ed2007-12-13 01:59:49 +000060
Chris Lattner4894f482007-10-07 08:47:24 +000061//===----------------------------------------------------------------------===//
62// Lexer Class Implementation
63//===----------------------------------------------------------------------===//
64
David Blaikie68e081d2011-12-20 02:48:34 +000065void Lexer::anchor() { }
66
Mike Stump11289f42009-09-09 15:08:12 +000067void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000068 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattnerf76b9202009-01-17 06:55:17 +000073 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000076
Eric Christopher7f36a792011-04-09 00:01:04 +000077 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000084 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
85 .Default(0);
86
87 // Skip the BOM.
88 BufferPtr += BOMLength;
89 }
90
Chris Lattnerf76b9202009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000093
Chris Lattnerf76b9202009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +000096
Chris Lattnerf76b9202009-01-17 06:55:17 +000097 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +000099
Chris Lattnerf76b9202009-01-17 06:55:17 +0000100 // We are not after parsing #include.
101 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattnerf76b9202009-01-17 06:55:17 +0000103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Chris Lattnerf76b9202009-01-17 06:55:17 +0000109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
111}
112
Chris Lattner5965a282009-01-17 07:56:59 +0000113/// Lexer constructor - Create a new lexer object for the specified buffer
114/// with the specified preprocessor managing the lexing process. This lexer
115/// assumes that the associated file buffer and Preprocessor objects will
116/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000117Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000120 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000121
Chris Lattner5965a282009-01-17 07:56:59 +0000122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000124
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000125 resetExtendedTokenMode();
126}
127
128void Lexer::resetExtendedTokenMode() {
129 assert(PP && "Cannot reset token mode without a preprocessor");
130 if (LangOpts.TraditionalCPP)
131 SetKeepWhitespaceMode(true);
132 else
133 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000134}
Chris Lattner4894f482007-10-07 08:47:24 +0000135
Chris Lattner02b436a2007-10-17 20:41:00 +0000136/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000137/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000138/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000139Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000140 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000141 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000142
Chris Lattnerf76b9202009-01-17 06:55:17 +0000143 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Chris Lattner02b436a2007-10-17 20:41:00 +0000145 // We *are* in raw mode.
146 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000147}
148
Chris Lattner08354fe2009-01-17 07:35:14 +0000149/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000150/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000151/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000152Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000153 const SourceManager &SM, const LangOptions &langOpts)
154 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner08354fe2009-01-17 07:35:14 +0000155
Mike Stump11289f42009-09-09 15:08:12 +0000156 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner08354fe2009-01-17 07:35:14 +0000157 FromFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000158
Chris Lattner08354fe2009-01-17 07:35:14 +0000159 // We *are* in raw mode.
160 LexingRawMode = true;
161}
162
Chris Lattner757169b2009-01-17 08:27:52 +0000163/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
164/// _Pragma expansion. This has a variety of magic semantics that this method
165/// sets up. It returns a new'd Lexer that must be delete'd when done.
166///
167/// On entrance to this routine, TokStartLoc is a macro location which has a
168/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000169/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000170/// "expanded from".
171///
172/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
173/// normal lexer that remaps tokens as they fly by. This would require making
174/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
175/// interface that could handle this stuff. This would pull GetMappedTokenLoc
176/// out of the critical path of the lexer!
177///
Mike Stump11289f42009-09-09 15:08:12 +0000178Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000179 SourceLocation ExpansionLocStart,
180 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000181 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000182 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000183
184 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000185 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000186 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
187 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner757169b2009-01-17 08:27:52 +0000189 // Now that the lexer is created, change the start/end locations so that we
190 // just lex the subsection of the file that we want. This is lexing from a
191 // scratch buffer.
192 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner757169b2009-01-17 08:27:52 +0000194 L->BufferPtr = StrData;
195 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000196 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000197
198 // Set the SourceLocation with the remapping information. This ensures that
199 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000200 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
201 ExpansionLocStart,
202 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner757169b2009-01-17 08:27:52 +0000204 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000205 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000206 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000207
Chris Lattner757169b2009-01-17 08:27:52 +0000208 // This lexer really is for _Pragma.
209 L->Is_PragmaLexer = true;
210 return L;
211}
212
Chris Lattner02b436a2007-10-17 20:41:00 +0000213
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000214/// Stringify - Convert the specified string into a C string, with surrounding
215/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000216std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000217 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000218 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000219 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000220 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000221 Result.insert(Result.begin()+i, '\\');
222 ++i; ++e;
223 }
224 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000225 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000226}
227
Chris Lattner4c4a2452007-07-24 06:57:14 +0000228/// Stringify - Convert the specified string into a C string by escaping '\'
229/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000230void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000231 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
232 if (Str[i] == '\\' || Str[i] == '"') {
233 Str.insert(Str.begin()+i, '\\');
234 ++i; ++e;
235 }
236 }
237}
238
Chris Lattner39720112010-11-17 07:26:20 +0000239//===----------------------------------------------------------------------===//
240// Token Spelling
241//===----------------------------------------------------------------------===//
242
Richard Smith9a67f472012-11-28 07:29:00 +0000243/// \brief Slow case of getSpelling. Extract the characters comprising the
244/// spelling of this token from the provided input buffer.
245static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
246 const LangOptions &LangOpts, char *Spelling) {
247 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
248
249 size_t Length = 0;
250 const char *BufEnd = BufPtr + Tok.getLength();
251
252 if (Tok.is(tok::string_literal)) {
253 // Munch the encoding-prefix and opening double-quote.
254 while (BufPtr < BufEnd) {
255 unsigned Size;
256 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
257 BufPtr += Size;
258
259 if (Spelling[Length - 1] == '"')
260 break;
261 }
262
263 // Raw string literals need special handling; trigraph expansion and line
264 // splicing do not occur within their d-char-sequence nor within their
265 // r-char-sequence.
266 if (Length >= 2 &&
267 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
268 // Search backwards from the end of the token to find the matching closing
269 // quote.
270 const char *RawEnd = BufEnd;
271 do --RawEnd; while (*RawEnd != '"');
272 size_t RawLength = RawEnd - BufPtr + 1;
273
274 // Everything between the quotes is included verbatim in the spelling.
275 memcpy(Spelling + Length, BufPtr, RawLength);
276 Length += RawLength;
277 BufPtr += RawLength;
278
279 // The rest of the token is lexed normally.
280 }
281 }
282
283 while (BufPtr < BufEnd) {
284 unsigned Size;
285 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
286 BufPtr += Size;
287 }
288
289 assert(Length < Tok.getLength() &&
290 "NeedsCleaning flag set on token that didn't need cleaning!");
291 return Length;
292}
293
Chris Lattner39720112010-11-17 07:26:20 +0000294/// getSpelling() - Return the 'spelling' of this token. The spelling of a
295/// token are the characters used to represent the token in the source file
296/// after trigraph expansion and escaped-newline folding. In particular, this
297/// wants to get the true, uncanonicalized, spelling of things like digraphs
298/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000300 SmallVectorImpl<char> &buffer,
301 const SourceManager &SM,
302 const LangOptions &options,
303 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000304 // Break down the source location.
305 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
306
307 // Try to the load the file buffer.
308 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000309 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000310 if (invalidTemp) {
311 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000312 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000313 }
314
315 const char *tokenBegin = file.data() + locInfo.second;
316
317 // Lex from the start of the given location.
318 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
319 file.begin(), tokenBegin, file.end());
320 Token token;
321 lexer.LexFromRawLexer(token);
322
323 unsigned length = token.getLength();
324
325 // Common case: no need for cleaning.
326 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000328
Richard Smith9a67f472012-11-28 07:29:00 +0000329 // Hard case, we need to relex the characters into the string.
330 buffer.resize(length);
331 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000332 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000333}
334
335/// getSpelling() - Return the 'spelling' of this token. The spelling of a
336/// token are the characters used to represent the token in the source file
337/// after trigraph expansion and escaped-newline folding. In particular, this
338/// wants to get the true, uncanonicalized, spelling of things like digraphs
339/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000340std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000341 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000342 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000343
Chris Lattner39720112010-11-17 07:26:20 +0000344 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000345 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000346 &CharDataInvalid);
347 if (Invalid)
348 *Invalid = CharDataInvalid;
349 if (CharDataInvalid)
350 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000351
352 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000353 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000354 return std::string(TokStart, TokStart + Tok.getLength());
355
Chris Lattner39720112010-11-17 07:26:20 +0000356 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000357 Result.resize(Tok.getLength());
358 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000359 return Result;
360}
361
362/// getSpelling - This method is used to get the spelling of a token into a
363/// preallocated buffer, instead of as an std::string. The caller is required
364/// to allocate enough space for the token, which is guaranteed to be at least
365/// Tok.getLength() bytes long. The actual length of the token is returned.
366///
367/// Note that this method may do two possible things: it may either fill in
368/// the buffer specified with characters, or it may *change the input pointer*
369/// to point to a constant buffer with the data already in it (avoiding a
370/// copy). The caller is not allowed to modify the returned buffer pointer
371/// if an internal buffer is returned.
372unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
373 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000374 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000375 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000376
377 const char *TokStart = 0;
378 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
379 if (Tok.is(tok::raw_identifier))
380 TokStart = Tok.getRawIdentifierData();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000381 else if (!Tok.hasUCN()) {
382 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
383 // Just return the string from the identifier table, which is very quick.
384 Buffer = II->getNameStart();
385 return II->getLength();
386 }
Chris Lattner39720112010-11-17 07:26:20 +0000387 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000388
389 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000390 if (Tok.isLiteral())
391 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000392
Chris Lattner39720112010-11-17 07:26:20 +0000393 if (TokStart == 0) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000394 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000395 bool CharDataInvalid = false;
396 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
397 if (Invalid)
398 *Invalid = CharDataInvalid;
399 if (CharDataInvalid) {
400 Buffer = "";
401 return 0;
402 }
403 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000404
Chris Lattner39720112010-11-17 07:26:20 +0000405 // If this token contains nothing interesting, return it directly.
406 if (!Tok.needsCleaning()) {
407 Buffer = TokStart;
408 return Tok.getLength();
409 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000410
Chris Lattner39720112010-11-17 07:26:20 +0000411 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000412 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000413}
414
415
Chris Lattner8e129c22007-10-17 21:18:47 +0000416/// MeasureTokenLength - Relex the token at the specified location and return
417/// its length in bytes in the input file. If the token needs cleaning (e.g.
418/// includes a trigraph or an escaped newline) then this count includes bytes
419/// that are part of that.
420unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000423 Token TheTok;
424 if (getRawToken(Loc, TheTok, SM, LangOpts))
425 return 0;
426 return TheTok.getLength();
427}
428
429/// \brief Relex the token at the specified location.
430/// \returns true if there was a failure, false on success.
431bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
432 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000433 const LangOptions &LangOpts,
434 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000435 // TODO: this could be special cased for common tokens like identifiers, ')',
436 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000437 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000438 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
439 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000440
441 // If this comes from a macro expansion, we really do want the macro name, not
442 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000443 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000444 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000445 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000446 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000447 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000448 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000449
450 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000451
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000452 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000453 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000454
Chris Lattner8e129c22007-10-17 21:18:47 +0000455 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000456 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
457 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000458 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000459 TheLexer.LexFromRawLexer(Result);
460 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000461}
462
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000463static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
464 const SourceManager &SM,
465 const LangOptions &LangOpts) {
466 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000467 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000468 if (LocInfo.first.isInvalid())
469 return Loc;
470
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000471 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000472 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000473 if (Invalid)
474 return Loc;
475
476 // Back up from the current location until we hit the beginning of a line
477 // (or the buffer). We'll relex from that point.
478 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000479 if (LocInfo.second >= Buffer.size())
480 return Loc;
481
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000482 const char *StrData = BufStart+LocInfo.second;
483 if (StrData[0] == '\n' || StrData[0] == '\r')
484 return Loc;
485
486 const char *LexStart = StrData;
487 while (LexStart != BufStart) {
488 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
489 ++LexStart;
490 break;
491 }
492
493 --LexStart;
494 }
495
496 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000497 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000498 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
499 TheLexer.SetCommentRetentionState(true);
500
501 // Lex tokens until we find the token that contains the source location.
502 Token TheTok;
503 do {
504 TheLexer.LexFromRawLexer(TheTok);
505
506 if (TheLexer.getBufferLocation() > StrData) {
507 // Lexing this token has taken the lexer past the source location we're
508 // looking for. If the current token encompasses our source location,
509 // return the beginning of that token.
510 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
511 return TheTok.getLocation();
512
513 // We ended up skipping over the source location entirely, which means
514 // that it points into whitespace. We're done here.
515 break;
516 }
517 } while (TheTok.getKind() != tok::eof);
518
519 // We've passed our source location; just return the original source location.
520 return Loc;
521}
522
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000523SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
524 const SourceManager &SM,
525 const LangOptions &LangOpts) {
526 if (Loc.isFileID())
527 return getBeginningOfFileToken(Loc, SM, LangOpts);
528
529 if (!SM.isMacroArgExpansion(Loc))
530 return Loc;
531
532 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
533 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
534 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000535 std::pair<FileID, unsigned> BeginFileLocInfo
536 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000537 assert(FileLocInfo.first == BeginFileLocInfo.first &&
538 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000539 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000540}
541
Douglas Gregoraf82e352010-07-20 20:18:03 +0000542namespace {
543 enum PreambleDirectiveKind {
544 PDK_Skipped,
545 PDK_StartIf,
546 PDK_EndIf,
547 PDK_Unknown
548 };
549}
550
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000551std::pair<unsigned, bool>
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000552Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000553 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000554 // Create a lexer starting at the beginning of the file. Note that we use a
555 // "fake" file source location at offset 1 so that the lexer will track our
556 // position within the file.
557 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000558 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
559 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregoraf82e352010-07-20 20:18:03 +0000560 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000561 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000562
563 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
564 SourceLocation StartLoc = TheLexer.getSourceLocation();
565
Douglas Gregoraf82e352010-07-20 20:18:03 +0000566 bool InPreprocessorDirective = false;
567 Token TheTok;
568 Token IfStartTok;
569 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000570 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000571
572 unsigned MaxLineOffset = 0;
573 if (MaxLines) {
574 const char *CurPtr = Buffer->getBufferStart();
575 unsigned CurLine = 0;
576 while (CurPtr != Buffer->getBufferEnd()) {
577 char ch = *CurPtr++;
578 if (ch == '\n') {
579 ++CurLine;
580 if (CurLine == MaxLines)
581 break;
582 }
583 }
584 if (CurPtr != Buffer->getBufferEnd())
585 MaxLineOffset = CurPtr - Buffer->getBufferStart();
586 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000587
Douglas Gregoraf82e352010-07-20 20:18:03 +0000588 do {
589 TheLexer.LexFromRawLexer(TheTok);
590
591 if (InPreprocessorDirective) {
592 // If we've hit the end of the file, we're done.
593 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000594 break;
595 }
596
597 // If we haven't hit the end of the preprocessor directive, skip this
598 // token.
599 if (!TheTok.isAtStartOfLine())
600 continue;
601
602 // We've passed the end of the preprocessor directive, and will look
603 // at this token again below.
604 InPreprocessorDirective = false;
605 }
606
Douglas Gregor028d3e42010-08-09 20:45:32 +0000607 // Keep track of the # of lines in the preamble.
608 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000609 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000610
611 // If we were asked to limit the number of lines in the preamble,
612 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000613 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000614 break;
615 }
616
Douglas Gregoraf82e352010-07-20 20:18:03 +0000617 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000618 if (TheTok.getKind() == tok::comment) {
619 if (ActiveCommentLoc.isInvalid())
620 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000621 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000622 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000623
624 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
625 // This is the start of a preprocessor directive.
626 Token HashTok = TheTok;
627 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000628 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000629
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000630 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000631 // we don't have an identifier table available. Instead, just look at
632 // the raw identifier to recognize and categorize preprocessor directives.
633 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000634 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000635 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000636 TheTok.getLength());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000637 PreambleDirectiveKind PDK
638 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
639 .Case("include", PDK_Skipped)
640 .Case("__include_macros", PDK_Skipped)
641 .Case("define", PDK_Skipped)
642 .Case("undef", PDK_Skipped)
643 .Case("line", PDK_Skipped)
644 .Case("error", PDK_Skipped)
645 .Case("pragma", PDK_Skipped)
646 .Case("import", PDK_Skipped)
647 .Case("include_next", PDK_Skipped)
648 .Case("warning", PDK_Skipped)
649 .Case("ident", PDK_Skipped)
650 .Case("sccs", PDK_Skipped)
651 .Case("assert", PDK_Skipped)
652 .Case("unassert", PDK_Skipped)
653 .Case("if", PDK_StartIf)
654 .Case("ifdef", PDK_StartIf)
655 .Case("ifndef", PDK_StartIf)
656 .Case("elif", PDK_Skipped)
657 .Case("else", PDK_Skipped)
658 .Case("endif", PDK_EndIf)
659 .Default(PDK_Unknown);
660
661 switch (PDK) {
662 case PDK_Skipped:
663 continue;
664
665 case PDK_StartIf:
666 if (IfCount == 0)
667 IfStartTok = HashTok;
668
669 ++IfCount;
670 continue;
671
672 case PDK_EndIf:
673 // Mismatched #endif. The preamble ends here.
674 if (IfCount == 0)
675 break;
676
677 --IfCount;
678 continue;
679
680 case PDK_Unknown:
681 // We don't know what this directive is; stop at the '#'.
682 break;
683 }
684 }
685
686 // We only end up here if we didn't recognize the preprocessor
687 // directive or it was one that can't occur in the preamble at this
688 // point. Roll back the current token to the location of the '#'.
689 InPreprocessorDirective = false;
690 TheTok = HashTok;
691 }
692
Douglas Gregor028d3e42010-08-09 20:45:32 +0000693 // We hit a token that we don't recognize as being in the
694 // "preprocessing only" part of the file, so we're no longer in
695 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000696 break;
697 } while (true);
698
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000699 SourceLocation End;
700 if (IfCount)
701 End = IfStartTok.getLocation();
702 else if (ActiveCommentLoc.isValid())
703 End = ActiveCommentLoc; // don't truncate a decl comment.
704 else
705 End = TheTok.getLocation();
706
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000707 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
708 IfCount? IfStartTok.isAtStartOfLine()
709 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000710}
711
Chris Lattner2a6ee912010-11-17 07:05:50 +0000712
713/// AdvanceToTokenCharacter - Given a location that specifies the start of a
714/// token, return a new location that specifies a character within the token.
715SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
716 unsigned CharNo,
717 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000718 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000719 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000720 // character is. This needs to take into consideration newlines and
721 // trigraphs.
722 bool Invalid = false;
723 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
724
725 // If they request the first char of the token, we're trivially done.
726 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
727 return TokStart;
728
729 unsigned PhysOffset = 0;
730
731 // The usual case is that tokens don't contain anything interesting. Skip
732 // over the uninteresting characters. If a token only consists of simple
733 // chars, this method is extremely fast.
734 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
735 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000736 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000737 ++TokPtr, --CharNo, ++PhysOffset;
738 }
739
740 // If we have a character that may be a trigraph or escaped newline, use a
741 // lexer to parse it correctly.
742 for (; CharNo; --CharNo) {
743 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000744 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000745 TokPtr += Size;
746 PhysOffset += Size;
747 }
748
749 // Final detail: if we end up on an escaped newline, we want to return the
750 // location of the actual byte of the token. For example foo\<newline>bar
751 // advanced by 3 should return the location of b, not of \\. One compounding
752 // detail of this is that the escape may be made by a trigraph.
753 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
754 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
755
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000756 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000757}
758
759/// \brief Computes the source location just past the end of the
760/// token at this source location.
761///
762/// This routine can be used to produce a source location that
763/// points just past the end of the token referenced by \p Loc, and
764/// is generally used when a diagnostic needs to point just after a
765/// token where it expected something different that it received. If
766/// the returned source location would not be meaningful (e.g., if
767/// it points into a macro), this routine returns an invalid
768/// source location.
769///
770/// \param Offset an offset from the end of the token, where the source
771/// location should refer to. The default offset (0) produces a source
772/// location pointing just past the end of the token; an offset of 1 produces
773/// a source location pointing to the last character in the token, etc.
774SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
775 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000777 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000778 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000779
780 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000782 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000783 }
784
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000786 if (Len > Offset)
787 Len = Len - Offset;
788 else
789 return Loc;
790
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000791 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000792}
793
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000794/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000795/// token of the macro expansion.
796bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000797 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000798 const LangOptions &LangOpts,
799 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000800 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
801
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000802 SourceLocation expansionLoc;
803 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
804 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000805
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000806 if (expansionLoc.isFileID()) {
807 // No other macro expansions, this is the first.
808 if (MacroBegin)
809 *MacroBegin = expansionLoc;
810 return true;
811 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000812
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000813 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000814}
815
816/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000817/// token of the macro expansion.
818bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000819 const SourceManager &SM,
820 const LangOptions &LangOpts,
821 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000822 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
823
824 SourceLocation spellLoc = SM.getSpellingLoc(loc);
825 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
826 if (tokLen == 0)
827 return false;
828
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000829 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
830 SourceLocation expansionLoc;
831 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
832 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000833
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000834 if (expansionLoc.isFileID()) {
835 // No other macro expansions.
836 if (MacroEnd)
837 *MacroEnd = expansionLoc;
838 return true;
839 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000840
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000841 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000842}
843
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000844static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000845 const SourceManager &SM,
846 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000847 SourceLocation Begin = Range.getBegin();
848 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000849 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000850 if (Range.isTokenRange()) {
851 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
852 if (End.isInvalid())
853 return CharSourceRange();
854 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000855
856 // Break down the source locations.
857 FileID FID;
858 unsigned BeginOffs;
859 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
860 if (FID.isInvalid())
861 return CharSourceRange();
862
863 unsigned EndOffs;
864 if (!SM.isInFileID(End, FID, &EndOffs) ||
865 BeginOffs > EndOffs)
866 return CharSourceRange();
867
868 return CharSourceRange::getCharRange(Begin, End);
869}
870
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000871CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000872 const SourceManager &SM,
873 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000874 SourceLocation Begin = Range.getBegin();
875 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000876 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000877 return CharSourceRange();
878
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000879 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000880 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881
882 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000883 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
884 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000885 Range.setBegin(Begin);
886 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000887 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000888
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000889 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000890 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
891 &End)) ||
892 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
893 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000894 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000895 Range.setEnd(End);
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000897 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000898
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000899 assert(Begin.isMacroID() && End.isMacroID());
900 SourceLocation MacroBegin, MacroEnd;
901 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000902 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
903 &MacroEnd)) ||
904 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
905 &MacroEnd)))) {
906 Range.setBegin(MacroBegin);
907 Range.setEnd(MacroEnd);
908 return makeRangeFromFileLocs(Range, SM, LangOpts);
909 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000910
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000911 bool Invalid = false;
912 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
913 &Invalid);
914 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000915 return CharSourceRange();
916
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000917 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
918 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
919 &Invalid);
920 if (Invalid)
921 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000922
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000923 if (EndEntry.getExpansion().isMacroArgExpansion() &&
924 BeginEntry.getExpansion().getExpansionLocStart() ==
925 EndEntry.getExpansion().getExpansionLocStart()) {
926 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
927 Range.setEnd(SM.getImmediateSpellingLoc(End));
928 return makeFileCharRange(Range, SM, LangOpts);
929 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000930 }
931
932 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000933}
934
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000935StringRef Lexer::getSourceText(CharSourceRange Range,
936 const SourceManager &SM,
937 const LangOptions &LangOpts,
938 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000939 Range = makeFileCharRange(Range, SM, LangOpts);
940 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000941 if (Invalid) *Invalid = true;
942 return StringRef();
943 }
944
945 // Break down the source location.
946 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
947 if (beginInfo.first.isInvalid()) {
948 if (Invalid) *Invalid = true;
949 return StringRef();
950 }
951
952 unsigned EndOffs;
953 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
954 beginInfo.second > EndOffs) {
955 if (Invalid) *Invalid = true;
956 return StringRef();
957 }
958
959 // Try to the load the file buffer.
960 bool invalidTemp = false;
961 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
962 if (invalidTemp) {
963 if (Invalid) *Invalid = true;
964 return StringRef();
965 }
966
967 if (Invalid) *Invalid = false;
968 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
969}
970
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000971StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
972 const SourceManager &SM,
973 const LangOptions &LangOpts) {
974 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000975
976 // Find the location of the immediate macro expansion.
977 while (1) {
978 FileID FID = SM.getFileID(Loc);
979 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
980 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
981 Loc = Expansion.getExpansionLocStart();
982 if (!Expansion.isMacroArgExpansion())
983 break;
984
985 // For macro arguments we need to check that the argument did not come
986 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
987
988 // Loc points to the argument id of the macro definition, move to the
989 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000990 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000991 SourceLocation SpellLoc = Expansion.getSpellingLoc();
992 if (SpellLoc.isFileID())
993 break; // No inner macro.
994
995 // If spelling location resides in the same FileID as macro expansion
996 // location, it means there is no inner macro.
997 FileID MacroFID = SM.getFileID(Loc);
998 if (SM.isInFileID(SpellLoc, MacroFID))
999 break;
1000
1001 // Argument came from inner macro.
1002 Loc = SpellLoc;
1003 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001004
1005 // Find the spelling location of the start of the non-argument expansion
1006 // range. This is where the macro name was spelled in order to begin
1007 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001008 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001009
1010 // Dig out the buffer where the macro name was spelled and the extents of the
1011 // name so that we can render it into the expansion note.
1012 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1013 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1014 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1015 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1016}
1017
Jordan Rose288c4212012-06-07 01:10:31 +00001018bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001019 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001020}
1021
Chris Lattnerd01e2912006-06-18 16:22:51 +00001022
Chris Lattner22eb9722006-06-18 05:43:12 +00001023//===----------------------------------------------------------------------===//
1024// Diagnostics forwarding code.
1025//===----------------------------------------------------------------------===//
1026
Chris Lattner619c1742007-07-22 18:38:25 +00001027/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001028/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001029/// This is currently only used for _Pragma implementation, so it is the slow
1030/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001031static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1032 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001033static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1034 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001035 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001036 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chris Lattner619c1742007-07-22 18:38:25 +00001038 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001039 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001040 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001041 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001043 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001044 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001045 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001046 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner9dc9c202009-02-15 20:52:18 +00001048 // Figure out the expansion loc range, which is the range covered by the
1049 // original _Pragma(...) sequence.
1050 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001051 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chandler Carruth115b0772011-07-26 03:03:05 +00001053 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001054}
1055
Chris Lattner22eb9722006-06-18 05:43:12 +00001056/// getSourceLocation - Return a source location identifier for the specified
1057/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001058SourceLocation Lexer::getSourceLocation(const char *Loc,
1059 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001060 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001061 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001062
1063 // In the normal case, we're just lexing from a simple file buffer, return
1064 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001065 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001066 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001067 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001068
Chris Lattnerd32480d2009-01-17 06:22:33 +00001069 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1070 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001071 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001072 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001073}
1074
Chris Lattner22eb9722006-06-18 05:43:12 +00001075/// Diag - Forwarding function for diagnostics. This translate a source
1076/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001077DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001078 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001079}
1080
1081//===----------------------------------------------------------------------===//
1082// Trigraph and Escaped Newline Handling Code.
1083//===----------------------------------------------------------------------===//
1084
1085/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1086/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1087static char GetTrigraphCharForLetter(char Letter) {
1088 switch (Letter) {
1089 default: return 0;
1090 case '=': return '#';
1091 case ')': return ']';
1092 case '(': return '[';
1093 case '!': return '|';
1094 case '\'': return '^';
1095 case '>': return '}';
1096 case '/': return '\\';
1097 case '<': return '{';
1098 case '-': return '~';
1099 }
1100}
1101
1102/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1103/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1104/// return the result character. Finally, emit a warning about trigraph use
1105/// whether trigraphs are enabled or not.
1106static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1107 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001108 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001109
David Blaikiebbafb8a2012-03-11 07:00:24 +00001110 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001111 if (!L->isLexingRawMode())
1112 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001113 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001114 }
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattner6d27a162008-11-22 02:02:22 +00001116 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001117 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 return Res;
1119}
1120
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001121/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1122/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
Mike Stump11289f42009-09-09 15:08:12 +00001123/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001124unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1125 unsigned Size = 0;
1126 while (isWhitespace(Ptr[Size])) {
1127 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001129 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1130 continue;
1131
1132 // If this is a \r\n or \n\r, skip the other half.
1133 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1134 Ptr[Size-1] != Ptr[Size])
1135 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001137 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001138 }
1139
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001140 // Not an escaped newline, must be a \t or something else.
1141 return 0;
1142}
1143
Chris Lattner38b2cde2009-04-18 22:27:02 +00001144/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1145/// them), skip over them and return the first non-escaped-newline found,
1146/// otherwise return P.
1147const char *Lexer::SkipEscapedNewLines(const char *P) {
1148 while (1) {
1149 const char *AfterEscape;
1150 if (*P == '\\') {
1151 AfterEscape = P+1;
1152 } else if (*P == '?') {
1153 // If not a trigraph for escape, bail out.
1154 if (P[1] != '?' || P[2] != '/')
1155 return P;
1156 AfterEscape = P+3;
1157 } else {
1158 return P;
1159 }
Mike Stump11289f42009-09-09 15:08:12 +00001160
Chris Lattner38b2cde2009-04-18 22:27:02 +00001161 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1162 if (NewLineSize == 0) return P;
1163 P = AfterEscape+NewLineSize;
1164 }
1165}
1166
Anna Zaks59a3c802011-07-27 21:43:43 +00001167/// \brief Checks that the given token is the first token that occurs after the
1168/// given location (this excludes comments and whitespace). Returns the location
1169/// immediately after the specified token. If the token is not found or the
1170/// location is inside a macro, the returned source location will be invalid.
1171SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1172 tok::TokenKind TKind,
1173 const SourceManager &SM,
1174 const LangOptions &LangOpts,
1175 bool SkipTrailingWhitespaceAndNewLine) {
1176 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001177 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001178 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001179 }
1180 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1181
1182 // Break down the source location.
1183 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1184
1185 // Try to load the file buffer.
1186 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001187 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001188 if (InvalidTemp)
1189 return SourceLocation();
1190
1191 const char *TokenBegin = File.data() + LocInfo.second;
1192
1193 // Lex from the start of the given location.
1194 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1195 TokenBegin, File.end());
1196 // Find the token.
1197 Token Tok;
1198 lexer.LexFromRawLexer(Tok);
1199 if (Tok.isNot(TKind))
1200 return SourceLocation();
1201 SourceLocation TokenLoc = Tok.getLocation();
1202
1203 // Calculate how much whitespace needs to be skipped if any.
1204 unsigned NumWhitespaceChars = 0;
1205 if (SkipTrailingWhitespaceAndNewLine) {
1206 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1207 Tok.getLength();
1208 unsigned char C = *TokenEnd;
1209 while (isHorizontalWhitespace(C)) {
1210 C = *(++TokenEnd);
1211 NumWhitespaceChars++;
1212 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001213
1214 // Skip \r, \n, \r\n, or \n\r
1215 if (C == '\n' || C == '\r') {
1216 char PrevC = C;
1217 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001218 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001219 if ((C == '\n' || C == '\r') && C != PrevC)
1220 NumWhitespaceChars++;
1221 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001222 }
1223
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001224 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001225}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001226
Chris Lattner22eb9722006-06-18 05:43:12 +00001227/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1228/// get its size, and return it. This is tricky in several cases:
1229/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1230/// then either return the trigraph (skipping 3 chars) or the '?',
1231/// depending on whether trigraphs are enabled or not.
1232/// 2. If this is an escaped newline (potentially with whitespace between
1233/// the backslash and newline), implicitly skip the newline and return
1234/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001235///
1236/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1237/// know that we can accumulate into Size, and that we have already incremented
1238/// Ptr by Size bytes.
1239///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001240/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1241/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001242///
1243char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001244 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001245 // If we have a slash, look for an escaped newline.
1246 if (Ptr[0] == '\\') {
1247 ++Size;
1248 ++Ptr;
1249Slash:
1250 // Common case, backslash-char where the char is not whitespace.
1251 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001252
Chris Lattnerc1835952009-06-23 05:15:06 +00001253 // See if we have optional whitespace characters between the slash and
1254 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001255 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1256 // Remember that this token needs to be cleaned.
1257 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001258
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001259 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001260 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001261 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001262
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001263 // Found backslash<whitespace><newline>. Parse the char after it.
1264 Size += EscapedNewLineSize;
1265 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001266
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001267 // If the char that we finally got was a \n, then we must have had
1268 // something like \<newline><newline>. We don't want to consume the
1269 // second newline.
1270 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1271 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001272
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001273 // Use slow version to accumulate a correct size field.
1274 return getCharAndSizeSlow(Ptr, Size, Tok);
1275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
Chris Lattner22eb9722006-06-18 05:43:12 +00001277 // Otherwise, this is not an escaped newline, just return the slash.
1278 return '\\';
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Chris Lattner22eb9722006-06-18 05:43:12 +00001281 // If this is a trigraph, process it.
1282 if (Ptr[0] == '?' && Ptr[1] == '?') {
1283 // If this is actually a legal trigraph (not something like "??x"), emit
1284 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1285 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1286 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001287 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001288
1289 Ptr += 3;
1290 Size += 3;
1291 if (C == '\\') goto Slash;
1292 return C;
1293 }
1294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Chris Lattner22eb9722006-06-18 05:43:12 +00001296 // If this is neither, return a single character.
1297 ++Size;
1298 return *Ptr;
1299}
1300
Chris Lattnerd01e2912006-06-18 16:22:51 +00001301
Chris Lattner22eb9722006-06-18 05:43:12 +00001302/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1303/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1304/// and that we have already incremented Ptr by Size bytes.
1305///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001306/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1307/// be updated to match.
1308char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001309 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001310 // If we have a slash, look for an escaped newline.
1311 if (Ptr[0] == '\\') {
1312 ++Size;
1313 ++Ptr;
1314Slash:
1315 // Common case, backslash-char where the char is not whitespace.
1316 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001317
Chris Lattner22eb9722006-06-18 05:43:12 +00001318 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001319 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1320 // Found backslash<whitespace><newline>. Parse the char after it.
1321 Size += EscapedNewLineSize;
1322 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001323
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001324 // If the char that we finally got was a \n, then we must have had
1325 // something like \<newline><newline>. We don't want to consume the
1326 // second newline.
1327 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1328 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001329
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001330 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattner22eb9722006-06-18 05:43:12 +00001334 // Otherwise, this is not an escaped newline, just return the slash.
1335 return '\\';
1336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001339 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001340 // If this is actually a legal trigraph (not something like "??x"), return
1341 // it.
1342 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1343 Ptr += 3;
1344 Size += 3;
1345 if (C == '\\') goto Slash;
1346 return C;
1347 }
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 // If this is neither, return a single character.
1351 ++Size;
1352 return *Ptr;
1353}
1354
Chris Lattner22eb9722006-06-18 05:43:12 +00001355//===----------------------------------------------------------------------===//
1356// Helper methods for lexing.
1357//===----------------------------------------------------------------------===//
1358
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001359/// \brief Routine that indiscriminately skips bytes in the source file.
1360void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1361 BufferPtr += Bytes;
1362 if (BufferPtr > BufferEnd)
1363 BufferPtr = BufferEnd;
1364 IsAtStartOfLine = StartOfLine;
1365}
1366
Jordan Rose58c61e02013-02-09 01:10:25 +00001367static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1368 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1369 return isCharInSet(C, C11AllowedIDChars);
1370 else if (LangOpts.CPlusPlus)
1371 return isCharInSet(C, CXX03AllowedIDChars);
1372 else
1373 return isCharInSet(C, C99AllowedIDChars);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001374}
1375
Jordan Rose58c61e02013-02-09 01:10:25 +00001376static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1377 assert(isAllowedIDChar(C, LangOpts));
1378 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1379 return !isCharInSet(C, C11DisallowedInitialIDChars);
1380 else if (LangOpts.CPlusPlus)
1381 return true;
1382 else
1383 return !isCharInSet(C, C99DisallowedInitialIDChars);
1384}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001385
Jordan Rose58c61e02013-02-09 01:10:25 +00001386static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1387 const char *End) {
1388 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1389 L.getSourceLocation(End));
1390}
1391
1392static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1393 CharSourceRange Range, bool IsFirst) {
1394 // Check C99 compatibility.
1395 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1396 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1397 enum {
1398 CannotAppearInIdentifier = 0,
1399 CannotStartIdentifier
1400 };
1401
1402 if (!isCharInSet(C, C99AllowedIDChars)) {
1403 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1404 << Range
1405 << CannotAppearInIdentifier;
1406 } else if (IsFirst && isCharInSet(C, C99DisallowedInitialIDChars)) {
1407 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1408 << Range
1409 << CannotStartIdentifier;
1410 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001411 }
1412
Jordan Rose58c61e02013-02-09 01:10:25 +00001413 // Check C++98 compatibility.
1414 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1415 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1416 if (!isCharInSet(C, CXX03AllowedIDChars)) {
1417 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1418 << Range;
1419 }
1420 }
1421 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001422
Chris Lattner146762e2007-07-20 16:59:19 +00001423void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001424 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1425 unsigned Size;
1426 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001427 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001428 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001429
Chris Lattner22eb9722006-06-18 05:43:12 +00001430 --CurPtr; // Back up over the skipped character.
1431
1432 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1433 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001434 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001435 // TODO: Could merge these checks into an InfoTable flag to make the
1436 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001437 if (isASCII(C) && C != '\\' && C != '?' &&
1438 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001439FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001440 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001441 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1442 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001443
Chris Lattner0f1f5052006-07-20 04:16:23 +00001444 // If we are in raw mode, return this identifier raw. There is no need to
1445 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001446 if (LexingRawMode)
1447 return;
Mike Stump11289f42009-09-09 15:08:12 +00001448
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001449 // Fill in Result.IdentifierInfo and update the token kind,
1450 // looking up the identifier in the identifier table.
1451 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Chris Lattnerc5a00062006-06-18 16:41:01 +00001453 // Finally, now that we know we have an identifier, pass this off to the
1454 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001455 if (II->isHandleIdentifierCase())
Chris Lattnerad89ec02009-01-21 07:43:11 +00001456 PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001457
Chris Lattnerad89ec02009-01-21 07:43:11 +00001458 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001459 }
Mike Stump11289f42009-09-09 15:08:12 +00001460
Chris Lattner22eb9722006-06-18 05:43:12 +00001461 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001462
Chris Lattner22eb9722006-06-18 05:43:12 +00001463 C = getCharAndSize(CurPtr, Size);
1464 while (1) {
1465 if (C == '$') {
1466 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001467 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001468
Chris Lattner22eb9722006-06-18 05:43:12 +00001469 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001470 if (!isLexingRawMode())
1471 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001472 CurPtr = ConsumeChar(CurPtr, Size, Result);
1473 C = getCharAndSize(CurPtr, Size);
1474 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001475
1476 } else if (C == '\\') {
1477 const char *UCNPtr = CurPtr + Size;
1478 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Rose58c61e02013-02-09 01:10:25 +00001479 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001480 goto FinishIdentifier;
1481
Jordan Rose58c61e02013-02-09 01:10:25 +00001482 if (!isLexingRawMode()) {
1483 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1484 makeCharRange(*this, CurPtr, UCNPtr),
1485 /*IsFirst=*/false);
1486 }
1487
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001488 Result.setFlag(Token::HasUCN);
1489 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1490 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1491 CurPtr = UCNPtr;
1492 else
1493 while (CurPtr != UCNPtr)
1494 (void)getAndAdvanceChar(CurPtr, Result);
1495
1496 C = getCharAndSize(CurPtr, Size);
1497 continue;
1498 } else if (!isASCII(C)) {
1499 const char *UnicodePtr = CurPtr;
1500 UTF32 CodePoint;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00001501 ConversionResult Result =
1502 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1503 (const UTF8 *)BufferEnd,
1504 &CodePoint,
1505 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001506 if (Result != conversionOK ||
Jordan Rose58c61e02013-02-09 01:10:25 +00001507 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001508 goto FinishIdentifier;
1509
Jordan Rose58c61e02013-02-09 01:10:25 +00001510 if (!isLexingRawMode()) {
1511 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1512 makeCharRange(*this, CurPtr, UnicodePtr),
1513 /*IsFirst=*/false);
1514 }
1515
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001516 CurPtr = UnicodePtr;
1517 C = getCharAndSize(CurPtr, Size);
1518 continue;
1519 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 goto FinishIdentifier;
1521 }
1522
1523 // Otherwise, this character is good, consume it.
1524 CurPtr = ConsumeChar(CurPtr, Size, Result);
1525
1526 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001527 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001528 CurPtr = ConsumeChar(CurPtr, Size, Result);
1529 C = getCharAndSize(CurPtr, Size);
1530 }
1531 }
1532}
1533
Douglas Gregor759ef232010-08-30 14:50:47 +00001534/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001535/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001536bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001537 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001538 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001539 if (C1 != '0')
1540 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001541 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001542 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001543}
Chris Lattner22eb9722006-06-18 05:43:12 +00001544
Nate Begeman5eee9332008-04-14 02:26:39 +00001545/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001546/// constant. From[-1] is the first character lexed. Return the end of the
1547/// constant.
Chris Lattner146762e2007-07-20 16:59:19 +00001548void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001549 unsigned Size;
1550 char C = getCharAndSize(CurPtr, Size);
1551 char PrevCh = 0;
Jordan Rosea2100d72013-02-08 22:30:22 +00001552 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Chris Lattner22eb9722006-06-18 05:43:12 +00001553 CurPtr = ConsumeChar(CurPtr, Size, Result);
1554 PrevCh = C;
1555 C = getCharAndSize(CurPtr, Size);
1556 }
Mike Stump11289f42009-09-09 15:08:12 +00001557
Chris Lattner22eb9722006-06-18 05:43:12 +00001558 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001559 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1560 // If we are in Microsoft mode, don't continue if the constant is hex.
1561 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001562 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001563 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1564 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001565
1566 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001567 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1568 // Outside C99, we accept hexadecimal floating point numbers as a
1569 // not-quite-conforming extension. Only do so if this looks like it's
1570 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1571 bool IsHexFloat = true;
1572 if (!LangOpts.C99) {
1573 if (!isHexaLiteral(BufferPtr, LangOpts))
1574 IsHexFloat = false;
1575 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1576 IsHexFloat = false;
1577 }
1578 if (IsHexFloat)
1579 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1580 }
Mike Stump11289f42009-09-09 15:08:12 +00001581
Chris Lattnerd01e2912006-06-18 16:22:51 +00001582 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001583 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001584 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001585 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001586}
1587
Richard Smithe18f0fa2012-03-05 04:02:15 +00001588/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001589/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001590const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1591 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001593
1594 // Maximally munch an identifier. FIXME: UCNs.
1595 unsigned Size;
1596 char C = getCharAndSize(CurPtr, Size);
1597 if (isIdentifierHead(C)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001598 if (!getLangOpts().CPlusPlus11) {
Richard Smith3e4a60a2012-03-07 03:13:00 +00001599 if (!isLexingRawMode())
Richard Smith0df56f42012-03-08 02:39:21 +00001600 Diag(CurPtr,
1601 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1602 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1603 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1604 return CurPtr;
1605 }
1606
1607 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1608 // that does not start with an underscore is ill-formed. As a conforming
1609 // extension, we treat all such suffixes as if they had whitespace before
1610 // them.
Richard Smithf4198b72013-07-23 08:14:48 +00001611 bool IsUDSuffix = false;
1612 if (C == '_')
1613 IsUDSuffix = true;
1614 else if (IsStringLiteral && C == 's' && getLangOpts().CPlusPlus1y) {
1615 // In C++1y, "s" is a valid ud-suffix for a string literal.
1616 unsigned NextSize;
1617 if (!isIdentifierBody(getCharAndSizeNoWarn(CurPtr + Size, NextSize,
1618 getLangOpts())))
1619 IsUDSuffix = true;
1620 }
1621
1622 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001623 if (!isLexingRawMode())
Richard Smithf4198b72013-07-23 08:14:48 +00001624 Diag(CurPtr, getLangOpts().MicrosoftMode ?
Francois Pichet7ebc4c12012-04-07 23:09:23 +00001625 diag::ext_ms_reserved_user_defined_literal :
1626 diag::ext_reserved_user_defined_literal)
Richard Smith3e4a60a2012-03-07 03:13:00 +00001627 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1628 return CurPtr;
1629 }
1630
Richard Smithd67aea22012-03-06 03:21:47 +00001631 Result.setFlag(Token::HasUDSuffix);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001632 do {
1633 CurPtr = ConsumeChar(CurPtr, Size, Result);
1634 C = getCharAndSize(CurPtr, Size);
1635 } while (isIdentifierBody(C));
1636 }
1637 return CurPtr;
1638}
1639
Chris Lattner22eb9722006-06-18 05:43:12 +00001640/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001641/// either " or L" or u8" or u" or U".
1642void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1643 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001644 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001645
Richard Smithacd4d3d2011-10-15 01:18:56 +00001646 if (!isLexingRawMode() &&
1647 (Kind == tok::utf8_string_literal ||
1648 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001649 Kind == tok::utf32_string_literal))
1650 Diag(BufferPtr, getLangOpts().CPlusPlus
1651 ? diag::warn_cxx98_compat_unicode_literal
1652 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001653
Chris Lattner22eb9722006-06-18 05:43:12 +00001654 char C = getAndAdvanceChar(CurPtr, Result);
1655 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001656 // Skip escaped characters. Escaped newlines will already be processed by
1657 // getAndAdvanceChar.
1658 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001659 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001660
Chris Lattner52d96ac2010-05-30 23:27:38 +00001661 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001662 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001663 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001664 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001665 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001666 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001667 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001668
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001669 if (C == 0) {
1670 if (isCodeCompletionPoint(CurPtr-1)) {
1671 PP->CodeCompleteNaturalLanguage();
1672 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1673 return cutOffLexing();
1674 }
1675
Chris Lattner52d96ac2010-05-30 23:27:38 +00001676 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001677 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001678 C = getAndAdvanceChar(CurPtr, Result);
1679 }
Mike Stump11289f42009-09-09 15:08:12 +00001680
Richard Smithe18f0fa2012-03-05 04:02:15 +00001681 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001682 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001683 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001684
Chris Lattner5a78a022006-07-20 06:02:19 +00001685 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001686 if (NulCharacter && !isLexingRawMode())
1687 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001688
Chris Lattnerd01e2912006-06-18 16:22:51 +00001689 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001690 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001691 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001692 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001693}
1694
Craig Topper54edcca2011-08-11 04:06:15 +00001695/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1696/// having lexed R", LR", u8R", uR", or UR".
1697void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1698 tok::TokenKind Kind) {
1699 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1700 // Between the initial and final double quote characters of the raw string,
1701 // any transformations performed in phases 1 and 2 (trigraphs,
1702 // universal-character-names, and line splicing) are reverted.
1703
Richard Smithacd4d3d2011-10-15 01:18:56 +00001704 if (!isLexingRawMode())
1705 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1706
Craig Topper54edcca2011-08-11 04:06:15 +00001707 unsigned PrefixLen = 0;
1708
1709 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1710 ++PrefixLen;
1711
1712 // If the last character was not a '(', then we didn't lex a valid delimiter.
1713 if (CurPtr[PrefixLen] != '(') {
1714 if (!isLexingRawMode()) {
1715 const char *PrefixEnd = &CurPtr[PrefixLen];
1716 if (PrefixLen == 16) {
1717 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1718 } else {
1719 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1720 << StringRef(PrefixEnd, 1);
1721 }
1722 }
1723
1724 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1725 // it's possible the '"' was intended to be part of the raw string, but
1726 // there's not much we can do about that.
1727 while (1) {
1728 char C = *CurPtr++;
1729
1730 if (C == '"')
1731 break;
1732 if (C == 0 && CurPtr-1 == BufferEnd) {
1733 --CurPtr;
1734 break;
1735 }
1736 }
1737
1738 FormTokenWithChars(Result, CurPtr, tok::unknown);
1739 return;
1740 }
1741
1742 // Save prefix and move CurPtr past it
1743 const char *Prefix = CurPtr;
1744 CurPtr += PrefixLen + 1; // skip over prefix and '('
1745
1746 while (1) {
1747 char C = *CurPtr++;
1748
1749 if (C == ')') {
1750 // Check for prefix match and closing quote.
1751 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1752 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1753 break;
1754 }
1755 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1756 if (!isLexingRawMode())
1757 Diag(BufferPtr, diag::err_unterminated_raw_string)
1758 << StringRef(Prefix, PrefixLen);
1759 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1760 return;
1761 }
1762 }
1763
Richard Smithe18f0fa2012-03-05 04:02:15 +00001764 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001765 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001766 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001767
Craig Topper54edcca2011-08-11 04:06:15 +00001768 // Update the location of token as well as BufferPtr.
1769 const char *TokStart = BufferPtr;
1770 FormTokenWithChars(Result, CurPtr, Kind);
1771 Result.setLiteralData(TokStart);
1772}
1773
Chris Lattner22eb9722006-06-18 05:43:12 +00001774/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1775/// after having lexed the '<' character. This is used for #include filenames.
Chris Lattner146762e2007-07-20 16:59:19 +00001776void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001777 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001778 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001779 char C = getAndAdvanceChar(CurPtr, Result);
1780 while (C != '>') {
1781 // Skip escaped characters.
1782 if (C == '\\') {
1783 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001784 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001785 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001786 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1787 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001788 // If the filename is unterminated, then it must just be a lone <
1789 // character. Return this as such.
1790 FormTokenWithChars(Result, AfterLessPos, tok::less);
Chris Lattner5a78a022006-07-20 06:02:19 +00001791 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00001792 } else if (C == 0) {
1793 NulCharacter = CurPtr-1;
1794 }
1795 C = getAndAdvanceChar(CurPtr, Result);
1796 }
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattner5a78a022006-07-20 06:02:19 +00001798 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001799 if (NulCharacter && !isLexingRawMode())
1800 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Chris Lattnerd01e2912006-06-18 16:22:51 +00001802 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001803 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001804 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001805 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001806}
1807
1808
1809/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001810/// lexed either ' or L' or u' or U'.
1811void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1812 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001813 const char *NulCharacter = 0; // Does this character contain the \0 character?
1814
Richard Smithacd4d3d2011-10-15 01:18:56 +00001815 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001816 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1817 Diag(BufferPtr, getLangOpts().CPlusPlus
1818 ? diag::warn_cxx98_compat_unicode_literal
1819 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001820
Chris Lattner22eb9722006-06-18 05:43:12 +00001821 char C = getAndAdvanceChar(CurPtr, Result);
1822 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001823 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001824 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001825 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner5a78a022006-07-20 06:02:19 +00001826 return;
Chris Lattner86851b82010-07-07 23:24:27 +00001827 }
1828
1829 while (C != '\'') {
1830 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001831 if (C == '\\')
1832 C = getAndAdvanceChar(CurPtr, Result);
1833
1834 if (C == '\n' || C == '\r' || // Newline.
1835 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001836 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001837 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001838 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1839 return;
Nico Weber4e270382012-11-17 20:25:54 +00001840 }
1841
1842 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001843 if (isCodeCompletionPoint(CurPtr-1)) {
1844 PP->CodeCompleteNaturalLanguage();
1845 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1846 return cutOffLexing();
1847 }
1848
Chris Lattner86851b82010-07-07 23:24:27 +00001849 NulCharacter = CurPtr-1;
1850 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001851 C = getAndAdvanceChar(CurPtr, Result);
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Richard Smithe18f0fa2012-03-05 04:02:15 +00001854 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001855 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001856 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001857
Chris Lattner86851b82010-07-07 23:24:27 +00001858 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001859 if (NulCharacter && !isLexingRawMode())
1860 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001861
Chris Lattnerd01e2912006-06-18 16:22:51 +00001862 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001863 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001864 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001865 Result.setLiteralData(TokStart);
Chris Lattner22eb9722006-06-18 05:43:12 +00001866}
1867
1868/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1869/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001870///
1871/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1872///
1873bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001874 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001875 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1876
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001877 unsigned char Char = *CurPtr;
1878
1879 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001880 while (1) {
1881 // Skip horizontal whitespace very aggressively.
1882 while (isHorizontalWhitespace(Char))
1883 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001884
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001885 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001886 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001887 break;
Mike Stump11289f42009-09-09 15:08:12 +00001888
Chris Lattner22eb9722006-06-18 05:43:12 +00001889 if (ParsingPreprocessorDirective) {
1890 // End of preprocessor directive line, let LexTokenInternal handle this.
1891 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001892 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001895 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001896 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001897 Char = *++CurPtr;
1898 }
1899
Chris Lattner4d963442008-10-12 04:05:48 +00001900 // If the client wants us to return whitespace, return it now.
1901 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001902 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001903 if (SawNewline)
1904 IsAtStartOfLine = true;
1905 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001906 return true;
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001909 // If this isn't immediately after a newline, there is leading space.
1910 char PrevChar = CurPtr[-1];
1911 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1912
1913 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1914 if (SawNewline)
1915 Result.setFlag(Token::StartOfLine);
1916
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001918 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001919}
1920
Nico Weber158a31a2012-11-11 07:02:14 +00001921/// We have just read the // characters from input. Skip until we find the
1922/// newline character thats terminate the comment. Then update BufferPtr and
1923/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00001924///
1925/// If we're in KeepCommentMode or any CommentHandler has inserted
1926/// some tokens, this will store the first token and return true.
Nico Weber158a31a2012-11-11 07:02:14 +00001927bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1928 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00001929 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00001930 if (!LangOpts.LineComment && !isLexingRawMode()) {
1931 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00001932
Chris Lattner22eb9722006-06-18 05:43:12 +00001933 // Mark them enabled so we only emit one warning for this translation
1934 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00001935 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Chris Lattner22eb9722006-06-18 05:43:12 +00001938 // Scan over the body of the comment. The common case, when scanning, is that
1939 // the comment contains normal ascii characters with nothing interesting in
1940 // them. As such, optimize for this case with the inner loop.
1941 char C;
1942 do {
1943 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001944 // Skip over characters in the fast loop.
1945 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00001946 C != '\n' && C != '\r') // Newline or DOS-style newline.
1947 C = *++CurPtr;
1948
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001949 const char *NextLine = CurPtr;
1950 if (C != 0) {
1951 // We found a newline, see if it's escaped.
1952 const char *EscapePtr = CurPtr-1;
1953 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1954 --EscapePtr;
1955
1956 if (*EscapePtr == '\\') // Escaped newline.
1957 CurPtr = EscapePtr;
1958 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1959 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1960 CurPtr = EscapePtr-2;
1961 else
1962 break; // This is a newline, we're done.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001963 }
Mike Stump11289f42009-09-09 15:08:12 +00001964
Chris Lattner22eb9722006-06-18 05:43:12 +00001965 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00001966 // properly decode the character. Read it in raw mode to avoid emitting
1967 // diagnostics about things like trigraphs. If we see an escaped newline,
1968 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00001969 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00001970 bool OldRawMode = isLexingRawMode();
1971 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001972 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00001973 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00001974
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001975 // If we only read only one character, then no special handling is needed.
1976 // We're done and can skip forward to the newline.
1977 if (C != 0 && CurPtr == OldPtr+1) {
1978 CurPtr = NextLine;
1979 break;
1980 }
1981
Chris Lattner22eb9722006-06-18 05:43:12 +00001982 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00001983 // \n, then we had an escaped newline within the comment. Emit diagnostic
1984 // unless the next line is also a // comment.
1985 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001986 for (; OldPtr != CurPtr; ++OldPtr)
1987 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00001988 // Okay, we found a // comment that ends in a newline, if the next
1989 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00001990 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00001991 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00001992 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00001993 ++ForwardPtr;
1994 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1995 break;
1996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Chris Lattner6d27a162008-11-22 02:02:22 +00001998 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00001999 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002000 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002001 }
2002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor11583702010-08-25 17:04:25 +00002004 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002005 --CurPtr;
2006 break;
2007 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002008
2009 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2010 PP->CodeCompleteNaturalLanguage();
2011 cutOffLexing();
2012 return false;
2013 }
2014
Chris Lattner22eb9722006-06-18 05:43:12 +00002015 } while (C != '\n' && C != '\r');
2016
Chris Lattner93ddf802010-02-03 21:06:21 +00002017 // Found but did not consume the newline. Notify comment handlers about the
2018 // comment unless we're in a #if 0 block.
2019 if (PP && !isLexingRawMode() &&
2020 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2021 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002022 BufferPtr = CurPtr;
2023 return true; // A token has to be returned.
2024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattner457fc152006-07-29 06:30:25 +00002026 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002027 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002028 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002029
2030 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002031 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002032 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002033 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002034 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002035 }
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattner22eb9722006-06-18 05:43:12 +00002037 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002038 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002039 // contribute to another token), it isn't needed for correctness. Note that
2040 // this is ok even in KeepWhitespaceMode, because we would have returned the
2041 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002043
Chris Lattner22eb9722006-06-18 05:43:12 +00002044 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002045 Result.setFlag(Token::StartOfLine);
Chris Lattner22eb9722006-06-18 05:43:12 +00002046 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002047 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002048 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002049 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002050}
Chris Lattner22eb9722006-06-18 05:43:12 +00002051
Nico Weber158a31a2012-11-11 07:02:14 +00002052/// If in save-comment mode, package up this Line comment in an appropriate
2053/// way and return it.
2054bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002055 // If we're not in a preprocessor directive, just return the // comment
2056 // directly.
2057 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002058
David Blaikied5321242012-06-06 18:52:13 +00002059 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002061
Nico Weber158a31a2012-11-11 07:02:14 +00002062 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002063 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002064 bool Invalid = false;
2065 std::string Spelling = PP->getSpelling(Result, &Invalid);
2066 if (Invalid)
2067 return true;
2068
Nico Weber158a31a2012-11-11 07:02:14 +00002069 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002070 Spelling[1] = '*'; // Change prefix to "/*".
2071 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002072
Chris Lattnerb11c3232008-10-12 04:51:35 +00002073 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002074 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002075 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002076 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002077}
2078
Chris Lattnercb283342006-06-18 06:48:37 +00002079/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002080/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2081/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002082static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002083 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002084 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattner22eb9722006-06-18 05:43:12 +00002086 // Back up off the newline.
2087 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattner22eb9722006-06-18 05:43:12 +00002089 // If this is a two-character newline sequence, skip the other character.
2090 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2091 // \n\n or \r\r -> not escaped newline.
2092 if (CurPtr[0] == CurPtr[1])
2093 return false;
2094 // \n\r or \r\n -> skip the newline.
2095 --CurPtr;
2096 }
Mike Stump11289f42009-09-09 15:08:12 +00002097
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 // If we have horizontal whitespace, skip over it. We allow whitespace
2099 // between the slash and newline.
2100 bool HasSpace = false;
2101 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2102 --CurPtr;
2103 HasSpace = true;
2104 }
Mike Stump11289f42009-09-09 15:08:12 +00002105
Chris Lattner22eb9722006-06-18 05:43:12 +00002106 // If we have a slash, we know this is an escaped newline.
2107 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002108 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002109 } else {
2110 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002111 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2112 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002114
Chris Lattnercb283342006-06-18 06:48:37 +00002115 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002116 CurPtr -= 2;
2117
2118 // If no trigraphs are enabled, warn that we ignored this trigraph and
2119 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002121 if (!L->isLexingRawMode())
2122 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002123 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002124 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002125 if (!L->isLexingRawMode())
2126 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002127 }
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattner22eb9722006-06-18 05:43:12 +00002129 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002130 if (!L->isLexingRawMode())
2131 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattner22eb9722006-06-18 05:43:12 +00002133 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002134 if (HasSpace && !L->isLexingRawMode())
2135 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002136
Chris Lattnercb283342006-06-18 06:48:37 +00002137 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002138}
2139
Chris Lattneraded4a92006-10-27 04:42:31 +00002140#ifdef __SSE2__
2141#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002142#elif __ALTIVEC__
2143#include <altivec.h>
2144#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002145#endif
2146
James Dennettf442d242012-06-17 03:40:43 +00002147/// We have just read from input the / and * characters that started a comment.
2148/// Read until we find the * and / characters that terminate the comment.
2149/// Note that we don't bother decoding trigraphs or escaped newlines in block
2150/// comments, because they cannot cause the comment to end. The only thing
2151/// that can happen is the comment could end with an escaped newline between
2152/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002153///
Chris Lattner87d02082010-01-18 22:35:47 +00002154/// If we're in KeepCommentMode or any CommentHandler has inserted
2155/// some tokens, this will store the first token and return true.
Chris Lattner146762e2007-07-20 16:59:19 +00002156bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002157 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002158 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002159 // optimization helps people who like to put a lot of * characters in their
2160 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002161
2162 // The first character we get with newlines and trigraphs skipped to handle
2163 // the degenerate /*/ case below correctly if the * has an escaped newline
2164 // after it.
2165 unsigned CharSize;
2166 unsigned char C = getCharAndSize(CurPtr, CharSize);
2167 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002169 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002170 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002171 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattner99e7d232008-10-12 04:19:49 +00002173 // KeepWhitespaceMode should return this broken comment as a token. Since
2174 // it isn't a well formed comment, just return it as an 'unknown' token.
2175 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002176 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002177 return true;
2178 }
Mike Stump11289f42009-09-09 15:08:12 +00002179
Chris Lattner99e7d232008-10-12 04:19:49 +00002180 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002181 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Chris Lattnerc850ad62007-07-21 23:43:37 +00002184 // Check to see if the first character after the '/*' is another /. If so,
2185 // then this slash does not end the block comment, it is part of it.
2186 if (C == '/')
2187 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002190 // Skip over all non-interesting characters until we find end of buffer or a
2191 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002192 if (CurPtr + 24 < BufferEnd &&
2193 // If there is a code-completion point avoid the fast scan because it
2194 // doesn't check for '\0'.
2195 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002196 // While not aligned to a 16-byte boundary.
2197 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2198 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner6cc3e362006-10-27 04:12:35 +00002200 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002201
2202#ifdef __SSE2__
Benjamin Kramer38857372011-11-22 18:56:46 +00002203 __m128i Slashes = _mm_set1_epi8('/');
2204 while (CurPtr+16 <= BufferEnd) {
Roman Divackye6377112012-09-06 15:59:27 +00002205 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2206 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002207 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002208 // Adjust the pointer to point directly after the first slash. It's
2209 // not necessary to set C here, it will be overwritten at the end of
2210 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002211 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002212 goto FoundSlash;
2213 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002214 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002215 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002216#elif __ALTIVEC__
2217 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002218 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002219 '/', '/', '/', '/', '/', '/', '/', '/'
2220 };
2221 while (CurPtr+16 <= BufferEnd &&
2222 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2223 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002224#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002225 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002226 while (CurPtr[0] != '/' &&
2227 CurPtr[1] != '/' &&
2228 CurPtr[2] != '/' &&
2229 CurPtr[3] != '/' &&
2230 CurPtr+4 < BufferEnd) {
2231 CurPtr += 4;
2232 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002233#endif
Mike Stump11289f42009-09-09 15:08:12 +00002234
Chris Lattneraded4a92006-10-27 04:42:31 +00002235 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002236 C = *CurPtr++;
2237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238
Chris Lattneraded4a92006-10-27 04:42:31 +00002239 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002240 while (C != '/' && C != '\0')
2241 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Chris Lattner22eb9722006-06-18 05:43:12 +00002243 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002244 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002245 if (CurPtr[-2] == '*') // We found the final */. We're done!
2246 break;
Mike Stump11289f42009-09-09 15:08:12 +00002247
Chris Lattner22eb9722006-06-18 05:43:12 +00002248 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002249 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002250 // We found the final */, though it had an escaped newline between the
2251 // * and /. We're done!
2252 break;
2253 }
2254 }
2255 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2256 // If this is a /* inside of the comment, emit a warning. Don't do this
2257 // if this is a /*/, which will end the comment. This misses cases with
2258 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002259 if (!isLexingRawMode())
2260 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002261 }
2262 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002263 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002264 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002265 // Note: the user probably forgot a */. We could continue immediately
2266 // after the /*, but this would involve lexing a lot of what really is the
2267 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002268 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattner99e7d232008-10-12 04:19:49 +00002270 // KeepWhitespaceMode should return this broken comment as a token. Since
2271 // it isn't a well formed comment, just return it as an 'unknown' token.
2272 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002273 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002274 return true;
2275 }
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattner99e7d232008-10-12 04:19:49 +00002277 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002278 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002279 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2280 PP->CodeCompleteNaturalLanguage();
2281 cutOffLexing();
2282 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002283 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002284
Chris Lattner22eb9722006-06-18 05:43:12 +00002285 C = *CurPtr++;
2286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Chris Lattner93ddf802010-02-03 21:06:21 +00002288 // Notify comment handlers about the comment unless we're in a #if 0 block.
2289 if (PP && !isLexingRawMode() &&
2290 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2291 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002292 BufferPtr = CurPtr;
2293 return true; // A token has to be returned.
2294 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002295
Chris Lattner457fc152006-07-29 06:30:25 +00002296 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002297 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002298 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002299 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002300 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002301
2302 // It is common for the tokens immediately after a /**/ comment to be
2303 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002304 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2305 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002306 if (isHorizontalWhitespace(*CurPtr)) {
Chris Lattner457fc152006-07-29 06:30:25 +00002307 SkipWhitespace(Result, CurPtr+1);
Chris Lattnere01e7582008-10-12 04:15:42 +00002308 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002309 }
2310
2311 // Otherwise, just return so that the next character will be lexed as a token.
2312 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002313 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002314 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002315}
2316
2317//===----------------------------------------------------------------------===//
2318// Primary Lexing Entry Points
2319//===----------------------------------------------------------------------===//
2320
Chris Lattner22eb9722006-06-18 05:43:12 +00002321/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2322/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002323void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002324 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2325 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002326 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002327
2328 // CurPtr - Cache BufferPtr in an automatic variable.
2329 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002330 while (1) {
2331 char Char = getAndAdvanceChar(CurPtr, Tmp);
2332 switch (Char) {
2333 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002334 if (Result)
2335 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002336 break;
2337 case 0: // Null.
2338 // Found end of file?
2339 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002340 if (isCodeCompletionPoint(CurPtr-1)) {
2341 PP->CodeCompleteNaturalLanguage();
2342 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002343 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002344 }
2345
Chris Lattner22eb9722006-06-18 05:43:12 +00002346 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002347 if (Result)
2348 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002349 break;
2350 }
2351 // FALL THROUGH.
2352 case '\r':
2353 case '\n':
2354 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2355 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2356 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002357
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002358 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002359 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002360 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002361 if (PP)
2362 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002363 Lex(Tmp);
2364 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002365 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002366
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002367 // Finally, we're done;
2368 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002369 }
2370 }
2371}
2372
2373/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2374/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002375/// This returns true if Result contains a token, false if PP.Lex should be
2376/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002377bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002378 // If we hit the end of the file while parsing a preprocessor directive,
2379 // end the preprocessor directive first. The next token returned will
2380 // then be the end of file.
2381 if (ParsingPreprocessorDirective) {
2382 // Done parsing the "line".
2383 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002384 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002385 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002386
Chris Lattner457fc152006-07-29 06:30:25 +00002387 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002388 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002389 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002390 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002391
Chris Lattner30a2fa12006-07-19 06:31:49 +00002392 // If we are in raw mode, return this event as an EOF token. Let the caller
2393 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002394 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002395 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002396 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002397 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002398 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002399 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002400
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002401 // Issue diagnostics for unterminated #if and missing newline.
2402
Chris Lattner30a2fa12006-07-19 06:31:49 +00002403 // If we are in a #if directive, emit an error.
2404 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002405 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002406 PP->Diag(ConditionalStack.back().IfLoc,
2407 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002408 ConditionalStack.pop_back();
2409 }
Mike Stump11289f42009-09-09 15:08:12 +00002410
Chris Lattner8f96d042008-04-12 05:54:25 +00002411 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2412 // a pedwarn.
Seth Cantrelle83c7312012-04-13 03:43:23 +00002413 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002414 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
Seth Cantrelle83c7312012-04-13 03:43:23 +00002415 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2416 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
Mike Stump11289f42009-09-09 15:08:12 +00002417
Chris Lattner22eb9722006-06-18 05:43:12 +00002418 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002419
2420 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002421 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002422}
2423
Chris Lattner678c8802006-07-11 05:46:12 +00002424/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2425/// the specified lexer will return a tok::l_paren token, 0 if it is something
2426/// else and 2 if there are no more tokens in the buffer controlled by the
2427/// lexer.
2428unsigned Lexer::isNextPPTokenLParen() {
2429 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002430
Chris Lattner678c8802006-07-11 05:46:12 +00002431 // Switch to 'skipping' mode. This will ensure that we can lex a token
2432 // without emitting diagnostics, disables macro expansion, and will cause EOF
2433 // to return an EOF token instead of popping the include stack.
2434 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002435
Chris Lattner678c8802006-07-11 05:46:12 +00002436 // Save state that can be changed while lexing so that we can restore it.
2437 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002438 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Mike Stump11289f42009-09-09 15:08:12 +00002439
Chris Lattner146762e2007-07-20 16:59:19 +00002440 Token Tok;
Chris Lattner8c204872006-10-14 05:19:21 +00002441 Tok.startToken();
Chris Lattner678c8802006-07-11 05:46:12 +00002442 LexTokenInternal(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002443
Chris Lattner678c8802006-07-11 05:46:12 +00002444 // Restore state that may have changed.
2445 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002446 ParsingPreprocessorDirective = inPPDirectiveMode;
Mike Stump11289f42009-09-09 15:08:12 +00002447
Chris Lattner678c8802006-07-11 05:46:12 +00002448 // Restore the lexer back to non-skipping mode.
2449 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002450
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002451 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002452 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002453 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002454}
2455
James Dennettf442d242012-06-17 03:40:43 +00002456/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002457static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2458 ConflictMarkerKind CMK) {
2459 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2460 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2461 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2462 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002463 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002464 // Must occur at start of line.
2465 if (RestOfBuffer[Pos-1] != '\r' &&
2466 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002467 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2468 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002469 continue;
2470 }
2471 return RestOfBuffer.data()+Pos;
2472 }
2473 return 0;
2474}
2475
2476/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2477/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2478/// and recover nicely. This returns true if it is a conflict marker and false
2479/// if not.
2480bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2481 // Only a conflict marker if it starts at the beginning of a line.
2482 if (CurPtr != BufferStart &&
2483 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2484 return false;
2485
Richard Smitha9e33d42011-10-12 00:37:51 +00002486 // Check to see if we have <<<<<<< or >>>>.
2487 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2488 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002489 return false;
2490
2491 // If we have a situation where we don't care about conflict markers, ignore
2492 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002493 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002494 return false;
2495
Richard Smitha9e33d42011-10-12 00:37:51 +00002496 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2497
2498 // Check to see if there is an ending marker somewhere in the buffer at the
2499 // start of a line to terminate this conflict marker.
2500 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002501 // We found a match. We are really in a conflict marker.
2502 // Diagnose this, and ignore to the end of line.
2503 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002504 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002505
2506 // Skip ahead to the end of line. We know this exists because the
2507 // end-of-conflict marker starts with \r or \n.
2508 while (*CurPtr != '\r' && *CurPtr != '\n') {
2509 assert(CurPtr != BufferEnd && "Didn't find end of line");
2510 ++CurPtr;
2511 }
2512 BufferPtr = CurPtr;
2513 return true;
2514 }
2515
2516 // No end of conflict marker found.
2517 return false;
2518}
2519
2520
Richard Smitha9e33d42011-10-12 00:37:51 +00002521/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2522/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2523/// is the end of a conflict marker. Handle it by ignoring up until the end of
2524/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002525bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2526 // Only a conflict marker if it starts at the beginning of a line.
2527 if (CurPtr != BufferStart &&
2528 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2529 return false;
2530
2531 // If we have a situation where we don't care about conflict markers, ignore
2532 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002533 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002534 return false;
2535
Richard Smitha9e33d42011-10-12 00:37:51 +00002536 // Check to see if we have the marker (4 characters in a row).
2537 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002538 if (CurPtr[i] != CurPtr[0])
2539 return false;
2540
2541 // If we do have it, search for the end of the conflict marker. This could
2542 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2543 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002544 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2545 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002546 CurPtr = End;
2547
2548 // Skip ahead to the end of line.
2549 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2550 ++CurPtr;
2551
2552 BufferPtr = CurPtr;
2553
2554 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002555 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002556 return true;
2557 }
2558
2559 return false;
2560}
2561
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002562bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2563 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002564 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002565 return Loc == PP->getCodeCompletionLoc();
2566 }
2567
2568 return false;
2569}
2570
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002571uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2572 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002573 unsigned CharSize;
2574 char Kind = getCharAndSize(StartPtr, CharSize);
2575
2576 unsigned NumHexDigits;
2577 if (Kind == 'u')
2578 NumHexDigits = 4;
2579 else if (Kind == 'U')
2580 NumHexDigits = 8;
2581 else
2582 return 0;
2583
Jordan Rosec0cba272013-01-27 20:12:04 +00002584 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002585 if (Result && !isLexingRawMode())
2586 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002587 return 0;
2588 }
2589
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002590 const char *CurPtr = StartPtr + CharSize;
2591 const char *KindLoc = &CurPtr[-1];
2592
2593 uint32_t CodePoint = 0;
2594 for (unsigned i = 0; i < NumHexDigits; ++i) {
2595 char C = getCharAndSize(CurPtr, CharSize);
2596
2597 unsigned Value = llvm::hexDigitValue(C);
2598 if (Value == -1U) {
2599 if (Result && !isLexingRawMode()) {
2600 if (i == 0) {
2601 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2602 << StringRef(KindLoc, 1);
2603 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002604 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002605
2606 // If the user wrote \U1234, suggest a fixit to \u.
2607 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002608 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002609 Diag(KindLoc, diag::note_ucn_four_not_eight)
2610 << FixItHint::CreateReplacement(URange, "u");
2611 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002612 }
2613 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002614
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002615 return 0;
2616 }
2617
2618 CodePoint <<= 4;
2619 CodePoint += Value;
2620
2621 CurPtr += CharSize;
2622 }
2623
2624 if (Result) {
2625 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002626 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002627 StartPtr = CurPtr;
2628 else
2629 while (StartPtr != CurPtr)
2630 (void)getAndAdvanceChar(StartPtr, *Result);
2631 } else {
2632 StartPtr = CurPtr;
2633 }
2634
2635 // C99 6.4.3p2: A universal character name shall not specify a character whose
2636 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2637 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2638 // C++11 [lex.charset]p2: If the hexadecimal value for a
2639 // universal-character-name corresponds to a surrogate code point (in the
2640 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2641 // if the hexadecimal value for a universal-character-name outside the
2642 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2643 // string literal corresponds to a control character (in either of the
2644 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2645 // basic source character set, the program is ill-formed.
2646 if (CodePoint < 0xA0) {
2647 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2648 return CodePoint;
2649
2650 // We don't use isLexingRawMode() here because we need to warn about bad
2651 // UCNs even when skipping preprocessing tokens in a #if block.
2652 if (Result && PP) {
2653 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2654 Diag(BufferPtr, diag::err_ucn_control_character);
2655 else {
2656 char C = static_cast<char>(CodePoint);
2657 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2658 }
2659 }
2660
2661 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002662
2663 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002664 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002665 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002666 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002667 if (Result && PP) {
2668 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2669 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2670 else
2671 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2672 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002673 return 0;
2674 }
2675
2676 return CodePoint;
2677}
2678
2679void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose17441582013-01-30 01:52:57 +00002680 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002681 isCharInSet(C, UnicodeWhitespaceChars)) {
Jordan Rose17441582013-01-30 01:52:57 +00002682 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002683 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002684
2685 Result.setFlag(Token::LeadingSpace);
2686 if (SkipWhitespace(Result, CurPtr))
2687 return; // KeepWhitespaceMode
2688
2689 return LexTokenInternal(Result);
2690 }
2691
Jordan Rose58c61e02013-02-09 01:10:25 +00002692 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2693 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2694 !PP->isPreprocessedOutput()) {
2695 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2696 makeCharRange(*this, BufferPtr, CurPtr),
2697 /*IsFirst=*/true);
2698 }
2699
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002700 MIOpt.ReadToken();
2701 return LexIdentifier(Result, CurPtr);
2702 }
2703
Jordan Rosecc538342013-01-31 19:48:48 +00002704 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2705 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002706 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002707 // Non-ASCII characters tend to creep into source code unintentionally.
2708 // Instead of letting the parser complain about the unknown token,
2709 // just drop the character.
2710 // Note that we can /only/ do this when the non-ASCII character is actually
2711 // spelled as Unicode, not written as a UCN. The standard requires that
2712 // we not throw away any possible preprocessor tokens, but there's a
2713 // loophole in the mapping of Unicode characters to basic character set
2714 // characters that allows us to map these particular characters to, say,
2715 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002716 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002717 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002718
2719 BufferPtr = CurPtr;
2720 return LexTokenInternal(Result);
2721 }
2722
2723 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2724 // up by accident.
2725 MIOpt.ReadToken();
2726 FormTokenWithChars(Result, CurPtr, tok::unknown);
2727}
2728
Chris Lattner22eb9722006-06-18 05:43:12 +00002729
2730/// LexTokenInternal - This implements a simple C family lexer. It is an
2731/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002732/// has a null character at the end of the file. This returns a preprocessing
2733/// token, not a normal token, as such, it is an internal interface. It assumes
2734/// that the Flags of result have been cleared before calling this.
Chris Lattner146762e2007-07-20 16:59:19 +00002735void Lexer::LexTokenInternal(Token &Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002736LexNextToken:
2737 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002738 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00002739 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00002740
Chris Lattner22eb9722006-06-18 05:43:12 +00002741 // CurPtr - Cache BufferPtr in an automatic variable.
2742 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002743
Chris Lattnereb54b592006-07-10 06:34:27 +00002744 // Small amounts of horizontal whitespace is very common between tokens.
2745 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2746 ++CurPtr;
2747 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2748 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002749
Chris Lattner4d963442008-10-12 04:05:48 +00002750 // If we are keeping whitespace and other tokens, just return what we just
2751 // skipped. The next lexer invocation will return the token after the
2752 // whitespace.
2753 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002754 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002755 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002756 return;
2757 }
Mike Stump11289f42009-09-09 15:08:12 +00002758
Chris Lattnereb54b592006-07-10 06:34:27 +00002759 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002760 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002761 }
Mike Stump11289f42009-09-09 15:08:12 +00002762
Chris Lattner22eb9722006-06-18 05:43:12 +00002763 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002764
Chris Lattner22eb9722006-06-18 05:43:12 +00002765 // Read a character, advancing over it.
2766 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002767 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002768
Chris Lattner22eb9722006-06-18 05:43:12 +00002769 switch (Char) {
2770 case 0: // Null.
2771 // Found end of file?
Chris Lattner2183a6e2006-07-18 06:36:12 +00002772 if (CurPtr-1 == BufferEnd) {
2773 // Read the PP instance variable into an automatic variable, because
2774 // LexEndOfFile will often delete 'this'.
Chris Lattner02b436a2007-10-17 20:41:00 +00002775 Preprocessor *PPCache = PP;
Chris Lattner2183a6e2006-07-18 06:36:12 +00002776 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2777 return; // Got a token to return.
Chris Lattner02b436a2007-10-17 20:41:00 +00002778 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2779 return PPCache->Lex(Result);
Chris Lattner2183a6e2006-07-18 06:36:12 +00002780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002782 // Check if we are performing code completion.
2783 if (isCodeCompletionPoint(CurPtr-1)) {
2784 // Return the code-completion token.
2785 Result.startToken();
2786 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2787 return;
2788 }
2789
Chris Lattner6d27a162008-11-22 02:02:22 +00002790 if (!isLexingRawMode())
2791 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002792 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00002793 if (SkipWhitespace(Result, CurPtr))
2794 return; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002795
Chris Lattner22eb9722006-06-18 05:43:12 +00002796 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00002797
2798 case 26: // DOS & CP/M EOF: "^Z".
2799 // If we're in Microsoft extensions mode, treat this as end of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002800 if (LangOpts.MicrosoftExt) {
Chris Lattner3dfff972009-12-17 05:29:40 +00002801 // Read the PP instance variable into an automatic variable, because
2802 // LexEndOfFile will often delete 'this'.
2803 Preprocessor *PPCache = PP;
2804 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2805 return; // Got a token to return.
2806 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2807 return PPCache->Lex(Result);
2808 }
2809 // If Microsoft extensions are disabled, this is just random garbage.
2810 Kind = tok::unknown;
2811 break;
2812
Chris Lattner22eb9722006-06-18 05:43:12 +00002813 case '\n':
2814 case '\r':
2815 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002816 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002817 if (ParsingPreprocessorDirective) {
2818 // Done parsing the "line".
2819 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002820
Chris Lattner457fc152006-07-29 06:30:25 +00002821 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002822 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002823 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002824
Chris Lattner22eb9722006-06-18 05:43:12 +00002825 // Since we consumed a newline, we are back at the start of a line.
2826 IsAtStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002827
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002828 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002829 break;
2830 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002831
Chris Lattner22eb9722006-06-18 05:43:12 +00002832 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002833 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002834
Chris Lattner4d963442008-10-12 04:05:48 +00002835 if (SkipWhitespace(Result, CurPtr))
2836 return; // KeepWhitespaceMode
Chris Lattner22eb9722006-06-18 05:43:12 +00002837 goto LexNextToken; // GCC isn't tail call eliminating.
2838 case ' ':
2839 case '\t':
2840 case '\f':
2841 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002842 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00002843 Result.setFlag(Token::LeadingSpace);
Chris Lattner4d963442008-10-12 04:05:48 +00002844 if (SkipWhitespace(Result, CurPtr))
2845 return; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00002846
2847 SkipIgnoredUnits:
2848 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002849
Chris Lattnerb9b85972007-07-22 06:29:05 +00002850 // If the next token is obviously a // or /* */ comment, skip it efficiently
2851 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00002852 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Nico Weber158a31a2012-11-11 07:02:14 +00002853 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2854 if (SkipLineComment(Result, CurPtr+2))
Chris Lattner87d02082010-01-18 22:35:47 +00002855 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002856 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00002857 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Chris Lattner87d02082010-01-18 22:35:47 +00002858 if (SkipBlockComment(Result, CurPtr+2))
2859 return; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002860 goto SkipIgnoredUnits;
2861 } else if (isHorizontalWhitespace(*CurPtr)) {
2862 goto SkipHorizontalWhitespace;
2863 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002864 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner3dfff972009-12-17 05:29:40 +00002865
Chris Lattner2b15cf72008-01-03 17:58:54 +00002866 // C99 6.4.4.1: Integer Constants.
2867 // C99 6.4.4.2: Floating Constants.
2868 case '0': case '1': case '2': case '3': case '4':
2869 case '5': case '6': case '7': case '8': case '9':
2870 // Notify MIOpt that we read a non-whitespace/non-comment token.
2871 MIOpt.ReadToken();
2872 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00002873
Richard Smith9b362092013-03-09 23:56:02 +00002874 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002875 // Notify MIOpt that we read a non-whitespace/non-comment token.
2876 MIOpt.ReadToken();
2877
Richard Smith9b362092013-03-09 23:56:02 +00002878 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002879 Char = getCharAndSize(CurPtr, SizeTmp);
2880
2881 // UTF-16 string literal
2882 if (Char == '"')
2883 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2884 tok::utf16_string_literal);
2885
2886 // UTF-16 character constant
2887 if (Char == '\'')
2888 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2889 tok::utf16_char_constant);
2890
Craig Topper54edcca2011-08-11 04:06:15 +00002891 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002892 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2893 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002894 return LexRawStringLiteral(Result,
2895 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2896 SizeTmp2, Result),
2897 tok::utf16_string_literal);
2898
2899 if (Char == '8') {
2900 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2901
2902 // UTF-8 string literal
2903 if (Char2 == '"')
2904 return LexStringLiteral(Result,
2905 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2906 SizeTmp2, Result),
2907 tok::utf8_string_literal);
2908
Richard Smith9b362092013-03-09 23:56:02 +00002909 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00002910 unsigned SizeTmp3;
2911 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2912 // UTF-8 raw string literal
2913 if (Char3 == '"') {
2914 return LexRawStringLiteral(Result,
2915 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2916 SizeTmp2, Result),
2917 SizeTmp3, Result),
2918 tok::utf8_string_literal);
2919 }
2920 }
2921 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00002922 }
2923
2924 // treat u like the start of an identifier.
2925 return LexIdentifier(Result, CurPtr);
2926
Richard Smith9b362092013-03-09 23:56:02 +00002927 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002928 // Notify MIOpt that we read a non-whitespace/non-comment token.
2929 MIOpt.ReadToken();
2930
Richard Smith9b362092013-03-09 23:56:02 +00002931 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002932 Char = getCharAndSize(CurPtr, SizeTmp);
2933
2934 // UTF-32 string literal
2935 if (Char == '"')
2936 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2937 tok::utf32_string_literal);
2938
2939 // UTF-32 character constant
2940 if (Char == '\'')
2941 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2942 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00002943
2944 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002945 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2946 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002947 return LexRawStringLiteral(Result,
2948 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2949 SizeTmp2, Result),
2950 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00002951 }
2952
2953 // treat U like the start of an identifier.
2954 return LexIdentifier(Result, CurPtr);
2955
Craig Topper54edcca2011-08-11 04:06:15 +00002956 case 'R': // Identifier or C++0x raw string literal
2957 // Notify MIOpt that we read a non-whitespace/non-comment token.
2958 MIOpt.ReadToken();
2959
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002960 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00002961 Char = getCharAndSize(CurPtr, SizeTmp);
2962
2963 if (Char == '"')
2964 return LexRawStringLiteral(Result,
2965 ConsumeChar(CurPtr, SizeTmp, Result),
2966 tok::string_literal);
2967 }
2968
2969 // treat R like the start of an identifier.
2970 return LexIdentifier(Result, CurPtr);
2971
Chris Lattner2b15cf72008-01-03 17:58:54 +00002972 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00002973 // Notify MIOpt that we read a non-whitespace/non-comment token.
2974 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00002975 Char = getCharAndSize(CurPtr, SizeTmp);
2976
2977 // Wide string literal.
2978 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00002979 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002980 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00002981
Craig Topper54edcca2011-08-11 04:06:15 +00002982 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002983 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00002984 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2985 return LexRawStringLiteral(Result,
2986 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2987 SizeTmp2, Result),
2988 tok::wide_string_literal);
2989
Chris Lattner22eb9722006-06-18 05:43:12 +00002990 // Wide character constant.
2991 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00002992 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2993 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00002994 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00002995
Chris Lattner22eb9722006-06-18 05:43:12 +00002996 // C99 6.4.2: Identifiers.
2997 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2998 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00002999 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003000 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3001 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3002 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003003 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003004 case 'v': case 'w': case 'x': case 'y': case 'z':
3005 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003006 // Notify MIOpt that we read a non-whitespace/non-comment token.
3007 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003008 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003009
3010 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003011 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003012 if (!isLexingRawMode())
3013 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003014 // Notify MIOpt that we read a non-whitespace/non-comment token.
3015 MIOpt.ReadToken();
3016 return LexIdentifier(Result, CurPtr);
3017 }
Mike Stump11289f42009-09-09 15:08:12 +00003018
Chris Lattnerb11c3232008-10-12 04:51:35 +00003019 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003020 break;
Mike Stump11289f42009-09-09 15:08:12 +00003021
Chris Lattner22eb9722006-06-18 05:43:12 +00003022 // C99 6.4.4: Character Constants.
3023 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003024 // Notify MIOpt that we read a non-whitespace/non-comment token.
3025 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003026 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003027
3028 // C99 6.4.5: String Literals.
3029 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003030 // Notify MIOpt that we read a non-whitespace/non-comment token.
3031 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003032 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003033
3034 // C99 6.4.6: Punctuators.
3035 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003036 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003037 break;
3038 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003039 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003040 break;
3041 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003042 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003043 break;
3044 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003045 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003046 break;
3047 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003048 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003049 break;
3050 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003051 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003052 break;
3053 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003054 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003055 break;
3056 case '.':
3057 Char = getCharAndSize(CurPtr, SizeTmp);
3058 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003059 // Notify MIOpt that we read a non-whitespace/non-comment token.
3060 MIOpt.ReadToken();
3061
Chris Lattner22eb9722006-06-18 05:43:12 +00003062 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003063 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003064 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003065 CurPtr += SizeTmp;
3066 } else if (Char == '.' &&
3067 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003068 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003069 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3070 SizeTmp2, Result);
3071 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003072 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003073 }
3074 break;
3075 case '&':
3076 Char = getCharAndSize(CurPtr, SizeTmp);
3077 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003078 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003079 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3080 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003081 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003082 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3083 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003084 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003085 }
3086 break;
Mike Stump11289f42009-09-09 15:08:12 +00003087 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003088 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003089 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003090 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3091 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003092 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003093 }
3094 break;
3095 case '+':
3096 Char = getCharAndSize(CurPtr, SizeTmp);
3097 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003098 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003099 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003100 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003101 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003102 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003103 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003104 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003105 }
3106 break;
3107 case '-':
3108 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003109 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003110 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003111 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003112 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003113 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003114 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3115 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003116 Kind = tok::arrowstar;
3117 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003118 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003119 Kind = tok::arrow;
3120 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003121 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003122 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003123 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003124 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003125 }
3126 break;
3127 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003128 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003129 break;
3130 case '!':
3131 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003132 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003133 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3134 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003135 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003136 }
3137 break;
3138 case '/':
3139 // 6.4.9: Comments
3140 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003141 if (Char == '/') { // Line comment.
3142 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003143 // want to lex this as a comment. There is one problem with this though,
3144 // that in one particular corner case, this can change the behavior of the
3145 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003146 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003147 // "foo". Check to see if the character after the second slash is a '*'.
3148 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003149 // However, we never do this if we are just preprocessing.
3150 bool TreatAsComment = LangOpts.LineComment && !LangOpts.TraditionalCPP;
3151 if (!TreatAsComment)
3152 if (!(PP && PP->isPreprocessedOutput()))
3153 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3154
3155 if (TreatAsComment) {
Nico Weber158a31a2012-11-11 07:02:14 +00003156 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00003157 return; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003158
Chris Lattner58827712009-01-16 22:39:25 +00003159 // It is common for the tokens immediately after a // comment to be
3160 // whitespace (indentation for the next line). Instead of going through
3161 // the big switch, handle it efficiently now.
3162 goto SkipIgnoredUnits;
3163 }
3164 }
Mike Stump11289f42009-09-09 15:08:12 +00003165
Chris Lattner58827712009-01-16 22:39:25 +00003166 if (Char == '*') { // /**/ comment.
Chris Lattner457fc152006-07-29 06:30:25 +00003167 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
Chris Lattner87d02082010-01-18 22:35:47 +00003168 return; // There is a token to return.
Chris Lattnere01e7582008-10-12 04:15:42 +00003169 goto LexNextToken; // GCC isn't tail call eliminating.
Chris Lattner58827712009-01-16 22:39:25 +00003170 }
Mike Stump11289f42009-09-09 15:08:12 +00003171
Chris Lattner58827712009-01-16 22:39:25 +00003172 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003173 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003174 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003175 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003176 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003177 }
3178 break;
3179 case '%':
3180 Char = getCharAndSize(CurPtr, SizeTmp);
3181 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003182 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003183 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003184 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003185 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003186 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003187 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003188 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003189 Char = getCharAndSize(CurPtr, SizeTmp);
3190 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003191 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003192 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3193 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003194 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003195 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003196 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003197 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003198 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003199 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003200 // We parsed a # character. If this occurs at the start of the line,
3201 // it's actually the start of a preprocessing directive. Callback to
3202 // the preprocessor to handle it.
3203 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003204 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3205 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003206
Chris Lattner2534324a2009-03-18 20:58:27 +00003207 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003208 }
3209 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003210 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003211 }
3212 break;
3213 case '<':
3214 Char = getCharAndSize(CurPtr, SizeTmp);
3215 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003216 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003217 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003218 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3219 if (After == '=') {
3220 Kind = tok::lesslessequal;
3221 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3222 SizeTmp2, Result);
3223 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3224 // If this is actually a '<<<<<<<' version control conflict marker,
3225 // recognize it as such and recover nicely.
3226 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003227 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3228 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3229 // ignore it.
3230 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003231 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003232 Kind = tok::lesslessless;
3233 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3234 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003235 } else {
3236 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3237 Kind = tok::lessless;
3238 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003239 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003240 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003241 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003242 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003243 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003244 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3245 // C++0x [lex.pptoken]p3:
3246 // Otherwise, if the next three characters are <:: and the subsequent
3247 // character is neither : nor >, the < is treated as a preprocessor
3248 // token by itself and not as the first character of the alternative
3249 // token <:.
3250 unsigned SizeTmp3;
3251 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3252 if (After != ':' && After != '>') {
3253 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003254 if (!isLexingRawMode())
3255 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003256 break;
3257 }
3258 }
3259
Chris Lattner22eb9722006-06-18 05:43:12 +00003260 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003261 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003262 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003263 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003264 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003265 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003266 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003267 }
3268 break;
3269 case '>':
3270 Char = getCharAndSize(CurPtr, SizeTmp);
3271 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003272 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003273 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003274 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003275 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3276 if (After == '=') {
3277 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3278 SizeTmp2, Result);
3279 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003280 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3281 // If this is actually a '>>>>' conflict marker, recognize it as such
3282 // and recover nicely.
3283 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003284 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3285 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3286 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003287 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003288 Kind = tok::greatergreatergreater;
3289 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3290 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003291 } else {
3292 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3293 Kind = tok::greatergreater;
3294 }
3295
Chris Lattner22eb9722006-06-18 05:43:12 +00003296 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003297 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 }
3299 break;
3300 case '^':
3301 Char = getCharAndSize(CurPtr, SizeTmp);
3302 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003303 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003304 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003305 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003306 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003307 }
3308 break;
3309 case '|':
3310 Char = getCharAndSize(CurPtr, SizeTmp);
3311 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003312 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003313 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3314 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003315 // If this is '|||||||' and we're in a conflict marker, ignore it.
3316 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3317 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003318 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003319 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3320 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003321 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003322 }
3323 break;
3324 case ':':
3325 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003326 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003327 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003328 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003329 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003330 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003331 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003332 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003333 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003334 }
3335 break;
3336 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003337 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003338 break;
3339 case '=':
3340 Char = getCharAndSize(CurPtr, SizeTmp);
3341 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003342 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003343 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3344 goto LexNextToken;
3345
Chris Lattnerb11c3232008-10-12 04:51:35 +00003346 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003347 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003348 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003349 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003350 }
3351 break;
3352 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003353 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003354 break;
3355 case '#':
3356 Char = getCharAndSize(CurPtr, SizeTmp);
3357 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003358 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003359 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003360 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003361 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003362 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003363 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003364 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003365 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003366 // We parsed a # character. If this occurs at the start of the line,
3367 // it's actually the start of a preprocessing directive. Callback to
3368 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00003369 // FIXME: -fpreprocessed mode??
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003370 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3371 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003372
Chris Lattner2534324a2009-03-18 20:58:27 +00003373 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003374 }
3375 break;
3376
Chris Lattner2b15cf72008-01-03 17:58:54 +00003377 case '@':
3378 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003379 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003380 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003381 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003382 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003383 break;
Mike Stump11289f42009-09-09 15:08:12 +00003384
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003385 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003386 case '\\':
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003387 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3388 return LexUnicode(Result, CodePoint, CurPtr);
3389
Chris Lattnerb11c3232008-10-12 04:51:35 +00003390 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003391 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003392
3393 default: {
3394 if (isASCII(Char)) {
3395 Kind = tok::unknown;
3396 break;
3397 }
3398
3399 UTF32 CodePoint;
3400
3401 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3402 // an escaped newline.
3403 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003404 ConversionResult Status =
3405 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3406 (const UTF8 *)BufferEnd,
3407 &CodePoint,
3408 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003409 if (Status == conversionOK)
3410 return LexUnicode(Result, CodePoint, CurPtr);
3411
Jordan Rosecc538342013-01-31 19:48:48 +00003412 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3413 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003414 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003415 Kind = tok::unknown;
3416 break;
3417 }
3418
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003419 // Non-ASCII characters tend to creep into source code unintentionally.
3420 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003421 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003422 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003423
3424 BufferPtr = CurPtr+1;
3425 goto LexNextToken;
3426 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003427 }
Mike Stump11289f42009-09-09 15:08:12 +00003428
Chris Lattner371ac8a2006-07-04 07:11:10 +00003429 // Notify MIOpt that we read a non-whitespace/non-comment token.
3430 MIOpt.ReadToken();
3431
Chris Lattnerd01e2912006-06-18 16:22:51 +00003432 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003433 FormTokenWithChars(Result, CurPtr, Kind);
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003434 return;
3435
3436HandleDirective:
3437 // We parsed a # character and it's the start of a preprocessing directive.
3438
3439 FormTokenWithChars(Result, CurPtr, tok::hash);
3440 PP->HandleDirective(Result);
3441
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003442 if (PP->hadModuleLoaderFatalFailure()) {
3443 // With a fatal failure in the module loader, we abort parsing.
3444 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3445 return;
3446 }
3447
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003448 // As an optimization, if the preprocessor didn't switch lexers, tail
3449 // recurse.
3450 if (PP->isCurrentLexer(this)) {
3451 // Start a new token. If this is a #include or something, the PP may
3452 // want us starting at the beginning of the line again. If so, set
3453 // the StartOfLine flag and clear LeadingSpace.
3454 if (IsAtStartOfLine) {
3455 Result.setFlag(Token::StartOfLine);
3456 Result.clearFlag(Token::LeadingSpace);
3457 IsAtStartOfLine = false;
3458 }
3459 goto LexNextToken; // GCC isn't tail call eliminating.
3460 }
3461 return PP->Lex(Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003462}