blob: 2570755cbdefbb5e6d6c04c3d99068bc84a3b023 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner146762e2007-07-20 16:59:19 +000010// This file implements the Lexer and Token interfaces.
Chris Lattner22eb9722006-06-18 05:43:12 +000011//
12//===----------------------------------------------------------------------===//
13//
14// TODO: GCC Diagnostics emitted by the lexer:
15// PEDWARN: (form feed|vertical tab) in preprocessing directive
16//
17// Universal characters, unicode, char mapping:
18// WARNING: `%.*s' is not in NFKC
19// WARNING: `%.*s' is not in NFC
20//
21// Other:
Chris Lattner22eb9722006-06-18 05:43:12 +000022// TODO: Options to support:
23// -fexec-charset,-fwide-exec-charset
24//
25//===----------------------------------------------------------------------===//
26
27#include "clang/Lex/Lexer.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000028#include "clang/Basic/CharInfo.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000029#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/CodeCompletionHandler.h"
31#include "clang/Lex/LexDiagnostic.h"
32#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +000033#include "llvm/ADT/STLExtras.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000034#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Chris Lattner739e7392007-04-29 07:12:06 +000038#include "llvm/Support/MemoryBuffer.h"
Jordan Rose58c61e02013-02-09 01:10:25 +000039#include "UnicodeCharSets.h"
Craig Topper54edcca2011-08-11 04:06:15 +000040#include <cstring>
Chris Lattner22eb9722006-06-18 05:43:12 +000041using namespace clang;
42
Chris Lattner4894f482007-10-07 08:47:24 +000043//===----------------------------------------------------------------------===//
44// Token Class Implementation
45//===----------------------------------------------------------------------===//
46
Mike Stump11289f42009-09-09 15:08:12 +000047/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000048bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000049 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
51 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000052}
53
54/// getObjCKeywordID - Return the ObjC keyword kind.
55tok::ObjCKeywordKind Token::getObjCKeywordID() const {
56 IdentifierInfo *specId = getIdentifierInfo();
57 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
58}
59
Chris Lattner67671ed2007-12-13 01:59:49 +000060
Chris Lattner4894f482007-10-07 08:47:24 +000061//===----------------------------------------------------------------------===//
62// Lexer Class Implementation
63//===----------------------------------------------------------------------===//
64
David Blaikie68e081d2011-12-20 02:48:34 +000065void Lexer::anchor() { }
66
Mike Stump11289f42009-09-09 15:08:12 +000067void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000068 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattnerf76b9202009-01-17 06:55:17 +000073 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000076
Eric Christopher7f36a792011-04-09 00:01:04 +000077 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000084 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
85 .Default(0);
86
87 // Skip the BOM.
88 BufferPtr += BOMLength;
89 }
90
Chris Lattnerf76b9202009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000093
Chris Lattnerf76b9202009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000096 IsAtPhysicalStartOfLine = true;
97
98 HasLeadingSpace = false;
99 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattnerf76b9202009-01-17 06:55:17 +0000101 // We are not after parsing a #.
102 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Chris Lattnerf76b9202009-01-17 06:55:17 +0000104 // We are not after parsing #include.
105 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattnerf76b9202009-01-17 06:55:17 +0000107 // We are not in raw mode. Raw mode disables diagnostics and interpretation
108 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
109 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
110 // or otherwise skipping over tokens.
111 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattnerf76b9202009-01-17 06:55:17 +0000113 // Default to not keeping comments.
114 ExtendedTokenMode = 0;
115}
116
Chris Lattner5965a282009-01-17 07:56:59 +0000117/// Lexer constructor - Create a new lexer object for the specified buffer
118/// with the specified preprocessor managing the lexing process. This lexer
119/// assumes that the associated file buffer and Preprocessor objects will
120/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000121Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000122 : PreprocessorLexer(&PP, FID),
123 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000124 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000125
Chris Lattner5965a282009-01-17 07:56:59 +0000126 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
127 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000128
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000129 resetExtendedTokenMode();
130}
131
132void Lexer::resetExtendedTokenMode() {
133 assert(PP && "Cannot reset token mode without a preprocessor");
134 if (LangOpts.TraditionalCPP)
135 SetKeepWhitespaceMode(true);
136 else
137 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000138}
Chris Lattner4894f482007-10-07 08:47:24 +0000139
Chris Lattner02b436a2007-10-17 20:41:00 +0000140/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000141/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000142/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000143Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000144 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000145 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000146
Chris Lattnerf76b9202009-01-17 06:55:17 +0000147 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000148
Chris Lattner02b436a2007-10-17 20:41:00 +0000149 // We *are* in raw mode.
150 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000151}
152
Chris Lattner08354fe2009-01-17 07:35:14 +0000153/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000154/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000155/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000156Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000157 const SourceManager &SM, const LangOptions &langOpts)
158 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
Chris Lattner08354fe2009-01-17 07:35:14 +0000159
Mike Stump11289f42009-09-09 15:08:12 +0000160 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
Chris Lattner08354fe2009-01-17 07:35:14 +0000161 FromFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000162
Chris Lattner08354fe2009-01-17 07:35:14 +0000163 // We *are* in raw mode.
164 LexingRawMode = true;
165}
166
Chris Lattner757169b2009-01-17 08:27:52 +0000167/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
168/// _Pragma expansion. This has a variety of magic semantics that this method
169/// sets up. It returns a new'd Lexer that must be delete'd when done.
170///
171/// On entrance to this routine, TokStartLoc is a macro location which has a
172/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000173/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000174/// "expanded from".
175///
176/// FIXME: It would really be nice to make _Pragma just be a wrapper around a
177/// normal lexer that remaps tokens as they fly by. This would require making
178/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
179/// interface that could handle this stuff. This would pull GetMappedTokenLoc
180/// out of the critical path of the lexer!
181///
Mike Stump11289f42009-09-09 15:08:12 +0000182Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000183 SourceLocation ExpansionLocStart,
184 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000185 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000186 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000187
188 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000189 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000190 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
191 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000192
Chris Lattner757169b2009-01-17 08:27:52 +0000193 // Now that the lexer is created, change the start/end locations so that we
194 // just lex the subsection of the file that we want. This is lexing from a
195 // scratch buffer.
196 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner757169b2009-01-17 08:27:52 +0000198 L->BufferPtr = StrData;
199 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000200 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000201
202 // Set the SourceLocation with the remapping information. This ensures that
203 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000204 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
205 ExpansionLocStart,
206 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000207
Chris Lattner757169b2009-01-17 08:27:52 +0000208 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000209 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000210 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattner757169b2009-01-17 08:27:52 +0000212 // This lexer really is for _Pragma.
213 L->Is_PragmaLexer = true;
214 return L;
215}
216
Chris Lattner02b436a2007-10-17 20:41:00 +0000217
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000218/// Stringify - Convert the specified string into a C string, with surrounding
219/// ""'s, and with escaped \ and " characters.
Chris Lattnerecc39e92006-07-15 05:23:31 +0000220std::string Lexer::Stringify(const std::string &Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000221 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000222 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000223 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000224 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000225 Result.insert(Result.begin()+i, '\\');
226 ++i; ++e;
227 }
228 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000229 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000230}
231
Chris Lattner4c4a2452007-07-24 06:57:14 +0000232/// Stringify - Convert the specified string into a C string by escaping '\'
233/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000234void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000235 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
236 if (Str[i] == '\\' || Str[i] == '"') {
237 Str.insert(Str.begin()+i, '\\');
238 ++i; ++e;
239 }
240 }
241}
242
Chris Lattner39720112010-11-17 07:26:20 +0000243//===----------------------------------------------------------------------===//
244// Token Spelling
245//===----------------------------------------------------------------------===//
246
Richard Smith9a67f472012-11-28 07:29:00 +0000247/// \brief Slow case of getSpelling. Extract the characters comprising the
248/// spelling of this token from the provided input buffer.
249static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
250 const LangOptions &LangOpts, char *Spelling) {
251 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
252
253 size_t Length = 0;
254 const char *BufEnd = BufPtr + Tok.getLength();
255
256 if (Tok.is(tok::string_literal)) {
257 // Munch the encoding-prefix and opening double-quote.
258 while (BufPtr < BufEnd) {
259 unsigned Size;
260 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
261 BufPtr += Size;
262
263 if (Spelling[Length - 1] == '"')
264 break;
265 }
266
267 // Raw string literals need special handling; trigraph expansion and line
268 // splicing do not occur within their d-char-sequence nor within their
269 // r-char-sequence.
270 if (Length >= 2 &&
271 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
272 // Search backwards from the end of the token to find the matching closing
273 // quote.
274 const char *RawEnd = BufEnd;
275 do --RawEnd; while (*RawEnd != '"');
276 size_t RawLength = RawEnd - BufPtr + 1;
277
278 // Everything between the quotes is included verbatim in the spelling.
279 memcpy(Spelling + Length, BufPtr, RawLength);
280 Length += RawLength;
281 BufPtr += RawLength;
282
283 // The rest of the token is lexed normally.
284 }
285 }
286
287 while (BufPtr < BufEnd) {
288 unsigned Size;
289 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
290 BufPtr += Size;
291 }
292
293 assert(Length < Tok.getLength() &&
294 "NeedsCleaning flag set on token that didn't need cleaning!");
295 return Length;
296}
297
Chris Lattner39720112010-11-17 07:26:20 +0000298/// getSpelling() - Return the 'spelling' of this token. The spelling of a
299/// token are the characters used to represent the token in the source file
300/// after trigraph expansion and escaped-newline folding. In particular, this
301/// wants to get the true, uncanonicalized, spelling of things like digraphs
302/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000304 SmallVectorImpl<char> &buffer,
305 const SourceManager &SM,
306 const LangOptions &options,
307 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000308 // Break down the source location.
309 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
310
311 // Try to the load the file buffer.
312 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000313 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000314 if (invalidTemp) {
315 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000316 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000317 }
318
319 const char *tokenBegin = file.data() + locInfo.second;
320
321 // Lex from the start of the given location.
322 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
323 file.begin(), tokenBegin, file.end());
324 Token token;
325 lexer.LexFromRawLexer(token);
326
327 unsigned length = token.getLength();
328
329 // Common case: no need for cleaning.
330 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000331 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000332
Richard Smith9a67f472012-11-28 07:29:00 +0000333 // Hard case, we need to relex the characters into the string.
334 buffer.resize(length);
335 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000337}
338
339/// getSpelling() - Return the 'spelling' of this token. The spelling of a
340/// token are the characters used to represent the token in the source file
341/// after trigraph expansion and escaped-newline folding. In particular, this
342/// wants to get the true, uncanonicalized, spelling of things like digraphs
343/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000344std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000345 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000346 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000347
Chris Lattner39720112010-11-17 07:26:20 +0000348 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000349 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000350 &CharDataInvalid);
351 if (Invalid)
352 *Invalid = CharDataInvalid;
353 if (CharDataInvalid)
354 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000355
356 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000357 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000358 return std::string(TokStart, TokStart + Tok.getLength());
359
Chris Lattner39720112010-11-17 07:26:20 +0000360 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000361 Result.resize(Tok.getLength());
362 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000363 return Result;
364}
365
366/// getSpelling - This method is used to get the spelling of a token into a
367/// preallocated buffer, instead of as an std::string. The caller is required
368/// to allocate enough space for the token, which is guaranteed to be at least
369/// Tok.getLength() bytes long. The actual length of the token is returned.
370///
371/// Note that this method may do two possible things: it may either fill in
372/// the buffer specified with characters, or it may *change the input pointer*
373/// to point to a constant buffer with the data already in it (avoiding a
374/// copy). The caller is not allowed to modify the returned buffer pointer
375/// if an internal buffer is returned.
376unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
377 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000378 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000379 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000380
381 const char *TokStart = 0;
382 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
383 if (Tok.is(tok::raw_identifier))
384 TokStart = Tok.getRawIdentifierData();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000385 else if (!Tok.hasUCN()) {
386 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
387 // Just return the string from the identifier table, which is very quick.
388 Buffer = II->getNameStart();
389 return II->getLength();
390 }
Chris Lattner39720112010-11-17 07:26:20 +0000391 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000392
393 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000394 if (Tok.isLiteral())
395 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000396
Chris Lattner39720112010-11-17 07:26:20 +0000397 if (TokStart == 0) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000398 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000399 bool CharDataInvalid = false;
400 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
401 if (Invalid)
402 *Invalid = CharDataInvalid;
403 if (CharDataInvalid) {
404 Buffer = "";
405 return 0;
406 }
407 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000408
Chris Lattner39720112010-11-17 07:26:20 +0000409 // If this token contains nothing interesting, return it directly.
410 if (!Tok.needsCleaning()) {
411 Buffer = TokStart;
412 return Tok.getLength();
413 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000414
Chris Lattner39720112010-11-17 07:26:20 +0000415 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000416 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000417}
418
419
Chris Lattner8e129c22007-10-17 21:18:47 +0000420/// MeasureTokenLength - Relex the token at the specified location and return
421/// its length in bytes in the input file. If the token needs cleaning (e.g.
422/// includes a trigraph or an escaped newline) then this count includes bytes
423/// that are part of that.
424unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000425 const SourceManager &SM,
426 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000427 Token TheTok;
428 if (getRawToken(Loc, TheTok, SM, LangOpts))
429 return 0;
430 return TheTok.getLength();
431}
432
433/// \brief Relex the token at the specified location.
434/// \returns true if there was a failure, false on success.
435bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
436 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000437 const LangOptions &LangOpts,
438 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000439 // TODO: this could be special cased for common tokens like identifiers, ')',
440 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000441 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000442 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
443 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000444
445 // If this comes from a macro expansion, we really do want the macro name, not
446 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000447 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000448 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000449 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000450 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000451 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000452 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000453
454 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000455
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000456 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000457 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000458
Chris Lattner8e129c22007-10-17 21:18:47 +0000459 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000460 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
461 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000462 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000463 TheLexer.LexFromRawLexer(Result);
464 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000465}
466
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000467static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
468 const SourceManager &SM,
469 const LangOptions &LangOpts) {
470 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000471 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000472 if (LocInfo.first.isInvalid())
473 return Loc;
474
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000475 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000477 if (Invalid)
478 return Loc;
479
480 // Back up from the current location until we hit the beginning of a line
481 // (or the buffer). We'll relex from that point.
482 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000483 if (LocInfo.second >= Buffer.size())
484 return Loc;
485
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000486 const char *StrData = BufStart+LocInfo.second;
487 if (StrData[0] == '\n' || StrData[0] == '\r')
488 return Loc;
489
490 const char *LexStart = StrData;
491 while (LexStart != BufStart) {
492 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
493 ++LexStart;
494 break;
495 }
496
497 --LexStart;
498 }
499
500 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000501 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000502 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
503 TheLexer.SetCommentRetentionState(true);
504
505 // Lex tokens until we find the token that contains the source location.
506 Token TheTok;
507 do {
508 TheLexer.LexFromRawLexer(TheTok);
509
510 if (TheLexer.getBufferLocation() > StrData) {
511 // Lexing this token has taken the lexer past the source location we're
512 // looking for. If the current token encompasses our source location,
513 // return the beginning of that token.
514 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
515 return TheTok.getLocation();
516
517 // We ended up skipping over the source location entirely, which means
518 // that it points into whitespace. We're done here.
519 break;
520 }
521 } while (TheTok.getKind() != tok::eof);
522
523 // We've passed our source location; just return the original source location.
524 return Loc;
525}
526
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000527SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
528 const SourceManager &SM,
529 const LangOptions &LangOpts) {
530 if (Loc.isFileID())
531 return getBeginningOfFileToken(Loc, SM, LangOpts);
532
533 if (!SM.isMacroArgExpansion(Loc))
534 return Loc;
535
536 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
537 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
538 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000539 std::pair<FileID, unsigned> BeginFileLocInfo
540 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000541 assert(FileLocInfo.first == BeginFileLocInfo.first &&
542 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000543 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000544}
545
Douglas Gregoraf82e352010-07-20 20:18:03 +0000546namespace {
547 enum PreambleDirectiveKind {
548 PDK_Skipped,
549 PDK_StartIf,
550 PDK_EndIf,
551 PDK_Unknown
552 };
553}
554
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000555std::pair<unsigned, bool>
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000556Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000557 const LangOptions &LangOpts, unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000558 // Create a lexer starting at the beginning of the file. Note that we use a
559 // "fake" file source location at offset 1 so that the lexer will track our
560 // position within the file.
561 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000562 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
563 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
Douglas Gregoraf82e352010-07-20 20:18:03 +0000564 Buffer->getBufferStart(), Buffer->getBufferEnd());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000565 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000566
567 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
568 SourceLocation StartLoc = TheLexer.getSourceLocation();
569
Douglas Gregoraf82e352010-07-20 20:18:03 +0000570 bool InPreprocessorDirective = false;
571 Token TheTok;
572 Token IfStartTok;
573 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000574 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000575
576 unsigned MaxLineOffset = 0;
577 if (MaxLines) {
578 const char *CurPtr = Buffer->getBufferStart();
579 unsigned CurLine = 0;
580 while (CurPtr != Buffer->getBufferEnd()) {
581 char ch = *CurPtr++;
582 if (ch == '\n') {
583 ++CurLine;
584 if (CurLine == MaxLines)
585 break;
586 }
587 }
588 if (CurPtr != Buffer->getBufferEnd())
589 MaxLineOffset = CurPtr - Buffer->getBufferStart();
590 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000591
Douglas Gregoraf82e352010-07-20 20:18:03 +0000592 do {
593 TheLexer.LexFromRawLexer(TheTok);
594
595 if (InPreprocessorDirective) {
596 // If we've hit the end of the file, we're done.
597 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000598 break;
599 }
600
601 // If we haven't hit the end of the preprocessor directive, skip this
602 // token.
603 if (!TheTok.isAtStartOfLine())
604 continue;
605
606 // We've passed the end of the preprocessor directive, and will look
607 // at this token again below.
608 InPreprocessorDirective = false;
609 }
610
Douglas Gregor028d3e42010-08-09 20:45:32 +0000611 // Keep track of the # of lines in the preamble.
612 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000613 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000614
615 // If we were asked to limit the number of lines in the preamble,
616 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000617 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000618 break;
619 }
620
Douglas Gregoraf82e352010-07-20 20:18:03 +0000621 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000622 if (TheTok.getKind() == tok::comment) {
623 if (ActiveCommentLoc.isInvalid())
624 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000625 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000626 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000627
628 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
629 // This is the start of a preprocessor directive.
630 Token HashTok = TheTok;
631 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000632 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000633
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000634 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000635 // we don't have an identifier table available. Instead, just look at
636 // the raw identifier to recognize and categorize preprocessor directives.
637 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000638 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000639 StringRef Keyword(TheTok.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000640 TheTok.getLength());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000641 PreambleDirectiveKind PDK
642 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
643 .Case("include", PDK_Skipped)
644 .Case("__include_macros", PDK_Skipped)
645 .Case("define", PDK_Skipped)
646 .Case("undef", PDK_Skipped)
647 .Case("line", PDK_Skipped)
648 .Case("error", PDK_Skipped)
649 .Case("pragma", PDK_Skipped)
650 .Case("import", PDK_Skipped)
651 .Case("include_next", PDK_Skipped)
652 .Case("warning", PDK_Skipped)
653 .Case("ident", PDK_Skipped)
654 .Case("sccs", PDK_Skipped)
655 .Case("assert", PDK_Skipped)
656 .Case("unassert", PDK_Skipped)
657 .Case("if", PDK_StartIf)
658 .Case("ifdef", PDK_StartIf)
659 .Case("ifndef", PDK_StartIf)
660 .Case("elif", PDK_Skipped)
661 .Case("else", PDK_Skipped)
662 .Case("endif", PDK_EndIf)
663 .Default(PDK_Unknown);
664
665 switch (PDK) {
666 case PDK_Skipped:
667 continue;
668
669 case PDK_StartIf:
670 if (IfCount == 0)
671 IfStartTok = HashTok;
672
673 ++IfCount;
674 continue;
675
676 case PDK_EndIf:
677 // Mismatched #endif. The preamble ends here.
678 if (IfCount == 0)
679 break;
680
681 --IfCount;
682 continue;
683
684 case PDK_Unknown:
685 // We don't know what this directive is; stop at the '#'.
686 break;
687 }
688 }
689
690 // We only end up here if we didn't recognize the preprocessor
691 // directive or it was one that can't occur in the preamble at this
692 // point. Roll back the current token to the location of the '#'.
693 InPreprocessorDirective = false;
694 TheTok = HashTok;
695 }
696
Douglas Gregor028d3e42010-08-09 20:45:32 +0000697 // We hit a token that we don't recognize as being in the
698 // "preprocessing only" part of the file, so we're no longer in
699 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000700 break;
701 } while (true);
702
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000703 SourceLocation End;
704 if (IfCount)
705 End = IfStartTok.getLocation();
706 else if (ActiveCommentLoc.isValid())
707 End = ActiveCommentLoc; // don't truncate a decl comment.
708 else
709 End = TheTok.getLocation();
710
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000711 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
712 IfCount? IfStartTok.isAtStartOfLine()
713 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000714}
715
Chris Lattner2a6ee912010-11-17 07:05:50 +0000716
717/// AdvanceToTokenCharacter - Given a location that specifies the start of a
718/// token, return a new location that specifies a character within the token.
719SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
720 unsigned CharNo,
721 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000723 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000724 // character is. This needs to take into consideration newlines and
725 // trigraphs.
726 bool Invalid = false;
727 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
728
729 // If they request the first char of the token, we're trivially done.
730 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
731 return TokStart;
732
733 unsigned PhysOffset = 0;
734
735 // The usual case is that tokens don't contain anything interesting. Skip
736 // over the uninteresting characters. If a token only consists of simple
737 // chars, this method is extremely fast.
738 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
739 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000740 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000741 ++TokPtr, --CharNo, ++PhysOffset;
742 }
743
744 // If we have a character that may be a trigraph or escaped newline, use a
745 // lexer to parse it correctly.
746 for (; CharNo; --CharNo) {
747 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000748 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000749 TokPtr += Size;
750 PhysOffset += Size;
751 }
752
753 // Final detail: if we end up on an escaped newline, we want to return the
754 // location of the actual byte of the token. For example foo\<newline>bar
755 // advanced by 3 should return the location of b, not of \\. One compounding
756 // detail of this is that the escape may be made by a trigraph.
757 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
758 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
759
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000760 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000761}
762
763/// \brief Computes the source location just past the end of the
764/// token at this source location.
765///
766/// This routine can be used to produce a source location that
767/// points just past the end of the token referenced by \p Loc, and
768/// is generally used when a diagnostic needs to point just after a
769/// token where it expected something different that it received. If
770/// the returned source location would not be meaningful (e.g., if
771/// it points into a macro), this routine returns an invalid
772/// source location.
773///
774/// \param Offset an offset from the end of the token, where the source
775/// location should refer to. The default offset (0) produces a source
776/// location pointing just past the end of the token; an offset of 1 produces
777/// a source location pointing to the last character in the token, etc.
778SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
779 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000780 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000781 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000782 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000783
784 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000786 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000787 }
788
David Blaikiebbafb8a2012-03-11 07:00:24 +0000789 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000790 if (Len > Offset)
791 Len = Len - Offset;
792 else
793 return Loc;
794
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000795 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000796}
797
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000798/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000799/// token of the macro expansion.
800bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000801 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000802 const LangOptions &LangOpts,
803 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000804 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
805
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000806 SourceLocation expansionLoc;
807 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
808 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000809
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000810 if (expansionLoc.isFileID()) {
811 // No other macro expansions, this is the first.
812 if (MacroBegin)
813 *MacroBegin = expansionLoc;
814 return true;
815 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000816
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000817 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000818}
819
820/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000821/// token of the macro expansion.
822bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000823 const SourceManager &SM,
824 const LangOptions &LangOpts,
825 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000826 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
827
828 SourceLocation spellLoc = SM.getSpellingLoc(loc);
829 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
830 if (tokLen == 0)
831 return false;
832
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000833 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
834 SourceLocation expansionLoc;
835 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
836 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000837
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000838 if (expansionLoc.isFileID()) {
839 // No other macro expansions.
840 if (MacroEnd)
841 *MacroEnd = expansionLoc;
842 return true;
843 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000844
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000845 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000846}
847
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000848static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000849 const SourceManager &SM,
850 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000851 SourceLocation Begin = Range.getBegin();
852 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000853 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000854 if (Range.isTokenRange()) {
855 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
856 if (End.isInvalid())
857 return CharSourceRange();
858 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000859
860 // Break down the source locations.
861 FileID FID;
862 unsigned BeginOffs;
863 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
864 if (FID.isInvalid())
865 return CharSourceRange();
866
867 unsigned EndOffs;
868 if (!SM.isInFileID(End, FID, &EndOffs) ||
869 BeginOffs > EndOffs)
870 return CharSourceRange();
871
872 return CharSourceRange::getCharRange(Begin, End);
873}
874
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000875CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000876 const SourceManager &SM,
877 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000878 SourceLocation Begin = Range.getBegin();
879 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000880 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000881 return CharSourceRange();
882
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000883 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000884 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000885
886 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000887 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
888 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 Range.setBegin(Begin);
890 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000891 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000892
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000893 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000894 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
895 &End)) ||
896 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
897 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000898 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000899 Range.setEnd(End);
900 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000901 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000902
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000903 assert(Begin.isMacroID() && End.isMacroID());
904 SourceLocation MacroBegin, MacroEnd;
905 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000906 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
907 &MacroEnd)) ||
908 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
909 &MacroEnd)))) {
910 Range.setBegin(MacroBegin);
911 Range.setEnd(MacroEnd);
912 return makeRangeFromFileLocs(Range, SM, LangOpts);
913 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000914
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000915 bool Invalid = false;
916 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
917 &Invalid);
918 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000919 return CharSourceRange();
920
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000921 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
922 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
923 &Invalid);
924 if (Invalid)
925 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000926
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000927 if (EndEntry.getExpansion().isMacroArgExpansion() &&
928 BeginEntry.getExpansion().getExpansionLocStart() ==
929 EndEntry.getExpansion().getExpansionLocStart()) {
930 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
931 Range.setEnd(SM.getImmediateSpellingLoc(End));
932 return makeFileCharRange(Range, SM, LangOpts);
933 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000934 }
935
936 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000937}
938
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000939StringRef Lexer::getSourceText(CharSourceRange Range,
940 const SourceManager &SM,
941 const LangOptions &LangOpts,
942 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000943 Range = makeFileCharRange(Range, SM, LangOpts);
944 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000945 if (Invalid) *Invalid = true;
946 return StringRef();
947 }
948
949 // Break down the source location.
950 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
951 if (beginInfo.first.isInvalid()) {
952 if (Invalid) *Invalid = true;
953 return StringRef();
954 }
955
956 unsigned EndOffs;
957 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
958 beginInfo.second > EndOffs) {
959 if (Invalid) *Invalid = true;
960 return StringRef();
961 }
962
963 // Try to the load the file buffer.
964 bool invalidTemp = false;
965 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
966 if (invalidTemp) {
967 if (Invalid) *Invalid = true;
968 return StringRef();
969 }
970
971 if (Invalid) *Invalid = false;
972 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
973}
974
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000975StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
976 const SourceManager &SM,
977 const LangOptions &LangOpts) {
978 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000979
980 // Find the location of the immediate macro expansion.
981 while (1) {
982 FileID FID = SM.getFileID(Loc);
983 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
984 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
985 Loc = Expansion.getExpansionLocStart();
986 if (!Expansion.isMacroArgExpansion())
987 break;
988
989 // For macro arguments we need to check that the argument did not come
990 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
991
992 // Loc points to the argument id of the macro definition, move to the
993 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000994 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000995 SourceLocation SpellLoc = Expansion.getSpellingLoc();
996 if (SpellLoc.isFileID())
997 break; // No inner macro.
998
999 // If spelling location resides in the same FileID as macro expansion
1000 // location, it means there is no inner macro.
1001 FileID MacroFID = SM.getFileID(Loc);
1002 if (SM.isInFileID(SpellLoc, MacroFID))
1003 break;
1004
1005 // Argument came from inner macro.
1006 Loc = SpellLoc;
1007 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001008
1009 // Find the spelling location of the start of the non-argument expansion
1010 // range. This is where the macro name was spelled in order to begin
1011 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001012 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001013
1014 // Dig out the buffer where the macro name was spelled and the extents of the
1015 // name so that we can render it into the expansion note.
1016 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1017 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1018 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1019 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1020}
1021
Jordan Rose288c4212012-06-07 01:10:31 +00001022bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001023 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001024}
1025
Chris Lattnerd01e2912006-06-18 16:22:51 +00001026
Chris Lattner22eb9722006-06-18 05:43:12 +00001027//===----------------------------------------------------------------------===//
1028// Diagnostics forwarding code.
1029//===----------------------------------------------------------------------===//
1030
Chris Lattner619c1742007-07-22 18:38:25 +00001031/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001032/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001033/// This is currently only used for _Pragma implementation, so it is the slow
1034/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001035static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1036 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001037static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1038 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001039 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001040 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattner619c1742007-07-22 18:38:25 +00001042 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001043 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001044 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001045 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001047 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001048 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001049 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001050 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattner9dc9c202009-02-15 20:52:18 +00001052 // Figure out the expansion loc range, which is the range covered by the
1053 // original _Pragma(...) sequence.
1054 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001055 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001056
Chandler Carruth115b0772011-07-26 03:03:05 +00001057 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001058}
1059
Chris Lattner22eb9722006-06-18 05:43:12 +00001060/// getSourceLocation - Return a source location identifier for the specified
1061/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001062SourceLocation Lexer::getSourceLocation(const char *Loc,
1063 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001064 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001065 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001066
1067 // In the normal case, we're just lexing from a simple file buffer, return
1068 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001069 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001070 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001071 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattnerd32480d2009-01-17 06:22:33 +00001073 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1074 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001075 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001076 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001077}
1078
Chris Lattner22eb9722006-06-18 05:43:12 +00001079/// Diag - Forwarding function for diagnostics. This translate a source
1080/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001081DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001082 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001083}
1084
1085//===----------------------------------------------------------------------===//
1086// Trigraph and Escaped Newline Handling Code.
1087//===----------------------------------------------------------------------===//
1088
1089/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1090/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1091static char GetTrigraphCharForLetter(char Letter) {
1092 switch (Letter) {
1093 default: return 0;
1094 case '=': return '#';
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 }
1104}
1105
1106/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1107/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1108/// return the result character. Finally, emit a warning about trigraph use
1109/// whether trigraphs are enabled or not.
1110static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1111 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001112 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001113
David Blaikiebbafb8a2012-03-11 07:00:24 +00001114 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001115 if (!L->isLexingRawMode())
1116 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001117 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119
Chris Lattner6d27a162008-11-22 02:02:22 +00001120 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001121 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001122 return Res;
1123}
1124
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001125/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1126/// 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 +00001127/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001128unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1129 unsigned Size = 0;
1130 while (isWhitespace(Ptr[Size])) {
1131 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001132
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001133 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1134 continue;
1135
1136 // If this is a \r\n or \n\r, skip the other half.
1137 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1138 Ptr[Size-1] != Ptr[Size])
1139 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001141 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001142 }
1143
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001144 // Not an escaped newline, must be a \t or something else.
1145 return 0;
1146}
1147
Chris Lattner38b2cde2009-04-18 22:27:02 +00001148/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1149/// them), skip over them and return the first non-escaped-newline found,
1150/// otherwise return P.
1151const char *Lexer::SkipEscapedNewLines(const char *P) {
1152 while (1) {
1153 const char *AfterEscape;
1154 if (*P == '\\') {
1155 AfterEscape = P+1;
1156 } else if (*P == '?') {
1157 // If not a trigraph for escape, bail out.
1158 if (P[1] != '?' || P[2] != '/')
1159 return P;
1160 AfterEscape = P+3;
1161 } else {
1162 return P;
1163 }
Mike Stump11289f42009-09-09 15:08:12 +00001164
Chris Lattner38b2cde2009-04-18 22:27:02 +00001165 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1166 if (NewLineSize == 0) return P;
1167 P = AfterEscape+NewLineSize;
1168 }
1169}
1170
Anna Zaks59a3c802011-07-27 21:43:43 +00001171/// \brief Checks that the given token is the first token that occurs after the
1172/// given location (this excludes comments and whitespace). Returns the location
1173/// immediately after the specified token. If the token is not found or the
1174/// location is inside a macro, the returned source location will be invalid.
1175SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1176 tok::TokenKind TKind,
1177 const SourceManager &SM,
1178 const LangOptions &LangOpts,
1179 bool SkipTrailingWhitespaceAndNewLine) {
1180 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001181 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001182 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001183 }
1184 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1185
1186 // Break down the source location.
1187 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1188
1189 // Try to load the file buffer.
1190 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001191 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001192 if (InvalidTemp)
1193 return SourceLocation();
1194
1195 const char *TokenBegin = File.data() + LocInfo.second;
1196
1197 // Lex from the start of the given location.
1198 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1199 TokenBegin, File.end());
1200 // Find the token.
1201 Token Tok;
1202 lexer.LexFromRawLexer(Tok);
1203 if (Tok.isNot(TKind))
1204 return SourceLocation();
1205 SourceLocation TokenLoc = Tok.getLocation();
1206
1207 // Calculate how much whitespace needs to be skipped if any.
1208 unsigned NumWhitespaceChars = 0;
1209 if (SkipTrailingWhitespaceAndNewLine) {
1210 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1211 Tok.getLength();
1212 unsigned char C = *TokenEnd;
1213 while (isHorizontalWhitespace(C)) {
1214 C = *(++TokenEnd);
1215 NumWhitespaceChars++;
1216 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001217
1218 // Skip \r, \n, \r\n, or \n\r
1219 if (C == '\n' || C == '\r') {
1220 char PrevC = C;
1221 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001222 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001223 if ((C == '\n' || C == '\r') && C != PrevC)
1224 NumWhitespaceChars++;
1225 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001226 }
1227
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001228 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001229}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001230
Chris Lattner22eb9722006-06-18 05:43:12 +00001231/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1232/// get its size, and return it. This is tricky in several cases:
1233/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1234/// then either return the trigraph (skipping 3 chars) or the '?',
1235/// depending on whether trigraphs are enabled or not.
1236/// 2. If this is an escaped newline (potentially with whitespace between
1237/// the backslash and newline), implicitly skip the newline and return
1238/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001239///
1240/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1241/// know that we can accumulate into Size, and that we have already incremented
1242/// Ptr by Size bytes.
1243///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001244/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1245/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001246///
1247char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001248 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001249 // If we have a slash, look for an escaped newline.
1250 if (Ptr[0] == '\\') {
1251 ++Size;
1252 ++Ptr;
1253Slash:
1254 // Common case, backslash-char where the char is not whitespace.
1255 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001256
Chris Lattnerc1835952009-06-23 05:15:06 +00001257 // See if we have optional whitespace characters between the slash and
1258 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001259 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1260 // Remember that this token needs to be cleaned.
1261 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001262
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001263 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001264 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001265 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001266
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001267 // Found backslash<whitespace><newline>. Parse the char after it.
1268 Size += EscapedNewLineSize;
1269 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001270
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001271 // If the char that we finally got was a \n, then we must have had
1272 // something like \<newline><newline>. We don't want to consume the
1273 // second newline.
1274 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1275 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001276
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001277 // Use slow version to accumulate a correct size field.
1278 return getCharAndSizeSlow(Ptr, Size, Tok);
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Chris Lattner22eb9722006-06-18 05:43:12 +00001281 // Otherwise, this is not an escaped newline, just return the slash.
1282 return '\\';
1283 }
Mike Stump11289f42009-09-09 15:08:12 +00001284
Chris Lattner22eb9722006-06-18 05:43:12 +00001285 // If this is a trigraph, process it.
1286 if (Ptr[0] == '?' && Ptr[1] == '?') {
1287 // If this is actually a legal trigraph (not something like "??x"), emit
1288 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1289 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1290 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001291 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001292
1293 Ptr += 3;
1294 Size += 3;
1295 if (C == '\\') goto Slash;
1296 return C;
1297 }
1298 }
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattner22eb9722006-06-18 05:43:12 +00001300 // If this is neither, return a single character.
1301 ++Size;
1302 return *Ptr;
1303}
1304
Chris Lattnerd01e2912006-06-18 16:22:51 +00001305
Chris Lattner22eb9722006-06-18 05:43:12 +00001306/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1307/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1308/// and that we have already incremented Ptr by Size bytes.
1309///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001310/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1311/// be updated to match.
1312char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001313 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 // If we have a slash, look for an escaped newline.
1315 if (Ptr[0] == '\\') {
1316 ++Size;
1317 ++Ptr;
1318Slash:
1319 // Common case, backslash-char where the char is not whitespace.
1320 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattner22eb9722006-06-18 05:43:12 +00001322 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001323 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1324 // Found backslash<whitespace><newline>. Parse the char after it.
1325 Size += EscapedNewLineSize;
1326 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001327
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001328 // If the char that we finally got was a \n, then we must have had
1329 // something like \<newline><newline>. We don't want to consume the
1330 // second newline.
1331 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1332 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001333
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001334 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001335 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattner22eb9722006-06-18 05:43:12 +00001338 // Otherwise, this is not an escaped newline, just return the slash.
1339 return '\\';
1340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
Chris Lattner22eb9722006-06-18 05:43:12 +00001342 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001343 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001344 // If this is actually a legal trigraph (not something like "??x"), return
1345 // it.
1346 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1347 Ptr += 3;
1348 Size += 3;
1349 if (C == '\\') goto Slash;
1350 return C;
1351 }
1352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattner22eb9722006-06-18 05:43:12 +00001354 // If this is neither, return a single character.
1355 ++Size;
1356 return *Ptr;
1357}
1358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359//===----------------------------------------------------------------------===//
1360// Helper methods for lexing.
1361//===----------------------------------------------------------------------===//
1362
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001363/// \brief Routine that indiscriminately skips bytes in the source file.
1364void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1365 BufferPtr += Bytes;
1366 if (BufferPtr > BufferEnd)
1367 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001368 // FIXME: What exactly does the StartOfLine bit mean? There are two
1369 // possible meanings for the "start" of the line: the first token on the
1370 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001371 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001372 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001373}
1374
Jordan Rose58c61e02013-02-09 01:10:25 +00001375static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001376 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1377 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1378 C11AllowedIDCharRanges);
1379 return C11AllowedIDChars.contains(C);
1380 } else if (LangOpts.CPlusPlus) {
1381 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1382 CXX03AllowedIDCharRanges);
1383 return CXX03AllowedIDChars.contains(C);
1384 } else {
1385 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1386 C99AllowedIDCharRanges);
1387 return C99AllowedIDChars.contains(C);
1388 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001389}
1390
Jordan Rose58c61e02013-02-09 01:10:25 +00001391static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1392 assert(isAllowedIDChar(C, LangOpts));
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001393 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1394 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1395 C11DisallowedInitialIDCharRanges);
1396 return !C11DisallowedInitialIDChars.contains(C);
1397 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001398 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001399 } else {
1400 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1401 C99DisallowedInitialIDCharRanges);
1402 return !C99DisallowedInitialIDChars.contains(C);
1403 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001404}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001405
Jordan Rose58c61e02013-02-09 01:10:25 +00001406static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1407 const char *End) {
1408 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1409 L.getSourceLocation(End));
1410}
1411
1412static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1413 CharSourceRange Range, bool IsFirst) {
1414 // Check C99 compatibility.
1415 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1416 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1417 enum {
1418 CannotAppearInIdentifier = 0,
1419 CannotStartIdentifier
1420 };
1421
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001422 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1423 C99AllowedIDCharRanges);
1424 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1425 C99DisallowedInitialIDCharRanges);
1426 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001427 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1428 << Range
1429 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001430 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001431 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1432 << Range
1433 << CannotStartIdentifier;
1434 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001435 }
1436
Jordan Rose58c61e02013-02-09 01:10:25 +00001437 // Check C++98 compatibility.
1438 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1439 Range.getBegin()) > DiagnosticsEngine::Ignored) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001440 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1441 CXX03AllowedIDCharRanges);
1442 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001443 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1444 << Range;
1445 }
1446 }
1447 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001448
Eli Friedman0834a4b2013-09-19 00:41:32 +00001449bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001450 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1451 unsigned Size;
1452 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001453 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001454 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001455
Chris Lattner22eb9722006-06-18 05:43:12 +00001456 --CurPtr; // Back up over the skipped character.
1457
1458 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1459 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001460 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001461 // TODO: Could merge these checks into an InfoTable flag to make the
1462 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001463 if (isASCII(C) && C != '\\' && C != '?' &&
1464 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001465FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001466 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001467 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1468 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Chris Lattner0f1f5052006-07-20 04:16:23 +00001470 // If we are in raw mode, return this identifier raw. There is no need to
1471 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001472 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001473 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001474
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001475 // Fill in Result.IdentifierInfo and update the token kind,
1476 // looking up the identifier in the identifier table.
1477 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001478
Chris Lattnerc5a00062006-06-18 16:41:01 +00001479 // Finally, now that we know we have an identifier, pass this off to the
1480 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001481 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001482 return PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001483
Eli Friedman0834a4b2013-09-19 00:41:32 +00001484 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Chris Lattner22eb9722006-06-18 05:43:12 +00001487 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattner22eb9722006-06-18 05:43:12 +00001489 C = getCharAndSize(CurPtr, Size);
1490 while (1) {
1491 if (C == '$') {
1492 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001493 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001494
Chris Lattner22eb9722006-06-18 05:43:12 +00001495 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001496 if (!isLexingRawMode())
1497 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001498 CurPtr = ConsumeChar(CurPtr, Size, Result);
1499 C = getCharAndSize(CurPtr, Size);
1500 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001501
1502 } else if (C == '\\') {
1503 const char *UCNPtr = CurPtr + Size;
1504 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
Jordan Rose58c61e02013-02-09 01:10:25 +00001505 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001506 goto FinishIdentifier;
1507
Jordan Rose58c61e02013-02-09 01:10:25 +00001508 if (!isLexingRawMode()) {
1509 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1510 makeCharRange(*this, CurPtr, UCNPtr),
1511 /*IsFirst=*/false);
1512 }
1513
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001514 Result.setFlag(Token::HasUCN);
1515 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1516 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1517 CurPtr = UCNPtr;
1518 else
1519 while (CurPtr != UCNPtr)
1520 (void)getAndAdvanceChar(CurPtr, Result);
1521
1522 C = getCharAndSize(CurPtr, Size);
1523 continue;
1524 } else if (!isASCII(C)) {
1525 const char *UnicodePtr = CurPtr;
1526 UTF32 CodePoint;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00001527 ConversionResult Result =
1528 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1529 (const UTF8 *)BufferEnd,
1530 &CodePoint,
1531 strictConversion);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001532 if (Result != conversionOK ||
Jordan Rose58c61e02013-02-09 01:10:25 +00001533 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001534 goto FinishIdentifier;
1535
Jordan Rose58c61e02013-02-09 01:10:25 +00001536 if (!isLexingRawMode()) {
1537 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1538 makeCharRange(*this, CurPtr, UnicodePtr),
1539 /*IsFirst=*/false);
1540 }
1541
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001542 CurPtr = UnicodePtr;
1543 C = getCharAndSize(CurPtr, Size);
1544 continue;
1545 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001546 goto FinishIdentifier;
1547 }
1548
1549 // Otherwise, this character is good, consume it.
1550 CurPtr = ConsumeChar(CurPtr, Size, Result);
1551
1552 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001553 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001554 CurPtr = ConsumeChar(CurPtr, Size, Result);
1555 C = getCharAndSize(CurPtr, Size);
1556 }
1557 }
1558}
1559
Douglas Gregor759ef232010-08-30 14:50:47 +00001560/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001561/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001562bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001563 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001564 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001565 if (C1 != '0')
1566 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001567 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001568 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001569}
Chris Lattner22eb9722006-06-18 05:43:12 +00001570
Nate Begeman5eee9332008-04-14 02:26:39 +00001571/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001572/// constant. From[-1] is the first character lexed. Return the end of the
1573/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001574bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001575 unsigned Size;
1576 char C = getCharAndSize(CurPtr, Size);
1577 char PrevCh = 0;
Jordan Rosea2100d72013-02-08 22:30:22 +00001578 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 CurPtr = ConsumeChar(CurPtr, Size, Result);
1580 PrevCh = C;
1581 C = getCharAndSize(CurPtr, Size);
1582 }
Mike Stump11289f42009-09-09 15:08:12 +00001583
Chris Lattner22eb9722006-06-18 05:43:12 +00001584 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001585 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1586 // If we are in Microsoft mode, don't continue if the constant is hex.
1587 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001588 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001589 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1590 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001591
1592 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001593 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1594 // Outside C99, we accept hexadecimal floating point numbers as a
1595 // not-quite-conforming extension. Only do so if this looks like it's
1596 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1597 bool IsHexFloat = true;
1598 if (!LangOpts.C99) {
1599 if (!isHexaLiteral(BufferPtr, LangOpts))
1600 IsHexFloat = false;
1601 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1602 IsHexFloat = false;
1603 }
1604 if (IsHexFloat)
1605 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1606 }
Mike Stump11289f42009-09-09 15:08:12 +00001607
Chris Lattnerd01e2912006-06-18 16:22:51 +00001608 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001609 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001610 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001611 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001612 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001613}
1614
Richard Smithe18f0fa2012-03-05 04:02:15 +00001615/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001616/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001617const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1618 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001619 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001620
1621 // Maximally munch an identifier. FIXME: UCNs.
1622 unsigned Size;
1623 char C = getCharAndSize(CurPtr, Size);
1624 if (isIdentifierHead(C)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001625 if (!getLangOpts().CPlusPlus11) {
Richard Smith3e4a60a2012-03-07 03:13:00 +00001626 if (!isLexingRawMode())
Richard Smith0df56f42012-03-08 02:39:21 +00001627 Diag(CurPtr,
1628 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1629 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1630 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1631 return CurPtr;
1632 }
1633
1634 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1635 // that does not start with an underscore is ill-formed. As a conforming
1636 // extension, we treat all such suffixes as if they had whitespace before
1637 // them.
Richard Smithf4198b72013-07-23 08:14:48 +00001638 bool IsUDSuffix = false;
1639 if (C == '_')
1640 IsUDSuffix = true;
1641 else if (IsStringLiteral && C == 's' && getLangOpts().CPlusPlus1y) {
1642 // In C++1y, "s" is a valid ud-suffix for a string literal.
1643 unsigned NextSize;
1644 if (!isIdentifierBody(getCharAndSizeNoWarn(CurPtr + Size, NextSize,
1645 getLangOpts())))
1646 IsUDSuffix = true;
1647 }
1648
1649 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001650 if (!isLexingRawMode())
Richard Smithf4198b72013-07-23 08:14:48 +00001651 Diag(CurPtr, getLangOpts().MicrosoftMode ?
Francois Pichet7ebc4c12012-04-07 23:09:23 +00001652 diag::ext_ms_reserved_user_defined_literal :
1653 diag::ext_reserved_user_defined_literal)
Richard Smith3e4a60a2012-03-07 03:13:00 +00001654 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1655 return CurPtr;
1656 }
1657
Richard Smithd67aea22012-03-06 03:21:47 +00001658 Result.setFlag(Token::HasUDSuffix);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001659 do {
1660 CurPtr = ConsumeChar(CurPtr, Size, Result);
1661 C = getCharAndSize(CurPtr, Size);
1662 } while (isIdentifierBody(C));
1663 }
1664 return CurPtr;
1665}
1666
Chris Lattner22eb9722006-06-18 05:43:12 +00001667/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001668/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001669bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001670 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001671 const char *NulCharacter = 0; // Does this string contain the \0 character?
Mike Stump11289f42009-09-09 15:08:12 +00001672
Richard Smithacd4d3d2011-10-15 01:18:56 +00001673 if (!isLexingRawMode() &&
1674 (Kind == tok::utf8_string_literal ||
1675 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001676 Kind == tok::utf32_string_literal))
1677 Diag(BufferPtr, getLangOpts().CPlusPlus
1678 ? diag::warn_cxx98_compat_unicode_literal
1679 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001680
Chris Lattner22eb9722006-06-18 05:43:12 +00001681 char C = getAndAdvanceChar(CurPtr, Result);
1682 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001683 // Skip escaped characters. Escaped newlines will already be processed by
1684 // getAndAdvanceChar.
1685 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001686 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001687
Chris Lattner52d96ac2010-05-30 23:27:38 +00001688 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001689 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001690 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001691 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001692 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001693 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001694 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001695
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001696 if (C == 0) {
1697 if (isCodeCompletionPoint(CurPtr-1)) {
1698 PP->CodeCompleteNaturalLanguage();
1699 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001700 cutOffLexing();
1701 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001702 }
1703
Chris Lattner52d96ac2010-05-30 23:27:38 +00001704 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001705 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001706 C = getAndAdvanceChar(CurPtr, Result);
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708
Richard Smithe18f0fa2012-03-05 04:02:15 +00001709 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001710 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001711 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001712
Chris Lattner5a78a022006-07-20 06:02:19 +00001713 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001714 if (NulCharacter && !isLexingRawMode())
1715 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001716
Chris Lattnerd01e2912006-06-18 16:22:51 +00001717 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001718 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001719 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001720 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001721 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001722}
1723
Craig Topper54edcca2011-08-11 04:06:15 +00001724/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1725/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001726bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001727 tok::TokenKind Kind) {
1728 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1729 // Between the initial and final double quote characters of the raw string,
1730 // any transformations performed in phases 1 and 2 (trigraphs,
1731 // universal-character-names, and line splicing) are reverted.
1732
Richard Smithacd4d3d2011-10-15 01:18:56 +00001733 if (!isLexingRawMode())
1734 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1735
Craig Topper54edcca2011-08-11 04:06:15 +00001736 unsigned PrefixLen = 0;
1737
1738 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1739 ++PrefixLen;
1740
1741 // If the last character was not a '(', then we didn't lex a valid delimiter.
1742 if (CurPtr[PrefixLen] != '(') {
1743 if (!isLexingRawMode()) {
1744 const char *PrefixEnd = &CurPtr[PrefixLen];
1745 if (PrefixLen == 16) {
1746 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1747 } else {
1748 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1749 << StringRef(PrefixEnd, 1);
1750 }
1751 }
1752
1753 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1754 // it's possible the '"' was intended to be part of the raw string, but
1755 // there's not much we can do about that.
1756 while (1) {
1757 char C = *CurPtr++;
1758
1759 if (C == '"')
1760 break;
1761 if (C == 0 && CurPtr-1 == BufferEnd) {
1762 --CurPtr;
1763 break;
1764 }
1765 }
1766
1767 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001768 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001769 }
1770
1771 // Save prefix and move CurPtr past it
1772 const char *Prefix = CurPtr;
1773 CurPtr += PrefixLen + 1; // skip over prefix and '('
1774
1775 while (1) {
1776 char C = *CurPtr++;
1777
1778 if (C == ')') {
1779 // Check for prefix match and closing quote.
1780 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1781 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1782 break;
1783 }
1784 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1785 if (!isLexingRawMode())
1786 Diag(BufferPtr, diag::err_unterminated_raw_string)
1787 << StringRef(Prefix, PrefixLen);
1788 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001789 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001790 }
1791 }
1792
Richard Smithe18f0fa2012-03-05 04:02:15 +00001793 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001794 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001795 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001796
Craig Topper54edcca2011-08-11 04:06:15 +00001797 // Update the location of token as well as BufferPtr.
1798 const char *TokStart = BufferPtr;
1799 FormTokenWithChars(Result, CurPtr, Kind);
1800 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001801 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001802}
1803
Chris Lattner22eb9722006-06-18 05:43:12 +00001804/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1805/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001806bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001807 const char *NulCharacter = 0; // Does this string contain the \0 character?
Chris Lattnerb40289b2009-04-17 23:56:52 +00001808 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001809 char C = getAndAdvanceChar(CurPtr, Result);
1810 while (C != '>') {
1811 // Skip escaped characters.
1812 if (C == '\\') {
1813 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001814 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001815 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001816 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1817 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001818 // If the filename is unterminated, then it must just be a lone <
1819 // character. Return this as such.
1820 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001821 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001822 } else if (C == 0) {
1823 NulCharacter = CurPtr-1;
1824 }
1825 C = getAndAdvanceChar(CurPtr, Result);
1826 }
Mike Stump11289f42009-09-09 15:08:12 +00001827
Chris Lattner5a78a022006-07-20 06:02:19 +00001828 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001829 if (NulCharacter && !isLexingRawMode())
1830 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001831
Chris Lattnerd01e2912006-06-18 16:22:51 +00001832 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001833 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001834 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001835 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001836 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001837}
1838
1839
1840/// LexCharConstant - Lex the remainder of a character constant, after having
Douglas Gregorfb65e592011-07-27 05:40:30 +00001841/// lexed either ' or L' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001842bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001843 tok::TokenKind Kind) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001844 const char *NulCharacter = 0; // Does this character contain the \0 character?
1845
Richard Smithacd4d3d2011-10-15 01:18:56 +00001846 if (!isLexingRawMode() &&
Richard Smith06d274f2013-03-11 18:01:42 +00001847 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1848 Diag(BufferPtr, getLangOpts().CPlusPlus
1849 ? diag::warn_cxx98_compat_unicode_literal
1850 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001851
Chris Lattner22eb9722006-06-18 05:43:12 +00001852 char C = getAndAdvanceChar(CurPtr, Result);
1853 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001854 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001855 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001856 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001857 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001858 }
1859
1860 while (C != '\'') {
1861 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001862 if (C == '\\')
1863 C = getAndAdvanceChar(CurPtr, Result);
1864
1865 if (C == '\n' || C == '\r' || // Newline.
1866 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001867 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001868 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001869 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001870 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001871 }
1872
1873 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001874 if (isCodeCompletionPoint(CurPtr-1)) {
1875 PP->CodeCompleteNaturalLanguage();
1876 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001877 cutOffLexing();
1878 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001879 }
1880
Chris Lattner86851b82010-07-07 23:24:27 +00001881 NulCharacter = CurPtr-1;
1882 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001883 C = getAndAdvanceChar(CurPtr, Result);
1884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Richard Smithe18f0fa2012-03-05 04:02:15 +00001886 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001887 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001888 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001889
Chris Lattner86851b82010-07-07 23:24:27 +00001890 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001891 if (NulCharacter && !isLexingRawMode())
1892 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001893
Chris Lattnerd01e2912006-06-18 16:22:51 +00001894 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001895 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001896 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001897 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001898 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001899}
1900
1901/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1902/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001903///
1904/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1905///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001906bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1907 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001908 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001909 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1910
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001911 unsigned char Char = *CurPtr;
1912
1913 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001914 while (1) {
1915 // Skip horizontal whitespace very aggressively.
1916 while (isHorizontalWhitespace(Char))
1917 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001918
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001919 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001920 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001921 break;
Mike Stump11289f42009-09-09 15:08:12 +00001922
Chris Lattner22eb9722006-06-18 05:43:12 +00001923 if (ParsingPreprocessorDirective) {
1924 // End of preprocessor directive line, let LexTokenInternal handle this.
1925 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001926 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001927 }
Mike Stump11289f42009-09-09 15:08:12 +00001928
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001929 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001930 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001931 Char = *++CurPtr;
1932 }
1933
Chris Lattner4d963442008-10-12 04:05:48 +00001934 // If the client wants us to return whitespace, return it now.
1935 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001936 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001937 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001938 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001939 IsAtPhysicalStartOfLine = true;
1940 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001941 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001942 return true;
1943 }
Mike Stump11289f42009-09-09 15:08:12 +00001944
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001945 // If this isn't immediately after a newline, there is leading space.
1946 char PrevChar = CurPtr[-1];
1947 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1948
1949 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001950 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001951 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001952 TokAtPhysicalStartOfLine = true;
1953 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001954
Chris Lattner22eb9722006-06-18 05:43:12 +00001955 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001956 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001957}
1958
Nico Weber158a31a2012-11-11 07:02:14 +00001959/// We have just read the // characters from input. Skip until we find the
1960/// newline character thats terminate the comment. Then update BufferPtr and
1961/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00001962///
1963/// If we're in KeepCommentMode or any CommentHandler has inserted
1964/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001965bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
1966 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00001967 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00001968 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00001969 if (!LangOpts.LineComment && !isLexingRawMode()) {
1970 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattner22eb9722006-06-18 05:43:12 +00001972 // Mark them enabled so we only emit one warning for this translation
1973 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00001974 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chris Lattner22eb9722006-06-18 05:43:12 +00001977 // Scan over the body of the comment. The common case, when scanning, is that
1978 // the comment contains normal ascii characters with nothing interesting in
1979 // them. As such, optimize for this case with the inner loop.
1980 char C;
1981 do {
1982 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001983 // Skip over characters in the fast loop.
1984 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00001985 C != '\n' && C != '\r') // Newline or DOS-style newline.
1986 C = *++CurPtr;
1987
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00001988 const char *NextLine = CurPtr;
1989 if (C != 0) {
1990 // We found a newline, see if it's escaped.
1991 const char *EscapePtr = CurPtr-1;
1992 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1993 --EscapePtr;
1994
1995 if (*EscapePtr == '\\') // Escaped newline.
1996 CurPtr = EscapePtr;
1997 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1998 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1999 CurPtr = EscapePtr-2;
2000 else
2001 break; // This is a newline, we're done.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002002 }
Mike Stump11289f42009-09-09 15:08:12 +00002003
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002005 // properly decode the character. Read it in raw mode to avoid emitting
2006 // diagnostics about things like trigraphs. If we see an escaped newline,
2007 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002008 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002009 bool OldRawMode = isLexingRawMode();
2010 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002011 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002012 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002013
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002014 // If we only read only one character, then no special handling is needed.
2015 // We're done and can skip forward to the newline.
2016 if (C != 0 && CurPtr == OldPtr+1) {
2017 CurPtr = NextLine;
2018 break;
2019 }
2020
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002022 // \n, then we had an escaped newline within the comment. Emit diagnostic
2023 // unless the next line is also a // comment.
2024 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002025 for (; OldPtr != CurPtr; ++OldPtr)
2026 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002027 // Okay, we found a // comment that ends in a newline, if the next
2028 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002029 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002030 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002031 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002032 ++ForwardPtr;
2033 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2034 break;
2035 }
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattner6d27a162008-11-22 02:02:22 +00002037 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002038 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002039 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002040 }
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Douglas Gregor11583702010-08-25 17:04:25 +00002043 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002044 --CurPtr;
2045 break;
2046 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002047
2048 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2049 PP->CodeCompleteNaturalLanguage();
2050 cutOffLexing();
2051 return false;
2052 }
2053
Chris Lattner22eb9722006-06-18 05:43:12 +00002054 } while (C != '\n' && C != '\r');
2055
Chris Lattner93ddf802010-02-03 21:06:21 +00002056 // Found but did not consume the newline. Notify comment handlers about the
2057 // comment unless we're in a #if 0 block.
2058 if (PP && !isLexingRawMode() &&
2059 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2060 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002061 BufferPtr = CurPtr;
2062 return true; // A token has to be returned.
2063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Chris Lattner457fc152006-07-29 06:30:25 +00002065 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002066 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002067 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002068
2069 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002070 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002071 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002072 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002073 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
Chris Lattner22eb9722006-06-18 05:43:12 +00002076 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002077 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002078 // contribute to another token), it isn't needed for correctness. Note that
2079 // this is ok even in KeepWhitespaceMode, because we would have returned the
2080 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002081 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002082
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002084 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002085 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002086 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002087 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002088 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002089 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002090}
Chris Lattner22eb9722006-06-18 05:43:12 +00002091
Nico Weber158a31a2012-11-11 07:02:14 +00002092/// If in save-comment mode, package up this Line comment in an appropriate
2093/// way and return it.
2094bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002095 // If we're not in a preprocessor directive, just return the // comment
2096 // directly.
2097 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002098
David Blaikied5321242012-06-06 18:52:13 +00002099 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002100 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002101
Nico Weber158a31a2012-11-11 07:02:14 +00002102 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002103 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002104 bool Invalid = false;
2105 std::string Spelling = PP->getSpelling(Result, &Invalid);
2106 if (Invalid)
2107 return true;
2108
Nico Weber158a31a2012-11-11 07:02:14 +00002109 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002110 Spelling[1] = '*'; // Change prefix to "/*".
2111 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002112
Chris Lattnerb11c3232008-10-12 04:51:35 +00002113 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002114 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002115 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002116 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002117}
2118
Chris Lattnercb283342006-06-18 06:48:37 +00002119/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002120/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2121/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002122static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002123 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002124 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattner22eb9722006-06-18 05:43:12 +00002126 // Back up off the newline.
2127 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002128
Chris Lattner22eb9722006-06-18 05:43:12 +00002129 // If this is a two-character newline sequence, skip the other character.
2130 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2131 // \n\n or \r\r -> not escaped newline.
2132 if (CurPtr[0] == CurPtr[1])
2133 return false;
2134 // \n\r or \r\n -> skip the newline.
2135 --CurPtr;
2136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Chris Lattner22eb9722006-06-18 05:43:12 +00002138 // If we have horizontal whitespace, skip over it. We allow whitespace
2139 // between the slash and newline.
2140 bool HasSpace = false;
2141 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2142 --CurPtr;
2143 HasSpace = true;
2144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner22eb9722006-06-18 05:43:12 +00002146 // If we have a slash, we know this is an escaped newline.
2147 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002148 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002149 } else {
2150 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002151 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2152 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002153 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002154
Chris Lattnercb283342006-06-18 06:48:37 +00002155 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002156 CurPtr -= 2;
2157
2158 // If no trigraphs are enabled, warn that we ignored this trigraph and
2159 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002160 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002161 if (!L->isLexingRawMode())
2162 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002163 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002164 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002165 if (!L->isLexingRawMode())
2166 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002167 }
Mike Stump11289f42009-09-09 15:08:12 +00002168
Chris Lattner22eb9722006-06-18 05:43:12 +00002169 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002170 if (!L->isLexingRawMode())
2171 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattner22eb9722006-06-18 05:43:12 +00002173 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002174 if (HasSpace && !L->isLexingRawMode())
2175 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002176
Chris Lattnercb283342006-06-18 06:48:37 +00002177 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002178}
2179
Chris Lattneraded4a92006-10-27 04:42:31 +00002180#ifdef __SSE2__
2181#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002182#elif __ALTIVEC__
2183#include <altivec.h>
2184#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002185#endif
2186
James Dennettf442d242012-06-17 03:40:43 +00002187/// We have just read from input the / and * characters that started a comment.
2188/// Read until we find the * and / characters that terminate the comment.
2189/// Note that we don't bother decoding trigraphs or escaped newlines in block
2190/// comments, because they cannot cause the comment to end. The only thing
2191/// that can happen is the comment could end with an escaped newline between
2192/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002193///
Chris Lattner87d02082010-01-18 22:35:47 +00002194/// If we're in KeepCommentMode or any CommentHandler has inserted
2195/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002196bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2197 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002198 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002199 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002200 // optimization helps people who like to put a lot of * characters in their
2201 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002202
2203 // The first character we get with newlines and trigraphs skipped to handle
2204 // the degenerate /*/ case below correctly if the * has an escaped newline
2205 // after it.
2206 unsigned CharSize;
2207 unsigned char C = getCharAndSize(CurPtr, CharSize);
2208 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002209 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002210 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002211 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002212 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattner99e7d232008-10-12 04:19:49 +00002214 // KeepWhitespaceMode should return this broken comment as a token. Since
2215 // it isn't a well formed comment, just return it as an 'unknown' token.
2216 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002217 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002218 return true;
2219 }
Mike Stump11289f42009-09-09 15:08:12 +00002220
Chris Lattner99e7d232008-10-12 04:19:49 +00002221 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002222 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 }
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattnerc850ad62007-07-21 23:43:37 +00002225 // Check to see if the first character after the '/*' is another /. If so,
2226 // then this slash does not end the block comment, it is part of it.
2227 if (C == '/')
2228 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002229
Chris Lattner22eb9722006-06-18 05:43:12 +00002230 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002231 // Skip over all non-interesting characters until we find end of buffer or a
2232 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002233 if (CurPtr + 24 < BufferEnd &&
2234 // If there is a code-completion point avoid the fast scan because it
2235 // doesn't check for '\0'.
2236 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002237 // While not aligned to a 16-byte boundary.
2238 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2239 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002240
Chris Lattner6cc3e362006-10-27 04:12:35 +00002241 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002242
2243#ifdef __SSE2__
Benjamin Kramer38857372011-11-22 18:56:46 +00002244 __m128i Slashes = _mm_set1_epi8('/');
2245 while (CurPtr+16 <= BufferEnd) {
Roman Divackye6377112012-09-06 15:59:27 +00002246 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2247 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002248 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002249 // Adjust the pointer to point directly after the first slash. It's
2250 // not necessary to set C here, it will be overwritten at the end of
2251 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002252 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002253 goto FoundSlash;
2254 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002255 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002256 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002257#elif __ALTIVEC__
2258 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002259 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002260 '/', '/', '/', '/', '/', '/', '/', '/'
2261 };
2262 while (CurPtr+16 <= BufferEnd &&
2263 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2264 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002265#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002266 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002267 while (CurPtr[0] != '/' &&
2268 CurPtr[1] != '/' &&
2269 CurPtr[2] != '/' &&
2270 CurPtr[3] != '/' &&
2271 CurPtr+4 < BufferEnd) {
2272 CurPtr += 4;
2273 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002274#endif
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattneraded4a92006-10-27 04:42:31 +00002276 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002277 C = *CurPtr++;
2278 }
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattneraded4a92006-10-27 04:42:31 +00002280 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002281 while (C != '/' && C != '\0')
2282 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002283
Chris Lattner22eb9722006-06-18 05:43:12 +00002284 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002285 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002286 if (CurPtr[-2] == '*') // We found the final */. We're done!
2287 break;
Mike Stump11289f42009-09-09 15:08:12 +00002288
Chris Lattner22eb9722006-06-18 05:43:12 +00002289 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002290 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002291 // We found the final */, though it had an escaped newline between the
2292 // * and /. We're done!
2293 break;
2294 }
2295 }
2296 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2297 // If this is a /* inside of the comment, emit a warning. Don't do this
2298 // if this is a /*/, which will end the comment. This misses cases with
2299 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002300 if (!isLexingRawMode())
2301 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002302 }
2303 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002304 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002305 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002306 // Note: the user probably forgot a */. We could continue immediately
2307 // after the /*, but this would involve lexing a lot of what really is the
2308 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002309 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattner99e7d232008-10-12 04:19:49 +00002311 // KeepWhitespaceMode should return this broken comment as a token. Since
2312 // it isn't a well formed comment, just return it as an 'unknown' token.
2313 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002314 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002315 return true;
2316 }
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattner99e7d232008-10-12 04:19:49 +00002318 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002319 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002320 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2321 PP->CodeCompleteNaturalLanguage();
2322 cutOffLexing();
2323 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002324 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002325
Chris Lattner22eb9722006-06-18 05:43:12 +00002326 C = *CurPtr++;
2327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Chris Lattner93ddf802010-02-03 21:06:21 +00002329 // Notify comment handlers about the comment unless we're in a #if 0 block.
2330 if (PP && !isLexingRawMode() &&
2331 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2332 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002333 BufferPtr = CurPtr;
2334 return true; // A token has to be returned.
2335 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002336
Chris Lattner457fc152006-07-29 06:30:25 +00002337 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002338 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002339 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002340 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002341 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002342
2343 // It is common for the tokens immediately after a /**/ comment to be
2344 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002345 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2346 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002347 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002348 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002349 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002350 }
2351
2352 // Otherwise, just return so that the next character will be lexed as a token.
2353 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002354 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002355 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002356}
2357
2358//===----------------------------------------------------------------------===//
2359// Primary Lexing Entry Points
2360//===----------------------------------------------------------------------===//
2361
Chris Lattner22eb9722006-06-18 05:43:12 +00002362/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2363/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002364void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002365 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2366 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002367 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002368
2369 // CurPtr - Cache BufferPtr in an automatic variable.
2370 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002371 while (1) {
2372 char Char = getAndAdvanceChar(CurPtr, Tmp);
2373 switch (Char) {
2374 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002375 if (Result)
2376 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002377 break;
2378 case 0: // Null.
2379 // Found end of file?
2380 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002381 if (isCodeCompletionPoint(CurPtr-1)) {
2382 PP->CodeCompleteNaturalLanguage();
2383 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002384 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002385 }
2386
Chris Lattner22eb9722006-06-18 05:43:12 +00002387 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002388 if (Result)
2389 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002390 break;
2391 }
2392 // FALL THROUGH.
2393 case '\r':
2394 case '\n':
2395 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2396 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2397 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002398
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002399 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002400 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002401 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002402 if (PP)
2403 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002404 Lex(Tmp);
2405 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002406 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002407
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002408 // Finally, we're done;
2409 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002410 }
2411 }
2412}
2413
2414/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2415/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002416/// This returns true if Result contains a token, false if PP.Lex should be
2417/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002418bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002419 // If we hit the end of the file while parsing a preprocessor directive,
2420 // end the preprocessor directive first. The next token returned will
2421 // then be the end of file.
2422 if (ParsingPreprocessorDirective) {
2423 // Done parsing the "line".
2424 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002425 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002426 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002427
Chris Lattner457fc152006-07-29 06:30:25 +00002428 // Restore comment saving mode, in case it was disabled for directive.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002429 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002430 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002431 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002432
Chris Lattner30a2fa12006-07-19 06:31:49 +00002433 // If we are in raw mode, return this event as an EOF token. Let the caller
2434 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002435 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002436 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002437 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002438 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002439 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002440 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002441
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002442 // Issue diagnostics for unterminated #if and missing newline.
2443
Chris Lattner30a2fa12006-07-19 06:31:49 +00002444 // If we are in a #if directive, emit an error.
2445 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002446 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002447 PP->Diag(ConditionalStack.back().IfLoc,
2448 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002449 ConditionalStack.pop_back();
2450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Chris Lattner8f96d042008-04-12 05:54:25 +00002452 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2453 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002454 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2455 DiagnosticsEngine &Diags = PP->getDiagnostics();
2456 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2457 unsigned DiagID;
2458
2459 if (LangOpts.CPlusPlus11) {
2460 // C++11 [lex.phases] 2.2 p2
2461 // Prefer the C++98 pedantic compatibility warning over the generic,
2462 // non-extension, user-requested "missing newline at EOF" warning.
2463 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_no_newline_eof,
2464 EndLoc) != DiagnosticsEngine::Ignored) {
2465 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2466 } else {
2467 DiagID = diag::warn_no_newline_eof;
2468 }
2469 } else {
2470 DiagID = diag::ext_no_newline_eof;
2471 }
2472
2473 Diag(BufferEnd, DiagID)
2474 << FixItHint::CreateInsertion(EndLoc, "\n");
2475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Chris Lattner22eb9722006-06-18 05:43:12 +00002477 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002478
2479 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002480 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002481}
2482
Chris Lattner678c8802006-07-11 05:46:12 +00002483/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2484/// the specified lexer will return a tok::l_paren token, 0 if it is something
2485/// else and 2 if there are no more tokens in the buffer controlled by the
2486/// lexer.
2487unsigned Lexer::isNextPPTokenLParen() {
2488 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002489
Chris Lattner678c8802006-07-11 05:46:12 +00002490 // Switch to 'skipping' mode. This will ensure that we can lex a token
2491 // without emitting diagnostics, disables macro expansion, and will cause EOF
2492 // to return an EOF token instead of popping the include stack.
2493 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002494
Chris Lattner678c8802006-07-11 05:46:12 +00002495 // Save state that can be changed while lexing so that we can restore it.
2496 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002497 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002498 bool atStartOfLine = IsAtStartOfLine;
2499 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2500 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattner146762e2007-07-20 16:59:19 +00002502 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002503 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002504
Chris Lattner678c8802006-07-11 05:46:12 +00002505 // Restore state that may have changed.
2506 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002507 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002508 HasLeadingSpace = leadingSpace;
2509 IsAtStartOfLine = atStartOfLine;
2510 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattner678c8802006-07-11 05:46:12 +00002512 // Restore the lexer back to non-skipping mode.
2513 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002514
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002515 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002516 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002517 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002518}
2519
James Dennettf442d242012-06-17 03:40:43 +00002520/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002521static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2522 ConflictMarkerKind CMK) {
2523 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2524 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2525 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2526 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002527 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002528 // Must occur at start of line.
2529 if (RestOfBuffer[Pos-1] != '\r' &&
2530 RestOfBuffer[Pos-1] != '\n') {
Richard Smitha9e33d42011-10-12 00:37:51 +00002531 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2532 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002533 continue;
2534 }
2535 return RestOfBuffer.data()+Pos;
2536 }
2537 return 0;
2538}
2539
2540/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2541/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2542/// and recover nicely. This returns true if it is a conflict marker and false
2543/// if not.
2544bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2545 // Only a conflict marker if it starts at the beginning of a line.
2546 if (CurPtr != BufferStart &&
2547 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2548 return false;
2549
Richard Smitha9e33d42011-10-12 00:37:51 +00002550 // Check to see if we have <<<<<<< or >>>>.
2551 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2552 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002553 return false;
2554
2555 // If we have a situation where we don't care about conflict markers, ignore
2556 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002557 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002558 return false;
2559
Richard Smitha9e33d42011-10-12 00:37:51 +00002560 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2561
2562 // Check to see if there is an ending marker somewhere in the buffer at the
2563 // start of a line to terminate this conflict marker.
2564 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002565 // We found a match. We are really in a conflict marker.
2566 // Diagnose this, and ignore to the end of line.
2567 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002568 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002569
2570 // Skip ahead to the end of line. We know this exists because the
2571 // end-of-conflict marker starts with \r or \n.
2572 while (*CurPtr != '\r' && *CurPtr != '\n') {
2573 assert(CurPtr != BufferEnd && "Didn't find end of line");
2574 ++CurPtr;
2575 }
2576 BufferPtr = CurPtr;
2577 return true;
2578 }
2579
2580 // No end of conflict marker found.
2581 return false;
2582}
2583
2584
Richard Smitha9e33d42011-10-12 00:37:51 +00002585/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2586/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2587/// is the end of a conflict marker. Handle it by ignoring up until the end of
2588/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002589bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2590 // Only a conflict marker if it starts at the beginning of a line.
2591 if (CurPtr != BufferStart &&
2592 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2593 return false;
2594
2595 // If we have a situation where we don't care about conflict markers, ignore
2596 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002597 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002598 return false;
2599
Richard Smitha9e33d42011-10-12 00:37:51 +00002600 // Check to see if we have the marker (4 characters in a row).
2601 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002602 if (CurPtr[i] != CurPtr[0])
2603 return false;
2604
2605 // If we do have it, search for the end of the conflict marker. This could
2606 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2607 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002608 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2609 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002610 CurPtr = End;
2611
2612 // Skip ahead to the end of line.
2613 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2614 ++CurPtr;
2615
2616 BufferPtr = CurPtr;
2617
2618 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002619 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002620 return true;
2621 }
2622
2623 return false;
2624}
2625
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002626bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2627 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002628 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002629 return Loc == PP->getCodeCompletionLoc();
2630 }
2631
2632 return false;
2633}
2634
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002635uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2636 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002637 unsigned CharSize;
2638 char Kind = getCharAndSize(StartPtr, CharSize);
2639
2640 unsigned NumHexDigits;
2641 if (Kind == 'u')
2642 NumHexDigits = 4;
2643 else if (Kind == 'U')
2644 NumHexDigits = 8;
2645 else
2646 return 0;
2647
Jordan Rosec0cba272013-01-27 20:12:04 +00002648 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002649 if (Result && !isLexingRawMode())
2650 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002651 return 0;
2652 }
2653
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002654 const char *CurPtr = StartPtr + CharSize;
2655 const char *KindLoc = &CurPtr[-1];
2656
2657 uint32_t CodePoint = 0;
2658 for (unsigned i = 0; i < NumHexDigits; ++i) {
2659 char C = getCharAndSize(CurPtr, CharSize);
2660
2661 unsigned Value = llvm::hexDigitValue(C);
2662 if (Value == -1U) {
2663 if (Result && !isLexingRawMode()) {
2664 if (i == 0) {
2665 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2666 << StringRef(KindLoc, 1);
2667 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002668 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002669
2670 // If the user wrote \U1234, suggest a fixit to \u.
2671 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002672 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002673 Diag(KindLoc, diag::note_ucn_four_not_eight)
2674 << FixItHint::CreateReplacement(URange, "u");
2675 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002676 }
2677 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002678
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002679 return 0;
2680 }
2681
2682 CodePoint <<= 4;
2683 CodePoint += Value;
2684
2685 CurPtr += CharSize;
2686 }
2687
2688 if (Result) {
2689 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002690 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002691 StartPtr = CurPtr;
2692 else
2693 while (StartPtr != CurPtr)
2694 (void)getAndAdvanceChar(StartPtr, *Result);
2695 } else {
2696 StartPtr = CurPtr;
2697 }
2698
2699 // C99 6.4.3p2: A universal character name shall not specify a character whose
2700 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2701 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2702 // C++11 [lex.charset]p2: If the hexadecimal value for a
2703 // universal-character-name corresponds to a surrogate code point (in the
2704 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2705 // if the hexadecimal value for a universal-character-name outside the
2706 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2707 // string literal corresponds to a control character (in either of the
2708 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2709 // basic source character set, the program is ill-formed.
2710 if (CodePoint < 0xA0) {
2711 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2712 return CodePoint;
2713
2714 // We don't use isLexingRawMode() here because we need to warn about bad
2715 // UCNs even when skipping preprocessing tokens in a #if block.
2716 if (Result && PP) {
2717 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2718 Diag(BufferPtr, diag::err_ucn_control_character);
2719 else {
2720 char C = static_cast<char>(CodePoint);
2721 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2722 }
2723 }
2724
2725 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002726
2727 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002728 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002729 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002730 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002731 if (Result && PP) {
2732 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2733 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2734 else
2735 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2736 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002737 return 0;
2738 }
2739
2740 return CodePoint;
2741}
2742
Eli Friedman0834a4b2013-09-19 00:41:32 +00002743bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2744 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002745 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2746 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002747 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002748 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002749 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002750 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002751
2752 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002753 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002754 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002755 return false;
2756}
Jordan Rose4246ae02013-01-24 20:50:50 +00002757
Eli Friedman0834a4b2013-09-19 00:41:32 +00002758bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002759 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2760 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2761 !PP->isPreprocessedOutput()) {
2762 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2763 makeCharRange(*this, BufferPtr, CurPtr),
2764 /*IsFirst=*/true);
2765 }
2766
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002767 MIOpt.ReadToken();
2768 return LexIdentifier(Result, CurPtr);
2769 }
2770
Jordan Rosecc538342013-01-31 19:48:48 +00002771 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2772 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002773 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002774 // Non-ASCII characters tend to creep into source code unintentionally.
2775 // Instead of letting the parser complain about the unknown token,
2776 // just drop the character.
2777 // Note that we can /only/ do this when the non-ASCII character is actually
2778 // spelled as Unicode, not written as a UCN. The standard requires that
2779 // we not throw away any possible preprocessor tokens, but there's a
2780 // loophole in the mapping of Unicode characters to basic character set
2781 // characters that allows us to map these particular characters to, say,
2782 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002783 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002784 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002785
2786 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002787 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002788 }
2789
2790 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2791 // up by accident.
2792 MIOpt.ReadToken();
2793 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002794 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002795}
2796
Eli Friedman0834a4b2013-09-19 00:41:32 +00002797void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2798 IsAtStartOfLine = Result.isAtStartOfLine();
2799 HasLeadingSpace = Result.hasLeadingSpace();
2800 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2801 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2802}
2803
2804bool Lexer::Lex(Token &Result) {
2805 // Start a new token.
2806 Result.startToken();
2807
2808 // Set up misc whitespace flags for LexTokenInternal.
2809 if (IsAtStartOfLine) {
2810 Result.setFlag(Token::StartOfLine);
2811 IsAtStartOfLine = false;
2812 }
2813
2814 if (HasLeadingSpace) {
2815 Result.setFlag(Token::LeadingSpace);
2816 HasLeadingSpace = false;
2817 }
2818
2819 if (HasLeadingEmptyMacro) {
2820 Result.setFlag(Token::LeadingEmptyMacro);
2821 HasLeadingEmptyMacro = false;
2822 }
2823
2824 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2825 IsAtPhysicalStartOfLine = false;
2826 bool result = LexTokenInternal(Result, atPhysicalStartOfLine);
2827 assert((result || !isLexingRawMode()) && "Raw lex must succeed");
2828 return result;
2829}
Chris Lattner22eb9722006-06-18 05:43:12 +00002830
2831/// LexTokenInternal - This implements a simple C family lexer. It is an
2832/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002833/// has a null character at the end of the file. This returns a preprocessing
2834/// token, not a normal token, as such, it is an internal interface. It assumes
2835/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002836bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002837LexNextToken:
2838 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002839 Result.clearFlag(Token::NeedsCleaning);
Chris Lattner8c204872006-10-14 05:19:21 +00002840 Result.setIdentifierInfo(0);
Mike Stump11289f42009-09-09 15:08:12 +00002841
Chris Lattner22eb9722006-06-18 05:43:12 +00002842 // CurPtr - Cache BufferPtr in an automatic variable.
2843 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002844
Chris Lattnereb54b592006-07-10 06:34:27 +00002845 // Small amounts of horizontal whitespace is very common between tokens.
2846 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2847 ++CurPtr;
2848 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2849 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002850
Chris Lattner4d963442008-10-12 04:05:48 +00002851 // If we are keeping whitespace and other tokens, just return what we just
2852 // skipped. The next lexer invocation will return the token after the
2853 // whitespace.
2854 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002855 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002856 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002857 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002858 }
Mike Stump11289f42009-09-09 15:08:12 +00002859
Chris Lattnereb54b592006-07-10 06:34:27 +00002860 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002861 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002862 }
Mike Stump11289f42009-09-09 15:08:12 +00002863
Chris Lattner22eb9722006-06-18 05:43:12 +00002864 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002865
Chris Lattner22eb9722006-06-18 05:43:12 +00002866 // Read a character, advancing over it.
2867 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002868 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002869
Chris Lattner22eb9722006-06-18 05:43:12 +00002870 switch (Char) {
2871 case 0: // Null.
2872 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002873 if (CurPtr-1 == BufferEnd)
2874 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002875
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002876 // Check if we are performing code completion.
2877 if (isCodeCompletionPoint(CurPtr-1)) {
2878 // Return the code-completion token.
2879 Result.startToken();
2880 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002881 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002882 }
2883
Chris Lattner6d27a162008-11-22 02:02:22 +00002884 if (!isLexingRawMode())
2885 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002886 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002887 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2888 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002889
Eli Friedman0834a4b2013-09-19 00:41:32 +00002890 // We know the lexer hasn't changed, so just try again with this lexer.
2891 // (We manually eliminate the tail call to avoid recursion.)
2892 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002893
2894 case 26: // DOS & CP/M EOF: "^Z".
2895 // If we're in Microsoft extensions mode, treat this as end of file.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002896 if (LangOpts.MicrosoftExt)
2897 return LexEndOfFile(Result, CurPtr-1);
2898
Chris Lattner3dfff972009-12-17 05:29:40 +00002899 // If Microsoft extensions are disabled, this is just random garbage.
2900 Kind = tok::unknown;
2901 break;
2902
Chris Lattner22eb9722006-06-18 05:43:12 +00002903 case '\n':
2904 case '\r':
2905 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002906 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002907 if (ParsingPreprocessorDirective) {
2908 // Done parsing the "line".
2909 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002910
Chris Lattner457fc152006-07-29 06:30:25 +00002911 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002912 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002913 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002914
Chris Lattner22eb9722006-06-18 05:43:12 +00002915 // Since we consumed a newline, we are back at the start of a line.
2916 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002917 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002918
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002919 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002920 break;
2921 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002922
Chris Lattner22eb9722006-06-18 05:43:12 +00002923 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002924 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Eli Friedman0834a4b2013-09-19 00:41:32 +00002926 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2927 return true; // KeepWhitespaceMode
2928
2929 // We only saw whitespace, so just try again with this lexer.
2930 // (We manually eliminate the tail call to avoid recursion.)
2931 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00002932 case ' ':
2933 case '\t':
2934 case '\f':
2935 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002936 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00002937 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002938 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2939 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00002940
2941 SkipIgnoredUnits:
2942 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002943
Chris Lattnerb9b85972007-07-22 06:29:05 +00002944 // If the next token is obviously a // or /* */ comment, skip it efficiently
2945 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00002946 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00002947 LangOpts.LineComment &&
2948 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002949 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
2950 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002951 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00002952 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002953 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
2954 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00002955 goto SkipIgnoredUnits;
2956 } else if (isHorizontalWhitespace(*CurPtr)) {
2957 goto SkipHorizontalWhitespace;
2958 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002959 // We only saw whitespace, so just try again with this lexer.
2960 // (We manually eliminate the tail call to avoid recursion.)
2961 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002962
Chris Lattner2b15cf72008-01-03 17:58:54 +00002963 // C99 6.4.4.1: Integer Constants.
2964 // C99 6.4.4.2: Floating Constants.
2965 case '0': case '1': case '2': case '3': case '4':
2966 case '5': case '6': case '7': case '8': case '9':
2967 // Notify MIOpt that we read a non-whitespace/non-comment token.
2968 MIOpt.ReadToken();
2969 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00002970
Richard Smith9b362092013-03-09 23:56:02 +00002971 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00002972 // Notify MIOpt that we read a non-whitespace/non-comment token.
2973 MIOpt.ReadToken();
2974
Richard Smith9b362092013-03-09 23:56:02 +00002975 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00002976 Char = getCharAndSize(CurPtr, SizeTmp);
2977
2978 // UTF-16 string literal
2979 if (Char == '"')
2980 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2981 tok::utf16_string_literal);
2982
2983 // UTF-16 character constant
2984 if (Char == '\'')
2985 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2986 tok::utf16_char_constant);
2987
Craig Topper54edcca2011-08-11 04:06:15 +00002988 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00002989 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2990 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00002991 return LexRawStringLiteral(Result,
2992 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2993 SizeTmp2, Result),
2994 tok::utf16_string_literal);
2995
2996 if (Char == '8') {
2997 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2998
2999 // UTF-8 string literal
3000 if (Char2 == '"')
3001 return LexStringLiteral(Result,
3002 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3003 SizeTmp2, Result),
3004 tok::utf8_string_literal);
3005
Richard Smith9b362092013-03-09 23:56:02 +00003006 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003007 unsigned SizeTmp3;
3008 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3009 // UTF-8 raw string literal
3010 if (Char3 == '"') {
3011 return LexRawStringLiteral(Result,
3012 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3013 SizeTmp2, Result),
3014 SizeTmp3, Result),
3015 tok::utf8_string_literal);
3016 }
3017 }
3018 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003019 }
3020
3021 // treat u like the start of an identifier.
3022 return LexIdentifier(Result, CurPtr);
3023
Richard Smith9b362092013-03-09 23:56:02 +00003024 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003025 // Notify MIOpt that we read a non-whitespace/non-comment token.
3026 MIOpt.ReadToken();
3027
Richard Smith9b362092013-03-09 23:56:02 +00003028 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003029 Char = getCharAndSize(CurPtr, SizeTmp);
3030
3031 // UTF-32 string literal
3032 if (Char == '"')
3033 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3034 tok::utf32_string_literal);
3035
3036 // UTF-32 character constant
3037 if (Char == '\'')
3038 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3039 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003040
3041 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003042 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3043 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003044 return LexRawStringLiteral(Result,
3045 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3046 SizeTmp2, Result),
3047 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003048 }
3049
3050 // treat U like the start of an identifier.
3051 return LexIdentifier(Result, CurPtr);
3052
Craig Topper54edcca2011-08-11 04:06:15 +00003053 case 'R': // Identifier or C++0x raw string literal
3054 // Notify MIOpt that we read a non-whitespace/non-comment token.
3055 MIOpt.ReadToken();
3056
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003057 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003058 Char = getCharAndSize(CurPtr, SizeTmp);
3059
3060 if (Char == '"')
3061 return LexRawStringLiteral(Result,
3062 ConsumeChar(CurPtr, SizeTmp, Result),
3063 tok::string_literal);
3064 }
3065
3066 // treat R like the start of an identifier.
3067 return LexIdentifier(Result, CurPtr);
3068
Chris Lattner2b15cf72008-01-03 17:58:54 +00003069 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003070 // Notify MIOpt that we read a non-whitespace/non-comment token.
3071 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003072 Char = getCharAndSize(CurPtr, SizeTmp);
3073
3074 // Wide string literal.
3075 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003076 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003077 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003078
Craig Topper54edcca2011-08-11 04:06:15 +00003079 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003080 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003081 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3082 return LexRawStringLiteral(Result,
3083 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3084 SizeTmp2, Result),
3085 tok::wide_string_literal);
3086
Chris Lattner22eb9722006-06-18 05:43:12 +00003087 // Wide character constant.
3088 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003089 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3090 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003091 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003092
Chris Lattner22eb9722006-06-18 05:43:12 +00003093 // C99 6.4.2: Identifiers.
3094 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3095 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003096 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003097 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3098 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3099 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003100 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003101 case 'v': case 'w': case 'x': case 'y': case 'z':
3102 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003103 // Notify MIOpt that we read a non-whitespace/non-comment token.
3104 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003105 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003106
3107 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003108 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003109 if (!isLexingRawMode())
3110 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003111 // Notify MIOpt that we read a non-whitespace/non-comment token.
3112 MIOpt.ReadToken();
3113 return LexIdentifier(Result, CurPtr);
3114 }
Mike Stump11289f42009-09-09 15:08:12 +00003115
Chris Lattnerb11c3232008-10-12 04:51:35 +00003116 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003117 break;
Mike Stump11289f42009-09-09 15:08:12 +00003118
Chris Lattner22eb9722006-06-18 05:43:12 +00003119 // C99 6.4.4: Character Constants.
3120 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003121 // Notify MIOpt that we read a non-whitespace/non-comment token.
3122 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003123 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003124
3125 // C99 6.4.5: String Literals.
3126 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003127 // Notify MIOpt that we read a non-whitespace/non-comment token.
3128 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003129 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003130
3131 // C99 6.4.6: Punctuators.
3132 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003133 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003134 break;
3135 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003136 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003137 break;
3138 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003139 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003140 break;
3141 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003142 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003143 break;
3144 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003145 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003146 break;
3147 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003148 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003149 break;
3150 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003151 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003152 break;
3153 case '.':
3154 Char = getCharAndSize(CurPtr, SizeTmp);
3155 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003156 // Notify MIOpt that we read a non-whitespace/non-comment token.
3157 MIOpt.ReadToken();
3158
Chris Lattner22eb9722006-06-18 05:43:12 +00003159 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003160 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003161 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003162 CurPtr += SizeTmp;
3163 } else if (Char == '.' &&
3164 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003165 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003166 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3167 SizeTmp2, Result);
3168 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003169 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003170 }
3171 break;
3172 case '&':
3173 Char = getCharAndSize(CurPtr, SizeTmp);
3174 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003175 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003176 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3177 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003178 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003179 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3180 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003181 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003182 }
3183 break;
Mike Stump11289f42009-09-09 15:08:12 +00003184 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003185 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003186 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3188 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003189 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003190 }
3191 break;
3192 case '+':
3193 Char = getCharAndSize(CurPtr, SizeTmp);
3194 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003195 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003196 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003197 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003198 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003199 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003200 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003201 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003202 }
3203 break;
3204 case '-':
3205 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003206 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003207 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003208 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003209 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003210 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003211 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3212 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003213 Kind = tok::arrowstar;
3214 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003215 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003216 Kind = tok::arrow;
3217 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003218 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003219 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003220 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003221 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003222 }
3223 break;
3224 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003225 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003226 break;
3227 case '!':
3228 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003229 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003230 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3231 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003232 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003233 }
3234 break;
3235 case '/':
3236 // 6.4.9: Comments
3237 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003238 if (Char == '/') { // Line comment.
3239 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003240 // want to lex this as a comment. There is one problem with this though,
3241 // that in one particular corner case, this can change the behavior of the
3242 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003243 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003244 // "foo". Check to see if the character after the second slash is a '*'.
3245 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003246 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003247 bool TreatAsComment = LangOpts.LineComment &&
3248 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003249 if (!TreatAsComment)
3250 if (!(PP && PP->isPreprocessedOutput()))
3251 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3252
3253 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003254 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3255 TokAtPhysicalStartOfLine))
3256 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003257
Chris Lattner58827712009-01-16 22:39:25 +00003258 // It is common for the tokens immediately after a // comment to be
3259 // whitespace (indentation for the next line). Instead of going through
3260 // the big switch, handle it efficiently now.
3261 goto SkipIgnoredUnits;
3262 }
3263 }
Mike Stump11289f42009-09-09 15:08:12 +00003264
Chris Lattner58827712009-01-16 22:39:25 +00003265 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003266 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3267 TokAtPhysicalStartOfLine))
3268 return true; // There is a token to return.
3269
3270 // We only saw whitespace, so just try again with this lexer.
3271 // (We manually eliminate the tail call to avoid recursion.)
3272 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
Chris Lattner58827712009-01-16 22:39:25 +00003275 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003276 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003277 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003278 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003279 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003280 }
3281 break;
3282 case '%':
3283 Char = getCharAndSize(CurPtr, SizeTmp);
3284 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003285 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003286 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003287 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003288 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003289 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003290 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003291 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003292 Char = getCharAndSize(CurPtr, SizeTmp);
3293 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003294 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003295 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3296 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003297 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003298 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003299 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003300 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003301 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003302 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003303 // We parsed a # character. If this occurs at the start of the line,
3304 // it's actually the start of a preprocessing directive. Callback to
3305 // the preprocessor to handle it.
3306 // FIXME: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003307 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003308 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003309
Chris Lattner2534324a2009-03-18 20:58:27 +00003310 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003311 }
3312 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003313 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003314 }
3315 break;
3316 case '<':
3317 Char = getCharAndSize(CurPtr, SizeTmp);
3318 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003319 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003320 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003321 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3322 if (After == '=') {
3323 Kind = tok::lesslessequal;
3324 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3325 SizeTmp2, Result);
3326 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3327 // If this is actually a '<<<<<<<' version control conflict marker,
3328 // recognize it as such and recover nicely.
3329 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003330 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3331 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3332 // ignore it.
3333 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003334 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003335 Kind = tok::lesslessless;
3336 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3337 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003338 } else {
3339 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3340 Kind = tok::lessless;
3341 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003342 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003343 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003344 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003345 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003346 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003347 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3348 // C++0x [lex.pptoken]p3:
3349 // Otherwise, if the next three characters are <:: and the subsequent
3350 // character is neither : nor >, the < is treated as a preprocessor
3351 // token by itself and not as the first character of the alternative
3352 // token <:.
3353 unsigned SizeTmp3;
3354 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3355 if (After != ':' && After != '>') {
3356 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003357 if (!isLexingRawMode())
3358 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003359 break;
3360 }
3361 }
3362
Chris Lattner22eb9722006-06-18 05:43:12 +00003363 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003364 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003365 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003366 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003367 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003368 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003369 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003370 }
3371 break;
3372 case '>':
3373 Char = getCharAndSize(CurPtr, SizeTmp);
3374 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003375 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003376 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003377 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003378 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3379 if (After == '=') {
3380 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3381 SizeTmp2, Result);
3382 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003383 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3384 // If this is actually a '>>>>' conflict marker, recognize it as such
3385 // and recover nicely.
3386 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003387 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3388 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3389 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003390 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003391 Kind = tok::greatergreatergreater;
3392 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3393 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003394 } else {
3395 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3396 Kind = tok::greatergreater;
3397 }
3398
Chris Lattner22eb9722006-06-18 05:43:12 +00003399 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003400 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003401 }
3402 break;
3403 case '^':
3404 Char = getCharAndSize(CurPtr, SizeTmp);
3405 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003406 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003407 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003408 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003409 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003410 }
3411 break;
3412 case '|':
3413 Char = getCharAndSize(CurPtr, SizeTmp);
3414 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003415 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003416 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3417 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003418 // If this is '|||||||' and we're in a conflict marker, ignore it.
3419 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3420 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003421 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003422 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3423 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003424 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003425 }
3426 break;
3427 case ':':
3428 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003429 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003430 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003431 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003432 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003433 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003434 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003435 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003436 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003437 }
3438 break;
3439 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003440 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003441 break;
3442 case '=':
3443 Char = getCharAndSize(CurPtr, SizeTmp);
3444 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003445 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003446 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3447 goto LexNextToken;
3448
Chris Lattnerb11c3232008-10-12 04:51:35 +00003449 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003450 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003451 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003452 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003453 }
3454 break;
3455 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003456 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003457 break;
3458 case '#':
3459 Char = getCharAndSize(CurPtr, SizeTmp);
3460 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003461 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003462 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003463 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003464 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003465 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003466 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003467 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003468 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003469 // We parsed a # character. If this occurs at the start of the line,
3470 // it's actually the start of a preprocessing directive. Callback to
3471 // the preprocessor to handle it.
Chris Lattner505c5472006-07-03 00:55:48 +00003472 // FIXME: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003473 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003474 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003475
Chris Lattner2534324a2009-03-18 20:58:27 +00003476 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003477 }
3478 break;
3479
Chris Lattner2b15cf72008-01-03 17:58:54 +00003480 case '@':
3481 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003482 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003483 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003484 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003485 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003486 break;
Mike Stump11289f42009-09-09 15:08:12 +00003487
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003488 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003489 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003490 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3491 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3492 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3493 return true; // KeepWhitespaceMode
3494
3495 // We only saw whitespace, so just try again with this lexer.
3496 // (We manually eliminate the tail call to avoid recursion.)
3497 goto LexNextToken;
3498 }
3499
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003500 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003501 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003502
Chris Lattnerb11c3232008-10-12 04:51:35 +00003503 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003504 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003505
3506 default: {
3507 if (isASCII(Char)) {
3508 Kind = tok::unknown;
3509 break;
3510 }
3511
3512 UTF32 CodePoint;
3513
3514 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3515 // an escaped newline.
3516 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003517 ConversionResult Status =
3518 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3519 (const UTF8 *)BufferEnd,
3520 &CodePoint,
3521 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003522 if (Status == conversionOK) {
3523 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3524 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3525 return true; // KeepWhitespaceMode
3526
3527 // We only saw whitespace, so just try again with this lexer.
3528 // (We manually eliminate the tail call to avoid recursion.)
3529 goto LexNextToken;
3530 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003531 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003532 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003533
Jordan Rosecc538342013-01-31 19:48:48 +00003534 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3535 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003536 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003537 Kind = tok::unknown;
3538 break;
3539 }
3540
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003541 // Non-ASCII characters tend to creep into source code unintentionally.
3542 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003543 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003544 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003545
3546 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003547 // We're pretending the character didn't exist, so just try again with
3548 // this lexer.
3549 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003550 goto LexNextToken;
3551 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003552 }
Mike Stump11289f42009-09-09 15:08:12 +00003553
Chris Lattner371ac8a2006-07-04 07:11:10 +00003554 // Notify MIOpt that we read a non-whitespace/non-comment token.
3555 MIOpt.ReadToken();
3556
Chris Lattnerd01e2912006-06-18 16:22:51 +00003557 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003558 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003559 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003560
3561HandleDirective:
3562 // We parsed a # character and it's the start of a preprocessing directive.
3563
3564 FormTokenWithChars(Result, CurPtr, tok::hash);
3565 PP->HandleDirective(Result);
3566
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003567 if (PP->hadModuleLoaderFatalFailure()) {
3568 // With a fatal failure in the module loader, we abort parsing.
3569 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003570 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003571 }
3572
Eli Friedman0834a4b2013-09-19 00:41:32 +00003573 // We parsed the directive; lex a token with the new state.
3574 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003575}