blob: 92942fd09a0c817e469b9293e0b9cdccc5cf5190 [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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000018#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#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"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000022#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "llvm/ADT/StringSwitch.h"
Chris Lattner619c1742007-07-22 18:38:25 +000024#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000025#include "llvm/Support/ConvertUTF.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000027#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000028#include "llvm/Support/UnicodeCharRanges.h"
29#include <algorithm>
30#include <cassert>
31#include <cstddef>
32#include <cstdint>
Craig Topper54edcca2011-08-11 04:06:15 +000033#include <cstring>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000034#include <string>
35#include <tuple>
36#include <utility>
37
Chris Lattner22eb9722006-06-18 05:43:12 +000038using namespace clang;
39
Chris Lattner4894f482007-10-07 08:47:24 +000040//===----------------------------------------------------------------------===//
41// Token Class Implementation
42//===----------------------------------------------------------------------===//
43
Mike Stump11289f42009-09-09 15:08:12 +000044/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000045bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Alex Lorenzd4754662017-05-17 11:08:36 +000046 if (isAnnotation())
47 return false;
Douglas Gregor90abb6d2008-12-01 21:46:47 +000048 if (IdentifierInfo *II = getIdentifierInfo())
49 return II->getObjCKeywordID() == objcKey;
50 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000051}
52
53/// getObjCKeywordID - Return the ObjC keyword kind.
54tok::ObjCKeywordKind Token::getObjCKeywordID() const {
Alex Lorenzd4754662017-05-17 11:08:36 +000055 if (isAnnotation())
56 return tok::objc_not_keyword;
Chris Lattner4894f482007-10-07 08:47:24 +000057 IdentifierInfo *specId = getIdentifierInfo();
58 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
59}
60
61//===----------------------------------------------------------------------===//
62// Lexer Class Implementation
63//===----------------------------------------------------------------------===//
64
David Blaikie68e081d2011-12-20 02:48:34 +000065void Lexer::anchor() { }
66
Mike Stump11289f42009-09-09 15:08:12 +000067void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000068 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000069 BufferStart = BufStart;
70 BufferPtr = BufPtr;
71 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattnerf76b9202009-01-17 06:55:17 +000073 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000076
Eric Christopher7f36a792011-04-09 00:01:04 +000077 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000082 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000083 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000084 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
85 .Default(0);
86
87 // Skip the BOM.
88 BufferPtr += BOMLength;
89 }
90
Chris Lattnerf76b9202009-01-17 06:55:17 +000091 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +000092 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +000093
Chris Lattnerf76b9202009-01-17 06:55:17 +000094 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +000096 IsAtPhysicalStartOfLine = true;
97
98 HasLeadingSpace = false;
99 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattnerf76b9202009-01-17 06:55:17 +0000101 // We are not after parsing a #.
102 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Chris Lattnerf76b9202009-01-17 06:55:17 +0000104 // We are not after parsing #include.
105 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattnerf76b9202009-01-17 06:55:17 +0000107 // We are not in raw mode. Raw mode disables diagnostics and interpretation
108 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
109 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
110 // or otherwise skipping over tokens.
111 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattnerf76b9202009-01-17 06:55:17 +0000113 // Default to not keeping comments.
114 ExtendedTokenMode = 0;
115}
116
Chris Lattner5965a282009-01-17 07:56:59 +0000117/// Lexer constructor - Create a new lexer object for the specified buffer
118/// with the specified preprocessor managing the lexing process. This lexer
119/// assumes that the associated file buffer and Preprocessor objects will
120/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000121Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Chris Lattnerc8090892009-01-17 08:03:42 +0000122 : PreprocessorLexer(&PP, FID),
123 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000124 LangOpts(PP.getLangOpts()) {
Mike Stump11289f42009-09-09 15:08:12 +0000125
Chris Lattner5965a282009-01-17 07:56:59 +0000126 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
127 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000128
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000129 resetExtendedTokenMode();
130}
131
132void Lexer::resetExtendedTokenMode() {
133 assert(PP && "Cannot reset token mode without a preprocessor");
134 if (LangOpts.TraditionalCPP)
135 SetKeepWhitespaceMode(true);
136 else
137 SetCommentRetentionState(PP->getCommentRetentionState());
Chris Lattner5965a282009-01-17 07:56:59 +0000138}
Chris Lattner4894f482007-10-07 08:47:24 +0000139
Chris Lattner02b436a2007-10-17 20:41:00 +0000140/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000141/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000142/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000143Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000144 const char *BufStart, const char *BufPtr, const char *BufEnd)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000145 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000146
Chris Lattnerf76b9202009-01-17 06:55:17 +0000147 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000148
Chris Lattner02b436a2007-10-17 20:41:00 +0000149 // We *are* in raw mode.
150 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000151}
152
Chris Lattner08354fe2009-01-17 07:35:14 +0000153/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000154/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000155/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000156Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000157 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000158 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
159 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000160
Chris Lattner757169b2009-01-17 08:27:52 +0000161/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
162/// _Pragma expansion. This has a variety of magic semantics that this method
163/// sets up. It returns a new'd Lexer that must be delete'd when done.
164///
165/// On entrance to this routine, TokStartLoc is a macro location which has a
166/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000167/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000168/// "expanded from".
169///
Alp Toker7755aff2014-05-18 18:37:59 +0000170/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000171/// normal lexer that remaps tokens as they fly by. This would require making
172/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
173/// interface that could handle this stuff. This would pull GetMappedTokenLoc
174/// out of the critical path of the lexer!
175///
Mike Stump11289f42009-09-09 15:08:12 +0000176Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000177 SourceLocation ExpansionLocStart,
178 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000179 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000180 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000181
182 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000183 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000184 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
185 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner757169b2009-01-17 08:27:52 +0000187 // Now that the lexer is created, change the start/end locations so that we
188 // just lex the subsection of the file that we want. This is lexing from a
189 // scratch buffer.
190 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000191
Chris Lattner757169b2009-01-17 08:27:52 +0000192 L->BufferPtr = StrData;
193 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000194 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000195
196 // Set the SourceLocation with the remapping information. This ensures that
197 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000198 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
199 ExpansionLocStart,
200 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000201
Chris Lattner757169b2009-01-17 08:27:52 +0000202 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000203 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000204 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000205
Chris Lattner757169b2009-01-17 08:27:52 +0000206 // This lexer really is for _Pragma.
207 L->Is_PragmaLexer = true;
208 return L;
209}
210
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000211/// Stringify - Convert the specified string into a C string, with surrounding
212/// ""'s, and with escaped \ and " characters.
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000213std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000214 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000215 char Quote = Charify ? '\'' : '"';
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000216 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
Chris Lattnerecc39e92006-07-15 05:23:31 +0000217 if (Result[i] == '\\' || Result[i] == Quote) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000218 Result.insert(Result.begin()+i, '\\');
219 ++i; ++e;
220 }
221 }
Chris Lattnerecc39e92006-07-15 05:23:31 +0000222 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000223}
224
Chris Lattner4c4a2452007-07-24 06:57:14 +0000225/// Stringify - Convert the specified string into a C string by escaping '\'
226/// and " characters. This does not add surrounding ""'s to the string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000227void Lexer::Stringify(SmallVectorImpl<char> &Str) {
Chris Lattner4c4a2452007-07-24 06:57:14 +0000228 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
229 if (Str[i] == '\\' || Str[i] == '"') {
230 Str.insert(Str.begin()+i, '\\');
231 ++i; ++e;
232 }
233 }
234}
235
Chris Lattner39720112010-11-17 07:26:20 +0000236//===----------------------------------------------------------------------===//
237// Token Spelling
238//===----------------------------------------------------------------------===//
239
Richard Smith9a67f472012-11-28 07:29:00 +0000240/// \brief Slow case of getSpelling. Extract the characters comprising the
241/// spelling of this token from the provided input buffer.
242static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
243 const LangOptions &LangOpts, char *Spelling) {
244 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
245
246 size_t Length = 0;
247 const char *BufEnd = BufPtr + Tok.getLength();
248
Craig Toppera6324c92015-10-22 15:35:21 +0000249 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000250 // Munch the encoding-prefix and opening double-quote.
251 while (BufPtr < BufEnd) {
252 unsigned Size;
253 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
254 BufPtr += Size;
255
256 if (Spelling[Length - 1] == '"')
257 break;
258 }
259
260 // Raw string literals need special handling; trigraph expansion and line
261 // splicing do not occur within their d-char-sequence nor within their
262 // r-char-sequence.
263 if (Length >= 2 &&
264 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
265 // Search backwards from the end of the token to find the matching closing
266 // quote.
267 const char *RawEnd = BufEnd;
268 do --RawEnd; while (*RawEnd != '"');
269 size_t RawLength = RawEnd - BufPtr + 1;
270
271 // Everything between the quotes is included verbatim in the spelling.
272 memcpy(Spelling + Length, BufPtr, RawLength);
273 Length += RawLength;
274 BufPtr += RawLength;
275
276 // The rest of the token is lexed normally.
277 }
278 }
279
280 while (BufPtr < BufEnd) {
281 unsigned Size;
282 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
283 BufPtr += Size;
284 }
285
286 assert(Length < Tok.getLength() &&
287 "NeedsCleaning flag set on token that didn't need cleaning!");
288 return Length;
289}
290
Chris Lattner39720112010-11-17 07:26:20 +0000291/// getSpelling() - Return the 'spelling' of this token. The spelling of a
292/// token are the characters used to represent the token in the source file
293/// after trigraph expansion and escaped-newline folding. In particular, this
294/// wants to get the true, uncanonicalized, spelling of things like digraphs
295/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000296StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000297 SmallVectorImpl<char> &buffer,
298 const SourceManager &SM,
299 const LangOptions &options,
300 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000301 // Break down the source location.
302 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
303
304 // Try to the load the file buffer.
305 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000307 if (invalidTemp) {
308 if (invalid) *invalid = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000309 return StringRef();
John McCall462c0552011-03-08 07:59:04 +0000310 }
311
312 const char *tokenBegin = file.data() + locInfo.second;
313
314 // Lex from the start of the given location.
315 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
316 file.begin(), tokenBegin, file.end());
317 Token token;
318 lexer.LexFromRawLexer(token);
319
320 unsigned length = token.getLength();
321
322 // Common case: no need for cleaning.
323 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000325
Richard Smith9a67f472012-11-28 07:29:00 +0000326 // Hard case, we need to relex the characters into the string.
327 buffer.resize(length);
328 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000330}
331
332/// getSpelling() - Return the 'spelling' of this token. The spelling of a
333/// token are the characters used to represent the token in the source file
334/// after trigraph expansion and escaped-newline folding. In particular, this
335/// wants to get the true, uncanonicalized, spelling of things like digraphs
336/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000337std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000339 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000340
Chris Lattner39720112010-11-17 07:26:20 +0000341 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000342 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000343 &CharDataInvalid);
344 if (Invalid)
345 *Invalid = CharDataInvalid;
346 if (CharDataInvalid)
347 return std::string();
Richard Smith9a67f472012-11-28 07:29:00 +0000348
349 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000350 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000351 return std::string(TokStart, TokStart + Tok.getLength());
352
Chris Lattner39720112010-11-17 07:26:20 +0000353 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000354 Result.resize(Tok.getLength());
355 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000356 return Result;
357}
358
359/// getSpelling - This method is used to get the spelling of a token into a
360/// preallocated buffer, instead of as an std::string. The caller is required
361/// to allocate enough space for the token, which is guaranteed to be at least
362/// Tok.getLength() bytes long. The actual length of the token is returned.
363///
364/// Note that this method may do two possible things: it may either fill in
365/// the buffer specified with characters, or it may *change the input pointer*
366/// to point to a constant buffer with the data already in it (avoiding a
367/// copy). The caller is not allowed to modify the returned buffer pointer
368/// if an internal buffer is returned.
369unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
370 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000371 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000372 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000373
Craig Topperd2d442c2014-05-17 23:10:59 +0000374 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000375 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
376 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000377 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000378 else if (!Tok.hasUCN()) {
379 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
380 // Just return the string from the identifier table, which is very quick.
381 Buffer = II->getNameStart();
382 return II->getLength();
383 }
Chris Lattner39720112010-11-17 07:26:20 +0000384 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000385
386 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000387 if (Tok.isLiteral())
388 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000389
Craig Topperd2d442c2014-05-17 23:10:59 +0000390 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000391 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000392 bool CharDataInvalid = false;
393 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
394 if (Invalid)
395 *Invalid = CharDataInvalid;
396 if (CharDataInvalid) {
397 Buffer = "";
398 return 0;
399 }
400 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000401
Chris Lattner39720112010-11-17 07:26:20 +0000402 // If this token contains nothing interesting, return it directly.
403 if (!Tok.needsCleaning()) {
404 Buffer = TokStart;
405 return Tok.getLength();
406 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000407
Chris Lattner39720112010-11-17 07:26:20 +0000408 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000409 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000410}
411
Chris Lattner8e129c22007-10-17 21:18:47 +0000412/// MeasureTokenLength - Relex the token at the specified location and return
413/// its length in bytes in the input file. If the token needs cleaning (e.g.
414/// includes a trigraph or an escaped newline) then this count includes bytes
415/// that are part of that.
416unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000417 const SourceManager &SM,
418 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000419 Token TheTok;
420 if (getRawToken(Loc, TheTok, SM, LangOpts))
421 return 0;
422 return TheTok.getLength();
423}
424
425/// \brief Relex the token at the specified location.
426/// \returns true if there was a failure, false on success.
427bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
428 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000429 const LangOptions &LangOpts,
430 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000431 // TODO: this could be special cased for common tokens like identifiers, ')',
432 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000433 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000434 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
435 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000436
437 // If this comes from a macro expansion, we really do want the macro name, not
438 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000439 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000440 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000441 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000442 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000443 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000444 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000445
446 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000447
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000448 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000449 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000450
Chris Lattner8e129c22007-10-17 21:18:47 +0000451 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000452 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
453 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000454 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000455 TheLexer.LexFromRawLexer(Result);
456 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000457}
458
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000459/// Returns the pointer that points to the beginning of line that contains
460/// the given offset, or null if the offset if invalid.
461static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
462 const char *BufStart = Buffer.data();
463 if (Offset >= Buffer.size())
464 return nullptr;
465 const char *StrData = BufStart + Offset;
466
467 if (StrData[0] == '\n' || StrData[0] == '\r')
468 return StrData;
469
470 const char *LexStart = StrData;
471 while (LexStart != BufStart) {
472 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
473 ++LexStart;
474 break;
475 }
476
477 --LexStart;
478 }
479 return LexStart;
480}
481
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000482static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
483 const SourceManager &SM,
484 const LangOptions &LangOpts) {
485 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000486 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000487 if (LocInfo.first.isInvalid())
488 return Loc;
489
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000490 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000491 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000492 if (Invalid)
493 return Loc;
494
495 // Back up from the current location until we hit the beginning of a line
496 // (or the buffer). We'll relex from that point.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000497 const char *StrData = Buffer.data() + LocInfo.second;
498 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
499 if (!LexStart || LexStart == StrData)
Douglas Gregor86af9842011-01-31 22:42:36 +0000500 return Loc;
501
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000502 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000503 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000504 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
505 Buffer.end());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000506 TheLexer.SetCommentRetentionState(true);
507
508 // Lex tokens until we find the token that contains the source location.
509 Token TheTok;
510 do {
511 TheLexer.LexFromRawLexer(TheTok);
512
513 if (TheLexer.getBufferLocation() > StrData) {
514 // Lexing this token has taken the lexer past the source location we're
515 // looking for. If the current token encompasses our source location,
516 // return the beginning of that token.
517 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
518 return TheTok.getLocation();
519
520 // We ended up skipping over the source location entirely, which means
521 // that it points into whitespace. We're done here.
522 break;
523 }
524 } while (TheTok.getKind() != tok::eof);
525
526 // We've passed our source location; just return the original source location.
527 return Loc;
528}
529
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000530SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
531 const SourceManager &SM,
532 const LangOptions &LangOpts) {
533 if (Loc.isFileID())
534 return getBeginningOfFileToken(Loc, SM, LangOpts);
535
536 if (!SM.isMacroArgExpansion(Loc))
537 return Loc;
538
539 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
540 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
541 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000542 std::pair<FileID, unsigned> BeginFileLocInfo
543 = SM.getDecomposedLoc(BeginFileLoc);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000544 assert(FileLocInfo.first == BeginFileLocInfo.first &&
545 FileLocInfo.second >= BeginFileLocInfo.second);
Chandler Carruth5b15a9b2012-01-15 09:03:45 +0000546 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000547}
548
Douglas Gregoraf82e352010-07-20 20:18:03 +0000549namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000550
Douglas Gregoraf82e352010-07-20 20:18:03 +0000551 enum PreambleDirectiveKind {
552 PDK_Skipped,
553 PDK_StartIf,
554 PDK_EndIf,
555 PDK_Unknown
556 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000557
558} // end anonymous namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000559
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000560std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
David Blaikie3d95d852014-08-11 22:08:06 +0000561 const LangOptions &LangOpts,
562 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000563 // Create a lexer starting at the beginning of the file. Note that we use a
564 // "fake" file source location at offset 1 so that the lexer will track our
565 // position within the file.
566 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000567 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000568 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
569 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000570 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000571
572 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
573 SourceLocation StartLoc = TheLexer.getSourceLocation();
574
Douglas Gregoraf82e352010-07-20 20:18:03 +0000575 bool InPreprocessorDirective = false;
576 Token TheTok;
577 Token IfStartTok;
578 unsigned IfCount = 0;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000579 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000580
581 unsigned MaxLineOffset = 0;
582 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000583 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000584 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000585 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000586 char ch = *CurPtr++;
587 if (ch == '\n') {
588 ++CurLine;
589 if (CurLine == MaxLines)
590 break;
591 }
592 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000593 if (CurPtr != Buffer.end())
594 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000595 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000596
Douglas Gregoraf82e352010-07-20 20:18:03 +0000597 do {
598 TheLexer.LexFromRawLexer(TheTok);
599
600 if (InPreprocessorDirective) {
601 // If we've hit the end of the file, we're done.
602 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000603 break;
604 }
605
606 // If we haven't hit the end of the preprocessor directive, skip this
607 // token.
608 if (!TheTok.isAtStartOfLine())
609 continue;
610
611 // We've passed the end of the preprocessor directive, and will look
612 // at this token again below.
613 InPreprocessorDirective = false;
614 }
615
Douglas Gregor028d3e42010-08-09 20:45:32 +0000616 // Keep track of the # of lines in the preamble.
617 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000618 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000619
620 // If we were asked to limit the number of lines in the preamble,
621 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000622 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000623 break;
624 }
625
Douglas Gregoraf82e352010-07-20 20:18:03 +0000626 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000627 if (TheTok.getKind() == tok::comment) {
628 if (ActiveCommentLoc.isInvalid())
629 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000630 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000631 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000632
633 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
634 // This is the start of a preprocessor directive.
635 Token HashTok = TheTok;
636 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000637 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000638
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000639 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000640 // we don't have an identifier table available. Instead, just look at
641 // the raw identifier to recognize and categorize preprocessor directives.
642 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000643 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000644 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000645 PreambleDirectiveKind PDK
646 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
647 .Case("include", PDK_Skipped)
648 .Case("__include_macros", PDK_Skipped)
649 .Case("define", PDK_Skipped)
650 .Case("undef", PDK_Skipped)
651 .Case("line", PDK_Skipped)
652 .Case("error", PDK_Skipped)
653 .Case("pragma", PDK_Skipped)
654 .Case("import", PDK_Skipped)
655 .Case("include_next", PDK_Skipped)
656 .Case("warning", PDK_Skipped)
657 .Case("ident", PDK_Skipped)
658 .Case("sccs", PDK_Skipped)
659 .Case("assert", PDK_Skipped)
660 .Case("unassert", PDK_Skipped)
661 .Case("if", PDK_StartIf)
662 .Case("ifdef", PDK_StartIf)
663 .Case("ifndef", PDK_StartIf)
664 .Case("elif", PDK_Skipped)
665 .Case("else", PDK_Skipped)
666 .Case("endif", PDK_EndIf)
667 .Default(PDK_Unknown);
668
669 switch (PDK) {
670 case PDK_Skipped:
671 continue;
672
673 case PDK_StartIf:
674 if (IfCount == 0)
675 IfStartTok = HashTok;
676
677 ++IfCount;
678 continue;
679
680 case PDK_EndIf:
681 // Mismatched #endif. The preamble ends here.
682 if (IfCount == 0)
683 break;
684
685 --IfCount;
686 continue;
687
688 case PDK_Unknown:
689 // We don't know what this directive is; stop at the '#'.
690 break;
691 }
692 }
693
694 // We only end up here if we didn't recognize the preprocessor
695 // directive or it was one that can't occur in the preamble at this
696 // point. Roll back the current token to the location of the '#'.
697 InPreprocessorDirective = false;
698 TheTok = HashTok;
699 }
700
Douglas Gregor028d3e42010-08-09 20:45:32 +0000701 // We hit a token that we don't recognize as being in the
702 // "preprocessing only" part of the file, so we're no longer in
703 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000704 break;
705 } while (true);
706
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000707 SourceLocation End;
708 if (IfCount)
709 End = IfStartTok.getLocation();
710 else if (ActiveCommentLoc.isValid())
711 End = ActiveCommentLoc; // don't truncate a decl comment.
712 else
713 End = TheTok.getLocation();
714
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000715 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
716 IfCount? IfStartTok.isAtStartOfLine()
717 : TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000718}
719
Chris Lattner2a6ee912010-11-17 07:05:50 +0000720/// AdvanceToTokenCharacter - Given a location that specifies the start of a
721/// token, return a new location that specifies a character within the token.
722SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
723 unsigned CharNo,
724 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000725 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000726 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000727 // character is. This needs to take into consideration newlines and
728 // trigraphs.
729 bool Invalid = false;
730 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
731
732 // If they request the first char of the token, we're trivially done.
733 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
734 return TokStart;
735
736 unsigned PhysOffset = 0;
737
738 // The usual case is that tokens don't contain anything interesting. Skip
739 // over the uninteresting characters. If a token only consists of simple
740 // chars, this method is extremely fast.
741 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
742 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000743 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000744 ++TokPtr;
745 --CharNo;
746 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000747 }
748
749 // If we have a character that may be a trigraph or escaped newline, use a
750 // lexer to parse it correctly.
751 for (; CharNo; --CharNo) {
752 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000753 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000754 TokPtr += Size;
755 PhysOffset += Size;
756 }
757
758 // Final detail: if we end up on an escaped newline, we want to return the
759 // location of the actual byte of the token. For example foo\<newline>bar
760 // advanced by 3 should return the location of b, not of \\. One compounding
761 // detail of this is that the escape may be made by a trigraph.
762 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
763 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
764
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000765 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000766}
767
768/// \brief Computes the source location just past the end of the
769/// token at this source location.
770///
771/// This routine can be used to produce a source location that
772/// points just past the end of the token referenced by \p Loc, and
773/// is generally used when a diagnostic needs to point just after a
774/// token where it expected something different that it received. If
775/// the returned source location would not be meaningful (e.g., if
776/// it points into a macro), this routine returns an invalid
777/// source location.
778///
779/// \param Offset an offset from the end of the token, where the source
780/// location should refer to. The default offset (0) produces a source
781/// location pointing just past the end of the token; an offset of 1 produces
782/// a source location pointing to the last character in the token, etc.
783SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
784 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000786 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000787 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000788
789 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000790 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000791 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000792 }
793
David Blaikiebbafb8a2012-03-11 07:00:24 +0000794 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000795 if (Len > Offset)
796 Len = Len - Offset;
797 else
798 return Loc;
799
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000800 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000801}
802
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000803/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000804/// token of the macro expansion.
805bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000806 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000807 const LangOptions &LangOpts,
808 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000809 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
810
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000811 SourceLocation expansionLoc;
812 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
813 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000814
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000815 if (expansionLoc.isFileID()) {
816 // No other macro expansions, this is the first.
817 if (MacroBegin)
818 *MacroBegin = expansionLoc;
819 return true;
820 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000821
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000822 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000823}
824
825/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000826/// token of the macro expansion.
827bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000828 const SourceManager &SM,
829 const LangOptions &LangOpts,
830 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000831 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
832
833 SourceLocation spellLoc = SM.getSpellingLoc(loc);
834 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
835 if (tokLen == 0)
836 return false;
837
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000838 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
839 SourceLocation expansionLoc;
840 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
841 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000842
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000843 if (expansionLoc.isFileID()) {
844 // No other macro expansions.
845 if (MacroEnd)
846 *MacroEnd = expansionLoc;
847 return true;
848 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000849
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000850 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000851}
852
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000853static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000854 const SourceManager &SM,
855 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000856 SourceLocation Begin = Range.getBegin();
857 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000858 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000859 if (Range.isTokenRange()) {
860 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
861 if (End.isInvalid())
862 return CharSourceRange();
863 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000864
865 // Break down the source locations.
866 FileID FID;
867 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000868 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000869 if (FID.isInvalid())
870 return CharSourceRange();
871
872 unsigned EndOffs;
873 if (!SM.isInFileID(End, FID, &EndOffs) ||
874 BeginOffs > EndOffs)
875 return CharSourceRange();
876
877 return CharSourceRange::getCharRange(Begin, End);
878}
879
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000880CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000881 const SourceManager &SM,
882 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000883 SourceLocation Begin = Range.getBegin();
884 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000885 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000886 return CharSourceRange();
887
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000888 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000890
891 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000892 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
893 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000894 Range.setBegin(Begin);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000896 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000897
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000898 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000899 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
900 &End)) ||
901 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
902 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000903 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000904 Range.setEnd(End);
905 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000906 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000907
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000908 assert(Begin.isMacroID() && End.isMacroID());
909 SourceLocation MacroBegin, MacroEnd;
910 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000911 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
912 &MacroEnd)) ||
913 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
914 &MacroEnd)))) {
915 Range.setBegin(MacroBegin);
916 Range.setEnd(MacroEnd);
917 return makeRangeFromFileLocs(Range, SM, LangOpts);
918 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000919
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000920 bool Invalid = false;
921 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
922 &Invalid);
923 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000924 return CharSourceRange();
925
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000926 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
927 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
928 &Invalid);
929 if (Invalid)
930 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000931
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000932 if (EndEntry.getExpansion().isMacroArgExpansion() &&
933 BeginEntry.getExpansion().getExpansionLocStart() ==
934 EndEntry.getExpansion().getExpansionLocStart()) {
935 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
936 Range.setEnd(SM.getImmediateSpellingLoc(End));
937 return makeFileCharRange(Range, SM, LangOpts);
938 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000939 }
940
941 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000942}
943
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000944StringRef Lexer::getSourceText(CharSourceRange Range,
945 const SourceManager &SM,
946 const LangOptions &LangOpts,
947 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000948 Range = makeFileCharRange(Range, SM, LangOpts);
949 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000950 if (Invalid) *Invalid = true;
951 return StringRef();
952 }
953
954 // Break down the source location.
955 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
956 if (beginInfo.first.isInvalid()) {
957 if (Invalid) *Invalid = true;
958 return StringRef();
959 }
960
961 unsigned EndOffs;
962 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
963 beginInfo.second > EndOffs) {
964 if (Invalid) *Invalid = true;
965 return StringRef();
966 }
967
968 // Try to the load the file buffer.
969 bool invalidTemp = false;
970 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
971 if (invalidTemp) {
972 if (Invalid) *Invalid = true;
973 return StringRef();
974 }
975
976 if (Invalid) *Invalid = false;
977 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
978}
979
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000980StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
981 const SourceManager &SM,
982 const LangOptions &LangOpts) {
983 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000984
985 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000986 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000987 FileID FID = SM.getFileID(Loc);
988 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
989 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
990 Loc = Expansion.getExpansionLocStart();
991 if (!Expansion.isMacroArgExpansion())
992 break;
993
994 // For macro arguments we need to check that the argument did not come
995 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
996
997 // Loc points to the argument id of the macro definition, move to the
998 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000999 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001000 SourceLocation SpellLoc = Expansion.getSpellingLoc();
1001 if (SpellLoc.isFileID())
1002 break; // No inner macro.
1003
1004 // If spelling location resides in the same FileID as macro expansion
1005 // location, it means there is no inner macro.
1006 FileID MacroFID = SM.getFileID(Loc);
1007 if (SM.isInFileID(SpellLoc, MacroFID))
1008 break;
1009
1010 // Argument came from inner macro.
1011 Loc = SpellLoc;
1012 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001013
1014 // Find the spelling location of the start of the non-argument expansion
1015 // range. This is where the macro name was spelled in order to begin
1016 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001017 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001018
1019 // Dig out the buffer where the macro name was spelled and the extents of the
1020 // name so that we can render it into the expansion note.
1021 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1022 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1023 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1024 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1025}
1026
Richard Trieu3a5c9582016-01-26 02:51:55 +00001027StringRef Lexer::getImmediateMacroNameForDiagnostics(
1028 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1029 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1030 // Walk past macro argument expanions.
1031 while (SM.isMacroArgExpansion(Loc))
1032 Loc = SM.getImmediateExpansionRange(Loc).first;
1033
1034 // If the macro's spelling has no FileID, then it's actually a token paste
1035 // or stringization (or similar) and not a macro at all.
1036 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1037 return StringRef();
1038
1039 // Find the spelling location of the start of the non-argument expansion
1040 // range. This is where the macro name was spelled in order to begin
1041 // expanding this macro.
1042 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1043
1044 // Dig out the buffer where the macro name was spelled and the extents of the
1045 // name so that we can render it into the expansion note.
1046 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1047 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1048 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1049 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1050}
1051
Jordan Rose288c4212012-06-07 01:10:31 +00001052bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001053 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001054}
1055
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001056StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1057 const SourceManager &SM) {
1058 if (Loc.isInvalid() || Loc.isMacroID())
1059 return "";
1060 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1061 if (LocInfo.first.isInvalid())
1062 return "";
1063 bool Invalid = false;
1064 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1065 if (Invalid)
1066 return "";
1067 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1068 if (!Line)
1069 return "";
1070 StringRef Rest = Buffer.substr(Line - Buffer.data());
1071 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1072 return NumWhitespaceChars == StringRef::npos
1073 ? ""
1074 : Rest.take_front(NumWhitespaceChars);
1075}
1076
Chris Lattner22eb9722006-06-18 05:43:12 +00001077//===----------------------------------------------------------------------===//
1078// Diagnostics forwarding code.
1079//===----------------------------------------------------------------------===//
1080
Chris Lattner619c1742007-07-22 18:38:25 +00001081/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001082/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001083/// This is currently only used for _Pragma implementation, so it is the slow
1084/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001085static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1086 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001087static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1088 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001089 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001090 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001091
Chris Lattner619c1742007-07-22 18:38:25 +00001092 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001093 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001094 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001095 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001096
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001097 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001098 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001099 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001100 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner9dc9c202009-02-15 20:52:18 +00001102 // Figure out the expansion loc range, which is the range covered by the
1103 // original _Pragma(...) sequence.
1104 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001105 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chandler Carruth115b0772011-07-26 03:03:05 +00001107 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001108}
1109
Chris Lattner22eb9722006-06-18 05:43:12 +00001110/// getSourceLocation - Return a source location identifier for the specified
1111/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001112SourceLocation Lexer::getSourceLocation(const char *Loc,
1113 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001114 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001115 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001116
1117 // In the normal case, we're just lexing from a simple file buffer, return
1118 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001119 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001120 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001121 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001122
Chris Lattnerd32480d2009-01-17 06:22:33 +00001123 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1124 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001125 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001126 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001127}
1128
Chris Lattner22eb9722006-06-18 05:43:12 +00001129/// Diag - Forwarding function for diagnostics. This translate a source
1130/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001131DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001132 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001133}
1134
1135//===----------------------------------------------------------------------===//
1136// Trigraph and Escaped Newline Handling Code.
1137//===----------------------------------------------------------------------===//
1138
1139/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1140/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1141static char GetTrigraphCharForLetter(char Letter) {
1142 switch (Letter) {
1143 default: return 0;
1144 case '=': return '#';
1145 case ')': return ']';
1146 case '(': return '[';
1147 case '!': return '|';
1148 case '\'': return '^';
1149 case '>': return '}';
1150 case '/': return '\\';
1151 case '<': return '{';
1152 case '-': return '~';
1153 }
1154}
1155
1156/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1157/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1158/// return the result character. Finally, emit a warning about trigraph use
1159/// whether trigraphs are enabled or not.
1160static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1161 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001162 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001163
David Blaikiebbafb8a2012-03-11 07:00:24 +00001164 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001165 if (!L->isLexingRawMode())
1166 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001167 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattner6d27a162008-11-22 02:02:22 +00001170 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001171 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001172 return Res;
1173}
1174
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001175/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1176/// 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 +00001177/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001178unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1179 unsigned Size = 0;
1180 while (isWhitespace(Ptr[Size])) {
1181 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001183 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1184 continue;
1185
1186 // If this is a \r\n or \n\r, skip the other half.
1187 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1188 Ptr[Size-1] != Ptr[Size])
1189 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001190
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001191 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001192 }
1193
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001194 // Not an escaped newline, must be a \t or something else.
1195 return 0;
1196}
1197
Chris Lattner38b2cde2009-04-18 22:27:02 +00001198/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1199/// them), skip over them and return the first non-escaped-newline found,
1200/// otherwise return P.
1201const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001202 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001203 const char *AfterEscape;
1204 if (*P == '\\') {
1205 AfterEscape = P+1;
1206 } else if (*P == '?') {
1207 // If not a trigraph for escape, bail out.
1208 if (P[1] != '?' || P[2] != '/')
1209 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001210 // FIXME: Take LangOpts into account; the language might not
1211 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001212 AfterEscape = P+3;
1213 } else {
1214 return P;
1215 }
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattner38b2cde2009-04-18 22:27:02 +00001217 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1218 if (NewLineSize == 0) return P;
1219 P = AfterEscape+NewLineSize;
1220 }
1221}
1222
Anna Zaks59a3c802011-07-27 21:43:43 +00001223/// \brief Checks that the given token is the first token that occurs after the
1224/// given location (this excludes comments and whitespace). Returns the location
1225/// immediately after the specified token. If the token is not found or the
1226/// location is inside a macro, the returned source location will be invalid.
1227SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1228 tok::TokenKind TKind,
1229 const SourceManager &SM,
1230 const LangOptions &LangOpts,
1231 bool SkipTrailingWhitespaceAndNewLine) {
1232 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001233 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001234 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001235 }
1236 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1237
1238 // Break down the source location.
1239 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1240
1241 // Try to load the file buffer.
1242 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001243 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001244 if (InvalidTemp)
1245 return SourceLocation();
1246
1247 const char *TokenBegin = File.data() + LocInfo.second;
1248
1249 // Lex from the start of the given location.
1250 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1251 TokenBegin, File.end());
1252 // Find the token.
1253 Token Tok;
1254 lexer.LexFromRawLexer(Tok);
1255 if (Tok.isNot(TKind))
1256 return SourceLocation();
1257 SourceLocation TokenLoc = Tok.getLocation();
1258
1259 // Calculate how much whitespace needs to be skipped if any.
1260 unsigned NumWhitespaceChars = 0;
1261 if (SkipTrailingWhitespaceAndNewLine) {
1262 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1263 Tok.getLength();
1264 unsigned char C = *TokenEnd;
1265 while (isHorizontalWhitespace(C)) {
1266 C = *(++TokenEnd);
1267 NumWhitespaceChars++;
1268 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001269
1270 // Skip \r, \n, \r\n, or \n\r
1271 if (C == '\n' || C == '\r') {
1272 char PrevC = C;
1273 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001274 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001275 if ((C == '\n' || C == '\r') && C != PrevC)
1276 NumWhitespaceChars++;
1277 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001278 }
1279
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001280 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001281}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001282
Chris Lattner22eb9722006-06-18 05:43:12 +00001283/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1284/// get its size, and return it. This is tricky in several cases:
1285/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1286/// then either return the trigraph (skipping 3 chars) or the '?',
1287/// depending on whether trigraphs are enabled or not.
1288/// 2. If this is an escaped newline (potentially with whitespace between
1289/// the backslash and newline), implicitly skip the newline and return
1290/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001291///
1292/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1293/// know that we can accumulate into Size, and that we have already incremented
1294/// Ptr by Size bytes.
1295///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001296/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1297/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001298///
1299char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001300 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001301 // If we have a slash, look for an escaped newline.
1302 if (Ptr[0] == '\\') {
1303 ++Size;
1304 ++Ptr;
1305Slash:
1306 // Common case, backslash-char where the char is not whitespace.
1307 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattnerc1835952009-06-23 05:15:06 +00001309 // See if we have optional whitespace characters between the slash and
1310 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001311 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1312 // Remember that this token needs to be cleaned.
1313 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001314
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001315 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001316 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001317 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001318
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001319 // Found backslash<whitespace><newline>. Parse the char after it.
1320 Size += EscapedNewLineSize;
1321 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001322
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001323 // Use slow version to accumulate a correct size field.
1324 return getCharAndSizeSlow(Ptr, Size, Tok);
1325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Chris Lattner22eb9722006-06-18 05:43:12 +00001327 // Otherwise, this is not an escaped newline, just return the slash.
1328 return '\\';
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattner22eb9722006-06-18 05:43:12 +00001331 // If this is a trigraph, process it.
1332 if (Ptr[0] == '?' && Ptr[1] == '?') {
1333 // If this is actually a legal trigraph (not something like "??x"), emit
1334 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001335 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001336 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001337 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001338
1339 Ptr += 3;
1340 Size += 3;
1341 if (C == '\\') goto Slash;
1342 return C;
1343 }
1344 }
Mike Stump11289f42009-09-09 15:08:12 +00001345
Chris Lattner22eb9722006-06-18 05:43:12 +00001346 // If this is neither, return a single character.
1347 ++Size;
1348 return *Ptr;
1349}
1350
1351/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1352/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1353/// and that we have already incremented Ptr by Size bytes.
1354///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001355/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1356/// be updated to match.
1357char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001358 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 // If we have a slash, look for an escaped newline.
1360 if (Ptr[0] == '\\') {
1361 ++Size;
1362 ++Ptr;
1363Slash:
1364 // Common case, backslash-char where the char is not whitespace.
1365 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattner22eb9722006-06-18 05:43:12 +00001367 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001368 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1369 // Found backslash<whitespace><newline>. Parse the char after it.
1370 Size += EscapedNewLineSize;
1371 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001373 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001374 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001375 }
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattner22eb9722006-06-18 05:43:12 +00001377 // Otherwise, this is not an escaped newline, just return the slash.
1378 return '\\';
1379 }
Mike Stump11289f42009-09-09 15:08:12 +00001380
Chris Lattner22eb9722006-06-18 05:43:12 +00001381 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001382 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001383 // If this is actually a legal trigraph (not something like "??x"), return
1384 // it.
1385 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1386 Ptr += 3;
1387 Size += 3;
1388 if (C == '\\') goto Slash;
1389 return C;
1390 }
1391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner22eb9722006-06-18 05:43:12 +00001393 // If this is neither, return a single character.
1394 ++Size;
1395 return *Ptr;
1396}
1397
Chris Lattner22eb9722006-06-18 05:43:12 +00001398//===----------------------------------------------------------------------===//
1399// Helper methods for lexing.
1400//===----------------------------------------------------------------------===//
1401
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001402/// \brief Routine that indiscriminately skips bytes in the source file.
1403void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1404 BufferPtr += Bytes;
1405 if (BufferPtr > BufferEnd)
1406 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001407 // FIXME: What exactly does the StartOfLine bit mean? There are two
1408 // possible meanings for the "start" of the line: the first token on the
1409 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001410 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001411 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001412}
1413
Jordan Rose58c61e02013-02-09 01:10:25 +00001414static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001415 if (LangOpts.AsmPreprocessor) {
1416 return false;
1417 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001418 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1419 C11AllowedIDCharRanges);
1420 return C11AllowedIDChars.contains(C);
1421 } else if (LangOpts.CPlusPlus) {
1422 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1423 CXX03AllowedIDCharRanges);
1424 return CXX03AllowedIDChars.contains(C);
1425 } else {
1426 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1427 C99AllowedIDCharRanges);
1428 return C99AllowedIDChars.contains(C);
1429 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001430}
1431
Jordan Rose58c61e02013-02-09 01:10:25 +00001432static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1433 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001434 if (LangOpts.AsmPreprocessor) {
1435 return false;
1436 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001437 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1438 C11DisallowedInitialIDCharRanges);
1439 return !C11DisallowedInitialIDChars.contains(C);
1440 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001441 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001442 } else {
1443 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1444 C99DisallowedInitialIDCharRanges);
1445 return !C99DisallowedInitialIDChars.contains(C);
1446 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001447}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001448
Jordan Rose58c61e02013-02-09 01:10:25 +00001449static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1450 const char *End) {
1451 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1452 L.getSourceLocation(End));
1453}
1454
1455static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1456 CharSourceRange Range, bool IsFirst) {
1457 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001458 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001459 enum {
1460 CannotAppearInIdentifier = 0,
1461 CannotStartIdentifier
1462 };
1463
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001464 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1465 C99AllowedIDCharRanges);
1466 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1467 C99DisallowedInitialIDCharRanges);
1468 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001469 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1470 << Range
1471 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001472 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001473 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1474 << Range
1475 << CannotStartIdentifier;
1476 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001477 }
1478
Jordan Rose58c61e02013-02-09 01:10:25 +00001479 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001480 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001481 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1482 CXX03AllowedIDCharRanges);
1483 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001484 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1485 << Range;
1486 }
1487 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001488}
1489
1490bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1491 Token &Result) {
1492 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001493 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001494 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1495 return false;
1496
1497 if (!isLexingRawMode())
1498 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1499 makeCharRange(*this, CurPtr, UCNPtr),
1500 /*IsFirst=*/false);
1501
1502 Result.setFlag(Token::HasUCN);
1503 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1504 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1505 CurPtr = UCNPtr;
1506 else
1507 while (CurPtr != UCNPtr)
1508 (void)getAndAdvanceChar(CurPtr, Result);
1509 return true;
1510}
1511
1512bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1513 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001514 llvm::UTF32 CodePoint;
1515 llvm::ConversionResult Result =
1516 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1517 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001518 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001519 llvm::strictConversion);
1520 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001521 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1522 return false;
1523
1524 if (!isLexingRawMode())
1525 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1526 makeCharRange(*this, CurPtr, UnicodePtr),
1527 /*IsFirst=*/false);
1528
1529 CurPtr = UnicodePtr;
1530 return true;
1531}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001532
Eli Friedman0834a4b2013-09-19 00:41:32 +00001533bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001534 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1535 unsigned Size;
1536 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001537 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001538 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001539
Chris Lattner22eb9722006-06-18 05:43:12 +00001540 --CurPtr; // Back up over the skipped character.
1541
1542 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1543 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001544 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001545 // TODO: Could merge these checks into an InfoTable flag to make the
1546 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001547 if (isASCII(C) && C != '\\' && C != '?' &&
1548 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001549FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001550 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001551 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1552 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001553
Chris Lattner0f1f5052006-07-20 04:16:23 +00001554 // If we are in raw mode, return this identifier raw. There is no need to
1555 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001556 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001557 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001558
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001559 // Fill in Result.IdentifierInfo and update the token kind,
1560 // looking up the identifier in the identifier table.
1561 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Chris Lattnerc5a00062006-06-18 16:41:01 +00001563 // Finally, now that we know we have an identifier, pass this off to the
1564 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001565 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001566 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001567
1568 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1569 && II->getPPKeywordID() == tok::pp_not_keyword
1570 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1571 // Return the code-completion token.
1572 Result.setKind(tok::code_completion);
1573 cutOffLexing();
1574 return true;
1575 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001576 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001577 }
Mike Stump11289f42009-09-09 15:08:12 +00001578
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chris Lattner22eb9722006-06-18 05:43:12 +00001581 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001582 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001583 if (C == '$') {
1584 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001585 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001586
Chris Lattner22eb9722006-06-18 05:43:12 +00001587 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001588 if (!isLexingRawMode())
1589 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001590 CurPtr = ConsumeChar(CurPtr, Size, Result);
1591 C = getCharAndSize(CurPtr, Size);
1592 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001593
Richard Smith8b7258b2014-02-17 21:52:30 +00001594 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001595 C = getCharAndSize(CurPtr, Size);
1596 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001597 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001598 C = getCharAndSize(CurPtr, Size);
1599 continue;
1600 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001601 goto FinishIdentifier;
1602 }
1603
1604 // Otherwise, this character is good, consume it.
1605 CurPtr = ConsumeChar(CurPtr, Size, Result);
1606
1607 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001608 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001609 CurPtr = ConsumeChar(CurPtr, Size, Result);
1610 C = getCharAndSize(CurPtr, Size);
1611 }
1612 }
1613}
1614
Douglas Gregor759ef232010-08-30 14:50:47 +00001615/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001616/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001617bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001618 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001619 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001620 if (C1 != '0')
1621 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001622 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001623 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001624}
Chris Lattner22eb9722006-06-18 05:43:12 +00001625
Nate Begeman5eee9332008-04-14 02:26:39 +00001626/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001627/// constant. From[-1] is the first character lexed. Return the end of the
1628/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001629bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001630 unsigned Size;
1631 char C = getCharAndSize(CurPtr, Size);
1632 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001633 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001634 CurPtr = ConsumeChar(CurPtr, Size, Result);
1635 PrevCh = C;
1636 C = getCharAndSize(CurPtr, Size);
1637 }
Mike Stump11289f42009-09-09 15:08:12 +00001638
Chris Lattner22eb9722006-06-18 05:43:12 +00001639 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001640 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1641 // If we are in Microsoft mode, don't continue if the constant is hex.
1642 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001643 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001644 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1645 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001646
1647 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001648 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001649 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001650 // not-quite-conforming extension. Only do so if this looks like it's
1651 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1652 bool IsHexFloat = true;
1653 if (!LangOpts.C99) {
1654 if (!isHexaLiteral(BufferPtr, LangOpts))
1655 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001656 else if (!getLangOpts().CPlusPlus1z &&
1657 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001658 IsHexFloat = false;
1659 }
1660 if (IsHexFloat)
1661 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
Richard Smithfde94852013-09-26 03:33:06 +00001664 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001665 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001666 unsigned NextSize;
1667 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001668 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001669 if (!isLexingRawMode())
1670 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1671 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001672 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001673 return LexNumericConstant(Result, CurPtr);
1674 }
1675 }
1676
Richard Smith8b7258b2014-02-17 21:52:30 +00001677 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1678 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1679 return LexNumericConstant(Result, CurPtr);
1680 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1681 return LexNumericConstant(Result, CurPtr);
1682
Chris Lattnerd01e2912006-06-18 16:22:51 +00001683 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001684 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001685 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001686 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001687 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001688}
1689
Richard Smithe18f0fa2012-03-05 04:02:15 +00001690/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001691/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001692const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1693 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001694 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001695
Richard Smith8b7258b2014-02-17 21:52:30 +00001696 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001697 unsigned Size;
1698 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001699 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001700
Richard Smith8b7258b2014-02-17 21:52:30 +00001701 if (!isIdentifierHead(C)) {
1702 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1703 Consumed = true;
1704 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1705 Consumed = true;
1706 else
1707 return CurPtr;
1708 }
1709
1710 if (!getLangOpts().CPlusPlus11) {
1711 if (!isLexingRawMode())
1712 Diag(CurPtr,
1713 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1714 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1715 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1716 return CurPtr;
1717 }
1718
1719 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1720 // that does not start with an underscore is ill-formed. As a conforming
1721 // extension, we treat all such suffixes as if they had whitespace before
1722 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1723 // likely to be a ud-suffix than a macro, however, and accept that.
1724 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001725 bool IsUDSuffix = false;
1726 if (C == '_')
1727 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001728 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001729 // In C++1y, we need to look ahead a few characters to see if this is a
1730 // valid suffix for a string literal or a numeric literal (this could be
1731 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001732 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001733 char Buffer[MaxStandardSuffixLength] = { C };
1734 unsigned Consumed = Size;
1735 unsigned Chars = 1;
1736 while (true) {
1737 unsigned NextSize;
1738 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1739 getLangOpts());
1740 if (!isIdentifierBody(Next)) {
1741 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001742 const StringRef CompleteSuffix(Buffer, Chars);
1743 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1744 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001745 break;
1746 }
1747
1748 if (Chars == MaxStandardSuffixLength)
1749 // Too long: can't be a standard suffix.
1750 break;
1751
1752 Buffer[Chars++] = Next;
1753 Consumed += NextSize;
1754 }
Richard Smithf4198b72013-07-23 08:14:48 +00001755 }
1756
1757 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001758 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001759 Diag(CurPtr, getLangOpts().MSVCCompat
1760 ? diag::ext_ms_reserved_user_defined_literal
1761 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001762 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001763 return CurPtr;
1764 }
1765
Richard Smith8b7258b2014-02-17 21:52:30 +00001766 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001767 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001768
1769 Result.setFlag(Token::HasUDSuffix);
1770 while (true) {
1771 C = getCharAndSize(CurPtr, Size);
1772 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1773 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1774 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1775 else break;
1776 }
1777
Richard Smithe18f0fa2012-03-05 04:02:15 +00001778 return CurPtr;
1779}
1780
Chris Lattner22eb9722006-06-18 05:43:12 +00001781/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001782/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001783bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001784 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001785 // Does this string contain the \0 character?
1786 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001787
Richard Smithacd4d3d2011-10-15 01:18:56 +00001788 if (!isLexingRawMode() &&
1789 (Kind == tok::utf8_string_literal ||
1790 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001791 Kind == tok::utf32_string_literal))
1792 Diag(BufferPtr, getLangOpts().CPlusPlus
1793 ? diag::warn_cxx98_compat_unicode_literal
1794 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001795
Chris Lattner22eb9722006-06-18 05:43:12 +00001796 char C = getAndAdvanceChar(CurPtr, Result);
1797 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001798 // Skip escaped characters. Escaped newlines will already be processed by
1799 // getAndAdvanceChar.
1800 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001801 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001802
Chris Lattner52d96ac2010-05-30 23:27:38 +00001803 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001804 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001805 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001806 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001807 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001808 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001809 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001810
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001811 if (C == 0) {
1812 if (isCodeCompletionPoint(CurPtr-1)) {
1813 PP->CodeCompleteNaturalLanguage();
1814 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001815 cutOffLexing();
1816 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001817 }
1818
Chris Lattner52d96ac2010-05-30 23:27:38 +00001819 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001820 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001821 C = getAndAdvanceChar(CurPtr, Result);
1822 }
Mike Stump11289f42009-09-09 15:08:12 +00001823
Richard Smithe18f0fa2012-03-05 04:02:15 +00001824 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001825 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001826 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001827
Chris Lattner5a78a022006-07-20 06:02:19 +00001828 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001829 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001830 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001831
Chris Lattnerd01e2912006-06-18 16:22:51 +00001832 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001833 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001834 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001835 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001836 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001837}
1838
Craig Topper54edcca2011-08-11 04:06:15 +00001839/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1840/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001841bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001842 tok::TokenKind Kind) {
1843 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1844 // Between the initial and final double quote characters of the raw string,
1845 // any transformations performed in phases 1 and 2 (trigraphs,
1846 // universal-character-names, and line splicing) are reverted.
1847
Richard Smithacd4d3d2011-10-15 01:18:56 +00001848 if (!isLexingRawMode())
1849 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1850
Craig Topper54edcca2011-08-11 04:06:15 +00001851 unsigned PrefixLen = 0;
1852
1853 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1854 ++PrefixLen;
1855
1856 // If the last character was not a '(', then we didn't lex a valid delimiter.
1857 if (CurPtr[PrefixLen] != '(') {
1858 if (!isLexingRawMode()) {
1859 const char *PrefixEnd = &CurPtr[PrefixLen];
1860 if (PrefixLen == 16) {
1861 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1862 } else {
1863 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1864 << StringRef(PrefixEnd, 1);
1865 }
1866 }
1867
1868 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1869 // it's possible the '"' was intended to be part of the raw string, but
1870 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001871 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001872 char C = *CurPtr++;
1873
1874 if (C == '"')
1875 break;
1876 if (C == 0 && CurPtr-1 == BufferEnd) {
1877 --CurPtr;
1878 break;
1879 }
1880 }
1881
1882 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001883 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001884 }
1885
1886 // Save prefix and move CurPtr past it
1887 const char *Prefix = CurPtr;
1888 CurPtr += PrefixLen + 1; // skip over prefix and '('
1889
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001890 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001891 char C = *CurPtr++;
1892
1893 if (C == ')') {
1894 // Check for prefix match and closing quote.
1895 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1896 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1897 break;
1898 }
1899 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1900 if (!isLexingRawMode())
1901 Diag(BufferPtr, diag::err_unterminated_raw_string)
1902 << StringRef(Prefix, PrefixLen);
1903 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001904 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001905 }
1906 }
1907
Richard Smithe18f0fa2012-03-05 04:02:15 +00001908 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001909 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001910 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001911
Craig Topper54edcca2011-08-11 04:06:15 +00001912 // Update the location of token as well as BufferPtr.
1913 const char *TokStart = BufferPtr;
1914 FormTokenWithChars(Result, CurPtr, Kind);
1915 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001916 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001917}
1918
Chris Lattner22eb9722006-06-18 05:43:12 +00001919/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1920/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001921bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001922 // Does this string contain the \0 character?
1923 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001924 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001925 char C = getAndAdvanceChar(CurPtr, Result);
1926 while (C != '>') {
1927 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001928 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001929 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001930 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001931 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001932 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1933 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001934 // If the filename is unterminated, then it must just be a lone <
1935 // character. Return this as such.
1936 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001937 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001938 } else if (C == 0) {
1939 NulCharacter = CurPtr-1;
1940 }
1941 C = getAndAdvanceChar(CurPtr, Result);
1942 }
Mike Stump11289f42009-09-09 15:08:12 +00001943
Chris Lattner5a78a022006-07-20 06:02:19 +00001944 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001945 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001946 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001947
Chris Lattnerd01e2912006-06-18 16:22:51 +00001948 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001949 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001950 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001951 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001952 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001953}
1954
Chris Lattner22eb9722006-06-18 05:43:12 +00001955/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001956/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001957bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001958 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001959 // Does this character contain the \0 character?
1960 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001961
Richard Smith3e3a7052014-11-08 06:08:42 +00001962 if (!isLexingRawMode()) {
1963 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1964 Diag(BufferPtr, getLangOpts().CPlusPlus
1965 ? diag::warn_cxx98_compat_unicode_literal
1966 : diag::warn_c99_compat_unicode_literal);
1967 else if (Kind == tok::utf8_char_constant)
1968 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1969 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001970
Chris Lattner22eb9722006-06-18 05:43:12 +00001971 char C = getAndAdvanceChar(CurPtr, Result);
1972 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001973 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001974 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001975 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001976 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001977 }
1978
1979 while (C != '\'') {
1980 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001981 if (C == '\\')
1982 C = getAndAdvanceChar(CurPtr, Result);
1983
1984 if (C == '\n' || C == '\r' || // Newline.
1985 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001986 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001987 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001988 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001989 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001990 }
1991
1992 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001993 if (isCodeCompletionPoint(CurPtr-1)) {
1994 PP->CodeCompleteNaturalLanguage();
1995 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001996 cutOffLexing();
1997 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001998 }
1999
Chris Lattner86851b82010-07-07 23:24:27 +00002000 NulCharacter = CurPtr-1;
2001 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002002 C = getAndAdvanceChar(CurPtr, Result);
2003 }
Mike Stump11289f42009-09-09 15:08:12 +00002004
Richard Smithe18f0fa2012-03-05 04:02:15 +00002005 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002006 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002007 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002008
Chris Lattner86851b82010-07-07 23:24:27 +00002009 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002010 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002011 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002012
Chris Lattnerd01e2912006-06-18 16:22:51 +00002013 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002014 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002015 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002016 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002017 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002018}
2019
2020/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2021/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002022///
2023/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2024///
Eli Friedman0834a4b2013-09-19 00:41:32 +00002025bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2026 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002027 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002028 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2029
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002030 unsigned char Char = *CurPtr;
2031
2032 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002033 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002034 // Skip horizontal whitespace very aggressively.
2035 while (isHorizontalWhitespace(Char))
2036 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002037
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002038 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002039 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002040 break;
Mike Stump11289f42009-09-09 15:08:12 +00002041
Chris Lattner22eb9722006-06-18 05:43:12 +00002042 if (ParsingPreprocessorDirective) {
2043 // End of preprocessor directive line, let LexTokenInternal handle this.
2044 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002045 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002046 }
Mike Stump11289f42009-09-09 15:08:12 +00002047
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002048 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002049 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002050 Char = *++CurPtr;
2051 }
2052
Chris Lattner4d963442008-10-12 04:05:48 +00002053 // If the client wants us to return whitespace, return it now.
2054 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002055 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002056 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002057 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002058 IsAtPhysicalStartOfLine = true;
2059 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002060 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002061 return true;
2062 }
Mike Stump11289f42009-09-09 15:08:12 +00002063
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002064 // If this isn't immediately after a newline, there is leading space.
2065 char PrevChar = CurPtr[-1];
2066 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2067
2068 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002069 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002070 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002071 TokAtPhysicalStartOfLine = true;
2072 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002073
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002075 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002076}
2077
Nico Weber158a31a2012-11-11 07:02:14 +00002078/// We have just read the // characters from input. Skip until we find the
2079/// newline character thats terminate the comment. Then update BufferPtr and
2080/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002081///
2082/// If we're in KeepCommentMode or any CommentHandler has inserted
2083/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002084bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2085 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002086 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002087 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002088 if (!LangOpts.LineComment && !isLexingRawMode()) {
2089 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002090
Chris Lattner22eb9722006-06-18 05:43:12 +00002091 // Mark them enabled so we only emit one warning for this translation
2092 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002093 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattner22eb9722006-06-18 05:43:12 +00002096 // Scan over the body of the comment. The common case, when scanning, is that
2097 // the comment contains normal ascii characters with nothing interesting in
2098 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002099 //
2100 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2101 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002102 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002103 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002104 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002105 // Skip over characters in the fast loop.
2106 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002107 C != '\n' && C != '\r') // Newline or DOS-style newline.
2108 C = *++CurPtr;
2109
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002110 const char *NextLine = CurPtr;
2111 if (C != 0) {
2112 // We found a newline, see if it's escaped.
2113 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002114 bool HasSpace = false;
2115 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002116 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002117 HasSpace = true;
2118 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002119
Richard Smith4c132e52017-04-18 21:45:04 +00002120 if (*EscapePtr == '\\')
2121 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002122 CurPtr = EscapePtr;
2123 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002124 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2125 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002126 CurPtr = EscapePtr-2;
2127 else
2128 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002129
2130 // If there was space between the backslash and newline, warn about it.
2131 if (HasSpace && !isLexingRawMode())
2132 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002133 }
Mike Stump11289f42009-09-09 15:08:12 +00002134
Chris Lattner22eb9722006-06-18 05:43:12 +00002135 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002136 // properly decode the character. Read it in raw mode to avoid emitting
2137 // diagnostics about things like trigraphs. If we see an escaped newline,
2138 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002139 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002140 bool OldRawMode = isLexingRawMode();
2141 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002142 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002143 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002144
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002145 // If we only read only one character, then no special handling is needed.
2146 // We're done and can skip forward to the newline.
2147 if (C != 0 && CurPtr == OldPtr+1) {
2148 CurPtr = NextLine;
2149 break;
2150 }
2151
Chris Lattner22eb9722006-06-18 05:43:12 +00002152 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002153 // \n, then we had an escaped newline within the comment. Emit diagnostic
2154 // unless the next line is also a // comment.
2155 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002156 for (; OldPtr != CurPtr; ++OldPtr)
2157 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002158 // Okay, we found a // comment that ends in a newline, if the next
2159 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002160 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002161 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002162 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002163 ++ForwardPtr;
2164 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2165 break;
2166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattner6d27a162008-11-22 02:02:22 +00002168 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002169 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002170 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002171 }
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173
Richard Smith1d2ae942017-04-17 23:44:51 +00002174 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2175 --CurPtr;
2176 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002177 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002178
2179 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2180 PP->CodeCompleteNaturalLanguage();
2181 cutOffLexing();
2182 return false;
2183 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002184 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002185
Chris Lattner93ddf802010-02-03 21:06:21 +00002186 // Found but did not consume the newline. Notify comment handlers about the
2187 // comment unless we're in a #if 0 block.
2188 if (PP && !isLexingRawMode() &&
2189 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2190 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002191 BufferPtr = CurPtr;
2192 return true; // A token has to be returned.
2193 }
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattner457fc152006-07-29 06:30:25 +00002195 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002196 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002197 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002198
2199 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002200 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002201 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002202 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002203 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002204 }
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattner22eb9722006-06-18 05:43:12 +00002206 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002207 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002208 // contribute to another token), it isn't needed for correctness. Note that
2209 // this is ok even in KeepWhitespaceMode, because we would have returned the
2210 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002211 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002212
Chris Lattner22eb9722006-06-18 05:43:12 +00002213 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002214 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002215 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002216 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002217 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002218 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002219 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002220}
Chris Lattner22eb9722006-06-18 05:43:12 +00002221
Nico Weber158a31a2012-11-11 07:02:14 +00002222/// If in save-comment mode, package up this Line comment in an appropriate
2223/// way and return it.
2224bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002225 // If we're not in a preprocessor directive, just return the // comment
2226 // directly.
2227 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002228
David Blaikied5321242012-06-06 18:52:13 +00002229 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002230 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002231
Nico Weber158a31a2012-11-11 07:02:14 +00002232 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002233 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002234 bool Invalid = false;
2235 std::string Spelling = PP->getSpelling(Result, &Invalid);
2236 if (Invalid)
2237 return true;
2238
Nico Weber158a31a2012-11-11 07:02:14 +00002239 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002240 Spelling[1] = '*'; // Change prefix to "/*".
2241 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002242
Chris Lattnerb11c3232008-10-12 04:51:35 +00002243 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002244 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002245 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002246 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002247}
2248
Chris Lattnercb283342006-06-18 06:48:37 +00002249/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002250/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2251/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002252static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002253 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002254 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattner22eb9722006-06-18 05:43:12 +00002256 // Back up off the newline.
2257 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattner22eb9722006-06-18 05:43:12 +00002259 // If this is a two-character newline sequence, skip the other character.
2260 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2261 // \n\n or \r\r -> not escaped newline.
2262 if (CurPtr[0] == CurPtr[1])
2263 return false;
2264 // \n\r or \r\n -> skip the newline.
2265 --CurPtr;
2266 }
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chris Lattner22eb9722006-06-18 05:43:12 +00002268 // If we have horizontal whitespace, skip over it. We allow whitespace
2269 // between the slash and newline.
2270 bool HasSpace = false;
2271 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2272 --CurPtr;
2273 HasSpace = true;
2274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattner22eb9722006-06-18 05:43:12 +00002276 // If we have a slash, we know this is an escaped newline.
2277 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002278 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002279 } else {
2280 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002281 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2282 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002283 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnercb283342006-06-18 06:48:37 +00002285 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002286 CurPtr -= 2;
2287
2288 // If no trigraphs are enabled, warn that we ignored this trigraph and
2289 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002290 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002291 if (!L->isLexingRawMode())
2292 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002293 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002294 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002295 if (!L->isLexingRawMode())
2296 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002297 }
Mike Stump11289f42009-09-09 15:08:12 +00002298
Chris Lattner22eb9722006-06-18 05:43:12 +00002299 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002300 if (!L->isLexingRawMode())
2301 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002302
Chris Lattner22eb9722006-06-18 05:43:12 +00002303 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002304 if (HasSpace && !L->isLexingRawMode())
2305 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002306
Chris Lattnercb283342006-06-18 06:48:37 +00002307 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002308}
2309
Chris Lattneraded4a92006-10-27 04:42:31 +00002310#ifdef __SSE2__
2311#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002312#elif __ALTIVEC__
2313#include <altivec.h>
2314#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002315#endif
2316
James Dennettf442d242012-06-17 03:40:43 +00002317/// We have just read from input the / and * characters that started a comment.
2318/// Read until we find the * and / characters that terminate the comment.
2319/// Note that we don't bother decoding trigraphs or escaped newlines in block
2320/// comments, because they cannot cause the comment to end. The only thing
2321/// that can happen is the comment could end with an escaped newline between
2322/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002323///
Chris Lattner87d02082010-01-18 22:35:47 +00002324/// If we're in KeepCommentMode or any CommentHandler has inserted
2325/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002326bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2327 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002328 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002329 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002330 // optimization helps people who like to put a lot of * characters in their
2331 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002332
2333 // The first character we get with newlines and trigraphs skipped to handle
2334 // the degenerate /*/ case below correctly if the * has an escaped newline
2335 // after it.
2336 unsigned CharSize;
2337 unsigned char C = getCharAndSize(CurPtr, CharSize);
2338 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002339 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002340 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002341 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002342 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002343
Chris Lattner99e7d232008-10-12 04:19:49 +00002344 // KeepWhitespaceMode should return this broken comment as a token. Since
2345 // it isn't a well formed comment, just return it as an 'unknown' token.
2346 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002347 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002348 return true;
2349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Chris Lattner99e7d232008-10-12 04:19:49 +00002351 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002352 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002353 }
Mike Stump11289f42009-09-09 15:08:12 +00002354
Chris Lattnerc850ad62007-07-21 23:43:37 +00002355 // Check to see if the first character after the '/*' is another /. If so,
2356 // then this slash does not end the block comment, it is part of it.
2357 if (C == '/')
2358 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002359
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002360 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002361 // Skip over all non-interesting characters until we find end of buffer or a
2362 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002363 if (CurPtr + 24 < BufferEnd &&
2364 // If there is a code-completion point avoid the fast scan because it
2365 // doesn't check for '\0'.
2366 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002367 // While not aligned to a 16-byte boundary.
2368 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2369 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002370
Chris Lattner6cc3e362006-10-27 04:12:35 +00002371 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002372
2373#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002374 __m128i Slashes = _mm_set1_epi8('/');
2375 while (CurPtr+16 <= BufferEnd) {
2376 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2377 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002378 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002379 // Adjust the pointer to point directly after the first slash. It's
2380 // not necessary to set C here, it will be overwritten at the end of
2381 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002382 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002383 goto FoundSlash;
2384 }
Roman Divacky61509902014-04-03 18:04:52 +00002385 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002386 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002387#elif __ALTIVEC__
2388 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002389 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002390 '/', '/', '/', '/', '/', '/', '/', '/'
2391 };
2392 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002393 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002394 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002395#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002396 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002397 while (CurPtr[0] != '/' &&
2398 CurPtr[1] != '/' &&
2399 CurPtr[2] != '/' &&
2400 CurPtr[3] != '/' &&
2401 CurPtr+4 < BufferEnd) {
2402 CurPtr += 4;
2403 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002404#endif
Mike Stump11289f42009-09-09 15:08:12 +00002405
Chris Lattneraded4a92006-10-27 04:42:31 +00002406 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002407 C = *CurPtr++;
2408 }
Mike Stump11289f42009-09-09 15:08:12 +00002409
Chris Lattneraded4a92006-10-27 04:42:31 +00002410 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002411 while (C != '/' && C != '\0')
2412 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002413
Chris Lattner22eb9722006-06-18 05:43:12 +00002414 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002415 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002416 if (CurPtr[-2] == '*') // We found the final */. We're done!
2417 break;
Mike Stump11289f42009-09-09 15:08:12 +00002418
Chris Lattner22eb9722006-06-18 05:43:12 +00002419 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002420 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002421 // We found the final */, though it had an escaped newline between the
2422 // * and /. We're done!
2423 break;
2424 }
2425 }
2426 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2427 // If this is a /* inside of the comment, emit a warning. Don't do this
2428 // if this is a /*/, which will end the comment. This misses cases with
2429 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002430 if (!isLexingRawMode())
2431 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002432 }
2433 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002434 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002435 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002436 // Note: the user probably forgot a */. We could continue immediately
2437 // after the /*, but this would involve lexing a lot of what really is the
2438 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002439 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Chris Lattner99e7d232008-10-12 04:19:49 +00002441 // KeepWhitespaceMode should return this broken comment as a token. Since
2442 // it isn't a well formed comment, just return it as an 'unknown' token.
2443 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002444 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002445 return true;
2446 }
Mike Stump11289f42009-09-09 15:08:12 +00002447
Chris Lattner99e7d232008-10-12 04:19:49 +00002448 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002449 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002450 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2451 PP->CodeCompleteNaturalLanguage();
2452 cutOffLexing();
2453 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002454 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002455
Chris Lattner22eb9722006-06-18 05:43:12 +00002456 C = *CurPtr++;
2457 }
Mike Stump11289f42009-09-09 15:08:12 +00002458
Chris Lattner93ddf802010-02-03 21:06:21 +00002459 // Notify comment handlers about the comment unless we're in a #if 0 block.
2460 if (PP && !isLexingRawMode() &&
2461 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2462 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002463 BufferPtr = CurPtr;
2464 return true; // A token has to be returned.
2465 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002466
Chris Lattner457fc152006-07-29 06:30:25 +00002467 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002468 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002469 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002470 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002471 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002472
2473 // It is common for the tokens immediately after a /**/ comment to be
2474 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002475 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2476 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002477 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002478 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002479 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002480 }
2481
2482 // Otherwise, just return so that the next character will be lexed as a token.
2483 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002484 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002485 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002486}
2487
2488//===----------------------------------------------------------------------===//
2489// Primary Lexing Entry Points
2490//===----------------------------------------------------------------------===//
2491
Chris Lattner22eb9722006-06-18 05:43:12 +00002492/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2493/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002494void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002495 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2496 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002497 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002498
2499 // CurPtr - Cache BufferPtr in an automatic variable.
2500 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002501 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002502 char Char = getAndAdvanceChar(CurPtr, Tmp);
2503 switch (Char) {
2504 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002505 if (Result)
2506 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002507 break;
2508 case 0: // Null.
2509 // Found end of file?
2510 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002511 if (isCodeCompletionPoint(CurPtr-1)) {
2512 PP->CodeCompleteNaturalLanguage();
2513 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002514 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002515 }
2516
Chris Lattner22eb9722006-06-18 05:43:12 +00002517 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002518 if (Result)
2519 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002520 break;
2521 }
2522 // FALL THROUGH.
2523 case '\r':
2524 case '\n':
2525 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2526 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2527 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002528
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002529 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002530 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002531 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002532 if (PP)
2533 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002534 Lex(Tmp);
2535 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002536 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002537
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002538 // Finally, we're done;
2539 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002540 }
2541 }
2542}
2543
2544/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2545/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002546/// This returns true if Result contains a token, false if PP.Lex should be
2547/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002548bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002549 // If we hit the end of the file while parsing a preprocessor directive,
2550 // end the preprocessor directive first. The next token returned will
2551 // then be the end of file.
2552 if (ParsingPreprocessorDirective) {
2553 // Done parsing the "line".
2554 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002555 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002556 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002557
Chris Lattner457fc152006-07-29 06:30:25 +00002558 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002559 if (PP)
2560 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002561 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002562 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002563
Chris Lattner30a2fa12006-07-19 06:31:49 +00002564 // If we are in raw mode, return this event as an EOF token. Let the caller
2565 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002566 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002567 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002568 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002569 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002570 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002571 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002572
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002573 // Issue diagnostics for unterminated #if and missing newline.
2574
Chris Lattner30a2fa12006-07-19 06:31:49 +00002575 // If we are in a #if directive, emit an error.
2576 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002577 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002578 PP->Diag(ConditionalStack.back().IfLoc,
2579 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002580 ConditionalStack.pop_back();
2581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Chris Lattner8f96d042008-04-12 05:54:25 +00002583 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2584 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002585 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2586 DiagnosticsEngine &Diags = PP->getDiagnostics();
2587 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2588 unsigned DiagID;
2589
2590 if (LangOpts.CPlusPlus11) {
2591 // C++11 [lex.phases] 2.2 p2
2592 // Prefer the C++98 pedantic compatibility warning over the generic,
2593 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002594 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002595 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2596 } else {
2597 DiagID = diag::warn_no_newline_eof;
2598 }
2599 } else {
2600 DiagID = diag::ext_no_newline_eof;
2601 }
2602
2603 Diag(BufferEnd, DiagID)
2604 << FixItHint::CreateInsertion(EndLoc, "\n");
2605 }
Mike Stump11289f42009-09-09 15:08:12 +00002606
Chris Lattner22eb9722006-06-18 05:43:12 +00002607 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002608
2609 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002610 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002611}
2612
Chris Lattner678c8802006-07-11 05:46:12 +00002613/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2614/// the specified lexer will return a tok::l_paren token, 0 if it is something
2615/// else and 2 if there are no more tokens in the buffer controlled by the
2616/// lexer.
2617unsigned Lexer::isNextPPTokenLParen() {
2618 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002619
Chris Lattner678c8802006-07-11 05:46:12 +00002620 // Switch to 'skipping' mode. This will ensure that we can lex a token
2621 // without emitting diagnostics, disables macro expansion, and will cause EOF
2622 // to return an EOF token instead of popping the include stack.
2623 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattner678c8802006-07-11 05:46:12 +00002625 // Save state that can be changed while lexing so that we can restore it.
2626 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002627 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002628 bool atStartOfLine = IsAtStartOfLine;
2629 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2630 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002631
Chris Lattner146762e2007-07-20 16:59:19 +00002632 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002633 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002634
Chris Lattner678c8802006-07-11 05:46:12 +00002635 // Restore state that may have changed.
2636 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002637 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002638 HasLeadingSpace = leadingSpace;
2639 IsAtStartOfLine = atStartOfLine;
2640 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002641
Chris Lattner678c8802006-07-11 05:46:12 +00002642 // Restore the lexer back to non-skipping mode.
2643 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002644
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002645 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002646 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002647 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002648}
2649
James Dennettf442d242012-06-17 03:40:43 +00002650/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002651static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2652 ConflictMarkerKind CMK) {
2653 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2654 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002655 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002656 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002657 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002658 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002659 if (Pos == 0 ||
2660 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002661 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2662 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002663 continue;
2664 }
2665 return RestOfBuffer.data()+Pos;
2666 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002667 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002668}
2669
2670/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2671/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2672/// and recover nicely. This returns true if it is a conflict marker and false
2673/// if not.
2674bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2675 // Only a conflict marker if it starts at the beginning of a line.
2676 if (CurPtr != BufferStart &&
2677 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2678 return false;
2679
Richard Smitha9e33d42011-10-12 00:37:51 +00002680 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002681 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2682 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002683 return false;
2684
2685 // If we have a situation where we don't care about conflict markers, ignore
2686 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002687 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002688 return false;
2689
Richard Smitha9e33d42011-10-12 00:37:51 +00002690 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2691
2692 // Check to see if there is an ending marker somewhere in the buffer at the
2693 // start of a line to terminate this conflict marker.
2694 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002695 // We found a match. We are really in a conflict marker.
2696 // Diagnose this, and ignore to the end of line.
2697 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002698 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002699
2700 // Skip ahead to the end of line. We know this exists because the
2701 // end-of-conflict marker starts with \r or \n.
2702 while (*CurPtr != '\r' && *CurPtr != '\n') {
2703 assert(CurPtr != BufferEnd && "Didn't find end of line");
2704 ++CurPtr;
2705 }
2706 BufferPtr = CurPtr;
2707 return true;
2708 }
2709
2710 // No end of conflict marker found.
2711 return false;
2712}
2713
Richard Smitha9e33d42011-10-12 00:37:51 +00002714/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2715/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2716/// is the end of a conflict marker. Handle it by ignoring up until the end of
2717/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002718bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2719 // Only a conflict marker if it starts at the beginning of a line.
2720 if (CurPtr != BufferStart &&
2721 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2722 return false;
2723
2724 // If we have a situation where we don't care about conflict markers, ignore
2725 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002726 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002727 return false;
2728
Richard Smitha9e33d42011-10-12 00:37:51 +00002729 // Check to see if we have the marker (4 characters in a row).
2730 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002731 if (CurPtr[i] != CurPtr[0])
2732 return false;
2733
2734 // If we do have it, search for the end of the conflict marker. This could
2735 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2736 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002737 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2738 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002739 CurPtr = End;
2740
2741 // Skip ahead to the end of line.
2742 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2743 ++CurPtr;
2744
2745 BufferPtr = CurPtr;
2746
2747 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002748 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002749 return true;
2750 }
2751
2752 return false;
2753}
2754
Alex Lorenz1be800c52017-04-19 08:58:56 +00002755static const char *findPlaceholderEnd(const char *CurPtr,
2756 const char *BufferEnd) {
2757 if (CurPtr == BufferEnd)
2758 return nullptr;
2759 BufferEnd -= 1; // Scan until the second last character.
2760 for (; CurPtr != BufferEnd; ++CurPtr) {
2761 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2762 return CurPtr + 2;
2763 }
2764 return nullptr;
2765}
2766
2767bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2768 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2769 if (!PP || LexingRawMode)
2770 return false;
2771 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2772 if (!End)
2773 return false;
2774 const char *Start = CurPtr - 1;
2775 if (!LangOpts.AllowEditorPlaceholders)
2776 Diag(Start, diag::err_placeholder_in_source);
2777 Result.startToken();
2778 FormTokenWithChars(Result, End, tok::raw_identifier);
2779 Result.setRawIdentifierData(Start);
2780 PP->LookUpIdentifierInfo(Result);
2781 Result.setFlag(Token::IsEditorPlaceholder);
2782 BufferPtr = End;
2783 return true;
2784}
2785
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002786bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2787 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002788 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002789 return Loc == PP->getCodeCompletionLoc();
2790 }
2791
2792 return false;
2793}
2794
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002795uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2796 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002797 unsigned CharSize;
2798 char Kind = getCharAndSize(StartPtr, CharSize);
2799
2800 unsigned NumHexDigits;
2801 if (Kind == 'u')
2802 NumHexDigits = 4;
2803 else if (Kind == 'U')
2804 NumHexDigits = 8;
2805 else
2806 return 0;
2807
Jordan Rosec0cba272013-01-27 20:12:04 +00002808 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002809 if (Result && !isLexingRawMode())
2810 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002811 return 0;
2812 }
2813
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002814 const char *CurPtr = StartPtr + CharSize;
2815 const char *KindLoc = &CurPtr[-1];
2816
2817 uint32_t CodePoint = 0;
2818 for (unsigned i = 0; i < NumHexDigits; ++i) {
2819 char C = getCharAndSize(CurPtr, CharSize);
2820
2821 unsigned Value = llvm::hexDigitValue(C);
2822 if (Value == -1U) {
2823 if (Result && !isLexingRawMode()) {
2824 if (i == 0) {
2825 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2826 << StringRef(KindLoc, 1);
2827 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002828 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002829
2830 // If the user wrote \U1234, suggest a fixit to \u.
2831 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002832 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002833 Diag(KindLoc, diag::note_ucn_four_not_eight)
2834 << FixItHint::CreateReplacement(URange, "u");
2835 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002836 }
2837 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002838
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002839 return 0;
2840 }
2841
2842 CodePoint <<= 4;
2843 CodePoint += Value;
2844
2845 CurPtr += CharSize;
2846 }
2847
2848 if (Result) {
2849 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002850 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002851 StartPtr = CurPtr;
2852 else
2853 while (StartPtr != CurPtr)
2854 (void)getAndAdvanceChar(StartPtr, *Result);
2855 } else {
2856 StartPtr = CurPtr;
2857 }
2858
Justin Bogner53535132013-10-21 05:02:28 +00002859 // Don't apply C family restrictions to UCNs in assembly mode
2860 if (LangOpts.AsmPreprocessor)
2861 return CodePoint;
2862
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002863 // C99 6.4.3p2: A universal character name shall not specify a character whose
2864 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2865 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2866 // C++11 [lex.charset]p2: If the hexadecimal value for a
2867 // universal-character-name corresponds to a surrogate code point (in the
2868 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2869 // if the hexadecimal value for a universal-character-name outside the
2870 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2871 // string literal corresponds to a control character (in either of the
2872 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2873 // basic source character set, the program is ill-formed.
2874 if (CodePoint < 0xA0) {
2875 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2876 return CodePoint;
2877
2878 // We don't use isLexingRawMode() here because we need to warn about bad
2879 // UCNs even when skipping preprocessing tokens in a #if block.
2880 if (Result && PP) {
2881 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2882 Diag(BufferPtr, diag::err_ucn_control_character);
2883 else {
2884 char C = static_cast<char>(CodePoint);
2885 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2886 }
2887 }
2888
2889 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002890
2891 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002892 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002893 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002894 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002895 if (Result && PP) {
2896 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2897 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2898 else
2899 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2900 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002901 return 0;
2902 }
2903
2904 return CodePoint;
2905}
2906
Eli Friedman0834a4b2013-09-19 00:41:32 +00002907bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2908 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002909 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2910 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002911 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002912 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002913 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002914 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002915
2916 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002917 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002918 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002919 return false;
2920}
Jordan Rose4246ae02013-01-24 20:50:50 +00002921
Eli Friedman0834a4b2013-09-19 00:41:32 +00002922bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002923 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2924 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2925 !PP->isPreprocessedOutput()) {
2926 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2927 makeCharRange(*this, BufferPtr, CurPtr),
2928 /*IsFirst=*/true);
2929 }
2930
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002931 MIOpt.ReadToken();
2932 return LexIdentifier(Result, CurPtr);
2933 }
2934
Jordan Rosecc538342013-01-31 19:48:48 +00002935 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2936 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002937 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002938 // Non-ASCII characters tend to creep into source code unintentionally.
2939 // Instead of letting the parser complain about the unknown token,
2940 // just drop the character.
2941 // Note that we can /only/ do this when the non-ASCII character is actually
2942 // spelled as Unicode, not written as a UCN. The standard requires that
2943 // we not throw away any possible preprocessor tokens, but there's a
2944 // loophole in the mapping of Unicode characters to basic character set
2945 // characters that allows us to map these particular characters to, say,
2946 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002947 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002948 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002949
2950 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002951 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002952 }
2953
2954 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2955 // up by accident.
2956 MIOpt.ReadToken();
2957 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002958 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002959}
2960
Eli Friedman0834a4b2013-09-19 00:41:32 +00002961void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2962 IsAtStartOfLine = Result.isAtStartOfLine();
2963 HasLeadingSpace = Result.hasLeadingSpace();
2964 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2965 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2966}
2967
2968bool Lexer::Lex(Token &Result) {
2969 // Start a new token.
2970 Result.startToken();
2971
2972 // Set up misc whitespace flags for LexTokenInternal.
2973 if (IsAtStartOfLine) {
2974 Result.setFlag(Token::StartOfLine);
2975 IsAtStartOfLine = false;
2976 }
2977
2978 if (HasLeadingSpace) {
2979 Result.setFlag(Token::LeadingSpace);
2980 HasLeadingSpace = false;
2981 }
2982
2983 if (HasLeadingEmptyMacro) {
2984 Result.setFlag(Token::LeadingEmptyMacro);
2985 HasLeadingEmptyMacro = false;
2986 }
2987
2988 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2989 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002990 bool isRawLex = isLexingRawMode();
2991 (void) isRawLex;
2992 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2993 // (After the LexTokenInternal call, the lexer might be destroyed.)
2994 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2995 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002996}
Chris Lattner22eb9722006-06-18 05:43:12 +00002997
2998/// LexTokenInternal - This implements a simple C family lexer. It is an
2999/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00003000/// has a null character at the end of the file. This returns a preprocessing
3001/// token, not a normal token, as such, it is an internal interface. It assumes
3002/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003003bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003004LexNextToken:
3005 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003006 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003007 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003008
Chris Lattner22eb9722006-06-18 05:43:12 +00003009 // CurPtr - Cache BufferPtr in an automatic variable.
3010 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003011
Chris Lattnereb54b592006-07-10 06:34:27 +00003012 // Small amounts of horizontal whitespace is very common between tokens.
3013 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3014 ++CurPtr;
3015 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3016 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003017
Chris Lattner4d963442008-10-12 04:05:48 +00003018 // If we are keeping whitespace and other tokens, just return what we just
3019 // skipped. The next lexer invocation will return the token after the
3020 // whitespace.
3021 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003022 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003023 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003024 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003025 }
Mike Stump11289f42009-09-09 15:08:12 +00003026
Chris Lattnereb54b592006-07-10 06:34:27 +00003027 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003028 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003029 }
Mike Stump11289f42009-09-09 15:08:12 +00003030
Chris Lattner22eb9722006-06-18 05:43:12 +00003031 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003032
Chris Lattner22eb9722006-06-18 05:43:12 +00003033 // Read a character, advancing over it.
3034 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003035 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003036
Chris Lattner22eb9722006-06-18 05:43:12 +00003037 switch (Char) {
3038 case 0: // Null.
3039 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003040 if (CurPtr-1 == BufferEnd)
3041 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003042
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003043 // Check if we are performing code completion.
3044 if (isCodeCompletionPoint(CurPtr-1)) {
3045 // Return the code-completion token.
3046 Result.startToken();
3047 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003048 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003049 }
3050
Chris Lattner6d27a162008-11-22 02:02:22 +00003051 if (!isLexingRawMode())
3052 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003053 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003054 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3055 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003056
Eli Friedman0834a4b2013-09-19 00:41:32 +00003057 // We know the lexer hasn't changed, 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
3061 case 26: // DOS & CP/M EOF: "^Z".
3062 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003063 if (LangOpts.MicrosoftExt) {
3064 if (!isLexingRawMode())
3065 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003066 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003067 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003068
Chris Lattner3dfff972009-12-17 05:29:40 +00003069 // If Microsoft extensions are disabled, this is just random garbage.
3070 Kind = tok::unknown;
3071 break;
3072
Chris Lattner22eb9722006-06-18 05:43:12 +00003073 case '\n':
3074 case '\r':
3075 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003076 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003077 if (ParsingPreprocessorDirective) {
3078 // Done parsing the "line".
3079 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003080
Chris Lattner457fc152006-07-29 06:30:25 +00003081 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003082 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003083 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003084
Chris Lattner22eb9722006-06-18 05:43:12 +00003085 // Since we consumed a newline, we are back at the start of a line.
3086 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003087 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003088
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003089 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003090 break;
3091 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003092
Chris Lattner22eb9722006-06-18 05:43:12 +00003093 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003094 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003095
Eli Friedman0834a4b2013-09-19 00:41:32 +00003096 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3097 return true; // KeepWhitespaceMode
3098
3099 // We only saw whitespace, so just try again with this lexer.
3100 // (We manually eliminate the tail call to avoid recursion.)
3101 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003102 case ' ':
3103 case '\t':
3104 case '\f':
3105 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003106 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003107 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003108 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3109 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003110
3111 SkipIgnoredUnits:
3112 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003113
Chris Lattnerb9b85972007-07-22 06:29:05 +00003114 // If the next token is obviously a // or /* */ comment, skip it efficiently
3115 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003116 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003117 LangOpts.LineComment &&
3118 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003119 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3120 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003121 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003122 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003123 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3124 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003125 goto SkipIgnoredUnits;
3126 } else if (isHorizontalWhitespace(*CurPtr)) {
3127 goto SkipHorizontalWhitespace;
3128 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003129 // We only saw whitespace, so just try again with this lexer.
3130 // (We manually eliminate the tail call to avoid recursion.)
3131 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003132
Chris Lattner2b15cf72008-01-03 17:58:54 +00003133 // C99 6.4.4.1: Integer Constants.
3134 // C99 6.4.4.2: Floating Constants.
3135 case '0': case '1': case '2': case '3': case '4':
3136 case '5': case '6': case '7': case '8': case '9':
3137 // Notify MIOpt that we read a non-whitespace/non-comment token.
3138 MIOpt.ReadToken();
3139 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003140
Richard Smith9b362092013-03-09 23:56:02 +00003141 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003142 // Notify MIOpt that we read a non-whitespace/non-comment token.
3143 MIOpt.ReadToken();
3144
Richard Smith9b362092013-03-09 23:56:02 +00003145 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003146 Char = getCharAndSize(CurPtr, SizeTmp);
3147
3148 // UTF-16 string literal
3149 if (Char == '"')
3150 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3151 tok::utf16_string_literal);
3152
3153 // UTF-16 character constant
3154 if (Char == '\'')
3155 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3156 tok::utf16_char_constant);
3157
Craig Topper54edcca2011-08-11 04:06:15 +00003158 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003159 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3160 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003161 return LexRawStringLiteral(Result,
3162 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3163 SizeTmp2, Result),
3164 tok::utf16_string_literal);
3165
3166 if (Char == '8') {
3167 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3168
3169 // UTF-8 string literal
3170 if (Char2 == '"')
3171 return LexStringLiteral(Result,
3172 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3173 SizeTmp2, Result),
3174 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003175 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3176 return LexCharConstant(
3177 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3178 SizeTmp2, Result),
3179 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003180
Richard Smith9b362092013-03-09 23:56:02 +00003181 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003182 unsigned SizeTmp3;
3183 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3184 // UTF-8 raw string literal
3185 if (Char3 == '"') {
3186 return LexRawStringLiteral(Result,
3187 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3188 SizeTmp2, Result),
3189 SizeTmp3, Result),
3190 tok::utf8_string_literal);
3191 }
3192 }
3193 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003194 }
3195
3196 // treat u like the start of an identifier.
3197 return LexIdentifier(Result, CurPtr);
3198
Richard Smith9b362092013-03-09 23:56:02 +00003199 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003200 // Notify MIOpt that we read a non-whitespace/non-comment token.
3201 MIOpt.ReadToken();
3202
Richard Smith9b362092013-03-09 23:56:02 +00003203 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003204 Char = getCharAndSize(CurPtr, SizeTmp);
3205
3206 // UTF-32 string literal
3207 if (Char == '"')
3208 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3209 tok::utf32_string_literal);
3210
3211 // UTF-32 character constant
3212 if (Char == '\'')
3213 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3214 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003215
3216 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003217 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3218 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003219 return LexRawStringLiteral(Result,
3220 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3221 SizeTmp2, Result),
3222 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003223 }
3224
3225 // treat U like the start of an identifier.
3226 return LexIdentifier(Result, CurPtr);
3227
Craig Topper54edcca2011-08-11 04:06:15 +00003228 case 'R': // Identifier or C++0x raw string literal
3229 // Notify MIOpt that we read a non-whitespace/non-comment token.
3230 MIOpt.ReadToken();
3231
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003232 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003233 Char = getCharAndSize(CurPtr, SizeTmp);
3234
3235 if (Char == '"')
3236 return LexRawStringLiteral(Result,
3237 ConsumeChar(CurPtr, SizeTmp, Result),
3238 tok::string_literal);
3239 }
3240
3241 // treat R like the start of an identifier.
3242 return LexIdentifier(Result, CurPtr);
3243
Chris Lattner2b15cf72008-01-03 17:58:54 +00003244 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003245 // Notify MIOpt that we read a non-whitespace/non-comment token.
3246 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003247 Char = getCharAndSize(CurPtr, SizeTmp);
3248
3249 // Wide string literal.
3250 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003251 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003252 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003253
Craig Topper54edcca2011-08-11 04:06:15 +00003254 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003255 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003256 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3257 return LexRawStringLiteral(Result,
3258 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3259 SizeTmp2, Result),
3260 tok::wide_string_literal);
3261
Chris Lattner22eb9722006-06-18 05:43:12 +00003262 // Wide character constant.
3263 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003264 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3265 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003266 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003267
Chris Lattner22eb9722006-06-18 05:43:12 +00003268 // C99 6.4.2: Identifiers.
3269 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3270 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003271 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003272 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3273 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3274 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003275 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003276 case 'v': case 'w': case 'x': case 'y': case 'z':
3277 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003278 // Notify MIOpt that we read a non-whitespace/non-comment token.
3279 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003280 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003281
3282 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003283 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003284 if (!isLexingRawMode())
3285 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003286 // Notify MIOpt that we read a non-whitespace/non-comment token.
3287 MIOpt.ReadToken();
3288 return LexIdentifier(Result, CurPtr);
3289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Chris Lattnerb11c3232008-10-12 04:51:35 +00003291 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003292 break;
Mike Stump11289f42009-09-09 15:08:12 +00003293
Chris Lattner22eb9722006-06-18 05:43:12 +00003294 // C99 6.4.4: Character Constants.
3295 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003296 // Notify MIOpt that we read a non-whitespace/non-comment token.
3297 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003298 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003299
3300 // C99 6.4.5: String Literals.
3301 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003302 // Notify MIOpt that we read a non-whitespace/non-comment token.
3303 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003304 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003305
3306 // C99 6.4.6: Punctuators.
3307 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003308 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003309 break;
3310 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003311 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003312 break;
3313 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003314 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003315 break;
3316 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003317 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003318 break;
3319 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003320 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003321 break;
3322 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003323 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003324 break;
3325 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003326 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003327 break;
3328 case '.':
3329 Char = getCharAndSize(CurPtr, SizeTmp);
3330 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003331 // Notify MIOpt that we read a non-whitespace/non-comment token.
3332 MIOpt.ReadToken();
3333
Chris Lattner22eb9722006-06-18 05:43:12 +00003334 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003335 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003336 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003337 CurPtr += SizeTmp;
3338 } else if (Char == '.' &&
3339 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003340 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003341 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3342 SizeTmp2, Result);
3343 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003344 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003345 }
3346 break;
3347 case '&':
3348 Char = getCharAndSize(CurPtr, SizeTmp);
3349 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003350 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003351 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3352 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003353 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003354 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3355 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003356 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003357 }
3358 break;
Mike Stump11289f42009-09-09 15:08:12 +00003359 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003360 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003361 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003362 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3363 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003364 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003365 }
3366 break;
3367 case '+':
3368 Char = getCharAndSize(CurPtr, SizeTmp);
3369 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003370 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003371 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003372 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003373 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003374 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003375 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003376 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003377 }
3378 break;
3379 case '-':
3380 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003381 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003382 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003383 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003384 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003385 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003386 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3387 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003388 Kind = tok::arrowstar;
3389 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003390 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003391 Kind = tok::arrow;
3392 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003393 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003394 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003395 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003396 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003397 }
3398 break;
3399 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003400 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003401 break;
3402 case '!':
3403 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003404 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003405 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3406 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003407 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003408 }
3409 break;
3410 case '/':
3411 // 6.4.9: Comments
3412 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003413 if (Char == '/') { // Line comment.
3414 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003415 // want to lex this as a comment. There is one problem with this though,
3416 // that in one particular corner case, this can change the behavior of the
3417 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003418 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003419 // "foo". Check to see if the character after the second slash is a '*'.
3420 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003421 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003422 bool TreatAsComment = LangOpts.LineComment &&
3423 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003424 if (!TreatAsComment)
3425 if (!(PP && PP->isPreprocessedOutput()))
3426 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3427
3428 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003429 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3430 TokAtPhysicalStartOfLine))
3431 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003432
Chris Lattner58827712009-01-16 22:39:25 +00003433 // It is common for the tokens immediately after a // comment to be
3434 // whitespace (indentation for the next line). Instead of going through
3435 // the big switch, handle it efficiently now.
3436 goto SkipIgnoredUnits;
3437 }
3438 }
Mike Stump11289f42009-09-09 15:08:12 +00003439
Chris Lattner58827712009-01-16 22:39:25 +00003440 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003441 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3442 TokAtPhysicalStartOfLine))
3443 return true; // There is a token to return.
3444
3445 // We only saw whitespace, so just try again with this lexer.
3446 // (We manually eliminate the tail call to avoid recursion.)
3447 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003448 }
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattner58827712009-01-16 22:39:25 +00003450 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003451 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003452 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003453 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003454 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003455 }
3456 break;
3457 case '%':
3458 Char = getCharAndSize(CurPtr, SizeTmp);
3459 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003460 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003461 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003462 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003463 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003464 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003465 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003466 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003467 Char = getCharAndSize(CurPtr, SizeTmp);
3468 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003469 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003470 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3471 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003472 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003474 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003475 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003476 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003477 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 // We parsed a # character. If this occurs at the start of the line,
3479 // it's actually the start of a preprocessing directive. Callback to
3480 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003481 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003482 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003483 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003484
Chris Lattner2534324a2009-03-18 20:58:27 +00003485 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003486 }
3487 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003488 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003489 }
3490 break;
3491 case '<':
3492 Char = getCharAndSize(CurPtr, SizeTmp);
3493 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003494 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003495 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003496 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3497 if (After == '=') {
3498 Kind = tok::lesslessequal;
3499 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3500 SizeTmp2, Result);
3501 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3502 // If this is actually a '<<<<<<<' version control conflict marker,
3503 // recognize it as such and recover nicely.
3504 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003505 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3506 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3507 // ignore it.
3508 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003509 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003510 Kind = tok::lesslessless;
3511 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3512 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003513 } else {
3514 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3515 Kind = tok::lessless;
3516 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003517 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003518 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003519 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003520 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003521 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003522 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3523 // C++0x [lex.pptoken]p3:
3524 // Otherwise, if the next three characters are <:: and the subsequent
3525 // character is neither : nor >, the < is treated as a preprocessor
3526 // token by itself and not as the first character of the alternative
3527 // token <:.
3528 unsigned SizeTmp3;
3529 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3530 if (After != ':' && After != '>') {
3531 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003532 if (!isLexingRawMode())
3533 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003534 break;
3535 }
3536 }
3537
Chris Lattner22eb9722006-06-18 05:43:12 +00003538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003539 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003540 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003541 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003542 Kind = tok::l_brace;
Alex Lorenz1be800c52017-04-19 08:58:56 +00003543 } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3544 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003545 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003546 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003547 }
3548 break;
3549 case '>':
3550 Char = getCharAndSize(CurPtr, SizeTmp);
3551 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003552 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003553 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003554 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003555 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3556 if (After == '=') {
3557 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3558 SizeTmp2, Result);
3559 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003560 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3561 // If this is actually a '>>>>' conflict marker, recognize it as such
3562 // and recover nicely.
3563 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003564 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3565 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3566 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003567 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003568 Kind = tok::greatergreatergreater;
3569 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3570 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003571 } else {
3572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3573 Kind = tok::greatergreater;
3574 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003575 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003576 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003577 }
3578 break;
3579 case '^':
3580 Char = getCharAndSize(CurPtr, SizeTmp);
3581 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003582 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003583 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003584 } else if (LangOpts.OpenCL && Char == '^') {
3585 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3586 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003587 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003588 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003589 }
3590 break;
3591 case '|':
3592 Char = getCharAndSize(CurPtr, SizeTmp);
3593 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003594 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003595 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3596 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003597 // If this is '|||||||' and we're in a conflict marker, ignore it.
3598 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3599 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003600 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003601 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3602 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003603 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003604 }
3605 break;
3606 case ':':
3607 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003608 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003609 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003610 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003611 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003612 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003613 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003614 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003615 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003616 }
3617 break;
3618 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003619 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003620 break;
3621 case '=':
3622 Char = getCharAndSize(CurPtr, SizeTmp);
3623 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003624 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003625 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3626 goto LexNextToken;
3627
Chris Lattnerb11c3232008-10-12 04:51:35 +00003628 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003629 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003630 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003631 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003632 }
3633 break;
3634 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003635 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003636 break;
3637 case '#':
3638 Char = getCharAndSize(CurPtr, SizeTmp);
3639 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003640 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003641 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003642 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003643 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003644 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003645 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003646 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003647 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003648 // We parsed a # character. If this occurs at the start of the line,
3649 // it's actually the start of a preprocessing directive. Callback to
3650 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003651 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003652 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003653 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003654
Chris Lattner2534324a2009-03-18 20:58:27 +00003655 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003656 }
3657 break;
3658
Chris Lattner2b15cf72008-01-03 17:58:54 +00003659 case '@':
3660 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003661 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003662 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003663 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003664 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003665 break;
Mike Stump11289f42009-09-09 15:08:12 +00003666
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003667 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003668 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003669 if (!LangOpts.AsmPreprocessor) {
3670 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3671 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3672 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3673 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003674
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003675 // We only saw whitespace, so just try again with this lexer.
3676 // (We manually eliminate the tail call to avoid recursion.)
3677 goto LexNextToken;
3678 }
3679
3680 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003681 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003682 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003683
Chris Lattnerb11c3232008-10-12 04:51:35 +00003684 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003685 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003686
3687 default: {
3688 if (isASCII(Char)) {
3689 Kind = tok::unknown;
3690 break;
3691 }
3692
Justin Lebar90910552016-09-30 00:38:45 +00003693 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003694
3695 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3696 // an escaped newline.
3697 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003698 llvm::ConversionResult Status =
3699 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3700 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003701 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003702 llvm::strictConversion);
3703 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003704 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3705 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3706 return true; // KeepWhitespaceMode
3707
3708 // We only saw whitespace, so just try again with this lexer.
3709 // (We manually eliminate the tail call to avoid recursion.)
3710 goto LexNextToken;
3711 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003712 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003713 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003714
Jordan Rosecc538342013-01-31 19:48:48 +00003715 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3716 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003717 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003718 Kind = tok::unknown;
3719 break;
3720 }
3721
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003722 // Non-ASCII characters tend to creep into source code unintentionally.
3723 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003724 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003725 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003726
3727 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003728 // We're pretending the character didn't exist, so just try again with
3729 // this lexer.
3730 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003731 goto LexNextToken;
3732 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003733 }
Mike Stump11289f42009-09-09 15:08:12 +00003734
Chris Lattner371ac8a2006-07-04 07:11:10 +00003735 // Notify MIOpt that we read a non-whitespace/non-comment token.
3736 MIOpt.ReadToken();
3737
Chris Lattnerd01e2912006-06-18 16:22:51 +00003738 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003739 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003740 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003741
3742HandleDirective:
3743 // We parsed a # character and it's the start of a preprocessing directive.
3744
3745 FormTokenWithChars(Result, CurPtr, tok::hash);
3746 PP->HandleDirective(Result);
3747
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003748 if (PP->hadModuleLoaderFatalFailure()) {
3749 // With a fatal failure in the module loader, we abort parsing.
3750 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003751 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003752 }
3753
Eli Friedman0834a4b2013-09-19 00:41:32 +00003754 // We parsed the directive; lex a token with the new state.
3755 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003756}