blob: d8a5160e95d50eee1f6c7cadf4136a64d0b91470 [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
Chris Lattnerd01e2912006-06-18 16:22:51 +00001609 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001610 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001611 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001612 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001613 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001614}
1615
Richard Smithe18f0fa2012-03-05 04:02:15 +00001616/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001617/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001618const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1619 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001620 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001621
1622 // Maximally munch an identifier. FIXME: UCNs.
1623 unsigned Size;
1624 char C = getCharAndSize(CurPtr, Size);
1625 if (isIdentifierHead(C)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001626 if (!getLangOpts().CPlusPlus11) {
Richard Smith3e4a60a2012-03-07 03:13:00 +00001627 if (!isLexingRawMode())
Richard Smith0df56f42012-03-08 02:39:21 +00001628 Diag(CurPtr,
1629 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1630 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1631 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1632 return CurPtr;
1633 }
1634
1635 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1636 // that does not start with an underscore is ill-formed. As a conforming
1637 // extension, we treat all such suffixes as if they had whitespace before
1638 // them.
Richard Smithf4198b72013-07-23 08:14:48 +00001639 bool IsUDSuffix = false;
1640 if (C == '_')
1641 IsUDSuffix = true;
Richard Smith2a988622013-09-24 04:06:10 +00001642 else if (IsStringLiteral && getLangOpts().CPlusPlus1y) {
1643 // In C++1y, we need to look ahead a few characters to see if this is a
1644 // valid suffix for a string literal or a numeric literal (this could be
1645 // the 'operator""if' defining a numeric literal operator).
1646 const int MaxStandardSuffixLength = 3;
1647 char Buffer[MaxStandardSuffixLength] = { C };
1648 unsigned Consumed = Size;
1649 unsigned Chars = 1;
1650 while (true) {
1651 unsigned NextSize;
1652 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1653 getLangOpts());
1654 if (!isIdentifierBody(Next)) {
1655 // End of suffix. Check whether this is on the whitelist.
1656 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1657 NumericLiteralParser::isValidUDSuffix(
1658 getLangOpts(), StringRef(Buffer, Chars));
1659 break;
1660 }
1661
1662 if (Chars == MaxStandardSuffixLength)
1663 // Too long: can't be a standard suffix.
1664 break;
1665
1666 Buffer[Chars++] = Next;
1667 Consumed += NextSize;
1668 }
Richard Smithf4198b72013-07-23 08:14:48 +00001669 }
1670
1671 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001672 if (!isLexingRawMode())
Richard Smithf4198b72013-07-23 08:14:48 +00001673 Diag(CurPtr, getLangOpts().MicrosoftMode ?
Francois Pichet7ebc4c12012-04-07 23:09:23 +00001674 diag::ext_ms_reserved_user_defined_literal :
1675 diag::ext_reserved_user_defined_literal)
Richard Smith3e4a60a2012-03-07 03:13:00 +00001676 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1677 return CurPtr;
1678 }
1679
Richard Smithd67aea22012-03-06 03:21:47 +00001680 Result.setFlag(Token::HasUDSuffix);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001681 do {
1682 CurPtr = ConsumeChar(CurPtr, Size, Result);
1683 C = getCharAndSize(CurPtr, Size);
1684 } while (isIdentifierBody(C));
1685 }
1686 return CurPtr;
1687}
1688
Chris Lattner22eb9722006-06-18 05:43:12 +00001689/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001690/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001691bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001692 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001693 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001694
Richard Smithacd4d3d2011-10-15 01:18:56 +00001695 if (!isLexingRawMode() &&
1696 (Kind == tok::utf8_string_literal ||
1697 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001698 Kind == tok::utf32_string_literal))
1699 Diag(BufferPtr, getLangOpts().CPlusPlus
1700 ? diag::warn_cxx98_compat_unicode_literal
1701 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001702
Chris Lattner22eb9722006-06-18 05:43:12 +00001703 char C = getAndAdvanceChar(CurPtr, Result);
1704 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001705 // Skip escaped characters. Escaped newlines will already be processed by
1706 // getAndAdvanceChar.
1707 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001708 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001709
Chris Lattner52d96ac2010-05-30 23:27:38 +00001710 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001711 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001712 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001713 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001714 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001715 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001716 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001717
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001718 if (C == 0) {
1719 if (isCodeCompletionPoint(CurPtr-1)) {
1720 PP->CodeCompleteNaturalLanguage();
1721 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001722 cutOffLexing();
1723 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001724 }
1725
Chris Lattner52d96ac2010-05-30 23:27:38 +00001726 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001727 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001728 C = getAndAdvanceChar(CurPtr, Result);
1729 }
Mike Stump11289f42009-09-09 15:08:12 +00001730
Richard Smithe18f0fa2012-03-05 04:02:15 +00001731 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001732 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001733 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001734
Chris Lattner5a78a022006-07-20 06:02:19 +00001735 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001736 if (NulCharacter && !isLexingRawMode())
1737 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001738
Chris Lattnerd01e2912006-06-18 16:22:51 +00001739 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001740 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001741 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001742 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001743 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001744}
1745
Craig Topper54edcca2011-08-11 04:06:15 +00001746/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1747/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001748bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001749 tok::TokenKind Kind) {
1750 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1751 // Between the initial and final double quote characters of the raw string,
1752 // any transformations performed in phases 1 and 2 (trigraphs,
1753 // universal-character-names, and line splicing) are reverted.
1754
Richard Smithacd4d3d2011-10-15 01:18:56 +00001755 if (!isLexingRawMode())
1756 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1757
Craig Topper54edcca2011-08-11 04:06:15 +00001758 unsigned PrefixLen = 0;
1759
1760 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1761 ++PrefixLen;
1762
1763 // If the last character was not a '(', then we didn't lex a valid delimiter.
1764 if (CurPtr[PrefixLen] != '(') {
1765 if (!isLexingRawMode()) {
1766 const char *PrefixEnd = &CurPtr[PrefixLen];
1767 if (PrefixLen == 16) {
1768 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1769 } else {
1770 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1771 << StringRef(PrefixEnd, 1);
1772 }
1773 }
1774
1775 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1776 // it's possible the '"' was intended to be part of the raw string, but
1777 // there's not much we can do about that.
1778 while (1) {
1779 char C = *CurPtr++;
1780
1781 if (C == '"')
1782 break;
1783 if (C == 0 && CurPtr-1 == BufferEnd) {
1784 --CurPtr;
1785 break;
1786 }
1787 }
1788
1789 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001790 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001791 }
1792
1793 // Save prefix and move CurPtr past it
1794 const char *Prefix = CurPtr;
1795 CurPtr += PrefixLen + 1; // skip over prefix and '('
1796
1797 while (1) {
1798 char C = *CurPtr++;
1799
1800 if (C == ')') {
1801 // Check for prefix match and closing quote.
1802 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1803 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1804 break;
1805 }
1806 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1807 if (!isLexingRawMode())
1808 Diag(BufferPtr, diag::err_unterminated_raw_string)
1809 << StringRef(Prefix, PrefixLen);
1810 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001811 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001812 }
1813 }
1814
Richard Smithe18f0fa2012-03-05 04:02:15 +00001815 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001816 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001817 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001818
Craig Topper54edcca2011-08-11 04:06:15 +00001819 // Update the location of token as well as BufferPtr.
1820 const char *TokStart = BufferPtr;
1821 FormTokenWithChars(Result, CurPtr, Kind);
1822 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001823 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001824}
1825
Chris Lattner22eb9722006-06-18 05:43:12 +00001826/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1827/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001828bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001829 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001830 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001831 char C = getAndAdvanceChar(CurPtr, Result);
1832 while (C != '>') {
1833 // Skip escaped characters.
1834 if (C == '\\') {
1835 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001836 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001837 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001838 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1839 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001840 // If the filename is unterminated, then it must just be a lone <
1841 // character. Return this as such.
1842 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001843 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001844 } else if (C == 0) {
1845 NulCharacter = CurPtr-1;
1846 }
1847 C = getAndAdvanceChar(CurPtr, Result);
1848 }
Mike Stump11289f42009-09-09 15:08:12 +00001849
Chris Lattner5a78a022006-07-20 06:02:19 +00001850 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001851 if (NulCharacter && !isLexingRawMode())
1852 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Chris Lattnerd01e2912006-06-18 16:22:51 +00001854 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001855 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001856 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001857 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001858 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001859}
1860
1861
1862/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001863/// lexed either ' or L' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001864bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001865 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001866 const char *NulCharacter = 0; // Does this character contain the \0 character?
1867
Richard Smithacd4d3d2011-10-15 01:18:56 +00001868 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001869 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1870 Diag(BufferPtr, getLangOpts().CPlusPlus
1871 ? diag::warn_cxx98_compat_unicode_literal
1872 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001873
Chris Lattner22eb9722006-06-18 05:43:12 +00001874 char C = getAndAdvanceChar(CurPtr, Result);
1875 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001876 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001877 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001878 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001879 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001880 }
1881
1882 while (C != '\'') {
1883 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001884 if (C == '\\')
1885 C = getAndAdvanceChar(CurPtr, Result);
1886
1887 if (C == '\n' || C == '\r' || // Newline.
1888 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001889 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001890 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001891 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001892 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001893 }
1894
1895 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001896 if (isCodeCompletionPoint(CurPtr-1)) {
1897 PP->CodeCompleteNaturalLanguage();
1898 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001899 cutOffLexing();
1900 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001901 }
1902
Chris Lattner86851b82010-07-07 23:24:27 +00001903 NulCharacter = CurPtr-1;
1904 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001905 C = getAndAdvanceChar(CurPtr, Result);
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Richard Smithe18f0fa2012-03-05 04:02:15 +00001908 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001909 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001910 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001911
Chris Lattner86851b82010-07-07 23:24:27 +00001912 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001913 if (NulCharacter && !isLexingRawMode())
1914 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001915
Chris Lattnerd01e2912006-06-18 16:22:51 +00001916 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001917 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001918 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001919 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001920 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001921}
1922
1923/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1924/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001925///
1926/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1927///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001928bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1929 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001930 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001931 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1932
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001933 unsigned char Char = *CurPtr;
1934
1935 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001936 while (1) {
1937 // Skip horizontal whitespace very aggressively.
1938 while (isHorizontalWhitespace(Char))
1939 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001940
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001941 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001942 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001943 break;
Mike Stump11289f42009-09-09 15:08:12 +00001944
Chris Lattner22eb9722006-06-18 05:43:12 +00001945 if (ParsingPreprocessorDirective) {
1946 // End of preprocessor directive line, let LexTokenInternal handle this.
1947 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001948 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001951 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001952 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001953 Char = *++CurPtr;
1954 }
1955
Chris Lattner4d963442008-10-12 04:05:48 +00001956 // If the client wants us to return whitespace, return it now.
1957 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001958 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001959 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001960 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001961 IsAtPhysicalStartOfLine = true;
1962 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001963 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001964 return true;
1965 }
Mike Stump11289f42009-09-09 15:08:12 +00001966
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001967 // If this isn't immediately after a newline, there is leading space.
1968 char PrevChar = CurPtr[-1];
1969 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1970
1971 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001972 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001973 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001974 TokAtPhysicalStartOfLine = true;
1975 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001976
Chris Lattner22eb9722006-06-18 05:43:12 +00001977 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001978 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001979}
1980
Nico Weber158a31a2012-11-11 07:02:14 +00001981/// We have just read the // characters from input. Skip until we find the
1982/// newline character thats terminate the comment. Then update BufferPtr and
1983/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00001984///
1985/// If we're in KeepCommentMode or any CommentHandler has inserted
1986/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001987bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
1988 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00001989 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00001990 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00001991 if (!LangOpts.LineComment && !isLexingRawMode()) {
1992 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Chris Lattner22eb9722006-06-18 05:43:12 +00001994 // Mark them enabled so we only emit one warning for this translation
1995 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00001996 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
Chris Lattner22eb9722006-06-18 05:43:12 +00001999 // Scan over the body of the comment. The common case, when scanning, is that
2000 // the comment contains normal ascii characters with nothing interesting in
2001 // them. As such, optimize for this case with the inner loop.
2002 char C;
2003 do {
2004 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002005 // Skip over characters in the fast loop.
2006 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002007 C != '\n' && C != '\r') // Newline or DOS-style newline.
2008 C = *++CurPtr;
2009
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002010 const char *NextLine = CurPtr;
2011 if (C != 0) {
2012 // We found a newline, see if it's escaped.
2013 const char *EscapePtr = CurPtr-1;
2014 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
2015 --EscapePtr;
2016
2017 if (*EscapePtr == '\\') // Escaped newline.
2018 CurPtr = EscapePtr;
2019 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2020 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2021 CurPtr = EscapePtr-2;
2022 else
2023 break; // This is a newline, we're done.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002027 // properly decode the character. Read it in raw mode to avoid emitting
2028 // diagnostics about things like trigraphs. If we see an escaped newline,
2029 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002030 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002031 bool OldRawMode = isLexingRawMode();
2032 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002033 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002034 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002035
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002036 // If we only read only one character, then no special handling is needed.
2037 // We're done and can skip forward to the newline.
2038 if (C != 0 && CurPtr == OldPtr+1) {
2039 CurPtr = NextLine;
2040 break;
2041 }
2042
Chris Lattner22eb9722006-06-18 05:43:12 +00002043 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002044 // \n, then we had an escaped newline within the comment. Emit diagnostic
2045 // unless the next line is also a // comment.
2046 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002047 for (; OldPtr != CurPtr; ++OldPtr)
2048 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002049 // Okay, we found a // comment that ends in a newline, if the next
2050 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002051 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002052 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002053 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002054 ++ForwardPtr;
2055 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2056 break;
2057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Chris Lattner6d27a162008-11-22 02:02:22 +00002059 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002060 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002061 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002062 }
2063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Douglas Gregor11583702010-08-25 17:04:25 +00002065 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002066 --CurPtr;
2067 break;
2068 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002069
2070 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2071 PP->CodeCompleteNaturalLanguage();
2072 cutOffLexing();
2073 return false;
2074 }
2075
Chris Lattner22eb9722006-06-18 05:43:12 +00002076 } while (C != '\n' && C != '\r');
2077
Chris Lattner93ddf802010-02-03 21:06:21 +00002078 // Found but did not consume the newline. Notify comment handlers about the
2079 // comment unless we're in a #if 0 block.
2080 if (PP && !isLexingRawMode() &&
2081 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2082 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002083 BufferPtr = CurPtr;
2084 return true; // A token has to be returned.
2085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Chris Lattner457fc152006-07-29 06:30:25 +00002087 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002088 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002089 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002090
2091 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002092 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002093 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002095 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002096 }
Mike Stump11289f42009-09-09 15:08:12 +00002097
Chris Lattner22eb9722006-06-18 05:43:12 +00002098 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002099 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002100 // contribute to another token), it isn't needed for correctness. Note that
2101 // this is ok even in KeepWhitespaceMode, because we would have returned the
2102 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002103 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002104
Chris Lattner22eb9722006-06-18 05:43:12 +00002105 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002106 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002107 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002108 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002109 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002110 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002111 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002112}
Chris Lattner22eb9722006-06-18 05:43:12 +00002113
Nico Weber158a31a2012-11-11 07:02:14 +00002114/// If in save-comment mode, package up this Line comment in an appropriate
2115/// way and return it.
2116bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002117 // If we're not in a preprocessor directive, just return the // comment
2118 // directly.
2119 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002120
David Blaikied5321242012-06-06 18:52:13 +00002121 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002122 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Nico Weber158a31a2012-11-11 07:02:14 +00002124 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002125 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002126 bool Invalid = false;
2127 std::string Spelling = PP->getSpelling(Result, &Invalid);
2128 if (Invalid)
2129 return true;
2130
Nico Weber158a31a2012-11-11 07:02:14 +00002131 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002132 Spelling[1] = '*'; // Change prefix to "/*".
2133 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002134
Chris Lattnerb11c3232008-10-12 04:51:35 +00002135 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002136 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002137 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002138 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002139}
2140
Chris Lattnercb283342006-06-18 06:48:37 +00002141/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002142/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2143/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002144static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002145 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002146 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002147
Chris Lattner22eb9722006-06-18 05:43:12 +00002148 // Back up off the newline.
2149 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattner22eb9722006-06-18 05:43:12 +00002151 // If this is a two-character newline sequence, skip the other character.
2152 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2153 // \n\n or \r\r -> not escaped newline.
2154 if (CurPtr[0] == CurPtr[1])
2155 return false;
2156 // \n\r or \r\n -> skip the newline.
2157 --CurPtr;
2158 }
Mike Stump11289f42009-09-09 15:08:12 +00002159
Chris Lattner22eb9722006-06-18 05:43:12 +00002160 // If we have horizontal whitespace, skip over it. We allow whitespace
2161 // between the slash and newline.
2162 bool HasSpace = false;
2163 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2164 --CurPtr;
2165 HasSpace = true;
2166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattner22eb9722006-06-18 05:43:12 +00002168 // If we have a slash, we know this is an escaped newline.
2169 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002170 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002171 } else {
2172 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002173 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2174 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002175 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002176
Chris Lattnercb283342006-06-18 06:48:37 +00002177 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002178 CurPtr -= 2;
2179
2180 // If no trigraphs are enabled, warn that we ignored this trigraph and
2181 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002182 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002183 if (!L->isLexingRawMode())
2184 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002185 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002186 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002187 if (!L->isLexingRawMode())
2188 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 }
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattner22eb9722006-06-18 05:43:12 +00002191 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002192 if (!L->isLexingRawMode())
2193 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattner22eb9722006-06-18 05:43:12 +00002195 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002196 if (HasSpace && !L->isLexingRawMode())
2197 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattnercb283342006-06-18 06:48:37 +00002199 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002200}
2201
Chris Lattneraded4a92006-10-27 04:42:31 +00002202#ifdef __SSE2__
2203#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002204#elif __ALTIVEC__
2205#include <altivec.h>
2206#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002207#endif
2208
James Dennettf442d242012-06-17 03:40:43 +00002209/// We have just read from input the / and * characters that started a comment.
2210/// Read until we find the * and / characters that terminate the comment.
2211/// Note that we don't bother decoding trigraphs or escaped newlines in block
2212/// comments, because they cannot cause the comment to end. The only thing
2213/// that can happen is the comment could end with an escaped newline between
2214/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002215///
Chris Lattner87d02082010-01-18 22:35:47 +00002216/// If we're in KeepCommentMode or any CommentHandler has inserted
2217/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002218bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2219 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002220 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002221 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002222 // optimization helps people who like to put a lot of * characters in their
2223 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002224
2225 // The first character we get with newlines and trigraphs skipped to handle
2226 // the degenerate /*/ case below correctly if the * has an escaped newline
2227 // after it.
2228 unsigned CharSize;
2229 unsigned char C = getCharAndSize(CurPtr, CharSize);
2230 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002231 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002232 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002233 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002234 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattner99e7d232008-10-12 04:19:49 +00002236 // KeepWhitespaceMode should return this broken comment as a token. Since
2237 // it isn't a well formed comment, just return it as an 'unknown' token.
2238 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002239 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002240 return true;
2241 }
Mike Stump11289f42009-09-09 15:08:12 +00002242
Chris Lattner99e7d232008-10-12 04:19:49 +00002243 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002244 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002245 }
Mike Stump11289f42009-09-09 15:08:12 +00002246
Chris Lattnerc850ad62007-07-21 23:43:37 +00002247 // Check to see if the first character after the '/*' is another /. If so,
2248 // then this slash does not end the block comment, it is part of it.
2249 if (C == '/')
2250 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002251
Chris Lattner22eb9722006-06-18 05:43:12 +00002252 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002253 // Skip over all non-interesting characters until we find end of buffer or a
2254 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002255 if (CurPtr + 24 < BufferEnd &&
2256 // If there is a code-completion point avoid the fast scan because it
2257 // doesn't check for '\0'.
2258 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002259 // While not aligned to a 16-byte boundary.
2260 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2261 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattner6cc3e362006-10-27 04:12:35 +00002263 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002264
2265#ifdef __SSE2__
Benjamin Kramer38857372011-11-22 18:56:46 +00002266 __m128i Slashes = _mm_set1_epi8('/');
2267 while (CurPtr+16 <= BufferEnd) {
Roman Divackye6377112012-09-06 15:59:27 +00002268 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2269 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002270 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002271 // Adjust the pointer to point directly after the first slash. It's
2272 // not necessary to set C here, it will be overwritten at the end of
2273 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002274 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002275 goto FoundSlash;
2276 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002277 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002278 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002279#elif __ALTIVEC__
2280 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002281 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002282 '/', '/', '/', '/', '/', '/', '/', '/'
2283 };
2284 while (CurPtr+16 <= BufferEnd &&
2285 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2286 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002287#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002288 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002289 while (CurPtr[0] != '/' &&
2290 CurPtr[1] != '/' &&
2291 CurPtr[2] != '/' &&
2292 CurPtr[3] != '/' &&
2293 CurPtr+4 < BufferEnd) {
2294 CurPtr += 4;
2295 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002296#endif
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattneraded4a92006-10-27 04:42:31 +00002298 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002299 C = *CurPtr++;
2300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattneraded4a92006-10-27 04:42:31 +00002302 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002303 while (C != '/' && C != '\0')
2304 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002305
Chris Lattner22eb9722006-06-18 05:43:12 +00002306 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002307 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002308 if (CurPtr[-2] == '*') // We found the final */. We're done!
2309 break;
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattner22eb9722006-06-18 05:43:12 +00002311 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002312 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002313 // We found the final */, though it had an escaped newline between the
2314 // * and /. We're done!
2315 break;
2316 }
2317 }
2318 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2319 // If this is a /* inside of the comment, emit a warning. Don't do this
2320 // if this is a /*/, which will end the comment. This misses cases with
2321 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002322 if (!isLexingRawMode())
2323 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002324 }
2325 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002326 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002327 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002328 // Note: the user probably forgot a */. We could continue immediately
2329 // after the /*, but this would involve lexing a lot of what really is the
2330 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002331 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002332
Chris Lattner99e7d232008-10-12 04:19:49 +00002333 // KeepWhitespaceMode should return this broken comment as a token. Since
2334 // it isn't a well formed comment, just return it as an 'unknown' token.
2335 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002336 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002337 return true;
2338 }
Mike Stump11289f42009-09-09 15:08:12 +00002339
Chris Lattner99e7d232008-10-12 04:19:49 +00002340 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002341 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002342 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2343 PP->CodeCompleteNaturalLanguage();
2344 cutOffLexing();
2345 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002346 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002347
Chris Lattner22eb9722006-06-18 05:43:12 +00002348 C = *CurPtr++;
2349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Chris Lattner93ddf802010-02-03 21:06:21 +00002351 // Notify comment handlers about the comment unless we're in a #if 0 block.
2352 if (PP && !isLexingRawMode() &&
2353 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2354 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002355 BufferPtr = CurPtr;
2356 return true; // A token has to be returned.
2357 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002358
Chris Lattner457fc152006-07-29 06:30:25 +00002359 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002360 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002361 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002362 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002363 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002364
2365 // It is common for the tokens immediately after a /**/ comment to be
2366 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002367 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2368 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002369 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002370 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002371 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002372 }
2373
2374 // Otherwise, just return so that the next character will be lexed as a token.
2375 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002376 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002377 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002378}
2379
2380//===----------------------------------------------------------------------===//
2381// Primary Lexing Entry Points
2382//===----------------------------------------------------------------------===//
2383
Chris Lattner22eb9722006-06-18 05:43:12 +00002384/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2385/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002386void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002387 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2388 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002389 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002390
2391 // CurPtr - Cache BufferPtr in an automatic variable.
2392 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002393 while (1) {
2394 char Char = getAndAdvanceChar(CurPtr, Tmp);
2395 switch (Char) {
2396 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002397 if (Result)
2398 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002399 break;
2400 case 0: // Null.
2401 // Found end of file?
2402 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002403 if (isCodeCompletionPoint(CurPtr-1)) {
2404 PP->CodeCompleteNaturalLanguage();
2405 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002406 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002407 }
2408
Chris Lattner22eb9722006-06-18 05:43:12 +00002409 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002410 if (Result)
2411 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002412 break;
2413 }
2414 // FALL THROUGH.
2415 case '\r':
2416 case '\n':
2417 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2418 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2419 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002420
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002421 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002422 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002423 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002424 if (PP)
2425 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002426 Lex(Tmp);
2427 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002428 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002429
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002430 // Finally, we're done;
2431 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002432 }
2433 }
2434}
2435
2436/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2437/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002438/// This returns true if Result contains a token, false if PP.Lex should be
2439/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002440bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002441 // If we hit the end of the file while parsing a preprocessor directive,
2442 // end the preprocessor directive first. The next token returned will
2443 // then be the end of file.
2444 if (ParsingPreprocessorDirective) {
2445 // Done parsing the "line".
2446 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002447 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002448 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002449
Chris Lattner457fc152006-07-29 06:30:25 +00002450 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002451 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002452 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002453 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002454
Chris Lattner30a2fa12006-07-19 06:31:49 +00002455 // If we are in raw mode, return this event as an EOF token. Let the caller
2456 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002457 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002458 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002459 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002460 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002461 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002462 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002463
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002464 // Issue diagnostics for unterminated #if and missing newline.
2465
Chris Lattner30a2fa12006-07-19 06:31:49 +00002466 // If we are in a #if directive, emit an error.
2467 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002468 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002469 PP->Diag(ConditionalStack.back().IfLoc,
2470 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002471 ConditionalStack.pop_back();
2472 }
Mike Stump11289f42009-09-09 15:08:12 +00002473
Chris Lattner8f96d042008-04-12 05:54:25 +00002474 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2475 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002476 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2477 DiagnosticsEngine &Diags = PP->getDiagnostics();
2478 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2479 unsigned DiagID;
2480
2481 if (LangOpts.CPlusPlus11) {
2482 // C++11 [lex.phases] 2.2 p2
2483 // Prefer the C++98 pedantic compatibility warning over the generic,
2484 // non-extension, user-requested "missing newline at EOF" warning.
2485 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_no_newline_eof,
2486 EndLoc) != DiagnosticsEngine::Ignored) {
2487 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2488 } else {
2489 DiagID = diag::warn_no_newline_eof;
2490 }
2491 } else {
2492 DiagID = diag::ext_no_newline_eof;
2493 }
2494
2495 Diag(BufferEnd, DiagID)
2496 << FixItHint::CreateInsertion(EndLoc, "\n");
2497 }
Mike Stump11289f42009-09-09 15:08:12 +00002498
Chris Lattner22eb9722006-06-18 05:43:12 +00002499 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002500
2501 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002502 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002503}
2504
Chris Lattner678c8802006-07-11 05:46:12 +00002505/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2506/// the specified lexer will return a tok::l_paren token, 0 if it is something
2507/// else and 2 if there are no more tokens in the buffer controlled by the
2508/// lexer.
2509unsigned Lexer::isNextPPTokenLParen() {
2510 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattner678c8802006-07-11 05:46:12 +00002512 // Switch to 'skipping' mode. This will ensure that we can lex a token
2513 // without emitting diagnostics, disables macro expansion, and will cause EOF
2514 // to return an EOF token instead of popping the include stack.
2515 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002516
Chris Lattner678c8802006-07-11 05:46:12 +00002517 // Save state that can be changed while lexing so that we can restore it.
2518 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002519 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002520 bool atStartOfLine = IsAtStartOfLine;
2521 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2522 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002523
Chris Lattner146762e2007-07-20 16:59:19 +00002524 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002525 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002526
Chris Lattner678c8802006-07-11 05:46:12 +00002527 // Restore state that may have changed.
2528 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002529 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002530 HasLeadingSpace = leadingSpace;
2531 IsAtStartOfLine = atStartOfLine;
2532 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002533
Chris Lattner678c8802006-07-11 05:46:12 +00002534 // Restore the lexer back to non-skipping mode.
2535 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002536
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002537 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002538 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002539 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002540}
2541
James Dennettf442d242012-06-17 03:40:43 +00002542/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002543static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2544 ConflictMarkerKind CMK) {
2545 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2546 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2547 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2548 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002549 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002550 // Must occur at start of line.
2551 if (RestOfBuffer[Pos-1] != '\r' &&
2552 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002553 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2554 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002555 continue;
2556 }
2557 return RestOfBuffer.data()+Pos;
2558 }
2559 return 0;
2560}
2561
2562/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2563/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2564/// and recover nicely. This returns true if it is a conflict marker and false
2565/// if not.
2566bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2567 // Only a conflict marker if it starts at the beginning of a line.
2568 if (CurPtr != BufferStart &&
2569 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2570 return false;
2571
Richard Smitha9e33d42011-10-12 00:37:51 +00002572 // Check to see if we have <<<<<<< or >>>>.
2573 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2574 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002575 return false;
2576
2577 // If we have a situation where we don't care about conflict markers, ignore
2578 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002579 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002580 return false;
2581
Richard Smitha9e33d42011-10-12 00:37:51 +00002582 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2583
2584 // Check to see if there is an ending marker somewhere in the buffer at the
2585 // start of a line to terminate this conflict marker.
2586 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002587 // We found a match. We are really in a conflict marker.
2588 // Diagnose this, and ignore to the end of line.
2589 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002590 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002591
2592 // Skip ahead to the end of line. We know this exists because the
2593 // end-of-conflict marker starts with \r or \n.
2594 while (*CurPtr != '\r' && *CurPtr != '\n') {
2595 assert(CurPtr != BufferEnd && "Didn't find end of line");
2596 ++CurPtr;
2597 }
2598 BufferPtr = CurPtr;
2599 return true;
2600 }
2601
2602 // No end of conflict marker found.
2603 return false;
2604}
2605
2606
Richard Smitha9e33d42011-10-12 00:37:51 +00002607/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2608/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2609/// is the end of a conflict marker. Handle it by ignoring up until the end of
2610/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002611bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2612 // Only a conflict marker if it starts at the beginning of a line.
2613 if (CurPtr != BufferStart &&
2614 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2615 return false;
2616
2617 // If we have a situation where we don't care about conflict markers, ignore
2618 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002619 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002620 return false;
2621
Richard Smitha9e33d42011-10-12 00:37:51 +00002622 // Check to see if we have the marker (4 characters in a row).
2623 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002624 if (CurPtr[i] != CurPtr[0])
2625 return false;
2626
2627 // If we do have it, search for the end of the conflict marker. This could
2628 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2629 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002630 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2631 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002632 CurPtr = End;
2633
2634 // Skip ahead to the end of line.
2635 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2636 ++CurPtr;
2637
2638 BufferPtr = CurPtr;
2639
2640 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002641 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002642 return true;
2643 }
2644
2645 return false;
2646}
2647
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002648bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2649 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002650 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002651 return Loc == PP->getCodeCompletionLoc();
2652 }
2653
2654 return false;
2655}
2656
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002657uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2658 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002659 unsigned CharSize;
2660 char Kind = getCharAndSize(StartPtr, CharSize);
2661
2662 unsigned NumHexDigits;
2663 if (Kind == 'u')
2664 NumHexDigits = 4;
2665 else if (Kind == 'U')
2666 NumHexDigits = 8;
2667 else
2668 return 0;
2669
Jordan Rosec0cba272013-01-27 20:12:04 +00002670 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002671 if (Result && !isLexingRawMode())
2672 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002673 return 0;
2674 }
2675
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002676 const char *CurPtr = StartPtr + CharSize;
2677 const char *KindLoc = &CurPtr[-1];
2678
2679 uint32_t CodePoint = 0;
2680 for (unsigned i = 0; i < NumHexDigits; ++i) {
2681 char C = getCharAndSize(CurPtr, CharSize);
2682
2683 unsigned Value = llvm::hexDigitValue(C);
2684 if (Value == -1U) {
2685 if (Result && !isLexingRawMode()) {
2686 if (i == 0) {
2687 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2688 << StringRef(KindLoc, 1);
2689 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002690 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002691
2692 // If the user wrote \U1234, suggest a fixit to \u.
2693 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002694 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002695 Diag(KindLoc, diag::note_ucn_four_not_eight)
2696 << FixItHint::CreateReplacement(URange, "u");
2697 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002698 }
2699 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002700
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002701 return 0;
2702 }
2703
2704 CodePoint <<= 4;
2705 CodePoint += Value;
2706
2707 CurPtr += CharSize;
2708 }
2709
2710 if (Result) {
2711 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002712 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002713 StartPtr = CurPtr;
2714 else
2715 while (StartPtr != CurPtr)
2716 (void)getAndAdvanceChar(StartPtr, *Result);
2717 } else {
2718 StartPtr = CurPtr;
2719 }
2720
2721 // C99 6.4.3p2: A universal character name shall not specify a character whose
2722 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2723 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2724 // C++11 [lex.charset]p2: If the hexadecimal value for a
2725 // universal-character-name corresponds to a surrogate code point (in the
2726 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2727 // if the hexadecimal value for a universal-character-name outside the
2728 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2729 // string literal corresponds to a control character (in either of the
2730 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2731 // basic source character set, the program is ill-formed.
2732 if (CodePoint < 0xA0) {
2733 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2734 return CodePoint;
2735
2736 // We don't use isLexingRawMode() here because we need to warn about bad
2737 // UCNs even when skipping preprocessing tokens in a #if block.
2738 if (Result && PP) {
2739 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2740 Diag(BufferPtr, diag::err_ucn_control_character);
2741 else {
2742 char C = static_cast<char>(CodePoint);
2743 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2744 }
2745 }
2746
2747 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002748
2749 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002750 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002751 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002752 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002753 if (Result && PP) {
2754 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2755 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2756 else
2757 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2758 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002759 return 0;
2760 }
2761
2762 return CodePoint;
2763}
2764
Eli Friedman0834a4b2013-09-19 00:41:32 +00002765bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2766 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002767 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2768 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002769 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002770 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002771 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002772 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002773
2774 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002775 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002776 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002777 return false;
2778}
Jordan Rose4246ae02013-01-24 20:50:50 +00002779
Eli Friedman0834a4b2013-09-19 00:41:32 +00002780bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002781 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2782 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2783 !PP->isPreprocessedOutput()) {
2784 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2785 makeCharRange(*this, BufferPtr, CurPtr),
2786 /*IsFirst=*/true);
2787 }
2788
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002789 MIOpt.ReadToken();
2790 return LexIdentifier(Result, CurPtr);
2791 }
2792
Jordan Rosecc538342013-01-31 19:48:48 +00002793 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2794 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002795 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002796 // Non-ASCII characters tend to creep into source code unintentionally.
2797 // Instead of letting the parser complain about the unknown token,
2798 // just drop the character.
2799 // Note that we can /only/ do this when the non-ASCII character is actually
2800 // spelled as Unicode, not written as a UCN. The standard requires that
2801 // we not throw away any possible preprocessor tokens, but there's a
2802 // loophole in the mapping of Unicode characters to basic character set
2803 // characters that allows us to map these particular characters to, say,
2804 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002805 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002806 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002807
2808 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002809 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002810 }
2811
2812 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2813 // up by accident.
2814 MIOpt.ReadToken();
2815 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002816 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002817}
2818
Eli Friedman0834a4b2013-09-19 00:41:32 +00002819void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2820 IsAtStartOfLine = Result.isAtStartOfLine();
2821 HasLeadingSpace = Result.hasLeadingSpace();
2822 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2823 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2824}
2825
2826bool Lexer::Lex(Token &Result) {
2827 // Start a new token.
2828 Result.startToken();
2829
2830 // Set up misc whitespace flags for LexTokenInternal.
2831 if (IsAtStartOfLine) {
2832 Result.setFlag(Token::StartOfLine);
2833 IsAtStartOfLine = false;
2834 }
2835
2836 if (HasLeadingSpace) {
2837 Result.setFlag(Token::LeadingSpace);
2838 HasLeadingSpace = false;
2839 }
2840
2841 if (HasLeadingEmptyMacro) {
2842 Result.setFlag(Token::LeadingEmptyMacro);
2843 HasLeadingEmptyMacro = false;
2844 }
2845
2846 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2847 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002848 bool isRawLex = isLexingRawMode();
2849 (void) isRawLex;
2850 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2851 // (After the LexTokenInternal call, the lexer might be destroyed.)
2852 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2853 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002854}
Chris Lattner22eb9722006-06-18 05:43:12 +00002855
2856/// LexTokenInternal - This implements a simple C family lexer. It is an
2857/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002858/// has a null character at the end of the file. This returns a preprocessing
2859/// token, not a normal token, as such, it is an internal interface. It assumes
2860/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002861bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002862LexNextToken:
2863 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002864 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00002865 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Chris Lattner22eb9722006-06-18 05:43:12 +00002867 // CurPtr - Cache BufferPtr in an automatic variable.
2868 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002869
Chris Lattnereb54b592006-07-10 06:34:27 +00002870 // Small amounts of horizontal whitespace is very common between tokens.
2871 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2872 ++CurPtr;
2873 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2874 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002875
Chris Lattner4d963442008-10-12 04:05:48 +00002876 // If we are keeping whitespace and other tokens, just return what we just
2877 // skipped. The next lexer invocation will return the token after the
2878 // whitespace.
2879 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002880 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002881 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002882 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002883 }
Mike Stump11289f42009-09-09 15:08:12 +00002884
Chris Lattnereb54b592006-07-10 06:34:27 +00002885 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002886 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
Chris Lattner22eb9722006-06-18 05:43:12 +00002889 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002890
Chris Lattner22eb9722006-06-18 05:43:12 +00002891 // Read a character, advancing over it.
2892 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002893 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002894
Chris Lattner22eb9722006-06-18 05:43:12 +00002895 switch (Char) {
2896 case 0: // Null.
2897 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002898 if (CurPtr-1 == BufferEnd)
2899 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002900
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002901 // Check if we are performing code completion.
2902 if (isCodeCompletionPoint(CurPtr-1)) {
2903 // Return the code-completion token.
2904 Result.startToken();
2905 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002906 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002907 }
2908
Chris Lattner6d27a162008-11-22 02:02:22 +00002909 if (!isLexingRawMode())
2910 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002911 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002912 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2913 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002914
Eli Friedman0834a4b2013-09-19 00:41:32 +00002915 // We know the lexer hasn't changed, so just try again with this lexer.
2916 // (We manually eliminate the tail call to avoid recursion.)
2917 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002918
2919 case 26: // DOS & CP/M EOF: "^Z".
2920 // If we're in Microsoft extensions mode, treat this as end of file.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002921 if (LangOpts.MicrosoftExt)
2922 return LexEndOfFile(Result, CurPtr-1);
2923
Chris Lattner3dfff972009-12-17 05:29:40 +00002924 // If Microsoft extensions are disabled, this is just random garbage.
2925 Kind = tok::unknown;
2926 break;
2927
Chris Lattner22eb9722006-06-18 05:43:12 +00002928 case '\n':
2929 case '\r':
2930 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002931 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002932 if (ParsingPreprocessorDirective) {
2933 // Done parsing the "line".
2934 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002935
Chris Lattner457fc152006-07-29 06:30:25 +00002936 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002937 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002938 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002939
Chris Lattner22eb9722006-06-18 05:43:12 +00002940 // Since we consumed a newline, we are back at the start of a line.
2941 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002942 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002943
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002944 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002945 break;
2946 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002947
Chris Lattner22eb9722006-06-18 05:43:12 +00002948 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002949 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002950
Eli Friedman0834a4b2013-09-19 00:41:32 +00002951 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2952 return true; // KeepWhitespaceMode
2953
2954 // We only saw whitespace, so just try again with this lexer.
2955 // (We manually eliminate the tail call to avoid recursion.)
2956 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00002957 case ' ':
2958 case '\t':
2959 case '\f':
2960 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002961 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00002962 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002963 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2964 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00002965
2966 SkipIgnoredUnits:
2967 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002968
Chris Lattnerb9b85972007-07-22 06:29:05 +00002969 // If the next token is obviously a // or /* */ comment, skip it efficiently
2970 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00002971 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00002972 LangOpts.LineComment &&
2973 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002974 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
2975 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002976 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00002977 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002978 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
2979 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002980 goto SkipIgnoredUnits;
2981 } else if (isHorizontalWhitespace(*CurPtr)) {
2982 goto SkipHorizontalWhitespace;
2983 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002984 // We only saw whitespace, so just try again with this lexer.
2985 // (We manually eliminate the tail call to avoid recursion.)
2986 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002987
Chris Lattner2b15cf72008-01-03 17:58:54 +00002988 // C99 6.4.4.1: Integer Constants.
2989 // C99 6.4.4.2: Floating Constants.
2990 case '0': case '1': case '2': case '3': case '4':
2991 case '5': case '6': case '7': case '8': case '9':
2992 // Notify MIOpt that we read a non-whitespace/non-comment token.
2993 MIOpt.ReadToken();
2994 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00002995
Richard Smith9b362092013-03-09 23:56:02 +00002996 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002997 // Notify MIOpt that we read a non-whitespace/non-comment token.
2998 MIOpt.ReadToken();
2999
Richard Smith9b362092013-03-09 23:56:02 +00003000 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003001 Char = getCharAndSize(CurPtr, SizeTmp);
3002
3003 // UTF-16 string literal
3004 if (Char == '"')
3005 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3006 tok::utf16_string_literal);
3007
3008 // UTF-16 character constant
3009 if (Char == '\'')
3010 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3011 tok::utf16_char_constant);
3012
Craig Topper54edcca2011-08-11 04:06:15 +00003013 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003014 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3015 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003016 return LexRawStringLiteral(Result,
3017 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3018 SizeTmp2, Result),
3019 tok::utf16_string_literal);
3020
3021 if (Char == '8') {
3022 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3023
3024 // UTF-8 string literal
3025 if (Char2 == '"')
3026 return LexStringLiteral(Result,
3027 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3028 SizeTmp2, Result),
3029 tok::utf8_string_literal);
3030
Richard Smith9b362092013-03-09 23:56:02 +00003031 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003032 unsigned SizeTmp3;
3033 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3034 // UTF-8 raw string literal
3035 if (Char3 == '"') {
3036 return LexRawStringLiteral(Result,
3037 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3038 SizeTmp2, Result),
3039 SizeTmp3, Result),
3040 tok::utf8_string_literal);
3041 }
3042 }
3043 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003044 }
3045
3046 // treat u like the start of an identifier.
3047 return LexIdentifier(Result, CurPtr);
3048
Richard Smith9b362092013-03-09 23:56:02 +00003049 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003050 // Notify MIOpt that we read a non-whitespace/non-comment token.
3051 MIOpt.ReadToken();
3052
Richard Smith9b362092013-03-09 23:56:02 +00003053 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003054 Char = getCharAndSize(CurPtr, SizeTmp);
3055
3056 // UTF-32 string literal
3057 if (Char == '"')
3058 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3059 tok::utf32_string_literal);
3060
3061 // UTF-32 character constant
3062 if (Char == '\'')
3063 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3064 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003065
3066 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003067 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3068 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003069 return LexRawStringLiteral(Result,
3070 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3071 SizeTmp2, Result),
3072 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003073 }
3074
3075 // treat U like the start of an identifier.
3076 return LexIdentifier(Result, CurPtr);
3077
Craig Topper54edcca2011-08-11 04:06:15 +00003078 case 'R': // Identifier or C++0x raw string literal
3079 // Notify MIOpt that we read a non-whitespace/non-comment token.
3080 MIOpt.ReadToken();
3081
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003082 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003083 Char = getCharAndSize(CurPtr, SizeTmp);
3084
3085 if (Char == '"')
3086 return LexRawStringLiteral(Result,
3087 ConsumeChar(CurPtr, SizeTmp, Result),
3088 tok::string_literal);
3089 }
3090
3091 // treat R like the start of an identifier.
3092 return LexIdentifier(Result, CurPtr);
3093
Chris Lattner2b15cf72008-01-03 17:58:54 +00003094 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003095 // Notify MIOpt that we read a non-whitespace/non-comment token.
3096 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003097 Char = getCharAndSize(CurPtr, SizeTmp);
3098
3099 // Wide string literal.
3100 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003101 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003102 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003103
Craig Topper54edcca2011-08-11 04:06:15 +00003104 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003105 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003106 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3107 return LexRawStringLiteral(Result,
3108 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3109 SizeTmp2, Result),
3110 tok::wide_string_literal);
3111
Chris Lattner22eb9722006-06-18 05:43:12 +00003112 // Wide character constant.
3113 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003114 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3115 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003116 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003117
Chris Lattner22eb9722006-06-18 05:43:12 +00003118 // C99 6.4.2: Identifiers.
3119 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3120 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003121 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003122 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3123 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3124 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003125 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003126 case 'v': case 'w': case 'x': case 'y': case 'z':
3127 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003128 // Notify MIOpt that we read a non-whitespace/non-comment token.
3129 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003130 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003131
3132 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003133 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003134 if (!isLexingRawMode())
3135 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003136 // Notify MIOpt that we read a non-whitespace/non-comment token.
3137 MIOpt.ReadToken();
3138 return LexIdentifier(Result, CurPtr);
3139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
Chris Lattnerb11c3232008-10-12 04:51:35 +00003141 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003142 break;
Mike Stump11289f42009-09-09 15:08:12 +00003143
Chris Lattner22eb9722006-06-18 05:43:12 +00003144 // C99 6.4.4: Character Constants.
3145 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003146 // Notify MIOpt that we read a non-whitespace/non-comment token.
3147 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003148 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003149
3150 // C99 6.4.5: String Literals.
3151 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003152 // Notify MIOpt that we read a non-whitespace/non-comment token.
3153 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003154 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003155
3156 // C99 6.4.6: Punctuators.
3157 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003158 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003159 break;
3160 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003161 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003162 break;
3163 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003164 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003165 break;
3166 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003167 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003168 break;
3169 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003170 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003171 break;
3172 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003173 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003174 break;
3175 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003176 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003177 break;
3178 case '.':
3179 Char = getCharAndSize(CurPtr, SizeTmp);
3180 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003181 // Notify MIOpt that we read a non-whitespace/non-comment token.
3182 MIOpt.ReadToken();
3183
Chris Lattner22eb9722006-06-18 05:43:12 +00003184 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003185 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003186 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 CurPtr += SizeTmp;
3188 } else if (Char == '.' &&
3189 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003190 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003191 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3192 SizeTmp2, Result);
3193 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003194 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003195 }
3196 break;
3197 case '&':
3198 Char = getCharAndSize(CurPtr, SizeTmp);
3199 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003200 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003201 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3202 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003203 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003204 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3205 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003206 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003207 }
3208 break;
Mike Stump11289f42009-09-09 15:08:12 +00003209 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003210 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003211 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003212 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3213 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003214 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003215 }
3216 break;
3217 case '+':
3218 Char = getCharAndSize(CurPtr, SizeTmp);
3219 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003220 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003221 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003222 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003223 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003224 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003225 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003226 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003227 }
3228 break;
3229 case '-':
3230 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003231 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003232 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003233 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003234 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003235 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003236 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3237 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003238 Kind = tok::arrowstar;
3239 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003240 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003241 Kind = tok::arrow;
3242 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003243 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003244 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003245 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003246 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003247 }
3248 break;
3249 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003250 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003251 break;
3252 case '!':
3253 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003254 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003255 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3256 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003257 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003258 }
3259 break;
3260 case '/':
3261 // 6.4.9: Comments
3262 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003263 if (Char == '/') { // Line comment.
3264 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003265 // want to lex this as a comment. There is one problem with this though,
3266 // that in one particular corner case, this can change the behavior of the
3267 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003268 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003269 // "foo". Check to see if the character after the second slash is a '*'.
3270 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003271 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003272 bool TreatAsComment = LangOpts.LineComment &&
3273 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003274 if (!TreatAsComment)
3275 if (!(PP && PP->isPreprocessedOutput()))
3276 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3277
3278 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003279 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3280 TokAtPhysicalStartOfLine))
3281 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chris Lattner58827712009-01-16 22:39:25 +00003283 // It is common for the tokens immediately after a // comment to be
3284 // whitespace (indentation for the next line). Instead of going through
3285 // the big switch, handle it efficiently now.
3286 goto SkipIgnoredUnits;
3287 }
3288 }
Mike Stump11289f42009-09-09 15:08:12 +00003289
Chris Lattner58827712009-01-16 22:39:25 +00003290 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003291 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3292 TokAtPhysicalStartOfLine))
3293 return true; // There is a token to return.
3294
3295 // We only saw whitespace, so just try again with this lexer.
3296 // (We manually eliminate the tail call to avoid recursion.)
3297 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003298 }
Mike Stump11289f42009-09-09 15:08:12 +00003299
Chris Lattner58827712009-01-16 22:39:25 +00003300 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003302 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003303 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003304 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003305 }
3306 break;
3307 case '%':
3308 Char = getCharAndSize(CurPtr, SizeTmp);
3309 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003310 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003311 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003312 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003313 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003314 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003315 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003316 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003317 Char = getCharAndSize(CurPtr, SizeTmp);
3318 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003319 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003320 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3321 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003322 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003323 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003324 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003325 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003326 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003327 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003328 // We parsed a # character. If this occurs at the start of the line,
3329 // it's actually the start of a preprocessing directive. Callback to
3330 // the preprocessor to handle it.
3331 // FIXME: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003332 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003333 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003334
Chris Lattner2534324a2009-03-18 20:58:27 +00003335 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003336 }
3337 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003338 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003339 }
3340 break;
3341 case '<':
3342 Char = getCharAndSize(CurPtr, SizeTmp);
3343 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003344 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003345 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003346 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3347 if (After == '=') {
3348 Kind = tok::lesslessequal;
3349 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3350 SizeTmp2, Result);
3351 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3352 // If this is actually a '<<<<<<<' version control conflict marker,
3353 // recognize it as such and recover nicely.
3354 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003355 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3356 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3357 // ignore it.
3358 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003359 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003360 Kind = tok::lesslessless;
3361 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3362 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003363 } else {
3364 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3365 Kind = tok::lessless;
3366 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003367 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003368 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003369 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003370 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003371 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003372 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3373 // C++0x [lex.pptoken]p3:
3374 // Otherwise, if the next three characters are <:: and the subsequent
3375 // character is neither : nor >, the < is treated as a preprocessor
3376 // token by itself and not as the first character of the alternative
3377 // token <:.
3378 unsigned SizeTmp3;
3379 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3380 if (After != ':' && After != '>') {
3381 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003382 if (!isLexingRawMode())
3383 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003384 break;
3385 }
3386 }
3387
Chris Lattner22eb9722006-06-18 05:43:12 +00003388 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003389 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003390 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003391 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003392 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003393 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003394 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003395 }
3396 break;
3397 case '>':
3398 Char = getCharAndSize(CurPtr, SizeTmp);
3399 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003400 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003401 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003402 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003403 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3404 if (After == '=') {
3405 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3406 SizeTmp2, Result);
3407 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003408 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3409 // If this is actually a '>>>>' conflict marker, recognize it as such
3410 // and recover nicely.
3411 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003412 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3413 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3414 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003415 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003416 Kind = tok::greatergreatergreater;
3417 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3418 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003419 } else {
3420 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3421 Kind = tok::greatergreater;
3422 }
3423
Chris Lattner22eb9722006-06-18 05:43:12 +00003424 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003425 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003426 }
3427 break;
3428 case '^':
3429 Char = getCharAndSize(CurPtr, SizeTmp);
3430 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003431 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003432 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003433 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003434 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003435 }
3436 break;
3437 case '|':
3438 Char = getCharAndSize(CurPtr, SizeTmp);
3439 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003440 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003441 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3442 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003443 // If this is '|||||||' and we're in a conflict marker, ignore it.
3444 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3445 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003446 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3448 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003449 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003450 }
3451 break;
3452 case ':':
3453 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003454 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003455 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003457 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003458 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003460 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003461 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003462 }
3463 break;
3464 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003465 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003466 break;
3467 case '=':
3468 Char = getCharAndSize(CurPtr, SizeTmp);
3469 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003470 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003471 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3472 goto LexNextToken;
3473
Chris Lattnerb11c3232008-10-12 04:51:35 +00003474 Kind = tok::equalequal;
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::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 }
3479 break;
3480 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003481 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003482 break;
3483 case '#':
3484 Char = getCharAndSize(CurPtr, SizeTmp);
3485 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003486 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003487 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003488 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003489 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003490 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003491 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003492 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003493 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003494 // We parsed a # character. If this occurs at the start of the line,
3495 // it's actually the start of a preprocessing directive. Callback to
3496 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00003497 // FIXME: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003498 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003499 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003500
Chris Lattner2534324a2009-03-18 20:58:27 +00003501 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003502 }
3503 break;
3504
Chris Lattner2b15cf72008-01-03 17:58:54 +00003505 case '@':
3506 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003507 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003508 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003509 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003510 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003511 break;
Mike Stump11289f42009-09-09 15:08:12 +00003512
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003513 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003514 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003515 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3516 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3517 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3518 return true; // KeepWhitespaceMode
3519
3520 // We only saw whitespace, so just try again with this lexer.
3521 // (We manually eliminate the tail call to avoid recursion.)
3522 goto LexNextToken;
3523 }
3524
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003525 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003526 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003527
Chris Lattnerb11c3232008-10-12 04:51:35 +00003528 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003529 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003530
3531 default: {
3532 if (isASCII(Char)) {
3533 Kind = tok::unknown;
3534 break;
3535 }
3536
3537 UTF32 CodePoint;
3538
3539 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3540 // an escaped newline.
3541 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003542 ConversionResult Status =
3543 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3544 (const UTF8 *)BufferEnd,
3545 &CodePoint,
3546 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003547 if (Status == conversionOK) {
3548 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3549 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3550 return true; // KeepWhitespaceMode
3551
3552 // We only saw whitespace, so just try again with this lexer.
3553 // (We manually eliminate the tail call to avoid recursion.)
3554 goto LexNextToken;
3555 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003556 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003557 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003558
Jordan Rosecc538342013-01-31 19:48:48 +00003559 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3560 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003561 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003562 Kind = tok::unknown;
3563 break;
3564 }
3565
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003566 // Non-ASCII characters tend to creep into source code unintentionally.
3567 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003568 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003569 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003570
3571 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003572 // We're pretending the character didn't exist, so just try again with
3573 // this lexer.
3574 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003575 goto LexNextToken;
3576 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003577 }
Mike Stump11289f42009-09-09 15:08:12 +00003578
Chris Lattner371ac8a2006-07-04 07:11:10 +00003579 // Notify MIOpt that we read a non-whitespace/non-comment token.
3580 MIOpt.ReadToken();
3581
Chris Lattnerd01e2912006-06-18 16:22:51 +00003582 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003583 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003584 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003585
3586HandleDirective:
3587 // We parsed a # character and it's the start of a preprocessing directive.
3588
3589 FormTokenWithChars(Result, CurPtr, tok::hash);
3590 PP->HandleDirective(Result);
3591
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003592 if (PP->hadModuleLoaderFatalFailure()) {
3593 // With a fatal failure in the module loader, we abort parsing.
3594 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003595 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003596 }
3597
Eli Friedman0834a4b2013-09-19 00:41:32 +00003598 // We parsed the directive; lex a token with the new state.
3599 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003600}