blob: f5a35e97d6e1cef761e8c11b62a1313082402fe1 [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,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000553 PDK_Unknown
554 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000555
556} // end anonymous namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000557
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000558std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
David Blaikie3d95d852014-08-11 22:08:06 +0000559 const LangOptions &LangOpts,
560 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000561 // Create a lexer starting at the beginning of the file. Note that we use a
562 // "fake" file source location at offset 1 so that the lexer will track our
563 // position within the file.
564 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000565 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000566 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
567 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000568 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000569
570 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
571 SourceLocation StartLoc = TheLexer.getSourceLocation();
572
Douglas Gregoraf82e352010-07-20 20:18:03 +0000573 bool InPreprocessorDirective = false;
574 Token TheTok;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000575 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000576
577 unsigned MaxLineOffset = 0;
578 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000579 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000580 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000581 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000582 char ch = *CurPtr++;
583 if (ch == '\n') {
584 ++CurLine;
585 if (CurLine == MaxLines)
586 break;
587 }
588 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000589 if (CurPtr != Buffer.end())
590 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000591 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000592
Douglas Gregoraf82e352010-07-20 20:18:03 +0000593 do {
594 TheLexer.LexFromRawLexer(TheTok);
595
596 if (InPreprocessorDirective) {
597 // If we've hit the end of the file, we're done.
598 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000599 break;
600 }
601
602 // If we haven't hit the end of the preprocessor directive, skip this
603 // token.
604 if (!TheTok.isAtStartOfLine())
605 continue;
606
607 // We've passed the end of the preprocessor directive, and will look
608 // at this token again below.
609 InPreprocessorDirective = false;
610 }
611
Douglas Gregor028d3e42010-08-09 20:45:32 +0000612 // Keep track of the # of lines in the preamble.
613 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000614 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000615
616 // If we were asked to limit the number of lines in the preamble,
617 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000618 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000619 break;
620 }
621
Douglas Gregoraf82e352010-07-20 20:18:03 +0000622 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000623 if (TheTok.getKind() == tok::comment) {
624 if (ActiveCommentLoc.isInvalid())
625 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000626 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000627 }
Douglas Gregoraf82e352010-07-20 20:18:03 +0000628
629 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
630 // This is the start of a preprocessor directive.
631 Token HashTok = TheTok;
632 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000633 ActiveCommentLoc = SourceLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000634
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000635 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000636 // we don't have an identifier table available. Instead, just look at
637 // the raw identifier to recognize and categorize preprocessor directives.
638 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000639 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000640 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000641 PreambleDirectiveKind PDK
642 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
643 .Case("include", PDK_Skipped)
644 .Case("__include_macros", PDK_Skipped)
645 .Case("define", PDK_Skipped)
646 .Case("undef", PDK_Skipped)
647 .Case("line", PDK_Skipped)
648 .Case("error", PDK_Skipped)
649 .Case("pragma", PDK_Skipped)
650 .Case("import", PDK_Skipped)
651 .Case("include_next", PDK_Skipped)
652 .Case("warning", PDK_Skipped)
653 .Case("ident", PDK_Skipped)
654 .Case("sccs", PDK_Skipped)
655 .Case("assert", PDK_Skipped)
656 .Case("unassert", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000657 .Case("if", PDK_Skipped)
658 .Case("ifdef", PDK_Skipped)
659 .Case("ifndef", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000660 .Case("elif", PDK_Skipped)
661 .Case("else", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000662 .Case("endif", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000663 .Default(PDK_Unknown);
664
665 switch (PDK) {
666 case PDK_Skipped:
667 continue;
668
Douglas Gregoraf82e352010-07-20 20:18:03 +0000669 case PDK_Unknown:
670 // We don't know what this directive is; stop at the '#'.
671 break;
672 }
673 }
674
675 // We only end up here if we didn't recognize the preprocessor
676 // directive or it was one that can't occur in the preamble at this
677 // point. Roll back the current token to the location of the '#'.
678 InPreprocessorDirective = false;
679 TheTok = HashTok;
680 }
681
Douglas Gregor028d3e42010-08-09 20:45:32 +0000682 // We hit a token that we don't recognize as being in the
683 // "preprocessing only" part of the file, so we're no longer in
684 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000685 break;
686 } while (true);
687
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000688 SourceLocation End;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000689 if (ActiveCommentLoc.isValid())
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000690 End = ActiveCommentLoc; // don't truncate a decl comment.
691 else
692 End = TheTok.getLocation();
693
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000694 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000695 TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000696}
697
Chris Lattner2a6ee912010-11-17 07:05:50 +0000698/// AdvanceToTokenCharacter - Given a location that specifies the start of a
699/// token, return a new location that specifies a character within the token.
700SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
701 unsigned CharNo,
702 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000703 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000704 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000705 // character is. This needs to take into consideration newlines and
706 // trigraphs.
707 bool Invalid = false;
708 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
709
710 // If they request the first char of the token, we're trivially done.
711 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
712 return TokStart;
713
714 unsigned PhysOffset = 0;
715
716 // The usual case is that tokens don't contain anything interesting. Skip
717 // over the uninteresting characters. If a token only consists of simple
718 // chars, this method is extremely fast.
719 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
720 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000721 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000722 ++TokPtr;
723 --CharNo;
724 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000725 }
726
727 // If we have a character that may be a trigraph or escaped newline, use a
728 // lexer to parse it correctly.
729 for (; CharNo; --CharNo) {
730 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000731 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000732 TokPtr += Size;
733 PhysOffset += Size;
734 }
735
736 // Final detail: if we end up on an escaped newline, we want to return the
737 // location of the actual byte of the token. For example foo\<newline>bar
738 // advanced by 3 should return the location of b, not of \\. One compounding
739 // detail of this is that the escape may be made by a trigraph.
740 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
741 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
742
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000743 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000744}
745
746/// \brief Computes the source location just past the end of the
747/// token at this source location.
748///
749/// This routine can be used to produce a source location that
750/// points just past the end of the token referenced by \p Loc, and
751/// is generally used when a diagnostic needs to point just after a
752/// token where it expected something different that it received. If
753/// the returned source location would not be meaningful (e.g., if
754/// it points into a macro), this routine returns an invalid
755/// source location.
756///
757/// \param Offset an offset from the end of the token, where the source
758/// location should refer to. The default offset (0) produces a source
759/// location pointing just past the end of the token; an offset of 1 produces
760/// a source location pointing to the last character in the token, etc.
761SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
762 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000763 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000764 if (Loc.isInvalid())
Chris Lattner2a6ee912010-11-17 07:05:50 +0000765 return SourceLocation();
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000766
767 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000768 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000769 return SourceLocation(); // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000770 }
771
David Blaikiebbafb8a2012-03-11 07:00:24 +0000772 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000773 if (Len > Offset)
774 Len = Len - Offset;
775 else
776 return Loc;
777
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000778 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000779}
780
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000781/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000782/// token of the macro expansion.
783bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000784 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000785 const LangOptions &LangOpts,
786 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000787 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
788
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000789 SourceLocation expansionLoc;
790 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
791 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000792
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000793 if (expansionLoc.isFileID()) {
794 // No other macro expansions, this is the first.
795 if (MacroBegin)
796 *MacroBegin = expansionLoc;
797 return true;
798 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000799
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000800 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000801}
802
803/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000804/// token of the macro expansion.
805bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000806 const SourceManager &SM,
807 const LangOptions &LangOpts,
808 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000809 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
810
811 SourceLocation spellLoc = SM.getSpellingLoc(loc);
812 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
813 if (tokLen == 0)
814 return false;
815
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000816 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
817 SourceLocation expansionLoc;
818 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
819 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000820
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000821 if (expansionLoc.isFileID()) {
822 // No other macro expansions.
823 if (MacroEnd)
824 *MacroEnd = expansionLoc;
825 return true;
826 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000827
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000828 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000829}
830
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000831static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000832 const SourceManager &SM,
833 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000834 SourceLocation Begin = Range.getBegin();
835 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000836 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000837 if (Range.isTokenRange()) {
838 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
839 if (End.isInvalid())
840 return CharSourceRange();
841 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000842
843 // Break down the source locations.
844 FileID FID;
845 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000846 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000847 if (FID.isInvalid())
848 return CharSourceRange();
849
850 unsigned EndOffs;
851 if (!SM.isInFileID(End, FID, &EndOffs) ||
852 BeginOffs > EndOffs)
853 return CharSourceRange();
854
855 return CharSourceRange::getCharRange(Begin, End);
856}
857
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000858CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000859 const SourceManager &SM,
860 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000861 SourceLocation Begin = Range.getBegin();
862 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000863 if (Begin.isInvalid() || End.isInvalid())
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000864 return CharSourceRange();
865
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000866 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000867 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000868
869 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000870 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
871 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000872 Range.setBegin(Begin);
873 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000874 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000875
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000876 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000877 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
878 &End)) ||
879 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
880 &End)))
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881 return CharSourceRange();
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000882 Range.setEnd(End);
883 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000884 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000885
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000886 assert(Begin.isMacroID() && End.isMacroID());
887 SourceLocation MacroBegin, MacroEnd;
888 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000889 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
890 &MacroEnd)) ||
891 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
892 &MacroEnd)))) {
893 Range.setBegin(MacroBegin);
894 Range.setEnd(MacroEnd);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
896 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000897
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000898 bool Invalid = false;
899 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
900 &Invalid);
901 if (Invalid)
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000902 return CharSourceRange();
903
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000904 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
905 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
906 &Invalid);
907 if (Invalid)
908 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000909
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000910 if (EndEntry.getExpansion().isMacroArgExpansion() &&
911 BeginEntry.getExpansion().getExpansionLocStart() ==
912 EndEntry.getExpansion().getExpansionLocStart()) {
913 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
914 Range.setEnd(SM.getImmediateSpellingLoc(End));
915 return makeFileCharRange(Range, SM, LangOpts);
916 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000917 }
918
919 return CharSourceRange();
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000920}
921
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000922StringRef Lexer::getSourceText(CharSourceRange Range,
923 const SourceManager &SM,
924 const LangOptions &LangOpts,
925 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000926 Range = makeFileCharRange(Range, SM, LangOpts);
927 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000928 if (Invalid) *Invalid = true;
929 return StringRef();
930 }
931
932 // Break down the source location.
933 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
934 if (beginInfo.first.isInvalid()) {
935 if (Invalid) *Invalid = true;
936 return StringRef();
937 }
938
939 unsigned EndOffs;
940 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
941 beginInfo.second > EndOffs) {
942 if (Invalid) *Invalid = true;
943 return StringRef();
944 }
945
946 // Try to the load the file buffer.
947 bool invalidTemp = false;
948 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
949 if (invalidTemp) {
950 if (Invalid) *Invalid = true;
951 return StringRef();
952 }
953
954 if (Invalid) *Invalid = false;
955 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
956}
957
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000958StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
959 const SourceManager &SM,
960 const LangOptions &LangOpts) {
961 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000962
963 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000964 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000965 FileID FID = SM.getFileID(Loc);
966 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
967 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
968 Loc = Expansion.getExpansionLocStart();
969 if (!Expansion.isMacroArgExpansion())
970 break;
971
972 // For macro arguments we need to check that the argument did not come
973 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
974
975 // Loc points to the argument id of the macro definition, move to the
976 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000977 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000978 SourceLocation SpellLoc = Expansion.getSpellingLoc();
979 if (SpellLoc.isFileID())
980 break; // No inner macro.
981
982 // If spelling location resides in the same FileID as macro expansion
983 // location, it means there is no inner macro.
984 FileID MacroFID = SM.getFileID(Loc);
985 if (SM.isInFileID(SpellLoc, MacroFID))
986 break;
987
988 // Argument came from inner macro.
989 Loc = SpellLoc;
990 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000991
992 // Find the spelling location of the start of the non-argument expansion
993 // range. This is where the macro name was spelled in order to begin
994 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000995 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000996
997 // Dig out the buffer where the macro name was spelled and the extents of the
998 // name so that we can render it into the expansion note.
999 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1000 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1001 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1002 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1003}
1004
Richard Trieu3a5c9582016-01-26 02:51:55 +00001005StringRef Lexer::getImmediateMacroNameForDiagnostics(
1006 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1007 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1008 // Walk past macro argument expanions.
1009 while (SM.isMacroArgExpansion(Loc))
1010 Loc = SM.getImmediateExpansionRange(Loc).first;
1011
1012 // If the macro's spelling has no FileID, then it's actually a token paste
1013 // or stringization (or similar) and not a macro at all.
1014 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1015 return StringRef();
1016
1017 // Find the spelling location of the start of the non-argument expansion
1018 // range. This is where the macro name was spelled in order to begin
1019 // expanding this macro.
1020 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1021
1022 // Dig out the buffer where the macro name was spelled and the extents of the
1023 // name so that we can render it into the expansion note.
1024 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1025 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1026 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1027 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1028}
1029
Jordan Rose288c4212012-06-07 01:10:31 +00001030bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001031 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001032}
1033
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001034StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1035 const SourceManager &SM) {
1036 if (Loc.isInvalid() || Loc.isMacroID())
1037 return "";
1038 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1039 if (LocInfo.first.isInvalid())
1040 return "";
1041 bool Invalid = false;
1042 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1043 if (Invalid)
1044 return "";
1045 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1046 if (!Line)
1047 return "";
1048 StringRef Rest = Buffer.substr(Line - Buffer.data());
1049 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1050 return NumWhitespaceChars == StringRef::npos
1051 ? ""
1052 : Rest.take_front(NumWhitespaceChars);
1053}
1054
Chris Lattner22eb9722006-06-18 05:43:12 +00001055//===----------------------------------------------------------------------===//
1056// Diagnostics forwarding code.
1057//===----------------------------------------------------------------------===//
1058
Chris Lattner619c1742007-07-22 18:38:25 +00001059/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001060/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001061/// This is currently only used for _Pragma implementation, so it is the slow
1062/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001063static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1064 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001065static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1066 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001067 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001068 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattner619c1742007-07-22 18:38:25 +00001070 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001071 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001072 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001073 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001075 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001076 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001077 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001078 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattner9dc9c202009-02-15 20:52:18 +00001080 // Figure out the expansion loc range, which is the range covered by the
1081 // original _Pragma(...) sequence.
1082 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001083 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chandler Carruth115b0772011-07-26 03:03:05 +00001085 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001086}
1087
Chris Lattner22eb9722006-06-18 05:43:12 +00001088/// getSourceLocation - Return a source location identifier for the specified
1089/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001090SourceLocation Lexer::getSourceLocation(const char *Loc,
1091 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001092 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001093 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001094
1095 // In the normal case, we're just lexing from a simple file buffer, return
1096 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001097 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001098 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001099 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattnerd32480d2009-01-17 06:22:33 +00001101 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1102 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001103 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001104 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001105}
1106
Chris Lattner22eb9722006-06-18 05:43:12 +00001107/// Diag - Forwarding function for diagnostics. This translate a source
1108/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001109DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001110 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001111}
1112
1113//===----------------------------------------------------------------------===//
1114// Trigraph and Escaped Newline Handling Code.
1115//===----------------------------------------------------------------------===//
1116
1117/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1118/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1119static char GetTrigraphCharForLetter(char Letter) {
1120 switch (Letter) {
1121 default: return 0;
1122 case '=': return '#';
1123 case ')': return ']';
1124 case '(': return '[';
1125 case '!': return '|';
1126 case '\'': return '^';
1127 case '>': return '}';
1128 case '/': return '\\';
1129 case '<': return '{';
1130 case '-': return '~';
1131 }
1132}
1133
1134/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1135/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1136/// return the result character. Finally, emit a warning about trigraph use
1137/// whether trigraphs are enabled or not.
1138static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1139 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001140 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001141
David Blaikiebbafb8a2012-03-11 07:00:24 +00001142 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001143 if (!L->isLexingRawMode())
1144 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001145 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001146 }
Mike Stump11289f42009-09-09 15:08:12 +00001147
Chris Lattner6d27a162008-11-22 02:02:22 +00001148 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001149 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001150 return Res;
1151}
1152
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001153/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1154/// 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 +00001155/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001156unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1157 unsigned Size = 0;
1158 while (isWhitespace(Ptr[Size])) {
1159 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001160
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001161 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1162 continue;
1163
1164 // If this is a \r\n or \n\r, skip the other half.
1165 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1166 Ptr[Size-1] != Ptr[Size])
1167 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001169 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001170 }
1171
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001172 // Not an escaped newline, must be a \t or something else.
1173 return 0;
1174}
1175
Chris Lattner38b2cde2009-04-18 22:27:02 +00001176/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1177/// them), skip over them and return the first non-escaped-newline found,
1178/// otherwise return P.
1179const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001180 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001181 const char *AfterEscape;
1182 if (*P == '\\') {
1183 AfterEscape = P+1;
1184 } else if (*P == '?') {
1185 // If not a trigraph for escape, bail out.
1186 if (P[1] != '?' || P[2] != '/')
1187 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001188 // FIXME: Take LangOpts into account; the language might not
1189 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001190 AfterEscape = P+3;
1191 } else {
1192 return P;
1193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattner38b2cde2009-04-18 22:27:02 +00001195 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1196 if (NewLineSize == 0) return P;
1197 P = AfterEscape+NewLineSize;
1198 }
1199}
1200
Anna Zaks59a3c802011-07-27 21:43:43 +00001201/// \brief Checks that the given token is the first token that occurs after the
1202/// given location (this excludes comments and whitespace). Returns the location
1203/// immediately after the specified token. If the token is not found or the
1204/// location is inside a macro, the returned source location will be invalid.
1205SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1206 tok::TokenKind TKind,
1207 const SourceManager &SM,
1208 const LangOptions &LangOpts,
1209 bool SkipTrailingWhitespaceAndNewLine) {
1210 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001211 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Anna Zaks59a3c802011-07-27 21:43:43 +00001212 return SourceLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001213 }
1214 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1215
1216 // Break down the source location.
1217 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1218
1219 // Try to load the file buffer.
1220 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001221 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001222 if (InvalidTemp)
1223 return SourceLocation();
1224
1225 const char *TokenBegin = File.data() + LocInfo.second;
1226
1227 // Lex from the start of the given location.
1228 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1229 TokenBegin, File.end());
1230 // Find the token.
1231 Token Tok;
1232 lexer.LexFromRawLexer(Tok);
1233 if (Tok.isNot(TKind))
1234 return SourceLocation();
1235 SourceLocation TokenLoc = Tok.getLocation();
1236
1237 // Calculate how much whitespace needs to be skipped if any.
1238 unsigned NumWhitespaceChars = 0;
1239 if (SkipTrailingWhitespaceAndNewLine) {
1240 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1241 Tok.getLength();
1242 unsigned char C = *TokenEnd;
1243 while (isHorizontalWhitespace(C)) {
1244 C = *(++TokenEnd);
1245 NumWhitespaceChars++;
1246 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001247
1248 // Skip \r, \n, \r\n, or \n\r
1249 if (C == '\n' || C == '\r') {
1250 char PrevC = C;
1251 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001252 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001253 if ((C == '\n' || C == '\r') && C != PrevC)
1254 NumWhitespaceChars++;
1255 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001256 }
1257
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001258 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001259}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001260
Chris Lattner22eb9722006-06-18 05:43:12 +00001261/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1262/// get its size, and return it. This is tricky in several cases:
1263/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1264/// then either return the trigraph (skipping 3 chars) or the '?',
1265/// depending on whether trigraphs are enabled or not.
1266/// 2. If this is an escaped newline (potentially with whitespace between
1267/// the backslash and newline), implicitly skip the newline and return
1268/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001269///
1270/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1271/// know that we can accumulate into Size, and that we have already incremented
1272/// Ptr by Size bytes.
1273///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001274/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1275/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001276///
1277char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001278 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001279 // If we have a slash, look for an escaped newline.
1280 if (Ptr[0] == '\\') {
1281 ++Size;
1282 ++Ptr;
1283Slash:
1284 // Common case, backslash-char where the char is not whitespace.
1285 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattnerc1835952009-06-23 05:15:06 +00001287 // See if we have optional whitespace characters between the slash and
1288 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001289 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1290 // Remember that this token needs to be cleaned.
1291 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001292
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001293 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001294 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001295 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001296
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001297 // Found backslash<whitespace><newline>. Parse the char after it.
1298 Size += EscapedNewLineSize;
1299 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001300
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001301 // Use slow version to accumulate a correct size field.
1302 return getCharAndSizeSlow(Ptr, Size, Tok);
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Chris Lattner22eb9722006-06-18 05:43:12 +00001305 // Otherwise, this is not an escaped newline, just return the slash.
1306 return '\\';
1307 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
Chris Lattner22eb9722006-06-18 05:43:12 +00001309 // If this is a trigraph, process it.
1310 if (Ptr[0] == '?' && Ptr[1] == '?') {
1311 // If this is actually a legal trigraph (not something like "??x"), emit
1312 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001313 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001314 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001315 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001316
1317 Ptr += 3;
1318 Size += 3;
1319 if (C == '\\') goto Slash;
1320 return C;
1321 }
1322 }
Mike Stump11289f42009-09-09 15:08:12 +00001323
Chris Lattner22eb9722006-06-18 05:43:12 +00001324 // If this is neither, return a single character.
1325 ++Size;
1326 return *Ptr;
1327}
1328
1329/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1330/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1331/// and that we have already incremented Ptr by Size bytes.
1332///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001333/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1334/// be updated to match.
1335char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001336 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001337 // If we have a slash, look for an escaped newline.
1338 if (Ptr[0] == '\\') {
1339 ++Size;
1340 ++Ptr;
1341Slash:
1342 // Common case, backslash-char where the char is not whitespace.
1343 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001344
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001346 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1347 // Found backslash<whitespace><newline>. Parse the char after it.
1348 Size += EscapedNewLineSize;
1349 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001351 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001352 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Chris Lattner22eb9722006-06-18 05:43:12 +00001355 // Otherwise, this is not an escaped newline, just return the slash.
1356 return '\\';
1357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattner22eb9722006-06-18 05:43:12 +00001359 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001360 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001361 // If this is actually a legal trigraph (not something like "??x"), return
1362 // it.
1363 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1364 Ptr += 3;
1365 Size += 3;
1366 if (C == '\\') goto Slash;
1367 return C;
1368 }
1369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattner22eb9722006-06-18 05:43:12 +00001371 // If this is neither, return a single character.
1372 ++Size;
1373 return *Ptr;
1374}
1375
Chris Lattner22eb9722006-06-18 05:43:12 +00001376//===----------------------------------------------------------------------===//
1377// Helper methods for lexing.
1378//===----------------------------------------------------------------------===//
1379
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001380/// \brief Routine that indiscriminately skips bytes in the source file.
1381void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1382 BufferPtr += Bytes;
1383 if (BufferPtr > BufferEnd)
1384 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001385 // FIXME: What exactly does the StartOfLine bit mean? There are two
1386 // possible meanings for the "start" of the line: the first token on the
1387 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001388 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001389 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001390}
1391
Jordan Rose58c61e02013-02-09 01:10:25 +00001392static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001393 if (LangOpts.AsmPreprocessor) {
1394 return false;
1395 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001396 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1397 C11AllowedIDCharRanges);
1398 return C11AllowedIDChars.contains(C);
1399 } else if (LangOpts.CPlusPlus) {
1400 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1401 CXX03AllowedIDCharRanges);
1402 return CXX03AllowedIDChars.contains(C);
1403 } else {
1404 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1405 C99AllowedIDCharRanges);
1406 return C99AllowedIDChars.contains(C);
1407 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001408}
1409
Jordan Rose58c61e02013-02-09 01:10:25 +00001410static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1411 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001412 if (LangOpts.AsmPreprocessor) {
1413 return false;
1414 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001415 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1416 C11DisallowedInitialIDCharRanges);
1417 return !C11DisallowedInitialIDChars.contains(C);
1418 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001419 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001420 } else {
1421 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1422 C99DisallowedInitialIDCharRanges);
1423 return !C99DisallowedInitialIDChars.contains(C);
1424 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001425}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001426
Jordan Rose58c61e02013-02-09 01:10:25 +00001427static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1428 const char *End) {
1429 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1430 L.getSourceLocation(End));
1431}
1432
1433static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1434 CharSourceRange Range, bool IsFirst) {
1435 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001436 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001437 enum {
1438 CannotAppearInIdentifier = 0,
1439 CannotStartIdentifier
1440 };
1441
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001442 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1443 C99AllowedIDCharRanges);
1444 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1445 C99DisallowedInitialIDCharRanges);
1446 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001447 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1448 << Range
1449 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001450 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001451 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1452 << Range
1453 << CannotStartIdentifier;
1454 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001455 }
1456
Jordan Rose58c61e02013-02-09 01:10:25 +00001457 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001458 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001459 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1460 CXX03AllowedIDCharRanges);
1461 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001462 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1463 << Range;
1464 }
1465 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001466}
1467
1468bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1469 Token &Result) {
1470 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001471 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001472 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1473 return false;
1474
1475 if (!isLexingRawMode())
1476 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1477 makeCharRange(*this, CurPtr, UCNPtr),
1478 /*IsFirst=*/false);
1479
1480 Result.setFlag(Token::HasUCN);
1481 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1482 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1483 CurPtr = UCNPtr;
1484 else
1485 while (CurPtr != UCNPtr)
1486 (void)getAndAdvanceChar(CurPtr, Result);
1487 return true;
1488}
1489
1490bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1491 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001492 llvm::UTF32 CodePoint;
1493 llvm::ConversionResult Result =
1494 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1495 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001496 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001497 llvm::strictConversion);
1498 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001499 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1500 return false;
1501
1502 if (!isLexingRawMode())
1503 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1504 makeCharRange(*this, CurPtr, UnicodePtr),
1505 /*IsFirst=*/false);
1506
1507 CurPtr = UnicodePtr;
1508 return true;
1509}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001510
Eli Friedman0834a4b2013-09-19 00:41:32 +00001511bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001512 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1513 unsigned Size;
1514 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001515 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001516 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001517
Chris Lattner22eb9722006-06-18 05:43:12 +00001518 --CurPtr; // Back up over the skipped character.
1519
1520 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1521 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001522 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001523 // TODO: Could merge these checks into an InfoTable flag to make the
1524 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001525 if (isASCII(C) && C != '\\' && C != '?' &&
1526 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001527FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001528 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001529 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1530 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001531
Chris Lattner0f1f5052006-07-20 04:16:23 +00001532 // If we are in raw mode, return this identifier raw. There is no need to
1533 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001534 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001535 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001536
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001537 // Fill in Result.IdentifierInfo and update the token kind,
1538 // looking up the identifier in the identifier table.
1539 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerc5a00062006-06-18 16:41:01 +00001541 // Finally, now that we know we have an identifier, pass this off to the
1542 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001543 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001544 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001545
1546 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1547 && II->getPPKeywordID() == tok::pp_not_keyword
1548 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1549 // Return the code-completion token.
1550 Result.setKind(tok::code_completion);
1551 cutOffLexing();
1552 return true;
1553 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00001554 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001555 }
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattner22eb9722006-06-18 05:43:12 +00001557 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001558
Chris Lattner22eb9722006-06-18 05:43:12 +00001559 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001560 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001561 if (C == '$') {
1562 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001563 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001564
Chris Lattner22eb9722006-06-18 05:43:12 +00001565 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001566 if (!isLexingRawMode())
1567 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001568 CurPtr = ConsumeChar(CurPtr, Size, Result);
1569 C = getCharAndSize(CurPtr, Size);
1570 continue;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001571
Richard Smith8b7258b2014-02-17 21:52:30 +00001572 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001573 C = getCharAndSize(CurPtr, Size);
1574 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001575 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001576 C = getCharAndSize(CurPtr, Size);
1577 continue;
1578 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001579 goto FinishIdentifier;
1580 }
1581
1582 // Otherwise, this character is good, consume it.
1583 CurPtr = ConsumeChar(CurPtr, Size, Result);
1584
1585 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001586 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001587 CurPtr = ConsumeChar(CurPtr, Size, Result);
1588 C = getCharAndSize(CurPtr, Size);
1589 }
1590 }
1591}
1592
Douglas Gregor759ef232010-08-30 14:50:47 +00001593/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001594/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001595bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001596 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001597 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001598 if (C1 != '0')
1599 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001600 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001601 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001602}
Chris Lattner22eb9722006-06-18 05:43:12 +00001603
Nate Begeman5eee9332008-04-14 02:26:39 +00001604/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001605/// constant. From[-1] is the first character lexed. Return the end of the
1606/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001607bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001608 unsigned Size;
1609 char C = getCharAndSize(CurPtr, Size);
1610 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001611 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001612 CurPtr = ConsumeChar(CurPtr, Size, Result);
1613 PrevCh = C;
1614 C = getCharAndSize(CurPtr, Size);
1615 }
Mike Stump11289f42009-09-09 15:08:12 +00001616
Chris Lattner22eb9722006-06-18 05:43:12 +00001617 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001618 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1619 // If we are in Microsoft mode, don't continue if the constant is hex.
1620 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001621 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001622 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1623 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001624
1625 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001626 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001627 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001628 // not-quite-conforming extension. Only do so if this looks like it's
1629 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1630 bool IsHexFloat = true;
1631 if (!LangOpts.C99) {
1632 if (!isHexaLiteral(BufferPtr, LangOpts))
1633 IsHexFloat = false;
Richard Smith560a3572016-03-04 22:32:06 +00001634 else if (!getLangOpts().CPlusPlus1z &&
1635 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001636 IsHexFloat = false;
1637 }
1638 if (IsHexFloat)
1639 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1640 }
Mike Stump11289f42009-09-09 15:08:12 +00001641
Richard Smithfde94852013-09-26 03:33:06 +00001642 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001643 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001644 unsigned NextSize;
1645 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001646 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001647 if (!isLexingRawMode())
1648 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1649 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001650 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001651 return LexNumericConstant(Result, CurPtr);
1652 }
1653 }
1654
Richard Smith8b7258b2014-02-17 21:52:30 +00001655 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1656 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1657 return LexNumericConstant(Result, CurPtr);
1658 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1659 return LexNumericConstant(Result, CurPtr);
1660
Chris Lattnerd01e2912006-06-18 16:22:51 +00001661 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001662 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001663 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001664 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001665 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001666}
1667
Richard Smithe18f0fa2012-03-05 04:02:15 +00001668/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001669/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001670const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1671 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001672 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001673
Richard Smith8b7258b2014-02-17 21:52:30 +00001674 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001675 unsigned Size;
1676 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001677 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001678
Richard Smith8b7258b2014-02-17 21:52:30 +00001679 if (!isIdentifierHead(C)) {
1680 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1681 Consumed = true;
1682 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1683 Consumed = true;
1684 else
1685 return CurPtr;
1686 }
1687
1688 if (!getLangOpts().CPlusPlus11) {
1689 if (!isLexingRawMode())
1690 Diag(CurPtr,
1691 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1692 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1693 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1694 return CurPtr;
1695 }
1696
1697 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1698 // that does not start with an underscore is ill-formed. As a conforming
1699 // extension, we treat all such suffixes as if they had whitespace before
1700 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1701 // likely to be a ud-suffix than a macro, however, and accept that.
1702 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001703 bool IsUDSuffix = false;
1704 if (C == '_')
1705 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001706 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001707 // In C++1y, we need to look ahead a few characters to see if this is a
1708 // valid suffix for a string literal or a numeric literal (this could be
1709 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001710 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001711 char Buffer[MaxStandardSuffixLength] = { C };
1712 unsigned Consumed = Size;
1713 unsigned Chars = 1;
1714 while (true) {
1715 unsigned NextSize;
1716 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1717 getLangOpts());
1718 if (!isIdentifierBody(Next)) {
1719 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001720 const StringRef CompleteSuffix(Buffer, Chars);
1721 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1722 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001723 break;
1724 }
1725
1726 if (Chars == MaxStandardSuffixLength)
1727 // Too long: can't be a standard suffix.
1728 break;
1729
1730 Buffer[Chars++] = Next;
1731 Consumed += NextSize;
1732 }
Richard Smithf4198b72013-07-23 08:14:48 +00001733 }
1734
1735 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001736 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001737 Diag(CurPtr, getLangOpts().MSVCCompat
1738 ? diag::ext_ms_reserved_user_defined_literal
1739 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001740 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001741 return CurPtr;
1742 }
1743
Richard Smith8b7258b2014-02-17 21:52:30 +00001744 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001745 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001746
1747 Result.setFlag(Token::HasUDSuffix);
1748 while (true) {
1749 C = getCharAndSize(CurPtr, Size);
1750 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1751 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1752 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1753 else break;
1754 }
1755
Richard Smithe18f0fa2012-03-05 04:02:15 +00001756 return CurPtr;
1757}
1758
Chris Lattner22eb9722006-06-18 05:43:12 +00001759/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001760/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001761bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001762 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001763 // Does this string contain the \0 character?
1764 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001765
Richard Smithacd4d3d2011-10-15 01:18:56 +00001766 if (!isLexingRawMode() &&
1767 (Kind == tok::utf8_string_literal ||
1768 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001769 Kind == tok::utf32_string_literal))
1770 Diag(BufferPtr, getLangOpts().CPlusPlus
1771 ? diag::warn_cxx98_compat_unicode_literal
1772 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001773
Chris Lattner22eb9722006-06-18 05:43:12 +00001774 char C = getAndAdvanceChar(CurPtr, Result);
1775 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001776 // Skip escaped characters. Escaped newlines will already be processed by
1777 // getAndAdvanceChar.
1778 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001779 C = getAndAdvanceChar(CurPtr, Result);
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001780
Chris Lattner52d96ac2010-05-30 23:27:38 +00001781 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001782 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001784 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001785 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001786 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001787 }
Chris Lattner52d96ac2010-05-30 23:27:38 +00001788
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001789 if (C == 0) {
1790 if (isCodeCompletionPoint(CurPtr-1)) {
1791 PP->CodeCompleteNaturalLanguage();
1792 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001793 cutOffLexing();
1794 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001795 }
1796
Chris Lattner52d96ac2010-05-30 23:27:38 +00001797 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001798 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001799 C = getAndAdvanceChar(CurPtr, Result);
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Richard Smithe18f0fa2012-03-05 04:02:15 +00001802 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001803 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001804 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001805
Chris Lattner5a78a022006-07-20 06:02:19 +00001806 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001807 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001808 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001809
Chris Lattnerd01e2912006-06-18 16:22:51 +00001810 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001811 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001812 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001813 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001814 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001815}
1816
Craig Topper54edcca2011-08-11 04:06:15 +00001817/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1818/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001819bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001820 tok::TokenKind Kind) {
1821 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1822 // Between the initial and final double quote characters of the raw string,
1823 // any transformations performed in phases 1 and 2 (trigraphs,
1824 // universal-character-names, and line splicing) are reverted.
1825
Richard Smithacd4d3d2011-10-15 01:18:56 +00001826 if (!isLexingRawMode())
1827 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1828
Craig Topper54edcca2011-08-11 04:06:15 +00001829 unsigned PrefixLen = 0;
1830
1831 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1832 ++PrefixLen;
1833
1834 // If the last character was not a '(', then we didn't lex a valid delimiter.
1835 if (CurPtr[PrefixLen] != '(') {
1836 if (!isLexingRawMode()) {
1837 const char *PrefixEnd = &CurPtr[PrefixLen];
1838 if (PrefixLen == 16) {
1839 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1840 } else {
1841 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1842 << StringRef(PrefixEnd, 1);
1843 }
1844 }
1845
1846 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1847 // it's possible the '"' was intended to be part of the raw string, but
1848 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001849 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001850 char C = *CurPtr++;
1851
1852 if (C == '"')
1853 break;
1854 if (C == 0 && CurPtr-1 == BufferEnd) {
1855 --CurPtr;
1856 break;
1857 }
1858 }
1859
1860 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001861 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001862 }
1863
1864 // Save prefix and move CurPtr past it
1865 const char *Prefix = CurPtr;
1866 CurPtr += PrefixLen + 1; // skip over prefix and '('
1867
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001868 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001869 char C = *CurPtr++;
1870
1871 if (C == ')') {
1872 // Check for prefix match and closing quote.
1873 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1874 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1875 break;
1876 }
1877 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1878 if (!isLexingRawMode())
1879 Diag(BufferPtr, diag::err_unterminated_raw_string)
1880 << StringRef(Prefix, PrefixLen);
1881 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001882 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001883 }
1884 }
1885
Richard Smithe18f0fa2012-03-05 04:02:15 +00001886 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001887 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001888 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001889
Craig Topper54edcca2011-08-11 04:06:15 +00001890 // Update the location of token as well as BufferPtr.
1891 const char *TokStart = BufferPtr;
1892 FormTokenWithChars(Result, CurPtr, Kind);
1893 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001894 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001895}
1896
Chris Lattner22eb9722006-06-18 05:43:12 +00001897/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1898/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001899bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001900 // Does this string contain the \0 character?
1901 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00001902 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001903 char C = getAndAdvanceChar(CurPtr, Result);
1904 while (C != '>') {
1905 // Skip escaped characters.
Kostya Serebryany6c2479b2015-05-04 22:30:29 +00001906 if (C == '\\' && CurPtr < BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001907 // Skip the escaped character.
Dmitri Gribenko4aa05c52012-07-30 17:59:40 +00001908 getAndAdvanceChar(CurPtr, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00001909 } else if (C == '\n' || C == '\r' || // Newline.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001910 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1911 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00001912 // If the filename is unterminated, then it must just be a lone <
1913 // character. Return this as such.
1914 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001915 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001916 } else if (C == 0) {
1917 NulCharacter = CurPtr-1;
1918 }
1919 C = getAndAdvanceChar(CurPtr, Result);
1920 }
Mike Stump11289f42009-09-09 15:08:12 +00001921
Chris Lattner5a78a022006-07-20 06:02:19 +00001922 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001923 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001924 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00001925
Chris Lattnerd01e2912006-06-18 16:22:51 +00001926 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001927 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001928 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001929 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001930 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001931}
1932
Chris Lattner22eb9722006-06-18 05:43:12 +00001933/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00001934/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001935bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001936 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001937 // Does this character contain the \0 character?
1938 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00001939
Richard Smith3e3a7052014-11-08 06:08:42 +00001940 if (!isLexingRawMode()) {
1941 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1942 Diag(BufferPtr, getLangOpts().CPlusPlus
1943 ? diag::warn_cxx98_compat_unicode_literal
1944 : diag::warn_c99_compat_unicode_literal);
1945 else if (Kind == tok::utf8_char_constant)
1946 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1947 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00001948
Chris Lattner22eb9722006-06-18 05:43:12 +00001949 char C = getAndAdvanceChar(CurPtr, Result);
1950 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001951 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00001952 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00001953 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001954 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00001955 }
1956
1957 while (C != '\'') {
1958 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00001959 if (C == '\\')
1960 C = getAndAdvanceChar(CurPtr, Result);
1961
1962 if (C == '\n' || C == '\r' || // Newline.
1963 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001964 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001965 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00001966 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001967 return true;
Nico Weber4e270382012-11-17 20:25:54 +00001968 }
1969
1970 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001971 if (isCodeCompletionPoint(CurPtr-1)) {
1972 PP->CodeCompleteNaturalLanguage();
1973 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001974 cutOffLexing();
1975 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001976 }
1977
Chris Lattner86851b82010-07-07 23:24:27 +00001978 NulCharacter = CurPtr-1;
1979 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001980 C = getAndAdvanceChar(CurPtr, Result);
1981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Richard Smithe18f0fa2012-03-05 04:02:15 +00001983 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001984 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001985 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001986
Chris Lattner86851b82010-07-07 23:24:27 +00001987 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001988 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001989 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001990
Chris Lattnerd01e2912006-06-18 16:22:51 +00001991 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001992 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001993 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001994 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001995 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001996}
1997
1998/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1999/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002000///
2001/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2002///
Eli Friedman0834a4b2013-09-19 00:41:32 +00002003bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2004 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002005 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002006 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2007
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002008 unsigned char Char = *CurPtr;
2009
2010 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002011 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002012 // Skip horizontal whitespace very aggressively.
2013 while (isHorizontalWhitespace(Char))
2014 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002015
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002016 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002017 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002018 break;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Chris Lattner22eb9722006-06-18 05:43:12 +00002020 if (ParsingPreprocessorDirective) {
2021 // End of preprocessor directive line, let LexTokenInternal handle this.
2022 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002023 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002024 }
Mike Stump11289f42009-09-09 15:08:12 +00002025
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002026 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002027 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002028 Char = *++CurPtr;
2029 }
2030
Chris Lattner4d963442008-10-12 04:05:48 +00002031 // If the client wants us to return whitespace, return it now.
2032 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002033 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002034 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002035 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002036 IsAtPhysicalStartOfLine = true;
2037 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002038 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002039 return true;
2040 }
Mike Stump11289f42009-09-09 15:08:12 +00002041
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002042 // If this isn't immediately after a newline, there is leading space.
2043 char PrevChar = CurPtr[-1];
2044 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2045
2046 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002047 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002048 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002049 TokAtPhysicalStartOfLine = true;
2050 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002051
Chris Lattner22eb9722006-06-18 05:43:12 +00002052 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002053 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002054}
2055
Nico Weber158a31a2012-11-11 07:02:14 +00002056/// We have just read the // characters from input. Skip until we find the
2057/// newline character thats terminate the comment. Then update BufferPtr and
2058/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002059///
2060/// If we're in KeepCommentMode or any CommentHandler has inserted
2061/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002062bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2063 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002064 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002065 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002066 if (!LangOpts.LineComment && !isLexingRawMode()) {
2067 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002068
Chris Lattner22eb9722006-06-18 05:43:12 +00002069 // Mark them enabled so we only emit one warning for this translation
2070 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002071 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattner22eb9722006-06-18 05:43:12 +00002074 // Scan over the body of the comment. The common case, when scanning, is that
2075 // the comment contains normal ascii characters with nothing interesting in
2076 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002077 //
2078 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2079 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002080 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002081 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002082 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002083 // Skip over characters in the fast loop.
2084 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002085 C != '\n' && C != '\r') // Newline or DOS-style newline.
2086 C = *++CurPtr;
2087
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002088 const char *NextLine = CurPtr;
2089 if (C != 0) {
2090 // We found a newline, see if it's escaped.
2091 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002092 bool HasSpace = false;
2093 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002094 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002095 HasSpace = true;
2096 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002097
Richard Smith4c132e52017-04-18 21:45:04 +00002098 if (*EscapePtr == '\\')
2099 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002100 CurPtr = EscapePtr;
2101 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002102 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2103 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002104 CurPtr = EscapePtr-2;
2105 else
2106 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002107
2108 // If there was space between the backslash and newline, warn about it.
2109 if (HasSpace && !isLexingRawMode())
2110 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
Chris Lattner22eb9722006-06-18 05:43:12 +00002113 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002114 // properly decode the character. Read it in raw mode to avoid emitting
2115 // diagnostics about things like trigraphs. If we see an escaped newline,
2116 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002117 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002118 bool OldRawMode = isLexingRawMode();
2119 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002120 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002121 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002122
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002123 // If we only read only one character, then no special handling is needed.
2124 // We're done and can skip forward to the newline.
2125 if (C != 0 && CurPtr == OldPtr+1) {
2126 CurPtr = NextLine;
2127 break;
2128 }
2129
Chris Lattner22eb9722006-06-18 05:43:12 +00002130 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002131 // \n, then we had an escaped newline within the comment. Emit diagnostic
2132 // unless the next line is also a // comment.
2133 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
Chris Lattner22eb9722006-06-18 05:43:12 +00002134 for (; OldPtr != CurPtr; ++OldPtr)
2135 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002136 // Okay, we found a // comment that ends in a newline, if the next
2137 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002138 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002139 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002140 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002141 ++ForwardPtr;
2142 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2143 break;
2144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner6d27a162008-11-22 02:02:22 +00002146 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002147 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002148 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002149 }
2150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
Richard Smith1d2ae942017-04-17 23:44:51 +00002152 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2153 --CurPtr;
2154 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002155 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002156
2157 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2158 PP->CodeCompleteNaturalLanguage();
2159 cutOffLexing();
2160 return false;
2161 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002162 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002163
Chris Lattner93ddf802010-02-03 21:06:21 +00002164 // Found but did not consume the newline. Notify comment handlers about the
2165 // comment unless we're in a #if 0 block.
2166 if (PP && !isLexingRawMode() &&
2167 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2168 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002169 BufferPtr = CurPtr;
2170 return true; // A token has to be returned.
2171 }
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattner457fc152006-07-29 06:30:25 +00002173 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002174 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002175 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002176
2177 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002178 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002179 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002180 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002181 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Chris Lattner22eb9722006-06-18 05:43:12 +00002184 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002185 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002186 // contribute to another token), it isn't needed for correctness. Note that
2187 // this is ok even in KeepWhitespaceMode, because we would have returned the
2188 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002189 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002190
Chris Lattner22eb9722006-06-18 05:43:12 +00002191 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002192 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002193 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002194 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002195 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002196 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002197 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002198}
Chris Lattner22eb9722006-06-18 05:43:12 +00002199
Nico Weber158a31a2012-11-11 07:02:14 +00002200/// If in save-comment mode, package up this Line comment in an appropriate
2201/// way and return it.
2202bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002203 // If we're not in a preprocessor directive, just return the // comment
2204 // directly.
2205 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002206
David Blaikied5321242012-06-06 18:52:13 +00002207 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002208 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002209
Nico Weber158a31a2012-11-11 07:02:14 +00002210 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002211 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002212 bool Invalid = false;
2213 std::string Spelling = PP->getSpelling(Result, &Invalid);
2214 if (Invalid)
2215 return true;
2216
Nico Weber158a31a2012-11-11 07:02:14 +00002217 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002218 Spelling[1] = '*'; // Change prefix to "/*".
2219 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002220
Chris Lattnerb11c3232008-10-12 04:51:35 +00002221 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002222 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002223 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002224 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002225}
2226
Chris Lattnercb283342006-06-18 06:48:37 +00002227/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002228/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2229/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002230static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002231 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002232 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattner22eb9722006-06-18 05:43:12 +00002234 // Back up off the newline.
2235 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Chris Lattner22eb9722006-06-18 05:43:12 +00002237 // If this is a two-character newline sequence, skip the other character.
2238 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2239 // \n\n or \r\r -> not escaped newline.
2240 if (CurPtr[0] == CurPtr[1])
2241 return false;
2242 // \n\r or \r\n -> skip the newline.
2243 --CurPtr;
2244 }
Mike Stump11289f42009-09-09 15:08:12 +00002245
Chris Lattner22eb9722006-06-18 05:43:12 +00002246 // If we have horizontal whitespace, skip over it. We allow whitespace
2247 // between the slash and newline.
2248 bool HasSpace = false;
2249 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2250 --CurPtr;
2251 HasSpace = true;
2252 }
Mike Stump11289f42009-09-09 15:08:12 +00002253
Chris Lattner22eb9722006-06-18 05:43:12 +00002254 // If we have a slash, we know this is an escaped newline.
2255 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002256 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002257 } else {
2258 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002259 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2260 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002261 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattnercb283342006-06-18 06:48:37 +00002263 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002264 CurPtr -= 2;
2265
2266 // If no trigraphs are enabled, warn that we ignored this trigraph and
2267 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002268 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002269 if (!L->isLexingRawMode())
2270 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002271 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002272 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002273 if (!L->isLexingRawMode())
2274 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002275 }
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chris Lattner22eb9722006-06-18 05:43:12 +00002277 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002278 if (!L->isLexingRawMode())
2279 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002280
Chris Lattner22eb9722006-06-18 05:43:12 +00002281 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002282 if (HasSpace && !L->isLexingRawMode())
2283 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnercb283342006-06-18 06:48:37 +00002285 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002286}
2287
Chris Lattneraded4a92006-10-27 04:42:31 +00002288#ifdef __SSE2__
2289#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002290#elif __ALTIVEC__
2291#include <altivec.h>
2292#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002293#endif
2294
James Dennettf442d242012-06-17 03:40:43 +00002295/// We have just read from input the / and * characters that started a comment.
2296/// Read until we find the * and / characters that terminate the comment.
2297/// Note that we don't bother decoding trigraphs or escaped newlines in block
2298/// comments, because they cannot cause the comment to end. The only thing
2299/// that can happen is the comment could end with an escaped newline between
2300/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002301///
Chris Lattner87d02082010-01-18 22:35:47 +00002302/// If we're in KeepCommentMode or any CommentHandler has inserted
2303/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002304bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2305 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002306 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002307 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002308 // optimization helps people who like to put a lot of * characters in their
2309 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002310
2311 // The first character we get with newlines and trigraphs skipped to handle
2312 // the degenerate /*/ case below correctly if the * has an escaped newline
2313 // after it.
2314 unsigned CharSize;
2315 unsigned char C = getCharAndSize(CurPtr, CharSize);
2316 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002317 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002318 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002319 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002320 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002321
Chris Lattner99e7d232008-10-12 04:19:49 +00002322 // KeepWhitespaceMode should return this broken comment as a token. Since
2323 // it isn't a well formed comment, just return it as an 'unknown' token.
2324 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002325 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002326 return true;
2327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Chris Lattner99e7d232008-10-12 04:19:49 +00002329 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002330 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002331 }
Mike Stump11289f42009-09-09 15:08:12 +00002332
Chris Lattnerc850ad62007-07-21 23:43:37 +00002333 // Check to see if the first character after the '/*' is another /. If so,
2334 // then this slash does not end the block comment, it is part of it.
2335 if (C == '/')
2336 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002337
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002338 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002339 // Skip over all non-interesting characters until we find end of buffer or a
2340 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002341 if (CurPtr + 24 < BufferEnd &&
2342 // If there is a code-completion point avoid the fast scan because it
2343 // doesn't check for '\0'.
2344 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002345 // While not aligned to a 16-byte boundary.
2346 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2347 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002348
Chris Lattner6cc3e362006-10-27 04:12:35 +00002349 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002350
2351#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002352 __m128i Slashes = _mm_set1_epi8('/');
2353 while (CurPtr+16 <= BufferEnd) {
2354 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2355 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002356 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002357 // Adjust the pointer to point directly after the first slash. It's
2358 // not necessary to set C here, it will be overwritten at the end of
2359 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002360 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002361 goto FoundSlash;
2362 }
Roman Divacky61509902014-04-03 18:04:52 +00002363 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002364 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002365#elif __ALTIVEC__
2366 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002367 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002368 '/', '/', '/', '/', '/', '/', '/', '/'
2369 };
2370 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002371 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002372 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002373#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002374 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002375 while (CurPtr[0] != '/' &&
2376 CurPtr[1] != '/' &&
2377 CurPtr[2] != '/' &&
2378 CurPtr[3] != '/' &&
2379 CurPtr+4 < BufferEnd) {
2380 CurPtr += 4;
2381 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002382#endif
Mike Stump11289f42009-09-09 15:08:12 +00002383
Chris Lattneraded4a92006-10-27 04:42:31 +00002384 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002385 C = *CurPtr++;
2386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Chris Lattneraded4a92006-10-27 04:42:31 +00002388 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002389 while (C != '/' && C != '\0')
2390 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002391
Chris Lattner22eb9722006-06-18 05:43:12 +00002392 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002393 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002394 if (CurPtr[-2] == '*') // We found the final */. We're done!
2395 break;
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chris Lattner22eb9722006-06-18 05:43:12 +00002397 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002398 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002399 // We found the final */, though it had an escaped newline between the
2400 // * and /. We're done!
2401 break;
2402 }
2403 }
2404 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2405 // If this is a /* inside of the comment, emit a warning. Don't do this
2406 // if this is a /*/, which will end the comment. This misses cases with
2407 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002408 if (!isLexingRawMode())
2409 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002410 }
2411 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002412 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002413 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002414 // Note: the user probably forgot a */. We could continue immediately
2415 // after the /*, but this would involve lexing a lot of what really is the
2416 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002417 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002418
Chris Lattner99e7d232008-10-12 04:19:49 +00002419 // KeepWhitespaceMode should return this broken comment as a token. Since
2420 // it isn't a well formed comment, just return it as an 'unknown' token.
2421 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002422 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002423 return true;
2424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Chris Lattner99e7d232008-10-12 04:19:49 +00002426 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002427 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002428 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2429 PP->CodeCompleteNaturalLanguage();
2430 cutOffLexing();
2431 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002432 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002433
Chris Lattner22eb9722006-06-18 05:43:12 +00002434 C = *CurPtr++;
2435 }
Mike Stump11289f42009-09-09 15:08:12 +00002436
Chris Lattner93ddf802010-02-03 21:06:21 +00002437 // Notify comment handlers about the comment unless we're in a #if 0 block.
2438 if (PP && !isLexingRawMode() &&
2439 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2440 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002441 BufferPtr = CurPtr;
2442 return true; // A token has to be returned.
2443 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002444
Chris Lattner457fc152006-07-29 06:30:25 +00002445 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002446 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002447 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002448 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002449 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002450
2451 // It is common for the tokens immediately after a /**/ comment to be
2452 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002453 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2454 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002455 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002456 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002457 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002458 }
2459
2460 // Otherwise, just return so that the next character will be lexed as a token.
2461 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002462 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002463 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002464}
2465
2466//===----------------------------------------------------------------------===//
2467// Primary Lexing Entry Points
2468//===----------------------------------------------------------------------===//
2469
Chris Lattner22eb9722006-06-18 05:43:12 +00002470/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2471/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002472void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002473 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2474 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002475 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002476
2477 // CurPtr - Cache BufferPtr in an automatic variable.
2478 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002479 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002480 char Char = getAndAdvanceChar(CurPtr, Tmp);
2481 switch (Char) {
2482 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002483 if (Result)
2484 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002485 break;
2486 case 0: // Null.
2487 // Found end of file?
2488 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002489 if (isCodeCompletionPoint(CurPtr-1)) {
2490 PP->CodeCompleteNaturalLanguage();
2491 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002492 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002493 }
2494
Chris Lattner22eb9722006-06-18 05:43:12 +00002495 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002496 if (Result)
2497 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002498 break;
2499 }
2500 // FALL THROUGH.
2501 case '\r':
2502 case '\n':
2503 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2504 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2505 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002506
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002507 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002508 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002509 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002510 if (PP)
2511 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002512 Lex(Tmp);
2513 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002514 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002515
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002516 // Finally, we're done;
2517 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002518 }
2519 }
2520}
2521
2522/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2523/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002524/// This returns true if Result contains a token, false if PP.Lex should be
2525/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002526bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002527 // If we hit the end of the file while parsing a preprocessor directive,
2528 // end the preprocessor directive first. The next token returned will
2529 // then be the end of file.
2530 if (ParsingPreprocessorDirective) {
2531 // Done parsing the "line".
2532 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002533 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002534 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002535
Chris Lattner457fc152006-07-29 06:30:25 +00002536 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002537 if (PP)
2538 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002539 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002540 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002541
Chris Lattner30a2fa12006-07-19 06:31:49 +00002542 // If we are in raw mode, return this event as an EOF token. Let the caller
2543 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002544 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002545 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002546 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002547 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002548 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002549 }
Douglas Gregor3545ff42009-09-21 16:56:56 +00002550
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002551 if (PP->isRecordingPreamble() && !PP->isInMainFile()) {
2552 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2553 ConditionalStack.clear();
2554 }
2555
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002556 // Issue diagnostics for unterminated #if and missing newline.
2557
Chris Lattner30a2fa12006-07-19 06:31:49 +00002558 // If we are in a #if directive, emit an error.
2559 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002560 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002561 PP->Diag(ConditionalStack.back().IfLoc,
2562 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002563 ConditionalStack.pop_back();
2564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Chris Lattner8f96d042008-04-12 05:54:25 +00002566 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2567 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002568 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2569 DiagnosticsEngine &Diags = PP->getDiagnostics();
2570 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2571 unsigned DiagID;
2572
2573 if (LangOpts.CPlusPlus11) {
2574 // C++11 [lex.phases] 2.2 p2
2575 // Prefer the C++98 pedantic compatibility warning over the generic,
2576 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002577 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002578 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2579 } else {
2580 DiagID = diag::warn_no_newline_eof;
2581 }
2582 } else {
2583 DiagID = diag::ext_no_newline_eof;
2584 }
2585
2586 Diag(BufferEnd, DiagID)
2587 << FixItHint::CreateInsertion(EndLoc, "\n");
2588 }
Mike Stump11289f42009-09-09 15:08:12 +00002589
Chris Lattner22eb9722006-06-18 05:43:12 +00002590 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002591
2592 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002593 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002594}
2595
Chris Lattner678c8802006-07-11 05:46:12 +00002596/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2597/// the specified lexer will return a tok::l_paren token, 0 if it is something
2598/// else and 2 if there are no more tokens in the buffer controlled by the
2599/// lexer.
2600unsigned Lexer::isNextPPTokenLParen() {
2601 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002602
Chris Lattner678c8802006-07-11 05:46:12 +00002603 // Switch to 'skipping' mode. This will ensure that we can lex a token
2604 // without emitting diagnostics, disables macro expansion, and will cause EOF
2605 // to return an EOF token instead of popping the include stack.
2606 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002607
Chris Lattner678c8802006-07-11 05:46:12 +00002608 // Save state that can be changed while lexing so that we can restore it.
2609 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002610 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002611 bool atStartOfLine = IsAtStartOfLine;
2612 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2613 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002614
Chris Lattner146762e2007-07-20 16:59:19 +00002615 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002616 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002617
Chris Lattner678c8802006-07-11 05:46:12 +00002618 // Restore state that may have changed.
2619 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002620 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002621 HasLeadingSpace = leadingSpace;
2622 IsAtStartOfLine = atStartOfLine;
2623 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattner678c8802006-07-11 05:46:12 +00002625 // Restore the lexer back to non-skipping mode.
2626 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002627
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002628 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002629 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002630 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002631}
2632
James Dennettf442d242012-06-17 03:40:43 +00002633/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002634static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2635 ConflictMarkerKind CMK) {
2636 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2637 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002638 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002639 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002640 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002641 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002642 if (Pos == 0 ||
2643 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002644 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2645 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002646 continue;
2647 }
2648 return RestOfBuffer.data()+Pos;
2649 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002650 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002651}
2652
2653/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2654/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2655/// and recover nicely. This returns true if it is a conflict marker and false
2656/// if not.
2657bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2658 // Only a conflict marker if it starts at the beginning of a line.
2659 if (CurPtr != BufferStart &&
2660 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2661 return false;
2662
Richard Smitha9e33d42011-10-12 00:37:51 +00002663 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002664 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2665 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002666 return false;
2667
2668 // If we have a situation where we don't care about conflict markers, ignore
2669 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002670 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002671 return false;
2672
Richard Smitha9e33d42011-10-12 00:37:51 +00002673 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2674
2675 // Check to see if there is an ending marker somewhere in the buffer at the
2676 // start of a line to terminate this conflict marker.
2677 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002678 // We found a match. We are really in a conflict marker.
2679 // Diagnose this, and ignore to the end of line.
2680 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002681 CurrentConflictMarkerState = Kind;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002682
2683 // Skip ahead to the end of line. We know this exists because the
2684 // end-of-conflict marker starts with \r or \n.
2685 while (*CurPtr != '\r' && *CurPtr != '\n') {
2686 assert(CurPtr != BufferEnd && "Didn't find end of line");
2687 ++CurPtr;
2688 }
2689 BufferPtr = CurPtr;
2690 return true;
2691 }
2692
2693 // No end of conflict marker found.
2694 return false;
2695}
2696
Richard Smitha9e33d42011-10-12 00:37:51 +00002697/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2698/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2699/// is the end of a conflict marker. Handle it by ignoring up until the end of
2700/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002701bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2702 // Only a conflict marker if it starts at the beginning of a line.
2703 if (CurPtr != BufferStart &&
2704 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2705 return false;
2706
2707 // If we have a situation where we don't care about conflict markers, ignore
2708 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002709 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002710 return false;
2711
Richard Smitha9e33d42011-10-12 00:37:51 +00002712 // Check to see if we have the marker (4 characters in a row).
2713 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002714 if (CurPtr[i] != CurPtr[0])
2715 return false;
2716
2717 // If we do have it, search for the end of the conflict marker. This could
2718 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2719 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002720 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2721 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002722 CurPtr = End;
2723
2724 // Skip ahead to the end of line.
2725 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2726 ++CurPtr;
2727
2728 BufferPtr = CurPtr;
2729
2730 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002731 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002732 return true;
2733 }
2734
2735 return false;
2736}
2737
Alex Lorenz1be800c52017-04-19 08:58:56 +00002738static const char *findPlaceholderEnd(const char *CurPtr,
2739 const char *BufferEnd) {
2740 if (CurPtr == BufferEnd)
2741 return nullptr;
2742 BufferEnd -= 1; // Scan until the second last character.
2743 for (; CurPtr != BufferEnd; ++CurPtr) {
2744 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2745 return CurPtr + 2;
2746 }
2747 return nullptr;
2748}
2749
2750bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2751 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2752 if (!PP || LexingRawMode)
2753 return false;
2754 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2755 if (!End)
2756 return false;
2757 const char *Start = CurPtr - 1;
2758 if (!LangOpts.AllowEditorPlaceholders)
2759 Diag(Start, diag::err_placeholder_in_source);
2760 Result.startToken();
2761 FormTokenWithChars(Result, End, tok::raw_identifier);
2762 Result.setRawIdentifierData(Start);
2763 PP->LookUpIdentifierInfo(Result);
2764 Result.setFlag(Token::IsEditorPlaceholder);
2765 BufferPtr = End;
2766 return true;
2767}
2768
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002769bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2770 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002771 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002772 return Loc == PP->getCodeCompletionLoc();
2773 }
2774
2775 return false;
2776}
2777
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002778uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2779 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002780 unsigned CharSize;
2781 char Kind = getCharAndSize(StartPtr, CharSize);
2782
2783 unsigned NumHexDigits;
2784 if (Kind == 'u')
2785 NumHexDigits = 4;
2786 else if (Kind == 'U')
2787 NumHexDigits = 8;
2788 else
2789 return 0;
2790
Jordan Rosec0cba272013-01-27 20:12:04 +00002791 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002792 if (Result && !isLexingRawMode())
2793 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002794 return 0;
2795 }
2796
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002797 const char *CurPtr = StartPtr + CharSize;
2798 const char *KindLoc = &CurPtr[-1];
2799
2800 uint32_t CodePoint = 0;
2801 for (unsigned i = 0; i < NumHexDigits; ++i) {
2802 char C = getCharAndSize(CurPtr, CharSize);
2803
2804 unsigned Value = llvm::hexDigitValue(C);
2805 if (Value == -1U) {
2806 if (Result && !isLexingRawMode()) {
2807 if (i == 0) {
2808 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2809 << StringRef(KindLoc, 1);
2810 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002811 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002812
2813 // If the user wrote \U1234, suggest a fixit to \u.
2814 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002815 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002816 Diag(KindLoc, diag::note_ucn_four_not_eight)
2817 << FixItHint::CreateReplacement(URange, "u");
2818 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002819 }
2820 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002821
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002822 return 0;
2823 }
2824
2825 CodePoint <<= 4;
2826 CodePoint += Value;
2827
2828 CurPtr += CharSize;
2829 }
2830
2831 if (Result) {
2832 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002833 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002834 StartPtr = CurPtr;
2835 else
2836 while (StartPtr != CurPtr)
2837 (void)getAndAdvanceChar(StartPtr, *Result);
2838 } else {
2839 StartPtr = CurPtr;
2840 }
2841
Justin Bogner53535132013-10-21 05:02:28 +00002842 // Don't apply C family restrictions to UCNs in assembly mode
2843 if (LangOpts.AsmPreprocessor)
2844 return CodePoint;
2845
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002846 // C99 6.4.3p2: A universal character name shall not specify a character whose
2847 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2848 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2849 // C++11 [lex.charset]p2: If the hexadecimal value for a
2850 // universal-character-name corresponds to a surrogate code point (in the
2851 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2852 // if the hexadecimal value for a universal-character-name outside the
2853 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2854 // string literal corresponds to a control character (in either of the
2855 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2856 // basic source character set, the program is ill-formed.
2857 if (CodePoint < 0xA0) {
2858 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2859 return CodePoint;
2860
2861 // We don't use isLexingRawMode() here because we need to warn about bad
2862 // UCNs even when skipping preprocessing tokens in a #if block.
2863 if (Result && PP) {
2864 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2865 Diag(BufferPtr, diag::err_ucn_control_character);
2866 else {
2867 char C = static_cast<char>(CodePoint);
2868 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2869 }
2870 }
2871
2872 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002873
2874 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002875 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002876 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002877 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002878 if (Result && PP) {
2879 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2880 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2881 else
2882 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2883 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002884 return 0;
2885 }
2886
2887 return CodePoint;
2888}
2889
Eli Friedman0834a4b2013-09-19 00:41:32 +00002890bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2891 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002892 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2893 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00002894 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00002895 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00002896 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00002897 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00002898
2899 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002900 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00002901 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00002902 return false;
2903}
Jordan Rose4246ae02013-01-24 20:50:50 +00002904
Eli Friedman0834a4b2013-09-19 00:41:32 +00002905bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002906 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2907 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2908 !PP->isPreprocessedOutput()) {
2909 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2910 makeCharRange(*this, BufferPtr, CurPtr),
2911 /*IsFirst=*/true);
2912 }
2913
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002914 MIOpt.ReadToken();
2915 return LexIdentifier(Result, CurPtr);
2916 }
2917
Jordan Rosecc538342013-01-31 19:48:48 +00002918 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2919 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00002920 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002921 // Non-ASCII characters tend to creep into source code unintentionally.
2922 // Instead of letting the parser complain about the unknown token,
2923 // just drop the character.
2924 // Note that we can /only/ do this when the non-ASCII character is actually
2925 // spelled as Unicode, not written as a UCN. The standard requires that
2926 // we not throw away any possible preprocessor tokens, but there's a
2927 // loophole in the mapping of Unicode characters to basic character set
2928 // characters that allows us to map these particular characters to, say,
2929 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00002930 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00002931 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002932
2933 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002934 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002935 }
2936
2937 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2938 // up by accident.
2939 MIOpt.ReadToken();
2940 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002941 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002942}
2943
Eli Friedman0834a4b2013-09-19 00:41:32 +00002944void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2945 IsAtStartOfLine = Result.isAtStartOfLine();
2946 HasLeadingSpace = Result.hasLeadingSpace();
2947 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2948 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2949}
2950
2951bool Lexer::Lex(Token &Result) {
2952 // Start a new token.
2953 Result.startToken();
2954
2955 // Set up misc whitespace flags for LexTokenInternal.
2956 if (IsAtStartOfLine) {
2957 Result.setFlag(Token::StartOfLine);
2958 IsAtStartOfLine = false;
2959 }
2960
2961 if (HasLeadingSpace) {
2962 Result.setFlag(Token::LeadingSpace);
2963 HasLeadingSpace = false;
2964 }
2965
2966 if (HasLeadingEmptyMacro) {
2967 Result.setFlag(Token::LeadingEmptyMacro);
2968 HasLeadingEmptyMacro = false;
2969 }
2970
2971 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2972 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00002973 bool isRawLex = isLexingRawMode();
2974 (void) isRawLex;
2975 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2976 // (After the LexTokenInternal call, the lexer might be destroyed.)
2977 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2978 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002979}
Chris Lattner22eb9722006-06-18 05:43:12 +00002980
2981/// LexTokenInternal - This implements a simple C family lexer. It is an
2982/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00002983/// has a null character at the end of the file. This returns a preprocessing
2984/// token, not a normal token, as such, it is an internal interface. It assumes
2985/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002986bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002987LexNextToken:
2988 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00002989 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00002990 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00002991
Chris Lattner22eb9722006-06-18 05:43:12 +00002992 // CurPtr - Cache BufferPtr in an automatic variable.
2993 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002994
Chris Lattnereb54b592006-07-10 06:34:27 +00002995 // Small amounts of horizontal whitespace is very common between tokens.
2996 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2997 ++CurPtr;
2998 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2999 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003000
Chris Lattner4d963442008-10-12 04:05:48 +00003001 // If we are keeping whitespace and other tokens, just return what we just
3002 // skipped. The next lexer invocation will return the token after the
3003 // whitespace.
3004 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003005 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003006 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003007 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003008 }
Mike Stump11289f42009-09-09 15:08:12 +00003009
Chris Lattnereb54b592006-07-10 06:34:27 +00003010 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003011 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattner22eb9722006-06-18 05:43:12 +00003014 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003015
Chris Lattner22eb9722006-06-18 05:43:12 +00003016 // Read a character, advancing over it.
3017 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003018 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003019
Chris Lattner22eb9722006-06-18 05:43:12 +00003020 switch (Char) {
3021 case 0: // Null.
3022 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003023 if (CurPtr-1 == BufferEnd)
3024 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003025
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003026 // Check if we are performing code completion.
3027 if (isCodeCompletionPoint(CurPtr-1)) {
3028 // Return the code-completion token.
3029 Result.startToken();
3030 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003031 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003032 }
3033
Chris Lattner6d27a162008-11-22 02:02:22 +00003034 if (!isLexingRawMode())
3035 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003036 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003037 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3038 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003039
Eli Friedman0834a4b2013-09-19 00:41:32 +00003040 // We know the lexer hasn't changed, so just try again with this lexer.
3041 // (We manually eliminate the tail call to avoid recursion.)
3042 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003043
3044 case 26: // DOS & CP/M EOF: "^Z".
3045 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003046 if (LangOpts.MicrosoftExt) {
3047 if (!isLexingRawMode())
3048 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003049 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003050 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003051
Chris Lattner3dfff972009-12-17 05:29:40 +00003052 // If Microsoft extensions are disabled, this is just random garbage.
3053 Kind = tok::unknown;
3054 break;
3055
Chris Lattner22eb9722006-06-18 05:43:12 +00003056 case '\n':
3057 case '\r':
3058 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003059 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003060 if (ParsingPreprocessorDirective) {
3061 // Done parsing the "line".
3062 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003063
Chris Lattner457fc152006-07-29 06:30:25 +00003064 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003065 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003066 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003067
Chris Lattner22eb9722006-06-18 05:43:12 +00003068 // Since we consumed a newline, we are back at the start of a line.
3069 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003070 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003071
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003072 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003073 break;
3074 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003075
Chris Lattner22eb9722006-06-18 05:43:12 +00003076 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003077 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003078
Eli Friedman0834a4b2013-09-19 00:41:32 +00003079 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3080 return true; // KeepWhitespaceMode
3081
3082 // We only saw whitespace, so just try again with this lexer.
3083 // (We manually eliminate the tail call to avoid recursion.)
3084 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003085 case ' ':
3086 case '\t':
3087 case '\f':
3088 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003089 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003090 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003091 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3092 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003093
3094 SkipIgnoredUnits:
3095 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003096
Chris Lattnerb9b85972007-07-22 06:29:05 +00003097 // If the next token is obviously a // or /* */ comment, skip it efficiently
3098 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003099 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003100 LangOpts.LineComment &&
3101 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003102 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3103 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003104 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003105 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003106 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3107 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003108 goto SkipIgnoredUnits;
3109 } else if (isHorizontalWhitespace(*CurPtr)) {
3110 goto SkipHorizontalWhitespace;
3111 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003112 // We only saw whitespace, so just try again with this lexer.
3113 // (We manually eliminate the tail call to avoid recursion.)
3114 goto LexNextToken;
Chris Lattner3dfff972009-12-17 05:29:40 +00003115
Chris Lattner2b15cf72008-01-03 17:58:54 +00003116 // C99 6.4.4.1: Integer Constants.
3117 // C99 6.4.4.2: Floating Constants.
3118 case '0': case '1': case '2': case '3': case '4':
3119 case '5': case '6': case '7': case '8': case '9':
3120 // Notify MIOpt that we read a non-whitespace/non-comment token.
3121 MIOpt.ReadToken();
3122 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003123
Richard Smith9b362092013-03-09 23:56:02 +00003124 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003125 // Notify MIOpt that we read a non-whitespace/non-comment token.
3126 MIOpt.ReadToken();
3127
Richard Smith9b362092013-03-09 23:56:02 +00003128 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003129 Char = getCharAndSize(CurPtr, SizeTmp);
3130
3131 // UTF-16 string literal
3132 if (Char == '"')
3133 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3134 tok::utf16_string_literal);
3135
3136 // UTF-16 character constant
3137 if (Char == '\'')
3138 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3139 tok::utf16_char_constant);
3140
Craig Topper54edcca2011-08-11 04:06:15 +00003141 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003142 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3143 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003144 return LexRawStringLiteral(Result,
3145 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3146 SizeTmp2, Result),
3147 tok::utf16_string_literal);
3148
3149 if (Char == '8') {
3150 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3151
3152 // UTF-8 string literal
3153 if (Char2 == '"')
3154 return LexStringLiteral(Result,
3155 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3156 SizeTmp2, Result),
3157 tok::utf8_string_literal);
Richard Smith3e3a7052014-11-08 06:08:42 +00003158 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3159 return LexCharConstant(
3160 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3161 SizeTmp2, Result),
3162 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003163
Richard Smith9b362092013-03-09 23:56:02 +00003164 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003165 unsigned SizeTmp3;
3166 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3167 // UTF-8 raw string literal
3168 if (Char3 == '"') {
3169 return LexRawStringLiteral(Result,
3170 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3171 SizeTmp2, Result),
3172 SizeTmp3, Result),
3173 tok::utf8_string_literal);
3174 }
3175 }
3176 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003177 }
3178
3179 // treat u like the start of an identifier.
3180 return LexIdentifier(Result, CurPtr);
3181
Richard Smith9b362092013-03-09 23:56:02 +00003182 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003183 // Notify MIOpt that we read a non-whitespace/non-comment token.
3184 MIOpt.ReadToken();
3185
Richard Smith9b362092013-03-09 23:56:02 +00003186 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003187 Char = getCharAndSize(CurPtr, SizeTmp);
3188
3189 // UTF-32 string literal
3190 if (Char == '"')
3191 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3192 tok::utf32_string_literal);
3193
3194 // UTF-32 character constant
3195 if (Char == '\'')
3196 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3197 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003198
3199 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003200 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3201 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003202 return LexRawStringLiteral(Result,
3203 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3204 SizeTmp2, Result),
3205 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003206 }
3207
3208 // treat U like the start of an identifier.
3209 return LexIdentifier(Result, CurPtr);
3210
Craig Topper54edcca2011-08-11 04:06:15 +00003211 case 'R': // Identifier or C++0x raw string literal
3212 // Notify MIOpt that we read a non-whitespace/non-comment token.
3213 MIOpt.ReadToken();
3214
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003215 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003216 Char = getCharAndSize(CurPtr, SizeTmp);
3217
3218 if (Char == '"')
3219 return LexRawStringLiteral(Result,
3220 ConsumeChar(CurPtr, SizeTmp, Result),
3221 tok::string_literal);
3222 }
3223
3224 // treat R like the start of an identifier.
3225 return LexIdentifier(Result, CurPtr);
3226
Chris Lattner2b15cf72008-01-03 17:58:54 +00003227 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003228 // Notify MIOpt that we read a non-whitespace/non-comment token.
3229 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003230 Char = getCharAndSize(CurPtr, SizeTmp);
3231
3232 // Wide string literal.
3233 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003234 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003235 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003236
Craig Topper54edcca2011-08-11 04:06:15 +00003237 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003238 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003239 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3240 return LexRawStringLiteral(Result,
3241 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3242 SizeTmp2, Result),
3243 tok::wide_string_literal);
3244
Chris Lattner22eb9722006-06-18 05:43:12 +00003245 // Wide character constant.
3246 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003247 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3248 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003249 // FALL THROUGH, treating L like the start of an identifier.
Mike Stump11289f42009-09-09 15:08:12 +00003250
Chris Lattner22eb9722006-06-18 05:43:12 +00003251 // C99 6.4.2: Identifiers.
3252 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3253 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003254 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003255 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3256 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3257 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003258 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003259 case 'v': case 'w': case 'x': case 'y': case 'z':
3260 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003261 // Notify MIOpt that we read a non-whitespace/non-comment token.
3262 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003263 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003264
3265 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003266 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003267 if (!isLexingRawMode())
3268 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003269 // Notify MIOpt that we read a non-whitespace/non-comment token.
3270 MIOpt.ReadToken();
3271 return LexIdentifier(Result, CurPtr);
3272 }
Mike Stump11289f42009-09-09 15:08:12 +00003273
Chris Lattnerb11c3232008-10-12 04:51:35 +00003274 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003275 break;
Mike Stump11289f42009-09-09 15:08:12 +00003276
Chris Lattner22eb9722006-06-18 05:43:12 +00003277 // C99 6.4.4: Character Constants.
3278 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003279 // Notify MIOpt that we read a non-whitespace/non-comment token.
3280 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003281 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003282
3283 // C99 6.4.5: String Literals.
3284 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003285 // Notify MIOpt that we read a non-whitespace/non-comment token.
3286 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003287 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003288
3289 // C99 6.4.6: Punctuators.
3290 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003291 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003292 break;
3293 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003294 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003295 break;
3296 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003297 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003298 break;
3299 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003300 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003301 break;
3302 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003303 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003304 break;
3305 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003306 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003307 break;
3308 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003309 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003310 break;
3311 case '.':
3312 Char = getCharAndSize(CurPtr, SizeTmp);
3313 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003314 // Notify MIOpt that we read a non-whitespace/non-comment token.
3315 MIOpt.ReadToken();
3316
Chris Lattner22eb9722006-06-18 05:43:12 +00003317 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003318 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003319 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003320 CurPtr += SizeTmp;
3321 } else if (Char == '.' &&
3322 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003323 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003324 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3325 SizeTmp2, Result);
3326 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003327 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003328 }
3329 break;
3330 case '&':
3331 Char = getCharAndSize(CurPtr, SizeTmp);
3332 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003333 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003334 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3335 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003336 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003337 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3338 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003339 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003340 }
3341 break;
Mike Stump11289f42009-09-09 15:08:12 +00003342 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003343 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003344 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003345 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3346 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003347 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003348 }
3349 break;
3350 case '+':
3351 Char = getCharAndSize(CurPtr, SizeTmp);
3352 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003353 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003354 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003355 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003356 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003357 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003358 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003359 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003360 }
3361 break;
3362 case '-':
3363 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003364 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003365 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003366 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003367 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003368 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003369 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3370 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003371 Kind = tok::arrowstar;
3372 } 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::arrow;
3375 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003376 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003377 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003378 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003379 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003380 }
3381 break;
3382 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003383 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003384 break;
3385 case '!':
3386 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003387 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003388 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3389 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003390 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003391 }
3392 break;
3393 case '/':
3394 // 6.4.9: Comments
3395 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003396 if (Char == '/') { // Line comment.
3397 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003398 // want to lex this as a comment. There is one problem with this though,
3399 // that in one particular corner case, this can change the behavior of the
3400 // resultant program. For example, In "foo //**/ bar", C89 would lex
Nico Weber158a31a2012-11-11 07:02:14 +00003401 // this as "foo / bar" and langauges with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003402 // "foo". Check to see if the character after the second slash is a '*'.
3403 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003404 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003405 bool TreatAsComment = LangOpts.LineComment &&
3406 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003407 if (!TreatAsComment)
3408 if (!(PP && PP->isPreprocessedOutput()))
3409 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3410
3411 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003412 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3413 TokAtPhysicalStartOfLine))
3414 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003415
Chris Lattner58827712009-01-16 22:39:25 +00003416 // It is common for the tokens immediately after a // comment to be
3417 // whitespace (indentation for the next line). Instead of going through
3418 // the big switch, handle it efficiently now.
3419 goto SkipIgnoredUnits;
3420 }
3421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
Chris Lattner58827712009-01-16 22:39:25 +00003423 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003424 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3425 TokAtPhysicalStartOfLine))
3426 return true; // There is a token to return.
3427
3428 // We only saw whitespace, so just try again with this lexer.
3429 // (We manually eliminate the tail call to avoid recursion.)
3430 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003431 }
Mike Stump11289f42009-09-09 15:08:12 +00003432
Chris Lattner58827712009-01-16 22:39:25 +00003433 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003434 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003435 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003436 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003437 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003438 }
3439 break;
3440 case '%':
3441 Char = getCharAndSize(CurPtr, SizeTmp);
3442 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003443 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003444 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003445 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003446 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003448 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003449 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003450 Char = getCharAndSize(CurPtr, SizeTmp);
3451 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003452 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003453 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3454 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003455 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003456 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003457 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003458 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003459 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003460 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003461 // We parsed a # character. If this occurs at the start of the line,
3462 // it's actually the start of a preprocessing directive. Callback to
3463 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003464 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003465 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003466 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003467
Chris Lattner2534324a2009-03-18 20:58:27 +00003468 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003469 }
3470 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003471 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003472 }
3473 break;
3474 case '<':
3475 Char = getCharAndSize(CurPtr, SizeTmp);
3476 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003477 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003479 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3480 if (After == '=') {
3481 Kind = tok::lesslessequal;
3482 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3483 SizeTmp2, Result);
3484 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3485 // If this is actually a '<<<<<<<' version control conflict marker,
3486 // recognize it as such and recover nicely.
3487 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003488 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3489 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3490 // ignore it.
3491 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003492 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003493 Kind = tok::lesslessless;
3494 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3495 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003496 } else {
3497 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3498 Kind = tok::lessless;
3499 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003500 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003501 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003502 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003503 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003504 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003505 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3506 // C++0x [lex.pptoken]p3:
3507 // Otherwise, if the next three characters are <:: and the subsequent
3508 // character is neither : nor >, the < is treated as a preprocessor
3509 // token by itself and not as the first character of the alternative
3510 // token <:.
3511 unsigned SizeTmp3;
3512 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3513 if (After != ':' && After != '>') {
3514 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003515 if (!isLexingRawMode())
3516 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003517 break;
3518 }
3519 }
3520
Chris Lattner22eb9722006-06-18 05:43:12 +00003521 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003522 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003523 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003524 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003525 Kind = tok::l_brace;
Alex Lorenz1be800c52017-04-19 08:58:56 +00003526 } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3527 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003528 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003529 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003530 }
3531 break;
3532 case '>':
3533 Char = getCharAndSize(CurPtr, SizeTmp);
3534 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003535 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003536 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003537 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003538 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3539 if (After == '=') {
3540 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3541 SizeTmp2, Result);
3542 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003543 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3544 // If this is actually a '>>>>' conflict marker, recognize it as such
3545 // and recover nicely.
3546 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003547 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3548 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3549 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003550 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003551 Kind = tok::greatergreatergreater;
3552 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3553 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003554 } else {
3555 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3556 Kind = tok::greatergreater;
3557 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003558 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003559 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003560 }
3561 break;
3562 case '^':
3563 Char = getCharAndSize(CurPtr, SizeTmp);
3564 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003565 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003566 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003567 } else if (LangOpts.OpenCL && Char == '^') {
3568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3569 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003570 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003571 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003572 }
3573 break;
3574 case '|':
3575 Char = getCharAndSize(CurPtr, SizeTmp);
3576 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003577 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3579 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003580 // If this is '|||||||' and we're in a conflict marker, ignore it.
3581 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3582 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003583 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003584 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3585 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003586 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003587 }
3588 break;
3589 case ':':
3590 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003591 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003592 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003593 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003594 } else if (LangOpts.CPlusPlus && Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003595 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003596 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003597 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003598 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003599 }
3600 break;
3601 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003602 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003603 break;
3604 case '=':
3605 Char = getCharAndSize(CurPtr, SizeTmp);
3606 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003607 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003608 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3609 goto LexNextToken;
3610
Chris Lattnerb11c3232008-10-12 04:51:35 +00003611 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003612 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003613 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003614 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003615 }
3616 break;
3617 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003618 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003619 break;
3620 case '#':
3621 Char = getCharAndSize(CurPtr, SizeTmp);
3622 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003623 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003624 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003625 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003626 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003627 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003628 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003629 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003630 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003631 // We parsed a # character. If this occurs at the start of the line,
3632 // it's actually the start of a preprocessing directive. Callback to
3633 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003634 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003635 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003636 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003637
Chris Lattner2534324a2009-03-18 20:58:27 +00003638 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003639 }
3640 break;
3641
Chris Lattner2b15cf72008-01-03 17:58:54 +00003642 case '@':
3643 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003644 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003645 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003646 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003647 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003648 break;
Mike Stump11289f42009-09-09 15:08:12 +00003649
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003650 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003651 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003652 if (!LangOpts.AsmPreprocessor) {
3653 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3654 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3655 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3656 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003657
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003658 // We only saw whitespace, so just try again with this lexer.
3659 // (We manually eliminate the tail call to avoid recursion.)
3660 goto LexNextToken;
3661 }
3662
3663 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003664 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003665 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003666
Chris Lattnerb11c3232008-10-12 04:51:35 +00003667 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003668 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003669
3670 default: {
3671 if (isASCII(Char)) {
3672 Kind = tok::unknown;
3673 break;
3674 }
3675
Justin Lebar90910552016-09-30 00:38:45 +00003676 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003677
3678 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3679 // an escaped newline.
3680 --CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003681 llvm::ConversionResult Status =
3682 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3683 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003684 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003685 llvm::strictConversion);
3686 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003687 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3688 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3689 return true; // KeepWhitespaceMode
3690
3691 // We only saw whitespace, so just try again with this lexer.
3692 // (We manually eliminate the tail call to avoid recursion.)
3693 goto LexNextToken;
3694 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003695 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003696 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003697
Jordan Rosecc538342013-01-31 19:48:48 +00003698 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3699 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003700 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003701 Kind = tok::unknown;
3702 break;
3703 }
3704
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003705 // Non-ASCII characters tend to creep into source code unintentionally.
3706 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003707 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003708 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003709
3710 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003711 // We're pretending the character didn't exist, so just try again with
3712 // this lexer.
3713 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003714 goto LexNextToken;
3715 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003716 }
Mike Stump11289f42009-09-09 15:08:12 +00003717
Chris Lattner371ac8a2006-07-04 07:11:10 +00003718 // Notify MIOpt that we read a non-whitespace/non-comment token.
3719 MIOpt.ReadToken();
3720
Chris Lattnerd01e2912006-06-18 16:22:51 +00003721 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003722 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003723 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003724
3725HandleDirective:
3726 // We parsed a # character and it's the start of a preprocessing directive.
3727
3728 FormTokenWithChars(Result, CurPtr, tok::hash);
3729 PP->HandleDirective(Result);
3730
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003731 if (PP->hadModuleLoaderFatalFailure()) {
3732 // With a fatal failure in the module loader, we abort parsing.
3733 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003734 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003735 }
3736
Eli Friedman0834a4b2013-09-19 00:41:32 +00003737 // We parsed the directive; lex a token with the new state.
3738 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003739}