blob: c071455da6623173b2d9b4b96946ef58658dad51 [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"
Richard Smith2a988622013-09-24 04:06:10 +000032#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +000034#include "llvm/ADT/STLExtras.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000035#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000037#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chris Lattner739e7392007-04-29 07:12:06 +000039#include "llvm/Support/MemoryBuffer.h"
Jordan Rose58c61e02013-02-09 01:10:25 +000040#include "UnicodeCharSets.h"
Craig Topper54edcca2011-08-11 04:06:15 +000041#include <cstring>
Chris Lattner22eb9722006-06-18 05:43:12 +000042using namespace clang;
43
Chris Lattner4894f482007-10-07 08:47:24 +000044//===----------------------------------------------------------------------===//
45// Token Class Implementation
46//===----------------------------------------------------------------------===//
47
Mike Stump11289f42009-09-09 15:08:12 +000048/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000049bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000050 if (IdentifierInfo *II = getIdentifierInfo())
51 return II->getObjCKeywordID() == objcKey;
52 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000053}
54
55/// getObjCKeywordID - Return the ObjC keyword kind.
56tok::ObjCKeywordKind Token::getObjCKeywordID() const {
57 IdentifierInfo *specId = getIdentifierInfo();
58 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
59}
60
Chris Lattner67671ed2007-12-13 01:59:49 +000061
Chris Lattner4894f482007-10-07 08:47:24 +000062//===----------------------------------------------------------------------===//
63// Lexer Class Implementation
64//===----------------------------------------------------------------------===//
65
David Blaikie68e081d2011-12-20 02:48:34 +000066void Lexer::anchor() { }
67
Mike Stump11289f42009-09-09 15:08:12 +000068void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000070 BufferStart = BufStart;
71 BufferPtr = BufPtr;
72 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattnerf76b9202009-01-17 06:55:17 +000074 assert(BufEnd[0] == 0 &&
75 "We assume that the input buffer has a null character at the end"
76 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000077
Eric Christopher7f36a792011-04-09 00:01:04 +000078 // Check whether we have a BOM in the beginning of the buffer. If yes - act
79 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
80 // skip the UTF-8 BOM if it's present.
81 if (BufferStart == BufferPtr) {
82 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000083 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000084 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000085 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
86 .Default(0);
87
88 // Skip the BOM.
89 BufferPtr += BOMLength;
90 }
91
Chris Lattnerf76b9202009-01-17 06:55:17 +000092 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000093 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000094
Chris Lattnerf76b9202009-01-17 06:55:17 +000095 // Start of the file is a start of line.
96 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000097 IsAtPhysicalStartOfLine = true;
98
99 HasLeadingSpace = false;
100 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Chris Lattnerf76b9202009-01-17 06:55:17 +0000102 // We are not after parsing a #.
103 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000104
Chris Lattnerf76b9202009-01-17 06:55:17 +0000105 // We are not after parsing #include.
106 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000107
Chris Lattnerf76b9202009-01-17 06:55:17 +0000108 // We are not in raw mode. Raw mode disables diagnostics and interpretation
109 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
110 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
111 // or otherwise skipping over tokens.
112 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattnerf76b9202009-01-17 06:55:17 +0000114 // Default to not keeping comments.
115 ExtendedTokenMode = 0;
116}
117
Chris Lattner5965a282009-01-17 07:56:59 +0000118/// Lexer constructor - Create a new lexer object for the specified buffer
119/// with the specified preprocessor managing the lexing process. This lexer
120/// assumes that the associated file buffer and Preprocessor objects will
121/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000122Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000123 : PreprocessorLexer(&PP, FID),
124 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000125 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000126
Chris Lattner5965a282009-01-17 07:56:59 +0000127 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
128 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000129
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000130 resetExtendedTokenMode();
131}
132
133void Lexer::resetExtendedTokenMode() {
134 assert(PP && "Cannot reset token mode without a preprocessor");
135 if (LangOpts.TraditionalCPP)
136 SetKeepWhitespaceMode(true);
137 else
138 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000139}
Chris Lattner4894f482007-10-07 08:47:24 +0000140
Chris Lattner02b436a2007-10-17 20:41:00 +0000141/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000142/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000143/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000144Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000145 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000146 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000147
Chris Lattnerf76b9202009-01-17 06:55:17 +0000148 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000149
Chris Lattner02b436a2007-10-17 20:41:00 +0000150 // We *are* in raw mode.
151 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000152}
153
Chris Lattner08354fe2009-01-17 07:35:14 +0000154/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000155/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000156/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000157Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000158 const SourceManager &SM, const LangOptions &langOpts)
159 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner08354fe2009-01-17 07:35:14 +0000160
Mike Stump11289f42009-09-09 15:08:12 +0000161 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner08354fe2009-01-17 07:35:14 +0000162 FromFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000163
Chris Lattner08354fe2009-01-17 07:35:14 +0000164 // We *are* in raw mode.
165 LexingRawMode = true;
166}
167
Chris Lattner757169b2009-01-17 08:27:52 +0000168/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
169/// _Pragma expansion. This has a variety of magic semantics that this method
170/// sets up. It returns a new'd Lexer that must be delete'd when done.
171///
172/// On entrance to this routine, TokStartLoc is a macro location which has a
173/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000174/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000175/// "expanded from".
176///
177/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
178/// normal lexer that remaps tokens as they fly by. This would require making
179/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
180/// interface that could handle this stuff. This would pull GetMappedTokenLoc
181/// out of the critical path of the lexer!
182///
Mike Stump11289f42009-09-09 15:08:12 +0000183Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000184 SourceLocation ExpansionLocStart,
185 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000186 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000187 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000188
189 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000190 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000191 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
192 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner757169b2009-01-17 08:27:52 +0000194 // Now that the lexer is created, change the start/end locations so that we
195 // just lex the subsection of the file that we want. This is lexing from a
196 // scratch buffer.
197 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner757169b2009-01-17 08:27:52 +0000199 L->BufferPtr = StrData;
200 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000201 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000202
203 // Set the SourceLocation with the remapping information. This ensures that
204 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000205 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
206 ExpansionLocStart,
207 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000208
Chris Lattner757169b2009-01-17 08:27:52 +0000209 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000210 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000211 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner757169b2009-01-17 08:27:52 +0000213 // This lexer really is for _Pragma.
214 L->Is_PragmaLexer = true;
215 return L;
216}
217
Chris Lattner02b436a2007-10-17 20:41:00 +0000218
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000219/// Stringify - Convert the specified string into a C string, with surrounding
220/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000221std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000222 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000223 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000224 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000225 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000226 Result.insert(Result.begin()+i, '\\');
227 ++i; ++e;
228 }
229 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000230 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000231}
232
Chris Lattner4c4a2452007-07-24 06:57:14 +0000233/// Stringify - Convert the specified string into a C string by escaping '\'
234/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000235void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000236 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
237 if (Str[i] == '\\' || Str[i] == '"') {
238 Str.insert(Str.begin()+i, '\\');
239 ++i; ++e;
240 }
241 }
242}
243
Chris Lattner39720112010-11-17 07:26:20 +0000244//===----------------------------------------------------------------------===//
245// Token Spelling
246//===----------------------------------------------------------------------===//
247
Richard Smith9a67f472012-11-28 07:29:00 +0000248/// \brief Slow case of getSpelling. Extract the characters comprising the
249/// spelling of this token from the provided input buffer.
250static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
251 const LangOptions &LangOpts, char *Spelling) {
252 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
253
254 size_t Length = 0;
255 const char *BufEnd = BufPtr + Tok.getLength();
256
257 if (Tok.is(tok::string_literal)) {
258 // Munch the encoding-prefix and opening double-quote.
259 while (BufPtr < BufEnd) {
260 unsigned Size;
261 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
262 BufPtr += Size;
263
264 if (Spelling[Length - 1] == '"')
265 break;
266 }
267
268 // Raw string literals need special handling; trigraph expansion and line
269 // splicing do not occur within their d-char-sequence nor within their
270 // r-char-sequence.
271 if (Length >= 2 &&
272 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
273 // Search backwards from the end of the token to find the matching closing
274 // quote.
275 const char *RawEnd = BufEnd;
276 do --RawEnd; while (*RawEnd != '"');
277 size_t RawLength = RawEnd - BufPtr + 1;
278
279 // Everything between the quotes is included verbatim in the spelling.
280 memcpy(Spelling + Length, BufPtr, RawLength);
281 Length += RawLength;
282 BufPtr += RawLength;
283
284 // The rest of the token is lexed normally.
285 }
286 }
287
288 while (BufPtr < BufEnd) {
289 unsigned Size;
290 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
291 BufPtr += Size;
292 }
293
294 assert(Length < Tok.getLength() &&
295 "NeedsCleaning flag set on token that didn't need cleaning!");
296 return Length;
297}
298
Chris Lattner39720112010-11-17 07:26:20 +0000299/// getSpelling() - Return the 'spelling' of this token. The spelling of a
300/// token are the characters used to represent the token in the source file
301/// after trigraph expansion and escaped-newline folding. In particular, this
302/// wants to get the true, uncanonicalized, spelling of things like digraphs
303/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000304StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000305 SmallVectorImpl<char> &buffer,
306 const SourceManager &SM,
307 const LangOptions &options,
308 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000309 // Break down the source location.
310 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
311
312 // Try to the load the file buffer.
313 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000314 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000315 if (invalidTemp) {
316 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000317 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000318 }
319
320 const char *tokenBegin = file.data() + locInfo.second;
321
322 // Lex from the start of the given location.
323 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
324 file.begin(), tokenBegin, file.end());
325 Token token;
326 lexer.LexFromRawLexer(token);
327
328 unsigned length = token.getLength();
329
330 // Common case: no need for cleaning.
331 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000332 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000333
Richard Smith9a67f472012-11-28 07:29:00 +0000334 // Hard case, we need to relex the characters into the string.
335 buffer.resize(length);
336 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000337 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000338}
339
340/// getSpelling() - Return the 'spelling' of this token. The spelling of a
341/// token are the characters used to represent the token in the source file
342/// after trigraph expansion and escaped-newline folding. In particular, this
343/// wants to get the true, uncanonicalized, spelling of things like digraphs
344/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000345std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000346 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000347 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000348
Chris Lattner39720112010-11-17 07:26:20 +0000349 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000350 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000351 &CharDataInvalid);
352 if (Invalid)
353 *Invalid = CharDataInvalid;
354 if (CharDataInvalid)
355 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000356
357 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000358 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000359 return std::string(TokStart, TokStart + Tok.getLength());
360
Chris Lattner39720112010-11-17 07:26:20 +0000361 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000362 Result.resize(Tok.getLength());
363 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000364 return Result;
365}
366
367/// getSpelling - This method is used to get the spelling of a token into a
368/// preallocated buffer, instead of as an std::string. The caller is required
369/// to allocate enough space for the token, which is guaranteed to be at least
370/// Tok.getLength() bytes long. The actual length of the token is returned.
371///
372/// Note that this method may do two possible things: it may either fill in
373/// the buffer specified with characters, or it may *change the input pointer*
374/// to point to a constant buffer with the data already in it (avoiding a
375/// copy). The caller is not allowed to modify the returned buffer pointer
376/// if an internal buffer is returned.
377unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
378 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000379 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000380 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000381
382 const char *TokStart = 0;
383 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
384 if (Tok.is(tok::raw_identifier))
385 TokStart = Tok.getRawIdentifierData();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000386 else if (!Tok.hasUCN()) {
387 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
388 // Just return the string from the identifier table, which is very quick.
389 Buffer = II->getNameStart();
390 return II->getLength();
391 }
Chris Lattner39720112010-11-17 07:26:20 +0000392 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000393
394 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000395 if (Tok.isLiteral())
396 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000397
Chris Lattner39720112010-11-17 07:26:20 +0000398 if (TokStart == 0) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000399 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000400 bool CharDataInvalid = false;
401 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
402 if (Invalid)
403 *Invalid = CharDataInvalid;
404 if (CharDataInvalid) {
405 Buffer = "";
406 return 0;
407 }
408 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000409
Chris Lattner39720112010-11-17 07:26:20 +0000410 // If this token contains nothing interesting, return it directly.
411 if (!Tok.needsCleaning()) {
412 Buffer = TokStart;
413 return Tok.getLength();
414 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000415
Chris Lattner39720112010-11-17 07:26:20 +0000416 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000417 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000418}
419
420
Chris Lattner8e129c22007-10-17 21:18:47 +0000421/// MeasureTokenLength - Relex the token at the specified location and return
422/// its length in bytes in the input file. If the token needs cleaning (e.g.
423/// includes a trigraph or an escaped newline) then this count includes bytes
424/// that are part of that.
425unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000426 const SourceManager &SM,
427 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000428 Token TheTok;
429 if (getRawToken(Loc, TheTok, SM, LangOpts))
430 return 0;
431 return TheTok.getLength();
432}
433
434/// \brief Relex the token at the specified location.
435/// \returns true if there was a failure, false on success.
436bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
437 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000438 const LangOptions &LangOpts,
439 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000440 // TODO: this could be special cased for common tokens like identifiers, ')',
441 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000442 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000443 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
444 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000445
446 // If this comes from a macro expansion, we really do want the macro name, not
447 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000448 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000449 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000450 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000451 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000452 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000453 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000454
455 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000456
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000457 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000458 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000459
Chris Lattner8e129c22007-10-17 21:18:47 +0000460 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000461 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
462 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000463 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000464 TheLexer.LexFromRawLexer(Result);
465 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000466}
467
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000468static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
469 const SourceManager &SM,
470 const LangOptions &LangOpts) {
471 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000472 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000473 if (LocInfo.first.isInvalid())
474 return Loc;
475
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000476 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000477 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000478 if (Invalid)
479 return Loc;
480
481 // Back up from the current location until we hit the beginning of a line
482 // (or the buffer). We'll relex from that point.
483 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000484 if (LocInfo.second >= Buffer.size())
485 return Loc;
486
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000487 const char *StrData = BufStart+LocInfo.second;
488 if (StrData[0] == '\n' || StrData[0] == '\r')
489 return Loc;
490
491 const char *LexStart = StrData;
492 while (LexStart != BufStart) {
493 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
494 ++LexStart;
495 break;
496 }
497
498 --LexStart;
499 }
500
501 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000502 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000503 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
504 TheLexer.SetCommentRetentionState(true);
505
506 // Lex tokens until we find the token that contains the source location.
507 Token TheTok;
508 do {
509 TheLexer.LexFromRawLexer(TheTok);
510
511 if (TheLexer.getBufferLocation() > StrData) {
512 // Lexing this token has taken the lexer past the source location we're
513 // looking for. If the current token encompasses our source location,
514 // return the beginning of that token.
515 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
516 return TheTok.getLocation();
517
518 // We ended up skipping over the source location entirely, which means
519 // that it points into whitespace. We're done here.
520 break;
521 }
522 } while (TheTok.getKind() != tok::eof);
523
524 // We've passed our source location; just return the original source location.
525 return Loc;
526}
527
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000528SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
529 const SourceManager &SM,
530 const LangOptions &LangOpts) {
531 if (Loc.isFileID())
532 return getBeginningOfFileToken(Loc, SM, LangOpts);
533
534 if (!SM.isMacroArgExpansion(Loc))
535 return Loc;
536
537 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
538 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
539 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000540 std::pair<FileID, unsigned> BeginFileLocInfo
541 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000542 assert(FileLocInfo.first == BeginFileLocInfo.first &&
543 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000544 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000545}
546
Douglas Gregoraf82e352010-07-20 20:18:03 +0000547namespace {
548 enum PreambleDirectiveKind {
549 PDK_Skipped,
550 PDK_StartIf,
551 PDK_EndIf,
552 PDK_Unknown
553 };
554}
555
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000556std::pair<unsigned, bool>
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000557Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000558 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000559 // Create a lexer starting at the beginning of the file. Note that we use a
560 // "fake" file source location at offset 1 so that the lexer will track our
561 // position within the file.
562 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000563 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
564 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregoraf82e352010-07-20 20:18:03 +0000565 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000566 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000567
568 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
569 SourceLocation StartLoc = TheLexer.getSourceLocation();
570
Douglas Gregoraf82e352010-07-20 20:18:03 +0000571 bool InPreprocessorDirective = false;
572 Token TheTok;
573 Token IfStartTok;
574 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000575 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000576
577 unsigned MaxLineOffset = 0;
578 if (MaxLines) {
579 const char *CurPtr = Buffer->getBufferStart();
580 unsigned CurLine = 0;
581 while (CurPtr != Buffer->getBufferEnd()) {
582 char ch = *CurPtr++;
583 if (ch == '\n') {
584 ++CurLine;
585 if (CurLine == MaxLines)
586 break;
587 }
588 }
589 if (CurPtr != Buffer->getBufferEnd())
590 MaxLineOffset = CurPtr - Buffer->getBufferStart();
591 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000592
Douglas Gregoraf82e352010-07-20 20:18:03 +0000593 do {
594 TheLexer.LexFromRawLexer(TheTok);
595
596 if (InPreprocessorDirective) {
597 // If we've hit the end of the file, we're done.
598 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000599 break;
600 }
601
602 // If we haven't hit the end of the preprocessor directive, skip this
603 // token.
604 if (!TheTok.isAtStartOfLine())
605 continue;
606
607 // We've passed the end of the preprocessor directive, and will look
608 // at this token again below.
609 InPreprocessorDirective = false;
610 }
611
Douglas Gregor028d3e42010-08-09 20:45:32 +0000612 // Keep track of the # of lines in the preamble.
613 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000614 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000615
616 // If we were asked to limit the number of lines in the preamble,
617 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000618 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000619 break;
620 }
621
Douglas Gregoraf82e352010-07-20 20:18:03 +0000622 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000623 if (TheTok.getKind() == tok::comment) {
624 if (ActiveCommentLoc.isInvalid())
625 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000626 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000627 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000628
629 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
630 // This is the start of a preprocessor directive.
631 Token HashTok = TheTok;
632 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000633 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000634
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000635 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000636 // we don't have an identifier table available. Instead, just look at
637 // the raw identifier to recognize and categorize preprocessor directives.
638 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000639 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000640 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000641 TheTok.getLength());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000642 PreambleDirectiveKind PDK
643 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
644 .Case("include", PDK_Skipped)
645 .Case("__include_macros", PDK_Skipped)
646 .Case("define", PDK_Skipped)
647 .Case("undef", PDK_Skipped)
648 .Case("line", PDK_Skipped)
649 .Case("error", PDK_Skipped)
650 .Case("pragma", PDK_Skipped)
651 .Case("import", PDK_Skipped)
652 .Case("include_next", PDK_Skipped)
653 .Case("warning", PDK_Skipped)
654 .Case("ident", PDK_Skipped)
655 .Case("sccs", PDK_Skipped)
656 .Case("assert", PDK_Skipped)
657 .Case("unassert", PDK_Skipped)
658 .Case("if", PDK_StartIf)
659 .Case("ifdef", PDK_StartIf)
660 .Case("ifndef", PDK_StartIf)
661 .Case("elif", PDK_Skipped)
662 .Case("else", PDK_Skipped)
663 .Case("endif", PDK_EndIf)
664 .Default(PDK_Unknown);
665
666 switch (PDK) {
667 case PDK_Skipped:
668 continue;
669
670 case PDK_StartIf:
671 if (IfCount == 0)
672 IfStartTok = HashTok;
673
674 ++IfCount;
675 continue;
676
677 case PDK_EndIf:
678 // Mismatched #endif. The preamble ends here.
679 if (IfCount == 0)
680 break;
681
682 --IfCount;
683 continue;
684
685 case PDK_Unknown:
686 // We don't know what this directive is; stop at the '#'.
687 break;
688 }
689 }
690
691 // We only end up here if we didn't recognize the preprocessor
692 // directive or it was one that can't occur in the preamble at this
693 // point. Roll back the current token to the location of the '#'.
694 InPreprocessorDirective = false;
695 TheTok = HashTok;
696 }
697
Douglas Gregor028d3e42010-08-09 20:45:32 +0000698 // We hit a token that we don't recognize as being in the
699 // "preprocessing only" part of the file, so we're no longer in
700 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000701 break;
702 } while (true);
703
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000704 SourceLocation End;
705 if (IfCount)
706 End = IfStartTok.getLocation();
707 else if (ActiveCommentLoc.isValid())
708 End = ActiveCommentLoc; // don't truncate a decl comment.
709 else
710 End = TheTok.getLocation();
711
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000712 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
713 IfCount? IfStartTok.isAtStartOfLine()
714 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000715}
716
Chris Lattner2a6ee912010-11-17 07:05:50 +0000717
718/// AdvanceToTokenCharacter - Given a location that specifies the start of a
719/// token, return a new location that specifies a character within the token.
720SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
721 unsigned CharNo,
722 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000723 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000724 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000725 // character is. This needs to take into consideration newlines and
726 // trigraphs.
727 bool Invalid = false;
728 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
729
730 // If they request the first char of the token, we're trivially done.
731 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
732 return TokStart;
733
734 unsigned PhysOffset = 0;
735
736 // The usual case is that tokens don't contain anything interesting. Skip
737 // over the uninteresting characters. If a token only consists of simple
738 // chars, this method is extremely fast.
739 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
740 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000741 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000742 ++TokPtr, --CharNo, ++PhysOffset;
743 }
744
745 // If we have a character that may be a trigraph or escaped newline, use a
746 // lexer to parse it correctly.
747 for (; CharNo; --CharNo) {
748 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000749 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000750 TokPtr += Size;
751 PhysOffset += Size;
752 }
753
754 // Final detail: if we end up on an escaped newline, we want to return the
755 // location of the actual byte of the token. For example foo\<newline>bar
756 // advanced by 3 should return the location of b, not of \\. One compounding
757 // detail of this is that the escape may be made by a trigraph.
758 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
759 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
760
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000761 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000762}
763
764/// \brief Computes the source location just past the end of the
765/// token at this source location.
766///
767/// This routine can be used to produce a source location that
768/// points just past the end of the token referenced by \p Loc, and
769/// is generally used when a diagnostic needs to point just after a
770/// token where it expected something different that it received. If
771/// the returned source location would not be meaningful (e.g., if
772/// it points into a macro), this routine returns an invalid
773/// source location.
774///
775/// \param Offset an offset from the end of the token, where the source
776/// location should refer to. The default offset (0) produces a source
777/// location pointing just past the end of the token; an offset of 1 produces
778/// a source location pointing to the last character in the token, etc.
779SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
780 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000782 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000783 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000784
785 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000786 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000787 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000788 }
789
David Blaikiebbafb8a2012-03-11 07:00:24 +0000790 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000791 if (Len > Offset)
792 Len = Len - Offset;
793 else
794 return Loc;
795
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000796 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000797}
798
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000800/// token of the macro expansion.
801bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000802 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000803 const LangOptions &LangOpts,
804 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000805 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
806
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000807 SourceLocation expansionLoc;
808 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
809 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000810
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000811 if (expansionLoc.isFileID()) {
812 // No other macro expansions, this is the first.
813 if (MacroBegin)
814 *MacroBegin = expansionLoc;
815 return true;
816 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000817
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000818 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000819}
820
821/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000822/// token of the macro expansion.
823bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000824 const SourceManager &SM,
825 const LangOptions &LangOpts,
826 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000827 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
828
829 SourceLocation spellLoc = SM.getSpellingLoc(loc);
830 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
831 if (tokLen == 0)
832 return false;
833
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000834 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
835 SourceLocation expansionLoc;
836 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
837 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000838
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000839 if (expansionLoc.isFileID()) {
840 // No other macro expansions.
841 if (MacroEnd)
842 *MacroEnd = expansionLoc;
843 return true;
844 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000845
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000846 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000847}
848
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000849static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000850 const SourceManager &SM,
851 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000852 SourceLocation Begin = Range.getBegin();
853 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000854 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000855 if (Range.isTokenRange()) {
856 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
857 if (End.isInvalid())
858 return CharSourceRange();
859 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000860
861 // Break down the source locations.
862 FileID FID;
863 unsigned BeginOffs;
864 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
865 if (FID.isInvalid())
866 return CharSourceRange();
867
868 unsigned EndOffs;
869 if (!SM.isInFileID(End, FID, &EndOffs) ||
870 BeginOffs > EndOffs)
871 return CharSourceRange();
872
873 return CharSourceRange::getCharRange(Begin, End);
874}
875
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000876CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000877 const SourceManager &SM,
878 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000879 SourceLocation Begin = Range.getBegin();
880 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000882 return CharSourceRange();
883
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000884 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000885 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000886
887 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000888 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
889 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000890 Range.setBegin(Begin);
891 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000892 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000893
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000894 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000895 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
896 &End)) ||
897 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
898 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000899 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000900 Range.setEnd(End);
901 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000902 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000903
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000904 assert(Begin.isMacroID() && End.isMacroID());
905 SourceLocation MacroBegin, MacroEnd;
906 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000907 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
908 &MacroEnd)) ||
909 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
910 &MacroEnd)))) {
911 Range.setBegin(MacroBegin);
912 Range.setEnd(MacroEnd);
913 return makeRangeFromFileLocs(Range, SM, LangOpts);
914 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000915
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000916 bool Invalid = false;
917 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
918 &Invalid);
919 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000920 return CharSourceRange();
921
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000922 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
923 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
924 &Invalid);
925 if (Invalid)
926 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000927
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000928 if (EndEntry.getExpansion().isMacroArgExpansion() &&
929 BeginEntry.getExpansion().getExpansionLocStart() ==
930 EndEntry.getExpansion().getExpansionLocStart()) {
931 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
932 Range.setEnd(SM.getImmediateSpellingLoc(End));
933 return makeFileCharRange(Range, SM, LangOpts);
934 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000935 }
936
937 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000938}
939
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000940StringRef Lexer::getSourceText(CharSourceRange Range,
941 const SourceManager &SM,
942 const LangOptions &LangOpts,
943 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000944 Range = makeFileCharRange(Range, SM, LangOpts);
945 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000946 if (Invalid) *Invalid = true;
947 return StringRef();
948 }
949
950 // Break down the source location.
951 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
952 if (beginInfo.first.isInvalid()) {
953 if (Invalid) *Invalid = true;
954 return StringRef();
955 }
956
957 unsigned EndOffs;
958 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
959 beginInfo.second > EndOffs) {
960 if (Invalid) *Invalid = true;
961 return StringRef();
962 }
963
964 // Try to the load the file buffer.
965 bool invalidTemp = false;
966 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
967 if (invalidTemp) {
968 if (Invalid) *Invalid = true;
969 return StringRef();
970 }
971
972 if (Invalid) *Invalid = false;
973 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
974}
975
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000976StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
977 const SourceManager &SM,
978 const LangOptions &LangOpts) {
979 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000980
981 // Find the location of the immediate macro expansion.
982 while (1) {
983 FileID FID = SM.getFileID(Loc);
984 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
985 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
986 Loc = Expansion.getExpansionLocStart();
987 if (!Expansion.isMacroArgExpansion())
988 break;
989
990 // For macro arguments we need to check that the argument did not come
991 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
992
993 // Loc points to the argument id of the macro definition, move to the
994 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000995 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000996 SourceLocation SpellLoc = Expansion.getSpellingLoc();
997 if (SpellLoc.isFileID())
998 break; // No inner macro.
999
1000 // If spelling location resides in the same FileID as macro expansion
1001 // location, it means there is no inner macro.
1002 FileID MacroFID = SM.getFileID(Loc);
1003 if (SM.isInFileID(SpellLoc, MacroFID))
1004 break;
1005
1006 // Argument came from inner macro.
1007 Loc = SpellLoc;
1008 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001009
1010 // Find the spelling location of the start of the non-argument expansion
1011 // range. This is where the macro name was spelled in order to begin
1012 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001013 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001014
1015 // Dig out the buffer where the macro name was spelled and the extents of the
1016 // name so that we can render it into the expansion note.
1017 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1018 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1019 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1020 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1021}
1022
Jordan Rose288c4212012-06-07 01:10:31 +00001023bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001024 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001025}
1026
Chris Lattnerd01e2912006-06-18 16:22:51 +00001027
Chris Lattner22eb9722006-06-18 05:43:12 +00001028//===----------------------------------------------------------------------===//
1029// Diagnostics forwarding code.
1030//===----------------------------------------------------------------------===//
1031
Chris Lattner619c1742007-07-22 18:38:25 +00001032/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001033/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001034/// This is currently only used for _Pragma implementation, so it is the slow
1035/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001036static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1037 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001038static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1039 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001040 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001041 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattner619c1742007-07-22 18:38:25 +00001043 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001044 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001045 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001046 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001048 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001049 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001050 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001051 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner9dc9c202009-02-15 20:52:18 +00001053 // Figure out the expansion loc range, which is the range covered by the
1054 // original _Pragma(...) sequence.
1055 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001056 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chandler Carruth115b0772011-07-26 03:03:05 +00001058 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001059}
1060
Chris Lattner22eb9722006-06-18 05:43:12 +00001061/// getSourceLocation - Return a source location identifier for the specified
1062/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001063SourceLocation Lexer::getSourceLocation(const char *Loc,
1064 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001065 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001066 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001067
1068 // In the normal case, we're just lexing from a simple file buffer, return
1069 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001070 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001071 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001072 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattnerd32480d2009-01-17 06:22:33 +00001074 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1075 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001076 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001077 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001078}
1079
Chris Lattner22eb9722006-06-18 05:43:12 +00001080/// Diag - Forwarding function for diagnostics. This translate a source
1081/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001082DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001083 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001084}
1085
1086//===----------------------------------------------------------------------===//
1087// Trigraph and Escaped Newline Handling Code.
1088//===----------------------------------------------------------------------===//
1089
1090/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1091/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1092static char GetTrigraphCharForLetter(char Letter) {
1093 switch (Letter) {
1094 default: return 0;
1095 case '=': return '#';
1096 case ')': return ']';
1097 case '(': return '[';
1098 case '!': return '|';
1099 case '\'': return '^';
1100 case '>': return '}';
1101 case '/': return '\\';
1102 case '<': return '{';
1103 case '-': return '~';
1104 }
1105}
1106
1107/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1108/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1109/// return the result character. Finally, emit a warning about trigraph use
1110/// whether trigraphs are enabled or not.
1111static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1112 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001113 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001114
David Blaikiebbafb8a2012-03-11 07:00:24 +00001115 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001116 if (!L->isLexingRawMode())
1117 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001118 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
Chris Lattner6d27a162008-11-22 02:02:22 +00001121 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001122 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001123 return Res;
1124}
1125
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001126/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1127/// 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 +00001128/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001129unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1130 unsigned Size = 0;
1131 while (isWhitespace(Ptr[Size])) {
1132 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001134 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1135 continue;
1136
1137 // If this is a \r\n or \n\r, skip the other half.
1138 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1139 Ptr[Size-1] != Ptr[Size])
1140 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001141
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001142 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001143 }
1144
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001145 // Not an escaped newline, must be a \t or something else.
1146 return 0;
1147}
1148
Chris Lattner38b2cde2009-04-18 22:27:02 +00001149/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1150/// them), skip over them and return the first non-escaped-newline found,
1151/// otherwise return P.
1152const char *Lexer::SkipEscapedNewLines(const char *P) {
1153 while (1) {
1154 const char *AfterEscape;
1155 if (*P == '\\') {
1156 AfterEscape = P+1;
1157 } else if (*P == '?') {
1158 // If not a trigraph for escape, bail out.
1159 if (P[1] != '?' || P[2] != '/')
1160 return P;
1161 AfterEscape = P+3;
1162 } else {
1163 return P;
1164 }
Mike Stump11289f42009-09-09 15:08:12 +00001165
Chris Lattner38b2cde2009-04-18 22:27:02 +00001166 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1167 if (NewLineSize == 0) return P;
1168 P = AfterEscape+NewLineSize;
1169 }
1170}
1171
Anna Zaks59a3c802011-07-27 21:43:43 +00001172/// \brief Checks that the given token is the first token that occurs after the
1173/// given location (this excludes comments and whitespace). Returns the location
1174/// immediately after the specified token. If the token is not found or the
1175/// location is inside a macro, the returned source location will be invalid.
1176SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1177 tok::TokenKind TKind,
1178 const SourceManager &SM,
1179 const LangOptions &LangOpts,
1180 bool SkipTrailingWhitespaceAndNewLine) {
1181 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001182 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001183 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001184 }
1185 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1186
1187 // Break down the source location.
1188 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1189
1190 // Try to load the file buffer.
1191 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001192 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001193 if (InvalidTemp)
1194 return SourceLocation();
1195
1196 const char *TokenBegin = File.data() + LocInfo.second;
1197
1198 // Lex from the start of the given location.
1199 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1200 TokenBegin, File.end());
1201 // Find the token.
1202 Token Tok;
1203 lexer.LexFromRawLexer(Tok);
1204 if (Tok.isNot(TKind))
1205 return SourceLocation();
1206 SourceLocation TokenLoc = Tok.getLocation();
1207
1208 // Calculate how much whitespace needs to be skipped if any.
1209 unsigned NumWhitespaceChars = 0;
1210 if (SkipTrailingWhitespaceAndNewLine) {
1211 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1212 Tok.getLength();
1213 unsigned char C = *TokenEnd;
1214 while (isHorizontalWhitespace(C)) {
1215 C = *(++TokenEnd);
1216 NumWhitespaceChars++;
1217 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001218
1219 // Skip \r, \n, \r\n, or \n\r
1220 if (C == '\n' || C == '\r') {
1221 char PrevC = C;
1222 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001223 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001224 if ((C == '\n' || C == '\r') && C != PrevC)
1225 NumWhitespaceChars++;
1226 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001227 }
1228
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001229 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001230}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001231
Chris Lattner22eb9722006-06-18 05:43:12 +00001232/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1233/// get its size, and return it. This is tricky in several cases:
1234/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1235/// then either return the trigraph (skipping 3 chars) or the '?',
1236/// depending on whether trigraphs are enabled or not.
1237/// 2. If this is an escaped newline (potentially with whitespace between
1238/// the backslash and newline), implicitly skip the newline and return
1239/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001240///
1241/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1242/// know that we can accumulate into Size, and that we have already incremented
1243/// Ptr by Size bytes.
1244///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001245/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1246/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001247///
1248char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001249 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001250 // If we have a slash, look for an escaped newline.
1251 if (Ptr[0] == '\\') {
1252 ++Size;
1253 ++Ptr;
1254Slash:
1255 // Common case, backslash-char where the char is not whitespace.
1256 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattnerc1835952009-06-23 05:15:06 +00001258 // See if we have optional whitespace characters between the slash and
1259 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001260 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1261 // Remember that this token needs to be cleaned.
1262 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001263
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001264 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001265 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001266 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001267
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001268 // Found backslash<whitespace><newline>. Parse the char after it.
1269 Size += EscapedNewLineSize;
1270 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001271
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001272 // If the char that we finally got was a \n, then we must have had
1273 // something like \<newline><newline>. We don't want to consume the
1274 // second newline.
1275 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1276 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001277
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001278 // Use slow version to accumulate a correct size field.
1279 return getCharAndSizeSlow(Ptr, Size, Tok);
1280 }
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner22eb9722006-06-18 05:43:12 +00001282 // Otherwise, this is not an escaped newline, just return the slash.
1283 return '\\';
1284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattner22eb9722006-06-18 05:43:12 +00001286 // If this is a trigraph, process it.
1287 if (Ptr[0] == '?' && Ptr[1] == '?') {
1288 // If this is actually a legal trigraph (not something like "??x"), emit
1289 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1290 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1291 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001292 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001293
1294 Ptr += 3;
1295 Size += 3;
1296 if (C == '\\') goto Slash;
1297 return C;
1298 }
1299 }
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattner22eb9722006-06-18 05:43:12 +00001301 // If this is neither, return a single character.
1302 ++Size;
1303 return *Ptr;
1304}
1305
Chris Lattnerd01e2912006-06-18 16:22:51 +00001306
Chris Lattner22eb9722006-06-18 05:43:12 +00001307/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1308/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1309/// and that we have already incremented Ptr by Size bytes.
1310///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001311/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1312/// be updated to match.
1313char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001314 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 // If we have a slash, look for an escaped newline.
1316 if (Ptr[0] == '\\') {
1317 ++Size;
1318 ++Ptr;
1319Slash:
1320 // Common case, backslash-char where the char is not whitespace.
1321 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001324 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1325 // Found backslash<whitespace><newline>. Parse the char after it.
1326 Size += EscapedNewLineSize;
1327 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001328
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001329 // If the char that we finally got was a \n, then we must have had
1330 // something like \<newline><newline>. We don't want to consume the
1331 // second newline.
1332 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1333 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001334
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001335 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001336 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001337 }
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattner22eb9722006-06-18 05:43:12 +00001339 // Otherwise, this is not an escaped newline, just return the slash.
1340 return '\\';
1341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Chris Lattner22eb9722006-06-18 05:43:12 +00001343 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001344 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 // If this is actually a legal trigraph (not something like "??x"), return
1346 // it.
1347 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1348 Ptr += 3;
1349 Size += 3;
1350 if (C == '\\') goto Slash;
1351 return C;
1352 }
1353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 // If this is neither, return a single character.
1356 ++Size;
1357 return *Ptr;
1358}
1359
Chris Lattner22eb9722006-06-18 05:43:12 +00001360//===----------------------------------------------------------------------===//
1361// Helper methods for lexing.
1362//===----------------------------------------------------------------------===//
1363
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001364/// \brief Routine that indiscriminately skips bytes in the source file.
1365void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1366 BufferPtr += Bytes;
1367 if (BufferPtr > BufferEnd)
1368 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001369 // FIXME: What exactly does the StartOfLine bit mean? There are two
1370 // possible meanings for the "start" of the line: the first token on the
1371 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001372 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001373 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001374}
1375
Jordan Rose58c61e02013-02-09 01:10:25 +00001376static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001377 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1378 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1379 C11AllowedIDCharRanges);
1380 return C11AllowedIDChars.contains(C);
1381 } else if (LangOpts.CPlusPlus) {
1382 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1383 CXX03AllowedIDCharRanges);
1384 return CXX03AllowedIDChars.contains(C);
1385 } else {
1386 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1387 C99AllowedIDCharRanges);
1388 return C99AllowedIDChars.contains(C);
1389 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001390}
1391
Jordan Rose58c61e02013-02-09 01:10:25 +00001392static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1393 assert(isAllowedIDChar(C, LangOpts));
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001394 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1395 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1396 C11DisallowedInitialIDCharRanges);
1397 return !C11DisallowedInitialIDChars.contains(C);
1398 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001399 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001400 } else {
1401 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1402 C99DisallowedInitialIDCharRanges);
1403 return !C99DisallowedInitialIDChars.contains(C);
1404 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001405}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001406
Jordan Rose58c61e02013-02-09 01:10:25 +00001407static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1408 const char *End) {
1409 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1410 L.getSourceLocation(End));
1411}
1412
1413static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1414 CharSourceRange Range, bool IsFirst) {
1415 // Check C99 compatibility.
1416 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1417 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1418 enum {
1419 CannotAppearInIdentifier = 0,
1420 CannotStartIdentifier
1421 };
1422
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001423 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1424 C99AllowedIDCharRanges);
1425 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1426 C99DisallowedInitialIDCharRanges);
1427 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001428 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1429 << Range
1430 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001431 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001432 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1433 << Range
1434 << CannotStartIdentifier;
1435 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001436 }
1437
Jordan Rose58c61e02013-02-09 01:10:25 +00001438 // Check C++98 compatibility.
1439 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1440 Range.getBegin()) > DiagnosticsEngine::Ignored) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001441 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1442 CXX03AllowedIDCharRanges);
1443 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001444 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1445 << Range;
1446 }
1447 }
1448 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001449
Eli Friedman0834a4b2013-09-19 00:41:32 +00001450bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001451 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1452 unsigned Size;
1453 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001454 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001455 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001456
Chris Lattner22eb9722006-06-18 05:43:12 +00001457 --CurPtr; // Back up over the skipped character.
1458
1459 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1460 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001461 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001462 // TODO: Could merge these checks into an InfoTable flag to make the
1463 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001464 if (isASCII(C) && C != '\\' && C != '?' &&
1465 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001466FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001467 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001468 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1469 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Chris Lattner0f1f5052006-07-20 04:16:23 +00001471 // If we are in raw mode, return this identifier raw. There is no need to
1472 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001473 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001474 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001475
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001476 // Fill in Result.IdentifierInfo and update the token kind,
1477 // looking up the identifier in the identifier table.
1478 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Chris Lattnerc5a00062006-06-18 16:41:01 +00001480 // Finally, now that we know we have an identifier, pass this off to the
1481 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001482 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001483 return PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001484
Eli Friedman0834a4b2013-09-19 00:41:32 +00001485 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001486 }
Mike Stump11289f42009-09-09 15:08:12 +00001487
Chris Lattner22eb9722006-06-18 05:43:12 +00001488 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001489
Chris Lattner22eb9722006-06-18 05:43:12 +00001490 C = getCharAndSize(CurPtr, Size);
1491 while (1) {
1492 if (C == '$') {
1493 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001494 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001495
Chris Lattner22eb9722006-06-18 05:43:12 +00001496 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001497 if (!isLexingRawMode())
1498 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001499 CurPtr = ConsumeChar(CurPtr, Size, Result);
1500 C = getCharAndSize(CurPtr, Size);
1501 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001502
1503 } else if (C == '\\') {
1504 const char *UCNPtr = CurPtr + Size;
1505 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Rose58c61e02013-02-09 01:10:25 +00001506 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001507 goto FinishIdentifier;
1508
Jordan Rose58c61e02013-02-09 01:10:25 +00001509 if (!isLexingRawMode()) {
1510 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1511 makeCharRange(*this, CurPtr, UCNPtr),
1512 /*IsFirst=*/false);
1513 }
1514
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001515 Result.setFlag(Token::HasUCN);
1516 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1517 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1518 CurPtr = UCNPtr;
1519 else
1520 while (CurPtr != UCNPtr)
1521 (void)getAndAdvanceChar(CurPtr, Result);
1522
1523 C = getCharAndSize(CurPtr, Size);
1524 continue;
1525 } else if (!isASCII(C)) {
1526 const char *UnicodePtr = CurPtr;
1527 UTF32 CodePoint;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00001528 ConversionResult Result =
1529 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1530 (const UTF8 *)BufferEnd,
1531 &CodePoint,
1532 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001533 if (Result != conversionOK ||
Jordan Rose58c61e02013-02-09 01:10:25 +00001534 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001535 goto FinishIdentifier;
1536
Jordan Rose58c61e02013-02-09 01:10:25 +00001537 if (!isLexingRawMode()) {
1538 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1539 makeCharRange(*this, CurPtr, UnicodePtr),
1540 /*IsFirst=*/false);
1541 }
1542
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001543 CurPtr = UnicodePtr;
1544 C = getCharAndSize(CurPtr, Size);
1545 continue;
1546 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001547 goto FinishIdentifier;
1548 }
1549
1550 // Otherwise, this character is good, consume it.
1551 CurPtr = ConsumeChar(CurPtr, Size, Result);
1552
1553 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001554 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001555 CurPtr = ConsumeChar(CurPtr, Size, Result);
1556 C = getCharAndSize(CurPtr, Size);
1557 }
1558 }
1559}
1560
Douglas Gregor759ef232010-08-30 14:50:47 +00001561/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001562/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001563bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001564 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001565 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001566 if (C1 != '0')
1567 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001568 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001569 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001570}
Chris Lattner22eb9722006-06-18 05:43:12 +00001571
Nate Begeman5eee9332008-04-14 02:26:39 +00001572/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001573/// constant. From[-1] is the first character lexed. Return the end of the
1574/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001575bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001576 unsigned Size;
1577 char C = getCharAndSize(CurPtr, Size);
1578 char PrevCh = 0;
Jordan Rosea2100d72013-02-08 22:30:22 +00001579 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Chris Lattner22eb9722006-06-18 05:43:12 +00001580 CurPtr = ConsumeChar(CurPtr, Size, Result);
1581 PrevCh = C;
1582 C = getCharAndSize(CurPtr, Size);
1583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattner22eb9722006-06-18 05:43:12 +00001585 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001586 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1587 // If we are in Microsoft mode, don't continue if the constant is hex.
1588 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001589 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001590 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1591 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001592
1593 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001594 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1595 // Outside C99, we accept hexadecimal floating point numbers as a
1596 // not-quite-conforming extension. Only do so if this looks like it's
1597 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1598 bool IsHexFloat = true;
1599 if (!LangOpts.C99) {
1600 if (!isHexaLiteral(BufferPtr, LangOpts))
1601 IsHexFloat = false;
1602 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1603 IsHexFloat = false;
1604 }
1605 if (IsHexFloat)
1606 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1607 }
Mike Stump11289f42009-09-09 15:08:12 +00001608
Richard Smithfde94852013-09-26 03:33:06 +00001609 // If we have a digit separator, continue.
1610 if (C == '\'' && getLangOpts().CPlusPlus1y) {
1611 unsigned NextSize;
1612 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001613 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001614 if (!isLexingRawMode())
1615 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1616 CurPtr = ConsumeChar(CurPtr, Size, Result);
1617 return LexNumericConstant(Result, CurPtr);
1618 }
1619 }
1620
Chris Lattnerd01e2912006-06-18 16:22:51 +00001621 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001622 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001623 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001624 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001625 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001626}
1627
Richard Smithe18f0fa2012-03-05 04:02:15 +00001628/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001629/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001630const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1631 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001632 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001633
1634 // Maximally munch an identifier. FIXME: UCNs.
1635 unsigned Size;
1636 char C = getCharAndSize(CurPtr, Size);
1637 if (isIdentifierHead(C)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001638 if (!getLangOpts().CPlusPlus11) {
Richard Smith3e4a60a2012-03-07 03:13:00 +00001639 if (!isLexingRawMode())
Richard Smith0df56f42012-03-08 02:39:21 +00001640 Diag(CurPtr,
1641 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1642 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1643 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1644 return CurPtr;
1645 }
1646
1647 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1648 // that does not start with an underscore is ill-formed. As a conforming
1649 // extension, we treat all such suffixes as if they had whitespace before
1650 // them.
Richard Smithf4198b72013-07-23 08:14:48 +00001651 bool IsUDSuffix = false;
1652 if (C == '_')
1653 IsUDSuffix = true;
Richard Smith2a988622013-09-24 04:06:10 +00001654 else if (IsStringLiteral && getLangOpts().CPlusPlus1y) {
1655 // In C++1y, we need to look ahead a few characters to see if this is a
1656 // valid suffix for a string literal or a numeric literal (this could be
1657 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001658 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001659 char Buffer[MaxStandardSuffixLength] = { C };
1660 unsigned Consumed = Size;
1661 unsigned Chars = 1;
1662 while (true) {
1663 unsigned NextSize;
1664 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1665 getLangOpts());
1666 if (!isIdentifierBody(Next)) {
1667 // End of suffix. Check whether this is on the whitelist.
1668 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1669 NumericLiteralParser::isValidUDSuffix(
1670 getLangOpts(), StringRef(Buffer, Chars));
1671 break;
1672 }
1673
1674 if (Chars == MaxStandardSuffixLength)
1675 // Too long: can't be a standard suffix.
1676 break;
1677
1678 Buffer[Chars++] = Next;
1679 Consumed += NextSize;
1680 }
Richard Smithf4198b72013-07-23 08:14:48 +00001681 }
1682
1683 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001684 if (!isLexingRawMode())
Richard Smithf4198b72013-07-23 08:14:48 +00001685 Diag(CurPtr, getLangOpts().MicrosoftMode ?
Francois Pichet7ebc4c12012-04-07 23:09:23 +00001686 diag::ext_ms_reserved_user_defined_literal :
1687 diag::ext_reserved_user_defined_literal)
Richard Smith3e4a60a2012-03-07 03:13:00 +00001688 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1689 return CurPtr;
1690 }
1691
Richard Smithd67aea22012-03-06 03:21:47 +00001692 Result.setFlag(Token::HasUDSuffix);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001693 do {
1694 CurPtr = ConsumeChar(CurPtr, Size, Result);
1695 C = getCharAndSize(CurPtr, Size);
1696 } while (isIdentifierBody(C));
1697 }
1698 return CurPtr;
1699}
1700
Chris Lattner22eb9722006-06-18 05:43:12 +00001701/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001702/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001703bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001704 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001705 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001706
Richard Smithacd4d3d2011-10-15 01:18:56 +00001707 if (!isLexingRawMode() &&
1708 (Kind == tok::utf8_string_literal ||
1709 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001710 Kind == tok::utf32_string_literal))
1711 Diag(BufferPtr, getLangOpts().CPlusPlus
1712 ? diag::warn_cxx98_compat_unicode_literal
1713 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001714
Chris Lattner22eb9722006-06-18 05:43:12 +00001715 char C = getAndAdvanceChar(CurPtr, Result);
1716 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001717 // Skip escaped characters. Escaped newlines will already be processed by
1718 // getAndAdvanceChar.
1719 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001720 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001721
Chris Lattner52d96ac2010-05-30 23:27:38 +00001722 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001723 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001724 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001725 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001726 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001727 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001728 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001729
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001730 if (C == 0) {
1731 if (isCodeCompletionPoint(CurPtr-1)) {
1732 PP->CodeCompleteNaturalLanguage();
1733 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001734 cutOffLexing();
1735 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001736 }
1737
Chris Lattner52d96ac2010-05-30 23:27:38 +00001738 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001739 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001740 C = getAndAdvanceChar(CurPtr, Result);
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Richard Smithe18f0fa2012-03-05 04:02:15 +00001743 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001744 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001745 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001746
Chris Lattner5a78a022006-07-20 06:02:19 +00001747 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001748 if (NulCharacter && !isLexingRawMode())
1749 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001750
Chris Lattnerd01e2912006-06-18 16:22:51 +00001751 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001752 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001753 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001754 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001755 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001756}
1757
Craig Topper54edcca2011-08-11 04:06:15 +00001758/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1759/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001760bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001761 tok::TokenKind Kind) {
1762 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1763 // Between the initial and final double quote characters of the raw string,
1764 // any transformations performed in phases 1 and 2 (trigraphs,
1765 // universal-character-names, and line splicing) are reverted.
1766
Richard Smithacd4d3d2011-10-15 01:18:56 +00001767 if (!isLexingRawMode())
1768 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1769
Craig Topper54edcca2011-08-11 04:06:15 +00001770 unsigned PrefixLen = 0;
1771
1772 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1773 ++PrefixLen;
1774
1775 // If the last character was not a '(', then we didn't lex a valid delimiter.
1776 if (CurPtr[PrefixLen] != '(') {
1777 if (!isLexingRawMode()) {
1778 const char *PrefixEnd = &CurPtr[PrefixLen];
1779 if (PrefixLen == 16) {
1780 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1781 } else {
1782 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1783 << StringRef(PrefixEnd, 1);
1784 }
1785 }
1786
1787 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1788 // it's possible the '"' was intended to be part of the raw string, but
1789 // there's not much we can do about that.
1790 while (1) {
1791 char C = *CurPtr++;
1792
1793 if (C == '"')
1794 break;
1795 if (C == 0 && CurPtr-1 == BufferEnd) {
1796 --CurPtr;
1797 break;
1798 }
1799 }
1800
1801 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001802 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001803 }
1804
1805 // Save prefix and move CurPtr past it
1806 const char *Prefix = CurPtr;
1807 CurPtr += PrefixLen + 1; // skip over prefix and '('
1808
1809 while (1) {
1810 char C = *CurPtr++;
1811
1812 if (C == ')') {
1813 // Check for prefix match and closing quote.
1814 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1815 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1816 break;
1817 }
1818 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1819 if (!isLexingRawMode())
1820 Diag(BufferPtr, diag::err_unterminated_raw_string)
1821 << StringRef(Prefix, PrefixLen);
1822 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001823 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001824 }
1825 }
1826
Richard Smithe18f0fa2012-03-05 04:02:15 +00001827 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001828 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001829 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001830
Craig Topper54edcca2011-08-11 04:06:15 +00001831 // Update the location of token as well as BufferPtr.
1832 const char *TokStart = BufferPtr;
1833 FormTokenWithChars(Result, CurPtr, Kind);
1834 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001835 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001836}
1837
Chris Lattner22eb9722006-06-18 05:43:12 +00001838/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1839/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001840bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001841 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001842 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001843 char C = getAndAdvanceChar(CurPtr, Result);
1844 while (C != '>') {
1845 // Skip escaped characters.
1846 if (C == '\\') {
1847 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001848 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001849 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001850 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1851 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001852 // If the filename is unterminated, then it must just be a lone <
1853 // character. Return this as such.
1854 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001855 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001856 } else if (C == 0) {
1857 NulCharacter = CurPtr-1;
1858 }
1859 C = getAndAdvanceChar(CurPtr, Result);
1860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattner5a78a022006-07-20 06:02:19 +00001862 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001863 if (NulCharacter && !isLexingRawMode())
1864 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Chris Lattnerd01e2912006-06-18 16:22:51 +00001866 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001867 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001868 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001869 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001870 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001871}
1872
1873
1874/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001875/// lexed either ' or L' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001876bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001877 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001878 const char *NulCharacter = 0; // Does this character contain the \0 character?
1879
Richard Smithacd4d3d2011-10-15 01:18:56 +00001880 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001881 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1882 Diag(BufferPtr, getLangOpts().CPlusPlus
1883 ? diag::warn_cxx98_compat_unicode_literal
1884 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001885
Chris Lattner22eb9722006-06-18 05:43:12 +00001886 char C = getAndAdvanceChar(CurPtr, Result);
1887 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001888 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001889 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001890 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001891 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001892 }
1893
1894 while (C != '\'') {
1895 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001896 if (C == '\\')
1897 C = getAndAdvanceChar(CurPtr, Result);
1898
1899 if (C == '\n' || C == '\r' || // Newline.
1900 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001901 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001902 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001903 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001904 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001905 }
1906
1907 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001908 if (isCodeCompletionPoint(CurPtr-1)) {
1909 PP->CodeCompleteNaturalLanguage();
1910 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001911 cutOffLexing();
1912 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001913 }
1914
Chris Lattner86851b82010-07-07 23:24:27 +00001915 NulCharacter = CurPtr-1;
1916 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001917 C = getAndAdvanceChar(CurPtr, Result);
1918 }
Mike Stump11289f42009-09-09 15:08:12 +00001919
Richard Smithe18f0fa2012-03-05 04:02:15 +00001920 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001921 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001922 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001923
Chris Lattner86851b82010-07-07 23:24:27 +00001924 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001925 if (NulCharacter && !isLexingRawMode())
1926 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001927
Chris Lattnerd01e2912006-06-18 16:22:51 +00001928 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001929 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001930 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001931 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001932 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001933}
1934
1935/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1936/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001937///
1938/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1939///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001940bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1941 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001942 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001943 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1944
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001945 unsigned char Char = *CurPtr;
1946
1947 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001948 while (1) {
1949 // Skip horizontal whitespace very aggressively.
1950 while (isHorizontalWhitespace(Char))
1951 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001952
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001953 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001954 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001955 break;
Mike Stump11289f42009-09-09 15:08:12 +00001956
Chris Lattner22eb9722006-06-18 05:43:12 +00001957 if (ParsingPreprocessorDirective) {
1958 // End of preprocessor directive line, let LexTokenInternal handle this.
1959 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001960 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001963 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001964 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001965 Char = *++CurPtr;
1966 }
1967
Chris Lattner4d963442008-10-12 04:05:48 +00001968 // If the client wants us to return whitespace, return it now.
1969 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001970 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001971 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001972 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001973 IsAtPhysicalStartOfLine = true;
1974 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001975 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001976 return true;
1977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001979 // If this isn't immediately after a newline, there is leading space.
1980 char PrevChar = CurPtr[-1];
1981 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1982
1983 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001984 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001985 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001986 TokAtPhysicalStartOfLine = true;
1987 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001988
Chris Lattner22eb9722006-06-18 05:43:12 +00001989 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001990 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001991}
1992
Nico Weber158a31a2012-11-11 07:02:14 +00001993/// We have just read the // characters from input. Skip until we find the
1994/// newline character thats terminate the comment. Then update BufferPtr and
1995/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00001996///
1997/// If we're in KeepCommentMode or any CommentHandler has inserted
1998/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001999bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2000 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002001 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002003 if (!LangOpts.LineComment && !isLexingRawMode()) {
2004 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002005
Chris Lattner22eb9722006-06-18 05:43:12 +00002006 // Mark them enabled so we only emit one warning for this translation
2007 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002008 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattner22eb9722006-06-18 05:43:12 +00002011 // Scan over the body of the comment. The common case, when scanning, is that
2012 // the comment contains normal ascii characters with nothing interesting in
2013 // them. As such, optimize for this case with the inner loop.
2014 char C;
2015 do {
2016 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002017 // Skip over characters in the fast loop.
2018 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002019 C != '\n' && C != '\r') // Newline or DOS-style newline.
2020 C = *++CurPtr;
2021
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002022 const char *NextLine = CurPtr;
2023 if (C != 0) {
2024 // We found a newline, see if it's escaped.
2025 const char *EscapePtr = CurPtr-1;
2026 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
2027 --EscapePtr;
2028
2029 if (*EscapePtr == '\\') // Escaped newline.
2030 CurPtr = EscapePtr;
2031 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2032 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2033 CurPtr = EscapePtr-2;
2034 else
2035 break; // This is a newline, we're done.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002036 }
Mike Stump11289f42009-09-09 15:08:12 +00002037
Chris Lattner22eb9722006-06-18 05:43:12 +00002038 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002039 // properly decode the character. Read it in raw mode to avoid emitting
2040 // diagnostics about things like trigraphs. If we see an escaped newline,
2041 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002043 bool OldRawMode = isLexingRawMode();
2044 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002045 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002046 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002047
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002048 // If we only read only one character, then no special handling is needed.
2049 // We're done and can skip forward to the newline.
2050 if (C != 0 && CurPtr == OldPtr+1) {
2051 CurPtr = NextLine;
2052 break;
2053 }
2054
Chris Lattner22eb9722006-06-18 05:43:12 +00002055 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002056 // \n, then we had an escaped newline within the comment. Emit diagnostic
2057 // unless the next line is also a // comment.
2058 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002059 for (; OldPtr != CurPtr; ++OldPtr)
2060 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002061 // Okay, we found a // comment that ends in a newline, if the next
2062 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002063 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002064 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002065 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002066 ++ForwardPtr;
2067 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2068 break;
2069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Chris Lattner6d27a162008-11-22 02:02:22 +00002071 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002072 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002073 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 }
2075 }
Mike Stump11289f42009-09-09 15:08:12 +00002076
Douglas Gregor11583702010-08-25 17:04:25 +00002077 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002078 --CurPtr;
2079 break;
2080 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002081
2082 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2083 PP->CodeCompleteNaturalLanguage();
2084 cutOffLexing();
2085 return false;
2086 }
2087
Chris Lattner22eb9722006-06-18 05:43:12 +00002088 } while (C != '\n' && C != '\r');
2089
Chris Lattner93ddf802010-02-03 21:06:21 +00002090 // Found but did not consume the newline. Notify comment handlers about the
2091 // comment unless we're in a #if 0 block.
2092 if (PP && !isLexingRawMode() &&
2093 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2094 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002095 BufferPtr = CurPtr;
2096 return true; // A token has to be returned.
2097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
Chris Lattner457fc152006-07-29 06:30:25 +00002099 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002100 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002101 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002102
2103 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002104 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002105 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002106 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002107 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002108 }
Mike Stump11289f42009-09-09 15:08:12 +00002109
Chris Lattner22eb9722006-06-18 05:43:12 +00002110 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002111 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002112 // contribute to another token), it isn't needed for correctness. Note that
2113 // this is ok even in KeepWhitespaceMode, because we would have returned the
2114 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002115 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002116
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002118 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002119 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002120 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002121 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002122 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002123 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002124}
Chris Lattner22eb9722006-06-18 05:43:12 +00002125
Nico Weber158a31a2012-11-11 07:02:14 +00002126/// If in save-comment mode, package up this Line comment in an appropriate
2127/// way and return it.
2128bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002129 // If we're not in a preprocessor directive, just return the // comment
2130 // directly.
2131 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002132
David Blaikied5321242012-06-06 18:52:13 +00002133 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002134 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002135
Nico Weber158a31a2012-11-11 07:02:14 +00002136 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002137 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002138 bool Invalid = false;
2139 std::string Spelling = PP->getSpelling(Result, &Invalid);
2140 if (Invalid)
2141 return true;
2142
Nico Weber158a31a2012-11-11 07:02:14 +00002143 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002144 Spelling[1] = '*'; // Change prefix to "/*".
2145 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002146
Chris Lattnerb11c3232008-10-12 04:51:35 +00002147 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002148 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002149 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002150 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002151}
2152
Chris Lattnercb283342006-06-18 06:48:37 +00002153/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002154/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2155/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002156static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002157 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002158 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002159
Chris Lattner22eb9722006-06-18 05:43:12 +00002160 // Back up off the newline.
2161 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Chris Lattner22eb9722006-06-18 05:43:12 +00002163 // If this is a two-character newline sequence, skip the other character.
2164 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2165 // \n\n or \r\r -> not escaped newline.
2166 if (CurPtr[0] == CurPtr[1])
2167 return false;
2168 // \n\r or \r\n -> skip the newline.
2169 --CurPtr;
2170 }
Mike Stump11289f42009-09-09 15:08:12 +00002171
Chris Lattner22eb9722006-06-18 05:43:12 +00002172 // If we have horizontal whitespace, skip over it. We allow whitespace
2173 // between the slash and newline.
2174 bool HasSpace = false;
2175 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2176 --CurPtr;
2177 HasSpace = true;
2178 }
Mike Stump11289f42009-09-09 15:08:12 +00002179
Chris Lattner22eb9722006-06-18 05:43:12 +00002180 // If we have a slash, we know this is an escaped newline.
2181 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002182 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002183 } else {
2184 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002185 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2186 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002187 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattnercb283342006-06-18 06:48:37 +00002189 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002190 CurPtr -= 2;
2191
2192 // If no trigraphs are enabled, warn that we ignored this trigraph and
2193 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002194 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002195 if (!L->isLexingRawMode())
2196 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002197 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002198 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002199 if (!L->isLexingRawMode())
2200 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattner22eb9722006-06-18 05:43:12 +00002203 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002204 if (!L->isLexingRawMode())
2205 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattner22eb9722006-06-18 05:43:12 +00002207 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002208 if (HasSpace && !L->isLexingRawMode())
2209 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnercb283342006-06-18 06:48:37 +00002211 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002212}
2213
Chris Lattneraded4a92006-10-27 04:42:31 +00002214#ifdef __SSE2__
2215#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002216#elif __ALTIVEC__
2217#include <altivec.h>
2218#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002219#endif
2220
James Dennettf442d242012-06-17 03:40:43 +00002221/// We have just read from input the / and * characters that started a comment.
2222/// Read until we find the * and / characters that terminate the comment.
2223/// Note that we don't bother decoding trigraphs or escaped newlines in block
2224/// comments, because they cannot cause the comment to end. The only thing
2225/// that can happen is the comment could end with an escaped newline between
2226/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002227///
Chris Lattner87d02082010-01-18 22:35:47 +00002228/// If we're in KeepCommentMode or any CommentHandler has inserted
2229/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002230bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2231 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002232 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002233 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002234 // optimization helps people who like to put a lot of * characters in their
2235 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002236
2237 // The first character we get with newlines and trigraphs skipped to handle
2238 // the degenerate /*/ case below correctly if the * has an escaped newline
2239 // after it.
2240 unsigned CharSize;
2241 unsigned char C = getCharAndSize(CurPtr, CharSize);
2242 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002243 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002244 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002245 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002246 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002247
Chris Lattner99e7d232008-10-12 04:19:49 +00002248 // KeepWhitespaceMode should return this broken comment as a token. Since
2249 // it isn't a well formed comment, just return it as an 'unknown' token.
2250 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002251 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002252 return true;
2253 }
Mike Stump11289f42009-09-09 15:08:12 +00002254
Chris Lattner99e7d232008-10-12 04:19:49 +00002255 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002256 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002257 }
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattnerc850ad62007-07-21 23:43:37 +00002259 // Check to see if the first character after the '/*' is another /. If so,
2260 // then this slash does not end the block comment, it is part of it.
2261 if (C == '/')
2262 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002263
Chris Lattner22eb9722006-06-18 05:43:12 +00002264 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002265 // Skip over all non-interesting characters until we find end of buffer or a
2266 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002267 if (CurPtr + 24 < BufferEnd &&
2268 // If there is a code-completion point avoid the fast scan because it
2269 // doesn't check for '\0'.
2270 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002271 // While not aligned to a 16-byte boundary.
2272 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2273 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chris Lattner6cc3e362006-10-27 04:12:35 +00002275 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002276
2277#ifdef __SSE2__
Benjamin Kramer38857372011-11-22 18:56:46 +00002278 __m128i Slashes = _mm_set1_epi8('/');
2279 while (CurPtr+16 <= BufferEnd) {
Roman Divackye6377112012-09-06 15:59:27 +00002280 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2281 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002282 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002283 // Adjust the pointer to point directly after the first slash. It's
2284 // not necessary to set C here, it will be overwritten at the end of
2285 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002286 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002287 goto FoundSlash;
2288 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002289 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002290 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002291#elif __ALTIVEC__
2292 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002293 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002294 '/', '/', '/', '/', '/', '/', '/', '/'
2295 };
2296 while (CurPtr+16 <= BufferEnd &&
2297 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2298 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002299#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002300 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002301 while (CurPtr[0] != '/' &&
2302 CurPtr[1] != '/' &&
2303 CurPtr[2] != '/' &&
2304 CurPtr[3] != '/' &&
2305 CurPtr+4 < BufferEnd) {
2306 CurPtr += 4;
2307 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002308#endif
Mike Stump11289f42009-09-09 15:08:12 +00002309
Chris Lattneraded4a92006-10-27 04:42:31 +00002310 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002311 C = *CurPtr++;
2312 }
Mike Stump11289f42009-09-09 15:08:12 +00002313
Chris Lattneraded4a92006-10-27 04:42:31 +00002314 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002315 while (C != '/' && C != '\0')
2316 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattner22eb9722006-06-18 05:43:12 +00002318 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002319 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002320 if (CurPtr[-2] == '*') // We found the final */. We're done!
2321 break;
Mike Stump11289f42009-09-09 15:08:12 +00002322
Chris Lattner22eb9722006-06-18 05:43:12 +00002323 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002324 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002325 // We found the final */, though it had an escaped newline between the
2326 // * and /. We're done!
2327 break;
2328 }
2329 }
2330 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2331 // If this is a /* inside of the comment, emit a warning. Don't do this
2332 // if this is a /*/, which will end the comment. This misses cases with
2333 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002334 if (!isLexingRawMode())
2335 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002336 }
2337 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002338 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002339 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002340 // Note: the user probably forgot a */. We could continue immediately
2341 // after the /*, but this would involve lexing a lot of what really is the
2342 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002343 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002344
Chris Lattner99e7d232008-10-12 04:19:49 +00002345 // KeepWhitespaceMode should return this broken comment as a token. Since
2346 // it isn't a well formed comment, just return it as an 'unknown' token.
2347 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002348 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002349 return true;
2350 }
Mike Stump11289f42009-09-09 15:08:12 +00002351
Chris Lattner99e7d232008-10-12 04:19:49 +00002352 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002353 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002354 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2355 PP->CodeCompleteNaturalLanguage();
2356 cutOffLexing();
2357 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002358 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002359
Chris Lattner22eb9722006-06-18 05:43:12 +00002360 C = *CurPtr++;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattner93ddf802010-02-03 21:06:21 +00002363 // Notify comment handlers about the comment unless we're in a #if 0 block.
2364 if (PP && !isLexingRawMode() &&
2365 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2366 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002367 BufferPtr = CurPtr;
2368 return true; // A token has to be returned.
2369 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002370
Chris Lattner457fc152006-07-29 06:30:25 +00002371 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002372 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002373 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002374 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002375 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002376
2377 // It is common for the tokens immediately after a /**/ comment to be
2378 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002379 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2380 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002381 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002382 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002383 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002384 }
2385
2386 // Otherwise, just return so that the next character will be lexed as a token.
2387 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002388 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002389 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002390}
2391
2392//===----------------------------------------------------------------------===//
2393// Primary Lexing Entry Points
2394//===----------------------------------------------------------------------===//
2395
Chris Lattner22eb9722006-06-18 05:43:12 +00002396/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2397/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002398void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002399 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2400 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002401 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002402
2403 // CurPtr - Cache BufferPtr in an automatic variable.
2404 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002405 while (1) {
2406 char Char = getAndAdvanceChar(CurPtr, Tmp);
2407 switch (Char) {
2408 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002409 if (Result)
2410 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002411 break;
2412 case 0: // Null.
2413 // Found end of file?
2414 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002415 if (isCodeCompletionPoint(CurPtr-1)) {
2416 PP->CodeCompleteNaturalLanguage();
2417 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002418 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002419 }
2420
Chris Lattner22eb9722006-06-18 05:43:12 +00002421 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002422 if (Result)
2423 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002424 break;
2425 }
2426 // FALL THROUGH.
2427 case '\r':
2428 case '\n':
2429 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2430 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2431 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002432
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002433 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002434 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002435 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002436 if (PP)
2437 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002438 Lex(Tmp);
2439 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002440 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002441
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002442 // Finally, we're done;
2443 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002444 }
2445 }
2446}
2447
2448/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2449/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002450/// This returns true if Result contains a token, false if PP.Lex should be
2451/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002452bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002453 // If we hit the end of the file while parsing a preprocessor directive,
2454 // end the preprocessor directive first. The next token returned will
2455 // then be the end of file.
2456 if (ParsingPreprocessorDirective) {
2457 // Done parsing the "line".
2458 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002459 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002460 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002461
Chris Lattner457fc152006-07-29 06:30:25 +00002462 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002463 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002464 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002465 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002466
Chris Lattner30a2fa12006-07-19 06:31:49 +00002467 // If we are in raw mode, return this event as an EOF token. Let the caller
2468 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002469 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002470 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002471 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002472 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002473 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002474 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002475
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002476 // Issue diagnostics for unterminated #if and missing newline.
2477
Chris Lattner30a2fa12006-07-19 06:31:49 +00002478 // If we are in a #if directive, emit an error.
2479 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002480 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002481 PP->Diag(ConditionalStack.back().IfLoc,
2482 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002483 ConditionalStack.pop_back();
2484 }
Mike Stump11289f42009-09-09 15:08:12 +00002485
Chris Lattner8f96d042008-04-12 05:54:25 +00002486 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2487 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002488 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2489 DiagnosticsEngine &Diags = PP->getDiagnostics();
2490 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2491 unsigned DiagID;
2492
2493 if (LangOpts.CPlusPlus11) {
2494 // C++11 [lex.phases] 2.2 p2
2495 // Prefer the C++98 pedantic compatibility warning over the generic,
2496 // non-extension, user-requested "missing newline at EOF" warning.
2497 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_no_newline_eof,
2498 EndLoc) != DiagnosticsEngine::Ignored) {
2499 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2500 } else {
2501 DiagID = diag::warn_no_newline_eof;
2502 }
2503 } else {
2504 DiagID = diag::ext_no_newline_eof;
2505 }
2506
2507 Diag(BufferEnd, DiagID)
2508 << FixItHint::CreateInsertion(EndLoc, "\n");
2509 }
Mike Stump11289f42009-09-09 15:08:12 +00002510
Chris Lattner22eb9722006-06-18 05:43:12 +00002511 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002512
2513 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002514 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002515}
2516
Chris Lattner678c8802006-07-11 05:46:12 +00002517/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2518/// the specified lexer will return a tok::l_paren token, 0 if it is something
2519/// else and 2 if there are no more tokens in the buffer controlled by the
2520/// lexer.
2521unsigned Lexer::isNextPPTokenLParen() {
2522 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002523
Chris Lattner678c8802006-07-11 05:46:12 +00002524 // Switch to 'skipping' mode. This will ensure that we can lex a token
2525 // without emitting diagnostics, disables macro expansion, and will cause EOF
2526 // to return an EOF token instead of popping the include stack.
2527 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002528
Chris Lattner678c8802006-07-11 05:46:12 +00002529 // Save state that can be changed while lexing so that we can restore it.
2530 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002531 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002532 bool atStartOfLine = IsAtStartOfLine;
2533 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2534 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002535
Chris Lattner146762e2007-07-20 16:59:19 +00002536 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002537 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002538
Chris Lattner678c8802006-07-11 05:46:12 +00002539 // Restore state that may have changed.
2540 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002541 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002542 HasLeadingSpace = leadingSpace;
2543 IsAtStartOfLine = atStartOfLine;
2544 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002545
Chris Lattner678c8802006-07-11 05:46:12 +00002546 // Restore the lexer back to non-skipping mode.
2547 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002549 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002550 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002551 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002552}
2553
James Dennettf442d242012-06-17 03:40:43 +00002554/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002555static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2556 ConflictMarkerKind CMK) {
2557 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2558 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2559 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2560 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002561 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002562 // Must occur at start of line.
2563 if (RestOfBuffer[Pos-1] != '\r' &&
2564 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002565 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2566 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002567 continue;
2568 }
2569 return RestOfBuffer.data()+Pos;
2570 }
2571 return 0;
2572}
2573
2574/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2575/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2576/// and recover nicely. This returns true if it is a conflict marker and false
2577/// if not.
2578bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2579 // Only a conflict marker if it starts at the beginning of a line.
2580 if (CurPtr != BufferStart &&
2581 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2582 return false;
2583
Richard Smitha9e33d42011-10-12 00:37:51 +00002584 // Check to see if we have <<<<<<< or >>>>.
2585 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2586 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002587 return false;
2588
2589 // If we have a situation where we don't care about conflict markers, ignore
2590 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002591 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002592 return false;
2593
Richard Smitha9e33d42011-10-12 00:37:51 +00002594 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2595
2596 // Check to see if there is an ending marker somewhere in the buffer at the
2597 // start of a line to terminate this conflict marker.
2598 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002599 // We found a match. We are really in a conflict marker.
2600 // Diagnose this, and ignore to the end of line.
2601 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002602 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002603
2604 // Skip ahead to the end of line. We know this exists because the
2605 // end-of-conflict marker starts with \r or \n.
2606 while (*CurPtr != '\r' && *CurPtr != '\n') {
2607 assert(CurPtr != BufferEnd && "Didn't find end of line");
2608 ++CurPtr;
2609 }
2610 BufferPtr = CurPtr;
2611 return true;
2612 }
2613
2614 // No end of conflict marker found.
2615 return false;
2616}
2617
2618
Richard Smitha9e33d42011-10-12 00:37:51 +00002619/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2620/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2621/// is the end of a conflict marker. Handle it by ignoring up until the end of
2622/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002623bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2624 // Only a conflict marker if it starts at the beginning of a line.
2625 if (CurPtr != BufferStart &&
2626 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2627 return false;
2628
2629 // If we have a situation where we don't care about conflict markers, ignore
2630 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002631 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002632 return false;
2633
Richard Smitha9e33d42011-10-12 00:37:51 +00002634 // Check to see if we have the marker (4 characters in a row).
2635 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002636 if (CurPtr[i] != CurPtr[0])
2637 return false;
2638
2639 // If we do have it, search for the end of the conflict marker. This could
2640 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2641 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002642 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2643 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002644 CurPtr = End;
2645
2646 // Skip ahead to the end of line.
2647 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2648 ++CurPtr;
2649
2650 BufferPtr = CurPtr;
2651
2652 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002653 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002654 return true;
2655 }
2656
2657 return false;
2658}
2659
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002660bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2661 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002662 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002663 return Loc == PP->getCodeCompletionLoc();
2664 }
2665
2666 return false;
2667}
2668
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002669uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2670 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002671 unsigned CharSize;
2672 char Kind = getCharAndSize(StartPtr, CharSize);
2673
2674 unsigned NumHexDigits;
2675 if (Kind == 'u')
2676 NumHexDigits = 4;
2677 else if (Kind == 'U')
2678 NumHexDigits = 8;
2679 else
2680 return 0;
2681
Jordan Rosec0cba272013-01-27 20:12:04 +00002682 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002683 if (Result && !isLexingRawMode())
2684 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002685 return 0;
2686 }
2687
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002688 const char *CurPtr = StartPtr + CharSize;
2689 const char *KindLoc = &CurPtr[-1];
2690
2691 uint32_t CodePoint = 0;
2692 for (unsigned i = 0; i < NumHexDigits; ++i) {
2693 char C = getCharAndSize(CurPtr, CharSize);
2694
2695 unsigned Value = llvm::hexDigitValue(C);
2696 if (Value == -1U) {
2697 if (Result && !isLexingRawMode()) {
2698 if (i == 0) {
2699 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2700 << StringRef(KindLoc, 1);
2701 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002702 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002703
2704 // If the user wrote \U1234, suggest a fixit to \u.
2705 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002706 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002707 Diag(KindLoc, diag::note_ucn_four_not_eight)
2708 << FixItHint::CreateReplacement(URange, "u");
2709 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002710 }
2711 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002712
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002713 return 0;
2714 }
2715
2716 CodePoint <<= 4;
2717 CodePoint += Value;
2718
2719 CurPtr += CharSize;
2720 }
2721
2722 if (Result) {
2723 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002724 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002725 StartPtr = CurPtr;
2726 else
2727 while (StartPtr != CurPtr)
2728 (void)getAndAdvanceChar(StartPtr, *Result);
2729 } else {
2730 StartPtr = CurPtr;
2731 }
2732
Justin Bogner53535132013-10-21 05:02:28 +00002733 // Don't apply C family restrictions to UCNs in assembly mode
2734 if (LangOpts.AsmPreprocessor)
2735 return CodePoint;
2736
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002737 // C99 6.4.3p2: A universal character name shall not specify a character whose
2738 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2739 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2740 // C++11 [lex.charset]p2: If the hexadecimal value for a
2741 // universal-character-name corresponds to a surrogate code point (in the
2742 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2743 // if the hexadecimal value for a universal-character-name outside the
2744 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2745 // string literal corresponds to a control character (in either of the
2746 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2747 // basic source character set, the program is ill-formed.
2748 if (CodePoint < 0xA0) {
2749 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2750 return CodePoint;
2751
2752 // We don't use isLexingRawMode() here because we need to warn about bad
2753 // UCNs even when skipping preprocessing tokens in a #if block.
2754 if (Result && PP) {
2755 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2756 Diag(BufferPtr, diag::err_ucn_control_character);
2757 else {
2758 char C = static_cast<char>(CodePoint);
2759 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2760 }
2761 }
2762
2763 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002764
2765 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002766 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002767 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002768 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002769 if (Result && PP) {
2770 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2771 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2772 else
2773 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2774 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002775 return 0;
2776 }
2777
2778 return CodePoint;
2779}
2780
Eli Friedman0834a4b2013-09-19 00:41:32 +00002781bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2782 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002783 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2784 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002785 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002786 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002787 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002788 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002789
2790 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002791 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002792 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002793 return false;
2794}
Jordan Rose4246ae02013-01-24 20:50:50 +00002795
Eli Friedman0834a4b2013-09-19 00:41:32 +00002796bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002797 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2798 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2799 !PP->isPreprocessedOutput()) {
2800 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2801 makeCharRange(*this, BufferPtr, CurPtr),
2802 /*IsFirst=*/true);
2803 }
2804
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002805 MIOpt.ReadToken();
2806 return LexIdentifier(Result, CurPtr);
2807 }
2808
Jordan Rosecc538342013-01-31 19:48:48 +00002809 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2810 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002811 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002812 // Non-ASCII characters tend to creep into source code unintentionally.
2813 // Instead of letting the parser complain about the unknown token,
2814 // just drop the character.
2815 // Note that we can /only/ do this when the non-ASCII character is actually
2816 // spelled as Unicode, not written as a UCN. The standard requires that
2817 // we not throw away any possible preprocessor tokens, but there's a
2818 // loophole in the mapping of Unicode characters to basic character set
2819 // characters that allows us to map these particular characters to, say,
2820 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002821 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002822 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002823
2824 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002825 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002826 }
2827
2828 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2829 // up by accident.
2830 MIOpt.ReadToken();
2831 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002832 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002833}
2834
Eli Friedman0834a4b2013-09-19 00:41:32 +00002835void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2836 IsAtStartOfLine = Result.isAtStartOfLine();
2837 HasLeadingSpace = Result.hasLeadingSpace();
2838 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2839 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2840}
2841
2842bool Lexer::Lex(Token &Result) {
2843 // Start a new token.
2844 Result.startToken();
2845
2846 // Set up misc whitespace flags for LexTokenInternal.
2847 if (IsAtStartOfLine) {
2848 Result.setFlag(Token::StartOfLine);
2849 IsAtStartOfLine = false;
2850 }
2851
2852 if (HasLeadingSpace) {
2853 Result.setFlag(Token::LeadingSpace);
2854 HasLeadingSpace = false;
2855 }
2856
2857 if (HasLeadingEmptyMacro) {
2858 Result.setFlag(Token::LeadingEmptyMacro);
2859 HasLeadingEmptyMacro = false;
2860 }
2861
2862 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2863 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002864 bool isRawLex = isLexingRawMode();
2865 (void) isRawLex;
2866 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2867 // (After the LexTokenInternal call, the lexer might be destroyed.)
2868 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2869 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002870}
Chris Lattner22eb9722006-06-18 05:43:12 +00002871
2872/// LexTokenInternal - This implements a simple C family lexer. It is an
2873/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002874/// has a null character at the end of the file. This returns a preprocessing
2875/// token, not a normal token, as such, it is an internal interface. It assumes
2876/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002877bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002878LexNextToken:
2879 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002880 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00002881 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00002882
Chris Lattner22eb9722006-06-18 05:43:12 +00002883 // CurPtr - Cache BufferPtr in an automatic variable.
2884 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002885
Chris Lattnereb54b592006-07-10 06:34:27 +00002886 // Small amounts of horizontal whitespace is very common between tokens.
2887 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2888 ++CurPtr;
2889 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2890 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Chris Lattner4d963442008-10-12 04:05:48 +00002892 // If we are keeping whitespace and other tokens, just return what we just
2893 // skipped. The next lexer invocation will return the token after the
2894 // whitespace.
2895 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002896 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002897 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002898 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002899 }
Mike Stump11289f42009-09-09 15:08:12 +00002900
Chris Lattnereb54b592006-07-10 06:34:27 +00002901 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002902 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002903 }
Mike Stump11289f42009-09-09 15:08:12 +00002904
Chris Lattner22eb9722006-06-18 05:43:12 +00002905 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002906
Chris Lattner22eb9722006-06-18 05:43:12 +00002907 // Read a character, advancing over it.
2908 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002909 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002910
Chris Lattner22eb9722006-06-18 05:43:12 +00002911 switch (Char) {
2912 case 0: // Null.
2913 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002914 if (CurPtr-1 == BufferEnd)
2915 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002916
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002917 // Check if we are performing code completion.
2918 if (isCodeCompletionPoint(CurPtr-1)) {
2919 // Return the code-completion token.
2920 Result.startToken();
2921 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002922 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002923 }
2924
Chris Lattner6d27a162008-11-22 02:02:22 +00002925 if (!isLexingRawMode())
2926 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002927 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002928 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2929 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002930
Eli Friedman0834a4b2013-09-19 00:41:32 +00002931 // We know the lexer hasn't changed, so just try again with this lexer.
2932 // (We manually eliminate the tail call to avoid recursion.)
2933 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002934
2935 case 26: // DOS & CP/M EOF: "^Z".
2936 // If we're in Microsoft extensions mode, treat this as end of file.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002937 if (LangOpts.MicrosoftExt)
2938 return LexEndOfFile(Result, CurPtr-1);
2939
Chris Lattner3dfff972009-12-17 05:29:40 +00002940 // If Microsoft extensions are disabled, this is just random garbage.
2941 Kind = tok::unknown;
2942 break;
2943
Chris Lattner22eb9722006-06-18 05:43:12 +00002944 case '\n':
2945 case '\r':
2946 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002947 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002948 if (ParsingPreprocessorDirective) {
2949 // Done parsing the "line".
2950 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002951
Chris Lattner457fc152006-07-29 06:30:25 +00002952 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002953 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002954 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002955
Chris Lattner22eb9722006-06-18 05:43:12 +00002956 // Since we consumed a newline, we are back at the start of a line.
2957 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002958 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002959
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002960 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002961 break;
2962 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002963
Chris Lattner22eb9722006-06-18 05:43:12 +00002964 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002965 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002966
Eli Friedman0834a4b2013-09-19 00:41:32 +00002967 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2968 return true; // KeepWhitespaceMode
2969
2970 // We only saw whitespace, so just try again with this lexer.
2971 // (We manually eliminate the tail call to avoid recursion.)
2972 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00002973 case ' ':
2974 case '\t':
2975 case '\f':
2976 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002977 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00002978 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002979 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2980 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00002981
2982 SkipIgnoredUnits:
2983 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002984
Chris Lattnerb9b85972007-07-22 06:29:05 +00002985 // If the next token is obviously a // or /* */ comment, skip it efficiently
2986 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00002987 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00002988 LangOpts.LineComment &&
2989 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002990 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
2991 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002992 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00002993 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002994 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
2995 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002996 goto SkipIgnoredUnits;
2997 } else if (isHorizontalWhitespace(*CurPtr)) {
2998 goto SkipHorizontalWhitespace;
2999 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003000 // We only saw whitespace, so just try again with this lexer.
3001 // (We manually eliminate the tail call to avoid recursion.)
3002 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003003
Chris Lattner2b15cf72008-01-03 17:58:54 +00003004 // C99 6.4.4.1: Integer Constants.
3005 // C99 6.4.4.2: Floating Constants.
3006 case '0': case '1': case '2': case '3': case '4':
3007 case '5': case '6': case '7': case '8': case '9':
3008 // Notify MIOpt that we read a non-whitespace/non-comment token.
3009 MIOpt.ReadToken();
3010 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003011
Richard Smith9b362092013-03-09 23:56:02 +00003012 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003013 // Notify MIOpt that we read a non-whitespace/non-comment token.
3014 MIOpt.ReadToken();
3015
Richard Smith9b362092013-03-09 23:56:02 +00003016 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003017 Char = getCharAndSize(CurPtr, SizeTmp);
3018
3019 // UTF-16 string literal
3020 if (Char == '"')
3021 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3022 tok::utf16_string_literal);
3023
3024 // UTF-16 character constant
3025 if (Char == '\'')
3026 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3027 tok::utf16_char_constant);
3028
Craig Topper54edcca2011-08-11 04:06:15 +00003029 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003030 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3031 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003032 return LexRawStringLiteral(Result,
3033 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3034 SizeTmp2, Result),
3035 tok::utf16_string_literal);
3036
3037 if (Char == '8') {
3038 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3039
3040 // UTF-8 string literal
3041 if (Char2 == '"')
3042 return LexStringLiteral(Result,
3043 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3044 SizeTmp2, Result),
3045 tok::utf8_string_literal);
3046
Richard Smith9b362092013-03-09 23:56:02 +00003047 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003048 unsigned SizeTmp3;
3049 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3050 // UTF-8 raw string literal
3051 if (Char3 == '"') {
3052 return LexRawStringLiteral(Result,
3053 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3054 SizeTmp2, Result),
3055 SizeTmp3, Result),
3056 tok::utf8_string_literal);
3057 }
3058 }
3059 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003060 }
3061
3062 // treat u like the start of an identifier.
3063 return LexIdentifier(Result, CurPtr);
3064
Richard Smith9b362092013-03-09 23:56:02 +00003065 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003066 // Notify MIOpt that we read a non-whitespace/non-comment token.
3067 MIOpt.ReadToken();
3068
Richard Smith9b362092013-03-09 23:56:02 +00003069 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003070 Char = getCharAndSize(CurPtr, SizeTmp);
3071
3072 // UTF-32 string literal
3073 if (Char == '"')
3074 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3075 tok::utf32_string_literal);
3076
3077 // UTF-32 character constant
3078 if (Char == '\'')
3079 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3080 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003081
3082 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003083 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3084 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003085 return LexRawStringLiteral(Result,
3086 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3087 SizeTmp2, Result),
3088 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003089 }
3090
3091 // treat U like the start of an identifier.
3092 return LexIdentifier(Result, CurPtr);
3093
Craig Topper54edcca2011-08-11 04:06:15 +00003094 case 'R': // Identifier or C++0x raw string literal
3095 // Notify MIOpt that we read a non-whitespace/non-comment token.
3096 MIOpt.ReadToken();
3097
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003098 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003099 Char = getCharAndSize(CurPtr, SizeTmp);
3100
3101 if (Char == '"')
3102 return LexRawStringLiteral(Result,
3103 ConsumeChar(CurPtr, SizeTmp, Result),
3104 tok::string_literal);
3105 }
3106
3107 // treat R like the start of an identifier.
3108 return LexIdentifier(Result, CurPtr);
3109
Chris Lattner2b15cf72008-01-03 17:58:54 +00003110 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003111 // Notify MIOpt that we read a non-whitespace/non-comment token.
3112 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003113 Char = getCharAndSize(CurPtr, SizeTmp);
3114
3115 // Wide string literal.
3116 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003117 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003118 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003119
Craig Topper54edcca2011-08-11 04:06:15 +00003120 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003121 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003122 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3123 return LexRawStringLiteral(Result,
3124 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3125 SizeTmp2, Result),
3126 tok::wide_string_literal);
3127
Chris Lattner22eb9722006-06-18 05:43:12 +00003128 // Wide character constant.
3129 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003130 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3131 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003132 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattner22eb9722006-06-18 05:43:12 +00003134 // C99 6.4.2: Identifiers.
3135 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3136 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003137 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003138 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3139 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3140 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003141 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003142 case 'v': case 'w': case 'x': case 'y': case 'z':
3143 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003144 // Notify MIOpt that we read a non-whitespace/non-comment token.
3145 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003146 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003147
3148 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003149 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003150 if (!isLexingRawMode())
3151 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003152 // Notify MIOpt that we read a non-whitespace/non-comment token.
3153 MIOpt.ReadToken();
3154 return LexIdentifier(Result, CurPtr);
3155 }
Mike Stump11289f42009-09-09 15:08:12 +00003156
Chris Lattnerb11c3232008-10-12 04:51:35 +00003157 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003158 break;
Mike Stump11289f42009-09-09 15:08:12 +00003159
Chris Lattner22eb9722006-06-18 05:43:12 +00003160 // C99 6.4.4: Character Constants.
3161 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003162 // Notify MIOpt that we read a non-whitespace/non-comment token.
3163 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003164 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003165
3166 // C99 6.4.5: String Literals.
3167 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003168 // Notify MIOpt that we read a non-whitespace/non-comment token.
3169 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003170 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003171
3172 // C99 6.4.6: Punctuators.
3173 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003174 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003175 break;
3176 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003177 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003178 break;
3179 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003180 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003181 break;
3182 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003183 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003184 break;
3185 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003186 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 break;
3188 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003189 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003190 break;
3191 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003192 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003193 break;
3194 case '.':
3195 Char = getCharAndSize(CurPtr, SizeTmp);
3196 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003197 // Notify MIOpt that we read a non-whitespace/non-comment token.
3198 MIOpt.ReadToken();
3199
Chris Lattner22eb9722006-06-18 05:43:12 +00003200 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003201 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003202 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003203 CurPtr += SizeTmp;
3204 } else if (Char == '.' &&
3205 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003206 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003207 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3208 SizeTmp2, Result);
3209 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003210 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003211 }
3212 break;
3213 case '&':
3214 Char = getCharAndSize(CurPtr, SizeTmp);
3215 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003216 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003217 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3218 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003219 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003220 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3221 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003222 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003223 }
3224 break;
Mike Stump11289f42009-09-09 15:08:12 +00003225 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003226 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003227 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003228 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3229 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003230 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003231 }
3232 break;
3233 case '+':
3234 Char = getCharAndSize(CurPtr, SizeTmp);
3235 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003236 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003237 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003238 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003239 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003240 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003241 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003242 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003243 }
3244 break;
3245 case '-':
3246 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003247 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003248 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003249 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003250 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003251 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003252 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3253 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003254 Kind = tok::arrowstar;
3255 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003256 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003257 Kind = tok::arrow;
3258 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003259 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003260 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003261 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003262 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003263 }
3264 break;
3265 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003266 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003267 break;
3268 case '!':
3269 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003270 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003271 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3272 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003273 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003274 }
3275 break;
3276 case '/':
3277 // 6.4.9: Comments
3278 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003279 if (Char == '/') { // Line comment.
3280 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003281 // want to lex this as a comment. There is one problem with this though,
3282 // that in one particular corner case, this can change the behavior of the
3283 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003284 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003285 // "foo". Check to see if the character after the second slash is a '*'.
3286 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003287 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003288 bool TreatAsComment = LangOpts.LineComment &&
3289 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003290 if (!TreatAsComment)
3291 if (!(PP && PP->isPreprocessedOutput()))
3292 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3293
3294 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003295 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3296 TokAtPhysicalStartOfLine))
3297 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003298
Chris Lattner58827712009-01-16 22:39:25 +00003299 // It is common for the tokens immediately after a // comment to be
3300 // whitespace (indentation for the next line). Instead of going through
3301 // the big switch, handle it efficiently now.
3302 goto SkipIgnoredUnits;
3303 }
3304 }
Mike Stump11289f42009-09-09 15:08:12 +00003305
Chris Lattner58827712009-01-16 22:39:25 +00003306 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003307 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3308 TokAtPhysicalStartOfLine))
3309 return true; // There is a token to return.
3310
3311 // We only saw whitespace, so just try again with this lexer.
3312 // (We manually eliminate the tail call to avoid recursion.)
3313 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003314 }
Mike Stump11289f42009-09-09 15:08:12 +00003315
Chris Lattner58827712009-01-16 22:39:25 +00003316 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003317 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003318 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003319 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003320 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003321 }
3322 break;
3323 case '%':
3324 Char = getCharAndSize(CurPtr, SizeTmp);
3325 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003326 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003327 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003328 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003329 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003331 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003332 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003333 Char = getCharAndSize(CurPtr, SizeTmp);
3334 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003335 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003336 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3337 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003338 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003339 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003340 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003341 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003342 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003343 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003344 // We parsed a # character. If this occurs at the start of the line,
3345 // it's actually the start of a preprocessing directive. Callback to
3346 // the preprocessor to handle it.
3347 // FIXME: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003348 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003349 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003350
Chris Lattner2534324a2009-03-18 20:58:27 +00003351 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003352 }
3353 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003354 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003355 }
3356 break;
3357 case '<':
3358 Char = getCharAndSize(CurPtr, SizeTmp);
3359 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003360 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003361 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003362 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3363 if (After == '=') {
3364 Kind = tok::lesslessequal;
3365 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3366 SizeTmp2, Result);
3367 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3368 // If this is actually a '<<<<<<<' version control conflict marker,
3369 // recognize it as such and recover nicely.
3370 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003371 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3372 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3373 // ignore it.
3374 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003375 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003376 Kind = tok::lesslessless;
3377 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3378 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003379 } else {
3380 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3381 Kind = tok::lessless;
3382 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003383 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003384 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003385 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003386 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003387 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003388 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3389 // C++0x [lex.pptoken]p3:
3390 // Otherwise, if the next three characters are <:: and the subsequent
3391 // character is neither : nor >, the < is treated as a preprocessor
3392 // token by itself and not as the first character of the alternative
3393 // token <:.
3394 unsigned SizeTmp3;
3395 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3396 if (After != ':' && After != '>') {
3397 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003398 if (!isLexingRawMode())
3399 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003400 break;
3401 }
3402 }
3403
Chris Lattner22eb9722006-06-18 05:43:12 +00003404 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003405 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003406 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003407 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003408 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003409 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003410 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 }
3412 break;
3413 case '>':
3414 Char = getCharAndSize(CurPtr, SizeTmp);
3415 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003416 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003417 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003418 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003419 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3420 if (After == '=') {
3421 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3422 SizeTmp2, Result);
3423 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003424 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3425 // If this is actually a '>>>>' conflict marker, recognize it as such
3426 // and recover nicely.
3427 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003428 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3429 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3430 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003431 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003432 Kind = tok::greatergreatergreater;
3433 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3434 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003435 } else {
3436 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3437 Kind = tok::greatergreater;
3438 }
3439
Chris Lattner22eb9722006-06-18 05:43:12 +00003440 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003441 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003442 }
3443 break;
3444 case '^':
3445 Char = getCharAndSize(CurPtr, SizeTmp);
3446 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003448 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003449 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003450 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003451 }
3452 break;
3453 case '|':
3454 Char = getCharAndSize(CurPtr, SizeTmp);
3455 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003456 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003457 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3458 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003459 // If this is '|||||||' and we're in a conflict marker, ignore it.
3460 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3461 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003462 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003463 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3464 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003465 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003466 }
3467 break;
3468 case ':':
3469 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003470 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003471 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003473 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003474 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003475 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003476 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003477 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 }
3479 break;
3480 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003481 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003482 break;
3483 case '=':
3484 Char = getCharAndSize(CurPtr, SizeTmp);
3485 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003486 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003487 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3488 goto LexNextToken;
3489
Chris Lattnerb11c3232008-10-12 04:51:35 +00003490 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003491 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003492 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003493 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003494 }
3495 break;
3496 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003497 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003498 break;
3499 case '#':
3500 Char = getCharAndSize(CurPtr, SizeTmp);
3501 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003502 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003503 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003504 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003505 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003506 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003507 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003508 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003509 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003510 // We parsed a # character. If this occurs at the start of the line,
3511 // it's actually the start of a preprocessing directive. Callback to
3512 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00003513 // FIXME: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003514 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003515 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003516
Chris Lattner2534324a2009-03-18 20:58:27 +00003517 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003518 }
3519 break;
3520
Chris Lattner2b15cf72008-01-03 17:58:54 +00003521 case '@':
3522 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003524 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003525 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003526 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003527 break;
Mike Stump11289f42009-09-09 15:08:12 +00003528
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003529 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003530 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003531 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3532 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3533 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3534 return true; // KeepWhitespaceMode
3535
3536 // We only saw whitespace, so just try again with this lexer.
3537 // (We manually eliminate the tail call to avoid recursion.)
3538 goto LexNextToken;
3539 }
3540
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003541 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003542 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003543
Chris Lattnerb11c3232008-10-12 04:51:35 +00003544 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003545 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003546
3547 default: {
3548 if (isASCII(Char)) {
3549 Kind = tok::unknown;
3550 break;
3551 }
3552
3553 UTF32 CodePoint;
3554
3555 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3556 // an escaped newline.
3557 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003558 ConversionResult Status =
3559 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3560 (const UTF8 *)BufferEnd,
3561 &CodePoint,
3562 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003563 if (Status == conversionOK) {
3564 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3565 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3566 return true; // KeepWhitespaceMode
3567
3568 // We only saw whitespace, so just try again with this lexer.
3569 // (We manually eliminate the tail call to avoid recursion.)
3570 goto LexNextToken;
3571 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003572 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003573 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003574
Jordan Rosecc538342013-01-31 19:48:48 +00003575 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3576 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003577 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003578 Kind = tok::unknown;
3579 break;
3580 }
3581
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003582 // Non-ASCII characters tend to creep into source code unintentionally.
3583 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003584 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003585 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003586
3587 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003588 // We're pretending the character didn't exist, so just try again with
3589 // this lexer.
3590 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003591 goto LexNextToken;
3592 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003593 }
Mike Stump11289f42009-09-09 15:08:12 +00003594
Chris Lattner371ac8a2006-07-04 07:11:10 +00003595 // Notify MIOpt that we read a non-whitespace/non-comment token.
3596 MIOpt.ReadToken();
3597
Chris Lattnerd01e2912006-06-18 16:22:51 +00003598 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003599 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003600 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003601
3602HandleDirective:
3603 // We parsed a # character and it's the start of a preprocessing directive.
3604
3605 FormTokenWithChars(Result, CurPtr, tok::hash);
3606 PP->HandleDirective(Result);
3607
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003608 if (PP->hadModuleLoaderFatalFailure()) {
3609 // With a fatal failure in the module loader, we abort parsing.
3610 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003611 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003612 }
3613
Eli Friedman0834a4b2013-09-19 00:41:32 +00003614 // We parsed the directive; lex a token with the new state.
3615 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003616}