blob: 9c2a0163acead0d9a6799adf157b561e5ec5f8ee [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);
Richard Trieucc3949d2016-02-18 22:34:54 +0000722 ++TokPtr;
723 --CharNo;
724 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000725 }
726
727 // If we have a character that may be a trigraph or escaped newline, use a
728 // lexer to parse it correctly.
729 for (; CharNo; --CharNo) {
730 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000732 TokPtr += Size;
733 PhysOffset += Size;
734 }
735
736 // Final detail: if we end up on an escaped newline, we want to return the
737 // location of the actual byte of the token. For example foo\<newline>bar
738 // advanced by 3 should return the location of b, not of \\. One compounding
739 // detail of this is that the escape may be made by a trigraph.
740 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
741 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
742
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000743 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000744}
745
746/// \brief Computes the source location just past the end of the
747/// token at this source location.
748///
749/// This routine can be used to produce a source location that
750/// points just past the end of the token referenced by \p Loc, and
751/// is generally used when a diagnostic needs to point just after a
752/// token where it expected something different that it received. If
753/// the returned source location would not be meaningful (e.g., if
754/// it points into a macro), this routine returns an invalid
755/// source location.
756///
757/// \param Offset an offset from the end of the token, where the source
758/// location should refer to. The default offset (0) produces a source
759/// location pointing just past the end of the token; an offset of 1 produces
760/// a source location pointing to the last character in the token, etc.
761SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
762 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000763 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000764 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000765 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000766
767 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000768 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000769 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000770 }
771
David Blaikiebbafb8a2012-03-11 07:00:24 +0000772 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000773 if (Len > Offset)
774 Len = Len - Offset;
775 else
776 return Loc;
777
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000778 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000779}
780
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000781/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000782/// token of the macro expansion.
783bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000784 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000785 const LangOptions &LangOpts,
786 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000787 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
788
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000789 SourceLocation expansionLoc;
790 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
791 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000792
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000793 if (expansionLoc.isFileID()) {
794 // No other macro expansions, this is the first.
795 if (MacroBegin)
796 *MacroBegin = expansionLoc;
797 return true;
798 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000800 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000801}
802
803/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000804/// token of the macro expansion.
805bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000806 const SourceManager &SM,
807 const LangOptions &LangOpts,
808 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000809 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
810
811 SourceLocation spellLoc = SM.getSpellingLoc(loc);
812 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
813 if (tokLen == 0)
814 return false;
815
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000816 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
817 SourceLocation expansionLoc;
818 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
819 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000820
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000821 if (expansionLoc.isFileID()) {
822 // No other macro expansions.
823 if (MacroEnd)
824 *MacroEnd = expansionLoc;
825 return true;
826 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000827
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000828 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000829}
830
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000831static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000832 const SourceManager &SM,
833 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000834 SourceLocation Begin = Range.getBegin();
835 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000836 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000837 if (Range.isTokenRange()) {
838 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
839 if (End.isInvalid())
840 return CharSourceRange();
841 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000842
843 // Break down the source locations.
844 FileID FID;
845 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000846 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000847 if (FID.isInvalid())
848 return CharSourceRange();
849
850 unsigned EndOffs;
851 if (!SM.isInFileID(End, FID, &EndOffs) ||
852 BeginOffs > EndOffs)
853 return CharSourceRange();
854
855 return CharSourceRange::getCharRange(Begin, End);
856}
857
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000858CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000859 const SourceManager &SM,
860 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000861 SourceLocation Begin = Range.getBegin();
862 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000863 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000864 return CharSourceRange();
865
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000866 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000867 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000868
869 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000870 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
871 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000872 Range.setBegin(Begin);
873 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000874 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000875
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000876 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000877 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
878 &End)) ||
879 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
880 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000882 Range.setEnd(End);
883 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000884 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000885
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000886 assert(Begin.isMacroID() && End.isMacroID());
887 SourceLocation MacroBegin, MacroEnd;
888 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
890 &MacroEnd)) ||
891 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
892 &MacroEnd)))) {
893 Range.setBegin(MacroBegin);
894 Range.setEnd(MacroEnd);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
896 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000897
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000898 bool Invalid = false;
899 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
900 &Invalid);
901 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000902 return CharSourceRange();
903
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000904 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
905 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
906 &Invalid);
907 if (Invalid)
908 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000909
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000910 if (EndEntry.getExpansion().isMacroArgExpansion() &&
911 BeginEntry.getExpansion().getExpansionLocStart() ==
912 EndEntry.getExpansion().getExpansionLocStart()) {
913 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
914 Range.setEnd(SM.getImmediateSpellingLoc(End));
915 return makeFileCharRange(Range, SM, LangOpts);
916 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000917 }
918
919 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000920}
921
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000922StringRef Lexer::getSourceText(CharSourceRange Range,
923 const SourceManager &SM,
924 const LangOptions &LangOpts,
925 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000926 Range = makeFileCharRange(Range, SM, LangOpts);
927 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000928 if (Invalid) *Invalid = true;
929 return StringRef();
930 }
931
932 // Break down the source location.
933 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
934 if (beginInfo.first.isInvalid()) {
935 if (Invalid) *Invalid = true;
936 return StringRef();
937 }
938
939 unsigned EndOffs;
940 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
941 beginInfo.second > EndOffs) {
942 if (Invalid) *Invalid = true;
943 return StringRef();
944 }
945
946 // Try to the load the file buffer.
947 bool invalidTemp = false;
948 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
949 if (invalidTemp) {
950 if (Invalid) *Invalid = true;
951 return StringRef();
952 }
953
954 if (Invalid) *Invalid = false;
955 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
956}
957
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000958StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
959 const SourceManager &SM,
960 const LangOptions &LangOpts) {
961 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000962
963 // Find the location of the immediate macro expansion.
964 while (1) {
965 FileID FID = SM.getFileID(Loc);
966 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
967 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
968 Loc = Expansion.getExpansionLocStart();
969 if (!Expansion.isMacroArgExpansion())
970 break;
971
972 // For macro arguments we need to check that the argument did not come
973 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
974
975 // Loc points to the argument id of the macro definition, move to the
976 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000977 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000978 SourceLocation SpellLoc = Expansion.getSpellingLoc();
979 if (SpellLoc.isFileID())
980 break; // No inner macro.
981
982 // If spelling location resides in the same FileID as macro expansion
983 // location, it means there is no inner macro.
984 FileID MacroFID = SM.getFileID(Loc);
985 if (SM.isInFileID(SpellLoc, MacroFID))
986 break;
987
988 // Argument came from inner macro.
989 Loc = SpellLoc;
990 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000991
992 // Find the spelling location of the start of the non-argument expansion
993 // range. This is where the macro name was spelled in order to begin
994 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000995 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000996
997 // Dig out the buffer where the macro name was spelled and the extents of the
998 // name so that we can render it into the expansion note.
999 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1000 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1001 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1002 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1003}
1004
Richard Trieu3a5c9582016-01-26 02:51:55 +00001005StringRef Lexer::getImmediateMacroNameForDiagnostics(
1006 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1007 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1008 // Walk past macro argument expanions.
1009 while (SM.isMacroArgExpansion(Loc))
1010 Loc = SM.getImmediateExpansionRange(Loc).first;
1011
1012 // If the macro's spelling has no FileID, then it's actually a token paste
1013 // or stringization (or similar) and not a macro at all.
1014 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1015 return StringRef();
1016
1017 // Find the spelling location of the start of the non-argument expansion
1018 // range. This is where the macro name was spelled in order to begin
1019 // expanding this macro.
1020 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1021
1022 // Dig out the buffer where the macro name was spelled and the extents of the
1023 // name so that we can render it into the expansion note.
1024 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1025 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1026 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1027 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1028}
1029
Jordan Rose288c4212012-06-07 01:10:31 +00001030bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001031 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001032}
1033
Chris Lattnerd01e2912006-06-18 16:22:51 +00001034
Chris Lattner22eb9722006-06-18 05:43:12 +00001035//===----------------------------------------------------------------------===//
1036// Diagnostics forwarding code.
1037//===----------------------------------------------------------------------===//
1038
Chris Lattner619c1742007-07-22 18:38:25 +00001039/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001040/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001041/// This is currently only used for _Pragma implementation, so it is the slow
1042/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001043static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1044 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001045static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1046 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001047 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001048 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001049
Chris Lattner619c1742007-07-22 18:38:25 +00001050 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001051 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001052 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001053 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001054
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001055 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001056 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001057 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001058 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattner9dc9c202009-02-15 20:52:18 +00001060 // Figure out the expansion loc range, which is the range covered by the
1061 // original _Pragma(...) sequence.
1062 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001063 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001064
Chandler Carruth115b0772011-07-26 03:03:05 +00001065 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001066}
1067
Chris Lattner22eb9722006-06-18 05:43:12 +00001068/// getSourceLocation - Return a source location identifier for the specified
1069/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001070SourceLocation Lexer::getSourceLocation(const char *Loc,
1071 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001072 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001073 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001074
1075 // In the normal case, we're just lexing from a simple file buffer, return
1076 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001077 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001078 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001079 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattnerd32480d2009-01-17 06:22:33 +00001081 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1082 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001083 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001084 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001085}
1086
Chris Lattner22eb9722006-06-18 05:43:12 +00001087/// Diag - Forwarding function for diagnostics. This translate a source
1088/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001089DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001090 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001091}
1092
1093//===----------------------------------------------------------------------===//
1094// Trigraph and Escaped Newline Handling Code.
1095//===----------------------------------------------------------------------===//
1096
1097/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1098/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1099static char GetTrigraphCharForLetter(char Letter) {
1100 switch (Letter) {
1101 default: return 0;
1102 case '=': return '#';
1103 case ')': return ']';
1104 case '(': return '[';
1105 case '!': return '|';
1106 case '\'': return '^';
1107 case '>': return '}';
1108 case '/': return '\\';
1109 case '<': return '{';
1110 case '-': return '~';
1111 }
1112}
1113
1114/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1115/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1116/// return the result character. Finally, emit a warning about trigraph use
1117/// whether trigraphs are enabled or not.
1118static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1119 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001120 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001121
David Blaikiebbafb8a2012-03-11 07:00:24 +00001122 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001123 if (!L->isLexingRawMode())
1124 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001125 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001126 }
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattner6d27a162008-11-22 02:02:22 +00001128 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001129 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001130 return Res;
1131}
1132
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001133/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1134/// 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 +00001135/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001136unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1137 unsigned Size = 0;
1138 while (isWhitespace(Ptr[Size])) {
1139 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001141 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1142 continue;
1143
1144 // If this is a \r\n or \n\r, skip the other half.
1145 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1146 Ptr[Size-1] != Ptr[Size])
1147 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001148
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001149 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001150 }
1151
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001152 // Not an escaped newline, must be a \t or something else.
1153 return 0;
1154}
1155
Chris Lattner38b2cde2009-04-18 22:27:02 +00001156/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1157/// them), skip over them and return the first non-escaped-newline found,
1158/// otherwise return P.
1159const char *Lexer::SkipEscapedNewLines(const char *P) {
1160 while (1) {
1161 const char *AfterEscape;
1162 if (*P == '\\') {
1163 AfterEscape = P+1;
1164 } else if (*P == '?') {
1165 // If not a trigraph for escape, bail out.
1166 if (P[1] != '?' || P[2] != '/')
1167 return P;
1168 AfterEscape = P+3;
1169 } else {
1170 return P;
1171 }
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattner38b2cde2009-04-18 22:27:02 +00001173 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1174 if (NewLineSize == 0) return P;
1175 P = AfterEscape+NewLineSize;
1176 }
1177}
1178
Anna Zaks59a3c802011-07-27 21:43:43 +00001179/// \brief Checks that the given token is the first token that occurs after the
1180/// given location (this excludes comments and whitespace). Returns the location
1181/// immediately after the specified token. If the token is not found or the
1182/// location is inside a macro, the returned source location will be invalid.
1183SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1184 tok::TokenKind TKind,
1185 const SourceManager &SM,
1186 const LangOptions &LangOpts,
1187 bool SkipTrailingWhitespaceAndNewLine) {
1188 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001189 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001190 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001191 }
1192 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1193
1194 // Break down the source location.
1195 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1196
1197 // Try to load the file buffer.
1198 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001199 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001200 if (InvalidTemp)
1201 return SourceLocation();
1202
1203 const char *TokenBegin = File.data() + LocInfo.second;
1204
1205 // Lex from the start of the given location.
1206 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1207 TokenBegin, File.end());
1208 // Find the token.
1209 Token Tok;
1210 lexer.LexFromRawLexer(Tok);
1211 if (Tok.isNot(TKind))
1212 return SourceLocation();
1213 SourceLocation TokenLoc = Tok.getLocation();
1214
1215 // Calculate how much whitespace needs to be skipped if any.
1216 unsigned NumWhitespaceChars = 0;
1217 if (SkipTrailingWhitespaceAndNewLine) {
1218 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1219 Tok.getLength();
1220 unsigned char C = *TokenEnd;
1221 while (isHorizontalWhitespace(C)) {
1222 C = *(++TokenEnd);
1223 NumWhitespaceChars++;
1224 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001225
1226 // Skip \r, \n, \r\n, or \n\r
1227 if (C == '\n' || C == '\r') {
1228 char PrevC = C;
1229 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001230 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001231 if ((C == '\n' || C == '\r') && C != PrevC)
1232 NumWhitespaceChars++;
1233 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001234 }
1235
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001236 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001237}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001238
Chris Lattner22eb9722006-06-18 05:43:12 +00001239/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1240/// get its size, and return it. This is tricky in several cases:
1241/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1242/// then either return the trigraph (skipping 3 chars) or the '?',
1243/// depending on whether trigraphs are enabled or not.
1244/// 2. If this is an escaped newline (potentially with whitespace between
1245/// the backslash and newline), implicitly skip the newline and return
1246/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001247///
1248/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1249/// know that we can accumulate into Size, and that we have already incremented
1250/// Ptr by Size bytes.
1251///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001252/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1253/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001254///
1255char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001256 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001257 // If we have a slash, look for an escaped newline.
1258 if (Ptr[0] == '\\') {
1259 ++Size;
1260 ++Ptr;
1261Slash:
1262 // Common case, backslash-char where the char is not whitespace.
1263 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001264
Chris Lattnerc1835952009-06-23 05:15:06 +00001265 // See if we have optional whitespace characters between the slash and
1266 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001267 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1268 // Remember that this token needs to be cleaned.
1269 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001270
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001271 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001272 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001273 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001274
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001275 // Found backslash<whitespace><newline>. Parse the char after it.
1276 Size += EscapedNewLineSize;
1277 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001278
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001279 // If the char that we finally got was a \n, then we must have had
1280 // something like \<newline><newline>. We don't want to consume the
1281 // second newline.
1282 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1283 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001284
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001285 // Use slow version to accumulate a correct size field.
1286 return getCharAndSizeSlow(Ptr, Size, Tok);
1287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Chris Lattner22eb9722006-06-18 05:43:12 +00001289 // Otherwise, this is not an escaped newline, just return the slash.
1290 return '\\';
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Chris Lattner22eb9722006-06-18 05:43:12 +00001293 // If this is a trigraph, process it.
1294 if (Ptr[0] == '?' && Ptr[1] == '?') {
1295 // If this is actually a legal trigraph (not something like "??x"), emit
1296 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001297 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001298 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001299 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001300
1301 Ptr += 3;
1302 Size += 3;
1303 if (C == '\\') goto Slash;
1304 return C;
1305 }
1306 }
Mike Stump11289f42009-09-09 15:08:12 +00001307
Chris Lattner22eb9722006-06-18 05:43:12 +00001308 // If this is neither, return a single character.
1309 ++Size;
1310 return *Ptr;
1311}
1312
Chris Lattnerd01e2912006-06-18 16:22:51 +00001313
Chris Lattner22eb9722006-06-18 05:43:12 +00001314/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1315/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1316/// and that we have already incremented Ptr by Size bytes.
1317///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001318/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1319/// be updated to match.
1320char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001321 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001322 // If we have a slash, look for an escaped newline.
1323 if (Ptr[0] == '\\') {
1324 ++Size;
1325 ++Ptr;
1326Slash:
1327 // Common case, backslash-char where the char is not whitespace.
1328 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattner22eb9722006-06-18 05:43:12 +00001330 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001331 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1332 // Found backslash<whitespace><newline>. Parse the char after it.
1333 Size += EscapedNewLineSize;
1334 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Argyrios Kyrtzidis8a26c4d2011-12-22 04:38:07 +00001336 // If the char that we finally got was a \n, then we must have had
1337 // something like \<newline><newline>. We don't want to consume the
1338 // second newline.
1339 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1340 return ' ';
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001341
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001342 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001343 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001344 }
Mike Stump11289f42009-09-09 15:08:12 +00001345
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 // Otherwise, this is not an escaped newline, just return the slash.
1347 return '\\';
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001351 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001352 // If this is actually a legal trigraph (not something like "??x"), return
1353 // it.
1354 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1355 Ptr += 3;
1356 Size += 3;
1357 if (C == '\\') goto Slash;
1358 return C;
1359 }
1360 }
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattner22eb9722006-06-18 05:43:12 +00001362 // If this is neither, return a single character.
1363 ++Size;
1364 return *Ptr;
1365}
1366
Chris Lattner22eb9722006-06-18 05:43:12 +00001367//===----------------------------------------------------------------------===//
1368// Helper methods for lexing.
1369//===----------------------------------------------------------------------===//
1370
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001371/// \brief Routine that indiscriminately skips bytes in the source file.
1372void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1373 BufferPtr += Bytes;
1374 if (BufferPtr > BufferEnd)
1375 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001376 // FIXME: What exactly does the StartOfLine bit mean? There are two
1377 // possible meanings for the "start" of the line: the first token on the
1378 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001379 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001380 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001381}
1382
Jordan Rose58c61e02013-02-09 01:10:25 +00001383static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001384 if (LangOpts.AsmPreprocessor) {
1385 return false;
1386 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001387 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1388 C11AllowedIDCharRanges);
1389 return C11AllowedIDChars.contains(C);
1390 } else if (LangOpts.CPlusPlus) {
1391 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1392 CXX03AllowedIDCharRanges);
1393 return CXX03AllowedIDChars.contains(C);
1394 } else {
1395 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1396 C99AllowedIDCharRanges);
1397 return C99AllowedIDChars.contains(C);
1398 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001399}
1400
Jordan Rose58c61e02013-02-09 01:10:25 +00001401static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1402 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001403 if (LangOpts.AsmPreprocessor) {
1404 return false;
1405 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001406 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1407 C11DisallowedInitialIDCharRanges);
1408 return !C11DisallowedInitialIDChars.contains(C);
1409 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001410 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001411 } else {
1412 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1413 C99DisallowedInitialIDCharRanges);
1414 return !C99DisallowedInitialIDChars.contains(C);
1415 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001416}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001417
Jordan Rose58c61e02013-02-09 01:10:25 +00001418static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1419 const char *End) {
1420 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1421 L.getSourceLocation(End));
1422}
1423
1424static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1425 CharSourceRange Range, bool IsFirst) {
1426 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001427 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001428 enum {
1429 CannotAppearInIdentifier = 0,
1430 CannotStartIdentifier
1431 };
1432
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001433 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1434 C99AllowedIDCharRanges);
1435 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1436 C99DisallowedInitialIDCharRanges);
1437 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001438 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1439 << Range
1440 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001441 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001442 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1443 << Range
1444 << CannotStartIdentifier;
1445 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001446 }
1447
Jordan Rose58c61e02013-02-09 01:10:25 +00001448 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001449 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001450 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1451 CXX03AllowedIDCharRanges);
1452 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001453 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1454 << Range;
1455 }
1456 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001457}
1458
1459bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1460 Token &Result) {
1461 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001462 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001463 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1464 return false;
1465
1466 if (!isLexingRawMode())
1467 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1468 makeCharRange(*this, CurPtr, UCNPtr),
1469 /*IsFirst=*/false);
1470
1471 Result.setFlag(Token::HasUCN);
1472 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1473 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1474 CurPtr = UCNPtr;
1475 else
1476 while (CurPtr != UCNPtr)
1477 (void)getAndAdvanceChar(CurPtr, Result);
1478 return true;
1479}
1480
1481bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1482 const char *UnicodePtr = CurPtr;
1483 UTF32 CodePoint;
1484 ConversionResult Result =
1485 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1486 (const UTF8 *)BufferEnd,
1487 &CodePoint,
1488 strictConversion);
1489 if (Result != conversionOK ||
1490 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1491 return false;
1492
1493 if (!isLexingRawMode())
1494 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1495 makeCharRange(*this, CurPtr, UnicodePtr),
1496 /*IsFirst=*/false);
1497
1498 CurPtr = UnicodePtr;
1499 return true;
1500}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001501
Eli Friedman0834a4b2013-09-19 00:41:32 +00001502bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001503 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1504 unsigned Size;
1505 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001506 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001507 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001508
Chris Lattner22eb9722006-06-18 05:43:12 +00001509 --CurPtr; // Back up over the skipped character.
1510
1511 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1512 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001513 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001514 // TODO: Could merge these checks into an InfoTable flag to make the
1515 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001516 if (isASCII(C) && C != '\\' && C != '?' &&
1517 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001518FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001519 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001520 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1521 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattner0f1f5052006-07-20 04:16:23 +00001523 // If we are in raw mode, return this identifier raw. There is no need to
1524 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001525 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001526 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001527
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001528 // Fill in Result.IdentifierInfo and update the token kind,
1529 // looking up the identifier in the identifier table.
1530 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001531
Chris Lattnerc5a00062006-06-18 16:41:01 +00001532 // Finally, now that we know we have an identifier, pass this off to the
1533 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001534 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001535 return PP->HandleIdentifier(Result);
Douglas Gregor08142532011-08-26 23:56:07 +00001536
Eli Friedman0834a4b2013-09-19 00:41:32 +00001537 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001541
Chris Lattner22eb9722006-06-18 05:43:12 +00001542 C = getCharAndSize(CurPtr, Size);
1543 while (1) {
1544 if (C == '$') {
1545 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001546 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001547
Chris Lattner22eb9722006-06-18 05:43:12 +00001548 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001549 if (!isLexingRawMode())
1550 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001551 CurPtr = ConsumeChar(CurPtr, Size, Result);
1552 C = getCharAndSize(CurPtr, Size);
1553 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001554
Richard Smith8b7258b2014-02-17 21:52:30 +00001555 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001556 C = getCharAndSize(CurPtr, Size);
1557 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001558 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001559 C = getCharAndSize(CurPtr, Size);
1560 continue;
1561 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001562 goto FinishIdentifier;
1563 }
1564
1565 // Otherwise, this character is good, consume it.
1566 CurPtr = ConsumeChar(CurPtr, Size, Result);
1567
1568 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001569 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001570 CurPtr = ConsumeChar(CurPtr, Size, Result);
1571 C = getCharAndSize(CurPtr, Size);
1572 }
1573 }
1574}
1575
Douglas Gregor759ef232010-08-30 14:50:47 +00001576/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001577/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001578bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001579 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001580 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001581 if (C1 != '0')
1582 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001583 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001584 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001585}
Chris Lattner22eb9722006-06-18 05:43:12 +00001586
Nate Begeman5eee9332008-04-14 02:26:39 +00001587/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001588/// constant. From[-1] is the first character lexed. Return the end of the
1589/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001590bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001591 unsigned Size;
1592 char C = getCharAndSize(CurPtr, Size);
1593 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001594 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001595 CurPtr = ConsumeChar(CurPtr, Size, Result);
1596 PrevCh = C;
1597 C = getCharAndSize(CurPtr, Size);
1598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattner22eb9722006-06-18 05:43:12 +00001600 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001601 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1602 // If we are in Microsoft mode, don't continue if the constant is hex.
1603 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001604 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001605 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1606 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001607
1608 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001609 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001610 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001611 // not-quite-conforming extension. Only do so if this looks like it's
1612 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1613 bool IsHexFloat = true;
1614 if (!LangOpts.C99) {
1615 if (!isHexaLiteral(BufferPtr, LangOpts))
1616 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001617 else if (!getLangOpts().CPlusPlus1z &&
1618 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001619 IsHexFloat = false;
1620 }
1621 if (IsHexFloat)
1622 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Richard Smithfde94852013-09-26 03:33:06 +00001625 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001626 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001627 unsigned NextSize;
1628 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001629 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001630 if (!isLexingRawMode())
1631 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1632 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001633 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001634 return LexNumericConstant(Result, CurPtr);
1635 }
1636 }
1637
Richard Smith8b7258b2014-02-17 21:52:30 +00001638 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1639 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1640 return LexNumericConstant(Result, CurPtr);
1641 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1642 return LexNumericConstant(Result, CurPtr);
1643
Chris Lattnerd01e2912006-06-18 16:22:51 +00001644 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001645 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001646 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001647 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001648 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001649}
1650
Richard Smithe18f0fa2012-03-05 04:02:15 +00001651/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001652/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001653const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1654 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001655 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001656
Richard Smith8b7258b2014-02-17 21:52:30 +00001657 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001658 unsigned Size;
1659 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001660 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001661
Richard Smith8b7258b2014-02-17 21:52:30 +00001662 if (!isIdentifierHead(C)) {
1663 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1664 Consumed = true;
1665 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1666 Consumed = true;
1667 else
1668 return CurPtr;
1669 }
1670
1671 if (!getLangOpts().CPlusPlus11) {
1672 if (!isLexingRawMode())
1673 Diag(CurPtr,
1674 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1675 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1676 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1677 return CurPtr;
1678 }
1679
1680 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1681 // that does not start with an underscore is ill-formed. As a conforming
1682 // extension, we treat all such suffixes as if they had whitespace before
1683 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1684 // likely to be a ud-suffix than a macro, however, and accept that.
1685 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001686 bool IsUDSuffix = false;
1687 if (C == '_')
1688 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001689 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001690 // In C++1y, we need to look ahead a few characters to see if this is a
1691 // valid suffix for a string literal or a numeric literal (this could be
1692 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001693 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001694 char Buffer[MaxStandardSuffixLength] = { C };
1695 unsigned Consumed = Size;
1696 unsigned Chars = 1;
1697 while (true) {
1698 unsigned NextSize;
1699 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1700 getLangOpts());
1701 if (!isIdentifierBody(Next)) {
1702 // End of suffix. Check whether this is on the whitelist.
1703 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1704 NumericLiteralParser::isValidUDSuffix(
1705 getLangOpts(), StringRef(Buffer, Chars));
1706 break;
1707 }
1708
1709 if (Chars == MaxStandardSuffixLength)
1710 // Too long: can't be a standard suffix.
1711 break;
1712
1713 Buffer[Chars++] = Next;
1714 Consumed += NextSize;
1715 }
Richard Smithf4198b72013-07-23 08:14:48 +00001716 }
1717
1718 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001719 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001720 Diag(CurPtr, getLangOpts().MSVCCompat
1721 ? diag::ext_ms_reserved_user_defined_literal
1722 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001723 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001724 return CurPtr;
1725 }
1726
Richard Smith8b7258b2014-02-17 21:52:30 +00001727 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001728 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001729
1730 Result.setFlag(Token::HasUDSuffix);
1731 while (true) {
1732 C = getCharAndSize(CurPtr, Size);
1733 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1734 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1735 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1736 else break;
1737 }
1738
Richard Smithe18f0fa2012-03-05 04:02:15 +00001739 return CurPtr;
1740}
1741
Chris Lattner22eb9722006-06-18 05:43:12 +00001742/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001743/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001744bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001745 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001746 // Does this string contain the \0 character?
1747 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001748
Richard Smithacd4d3d2011-10-15 01:18:56 +00001749 if (!isLexingRawMode() &&
1750 (Kind == tok::utf8_string_literal ||
1751 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001752 Kind == tok::utf32_string_literal))
1753 Diag(BufferPtr, getLangOpts().CPlusPlus
1754 ? diag::warn_cxx98_compat_unicode_literal
1755 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001756
Chris Lattner22eb9722006-06-18 05:43:12 +00001757 char C = getAndAdvanceChar(CurPtr, Result);
1758 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001759 // Skip escaped characters. Escaped newlines will already be processed by
1760 // getAndAdvanceChar.
1761 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001762 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001763
Chris Lattner52d96ac2010-05-30 23:27:38 +00001764 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001765 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001766 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001767 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001768 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001769 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001770 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001771
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001772 if (C == 0) {
1773 if (isCodeCompletionPoint(CurPtr-1)) {
1774 PP->CodeCompleteNaturalLanguage();
1775 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001776 cutOffLexing();
1777 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001778 }
1779
Chris Lattner52d96ac2010-05-30 23:27:38 +00001780 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001781 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001782 C = getAndAdvanceChar(CurPtr, Result);
1783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
Richard Smithe18f0fa2012-03-05 04:02:15 +00001785 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001786 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001787 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001788
Chris Lattner5a78a022006-07-20 06:02:19 +00001789 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001790 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001791 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001792
Chris Lattnerd01e2912006-06-18 16:22:51 +00001793 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001794 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001795 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001796 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001797 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001798}
1799
Craig Topper54edcca2011-08-11 04:06:15 +00001800/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1801/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001802bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001803 tok::TokenKind Kind) {
1804 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1805 // Between the initial and final double quote characters of the raw string,
1806 // any transformations performed in phases 1 and 2 (trigraphs,
1807 // universal-character-names, and line splicing) are reverted.
1808
Richard Smithacd4d3d2011-10-15 01:18:56 +00001809 if (!isLexingRawMode())
1810 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1811
Craig Topper54edcca2011-08-11 04:06:15 +00001812 unsigned PrefixLen = 0;
1813
1814 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1815 ++PrefixLen;
1816
1817 // If the last character was not a '(', then we didn't lex a valid delimiter.
1818 if (CurPtr[PrefixLen] != '(') {
1819 if (!isLexingRawMode()) {
1820 const char *PrefixEnd = &CurPtr[PrefixLen];
1821 if (PrefixLen == 16) {
1822 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1823 } else {
1824 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1825 << StringRef(PrefixEnd, 1);
1826 }
1827 }
1828
1829 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1830 // it's possible the '"' was intended to be part of the raw string, but
1831 // there's not much we can do about that.
1832 while (1) {
1833 char C = *CurPtr++;
1834
1835 if (C == '"')
1836 break;
1837 if (C == 0 && CurPtr-1 == BufferEnd) {
1838 --CurPtr;
1839 break;
1840 }
1841 }
1842
1843 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001844 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001845 }
1846
1847 // Save prefix and move CurPtr past it
1848 const char *Prefix = CurPtr;
1849 CurPtr += PrefixLen + 1; // skip over prefix and '('
1850
1851 while (1) {
1852 char C = *CurPtr++;
1853
1854 if (C == ')') {
1855 // Check for prefix match and closing quote.
1856 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1857 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1858 break;
1859 }
1860 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1861 if (!isLexingRawMode())
1862 Diag(BufferPtr, diag::err_unterminated_raw_string)
1863 << StringRef(Prefix, PrefixLen);
1864 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001865 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001866 }
1867 }
1868
Richard Smithe18f0fa2012-03-05 04:02:15 +00001869 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001870 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001871 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001872
Craig Topper54edcca2011-08-11 04:06:15 +00001873 // Update the location of token as well as BufferPtr.
1874 const char *TokStart = BufferPtr;
1875 FormTokenWithChars(Result, CurPtr, Kind);
1876 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001877 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001878}
1879
Chris Lattner22eb9722006-06-18 05:43:12 +00001880/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1881/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001882bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001883 // Does this string contain the \0 character?
1884 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001885 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001886 char C = getAndAdvanceChar(CurPtr, Result);
1887 while (C != '>') {
1888 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001889 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001890 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001891 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001892 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001893 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1894 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001895 // If the filename is unterminated, then it must just be a lone <
1896 // character. Return this as such.
1897 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001898 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001899 } else if (C == 0) {
1900 NulCharacter = CurPtr-1;
1901 }
1902 C = getAndAdvanceChar(CurPtr, Result);
1903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
Chris Lattner5a78a022006-07-20 06:02:19 +00001905 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001906 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001907 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Chris Lattnerd01e2912006-06-18 16:22:51 +00001909 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001910 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001911 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001912 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001913 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001914}
1915
1916
1917/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001918/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001919bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001920 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001921 // Does this character contain the \0 character?
1922 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001923
Richard Smith3e3a7052014-11-08 06:08:42 +00001924 if (!isLexingRawMode()) {
1925 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1926 Diag(BufferPtr, getLangOpts().CPlusPlus
1927 ? diag::warn_cxx98_compat_unicode_literal
1928 : diag::warn_c99_compat_unicode_literal);
1929 else if (Kind == tok::utf8_char_constant)
1930 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1931 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001932
Chris Lattner22eb9722006-06-18 05:43:12 +00001933 char C = getAndAdvanceChar(CurPtr, Result);
1934 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001935 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001936 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001937 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001938 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001939 }
1940
1941 while (C != '\'') {
1942 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001943 if (C == '\\')
1944 C = getAndAdvanceChar(CurPtr, Result);
1945
1946 if (C == '\n' || C == '\r' || // Newline.
1947 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001948 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001949 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001950 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001951 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001952 }
1953
1954 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001955 if (isCodeCompletionPoint(CurPtr-1)) {
1956 PP->CodeCompleteNaturalLanguage();
1957 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001958 cutOffLexing();
1959 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001960 }
1961
Chris Lattner86851b82010-07-07 23:24:27 +00001962 NulCharacter = CurPtr-1;
1963 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001964 C = getAndAdvanceChar(CurPtr, Result);
1965 }
Mike Stump11289f42009-09-09 15:08:12 +00001966
Richard Smithe18f0fa2012-03-05 04:02:15 +00001967 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001968 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001969 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001970
Chris Lattner86851b82010-07-07 23:24:27 +00001971 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001972 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001973 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001974
Chris Lattnerd01e2912006-06-18 16:22:51 +00001975 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001976 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001977 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001978 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001979 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001980}
1981
1982/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1983/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00001984///
1985/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1986///
Eli Friedman0834a4b2013-09-19 00:41:32 +00001987bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1988 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001989 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00001990 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1991
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00001992 unsigned char Char = *CurPtr;
1993
1994 // Skip consecutive spaces efficiently.
Chris Lattner22eb9722006-06-18 05:43:12 +00001995 while (1) {
1996 // Skip horizontal whitespace very aggressively.
1997 while (isHorizontalWhitespace(Char))
1998 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00001999
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002000 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002001 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 break;
Mike Stump11289f42009-09-09 15:08:12 +00002003
Chris Lattner22eb9722006-06-18 05:43:12 +00002004 if (ParsingPreprocessorDirective) {
2005 // End of preprocessor directive line, let LexTokenInternal handle this.
2006 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002007 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002010 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002011 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002012 Char = *++CurPtr;
2013 }
2014
Chris Lattner4d963442008-10-12 04:05:48 +00002015 // If the client wants us to return whitespace, return it now.
2016 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002017 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002018 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002019 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002020 IsAtPhysicalStartOfLine = true;
2021 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002022 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002023 return true;
2024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002026 // If this isn't immediately after a newline, there is leading space.
2027 char PrevChar = CurPtr[-1];
2028 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2029
2030 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002031 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002032 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002033 TokAtPhysicalStartOfLine = true;
2034 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002035
Chris Lattner22eb9722006-06-18 05:43:12 +00002036 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002037 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002038}
2039
Nico Weber158a31a2012-11-11 07:02:14 +00002040/// We have just read the // characters from input. Skip until we find the
2041/// newline character thats terminate the comment. Then update BufferPtr and
2042/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002043///
2044/// If we're in KeepCommentMode or any CommentHandler has inserted
2045/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002046bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2047 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002048 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002049 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002050 if (!LangOpts.LineComment && !isLexingRawMode()) {
2051 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Chris Lattner22eb9722006-06-18 05:43:12 +00002053 // Mark them enabled so we only emit one warning for this translation
2054 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002055 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
Chris Lattner22eb9722006-06-18 05:43:12 +00002058 // Scan over the body of the comment. The common case, when scanning, is that
2059 // the comment contains normal ascii characters with nothing interesting in
2060 // them. As such, optimize for this case with the inner loop.
2061 char C;
2062 do {
2063 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002064 // Skip over characters in the fast loop.
2065 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002066 C != '\n' && C != '\r') // Newline or DOS-style newline.
2067 C = *++CurPtr;
2068
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002069 const char *NextLine = CurPtr;
2070 if (C != 0) {
2071 // We found a newline, see if it's escaped.
2072 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002073 bool HasSpace = false;
2074 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002075 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002076 HasSpace = true;
2077 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002078
2079 if (*EscapePtr == '\\') // Escaped newline.
2080 CurPtr = EscapePtr;
2081 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2082 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2083 CurPtr = EscapePtr-2;
2084 else
2085 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002086
2087 // If there was space between the backslash and newline, warn about it.
2088 if (HasSpace && !isLexingRawMode())
2089 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Chris Lattner22eb9722006-06-18 05:43:12 +00002092 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002093 // properly decode the character. Read it in raw mode to avoid emitting
2094 // diagnostics about things like trigraphs. If we see an escaped newline,
2095 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002096 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002097 bool OldRawMode = isLexingRawMode();
2098 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002099 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002100 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002101
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002102 // If we only read only one character, then no special handling is needed.
2103 // We're done and can skip forward to the newline.
2104 if (C != 0 && CurPtr == OldPtr+1) {
2105 CurPtr = NextLine;
2106 break;
2107 }
2108
Chris Lattner22eb9722006-06-18 05:43:12 +00002109 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002110 // \n, then we had an escaped newline within the comment. Emit diagnostic
2111 // unless the next line is also a // comment.
2112 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 for (; OldPtr != CurPtr; ++OldPtr)
2114 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002115 // Okay, we found a // comment that ends in a newline, if the next
2116 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002117 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002118 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002119 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002120 ++ForwardPtr;
2121 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2122 break;
2123 }
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattner6d27a162008-11-22 02:02:22 +00002125 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002126 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002127 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002128 }
2129 }
Mike Stump11289f42009-09-09 15:08:12 +00002130
Douglas Gregor11583702010-08-25 17:04:25 +00002131 if (CurPtr == BufferEnd+1) {
Douglas Gregor11583702010-08-25 17:04:25 +00002132 --CurPtr;
2133 break;
2134 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002135
2136 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2137 PP->CodeCompleteNaturalLanguage();
2138 cutOffLexing();
2139 return false;
2140 }
2141
Chris Lattner22eb9722006-06-18 05:43:12 +00002142 } while (C != '\n' && C != '\r');
2143
Chris Lattner93ddf802010-02-03 21:06:21 +00002144 // Found but did not consume the newline. Notify comment handlers about the
2145 // comment unless we're in a #if 0 block.
2146 if (PP && !isLexingRawMode() &&
2147 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2148 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002149 BufferPtr = CurPtr;
2150 return true; // A token has to be returned.
2151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Chris Lattner457fc152006-07-29 06:30:25 +00002153 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002154 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002155 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002156
2157 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002158 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002159 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002160 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002161 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002162 }
Mike Stump11289f42009-09-09 15:08:12 +00002163
Chris Lattner22eb9722006-06-18 05:43:12 +00002164 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002165 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002166 // contribute to another token), it isn't needed for correctness. Note that
2167 // this is ok even in KeepWhitespaceMode, because we would have returned the
2168 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002169 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002170
Chris Lattner22eb9722006-06-18 05:43:12 +00002171 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002172 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002173 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002174 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002175 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002176 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002177 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002178}
Chris Lattner22eb9722006-06-18 05:43:12 +00002179
Nico Weber158a31a2012-11-11 07:02:14 +00002180/// If in save-comment mode, package up this Line comment in an appropriate
2181/// way and return it.
2182bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002183 // If we're not in a preprocessor directive, just return the // comment
2184 // directly.
2185 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002186
David Blaikied5321242012-06-06 18:52:13 +00002187 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002188 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002189
Nico Weber158a31a2012-11-11 07:02:14 +00002190 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002191 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002192 bool Invalid = false;
2193 std::string Spelling = PP->getSpelling(Result, &Invalid);
2194 if (Invalid)
2195 return true;
2196
Nico Weber158a31a2012-11-11 07:02:14 +00002197 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002198 Spelling[1] = '*'; // Change prefix to "/*".
2199 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerb11c3232008-10-12 04:51:35 +00002201 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002202 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002203 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002204 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002205}
2206
Chris Lattnercb283342006-06-18 06:48:37 +00002207/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002208/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2209/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002210static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002211 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002212 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattner22eb9722006-06-18 05:43:12 +00002214 // Back up off the newline.
2215 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chris Lattner22eb9722006-06-18 05:43:12 +00002217 // If this is a two-character newline sequence, skip the other character.
2218 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2219 // \n\n or \r\r -> not escaped newline.
2220 if (CurPtr[0] == CurPtr[1])
2221 return false;
2222 // \n\r or \r\n -> skip the newline.
2223 --CurPtr;
2224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
Chris Lattner22eb9722006-06-18 05:43:12 +00002226 // If we have horizontal whitespace, skip over it. We allow whitespace
2227 // between the slash and newline.
2228 bool HasSpace = false;
2229 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2230 --CurPtr;
2231 HasSpace = true;
2232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattner22eb9722006-06-18 05:43:12 +00002234 // If we have a slash, we know this is an escaped newline.
2235 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002236 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002237 } else {
2238 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002239 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2240 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002241 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Chris Lattnercb283342006-06-18 06:48:37 +00002243 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002244 CurPtr -= 2;
2245
2246 // If no trigraphs are enabled, warn that we ignored this trigraph and
2247 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002248 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002249 if (!L->isLexingRawMode())
2250 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002251 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002252 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002253 if (!L->isLexingRawMode())
2254 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002255 }
Mike Stump11289f42009-09-09 15:08:12 +00002256
Chris Lattner22eb9722006-06-18 05:43:12 +00002257 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002258 if (!L->isLexingRawMode())
2259 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattner22eb9722006-06-18 05:43:12 +00002261 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002262 if (HasSpace && !L->isLexingRawMode())
2263 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002264
Chris Lattnercb283342006-06-18 06:48:37 +00002265 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002266}
2267
Chris Lattneraded4a92006-10-27 04:42:31 +00002268#ifdef __SSE2__
2269#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002270#elif __ALTIVEC__
2271#include <altivec.h>
2272#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002273#endif
2274
James Dennettf442d242012-06-17 03:40:43 +00002275/// We have just read from input the / and * characters that started a comment.
2276/// Read until we find the * and / characters that terminate the comment.
2277/// Note that we don't bother decoding trigraphs or escaped newlines in block
2278/// comments, because they cannot cause the comment to end. The only thing
2279/// that can happen is the comment could end with an escaped newline between
2280/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002281///
Chris Lattner87d02082010-01-18 22:35:47 +00002282/// If we're in KeepCommentMode or any CommentHandler has inserted
2283/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002284bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2285 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002286 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002287 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002288 // optimization helps people who like to put a lot of * characters in their
2289 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002290
2291 // The first character we get with newlines and trigraphs skipped to handle
2292 // the degenerate /*/ case below correctly if the * has an escaped newline
2293 // after it.
2294 unsigned CharSize;
2295 unsigned char C = getCharAndSize(CurPtr, CharSize);
2296 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002297 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002298 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002299 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002300 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattner99e7d232008-10-12 04:19:49 +00002302 // KeepWhitespaceMode should return this broken comment as a token. Since
2303 // it isn't a well formed comment, just return it as an 'unknown' token.
2304 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002305 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002306 return true;
2307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Chris Lattner99e7d232008-10-12 04:19:49 +00002309 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002310 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002311 }
Mike Stump11289f42009-09-09 15:08:12 +00002312
Chris Lattnerc850ad62007-07-21 23:43:37 +00002313 // Check to see if the first character after the '/*' is another /. If so,
2314 // then this slash does not end the block comment, it is part of it.
2315 if (C == '/')
2316 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattner22eb9722006-06-18 05:43:12 +00002318 while (1) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002319 // Skip over all non-interesting characters until we find end of buffer or a
2320 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002321 if (CurPtr + 24 < BufferEnd &&
2322 // If there is a code-completion point avoid the fast scan because it
2323 // doesn't check for '\0'.
2324 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002325 // While not aligned to a 16-byte boundary.
2326 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2327 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002328
Chris Lattner6cc3e362006-10-27 04:12:35 +00002329 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002330
2331#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002332 __m128i Slashes = _mm_set1_epi8('/');
2333 while (CurPtr+16 <= BufferEnd) {
2334 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2335 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002336 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002337 // Adjust the pointer to point directly after the first slash. It's
2338 // not necessary to set C here, it will be overwritten at the end of
2339 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002340 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002341 goto FoundSlash;
2342 }
Roman Divacky61509902014-04-03 18:04:52 +00002343 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002344 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002345#elif __ALTIVEC__
2346 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002347 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002348 '/', '/', '/', '/', '/', '/', '/', '/'
2349 };
2350 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002351 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002352 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002353#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002354 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002355 while (CurPtr[0] != '/' &&
2356 CurPtr[1] != '/' &&
2357 CurPtr[2] != '/' &&
2358 CurPtr[3] != '/' &&
2359 CurPtr+4 < BufferEnd) {
2360 CurPtr += 4;
2361 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002362#endif
Mike Stump11289f42009-09-09 15:08:12 +00002363
Chris Lattneraded4a92006-10-27 04:42:31 +00002364 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002365 C = *CurPtr++;
2366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
Chris Lattneraded4a92006-10-27 04:42:31 +00002368 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002369 while (C != '/' && C != '\0')
2370 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002371
Chris Lattner22eb9722006-06-18 05:43:12 +00002372 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002373 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002374 if (CurPtr[-2] == '*') // We found the final */. We're done!
2375 break;
Mike Stump11289f42009-09-09 15:08:12 +00002376
Chris Lattner22eb9722006-06-18 05:43:12 +00002377 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002378 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002379 // We found the final */, though it had an escaped newline between the
2380 // * and /. We're done!
2381 break;
2382 }
2383 }
2384 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2385 // If this is a /* inside of the comment, emit a warning. Don't do this
2386 // if this is a /*/, which will end the comment. This misses cases with
2387 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002388 if (!isLexingRawMode())
2389 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002390 }
2391 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002392 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002393 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002394 // Note: the user probably forgot a */. We could continue immediately
2395 // after the /*, but this would involve lexing a lot of what really is the
2396 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002397 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattner99e7d232008-10-12 04:19:49 +00002399 // KeepWhitespaceMode should return this broken comment as a token. Since
2400 // it isn't a well formed comment, just return it as an 'unknown' token.
2401 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002402 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002403 return true;
2404 }
Mike Stump11289f42009-09-09 15:08:12 +00002405
Chris Lattner99e7d232008-10-12 04:19:49 +00002406 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002407 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002408 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2409 PP->CodeCompleteNaturalLanguage();
2410 cutOffLexing();
2411 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002412 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002413
Chris Lattner22eb9722006-06-18 05:43:12 +00002414 C = *CurPtr++;
2415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
Chris Lattner93ddf802010-02-03 21:06:21 +00002417 // Notify comment handlers about the comment unless we're in a #if 0 block.
2418 if (PP && !isLexingRawMode() &&
2419 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2420 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002421 BufferPtr = CurPtr;
2422 return true; // A token has to be returned.
2423 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002424
Chris Lattner457fc152006-07-29 06:30:25 +00002425 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002426 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002427 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002428 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002429 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002430
2431 // It is common for the tokens immediately after a /**/ comment to be
2432 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002433 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2434 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002435 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002436 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002437 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002438 }
2439
2440 // Otherwise, just return so that the next character will be lexed as a token.
2441 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002442 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002443 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002444}
2445
2446//===----------------------------------------------------------------------===//
2447// Primary Lexing Entry Points
2448//===----------------------------------------------------------------------===//
2449
Chris Lattner22eb9722006-06-18 05:43:12 +00002450/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2451/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002452void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002453 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2454 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002455 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002456
2457 // CurPtr - Cache BufferPtr in an automatic variable.
2458 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002459 while (1) {
2460 char Char = getAndAdvanceChar(CurPtr, Tmp);
2461 switch (Char) {
2462 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002463 if (Result)
2464 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002465 break;
2466 case 0: // Null.
2467 // Found end of file?
2468 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002469 if (isCodeCompletionPoint(CurPtr-1)) {
2470 PP->CodeCompleteNaturalLanguage();
2471 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002472 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002473 }
2474
Chris Lattner22eb9722006-06-18 05:43:12 +00002475 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002476 if (Result)
2477 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002478 break;
2479 }
2480 // FALL THROUGH.
2481 case '\r':
2482 case '\n':
2483 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2484 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2485 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002486
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002487 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002488 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002489 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002490 if (PP)
2491 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002492 Lex(Tmp);
2493 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002494 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002495
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002496 // Finally, we're done;
2497 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002498 }
2499 }
2500}
2501
2502/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2503/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002504/// This returns true if Result contains a token, false if PP.Lex should be
2505/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002506bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002507 // If we hit the end of the file while parsing a preprocessor directive,
2508 // end the preprocessor directive first. The next token returned will
2509 // then be the end of file.
2510 if (ParsingPreprocessorDirective) {
2511 // Done parsing the "line".
2512 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002513 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002514 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002515
Chris Lattner457fc152006-07-29 06:30:25 +00002516 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002517 if (PP)
2518 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002519 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002520 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002521
Chris Lattner30a2fa12006-07-19 06:31:49 +00002522 // If we are in raw mode, return this event as an EOF token. Let the caller
2523 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002524 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002525 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002526 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002527 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002528 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002529 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002530
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002531 // Issue diagnostics for unterminated #if and missing newline.
2532
Chris Lattner30a2fa12006-07-19 06:31:49 +00002533 // If we are in a #if directive, emit an error.
2534 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002535 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002536 PP->Diag(ConditionalStack.back().IfLoc,
2537 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002538 ConditionalStack.pop_back();
2539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
Chris Lattner8f96d042008-04-12 05:54:25 +00002541 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2542 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002543 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2544 DiagnosticsEngine &Diags = PP->getDiagnostics();
2545 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2546 unsigned DiagID;
2547
2548 if (LangOpts.CPlusPlus11) {
2549 // C++11 [lex.phases] 2.2 p2
2550 // Prefer the C++98 pedantic compatibility warning over the generic,
2551 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002552 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002553 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2554 } else {
2555 DiagID = diag::warn_no_newline_eof;
2556 }
2557 } else {
2558 DiagID = diag::ext_no_newline_eof;
2559 }
2560
2561 Diag(BufferEnd, DiagID)
2562 << FixItHint::CreateInsertion(EndLoc, "\n");
2563 }
Mike Stump11289f42009-09-09 15:08:12 +00002564
Chris Lattner22eb9722006-06-18 05:43:12 +00002565 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002566
2567 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002568 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002569}
2570
Chris Lattner678c8802006-07-11 05:46:12 +00002571/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2572/// the specified lexer will return a tok::l_paren token, 0 if it is something
2573/// else and 2 if there are no more tokens in the buffer controlled by the
2574/// lexer.
2575unsigned Lexer::isNextPPTokenLParen() {
2576 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002577
Chris Lattner678c8802006-07-11 05:46:12 +00002578 // Switch to 'skipping' mode. This will ensure that we can lex a token
2579 // without emitting diagnostics, disables macro expansion, and will cause EOF
2580 // to return an EOF token instead of popping the include stack.
2581 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002582
Chris Lattner678c8802006-07-11 05:46:12 +00002583 // Save state that can be changed while lexing so that we can restore it.
2584 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002585 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002586 bool atStartOfLine = IsAtStartOfLine;
2587 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2588 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002589
Chris Lattner146762e2007-07-20 16:59:19 +00002590 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002591 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002592
Chris Lattner678c8802006-07-11 05:46:12 +00002593 // Restore state that may have changed.
2594 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002595 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002596 HasLeadingSpace = leadingSpace;
2597 IsAtStartOfLine = atStartOfLine;
2598 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002599
Chris Lattner678c8802006-07-11 05:46:12 +00002600 // Restore the lexer back to non-skipping mode.
2601 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002602
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002603 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002604 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002605 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002606}
2607
James Dennettf442d242012-06-17 03:40:43 +00002608/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002609static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2610 ConflictMarkerKind CMK) {
2611 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2612 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002613 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002614 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002615 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002616 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002617 if (Pos == 0 ||
2618 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002619 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2620 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002621 continue;
2622 }
2623 return RestOfBuffer.data()+Pos;
2624 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002625 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002626}
2627
2628/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2629/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2630/// and recover nicely. This returns true if it is a conflict marker and false
2631/// if not.
2632bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2633 // Only a conflict marker if it starts at the beginning of a line.
2634 if (CurPtr != BufferStart &&
2635 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2636 return false;
2637
Richard Smitha9e33d42011-10-12 00:37:51 +00002638 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002639 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2640 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002641 return false;
2642
2643 // If we have a situation where we don't care about conflict markers, ignore
2644 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002645 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002646 return false;
2647
Richard Smitha9e33d42011-10-12 00:37:51 +00002648 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2649
2650 // Check to see if there is an ending marker somewhere in the buffer at the
2651 // start of a line to terminate this conflict marker.
2652 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002653 // We found a match. We are really in a conflict marker.
2654 // Diagnose this, and ignore to the end of line.
2655 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002656 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002657
2658 // Skip ahead to the end of line. We know this exists because the
2659 // end-of-conflict marker starts with \r or \n.
2660 while (*CurPtr != '\r' && *CurPtr != '\n') {
2661 assert(CurPtr != BufferEnd && "Didn't find end of line");
2662 ++CurPtr;
2663 }
2664 BufferPtr = CurPtr;
2665 return true;
2666 }
2667
2668 // No end of conflict marker found.
2669 return false;
2670}
2671
2672
Richard Smitha9e33d42011-10-12 00:37:51 +00002673/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2674/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2675/// is the end of a conflict marker. Handle it by ignoring up until the end of
2676/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002677bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2678 // Only a conflict marker if it starts at the beginning of a line.
2679 if (CurPtr != BufferStart &&
2680 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2681 return false;
2682
2683 // If we have a situation where we don't care about conflict markers, ignore
2684 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002685 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002686 return false;
2687
Richard Smitha9e33d42011-10-12 00:37:51 +00002688 // Check to see if we have the marker (4 characters in a row).
2689 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002690 if (CurPtr[i] != CurPtr[0])
2691 return false;
2692
2693 // If we do have it, search for the end of the conflict marker. This could
2694 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2695 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002696 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2697 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002698 CurPtr = End;
2699
2700 // Skip ahead to the end of line.
2701 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2702 ++CurPtr;
2703
2704 BufferPtr = CurPtr;
2705
2706 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002707 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002708 return true;
2709 }
2710
2711 return false;
2712}
2713
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002714bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2715 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002716 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002717 return Loc == PP->getCodeCompletionLoc();
2718 }
2719
2720 return false;
2721}
2722
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002723uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2724 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002725 unsigned CharSize;
2726 char Kind = getCharAndSize(StartPtr, CharSize);
2727
2728 unsigned NumHexDigits;
2729 if (Kind == 'u')
2730 NumHexDigits = 4;
2731 else if (Kind == 'U')
2732 NumHexDigits = 8;
2733 else
2734 return 0;
2735
Jordan Rosec0cba272013-01-27 20:12:04 +00002736 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002737 if (Result && !isLexingRawMode())
2738 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002739 return 0;
2740 }
2741
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002742 const char *CurPtr = StartPtr + CharSize;
2743 const char *KindLoc = &CurPtr[-1];
2744
2745 uint32_t CodePoint = 0;
2746 for (unsigned i = 0; i < NumHexDigits; ++i) {
2747 char C = getCharAndSize(CurPtr, CharSize);
2748
2749 unsigned Value = llvm::hexDigitValue(C);
2750 if (Value == -1U) {
2751 if (Result && !isLexingRawMode()) {
2752 if (i == 0) {
2753 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2754 << StringRef(KindLoc, 1);
2755 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002756 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002757
2758 // If the user wrote \U1234, suggest a fixit to \u.
2759 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002760 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002761 Diag(KindLoc, diag::note_ucn_four_not_eight)
2762 << FixItHint::CreateReplacement(URange, "u");
2763 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002764 }
2765 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002766
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002767 return 0;
2768 }
2769
2770 CodePoint <<= 4;
2771 CodePoint += Value;
2772
2773 CurPtr += CharSize;
2774 }
2775
2776 if (Result) {
2777 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002778 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002779 StartPtr = CurPtr;
2780 else
2781 while (StartPtr != CurPtr)
2782 (void)getAndAdvanceChar(StartPtr, *Result);
2783 } else {
2784 StartPtr = CurPtr;
2785 }
2786
Justin Bogner53535132013-10-21 05:02:28 +00002787 // Don't apply C family restrictions to UCNs in assembly mode
2788 if (LangOpts.AsmPreprocessor)
2789 return CodePoint;
2790
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002791 // C99 6.4.3p2: A universal character name shall not specify a character whose
2792 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2793 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2794 // C++11 [lex.charset]p2: If the hexadecimal value for a
2795 // universal-character-name corresponds to a surrogate code point (in the
2796 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2797 // if the hexadecimal value for a universal-character-name outside the
2798 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2799 // string literal corresponds to a control character (in either of the
2800 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2801 // basic source character set, the program is ill-formed.
2802 if (CodePoint < 0xA0) {
2803 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2804 return CodePoint;
2805
2806 // We don't use isLexingRawMode() here because we need to warn about bad
2807 // UCNs even when skipping preprocessing tokens in a #if block.
2808 if (Result && PP) {
2809 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2810 Diag(BufferPtr, diag::err_ucn_control_character);
2811 else {
2812 char C = static_cast<char>(CodePoint);
2813 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2814 }
2815 }
2816
2817 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002818
2819 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002820 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002821 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002822 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002823 if (Result && PP) {
2824 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2825 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2826 else
2827 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2828 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002829 return 0;
2830 }
2831
2832 return CodePoint;
2833}
2834
Eli Friedman0834a4b2013-09-19 00:41:32 +00002835bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2836 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002837 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2838 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002839 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002840 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002841 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002842 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002843
2844 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002845 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002846 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002847 return false;
2848}
Jordan Rose4246ae02013-01-24 20:50:50 +00002849
Eli Friedman0834a4b2013-09-19 00:41:32 +00002850bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002851 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2852 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2853 !PP->isPreprocessedOutput()) {
2854 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2855 makeCharRange(*this, BufferPtr, CurPtr),
2856 /*IsFirst=*/true);
2857 }
2858
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002859 MIOpt.ReadToken();
2860 return LexIdentifier(Result, CurPtr);
2861 }
2862
Jordan Rosecc538342013-01-31 19:48:48 +00002863 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2864 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002865 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002866 // Non-ASCII characters tend to creep into source code unintentionally.
2867 // Instead of letting the parser complain about the unknown token,
2868 // just drop the character.
2869 // Note that we can /only/ do this when the non-ASCII character is actually
2870 // spelled as Unicode, not written as a UCN. The standard requires that
2871 // we not throw away any possible preprocessor tokens, but there's a
2872 // loophole in the mapping of Unicode characters to basic character set
2873 // characters that allows us to map these particular characters to, say,
2874 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002875 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002876 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002877
2878 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002879 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002880 }
2881
2882 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2883 // up by accident.
2884 MIOpt.ReadToken();
2885 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002886 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002887}
2888
Eli Friedman0834a4b2013-09-19 00:41:32 +00002889void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2890 IsAtStartOfLine = Result.isAtStartOfLine();
2891 HasLeadingSpace = Result.hasLeadingSpace();
2892 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2893 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2894}
2895
2896bool Lexer::Lex(Token &Result) {
2897 // Start a new token.
2898 Result.startToken();
2899
2900 // Set up misc whitespace flags for LexTokenInternal.
2901 if (IsAtStartOfLine) {
2902 Result.setFlag(Token::StartOfLine);
2903 IsAtStartOfLine = false;
2904 }
2905
2906 if (HasLeadingSpace) {
2907 Result.setFlag(Token::LeadingSpace);
2908 HasLeadingSpace = false;
2909 }
2910
2911 if (HasLeadingEmptyMacro) {
2912 Result.setFlag(Token::LeadingEmptyMacro);
2913 HasLeadingEmptyMacro = false;
2914 }
2915
2916 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2917 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002918 bool isRawLex = isLexingRawMode();
2919 (void) isRawLex;
2920 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2921 // (After the LexTokenInternal call, the lexer might be destroyed.)
2922 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2923 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002924}
Chris Lattner22eb9722006-06-18 05:43:12 +00002925
2926/// LexTokenInternal - This implements a simple C family lexer. It is an
2927/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002928/// has a null character at the end of the file. This returns a preprocessing
2929/// token, not a normal token, as such, it is an internal interface. It assumes
2930/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002931bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002932LexNextToken:
2933 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002934 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002935 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002936
Chris Lattner22eb9722006-06-18 05:43:12 +00002937 // CurPtr - Cache BufferPtr in an automatic variable.
2938 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002939
Chris Lattnereb54b592006-07-10 06:34:27 +00002940 // Small amounts of horizontal whitespace is very common between tokens.
2941 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2942 ++CurPtr;
2943 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2944 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002945
Chris Lattner4d963442008-10-12 04:05:48 +00002946 // If we are keeping whitespace and other tokens, just return what we just
2947 // skipped. The next lexer invocation will return the token after the
2948 // whitespace.
2949 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002950 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002951 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002952 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00002953 }
Mike Stump11289f42009-09-09 15:08:12 +00002954
Chris Lattnereb54b592006-07-10 06:34:27 +00002955 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002956 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00002957 }
Mike Stump11289f42009-09-09 15:08:12 +00002958
Chris Lattner22eb9722006-06-18 05:43:12 +00002959 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00002960
Chris Lattner22eb9722006-06-18 05:43:12 +00002961 // Read a character, advancing over it.
2962 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002963 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00002964
Chris Lattner22eb9722006-06-18 05:43:12 +00002965 switch (Char) {
2966 case 0: // Null.
2967 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00002968 if (CurPtr-1 == BufferEnd)
2969 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00002970
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002971 // Check if we are performing code completion.
2972 if (isCodeCompletionPoint(CurPtr-1)) {
2973 // Return the code-completion token.
2974 Result.startToken();
2975 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002976 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002977 }
2978
Chris Lattner6d27a162008-11-22 02:02:22 +00002979 if (!isLexingRawMode())
2980 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00002981 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002982 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2983 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00002984
Eli Friedman0834a4b2013-09-19 00:41:32 +00002985 // We know the lexer hasn't changed, so just try again with this lexer.
2986 // (We manually eliminate the tail call to avoid recursion.)
2987 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00002988
2989 case 26: // DOS & CP/M EOF: "^Z".
2990 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00002991 if (LangOpts.MicrosoftExt) {
2992 if (!isLexingRawMode())
2993 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002994 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00002995 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002996
Chris Lattner3dfff972009-12-17 05:29:40 +00002997 // If Microsoft extensions are disabled, this is just random garbage.
2998 Kind = tok::unknown;
2999 break;
3000
Chris Lattner22eb9722006-06-18 05:43:12 +00003001 case '\n':
3002 case '\r':
3003 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003004 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003005 if (ParsingPreprocessorDirective) {
3006 // Done parsing the "line".
3007 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003008
Chris Lattner457fc152006-07-29 06:30:25 +00003009 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003010 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003011 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003012
Chris Lattner22eb9722006-06-18 05:43:12 +00003013 // Since we consumed a newline, we are back at the start of a line.
3014 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003015 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003016
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003017 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003018 break;
3019 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003020
Chris Lattner22eb9722006-06-18 05:43:12 +00003021 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003022 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003023
Eli Friedman0834a4b2013-09-19 00:41:32 +00003024 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3025 return true; // KeepWhitespaceMode
3026
3027 // We only saw whitespace, so just try again with this lexer.
3028 // (We manually eliminate the tail call to avoid recursion.)
3029 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003030 case ' ':
3031 case '\t':
3032 case '\f':
3033 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003034 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003035 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003036 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3037 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003038
3039 SkipIgnoredUnits:
3040 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003041
Chris Lattnerb9b85972007-07-22 06:29:05 +00003042 // If the next token is obviously a // or /* */ comment, skip it efficiently
3043 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003044 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003045 LangOpts.LineComment &&
3046 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003047 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3048 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003049 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003050 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003051 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3052 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003053 goto SkipIgnoredUnits;
3054 } else if (isHorizontalWhitespace(*CurPtr)) {
3055 goto SkipHorizontalWhitespace;
3056 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003057 // We only saw whitespace, so just try again with this lexer.
3058 // (We manually eliminate the tail call to avoid recursion.)
3059 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003060
Chris Lattner2b15cf72008-01-03 17:58:54 +00003061 // C99 6.4.4.1: Integer Constants.
3062 // C99 6.4.4.2: Floating Constants.
3063 case '0': case '1': case '2': case '3': case '4':
3064 case '5': case '6': case '7': case '8': case '9':
3065 // Notify MIOpt that we read a non-whitespace/non-comment token.
3066 MIOpt.ReadToken();
3067 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003068
Richard Smith9b362092013-03-09 23:56:02 +00003069 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003070 // Notify MIOpt that we read a non-whitespace/non-comment token.
3071 MIOpt.ReadToken();
3072
Richard Smith9b362092013-03-09 23:56:02 +00003073 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003074 Char = getCharAndSize(CurPtr, SizeTmp);
3075
3076 // UTF-16 string literal
3077 if (Char == '"')
3078 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3079 tok::utf16_string_literal);
3080
3081 // UTF-16 character constant
3082 if (Char == '\'')
3083 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3084 tok::utf16_char_constant);
3085
Craig Topper54edcca2011-08-11 04:06:15 +00003086 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003087 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3088 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003089 return LexRawStringLiteral(Result,
3090 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3091 SizeTmp2, Result),
3092 tok::utf16_string_literal);
3093
3094 if (Char == '8') {
3095 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3096
3097 // UTF-8 string literal
3098 if (Char2 == '"')
3099 return LexStringLiteral(Result,
3100 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3101 SizeTmp2, Result),
3102 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003103 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3104 return LexCharConstant(
3105 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3106 SizeTmp2, Result),
3107 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003108
Richard Smith9b362092013-03-09 23:56:02 +00003109 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003110 unsigned SizeTmp3;
3111 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3112 // UTF-8 raw string literal
3113 if (Char3 == '"') {
3114 return LexRawStringLiteral(Result,
3115 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3116 SizeTmp2, Result),
3117 SizeTmp3, Result),
3118 tok::utf8_string_literal);
3119 }
3120 }
3121 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003122 }
3123
3124 // treat u like the start of an identifier.
3125 return LexIdentifier(Result, CurPtr);
3126
Richard Smith9b362092013-03-09 23:56:02 +00003127 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003128 // Notify MIOpt that we read a non-whitespace/non-comment token.
3129 MIOpt.ReadToken();
3130
Richard Smith9b362092013-03-09 23:56:02 +00003131 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003132 Char = getCharAndSize(CurPtr, SizeTmp);
3133
3134 // UTF-32 string literal
3135 if (Char == '"')
3136 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3137 tok::utf32_string_literal);
3138
3139 // UTF-32 character constant
3140 if (Char == '\'')
3141 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3142 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003143
3144 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003145 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3146 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003147 return LexRawStringLiteral(Result,
3148 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3149 SizeTmp2, Result),
3150 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003151 }
3152
3153 // treat U like the start of an identifier.
3154 return LexIdentifier(Result, CurPtr);
3155
Craig Topper54edcca2011-08-11 04:06:15 +00003156 case 'R': // Identifier or C++0x raw string literal
3157 // Notify MIOpt that we read a non-whitespace/non-comment token.
3158 MIOpt.ReadToken();
3159
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003160 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003161 Char = getCharAndSize(CurPtr, SizeTmp);
3162
3163 if (Char == '"')
3164 return LexRawStringLiteral(Result,
3165 ConsumeChar(CurPtr, SizeTmp, Result),
3166 tok::string_literal);
3167 }
3168
3169 // treat R like the start of an identifier.
3170 return LexIdentifier(Result, CurPtr);
3171
Chris Lattner2b15cf72008-01-03 17:58:54 +00003172 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003173 // Notify MIOpt that we read a non-whitespace/non-comment token.
3174 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003175 Char = getCharAndSize(CurPtr, SizeTmp);
3176
3177 // Wide string literal.
3178 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003179 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003180 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003181
Craig Topper54edcca2011-08-11 04:06:15 +00003182 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003183 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003184 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3185 return LexRawStringLiteral(Result,
3186 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3187 SizeTmp2, Result),
3188 tok::wide_string_literal);
3189
Chris Lattner22eb9722006-06-18 05:43:12 +00003190 // Wide character constant.
3191 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003192 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3193 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003194 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003195
Chris Lattner22eb9722006-06-18 05:43:12 +00003196 // C99 6.4.2: Identifiers.
3197 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3198 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003199 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003200 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3201 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3202 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003203 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003204 case 'v': case 'w': case 'x': case 'y': case 'z':
3205 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003206 // Notify MIOpt that we read a non-whitespace/non-comment token.
3207 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003208 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003209
3210 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003211 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003212 if (!isLexingRawMode())
3213 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003214 // Notify MIOpt that we read a non-whitespace/non-comment token.
3215 MIOpt.ReadToken();
3216 return LexIdentifier(Result, CurPtr);
3217 }
Mike Stump11289f42009-09-09 15:08:12 +00003218
Chris Lattnerb11c3232008-10-12 04:51:35 +00003219 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003220 break;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Chris Lattner22eb9722006-06-18 05:43:12 +00003222 // C99 6.4.4: Character Constants.
3223 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003224 // Notify MIOpt that we read a non-whitespace/non-comment token.
3225 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003226 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003227
3228 // C99 6.4.5: String Literals.
3229 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003230 // Notify MIOpt that we read a non-whitespace/non-comment token.
3231 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003232 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003233
3234 // C99 6.4.6: Punctuators.
3235 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003236 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003237 break;
3238 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003239 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003240 break;
3241 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003242 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003243 break;
3244 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003245 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003246 break;
3247 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003248 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003249 break;
3250 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003251 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003252 break;
3253 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003254 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003255 break;
3256 case '.':
3257 Char = getCharAndSize(CurPtr, SizeTmp);
3258 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003259 // Notify MIOpt that we read a non-whitespace/non-comment token.
3260 MIOpt.ReadToken();
3261
Chris Lattner22eb9722006-06-18 05:43:12 +00003262 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003263 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003264 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003265 CurPtr += SizeTmp;
3266 } else if (Char == '.' &&
3267 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003268 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003269 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3270 SizeTmp2, Result);
3271 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003272 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003273 }
3274 break;
3275 case '&':
3276 Char = getCharAndSize(CurPtr, SizeTmp);
3277 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003278 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003279 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3280 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003281 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003282 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3283 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003284 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003285 }
3286 break;
Mike Stump11289f42009-09-09 15:08:12 +00003287 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003288 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003289 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3291 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003292 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003293 }
3294 break;
3295 case '+':
3296 Char = getCharAndSize(CurPtr, SizeTmp);
3297 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003299 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003300 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003302 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003303 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003304 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003305 }
3306 break;
3307 case '-':
3308 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003309 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003310 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003311 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003312 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003313 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003314 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3315 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003316 Kind = tok::arrowstar;
3317 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003319 Kind = tok::arrow;
3320 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003321 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003322 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003323 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003324 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003325 }
3326 break;
3327 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003328 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003329 break;
3330 case '!':
3331 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003332 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003333 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3334 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003335 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003336 }
3337 break;
3338 case '/':
3339 // 6.4.9: Comments
3340 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003341 if (Char == '/') { // Line comment.
3342 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003343 // want to lex this as a comment. There is one problem with this though,
3344 // that in one particular corner case, this can change the behavior of the
3345 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003346 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003347 // "foo". Check to see if the character after the second slash is a '*'.
3348 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003349 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003350 bool TreatAsComment = LangOpts.LineComment &&
3351 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003352 if (!TreatAsComment)
3353 if (!(PP && PP->isPreprocessedOutput()))
3354 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3355
3356 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003357 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3358 TokAtPhysicalStartOfLine))
3359 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003360
Chris Lattner58827712009-01-16 22:39:25 +00003361 // It is common for the tokens immediately after a // comment to be
3362 // whitespace (indentation for the next line). Instead of going through
3363 // the big switch, handle it efficiently now.
3364 goto SkipIgnoredUnits;
3365 }
3366 }
Mike Stump11289f42009-09-09 15:08:12 +00003367
Chris Lattner58827712009-01-16 22:39:25 +00003368 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003369 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3370 TokAtPhysicalStartOfLine))
3371 return true; // There is a token to return.
3372
3373 // We only saw whitespace, so just try again with this lexer.
3374 // (We manually eliminate the tail call to avoid recursion.)
3375 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003376 }
Mike Stump11289f42009-09-09 15:08:12 +00003377
Chris Lattner58827712009-01-16 22:39:25 +00003378 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003379 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003380 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003381 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003382 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003383 }
3384 break;
3385 case '%':
3386 Char = getCharAndSize(CurPtr, SizeTmp);
3387 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003388 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003389 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003390 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003391 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003392 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003393 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003395 Char = getCharAndSize(CurPtr, SizeTmp);
3396 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003397 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003398 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3399 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003400 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003401 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003402 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003403 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003404 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003405 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003406 // We parsed a # character. If this occurs at the start of the line,
3407 // it's actually the start of a preprocessing directive. Callback to
3408 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003409 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003410 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003411 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003412
Chris Lattner2534324a2009-03-18 20:58:27 +00003413 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003414 }
3415 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003416 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003417 }
3418 break;
3419 case '<':
3420 Char = getCharAndSize(CurPtr, SizeTmp);
3421 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003422 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003423 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003424 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3425 if (After == '=') {
3426 Kind = tok::lesslessequal;
3427 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3428 SizeTmp2, Result);
3429 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3430 // If this is actually a '<<<<<<<' version control conflict marker,
3431 // recognize it as such and recover nicely.
3432 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003433 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3434 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3435 // ignore it.
3436 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003437 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003438 Kind = tok::lesslessless;
3439 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3440 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003441 } else {
3442 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3443 Kind = tok::lessless;
3444 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003445 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003446 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003447 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003448 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003449 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003450 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3451 // C++0x [lex.pptoken]p3:
3452 // Otherwise, if the next three characters are <:: and the subsequent
3453 // character is neither : nor >, the < is treated as a preprocessor
3454 // token by itself and not as the first character of the alternative
3455 // token <:.
3456 unsigned SizeTmp3;
3457 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3458 if (After != ':' && After != '>') {
3459 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003460 if (!isLexingRawMode())
3461 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003462 break;
3463 }
3464 }
3465
Chris Lattner22eb9722006-06-18 05:43:12 +00003466 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003467 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003468 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003469 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003470 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003471 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003472 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003473 }
3474 break;
3475 case '>':
3476 Char = getCharAndSize(CurPtr, SizeTmp);
3477 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003479 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003480 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003481 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3482 if (After == '=') {
3483 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3484 SizeTmp2, Result);
3485 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003486 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3487 // If this is actually a '>>>>' conflict marker, recognize it as such
3488 // and recover nicely.
3489 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003490 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3491 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3492 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003493 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003494 Kind = tok::greatergreatergreater;
3495 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3496 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003497 } else {
3498 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3499 Kind = tok::greatergreater;
3500 }
3501
Chris Lattner22eb9722006-06-18 05:43:12 +00003502 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003503 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003504 }
3505 break;
3506 case '^':
3507 Char = getCharAndSize(CurPtr, SizeTmp);
3508 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003509 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003510 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003511 } else if (LangOpts.OpenCL && Char == '^') {
3512 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3513 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003514 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003515 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003516 }
3517 break;
3518 case '|':
3519 Char = getCharAndSize(CurPtr, SizeTmp);
3520 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003521 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003522 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3523 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003524 // If this is '|||||||' and we're in a conflict marker, ignore it.
3525 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3526 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003527 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3529 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003530 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003531 }
3532 break;
3533 case ':':
3534 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003535 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003536 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003537 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003538 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003539 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003540 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003541 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003542 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003543 }
3544 break;
3545 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003546 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003547 break;
3548 case '=':
3549 Char = getCharAndSize(CurPtr, SizeTmp);
3550 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003551 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003552 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3553 goto LexNextToken;
3554
Chris Lattnerb11c3232008-10-12 04:51:35 +00003555 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003556 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003557 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003558 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003559 }
3560 break;
3561 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003562 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003563 break;
3564 case '#':
3565 Char = getCharAndSize(CurPtr, SizeTmp);
3566 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003567 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003569 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003570 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003571 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003572 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003573 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003574 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003575 // We parsed a # character. If this occurs at the start of the line,
3576 // it's actually the start of a preprocessing directive. Callback to
3577 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003578 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003579 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003580 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003581
Chris Lattner2534324a2009-03-18 20:58:27 +00003582 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003583 }
3584 break;
3585
Chris Lattner2b15cf72008-01-03 17:58:54 +00003586 case '@':
3587 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003588 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003589 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003590 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003591 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003592 break;
Mike Stump11289f42009-09-09 15:08:12 +00003593
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003594 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003595 case '\\':
Eli Friedman0834a4b2013-09-19 00:41:32 +00003596 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3597 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3598 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3599 return true; // KeepWhitespaceMode
3600
3601 // We only saw whitespace, so just try again with this lexer.
3602 // (We manually eliminate the tail call to avoid recursion.)
3603 goto LexNextToken;
3604 }
3605
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003606 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003607 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003608
Chris Lattnerb11c3232008-10-12 04:51:35 +00003609 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003610 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003611
3612 default: {
3613 if (isASCII(Char)) {
3614 Kind = tok::unknown;
3615 break;
3616 }
3617
3618 UTF32 CodePoint;
3619
3620 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3621 // an escaped newline.
3622 --CurPtr;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003623 ConversionResult Status =
3624 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3625 (const UTF8 *)BufferEnd,
3626 &CodePoint,
3627 strictConversion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003628 if (Status == conversionOK) {
3629 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3630 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3631 return true; // KeepWhitespaceMode
3632
3633 // We only saw whitespace, so just try again with this lexer.
3634 // (We manually eliminate the tail call to avoid recursion.)
3635 goto LexNextToken;
3636 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003637 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003638 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003639
Jordan Rosecc538342013-01-31 19:48:48 +00003640 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3641 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003642 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003643 Kind = tok::unknown;
3644 break;
3645 }
3646
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003647 // Non-ASCII characters tend to creep into source code unintentionally.
3648 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003649 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003650 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003651
3652 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003653 // We're pretending the character didn't exist, so just try again with
3654 // this lexer.
3655 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003656 goto LexNextToken;
3657 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003658 }
Mike Stump11289f42009-09-09 15:08:12 +00003659
Chris Lattner371ac8a2006-07-04 07:11:10 +00003660 // Notify MIOpt that we read a non-whitespace/non-comment token.
3661 MIOpt.ReadToken();
3662
Chris Lattnerd01e2912006-06-18 16:22:51 +00003663 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003664 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003665 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003666
3667HandleDirective:
3668 // We parsed a # character and it's the start of a preprocessing directive.
3669
3670 FormTokenWithChars(Result, CurPtr, tok::hash);
3671 PP->HandleDirective(Result);
3672
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003673 if (PP->hadModuleLoaderFatalFailure()) {
3674 // With a fatal failure in the module loader, we abort parsing.
3675 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003676 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003677 }
3678
Eli Friedman0834a4b2013-09-19 00:41:32 +00003679 // We parsed the directive; lex a token with the new state.
3680 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003681}