blob: ecb7c87a3c6961e03ba8a0a17456f61f89d94a00 [file] [log] [blame]
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001//===- Lexer.cpp - C Language Family Lexer --------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
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"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceLocation.h"
Chris Lattnerdc5c0552007-07-20 16:37:10 +000020#include "clang/Basic/SourceManager.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000021#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
Richard Smith2a988622013-09-24 04:06:10 +000023#include "clang/Lex/LiteralSupport.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000024#include "clang/Lex/MultipleIncludeOpt.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
Alex Lorenzfb7654a2017-06-16 20:13:39 +000026#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000027#include "clang/Lex/Token.h"
28#include "clang/Basic/Diagnostic.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/TokenKinds.h"
31#include "llvm/ADT/None.h"
32#include "llvm/ADT/Optional.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000033#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000035#include "llvm/ADT/StringRef.h"
Chris Lattner619c1742007-07-22 18:38:25 +000036#include "llvm/Support/Compiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "llvm/Support/MathExtras.h"
Chris Lattner739e7392007-04-29 07:12:06 +000039#include "llvm/Support/MemoryBuffer.h"
Richard Smith77091b12017-12-14 13:15:08 +000040#include "llvm/Support/NativeFormatting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "llvm/Support/UnicodeCharRanges.h"
42#include <algorithm>
43#include <cassert>
44#include <cstddef>
45#include <cstdint>
Craig Topper54edcca2011-08-11 04:06:15 +000046#include <cstring>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include <string>
48#include <tuple>
49#include <utility>
50
Chris Lattner22eb9722006-06-18 05:43:12 +000051using namespace clang;
52
Chris Lattner4894f482007-10-07 08:47:24 +000053//===----------------------------------------------------------------------===//
54// Token Class Implementation
55//===----------------------------------------------------------------------===//
56
Mike Stump11289f42009-09-09 15:08:12 +000057/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
Chris Lattner4894f482007-10-07 08:47:24 +000058bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
Alex Lorenzd4754662017-05-17 11:08:36 +000059 if (isAnnotation())
60 return false;
Douglas Gregor90abb6d2008-12-01 21:46:47 +000061 if (IdentifierInfo *II = getIdentifierInfo())
62 return II->getObjCKeywordID() == objcKey;
63 return false;
Chris Lattner4894f482007-10-07 08:47:24 +000064}
65
66/// getObjCKeywordID - Return the ObjC keyword kind.
67tok::ObjCKeywordKind Token::getObjCKeywordID() const {
Alex Lorenzd4754662017-05-17 11:08:36 +000068 if (isAnnotation())
69 return tok::objc_not_keyword;
Chris Lattner4894f482007-10-07 08:47:24 +000070 IdentifierInfo *specId = getIdentifierInfo();
71 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
72}
73
74//===----------------------------------------------------------------------===//
75// Lexer Class Implementation
76//===----------------------------------------------------------------------===//
77
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000078void Lexer::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +000079
Mike Stump11289f42009-09-09 15:08:12 +000080void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
Chris Lattnerf76b9202009-01-17 06:55:17 +000081 const char *BufEnd) {
Chris Lattnerf76b9202009-01-17 06:55:17 +000082 BufferStart = BufStart;
83 BufferPtr = BufPtr;
84 BufferEnd = BufEnd;
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattnerf76b9202009-01-17 06:55:17 +000086 assert(BufEnd[0] == 0 &&
87 "We assume that the input buffer has a null character at the end"
88 " to simplify lexing!");
Mike Stump11289f42009-09-09 15:08:12 +000089
Eric Christopher7f36a792011-04-09 00:01:04 +000090 // Check whether we have a BOM in the beginning of the buffer. If yes - act
91 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
92 // skip the UTF-8 BOM if it's present.
93 if (BufferStart == BufferPtr) {
94 // Determine the size of the BOM.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000095 StringRef Buf(BufferStart, BufferEnd - BufferStart);
Eli Friedman86a51012011-05-10 17:11:21 +000096 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
Eric Christopher7f36a792011-04-09 00:01:04 +000097 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
98 .Default(0);
99
100 // Skip the BOM.
101 BufferPtr += BOMLength;
102 }
103
Chris Lattnerf76b9202009-01-17 06:55:17 +0000104 Is_PragmaLexer = false;
Richard Smitha9e33d42011-10-12 00:37:51 +0000105 CurrentConflictMarkerState = CMK_None;
Eric Christopher7f36a792011-04-09 00:01:04 +0000106
Chris Lattnerf76b9202009-01-17 06:55:17 +0000107 // Start of the file is a start of line.
108 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000109 IsAtPhysicalStartOfLine = true;
110
111 HasLeadingSpace = false;
112 HasLeadingEmptyMacro = false;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattnerf76b9202009-01-17 06:55:17 +0000114 // We are not after parsing a #.
115 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerf76b9202009-01-17 06:55:17 +0000117 // We are not after parsing #include.
118 ParsingFilename = false;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Chris Lattnerf76b9202009-01-17 06:55:17 +0000120 // We are not in raw mode. Raw mode disables diagnostics and interpretation
121 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
122 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
123 // or otherwise skipping over tokens.
124 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Chris Lattnerf76b9202009-01-17 06:55:17 +0000126 // Default to not keeping comments.
127 ExtendedTokenMode = 0;
128}
129
Chris Lattner5965a282009-01-17 07:56:59 +0000130/// Lexer constructor - Create a new lexer object for the specified buffer
131/// with the specified preprocessor managing the lexing process. This lexer
132/// assumes that the associated file buffer and Preprocessor objects will
133/// outlive it, so it doesn't take ownership of either of them.
Chris Lattner710bb872009-11-30 04:18:44 +0000134Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000135 : PreprocessorLexer(&PP, FID),
136 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
137 LangOpts(PP.getLangOpts()) {
Chris Lattner5965a282009-01-17 07:56:59 +0000138 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
139 InputFile->getBufferEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000140
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000141 resetExtendedTokenMode();
142}
143
Chris Lattner02b436a2007-10-17 20:41:00 +0000144/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000145/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner50c90502008-10-12 01:15:46 +0000146/// range will outlive it, so it doesn't take ownership of it.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000147Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
Chris Lattnerfcf64522009-01-17 07:42:27 +0000148 const char *BufStart, const char *BufPtr, const char *BufEnd)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000149 : FileLoc(fileloc), LangOpts(langOpts) {
Chris Lattnerf76b9202009-01-17 06:55:17 +0000150 InitLexer(BufStart, BufPtr, BufEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000151
Chris Lattner02b436a2007-10-17 20:41:00 +0000152 // We *are* in raw mode.
153 LexingRawMode = true;
Chris Lattner02b436a2007-10-17 20:41:00 +0000154}
155
Chris Lattner08354fe2009-01-17 07:35:14 +0000156/// Lexer constructor - Create a new raw lexer object. This object is only
Dmitri Gribenko702b7322012-06-08 23:19:37 +0000157/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
Chris Lattner08354fe2009-01-17 07:35:14 +0000158/// range will outlive it, so it doesn't take ownership of it.
Chris Lattner710bb872009-11-30 04:18:44 +0000159Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000160 const SourceManager &SM, const LangOptions &langOpts)
Benjamin Kramerf04f98d2015-03-06 14:15:57 +0000161 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
162 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
Chris Lattner08354fe2009-01-17 07:35:14 +0000163
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000164void Lexer::resetExtendedTokenMode() {
165 assert(PP && "Cannot reset token mode without a preprocessor");
166 if (LangOpts.TraditionalCPP)
167 SetKeepWhitespaceMode(true);
168 else
169 SetCommentRetentionState(PP->getCommentRetentionState());
170}
171
Chris Lattner757169b2009-01-17 08:27:52 +0000172/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
173/// _Pragma expansion. This has a variety of magic semantics that this method
174/// sets up. It returns a new'd Lexer that must be delete'd when done.
175///
176/// On entrance to this routine, TokStartLoc is a macro location which has a
177/// spelling loc that indicates the bytes to be lexed for the token and an
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000178/// expansion location that indicates where all lexed tokens should be
Chris Lattner757169b2009-01-17 08:27:52 +0000179/// "expanded from".
180///
Alp Toker7755aff2014-05-18 18:37:59 +0000181/// TODO: It would really be nice to make _Pragma just be a wrapper around a
Chris Lattner757169b2009-01-17 08:27:52 +0000182/// normal lexer that remaps tokens as they fly by. This would require making
183/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
184/// interface that could handle this stuff. This would pull GetMappedTokenLoc
185/// out of the critical path of the lexer!
186///
Mike Stump11289f42009-09-09 15:08:12 +0000187Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000188 SourceLocation ExpansionLocStart,
189 SourceLocation ExpansionLocEnd,
Chris Lattner29a2a192009-01-19 06:46:35 +0000190 unsigned TokLen, Preprocessor &PP) {
Chris Lattner757169b2009-01-17 08:27:52 +0000191 SourceManager &SM = PP.getSourceManager();
Chris Lattner757169b2009-01-17 08:27:52 +0000192
193 // Create the lexer as if we were going to lex the file normally.
Chris Lattnercbc35ecb2009-01-19 07:46:45 +0000194 FileID SpellingFID = SM.getFileID(SpellingLoc);
Chris Lattner710bb872009-11-30 04:18:44 +0000195 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
196 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner757169b2009-01-17 08:27:52 +0000198 // Now that the lexer is created, change the start/end locations so that we
199 // just lex the subsection of the file that we want. This is lexing from a
200 // scratch buffer.
201 const char *StrData = SM.getCharacterData(SpellingLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner757169b2009-01-17 08:27:52 +0000203 L->BufferPtr = StrData;
204 L->BufferEnd = StrData+TokLen;
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000205 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
Chris Lattner757169b2009-01-17 08:27:52 +0000206
207 // Set the SourceLocation with the remapping information. This ensures that
208 // GetMappedTokenLoc will remap the tokens as they are lexed.
Chandler Carruth115b0772011-07-26 03:03:05 +0000209 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
210 ExpansionLocStart,
211 ExpansionLocEnd, TokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner757169b2009-01-17 08:27:52 +0000213 // Ensure that the lexer thinks it is inside a directive, so that end \n will
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000214 // return an EOD token.
Chris Lattner757169b2009-01-17 08:27:52 +0000215 L->ParsingPreprocessorDirective = true;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner757169b2009-01-17 08:27:52 +0000217 // This lexer really is for _Pragma.
218 L->Is_PragmaLexer = true;
219 return L;
220}
221
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000222template <typename T> static void StringifyImpl(T &Str, char Quote) {
Taewook Ohcebac482017-12-06 17:00:53 +0000223 typename T::size_type i = 0, e = Str.size();
224 while (i < e) {
225 if (Str[i] == '\\' || Str[i] == Quote) {
226 Str.insert(Str.begin() + i, '\\');
227 i += 2;
228 ++e;
229 } else if (Str[i] == '\n' || Str[i] == '\r') {
230 // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
231 if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
232 Str[i] != Str[i + 1]) {
233 Str[i] = '\\';
234 Str[i + 1] = 'n';
235 } else {
236 // Replace '\n' and '\r' to '\\' followed by 'n'.
237 Str[i] = '\\';
238 Str.insert(Str.begin() + i + 1, 'n');
239 ++e;
240 }
241 i += 2;
242 } else
243 ++i;
244 }
245}
246
Rafael Espindolac0f18a92015-06-01 20:00:16 +0000247std::string Lexer::Stringify(StringRef Str, bool Charify) {
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000248 std::string Result = Str;
Chris Lattnerecc39e92006-07-15 05:23:31 +0000249 char Quote = Charify ? '\'' : '"';
Taewook Ohcebac482017-12-06 17:00:53 +0000250 StringifyImpl(Result, Quote);
Chris Lattnerecc39e92006-07-15 05:23:31 +0000251 return Result;
Chris Lattnere3e81ea2006-07-03 01:13:26 +0000252}
253
Taewook Ohcebac482017-12-06 17:00:53 +0000254void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
Chris Lattner4c4a2452007-07-24 06:57:14 +0000255
Chris Lattner39720112010-11-17 07:26:20 +0000256//===----------------------------------------------------------------------===//
257// Token Spelling
258//===----------------------------------------------------------------------===//
259
Richard Smith9a67f472012-11-28 07:29:00 +0000260/// \brief Slow case of getSpelling. Extract the characters comprising the
261/// spelling of this token from the provided input buffer.
262static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
263 const LangOptions &LangOpts, char *Spelling) {
264 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
265
266 size_t Length = 0;
267 const char *BufEnd = BufPtr + Tok.getLength();
268
Craig Toppera6324c92015-10-22 15:35:21 +0000269 if (tok::isStringLiteral(Tok.getKind())) {
Richard Smith9a67f472012-11-28 07:29:00 +0000270 // Munch the encoding-prefix and opening double-quote.
271 while (BufPtr < BufEnd) {
272 unsigned Size;
273 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
274 BufPtr += Size;
275
276 if (Spelling[Length - 1] == '"')
277 break;
278 }
279
280 // Raw string literals need special handling; trigraph expansion and line
281 // splicing do not occur within their d-char-sequence nor within their
282 // r-char-sequence.
283 if (Length >= 2 &&
284 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
285 // Search backwards from the end of the token to find the matching closing
286 // quote.
287 const char *RawEnd = BufEnd;
288 do --RawEnd; while (*RawEnd != '"');
289 size_t RawLength = RawEnd - BufPtr + 1;
290
291 // Everything between the quotes is included verbatim in the spelling.
292 memcpy(Spelling + Length, BufPtr, RawLength);
293 Length += RawLength;
294 BufPtr += RawLength;
295
296 // The rest of the token is lexed normally.
297 }
298 }
299
300 while (BufPtr < BufEnd) {
301 unsigned Size;
302 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
303 BufPtr += Size;
304 }
305
306 assert(Length < Tok.getLength() &&
307 "NeedsCleaning flag set on token that didn't need cleaning!");
308 return Length;
309}
310
Chris Lattner39720112010-11-17 07:26:20 +0000311/// getSpelling() - Return the 'spelling' of this token. The spelling of a
312/// token are the characters used to represent the token in the source file
313/// after trigraph expansion and escaped-newline folding. In particular, this
314/// wants to get the true, uncanonicalized, spelling of things like digraphs
315/// UCNs, etc.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000316StringRef Lexer::getSpelling(SourceLocation loc,
Richard Smith9a67f472012-11-28 07:29:00 +0000317 SmallVectorImpl<char> &buffer,
318 const SourceManager &SM,
319 const LangOptions &options,
320 bool *invalid) {
John McCall462c0552011-03-08 07:59:04 +0000321 // Break down the source location.
322 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
323
324 // Try to the load the file buffer.
325 bool invalidTemp = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
John McCall462c0552011-03-08 07:59:04 +0000327 if (invalidTemp) {
328 if (invalid) *invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000329 return {};
John McCall462c0552011-03-08 07:59:04 +0000330 }
331
332 const char *tokenBegin = file.data() + locInfo.second;
333
334 // Lex from the start of the given location.
335 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
336 file.begin(), tokenBegin, file.end());
337 Token token;
338 lexer.LexFromRawLexer(token);
339
340 unsigned length = token.getLength();
341
342 // Common case: no need for cleaning.
343 if (!token.needsCleaning())
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000344 return StringRef(tokenBegin, length);
John McCall462c0552011-03-08 07:59:04 +0000345
Richard Smith9a67f472012-11-28 07:29:00 +0000346 // Hard case, we need to relex the characters into the string.
347 buffer.resize(length);
348 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 return StringRef(buffer.data(), buffer.size());
John McCall462c0552011-03-08 07:59:04 +0000350}
351
352/// getSpelling() - Return the 'spelling' of this token. The spelling of a
353/// token are the characters used to represent the token in the source file
354/// after trigraph expansion and escaped-newline folding. In particular, this
355/// wants to get the true, uncanonicalized, spelling of things like digraphs
356/// UCNs, etc.
Chris Lattner39720112010-11-17 07:26:20 +0000357std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000358 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000359 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Richard Smith9a67f472012-11-28 07:29:00 +0000360
Chris Lattner39720112010-11-17 07:26:20 +0000361 bool CharDataInvalid = false;
Richard Smith9a67f472012-11-28 07:29:00 +0000362 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
Chris Lattner39720112010-11-17 07:26:20 +0000363 &CharDataInvalid);
364 if (Invalid)
365 *Invalid = CharDataInvalid;
366 if (CharDataInvalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000367 return {};
Richard Smith9a67f472012-11-28 07:29:00 +0000368
369 // If this token contains nothing interesting, return it directly.
Chris Lattner39720112010-11-17 07:26:20 +0000370 if (!Tok.needsCleaning())
Richard Smith9a67f472012-11-28 07:29:00 +0000371 return std::string(TokStart, TokStart + Tok.getLength());
372
Chris Lattner39720112010-11-17 07:26:20 +0000373 std::string Result;
Richard Smith9a67f472012-11-28 07:29:00 +0000374 Result.resize(Tok.getLength());
375 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
Chris Lattner39720112010-11-17 07:26:20 +0000376 return Result;
377}
378
379/// getSpelling - This method is used to get the spelling of a token into a
380/// preallocated buffer, instead of as an std::string. The caller is required
381/// to allocate enough space for the token, which is guaranteed to be at least
382/// Tok.getLength() bytes long. The actual length of the token is returned.
383///
384/// Note that this method may do two possible things: it may either fill in
385/// the buffer specified with characters, or it may *change the input pointer*
386/// to point to a constant buffer with the data already in it (avoiding a
387/// copy). The caller is not allowed to modify the returned buffer pointer
388/// if an internal buffer is returned.
Taewook Ohcebac482017-12-06 17:00:53 +0000389unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
Chris Lattner39720112010-11-17 07:26:20 +0000390 const SourceManager &SourceMgr,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000391 const LangOptions &LangOpts, bool *Invalid) {
Chris Lattner39720112010-11-17 07:26:20 +0000392 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000393
Craig Topperd2d442c2014-05-17 23:10:59 +0000394 const char *TokStart = nullptr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000395 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
396 if (Tok.is(tok::raw_identifier))
Alp Toker2d57cea2014-05-17 04:53:25 +0000397 TokStart = Tok.getRawIdentifier().data();
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000398 else if (!Tok.hasUCN()) {
399 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
400 // Just return the string from the identifier table, which is very quick.
401 Buffer = II->getNameStart();
402 return II->getLength();
403 }
Chris Lattner39720112010-11-17 07:26:20 +0000404 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000405
406 // NOTE: this can be checked even after testing for an IdentifierInfo.
Chris Lattner39720112010-11-17 07:26:20 +0000407 if (Tok.isLiteral())
408 TokStart = Tok.getLiteralData();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000409
Craig Topperd2d442c2014-05-17 23:10:59 +0000410 if (!TokStart) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000411 // Compute the start of the token in the input lexer buffer.
Chris Lattner39720112010-11-17 07:26:20 +0000412 bool CharDataInvalid = false;
413 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
414 if (Invalid)
415 *Invalid = CharDataInvalid;
416 if (CharDataInvalid) {
417 Buffer = "";
418 return 0;
419 }
420 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000421
Chris Lattner39720112010-11-17 07:26:20 +0000422 // If this token contains nothing interesting, return it directly.
423 if (!Tok.needsCleaning()) {
424 Buffer = TokStart;
425 return Tok.getLength();
426 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000427
Chris Lattner39720112010-11-17 07:26:20 +0000428 // Otherwise, hard case, relex the characters into the string.
Richard Smith9a67f472012-11-28 07:29:00 +0000429 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
Chris Lattner39720112010-11-17 07:26:20 +0000430}
431
Chris Lattner8e129c22007-10-17 21:18:47 +0000432/// MeasureTokenLength - Relex the token at the specified location and return
433/// its length in bytes in the input file. If the token needs cleaning (e.g.
434/// includes a trigraph or an escaped newline) then this count includes bytes
435/// that are part of that.
436unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
Chris Lattner184e65d2009-04-14 23:22:57 +0000437 const SourceManager &SM,
438 const LangOptions &LangOpts) {
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000439 Token TheTok;
440 if (getRawToken(Loc, TheTok, SM, LangOpts))
441 return 0;
442 return TheTok.getLength();
443}
444
445/// \brief Relex the token at the specified location.
446/// \returns true if there was a failure, false on success.
447bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
448 const SourceManager &SM,
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000449 const LangOptions &LangOpts,
450 bool IgnoreWhiteSpace) {
Chris Lattner8e129c22007-10-17 21:18:47 +0000451 // TODO: this could be special cased for common tokens like identifiers, ')',
452 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
Mike Stump11289f42009-09-09 15:08:12 +0000453 // all obviously single-char tokens. This could use
Chris Lattner8e129c22007-10-17 21:18:47 +0000454 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
455 // something.
Chris Lattner4fa23622009-01-26 00:43:02 +0000456
457 // If this comes from a macro expansion, we really do want the macro name, not
458 // the token this macro expanded to.
Chandler Carruth35f53202011-07-25 16:49:02 +0000459 Loc = SM.getExpansionLoc(Loc);
Chris Lattnerd3817212009-01-26 22:24:27 +0000460 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000461 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000463 if (Invalid)
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000464 return true;
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000465
466 const char *StrData = Buffer.data()+LocInfo.second;
Chris Lattner5509d532009-01-17 08:30:10 +0000467
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000468 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000469 return true;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000470
Chris Lattner8e129c22007-10-17 21:18:47 +0000471 // Create a lexer starting at the beginning of this token.
Sebastian Redl51752302010-09-30 01:03:03 +0000472 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
473 Buffer.begin(), StrData, Buffer.end());
Chris Lattnera3d4f162009-10-14 15:04:18 +0000474 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidis86f1a932013-01-07 19:16:18 +0000475 TheLexer.LexFromRawLexer(Result);
476 return false;
Chris Lattner8e129c22007-10-17 21:18:47 +0000477}
478
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000479/// Returns the pointer that points to the beginning of line that contains
480/// the given offset, or null if the offset if invalid.
481static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
482 const char *BufStart = Buffer.data();
483 if (Offset >= Buffer.size())
484 return nullptr;
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000485
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000486 const char *LexStart = BufStart + Offset;
487 for (; LexStart != BufStart; --LexStart) {
488 if (isVerticalWhitespace(LexStart[0]) &&
489 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
490 // LexStart should point at first character of logical line.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000491 ++LexStart;
492 break;
493 }
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000494 }
495 return LexStart;
496}
497
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000498static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
499 const SourceManager &SM,
500 const LangOptions &LangOpts) {
501 assert(Loc.isFileID());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000502 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
Douglas Gregor86af9842011-01-31 22:42:36 +0000503 if (LocInfo.first.isInvalid())
504 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000505
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000506 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000507 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000508 if (Invalid)
509 return Loc;
510
511 // Back up from the current location until we hit the beginning of a line
512 // (or the buffer). We'll relex from that point.
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000513 const char *StrData = Buffer.data() + LocInfo.second;
514 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
515 if (!LexStart || LexStart == StrData)
Douglas Gregor86af9842011-01-31 22:42:36 +0000516 return Loc;
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000517
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000518 // Create a lexer starting at the beginning of this token.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000519 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +0000520 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
521 Buffer.end());
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000522 TheLexer.SetCommentRetentionState(true);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000523
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000524 // Lex tokens until we find the token that contains the source location.
525 Token TheTok;
526 do {
527 TheLexer.LexFromRawLexer(TheTok);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000528
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000529 if (TheLexer.getBufferLocation() > StrData) {
530 // Lexing this token has taken the lexer past the source location we're
531 // looking for. If the current token encompasses our source location,
532 // return the beginning of that token.
533 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
534 return TheTok.getLocation();
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000535
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000536 // We ended up skipping over the source location entirely, which means
537 // that it points into whitespace. We're done here.
538 break;
539 }
540 } while (TheTok.getKind() != tok::eof);
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000541
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000542 // We've passed our source location; just return the original source location.
543 return Loc;
544}
545
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000546SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
547 const SourceManager &SM,
548 const LangOptions &LangOpts) {
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000549 if (Loc.isFileID())
550 return getBeginningOfFileToken(Loc, SM, LangOpts);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000551
Alexander Kornienkocf007a72017-08-10 10:06:16 +0000552 if (!SM.isMacroArgExpansion(Loc))
553 return Loc;
554
555 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
556 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
557 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
558 std::pair<FileID, unsigned> BeginFileLocInfo =
559 SM.getDecomposedLoc(BeginFileLoc);
560 assert(FileLocInfo.first == BeginFileLocInfo.first &&
561 FileLocInfo.second >= BeginFileLocInfo.second);
562 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
Argyrios Kyrtzidis161868d2011-08-17 00:31:23 +0000563}
564
Douglas Gregoraf82e352010-07-20 20:18:03 +0000565namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000566
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000567enum PreambleDirectiveKind {
568 PDK_Skipped,
569 PDK_Unknown
570};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000571
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000572} // namespace
Douglas Gregoraf82e352010-07-20 20:18:03 +0000573
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000574PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
575 const LangOptions &LangOpts,
576 unsigned MaxLines) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000577 // Create a lexer starting at the beginning of the file. Note that we use a
578 // "fake" file source location at offset 1 so that the lexer will track our
579 // position within the file.
580 const unsigned StartOffset = 1;
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000581 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000582 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
583 Buffer.end());
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000584 TheLexer.SetCommentRetentionState(true);
Argyrios Kyrtzidisd53d0da2012-10-25 01:51:45 +0000585
Douglas Gregoraf82e352010-07-20 20:18:03 +0000586 bool InPreprocessorDirective = false;
587 Token TheTok;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000588 SourceLocation ActiveCommentLoc;
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000589
590 unsigned MaxLineOffset = 0;
591 if (MaxLines) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000592 const char *CurPtr = Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000593 unsigned CurLine = 0;
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000594 while (CurPtr != Buffer.end()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000595 char ch = *CurPtr++;
596 if (ch == '\n') {
597 ++CurLine;
598 if (CurLine == MaxLines)
599 break;
600 }
601 }
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000602 if (CurPtr != Buffer.end())
603 MaxLineOffset = CurPtr - Buffer.begin();
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000604 }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000605
Douglas Gregoraf82e352010-07-20 20:18:03 +0000606 do {
607 TheLexer.LexFromRawLexer(TheTok);
608
609 if (InPreprocessorDirective) {
610 // If we've hit the end of the file, we're done.
611 if (TheTok.getKind() == tok::eof) {
Douglas Gregoraf82e352010-07-20 20:18:03 +0000612 break;
613 }
Taewook Ohcebac482017-12-06 17:00:53 +0000614
Douglas Gregoraf82e352010-07-20 20:18:03 +0000615 // If we haven't hit the end of the preprocessor directive, skip this
616 // token.
617 if (!TheTok.isAtStartOfLine())
618 continue;
Taewook Ohcebac482017-12-06 17:00:53 +0000619
Douglas Gregoraf82e352010-07-20 20:18:03 +0000620 // We've passed the end of the preprocessor directive, and will look
621 // at this token again below.
622 InPreprocessorDirective = false;
623 }
Taewook Ohcebac482017-12-06 17:00:53 +0000624
Douglas Gregor028d3e42010-08-09 20:45:32 +0000625 // Keep track of the # of lines in the preamble.
626 if (TheTok.isAtStartOfLine()) {
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000627 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
Douglas Gregor028d3e42010-08-09 20:45:32 +0000628
629 // If we were asked to limit the number of lines in the preamble,
630 // and we're about to exceed that limit, we're done.
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +0000631 if (MaxLineOffset && TokOffset >= MaxLineOffset)
Douglas Gregor028d3e42010-08-09 20:45:32 +0000632 break;
633 }
634
Douglas Gregoraf82e352010-07-20 20:18:03 +0000635 // Comments are okay; skip over them.
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000636 if (TheTok.getKind() == tok::comment) {
637 if (ActiveCommentLoc.isInvalid())
638 ActiveCommentLoc = TheTok.getLocation();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000639 continue;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000640 }
Taewook Ohcebac482017-12-06 17:00:53 +0000641
Douglas Gregoraf82e352010-07-20 20:18:03 +0000642 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
Taewook Ohcebac482017-12-06 17:00:53 +0000643 // This is the start of a preprocessor directive.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000644 Token HashTok = TheTok;
645 InPreprocessorDirective = true;
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000646 ActiveCommentLoc = SourceLocation();
Taewook Ohcebac482017-12-06 17:00:53 +0000647
Joerg Sonnenbergerda5d2b72011-07-20 00:14:37 +0000648 // Figure out which directive this is. Since we're lexing raw tokens,
Douglas Gregoraf82e352010-07-20 20:18:03 +0000649 // we don't have an identifier table available. Instead, just look at
650 // the raw identifier to recognize and categorize preprocessor directives.
651 TheLexer.LexFromRawLexer(TheTok);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000652 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
Alp Toker2d57cea2014-05-17 04:53:25 +0000653 StringRef Keyword = TheTok.getRawIdentifier();
Douglas Gregoraf82e352010-07-20 20:18:03 +0000654 PreambleDirectiveKind PDK
655 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
656 .Case("include", PDK_Skipped)
657 .Case("__include_macros", PDK_Skipped)
658 .Case("define", PDK_Skipped)
659 .Case("undef", PDK_Skipped)
660 .Case("line", PDK_Skipped)
661 .Case("error", PDK_Skipped)
662 .Case("pragma", PDK_Skipped)
663 .Case("import", PDK_Skipped)
664 .Case("include_next", PDK_Skipped)
665 .Case("warning", PDK_Skipped)
666 .Case("ident", PDK_Skipped)
667 .Case("sccs", PDK_Skipped)
668 .Case("assert", PDK_Skipped)
669 .Case("unassert", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000670 .Case("if", PDK_Skipped)
671 .Case("ifdef", PDK_Skipped)
672 .Case("ifndef", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000673 .Case("elif", PDK_Skipped)
674 .Case("else", PDK_Skipped)
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000675 .Case("endif", PDK_Skipped)
Douglas Gregoraf82e352010-07-20 20:18:03 +0000676 .Default(PDK_Unknown);
677
678 switch (PDK) {
679 case PDK_Skipped:
680 continue;
681
Douglas Gregoraf82e352010-07-20 20:18:03 +0000682 case PDK_Unknown:
683 // We don't know what this directive is; stop at the '#'.
684 break;
685 }
686 }
Taewook Ohcebac482017-12-06 17:00:53 +0000687
Douglas Gregoraf82e352010-07-20 20:18:03 +0000688 // We only end up here if we didn't recognize the preprocessor
689 // directive or it was one that can't occur in the preamble at this
690 // point. Roll back the current token to the location of the '#'.
691 InPreprocessorDirective = false;
692 TheTok = HashTok;
693 }
694
Douglas Gregor028d3e42010-08-09 20:45:32 +0000695 // We hit a token that we don't recognize as being in the
696 // "preprocessing only" part of the file, so we're no longer in
697 // the preamble.
Douglas Gregoraf82e352010-07-20 20:18:03 +0000698 break;
699 } while (true);
Taewook Ohcebac482017-12-06 17:00:53 +0000700
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000701 SourceLocation End;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000702 if (ActiveCommentLoc.isValid())
Argyrios Kyrtzidis0903f8d2013-04-19 23:24:25 +0000703 End = ActiveCommentLoc; // don't truncate a decl comment.
704 else
705 End = TheTok.getLocation();
706
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000707 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000708 TheTok.isAtStartOfLine());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000709}
710
Chris Lattner2a6ee912010-11-17 07:05:50 +0000711/// AdvanceToTokenCharacter - Given a location that specifies the start of a
712/// token, return a new location that specifies a character within the token.
713SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
714 unsigned CharNo,
715 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000716 const LangOptions &LangOpts) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000717 // Figure out how many physical characters away the specified expansion
Chris Lattner2a6ee912010-11-17 07:05:50 +0000718 // character is. This needs to take into consideration newlines and
719 // trigraphs.
720 bool Invalid = false;
721 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
Taewook Ohcebac482017-12-06 17:00:53 +0000722
Chris Lattner2a6ee912010-11-17 07:05:50 +0000723 // If they request the first char of the token, we're trivially done.
724 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
725 return TokStart;
Taewook Ohcebac482017-12-06 17:00:53 +0000726
Chris Lattner2a6ee912010-11-17 07:05:50 +0000727 unsigned PhysOffset = 0;
Taewook Ohcebac482017-12-06 17:00:53 +0000728
Chris Lattner2a6ee912010-11-17 07:05:50 +0000729 // The usual case is that tokens don't contain anything interesting. Skip
730 // over the uninteresting characters. If a token only consists of simple
731 // chars, this method is extremely fast.
732 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
733 if (CharNo == 0)
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000734 return TokStart.getLocWithOffset(PhysOffset);
Richard Trieucc3949d2016-02-18 22:34:54 +0000735 ++TokPtr;
736 --CharNo;
737 ++PhysOffset;
Chris Lattner2a6ee912010-11-17 07:05:50 +0000738 }
Taewook Ohcebac482017-12-06 17:00:53 +0000739
Chris Lattner2a6ee912010-11-17 07:05:50 +0000740 // If we have a character that may be a trigraph or escaped newline, use a
741 // lexer to parse it correctly.
742 for (; CharNo; --CharNo) {
743 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000744 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000745 TokPtr += Size;
746 PhysOffset += Size;
747 }
Taewook Ohcebac482017-12-06 17:00:53 +0000748
Chris Lattner2a6ee912010-11-17 07:05:50 +0000749 // Final detail: if we end up on an escaped newline, we want to return the
750 // location of the actual byte of the token. For example foo\<newline>bar
751 // advanced by 3 should return the location of b, not of \\. One compounding
752 // detail of this is that the escape may be made by a trigraph.
753 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
754 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
Taewook Ohcebac482017-12-06 17:00:53 +0000755
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000756 return TokStart.getLocWithOffset(PhysOffset);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000757}
758
759/// \brief Computes the source location just past the end of the
760/// token at this source location.
761///
762/// This routine can be used to produce a source location that
763/// points just past the end of the token referenced by \p Loc, and
764/// is generally used when a diagnostic needs to point just after a
765/// token where it expected something different that it received. If
766/// the returned source location would not be meaningful (e.g., if
767/// it points into a macro), this routine returns an invalid
768/// source location.
769///
770/// \param Offset an offset from the end of the token, where the source
771/// location should refer to. The default offset (0) produces a source
772/// location pointing just past the end of the token; an offset of 1 produces
773/// a source location pointing to the last character in the token, etc.
774SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
775 const SourceManager &SM,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 const LangOptions &LangOpts) {
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000777 if (Loc.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000778 return {};
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000779
780 if (Loc.isMacroID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000781 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000782 return {}; // Points inside the macro expansion.
Argyrios Kyrtzidis2cfce182011-06-24 17:58:59 +0000783 }
784
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000786 if (Len > Offset)
787 Len = Len - Offset;
788 else
789 return Loc;
Taewook Ohcebac482017-12-06 17:00:53 +0000790
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000791 return Loc.getLocWithOffset(Len);
Chris Lattner2a6ee912010-11-17 07:05:50 +0000792}
793
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000794/// \brief Returns true if the given MacroID location points at the first
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000795/// token of the macro expansion.
796bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
Douglas Gregor925296b2011-07-19 16:10:42 +0000797 const SourceManager &SM,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000798 const LangOptions &LangOpts,
799 SourceLocation *MacroBegin) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000800 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
801
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000802 SourceLocation expansionLoc;
803 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
804 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000805
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000806 if (expansionLoc.isFileID()) {
807 // No other macro expansions, this is the first.
808 if (MacroBegin)
809 *MacroBegin = expansionLoc;
810 return true;
811 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000812
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000813 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000814}
815
816/// \brief Returns true if the given MacroID location points at the last
Chandler Carruthe2c09eb2011-07-14 08:20:40 +0000817/// token of the macro expansion.
818bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000819 const SourceManager &SM,
820 const LangOptions &LangOpts,
821 SourceLocation *MacroEnd) {
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000822 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
823
824 SourceLocation spellLoc = SM.getSpellingLoc(loc);
825 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
826 if (tokLen == 0)
827 return false;
828
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000829 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
830 SourceLocation expansionLoc;
831 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
832 return false;
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000833
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000834 if (expansionLoc.isFileID()) {
835 // No other macro expansions.
836 if (MacroEnd)
837 *MacroEnd = expansionLoc;
838 return true;
839 }
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000840
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +0000841 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
Argyrios Kyrtzidis61c58f72011-07-07 21:54:45 +0000842}
843
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000844static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000845 const SourceManager &SM,
846 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000847 SourceLocation Begin = Range.getBegin();
848 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000849 assert(Begin.isFileID() && End.isFileID());
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000850 if (Range.isTokenRange()) {
851 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
852 if (End.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000853 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000854 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000855
856 // Break down the source locations.
857 FileID FID;
858 unsigned BeginOffs;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000859 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000860 if (FID.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000861 return {};
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000862
863 unsigned EndOffs;
864 if (!SM.isInFileID(End, FID, &EndOffs) ||
865 BeginOffs > EndOffs)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000866 return {};
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000867
868 return CharSourceRange::getCharRange(Begin, End);
869}
870
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000871CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000872 const SourceManager &SM,
873 const LangOptions &LangOpts) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000874 SourceLocation Begin = Range.getBegin();
875 SourceLocation End = Range.getEnd();
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000876 if (Begin.isInvalid() || End.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000877 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000878
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000879 if (Begin.isFileID() && End.isFileID())
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000880 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000881
882 if (Begin.isMacroID() && End.isFileID()) {
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000883 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000884 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000885 Range.setBegin(Begin);
886 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000887 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000888
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000889 if (Begin.isFileID() && End.isMacroID()) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000890 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
891 &End)) ||
892 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
893 &End)))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000894 return {};
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000895 Range.setEnd(End);
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000897 }
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000898
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000899 assert(Begin.isMacroID() && End.isMacroID());
900 SourceLocation MacroBegin, MacroEnd;
901 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000902 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
903 &MacroEnd)) ||
904 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
905 &MacroEnd)))) {
906 Range.setBegin(MacroBegin);
907 Range.setEnd(MacroEnd);
908 return makeRangeFromFileLocs(Range, SM, LangOpts);
909 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000910
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000911 bool Invalid = false;
912 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
913 &Invalid);
914 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000915 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000916
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000917 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
918 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
919 &Invalid);
920 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000921 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000922
Argyrios Kyrtzidis065d7202013-05-16 21:37:39 +0000923 if (EndEntry.getExpansion().isMacroArgExpansion() &&
924 BeginEntry.getExpansion().getExpansionLocStart() ==
925 EndEntry.getExpansion().getExpansionLocStart()) {
926 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
927 Range.setEnd(SM.getImmediateSpellingLoc(End));
928 return makeFileCharRange(Range, SM, LangOpts);
929 }
Argyrios Kyrtzidis85e76712012-01-20 16:52:43 +0000930 }
931
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000932 return {};
Argyrios Kyrtzidisa99e02d2012-01-19 15:59:14 +0000933}
934
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000935StringRef Lexer::getSourceText(CharSourceRange Range,
936 const SourceManager &SM,
937 const LangOptions &LangOpts,
938 bool *Invalid) {
Argyrios Kyrtzidis0d9e24b2012-02-03 05:58:29 +0000939 Range = makeFileCharRange(Range, SM, LangOpts);
940 if (Range.isInvalid()) {
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000941 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000942 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000943 }
944
945 // Break down the source location.
946 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
947 if (beginInfo.first.isInvalid()) {
948 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000949 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000950 }
951
952 unsigned EndOffs;
953 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
954 beginInfo.second > EndOffs) {
955 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000956 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000957 }
958
959 // Try to the load the file buffer.
960 bool invalidTemp = false;
961 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
962 if (invalidTemp) {
963 if (Invalid) *Invalid = true;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000964 return {};
Argyrios Kyrtzidis7838a2b2012-01-19 15:59:19 +0000965 }
966
967 if (Invalid) *Invalid = false;
968 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
969}
970
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000971StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
972 const SourceManager &SM,
973 const LangOptions &LangOpts) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000974 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000975
976 // Find the location of the immediate macro expansion.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000977 while (true) {
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000978 FileID FID = SM.getFileID(Loc);
979 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
980 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
981 Loc = Expansion.getExpansionLocStart();
982 if (!Expansion.isMacroArgExpansion())
983 break;
984
985 // For macro arguments we need to check that the argument did not come
986 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
Taewook Ohcebac482017-12-06 17:00:53 +0000987
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000988 // Loc points to the argument id of the macro definition, move to the
989 // macro expansion.
Anna Zaks1bea4bf2012-01-18 20:17:16 +0000990 Loc = SM.getImmediateExpansionRange(Loc).first;
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +0000991 SourceLocation SpellLoc = Expansion.getSpellingLoc();
992 if (SpellLoc.isFileID())
993 break; // No inner macro.
994
995 // If spelling location resides in the same FileID as macro expansion
996 // location, it means there is no inner macro.
997 FileID MacroFID = SM.getFileID(Loc);
998 if (SM.isInFileID(SpellLoc, MacroFID))
999 break;
1000
1001 // Argument came from inner macro.
1002 Loc = SpellLoc;
1003 }
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001004
1005 // Find the spelling location of the start of the non-argument expansion
1006 // range. This is where the macro name was spelled in order to begin
1007 // expanding this macro.
Argyrios Kyrtzidisabff5f12012-01-23 16:58:33 +00001008 Loc = SM.getSpellingLoc(Loc);
Anna Zaks1bea4bf2012-01-18 20:17:16 +00001009
1010 // Dig out the buffer where the macro name was spelled and the extents of the
1011 // name so that we can render it into the expansion note.
1012 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1013 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1014 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1015 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1016}
1017
Richard Trieu3a5c9582016-01-26 02:51:55 +00001018StringRef Lexer::getImmediateMacroNameForDiagnostics(
1019 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001020 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
Richard Trieu3a5c9582016-01-26 02:51:55 +00001021 // Walk past macro argument expanions.
1022 while (SM.isMacroArgExpansion(Loc))
1023 Loc = SM.getImmediateExpansionRange(Loc).first;
1024
1025 // If the macro's spelling has no FileID, then it's actually a token paste
1026 // or stringization (or similar) and not a macro at all.
1027 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001028 return {};
Richard Trieu3a5c9582016-01-26 02:51:55 +00001029
1030 // Find the spelling location of the start of the non-argument expansion
1031 // range. This is where the macro name was spelled in order to begin
1032 // expanding this macro.
1033 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1034
1035 // Dig out the buffer where the macro name was spelled and the extents of the
1036 // name so that we can render it into the expansion note.
1037 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1038 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1039 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1040 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1041}
1042
Jordan Rose288c4212012-06-07 01:10:31 +00001043bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
Jordan Rosea2100d72013-02-08 22:30:22 +00001044 return isIdentifierBody(c, LangOpts.DollarIdents);
Jordan Rose288c4212012-06-07 01:10:31 +00001045}
1046
Alexander Kornienkocf007a72017-08-10 10:06:16 +00001047bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1048 assert(isVerticalWhitespace(Str[0]));
1049 if (Str - 1 < BufferStart)
1050 return false;
1051
1052 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1053 (Str[0] == '\r' && Str[-1] == '\n')) {
1054 if (Str - 2 < BufferStart)
1055 return false;
1056 --Str;
1057 }
1058 --Str;
1059
1060 // Rewind to first non-space character:
1061 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1062 --Str;
1063
1064 return *Str == '\\';
1065}
1066
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001067StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1068 const SourceManager &SM) {
1069 if (Loc.isInvalid() || Loc.isMacroID())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001070 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001071 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1072 if (LocInfo.first.isInvalid())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001073 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001074 bool Invalid = false;
1075 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1076 if (Invalid)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001077 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001078 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1079 if (!Line)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001080 return {};
Alex Lorenz9c5c2bf2017-05-05 16:42:44 +00001081 StringRef Rest = Buffer.substr(Line - Buffer.data());
1082 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1083 return NumWhitespaceChars == StringRef::npos
1084 ? ""
1085 : Rest.take_front(NumWhitespaceChars);
1086}
1087
Chris Lattner22eb9722006-06-18 05:43:12 +00001088//===----------------------------------------------------------------------===//
1089// Diagnostics forwarding code.
1090//===----------------------------------------------------------------------===//
1091
Chris Lattner619c1742007-07-22 18:38:25 +00001092/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001093/// lexer buffer was all expanded at a single point, perform the mapping.
Chris Lattner619c1742007-07-22 18:38:25 +00001094/// This is currently only used for _Pragma implementation, so it is the slow
1095/// path of the hot getSourceLocation method. Do not allow it to be inlined.
Chandler Carruthc3ce5842010-10-23 08:44:57 +00001096static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1097 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001098static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1099 SourceLocation FileLoc,
Chris Lattner4fa23622009-01-26 00:43:02 +00001100 unsigned CharNo, unsigned TokLen) {
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001101 assert(FileLoc.isMacroID() && "Must be a macro expansion");
Mike Stump11289f42009-09-09 15:08:12 +00001102
Chris Lattner619c1742007-07-22 18:38:25 +00001103 // Otherwise, we're lexing "mapped tokens". This is used for things like
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001104 // _Pragma handling. Combine the expansion location of FileLoc with the
Chris Lattner53e384f2009-01-16 07:00:02 +00001105 // spelling location.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001106 SourceManager &SM = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chandler Carruthe2c09eb2011-07-14 08:20:40 +00001108 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
Chris Lattner53e384f2009-01-16 07:00:02 +00001109 // characters come from spelling(FileLoc)+Offset.
Chris Lattner9dc9c202009-02-15 20:52:18 +00001110 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001111 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattner9dc9c202009-02-15 20:52:18 +00001113 // Figure out the expansion loc range, which is the range covered by the
1114 // original _Pragma(...) sequence.
1115 std::pair<SourceLocation,SourceLocation> II =
Chandler Carruthca757582011-07-25 20:52:21 +00001116 SM.getImmediateExpansionRange(FileLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001117
Chandler Carruth115b0772011-07-26 03:03:05 +00001118 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
Chris Lattner619c1742007-07-22 18:38:25 +00001119}
1120
Chris Lattner22eb9722006-06-18 05:43:12 +00001121/// getSourceLocation - Return a source location identifier for the specified
1122/// offset in the current file.
Chris Lattner4fa23622009-01-26 00:43:02 +00001123SourceLocation Lexer::getSourceLocation(const char *Loc,
1124 unsigned TokLen) const {
Chris Lattner5d1c0272007-07-22 18:44:36 +00001125 assert(Loc >= BufferStart && Loc <= BufferEnd &&
Chris Lattner4cca5ba2006-07-02 20:05:54 +00001126 "Location out of range for this buffer!");
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001127
1128 // In the normal case, we're just lexing from a simple file buffer, return
1129 // the file id from FileLoc with the offset specified.
Chris Lattner5d1c0272007-07-22 18:44:36 +00001130 unsigned CharNo = Loc-BufferStart;
Chris Lattnerdc5c0552007-07-20 16:37:10 +00001131 if (FileLoc.isFileID())
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001132 return FileLoc.getLocWithOffset(CharNo);
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattnerd32480d2009-01-17 06:22:33 +00001134 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1135 // tokens are lexed from where the _Pragma was defined.
Chris Lattner02b436a2007-10-17 20:41:00 +00001136 assert(PP && "This doesn't work on raw lexers");
Chris Lattner4fa23622009-01-26 00:43:02 +00001137 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
Chris Lattner22eb9722006-06-18 05:43:12 +00001138}
1139
Chris Lattner22eb9722006-06-18 05:43:12 +00001140/// Diag - Forwarding function for diagnostics. This translate a source
1141/// position in the current buffer into a SourceLocation object for rendering.
Chris Lattner427c9c12008-11-22 00:59:29 +00001142DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
Chris Lattner907dfe92008-11-18 07:59:24 +00001143 return PP->Diag(getSourceLocation(Loc), DiagID);
Chris Lattner22eb9722006-06-18 05:43:12 +00001144}
1145
1146//===----------------------------------------------------------------------===//
1147// Trigraph and Escaped Newline Handling Code.
1148//===----------------------------------------------------------------------===//
1149
1150/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1151/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1152static char GetTrigraphCharForLetter(char Letter) {
1153 switch (Letter) {
1154 default: return 0;
1155 case '=': return '#';
1156 case ')': return ']';
1157 case '(': return '[';
1158 case '!': return '|';
1159 case '\'': return '^';
1160 case '>': return '}';
1161 case '/': return '\\';
1162 case '<': return '{';
1163 case '-': return '~';
1164 }
1165}
1166
1167/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1168/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1169/// return the result character. Finally, emit a warning about trigraph use
1170/// whether trigraphs are enabled or not.
1171static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1172 char Res = GetTrigraphCharForLetter(*CP);
Chris Lattner907dfe92008-11-18 07:59:24 +00001173 if (!Res || !L) return Res;
Mike Stump11289f42009-09-09 15:08:12 +00001174
David Blaikiebbafb8a2012-03-11 07:00:24 +00001175 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00001176 if (!L->isLexingRawMode())
1177 L->Diag(CP-2, diag::trigraph_ignored);
Chris Lattner907dfe92008-11-18 07:59:24 +00001178 return 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattner6d27a162008-11-22 02:02:22 +00001181 if (!L->isLexingRawMode())
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001182 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
Chris Lattner22eb9722006-06-18 05:43:12 +00001183 return Res;
1184}
1185
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001186/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1187/// 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 +00001188/// trigraph equivalent on entry to this function.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001189unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1190 unsigned Size = 0;
1191 while (isWhitespace(Ptr[Size])) {
1192 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001193
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001194 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1195 continue;
1196
1197 // If this is a \r\n or \n\r, skip the other half.
1198 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1199 Ptr[Size-1] != Ptr[Size])
1200 ++Size;
Mike Stump11289f42009-09-09 15:08:12 +00001201
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001202 return Size;
Mike Stump11289f42009-09-09 15:08:12 +00001203 }
1204
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001205 // Not an escaped newline, must be a \t or something else.
1206 return 0;
1207}
1208
Chris Lattner38b2cde2009-04-18 22:27:02 +00001209/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1210/// them), skip over them and return the first non-escaped-newline found,
1211/// otherwise return P.
1212const char *Lexer::SkipEscapedNewLines(const char *P) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001213 while (true) {
Chris Lattner38b2cde2009-04-18 22:27:02 +00001214 const char *AfterEscape;
1215 if (*P == '\\') {
1216 AfterEscape = P+1;
1217 } else if (*P == '?') {
1218 // If not a trigraph for escape, bail out.
1219 if (P[1] != '?' || P[2] != '/')
1220 return P;
Richard Smith4c132e52017-04-18 21:45:04 +00001221 // FIXME: Take LangOpts into account; the language might not
1222 // support trigraphs.
Chris Lattner38b2cde2009-04-18 22:27:02 +00001223 AfterEscape = P+3;
1224 } else {
1225 return P;
1226 }
Mike Stump11289f42009-09-09 15:08:12 +00001227
Chris Lattner38b2cde2009-04-18 22:27:02 +00001228 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1229 if (NewLineSize == 0) return P;
1230 P = AfterEscape+NewLineSize;
1231 }
1232}
1233
Alex Lorenzebbbb812017-11-03 18:11:22 +00001234Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1235 const SourceManager &SM,
1236 const LangOptions &LangOpts) {
Anna Zaks59a3c802011-07-27 21:43:43 +00001237 if (Loc.isMacroID()) {
Argyrios Kyrtzidis1b07c342012-01-19 15:59:08 +00001238 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
Alex Lorenzebbbb812017-11-03 18:11:22 +00001239 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001240 }
1241 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1242
1243 // Break down the source location.
1244 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1245
1246 // Try to load the file buffer.
1247 bool InvalidTemp = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001248 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
Anna Zaks59a3c802011-07-27 21:43:43 +00001249 if (InvalidTemp)
Alex Lorenzebbbb812017-11-03 18:11:22 +00001250 return None;
Anna Zaks59a3c802011-07-27 21:43:43 +00001251
1252 const char *TokenBegin = File.data() + LocInfo.second;
1253
1254 // Lex from the start of the given location.
1255 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1256 TokenBegin, File.end());
1257 // Find the token.
1258 Token Tok;
1259 lexer.LexFromRawLexer(Tok);
Alex Lorenzebbbb812017-11-03 18:11:22 +00001260 return Tok;
1261}
1262
1263/// \brief Checks that the given token is the first token that occurs after the
1264/// given location (this excludes comments and whitespace). Returns the location
1265/// immediately after the specified token. If the token is not found or the
1266/// location is inside a macro, the returned source location will be invalid.
1267SourceLocation Lexer::findLocationAfterToken(
1268 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1269 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1270 Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1271 if (!Tok || Tok->isNot(TKind))
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001272 return {};
Alex Lorenzebbbb812017-11-03 18:11:22 +00001273 SourceLocation TokenLoc = Tok->getLocation();
Anna Zaks59a3c802011-07-27 21:43:43 +00001274
1275 // Calculate how much whitespace needs to be skipped if any.
1276 unsigned NumWhitespaceChars = 0;
1277 if (SkipTrailingWhitespaceAndNewLine) {
Alex Lorenzebbbb812017-11-03 18:11:22 +00001278 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
Anna Zaks59a3c802011-07-27 21:43:43 +00001279 unsigned char C = *TokenEnd;
1280 while (isHorizontalWhitespace(C)) {
1281 C = *(++TokenEnd);
1282 NumWhitespaceChars++;
1283 }
Eli Friedmanb699e612012-11-14 01:28:38 +00001284
1285 // Skip \r, \n, \r\n, or \n\r
1286 if (C == '\n' || C == '\r') {
1287 char PrevC = C;
1288 C = *(++TokenEnd);
Anna Zaks59a3c802011-07-27 21:43:43 +00001289 NumWhitespaceChars++;
Eli Friedmanb699e612012-11-14 01:28:38 +00001290 if ((C == '\n' || C == '\r') && C != PrevC)
1291 NumWhitespaceChars++;
1292 }
Anna Zaks59a3c802011-07-27 21:43:43 +00001293 }
1294
Alex Lorenzebbbb812017-11-03 18:11:22 +00001295 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
Anna Zaks59a3c802011-07-27 21:43:43 +00001296}
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001297
Chris Lattner22eb9722006-06-18 05:43:12 +00001298/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1299/// get its size, and return it. This is tricky in several cases:
1300/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1301/// then either return the trigraph (skipping 3 chars) or the '?',
1302/// depending on whether trigraphs are enabled or not.
1303/// 2. If this is an escaped newline (potentially with whitespace between
1304/// the backslash and newline), implicitly skip the newline and return
1305/// the char after it.
Chris Lattner22eb9722006-06-18 05:43:12 +00001306///
1307/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1308/// know that we can accumulate into Size, and that we have already incremented
1309/// Ptr by Size bytes.
1310///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001311/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1312/// be updated to match.
Chris Lattner22eb9722006-06-18 05:43:12 +00001313char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
Chris Lattner146762e2007-07-20 16:59:19 +00001314 Token *Tok) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001315 // If we have a slash, look for an escaped newline.
1316 if (Ptr[0] == '\\') {
1317 ++Size;
1318 ++Ptr;
1319Slash:
1320 // Common case, backslash-char where the char is not whitespace.
1321 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001322
Chris Lattnerc1835952009-06-23 05:15:06 +00001323 // See if we have optional whitespace characters between the slash and
1324 // newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001325 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1326 // Remember that this token needs to be cleaned.
1327 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001328
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001329 // Warn if there was whitespace between the backslash and newline.
Chris Lattnerc1835952009-06-23 05:15:06 +00001330 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001331 Diag(Ptr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001333 // Found backslash<whitespace><newline>. Parse the char after it.
1334 Size += EscapedNewLineSize;
1335 Ptr += EscapedNewLineSize;
Argyrios Kyrtzidise5cdd082011-12-21 20:19:55 +00001336
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001337 // Use slow version to accumulate a correct size field.
1338 return getCharAndSizeSlow(Ptr, Size, Tok);
1339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattner22eb9722006-06-18 05:43:12 +00001341 // Otherwise, this is not an escaped newline, just return the slash.
1342 return '\\';
1343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Chris Lattner22eb9722006-06-18 05:43:12 +00001345 // If this is a trigraph, process it.
1346 if (Ptr[0] == '?' && Ptr[1] == '?') {
1347 // If this is actually a legal trigraph (not something like "??x"), emit
1348 // a trigraph warning. If so, and if trigraphs are enabled, return it.
Craig Topperd2d442c2014-05-17 23:10:59 +00001349 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001350 // Remember that this token needs to be cleaned.
Chris Lattner146762e2007-07-20 16:59:19 +00001351 if (Tok) Tok->setFlag(Token::NeedsCleaning);
Chris Lattner22eb9722006-06-18 05:43:12 +00001352
1353 Ptr += 3;
1354 Size += 3;
1355 if (C == '\\') goto Slash;
1356 return C;
1357 }
1358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
Chris Lattner22eb9722006-06-18 05:43:12 +00001360 // If this is neither, return a single character.
1361 ++Size;
1362 return *Ptr;
1363}
1364
1365/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1366/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1367/// and that we have already incremented Ptr by Size bytes.
1368///
Chris Lattnerd01e2912006-06-18 16:22:51 +00001369/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1370/// be updated to match.
1371char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001372 const LangOptions &LangOpts) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001373 // If we have a slash, look for an escaped newline.
1374 if (Ptr[0] == '\\') {
1375 ++Size;
1376 ++Ptr;
1377Slash:
1378 // Common case, backslash-char where the char is not whitespace.
1379 if (!isWhitespace(Ptr[0])) return '\\';
Mike Stump11289f42009-09-09 15:08:12 +00001380
Chris Lattner22eb9722006-06-18 05:43:12 +00001381 // See if we have optional whitespace characters followed by a newline.
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001382 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1383 // Found backslash<whitespace><newline>. Parse the char after it.
1384 Size += EscapedNewLineSize;
1385 Ptr += EscapedNewLineSize;
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001387 // Use slow version to accumulate a correct size field.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001388 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
Chris Lattnerfbce7aa2009-04-18 22:05:41 +00001389 }
Mike Stump11289f42009-09-09 15:08:12 +00001390
Chris Lattner22eb9722006-06-18 05:43:12 +00001391 // Otherwise, this is not an escaped newline, just return the slash.
1392 return '\\';
1393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattner22eb9722006-06-18 05:43:12 +00001395 // If this is a trigraph, process it.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001396 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
Chris Lattner22eb9722006-06-18 05:43:12 +00001397 // If this is actually a legal trigraph (not something like "??x"), return
1398 // it.
1399 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1400 Ptr += 3;
1401 Size += 3;
1402 if (C == '\\') goto Slash;
1403 return C;
1404 }
1405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattner22eb9722006-06-18 05:43:12 +00001407 // If this is neither, return a single character.
1408 ++Size;
1409 return *Ptr;
1410}
1411
Chris Lattner22eb9722006-06-18 05:43:12 +00001412//===----------------------------------------------------------------------===//
1413// Helper methods for lexing.
1414//===----------------------------------------------------------------------===//
1415
Cameron Desrochers84fd0642017-09-20 19:03:37 +00001416/// \brief Routine that indiscriminately sets the offset into the source file.
1417void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1418 BufferPtr = BufferStart + Offset;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001419 if (BufferPtr > BufferEnd)
1420 BufferPtr = BufferEnd;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001421 // FIXME: What exactly does the StartOfLine bit mean? There are two
1422 // possible meanings for the "start" of the line: the first token on the
1423 // unexpanded line, or the first token on the expanded line.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001424 IsAtStartOfLine = StartOfLine;
Eli Friedman0834a4b2013-09-19 00:41:32 +00001425 IsAtPhysicalStartOfLine = StartOfLine;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001426}
1427
Jordan Rose58c61e02013-02-09 01:10:25 +00001428static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001429 if (LangOpts.AsmPreprocessor) {
1430 return false;
1431 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001432 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1433 C11AllowedIDCharRanges);
1434 return C11AllowedIDChars.contains(C);
1435 } else if (LangOpts.CPlusPlus) {
1436 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1437 CXX03AllowedIDCharRanges);
1438 return CXX03AllowedIDChars.contains(C);
1439 } else {
1440 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1441 C99AllowedIDCharRanges);
1442 return C99AllowedIDChars.contains(C);
1443 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001444}
1445
Jordan Rose58c61e02013-02-09 01:10:25 +00001446static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1447 assert(isAllowedIDChar(C, LangOpts));
Vinicius Tinti92e68c22015-11-20 23:42:39 +00001448 if (LangOpts.AsmPreprocessor) {
1449 return false;
1450 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001451 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1452 C11DisallowedInitialIDCharRanges);
1453 return !C11DisallowedInitialIDChars.contains(C);
1454 } else if (LangOpts.CPlusPlus) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001455 return true;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001456 } else {
1457 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1458 C99DisallowedInitialIDCharRanges);
1459 return !C99DisallowedInitialIDChars.contains(C);
1460 }
Jordan Rose58c61e02013-02-09 01:10:25 +00001461}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001462
Jordan Rose58c61e02013-02-09 01:10:25 +00001463static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1464 const char *End) {
1465 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1466 L.getSourceLocation(End));
1467}
1468
1469static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1470 CharSourceRange Range, bool IsFirst) {
1471 // Check C99 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001472 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001473 enum {
1474 CannotAppearInIdentifier = 0,
1475 CannotStartIdentifier
1476 };
1477
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001478 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1479 C99AllowedIDCharRanges);
1480 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1481 C99DisallowedInitialIDCharRanges);
1482 if (!C99AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001483 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1484 << Range
1485 << CannotAppearInIdentifier;
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001486 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001487 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1488 << Range
1489 << CannotStartIdentifier;
1490 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001491 }
1492
Jordan Rose58c61e02013-02-09 01:10:25 +00001493 // Check C++98 compatibility.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001494 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00001495 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1496 CXX03AllowedIDCharRanges);
1497 if (!CXX03AllowedIDChars.contains(C)) {
Jordan Rose58c61e02013-02-09 01:10:25 +00001498 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1499 << Range;
1500 }
1501 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001502}
1503
Richard Smith77091b12017-12-14 13:15:08 +00001504/// After encountering UTF-8 character C and interpreting it as an identifier
1505/// character, check whether it's a homoglyph for a common non-identifier
1506/// source character that is unlikely to be an intentional identifier
1507/// character and warn if so.
1508static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1509 CharSourceRange Range) {
1510 // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1511 struct HomoglyphPair {
1512 uint32_t Character;
1513 char LooksLike;
1514 bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1515 };
1516 static constexpr HomoglyphPair SortedHomoglyphs[] = {
1517 {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1518 {U'\u037e', ';'}, // GREEK QUESTION MARK
1519 {U'\u2212', '-'}, // MINUS SIGN
1520 {U'\u2215', '/'}, // DIVISION SLASH
1521 {U'\u2216', '\\'}, // SET MINUS
1522 {U'\u2217', '*'}, // ASTERISK OPERATOR
1523 {U'\u2223', '|'}, // DIVIDES
1524 {U'\u2227', '^'}, // LOGICAL AND
1525 {U'\u2236', ':'}, // RATIO
1526 {U'\u223c', '~'}, // TILDE OPERATOR
1527 {U'\ua789', ':'}, // MODIFIER LETTER COLON
1528 {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1529 {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1530 {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1531 {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1532 {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1533 {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1534 {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1535 {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1536 {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1537 {U'\uff0c', ','}, // FULLWIDTH COMMA
1538 {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1539 {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1540 {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1541 {U'\uff1a', ':'}, // FULLWIDTH COLON
1542 {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1543 {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1544 {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1545 {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1546 {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1547 {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1548 {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1549 {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1550 {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1551 {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1552 {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1553 {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1554 {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1555 {U'\uff5e', '~'}, // FULLWIDTH TILDE
1556 {0, 0}
1557 };
1558 auto Homoglyph =
1559 std::lower_bound(std::begin(SortedHomoglyphs),
1560 std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1561 if (Homoglyph->Character == C) {
1562 llvm::SmallString<5> CharBuf;
1563 {
1564 llvm::raw_svector_ostream CharOS(CharBuf);
1565 llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1566 }
1567 const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1568 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1569 << Range << CharBuf << LooksLikeStr;
1570 }
1571}
1572
Richard Smith8b7258b2014-02-17 21:52:30 +00001573bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1574 Token &Result) {
1575 const char *UCNPtr = CurPtr + Size;
Craig Topperd2d442c2014-05-17 23:10:59 +00001576 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
Richard Smith8b7258b2014-02-17 21:52:30 +00001577 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1578 return false;
1579
1580 if (!isLexingRawMode())
1581 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1582 makeCharRange(*this, CurPtr, UCNPtr),
1583 /*IsFirst=*/false);
1584
1585 Result.setFlag(Token::HasUCN);
1586 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1587 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1588 CurPtr = UCNPtr;
1589 else
1590 while (CurPtr != UCNPtr)
1591 (void)getAndAdvanceChar(CurPtr, Result);
1592 return true;
1593}
1594
1595bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1596 const char *UnicodePtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00001597 llvm::UTF32 CodePoint;
1598 llvm::ConversionResult Result =
1599 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1600 (const llvm::UTF8 *)BufferEnd,
Richard Smith8b7258b2014-02-17 21:52:30 +00001601 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00001602 llvm::strictConversion);
1603 if (Result != llvm::conversionOK ||
Richard Smith8b7258b2014-02-17 21:52:30 +00001604 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1605 return false;
1606
Richard Smith77091b12017-12-14 13:15:08 +00001607 if (!isLexingRawMode()) {
Richard Smith8b7258b2014-02-17 21:52:30 +00001608 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1609 makeCharRange(*this, CurPtr, UnicodePtr),
1610 /*IsFirst=*/false);
Richard Smith77091b12017-12-14 13:15:08 +00001611 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1612 makeCharRange(*this, CurPtr, UnicodePtr));
1613 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001614
1615 CurPtr = UnicodePtr;
1616 return true;
1617}
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001618
Eli Friedman0834a4b2013-09-19 00:41:32 +00001619bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001620 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1621 unsigned Size;
1622 unsigned char C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001623 while (isIdentifierBody(C))
Chris Lattner22eb9722006-06-18 05:43:12 +00001624 C = *CurPtr++;
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001625
Chris Lattner22eb9722006-06-18 05:43:12 +00001626 --CurPtr; // Back up over the skipped character.
1627
1628 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1629 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
Chris Lattner21d9b9a2010-01-11 02:38:50 +00001630 //
Jordan Rosea2100d72013-02-08 22:30:22 +00001631 // TODO: Could merge these checks into an InfoTable flag to make the
1632 // comparison cheaper
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001633 if (isASCII(C) && C != '\\' && C != '?' &&
1634 (C != '$' || !LangOpts.DollarIdents)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001635FinishIdentifier:
Chris Lattnercefc7682006-07-08 08:28:12 +00001636 const char *IdStart = BufferPtr;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001637 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1638 Result.setRawIdentifierData(IdStart);
Mike Stump11289f42009-09-09 15:08:12 +00001639
Chris Lattner0f1f5052006-07-20 04:16:23 +00001640 // If we are in raw mode, return this identifier raw. There is no need to
1641 // look up identifier information or attempt to macro expand it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001642 if (LexingRawMode)
Eli Friedman0834a4b2013-09-19 00:41:32 +00001643 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001644
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +00001645 // Fill in Result.IdentifierInfo and update the token kind,
1646 // looking up the identifier in the identifier table.
1647 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
Ilya Biryukovb3510c42018-04-24 13:48:53 +00001648 // Note that we have to call PP->LookUpIdentifierInfo() even for code
1649 // completion, it writes IdentifierInfo into Result, and callers rely on it.
1650
1651 // If the completion point is at the end of an identifier, we want to treat
1652 // the identifier as incomplete even if it resolves to a macro or a keyword.
1653 // This allows e.g. 'class^' to complete to 'classifier'.
1654 if (isCodeCompletionPoint(CurPtr)) {
1655 // Return the code-completion token.
1656 Result.setKind(tok::code_completion);
1657 cutOffLexing();
1658 return true;
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
Chris Lattnerc5a00062006-06-18 16:41:01 +00001661 // Finally, now that we know we have an identifier, pass this off to the
1662 // preprocessor, which may macro expand it or something.
Chris Lattner8256b972009-01-21 07:45:14 +00001663 if (II->isHandleIdentifierCase())
Eli Friedman0834a4b2013-09-19 00:41:32 +00001664 return PP->HandleIdentifier(Result);
Vassil Vassilev644ea612016-07-27 14:56:59 +00001665
Eli Friedman0834a4b2013-09-19 00:41:32 +00001666 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001667 }
Mike Stump11289f42009-09-09 15:08:12 +00001668
Chris Lattner22eb9722006-06-18 05:43:12 +00001669 // Otherwise, $,\,? in identifier found. Enter slower path.
Mike Stump11289f42009-09-09 15:08:12 +00001670
Chris Lattner22eb9722006-06-18 05:43:12 +00001671 C = getCharAndSize(CurPtr, Size);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001672 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001673 if (C == '$') {
1674 // If we hit a $ and they are not supported in identifiers, we are done.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001675 if (!LangOpts.DollarIdents) goto FinishIdentifier;
Mike Stump11289f42009-09-09 15:08:12 +00001676
Chris Lattner22eb9722006-06-18 05:43:12 +00001677 // Otherwise, emit a diagnostic and continue.
Chris Lattner6d27a162008-11-22 02:02:22 +00001678 if (!isLexingRawMode())
1679 Diag(CurPtr, diag::ext_dollar_in_identifier);
Chris Lattner22eb9722006-06-18 05:43:12 +00001680 CurPtr = ConsumeChar(CurPtr, Size, Result);
1681 C = getCharAndSize(CurPtr, Size);
1682 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001683 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001684 C = getCharAndSize(CurPtr, Size);
1685 continue;
Richard Smith8b7258b2014-02-17 21:52:30 +00001686 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001687 C = getCharAndSize(CurPtr, Size);
1688 continue;
1689 } else if (!isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001690 goto FinishIdentifier;
1691 }
1692
1693 // Otherwise, this character is good, consume it.
1694 CurPtr = ConsumeChar(CurPtr, Size, Result);
1695
1696 C = getCharAndSize(CurPtr, Size);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00001697 while (isIdentifierBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001698 CurPtr = ConsumeChar(CurPtr, Size, Result);
1699 C = getCharAndSize(CurPtr, Size);
1700 }
1701 }
1702}
1703
Douglas Gregor759ef232010-08-30 14:50:47 +00001704/// isHexaLiteral - Return true if Start points to a hex constant.
Chris Lattner5f183aa2010-08-30 17:11:14 +00001705/// in microsoft mode (where this is supposed to be several different tokens).
Eli Friedman324adad2012-08-31 02:29:37 +00001706bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
Chris Lattner0f0492e2010-08-31 16:42:00 +00001707 unsigned Size;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001708 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001709 if (C1 != '0')
1710 return false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001711 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
Chris Lattner0f0492e2010-08-31 16:42:00 +00001712 return (C2 == 'x' || C2 == 'X');
Douglas Gregor759ef232010-08-30 14:50:47 +00001713}
Chris Lattner22eb9722006-06-18 05:43:12 +00001714
Nate Begeman5eee9332008-04-14 02:26:39 +00001715/// LexNumericConstant - Lex the remainder of a integer or floating point
Chris Lattner22eb9722006-06-18 05:43:12 +00001716/// constant. From[-1] is the first character lexed. Return the end of the
1717/// constant.
Eli Friedman0834a4b2013-09-19 00:41:32 +00001718bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001719 unsigned Size;
1720 char C = getCharAndSize(CurPtr, Size);
1721 char PrevCh = 0;
Richard Smith8b7258b2014-02-17 21:52:30 +00001722 while (isPreprocessingNumberBody(C)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00001723 CurPtr = ConsumeChar(CurPtr, Size, Result);
1724 PrevCh = C;
1725 C = getCharAndSize(CurPtr, Size);
1726 }
Mike Stump11289f42009-09-09 15:08:12 +00001727
Chris Lattner22eb9722006-06-18 05:43:12 +00001728 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001729 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1730 // If we are in Microsoft mode, don't continue if the constant is hex.
1731 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
David Blaikiebbafb8a2012-03-11 07:00:24 +00001732 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
Chris Lattner7a9e9e72010-08-30 17:09:08 +00001733 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1734 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001735
1736 // If we have a hex FP constant, continue.
Richard Smithe6799dd2012-06-15 05:07:49 +00001737 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
Richard Smith560a3572016-03-04 22:32:06 +00001738 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
Richard Smithe6799dd2012-06-15 05:07:49 +00001739 // not-quite-conforming extension. Only do so if this looks like it's
1740 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1741 bool IsHexFloat = true;
1742 if (!LangOpts.C99) {
1743 if (!isHexaLiteral(BufferPtr, LangOpts))
1744 IsHexFloat = false;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001745 else if (!getLangOpts().CPlusPlus17 &&
Richard Smith560a3572016-03-04 22:32:06 +00001746 std::find(BufferPtr, CurPtr, '_') != CurPtr)
Richard Smithe6799dd2012-06-15 05:07:49 +00001747 IsHexFloat = false;
1748 }
1749 if (IsHexFloat)
1750 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
Richard Smithfde94852013-09-26 03:33:06 +00001753 // If we have a digit separator, continue.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001754 if (C == '\'' && getLangOpts().CPlusPlus14) {
Richard Smithfde94852013-09-26 03:33:06 +00001755 unsigned NextSize;
1756 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
Richard Smith7f2707a2013-09-26 18:13:20 +00001757 if (isIdentifierBody(Next)) {
Richard Smithfde94852013-09-26 03:33:06 +00001758 if (!isLexingRawMode())
1759 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1760 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smith35ddad02014-02-28 20:06:02 +00001761 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
Richard Smithfde94852013-09-26 03:33:06 +00001762 return LexNumericConstant(Result, CurPtr);
1763 }
1764 }
1765
Richard Smith8b7258b2014-02-17 21:52:30 +00001766 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1767 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1768 return LexNumericConstant(Result, CurPtr);
1769 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1770 return LexNumericConstant(Result, CurPtr);
1771
Chris Lattnerd01e2912006-06-18 16:22:51 +00001772 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001773 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001774 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001775 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001776 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001777}
1778
Richard Smithe18f0fa2012-03-05 04:02:15 +00001779/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
Richard Smith3e4a60a2012-03-07 03:13:00 +00001780/// in C++11, or warn on a ud-suffix in C++98.
Richard Smithf4198b72013-07-23 08:14:48 +00001781const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1782 bool IsStringLiteral) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 assert(getLangOpts().CPlusPlus);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001784
Richard Smith8b7258b2014-02-17 21:52:30 +00001785 // Maximally munch an identifier.
Richard Smithe18f0fa2012-03-05 04:02:15 +00001786 unsigned Size;
1787 char C = getCharAndSize(CurPtr, Size);
Richard Smith8b7258b2014-02-17 21:52:30 +00001788 bool Consumed = false;
Richard Smith0df56f42012-03-08 02:39:21 +00001789
Richard Smith8b7258b2014-02-17 21:52:30 +00001790 if (!isIdentifierHead(C)) {
1791 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1792 Consumed = true;
1793 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1794 Consumed = true;
1795 else
1796 return CurPtr;
1797 }
1798
1799 if (!getLangOpts().CPlusPlus11) {
1800 if (!isLexingRawMode())
1801 Diag(CurPtr,
1802 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1803 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1804 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1805 return CurPtr;
1806 }
1807
1808 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1809 // that does not start with an underscore is ill-formed. As a conforming
1810 // extension, we treat all such suffixes as if they had whitespace before
1811 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1812 // likely to be a ud-suffix than a macro, however, and accept that.
1813 if (!Consumed) {
Richard Smithf4198b72013-07-23 08:14:48 +00001814 bool IsUDSuffix = false;
1815 if (C == '_')
1816 IsUDSuffix = true;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001817 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
Richard Smith2a988622013-09-24 04:06:10 +00001818 // In C++1y, we need to look ahead a few characters to see if this is a
1819 // valid suffix for a string literal or a numeric literal (this could be
1820 // the 'operator""if' defining a numeric literal operator).
Richard Smith5acb7592013-09-24 22:13:21 +00001821 const unsigned MaxStandardSuffixLength = 3;
Richard Smith2a988622013-09-24 04:06:10 +00001822 char Buffer[MaxStandardSuffixLength] = { C };
1823 unsigned Consumed = Size;
1824 unsigned Chars = 1;
1825 while (true) {
1826 unsigned NextSize;
1827 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1828 getLangOpts());
1829 if (!isIdentifierBody(Next)) {
1830 // End of suffix. Check whether this is on the whitelist.
Eric Fiseliercb2f3262016-12-30 04:51:10 +00001831 const StringRef CompleteSuffix(Buffer, Chars);
1832 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1833 CompleteSuffix);
Richard Smith2a988622013-09-24 04:06:10 +00001834 break;
1835 }
1836
1837 if (Chars == MaxStandardSuffixLength)
1838 // Too long: can't be a standard suffix.
1839 break;
1840
1841 Buffer[Chars++] = Next;
1842 Consumed += NextSize;
1843 }
Richard Smithf4198b72013-07-23 08:14:48 +00001844 }
1845
1846 if (!IsUDSuffix) {
Richard Smith0df56f42012-03-08 02:39:21 +00001847 if (!isLexingRawMode())
Alp Tokerbfa39342014-01-14 12:51:41 +00001848 Diag(CurPtr, getLangOpts().MSVCCompat
1849 ? diag::ext_ms_reserved_user_defined_literal
1850 : diag::ext_reserved_user_defined_literal)
Richard Smith8b7258b2014-02-17 21:52:30 +00001851 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
Richard Smith3e4a60a2012-03-07 03:13:00 +00001852 return CurPtr;
1853 }
1854
Richard Smith8b7258b2014-02-17 21:52:30 +00001855 CurPtr = ConsumeChar(CurPtr, Size, Result);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001856 }
Richard Smith8b7258b2014-02-17 21:52:30 +00001857
1858 Result.setFlag(Token::HasUDSuffix);
1859 while (true) {
1860 C = getCharAndSize(CurPtr, Size);
1861 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1862 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1863 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1864 else break;
1865 }
1866
Richard Smithe18f0fa2012-03-05 04:02:15 +00001867 return CurPtr;
1868}
1869
Chris Lattner22eb9722006-06-18 05:43:12 +00001870/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
Douglas Gregorfb65e592011-07-27 05:40:30 +00001871/// either " or L" or u8" or u" or U".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001872bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00001873 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001874 // Does this string contain the \0 character?
1875 const char *NulCharacter = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001876
Richard Smithacd4d3d2011-10-15 01:18:56 +00001877 if (!isLexingRawMode() &&
1878 (Kind == tok::utf8_string_literal ||
1879 Kind == tok::utf16_string_literal ||
Richard Smith06d274f2013-03-11 18:01:42 +00001880 Kind == tok::utf32_string_literal))
1881 Diag(BufferPtr, getLangOpts().CPlusPlus
1882 ? diag::warn_cxx98_compat_unicode_literal
1883 : diag::warn_c99_compat_unicode_literal);
Richard Smithacd4d3d2011-10-15 01:18:56 +00001884
Chris Lattner22eb9722006-06-18 05:43:12 +00001885 char C = getAndAdvanceChar(CurPtr, Result);
1886 while (C != '"') {
Chris Lattner52d96ac2010-05-30 23:27:38 +00001887 // Skip escaped characters. Escaped newlines will already be processed by
1888 // getAndAdvanceChar.
1889 if (C == '\\')
Chris Lattner22eb9722006-06-18 05:43:12 +00001890 C = getAndAdvanceChar(CurPtr, Result);
Taewook Ohcebac482017-12-06 17:00:53 +00001891
Chris Lattner52d96ac2010-05-30 23:27:38 +00001892 if (C == '\n' || C == '\r' || // Newline.
Douglas Gregorfe4a4102010-05-30 22:59:50 +00001893 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001894 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00001895 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
Chris Lattnerb11c3232008-10-12 04:51:35 +00001896 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001897 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001898 }
Taewook Ohcebac482017-12-06 17:00:53 +00001899
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001900 if (C == 0) {
1901 if (isCodeCompletionPoint(CurPtr-1)) {
1902 PP->CodeCompleteNaturalLanguage();
1903 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001904 cutOffLexing();
1905 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001906 }
1907
Chris Lattner52d96ac2010-05-30 23:27:38 +00001908 NulCharacter = CurPtr-1;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001909 }
Chris Lattner22eb9722006-06-18 05:43:12 +00001910 C = getAndAdvanceChar(CurPtr, Result);
1911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
Richard Smithe18f0fa2012-03-05 04:02:15 +00001913 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001914 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001915 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00001916
Chris Lattner5a78a022006-07-20 06:02:19 +00001917 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00001918 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00001919 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Chris Lattner22eb9722006-06-18 05:43:12 +00001920
Chris Lattnerd01e2912006-06-18 16:22:51 +00001921 // Update the location of the token as well as the BufferPtr instance var.
Chris Lattner5a7971e2009-01-26 19:29:26 +00001922 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001923 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00001924 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001925 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00001926}
1927
Craig Topper54edcca2011-08-11 04:06:15 +00001928/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1929/// having lexed R", LR", u8R", uR", or UR".
Eli Friedman0834a4b2013-09-19 00:41:32 +00001930bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
Craig Topper54edcca2011-08-11 04:06:15 +00001931 tok::TokenKind Kind) {
1932 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1933 // Between the initial and final double quote characters of the raw string,
1934 // any transformations performed in phases 1 and 2 (trigraphs,
1935 // universal-character-names, and line splicing) are reverted.
1936
Richard Smithacd4d3d2011-10-15 01:18:56 +00001937 if (!isLexingRawMode())
1938 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1939
Craig Topper54edcca2011-08-11 04:06:15 +00001940 unsigned PrefixLen = 0;
1941
1942 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1943 ++PrefixLen;
1944
1945 // If the last character was not a '(', then we didn't lex a valid delimiter.
1946 if (CurPtr[PrefixLen] != '(') {
1947 if (!isLexingRawMode()) {
1948 const char *PrefixEnd = &CurPtr[PrefixLen];
1949 if (PrefixLen == 16) {
1950 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1951 } else {
1952 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1953 << StringRef(PrefixEnd, 1);
1954 }
1955 }
1956
1957 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1958 // it's possible the '"' was intended to be part of the raw string, but
1959 // there's not much we can do about that.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001960 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001961 char C = *CurPtr++;
1962
1963 if (C == '"')
1964 break;
1965 if (C == 0 && CurPtr-1 == BufferEnd) {
1966 --CurPtr;
1967 break;
1968 }
1969 }
1970
1971 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001972 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001973 }
1974
1975 // Save prefix and move CurPtr past it
1976 const char *Prefix = CurPtr;
1977 CurPtr += PrefixLen + 1; // skip over prefix and '('
1978
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001979 while (true) {
Craig Topper54edcca2011-08-11 04:06:15 +00001980 char C = *CurPtr++;
1981
1982 if (C == ')') {
1983 // Check for prefix match and closing quote.
1984 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1985 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1986 break;
1987 }
1988 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1989 if (!isLexingRawMode())
1990 Diag(BufferPtr, diag::err_unterminated_raw_string)
1991 << StringRef(Prefix, PrefixLen);
1992 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00001993 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00001994 }
1995 }
1996
Richard Smithe18f0fa2012-03-05 04:02:15 +00001997 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001998 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00001999 CurPtr = LexUDSuffix(Result, CurPtr, true);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002000
Craig Topper54edcca2011-08-11 04:06:15 +00002001 // Update the location of token as well as BufferPtr.
2002 const char *TokStart = BufferPtr;
2003 FormTokenWithChars(Result, CurPtr, Kind);
2004 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002005 return true;
Craig Topper54edcca2011-08-11 04:06:15 +00002006}
2007
Chris Lattner22eb9722006-06-18 05:43:12 +00002008/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2009/// after having lexed the '<' character. This is used for #include filenames.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002010bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002011 // Does this string contain the \0 character?
2012 const char *NulCharacter = nullptr;
Chris Lattnerb40289b2009-04-17 23:56:52 +00002013 const char *AfterLessPos = CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002014 char C = getAndAdvanceChar(CurPtr, Result);
2015 while (C != '>') {
Volodymyr Sapsaiabb8dfc2018-01-12 18:54:35 +00002016 // Skip escaped characters. Escaped newlines will already be processed by
2017 // getAndAdvanceChar.
2018 if (C == '\\')
2019 C = getAndAdvanceChar(CurPtr, Result);
2020
2021 if (C == '\n' || C == '\r' || // Newline.
2022 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
2023 isCodeCompletionPoint(CurPtr-1)))) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00002024 // If the filename is unterminated, then it must just be a lone <
2025 // character. Return this as such.
2026 FormTokenWithChars(Result, AfterLessPos, tok::less);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002027 return true;
Volodymyr Sapsaiabb8dfc2018-01-12 18:54:35 +00002028 }
2029
2030 if (C == 0) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002031 NulCharacter = CurPtr-1;
2032 }
2033 C = getAndAdvanceChar(CurPtr, Result);
2034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Chris Lattner5a78a022006-07-20 06:02:19 +00002036 // If a nul character existed in the string, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002037 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002038 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
Mike Stump11289f42009-09-09 15:08:12 +00002039
Chris Lattnerd01e2912006-06-18 16:22:51 +00002040 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002041 const char *TokStart = BufferPtr;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002042 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002043 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002044 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002045}
2046
Chris Lattner22eb9722006-06-18 05:43:12 +00002047/// LexCharConstant - Lex the remainder of a character constant, after having
Richard Smith3e3a7052014-11-08 06:08:42 +00002048/// lexed either ' or L' or u8' or u' or U'.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002049bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
Douglas Gregorfb65e592011-07-27 05:40:30 +00002050 tok::TokenKind Kind) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002051 // Does this character contain the \0 character?
2052 const char *NulCharacter = nullptr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002053
Richard Smith3e3a7052014-11-08 06:08:42 +00002054 if (!isLexingRawMode()) {
2055 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2056 Diag(BufferPtr, getLangOpts().CPlusPlus
2057 ? diag::warn_cxx98_compat_unicode_literal
2058 : diag::warn_c99_compat_unicode_literal);
2059 else if (Kind == tok::utf8_char_constant)
2060 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2061 }
Richard Smithacd4d3d2011-10-15 01:18:56 +00002062
Chris Lattner22eb9722006-06-18 05:43:12 +00002063 char C = getAndAdvanceChar(CurPtr, Result);
2064 if (C == '\'') {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002065 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Richard Smith608c0b62012-06-28 07:51:56 +00002066 Diag(BufferPtr, diag::ext_empty_character);
Chris Lattnerb11c3232008-10-12 04:51:35 +00002067 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002068 return true;
Chris Lattner86851b82010-07-07 23:24:27 +00002069 }
2070
2071 while (C != '\'') {
2072 // Skip escaped characters.
Nico Weber4e270382012-11-17 20:25:54 +00002073 if (C == '\\')
2074 C = getAndAdvanceChar(CurPtr, Result);
2075
2076 if (C == '\n' || C == '\r' || // Newline.
2077 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002078 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
Craig Topper7f5ff212015-11-14 02:09:55 +00002079 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
Chris Lattner86851b82010-07-07 23:24:27 +00002080 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002081 return true;
Nico Weber4e270382012-11-17 20:25:54 +00002082 }
2083
2084 if (C == 0) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002085 if (isCodeCompletionPoint(CurPtr-1)) {
2086 PP->CodeCompleteNaturalLanguage();
2087 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002088 cutOffLexing();
2089 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002090 }
2091
Chris Lattner86851b82010-07-07 23:24:27 +00002092 NulCharacter = CurPtr-1;
2093 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002094 C = getAndAdvanceChar(CurPtr, Result);
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Richard Smithe18f0fa2012-03-05 04:02:15 +00002097 // If we are in C++11, lex the optional ud-suffix.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002098 if (getLangOpts().CPlusPlus)
Richard Smithf4198b72013-07-23 08:14:48 +00002099 CurPtr = LexUDSuffix(Result, CurPtr, false);
Richard Smithe18f0fa2012-03-05 04:02:15 +00002100
Chris Lattner86851b82010-07-07 23:24:27 +00002101 // If a nul character existed in the character, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002102 if (NulCharacter && !isLexingRawMode())
Craig Topper7f5ff212015-11-14 02:09:55 +00002103 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00002104
Chris Lattnerd01e2912006-06-18 16:22:51 +00002105 // Update the location of token as well as BufferPtr.
Chris Lattner5a7971e2009-01-26 19:29:26 +00002106 const char *TokStart = BufferPtr;
Douglas Gregorfb65e592011-07-27 05:40:30 +00002107 FormTokenWithChars(Result, CurPtr, Kind);
Chris Lattner5a7971e2009-01-26 19:29:26 +00002108 Result.setLiteralData(TokStart);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002109 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002110}
2111
2112/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2113/// Update BufferPtr to point to the next non-whitespace character and return.
Chris Lattner4d963442008-10-12 04:05:48 +00002114///
2115/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002116bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2117 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002118 // Whitespace - Skip it, then return the token after the whitespace.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002119 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2120
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002121 unsigned char Char = *CurPtr;
2122
2123 // Skip consecutive spaces efficiently.
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002124 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002125 // Skip horizontal whitespace very aggressively.
2126 while (isHorizontalWhitespace(Char))
2127 Char = *++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002128
Daniel Dunbar5c4cc092008-11-25 00:20:22 +00002129 // Otherwise if we have something other than whitespace, we're done.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002130 if (!isVerticalWhitespace(Char))
Chris Lattner22eb9722006-06-18 05:43:12 +00002131 break;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattner22eb9722006-06-18 05:43:12 +00002133 if (ParsingPreprocessorDirective) {
2134 // End of preprocessor directive line, let LexTokenInternal handle this.
2135 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002136 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002137 }
Mike Stump11289f42009-09-09 15:08:12 +00002138
Richard Smith0f7f6f1a2013-05-10 02:36:35 +00002139 // OK, but handle newline.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002140 SawNewline = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002141 Char = *++CurPtr;
2142 }
2143
Chris Lattner4d963442008-10-12 04:05:48 +00002144 // If the client wants us to return whitespace, return it now.
2145 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002146 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002147 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002148 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002149 IsAtPhysicalStartOfLine = true;
2150 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002151 // FIXME: The next token will not have LeadingSpace set.
Chris Lattner4d963442008-10-12 04:05:48 +00002152 return true;
2153 }
Mike Stump11289f42009-09-09 15:08:12 +00002154
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002155 // If this isn't immediately after a newline, there is leading space.
2156 char PrevChar = CurPtr[-1];
2157 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2158
2159 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002160 if (SawNewline) {
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002161 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002162 TokAtPhysicalStartOfLine = true;
2163 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00002164
Chris Lattner22eb9722006-06-18 05:43:12 +00002165 BufferPtr = CurPtr;
Chris Lattner4d963442008-10-12 04:05:48 +00002166 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002167}
2168
Nico Weber158a31a2012-11-11 07:02:14 +00002169/// We have just read the // characters from input. Skip until we find the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002170/// newline character that terminates the comment. Then update BufferPtr and
Nico Weber158a31a2012-11-11 07:02:14 +00002171/// return.
Chris Lattner87d02082010-01-18 22:35:47 +00002172///
2173/// If we're in KeepCommentMode or any CommentHandler has inserted
2174/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002175bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2176 bool &TokAtPhysicalStartOfLine) {
Nico Weber158a31a2012-11-11 07:02:14 +00002177 // If Line comments aren't explicitly enabled for this language, emit an
Chris Lattner22eb9722006-06-18 05:43:12 +00002178 // extension warning.
Nico Weber158a31a2012-11-11 07:02:14 +00002179 if (!LangOpts.LineComment && !isLexingRawMode()) {
2180 Diag(BufferPtr, diag::ext_line_comment);
Mike Stump11289f42009-09-09 15:08:12 +00002181
Chris Lattner22eb9722006-06-18 05:43:12 +00002182 // Mark them enabled so we only emit one warning for this translation
2183 // unit.
Nico Weber158a31a2012-11-11 07:02:14 +00002184 LangOpts.LineComment = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002185 }
Mike Stump11289f42009-09-09 15:08:12 +00002186
Chris Lattner22eb9722006-06-18 05:43:12 +00002187 // Scan over the body of the comment. The common case, when scanning, is that
2188 // the comment contains normal ascii characters with nothing interesting in
2189 // them. As such, optimize for this case with the inner loop.
Richard Smith1d2ae942017-04-17 23:44:51 +00002190 //
2191 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2192 // character that ends the line comment.
Chris Lattner22eb9722006-06-18 05:43:12 +00002193 char C;
Richard Smith1d2ae942017-04-17 23:44:51 +00002194 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002195 C = *CurPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00002196 // Skip over characters in the fast loop.
2197 while (C != 0 && // Potentially EOF.
Chris Lattner22eb9722006-06-18 05:43:12 +00002198 C != '\n' && C != '\r') // Newline or DOS-style newline.
2199 C = *++CurPtr;
2200
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002201 const char *NextLine = CurPtr;
2202 if (C != 0) {
2203 // We found a newline, see if it's escaped.
2204 const char *EscapePtr = CurPtr-1;
Alp Toker6de6da62013-12-14 23:32:31 +00002205 bool HasSpace = false;
2206 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002207 --EscapePtr;
Alp Toker6de6da62013-12-14 23:32:31 +00002208 HasSpace = true;
2209 }
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002210
Richard Smith4c132e52017-04-18 21:45:04 +00002211 if (*EscapePtr == '\\')
2212 // Escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002213 CurPtr = EscapePtr;
2214 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
Richard Smith4c132e52017-04-18 21:45:04 +00002215 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2216 // Trigraph-escaped newline.
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002217 CurPtr = EscapePtr-2;
2218 else
2219 break; // This is a newline, we're done.
Alp Toker6de6da62013-12-14 23:32:31 +00002220
2221 // If there was space between the backslash and newline, warn about it.
2222 if (HasSpace && !isLexingRawMode())
2223 Diag(EscapePtr, diag::backslash_newline_space);
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225
Chris Lattner22eb9722006-06-18 05:43:12 +00002226 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
Chris Lattnere141a9e2008-12-12 07:34:39 +00002227 // properly decode the character. Read it in raw mode to avoid emitting
2228 // diagnostics about things like trigraphs. If we see an escaped newline,
2229 // we'll handle it below.
Chris Lattner22eb9722006-06-18 05:43:12 +00002230 const char *OldPtr = CurPtr;
Chris Lattnere141a9e2008-12-12 07:34:39 +00002231 bool OldRawMode = isLexingRawMode();
2232 LexingRawMode = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002233 C = getAndAdvanceChar(CurPtr, Result);
Chris Lattnere141a9e2008-12-12 07:34:39 +00002234 LexingRawMode = OldRawMode;
Chris Lattnerecdaf402009-04-05 00:26:41 +00002235
Benjamin Kramer17ff23c72011-09-05 07:19:39 +00002236 // If we only read only one character, then no special handling is needed.
2237 // We're done and can skip forward to the newline.
2238 if (C != 0 && CurPtr == OldPtr+1) {
2239 CurPtr = NextLine;
2240 break;
2241 }
2242
Chris Lattner22eb9722006-06-18 05:43:12 +00002243 // If we read multiple characters, and one of those characters was a \r or
Chris Lattnerff591e22007-06-09 06:07:22 +00002244 // \n, then we had an escaped newline within the comment. Emit diagnostic
2245 // unless the next line is also a // comment.
Alex Lorenzd5bf4362017-10-14 01:18:30 +00002246 if (CurPtr != OldPtr + 1 && C != '/' &&
2247 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002248 for (; OldPtr != CurPtr; ++OldPtr)
2249 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
Chris Lattnerff591e22007-06-09 06:07:22 +00002250 // Okay, we found a // comment that ends in a newline, if the next
2251 // line is also a // comment, but has spaces, don't emit a diagnostic.
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002252 if (isWhitespace(C)) {
Chris Lattnerff591e22007-06-09 06:07:22 +00002253 const char *ForwardPtr = CurPtr;
Benjamin Kramerdbfb18a2011-09-05 07:19:35 +00002254 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
Chris Lattnerff591e22007-06-09 06:07:22 +00002255 ++ForwardPtr;
2256 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2257 break;
2258 }
Mike Stump11289f42009-09-09 15:08:12 +00002259
Chris Lattner6d27a162008-11-22 02:02:22 +00002260 if (!isLexingRawMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002261 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002262 break;
Chris Lattner22eb9722006-06-18 05:43:12 +00002263 }
2264 }
Mike Stump11289f42009-09-09 15:08:12 +00002265
Richard Smith1d2ae942017-04-17 23:44:51 +00002266 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2267 --CurPtr;
2268 break;
Douglas Gregor11583702010-08-25 17:04:25 +00002269 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002270
2271 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2272 PP->CodeCompleteNaturalLanguage();
2273 cutOffLexing();
2274 return false;
2275 }
Richard Smith1d2ae942017-04-17 23:44:51 +00002276 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002277
Chris Lattner93ddf802010-02-03 21:06:21 +00002278 // Found but did not consume the newline. Notify comment handlers about the
2279 // comment unless we're in a #if 0 block.
2280 if (PP && !isLexingRawMode() &&
2281 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2282 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002283 BufferPtr = CurPtr;
2284 return true; // A token has to be returned.
2285 }
Mike Stump11289f42009-09-09 15:08:12 +00002286
Chris Lattner457fc152006-07-29 06:30:25 +00002287 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002288 if (inKeepCommentMode())
Nico Weber158a31a2012-11-11 07:02:14 +00002289 return SaveLineComment(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00002290
2291 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002292 // return immediately, so that the lexer can return this as an EOD token.
Chris Lattner457fc152006-07-29 06:30:25 +00002293 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002294 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002295 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002296 }
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattner22eb9722006-06-18 05:43:12 +00002298 // Otherwise, eat the \n character. We don't care if this is a \n\r or
Chris Lattner87e97ea2008-10-12 00:23:07 +00002299 // \r\n sequence. This is an efficiency hack (because we know the \n can't
Chris Lattner4d963442008-10-12 04:05:48 +00002300 // contribute to another token), it isn't needed for correctness. Note that
2301 // this is ok even in KeepWhitespaceMode, because we would have returned the
2302 /// comment above in that mode.
Chris Lattner22eb9722006-06-18 05:43:12 +00002303 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002304
Chris Lattner22eb9722006-06-18 05:43:12 +00002305 // The next returned token is at the start of the line.
Chris Lattner146762e2007-07-20 16:59:19 +00002306 Result.setFlag(Token::StartOfLine);
Eli Friedman0834a4b2013-09-19 00:41:32 +00002307 TokAtPhysicalStartOfLine = true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002308 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00002309 Result.clearFlag(Token::LeadingSpace);
Chris Lattner22eb9722006-06-18 05:43:12 +00002310 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002311 return false;
Chris Lattner457fc152006-07-29 06:30:25 +00002312}
Chris Lattner22eb9722006-06-18 05:43:12 +00002313
Nico Weber158a31a2012-11-11 07:02:14 +00002314/// If in save-comment mode, package up this Line comment in an appropriate
2315/// way and return it.
2316bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002317 // If we're not in a preprocessor directive, just return the // comment
2318 // directly.
2319 FormTokenWithChars(Result, CurPtr, tok::comment);
Mike Stump11289f42009-09-09 15:08:12 +00002320
David Blaikied5321242012-06-06 18:52:13 +00002321 if (!ParsingPreprocessorDirective || LexingRawMode)
Chris Lattnerb11c3232008-10-12 04:51:35 +00002322 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002323
Nico Weber158a31a2012-11-11 07:02:14 +00002324 // If this Line-style comment is in a macro definition, transmogrify it into
Chris Lattnerb11c3232008-10-12 04:51:35 +00002325 // a C-style block comment.
Douglas Gregordc970f02010-03-16 22:30:13 +00002326 bool Invalid = false;
2327 std::string Spelling = PP->getSpelling(Result, &Invalid);
2328 if (Invalid)
2329 return true;
Taewook Ohcebac482017-12-06 17:00:53 +00002330
Nico Weber158a31a2012-11-11 07:02:14 +00002331 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
Chris Lattnerb11c3232008-10-12 04:51:35 +00002332 Spelling[1] = '*'; // Change prefix to "/*".
2333 Spelling += "*/"; // add suffix.
Mike Stump11289f42009-09-09 15:08:12 +00002334
Chris Lattnerb11c3232008-10-12 04:51:35 +00002335 Result.setKind(tok::comment);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00002336 PP->CreateString(Spelling, Result,
Abramo Bagnarae398e602011-10-03 18:39:03 +00002337 Result.getLocation(), Result.getLocation());
Chris Lattnere01e7582008-10-12 04:15:42 +00002338 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002339}
2340
Chris Lattnercb283342006-06-18 06:48:37 +00002341/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
David Blaikie987bcf92012-06-06 18:43:20 +00002342/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2343/// a diagnostic if so. We know that the newline is inside of a block comment.
Mike Stump11289f42009-09-09 15:08:12 +00002344static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
Chris Lattner1f583052006-06-18 06:53:56 +00002345 Lexer *L) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002346 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
Mike Stump11289f42009-09-09 15:08:12 +00002347
Chris Lattner22eb9722006-06-18 05:43:12 +00002348 // Back up off the newline.
2349 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002350
Chris Lattner22eb9722006-06-18 05:43:12 +00002351 // If this is a two-character newline sequence, skip the other character.
2352 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2353 // \n\n or \r\r -> not escaped newline.
2354 if (CurPtr[0] == CurPtr[1])
2355 return false;
2356 // \n\r or \r\n -> skip the newline.
2357 --CurPtr;
2358 }
Mike Stump11289f42009-09-09 15:08:12 +00002359
Chris Lattner22eb9722006-06-18 05:43:12 +00002360 // If we have horizontal whitespace, skip over it. We allow whitespace
2361 // between the slash and newline.
2362 bool HasSpace = false;
2363 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2364 --CurPtr;
2365 HasSpace = true;
2366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
Chris Lattner22eb9722006-06-18 05:43:12 +00002368 // If we have a slash, we know this is an escaped newline.
2369 if (*CurPtr == '\\') {
Chris Lattnercb283342006-06-18 06:48:37 +00002370 if (CurPtr[-1] != '*') return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002371 } else {
2372 // It isn't a slash, is it the ?? / trigraph?
Chris Lattnercb283342006-06-18 06:48:37 +00002373 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2374 CurPtr[-3] != '*')
Chris Lattner22eb9722006-06-18 05:43:12 +00002375 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002376
Chris Lattnercb283342006-06-18 06:48:37 +00002377 // This is the trigraph ending the comment. Emit a stern warning!
Chris Lattner22eb9722006-06-18 05:43:12 +00002378 CurPtr -= 2;
2379
2380 // If no trigraphs are enabled, warn that we ignored this trigraph and
2381 // ignore this * character.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002382 if (!L->getLangOpts().Trigraphs) {
Chris Lattner6d27a162008-11-22 02:02:22 +00002383 if (!L->isLexingRawMode())
2384 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
Chris Lattnercb283342006-06-18 06:48:37 +00002385 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002386 }
Chris Lattner6d27a162008-11-22 02:02:22 +00002387 if (!L->isLexingRawMode())
2388 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002389 }
Mike Stump11289f42009-09-09 15:08:12 +00002390
Chris Lattner22eb9722006-06-18 05:43:12 +00002391 // Warn about having an escaped newline between the */ characters.
Chris Lattner6d27a162008-11-22 02:02:22 +00002392 if (!L->isLexingRawMode())
2393 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
Mike Stump11289f42009-09-09 15:08:12 +00002394
Chris Lattner22eb9722006-06-18 05:43:12 +00002395 // If there was space between the backslash and newline, warn about it.
Chris Lattner6d27a162008-11-22 02:02:22 +00002396 if (HasSpace && !L->isLexingRawMode())
2397 L->Diag(CurPtr, diag::backslash_newline_space);
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chris Lattnercb283342006-06-18 06:48:37 +00002399 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00002400}
2401
Chris Lattneraded4a92006-10-27 04:42:31 +00002402#ifdef __SSE2__
2403#include <emmintrin.h>
Chris Lattner9f6604f2006-10-30 20:01:22 +00002404#elif __ALTIVEC__
2405#include <altivec.h>
2406#undef bool
Chris Lattneraded4a92006-10-27 04:42:31 +00002407#endif
2408
James Dennettf442d242012-06-17 03:40:43 +00002409/// We have just read from input the / and * characters that started a comment.
2410/// Read until we find the * and / characters that terminate the comment.
2411/// Note that we don't bother decoding trigraphs or escaped newlines in block
2412/// comments, because they cannot cause the comment to end. The only thing
2413/// that can happen is the comment could end with an escaped newline between
2414/// the terminating * and /.
Chris Lattnere01e7582008-10-12 04:15:42 +00002415///
Chris Lattner87d02082010-01-18 22:35:47 +00002416/// If we're in KeepCommentMode or any CommentHandler has inserted
2417/// some tokens, this will store the first token and return true.
Eli Friedman0834a4b2013-09-19 00:41:32 +00002418bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2419 bool &TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002420 // Scan one character past where we should, looking for a '/' character. Once
Chris Lattner57540c52011-04-15 05:22:18 +00002421 // we find it, check to see if it was preceded by a *. This common
Chris Lattner22eb9722006-06-18 05:43:12 +00002422 // optimization helps people who like to put a lot of * characters in their
2423 // comments.
Chris Lattnerc850ad62007-07-21 23:43:37 +00002424
2425 // The first character we get with newlines and trigraphs skipped to handle
2426 // the degenerate /*/ case below correctly if the * has an escaped newline
2427 // after it.
2428 unsigned CharSize;
2429 unsigned char C = getCharAndSize(CurPtr, CharSize);
2430 CurPtr += CharSize;
Chris Lattner22eb9722006-06-18 05:43:12 +00002431 if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002432 if (!isLexingRawMode())
Chris Lattner7c2e9802008-10-12 01:31:51 +00002433 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner99e7d232008-10-12 04:19:49 +00002434 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002435
Chris Lattner99e7d232008-10-12 04:19:49 +00002436 // KeepWhitespaceMode should return this broken comment as a token. Since
2437 // it isn't a well formed comment, just return it as an 'unknown' token.
2438 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002439 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002440 return true;
2441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Chris Lattner99e7d232008-10-12 04:19:49 +00002443 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002444 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
Chris Lattnerc850ad62007-07-21 23:43:37 +00002447 // Check to see if the first character after the '/*' is another /. If so,
2448 // then this slash does not end the block comment, it is part of it.
2449 if (C == '/')
2450 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002451
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002452 while (true) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002453 // Skip over all non-interesting characters until we find end of buffer or a
2454 // (probably ending) '/' character.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002455 if (CurPtr + 24 < BufferEnd &&
2456 // If there is a code-completion point avoid the fast scan because it
2457 // doesn't check for '\0'.
2458 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
Chris Lattner6cc3e362006-10-27 04:12:35 +00002459 // While not aligned to a 16-byte boundary.
2460 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2461 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002462
Chris Lattner6cc3e362006-10-27 04:12:35 +00002463 if (C == '/') goto FoundSlash;
Chris Lattneraded4a92006-10-27 04:42:31 +00002464
2465#ifdef __SSE2__
Roman Divacky61509902014-04-03 18:04:52 +00002466 __m128i Slashes = _mm_set1_epi8('/');
2467 while (CurPtr+16 <= BufferEnd) {
2468 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2469 Slashes));
Benjamin Kramer38857372011-11-22 18:56:46 +00002470 if (cmp != 0) {
Benjamin Kramer900f1de2011-11-22 20:39:31 +00002471 // Adjust the pointer to point directly after the first slash. It's
2472 // not necessary to set C here, it will be overwritten at the end of
2473 // the outer loop.
Michael J. Spencer8c398402013-05-24 21:42:04 +00002474 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
Benjamin Kramer38857372011-11-22 18:56:46 +00002475 goto FoundSlash;
2476 }
Roman Divacky61509902014-04-03 18:04:52 +00002477 CurPtr += 16;
Benjamin Kramer38857372011-11-22 18:56:46 +00002478 }
Chris Lattner9f6604f2006-10-30 20:01:22 +00002479#elif __ALTIVEC__
2480 __vector unsigned char Slashes = {
Mike Stump11289f42009-09-09 15:08:12 +00002481 '/', '/', '/', '/', '/', '/', '/', '/',
Chris Lattner9f6604f2006-10-30 20:01:22 +00002482 '/', '/', '/', '/', '/', '/', '/', '/'
2483 };
2484 while (CurPtr+16 <= BufferEnd &&
Jay Foad6af95d32014-10-29 14:42:12 +00002485 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
Chris Lattner9f6604f2006-10-30 20:01:22 +00002486 CurPtr += 16;
Mike Stump11289f42009-09-09 15:08:12 +00002487#else
Chris Lattneraded4a92006-10-27 04:42:31 +00002488 // Scan for '/' quickly. Many block comments are very large.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002489 while (CurPtr[0] != '/' &&
2490 CurPtr[1] != '/' &&
2491 CurPtr[2] != '/' &&
2492 CurPtr[3] != '/' &&
2493 CurPtr+4 < BufferEnd) {
2494 CurPtr += 4;
2495 }
Chris Lattneraded4a92006-10-27 04:42:31 +00002496#endif
Mike Stump11289f42009-09-09 15:08:12 +00002497
Chris Lattneraded4a92006-10-27 04:42:31 +00002498 // It has to be one of the bytes scanned, increment to it and read one.
Chris Lattner6cc3e362006-10-27 04:12:35 +00002499 C = *CurPtr++;
2500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattneraded4a92006-10-27 04:42:31 +00002502 // Loop to scan the remainder.
Chris Lattner22eb9722006-06-18 05:43:12 +00002503 while (C != '/' && C != '\0')
2504 C = *CurPtr++;
Mike Stump11289f42009-09-09 15:08:12 +00002505
Chris Lattner22eb9722006-06-18 05:43:12 +00002506 if (C == '/') {
Benjamin Kramer38857372011-11-22 18:56:46 +00002507 FoundSlash:
Chris Lattner22eb9722006-06-18 05:43:12 +00002508 if (CurPtr[-2] == '*') // We found the final */. We're done!
2509 break;
Mike Stump11289f42009-09-09 15:08:12 +00002510
Chris Lattner22eb9722006-06-18 05:43:12 +00002511 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
Chris Lattner1f583052006-06-18 06:53:56 +00002512 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002513 // We found the final */, though it had an escaped newline between the
2514 // * and /. We're done!
2515 break;
2516 }
2517 }
2518 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2519 // If this is a /* inside of the comment, emit a warning. Don't do this
2520 // if this is a /*/, which will end the comment. This misses cases with
2521 // embedded escaped newlines, but oh well.
Chris Lattner6d27a162008-11-22 02:02:22 +00002522 if (!isLexingRawMode())
2523 Diag(CurPtr-1, diag::warn_nested_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002524 }
2525 } else if (C == 0 && CurPtr == BufferEnd+1) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002526 if (!isLexingRawMode())
Chris Lattner6d27a162008-11-22 02:02:22 +00002527 Diag(BufferPtr, diag::err_unterminated_block_comment);
Chris Lattner22eb9722006-06-18 05:43:12 +00002528 // Note: the user probably forgot a */. We could continue immediately
2529 // after the /*, but this would involve lexing a lot of what really is the
2530 // comment, which surely would confuse the parser.
Chris Lattner99e7d232008-10-12 04:19:49 +00002531 --CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00002532
Chris Lattner99e7d232008-10-12 04:19:49 +00002533 // KeepWhitespaceMode should return this broken comment as a token. Since
2534 // it isn't a well formed comment, just return it as an 'unknown' token.
2535 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002536 FormTokenWithChars(Result, CurPtr, tok::unknown);
Chris Lattner99e7d232008-10-12 04:19:49 +00002537 return true;
2538 }
Mike Stump11289f42009-09-09 15:08:12 +00002539
Chris Lattner99e7d232008-10-12 04:19:49 +00002540 BufferPtr = CurPtr;
Chris Lattnere01e7582008-10-12 04:15:42 +00002541 return false;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002542 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2543 PP->CodeCompleteNaturalLanguage();
2544 cutOffLexing();
2545 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002546 }
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002547
Chris Lattner22eb9722006-06-18 05:43:12 +00002548 C = *CurPtr++;
2549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner93ddf802010-02-03 21:06:21 +00002551 // Notify comment handlers about the comment unless we're in a #if 0 block.
2552 if (PP && !isLexingRawMode() &&
2553 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2554 getSourceLocation(CurPtr)))) {
Chris Lattner87d02082010-01-18 22:35:47 +00002555 BufferPtr = CurPtr;
2556 return true; // A token has to be returned.
2557 }
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00002558
Chris Lattner457fc152006-07-29 06:30:25 +00002559 // If we are returning comments as tokens, return this comment as a token.
Chris Lattner8637abd2008-10-12 03:22:02 +00002560 if (inKeepCommentMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00002561 FormTokenWithChars(Result, CurPtr, tok::comment);
Chris Lattnere01e7582008-10-12 04:15:42 +00002562 return true;
Chris Lattner457fc152006-07-29 06:30:25 +00002563 }
Chris Lattner22eb9722006-06-18 05:43:12 +00002564
2565 // It is common for the tokens immediately after a /**/ comment to be
2566 // whitespace. Instead of going through the big switch, handle it
Chris Lattner4d963442008-10-12 04:05:48 +00002567 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2568 // have already returned above with the comment as a token.
Chris Lattner22eb9722006-06-18 05:43:12 +00002569 if (isHorizontalWhitespace(*CurPtr)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00002570 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
Chris Lattnere01e7582008-10-12 04:15:42 +00002571 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002572 }
2573
2574 // Otherwise, just return so that the next character will be lexed as a token.
2575 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00002576 Result.setFlag(Token::LeadingSpace);
Chris Lattnere01e7582008-10-12 04:15:42 +00002577 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00002578}
2579
2580//===----------------------------------------------------------------------===//
2581// Primary Lexing Entry Points
2582//===----------------------------------------------------------------------===//
2583
Chris Lattner22eb9722006-06-18 05:43:12 +00002584/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2585/// uninterpreted string. This switches the lexer out of directive mode.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002586void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002587 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2588 "Must be in a preprocessing directive!");
Chris Lattner146762e2007-07-20 16:59:19 +00002589 Token Tmp;
Chris Lattner22eb9722006-06-18 05:43:12 +00002590
2591 // CurPtr - Cache BufferPtr in an automatic variable.
2592 const char *CurPtr = BufferPtr;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002593 while (true) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002594 char Char = getAndAdvanceChar(CurPtr, Tmp);
2595 switch (Char) {
2596 default:
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002597 if (Result)
2598 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002599 break;
2600 case 0: // Null.
2601 // Found end of file?
2602 if (CurPtr-1 != BufferEnd) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002603 if (isCodeCompletionPoint(CurPtr-1)) {
2604 PP->CodeCompleteNaturalLanguage();
2605 cutOffLexing();
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002606 return;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002607 }
2608
Chris Lattner22eb9722006-06-18 05:43:12 +00002609 // Nope, normal character, continue.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002610 if (Result)
2611 Result->push_back(Char);
Chris Lattner22eb9722006-06-18 05:43:12 +00002612 break;
2613 }
2614 // FALL THROUGH.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00002615 LLVM_FALLTHROUGH;
Chris Lattner22eb9722006-06-18 05:43:12 +00002616 case '\r':
2617 case '\n':
2618 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2619 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2620 BufferPtr = CurPtr-1;
Mike Stump11289f42009-09-09 15:08:12 +00002621
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002622 // Next, lex the character, which should handle the EOD transition.
Chris Lattnercb283342006-06-18 06:48:37 +00002623 Lex(Tmp);
Douglas Gregor11583702010-08-25 17:04:25 +00002624 if (Tmp.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002625 if (PP)
2626 PP->CodeCompleteNaturalLanguage();
Douglas Gregor11583702010-08-25 17:04:25 +00002627 Lex(Tmp);
2628 }
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002629 assert(Tmp.is(tok::eod) && "Unexpected token!");
Mike Stump11289f42009-09-09 15:08:12 +00002630
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00002631 // Finally, we're done;
2632 return;
Chris Lattner22eb9722006-06-18 05:43:12 +00002633 }
2634 }
2635}
2636
2637/// LexEndOfFile - CurPtr points to the end of this file. Handle this
2638/// condition, reporting diagnostics and handling other edge cases as required.
Chris Lattner2183a6e2006-07-18 06:36:12 +00002639/// This returns true if Result contains a token, false if PP.Lex should be
2640/// called again.
Chris Lattner146762e2007-07-20 16:59:19 +00002641bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
Chris Lattner22eb9722006-06-18 05:43:12 +00002642 // If we hit the end of the file while parsing a preprocessor directive,
2643 // end the preprocessor directive first. The next token returned will
2644 // then be the end of file.
2645 if (ParsingPreprocessorDirective) {
2646 // Done parsing the "line".
2647 ParsingPreprocessorDirective = false;
Chris Lattnerd01e2912006-06-18 16:22:51 +00002648 // Update the location of token as well as BufferPtr.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002649 FormTokenWithChars(Result, CurPtr, tok::eod);
Mike Stump11289f42009-09-09 15:08:12 +00002650
Chris Lattner457fc152006-07-29 06:30:25 +00002651 // Restore comment saving mode, in case it was disabled for directive.
Alp Toker08c25002013-12-13 17:04:55 +00002652 if (PP)
2653 resetExtendedTokenMode();
Chris Lattner2183a6e2006-07-18 06:36:12 +00002654 return true; // Have a token.
Mike Stump11289f42009-09-09 15:08:12 +00002655 }
Taewook Ohcebac482017-12-06 17:00:53 +00002656
Chris Lattner30a2fa12006-07-19 06:31:49 +00002657 // If we are in raw mode, return this event as an EOF token. Let the caller
2658 // that put us in raw mode handle the event.
Chris Lattner6d27a162008-11-22 02:02:22 +00002659 if (isLexingRawMode()) {
Chris Lattner8c204872006-10-14 05:19:21 +00002660 Result.startToken();
Chris Lattner30a2fa12006-07-19 06:31:49 +00002661 BufferPtr = BufferEnd;
Chris Lattnerb11c3232008-10-12 04:51:35 +00002662 FormTokenWithChars(Result, BufferEnd, tok::eof);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002663 return true;
Chris Lattnerd8aee0e2006-07-11 05:04:55 +00002664 }
Taewook Ohcebac482017-12-06 17:00:53 +00002665
Erik Verbruggen795eee92017-07-05 09:44:07 +00002666 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002667 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2668 ConditionalStack.clear();
2669 }
2670
Douglas Gregor3a7ad252010-08-24 19:08:16 +00002671 // Issue diagnostics for unterminated #if and missing newline.
2672
Chris Lattner30a2fa12006-07-19 06:31:49 +00002673 // If we are in a #if directive, emit an error.
2674 while (!ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002675 if (PP->getCodeCompletionFileLoc() != FileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +00002676 PP->Diag(ConditionalStack.back().IfLoc,
2677 diag::err_pp_unterminated_conditional);
Chris Lattner30a2fa12006-07-19 06:31:49 +00002678 ConditionalStack.pop_back();
2679 }
Mike Stump11289f42009-09-09 15:08:12 +00002680
Chris Lattner8f96d042008-04-12 05:54:25 +00002681 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2682 // a pedwarn.
Jordan Rose4c55d452013-08-23 15:42:01 +00002683 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2684 DiagnosticsEngine &Diags = PP->getDiagnostics();
2685 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2686 unsigned DiagID;
2687
2688 if (LangOpts.CPlusPlus11) {
2689 // C++11 [lex.phases] 2.2 p2
2690 // Prefer the C++98 pedantic compatibility warning over the generic,
2691 // non-extension, user-requested "missing newline at EOF" warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002692 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
Jordan Rose4c55d452013-08-23 15:42:01 +00002693 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2694 } else {
2695 DiagID = diag::warn_no_newline_eof;
2696 }
2697 } else {
2698 DiagID = diag::ext_no_newline_eof;
2699 }
2700
2701 Diag(BufferEnd, DiagID)
2702 << FixItHint::CreateInsertion(EndLoc, "\n");
2703 }
Mike Stump11289f42009-09-09 15:08:12 +00002704
Chris Lattner22eb9722006-06-18 05:43:12 +00002705 BufferPtr = CurPtr;
Chris Lattner30a2fa12006-07-19 06:31:49 +00002706
2707 // Finally, let the preprocessor handle this.
Jordan Rose127f6ee2012-06-15 23:33:51 +00002708 return PP->HandleEndOfFile(Result, isPragmaLexer());
Chris Lattner22eb9722006-06-18 05:43:12 +00002709}
2710
Chris Lattner678c8802006-07-11 05:46:12 +00002711/// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2712/// the specified lexer will return a tok::l_paren token, 0 if it is something
2713/// else and 2 if there are no more tokens in the buffer controlled by the
2714/// lexer.
2715unsigned Lexer::isNextPPTokenLParen() {
2716 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
Mike Stump11289f42009-09-09 15:08:12 +00002717
Chris Lattner678c8802006-07-11 05:46:12 +00002718 // Switch to 'skipping' mode. This will ensure that we can lex a token
2719 // without emitting diagnostics, disables macro expansion, and will cause EOF
2720 // to return an EOF token instead of popping the include stack.
2721 LexingRawMode = true;
Mike Stump11289f42009-09-09 15:08:12 +00002722
Chris Lattner678c8802006-07-11 05:46:12 +00002723 // Save state that can be changed while lexing so that we can restore it.
2724 const char *TmpBufferPtr = BufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002725 bool inPPDirectiveMode = ParsingPreprocessorDirective;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002726 bool atStartOfLine = IsAtStartOfLine;
2727 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2728 bool leadingSpace = HasLeadingSpace;
Mike Stump11289f42009-09-09 15:08:12 +00002729
Chris Lattner146762e2007-07-20 16:59:19 +00002730 Token Tok;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002731 Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002732
Chris Lattner678c8802006-07-11 05:46:12 +00002733 // Restore state that may have changed.
2734 BufferPtr = TmpBufferPtr;
Chris Lattner40493eb2009-04-24 07:15:46 +00002735 ParsingPreprocessorDirective = inPPDirectiveMode;
Eli Friedman0834a4b2013-09-19 00:41:32 +00002736 HasLeadingSpace = leadingSpace;
2737 IsAtStartOfLine = atStartOfLine;
2738 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
Mike Stump11289f42009-09-09 15:08:12 +00002739
Chris Lattner678c8802006-07-11 05:46:12 +00002740 // Restore the lexer back to non-skipping mode.
2741 LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +00002742
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002743 if (Tok.is(tok::eof))
Chris Lattner678c8802006-07-11 05:46:12 +00002744 return 2;
Chris Lattner98c1f7c2007-10-09 18:02:16 +00002745 return Tok.is(tok::l_paren);
Chris Lattner678c8802006-07-11 05:46:12 +00002746}
2747
James Dennettf442d242012-06-17 03:40:43 +00002748/// \brief Find the end of a version control conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002749static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2750 ConflictMarkerKind CMK) {
2751 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2752 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
Benjamin Kramere550bbd2016-04-01 09:58:45 +00002753 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
Richard Smitha9e33d42011-10-12 00:37:51 +00002754 size_t Pos = RestOfBuffer.find(Terminator);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002755 while (Pos != StringRef::npos) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002756 // Must occur at start of line.
David Majnemer5a549772014-12-14 04:53:11 +00002757 if (Pos == 0 ||
2758 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
Richard Smitha9e33d42011-10-12 00:37:51 +00002759 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2760 Pos = RestOfBuffer.find(Terminator);
Chris Lattner7c027ee2009-12-14 06:16:57 +00002761 continue;
2762 }
2763 return RestOfBuffer.data()+Pos;
2764 }
Craig Topperd2d442c2014-05-17 23:10:59 +00002765 return nullptr;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002766}
2767
2768/// IsStartOfConflictMarker - If the specified pointer is the start of a version
2769/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2770/// and recover nicely. This returns true if it is a conflict marker and false
2771/// if not.
2772bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2773 // Only a conflict marker if it starts at the beginning of a line.
2774 if (CurPtr != BufferStart &&
2775 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2776 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002777
Richard Smitha9e33d42011-10-12 00:37:51 +00002778 // Check to see if we have <<<<<<< or >>>>.
Benjamin Kramer22f24f62016-04-01 10:04:07 +00002779 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2780 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
Chris Lattner7c027ee2009-12-14 06:16:57 +00002781 return false;
2782
2783 // If we have a situation where we don't care about conflict markers, ignore
2784 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002785 if (CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002786 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002787
Richard Smitha9e33d42011-10-12 00:37:51 +00002788 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2789
2790 // Check to see if there is an ending marker somewhere in the buffer at the
2791 // start of a line to terminate this conflict marker.
2792 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002793 // We found a match. We are really in a conflict marker.
2794 // Diagnose this, and ignore to the end of line.
2795 Diag(CurPtr, diag::err_conflict_marker);
Richard Smitha9e33d42011-10-12 00:37:51 +00002796 CurrentConflictMarkerState = Kind;
Taewook Ohcebac482017-12-06 17:00:53 +00002797
Chris Lattner7c027ee2009-12-14 06:16:57 +00002798 // Skip ahead to the end of line. We know this exists because the
2799 // end-of-conflict marker starts with \r or \n.
2800 while (*CurPtr != '\r' && *CurPtr != '\n') {
2801 assert(CurPtr != BufferEnd && "Didn't find end of line");
2802 ++CurPtr;
2803 }
2804 BufferPtr = CurPtr;
2805 return true;
2806 }
Taewook Ohcebac482017-12-06 17:00:53 +00002807
Chris Lattner7c027ee2009-12-14 06:16:57 +00002808 // No end of conflict marker found.
2809 return false;
2810}
2811
Richard Smitha9e33d42011-10-12 00:37:51 +00002812/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2813/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2814/// is the end of a conflict marker. Handle it by ignoring up until the end of
2815/// the line. This returns true if it is a conflict marker and false if not.
Chris Lattner7c027ee2009-12-14 06:16:57 +00002816bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2817 // Only a conflict marker if it starts at the beginning of a line.
2818 if (CurPtr != BufferStart &&
2819 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2820 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002821
Chris Lattner7c027ee2009-12-14 06:16:57 +00002822 // If we have a situation where we don't care about conflict markers, ignore
2823 // it.
Richard Smitha9e33d42011-10-12 00:37:51 +00002824 if (!CurrentConflictMarkerState || isLexingRawMode())
Chris Lattner7c027ee2009-12-14 06:16:57 +00002825 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002826
Richard Smitha9e33d42011-10-12 00:37:51 +00002827 // Check to see if we have the marker (4 characters in a row).
2828 for (unsigned i = 1; i != 4; ++i)
Chris Lattner7c027ee2009-12-14 06:16:57 +00002829 if (CurPtr[i] != CurPtr[0])
2830 return false;
Taewook Ohcebac482017-12-06 17:00:53 +00002831
Chris Lattner7c027ee2009-12-14 06:16:57 +00002832 // If we do have it, search for the end of the conflict marker. This could
2833 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2834 // be the end of conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002835 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2836 CurrentConflictMarkerState)) {
Chris Lattner7c027ee2009-12-14 06:16:57 +00002837 CurPtr = End;
Taewook Ohcebac482017-12-06 17:00:53 +00002838
Chris Lattner7c027ee2009-12-14 06:16:57 +00002839 // Skip ahead to the end of line.
2840 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2841 ++CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002842
Chris Lattner7c027ee2009-12-14 06:16:57 +00002843 BufferPtr = CurPtr;
Taewook Ohcebac482017-12-06 17:00:53 +00002844
Chris Lattner7c027ee2009-12-14 06:16:57 +00002845 // No longer in the conflict marker.
Richard Smitha9e33d42011-10-12 00:37:51 +00002846 CurrentConflictMarkerState = CMK_None;
Chris Lattner7c027ee2009-12-14 06:16:57 +00002847 return true;
2848 }
Taewook Ohcebac482017-12-06 17:00:53 +00002849
Chris Lattner7c027ee2009-12-14 06:16:57 +00002850 return false;
2851}
2852
Alex Lorenz1be800c52017-04-19 08:58:56 +00002853static const char *findPlaceholderEnd(const char *CurPtr,
2854 const char *BufferEnd) {
2855 if (CurPtr == BufferEnd)
2856 return nullptr;
2857 BufferEnd -= 1; // Scan until the second last character.
2858 for (; CurPtr != BufferEnd; ++CurPtr) {
2859 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2860 return CurPtr + 2;
2861 }
2862 return nullptr;
2863}
2864
2865bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2866 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
Alex Lorenzfb7654a2017-06-16 20:13:39 +00002867 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
Alex Lorenz1be800c52017-04-19 08:58:56 +00002868 return false;
2869 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2870 if (!End)
2871 return false;
2872 const char *Start = CurPtr - 1;
2873 if (!LangOpts.AllowEditorPlaceholders)
2874 Diag(Start, diag::err_placeholder_in_source);
2875 Result.startToken();
2876 FormTokenWithChars(Result, End, tok::raw_identifier);
2877 Result.setRawIdentifierData(Start);
2878 PP->LookUpIdentifierInfo(Result);
2879 Result.setFlag(Token::IsEditorPlaceholder);
2880 BufferPtr = End;
2881 return true;
2882}
2883
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002884bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2885 if (PP && PP->isCodeCompletionEnabled()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002886 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002887 return Loc == PP->getCodeCompletionLoc();
2888 }
2889
2890 return false;
2891}
2892
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002893uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2894 Token *Result) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002895 unsigned CharSize;
2896 char Kind = getCharAndSize(StartPtr, CharSize);
2897
2898 unsigned NumHexDigits;
2899 if (Kind == 'u')
2900 NumHexDigits = 4;
2901 else if (Kind == 'U')
2902 NumHexDigits = 8;
2903 else
2904 return 0;
2905
Jordan Rosec0cba272013-01-27 20:12:04 +00002906 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
Jordan Rosecccbdbf2013-01-28 17:49:02 +00002907 if (Result && !isLexingRawMode())
2908 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
Jordan Rosec0cba272013-01-27 20:12:04 +00002909 return 0;
2910 }
2911
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002912 const char *CurPtr = StartPtr + CharSize;
2913 const char *KindLoc = &CurPtr[-1];
2914
2915 uint32_t CodePoint = 0;
2916 for (unsigned i = 0; i < NumHexDigits; ++i) {
2917 char C = getCharAndSize(CurPtr, CharSize);
2918
2919 unsigned Value = llvm::hexDigitValue(C);
2920 if (Value == -1U) {
2921 if (Result && !isLexingRawMode()) {
2922 if (i == 0) {
2923 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2924 << StringRef(KindLoc, 1);
2925 } else {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002926 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
Jordan Rose62db5062013-01-24 20:50:52 +00002927
2928 // If the user wrote \U1234, suggest a fixit to \u.
2929 if (i == 4 && NumHexDigits == 8) {
Jordan Rose58c61e02013-02-09 01:10:25 +00002930 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
Jordan Rose62db5062013-01-24 20:50:52 +00002931 Diag(KindLoc, diag::note_ucn_four_not_eight)
2932 << FixItHint::CreateReplacement(URange, "u");
2933 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002934 }
2935 }
Jordan Rosec0cba272013-01-27 20:12:04 +00002936
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002937 return 0;
2938 }
2939
2940 CodePoint <<= 4;
2941 CodePoint += Value;
2942
2943 CurPtr += CharSize;
2944 }
2945
2946 if (Result) {
2947 Result->setFlag(Token::HasUCN);
NAKAMURA Takumie8f83db2013-01-25 14:57:21 +00002948 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002949 StartPtr = CurPtr;
2950 else
2951 while (StartPtr != CurPtr)
2952 (void)getAndAdvanceChar(StartPtr, *Result);
2953 } else {
2954 StartPtr = CurPtr;
2955 }
2956
Justin Bogner53535132013-10-21 05:02:28 +00002957 // Don't apply C family restrictions to UCNs in assembly mode
2958 if (LangOpts.AsmPreprocessor)
2959 return CodePoint;
2960
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002961 // C99 6.4.3p2: A universal character name shall not specify a character whose
2962 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2963 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2964 // C++11 [lex.charset]p2: If the hexadecimal value for a
2965 // universal-character-name corresponds to a surrogate code point (in the
2966 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2967 // if the hexadecimal value for a universal-character-name outside the
2968 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2969 // string literal corresponds to a control character (in either of the
2970 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2971 // basic source character set, the program is ill-formed.
2972 if (CodePoint < 0xA0) {
2973 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2974 return CodePoint;
2975
2976 // We don't use isLexingRawMode() here because we need to warn about bad
2977 // UCNs even when skipping preprocessing tokens in a #if block.
2978 if (Result && PP) {
2979 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2980 Diag(BufferPtr, diag::err_ucn_control_character);
2981 else {
2982 char C = static_cast<char>(CodePoint);
2983 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2984 }
2985 }
2986
2987 return 0;
Jordan Rose58c61e02013-02-09 01:10:25 +00002988 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002989 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
Jordan Rose58c61e02013-02-09 01:10:25 +00002990 // We don't use isLexingRawMode() here because we need to diagnose bad
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002991 // UCNs even when skipping preprocessing tokens in a #if block.
Jordan Rose58c61e02013-02-09 01:10:25 +00002992 if (Result && PP) {
2993 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2994 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2995 else
2996 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2997 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00002998 return 0;
2999 }
3000
3001 return CodePoint;
3002}
3003
Eli Friedman0834a4b2013-09-19 00:41:32 +00003004bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3005 const char *CurPtr) {
Alexander Kornienko37d6b182013-08-29 12:12:31 +00003006 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
3007 UnicodeWhitespaceCharRanges);
Jordan Rose17441582013-01-30 01:52:57 +00003008 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
Alexander Kornienko37d6b182013-08-29 12:12:31 +00003009 UnicodeWhitespaceChars.contains(C)) {
Jordan Rose17441582013-01-30 01:52:57 +00003010 Diag(BufferPtr, diag::ext_unicode_whitespace)
Jordan Rose58c61e02013-02-09 01:10:25 +00003011 << makeCharRange(*this, BufferPtr, CurPtr);
Jordan Rose4246ae02013-01-24 20:50:50 +00003012
3013 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003014 return true;
Jordan Rose4246ae02013-01-24 20:50:50 +00003015 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003016 return false;
3017}
Jordan Rose4246ae02013-01-24 20:50:50 +00003018
Eli Friedman0834a4b2013-09-19 00:41:32 +00003019bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
Jordan Rose58c61e02013-02-09 01:10:25 +00003020 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
3021 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3022 !PP->isPreprocessedOutput()) {
3023 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
3024 makeCharRange(*this, BufferPtr, CurPtr),
3025 /*IsFirst=*/true);
3026 }
3027
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003028 MIOpt.ReadToken();
3029 return LexIdentifier(Result, CurPtr);
3030 }
3031
Jordan Rosecc538342013-01-31 19:48:48 +00003032 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3033 !PP->isPreprocessedOutput() &&
Jordan Rose58c61e02013-02-09 01:10:25 +00003034 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003035 // Non-ASCII characters tend to creep into source code unintentionally.
3036 // Instead of letting the parser complain about the unknown token,
3037 // just drop the character.
3038 // Note that we can /only/ do this when the non-ASCII character is actually
3039 // spelled as Unicode, not written as a UCN. The standard requires that
3040 // we not throw away any possible preprocessor tokens, but there's a
3041 // loophole in the mapping of Unicode characters to basic character set
3042 // characters that allows us to map these particular characters to, say,
3043 // whitespace.
Jordan Rose17441582013-01-30 01:52:57 +00003044 Diag(BufferPtr, diag::err_non_ascii)
Jordan Rose58c61e02013-02-09 01:10:25 +00003045 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003046
3047 BufferPtr = CurPtr;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003048 return false;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003049 }
3050
3051 // Otherwise, we have an explicit UCN or a character that's unlikely to show
3052 // up by accident.
3053 MIOpt.ReadToken();
3054 FormTokenWithChars(Result, CurPtr, tok::unknown);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003055 return true;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003056}
3057
Eli Friedman0834a4b2013-09-19 00:41:32 +00003058void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3059 IsAtStartOfLine = Result.isAtStartOfLine();
3060 HasLeadingSpace = Result.hasLeadingSpace();
3061 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3062 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3063}
3064
3065bool Lexer::Lex(Token &Result) {
3066 // Start a new token.
3067 Result.startToken();
3068
3069 // Set up misc whitespace flags for LexTokenInternal.
3070 if (IsAtStartOfLine) {
3071 Result.setFlag(Token::StartOfLine);
3072 IsAtStartOfLine = false;
3073 }
3074
3075 if (HasLeadingSpace) {
3076 Result.setFlag(Token::LeadingSpace);
3077 HasLeadingSpace = false;
3078 }
3079
3080 if (HasLeadingEmptyMacro) {
3081 Result.setFlag(Token::LeadingEmptyMacro);
3082 HasLeadingEmptyMacro = false;
3083 }
3084
3085 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3086 IsAtPhysicalStartOfLine = false;
Eli Friedman29749d22013-09-19 01:51:23 +00003087 bool isRawLex = isLexingRawMode();
3088 (void) isRawLex;
3089 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3090 // (After the LexTokenInternal call, the lexer might be destroyed.)
3091 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3092 return returnedToken;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003093}
Chris Lattner22eb9722006-06-18 05:43:12 +00003094
3095/// LexTokenInternal - This implements a simple C family lexer. It is an
3096/// extremely performance critical piece of code. This assumes that the buffer
Chris Lattner5c349382009-07-07 05:05:42 +00003097/// has a null character at the end of the file. This returns a preprocessing
3098/// token, not a normal token, as such, it is an internal interface. It assumes
3099/// that the Flags of result have been cleared before calling this.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003100bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
Chris Lattner22eb9722006-06-18 05:43:12 +00003101LexNextToken:
3102 // New token, can't need cleaning yet.
Chris Lattner146762e2007-07-20 16:59:19 +00003103 Result.clearFlag(Token::NeedsCleaning);
Craig Topperd2d442c2014-05-17 23:10:59 +00003104 Result.setIdentifierInfo(nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003105
Chris Lattner22eb9722006-06-18 05:43:12 +00003106 // CurPtr - Cache BufferPtr in an automatic variable.
3107 const char *CurPtr = BufferPtr;
Chris Lattner22eb9722006-06-18 05:43:12 +00003108
Chris Lattnereb54b592006-07-10 06:34:27 +00003109 // Small amounts of horizontal whitespace is very common between tokens.
3110 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3111 ++CurPtr;
3112 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3113 ++CurPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003114
Chris Lattner4d963442008-10-12 04:05:48 +00003115 // If we are keeping whitespace and other tokens, just return what we just
3116 // skipped. The next lexer invocation will return the token after the
3117 // whitespace.
3118 if (isKeepWhitespaceMode()) {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003119 FormTokenWithChars(Result, CurPtr, tok::unknown);
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003120 // FIXME: The next token will not have LeadingSpace set.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003121 return true;
Chris Lattner4d963442008-10-12 04:05:48 +00003122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
Chris Lattnereb54b592006-07-10 06:34:27 +00003124 BufferPtr = CurPtr;
Chris Lattner146762e2007-07-20 16:59:19 +00003125 Result.setFlag(Token::LeadingSpace);
Chris Lattnereb54b592006-07-10 06:34:27 +00003126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
Chris Lattner22eb9722006-06-18 05:43:12 +00003128 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
Mike Stump11289f42009-09-09 15:08:12 +00003129
Chris Lattner22eb9722006-06-18 05:43:12 +00003130 // Read a character, advancing over it.
3131 char Char = getAndAdvanceChar(CurPtr, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003132 tok::TokenKind Kind;
Mike Stump11289f42009-09-09 15:08:12 +00003133
Chris Lattner22eb9722006-06-18 05:43:12 +00003134 switch (Char) {
3135 case 0: // Null.
3136 // Found end of file?
Eli Friedman0834a4b2013-09-19 00:41:32 +00003137 if (CurPtr-1 == BufferEnd)
3138 return LexEndOfFile(Result, CurPtr-1);
Mike Stump11289f42009-09-09 15:08:12 +00003139
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003140 // Check if we are performing code completion.
3141 if (isCodeCompletionPoint(CurPtr-1)) {
3142 // Return the code-completion token.
3143 Result.startToken();
3144 FormTokenWithChars(Result, CurPtr, tok::code_completion);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003145 return true;
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00003146 }
3147
Chris Lattner6d27a162008-11-22 02:02:22 +00003148 if (!isLexingRawMode())
3149 Diag(CurPtr-1, diag::null_in_file);
Chris Lattner146762e2007-07-20 16:59:19 +00003150 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003151 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3152 return true; // KeepWhitespaceMode
Mike Stump11289f42009-09-09 15:08:12 +00003153
Eli Friedman0834a4b2013-09-19 00:41:32 +00003154 // We know the lexer hasn't changed, so just try again with this lexer.
3155 // (We manually eliminate the tail call to avoid recursion.)
3156 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003157
Chris Lattner3dfff972009-12-17 05:29:40 +00003158 case 26: // DOS & CP/M EOF: "^Z".
3159 // If we're in Microsoft extensions mode, treat this as end of file.
Nico Weberde2310b2015-12-29 23:17:27 +00003160 if (LangOpts.MicrosoftExt) {
3161 if (!isLexingRawMode())
3162 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003163 return LexEndOfFile(Result, CurPtr-1);
Nico Weberde2310b2015-12-29 23:17:27 +00003164 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003165
Chris Lattner3dfff972009-12-17 05:29:40 +00003166 // If Microsoft extensions are disabled, this is just random garbage.
3167 Kind = tok::unknown;
3168 break;
Taewook Ohcebac482017-12-06 17:00:53 +00003169
Chris Lattner22eb9722006-06-18 05:43:12 +00003170 case '\r':
Erich Keanee916d542017-09-05 17:32:36 +00003171 if (CurPtr[0] == '\n')
Erich Keane5a2b3222017-08-24 18:36:07 +00003172 Char = getAndAdvanceChar(CurPtr, Result);
Erich Keanee916d542017-09-05 17:32:36 +00003173 LLVM_FALLTHROUGH;
3174 case '\n':
Chris Lattner22eb9722006-06-18 05:43:12 +00003175 // If we are inside a preprocessor directive and we see the end of line,
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003176 // we know we are done with the directive, so return an EOD token.
Chris Lattner22eb9722006-06-18 05:43:12 +00003177 if (ParsingPreprocessorDirective) {
3178 // Done parsing the "line".
3179 ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +00003180
Chris Lattner457fc152006-07-29 06:30:25 +00003181 // Restore comment saving mode, in case it was disabled for directive.
David Blaikie2af2b302012-06-15 00:47:13 +00003182 if (PP)
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003183 resetExtendedTokenMode();
Mike Stump11289f42009-09-09 15:08:12 +00003184
Chris Lattner22eb9722006-06-18 05:43:12 +00003185 // Since we consumed a newline, we are back at the start of a line.
3186 IsAtStartOfLine = true;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003187 IsAtPhysicalStartOfLine = true;
Mike Stump11289f42009-09-09 15:08:12 +00003188
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00003189 Kind = tok::eod;
Chris Lattner22eb9722006-06-18 05:43:12 +00003190 break;
3191 }
Jordan Rosecb8a1ac2013-02-21 18:53:19 +00003192
Chris Lattner22eb9722006-06-18 05:43:12 +00003193 // No leading whitespace seen so far.
Chris Lattner146762e2007-07-20 16:59:19 +00003194 Result.clearFlag(Token::LeadingSpace);
Mike Stump11289f42009-09-09 15:08:12 +00003195
Eli Friedman0834a4b2013-09-19 00:41:32 +00003196 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3197 return true; // KeepWhitespaceMode
3198
3199 // We only saw whitespace, so just try again with this lexer.
3200 // (We manually eliminate the tail call to avoid recursion.)
3201 goto LexNextToken;
Chris Lattner22eb9722006-06-18 05:43:12 +00003202 case ' ':
3203 case '\t':
3204 case '\f':
3205 case '\v':
Chris Lattnerb9b85972007-07-22 06:29:05 +00003206 SkipHorizontalWhitespace:
Chris Lattner146762e2007-07-20 16:59:19 +00003207 Result.setFlag(Token::LeadingSpace);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003208 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3209 return true; // KeepWhitespaceMode
Chris Lattnerb9b85972007-07-22 06:29:05 +00003210
3211 SkipIgnoredUnits:
3212 CurPtr = BufferPtr;
Mike Stump11289f42009-09-09 15:08:12 +00003213
Chris Lattnerb9b85972007-07-22 06:29:05 +00003214 // If the next token is obviously a // or /* */ comment, skip it efficiently
3215 // too (without going through the big switch stmt).
Chris Lattner58827712009-01-16 22:39:25 +00003216 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003217 LangOpts.LineComment &&
3218 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003219 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3220 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003221 goto SkipIgnoredUnits;
Chris Lattner8637abd2008-10-12 03:22:02 +00003222 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003223 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3224 return true; // There is a token to return.
Chris Lattnerb9b85972007-07-22 06:29:05 +00003225 goto SkipIgnoredUnits;
3226 } else if (isHorizontalWhitespace(*CurPtr)) {
3227 goto SkipHorizontalWhitespace;
3228 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003229 // We only saw whitespace, so just try again with this lexer.
3230 // (We manually eliminate the tail call to avoid recursion.)
3231 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003232
Chris Lattner2b15cf72008-01-03 17:58:54 +00003233 // C99 6.4.4.1: Integer Constants.
3234 // C99 6.4.4.2: Floating Constants.
3235 case '0': case '1': case '2': case '3': case '4':
3236 case '5': case '6': case '7': case '8': case '9':
3237 // Notify MIOpt that we read a non-whitespace/non-comment token.
3238 MIOpt.ReadToken();
3239 return LexNumericConstant(Result, CurPtr);
Mike Stump11289f42009-09-09 15:08:12 +00003240
Richard Smith9b362092013-03-09 23:56:02 +00003241 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003242 // Notify MIOpt that we read a non-whitespace/non-comment token.
3243 MIOpt.ReadToken();
3244
Richard Smith9b362092013-03-09 23:56:02 +00003245 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003246 Char = getCharAndSize(CurPtr, SizeTmp);
3247
3248 // UTF-16 string literal
3249 if (Char == '"')
3250 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3251 tok::utf16_string_literal);
3252
3253 // UTF-16 character constant
3254 if (Char == '\'')
3255 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3256 tok::utf16_char_constant);
3257
Craig Topper54edcca2011-08-11 04:06:15 +00003258 // UTF-16 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003259 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3260 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003261 return LexRawStringLiteral(Result,
3262 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3263 SizeTmp2, Result),
3264 tok::utf16_string_literal);
3265
3266 if (Char == '8') {
3267 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3268
3269 // UTF-8 string literal
3270 if (Char2 == '"')
3271 return LexStringLiteral(Result,
3272 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3273 SizeTmp2, Result),
3274 tok::utf8_string_literal);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003275 if (Char2 == '\'' && LangOpts.CPlusPlus17)
Richard Smith3e3a7052014-11-08 06:08:42 +00003276 return LexCharConstant(
3277 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3278 SizeTmp2, Result),
3279 tok::utf8_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003280
Richard Smith9b362092013-03-09 23:56:02 +00003281 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003282 unsigned SizeTmp3;
3283 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3284 // UTF-8 raw string literal
3285 if (Char3 == '"') {
3286 return LexRawStringLiteral(Result,
3287 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3288 SizeTmp2, Result),
3289 SizeTmp3, Result),
3290 tok::utf8_string_literal);
3291 }
3292 }
3293 }
Douglas Gregorfb65e592011-07-27 05:40:30 +00003294 }
3295
3296 // treat u like the start of an identifier.
3297 return LexIdentifier(Result, CurPtr);
3298
Richard Smith9b362092013-03-09 23:56:02 +00003299 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
Douglas Gregorfb65e592011-07-27 05:40:30 +00003300 // Notify MIOpt that we read a non-whitespace/non-comment token.
3301 MIOpt.ReadToken();
3302
Richard Smith9b362092013-03-09 23:56:02 +00003303 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
Douglas Gregorfb65e592011-07-27 05:40:30 +00003304 Char = getCharAndSize(CurPtr, SizeTmp);
3305
3306 // UTF-32 string literal
3307 if (Char == '"')
3308 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3309 tok::utf32_string_literal);
3310
3311 // UTF-32 character constant
3312 if (Char == '\'')
3313 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3314 tok::utf32_char_constant);
Craig Topper54edcca2011-08-11 04:06:15 +00003315
3316 // UTF-32 raw string literal
Richard Smith9b362092013-03-09 23:56:02 +00003317 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3318 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
Craig Topper54edcca2011-08-11 04:06:15 +00003319 return LexRawStringLiteral(Result,
3320 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3321 SizeTmp2, Result),
3322 tok::utf32_string_literal);
Douglas Gregorfb65e592011-07-27 05:40:30 +00003323 }
3324
3325 // treat U like the start of an identifier.
3326 return LexIdentifier(Result, CurPtr);
3327
Craig Topper54edcca2011-08-11 04:06:15 +00003328 case 'R': // Identifier or C++0x raw string literal
3329 // Notify MIOpt that we read a non-whitespace/non-comment token.
3330 MIOpt.ReadToken();
3331
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003332 if (LangOpts.CPlusPlus11) {
Craig Topper54edcca2011-08-11 04:06:15 +00003333 Char = getCharAndSize(CurPtr, SizeTmp);
3334
3335 if (Char == '"')
3336 return LexRawStringLiteral(Result,
3337 ConsumeChar(CurPtr, SizeTmp, Result),
3338 tok::string_literal);
3339 }
3340
3341 // treat R like the start of an identifier.
3342 return LexIdentifier(Result, CurPtr);
3343
Chris Lattner2b15cf72008-01-03 17:58:54 +00003344 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
Chris Lattner371ac8a2006-07-04 07:11:10 +00003345 // Notify MIOpt that we read a non-whitespace/non-comment token.
3346 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003347 Char = getCharAndSize(CurPtr, SizeTmp);
3348
3349 // Wide string literal.
3350 if (Char == '"')
Chris Lattnerd3e98952006-10-06 05:22:26 +00003351 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
Douglas Gregorfb65e592011-07-27 05:40:30 +00003352 tok::wide_string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003353
Craig Topper54edcca2011-08-11 04:06:15 +00003354 // Wide raw string literal.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003355 if (LangOpts.CPlusPlus11 && Char == 'R' &&
Craig Topper54edcca2011-08-11 04:06:15 +00003356 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3357 return LexRawStringLiteral(Result,
3358 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3359 SizeTmp2, Result),
3360 tok::wide_string_literal);
3361
Chris Lattner22eb9722006-06-18 05:43:12 +00003362 // Wide character constant.
3363 if (Char == '\'')
Douglas Gregorfb65e592011-07-27 05:40:30 +00003364 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3365 tok::wide_char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003366 // FALL THROUGH, treating L like the start of an identifier.
Galina Kistanova39edaaa2017-06-03 06:25:47 +00003367 LLVM_FALLTHROUGH;
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattner22eb9722006-06-18 05:43:12 +00003369 // C99 6.4.2: Identifiers.
3370 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3371 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
Craig Topper54edcca2011-08-11 04:06:15 +00003372 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003373 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3374 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3375 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
Douglas Gregorfb65e592011-07-27 05:40:30 +00003376 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
Chris Lattner22eb9722006-06-18 05:43:12 +00003377 case 'v': case 'w': case 'x': case 'y': case 'z':
3378 case '_':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003379 // Notify MIOpt that we read a non-whitespace/non-comment token.
3380 MIOpt.ReadToken();
Chris Lattner22eb9722006-06-18 05:43:12 +00003381 return LexIdentifier(Result, CurPtr);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003382
3383 case '$': // $ in identifiers.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003384 if (LangOpts.DollarIdents) {
Chris Lattner6d27a162008-11-22 02:02:22 +00003385 if (!isLexingRawMode())
3386 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
Chris Lattner2b15cf72008-01-03 17:58:54 +00003387 // Notify MIOpt that we read a non-whitespace/non-comment token.
3388 MIOpt.ReadToken();
3389 return LexIdentifier(Result, CurPtr);
3390 }
Mike Stump11289f42009-09-09 15:08:12 +00003391
Chris Lattnerb11c3232008-10-12 04:51:35 +00003392 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003393 break;
Mike Stump11289f42009-09-09 15:08:12 +00003394
Chris Lattner22eb9722006-06-18 05:43:12 +00003395 // C99 6.4.4: Character Constants.
3396 case '\'':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003397 // Notify MIOpt that we read a non-whitespace/non-comment token.
3398 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003399 return LexCharConstant(Result, CurPtr, tok::char_constant);
Chris Lattner22eb9722006-06-18 05:43:12 +00003400
3401 // C99 6.4.5: String Literals.
3402 case '"':
Chris Lattner371ac8a2006-07-04 07:11:10 +00003403 // Notify MIOpt that we read a non-whitespace/non-comment token.
3404 MIOpt.ReadToken();
Douglas Gregorfb65e592011-07-27 05:40:30 +00003405 return LexStringLiteral(Result, CurPtr, tok::string_literal);
Chris Lattner22eb9722006-06-18 05:43:12 +00003406
3407 // C99 6.4.6: Punctuators.
3408 case '?':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003409 Kind = tok::question;
Chris Lattner22eb9722006-06-18 05:43:12 +00003410 break;
3411 case '[':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003412 Kind = tok::l_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003413 break;
3414 case ']':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003415 Kind = tok::r_square;
Chris Lattner22eb9722006-06-18 05:43:12 +00003416 break;
3417 case '(':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003418 Kind = tok::l_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003419 break;
3420 case ')':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003421 Kind = tok::r_paren;
Chris Lattner22eb9722006-06-18 05:43:12 +00003422 break;
3423 case '{':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003424 Kind = tok::l_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003425 break;
3426 case '}':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003427 Kind = tok::r_brace;
Chris Lattner22eb9722006-06-18 05:43:12 +00003428 break;
3429 case '.':
3430 Char = getCharAndSize(CurPtr, SizeTmp);
3431 if (Char >= '0' && Char <= '9') {
Chris Lattner371ac8a2006-07-04 07:11:10 +00003432 // Notify MIOpt that we read a non-whitespace/non-comment token.
3433 MIOpt.ReadToken();
3434
Chris Lattner22eb9722006-06-18 05:43:12 +00003435 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
David Blaikiebbafb8a2012-03-11 07:00:24 +00003436 } else if (LangOpts.CPlusPlus && Char == '*') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003437 Kind = tok::periodstar;
Chris Lattner22eb9722006-06-18 05:43:12 +00003438 CurPtr += SizeTmp;
3439 } else if (Char == '.' &&
3440 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003441 Kind = tok::ellipsis;
Chris Lattner22eb9722006-06-18 05:43:12 +00003442 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3443 SizeTmp2, Result);
3444 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003445 Kind = tok::period;
Chris Lattner22eb9722006-06-18 05:43:12 +00003446 }
3447 break;
3448 case '&':
3449 Char = getCharAndSize(CurPtr, SizeTmp);
3450 if (Char == '&') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003451 Kind = tok::ampamp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003452 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3453 } else if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003454 Kind = tok::ampequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003455 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3456 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003457 Kind = tok::amp;
Chris Lattner22eb9722006-06-18 05:43:12 +00003458 }
3459 break;
Mike Stump11289f42009-09-09 15:08:12 +00003460 case '*':
Chris Lattner22eb9722006-06-18 05:43:12 +00003461 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003462 Kind = tok::starequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003463 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3464 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003465 Kind = tok::star;
Chris Lattner22eb9722006-06-18 05:43:12 +00003466 }
3467 break;
3468 case '+':
3469 Char = getCharAndSize(CurPtr, SizeTmp);
3470 if (Char == '+') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003471 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003472 Kind = tok::plusplus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003473 } else if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003474 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003475 Kind = tok::plusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003476 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003477 Kind = tok::plus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003478 }
3479 break;
3480 case '-':
3481 Char = getCharAndSize(CurPtr, SizeTmp);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003482 if (Char == '-') { // --
Chris Lattner22eb9722006-06-18 05:43:12 +00003483 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003484 Kind = tok::minusminus;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003485 } else if (Char == '>' && LangOpts.CPlusPlus &&
Chris Lattnerb11c3232008-10-12 04:51:35 +00003486 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
Chris Lattner22eb9722006-06-18 05:43:12 +00003487 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3488 SizeTmp2, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003489 Kind = tok::arrowstar;
3490 } else if (Char == '>') { // ->
Chris Lattner22eb9722006-06-18 05:43:12 +00003491 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003492 Kind = tok::arrow;
3493 } else if (Char == '=') { // -=
Chris Lattner22eb9722006-06-18 05:43:12 +00003494 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003495 Kind = tok::minusequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003496 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003497 Kind = tok::minus;
Chris Lattner22eb9722006-06-18 05:43:12 +00003498 }
3499 break;
3500 case '~':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003501 Kind = tok::tilde;
Chris Lattner22eb9722006-06-18 05:43:12 +00003502 break;
3503 case '!':
3504 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003505 Kind = tok::exclaimequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003506 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3507 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003508 Kind = tok::exclaim;
Chris Lattner22eb9722006-06-18 05:43:12 +00003509 }
3510 break;
3511 case '/':
3512 // 6.4.9: Comments
3513 Char = getCharAndSize(CurPtr, SizeTmp);
Nico Weber158a31a2012-11-11 07:02:14 +00003514 if (Char == '/') { // Line comment.
3515 // Even if Line comments are disabled (e.g. in C89 mode), we generally
Chris Lattner58827712009-01-16 22:39:25 +00003516 // want to lex this as a comment. There is one problem with this though,
3517 // that in one particular corner case, this can change the behavior of the
3518 // resultant program. For example, In "foo //**/ bar", C89 would lex
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003519 // this as "foo / bar" and languages with Line comments would lex it as
Chris Lattner58827712009-01-16 22:39:25 +00003520 // "foo". Check to see if the character after the second slash is a '*'.
3521 // If so, we will lex that as a "/" instead of the start of a comment.
Jordan Rose864b8102013-03-05 22:51:04 +00003522 // However, we never do this if we are just preprocessing.
Eli Friedmancefc7ea2013-08-28 20:53:32 +00003523 bool TreatAsComment = LangOpts.LineComment &&
3524 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
Jordan Rose864b8102013-03-05 22:51:04 +00003525 if (!TreatAsComment)
3526 if (!(PP && PP->isPreprocessedOutput()))
3527 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3528
3529 if (TreatAsComment) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003530 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3531 TokAtPhysicalStartOfLine))
3532 return true; // There is a token to return.
Mike Stump11289f42009-09-09 15:08:12 +00003533
Chris Lattner58827712009-01-16 22:39:25 +00003534 // It is common for the tokens immediately after a // comment to be
3535 // whitespace (indentation for the next line). Instead of going through
3536 // the big switch, handle it efficiently now.
3537 goto SkipIgnoredUnits;
3538 }
3539 }
Mike Stump11289f42009-09-09 15:08:12 +00003540
Chris Lattner58827712009-01-16 22:39:25 +00003541 if (Char == '*') { // /**/ comment.
Eli Friedman0834a4b2013-09-19 00:41:32 +00003542 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3543 TokAtPhysicalStartOfLine))
3544 return true; // There is a token to return.
3545
3546 // We only saw whitespace, so just try again with this lexer.
3547 // (We manually eliminate the tail call to avoid recursion.)
3548 goto LexNextToken;
Chris Lattner58827712009-01-16 22:39:25 +00003549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Chris Lattner58827712009-01-16 22:39:25 +00003551 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003552 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003553 Kind = tok::slashequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003554 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003555 Kind = tok::slash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003556 }
3557 break;
3558 case '%':
3559 Char = getCharAndSize(CurPtr, SizeTmp);
3560 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003561 Kind = tok::percentequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003562 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003563 } else if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003564 Kind = tok::r_brace; // '%>' -> '}'
Chris Lattner22eb9722006-06-18 05:43:12 +00003565 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003566 } else if (LangOpts.Digraphs && Char == ':') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003567 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner2b271db2006-07-15 05:41:09 +00003568 Char = getCharAndSize(CurPtr, SizeTmp);
3569 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003570 Kind = tok::hashhash; // '%:%:' -> '##'
Chris Lattner22eb9722006-06-18 05:43:12 +00003571 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3572 SizeTmp2, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003573 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
Chris Lattner2b271db2006-07-15 05:41:09 +00003574 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner6d27a162008-11-22 02:02:22 +00003575 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003576 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003577 Kind = tok::hashat;
Chris Lattner2534324a2009-03-18 20:58:27 +00003578 } else { // '%:' -> '#'
Chris Lattner22eb9722006-06-18 05:43:12 +00003579 // We parsed a # character. If this occurs at the start of the line,
3580 // it's actually the start of a preprocessing directive. Callback to
3581 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003582 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003583 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003584 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chris Lattner2534324a2009-03-18 20:58:27 +00003586 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003587 }
3588 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003589 Kind = tok::percent;
Chris Lattner22eb9722006-06-18 05:43:12 +00003590 }
3591 break;
3592 case '<':
3593 Char = getCharAndSize(CurPtr, SizeTmp);
3594 if (ParsingFilename) {
Chris Lattnerb40289b2009-04-17 23:56:52 +00003595 return LexAngledStringLiteral(Result, CurPtr);
Chris Lattner22eb9722006-06-18 05:43:12 +00003596 } else if (Char == '<') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003597 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3598 if (After == '=') {
3599 Kind = tok::lesslessequal;
3600 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3601 SizeTmp2, Result);
3602 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3603 // If this is actually a '<<<<<<<' version control conflict marker,
3604 // recognize it as such and recover nicely.
3605 goto LexNextToken;
Richard Smitha9e33d42011-10-12 00:37:51 +00003606 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3607 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3608 // ignore it.
3609 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003610 } else if (LangOpts.CUDA && After == '<') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003611 Kind = tok::lesslessless;
3612 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3613 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003614 } else {
3615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3616 Kind = tok::lessless;
3617 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003618 } else if (Char == '=') {
Richard Smithedbf5972017-12-01 01:07:10 +00003619 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3620 if (After == '>') {
3621 if (getLangOpts().CPlusPlus2a) {
3622 if (!isLexingRawMode())
3623 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3624 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3625 SizeTmp2, Result);
3626 Kind = tok::spaceship;
3627 break;
3628 }
3629 // Suggest adding a space between the '<=' and the '>' to avoid a
3630 // change in semantics if this turns up in C++ <=17 mode.
3631 if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3632 Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3633 << FixItHint::CreateInsertion(
3634 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3635 }
3636 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003637 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003638 Kind = tok::lessequal;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003639 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003640 if (LangOpts.CPlusPlus11 &&
Richard Smithf7b62022011-04-14 18:36:27 +00003641 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3642 // C++0x [lex.pptoken]p3:
3643 // Otherwise, if the next three characters are <:: and the subsequent
3644 // character is neither : nor >, the < is treated as a preprocessor
3645 // token by itself and not as the first character of the alternative
3646 // token <:.
3647 unsigned SizeTmp3;
3648 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3649 if (After != ':' && After != '>') {
3650 Kind = tok::less;
Richard Smithacd4d3d2011-10-15 01:18:56 +00003651 if (!isLexingRawMode())
3652 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
Richard Smithf7b62022011-04-14 18:36:27 +00003653 break;
3654 }
3655 }
3656
Chris Lattner22eb9722006-06-18 05:43:12 +00003657 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003658 Kind = tok::l_square;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003659 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
Chris Lattner22eb9722006-06-18 05:43:12 +00003660 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003661 Kind = tok::l_brace;
Alex Lorenzc1e32fc2017-10-11 00:41:20 +00003662 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3663 lexEditorPlaceholder(Result, CurPtr)) {
Alex Lorenz1be800c52017-04-19 08:58:56 +00003664 return true;
Chris Lattner22eb9722006-06-18 05:43:12 +00003665 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003666 Kind = tok::less;
Chris Lattner22eb9722006-06-18 05:43:12 +00003667 }
3668 break;
3669 case '>':
3670 Char = getCharAndSize(CurPtr, SizeTmp);
3671 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003672 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003673 Kind = tok::greaterequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003674 } else if (Char == '>') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003675 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3676 if (After == '=') {
3677 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3678 SizeTmp2, Result);
3679 Kind = tok::greatergreaterequal;
Richard Smitha9e33d42011-10-12 00:37:51 +00003680 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3681 // If this is actually a '>>>>' conflict marker, recognize it as such
3682 // and recover nicely.
3683 goto LexNextToken;
Chris Lattner7c027ee2009-12-14 06:16:57 +00003684 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3685 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3686 goto LexNextToken;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003687 } else if (LangOpts.CUDA && After == '>') {
Peter Collingbournec1270f52011-02-09 21:08:21 +00003688 Kind = tok::greatergreatergreater;
3689 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3690 SizeTmp2, Result);
Chris Lattner7c027ee2009-12-14 06:16:57 +00003691 } else {
3692 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3693 Kind = tok::greatergreater;
3694 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003695 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003696 Kind = tok::greater;
Chris Lattner22eb9722006-06-18 05:43:12 +00003697 }
3698 break;
3699 case '^':
3700 Char = getCharAndSize(CurPtr, SizeTmp);
3701 if (Char == '=') {
Chris Lattner22eb9722006-06-18 05:43:12 +00003702 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattnerb11c3232008-10-12 04:51:35 +00003703 Kind = tok::caretequal;
Anastasia Stulova735c6cd2016-02-03 15:17:14 +00003704 } else if (LangOpts.OpenCL && Char == '^') {
3705 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3706 Kind = tok::caretcaret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003707 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003708 Kind = tok::caret;
Chris Lattner22eb9722006-06-18 05:43:12 +00003709 }
3710 break;
3711 case '|':
3712 Char = getCharAndSize(CurPtr, SizeTmp);
3713 if (Char == '=') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003714 Kind = tok::pipeequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003715 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3716 } else if (Char == '|') {
Chris Lattner7c027ee2009-12-14 06:16:57 +00003717 // If this is '|||||||' and we're in a conflict marker, ignore it.
3718 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3719 goto LexNextToken;
Chris Lattnerb11c3232008-10-12 04:51:35 +00003720 Kind = tok::pipepipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003721 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3722 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003723 Kind = tok::pipe;
Chris Lattner22eb9722006-06-18 05:43:12 +00003724 }
3725 break;
3726 case ':':
3727 Char = getCharAndSize(CurPtr, SizeTmp);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003728 if (LangOpts.Digraphs && Char == '>') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003729 Kind = tok::r_square; // ':>' -> ']'
Chris Lattner22eb9722006-06-18 05:43:12 +00003730 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Aaron Ballman606093a2017-10-15 15:01:42 +00003731 } else if ((LangOpts.CPlusPlus ||
3732 LangOpts.DoubleSquareBracketAttributes) &&
3733 Char == ':') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003734 Kind = tok::coloncolon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003735 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003736 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003737 Kind = tok::colon;
Chris Lattner22eb9722006-06-18 05:43:12 +00003738 }
3739 break;
3740 case ';':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003741 Kind = tok::semi;
Chris Lattner22eb9722006-06-18 05:43:12 +00003742 break;
3743 case '=':
3744 Char = getCharAndSize(CurPtr, SizeTmp);
3745 if (Char == '=') {
Richard Smitha9e33d42011-10-12 00:37:51 +00003746 // If this is '====' and we're in a conflict marker, ignore it.
Chris Lattner7c027ee2009-12-14 06:16:57 +00003747 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3748 goto LexNextToken;
Taewook Ohcebac482017-12-06 17:00:53 +00003749
Chris Lattnerb11c3232008-10-12 04:51:35 +00003750 Kind = tok::equalequal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003751 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Mike Stump11289f42009-09-09 15:08:12 +00003752 } else {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003753 Kind = tok::equal;
Chris Lattner22eb9722006-06-18 05:43:12 +00003754 }
3755 break;
3756 case ',':
Chris Lattnerb11c3232008-10-12 04:51:35 +00003757 Kind = tok::comma;
Chris Lattner22eb9722006-06-18 05:43:12 +00003758 break;
3759 case '#':
3760 Char = getCharAndSize(CurPtr, SizeTmp);
3761 if (Char == '#') {
Chris Lattnerb11c3232008-10-12 04:51:35 +00003762 Kind = tok::hashhash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003763 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003764 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
Chris Lattnerb11c3232008-10-12 04:51:35 +00003765 Kind = tok::hashat;
Chris Lattner6d27a162008-11-22 02:02:22 +00003766 if (!isLexingRawMode())
Ted Kremeneka08713c2011-10-17 21:47:53 +00003767 Diag(BufferPtr, diag::ext_charize_microsoft);
Chris Lattner2b271db2006-07-15 05:41:09 +00003768 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
Chris Lattner22eb9722006-06-18 05:43:12 +00003769 } else {
Chris Lattner22eb9722006-06-18 05:43:12 +00003770 // We parsed a # character. If this occurs at the start of the line,
3771 // it's actually the start of a preprocessing directive. Callback to
3772 // the preprocessor to handle it.
Alp Toker7755aff2014-05-18 18:37:59 +00003773 // TODO: -fpreprocessed mode??
Eli Friedman0834a4b2013-09-19 00:41:32 +00003774 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003775 goto HandleDirective;
Mike Stump11289f42009-09-09 15:08:12 +00003776
Chris Lattner2534324a2009-03-18 20:58:27 +00003777 Kind = tok::hash;
Chris Lattner22eb9722006-06-18 05:43:12 +00003778 }
3779 break;
3780
Chris Lattner2b15cf72008-01-03 17:58:54 +00003781 case '@':
3782 // Objective C support.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003783 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
Chris Lattnerb11c3232008-10-12 04:51:35 +00003784 Kind = tok::at;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003785 else
Chris Lattnerb11c3232008-10-12 04:51:35 +00003786 Kind = tok::unknown;
Chris Lattner2b15cf72008-01-03 17:58:54 +00003787 break;
Mike Stump11289f42009-09-09 15:08:12 +00003788
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003789 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
Chris Lattner22eb9722006-06-18 05:43:12 +00003790 case '\\':
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003791 if (!LangOpts.AsmPreprocessor) {
3792 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3793 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3794 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3795 return true; // KeepWhitespaceMode
Eli Friedman0834a4b2013-09-19 00:41:32 +00003796
Sanne Woudadb1bdf42017-04-07 10:13:00 +00003797 // We only saw whitespace, so just try again with this lexer.
3798 // (We manually eliminate the tail call to avoid recursion.)
3799 goto LexNextToken;
3800 }
3801
3802 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003803 }
Eli Friedman0834a4b2013-09-19 00:41:32 +00003804 }
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003805
Chris Lattnerb11c3232008-10-12 04:51:35 +00003806 Kind = tok::unknown;
Chris Lattner041bef82006-07-11 05:52:53 +00003807 break;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003808
3809 default: {
3810 if (isASCII(Char)) {
3811 Kind = tok::unknown;
3812 break;
3813 }
3814
Justin Lebar90910552016-09-30 00:38:45 +00003815 llvm::UTF32 CodePoint;
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003816
3817 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3818 // an escaped newline.
3819 --CurPtr;
Richard Smith77091b12017-12-14 13:15:08 +00003820 const char *UTF8StartPtr = CurPtr;
Justin Lebar90910552016-09-30 00:38:45 +00003821 llvm::ConversionResult Status =
3822 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3823 (const llvm::UTF8 *)BufferEnd,
Dmitri Gribenko9feeef42013-01-30 12:06:08 +00003824 &CodePoint,
Justin Lebar90910552016-09-30 00:38:45 +00003825 llvm::strictConversion);
3826 if (Status == llvm::conversionOK) {
Eli Friedman0834a4b2013-09-19 00:41:32 +00003827 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3828 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3829 return true; // KeepWhitespaceMode
3830
3831 // We only saw whitespace, so just try again with this lexer.
3832 // (We manually eliminate the tail call to avoid recursion.)
3833 goto LexNextToken;
3834 }
Richard Smith77091b12017-12-14 13:15:08 +00003835 if (!isLexingRawMode())
3836 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
3837 makeCharRange(*this, UTF8StartPtr, CurPtr));
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003838 return LexUnicode(Result, CodePoint, CurPtr);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003839 }
Taewook Ohcebac482017-12-06 17:00:53 +00003840
Jordan Rosecc538342013-01-31 19:48:48 +00003841 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3842 PP->isPreprocessedOutput()) {
Jordan Rosef6497952013-01-30 19:21:12 +00003843 ++CurPtr;
Jordan Rose17441582013-01-30 01:52:57 +00003844 Kind = tok::unknown;
3845 break;
3846 }
3847
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003848 // Non-ASCII characters tend to creep into source code unintentionally.
3849 // Instead of letting the parser complain about the unknown token,
Jordan Rose8b4af2a2013-01-25 00:20:28 +00003850 // just diagnose the invalid UTF-8, then drop the character.
Jordan Rose17441582013-01-30 01:52:57 +00003851 Diag(CurPtr, diag::err_invalid_utf8);
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003852
3853 BufferPtr = CurPtr+1;
Eli Friedman0834a4b2013-09-19 00:41:32 +00003854 // We're pretending the character didn't exist, so just try again with
3855 // this lexer.
3856 // (We manually eliminate the tail call to avoid recursion.)
Jordan Rose7f43ddd2013-01-24 20:50:46 +00003857 goto LexNextToken;
3858 }
Chris Lattner22eb9722006-06-18 05:43:12 +00003859 }
Mike Stump11289f42009-09-09 15:08:12 +00003860
Chris Lattner371ac8a2006-07-04 07:11:10 +00003861 // Notify MIOpt that we read a non-whitespace/non-comment token.
3862 MIOpt.ReadToken();
3863
Chris Lattnerd01e2912006-06-18 16:22:51 +00003864 // Update the location of token as well as BufferPtr.
Chris Lattnerb11c3232008-10-12 04:51:35 +00003865 FormTokenWithChars(Result, CurPtr, Kind);
Eli Friedman0834a4b2013-09-19 00:41:32 +00003866 return true;
Argyrios Kyrtzidis36675b72012-11-13 01:02:40 +00003867
3868HandleDirective:
3869 // We parsed a # character and it's the start of a preprocessing directive.
3870
3871 FormTokenWithChars(Result, CurPtr, tok::hash);
3872 PP->HandleDirective(Result);
3873
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003874 if (PP->hadModuleLoaderFatalFailure()) {
3875 // With a fatal failure in the module loader, we abort parsing.
3876 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
Eli Friedman0834a4b2013-09-19 00:41:32 +00003877 return true;
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003878 }
3879
Eli Friedman0834a4b2013-09-19 00:41:32 +00003880 // We parsed the directive; lex a token with the new state.
3881 return false;
Chris Lattner22eb9722006-06-18 05:43:12 +00003882}