blob: a3ec1b3b0e091b11bb4544ea64360c5ebcdfd879 [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//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +000013
14#include "clang/Lex/Lexer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "UnicodeCharSets.h"
Jordan Rosea2100d72013-02-08 22:30:22 +000016#include "clang/Basic/CharInfo.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/LexDiagnostic.h"
Richard Smith2a988622013-09-24 04:06:10 +000020#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/Preprocessor.h"
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +000022#include "llvm/ADT/STLExtras.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000023#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000025#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000026#include "llvm/Support/ConvertUTF.h"
Chris Lattner739e7392007-04-29 07:12:06 +000027#include "llvm/Support/MemoryBuffer.h"
Craig Topper54edcca2011-08-11 04:06:15 +000028#include <cstring>
Chris Lattner22eb9722006-06-18 05:43:12 +000029using namespace clang;
30
Chris Lattner4894f482007-10-07 08:47:24 +000031//===----------------------------------------------------------------------===//
32// Token Class Implementation
33//===----------------------------------------------------------------------===//
34
Mike Stump11289f42009-09-09 15:08:12 +000035/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000036bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Douglas Gregor90abb6d2008-12-01 21:46:47 +000037 if (IdentifierInfo *II = getIdentifierInfo())
38 return II->getObjCKeywordID() == objcKey;
39 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000040}
41
42/// getObjCKeywordID - Return the ObjC keyword kind.
43tok::ObjCKeywordKind Token::getObjCKeywordID() const {
44 IdentifierInfo *specId = getIdentifierInfo();
45 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
46}
47
Chris Lattner67671ed2007-12-13 01:59:49 +000048
Chris Lattner4894f482007-10-07 08:47:24 +000049//===----------------------------------------------------------------------===//
50// Lexer Class Implementation
51//===----------------------------------------------------------------------===//
52
David Blaikie68e081d2011-12-20 02:48:34 +000053void Lexer::anchor() { }
54
Mike Stump11289f42009-09-09 15:08:12 +000055void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000056 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000057 BufferStart = BufStart;
58 BufferPtr = BufPtr;
59 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattnerf76b9202009-01-17 06:55:17 +000061 assert(BufEnd[0] == 0 &&
62 "We assume that the input buffer has a null character at the end"
63 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000064
Eric Christopher7f36a792011-04-09 00:01:04 +000065 // Check whether we have a BOM in the beginning of the buffer. If yes - act
66 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
67 // skip the UTF-8 BOM if it's present.
68 if (BufferStart == BufferPtr) {
69 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000071 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000072 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
73 .Default(0);
74
75 // Skip the BOM.
76 BufferPtr += BOMLength;
77 }
78
Chris Lattnerf76b9202009-01-17 06:55:17 +000079 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000080 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000081
Chris Lattnerf76b9202009-01-17 06:55:17 +000082 // Start of the file is a start of line.
83 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000084 IsAtPhysicalStartOfLine = true;
85
86 HasLeadingSpace = false;
87 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +000088
Chris Lattnerf76b9202009-01-17 06:55:17 +000089 // We are not after parsing a #.
90 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattnerf76b9202009-01-17 06:55:17 +000092 // We are not after parsing #include.
93 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattnerf76b9202009-01-17 06:55:17 +000095 // We are not in raw mode. Raw mode disables diagnostics and interpretation
96 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
97 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
98 // or otherwise skipping over tokens.
99 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattnerf76b9202009-01-17 06:55:17 +0000101 // Default to not keeping comments.
102 ExtendedTokenMode = 0;
103}
104
Chris Lattner5965a282009-01-17 07:56:59 +0000105/// Lexer constructor - Create a new lexer object for the specified buffer
106/// with the specified preprocessor managing the lexing process. This lexer
107/// assumes that the associated file buffer and Preprocessor objects will
108/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000109Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000110 : PreprocessorLexer(&PP, FID),
111 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000112 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattner5965a282009-01-17 07:56:59 +0000114 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
115 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000116
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000117 resetExtendedTokenMode();
118}
119
120void Lexer::resetExtendedTokenMode() {
121 assert(PP && "Cannot reset token mode without a preprocessor");
122 if (LangOpts.TraditionalCPP)
123 SetKeepWhitespaceMode(true);
124 else
125 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000126}
Chris Lattner4894f482007-10-07 08:47:24 +0000127
Chris Lattner02b436a2007-10-17 20:41:00 +0000128/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000129/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000130/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000132 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000133 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000134
Chris Lattnerf76b9202009-01-17 06:55:17 +0000135 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattner02b436a2007-10-17 20:41:00 +0000137 // We *are* in raw mode.
138 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000139}
140
Chris Lattner08354fe2009-01-17 07:35:14 +0000141/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000142/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000143/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000144Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000145 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000146 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
147 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000148
Chris Lattner757169b2009-01-17 08:27:52 +0000149/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
150/// _Pragma expansion. This has a variety of magic semantics that this method
151/// sets up. It returns a new'd Lexer that must be delete'd when done.
152///
153/// On entrance to this routine, TokStartLoc is a macro location which has a
154/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000155/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000156/// "expanded from".
157///
Alp Toker7755aff2014-05-18 18:37:59 +0000158/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000159/// normal lexer that remaps tokens as they fly by. This would require making
160/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
161/// interface that could handle this stuff. This would pull GetMappedTokenLoc
162/// out of the critical path of the lexer!
163///
Mike Stump11289f42009-09-09 15:08:12 +0000164Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000165 SourceLocation ExpansionLocStart,
166 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000167 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000168 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000169
170 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000171 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000172 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
173 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000174
Chris Lattner757169b2009-01-17 08:27:52 +0000175 // Now that the lexer is created, change the start/end locations so that we
176 // just lex the subsection of the file that we want. This is lexing from a
177 // scratch buffer.
178 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattner757169b2009-01-17 08:27:52 +0000180 L->BufferPtr = StrData;
181 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000182 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000183
184 // Set the SourceLocation with the remapping information. This ensures that
185 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000186 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
187 ExpansionLocStart,
188 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattner757169b2009-01-17 08:27:52 +0000190 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000191 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000192 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattner757169b2009-01-17 08:27:52 +0000194 // This lexer really is for _Pragma.
195 L->Is_PragmaLexer = true;
196 return L;
197}
198
Chris Lattner02b436a2007-10-17 20:41:00 +0000199
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000200/// Stringify - Convert the specified string into a C string, with surrounding
201/// ""'s, and with escaped \ and " characters.
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000202std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000203 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000204 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000205 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000206 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000207 Result.insert(Result.begin()+i, '\\');
208 ++i; ++e;
209 }
210 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000211 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000212}
213
Chris Lattner4c4a2452007-07-24 06:57:14 +0000214/// Stringify - Convert the specified string into a C string by escaping '\'
215/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000216void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000217 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
218 if (Str[i] == '\\' || Str[i] == '"') {
219 Str.insert(Str.begin()+i, '\\');
220 ++i; ++e;
221 }
222 }
223}
224
Chris Lattner39720112010-11-17 07:26:20 +0000225//===----------------------------------------------------------------------===//
226// Token Spelling
227//===----------------------------------------------------------------------===//
228
Richard Smith9a67f472012-11-28 07:29:00 +0000229/// \brief Slow case of getSpelling. Extract the characters comprising the
230/// spelling of this token from the provided input buffer.
231static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
232 const LangOptions &LangOpts, char *Spelling) {
233 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
234
235 size_t Length = 0;
236 const char *BufEnd = BufPtr + Tok.getLength();
237
Craig Toppera6324c92015-10-22 15:35:21 +0000238 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000239 // Munch the encoding-prefix and opening double-quote.
240 while (BufPtr < BufEnd) {
241 unsigned Size;
242 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
243 BufPtr += Size;
244
245 if (Spelling[Length - 1] == '"')
246 break;
247 }
248
249 // Raw string literals need special handling; trigraph expansion and line
250 // splicing do not occur within their d-char-sequence nor within their
251 // r-char-sequence.
252 if (Length >= 2 &&
253 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
254 // Search backwards from the end of the token to find the matching closing
255 // quote.
256 const char *RawEnd = BufEnd;
257 do --RawEnd; while (*RawEnd != '"');
258 size_t RawLength = RawEnd - BufPtr + 1;
259
260 // Everything between the quotes is included verbatim in the spelling.
261 memcpy(Spelling + Length, BufPtr, RawLength);
262 Length += RawLength;
263 BufPtr += RawLength;
264
265 // The rest of the token is lexed normally.
266 }
267 }
268
269 while (BufPtr < BufEnd) {
270 unsigned Size;
271 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
272 BufPtr += Size;
273 }
274
275 assert(Length < Tok.getLength() &&
276 "NeedsCleaning flag set on token that didn't need cleaning!");
277 return Length;
278}
279
Chris Lattner39720112010-11-17 07:26:20 +0000280/// getSpelling() - Return the 'spelling' of this token. The spelling of a
281/// token are the characters used to represent the token in the source file
282/// after trigraph expansion and escaped-newline folding. In particular, this
283/// wants to get the true, uncanonicalized, spelling of things like digraphs
284/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000285StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000286 SmallVectorImpl<char> &buffer,
287 const SourceManager &SM,
288 const LangOptions &options,
289 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000290 // Break down the source location.
291 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
292
293 // Try to the load the file buffer.
294 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000296 if (invalidTemp) {
297 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000298 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000299 }
300
301 const char *tokenBegin = file.data() + locInfo.second;
302
303 // Lex from the start of the given location.
304 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
305 file.begin(), tokenBegin, file.end());
306 Token token;
307 lexer.LexFromRawLexer(token);
308
309 unsigned length = token.getLength();
310
311 // Common case: no need for cleaning.
312 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000313 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000314
Richard Smith9a67f472012-11-28 07:29:00 +0000315 // Hard case, we need to relex the characters into the string.
316 buffer.resize(length);
317 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000319}
320
321/// getSpelling() - Return the 'spelling' of this token. The spelling of a
322/// token are the characters used to represent the token in the source file
323/// after trigraph expansion and escaped-newline folding. In particular, this
324/// wants to get the true, uncanonicalized, spelling of things like digraphs
325/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000326std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000327 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000328 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000329
Chris Lattner39720112010-11-17 07:26:20 +0000330 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000331 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000332 &CharDataInvalid);
333 if (Invalid)
334 *Invalid = CharDataInvalid;
335 if (CharDataInvalid)
336 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000337
338 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000339 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000340 return std::string(TokStart, TokStart + Tok.getLength());
341
Chris Lattner39720112010-11-17 07:26:20 +0000342 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000343 Result.resize(Tok.getLength());
344 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000345 return Result;
346}
347
348/// getSpelling - This method is used to get the spelling of a token into a
349/// preallocated buffer, instead of as an std::string. The caller is required
350/// to allocate enough space for the token, which is guaranteed to be at least
351/// Tok.getLength() bytes long. The actual length of the token is returned.
352///
353/// Note that this method may do two possible things: it may either fill in
354/// the buffer specified with characters, or it may *change the input pointer*
355/// to point to a constant buffer with the data already in it (avoiding a
356/// copy). The caller is not allowed to modify the returned buffer pointer
357/// if an internal buffer is returned.
358unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
359 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000360 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000361 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000362
Craig Topperd2d442c2014-05-17 23:10:59 +0000363 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000364 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
365 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000366 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000367 else if (!Tok.hasUCN()) {
368 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
369 // Just return the string from the identifier table, which is very quick.
370 Buffer = II->getNameStart();
371 return II->getLength();
372 }
Chris Lattner39720112010-11-17 07:26:20 +0000373 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000374
375 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000376 if (Tok.isLiteral())
377 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000378
Craig Topperd2d442c2014-05-17 23:10:59 +0000379 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000380 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000381 bool CharDataInvalid = false;
382 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
383 if (Invalid)
384 *Invalid = CharDataInvalid;
385 if (CharDataInvalid) {
386 Buffer = "";
387 return 0;
388 }
389 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000390
Chris Lattner39720112010-11-17 07:26:20 +0000391 // If this token contains nothing interesting, return it directly.
392 if (!Tok.needsCleaning()) {
393 Buffer = TokStart;
394 return Tok.getLength();
395 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000396
Chris Lattner39720112010-11-17 07:26:20 +0000397 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000398 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000399}
400
401
Chris Lattner8e129c22007-10-17 21:18:47 +0000402/// MeasureTokenLength - Relex the token at the specified location and return
403/// its length in bytes in the input file. If the token needs cleaning (e.g.
404/// includes a trigraph or an escaped newline) then this count includes bytes
405/// that are part of that.
406unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000407 const SourceManager &SM,
408 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000409 Token TheTok;
410 if (getRawToken(Loc, TheTok, SM, LangOpts))
411 return 0;
412 return TheTok.getLength();
413}
414
415/// \brief Relex the token at the specified location.
416/// \returns true if there was a failure, false on success.
417bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
418 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000419 const LangOptions &LangOpts,
420 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000421 // TODO: this could be special cased for common tokens like identifiers, ')',
422 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000423 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000424 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
425 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000426
427 // If this comes from a macro expansion, we really do want the macro name, not
428 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000429 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000430 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000431 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000432 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000433 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000434 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000435
436 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000437
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000438 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000439 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000440
Chris Lattner8e129c22007-10-17 21:18:47 +0000441 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000442 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
443 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000444 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000445 TheLexer.LexFromRawLexer(Result);
446 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000447}
448
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000449static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
450 const SourceManager &SM,
451 const LangOptions &LangOpts) {
452 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000453 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000454 if (LocInfo.first.isInvalid())
455 return Loc;
456
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000457 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000458 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000459 if (Invalid)
460 return Loc;
461
462 // Back up from the current location until we hit the beginning of a line
463 // (or the buffer). We'll relex from that point.
464 const char *BufStart = Buffer.data();
Douglas Gregor86af9842011-01-31 22:42:36 +0000465 if (LocInfo.second >= Buffer.size())
466 return Loc;
467
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000468 const char *StrData = BufStart+LocInfo.second;
469 if (StrData[0] == '\n' || StrData[0] == '\r')
470 return Loc;
471
472 const char *LexStart = StrData;
473 while (LexStart != BufStart) {
474 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
475 ++LexStart;
476 break;
477 }
478
479 --LexStart;
480 }
481
482 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000483 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000484 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
485 TheLexer.SetCommentRetentionState(true);
486
487 // Lex tokens until we find the token that contains the source location.
488 Token TheTok;
489 do {
490 TheLexer.LexFromRawLexer(TheTok);
491
492 if (TheLexer.getBufferLocation() > StrData) {
493 // Lexing this token has taken the lexer past the source location we're
494 // looking for. If the current token encompasses our source location,
495 // return the beginning of that token.
496 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
497 return TheTok.getLocation();
498
499 // We ended up skipping over the source location entirely, which means
500 // that it points into whitespace. We're done here.
501 break;
502 }
503 } while (TheTok.getKind() != tok::eof);
504
505 // We've passed our source location; just return the original source location.
506 return Loc;
507}
508
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000509SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
510 const SourceManager &SM,
511 const LangOptions &LangOpts) {
512 if (Loc.isFileID())
513 return getBeginningOfFileToken(Loc, SM, LangOpts);
514
515 if (!SM.isMacroArgExpansion(Loc))
516 return Loc;
517
518 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
519 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
520 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000521 std::pair<FileID, unsigned> BeginFileLocInfo
522 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000523 assert(FileLocInfo.first == BeginFileLocInfo.first &&
524 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000525 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000526}
527
Douglas Gregoraf82e352010-07-20 20:18:03 +0000528namespace {
529 enum PreambleDirectiveKind {
530 PDK_Skipped,
531 PDK_StartIf,
532 PDK_EndIf,
533 PDK_Unknown
534 };
535}
536
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000537std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
David Blaikie3d95d852014-08-11 22:08:06 +0000538 const LangOptions &LangOpts,
539 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000540 // Create a lexer starting at the beginning of the file. Note that we use a
541 // "fake" file source location at offset 1 so that the lexer will track our
542 // position within the file.
543 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000544 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000545 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
546 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000547 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000548
549 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
550 SourceLocation StartLoc = TheLexer.getSourceLocation();
551
Douglas Gregoraf82e352010-07-20 20:18:03 +0000552 bool InPreprocessorDirective = false;
553 Token TheTok;
554 Token IfStartTok;
555 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000556 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000557
558 unsigned MaxLineOffset = 0;
559 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000560 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000561 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000562 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000563 char ch = *CurPtr++;
564 if (ch == '\n') {
565 ++CurLine;
566 if (CurLine == MaxLines)
567 break;
568 }
569 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000570 if (CurPtr != Buffer.end())
571 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000572 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000573
Douglas Gregoraf82e352010-07-20 20:18:03 +0000574 do {
575 TheLexer.LexFromRawLexer(TheTok);
576
577 if (InPreprocessorDirective) {
578 // If we've hit the end of the file, we're done.
579 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000580 break;
581 }
582
583 // If we haven't hit the end of the preprocessor directive, skip this
584 // token.
585 if (!TheTok.isAtStartOfLine())
586 continue;
587
588 // We've passed the end of the preprocessor directive, and will look
589 // at this token again below.
590 InPreprocessorDirective = false;
591 }
592
Douglas Gregor028d3e42010-08-09 20:45:32 +0000593 // Keep track of the # of lines in the preamble.
594 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000595 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000596
597 // If we were asked to limit the number of lines in the preamble,
598 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000599 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000600 break;
601 }
602
Douglas Gregoraf82e352010-07-20 20:18:03 +0000603 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000604 if (TheTok.getKind() == tok::comment) {
605 if (ActiveCommentLoc.isInvalid())
606 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000607 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000608 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000609
610 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
611 // This is the start of a preprocessor directive.
612 Token HashTok = TheTok;
613 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000614 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000615
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000616 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000617 // we don't have an identifier table available. Instead, just look at
618 // the raw identifier to recognize and categorize preprocessor directives.
619 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000620 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000621 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000622 PreambleDirectiveKind PDK
623 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
624 .Case("include", PDK_Skipped)
625 .Case("__include_macros", PDK_Skipped)
626 .Case("define", PDK_Skipped)
627 .Case("undef", PDK_Skipped)
628 .Case("line", PDK_Skipped)
629 .Case("error", PDK_Skipped)
630 .Case("pragma", PDK_Skipped)
631 .Case("import", PDK_Skipped)
632 .Case("include_next", PDK_Skipped)
633 .Case("warning", PDK_Skipped)
634 .Case("ident", PDK_Skipped)
635 .Case("sccs", PDK_Skipped)
636 .Case("assert", PDK_Skipped)
637 .Case("unassert", PDK_Skipped)
638 .Case("if", PDK_StartIf)
639 .Case("ifdef", PDK_StartIf)
640 .Case("ifndef", PDK_StartIf)
641 .Case("elif", PDK_Skipped)
642 .Case("else", PDK_Skipped)
643 .Case("endif", PDK_EndIf)
644 .Default(PDK_Unknown);
645
646 switch (PDK) {
647 case PDK_Skipped:
648 continue;
649
650 case PDK_StartIf:
651 if (IfCount == 0)
652 IfStartTok = HashTok;
653
654 ++IfCount;
655 continue;
656
657 case PDK_EndIf:
658 // Mismatched #endif. The preamble ends here.
659 if (IfCount == 0)
660 break;
661
662 --IfCount;
663 continue;
664
665 case PDK_Unknown:
666 // We don't know what this directive is; stop at the '#'.
667 break;
668 }
669 }
670
671 // We only end up here if we didn't recognize the preprocessor
672 // directive or it was one that can't occur in the preamble at this
673 // point. Roll back the current token to the location of the '#'.
674 InPreprocessorDirective = false;
675 TheTok = HashTok;
676 }
677
Douglas Gregor028d3e42010-08-09 20:45:32 +0000678 // We hit a token that we don't recognize as being in the
679 // "preprocessing only" part of the file, so we're no longer in
680 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000681 break;
682 } while (true);
683
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000684 SourceLocation End;
685 if (IfCount)
686 End = IfStartTok.getLocation();
687 else if (ActiveCommentLoc.isValid())
688 End = ActiveCommentLoc; // don't truncate a decl comment.
689 else
690 End = TheTok.getLocation();
691
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000692 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
693 IfCount? IfStartTok.isAtStartOfLine()
694 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000695}
696
Chris Lattner2a6ee912010-11-17 07:05:50 +0000697
698/// AdvanceToTokenCharacter - Given a location that specifies the start of a
699/// token, return a new location that specifies a character within the token.
700SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
701 unsigned CharNo,
702 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000703 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000704 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000705 // character is. This needs to take into consideration newlines and
706 // trigraphs.
707 bool Invalid = false;
708 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
709
710 // If they request the first char of the token, we're trivially done.
711 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
712 return TokStart;
713
714 unsigned PhysOffset = 0;
715
716 // The usual case is that tokens don't contain anything interesting. Skip
717 // over the uninteresting characters. If a token only consists of simple
718 // chars, this method is extremely fast.
719 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
720 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000721 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000722 ++TokPtr, --CharNo, ++PhysOffset;
723 }
724
725 // If we have a character that may be a trigraph or escaped newline, use a
726 // lexer to parse it correctly.
727 for (; CharNo; --CharNo) {
728 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000729 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000730 TokPtr += Size;
731 PhysOffset += Size;
732 }
733
734 // Final detail: if we end up on an escaped newline, we want to return the
735 // location of the actual byte of the token. For example foo\<newline>bar
736 // advanced by 3 should return the location of b, not of \\. One compounding
737 // detail of this is that the escape may be made by a trigraph.
738 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
739 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
740
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000741 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000742}
743
744/// \brief Computes the source location just past the end of the
745/// token at this source location.
746///
747/// This routine can be used to produce a source location that
748/// points just past the end of the token referenced by \p Loc, and
749/// is generally used when a diagnostic needs to point just after a
750/// token where it expected something different that it received. If
751/// the returned source location would not be meaningful (e.g., if
752/// it points into a macro), this routine returns an invalid
753/// source location.
754///
755/// \param Offset an offset from the end of the token, where the source
756/// location should refer to. The default offset (0) produces a source
757/// location pointing just past the end of the token; an offset of 1 produces
758/// a source location pointing to the last character in the token, etc.
759SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
760 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000762 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000763 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000764
765 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000766 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000767 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000768 }
769
David Blaikiebbafb8a2012-03-11 07:00:24 +0000770 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000771 if (Len > Offset)
772 Len = Len - Offset;
773 else
774 return Loc;
775
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000776 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000777}
778
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000779/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000780/// token of the macro expansion.
781bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000782 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000783 const LangOptions &LangOpts,
784 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000785 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
786
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000787 SourceLocation expansionLoc;
788 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
789 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000790
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000791 if (expansionLoc.isFileID()) {
792 // No other macro expansions, this is the first.
793 if (MacroBegin)
794 *MacroBegin = expansionLoc;
795 return true;
796 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000797
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000798 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799}
800
801/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000802/// token of the macro expansion.
803bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000804 const SourceManager &SM,
805 const LangOptions &LangOpts,
806 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000807 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
808
809 SourceLocation spellLoc = SM.getSpellingLoc(loc);
810 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
811 if (tokLen == 0)
812 return false;
813
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000814 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
815 SourceLocation expansionLoc;
816 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
817 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000818
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000819 if (expansionLoc.isFileID()) {
820 // No other macro expansions.
821 if (MacroEnd)
822 *MacroEnd = expansionLoc;
823 return true;
824 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000825
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000826 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000827}
828
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000829static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000830 const SourceManager &SM,
831 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000832 SourceLocation Begin = Range.getBegin();
833 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000834 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000835 if (Range.isTokenRange()) {
836 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
837 if (End.isInvalid())
838 return CharSourceRange();
839 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000840
841 // Break down the source locations.
842 FileID FID;
843 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000844 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000845 if (FID.isInvalid())
846 return CharSourceRange();
847
848 unsigned EndOffs;
849 if (!SM.isInFileID(End, FID, &EndOffs) ||
850 BeginOffs > EndOffs)
851 return CharSourceRange();
852
853 return CharSourceRange::getCharRange(Begin, End);
854}
855
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000856CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000857 const SourceManager &SM,
858 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000859 SourceLocation Begin = Range.getBegin();
860 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000861 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000862 return CharSourceRange();
863
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000864 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000865 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000866
867 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000868 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
869 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000870 Range.setBegin(Begin);
871 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000872 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000873
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000874 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000875 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
876 &End)) ||
877 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
878 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000879 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000880 Range.setEnd(End);
881 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000882 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000883
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000884 assert(Begin.isMacroID() && End.isMacroID());
885 SourceLocation MacroBegin, MacroEnd;
886 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000887 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
888 &MacroEnd)) ||
889 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
890 &MacroEnd)))) {
891 Range.setBegin(MacroBegin);
892 Range.setEnd(MacroEnd);
893 return makeRangeFromFileLocs(Range, SM, LangOpts);
894 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000895
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000896 bool Invalid = false;
897 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
898 &Invalid);
899 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000900 return CharSourceRange();
901
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000902 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
903 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
904 &Invalid);
905 if (Invalid)
906 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000907
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000908 if (EndEntry.getExpansion().isMacroArgExpansion() &&
909 BeginEntry.getExpansion().getExpansionLocStart() ==
910 EndEntry.getExpansion().getExpansionLocStart()) {
911 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
912 Range.setEnd(SM.getImmediateSpellingLoc(End));
913 return makeFileCharRange(Range, SM, LangOpts);
914 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000915 }
916
917 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000918}
919
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000920StringRef Lexer::getSourceText(CharSourceRange Range,
921 const SourceManager &SM,
922 const LangOptions &LangOpts,
923 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000924 Range = makeFileCharRange(Range, SM, LangOpts);
925 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000926 if (Invalid) *Invalid = true;
927 return StringRef();
928 }
929
930 // Break down the source location.
931 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
932 if (beginInfo.first.isInvalid()) {
933 if (Invalid) *Invalid = true;
934 return StringRef();
935 }
936
937 unsigned EndOffs;
938 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
939 beginInfo.second > EndOffs) {
940 if (Invalid) *Invalid = true;
941 return StringRef();
942 }
943
944 // Try to the load the file buffer.
945 bool invalidTemp = false;
946 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
947 if (invalidTemp) {
948 if (Invalid) *Invalid = true;
949 return StringRef();
950 }
951
952 if (Invalid) *Invalid = false;
953 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
954}
955
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000956StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
957 const SourceManager &SM,
958 const LangOptions &LangOpts) {
959 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000960
961 // Find the location of the immediate macro expansion.
962 while (1) {
963 FileID FID = SM.getFileID(Loc);
964 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
965 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
966 Loc = Expansion.getExpansionLocStart();
967 if (!Expansion.isMacroArgExpansion())
968 break;
969
970 // For macro arguments we need to check that the argument did not come
971 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
972
973 // Loc points to the argument id of the macro definition, move to the
974 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000975 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000976 SourceLocation SpellLoc = Expansion.getSpellingLoc();
977 if (SpellLoc.isFileID())
978 break; // No inner macro.
979
980 // If spelling location resides in the same FileID as macro expansion
981 // location, it means there is no inner macro.
982 FileID MacroFID = SM.getFileID(Loc);
983 if (SM.isInFileID(SpellLoc, MacroFID))
984 break;
985
986 // Argument came from inner macro.
987 Loc = SpellLoc;
988 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000989
990 // Find the spelling location of the start of the non-argument expansion
991 // range. This is where the macro name was spelled in order to begin
992 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000993 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000994
995 // Dig out the buffer where the macro name was spelled and the extents of the
996 // name so that we can render it into the expansion note.
997 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
998 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
999 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1000 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1001}
1002
Jordan Rose288c4212012-06-07 01:10:31 +00001003bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001004 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001005}
1006
Chris Lattnerd01e2912006-06-18 16:22:51 +00001007
Chris Lattner22eb9722006-06-18 05:43:12 +00001008//===----------------------------------------------------------------------===//
1009// Diagnostics forwarding code.
1010//===----------------------------------------------------------------------===//
1011
Chris Lattner619c1742007-07-22 18:38:25 +00001012/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001013/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001014/// This is currently only used for _Pragma implementation, so it is the slow
1015/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001016static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1017 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001018static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1019 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001020 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001021 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner619c1742007-07-22 18:38:25 +00001023 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001024 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001025 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001026 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001027
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001028 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001029 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001030 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001031 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001032
Chris Lattner9dc9c202009-02-15 20:52:18 +00001033 // Figure out the expansion loc range, which is the range covered by the
1034 // original _Pragma(...) sequence.
1035 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001036 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chandler Carruth115b0772011-07-26 03:03:05 +00001038 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001039}
1040
Chris Lattner22eb9722006-06-18 05:43:12 +00001041/// getSourceLocation - Return a source location identifier for the specified
1042/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001043SourceLocation Lexer::getSourceLocation(const char *Loc,
1044 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001045 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001046 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001047
1048 // In the normal case, we're just lexing from a simple file buffer, return
1049 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001050 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001051 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001052 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001053
Chris Lattnerd32480d2009-01-17 06:22:33 +00001054 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1055 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001056 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001057 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001058}
1059
Chris Lattner22eb9722006-06-18 05:43:12 +00001060/// Diag - Forwarding function for diagnostics. This translate a source
1061/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001062DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001063 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001064}
1065
1066//===----------------------------------------------------------------------===//
1067// Trigraph and Escaped Newline Handling Code.
1068//===----------------------------------------------------------------------===//
1069
1070/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1071/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1072static char GetTrigraphCharForLetter(char Letter) {
1073 switch (Letter) {
1074 default: return 0;
1075 case '=': return '#';
1076 case ')': return ']';
1077 case '(': return '[';
1078 case '!': return '|';
1079 case '\'': return '^';
1080 case '>': return '}';
1081 case '/': return '\\';
1082 case '<': return '{';
1083 case '-': return '~';
1084 }
1085}
1086
1087/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1088/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1089/// return the result character. Finally, emit a warning about trigraph use
1090/// whether trigraphs are enabled or not.
1091static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1092 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001093 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001094
David Blaikiebbafb8a2012-03-11 07:00:24 +00001095 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001096 if (!L->isLexingRawMode())
1097 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001098 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001099 }
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattner6d27a162008-11-22 02:02:22 +00001101 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001102 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001103 return Res;
1104}
1105
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001106/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1107/// 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 +00001108/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001109unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1110 unsigned Size = 0;
1111 while (isWhitespace(Ptr[Size])) {
1112 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001113
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001114 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1115 continue;
1116
1117 // If this is a \r\n or \n\r, skip the other half.
1118 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1119 Ptr[Size-1] != Ptr[Size])
1120 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001122 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001123 }
1124
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001125 // Not an escaped newline, must be a \t or something else.
1126 return 0;
1127}
1128
Chris Lattner38b2cde2009-04-18 22:27:02 +00001129/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1130/// them), skip over them and return the first non-escaped-newline found,
1131/// otherwise return P.
1132const char *Lexer::SkipEscapedNewLines(const char *P) {
1133 while (1) {
1134 const char *AfterEscape;
1135 if (*P == '\\') {
1136 AfterEscape = P+1;
1137 } else if (*P == '?') {
1138 // If not a trigraph for escape, bail out.
1139 if (P[1] != '?' || P[2] != '/')
1140 return P;
1141 AfterEscape = P+3;
1142 } else {
1143 return P;
1144 }
Mike Stump11289f42009-09-09 15:08:12 +00001145
Chris Lattner38b2cde2009-04-18 22:27:02 +00001146 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1147 if (NewLineSize == 0) return P;
1148 P = AfterEscape+NewLineSize;
1149 }
1150}
1151
Anna Zaks59a3c802011-07-27 21:43:43 +00001152/// \brief Checks that the given token is the first token that occurs after the
1153/// given location (this excludes comments and whitespace). Returns the location
1154/// immediately after the specified token. If the token is not found or the
1155/// location is inside a macro, the returned source location will be invalid.
1156SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1157 tok::TokenKind TKind,
1158 const SourceManager &SM,
1159 const LangOptions &LangOpts,
1160 bool SkipTrailingWhitespaceAndNewLine) {
1161 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001162 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001163 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001164 }
1165 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1166
1167 // Break down the source location.
1168 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1169
1170 // Try to load the file buffer.
1171 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001172 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001173 if (InvalidTemp)
1174 return SourceLocation();
1175
1176 const char *TokenBegin = File.data() + LocInfo.second;
1177
1178 // Lex from the start of the given location.
1179 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1180 TokenBegin, File.end());
1181 // Find the token.
1182 Token Tok;
1183 lexer.LexFromRawLexer(Tok);
1184 if (Tok.isNot(TKind))
1185 return SourceLocation();
1186 SourceLocation TokenLoc = Tok.getLocation();
1187
1188 // Calculate how much whitespace needs to be skipped if any.
1189 unsigned NumWhitespaceChars = 0;
1190 if (SkipTrailingWhitespaceAndNewLine) {
1191 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1192 Tok.getLength();
1193 unsigned char C = *TokenEnd;
1194 while (isHorizontalWhitespace(C)) {
1195 C = *(++TokenEnd);
1196 NumWhitespaceChars++;
1197 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001198
1199 // Skip \r, \n, \r\n, or \n\r
1200 if (C == '\n' || C == '\r') {
1201 char PrevC = C;
1202 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001203 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001204 if ((C == '\n' || C == '\r') && C != PrevC)
1205 NumWhitespaceChars++;
1206 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001207 }
1208
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001209 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001210}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001211
Chris Lattner22eb9722006-06-18 05:43:12 +00001212/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1213/// get its size, and return it. This is tricky in several cases:
1214/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1215/// then either return the trigraph (skipping 3 chars) or the '?',
1216/// depending on whether trigraphs are enabled or not.
1217/// 2. If this is an escaped newline (potentially with whitespace between
1218/// the backslash and newline), implicitly skip the newline and return
1219/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001220///
1221/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1222/// know that we can accumulate into Size, and that we have already incremented
1223/// Ptr by Size bytes.
1224///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001225/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1226/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001227///
1228char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001229 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001230 // If we have a slash, look for an escaped newline.
1231 if (Ptr[0] == '\\') {
1232 ++Size;
1233 ++Ptr;
1234Slash:
1235 // Common case, backslash-char where the char is not whitespace.
1236 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattnerc1835952009-06-23 05:15:06 +00001238 // See if we have optional whitespace characters between the slash and
1239 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001240 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1241 // Remember that this token needs to be cleaned.
1242 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001243
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001244 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001245 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001246 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001247
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001248 // Found backslash<whitespace><newline>. Parse the char after it.
1249 Size += EscapedNewLineSize;
1250 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001251
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001252 // If the char that we finally got was a \n, then we must have had
1253 // something like \<newline><newline>. We don't want to consume the
1254 // second newline.
1255 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1256 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001257
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001258 // Use slow version to accumulate a correct size field.
1259 return getCharAndSizeSlow(Ptr, Size, Tok);
1260 }
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattner22eb9722006-06-18 05:43:12 +00001262 // Otherwise, this is not an escaped newline, just return the slash.
1263 return '\\';
1264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Chris Lattner22eb9722006-06-18 05:43:12 +00001266 // If this is a trigraph, process it.
1267 if (Ptr[0] == '?' && Ptr[1] == '?') {
1268 // If this is actually a legal trigraph (not something like "??x"), emit
1269 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001270 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001271 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001272 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001273
1274 Ptr += 3;
1275 Size += 3;
1276 if (C == '\\') goto Slash;
1277 return C;
1278 }
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Chris Lattner22eb9722006-06-18 05:43:12 +00001281 // If this is neither, return a single character.
1282 ++Size;
1283 return *Ptr;
1284}
1285
Chris Lattnerd01e2912006-06-18 16:22:51 +00001286
Chris Lattner22eb9722006-06-18 05:43:12 +00001287/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1288/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1289/// and that we have already incremented Ptr by Size bytes.
1290///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001291/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1292/// be updated to match.
1293char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001294 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001295 // If we have a slash, look for an escaped newline.
1296 if (Ptr[0] == '\\') {
1297 ++Size;
1298 ++Ptr;
1299Slash:
1300 // Common case, backslash-char where the char is not whitespace.
1301 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001302
Chris Lattner22eb9722006-06-18 05:43:12 +00001303 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001304 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1305 // Found backslash<whitespace><newline>. Parse the char after it.
1306 Size += EscapedNewLineSize;
1307 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001309 // If the char that we finally got was a \n, then we must have had
1310 // something like \<newline><newline>. We don't want to consume the
1311 // second newline.
1312 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1313 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001314
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001315 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001316 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattner22eb9722006-06-18 05:43:12 +00001319 // Otherwise, this is not an escaped newline, just return the slash.
1320 return '\\';
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattner22eb9722006-06-18 05:43:12 +00001323 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001325 // If this is actually a legal trigraph (not something like "??x"), return
1326 // it.
1327 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1328 Ptr += 3;
1329 Size += 3;
1330 if (C == '\\') goto Slash;
1331 return C;
1332 }
1333 }
Mike Stump11289f42009-09-09 15:08:12 +00001334
Chris Lattner22eb9722006-06-18 05:43:12 +00001335 // If this is neither, return a single character.
1336 ++Size;
1337 return *Ptr;
1338}
1339
Chris Lattner22eb9722006-06-18 05:43:12 +00001340//===----------------------------------------------------------------------===//
1341// Helper methods for lexing.
1342//===----------------------------------------------------------------------===//
1343
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001344/// \brief Routine that indiscriminately skips bytes in the source file.
1345void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1346 BufferPtr += Bytes;
1347 if (BufferPtr > BufferEnd)
1348 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001349 // FIXME: What exactly does the StartOfLine bit mean? There are two
1350 // possible meanings for the "start" of the line: the first token on the
1351 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001352 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001353 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001354}
1355
Jordan Rose58c61e02013-02-09 01:10:25 +00001356static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001357 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1358 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1359 C11AllowedIDCharRanges);
1360 return C11AllowedIDChars.contains(C);
1361 } else if (LangOpts.CPlusPlus) {
1362 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1363 CXX03AllowedIDCharRanges);
1364 return CXX03AllowedIDChars.contains(C);
1365 } else {
1366 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1367 C99AllowedIDCharRanges);
1368 return C99AllowedIDChars.contains(C);
1369 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001370}
1371
Jordan Rose58c61e02013-02-09 01:10:25 +00001372static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1373 assert(isAllowedIDChar(C, LangOpts));
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001374 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1375 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1376 C11DisallowedInitialIDCharRanges);
1377 return !C11DisallowedInitialIDChars.contains(C);
1378 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001379 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001380 } else {
1381 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1382 C99DisallowedInitialIDCharRanges);
1383 return !C99DisallowedInitialIDChars.contains(C);
1384 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001385}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001386
Jordan Rose58c61e02013-02-09 01:10:25 +00001387static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1388 const char *End) {
1389 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1390 L.getSourceLocation(End));
1391}
1392
1393static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1394 CharSourceRange Range, bool IsFirst) {
1395 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001396 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001397 enum {
1398 CannotAppearInIdentifier = 0,
1399 CannotStartIdentifier
1400 };
1401
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001402 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1403 C99AllowedIDCharRanges);
1404 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1405 C99DisallowedInitialIDCharRanges);
1406 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001407 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1408 << Range
1409 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001410 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001411 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1412 << Range
1413 << CannotStartIdentifier;
1414 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001415 }
1416
Jordan Rose58c61e02013-02-09 01:10:25 +00001417 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001418 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001419 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1420 CXX03AllowedIDCharRanges);
1421 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001422 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1423 << Range;
1424 }
1425 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001426}
1427
1428bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1429 Token &Result) {
1430 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001431 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001432 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1433 return false;
1434
1435 if (!isLexingRawMode())
1436 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1437 makeCharRange(*this, CurPtr, UCNPtr),
1438 /*IsFirst=*/false);
1439
1440 Result.setFlag(Token::HasUCN);
1441 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1442 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1443 CurPtr = UCNPtr;
1444 else
1445 while (CurPtr != UCNPtr)
1446 (void)getAndAdvanceChar(CurPtr, Result);
1447 return true;
1448}
1449
1450bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1451 const char *UnicodePtr = CurPtr;
1452 UTF32 CodePoint;
1453 ConversionResult Result =
1454 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1455 (const UTF8 *)BufferEnd,
1456 &CodePoint,
1457 strictConversion);
1458 if (Result != conversionOK ||
1459 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1460 return false;
1461
1462 if (!isLexingRawMode())
1463 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1464 makeCharRange(*this, CurPtr, UnicodePtr),
1465 /*IsFirst=*/false);
1466
1467 CurPtr = UnicodePtr;
1468 return true;
1469}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001470
Eli Friedman0834a4b2013-09-19 00:41:32 +00001471bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001472 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1473 unsigned Size;
1474 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001475 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001476 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001477
Chris Lattner22eb9722006-06-18 05:43:12 +00001478 --CurPtr; // Back up over the skipped character.
1479
1480 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1481 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001482 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001483 // TODO: Could merge these checks into an InfoTable flag to make the
1484 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001485 if (isASCII(C) && C != '\\' && C != '?' &&
1486 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001487FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001488 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001489 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1490 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001491
Chris Lattner0f1f5052006-07-20 04:16:23 +00001492 // If we are in raw mode, return this identifier raw. There is no need to
1493 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001494 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001495 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001496
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001497 // Fill in Result.IdentifierInfo and update the token kind,
1498 // looking up the identifier in the identifier table.
1499 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001500
Chris Lattnerc5a00062006-06-18 16:41:01 +00001501 // Finally, now that we know we have an identifier, pass this off to the
1502 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001503 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001504 return PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001505
Eli Friedman0834a4b2013-09-19 00:41:32 +00001506 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 }
Mike Stump11289f42009-09-09 15:08:12 +00001508
Chris Lattner22eb9722006-06-18 05:43:12 +00001509 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001510
Chris Lattner22eb9722006-06-18 05:43:12 +00001511 C = getCharAndSize(CurPtr, Size);
1512 while (1) {
1513 if (C == '$') {
1514 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001515 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001516
Chris Lattner22eb9722006-06-18 05:43:12 +00001517 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001518 if (!isLexingRawMode())
1519 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001520 CurPtr = ConsumeChar(CurPtr, Size, Result);
1521 C = getCharAndSize(CurPtr, Size);
1522 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001523
Richard Smith8b7258b2014-02-17 21:52:30 +00001524 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001525 C = getCharAndSize(CurPtr, Size);
1526 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001527 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001528 C = getCharAndSize(CurPtr, Size);
1529 continue;
1530 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001531 goto FinishIdentifier;
1532 }
1533
1534 // Otherwise, this character is good, consume it.
1535 CurPtr = ConsumeChar(CurPtr, Size, Result);
1536
1537 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001538 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001539 CurPtr = ConsumeChar(CurPtr, Size, Result);
1540 C = getCharAndSize(CurPtr, Size);
1541 }
1542 }
1543}
1544
Douglas Gregor759ef232010-08-30 14:50:47 +00001545/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001546/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001547bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001548 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001549 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001550 if (C1 != '0')
1551 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001552 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001553 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001554}
Chris Lattner22eb9722006-06-18 05:43:12 +00001555
Nate Begeman5eee9332008-04-14 02:26:39 +00001556/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001557/// constant. From[-1] is the first character lexed. Return the end of the
1558/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001559bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001560 unsigned Size;
1561 char C = getCharAndSize(CurPtr, Size);
1562 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001563 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001564 CurPtr = ConsumeChar(CurPtr, Size, Result);
1565 PrevCh = C;
1566 C = getCharAndSize(CurPtr, Size);
1567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Chris Lattner22eb9722006-06-18 05:43:12 +00001569 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001570 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1571 // If we are in Microsoft mode, don't continue if the constant is hex.
1572 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001573 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001574 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1575 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001576
1577 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001578 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1579 // Outside C99, we accept hexadecimal floating point numbers as a
1580 // not-quite-conforming extension. Only do so if this looks like it's
1581 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1582 bool IsHexFloat = true;
1583 if (!LangOpts.C99) {
1584 if (!isHexaLiteral(BufferPtr, LangOpts))
1585 IsHexFloat = false;
1586 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1587 IsHexFloat = false;
1588 }
1589 if (IsHexFloat)
1590 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
Richard Smithfde94852013-09-26 03:33:06 +00001593 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001594 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001595 unsigned NextSize;
1596 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001597 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001598 if (!isLexingRawMode())
1599 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1600 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001601 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001602 return LexNumericConstant(Result, CurPtr);
1603 }
1604 }
1605
Richard Smith8b7258b2014-02-17 21:52:30 +00001606 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1607 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1608 return LexNumericConstant(Result, CurPtr);
1609 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1610 return LexNumericConstant(Result, CurPtr);
1611
Chris Lattnerd01e2912006-06-18 16:22:51 +00001612 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001613 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001614 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001615 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001616 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001617}
1618
Richard Smithe18f0fa2012-03-05 04:02:15 +00001619/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001620/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001621const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1622 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001623 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001624
Richard Smith8b7258b2014-02-17 21:52:30 +00001625 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001626 unsigned Size;
1627 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001628 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001629
Richard Smith8b7258b2014-02-17 21:52:30 +00001630 if (!isIdentifierHead(C)) {
1631 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1632 Consumed = true;
1633 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1634 Consumed = true;
1635 else
1636 return CurPtr;
1637 }
1638
1639 if (!getLangOpts().CPlusPlus11) {
1640 if (!isLexingRawMode())
1641 Diag(CurPtr,
1642 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1643 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1644 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1645 return CurPtr;
1646 }
1647
1648 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1649 // that does not start with an underscore is ill-formed. As a conforming
1650 // extension, we treat all such suffixes as if they had whitespace before
1651 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1652 // likely to be a ud-suffix than a macro, however, and accept that.
1653 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001654 bool IsUDSuffix = false;
1655 if (C == '_')
1656 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001657 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001658 // In C++1y, we need to look ahead a few characters to see if this is a
1659 // valid suffix for a string literal or a numeric literal (this could be
1660 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001661 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001662 char Buffer[MaxStandardSuffixLength] = { C };
1663 unsigned Consumed = Size;
1664 unsigned Chars = 1;
1665 while (true) {
1666 unsigned NextSize;
1667 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1668 getLangOpts());
1669 if (!isIdentifierBody(Next)) {
1670 // End of suffix. Check whether this is on the whitelist.
1671 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1672 NumericLiteralParser::isValidUDSuffix(
1673 getLangOpts(), StringRef(Buffer, Chars));
1674 break;
1675 }
1676
1677 if (Chars == MaxStandardSuffixLength)
1678 // Too long: can't be a standard suffix.
1679 break;
1680
1681 Buffer[Chars++] = Next;
1682 Consumed += NextSize;
1683 }
Richard Smithf4198b72013-07-23 08:14:48 +00001684 }
1685
1686 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001687 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001688 Diag(CurPtr, getLangOpts().MSVCCompat
1689 ? diag::ext_ms_reserved_user_defined_literal
1690 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001691 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001692 return CurPtr;
1693 }
1694
Richard Smith8b7258b2014-02-17 21:52:30 +00001695 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001696 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001697
1698 Result.setFlag(Token::HasUDSuffix);
1699 while (true) {
1700 C = getCharAndSize(CurPtr, Size);
1701 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1702 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1703 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1704 else break;
1705 }
1706
Richard Smithe18f0fa2012-03-05 04:02:15 +00001707 return CurPtr;
1708}
1709
Chris Lattner22eb9722006-06-18 05:43:12 +00001710/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001711/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001712bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001713 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001714 // Does this string contain the \0 character?
1715 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001716
Richard Smithacd4d3d2011-10-15 01:18:56 +00001717 if (!isLexingRawMode() &&
1718 (Kind == tok::utf8_string_literal ||
1719 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001720 Kind == tok::utf32_string_literal))
1721 Diag(BufferPtr, getLangOpts().CPlusPlus
1722 ? diag::warn_cxx98_compat_unicode_literal
1723 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001724
Chris Lattner22eb9722006-06-18 05:43:12 +00001725 char C = getAndAdvanceChar(CurPtr, Result);
1726 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001727 // Skip escaped characters. Escaped newlines will already be processed by
1728 // getAndAdvanceChar.
1729 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001730 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001731
Chris Lattner52d96ac2010-05-30 23:27:38 +00001732 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001733 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001734 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001735 Diag(BufferPtr, diag::ext_unterminated_string);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001736 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001737 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001738 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001739
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001740 if (C == 0) {
1741 if (isCodeCompletionPoint(CurPtr-1)) {
1742 PP->CodeCompleteNaturalLanguage();
1743 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001744 cutOffLexing();
1745 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001746 }
1747
Chris Lattner52d96ac2010-05-30 23:27:38 +00001748 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001749 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001750 C = getAndAdvanceChar(CurPtr, Result);
1751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Richard Smithe18f0fa2012-03-05 04:02:15 +00001753 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001754 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001755 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001756
Chris Lattner5a78a022006-07-20 06:02:19 +00001757 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001758 if (NulCharacter && !isLexingRawMode())
1759 Diag(NulCharacter, diag::null_in_string);
Chris Lattner22eb9722006-06-18 05:43:12 +00001760
Chris Lattnerd01e2912006-06-18 16:22:51 +00001761 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001762 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001763 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001764 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001765 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001766}
1767
Craig Topper54edcca2011-08-11 04:06:15 +00001768/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1769/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001770bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001771 tok::TokenKind Kind) {
1772 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1773 // Between the initial and final double quote characters of the raw string,
1774 // any transformations performed in phases 1 and 2 (trigraphs,
1775 // universal-character-names, and line splicing) are reverted.
1776
Richard Smithacd4d3d2011-10-15 01:18:56 +00001777 if (!isLexingRawMode())
1778 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1779
Craig Topper54edcca2011-08-11 04:06:15 +00001780 unsigned PrefixLen = 0;
1781
1782 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1783 ++PrefixLen;
1784
1785 // If the last character was not a '(', then we didn't lex a valid delimiter.
1786 if (CurPtr[PrefixLen] != '(') {
1787 if (!isLexingRawMode()) {
1788 const char *PrefixEnd = &CurPtr[PrefixLen];
1789 if (PrefixLen == 16) {
1790 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1791 } else {
1792 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1793 << StringRef(PrefixEnd, 1);
1794 }
1795 }
1796
1797 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1798 // it's possible the '"' was intended to be part of the raw string, but
1799 // there's not much we can do about that.
1800 while (1) {
1801 char C = *CurPtr++;
1802
1803 if (C == '"')
1804 break;
1805 if (C == 0 && CurPtr-1 == BufferEnd) {
1806 --CurPtr;
1807 break;
1808 }
1809 }
1810
1811 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001812 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001813 }
1814
1815 // Save prefix and move CurPtr past it
1816 const char *Prefix = CurPtr;
1817 CurPtr += PrefixLen + 1; // skip over prefix and '('
1818
1819 while (1) {
1820 char C = *CurPtr++;
1821
1822 if (C == ')') {
1823 // Check for prefix match and closing quote.
1824 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1825 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1826 break;
1827 }
1828 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1829 if (!isLexingRawMode())
1830 Diag(BufferPtr, diag::err_unterminated_raw_string)
1831 << StringRef(Prefix, PrefixLen);
1832 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001833 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001834 }
1835 }
1836
Richard Smithe18f0fa2012-03-05 04:02:15 +00001837 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001838 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001839 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001840
Craig Topper54edcca2011-08-11 04:06:15 +00001841 // Update the location of token as well as BufferPtr.
1842 const char *TokStart = BufferPtr;
1843 FormTokenWithChars(Result, CurPtr, Kind);
1844 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001845 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001846}
1847
Chris Lattner22eb9722006-06-18 05:43:12 +00001848/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1849/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001850bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001851 // Does this string contain the \0 character?
1852 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001853 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001854 char C = getAndAdvanceChar(CurPtr, Result);
1855 while (C != '>') {
1856 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001857 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001858 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001859 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001860 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001861 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1862 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001863 // If the filename is unterminated, then it must just be a lone <
1864 // character. Return this as such.
1865 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001866 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001867 } else if (C == 0) {
1868 NulCharacter = CurPtr-1;
1869 }
1870 C = getAndAdvanceChar(CurPtr, Result);
1871 }
Mike Stump11289f42009-09-09 15:08:12 +00001872
Chris Lattner5a78a022006-07-20 06:02:19 +00001873 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001874 if (NulCharacter && !isLexingRawMode())
1875 Diag(NulCharacter, diag::null_in_string);
Mike Stump11289f42009-09-09 15:08:12 +00001876
Chris Lattnerd01e2912006-06-18 16:22:51 +00001877 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001878 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001879 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001880 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001881 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001882}
1883
1884
1885/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001886/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001887bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001888 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001889 // Does this character contain the \0 character?
1890 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001891
Richard Smith3e3a7052014-11-08 06:08:42 +00001892 if (!isLexingRawMode()) {
1893 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1894 Diag(BufferPtr, getLangOpts().CPlusPlus
1895 ? diag::warn_cxx98_compat_unicode_literal
1896 : diag::warn_c99_compat_unicode_literal);
1897 else if (Kind == tok::utf8_char_constant)
1898 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1899 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001900
Chris Lattner22eb9722006-06-18 05:43:12 +00001901 char C = getAndAdvanceChar(CurPtr, Result);
1902 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001903 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001904 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001905 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001906 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001907 }
1908
1909 while (C != '\'') {
1910 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001911 if (C == '\\')
1912 C = getAndAdvanceChar(CurPtr, Result);
1913
1914 if (C == '\n' || C == '\r' || // Newline.
1915 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001916 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001917 Diag(BufferPtr, diag::ext_unterminated_char);
Chris Lattner86851b82010-07-07 23:24:27 +00001918 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001919 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001920 }
1921
1922 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001923 if (isCodeCompletionPoint(CurPtr-1)) {
1924 PP->CodeCompleteNaturalLanguage();
1925 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001926 cutOffLexing();
1927 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001928 }
1929
Chris Lattner86851b82010-07-07 23:24:27 +00001930 NulCharacter = CurPtr-1;
1931 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001932 C = getAndAdvanceChar(CurPtr, Result);
1933 }
Mike Stump11289f42009-09-09 15:08:12 +00001934
Richard Smithe18f0fa2012-03-05 04:02:15 +00001935 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001936 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001937 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001938
Chris Lattner86851b82010-07-07 23:24:27 +00001939 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001940 if (NulCharacter && !isLexingRawMode())
1941 Diag(NulCharacter, diag::null_in_char);
Chris Lattner22eb9722006-06-18 05:43:12 +00001942
Chris Lattnerd01e2912006-06-18 16:22:51 +00001943 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001944 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001945 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001946 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001947 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001948}
1949
1950/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1951/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001952///
1953/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1954///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001955bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1956 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001957 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001958 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1959
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001960 unsigned char Char = *CurPtr;
1961
1962 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001963 while (1) {
1964 // Skip horizontal whitespace very aggressively.
1965 while (isHorizontalWhitespace(Char))
1966 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001967
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00001968 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001969 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00001970 break;
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattner22eb9722006-06-18 05:43:12 +00001972 if (ParsingPreprocessorDirective) {
1973 // End of preprocessor directive line, let LexTokenInternal handle this.
1974 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00001975 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001976 }
Mike Stump11289f42009-09-09 15:08:12 +00001977
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001978 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001979 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001980 Char = *++CurPtr;
1981 }
1982
Chris Lattner4d963442008-10-12 04:05:48 +00001983 // If the client wants us to return whitespace, return it now.
1984 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00001985 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001986 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001987 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001988 IsAtPhysicalStartOfLine = true;
1989 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001990 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00001991 return true;
1992 }
Mike Stump11289f42009-09-09 15:08:12 +00001993
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001994 // If this isn't immediately after a newline, there is leading space.
1995 char PrevChar = CurPtr[-1];
1996 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1997
1998 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001999 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002000 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002001 TokAtPhysicalStartOfLine = true;
2002 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002003
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002005 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002006}
2007
Nico Weber158a31a2012-11-11 07:02:14 +00002008/// We have just read the // characters from input. Skip until we find the
2009/// newline character thats terminate the comment. Then update BufferPtr and
2010/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002011///
2012/// If we're in KeepCommentMode or any CommentHandler has inserted
2013/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002014bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2015 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002016 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002017 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002018 if (!LangOpts.LineComment && !isLexingRawMode()) {
2019 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattner22eb9722006-06-18 05:43:12 +00002021 // Mark them enabled so we only emit one warning for this translation
2022 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002023 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattner22eb9722006-06-18 05:43:12 +00002026 // Scan over the body of the comment. The common case, when scanning, is that
2027 // the comment contains normal ascii characters with nothing interesting in
2028 // them. As such, optimize for this case with the inner loop.
2029 char C;
2030 do {
2031 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002032 // Skip over characters in the fast loop.
2033 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 C != '\n' && C != '\r') // Newline or DOS-style newline.
2035 C = *++CurPtr;
2036
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002037 const char *NextLine = CurPtr;
2038 if (C != 0) {
2039 // We found a newline, see if it's escaped.
2040 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002041 bool HasSpace = false;
2042 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002043 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002044 HasSpace = true;
2045 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002046
2047 if (*EscapePtr == '\\') // Escaped newline.
2048 CurPtr = EscapePtr;
2049 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2050 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2051 CurPtr = EscapePtr-2;
2052 else
2053 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002054
2055 // If there was space between the backslash and newline, warn about it.
2056 if (HasSpace && !isLexingRawMode())
2057 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattner22eb9722006-06-18 05:43:12 +00002060 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002061 // properly decode the character. Read it in raw mode to avoid emitting
2062 // diagnostics about things like trigraphs. If we see an escaped newline,
2063 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002064 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002065 bool OldRawMode = isLexingRawMode();
2066 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002067 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002068 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002069
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002070 // If we only read only one character, then no special handling is needed.
2071 // We're done and can skip forward to the newline.
2072 if (C != 0 && CurPtr == OldPtr+1) {
2073 CurPtr = NextLine;
2074 break;
2075 }
2076
Chris Lattner22eb9722006-06-18 05:43:12 +00002077 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002078 // \n, then we had an escaped newline within the comment. Emit diagnostic
2079 // unless the next line is also a // comment.
2080 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002081 for (; OldPtr != CurPtr; ++OldPtr)
2082 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002083 // Okay, we found a // comment that ends in a newline, if the next
2084 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002085 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002086 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002087 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002088 ++ForwardPtr;
2089 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2090 break;
2091 }
Mike Stump11289f42009-09-09 15:08:12 +00002092
Chris Lattner6d27a162008-11-22 02:02:22 +00002093 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002094 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002095 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002096 }
2097 }
Mike Stump11289f42009-09-09 15:08:12 +00002098
Douglas Gregor11583702010-08-25 17:04:25 +00002099 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002100 --CurPtr;
2101 break;
2102 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002103
2104 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2105 PP->CodeCompleteNaturalLanguage();
2106 cutOffLexing();
2107 return false;
2108 }
2109
Chris Lattner22eb9722006-06-18 05:43:12 +00002110 } while (C != '\n' && C != '\r');
2111
Chris Lattner93ddf802010-02-03 21:06:21 +00002112 // Found but did not consume the newline. Notify comment handlers about the
2113 // comment unless we're in a #if 0 block.
2114 if (PP && !isLexingRawMode() &&
2115 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2116 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002117 BufferPtr = CurPtr;
2118 return true; // A token has to be returned.
2119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Chris Lattner457fc152006-07-29 06:30:25 +00002121 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002122 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002123 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002124
2125 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002126 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002127 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002128 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002129 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattner22eb9722006-06-18 05:43:12 +00002132 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002133 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002134 // contribute to another token), it isn't needed for correctness. Note that
2135 // this is ok even in KeepWhitespaceMode, because we would have returned the
2136 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002137 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002138
Chris Lattner22eb9722006-06-18 05:43:12 +00002139 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002140 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002141 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002142 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002143 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002144 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002145 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002146}
Chris Lattner22eb9722006-06-18 05:43:12 +00002147
Nico Weber158a31a2012-11-11 07:02:14 +00002148/// If in save-comment mode, package up this Line comment in an appropriate
2149/// way and return it.
2150bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002151 // If we're not in a preprocessor directive, just return the // comment
2152 // directly.
2153 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002154
David Blaikied5321242012-06-06 18:52:13 +00002155 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002156 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002157
Nico Weber158a31a2012-11-11 07:02:14 +00002158 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002159 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002160 bool Invalid = false;
2161 std::string Spelling = PP->getSpelling(Result, &Invalid);
2162 if (Invalid)
2163 return true;
2164
Nico Weber158a31a2012-11-11 07:02:14 +00002165 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002166 Spelling[1] = '*'; // Change prefix to "/*".
2167 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002168
Chris Lattnerb11c3232008-10-12 04:51:35 +00002169 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002170 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002171 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002172 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002173}
2174
Chris Lattnercb283342006-06-18 06:48:37 +00002175/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002176/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2177/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002178static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002179 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002180 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002181
Chris Lattner22eb9722006-06-18 05:43:12 +00002182 // Back up off the newline.
2183 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002184
Chris Lattner22eb9722006-06-18 05:43:12 +00002185 // If this is a two-character newline sequence, skip the other character.
2186 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2187 // \n\n or \r\r -> not escaped newline.
2188 if (CurPtr[0] == CurPtr[1])
2189 return false;
2190 // \n\r or \r\n -> skip the newline.
2191 --CurPtr;
2192 }
Mike Stump11289f42009-09-09 15:08:12 +00002193
Chris Lattner22eb9722006-06-18 05:43:12 +00002194 // If we have horizontal whitespace, skip over it. We allow whitespace
2195 // between the slash and newline.
2196 bool HasSpace = false;
2197 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2198 --CurPtr;
2199 HasSpace = true;
2200 }
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattner22eb9722006-06-18 05:43:12 +00002202 // If we have a slash, we know this is an escaped newline.
2203 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002204 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002205 } else {
2206 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002207 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2208 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002209 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnercb283342006-06-18 06:48:37 +00002211 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002212 CurPtr -= 2;
2213
2214 // If no trigraphs are enabled, warn that we ignored this trigraph and
2215 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002216 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002217 if (!L->isLexingRawMode())
2218 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002219 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002220 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002221 if (!L->isLexingRawMode())
2222 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002223 }
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattner22eb9722006-06-18 05:43:12 +00002225 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002226 if (!L->isLexingRawMode())
2227 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002228
Chris Lattner22eb9722006-06-18 05:43:12 +00002229 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002230 if (HasSpace && !L->isLexingRawMode())
2231 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002232
Chris Lattnercb283342006-06-18 06:48:37 +00002233 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002234}
2235
Chris Lattneraded4a92006-10-27 04:42:31 +00002236#ifdef __SSE2__
2237#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002238#elif __ALTIVEC__
2239#include <altivec.h>
2240#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002241#endif
2242
James Dennettf442d242012-06-17 03:40:43 +00002243/// We have just read from input the / and * characters that started a comment.
2244/// Read until we find the * and / characters that terminate the comment.
2245/// Note that we don't bother decoding trigraphs or escaped newlines in block
2246/// comments, because they cannot cause the comment to end. The only thing
2247/// that can happen is the comment could end with an escaped newline between
2248/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002249///
Chris Lattner87d02082010-01-18 22:35:47 +00002250/// If we're in KeepCommentMode or any CommentHandler has inserted
2251/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002252bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2253 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002254 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002255 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002256 // optimization helps people who like to put a lot of * characters in their
2257 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002258
2259 // The first character we get with newlines and trigraphs skipped to handle
2260 // the degenerate /*/ case below correctly if the * has an escaped newline
2261 // after it.
2262 unsigned CharSize;
2263 unsigned char C = getCharAndSize(CurPtr, CharSize);
2264 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002265 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002266 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002267 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002268 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattner99e7d232008-10-12 04:19:49 +00002270 // KeepWhitespaceMode should return this broken comment as a token. Since
2271 // it isn't a well formed comment, just return it as an 'unknown' token.
2272 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002273 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002274 return true;
2275 }
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattner99e7d232008-10-12 04:19:49 +00002277 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002278 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002279 }
Mike Stump11289f42009-09-09 15:08:12 +00002280
Chris Lattnerc850ad62007-07-21 23:43:37 +00002281 // Check to see if the first character after the '/*' is another /. If so,
2282 // then this slash does not end the block comment, it is part of it.
2283 if (C == '/')
2284 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002285
Chris Lattner22eb9722006-06-18 05:43:12 +00002286 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002287 // Skip over all non-interesting characters until we find end of buffer or a
2288 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002289 if (CurPtr + 24 < BufferEnd &&
2290 // If there is a code-completion point avoid the fast scan because it
2291 // doesn't check for '\0'.
2292 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002293 // While not aligned to a 16-byte boundary.
2294 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2295 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattner6cc3e362006-10-27 04:12:35 +00002297 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002298
2299#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002300 __m128i Slashes = _mm_set1_epi8('/');
2301 while (CurPtr+16 <= BufferEnd) {
2302 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2303 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002304 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002305 // Adjust the pointer to point directly after the first slash. It's
2306 // not necessary to set C here, it will be overwritten at the end of
2307 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002308 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002309 goto FoundSlash;
2310 }
Roman Divacky61509902014-04-03 18:04:52 +00002311 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002312 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002313#elif __ALTIVEC__
2314 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002315 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002316 '/', '/', '/', '/', '/', '/', '/', '/'
2317 };
2318 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002319 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002320 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002321#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002322 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002323 while (CurPtr[0] != '/' &&
2324 CurPtr[1] != '/' &&
2325 CurPtr[2] != '/' &&
2326 CurPtr[3] != '/' &&
2327 CurPtr+4 < BufferEnd) {
2328 CurPtr += 4;
2329 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002330#endif
Mike Stump11289f42009-09-09 15:08:12 +00002331
Chris Lattneraded4a92006-10-27 04:42:31 +00002332 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002333 C = *CurPtr++;
2334 }
Mike Stump11289f42009-09-09 15:08:12 +00002335
Chris Lattneraded4a92006-10-27 04:42:31 +00002336 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002337 while (C != '/' && C != '\0')
2338 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002339
Chris Lattner22eb9722006-06-18 05:43:12 +00002340 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002341 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002342 if (CurPtr[-2] == '*') // We found the final */. We're done!
2343 break;
Mike Stump11289f42009-09-09 15:08:12 +00002344
Chris Lattner22eb9722006-06-18 05:43:12 +00002345 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002346 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002347 // We found the final */, though it had an escaped newline between the
2348 // * and /. We're done!
2349 break;
2350 }
2351 }
2352 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2353 // If this is a /* inside of the comment, emit a warning. Don't do this
2354 // if this is a /*/, which will end the comment. This misses cases with
2355 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002356 if (!isLexingRawMode())
2357 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002358 }
2359 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002360 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002361 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002362 // Note: the user probably forgot a */. We could continue immediately
2363 // after the /*, but this would involve lexing a lot of what really is the
2364 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002365 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002366
Chris Lattner99e7d232008-10-12 04:19:49 +00002367 // KeepWhitespaceMode should return this broken comment as a token. Since
2368 // it isn't a well formed comment, just return it as an 'unknown' token.
2369 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002370 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002371 return true;
2372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Chris Lattner99e7d232008-10-12 04:19:49 +00002374 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002375 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002376 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2377 PP->CodeCompleteNaturalLanguage();
2378 cutOffLexing();
2379 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002380 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002381
Chris Lattner22eb9722006-06-18 05:43:12 +00002382 C = *CurPtr++;
2383 }
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner93ddf802010-02-03 21:06:21 +00002385 // Notify comment handlers about the comment unless we're in a #if 0 block.
2386 if (PP && !isLexingRawMode() &&
2387 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2388 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002389 BufferPtr = CurPtr;
2390 return true; // A token has to be returned.
2391 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002392
Chris Lattner457fc152006-07-29 06:30:25 +00002393 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002394 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002395 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002396 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002397 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002398
2399 // It is common for the tokens immediately after a /**/ comment to be
2400 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002401 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2402 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002403 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002404 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002405 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002406 }
2407
2408 // Otherwise, just return so that the next character will be lexed as a token.
2409 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002410 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002411 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002412}
2413
2414//===----------------------------------------------------------------------===//
2415// Primary Lexing Entry Points
2416//===----------------------------------------------------------------------===//
2417
Chris Lattner22eb9722006-06-18 05:43:12 +00002418/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2419/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002420void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002421 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2422 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002423 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002424
2425 // CurPtr - Cache BufferPtr in an automatic variable.
2426 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002427 while (1) {
2428 char Char = getAndAdvanceChar(CurPtr, Tmp);
2429 switch (Char) {
2430 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002431 if (Result)
2432 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002433 break;
2434 case 0: // Null.
2435 // Found end of file?
2436 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002437 if (isCodeCompletionPoint(CurPtr-1)) {
2438 PP->CodeCompleteNaturalLanguage();
2439 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002440 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002441 }
2442
Chris Lattner22eb9722006-06-18 05:43:12 +00002443 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002444 if (Result)
2445 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002446 break;
2447 }
2448 // FALL THROUGH.
2449 case '\r':
2450 case '\n':
2451 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2452 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2453 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002454
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002455 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002456 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002457 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002458 if (PP)
2459 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002460 Lex(Tmp);
2461 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002462 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002463
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002464 // Finally, we're done;
2465 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002466 }
2467 }
2468}
2469
2470/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2471/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002472/// This returns true if Result contains a token, false if PP.Lex should be
2473/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002474bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002475 // If we hit the end of the file while parsing a preprocessor directive,
2476 // end the preprocessor directive first. The next token returned will
2477 // then be the end of file.
2478 if (ParsingPreprocessorDirective) {
2479 // Done parsing the "line".
2480 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002481 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002482 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002483
Chris Lattner457fc152006-07-29 06:30:25 +00002484 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002485 if (PP)
2486 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002487 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002488 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002489
Chris Lattner30a2fa12006-07-19 06:31:49 +00002490 // If we are in raw mode, return this event as an EOF token. Let the caller
2491 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002492 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002493 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002494 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002495 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002496 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002497 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002498
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002499 // Issue diagnostics for unterminated #if and missing newline.
2500
Chris Lattner30a2fa12006-07-19 06:31:49 +00002501 // If we are in a #if directive, emit an error.
2502 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002503 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002504 PP->Diag(ConditionalStack.back().IfLoc,
2505 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002506 ConditionalStack.pop_back();
2507 }
Mike Stump11289f42009-09-09 15:08:12 +00002508
Chris Lattner8f96d042008-04-12 05:54:25 +00002509 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2510 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002511 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2512 DiagnosticsEngine &Diags = PP->getDiagnostics();
2513 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2514 unsigned DiagID;
2515
2516 if (LangOpts.CPlusPlus11) {
2517 // C++11 [lex.phases] 2.2 p2
2518 // Prefer the C++98 pedantic compatibility warning over the generic,
2519 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002520 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002521 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2522 } else {
2523 DiagID = diag::warn_no_newline_eof;
2524 }
2525 } else {
2526 DiagID = diag::ext_no_newline_eof;
2527 }
2528
2529 Diag(BufferEnd, DiagID)
2530 << FixItHint::CreateInsertion(EndLoc, "\n");
2531 }
Mike Stump11289f42009-09-09 15:08:12 +00002532
Chris Lattner22eb9722006-06-18 05:43:12 +00002533 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002534
2535 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002536 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002537}
2538
Chris Lattner678c8802006-07-11 05:46:12 +00002539/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2540/// the specified lexer will return a tok::l_paren token, 0 if it is something
2541/// else and 2 if there are no more tokens in the buffer controlled by the
2542/// lexer.
2543unsigned Lexer::isNextPPTokenLParen() {
2544 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002545
Chris Lattner678c8802006-07-11 05:46:12 +00002546 // Switch to 'skipping' mode. This will ensure that we can lex a token
2547 // without emitting diagnostics, disables macro expansion, and will cause EOF
2548 // to return an EOF token instead of popping the include stack.
2549 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner678c8802006-07-11 05:46:12 +00002551 // Save state that can be changed while lexing so that we can restore it.
2552 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002553 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002554 bool atStartOfLine = IsAtStartOfLine;
2555 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2556 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Chris Lattner146762e2007-07-20 16:59:19 +00002558 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002559 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002560
Chris Lattner678c8802006-07-11 05:46:12 +00002561 // Restore state that may have changed.
2562 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002563 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002564 HasLeadingSpace = leadingSpace;
2565 IsAtStartOfLine = atStartOfLine;
2566 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002567
Chris Lattner678c8802006-07-11 05:46:12 +00002568 // Restore the lexer back to non-skipping mode.
2569 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002570
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002571 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002572 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002573 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002574}
2575
James Dennettf442d242012-06-17 03:40:43 +00002576/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002577static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2578 ConflictMarkerKind CMK) {
2579 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2580 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2581 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2582 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002583 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002584 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002585 if (Pos == 0 ||
2586 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002587 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2588 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002589 continue;
2590 }
2591 return RestOfBuffer.data()+Pos;
2592 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002593 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002594}
2595
2596/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2597/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2598/// and recover nicely. This returns true if it is a conflict marker and false
2599/// if not.
2600bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2601 // Only a conflict marker if it starts at the beginning of a line.
2602 if (CurPtr != BufferStart &&
2603 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2604 return false;
2605
Richard Smitha9e33d42011-10-12 00:37:51 +00002606 // Check to see if we have <<<<<<< or >>>>.
2607 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2608 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002609 return false;
2610
2611 // If we have a situation where we don't care about conflict markers, ignore
2612 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002613 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002614 return false;
2615
Richard Smitha9e33d42011-10-12 00:37:51 +00002616 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2617
2618 // Check to see if there is an ending marker somewhere in the buffer at the
2619 // start of a line to terminate this conflict marker.
2620 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002621 // We found a match. We are really in a conflict marker.
2622 // Diagnose this, and ignore to the end of line.
2623 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002624 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002625
2626 // Skip ahead to the end of line. We know this exists because the
2627 // end-of-conflict marker starts with \r or \n.
2628 while (*CurPtr != '\r' && *CurPtr != '\n') {
2629 assert(CurPtr != BufferEnd && "Didn't find end of line");
2630 ++CurPtr;
2631 }
2632 BufferPtr = CurPtr;
2633 return true;
2634 }
2635
2636 // No end of conflict marker found.
2637 return false;
2638}
2639
2640
Richard Smitha9e33d42011-10-12 00:37:51 +00002641/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2642/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2643/// is the end of a conflict marker. Handle it by ignoring up until the end of
2644/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002645bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2646 // Only a conflict marker if it starts at the beginning of a line.
2647 if (CurPtr != BufferStart &&
2648 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2649 return false;
2650
2651 // If we have a situation where we don't care about conflict markers, ignore
2652 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002653 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002654 return false;
2655
Richard Smitha9e33d42011-10-12 00:37:51 +00002656 // Check to see if we have the marker (4 characters in a row).
2657 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002658 if (CurPtr[i] != CurPtr[0])
2659 return false;
2660
2661 // If we do have it, search for the end of the conflict marker. This could
2662 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2663 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002664 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2665 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002666 CurPtr = End;
2667
2668 // Skip ahead to the end of line.
2669 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2670 ++CurPtr;
2671
2672 BufferPtr = CurPtr;
2673
2674 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002675 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002676 return true;
2677 }
2678
2679 return false;
2680}
2681
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002682bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2683 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002684 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002685 return Loc == PP->getCodeCompletionLoc();
2686 }
2687
2688 return false;
2689}
2690
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002691uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2692 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002693 unsigned CharSize;
2694 char Kind = getCharAndSize(StartPtr, CharSize);
2695
2696 unsigned NumHexDigits;
2697 if (Kind == 'u')
2698 NumHexDigits = 4;
2699 else if (Kind == 'U')
2700 NumHexDigits = 8;
2701 else
2702 return 0;
2703
Jordan Rosec0cba272013-01-27 20:12:04 +00002704 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002705 if (Result && !isLexingRawMode())
2706 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002707 return 0;
2708 }
2709
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002710 const char *CurPtr = StartPtr + CharSize;
2711 const char *KindLoc = &CurPtr[-1];
2712
2713 uint32_t CodePoint = 0;
2714 for (unsigned i = 0; i < NumHexDigits; ++i) {
2715 char C = getCharAndSize(CurPtr, CharSize);
2716
2717 unsigned Value = llvm::hexDigitValue(C);
2718 if (Value == -1U) {
2719 if (Result && !isLexingRawMode()) {
2720 if (i == 0) {
2721 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2722 << StringRef(KindLoc, 1);
2723 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002724 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002725
2726 // If the user wrote \U1234, suggest a fixit to \u.
2727 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002728 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002729 Diag(KindLoc, diag::note_ucn_four_not_eight)
2730 << FixItHint::CreateReplacement(URange, "u");
2731 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002732 }
2733 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002734
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002735 return 0;
2736 }
2737
2738 CodePoint <<= 4;
2739 CodePoint += Value;
2740
2741 CurPtr += CharSize;
2742 }
2743
2744 if (Result) {
2745 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002746 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002747 StartPtr = CurPtr;
2748 else
2749 while (StartPtr != CurPtr)
2750 (void)getAndAdvanceChar(StartPtr, *Result);
2751 } else {
2752 StartPtr = CurPtr;
2753 }
2754
Justin Bogner53535132013-10-21 05:02:28 +00002755 // Don't apply C family restrictions to UCNs in assembly mode
2756 if (LangOpts.AsmPreprocessor)
2757 return CodePoint;
2758
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002759 // C99 6.4.3p2: A universal character name shall not specify a character whose
2760 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2761 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2762 // C++11 [lex.charset]p2: If the hexadecimal value for a
2763 // universal-character-name corresponds to a surrogate code point (in the
2764 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2765 // if the hexadecimal value for a universal-character-name outside the
2766 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2767 // string literal corresponds to a control character (in either of the
2768 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2769 // basic source character set, the program is ill-formed.
2770 if (CodePoint < 0xA0) {
2771 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2772 return CodePoint;
2773
2774 // We don't use isLexingRawMode() here because we need to warn about bad
2775 // UCNs even when skipping preprocessing tokens in a #if block.
2776 if (Result && PP) {
2777 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2778 Diag(BufferPtr, diag::err_ucn_control_character);
2779 else {
2780 char C = static_cast<char>(CodePoint);
2781 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2782 }
2783 }
2784
2785 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002786
2787 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002788 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002789 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002790 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002791 if (Result && PP) {
2792 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2793 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2794 else
2795 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2796 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002797 return 0;
2798 }
2799
2800 return CodePoint;
2801}
2802
Eli Friedman0834a4b2013-09-19 00:41:32 +00002803bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2804 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002805 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2806 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002807 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002808 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002809 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002810 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002811
2812 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002813 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002814 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002815 return false;
2816}
Jordan Rose4246ae02013-01-24 20:50:50 +00002817
Eli Friedman0834a4b2013-09-19 00:41:32 +00002818bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002819 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2820 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2821 !PP->isPreprocessedOutput()) {
2822 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2823 makeCharRange(*this, BufferPtr, CurPtr),
2824 /*IsFirst=*/true);
2825 }
2826
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002827 MIOpt.ReadToken();
2828 return LexIdentifier(Result, CurPtr);
2829 }
2830
Jordan Rosecc538342013-01-31 19:48:48 +00002831 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2832 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002833 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002834 // Non-ASCII characters tend to creep into source code unintentionally.
2835 // Instead of letting the parser complain about the unknown token,
2836 // just drop the character.
2837 // Note that we can /only/ do this when the non-ASCII character is actually
2838 // spelled as Unicode, not written as a UCN. The standard requires that
2839 // we not throw away any possible preprocessor tokens, but there's a
2840 // loophole in the mapping of Unicode characters to basic character set
2841 // characters that allows us to map these particular characters to, say,
2842 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002843 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002844 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002845
2846 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002847 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002848 }
2849
2850 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2851 // up by accident.
2852 MIOpt.ReadToken();
2853 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002854 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002855}
2856
Eli Friedman0834a4b2013-09-19 00:41:32 +00002857void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2858 IsAtStartOfLine = Result.isAtStartOfLine();
2859 HasLeadingSpace = Result.hasLeadingSpace();
2860 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2861 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2862}
2863
2864bool Lexer::Lex(Token &Result) {
2865 // Start a new token.
2866 Result.startToken();
2867
2868 // Set up misc whitespace flags for LexTokenInternal.
2869 if (IsAtStartOfLine) {
2870 Result.setFlag(Token::StartOfLine);
2871 IsAtStartOfLine = false;
2872 }
2873
2874 if (HasLeadingSpace) {
2875 Result.setFlag(Token::LeadingSpace);
2876 HasLeadingSpace = false;
2877 }
2878
2879 if (HasLeadingEmptyMacro) {
2880 Result.setFlag(Token::LeadingEmptyMacro);
2881 HasLeadingEmptyMacro = false;
2882 }
2883
2884 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2885 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002886 bool isRawLex = isLexingRawMode();
2887 (void) isRawLex;
2888 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2889 // (After the LexTokenInternal call, the lexer might be destroyed.)
2890 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2891 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002892}
Chris Lattner22eb9722006-06-18 05:43:12 +00002893
2894/// LexTokenInternal - This implements a simple C family lexer. It is an
2895/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002896/// has a null character at the end of the file. This returns a preprocessing
2897/// token, not a normal token, as such, it is an internal interface. It assumes
2898/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002899bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002900LexNextToken:
2901 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002902 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002903 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002904
Chris Lattner22eb9722006-06-18 05:43:12 +00002905 // CurPtr - Cache BufferPtr in an automatic variable.
2906 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002907
Chris Lattnereb54b592006-07-10 06:34:27 +00002908 // Small amounts of horizontal whitespace is very common between tokens.
2909 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2910 ++CurPtr;
2911 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2912 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002913
Chris Lattner4d963442008-10-12 04:05:48 +00002914 // If we are keeping whitespace and other tokens, just return what we just
2915 // skipped. The next lexer invocation will return the token after the
2916 // whitespace.
2917 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002918 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002919 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002920 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002921 }
Mike Stump11289f42009-09-09 15:08:12 +00002922
Chris Lattnereb54b592006-07-10 06:34:27 +00002923 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002924 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002925 }
Mike Stump11289f42009-09-09 15:08:12 +00002926
Chris Lattner22eb9722006-06-18 05:43:12 +00002927 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002928
Chris Lattner22eb9722006-06-18 05:43:12 +00002929 // Read a character, advancing over it.
2930 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002931 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002932
Chris Lattner22eb9722006-06-18 05:43:12 +00002933 switch (Char) {
2934 case 0: // Null.
2935 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002936 if (CurPtr-1 == BufferEnd)
2937 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002938
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002939 // Check if we are performing code completion.
2940 if (isCodeCompletionPoint(CurPtr-1)) {
2941 // Return the code-completion token.
2942 Result.startToken();
2943 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002944 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002945 }
2946
Chris Lattner6d27a162008-11-22 02:02:22 +00002947 if (!isLexingRawMode())
2948 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002949 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002950 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2951 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002952
Eli Friedman0834a4b2013-09-19 00:41:32 +00002953 // We know the lexer hasn't changed, so just try again with this lexer.
2954 // (We manually eliminate the tail call to avoid recursion.)
2955 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002956
2957 case 26: // DOS & CP/M EOF: "^Z".
2958 // If we're in Microsoft extensions mode, treat this as end of file.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002959 if (LangOpts.MicrosoftExt)
2960 return LexEndOfFile(Result, CurPtr-1);
2961
Chris Lattner3dfff972009-12-17 05:29:40 +00002962 // If Microsoft extensions are disabled, this is just random garbage.
2963 Kind = tok::unknown;
2964 break;
2965
Chris Lattner22eb9722006-06-18 05:43:12 +00002966 case '\n':
2967 case '\r':
2968 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002969 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002970 if (ParsingPreprocessorDirective) {
2971 // Done parsing the "line".
2972 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00002973
Chris Lattner457fc152006-07-29 06:30:25 +00002974 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00002975 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002976 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00002977
Chris Lattner22eb9722006-06-18 05:43:12 +00002978 // Since we consumed a newline, we are back at the start of a line.
2979 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002980 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00002981
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002982 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00002983 break;
2984 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002985
Chris Lattner22eb9722006-06-18 05:43:12 +00002986 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002987 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002988
Eli Friedman0834a4b2013-09-19 00:41:32 +00002989 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2990 return true; // KeepWhitespaceMode
2991
2992 // We only saw whitespace, so just try again with this lexer.
2993 // (We manually eliminate the tail call to avoid recursion.)
2994 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00002995 case ' ':
2996 case '\t':
2997 case '\f':
2998 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00002999 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003000 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003001 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3002 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003003
3004 SkipIgnoredUnits:
3005 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003006
Chris Lattnerb9b85972007-07-22 06:29:05 +00003007 // If the next token is obviously a // or /* */ comment, skip it efficiently
3008 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003009 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003010 LangOpts.LineComment &&
3011 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003012 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3013 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003014 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003015 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003016 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3017 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003018 goto SkipIgnoredUnits;
3019 } else if (isHorizontalWhitespace(*CurPtr)) {
3020 goto SkipHorizontalWhitespace;
3021 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003022 // We only saw whitespace, so just try again with this lexer.
3023 // (We manually eliminate the tail call to avoid recursion.)
3024 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003025
Chris Lattner2b15cf72008-01-03 17:58:54 +00003026 // C99 6.4.4.1: Integer Constants.
3027 // C99 6.4.4.2: Floating Constants.
3028 case '0': case '1': case '2': case '3': case '4':
3029 case '5': case '6': case '7': case '8': case '9':
3030 // Notify MIOpt that we read a non-whitespace/non-comment token.
3031 MIOpt.ReadToken();
3032 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003033
Richard Smith9b362092013-03-09 23:56:02 +00003034 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003035 // Notify MIOpt that we read a non-whitespace/non-comment token.
3036 MIOpt.ReadToken();
3037
Richard Smith9b362092013-03-09 23:56:02 +00003038 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003039 Char = getCharAndSize(CurPtr, SizeTmp);
3040
3041 // UTF-16 string literal
3042 if (Char == '"')
3043 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3044 tok::utf16_string_literal);
3045
3046 // UTF-16 character constant
3047 if (Char == '\'')
3048 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3049 tok::utf16_char_constant);
3050
Craig Topper54edcca2011-08-11 04:06:15 +00003051 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003052 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3053 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003054 return LexRawStringLiteral(Result,
3055 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3056 SizeTmp2, Result),
3057 tok::utf16_string_literal);
3058
3059 if (Char == '8') {
3060 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3061
3062 // UTF-8 string literal
3063 if (Char2 == '"')
3064 return LexStringLiteral(Result,
3065 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3066 SizeTmp2, Result),
3067 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003068 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3069 return LexCharConstant(
3070 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3071 SizeTmp2, Result),
3072 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003073
Richard Smith9b362092013-03-09 23:56:02 +00003074 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003075 unsigned SizeTmp3;
3076 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3077 // UTF-8 raw string literal
3078 if (Char3 == '"') {
3079 return LexRawStringLiteral(Result,
3080 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3081 SizeTmp2, Result),
3082 SizeTmp3, Result),
3083 tok::utf8_string_literal);
3084 }
3085 }
3086 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003087 }
3088
3089 // treat u like the start of an identifier.
3090 return LexIdentifier(Result, CurPtr);
3091
Richard Smith9b362092013-03-09 23:56:02 +00003092 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003093 // Notify MIOpt that we read a non-whitespace/non-comment token.
3094 MIOpt.ReadToken();
3095
Richard Smith9b362092013-03-09 23:56:02 +00003096 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003097 Char = getCharAndSize(CurPtr, SizeTmp);
3098
3099 // UTF-32 string literal
3100 if (Char == '"')
3101 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3102 tok::utf32_string_literal);
3103
3104 // UTF-32 character constant
3105 if (Char == '\'')
3106 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3107 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003108
3109 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003110 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3111 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003112 return LexRawStringLiteral(Result,
3113 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3114 SizeTmp2, Result),
3115 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003116 }
3117
3118 // treat U like the start of an identifier.
3119 return LexIdentifier(Result, CurPtr);
3120
Craig Topper54edcca2011-08-11 04:06:15 +00003121 case 'R': // Identifier or C++0x raw string literal
3122 // Notify MIOpt that we read a non-whitespace/non-comment token.
3123 MIOpt.ReadToken();
3124
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003125 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003126 Char = getCharAndSize(CurPtr, SizeTmp);
3127
3128 if (Char == '"')
3129 return LexRawStringLiteral(Result,
3130 ConsumeChar(CurPtr, SizeTmp, Result),
3131 tok::string_literal);
3132 }
3133
3134 // treat R like the start of an identifier.
3135 return LexIdentifier(Result, CurPtr);
3136
Chris Lattner2b15cf72008-01-03 17:58:54 +00003137 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003138 // Notify MIOpt that we read a non-whitespace/non-comment token.
3139 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003140 Char = getCharAndSize(CurPtr, SizeTmp);
3141
3142 // Wide string literal.
3143 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003144 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003145 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003146
Craig Topper54edcca2011-08-11 04:06:15 +00003147 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003148 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003149 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3150 return LexRawStringLiteral(Result,
3151 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3152 SizeTmp2, Result),
3153 tok::wide_string_literal);
3154
Chris Lattner22eb9722006-06-18 05:43:12 +00003155 // Wide character constant.
3156 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003157 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3158 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003159 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003160
Chris Lattner22eb9722006-06-18 05:43:12 +00003161 // C99 6.4.2: Identifiers.
3162 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3163 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003164 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003165 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3166 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3167 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003168 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003169 case 'v': case 'w': case 'x': case 'y': case 'z':
3170 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003171 // Notify MIOpt that we read a non-whitespace/non-comment token.
3172 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003173 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003174
3175 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003176 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003177 if (!isLexingRawMode())
3178 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003179 // Notify MIOpt that we read a non-whitespace/non-comment token.
3180 MIOpt.ReadToken();
3181 return LexIdentifier(Result, CurPtr);
3182 }
Mike Stump11289f42009-09-09 15:08:12 +00003183
Chris Lattnerb11c3232008-10-12 04:51:35 +00003184 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003185 break;
Mike Stump11289f42009-09-09 15:08:12 +00003186
Chris Lattner22eb9722006-06-18 05:43:12 +00003187 // C99 6.4.4: Character Constants.
3188 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003189 // Notify MIOpt that we read a non-whitespace/non-comment token.
3190 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003191 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003192
3193 // C99 6.4.5: String Literals.
3194 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003195 // Notify MIOpt that we read a non-whitespace/non-comment token.
3196 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003197 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003198
3199 // C99 6.4.6: Punctuators.
3200 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003201 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003202 break;
3203 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003204 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003205 break;
3206 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003207 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003208 break;
3209 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003210 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003211 break;
3212 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003213 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003214 break;
3215 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003216 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003217 break;
3218 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003219 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003220 break;
3221 case '.':
3222 Char = getCharAndSize(CurPtr, SizeTmp);
3223 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003224 // Notify MIOpt that we read a non-whitespace/non-comment token.
3225 MIOpt.ReadToken();
3226
Chris Lattner22eb9722006-06-18 05:43:12 +00003227 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003228 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003229 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003230 CurPtr += SizeTmp;
3231 } else if (Char == '.' &&
3232 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003233 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003234 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3235 SizeTmp2, Result);
3236 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003237 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003238 }
3239 break;
3240 case '&':
3241 Char = getCharAndSize(CurPtr, SizeTmp);
3242 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003243 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003244 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3245 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003246 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003247 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3248 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003249 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003250 }
3251 break;
Mike Stump11289f42009-09-09 15:08:12 +00003252 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003253 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003254 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003255 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3256 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003257 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003258 }
3259 break;
3260 case '+':
3261 Char = getCharAndSize(CurPtr, SizeTmp);
3262 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003263 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003264 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003265 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003267 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003268 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003269 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003270 }
3271 break;
3272 case '-':
3273 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003274 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003275 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003276 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003277 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003278 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003279 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3280 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003281 Kind = tok::arrowstar;
3282 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003283 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003284 Kind = tok::arrow;
3285 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003286 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003287 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003288 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003289 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003290 }
3291 break;
3292 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003293 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003294 break;
3295 case '!':
3296 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003297 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3299 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003300 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 }
3302 break;
3303 case '/':
3304 // 6.4.9: Comments
3305 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003306 if (Char == '/') { // Line comment.
3307 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003308 // want to lex this as a comment. There is one problem with this though,
3309 // that in one particular corner case, this can change the behavior of the
3310 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003311 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003312 // "foo". Check to see if the character after the second slash is a '*'.
3313 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003314 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003315 bool TreatAsComment = LangOpts.LineComment &&
3316 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003317 if (!TreatAsComment)
3318 if (!(PP && PP->isPreprocessedOutput()))
3319 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3320
3321 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003322 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3323 TokAtPhysicalStartOfLine))
3324 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003325
Chris Lattner58827712009-01-16 22:39:25 +00003326 // It is common for the tokens immediately after a // comment to be
3327 // whitespace (indentation for the next line). Instead of going through
3328 // the big switch, handle it efficiently now.
3329 goto SkipIgnoredUnits;
3330 }
3331 }
Mike Stump11289f42009-09-09 15:08:12 +00003332
Chris Lattner58827712009-01-16 22:39:25 +00003333 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003334 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3335 TokAtPhysicalStartOfLine))
3336 return true; // There is a token to return.
3337
3338 // We only saw whitespace, so just try again with this lexer.
3339 // (We manually eliminate the tail call to avoid recursion.)
3340 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003341 }
Mike Stump11289f42009-09-09 15:08:12 +00003342
Chris Lattner58827712009-01-16 22:39:25 +00003343 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003344 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003345 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003346 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003347 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003348 }
3349 break;
3350 case '%':
3351 Char = getCharAndSize(CurPtr, SizeTmp);
3352 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003353 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003354 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003355 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003356 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003357 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003358 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003359 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003360 Char = getCharAndSize(CurPtr, SizeTmp);
3361 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003362 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003363 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3364 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003365 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003366 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003367 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003368 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003369 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003370 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003371 // We parsed a # character. If this occurs at the start of the line,
3372 // it's actually the start of a preprocessing directive. Callback to
3373 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003374 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003375 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003376 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003377
Chris Lattner2534324a2009-03-18 20:58:27 +00003378 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003379 }
3380 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003381 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003382 }
3383 break;
3384 case '<':
3385 Char = getCharAndSize(CurPtr, SizeTmp);
3386 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003387 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003388 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003389 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3390 if (After == '=') {
3391 Kind = tok::lesslessequal;
3392 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3393 SizeTmp2, Result);
3394 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3395 // If this is actually a '<<<<<<<' version control conflict marker,
3396 // recognize it as such and recover nicely.
3397 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003398 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3399 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3400 // ignore it.
3401 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003402 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003403 Kind = tok::lesslessless;
3404 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3405 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003406 } else {
3407 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3408 Kind = tok::lessless;
3409 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003410 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003411 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003412 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003413 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003414 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003415 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3416 // C++0x [lex.pptoken]p3:
3417 // Otherwise, if the next three characters are <:: and the subsequent
3418 // character is neither : nor >, the < is treated as a preprocessor
3419 // token by itself and not as the first character of the alternative
3420 // token <:.
3421 unsigned SizeTmp3;
3422 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3423 if (After != ':' && After != '>') {
3424 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003425 if (!isLexingRawMode())
3426 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003427 break;
3428 }
3429 }
3430
Chris Lattner22eb9722006-06-18 05:43:12 +00003431 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003432 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003433 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003434 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003435 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003436 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003437 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003438 }
3439 break;
3440 case '>':
3441 Char = getCharAndSize(CurPtr, SizeTmp);
3442 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003443 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003444 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003445 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003446 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3447 if (After == '=') {
3448 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3449 SizeTmp2, Result);
3450 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003451 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3452 // If this is actually a '>>>>' conflict marker, recognize it as such
3453 // and recover nicely.
3454 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003455 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3456 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3457 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003458 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003459 Kind = tok::greatergreatergreater;
3460 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3461 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003462 } else {
3463 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3464 Kind = tok::greatergreater;
3465 }
3466
Chris Lattner22eb9722006-06-18 05:43:12 +00003467 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003468 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003469 }
3470 break;
3471 case '^':
3472 Char = getCharAndSize(CurPtr, SizeTmp);
3473 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003474 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003475 Kind = tok::caretequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003476 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003477 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 }
3479 break;
3480 case '|':
3481 Char = getCharAndSize(CurPtr, SizeTmp);
3482 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003483 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003484 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3485 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003486 // If this is '|||||||' and we're in a conflict marker, ignore it.
3487 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3488 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003489 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003490 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3491 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003492 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003493 }
3494 break;
3495 case ':':
3496 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003497 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003498 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003499 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003500 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003501 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003502 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003503 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003504 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003505 }
3506 break;
3507 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003508 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003509 break;
3510 case '=':
3511 Char = getCharAndSize(CurPtr, SizeTmp);
3512 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003513 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003514 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3515 goto LexNextToken;
3516
Chris Lattnerb11c3232008-10-12 04:51:35 +00003517 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003518 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003519 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003520 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003521 }
3522 break;
3523 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003524 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003525 break;
3526 case '#':
3527 Char = getCharAndSize(CurPtr, SizeTmp);
3528 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003529 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003530 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003531 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003532 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003533 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003534 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003535 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003536 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003537 // We parsed a # character. If this occurs at the start of the line,
3538 // it's actually the start of a preprocessing directive. Callback to
3539 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003540 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003541 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003542 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003543
Chris Lattner2534324a2009-03-18 20:58:27 +00003544 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003545 }
3546 break;
3547
Chris Lattner2b15cf72008-01-03 17:58:54 +00003548 case '@':
3549 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003550 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003551 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003552 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003553 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003554 break;
Mike Stump11289f42009-09-09 15:08:12 +00003555
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003556 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003557 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003558 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3559 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3560 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3561 return true; // KeepWhitespaceMode
3562
3563 // We only saw whitespace, so just try again with this lexer.
3564 // (We manually eliminate the tail call to avoid recursion.)
3565 goto LexNextToken;
3566 }
3567
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003568 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003569 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003570
Chris Lattnerb11c3232008-10-12 04:51:35 +00003571 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003572 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003573
3574 default: {
3575 if (isASCII(Char)) {
3576 Kind = tok::unknown;
3577 break;
3578 }
3579
3580 UTF32 CodePoint;
3581
3582 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3583 // an escaped newline.
3584 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003585 ConversionResult Status =
3586 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3587 (const UTF8 *)BufferEnd,
3588 &CodePoint,
3589 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003590 if (Status == conversionOK) {
3591 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3592 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3593 return true; // KeepWhitespaceMode
3594
3595 // We only saw whitespace, so just try again with this lexer.
3596 // (We manually eliminate the tail call to avoid recursion.)
3597 goto LexNextToken;
3598 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003599 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003600 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003601
Jordan Rosecc538342013-01-31 19:48:48 +00003602 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3603 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003604 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003605 Kind = tok::unknown;
3606 break;
3607 }
3608
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003609 // Non-ASCII characters tend to creep into source code unintentionally.
3610 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003611 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003612 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003613
3614 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003615 // We're pretending the character didn't exist, so just try again with
3616 // this lexer.
3617 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003618 goto LexNextToken;
3619 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003620 }
Mike Stump11289f42009-09-09 15:08:12 +00003621
Chris Lattner371ac8a2006-07-04 07:11:10 +00003622 // Notify MIOpt that we read a non-whitespace/non-comment token.
3623 MIOpt.ReadToken();
3624
Chris Lattnerd01e2912006-06-18 16:22:51 +00003625 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003626 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003627 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003628
3629HandleDirective:
3630 // We parsed a # character and it's the start of a preprocessing directive.
3631
3632 FormTokenWithChars(Result, CurPtr, tok::hash);
3633 PP->HandleDirective(Result);
3634
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003635 if (PP->hadModuleLoaderFatalFailure()) {
3636 // With a fatal failure in the module loader, we abort parsing.
3637 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003638 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003639 }
3640
Eli Friedman0834a4b2013-09-19 00:41:32 +00003641 // We parsed the directive; lex a token with the new state.
3642 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003643}